blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
264
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 5
140
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 905
values | visit_date
timestamp[us]date 2015-08-09 11:21:18
2023-09-06 10:45:07
| revision_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-17 19:19:19
| committer_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-06 06:22:19
| github_id
int64 3.89k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-07 00:51:45
2023-09-14 21:58:39
⌀ | gha_created_at
timestamp[us]date 2008-03-27 23:40:48
2023-08-21 23:17:38
⌀ | gha_language
stringclasses 141
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
10.4M
| extension
stringclasses 115
values | content
stringlengths 3
10.4M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
158
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8dd7965c1d9390c3c70655b5d0b957865835a7fb | 890709473f3a49b452017d543defdf77c38b0054 | /core/src/labels/labelCollider.cpp | 1389f2c566a02c7231ca0240436a7fb434978449 | [
"MIT"
] | permissive | am2222/tangram-es | 5dd3562d07b30d2bf786e3519fd934ffc85b4c19 | 2d778ff31804a88e59e348ab8bd1cf017ef1e743 | refs/heads/master | 2021-01-18T19:51:04.891638 | 2016-07-27T21:53:35 | 2016-07-27T21:53:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,441 | cpp | #include "labelCollider.h"
#include "labels/labelSet.h"
#include "glm/gtc/matrix_transform.hpp"
#include "glm/gtx/norm.hpp"
#define MAX_SCALE 2
namespace Tangram {
void LabelCollider::setup(float _tileSize, float _tileScale) {
// Maximum scale at which this tile is used (unless it's a proxy)
m_tileScale = _tileScale * MAX_SCALE;
m_screenSize = glm::vec2{ _tileSize * m_tileScale };
}
void LabelCollider::addLabels(std::vector<std::unique_ptr<Label>>& _labels) {
for (auto& label : _labels) {
if (label->canOcclude()) {
m_labels.push_back(label.get());
}
}
}
void LabelCollider::handleRepeatGroup(size_t startPos) {
float threshold2 = pow(m_labels[startPos]->options().repeatDistance, 2);
size_t repeatGroup = m_labels[startPos]->options().repeatGroup;
// Get the range
size_t endPos = startPos;
for (;startPos > 0; startPos--) {
if (m_labels[startPos-1]->options().repeatGroup != repeatGroup) { break; }
}
for (;endPos < m_labels.size()-1; endPos++) {
if (m_labels[endPos+1]->options().repeatGroup != repeatGroup) { break; }
}
for (size_t i = startPos; i < endPos; i++) {
Label* l1 = m_labels[i];
if (l1->isOccluded()) { continue; }
for (size_t j = i+1; j <= endPos; j++) {
Label* l2 = m_labels[j];
if (l2->isOccluded()) { continue; }
float d2 = distance2(l1->center(), l2->center());
if (d2 < threshold2) {
l2->occlude();
}
}
}
}
void LabelCollider::process() {
// Sort labels so that all labels of one repeat group are next to each other
std::sort(m_labels.begin(), m_labels.end(),
[](auto* l1, auto* l2) {
if (l1->options().priority != l2->options().priority) {
// lower numeric priority means higher priority
return l1->options().priority > l2->options().priority;
}
if (l1->options().repeatGroup != l2->options().repeatGroup) {
return l1->options().repeatGroup < l2->options().repeatGroup;
}
if (l1->type() == Label::Type::line && l2->type() == Label::Type::line) {
// Prefer the label with longer line segment as it has a chance
// to be shown earlier (also on the lower zoom-level)
// TODO compare fraction segment_length/label_width
return glm::length2(l1->transform().modelPosition1 - l1->transform().modelPosition2) >
glm::length2(l2->transform().modelPosition1 - l2->transform().modelPosition2);
}
return l1->hash() < l2->hash();
});
// Project tile to NDC (-1 to 1, y-up)
glm::mat4 mvp{1};
// Scale tile to 'fullscreen'
mvp[0][0] = 2;
mvp[1][1] = -2;
// Place tile centered
mvp[3][0] = -1;
mvp[3][1] = 1;
for (auto* label : m_labels) {
label->update(mvp, m_screenSize, 1, true);
m_aabbs.push_back(label->aabb());
}
m_isect2d.resize({m_screenSize.x / 128, m_screenSize.y / 128}, m_screenSize);
m_isect2d.intersect(m_aabbs);
// Set the first item to be the one with higher priority
for (auto& pair : m_isect2d.pairs) {
auto* l1 = m_labels[pair.first];
auto* l2 = m_labels[pair.second];
if (l1->options().priority > l2->options().priority) {
std::swap(pair.first, pair.second);
// Note: Mark the label to be potentially occluded
l2->enterState(Label::State::sleep, 0.0f);
} else {
l1->enterState(Label::State::sleep, 0.0f);
}
}
// Sort by priority on the first item
std::sort(m_isect2d.pairs.begin(), m_isect2d.pairs.end(),
[&](auto& a, auto& b) {
auto* l1 = m_labels[a.first];
auto* l2 = m_labels[b.first];
if (l1->options().priority != l2->options().priority) {
// lower numeric priority means higher priority
return l1->options().priority > l2->options().priority;
}
if (l1->type() == Label::Type::line &&
l2->type() == Label::Type::line) {
// Prefer the label with longer line segment as it has a chance
// to be shown earlier (also on the lower zoom-level)
// TODO compare fraction segment_length/label_width
return glm::length2(l1->transform().modelPosition1 - l1->transform().modelPosition2) >
glm::length2(l2->transform().modelPosition1 - l2->transform().modelPosition2);
}
// just so it is consistent between two instances
return (l1->hash() < l2->hash());
});
// The collision pairs are sorted in a way that:
// - The first item may occlude the second it (but not the other way round!)
// At each iteration where the priority decreases:
// - the first item of the collision pair has a higher priority
// - all items of following collision pairs have a lower priority
// -> all labels of repeatGroups with higher priority have been added
// when reaching a collision pair with lower priority
// This allows to remove repeated labels before they occlude other candidates
size_t repeatGroup = 0;
// Narrow Phase, resolve conflicts
for (auto& pair : m_isect2d.pairs) {
auto* l1 = m_labels[pair.first];
auto* l2 = m_labels[pair.second];
// Occlude labels within repeat group so that they don't occlude other labels
if (repeatGroup != l1->options().repeatGroup) {
repeatGroup = l1->options().repeatGroup;
if (repeatGroup != 0) {
handleRepeatGroup(pair.first);
}
}
if (l1->parent() && l1->parent()->isOccluded()) {
l1->occlude();
}
if (l2->parent() && l2->parent()->isOccluded()) {
l2->occlude();
}
if (l1->isOccluded() || l2->isOccluded()) {
// One of this pair is already occluded.
// => conflict solved
continue;
}
if (!intersect(l1->obb(), l2->obb())) {
continue;
}
if (l1->options().priority != l2->options().priority) {
// lower numeric priority means higher priority
if(l1->options().priority > l2->options().priority) {
l1->occlude();
} else {
l2->occlude();
}
} else {
// just so it is consistent between two instances
if (l1->hash() < l2->hash()) {
l1->occlude();
} else {
l2->occlude();
}
}
}
for (auto* label : m_labels) {
// Manage link occlusion (unified icon labels)
if (label->parent() && label->parent()->isOccluded()) {
label->occlude();
}
if (label->isOccluded()) {
label->enterState(Label::State::dead, 0.0f);
} else {
label->enterState(Label::State::wait_occ, 0.0f);
}
}
m_labels.clear();
m_aabbs.clear();
}
}
| [
"[email protected]"
] | |
2d5a21f2552827f83b8b9ea0de780265742c9211 | 5dc817d8aa793ea8ad58cc66427fa46cfe86ad1c | /WGammaAnalysis/RooUnfold/src/RooUnfoldBayes.cxx | 37caa9e0b03c74a6f453c846bf4f94cd245e8e68 | [] | no_license | AnYpku/WGamma | 4c7b4b42d5706630151ff7facc966b968156be6f | 3f3f561b2af1f211cf46b240bea198c4d7442f1b | refs/heads/master | 2020-04-01T22:30:36.587613 | 2017-06-07T03:17:48 | 2017-06-07T03:17:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,459 | cxx | //=====================================================================-*-C++-*-
// File and Version Information:
// $Id: RooUnfoldBayes.cxx 335 2012-06-08 18:18:04Z T.J.Adye $
//
// Description:
// Bayesian unfolding.
//
// Author: Tim Adye <[email protected]>
//
//==============================================================================
//____________________________________________________________
/* BEGIN_HTML
<p>Links to the RooUnfoldBayesImpl class which uses Bayesian unfolding to reconstruct the truth distribution.</p>
<p>Works for 2 and 3 dimensional distributions
<p>Returned errors can be either as a diagonal matrix or as a full matrix of covariances
<p>Regularisation parameter sets the number of iterations used in the unfolding (default=4)
<p>Is able to account for bin migration and smearing
<p>Can unfold if test and measured distributions have different binning.
<p>Returns covariance matrices with conditions approximately that of the machine precision. This occasionally leads to very large chi squared values
END_HTML */
/////////////////////////////////////////////////////////////
//#define OLDERRS // restore old (incorrect) error calculation
//#define OLDERRS2 // restore old (incorrect) systematic error calculation
//#define OLDMULT // restore old (slower) matrix multiplications
#include "RooUnfoldBayes.h"
#include <iostream>
#include <iomanip>
#include <math.h>
#include "TNamed.h"
#include "TH1.h"
#include "TH2.h"
#include "RooUnfoldResponse.h"
using std::min;
using std::cerr;
using std::endl;
using std::cout;
using std::setw;
using std::left;
using std::right;
ClassImp (RooUnfoldBayes);
RooUnfoldBayes::RooUnfoldBayes (const RooUnfoldBayes& rhs)
: RooUnfold (rhs)
{
// Copy constructor.
Init();
CopyData (rhs);
}
RooUnfoldBayes::RooUnfoldBayes( const RooUnfoldResponse* res,
const TH1* meas,
Int_t niter, Bool_t smoothit, Bool_t usechi2,
const char* name, const char* title )
: RooUnfold (res, meas, name, title),
_niter(niter), _smoothit(smoothit), _usechi2(usechi2)
{
// Constructor with response matrix object and measured unfolding input histogram.
// The regularisation parameter is niter (number of iterations).
Init();
}
RooUnfoldBayes* RooUnfoldBayes::Clone (const char* newname) const
{
// Creates a copy of the RooUnfoldBayes object
RooUnfoldBayes* unfold= new RooUnfoldBayes(*this);
if (newname && strlen(newname)) unfold->SetName(newname);
return unfold;
}
void RooUnfoldBayes::Init()
{
_nc= _ne= 0;
_nbartrue= _N0C= 0.0;
GetSettings();
}
void RooUnfoldBayes::Reset()
{
Init();
RooUnfold::Reset();
}
void RooUnfoldBayes::Assign (const RooUnfoldBayes& rhs)
{
RooUnfold::Assign (rhs);
CopyData (rhs);
}
void RooUnfoldBayes::CopyData (const RooUnfoldBayes& rhs)
{
_niter= rhs._niter;
_smoothit= rhs._smoothit;
}
void RooUnfoldBayes::Unfold()
{
setup();
if (verbose() >= 2) {
Print();
RooUnfoldResponse::PrintMatrix(_Nji,"RooUnfoldBayes response matrix (Nji)");
}
if (verbose() >= 1) cout << "Now unfolding..." << endl;
unfold();
if (verbose() >= 2) Print();
_rec.ResizeTo(_nc);
_rec = _nbarCi;
_rec.ResizeTo(_nt); // drop fakes in final bin
_unfolded= true;
_haveCov= false;
}
void RooUnfoldBayes::GetCov()
{
getCovariance();
_cov.ResizeTo (_nt, _nt); // drop fakes in final bin
_haveCov= true;
}
void RooUnfoldBayes::GetSettings()
{
_minparm=1;
_maxparm=15;
_stepsizeparm=1;
_defaultparm=4;
}
TMatrixD& RooUnfoldBayes::H2M (const TH2* h, TMatrixD& m, Bool_t overflow)
{
// TH2 -> TMatrixD
if (!h) return m;
Int_t first= overflow ? 0 : 1;
Int_t nm= m.GetNrows(), nt= m.GetNcols();
for (Int_t j= 0; j < nt; j++)
for (Int_t i= 0; i < nm; i++)
m(i,j)= h->GetBinContent(i+first,j+first);
return m;
}
//-------------------------------------------------------------------------
void RooUnfoldBayes::setup()
{
_nc = _nt;
_ne = _nm;
_nEstj.ResizeTo(_ne);
_nEstj= Vmeasured();
_nCi.ResizeTo(_nt);
_nCi= _res->Vtruth();
_Nji.ResizeTo(_ne,_nt);
H2M (_res->Hresponse(), _Nji, _overflow); // don't normalise, which is what _res->Mresponse() would give us
if (_res->FakeEntries()) {
TVectorD fakes= _res->Vfakes();
Double_t nfakes= fakes.Sum();
if (verbose()>=0) cout << "Add truth bin for " << nfakes << " fakes" << endl;
_nc++;
_nCi.ResizeTo(_nc);
_nCi[_nc-1]= nfakes;
_Nji.ResizeTo(_ne,_nc);
for (Int_t i= 0; i<_nm; i++) _Nji(i,_nc-1)= fakes[i];
}
_nbarCi.ResizeTo(_nc);
_efficiencyCi.ResizeTo(_nc);
_Mij.ResizeTo(_nc,_ne);
_P0C.ResizeTo(_nc);
_UjInv.ResizeTo(_ne);
#ifndef OLDERRS
if (_dosys!=2) _dnCidnEj.ResizeTo(_nc,_ne);
#endif
if (_dosys) _dnCidPjk.ResizeTo(_nc,_ne*_nc);
// Initial distribution
_N0C= _nCi.Sum();
if (_N0C!=0.0) {
_P0C= _nCi;
_P0C *= 1.0/_N0C;
}
}
//-------------------------------------------------------------------------
void RooUnfoldBayes::unfold()
{
// Calculate the unfolding matrix.
// _niter = number of iterations to perform (3 by default).
// _smoothit = smooth the matrix in between iterations (default false).
TMatrixD PEjCi(_ne,_nc), PEjCiEff(_ne,_nc);
for (Int_t i = 0 ; i < _nc ; i++) {
if (_nCi[i] <= 0.0) { _efficiencyCi[i] = 0.0; continue; }
Double_t eff = 0.0;
for (Int_t j = 0 ; j < _ne ; j++) {
Double_t response = _Nji(j,i) / _nCi[i];
PEjCi(j,i) = PEjCiEff(j,i) = response; // efficiency of detecting the cause Ci in Effect Ej
eff += response;
}
_efficiencyCi[i] = eff;
Double_t effinv = eff > 0.0 ? 1.0/eff : 0.0; // reset PEjCiEff if eff=0
for (Int_t j = 0 ; j < _ne ; j++) PEjCiEff(j,i) *= effinv;
}
TVectorD PbarCi(_nc);
for (Int_t kiter = 0 ; kiter < _niter; kiter++) {
if (verbose()>=1) cout << "Iteration : " << kiter << endl;
// update prior from previous iteration
if (kiter>0) {
_P0C = PbarCi;
_N0C = _nbartrue;
}
for (Int_t j = 0 ; j < _ne ; j++) {
Double_t Uj = 0.0;
for (Int_t i = 0 ; i < _nc ; i++)
Uj += PEjCi(j,i) * _P0C[i];
_UjInv[j] = Uj > 0.0 ? 1.0/Uj : 0.0;
}
// Unfolding matrix M
_nbartrue = 0.0;
for (Int_t i = 0 ; i < _nc ; i++) {
Double_t nbarC = 0.0;
for (Int_t j = 0 ; j < _ne ; j++) {
Double_t Mij = _UjInv[j] * PEjCiEff(j,i) * _P0C[i];
_Mij(i,j) = Mij;
nbarC += Mij * _nEstj[j];
}
_nbarCi[i] = nbarC;
_nbartrue += nbarC; // best estimate of true number of events
}
// new estimate of true distribution
PbarCi= _nbarCi;
PbarCi *= 1.0/_nbartrue;
#ifndef OLDERRS
if (_dosys!=2) {
if (kiter <= 0) {
_dnCidnEj= _Mij;
} else {
#ifndef OLDMULT
TVectorD en(_nc), nr(_nc);
for (Int_t i = 0 ; i < _nc ; i++) {
if (_P0C[i]<=0.0) continue;
Double_t ni= 1.0/(_N0C*_P0C[i]);
en[i]= -ni*_efficiencyCi[i];
nr[i]= ni*_nbarCi[i];
}
TMatrixD M1= _dnCidnEj;
M1.NormByColumn(nr,"M");
TMatrixD M2 (TMatrixD::kTransposed, _Mij);
M2.NormByColumn(_nEstj,"M");
M2.NormByRow(en,"M");
TMatrixD M3 (M2, TMatrixD::kMult, _dnCidnEj);
_dnCidnEj.Mult (_Mij, M3);
_dnCidnEj += _Mij;
_dnCidnEj += M1;
#else /* OLDMULT */
TVectorD ksum(_ne);
for (Int_t j = 0 ; j < _ne ; j++) {
for (Int_t k = 0 ; k < _ne ; k++) {
Double_t sum = 0.0;
for (Int_t l = 0 ; l < _nc ; l++) {
if (_P0C[l]>0.0) sum += _efficiencyCi[l]*_Mij(l,k)*_dnCidnEj(l,j)/_P0C[l];
}
ksum[k]= sum;
}
for (Int_t i = 0 ; i < _nc ; i++) {
Double_t dsum = _P0C[i]>0 ? _dnCidnEj(i,j)*_nbarCi[i]/_P0C[i] : 0.0;
for (Int_t k = 0 ; k < _ne ; k++) {
dsum -= _Mij(i,k)*_nEstj[k]*ksum[k];
}
// update dnCidnEj. Note that we can do this in-place due to the ordering of the accesses.
_dnCidnEj(i,j) = _Mij(i,j) + dsum/_N0C;
}
}
#endif
}
}
#endif
if (_dosys) {
#ifndef OLDERRS2
if (kiter > 0) {
TVectorD mbyu(_ne);
for (Int_t j = 0 ; j < _ne ; j++) {
mbyu[j]= _UjInv[j]*_nEstj[j]/_N0C;
}
TMatrixD A= _Mij;
A.NormByRow (mbyu, "M");
TMatrixD B(A, TMatrixD::kMult, PEjCi);
TMatrixD dnCidPjkUpd (B, TMatrixD::kMult, _dnCidPjk);
Int_t nec= _ne*_nc;
for (Int_t i = 0 ; i < _nc ; i++) {
if (_P0C[i]<=0.0) continue; // skip loop: dnCidPjkUpd(i,jk) will also be 0 because _Mij(i,j) will be 0
Double_t r= PbarCi[i]/_P0C[i];
for (Int_t jk= 0; jk<nec; jk++)
_dnCidPjk(i,jk)= r*_dnCidPjk(i,jk) - dnCidPjkUpd(i,jk);
}
}
#else /* OLDERRS2 */
if (kiter == _niter-1) // used to only calculate _dnCidPjk for the final iteration
#endif
for (Int_t j = 0 ; j < _ne ; j++) {
if (_UjInv[j]==0.0) continue;
Double_t mbyu= _UjInv[j]*_nEstj[j];
Int_t j0= j*_nc;
for (Int_t i = 0 ; i < _nc ; i++) {
Double_t b= -mbyu * _Mij(i,j);
for (Int_t k = 0 ; k < _nc ; k++) _dnCidPjk(i,j0+k) += b*_P0C[k];
if (_efficiencyCi[i]!=0.0)
_dnCidPjk(i,j0+i) += (_P0C[i]*mbyu - _nbarCi[i]) / _efficiencyCi[i];
}
}
}
// no need to smooth the last iteraction
if (_smoothit && kiter < (_niter-1)) smooth(PbarCi);
// Chi2 based on Poisson errors
Double_t chi2 = getChi2(PbarCi, _P0C, _nbartrue);
if( verbose() >= 1 ) {
cout << "Chi^2 of change " << chi2 << endl;
}
// Break out if chi^2/dof < 1 when so configured:
// if( _usechi2 && chi2/float(_nc) < 1.0 ) {
// if( verbose() >= 1 ) {
// cout << "Chi^2/d.o.f. < 1, stop iterating" << endl;
// }
// break;
// }
// and repeat
}
}
//-------------------------------------------------------------------------
void RooUnfoldBayes::getCovariance()
{
if (_dosys!=2) {
if (verbose()>=1) cout << "Calculating covariances due to number of measured events" << endl;
// Create the covariance matrix of result from that of the measured distribution
_cov.ResizeTo (_nc, _nc);
#ifdef OLDERRS
const TMatrixD& Dprop= _Mij;
#else
const TMatrixD& Dprop= _dnCidnEj;
#endif
if (_haveCovMes) {
ABAT (Dprop, GetMeasuredCov(), _cov);
} else {
TVectorD v= Emeasured();
v.Sqr();
ABAT (Dprop, v, _cov);
}
}
if (_dosys) {
if (verbose()>=1) cout << "Calculating covariance due to unfolding matrix..." << endl;
const TMatrixD& Eres= _res->Eresponse();
TVectorD Vjk(_ne*_nc); // vec(Var(j,k))
for (Int_t j = 0 ; j < _ne ; j++) {
Int_t j0= j*_nc;
for (Int_t i = 0 ; i < _nc ; i++) {
Double_t e= Eres(j,i);
Vjk[j0+i]= e*e;
}
}
if (_dosys!=2) {
TMatrixD covres(_nc,_nc);
ABAT (_dnCidPjk, Vjk, covres);
_cov += covres;
} else {
_cov.ResizeTo (_nc, _nc);
ABAT (_dnCidPjk, Vjk, _cov);
}
}
}
//-------------------------------------------------------------------------
void RooUnfoldBayes::smooth(TVectorD& PbarCi) const
{
// Smooth unfolding distribution. PbarCi is the array of proababilities
// to be smoothed PbarCi; nevts is the numbers of events
// (needed to calculate suitable errors for the smearing).
// PbarCi is returned with the smoothed distribution.
if (_res->GetDimensionTruth() != 1) {
cerr << "Smoothing only implemented for 1-D distributions" << endl;
return;
}
if (verbose()>=1) cout << "Smoothing." << endl;
TH1::SmoothArray (_nc, PbarCi.GetMatrixArray(), 1);
return;
}
//-------------------------------------------------------------------------
Double_t RooUnfoldBayes::getChi2(const TVectorD& prob1,
const TVectorD& prob2,
Double_t nevents) const
{
// calculate the chi^2. prob1 and prob2 are the probabilities
// and nevents is the number of events used to calculate the probabilities
Double_t chi2= 0.0;
Int_t n= prob1.GetNrows();
if (verbose()>=2) cout << "chi2 " << n << " " << nevents << endl;
for (Int_t i = 0 ; i < n ; i++) {
Double_t psum = (prob1[i] + prob2[i])*nevents;
Double_t pdiff = (prob1[i] - prob2[i])*nevents;
if (psum > 1.0) {
chi2 = chi2 + (pdiff*pdiff)/psum;
} else {
chi2 = chi2 + (pdiff*pdiff);
}
}
return(chi2);
}
//-------------------------------------------------------------------------
void RooUnfoldBayes::Print(Option_t* option) const
{
RooUnfold::Print (option);
if (_nc<=0 || _ne<=0) return;
// Print out some useful info of progress so far
cout << "-------------------------------------------" << endl;
cout << "Unfolding Algorithm" << endl;
cout << "Generated (Training):" << endl;
cout << " Total Number of bins : " << _nc << endl;
cout << " Total Number of events : " << _nCi.Sum() << endl;
cout << "Measured (Training):" << endl;
cout << " Total Number of bins : " << _ne << endl;
cout << "Input (for unfolding):" << endl;
cout << " Total Number of events : " << _nEstj.Sum() << endl;
cout << "Output (unfolded):" << endl;
cout << " Total Number of events : " << _nbarCi.Sum() <<endl;
cout << "-------------------------------------------\n" << endl;
if (((_nEstj.Sum())!=0) || ((_nCi.Sum())!=0)) {
Int_t iend = min(_nCi.GetNrows(),_nEstj.GetNrows());
cout << " \tTrain \tTest\tUnfolded"<< endl;
cout << "Bin \tTruth \tInput\tOutput"<< endl;
for (Int_t i=0; i < iend ; i++) {
if ((_nCi[i] == 0) && (_nEstj[i] == 0) &&
(_nEstj[i] == 0) && (_nbarCi[i]==0)) continue;
cout << i << "\t" << _nCi[i] \
<< "\t " << _nEstj[i] << "\t " << _nbarCi[i] << endl;
}
// if the number of bins is different
if (_nCi.GetNrows() > _nEstj.GetNrows() ) {
for (Int_t i=iend; i < _nCi.GetNrows() ; i++) {
cout << i << "\t " << _nCi[i] << endl;
}
}
cout << "--------------------------------------------------------" << endl;
cout << " \t" << (_nCi.Sum())
<< "\t " << (_nEstj.Sum()) << "\t " << (_nbarCi.Sum()) << endl;
cout << "--------------------------------------------------------\n" << endl;
}
}
| [
"[email protected]"
] | |
b221aa0e2cbbe16e0f4cff1746ab843444315f06 | 6268844577048e845ede5d73bcbfebef1a834df0 | /Plotclock/src/arcstuff.cpp | 42554bed628bb1652634e7ccefae1b7d5659b81b | [] | no_license | Cirromulus/esp-spielereien | cc48dd8f419da2f2764de2ac794917d37dcc0ac4 | de7190c6395532fad3741d5574bcd2e68a4a4a52 | refs/heads/master | 2021-11-08T06:15:29.705567 | 2021-10-28T22:13:04 | 2021-10-28T22:13:04 | 152,147,517 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,575 | cpp | #include "arcstuff.hpp"
#include "config.hpp"
#ifndef GLOWINDARK
extern Servo servo_lift;
#endif
extern Servo servo_left;
extern Servo servo_right;
static unsigned servoLift = 1500; //also misused as "is writing" state
static double lastX = rest_position[0];
static double lastY = rest_position[1];
// Writing numeral with bx by being the bottom left originpoint. Scale 1 equals a 20 mm high font.
// The structure follows this principle: move to first startpoint of the numeral, lift down, draw numeral, lift up
void drawNumber(float bx, float by, int num, float scale) {
switch (num) {
case 0:
drawTo(bx + 12 * scale, by + 6 * scale);
lift(LIFT0);
bogenGZS(bx + 7 * scale, by + 10 * scale, 10 * scale, -0.8, 6.7, 0.5);
lift(LIFT1);
break;
case 1:
drawTo(bx + 3 * scale, by + 15 * scale);
lift(LIFT0);
drawTo(bx + 10 * scale, by + 20 * scale);
drawTo(bx + 10 * scale, by + 0 * scale);
lift(LIFT1);
break;
case 2:
drawTo(bx + 2 * scale, by + 12 * scale);
lift(LIFT0);
bogenUZS(bx + 8 * scale, by + 14 * scale, 6 * scale, 3, -0.8, 1);
drawTo(bx + 1 * scale, by + 0 * scale);
drawTo(bx + 12 * scale, by + 0 * scale);
lift(LIFT1);
break;
case 3:
drawTo(bx + 2 * scale, by + 17 * scale);
lift(LIFT0);
bogenUZS(bx + 5 * scale, by + 15 * scale, 5 * scale, 3, -2, 1);
bogenUZS(bx + 5 * scale, by + 5 * scale, 5 * scale, 1.57, -3, 1);
lift(LIFT1);
break;
case 4:
drawTo(bx + 10 * scale, by + 0 * scale);
lift(LIFT0);
drawTo(bx + 10 * scale, by + 20 * scale);
drawTo(bx + 2 * scale, by + 6 * scale);
drawTo(bx + 12 * scale, by + 6 * scale);
lift(LIFT1);
break;
case 5:
drawTo(bx + 2 * scale, by + 5 * scale);
lift(LIFT0);
bogenGZS(bx + 5 * scale, by + 6 * scale, 6 * scale, -2.5, 2, 1);
drawTo(bx + 5 * scale, by + 20 * scale);
drawTo(bx + 12 * scale, by + 20 * scale);
lift(LIFT1);
break;
case 6:
drawTo(bx + 2 * scale, by + 10 * scale);
lift(LIFT0);
bogenUZS(bx + 7 * scale, by + 6 * scale, 6 * scale, 2, -4.4, 1);
drawTo(bx + 11 * scale, by + 20 * scale);
lift(LIFT1);
break;
case 7:
drawTo(bx + 2 * scale, by + 20 * scale);
lift(LIFT0);
drawTo(bx + 12 * scale, by + 20 * scale);
drawTo(bx + 2 * scale, by + 0);
lift(LIFT1);
break;
case 8:
drawTo(bx + 5 * scale, by + 10 * scale);
lift(LIFT0);
bogenUZS(bx + 5 * scale, by + 15 * scale, 5 * scale, 4.7, -1.6, 1);
bogenGZS(bx + 5 * scale, by + 5 * scale, 5 * scale, -4.7, 2, 1);
lift(LIFT1);
break;
case 9:
drawTo(bx + 9 * scale, by + 11 * scale);
lift(LIFT0);
bogenUZS(bx + 7 * scale, by + 15 * scale, 5 * scale, 4, -0.5, 1);
drawTo(bx + 5 * scale, by + 0);
lift(LIFT1);
break;
case 111:
lift(LIFT0);
drawTo(70, 46);
drawTo(65, 43);
drawTo(65, 49);
drawTo(5, 49);
drawTo(5, 45);
drawTo(65, 45);
drawTo(65, 40);
drawTo(5, 40);
drawTo(5, 35);
drawTo(65, 35);
drawTo(65, 30);
drawTo(5, 30);
drawTo(5, 25);
drawTo(65, 25);
drawTo(65, 20);
drawTo(5, 20);
drawTo(60, 44);
drawTo(75.2, 47);
lift(LIFT2);
break;
case 11:
drawTo(bx + 5 * scale, by + 15 * scale);
lift(LIFT0);
bogenGZS(bx + 5 * scale, by + 15 * scale, 0.1 * scale, 1, -1, 1);
delay((PATH_WRITE_DELAY_US << 5) / 1000); // big value
lift(LIFT1);
drawTo(bx + 5 * scale, by + 5 * scale);
lift(LIFT0);
bogenGZS(bx + 5 * scale, by + 5 * scale, 0.1 * scale, 1, -1, 1);
delay((PATH_WRITE_DELAY_US << 5) / 1000);
lift(LIFT1);
break;
}
}
void lift(uint16_t lift_amount) {
#ifndef GLOWINDARK
if (servoLift >= lift_amount) {
while (servoLift >= lift_amount)
{
servoLift--;
servo_lift.writeMicroseconds(servoLift);
delayMicroseconds(LIFTSPEED);
}
}
else {
while (servoLift <= lift_amount) {
servoLift++;
servo_lift.writeMicroseconds(servoLift);
delayMicroseconds(LIFTSPEED);
}
}
delayMicroseconds(PATH_WRITE_DELAY_US); //ease the transition
#else
delayMicroseconds(PATH_WRITE_DELAY_US << 2); //ease the transition
servoLift = lift_amount;
digitalWrite(SERVOPINLIFT, lift_amount == LIFT0);
#endif
}
void bogenUZS(float bx, float by, float radius, int start, int ende, float sqee) {
float inkr = -0.05;
float count = 0;
do {
drawTo(sqee * radius * cos(start + count) + bx,
radius * sin(start + count) + by);
count += inkr;
}
while ((start + count) > ende);
}
void bogenGZS(float bx, float by, float radius, int start, int ende, float sqee) {
float inkr = 0.05;
float count = 0;
do {
drawTo(sqee * radius * cos(start + count) + bx,
radius * sin(start + count) + by);
count += inkr;
}
while ((start + count) <= ende);
}
double return_angle(double a, double b, double c) {
// cosine rule for angle between c and a
return acos((a * a + c * c - b * b) / (2 * a * c));
}
void set_XY(double Tx, double Ty)
{
double dx, dy, c, a1, a2, Hx, Hy;
// calculate triangle between pen, servoLeft and arm joint
// cartesian dx/dy
dx = Tx - O1X;
dy = Ty - O1Y;
// polar lemgth (c) and angle (a1)
c = sqrt(dx * dx + dy * dy); //
a1 = atan2(dy, dx); //
a2 = return_angle(L1, L2, c);
servo_left.writeMicroseconds(floor(((a2 + a1 - M_PI) * SERVOFAKTORLEFT) + SERVOLEFTNULL));
// calculate joinr arm point for triangle of the right servo arm
a2 = return_angle(L2, L1, c);
Hx = Tx + L3 * cos((a1 - a2 + 0.621) + M_PI); //36,5°
Hy = Ty + L3 * sin((a1 - a2 + 0.621) + M_PI);
// calculate triangle between pen joint, servoRight and arm joint
dx = Hx - O2X;
dy = Hy - O2Y;
c = sqrt(dx * dx + dy * dy);
a1 = atan2(dy, dx);
a2 = return_angle(L1, (L2 - L3), c);
servo_right.writeMicroseconds(floor(((a1 - a2) * SERVOFAKTORRIGHT) + SERVORIGHTNULL));
}
void drawTo(double pX, double pY) {
double dx, dy, c;
int i;
uint16_t delay_per_step_u = PATH_WRITE_DELAY_US;
// dx dy of new point
dx = pX - lastX;
dy = pY - lastY;
//path lenght in mm, times 4 equals 4 steps per mm
c = floor(4 * sqrt(dx * dx + dy * dy));
if (c < 1) {
delay_per_step_u >>= 3;
c = 1;
}
for (i = 0; i <= c; i++) {
// draw line point by point
set_XY(lastX + (i * dx / c), lastY + (i * dy / c));
if(servoLift == LIFT0)
delayMicroseconds(delay_per_step_u);
else
delayMicroseconds(delay_per_step_u >> 2);
}
lastX = pX;
lastY = pY;
}
| [
"[email protected]"
] | |
ccfb8274bf7ed2f35f6e9d8992fdd1c5222adb68 | b44e01223d86cf03976ed73a76a1f6d4b869344e | /lab9/part1/NDVector.cpp | b8679cb4a811d355143165280ddde94cc1ff478a | [] | no_license | mnelso12/CSE20212 | 65aece6b4bc16ff97a5659865758ec2cd1e72ee3 | 1399b5c400bd5d8a8a8ea16e1ddd9f7452699194 | refs/heads/master | 2021-01-10T06:05:40.730693 | 2015-12-20T18:10:47 | 2015-12-20T18:10:47 | 48,331,847 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,178 | cpp | // NDVector.cpp, also contains NDVector.h class
// Madelyn Nelson, CSE20212 Lab9
#ifndef NDVECTOR_H
#define NDVECTOR_H
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
template<typename T>
class NDVector {
public:
NDVector( int = 10 ); // default constructor
NDVector( const NDVector<T> & ); // copy constructor
~NDVector(); // deconstructor
int getSize() const; // returns size
const NDVector &operator=( const NDVector<T> & ); // assignment operator
int operator==( const NDVector<T> & )
const; // equality operator
T& operator[](int offset){ return ptr[offset];}
const T& operator[](int offset) const{
return ptr[offset];}
int operator!=( const NDVector<T> &right ) const {
return ! ( *this == right ); // invokes NDVector::operator==
} // end of function operator !=
void push_front( T );
void printVec();
void push_back( T );
void pop_back();
void pop_front();
T accessFront(); // returns front element
T accessLast(); // returns last element
void clear(); // clears vector
T getLast();
void random_shuffle(); // supports other shuffle method
private:
int size; // pointer-based array size
int capacity;
T *ptr; // pointer to first element of pointer-based array
};
#endif
template <typename T>
void NDVector<T>::random_shuffle(){
int tempVal;
int num1, num2;
int count = 0;
while ( count < 300 ) {
num1 = rand()%size;
num2 = rand()%size;
tempVal = ptr[num1];
ptr[num1] = ptr[num2];
ptr[num2] = tempVal;
tempVal = 0;
count++;
}
}
template <typename T>
void NDVector<T>::clear(){
for ( int i = 0; i < capacity; i++ ){ // sets all elements equal to NULL
ptr[i] = NULL;
}
capacity = 0; // capacity and size start over
size = 0;
}
template <typename T>
T NDVector<T>::accessFront(){
return (ptr[0]); // returns the first element
}
template <typename T>
T NDVector<T>::getLast(){
return (ptr[capacity-1]);
}
template <typename T>
T NDVector<T>::accessLast(){
return (ptr[size-1]); // returns the last element
}
template <typename T>
void NDVector<T>::pop_front(){
size--;
ptr[0] = NULL; // gets rid of the first element
}
template <typename T>
void NDVector<T>::pop_back(){
size--;
ptr[size] = NULL; // gets rid of the last one
}
template <typename T>
void NDVector<T>::push_back( T element ){
size++; // we are guna have one more element
if (size >= capacity) // adds new allocated memory if necessary
{
T * tempptr;
tempptr = new T[ capacity*2 ];
for (int j = 0; j < size; j++) {
tempptr[j] = ptr[j];
}
delete [] ptr;
ptr = new T [ capacity*2 ];
ptr = tempptr;
capacity*=2; // double the capacity
}
ptr[size-1] = element; // sets last value equal to inputted element
}
template <typename T>
void NDVector<T>::push_front( T element ){
size++;
if (size >= capacity) // adds new allocated memory if necessary
{
T * tempptr;
tempptr = new T[ capacity*2 ];
for (int j = 0; j < size; j++) {
tempptr[j] = ptr[j];
}
delete [] ptr;
ptr = new T [ capacity*2 ];
ptr = tempptr;
capacity*=2; // double the capacity
}
for (int i = size; i > 0; i--){
ptr[i] = ptr[i-1]; // each element is moved backwards one spot
}
ptr[0] = element; // new element is put in front
}
template <typename T>
void NDVector<T>::printVec() {
int length = getSize();
for (int i = (length-1); i>0; --i){
cout << ptr[i] << ", ";
}
cout << ptr[0] << ";";
cout << endl;
}
template <typename T>
NDVector<T>::NDVector( int arraySize ){ // defualt
size = 0;
capacity = ( arraySize > 0 ? arraySize : 10 ); // validate arraySize
ptr = new T[ capacity ]; // create space for pointer-based array
}
template <typename T>
NDVector<T>::NDVector( const NDVector<T> &arrayToCopy ) : size( arrayToCopy.size) { // copy-constructor
ptr = new T[ size ]; // create space for pointer-based array
for ( int i = 0; i < size; i++ ) {
ptr[ i ] = arrayToCopy.ptr[ i ]; // copy into object
}
}
template <typename T>
NDVector<T>::~NDVector(){ // deconstructor
delete [] ptr; // release pointer-based array space
}
template <typename T>
int NDVector<T>::getSize() const {
return (size); // number of elements in Array
}
template <typename T>
const NDVector<T> &NDVector<T>::operator=( const NDVector<T> &right ) {
if ( &right != this ) {
if ( size != right.size ) {
delete [] ptr; // release space
size = right.size; // resize this object
ptr = new T[ size ]; // create space for array copy
}
for ( int i = 0; i < size; i++ ){
ptr[ i ] = right.ptr[ i ]; // copy array into object
}
}
return (*this); // enables x = y = z function
} // end function operator=
| [
"[email protected]"
] | |
5477d3825b25c51e1fb390c8ce4d02b7f1d92a91 | 1f8882ab84fad4c8fcd41dbedad39a56dc8ad5f6 | /src/ChordFunctions.h | abcfe0485d48ab098c410988b6e77f99617e1ad2 | [] | no_license | ddplows/chordGuesser | 66da72967301d3cb406d31ea6b02033403912f91 | 093d83d08f3b53d6a5125631eb5d4fbba176880a | refs/heads/master | 2021-01-11T19:00:52.174850 | 2017-01-18T18:07:44 | 2017-01-18T18:07:44 | 79,291,052 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,010 | h | /*
* ChordFunctions.h
*
* Created on: Jan 16, 2017
* Author: dave
*/
#ifndef CHORDFUNCTIONS_H_
#define CHORDFUNCTIONS_H_
#include <map>
#include <vector>
#include <string>
#include <cstdint>
static std::map<std::string, std::vector<int8_t>> chordCatalog = {
{"E", std::vector<int8_t> { 0, 2, 2, 1, 0, 0 }},
{"A", std::vector<int8_t> { -1, 0, 2, 2, 2, 0 }},
{"D", std::vector<int8_t> { -1, -1, 0, 2, 3, 2 }},
{"G", std::vector<int8_t> { 3, 2, 0, 0, 0, 3 }},
{"C", std::vector<int8_t> { -1, 3, 2, 0, 1, 0 }},
{"E minor", std::vector<int8_t> { 0, 2, 2, 0, 0, 0 }},
{"A minor", std::vector<int8_t> { 0, 2, 2, 1, 0, 0 }},
{"D7", std::vector<int8_t> { -1, -1, 0, 2, 1, 2 }},
{"A7", std::vector<int8_t> { -1, 0, 2, 0, 2, 0 }},
{"F", std::vector<int8_t> { -1, -1, 3, 2, 1, 1 }}
};
std::string chooseChord(std::vector<int8_t> chordInfo);
std::vector<int8_t> chordToMidi(std::vector<int8_t> fretArr);
#endif /* CHORDFUNCTIONS_H_ */
| [
"[email protected]"
] | |
ff7e304a809160a2a48d4cf93073ce65a5e239a7 | 21144aeafc9c6a7bb38db1c3a0baddebab32a9e5 | /BachelorArbeit/BFilter.h | 193488f6f479ff101f45f2940ad127055419d844 | [] | no_license | PetrosSimidyan/Bloom-Filter | 2e0799014d5655140043ce5adf9c7aa9b917bf43 | 4451e266498e14f1dd8bbeedc05db4a9740b0bf9 | refs/heads/master | 2020-09-01T01:25:09.904420 | 2019-10-31T20:11:40 | 2019-10-31T20:11:40 | 218,840,706 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 930 | h | #pragma once
#ifndef _BFILTER_
#define _BFILTER_
#include "DietzHash.h"
static const ull seedVal = 13634516963058010950;
class BFilter
{
private:
ull hashTabLen;
short numOfHash;
ull *hashTable;
const ull ithHash(ull val, short i) const
{
return ((val >> 32) + i * (val & 0xFFFFFFFF))%(hashTabLen*64);
}
void setBit(const ull ind)
{
hashTable[(ind>>6)] |= ((ull)1 << 63 - (ind & 0x3f));
}
const bool isSet(ull ind) const
{
return (hashTable[ind >> 6] >>(63 - (ind & 0x3f)) & 1);
}
void insertPart(std::vector<ull> input, ull min, ull max)
{
for (ull i = min; i < max; i++)
insert(input[i]);
}
public:
BFilter() = delete;
BFilter(const std::vector<ull>& inputTab, ull len, short k = 4, short m = 8);
BFilter(const BFilter& bf);
~BFilter() { delete[]hashTable; }
const bool insert(ull key);
const bool lookUp(ull key) const;
BFilter& operator=(const BFilter& bf);
};
#endif // !_BFILTER_
| [
"[email protected]"
] | |
ccb4ef6e01739e2e081d48282af5cacb9da0cd64 | 0c0cb7569447b45da05deffe3fb429f966070881 | /Source/PVR/SDK_3.4/Examples/Advanced/ParticleSystem/OGLES3/Content/FragShader.cpp | 6eb4dba81671e35fa2522f83e313c48af15d20c3 | [] | no_license | njligames/GameEngine | 6bff1ce1e48f47ccb79f03d49501683c97e4bbf6 | c0193fd5877afec246915f406c4c66d19e028f3c | refs/heads/master | 2021-01-22T14:39:09.697529 | 2017-01-23T05:18:09 | 2017-01-23T05:18:09 | 68,660,880 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,002 | cpp | // This file was created by Filewrap 1.2
// Little endian mode
// DO NOT EDIT
#include "../PVRTMemoryFileSystem.h"
// using 32 bit to guarantee alignment.
#ifndef A32BIT
#define A32BIT static const unsigned int
#endif
// ******** Start: FragShader.fsh ********
// File data
static const char _FragShader_fsh[] =
"#version 300 es\r\n"
"\r\n"
"in highp vec3 vNormal;\r\n"
"in highp vec3 vLightDirection;\r\n"
"layout (location = 0) out lowp vec4 oColour;\r\n"
"\r\n"
"void main()\r\n"
"{\r\n"
"\thighp float inv_lightdist = 1.0 / length(vLightDirection);\r\n"
"\thighp float diffuse = max(dot(normalize(vNormal), vLightDirection * inv_lightdist), 0.0);\r\n"
"\toColour = vec4(vec3(diffuse) * inv_lightdist * 10.0, 1.0);\r\n"
"}\r\n";
// Register FragShader.fsh in memory file system at application startup time
static CPVRTMemoryFileSystem RegisterFile_FragShader_fsh("FragShader.fsh", _FragShader_fsh, 356);
// ******** End: FragShader.fsh ********
| [
"[email protected]"
] | |
638e23f871172705ae14a8ac3cb983e60180bad1 | 0e67921a73755903195d55132409036c9b6e1938 | /Utilities/Window/Window.h | 412fe9b670e4ffa6d3a01453ba4a9059434c035b | [] | no_license | christian-plourde/COMP-477-A1 | 9f8768b9902f092c21f00fa21c621b3b7b7f69b9 | ae50465486deec6b277e47877cedb2e1fdd2d764 | refs/heads/master | 2020-07-31T16:37:06.341647 | 2019-10-09T18:24:48 | 2019-10-09T18:24:48 | 210,677,125 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,031 | h | #ifndef COMP_371_A3_WINDOW
#define COMP_371_A3_WINDOW
#include <glew.h>
#include <GLFW/glfw3.h>
#include "glm.hpp"
#include "../Objects/MVP.h"
#include "../Shading/Shader.h"
#include "../ErrorHandling/ErrorHandlingFunctions.h"
class Window
{
private:
int width;
int height;
const char* title;
glm::vec3 back_color;
GLFWwindow* window_handle;
GLFWwindow* initHandle();
public:
Window();
Window(int width, int height, const char* title);
~Window();
inline const char* getTitle(){return title;}
inline int getHeight(){return height;}
inline int getWidth(){return width;}
inline glm::vec3 getBackColor(){return back_color;}
inline GLFWwindow* getHandle(){return window_handle;}
void setBackColor(float red, float green, float blue);
void set_keyboard_callback(GLFWkeyfun);
void PrepareDraw(); //call before beginning to draw
void EndDraw(); //call when finished drawing
};
#endif | [
"[email protected]"
] | |
bf77993208fdcb1b5402f7d550e2376d9a5df5e6 | 6930cbc7f72d4086352b17b2895c1c7c0effc8c0 | /Project/Project_1_MasterMind_V8_Final_V2/main.cpp | cc8aa5437872c7ce0a597344b5c9e5907f1f38c1 | [] | no_license | javierborja95/JB_CSC5 | 863a6366d7a2b67fd892f631dc282fab802ca862 | 29d5e8a6a5e750cb8b923b010b3ebccec3f189fb | refs/heads/master | 2021-04-12T12:03:05.969346 | 2016-07-29T17:43:40 | 2016-07-29T17:43:40 | 61,830,852 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,345 | cpp | /*
* File: main.cpp
* Author: Javier Borja
* Created on July 27, 2016, 3:40 PM
* Purpose: Player guesses a 4 digit combination against the computer.
*/
//System Libraries
#include <iostream> //Input/ Output Stream Library
#include <iomanip> //Output Manipulation
#include <ctime> //Computer Time for seed
#include <cstdlib> //Library for random number seed
#include <string> //String library
#include <sstream> //String Stream Library
#include <fstream> //File I/O
#include <vector> //Vectors
using namespace std; //Namespace of the System Libraries
//User Libraries
#include "Score.h"
//Global Constants
const int SIZE=4; //Size of code
//Function Prototypes
bool game(int &turn,bool&,bool=true);//A single game of MasterMind
bool turn(int[][SIZE],bool&,bool); //A single turn of mastermind
void help(int[][SIZE]); //Hint
void read(); //Read rules
void menu(); //Menu
void sort(int[],int); //Sort hint
void sort(vector<Score>&,int); //Sort leaderboard
void swap(int[],int,int); //Swap
void lderBrd(); //Leaderboard
void result(int,bool,bool,bool,int[][SIZE]); //Result of game
//Execution
int main(int argc, char** argv) {
//Set Random seed
srand(static_cast<unsigned int>(time(0)));
//Variables
Score user; //Player
user.wins=0; //Wins
user.loss=0; //Losses
char choice; //Menu choice
int trn; //Turn
bool win; //Game result. True results in win
bool hint; //Hint
bool ez; //Difficulty easy or hard
ofstream out; //Output results to file
//Input Data
cout<<"Welcome to MasterMind: A logic codebreaker game.\n"
"Enter your first and last name and press return. Omit any middle"
" initial you might have."<<endl;
cin>>user.first>>user.last;
//Process Data & Menu
cout<<"Welcome "<<user.first<<" "<<user.last<<endl<<endl;
do{
menu();
cin>>choice;
cout<<endl;
switch(choice){
case'1':
win=game(trn,hint);
if(hint==true&&win==true)
break;
if(hint==true&&win==false){
user.loss++;
break;
}
if(win==true)
user.wins++;
else
user.loss++;
break;
case'2':
ez=false;
win=game(trn,hint,ez);
if(hint==true&&win==true)
break;
if(hint==true&&win==false){
user.loss++;
break;
}
if(win==true)
user.wins+=2;
else
user.loss++;
break;
case'3':read();break;
case'4':lderBrd();
}
}while (choice=='1'||choice=='2'||choice=='3'||choice=='4');
//Output Data and output to file
cout<<"Thanks for playing "<<user.first<<" "<<user.last<<endl;
cout<<"Wins this session"<<setw(5)<<"= "<<user.wins<<endl;
cout<<"Losses this session = "<<user.loss<<endl;
out.open("stats.dat",ios::app); //Append to file
if (out.fail())
cout<<"Input file 1 opening failed.\n";
out<<'\r'<<user.wins<<' '<<user.loss<<' '
<<user.first<<' '<<user.last;
out.close();
return 0;
}
bool game(int &trn,bool &hint,bool ez){
//Set variables
const int ROW=2; //Two codes, Ai choice and player choice
int code[ROW][SIZE]; //2x4 Array
bool win;
bool nxtTrn;
nxtTrn=true; //Decides to go to next turn
//Process Data and get random combination
trn=1;
hint=false;
if(ez==true){
//Normal Mode
code[0][0]=(rand()%8+1);
do{
code[0][1]=(rand()%8+1);
}while (code[0][1]==code[0][0]); //No duplicates
do{
code[0][2]=(rand()%8+1);
}while (code[0][2]==code[0][1]||code[0][2]==code[0][0]); //No duplicates
do{
code[0][3]=(rand()%8+1);
}while (code[0][3]==code[0][2]||code[0][3]==code[0][1]|| //No duplicates
code[0][3]==code[0][0]);
for(int maxTrn=8;(trn<=maxTrn&&nxtTrn==true);trn++){//Max turns 8
cout<<"Turn = "<<trn<<endl;
nxtTrn=turn(code,hint,ez);
}
}
else{
//Hard Mode
code[0][0]=(rand()%8+1); //Duplicates allowed
code[0][1]=(rand()%8+1);
code[0][2]=(rand()%8+1);
code[0][3]=(rand()%8+1);
for(int maxTrn=12;(trn<=maxTrn&&nxtTrn==true);trn++){//Max turns 12
cout<<"Turn = "<<trn<<endl;
nxtTrn=turn(code,hint,ez);
}
}
trn--; //Offset the extra turn from end of loop
if(nxtTrn==true)
win=false; //Lose if the game still wants to go to another turn
else win=true; //Win if game doesn't need to go to another turn
//Output Result
result(trn,win,hint,ez,code);
return(win);
}
bool turn(int a[][SIZE],bool& hint,bool ez){
//Declare Variables
int orig1,orig2,orig3,orig4,orig5,orig6,orig7,orig8;
bool nxtTrn;
nxtTrn=true;
stringstream ss1,ss2,ss3,ss4;
char p1, p2, p3, p4;//Strip 4 character combination to 4 separate ints
//Input Data
if(ez==true)
cout<<"Enter a 4 digit combination using numbers 1-8, no duplicates"<<endl;
else
cout<<"Enter a 4 digit combination using numbers 1-8, duplicates allowed\n";
cout<<"To call a hint input 4 zeros (0,0,0,0)"<<endl;
cin>>p1>>p2>>p3>>p4; //Input player, 4 character combination
//Process Data
ss1<<p1; ss1>>a[1][0]; //Convert char to ints
ss2<<p2; ss2>>a[1][1];
ss3<<p3; ss3>>a[1][2];
ss4<<p4; ss4>>a[1][3];
orig1=a[1][0]; orig5=a[0][0]; //Copy original Values
orig2=a[1][1]; orig6=a[0][1];
orig3=a[1][2]; orig7=a[0][2];
orig4=a[1][3]; orig8=a[0][3];
//Output Data
if(a[0][0]==a[1][0]){ //If number and position match
cout<<"X";
a[1][0]=-1; //Change value to prevent duplication bugs when
a[0][0]=-1; // comparing with other digits
} //Prevents outputs like 'XXXOOO'
if(a[0][1]==a[1][1]){ //If number and position match
cout<<"X";
a[1][1]=-2;
a[0][1]=-2;
}
if(a[0][2]==a[1][2]){ //If number and position match
cout<<"X";
a[1][2]=-3;
a[0][2]=-3;
}
if(a[0][3]==a[1][3]){ //If number and position match
cout<<"X";
a[1][3]=-4;
a[0][3]=-4;
}
if(a[1][0]==a[0][1]||a[1][0]==a[0][2]||a[1][0]==a[0][3]){ //If numbers match
cout<<"O";
a[1][0]=-1;
}
if(a[1][1]==a[0][0]||a[1][1]==a[0][2]||a[1][1]==a[0][3]){ //If numbers match
cout<<"O";
a[1][1]=-2;
}
if(a[1][2]==a[0][0]||a[1][2]==a[0][1]||a[1][2]==a[0][3]){ //If numbers match
cout<<"O";
a[1][2]=-3;
}
if(a[1][3]==a[0][0]||a[1][3]==a[0][1]||a[1][3]==a[0][2]){ //If numbers match
cout<<"O";
a[1][3]=-4;
}
if(a[1][0]==0&&a[1][1]==0&&a[1][2]==0&&a[1][3]==0){
hint=true;
help(a);
}
a[1][0]=orig1; //Set back to original values
a[1][1]=orig2;
a[1][2]=orig3;
a[1][3]=orig4;
a[0][0]=orig5;
a[0][1]=orig6;
a[0][2]=orig7;
a[0][3]=orig8;
nxtTrn=(a[0][0]==a[1][0]&&a[0][1]==a[1][1]&&
a[0][2]==a[1][2]&&a[0][3]==a[1][3])?false:true;
//If combinations equal then no need for next turn.
if(ez==true) //Different output based on mode, just for program to look pretty
cout<<endl<<"************************************************************";
else
cout<<endl<<"*****************************************************************";
cout<<endl;
return(nxtTrn);
}
void help(int a[][SIZE]){
//Declare Variables
int b[SIZE]; //Original array, sorted
//Input data
for(int i=0;i<SIZE;i++){
b[i]=a[0][i];
}
//Process Data
sort(b,SIZE);
//Output Data
cout<<"Your hint:"<<endl;
for(int i=0;i<SIZE;i++){
cout<<b[i];
}
cout<<endl;
}
void sort(int a[],int n){
for(int i=0;i<n-1;i++){
for(int x=i+1;x<n;x++){
if(a[i]>a[x]){
swap(a,i,x);
}
}
}
}
void swap(int a[],int x,int y){
a[x]=a[x]^a[y];
a[y]=a[x]^a[y];
a[x]=a[x]^a[y];
}
void sort(vector<Score>& a,int n){
//Declare Variables
bool goAgn;
//Process Data
do{
goAgn=false;
for(int i=0;i<n-1;i++){
if(a[i].wins<a[i+1].wins){
swap(a[i],a[i+1]);
goAgn=true;
}
}
}while(goAgn==true);
}
void result(int turn, bool win,bool hint,bool ez,int a[][SIZE]){//Result of game
//Output Data
if(win==0){
cout<<"You lose!\n"
"Better luck next time.\n"
"The code was actually:"<<endl;
cout<<a[0][0]<<a[0][1]<<a[0][2]<<a[0][3]<<endl<<endl;
return;
}
if (hint==true){
cout<<"You used a hint, win doesn't count."<<endl<<endl;
return;
}
else if(ez==true){
switch(turn){
case 1:
case 2:
case 3:
cout<<"Wow, very lucky. You win!"<<endl;break;
case 4:
cout<<"Congratulations!\n"
"You're very smart, you won in 4 turns!"
<<endl;break;
case 5:
cout<<"Congratulations!\n"
<<"You won in 5 turns. Very good performance!"
<<endl;break;
case 6:
cout<<"Congratulations!\n"
<<"You won in 6 turns. Good performance!"
<<endl;break;
case 7:
cout<<"Congratulations!\n"
<<"You won in 7 turns. Decent performance."
<<endl;break;
default:
cout<<"That was close! You barely won."
<<endl;break;
}
}
else{
switch(turn){
case 1:
case 2:
case 3:
cout<<"Wow, very lucky. You win!"<<endl;break;
case 4:
cout<<"Congratulations!\n"
"You're very smart, you won in 4 turns!"
<<endl;break;
case 5:
cout<<"Congratulations!\n"
<<"You won in 5 turns. Very good performance!"
<<endl;break;
case 6:
cout<<"Congratulations!\n"
<<"You won in 6 turns. Very good performance!"
<<endl;break;
case 7:
cout<<"Congratulations!\n"
<<"You won in 7 turns. Good performance!"
<<endl;break;
case 8:
cout<<"Congratulations!\n"
<<"You won in 8 turns. Good performance!"
<<endl;break;
case 9:
cout<<"Congratulations!\n"
<<"You won in 9 turns. Decent performance."
<<endl;break;
case 10:
cout<<"Congratulations!\n"
<<"You won in 10 turns. Good job."
<<endl;break;
case 11:
cout<<"Congratulations!\n"
<<"You won in 11 turns. Good job."
<<endl;break;
default:
cout<<"That was close! You barely won."
<<endl;break;
}
cout<<"Because this is hard mode, this win counts as two wins!"<<endl;
}
cout<<endl;
}
void read(){ //Input Rules to display
//Declare Variables
ifstream line;
string string;
//Process and Output Data
line.open("rules.dat");
if(line.fail()){
cout<<"Input file opening failed.\n";
}
cout<<endl;
while(getline(line,string)){
cout<<string<<endl;
}
line.close();
cout<<endl<<endl;
}
void menu(){
cout<<"Press 1 to play Normal Mode MasterMind.\n"
"Press 2 to play Hard Mode MasterMind.\n"
"Press 3 to learn how to play.\n"
"Press 4 to see the leaderboard.\n"
"Press anything else to exit."<<endl;
}
void lderBrd(){
//Declare Variables
int MAX=100;
vector<Score> player(MAX);
ifstream line;
int count=0;
//Process and Output Data
line.open("stats.dat");
if(line.fail()){
cout<<"Input file opening failed.\n";
return;
}
cout<<"Sorted by amount of wins per session."<<endl;
do{
line>>player[count].wins;
line>>player[count].loss;
line>>player[count].first;
line>>player[count].last;
count++;
}while(!line.eof());
sort(player,count);
for(int i=0;i<count;i++){
cout<<endl;
cout<<player[i].first<<" "<<player[i].last<<",\ngot "<<player[i].wins
<<" wins and "<<player[i].loss<<" losses."<<endl;
}
cout<<endl;
cout<<"Can you beat "<<player[0].first<<" "<<player[0].last<<"?"<<endl<<endl;
} | [
"[email protected]"
] | |
9def1d549c916c03c89016b389923e2b9289b4a5 | ce300aa88d78015ae4232e70720b118029e0e0ce | /src/chain.h | f7699e324264829091a542b0ad15814bdd444960 | [
"MIT"
] | permissive | bitnows/bitnow | ce9b4b8e70c49669640164ae0115c24051b69978 | 235e54aa6981fa3f26373b253bb35dad49aa2a07 | refs/heads/master | 2023-05-28T05:15:49.382581 | 2021-06-10T08:16:31 | 2021-06-10T08:16:31 | 375,585,076 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,403 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2015-2017 The PIVX developers
// Copyright (c) 2018-2019 The Bitnow Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_CHAIN_H
#define BITCOIN_CHAIN_H
#include "pow.h"
#include "primitives/block.h"
#include "tinyformat.h"
#include "uint256.h"
#include "util.h"
#include <vector>
#include <boost/foreach.hpp>
#include <boost/lexical_cast.hpp>
struct CDiskBlockPos {
int nFile;
unsigned int nPos;
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
{
READWRITE(VARINT(nFile));
READWRITE(VARINT(nPos));
}
CDiskBlockPos()
{
SetNull();
}
CDiskBlockPos(int nFileIn, unsigned int nPosIn)
{
nFile = nFileIn;
nPos = nPosIn;
}
friend bool operator==(const CDiskBlockPos& a, const CDiskBlockPos& b)
{
return (a.nFile == b.nFile && a.nPos == b.nPos);
}
friend bool operator!=(const CDiskBlockPos& a, const CDiskBlockPos& b)
{
return !(a == b);
}
void SetNull()
{
nFile = -1;
nPos = 0;
}
bool IsNull() const { return (nFile == -1); }
};
enum BlockStatus {
//! Unused.
BLOCK_VALID_UNKNOWN = 0,
//! Parsed, version ok, hash satisfies claimed PoW, 1 <= vtx count <= max, timestamp not in future
BLOCK_VALID_HEADER = 1,
//! All parent headers found, difficulty matches, timestamp >= median previous, checkpoint. Implies all parents
//! are also at least TREE.
BLOCK_VALID_TREE = 2,
/**
* Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid, no duplicate txids,
* sigops, size, merkle root. Implies all parents are at least TREE but not necessarily TRANSACTIONS. When all
* parent blocks also have TRANSACTIONS, CBlockIndex::nChainTx will be set.
*/
BLOCK_VALID_TRANSACTIONS = 3,
//! Outputs do not overspend inputs, no double spends, coinbase output ok, immature coinbase spends, BIP30.
//! Implies all parents are also at least CHAIN.
BLOCK_VALID_CHAIN = 4,
//! Scripts & signatures ok. Implies all parents are also at least SCRIPTS.
BLOCK_VALID_SCRIPTS = 5,
//! All validity bits.
BLOCK_VALID_MASK = BLOCK_VALID_HEADER | BLOCK_VALID_TREE | BLOCK_VALID_TRANSACTIONS |
BLOCK_VALID_CHAIN |
BLOCK_VALID_SCRIPTS,
BLOCK_HAVE_DATA = 8, //! full block available in blk*.dat
BLOCK_HAVE_UNDO = 16, //! undo data available in rev*.dat
BLOCK_HAVE_MASK = BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO,
BLOCK_FAILED_VALID = 32, //! stage after last reached validness failed
BLOCK_FAILED_CHILD = 64, //! descends from failed block
BLOCK_FAILED_MASK = BLOCK_FAILED_VALID | BLOCK_FAILED_CHILD,
};
/** The block chain is a tree shaped structure starting with the
* genesis block at the root, with each block potentially having multiple
* candidates to be the next block. A blockindex may have multiple pprev pointing
* to it, but at most one of them can be part of the currently active branch.
*/
class CBlockIndex
{
public:
//! pointer to the hash of the block, if any. memory is owned by this CBlockIndex
const uint256* phashBlock;
//! pointer to the index of the predecessor of this block
CBlockIndex* pprev;
//! pointer to the index of the next block
CBlockIndex* pnext;
//! pointer to the index of some further predecessor of this block
CBlockIndex* pskip;
//ppcoin: trust score of block chain
uint256 bnChainTrust;
//! height of the entry in the chain. The genesis block has height 0
int nHeight;
//! Which # file this block is stored in (blk?????.dat)
int nFile;
//! Byte offset within blk?????.dat where this block's data is stored
unsigned int nDataPos;
//! Byte offset within rev?????.dat where this block's undo data is stored
unsigned int nUndoPos;
//! (memory only) Total amount of work (expected number of hashes) in the chain up to and including this block
uint256 nChainWork;
//! Number of transactions in this block.
//! Note: in a potential headers-first mode, this number cannot be relied upon
unsigned int nTx;
//! (memory only) Number of transactions in the chain up to and including this block.
//! This value will be non-zero only if and only if transactions for this block and all its parents are available.
//! Change to 64-bit type when necessary; won't happen before 2030
unsigned int nChainTx;
//! Verification status of this block. See enum BlockStatus
unsigned int nStatus;
unsigned int nFlags; // ppcoin: block index flags
enum {
BLOCK_PROOF_OF_STAKE = (1 << 0), // is proof-of-stake block
BLOCK_STAKE_ENTROPY = (1 << 1), // entropy bit for stake modifier
BLOCK_STAKE_MODIFIER = (1 << 2), // regenerated stake modifier
};
// proof-of-stake specific fields
uint256 GetBlockTrust() const;
uint64_t nStakeModifier; // hash modifier for proof-of-stake
unsigned int nStakeModifierChecksum; // checksum of index; in-memeory only
COutPoint prevoutStake;
unsigned int nStakeTime;
uint256 hashProofOfStake;
int64_t nMint;
int64_t nMoneySupply;
//! block header
int nVersion;
uint256 hashMerkleRoot;
unsigned int nTime;
unsigned int nBits;
unsigned int nNonce;
//! (memory only) Sequential id assigned to distinguish order in which blocks are received.
uint32_t nSequenceId;
void SetNull()
{
phashBlock = NULL;
pprev = NULL;
pskip = NULL;
nHeight = 0;
nFile = 0;
nDataPos = 0;
nUndoPos = 0;
nChainWork = 0;
nTx = 0;
nChainTx = 0;
nStatus = 0;
nSequenceId = 0;
nMint = 0;
nMoneySupply = 0;
nFlags = 0;
nStakeModifier = 0;
nStakeModifierChecksum = 0;
prevoutStake.SetNull();
nStakeTime = 0;
nVersion = 0;
hashMerkleRoot = uint256();
nTime = 0;
nBits = 0;
nNonce = 0;
}
CBlockIndex()
{
SetNull();
}
CBlockIndex(const CBlock& block)
{
SetNull();
nVersion = block.nVersion;
hashMerkleRoot = block.hashMerkleRoot;
nTime = block.nTime;
nBits = block.nBits;
nNonce = block.nNonce;
//Proof of Stake
bnChainTrust = uint256();
nMint = 0;
nMoneySupply = 0;
nFlags = 0;
nStakeModifier = 0;
nStakeModifierChecksum = 0;
hashProofOfStake = uint256();
if (block.IsProofOfStake()) {
SetProofOfStake();
prevoutStake = block.vtx[1].vin[0].prevout;
nStakeTime = block.nTime;
} else {
prevoutStake.SetNull();
nStakeTime = 0;
}
}
CDiskBlockPos GetBlockPos() const
{
CDiskBlockPos ret;
if (nStatus & BLOCK_HAVE_DATA) {
ret.nFile = nFile;
ret.nPos = nDataPos;
}
return ret;
}
CDiskBlockPos GetUndoPos() const
{
CDiskBlockPos ret;
if (nStatus & BLOCK_HAVE_UNDO) {
ret.nFile = nFile;
ret.nPos = nUndoPos;
}
return ret;
}
CBlockHeader GetBlockHeader() const
{
CBlockHeader block;
block.nVersion = nVersion;
if (pprev)
block.hashPrevBlock = pprev->GetBlockHash();
block.hashMerkleRoot = hashMerkleRoot;
block.nTime = nTime;
block.nBits = nBits;
block.nNonce = nNonce;
return block;
}
uint256 GetBlockHash() const
{
return *phashBlock;
}
int64_t GetBlockTime() const
{
return (int64_t)nTime;
}
enum { nMedianTimeSpan = 11 };
int64_t GetMedianTimePast() const
{
int64_t pmedian[nMedianTimeSpan];
int64_t* pbegin = &pmedian[nMedianTimeSpan];
int64_t* pend = &pmedian[nMedianTimeSpan];
const CBlockIndex* pindex = this;
for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
*(--pbegin) = pindex->GetBlockTime();
std::sort(pbegin, pend);
return pbegin[(pend - pbegin) / 2];
}
bool IsProofOfWork() const
{
return !(nFlags & BLOCK_PROOF_OF_STAKE);
}
bool IsProofOfStake() const
{
return (nFlags & BLOCK_PROOF_OF_STAKE);
}
void SetProofOfStake()
{
nFlags |= BLOCK_PROOF_OF_STAKE;
}
unsigned int GetStakeEntropyBit() const
{
unsigned int nEntropyBit = ((GetBlockHash().Get64()) & 1);
if (fDebug || GetBoolArg("-printstakemodifier", false))
LogPrintf("GetStakeEntropyBit: nHeight=%u hashBlock=%s nEntropyBit=%u\n", nHeight, GetBlockHash().ToString().c_str(), nEntropyBit);
return nEntropyBit;
}
bool SetStakeEntropyBit(unsigned int nEntropyBit)
{
if (nEntropyBit > 1)
return false;
nFlags |= (nEntropyBit ? BLOCK_STAKE_ENTROPY : 0);
return true;
}
bool GeneratedStakeModifier() const
{
return (nFlags & BLOCK_STAKE_MODIFIER);
}
void SetStakeModifier(uint64_t nModifier, bool fGeneratedStakeModifier)
{
nStakeModifier = nModifier;
if (fGeneratedStakeModifier)
nFlags |= BLOCK_STAKE_MODIFIER;
}
/**
* Returns true if there are nRequired or more blocks of minVersion or above
* in the last Params().ToCheckBlockUpgradeMajority() blocks, starting at pstart
* and going backwards.
*/
static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired);
std::string ToString() const
{
return strprintf("CBlockIndex(pprev=%p, nHeight=%d, merkle=%s, hashBlock=%s)",
pprev, nHeight,
hashMerkleRoot.ToString(),
GetBlockHash().ToString());
}
//! Check whether this block index entry is valid up to the passed validity level.
bool IsValid(enum BlockStatus nUpTo = BLOCK_VALID_TRANSACTIONS) const
{
assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
if (nStatus & BLOCK_FAILED_MASK)
return false;
return ((nStatus & BLOCK_VALID_MASK) >= nUpTo);
}
//! Raise the validity level of this block index entry.
//! Returns true if the validity was changed.
bool RaiseValidity(enum BlockStatus nUpTo)
{
assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
if (nStatus & BLOCK_FAILED_MASK)
return false;
if ((nStatus & BLOCK_VALID_MASK) < nUpTo) {
nStatus = (nStatus & ~BLOCK_VALID_MASK) | nUpTo;
return true;
}
return false;
}
//! Build the skiplist pointer for this entry.
void BuildSkip();
//! Efficiently find an ancestor of this block.
CBlockIndex* GetAncestor(int height);
const CBlockIndex* GetAncestor(int height) const;
};
/** Used to marshal pointers into hashes for db storage. */
class CDiskBlockIndex : public CBlockIndex
{
public:
uint256 hashPrev;
uint256 hashNext;
CDiskBlockIndex()
{
hashPrev = uint256();
hashNext = uint256();
}
explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
{
hashPrev = (pprev ? pprev->GetBlockHash() : uint256());
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
{
if (!(nType & SER_GETHASH))
READWRITE(VARINT(nVersion));
READWRITE(VARINT(nHeight));
READWRITE(VARINT(nStatus));
READWRITE(VARINT(nTx));
if (nStatus & (BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO))
READWRITE(VARINT(nFile));
if (nStatus & BLOCK_HAVE_DATA)
READWRITE(VARINT(nDataPos));
if (nStatus & BLOCK_HAVE_UNDO)
READWRITE(VARINT(nUndoPos));
READWRITE(nMint);
READWRITE(nMoneySupply);
READWRITE(nFlags);
READWRITE(nStakeModifier);
if (IsProofOfStake()) {
READWRITE(prevoutStake);
READWRITE(nStakeTime);
} else {
const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
const_cast<CDiskBlockIndex*>(this)->hashProofOfStake = uint256();
}
// block header
READWRITE(this->nVersion);
READWRITE(hashPrev);
READWRITE(hashNext);
READWRITE(hashMerkleRoot);
READWRITE(nTime);
READWRITE(nBits);
READWRITE(nNonce);
}
uint256 GetBlockHash() const
{
CBlockHeader block;
block.nVersion = nVersion;
block.hashPrevBlock = hashPrev;
block.hashMerkleRoot = hashMerkleRoot;
block.nTime = nTime;
block.nBits = nBits;
block.nNonce = nNonce;
return block.GetHash();
}
std::string ToString() const
{
std::string str = "CDiskBlockIndex(";
str += CBlockIndex::ToString();
str += strprintf("\n hashBlock=%s, hashPrev=%s)",
GetBlockHash().ToString(),
hashPrev.ToString());
return str;
}
};
/** An in-memory indexed chain of blocks. */
class CChain
{
private:
std::vector<CBlockIndex*> vChain;
public:
/** Returns the index entry for the genesis block of this chain, or NULL if none. */
CBlockIndex* Genesis() const
{
return vChain.size() > 0 ? vChain[0] : NULL;
}
/** Returns the index entry for the tip of this chain, or NULL if none. */
CBlockIndex* Tip(bool fProofOfStake = false) const
{
if (vChain.size() < 1)
return NULL;
CBlockIndex* pindex = vChain[vChain.size() - 1];
if (fProofOfStake) {
while (pindex && pindex->pprev && !pindex->IsProofOfStake())
pindex = pindex->pprev;
}
return pindex;
}
/**
* Return average network hashes per second based on the last 'lookup' blocks,
* or from the last difficulty change if 'lookup' is nonpositive.
* If 'height' is nonnegative, compute the estimate at the time when a given block was found.
*/
int64_t GetNetworkHashPS(int lookup, int height);
/** Returns the index entry at a particular height in this chain, or NULL if no such height exists. */
CBlockIndex* operator[](int nHeight) const
{
if (nHeight < 0 || nHeight >= (int)vChain.size())
return NULL;
return vChain[nHeight];
}
/** Compare two chains efficiently. */
friend bool operator==(const CChain& a, const CChain& b)
{
return a.vChain.size() == b.vChain.size() &&
a.vChain[a.vChain.size() - 1] == b.vChain[b.vChain.size() - 1];
}
/** Efficiently check whether a block is present in this chain. */
bool Contains(const CBlockIndex* pindex) const
{
return (*this)[pindex->nHeight] == pindex;
}
/** Find the successor of a block in this chain, or NULL if the given index is not found or is the tip. */
CBlockIndex* Next(const CBlockIndex* pindex) const
{
if (Contains(pindex))
return (*this)[pindex->nHeight + 1];
else
return NULL;
}
/** Return the maximal height in the chain. Is equal to chain.Tip() ? chain.Tip()->nHeight : -1. */
int Height() const
{
return vChain.size() - 1;
}
/** Set/initialize a chain with a given tip. */
void SetTip(CBlockIndex* pindex);
/** Return a CBlockLocator that refers to a block in this chain (by default the tip). */
CBlockLocator GetLocator(const CBlockIndex* pindex = NULL) const;
/** Find the last common block between this chain and a block index entry. */
const CBlockIndex* FindFork(const CBlockIndex* pindex) const;
};
#endif // BITCOIN_CHAIN_H
| [
"[email protected]"
] | |
635c0b0101780f0a819c2aeefd45e7e6d94e641c | ff4bb485cb5d6561c952f9bec0e35d1581eced53 | /Aproblem/A. Tavas and Nafas.cpp | a3a74cb5f6669186dcf6416625962c27d97fc1bc | [] | no_license | mohumedsalah/Problem-Solve | ed3a170b4364d1039c1b9596fb1a7b37bcfc3298 | ebf997e24f35f78b2ca2abec86cbae4a22a37a18 | refs/heads/master | 2021-05-16T10:43:44.026762 | 2017-11-10T22:21:32 | 2017-11-10T22:21:32 | 104,812,632 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,637 | cpp | #include <bits/stdc++.h>
using namespace std;
#define repi(i, j, n) for(int i=(j);i<(int)(n);++i)
#define rln() getchar()
#define rint(n) scanf("%d",&n)
#define rs(n) scanf("%s",n)
#define rc(n) scanf("%c",&n)
#define rf(n) scanf("%lf",&n)
#define rl(n) scanf("%lld",&n)
#define pint(x) printf("%d", x)
#define psp() printf(" ")
#define ps(x) printf("%s", x)
#define pc(x) printf("%c", x)
#define pnl() printf("\n")
#define pl(x) printf("%lld", x)
#define pf(x) printf("%.6lf", x)
#define isOn(S, j) (S & (1 << j))
#define setBit(S, j) (S |= (1 << j))
#define clearBit(S, j) (S &= ~(1 << j))
#define toggleBit(S, j) (S ^= (1 << j))
#define lowBit(S) (S & (-S))
#define setAll(S, n) (S = (1 << n) - 1)
#define sz(v) ((int)((v).size()))
#define ssz(s) ((int)strlen(s))
#define f first
#define s second
#define INF_MAX 2147483647
#define INF_MIN -2147483647
#define INF_LL 2000000000000000000LL
#define INF 1000000000
#define EPS 1e-8
#define mod 1000000007
#define pb push_back
#define mp make_pair
typedef long long ll;
typedef pair<int, int> ii;
typedef pair<ll, ll> pll;
typedef vector<int> vi;
typedef vector<ii> vii;
int main(){
string ss[] = {"zero","one","two","three","four","five","six","seven","eight","nine",
"ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"};
string big[] = {"twenty","thirty","forty","fifty","sixty","seventy","eighty",
"ninety"};
int n;
rint(n);
if(n <= 19)
cout << ss[n];
else{
int ff = n % 10;
n/= 10;
int sss = n % 10;
if(ff == 0)
cout << big[sss - 2];
else
cout << big[sss - 2 ] << '-' << ss[ff];
}
return 0;
}
| [
"[email protected]"
] | |
c27d569d374a21420e3c4c09522a2dd10a979685 | 9e4a4567aeebb520438dced3529bc8713e7fe8ec | /parser_shp.cpp | 88767a553e8cb0fb08b88afe66d0cdbd291565d0 | [] | no_license | gkiranp/gio-embd | e159faca66b7009a4b7a55541f2b718259018466 | efc30a623db977aa420f24952d90016ef7a72e27 | refs/heads/master | 2020-06-12T19:43:23.158689 | 2016-12-28T11:47:00 | 2016-12-28T11:47:00 | 75,760,861 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,034 | cpp | #include <iostream>
#include <string.h>
#include <string>
#include <math.h>
#include <algorithm>
#include <sstream>
#include <stdlib.h>
#include <list>
#include <vector>
#include "./shapelib/shapelib-1.3.0/shapefil.h"
#include "parser_shp.h"
using namespace std;
namespace str2str {
template < typename T > std::string to_string( const T& n ){
std::ostringstream stm;
stm << n;
return stm.str();
}
template < typename T > std::string to_string( const T* n ){
std::string s(n);
return s;
}
}
MapperShp::MapperShp() {}
MapperShp::~MapperShp() {}
double MapperShp::deg2rad (double degree) {
return ((double)((M_PI*degree)/180.0));
}
double MapperShp::rad2deg (double radians) {
return ((double)(radians * (180.0 / M_PI)));
}
double MapperShp::distance(double latA, double lonA, double latB, double lonB) {
double radius = 6378.137;
double rLatA = deg2rad(latA);
double rLatB = deg2rad(latB);
double rHalfDeltaLat = deg2rad((latB - latA) / 2.0);
double rHalfDeltaLon = deg2rad((lonB - lonA) / 2.0);
return (2 * radius * asin(sqrt(pow(sin(rHalfDeltaLat), 2.0) + cos(rLatA) * cos(rLatB) * pow(sin(rHalfDeltaLon), 2.0))));
}
double MapperShp::destination_lat(double lat, double lon, double bearing, double distance) {
double radius = 6378.137;
double rLat = deg2rad(lat);
double rLon = deg2rad(lon);
double rBearing = deg2rad(bearing);
double rAngDist = (double)(distance/radius);
double rLatB = asin(sin(rLat) * cos(rAngDist) + cos(rLat) * sin(rAngDist) * cos(rBearing));
return rad2deg(rLatB);
}
double MapperShp::destination_lon(double lat, double lon, double bearing, double distance) {
double radius = 6378.137;
double rLat = deg2rad(lat);
double rLon = deg2rad(lon);
double rBearing = deg2rad(bearing);
double rAngDist = (double)(distance/radius);
double rLatB = asin(sin(rLat) * cos(rAngDist) + cos(rLat) * sin(rAngDist) * cos(rBearing));
double rLonB = rLon + atan2(sin(rBearing) * sin(rAngDist) * cos(rLat), cos(rAngDist) - sin(rLat) * sin(rLatB));
return rad2deg(rLonB);
}
double MapperShp::bound_N_lat(double lat, double lon, double distance) {
return destination_lat(lat, lon, 0, distance);
}
double MapperShp::bound_E_lon(double lat, double lon, double distance) {
return destination_lon(lat, lon, 90, distance);
}
double MapperShp::bound_S_lat(double lat, double lon, double distance) {
return destination_lat(lat, lon, 180, distance);
}
double MapperShp::bound_W_lon(double lat, double lon, double distance) {
return destination_lon(lat, lon, 270, distance);
}
ParserShpMap::ParserShpMap()
{
m_InitSts = InitializeParser();
}
ParserShpMap::~ParserShpMap()
{
if(m_ShpObj) {
SHPDestroyObject(m_ShpObj);
}
}
eUserStatus ParserShpMap::InitializeParser()
{
eUserStatus sts = eStsFailed;
int index = 0;
const char *field_name;
st_CityMap CityElement;
double dist = 0.0;
MapperShp *mShp = new MapperShp();
m_ShpObj = NULL;
m_CityMap.clear();
m_HdlShapes = SHPOpen(WORLD_SHP_FILE_SHP, "rb");
m_HdlDatabase = DBFOpen(WORLD_SHP_FILE_DBF, "rb");
if(m_HdlShapes && m_HdlDatabase)
{
SHPGetInfo(m_HdlShapes, &m_ShapesCount, NULL, NULL, NULL);
m_DBCount = DBFGetRecordCount(m_HdlDatabase);
if((m_DBCount == m_ShapesCount) && (m_DBCount > 0) && (m_ShapesCount > 0)) {
/* let's build an offline map */
for(index = 0; index < m_DBCount; index++) {
m_ShpObj = SHPReadObject(m_HdlShapes, index);
field_name = DBFReadStringAttribute(m_HdlDatabase, index, 0);
if((field_name) && (m_ShpObj)) {
dist = mShp->distance( m_ShpObj->dfXMin,
m_ShpObj->dfYMin,
m_ShpObj->dfXMax,
m_ShpObj->dfYMax);
CityElement.dist = dist;
CityElement.latN = m_ShpObj->dfYMax;
CityElement.lonE = m_ShpObj->dfXMax;
CityElement.latS = m_ShpObj->dfYMin;
CityElement.lonW = m_ShpObj->dfXMin;
CityElement.city = str2str::to_string(field_name);
#if PRINT_MAP_ON_CONSOLE
std::cout << CityElement.city << ","
<< CityElement.latN << ","
<< CityElement.lonE << ","
<< CityElement.latS << ","
<< CityElement.lonW << ","
<< dist << std::endl;
#endif
m_CityMap.push_back(CityElement);
}
}
if(m_ShpObj) {
SHPDestroyObject(m_ShpObj);
m_ShpObj = NULL;
}
sts = eStsSuccess;
}
}
return sts;
}
std::vector< st_CityMap > ParserShpMap::GetCitiesRange(double iLat, double iLon)
{
std::vector< st_CityMap > cities;
if(m_InitSts == eStsSuccess) {
st_CityMap city_element;
for (std::list< st_CityMap >::iterator it = m_CityMap.begin(); it != m_CityMap.end(); ++it) {
city_element = *it;
if((city_element.latS <= iLat) &&
(city_element.latN >= iLat) &&
(city_element.lonW <= iLon) &&
(city_element.lonE >= iLon)) {
cities.push_back(city_element);
}
}
}
return cities;
}
| [
"[email protected]"
] | |
450796aaede36ece5ff8ce172fde4692ea1fbd69 | 20c63560bd679381ed9a9d84be09c225cdfcf3ee | /Classes/CreatModeMenuLayer.h | 9e0d3c0fdba3954c5708212decab13c2b4f54303 | [] | no_license | binss/myMiku | e589c79b89d946eb78cfcee9debbacb3a7d79056 | 12e40c77ce83d5dcd83d46f1d894a97a99ddc83d | refs/heads/master | 2021-03-12T22:21:44.153675 | 2015-02-17T16:06:55 | 2015-02-17T16:06:55 | 15,929,149 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 815 | h | //
// CreatModeMenuLayer.h
// myMiku
//
// Created by bin on 14-1-28.
//
//
#ifndef __myMiku__CreatModeMenuLayer__
#define __myMiku__CreatModeMenuLayer__
#include "cocos2d.h"
#include "cocos-ext.h"
#include "CreatModeSelectLayer.h"
USING_NS_CC;
using namespace extension;
class CreatModeMenuLayer : public cocos2d::CCLayer
{
public:
virtual bool init();
void setCreatItemData(std::string name,double value);
CREATE_FUNC(CreatModeMenuLayer);
private:
void clearMenuCallback(CCNode *pSender);
void creatMenuCallback(CCNode *pSender);
void penMenuCallback(CCNode *pSender);
CCMenuItemLabel *clearItem;
CCMenuItemLabel *creatItem;
bool selectState;
CreatModeSelectLayer* selectLayer;
};
#endif /* defined(__myMiku__CreatModeMenuLayer__) */
| [
"[email protected]"
] | |
c04f83f9d2ecf2225fbfa429e5366783ac01b63f | e5b56a2675592d8b9ecae30d469c50b37812e5d0 | /DOTAA/test.cpp | b9fab712ad8707120d563d039e17abf1aeebfb33 | [] | no_license | rituraj2847/spoj | 4d3a4b677eaa0043b94b310cc3485975ee2062de | 324b02885e8d342ef58a40cb3803c8cf27e39a9d | refs/heads/master | 2021-05-14T16:52:58.514466 | 2015-08-16T09:44:47 | 2015-08-16T09:44:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 214 | cpp | #include<stdio.h>
int main()
{
int t;
scanf("%i", &t);
int p[t];
for(int k=0; k<t; k++)
{
scanf("%i", &p[k]);
}
int j;
for(j=0; j<t; j++)
{
if(p[j]==0)
break;
}
printf("\n%i\n", j);
return 0;
} | [
"[email protected]"
] | |
db02522baf7551648115d4b049167653d96e8dd1 | 8aed0e4b4e570e063b394e579cc850757ce66e71 | /Finish_it/Src/Entities/Playable/inventory.h | 6233557e0f47619d3d742eed7dcb797bb2f69bc5 | [] | no_license | Olxe/Finish_it | 2df1c53c0e4db096a6df8d300d93ac48b5b50e87 | 007e7a2fe303cb7d96bc79143fd22c7d066d04b0 | refs/heads/master | 2022-05-27T07:34:15.709510 | 2019-12-21T15:38:19 | 2019-12-21T15:38:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 311 | h | #pragma once
#include <vector>
#include <iostream>
#include "Inventory/Item/item.h"
class Inventory
{
public:
Inventory();
~Inventory();
void AddItem(ItemType type);
bool RemoveItem(ItemType type);
//return amount of item stocked
int HaveItem(ItemType type);
private:
std::vector<Item*> m_items;
}; | [
"[email protected]"
] | |
255292dbb2fa622fd504cd97d0e5c5e6009020cf | 777d41c7dc3c04b17dfcb2c72c1328ea33d74c98 | /DongCi_Android/dongciSDK_android/src/main/jni/handwritten-src/foundation/Archive/WindowsTypeHelper.h | cb65f64d7da863910abef66e541c42619b1cefd5 | [
"BSL-1.0"
] | permissive | foryoung2018/videoedit | 00fc132c688be6565efb373cae4564874f61d52a | 7a316996ce1be0f08dbf4c4383da2c091447c183 | refs/heads/master | 2020-04-08T04:56:42.930063 | 2018-11-25T14:27:43 | 2018-11-25T14:27:43 | 159,038,966 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,394 | h | //
// WindowsTypeHelper.h
// SquareCam-Test
//
// Created by LiuJiangyu on 3/11/15.
//
//
#ifndef SquareCam_Test_WindowsTypeHelper_h
#define SquareCam_Test_WindowsTypeHelper_h
#include <sys/types.h>
#include <string.h>
#include <stdlib.h>
#include <algorithm>
// std::min/max
using std::min;
using std::max;
//
//BaseTsd.h
//
typedef unsigned long ULONG_PTR;
//
//limits.h
//
#ifndef UINT_MAX
#define UINT_MAX 0xffffffff
#endif
#define INFINITE UINT_MAX
typedef long int INT32, *PINT32;
typedef unsigned int DWORD;
#ifndef TARGET_OS_IPHONE
typedef signed char BOOL;
#endif
typedef unsigned char BYTE, BOOLEAN;
typedef unsigned short WORD;
typedef float FLOAT;
typedef int INT;
typedef unsigned int UINT, UINT32;
typedef unsigned int WPARAM;
typedef long LPARAM;
typedef void* LPVOID;
typedef void VOID, *PVOID;
typedef UINT* UINT_PTR;
typedef DWORD* DWORD_PTR;
typedef long LRESULT;
typedef char CHAR;
typedef short SHORT;
typedef long LONG;
typedef unsigned short USHORT;
typedef unsigned char UCHAR;
#define CONST const
#define CALLBACK __stdcall
#define far
#define near
#define FAR far
#define NEAR near
typedef unsigned long long ULONGLONG;
typedef wchar_t WCHAR;
typedef CONST CHAR *LPCSTR;
typedef WCHAR TCHAR, *PTCHAR, *LPWSTR;
typedef CONST WCHAR *LPCWSTR;
typedef unsigned char byte;
#ifndef _HRESULT_DEFINED
#define _HRESULT_DEFINED
typedef long HRESULT;
#endif
#ifndef IN
#define IN
#endif
#ifndef OUT
#define OUT
#endif
#ifndef NULL
#ifdef __cplusplus
#define NULL 0
#endif
#endif
#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif
// WinError.h
//
#define _HRESULT_TYPEDEF_(_sc) ((HRESULT)_sc)
#define S_OK ((HRESULT)0L)
#define S_FALSE ((HRESULT)1L)
#define E_NOTIMPL ((HRESULT)0x80004001L)
#define E_OUTOFMEMORY _HRESULT_TYPEDEF_(0x8007000EL)
#define E_INVALIDARG _HRESULT_TYPEDEF_(0x80070057L)
#define E_FAIL _HRESULT_TYPEDEF_(0x80004005L)
#define FAILED(hr) (((HRESULT)(hr)) < 0)
#define MAKE_HRESULT(sev, fac, code) \
((HRESULT)(((unsigned long)(sev)<<31) | ((unsigned long)(fac)<<16) | ((unsigned long)(code))))
#define SUCCEEDED(hr) (((HRESULT)(hr))>=0)
#define E_UNEXPECTED false
#define UINT32 unsigned int
#define nullptr NULL
#define __min(a, b) (((a) < (b)) ? (a) : (b))
#define __max(a, b) (((a) > (b)) ? (a) : (b))
#define UNREFERENCED_PARAMETER(x) (void)(x)
template <typename T, size_t N>
char ( &_ArraySizeHelper( T (&array)[N] ))[N];
#define ARRAYSIZE( array ) (sizeof( _ArraySizeHelper( array ) ))
//
// stdlib.h
//
#define MAX_PATH 260
// handle
typedef void *HANDLE;
typedef struct {} BITMAP, *HBITMAP;
typedef struct {} ICONIMAGE, *HICON;
typedef struct {} MENU, *HMENU;
typedef struct {} DC, *HDC;
typedef struct {} WND, *HWND;
inline int CloseHandle(HANDLE){
return 1;
}
inline int DeleteObject(HBITMAP){
return 1;
}
inline int DestroyIcon(HICON){
return 1;
}
inline int DestroyMenu(HMENU){
return 1;
}
inline int ReleaseDC(HWND,HDC){
return 1;
}
inline int DeleteDC(HDC){
return 1;
}
struct RECT
{
int left;
int top;
int right;
int bottom;
RECT() : left(0), top(0), right(0), bottom(0)
{
}
RECT(int _left, int _top, int _right, int _bottom)
{
left = _left;
top = _top;
right = _right;
bottom = _bottom;
}
RECT& operator=(const RECT& rhs)
{
left = rhs.left;
top = rhs.top;
right = rhs.right;
bottom = rhs.bottom;
return *this;
}
bool operator==(const RECT& rhs)
{
return (top == rhs.top && left == rhs.left
&& right == rhs.right && bottom == rhs.bottom);
}
bool operator!=(const RECT& rhs)
{
return (top != rhs.top || left != rhs.left
|| right != rhs.right || bottom != rhs.bottom);
}
bool IsEmpty() const
{
return (left >= right || top >= bottom);
}
void Clear()
{
left = top = right = bottom = 0;
}
int Width() const
{
return (int)(right - left);
}
int Height() const
{
return (int)(bottom - top);
}
int Area() const
{
return Width() * Height();
}
int CenterX() const
{
return (int)((left + right) / 2);
}
int CenterY() const
{
return (int)((top + bottom) / 2);
}
void Shift(int dx, int dy)
{
left += dx;
right += dx;
top += dy;
bottom += dy;
}
float GetOverlap(const RECT& rhs) const
{
const int l = (int)__max(left, rhs.left);
const int r = (int)__min(right, rhs.right);
const int t = (int)__max(top, rhs.top);
const int b = (int)__min(bottom, rhs.bottom);
if (l >= r|| t >= b)
{
return 0.f;
}
else
{
const int aInter = (r - l) * (b - t);
const int aUnion = Area() + rhs.Area() - aInter;
return ((float)aInter / aUnion);
}
}
static bool IsOverlapped(const RECT& r0,
const RECT& r1,
const float threshold = 0.3f)
{
return (r0.GetOverlap(r1) >= threshold);
}
};
typedef struct tagPOINT {
LONG x;
LONG y;
} POINT, *PPOINT;
#endif
| [
"[email protected]"
] | |
214309b817442095c457b14558c7f07404b9a46d | 291add73c592d04e980873537b2f92949e3bd32c | /555-Parsing/61-SLK/slk-example/cpp/SlkError.h | f36fb1981ed78e138a45cdcecb9b36aa16fd3bca | [] | no_license | wojsamjan/clabs | 2c196320bc467cf3f9f6642aa3eae2f3ab889f6c | 24e1c8a5608b4211aab568307e66a40102b2d2f6 | refs/heads/master | 2020-02-26T16:27:06.577826 | 2017-01-21T11:55:45 | 2017-01-21T11:55:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 623 | h | /**************************************************************************
SlkError.h
**************************************************************************/
#ifndef _SLKERROR_H
#define _SLKERROR_H
#include "calc.h"
class SlkError
{
public:
SlkError ( SlkToken &tokens,
SlkLog &log );
short
mismatch ( short symbol,
short token );
short
no_entry ( short nonterminal,
short token,
int level );
void
input_left ( void );
private:
SlkToken *tokens;
SlkLog *log;
};
#endif
| [
"[email protected]"
] | |
9d7499aa1220b77853a879f17fd97414eac5551a | 822c829c886a5ee8de3b5a7cbd3fbc0421a358d9 | /2.3.x/channel/constant/polyMesh/boundary | 035217942d15268809881307287a31d1a3dc7cca | [] | no_license | OSCCAR-PFM/afsol | 9c66de7b74521bcead77a966198c3f79e932c819 | 6d05655691393494bb26ff0a6317ef338b9c0121 | refs/heads/master | 2021-01-20T09:32:50.280765 | 2014-09-12T08:35:06 | 2014-09-12T08:35:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,561 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 2.3.x |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format binary;
class polyBoundaryMesh;
location "constant/polyMesh";
object boundary;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
5
(
top
{
type wall;
inGroups 1(wall);
nFaces 3428;
startFace 133672;
}
bottom
{
type wall;
inGroups 1(wall);
nFaces 3428;
startFace 137100;
}
inlet
{
type patch;
nFaces 20;
startFace 140528;
}
outlet
{
type patch;
nFaces 20;
startFace 140548;
}
frontAndBack
{
type empty;
inGroups 1(empty);
nFaces 137120;
startFace 140568;
}
)
// ************************************************************************* //
| [
"gijsbert"
] | gijsbert |
|
bc11c0ba2d917edaa491c39a2e649b26dfb33460 | 71501709864eff17c873abbb97ffabbeba4cb5e3 | /llvm10.0.0/llvm/lib/Target/VideoCore4/VideoCore4InstrInfo.cpp | eb8451442b9c3de8e200420e5d5f35d98f290145 | [
"NCSA",
"LLVM-exception",
"Apache-2.0"
] | permissive | LEA0317/LLVM-VideoCore4 | d08ba6e6f26f7893709d3285bdbd67442b3e1651 | 7ae2304339760685e8b5556aacc7e9eee91de05c | refs/heads/master | 2022-06-22T15:15:52.112867 | 2022-06-09T08:45:24 | 2022-06-09T08:45:24 | 189,765,789 | 1 | 0 | NOASSERTION | 2019-06-01T18:31:29 | 2019-06-01T18:31:29 | null | UTF-8 | C++ | false | false | 10,289 | cpp | //===-- VideoCore4InstrInfo.cpp - VideoCore4 Instruction Information -----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the VideoCore4 implementation of the TargetInstrInfo class.
//
//===----------------------------------------------------------------------===//
#include "VideoCore4InstrInfo.h"
#include "VideoCore4.h"
#include "VideoCore4Util.h"
#include "VideoCore4MachineFunctionInfo.h"
#include "VideoCore4TargetMachine.h"
#include "llvm/IR/Function.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#define GET_INSTRINFO_CTOR_DTOR
#include "VideoCore4GenInstrInfo.inc"
using namespace llvm;
VideoCore4InstrInfo::VideoCore4InstrInfo(const VideoCore4Subtarget &STI)
: VideoCore4GenInstrInfo(VideoCore4::ADJCALLSTACKDOWN, VideoCore4::ADJCALLSTACKUP),
RI(),
Subtarget(STI) {}
VideoCore4InstrInfo*
VideoCore4InstrInfo::create(VideoCore4Subtarget &STI) {
return new llvm::VideoCore4InstrInfo(STI);
}
void
VideoCore4InstrInfo::copyPhysReg(MachineBasicBlock &MBB,
MachineBasicBlock::iterator I,
const DebugLoc &DL,
MCRegister DestReg,
MCRegister SrcReg,
bool KillSrc) const {
if (VideoCore4::FR32RegClass.contains(DestReg, SrcReg)) {
BuildMI(MBB, I, DL, get(VideoCore4::MOV_F), DestReg)
.addReg(SrcReg, getKillRegState(KillSrc));
return;
} else if (VideoCore4::GR32RegClass.contains(DestReg, SrcReg)) {
BuildMI(MBB, I, DL, get(VideoCore4::MOV_R), DestReg)
.addReg(SrcReg, getKillRegState(KillSrc));
return;
}
llvm_unreachable("Cannot emit physreg copy instruction");
}
void
VideoCore4InstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
MachineBasicBlock::iterator I,
unsigned SrcReg,
bool isKill,
int FI,
const TargetRegisterClass *RC,
const TargetRegisterInfo *TRI) const {
DebugLoc DL;
if (I != MBB.end())
DL = I->getDebugLoc();
MachineFunction &MF = *MBB.getParent();
const MachineFrameInfo &MFI = MF.getFrameInfo();
MachineMemOperand *MMO = MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF,
FI),
MachineMemOperand::MOStore,
MFI.getObjectSize(FI),
MFI.getObjectAlignment(FI));
BuildMI(MBB, I, DL, get(VideoCore4::MEM32_ST_LI))
.addReg(SrcReg, getKillRegState(isKill))
.addFrameIndex(FI)
.addImm(0)
.addMemOperand(MMO);
}
void
VideoCore4InstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
MachineBasicBlock::iterator I,
unsigned DestReg,
int FI,
const TargetRegisterClass *RC,
const TargetRegisterInfo *TRI) const {
DebugLoc DL;
if (I != MBB.end())
DL = I->getDebugLoc();
MachineFunction &MF = *MBB.getParent();
const MachineFrameInfo &MFI = MF.getFrameInfo();
MachineMemOperand *MMO = MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF,
FI),
MachineMemOperand::MOStore,
MFI.getObjectSize(FI),
MFI.getObjectAlignment(FI));
BuildMI(MBB, I, DL, get(VideoCore4::MEM32_LD_LI), DestReg)
.addFrameIndex(FI)
.addImm(0)
.addMemOperand(MMO);
}
void
VideoCore4InstrInfo::adjustStackPtr(int64_t amount,
MachineBasicBlock &MBB,
MachineBasicBlock::iterator I) const {
DebugLoc DL = I != MBB.end() ? I->getDebugLoc() : DebugLoc();
if (amount < 0) {
BuildMI(MBB, I, DL, get(VideoCore4::SUB_F_RI), VideoCore4::SP)
.addReg(VideoCore4::SP)
.addImm(-amount);
} else if (amount > 0) {
BuildMI(MBB, I, DL, get(VideoCore4::ADD_F_RI), VideoCore4::SP)
.addReg(VideoCore4::SP)
.addImm(amount);
} else {
/* Do nothing if we're adjusting the stack by zero */
}
}
bool
VideoCore4InstrInfo::analyzeBranch(MachineBasicBlock &MBB,
MachineBasicBlock *&TBB,
MachineBasicBlock *&FBB,
SmallVectorImpl<MachineOperand> &Cond,
bool AllowModify) const {
MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
if (I == MBB.end()) {
return false;
}
if (!isUnpredicatedTerminator(*I)) {
return false;
}
// Get the last instruction in the block.
MachineInstr *LastInst = &*I;
MachineBasicBlock::iterator LastMBBI = I;
unsigned LastOpc = LastInst->getOpcode();
// If there is only one terminator instruction, process it.
if (I == MBB.begin() || !isUnpredicatedTerminator(*--I)) {
if (vc4util::isUnconditionalJump(LastOpc)) {
TBB = LastInst->getOperand(0).getMBB();
return false;
}
if (vc4util::isCondTrueBranch(LastOpc)) {
// Block ends with fall-through condbranch.
vc4util::parseCondBranch(LastInst, TBB, Cond);
return false;
}
return true; // Can't handle indirect branch.
}
// Get the instruction before it if it is a terminator.
MachineInstr *SecondLastInst = &*I;
unsigned SecondLastOpc = SecondLastInst->getOpcode();
// If AllowModify is true and the block ends with two or more unconditional
// branches, delete all but the first unconditional branch.
if (AllowModify && vc4util::isUnconditionalJump(LastOpc)) {
while (vc4util::isUnconditionalJump(SecondLastOpc)) {
LastInst->eraseFromParent();
LastInst = SecondLastInst;
LastOpc = LastInst->getOpcode();
if (I == MBB.begin() || !isUnpredicatedTerminator(*--I)) {
// Return now the only terminator is an unconditional branch.
TBB = LastInst->getOperand(0).getMBB();
return false;
} else {
SecondLastInst = &*I;
SecondLastOpc = SecondLastInst->getOpcode();
}
}
}
// If the block ends with a B and a Bcc, handle it.
if (vc4util::isCondBranch(SecondLastOpc) && vc4util::isUnconditionalJump(LastOpc)) {
for (int i=0; i<vc4util::branchKindNum; i++) {
if (SecondLastOpc == vc4util::BranchTakenOpcode[i]) {
// Transform the code
//
// L2:
// bt L1
// ba L2
// L1:
// ..
//
// into
//
// L2:
// bf L2
// L1:
// ...
//
MachineBasicBlock *TargetBB = SecondLastInst->getOperand(2).getMBB();
if (AllowModify
&& LastMBBI != MBB.end()
&& MBB.isLayoutSuccessor(TargetBB)) {
MachineBasicBlock *BNcondMBB = LastInst->getOperand(0).getMBB();
BuildMI(&MBB, MBB.findDebugLoc(SecondLastInst), get(vc4util::BranchNotTakenOpcode[i]))
.addReg(SecondLastInst->getOperand(0).getReg())
.addReg(SecondLastInst->getOperand(1).getReg())
.addMBB(BNcondMBB);
LastMBBI->eraseFromParent();
TBB = FBB = nullptr;
return true;
}
} else if (vc4util::isRawBranch(SecondLastOpc)) {
// Transform the code
//
// L2:
// bt L1
// ba L2
// L1:
// ..
//
// into
//
// L2:
// bf L2
// L1:
// ...
//
MachineBasicBlock *TargetBB = SecondLastInst->getOperand(0).getMBB();
if (AllowModify
&& LastMBBI != MBB.end()
&& MBB.isLayoutSuccessor(TargetBB)) {
MachineBasicBlock::iterator OldInst = SecondLastInst;
MachineBasicBlock *BNcondMBB = LastInst->getOperand(0).getMBB();
BuildMI(&MBB, MBB.findDebugLoc(SecondLastInst), get(vc4util::reverseBranch(SecondLastOpc)))
.addMBB(BNcondMBB);
OldInst->eraseFromParent();
LastMBBI->eraseFromParent();
TBB = FBB = nullptr;
return true;
}
}
}
TBB = FBB = nullptr;
return true;
}
// If the block ends with two unconditional branches, handle it. The second
// one is not executed.
if (vc4util::isUnconditionalJump(SecondLastOpc) && vc4util::isUnconditionalJump(LastOpc)) {
TBB = SecondLastInst->getOperand(0).getMBB();
return false;
}
// Otherwise, can't handle this.
return true;
}
unsigned
VideoCore4InstrInfo::insertBranch(MachineBasicBlock &MBB,
MachineBasicBlock *TBB,
MachineBasicBlock *FBB,
ArrayRef<MachineOperand> Cond,
const DebugLoc &DL,
int *BytesAdded) const {
if (Cond.empty()) {
BuildMI(&MBB, DL, get(VideoCore4::JMP))
.addMBB(TBB);
return 1;
}
// FIXME(konda): handle this
BuildMI(&MBB, DL, get(VideoCore4::JMP_TRUE_P))
.addMBB(TBB);
if (!FBB) {
return 1;
}
BuildMI(&MBB, DL, get(VideoCore4::JMP))
.addMBB(FBB);
return 2;
}
unsigned
VideoCore4InstrInfo::removeBranch(MachineBasicBlock &MBB,
int *BytesRemoved) const {
MachineBasicBlock::iterator I = MBB.end();
unsigned Count = 0;
while (I != MBB.begin()) {
--I;
if (I->isDebugValue())
continue;
if (vc4util::isBranchMBBI(I) == false)
break;
I->eraseFromParent();
I = MBB.end();
++Count;
}
return Count;
}
MachineBasicBlock*
VideoCore4InstrInfo::getBranchDestBlock(const MachineInstr &MI) const {
switch (MI.getOpcode()) {
default:
{
llvm_unreachable("cannot handle branch dst");
}
case VideoCore4::JMP_CC_EQ:
case VideoCore4::JMP_CC_NE:
case VideoCore4::JMP_CC_GT:
case VideoCore4::JMP_CC_GE:
case VideoCore4::JMP_CC_LT:
case VideoCore4::JMP_CC_LE:
case VideoCore4::JMP_CC_HI:
case VideoCore4::JMP_CC_HS:
case VideoCore4::JMP_CC_LO:
case VideoCore4::JMP_CC_LS:
case VideoCore4::JMP:
{
return MI.getOperand(0).getMBB();
}
}
}
| [
"[email protected]"
] | |
af5fc455edc61df1753da65bd1342e7c91f7e89d | 714c671927137b9d876715a4a616f3806ff1a0d9 | /cpp_libraries/container/values/uint_value.cpp | c1692d7151d1047f2aceb3c8ca397b122c1317b9 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | Gouldian0120/serverclienttcp | da9c2a194f80c8c3aae795a6bfa949fff433af76 | 3ae5307e15e538a2736ae36d5cff31568cbb02e6 | refs/heads/main | 2023-07-18T17:34:20.560995 | 2021-08-23T07:31:28 | 2021-09-02T09:49:39 | 402,368,836 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,010 | cpp | #include "uint_value.h"
#include "fmt/format.h"
namespace container
{
uint_value::uint_value(void)
: value()
{
_type = value_types::uint_value;
}
uint_value::uint_value(const std::wstring& name, const unsigned int& value)
: value(name, (const unsigned char*)&value, sizeof(unsigned int), value_types::uint_value)
{
}
uint_value::~uint_value(void)
{
}
short uint_value::to_short(void) const
{
unsigned int temp = 0;
memcpy(&temp, _data.data(), _size);
return static_cast<short>(temp);
}
unsigned short uint_value::to_ushort(void) const
{
unsigned int temp = 0;
memcpy(&temp, _data.data(), _size);
return static_cast<unsigned short>(temp);
}
int uint_value::to_int(void) const
{
unsigned int temp = 0;
memcpy(&temp, _data.data(), _size);
return static_cast<int>(temp);
}
unsigned int uint_value::to_uint(void) const
{
unsigned int temp = 0;
memcpy(&temp, _data.data(), _size);
return static_cast<unsigned int>(temp);
}
long uint_value::to_long(void) const
{
unsigned int temp = 0;
memcpy(&temp, _data.data(), _size);
return static_cast<long>(temp);
}
unsigned long uint_value::to_ulong(void) const
{
unsigned int temp = 0;
memcpy(&temp, _data.data(), _size);
return static_cast<unsigned long>(temp);
}
long long uint_value::to_llong(void) const
{
unsigned int temp = 0;
memcpy(&temp, _data.data(), _size);
return static_cast<long long>(temp);
}
unsigned long long uint_value::to_ullong(void) const
{
unsigned int temp = 0;
memcpy(&temp, _data.data(), _size);
return static_cast<unsigned long long>(temp);
}
float uint_value::to_float(void) const
{
unsigned int temp = 0;
memcpy(&temp, _data.data(), _size);
return static_cast<float>(temp);
}
double uint_value::to_double(void) const
{
unsigned int temp = 0;
memcpy(&temp, _data.data(), _size);
return static_cast<double>(temp);
}
std::wstring uint_value::to_string(const bool&) const
{
return fmt::format(L"{}", to_uint());
}
} | [
"[email protected]"
] | |
070fd7dbce12c96d360dda5cebfec2b5334e2c95 | a398c5d782f7dc59d7fc43a67bfefdd1872f13c6 | /ScriptExtender/Extender/Client/StatusHelpers.h | 1a5647626499557d32795fc1a3772cb2bd415062 | [
"MIT"
] | permissive | Norbyte/ositools | b11f82221000f0a8be6dc85bfe6c40645746524e | e2d351a5503f8660c5c40fc4a68570373befc7d9 | refs/heads/master | 2023-08-14T16:31:00.481306 | 2023-07-28T16:11:30 | 2023-07-28T16:11:30 | 120,127,571 | 351 | 41 | MIT | 2023-08-30T10:32:44 | 2018-02-03T20:37:56 | C++ | UTF-8 | C++ | false | false | 328 | h | #pragma once
#include <GameDefinitions/Base/Base.h>
#include <GameDefinitions/Enumerations.h>
#include <GameDefinitions/GameObjects/Status.h>
BEGIN_NS(ecl)
class StatusHelpers
{
public:
void PostStartup();
void OnStatusMachineExit(StatusMachine::ExitStatusProc* wrapped, StatusMachine* self, Status* status);
};
END_NS()
| [
"[email protected]"
] | |
a58c4e255793fe456b3ad2a44573b9fa24b5cf14 | 520ae0b097b29744d1897ad34a8736efd181ca95 | /castle/Castle/Classes/Objects/Chaser/Chaser.h | 1738b9fb6f7d62783e1a96eda9e78706bb10f315 | [] | no_license | Nyuno/SLL_Castle | e0ba8ecc9a26d06cf8068dd01a8f713c02619157 | 7f957dc02162f0624b8a3c47154f5c6d5542bfe4 | refs/heads/master | 2021-01-10T20:13:20.100643 | 2013-11-18T22:57:09 | 2013-11-18T22:57:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,240 | h | //
// Chaser.h
// Castle
//
// Created by 이 대성 on 13. 10. 17..
//
//
#ifndef __Castle__Chaser__
#define __Castle__Chaser__
#include "cocos2d.h"
#include "TestResource.h"
#define CHASER_HEIGHT 50
#define CHASER_WIDTH 60
using namespace cocos2d;
namespace CHASER_CONST
{
enum{
STATE_RUN_LEFT = -1,
STATE_JUMP_LEFT = -2,
STATE_RUN_RIGHT = 1,
STATE_JUMP_RIGHT,
STATE_LIGHT_NULL,
STATE_LIGHT_FRONT,
STATE_LIGHT_BACK,
ID_SPRITE,
ID_SPRITE_LIGHT,
DIRECTION_LEFT = -1,
DIRECTION_RIGHT= 1,
};
}
class ChaseMonster : public CCNode{
private:
CCPoint mPos;
int mDirection;
int mFloor;
int mFirstIndex;
int mFrameMax;
public:
virtual bool init();
virtual void update(float dt);
virtual void OnExit();
CREATE_FUNC(ChaseMonster);
};
class Chaser : public CCNode{
private:
CCPoint mPos;
int mV;
int mChaserNum;
ChaseMonster* recentMonster;
public:
virtual bool init();
virtual void update(float dt);
virtual void onExit();
CCRect getBounding();
CREATE_FUNC(Chaser);
ChaseMonster* addChaser();
};
#endif /* defined(__Castle__Chaser__) */
| [
"[email protected]"
] | |
e5d7e28f0df5e20b6da6f759f56789fa5aae064b | 067264ffed211f8695f367b7eae6075861eabbc2 | /Alpha-Tree/Alpha-Tree/recognizer.h | ba33d66e5b90073356b73e0957988f36f51e81e4 | [] | no_license | thegendolz/In-company-research | ec561ee28c0c35d1082932e45009ad93b663ca4d | d74f6f0205905761f531018c86e1745406796782 | refs/heads/master | 2022-04-02T19:21:46.048343 | 2020-02-07T13:02:13 | 2020-02-07T13:02:13 | 185,986,435 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 485 | h | #ifndef RECOGNIZER_H
#define RECOGNIZER_H
#include "pixel.h"
#include "alphalevel.h"
#include "filereader.h"
#include <vector>
#include "dissimilarity.h"
class Recognizer{
public:
//Constructors
Recognizer();
Recognizer(FileReader fileReader);
//Functions
bool isTriangle(int sizeOfTriangle, std::vector<std::vector<int>> cluster);
bool isRed(int sizeOfTriangle, std::vector<std::vector<std::vector<int>>> cluster);
private:
//Variables
bool triangle;
bool red;
};
#endif
| [
"[email protected]"
] | |
e7b26c048268c66dfaa2ea42088b16b57899cef0 | ec0e41c1b962f60fa0e2048811502c9767278de1 | /04_도안/humanTestFrame/DirectX3D/SkyBox.cpp | cb7a995550b893d81c77cee3de084a1feb2c3f8f | [] | no_license | 1221kwj/D3DX_SemiPortPolio | 52428a5270dbb92fb5ff5a2eb4c95e929415568f | ccfbc7bace2e1e19beef951759bd3b2fd18457f1 | refs/heads/master | 2021-09-06T16:42:53.051909 | 2017-12-18T17:34:23 | 2017-12-18T17:34:23 | 113,929,589 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,368 | cpp | #include "stdafx.h"
#include "SkyBox.h"
SkyBox::SkyBox()
{
}
SkyBox::~SkyBox()
{
}
void SkyBox::Init()
{
std::vector<D3DXVECTOR3> vertexFormat;
vertexFormat.push_back(D3DXVECTOR3(-1.0f, -1.0f, -1.0f));
vertexFormat.push_back(D3DXVECTOR3(-1.0f, 1.0f, -1.0f));
vertexFormat.push_back(D3DXVECTOR3(1.0f, 1.0f, -1.0f));
vertexFormat.push_back(D3DXVECTOR3(1.0f, -1.0f, -1.0f));
vertexFormat.push_back(D3DXVECTOR3(-1.0f, -1.0f, 1.0f));
vertexFormat.push_back(D3DXVECTOR3(-1.0f, 1.0f, 1.0f));
vertexFormat.push_back(D3DXVECTOR3(1.0f, 1.0f, 1.0f));
vertexFormat.push_back(D3DXVECTOR3(1.0f, -1.0f, 1.0f));
//back
skyBox.push_back(VertexPT(vertexFormat[0], D3DXVECTOR2(0, 1)));
skyBox.push_back(VertexPT(vertexFormat[1], D3DXVECTOR2(0, 0)));
skyBox.push_back(VertexPT(vertexFormat[2], D3DXVECTOR2(1, 0)));
skyBox.push_back(VertexPT(vertexFormat[0], D3DXVECTOR2(0, 1)));
skyBox.push_back(VertexPT(vertexFormat[2], D3DXVECTOR2(1, 0)));
skyBox.push_back(VertexPT(vertexFormat[3], D3DXVECTOR2(1, 1)));
//front
skyBox.push_back(VertexPT(vertexFormat[4], D3DXVECTOR2(1, 1)));
skyBox.push_back(VertexPT(vertexFormat[6], D3DXVECTOR2(0, 0)));
skyBox.push_back(VertexPT(vertexFormat[5], D3DXVECTOR2(1, 0)));
skyBox.push_back(VertexPT(vertexFormat[4], D3DXVECTOR2(1, 1)));
skyBox.push_back(VertexPT(vertexFormat[7], D3DXVECTOR2(0, 1)));
skyBox.push_back(VertexPT(vertexFormat[6], D3DXVECTOR2(0, 0)));
//left
skyBox.push_back(VertexPT(vertexFormat[4], D3DXVECTOR2(0, 1)));
skyBox.push_back(VertexPT(vertexFormat[5], D3DXVECTOR2(0, 0)));
skyBox.push_back(VertexPT(vertexFormat[1], D3DXVECTOR2(1, 0)));
skyBox.push_back(VertexPT(vertexFormat[4], D3DXVECTOR2(0, 1)));
skyBox.push_back(VertexPT(vertexFormat[1], D3DXVECTOR2(1, 0)));
skyBox.push_back(VertexPT(vertexFormat[0], D3DXVECTOR2(1, 1)));
//right
skyBox.push_back(VertexPT(vertexFormat[3], D3DXVECTOR2(0, 1)));
skyBox.push_back(VertexPT(vertexFormat[2], D3DXVECTOR2(0, 0)));
skyBox.push_back(VertexPT(vertexFormat[6], D3DXVECTOR2(1, 0)));
skyBox.push_back(VertexPT(vertexFormat[3], D3DXVECTOR2(0, 1)));
skyBox.push_back(VertexPT(vertexFormat[6], D3DXVECTOR2(1, 0)));
skyBox.push_back(VertexPT(vertexFormat[7], D3DXVECTOR2(1, 1)));
//top
skyBox.push_back(VertexPT(vertexFormat[1], D3DXVECTOR2(0, 0)));
skyBox.push_back(VertexPT(vertexFormat[5], D3DXVECTOR2(1, 0)));
skyBox.push_back(VertexPT(vertexFormat[6], D3DXVECTOR2(1, 1)));
skyBox.push_back(VertexPT(vertexFormat[1], D3DXVECTOR2(0, 0)));
skyBox.push_back(VertexPT(vertexFormat[6], D3DXVECTOR2(1, 1)));
skyBox.push_back(VertexPT(vertexFormat[2], D3DXVECTOR2(0, 1)));
//bottom
skyBox.push_back(VertexPT(vertexFormat[4], D3DXVECTOR2(1, 1)));
skyBox.push_back(VertexPT(vertexFormat[0], D3DXVECTOR2(0, 1)));
skyBox.push_back(VertexPT(vertexFormat[3], D3DXVECTOR2(0, 0)));
skyBox.push_back(VertexPT(vertexFormat[4], D3DXVECTOR2(1, 1)));
skyBox.push_back(VertexPT(vertexFormat[3], D3DXVECTOR2(0, 0)));
skyBox.push_back(VertexPT(vertexFormat[7], D3DXVECTOR2(1, 0)));
}
void SkyBox::Render()
{
D3DXMATRIXA16 skyWorld;
D3DXMatrixIdentity(&skyWorld);
D3DXMatrixScaling(&skyWorld, 200.0f, 200.0f, 200.0f);
D3DDevice->SetRenderState(D3DRS_LIGHTING, false);
D3DDevice->SetTransform(D3DTS_WORLD, &skyWorld);
D3DDevice->SetRenderState(D3DRS_CULLMODE, true);
//Back
D3DDevice->SetTexture(0, g_pTextureManager->GetTexture("./SkyBox/badomen_bk.png"));
D3DDevice->DrawPrimitiveUP(D3DPT_TRIANGLELIST, 2, &skyBox[0], sizeof(VertexPT));
//front
D3DDevice->SetTexture(0, g_pTextureManager->GetTexture("./SkyBox/badomen_ft.png"));
D3DDevice->DrawPrimitiveUP(D3DPT_TRIANGLELIST, 2, &skyBox[6], sizeof(VertexPT));
//left
D3DDevice->SetTexture(0, g_pTextureManager->GetTexture("./SkyBox/badomen_lf.png"));
D3DDevice->DrawPrimitiveUP(D3DPT_TRIANGLELIST, 2, &skyBox[12], sizeof(VertexPT));
//right
D3DDevice->SetTexture(0, g_pTextureManager->GetTexture("./SkyBox/badomen_rt.png"));
D3DDevice->DrawPrimitiveUP(D3DPT_TRIANGLELIST, 2, &skyBox[18], sizeof(VertexPT));
//top
D3DDevice->SetTexture(0, g_pTextureManager->GetTexture("./SkyBox/badomen_up.png"));
D3DDevice->DrawPrimitiveUP(D3DPT_TRIANGLELIST, 2, &skyBox[24], sizeof(VertexPT));
//bottom
D3DDevice->SetTexture(0, g_pTextureManager->GetTexture("./SkyBox/badomen_dn.png"));
D3DDevice->DrawPrimitiveUP(D3DPT_TRIANGLELIST, 2, &skyBox[30], sizeof(VertexPT));
}
| [
"[email protected]"
] | |
bca59c46a920bfe5f8475fb254c30878f78ada18 | d6794736f216e2dc0e8798032e0ffead2fceb874 | /models/lowNE6SSM/lowNE6SSM_utilities.hpp | 4f0ce0068bf2887a970b8ed9e1448781f7251852 | [] | no_license | azedarach/CNE6SSM-Spectrum | 02f42cd79cece6f23a32f96546415e7630e62b27 | 6c5468dc359c0e2e37afece3b939d7034d55fd04 | refs/heads/master | 2021-06-07T08:34:04.063733 | 2015-10-26T02:47:17 | 2015-10-26T02:47:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,436 | hpp | // ====================================================================
// This file is part of FlexibleSUSY.
//
// FlexibleSUSY is free software: you can redistribute it and/or modify
// it 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.
//
// FlexibleSUSY 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
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with FlexibleSUSY. If not, see
// <http://www.gnu.org/licenses/>.
// ====================================================================
// File generated at Sun 21 Sep 2014 21:51:16
#ifndef lowNE6SSM_UTILITIES_H
#define lowNE6SSM_UTILITIES_H
#include "lowNE6SSM_two_scale_model.hpp"
#include "lowNE6SSM_info.hpp"
#include "wrappers.hpp"
#include <Eigen/Core>
#include <string>
#include <vector>
#include <valarray>
#include <utility>
#define PHYSICAL(p) model.get_physical().p
#define MODELPARAMETER(p) model.get_##p()
namespace flexiblesusy {
class lowNE6SSM_parameter_getter {
public:
Eigen::ArrayXd get_parameters(const lowNE6SSM<Two_scale>& model) {
return model.get();
}
std::vector<std::string> get_parameter_names(const lowNE6SSM<Two_scale>&) const {
using namespace lowNE6SSM_info;
return std::vector<std::string>(parameter_names,
parameter_names + NUMBER_OF_PARAMETERS);
}
};
class lowNE6SSM_spectrum_plotter {
public:
lowNE6SSM_spectrum_plotter();
~lowNE6SSM_spectrum_plotter() {}
template <class T>
void extract_spectrum(const lowNE6SSM<T>&);
void write_to_file(const std::string&) const;
private:
struct TParticle {
std::string name;
std::string latex_name;
std::valarray<double> masses;
TParticle(const std::string& name_, const std::string& latex_name_,
const std::valarray<double>& masses_)
: name(name_)
, latex_name(latex_name_)
, masses(masses_)
{}
};
typedef std::vector<TParticle> TSpectrum;
TSpectrum spectrum;
double scale;
unsigned width;
void write_spectrum(const TSpectrum&, std::ofstream&) const;
static std::valarray<double> to_valarray(double);
template <class Scalar, int M, int N>
static std::valarray<double> to_valarray(const Eigen::Array<Scalar, M, N>&);
};
template <class T>
void lowNE6SSM_spectrum_plotter::extract_spectrum(const lowNE6SSM<T>& model)
{
spectrum.clear();
scale = model.get_scale();
spectrum.push_back(TParticle("Glu", "\\tilde{g}", to_valarray(PHYSICAL(MGlu))));
spectrum.push_back(TParticle("ChaP", "\\tilde{\\chi}^{'-}", to_valarray(PHYSICAL(MChaP))));
spectrum.push_back(TParticle("VZp", "{Z'}", to_valarray(PHYSICAL(MVZp))));
spectrum.push_back(TParticle("Sd", "\\tilde{d}", to_valarray(PHYSICAL(MSd))));
spectrum.push_back(TParticle("Sv", "\\tilde{\\nu}", to_valarray(PHYSICAL(MSv))));
spectrum.push_back(TParticle("Su", "\\tilde{u}", to_valarray(PHYSICAL(MSu))));
spectrum.push_back(TParticle("Se", "\\tilde{e}", to_valarray(PHYSICAL(MSe))));
spectrum.push_back(TParticle("SDX", "\\tilde{x}", to_valarray(PHYSICAL(MSDX))));
spectrum.push_back(TParticle("hh", "h", to_valarray(PHYSICAL(Mhh))));
spectrum.push_back(TParticle("Ah", "A^0", to_valarray(PHYSICAL(MAh))));
spectrum.push_back(TParticle("Hpm", "H^-", to_valarray(PHYSICAL(MHpm))));
spectrum.push_back(TParticle("Chi", "\\tilde{\\chi}^0", to_valarray(PHYSICAL(MChi))));
spectrum.push_back(TParticle("Cha", "\\tilde{\\chi}^-", to_valarray(PHYSICAL(MCha))));
spectrum.push_back(TParticle("FDX", "x", to_valarray(PHYSICAL(MFDX))));
spectrum.push_back(TParticle("SHI0", "h^{0,Inert}", to_valarray(PHYSICAL(MSHI0))));
spectrum.push_back(TParticle("SHIPM", "h^{-,Inert}", to_valarray(PHYSICAL(MSHIPM))));
spectrum.push_back(TParticle("ChaI", "\\tilde{\\chi}^{-,Inert}", to_valarray(PHYSICAL(MChaI))));
spectrum.push_back(TParticle("ChiI", "\\tilde{\\chi}^{0,Inert}", to_valarray(PHYSICAL(MChiI))));
spectrum.push_back(TParticle("SHp0", "H^{'0}", to_valarray(PHYSICAL(MSHp0))));
spectrum.push_back(TParticle("SHpp", "H^{'-}", to_valarray(PHYSICAL(MSHpp))));
spectrum.push_back(TParticle("ChiP", "\\tilde{\\chi}^{'0}", to_valarray(PHYSICAL(MChiP))));
if (model.do_calculate_sm_pole_masses()) {
spectrum.push_back(TParticle("Fd", "d", to_valarray(PHYSICAL(MFd))));
spectrum.push_back(TParticle("Fe", "e", to_valarray(PHYSICAL(MFe))));
spectrum.push_back(TParticle("Fu", "u", to_valarray(PHYSICAL(MFu))));
spectrum.push_back(TParticle("Fv", "\\nu", to_valarray(PHYSICAL(MFv))));
spectrum.push_back(TParticle("VG", "g", to_valarray(PHYSICAL(MVG))));
spectrum.push_back(TParticle("VP", "\\gamma", to_valarray(PHYSICAL(MVP))));
spectrum.push_back(TParticle("VWm", "W^-", to_valarray(PHYSICAL(MVWm))));
spectrum.push_back(TParticle("VZ", "Z", to_valarray(PHYSICAL(MVZ))));
}
}
template <class Scalar, int M, int N>
std::valarray<double> lowNE6SSM_spectrum_plotter::to_valarray(const Eigen::Array<Scalar, M, N>& v)
{
return std::valarray<double>(v.data(), v.size());
}
} // namespace flexiblesusy
#endif
| [
"[email protected]"
] | |
4b78e7b1ac9e80c266de37c4134f477f6ca7ee40 | b6371cf32d8afb2d9afa6c5ae67434a7d958a94f | /BUAS Ray Tracer/ext/imgui-sfml/imgui-SFML.cpp | 699c1b34bae0e9edd2cac659e7b1e4b0bf851697 | [] | no_license | davidschep/brt | fbfd9a12423cbe7c865f9460c5100f78f4c3ca71 | b60c51fe83788ad5277d660de3837c52fee87636 | refs/heads/master | 2023-01-06T07:50:14.356965 | 2019-07-10T14:41:23 | 2019-07-10T14:41:23 | 185,023,544 | 0 | 1 | null | 2023-01-03T12:06:46 | 2019-05-05T11:41:13 | C++ | UTF-8 | C++ | false | false | 32,357 | cpp | #include "imgui-SFML.h"
#include "../imgui/imgui.h"
#include <SFML/Config.hpp>
#include <SFML/Graphics/Color.hpp>
#include <SFML/Graphics/RenderTarget.hpp>
#include <SFML/Graphics/RenderWindow.hpp>
#include <SFML/Graphics/Sprite.hpp>
#include <SFML/Graphics/Texture.hpp>
#include <SFML/OpenGL.hpp>
#include <SFML/Window/Clipboard.hpp>
#include <SFML/Window/Cursor.hpp>
#include <SFML/Window/Event.hpp>
#include <SFML/Window/Touch.hpp>
#include <SFML/Window/Window.hpp>
#include <cassert>
#include <cmath> // abs
#include <cstddef> // offsetof, NULL
#include <cstring> // memcpy
#ifdef ANDROID
#ifdef USE_JNI
#include <android/native_activity.h>
#include <jni.h>
#include <SFML/System/NativeActivity.hpp>
static bool s_wantTextInput = false;
int openKeyboardIME() {
ANativeActivity* activity = sf::getNativeActivity();
JavaVM* vm = activity->vm;
JNIEnv* env = activity->env;
JavaVMAttachArgs attachargs;
attachargs.version = JNI_VERSION_1_6;
attachargs.name = "NativeThread";
attachargs.group = NULL;
jint res = vm->AttachCurrentThread(&env, &attachargs);
if (res == JNI_ERR) return EXIT_FAILURE;
jclass natact = env->FindClass("android/app/NativeActivity");
jclass context = env->FindClass("android/content/Context");
jfieldID fid = env->GetStaticFieldID(context, "INPUT_METHOD_SERVICE",
"Ljava/lang/String;");
jobject svcstr = env->GetStaticObjectField(context, fid);
jmethodID getss = env->GetMethodID(
natact, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;");
jobject imm_obj = env->CallObjectMethod(activity->clazz, getss, svcstr);
jclass imm_cls = env->GetObjectClass(imm_obj);
jmethodID toggleSoftInput =
env->GetMethodID(imm_cls, "toggleSoftInput", "(II)V");
env->CallVoidMethod(imm_obj, toggleSoftInput, 2, 0);
env->DeleteLocalRef(imm_obj);
env->DeleteLocalRef(imm_cls);
env->DeleteLocalRef(svcstr);
env->DeleteLocalRef(context);
env->DeleteLocalRef(natact);
vm->DetachCurrentThread();
return EXIT_SUCCESS;
}
int closeKeyboardIME() {
ANativeActivity* activity = sf::getNativeActivity();
JavaVM* vm = activity->vm;
JNIEnv* env = activity->env;
JavaVMAttachArgs attachargs;
attachargs.version = JNI_VERSION_1_6;
attachargs.name = "NativeThread";
attachargs.group = NULL;
jint res = vm->AttachCurrentThread(&env, &attachargs);
if (res == JNI_ERR) return EXIT_FAILURE;
jclass natact = env->FindClass("android/app/NativeActivity");
jclass context = env->FindClass("android/content/Context");
jfieldID fid = env->GetStaticFieldID(context, "INPUT_METHOD_SERVICE",
"Ljava/lang/String;");
jobject svcstr = env->GetStaticObjectField(context, fid);
jmethodID getss = env->GetMethodID(
natact, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;");
jobject imm_obj = env->CallObjectMethod(activity->clazz, getss, svcstr);
jclass imm_cls = env->GetObjectClass(imm_obj);
jmethodID toggleSoftInput =
env->GetMethodID(imm_cls, "toggleSoftInput", "(II)V");
env->CallVoidMethod(imm_obj, toggleSoftInput, 1, 0);
env->DeleteLocalRef(imm_obj);
env->DeleteLocalRef(imm_cls);
env->DeleteLocalRef(svcstr);
env->DeleteLocalRef(context);
env->DeleteLocalRef(natact);
vm->DetachCurrentThread();
return EXIT_SUCCESS;
}
#endif
#endif
#if __cplusplus >= 201103L // C++11 and above
static_assert(sizeof(GLuint) <= sizeof(ImTextureID),
"ImTextureID is not large enough to fit GLuint.");
#endif
namespace {
// data
static bool s_windowHasFocus = false;
static bool s_mousePressed[3] = {false, false, false};
static bool s_touchDown[3] = {false, false, false};
static bool s_mouseMoved = false;
static sf::Vector2i s_touchPos;
static sf::Texture* s_fontTexture =
NULL; // owning pointer to internal font atlas which is used if user
// doesn't set custom sf::Texture.
static const unsigned int NULL_JOYSTICK_ID = sf::Joystick::Count;
static unsigned int s_joystickId = NULL_JOYSTICK_ID;
static const unsigned int NULL_JOYSTICK_BUTTON = sf::Joystick::ButtonCount;
static unsigned int s_joystickMapping[ImGuiNavInput_COUNT];
struct StickInfo {
sf::Joystick::Axis xAxis;
sf::Joystick::Axis yAxis;
bool xInverted;
bool yInverted;
float threshold;
};
StickInfo s_dPadInfo;
StickInfo s_lStickInfo;
// various helper functions
ImVec2 getTopLeftAbsolute(const sf::FloatRect& rect);
ImVec2 getDownRightAbsolute(const sf::FloatRect& rect);
ImTextureID convertGLTextureHandleToImTextureID(GLuint glTextureHandle);
GLuint convertImTextureIDToGLTextureHandle(ImTextureID textureID);
void RenderDrawLists(
ImDrawData* draw_data); // rendering callback function prototype
// Implementation of ImageButton overload
bool imageButtonImpl(const sf::Texture& texture,
const sf::FloatRect& textureRect, const sf::Vector2f& size,
const int framePadding, const sf::Color& bgColor,
const sf::Color& tintColor);
// Default mapping is XInput gamepad mapping
void initDefaultJoystickMapping();
// Returns first id of connected joystick
unsigned int getConnectedJoystickId();
void updateJoystickActionState(ImGuiIO& io, ImGuiNavInput_ action);
void updateJoystickDPadState(ImGuiIO& io);
void updateJoystickLStickState(ImGuiIO& io);
// clipboard functions
void setClipboardText(void* userData, const char* text);
const char* getClipboadText(void* userData);
std::string s_clipboardText;
// mouse cursors
void loadMouseCursor(ImGuiMouseCursor imguiCursorType,
sf::Cursor::Type sfmlCursorType);
void updateMouseCursor(sf::Window& window);
sf::Cursor* s_mouseCursors[ImGuiMouseCursor_COUNT];
bool s_mouseCursorLoaded[ImGuiMouseCursor_COUNT];
} // namespace
namespace ImGui {
namespace SFML {
void Init(sf::RenderWindow& window, bool loadDefaultFont) {
Init(window, window, loadDefaultFont);
}
void Init(sf::Window& window, sf::RenderTarget& target, bool loadDefaultFont) {
#if __cplusplus < 201103L // runtime assert when using earlier than C++11 as no
// static_assert support
assert(
sizeof(GLuint) <=
sizeof(ImTextureID)); // ImTextureID is not large enough to fit GLuint.
#endif
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
// tell ImGui which features we support
io.BackendFlags |= ImGuiBackendFlags_HasGamepad;
io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors;
io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos;
io.BackendPlatformName = "imgui_impl_sfml";
// init keyboard mapping
io.KeyMap[ImGuiKey_Tab] = sf::Keyboard::Tab;
io.KeyMap[ImGuiKey_LeftArrow] = sf::Keyboard::Left;
io.KeyMap[ImGuiKey_RightArrow] = sf::Keyboard::Right;
io.KeyMap[ImGuiKey_UpArrow] = sf::Keyboard::Up;
io.KeyMap[ImGuiKey_DownArrow] = sf::Keyboard::Down;
io.KeyMap[ImGuiKey_PageUp] = sf::Keyboard::PageUp;
io.KeyMap[ImGuiKey_PageDown] = sf::Keyboard::PageDown;
io.KeyMap[ImGuiKey_Home] = sf::Keyboard::Home;
io.KeyMap[ImGuiKey_End] = sf::Keyboard::End;
io.KeyMap[ImGuiKey_Insert] = sf::Keyboard::Insert;
#ifdef ANDROID
io.KeyMap[ImGuiKey_Backspace] = sf::Keyboard::Delete;
#else
io.KeyMap[ImGuiKey_Delete] = sf::Keyboard::Delete;
io.KeyMap[ImGuiKey_Backspace] = sf::Keyboard::BackSpace;
#endif
io.KeyMap[ImGuiKey_Space] = sf::Keyboard::Space;
io.KeyMap[ImGuiKey_Enter] = sf::Keyboard::Return;
io.KeyMap[ImGuiKey_Escape] = sf::Keyboard::Escape;
io.KeyMap[ImGuiKey_A] = sf::Keyboard::A;
io.KeyMap[ImGuiKey_C] = sf::Keyboard::C;
io.KeyMap[ImGuiKey_V] = sf::Keyboard::V;
io.KeyMap[ImGuiKey_X] = sf::Keyboard::X;
io.KeyMap[ImGuiKey_Y] = sf::Keyboard::Y;
io.KeyMap[ImGuiKey_Z] = sf::Keyboard::Z;
s_joystickId = getConnectedJoystickId();
for (unsigned int i = 0; i < ImGuiNavInput_COUNT; i++) {
s_joystickMapping[i] = NULL_JOYSTICK_BUTTON;
}
initDefaultJoystickMapping();
// init rendering
io.DisplaySize = static_cast<sf::Vector2f>(target.getSize());
// clipboard
io.SetClipboardTextFn = setClipboardText;
io.GetClipboardTextFn = getClipboadText;
// load mouse cursors
for (int i = 0; i < ImGuiMouseCursor_COUNT; ++i) {
s_mouseCursorLoaded[i] = false;
}
loadMouseCursor(ImGuiMouseCursor_Arrow, sf::Cursor::Arrow);
loadMouseCursor(ImGuiMouseCursor_TextInput, sf::Cursor::Text);
loadMouseCursor(ImGuiMouseCursor_ResizeAll, sf::Cursor::SizeAll);
loadMouseCursor(ImGuiMouseCursor_ResizeNS, sf::Cursor::SizeVertical);
loadMouseCursor(ImGuiMouseCursor_ResizeEW, sf::Cursor::SizeHorizontal);
loadMouseCursor(ImGuiMouseCursor_ResizeNESW,
sf::Cursor::SizeBottomLeftTopRight);
loadMouseCursor(ImGuiMouseCursor_ResizeNWSE,
sf::Cursor::SizeTopLeftBottomRight);
if (s_fontTexture) { // delete previously created texture
delete s_fontTexture;
}
s_fontTexture = new sf::Texture;
if (loadDefaultFont) {
// this will load default font automatically
// No need to call AddDefaultFont
UpdateFontTexture();
}
s_windowHasFocus = window.hasFocus();
}
void ProcessEvent(const sf::Event& event) {
if (s_windowHasFocus) {
ImGuiIO& io = ImGui::GetIO();
switch (event.type) {
case sf::Event::MouseMoved:
s_mouseMoved = true;
break;
case sf::Event::MouseButtonPressed: // fall-through
case sf::Event::MouseButtonReleased: {
int button = event.mouseButton.button;
if (event.type == sf::Event::MouseButtonPressed &&
button >= 0 && button < 3) {
s_mousePressed[event.mouseButton.button] = true;
}
} break;
case sf::Event::TouchBegan: // fall-through
case sf::Event::TouchEnded: {
s_mouseMoved = false;
int button = event.touch.finger;
if (event.type == sf::Event::TouchBegan && button >= 0 &&
button < 3) {
s_touchDown[event.touch.finger] = true;
}
} break;
case sf::Event::MouseWheelScrolled:
if (event.mouseWheelScroll.wheel == sf::Mouse::VerticalWheel ||
(event.mouseWheelScroll.wheel == sf::Mouse::HorizontalWheel &&
io.KeyShift)) {
io.MouseWheel += event.mouseWheelScroll.delta;
} else if (event.mouseWheelScroll.wheel == sf::Mouse::HorizontalWheel) {
io.MouseWheelH += event.mouseWheelScroll.delta;
}
break;
case sf::Event::KeyPressed: // fall-through
case sf::Event::KeyReleased:
io.KeysDown[event.key.code] =
(event.type == sf::Event::KeyPressed);
break;
case sf::Event::TextEntered:
// Don't handle the event for unprintable characters
if (event.text.unicode < ' ' || event.text.unicode == 127) {
break;
}
io.AddInputCharacter(event.text.unicode);
break;
case sf::Event::JoystickConnected:
if (s_joystickId == NULL_JOYSTICK_ID) {
s_joystickId = event.joystickConnect.joystickId;
}
break;
case sf::Event::JoystickDisconnected:
if (s_joystickId ==
event.joystickConnect
.joystickId) { // used gamepad was disconnected
s_joystickId = getConnectedJoystickId();
}
break;
default:
break;
}
}
switch (event.type) {
case sf::Event::LostFocus:
s_windowHasFocus = false;
break;
case sf::Event::GainedFocus:
s_windowHasFocus = true;
break;
default:
break;
}
}
void Update(sf::RenderWindow& window, sf::Time dt) {
Update(window, window, dt);
}
void Update(sf::Window& window, sf::RenderTarget& target, sf::Time dt) {
// Update OS/hardware mouse cursor if imgui isn't drawing a software cursor
updateMouseCursor(window);
if (!s_mouseMoved) {
if (sf::Touch::isDown(0))
s_touchPos = sf::Touch::getPosition(0, window);
Update(s_touchPos, static_cast<sf::Vector2f>(target.getSize()), dt);
} else {
Update(sf::Mouse::getPosition(window),
static_cast<sf::Vector2f>(target.getSize()), dt);
}
if (ImGui::GetIO().MouseDrawCursor) {
// Hide OS mouse cursor if imgui is drawing it
window.setMouseCursorVisible(false);
}
}
void Update(const sf::Vector2i& mousePos, const sf::Vector2f& displaySize,
sf::Time dt) {
ImGuiIO& io = ImGui::GetIO();
io.DisplaySize = displaySize;
io.DeltaTime = dt.asSeconds();
if (s_windowHasFocus) {
if (io.WantSetMousePos) {
sf::Vector2i newMousePos(static_cast<int>(io.MousePos.x),
static_cast<int>(io.MousePos.y));
sf::Mouse::setPosition(newMousePos);
} else {
io.MousePos = mousePos;
}
for (unsigned int i = 0; i < 3; i++) {
io.MouseDown[i] = s_touchDown[i] || sf::Touch::isDown(i) ||
s_mousePressed[i] ||
sf::Mouse::isButtonPressed((sf::Mouse::Button)i);
s_mousePressed[i] = false;
s_touchDown[i] = false;
}
}
// Update Ctrl, Shift, Alt, Super state
io.KeyCtrl = io.KeysDown[sf::Keyboard::LControl] ||
io.KeysDown[sf::Keyboard::RControl];
io.KeyAlt =
io.KeysDown[sf::Keyboard::LAlt] || io.KeysDown[sf::Keyboard::RAlt];
io.KeyShift =
io.KeysDown[sf::Keyboard::LShift] || io.KeysDown[sf::Keyboard::RShift];
io.KeySuper = io.KeysDown[sf::Keyboard::LSystem] ||
io.KeysDown[sf::Keyboard::RSystem];
#ifdef ANDROID
#ifdef USE_JNI
if (io.WantTextInput && !s_wantTextInput) {
openKeyboardIME();
s_wantTextInput = true;
}
if (!io.WantTextInput && s_wantTextInput) {
closeKeyboardIME();
s_wantTextInput = false;
}
#endif
#endif
assert(io.Fonts->Fonts.Size > 0); // You forgot to create and set up font
// atlas (see createFontTexture)
// gamepad navigation
if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) &&
s_joystickId != NULL_JOYSTICK_ID) {
updateJoystickActionState(io, ImGuiNavInput_Activate);
updateJoystickActionState(io, ImGuiNavInput_Cancel);
updateJoystickActionState(io, ImGuiNavInput_Input);
updateJoystickActionState(io, ImGuiNavInput_Menu);
updateJoystickActionState(io, ImGuiNavInput_FocusPrev);
updateJoystickActionState(io, ImGuiNavInput_FocusNext);
updateJoystickActionState(io, ImGuiNavInput_TweakSlow);
updateJoystickActionState(io, ImGuiNavInput_TweakFast);
updateJoystickDPadState(io);
updateJoystickLStickState(io);
}
ImGui::NewFrame();
}
void Render(sf::RenderTarget& target) {
target.resetGLStates();
ImGui::Render();
RenderDrawLists(ImGui::GetDrawData());
}
void Shutdown() {
ImGui::GetIO().Fonts->TexID = (ImTextureID)NULL;
if (s_fontTexture) { // if internal texture was created, we delete it
delete s_fontTexture;
s_fontTexture = NULL;
}
for (int i = 0; i < ImGuiMouseCursor_COUNT; ++i) {
if (s_mouseCursorLoaded[i]) {
delete s_mouseCursors[i];
s_mouseCursors[i] = NULL;
s_mouseCursorLoaded[i] = false;
}
}
ImGui::DestroyContext();
}
void UpdateFontTexture() {
ImGuiIO& io = ImGui::GetIO();
unsigned char* pixels;
int width, height;
io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
sf::Texture& texture = *s_fontTexture;
texture.create(width, height);
texture.update(pixels);
io.Fonts->TexID =
convertGLTextureHandleToImTextureID(texture.getNativeHandle());
}
sf::Texture& GetFontTexture() { return *s_fontTexture; }
void SetActiveJoystickId(unsigned int joystickId) {
assert(joystickId < sf::Joystick::Count);
s_joystickId = joystickId;
}
void SetJoytickDPadThreshold(float threshold) {
assert(threshold >= 0.f && threshold <= 100.f);
s_dPadInfo.threshold = threshold;
}
void SetJoytickLStickThreshold(float threshold) {
assert(threshold >= 0.f && threshold <= 100.f);
s_lStickInfo.threshold = threshold;
}
void SetJoystickMapping(int action, unsigned int joystickButton) {
assert(action < ImGuiNavInput_COUNT);
assert(joystickButton < sf::Joystick::ButtonCount);
s_joystickMapping[action] = joystickButton;
}
void SetDPadXAxis(sf::Joystick::Axis dPadXAxis, bool inverted) {
s_dPadInfo.xAxis = dPadXAxis;
s_dPadInfo.xInverted = inverted;
}
void SetDPadYAxis(sf::Joystick::Axis dPadYAxis, bool inverted) {
s_dPadInfo.yAxis = dPadYAxis;
s_dPadInfo.yInverted = inverted;
}
void SetLStickXAxis(sf::Joystick::Axis lStickXAxis, bool inverted) {
s_lStickInfo.xAxis = lStickXAxis;
s_lStickInfo.xInverted = inverted;
}
void SetLStickYAxis(sf::Joystick::Axis lStickYAxis, bool inverted) {
s_lStickInfo.yAxis = lStickYAxis;
s_lStickInfo.yInverted = inverted;
}
} // end of namespace SFML
/////////////// Image Overloads
void Image(const sf::Texture& texture, const sf::Color& tintColor,
const sf::Color& borderColor) {
Image(texture, static_cast<sf::Vector2f>(texture.getSize()), tintColor,
borderColor);
}
void Image(const sf::Texture& texture, const sf::Vector2f& size,
const sf::Color& tintColor, const sf::Color& borderColor) {
ImTextureID textureID =
convertGLTextureHandleToImTextureID(texture.getNativeHandle());
ImGui::Image(textureID, size, ImVec2(0, 0), ImVec2(1, 1), tintColor,
borderColor);
}
void Image(const sf::Texture& texture, const sf::FloatRect& textureRect,
const sf::Color& tintColor, const sf::Color& borderColor) {
Image(
texture,
sf::Vector2f(std::abs(textureRect.width), std::abs(textureRect.height)),
textureRect, tintColor, borderColor);
}
void Image(const sf::Texture& texture, const sf::Vector2f& size,
const sf::FloatRect& textureRect, const sf::Color& tintColor,
const sf::Color& borderColor) {
sf::Vector2f textureSize = static_cast<sf::Vector2f>(texture.getSize());
ImVec2 uv0(textureRect.left / textureSize.x,
textureRect.top / textureSize.y);
ImVec2 uv1((textureRect.left + textureRect.width) / textureSize.x,
(textureRect.top + textureRect.height) / textureSize.y);
ImTextureID textureID =
convertGLTextureHandleToImTextureID(texture.getNativeHandle());
ImGui::Image(textureID, size, uv0, uv1, tintColor, borderColor);
}
void Image(const sf::Sprite& sprite, const sf::Color& tintColor,
const sf::Color& borderColor) {
sf::FloatRect bounds = sprite.getGlobalBounds();
Image(sprite, sf::Vector2f(bounds.width, bounds.height), tintColor,
borderColor);
}
void Image(const sf::Sprite& sprite, const sf::Vector2f& size,
const sf::Color& tintColor, const sf::Color& borderColor) {
const sf::Texture* texturePtr = sprite.getTexture();
// sprite without texture cannot be drawn
if (!texturePtr) {
return;
}
Image(*texturePtr, size,
static_cast<sf::FloatRect>(sprite.getTextureRect()), tintColor,
borderColor);
}
/////////////// Image Button Overloads
bool ImageButton(const sf::Texture& texture, const int framePadding,
const sf::Color& bgColor, const sf::Color& tintColor) {
return ImageButton(texture, static_cast<sf::Vector2f>(texture.getSize()),
framePadding, bgColor, tintColor);
}
bool ImageButton(const sf::Texture& texture, const sf::Vector2f& size,
const int framePadding, const sf::Color& bgColor,
const sf::Color& tintColor) {
sf::Vector2f textureSize = static_cast<sf::Vector2f>(texture.getSize());
return ::imageButtonImpl(
texture, sf::FloatRect(0.f, 0.f, textureSize.x, textureSize.y), size,
framePadding, bgColor, tintColor);
}
bool ImageButton(const sf::Sprite& sprite, const int framePadding,
const sf::Color& bgColor, const sf::Color& tintColor) {
sf::FloatRect spriteSize = sprite.getGlobalBounds();
return ImageButton(sprite,
sf::Vector2f(spriteSize.width, spriteSize.height),
framePadding, bgColor, tintColor);
}
bool ImageButton(const sf::Sprite& sprite, const sf::Vector2f& size,
const int framePadding, const sf::Color& bgColor,
const sf::Color& tintColor) {
const sf::Texture* texturePtr = sprite.getTexture();
if (!texturePtr) {
return false;
}
return ::imageButtonImpl(
*texturePtr, static_cast<sf::FloatRect>(sprite.getTextureRect()), size,
framePadding, bgColor, tintColor);
}
/////////////// Draw_list Overloads
void DrawLine(const sf::Vector2f& a, const sf::Vector2f& b,
const sf::Color& color, float thickness) {
ImDrawList* draw_list = ImGui::GetWindowDrawList();
sf::Vector2f pos = ImGui::GetCursorScreenPos();
draw_list->AddLine(a + pos, b + pos, ColorConvertFloat4ToU32(color),
thickness);
}
void DrawRect(const sf::FloatRect& rect, const sf::Color& color, float rounding,
int rounding_corners, float thickness) {
ImDrawList* draw_list = ImGui::GetWindowDrawList();
draw_list->AddRect(getTopLeftAbsolute(rect), getDownRightAbsolute(rect),
ColorConvertFloat4ToU32(color), rounding,
rounding_corners, thickness);
}
void DrawRectFilled(const sf::FloatRect& rect, const sf::Color& color,
float rounding, int rounding_corners) {
ImDrawList* draw_list = ImGui::GetWindowDrawList();
draw_list->AddRectFilled(
getTopLeftAbsolute(rect), getDownRightAbsolute(rect),
ColorConvertFloat4ToU32(color), rounding, rounding_corners);
}
} // end of namespace ImGui
namespace {
ImVec2 getTopLeftAbsolute(const sf::FloatRect& rect) {
ImVec2 pos = ImGui::GetCursorScreenPos();
return ImVec2(rect.left + pos.x, rect.top + pos.y);
}
ImVec2 getDownRightAbsolute(const sf::FloatRect& rect) {
ImVec2 pos = ImGui::GetCursorScreenPos();
return ImVec2(rect.left + rect.width + pos.x,
rect.top + rect.height + pos.y);
}
ImTextureID convertGLTextureHandleToImTextureID(GLuint glTextureHandle) {
ImTextureID textureID = (ImTextureID)NULL;
std::memcpy(&textureID, &glTextureHandle, sizeof(GLuint));
return textureID;
}
GLuint convertImTextureIDToGLTextureHandle(ImTextureID textureID) {
GLuint glTextureHandle;
std::memcpy(&glTextureHandle, &textureID, sizeof(GLuint));
return glTextureHandle;
}
// Rendering callback
void RenderDrawLists(ImDrawData* draw_data) {
ImGui::GetDrawData();
if (draw_data->CmdListsCount == 0) {
return;
}
ImGuiIO& io = ImGui::GetIO();
assert(io.Fonts->TexID !=
(ImTextureID)NULL); // You forgot to create and set font texture
// scale stuff (needed for proper handling of window resize)
int fb_width =
static_cast<int>(io.DisplaySize.x * io.DisplayFramebufferScale.x);
int fb_height =
static_cast<int>(io.DisplaySize.y * io.DisplayFramebufferScale.y);
if (fb_width == 0 || fb_height == 0) {
return;
}
draw_data->ScaleClipRects(io.DisplayFramebufferScale);
#ifdef GL_VERSION_ES_CL_1_1
GLint last_program, last_texture, last_array_buffer,
last_element_array_buffer;
glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer);
glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &last_element_array_buffer);
#else
glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT | GL_TRANSFORM_BIT);
#endif
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
glEnable(GL_SCISSOR_TEST);
glEnable(GL_TEXTURE_2D);
glDisable(GL_LIGHTING);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height);
glMatrixMode(GL_TEXTURE);
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
#ifdef GL_VERSION_ES_CL_1_1
glOrthof(0.0f, io.DisplaySize.x, io.DisplaySize.y, 0.0f, -1.0f, +1.0f);
#else
glOrtho(0.0f, io.DisplaySize.x, io.DisplaySize.y, 0.0f, -1.0f, +1.0f);
#endif
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
for (int n = 0; n < draw_data->CmdListsCount; ++n) {
const ImDrawList* cmd_list = draw_data->CmdLists[n];
const unsigned char* vtx_buffer =
(const unsigned char*)&cmd_list->VtxBuffer.front();
const ImDrawIdx* idx_buffer = &cmd_list->IdxBuffer.front();
glVertexPointer(2, GL_FLOAT, sizeof(ImDrawVert),
(void*)(vtx_buffer + offsetof(ImDrawVert, pos)));
glTexCoordPointer(2, GL_FLOAT, sizeof(ImDrawVert),
(void*)(vtx_buffer + offsetof(ImDrawVert, uv)));
glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(ImDrawVert),
(void*)(vtx_buffer + offsetof(ImDrawVert, col)));
for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.size(); ++cmd_i) {
const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
if (pcmd->UserCallback) {
pcmd->UserCallback(cmd_list, pcmd);
} else {
GLuint textureHandle =
convertImTextureIDToGLTextureHandle(pcmd->TextureId);
glBindTexture(GL_TEXTURE_2D, textureHandle);
glScissor((int)pcmd->ClipRect.x,
(int)(fb_height - pcmd->ClipRect.w),
(int)(pcmd->ClipRect.z - pcmd->ClipRect.x),
(int)(pcmd->ClipRect.w - pcmd->ClipRect.y));
glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount,
GL_UNSIGNED_SHORT, idx_buffer);
}
idx_buffer += pcmd->ElemCount;
}
}
#ifdef GL_VERSION_ES_CL_1_1
glBindTexture(GL_TEXTURE_2D, last_texture);
glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, last_element_array_buffer);
glDisable(GL_SCISSOR_TEST);
#else
glPopAttrib();
#endif
}
bool imageButtonImpl(const sf::Texture& texture,
const sf::FloatRect& textureRect, const sf::Vector2f& size,
const int framePadding, const sf::Color& bgColor,
const sf::Color& tintColor) {
sf::Vector2f textureSize = static_cast<sf::Vector2f>(texture.getSize());
ImVec2 uv0(textureRect.left / textureSize.x,
textureRect.top / textureSize.y);
ImVec2 uv1((textureRect.left + textureRect.width) / textureSize.x,
(textureRect.top + textureRect.height) / textureSize.y);
ImTextureID textureID =
convertGLTextureHandleToImTextureID(texture.getNativeHandle());
return ImGui::ImageButton(textureID, size, uv0, uv1, framePadding, bgColor,
tintColor);
}
unsigned int getConnectedJoystickId() {
for (unsigned int i = 0; i < (unsigned int)sf::Joystick::Count; ++i) {
if (sf::Joystick::isConnected(i)) return i;
}
return NULL_JOYSTICK_ID;
}
void initDefaultJoystickMapping() {
ImGui::SFML::SetJoystickMapping(ImGuiNavInput_Activate, 0);
ImGui::SFML::SetJoystickMapping(ImGuiNavInput_Cancel, 1);
ImGui::SFML::SetJoystickMapping(ImGuiNavInput_Input, 3);
ImGui::SFML::SetJoystickMapping(ImGuiNavInput_Menu, 2);
ImGui::SFML::SetJoystickMapping(ImGuiNavInput_FocusPrev, 4);
ImGui::SFML::SetJoystickMapping(ImGuiNavInput_FocusNext, 5);
ImGui::SFML::SetJoystickMapping(ImGuiNavInput_TweakSlow, 4);
ImGui::SFML::SetJoystickMapping(ImGuiNavInput_TweakFast, 5);
ImGui::SFML::SetDPadXAxis(sf::Joystick::PovX);
// D-pad Y axis is inverted on Windows
#ifdef _WIN32
ImGui::SFML::SetDPadYAxis(sf::Joystick::PovY, true);
#else
ImGui::SFML::SetDPadYAxis(sf::Joystick::PovY);
#endif
ImGui::SFML::SetLStickXAxis(sf::Joystick::X);
ImGui::SFML::SetLStickYAxis(sf::Joystick::Y);
ImGui::SFML::SetJoytickDPadThreshold(5.f);
ImGui::SFML::SetJoytickLStickThreshold(5.f);
}
void updateJoystickActionState(ImGuiIO& io, ImGuiNavInput_ action) {
bool isPressed =
sf::Joystick::isButtonPressed(s_joystickId, s_joystickMapping[action]);
io.NavInputs[action] = isPressed ? 1.0f : 0.0f;
}
void updateJoystickDPadState(ImGuiIO& io) {
float dpadXPos =
sf::Joystick::getAxisPosition(s_joystickId, s_dPadInfo.xAxis);
if (s_dPadInfo.xInverted) dpadXPos = -dpadXPos;
float dpadYPos =
sf::Joystick::getAxisPosition(s_joystickId, s_dPadInfo.yAxis);
if (s_dPadInfo.yInverted) dpadYPos = -dpadYPos;
io.NavInputs[ImGuiNavInput_DpadLeft] =
dpadXPos < -s_dPadInfo.threshold ? 1.0f : 0.0f;
io.NavInputs[ImGuiNavInput_DpadRight] =
dpadXPos > s_dPadInfo.threshold ? 1.0f : 0.0f;
io.NavInputs[ImGuiNavInput_DpadUp] =
dpadYPos < -s_dPadInfo.threshold ? 1.0f : 0.0f;
io.NavInputs[ImGuiNavInput_DpadDown] =
dpadYPos > s_dPadInfo.threshold ? 1.0f : 0.0f;
}
void updateJoystickLStickState(ImGuiIO& io) {
float lStickXPos =
sf::Joystick::getAxisPosition(s_joystickId, s_lStickInfo.xAxis);
if (s_lStickInfo.xInverted) lStickXPos = -lStickXPos;
float lStickYPos =
sf::Joystick::getAxisPosition(s_joystickId, s_lStickInfo.yAxis);
if (s_lStickInfo.yInverted) lStickYPos = -lStickYPos;
if (lStickXPos < -s_lStickInfo.threshold) {
io.NavInputs[ImGuiNavInput_LStickLeft] = std::abs(lStickXPos / 100.f);
}
if (lStickXPos > s_lStickInfo.threshold) {
io.NavInputs[ImGuiNavInput_LStickRight] = lStickXPos / 100.f;
}
if (lStickYPos < -s_lStickInfo.threshold) {
io.NavInputs[ImGuiNavInput_LStickUp] = std::abs(lStickYPos / 100.f);
}
if (lStickYPos > s_lStickInfo.threshold) {
io.NavInputs[ImGuiNavInput_LStickDown] = lStickYPos / 100.f;
}
}
void setClipboardText(void* /*userData*/, const char* text) {
sf::Clipboard::setString(sf::String::fromUtf8(text, text + std::strlen(text)));
}
const char* getClipboadText(void* /*userData*/) {
std::basic_string<sf::Uint8> tmp = sf::Clipboard::getString().toUtf8();
s_clipboardText = std::string(tmp.begin(), tmp.end());
return s_clipboardText.c_str();
}
void loadMouseCursor(ImGuiMouseCursor imguiCursorType,
sf::Cursor::Type sfmlCursorType) {
s_mouseCursors[imguiCursorType] = new sf::Cursor();
s_mouseCursorLoaded[imguiCursorType] =
s_mouseCursors[imguiCursorType]->loadFromSystem(sfmlCursorType);
}
void updateMouseCursor(sf::Window& window) {
ImGuiIO& io = ImGui::GetIO();
if ((io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange) == 0) {
ImGuiMouseCursor cursor = ImGui::GetMouseCursor();
if (io.MouseDrawCursor || cursor == ImGuiMouseCursor_None) {
window.setMouseCursorVisible(false);
} else {
window.setMouseCursorVisible(true);
sf::Cursor& c = s_mouseCursorLoaded[cursor]
? *s_mouseCursors[cursor]
: *s_mouseCursors[ImGuiMouseCursor_Arrow];
window.setMouseCursor(c);
}
}
}
} // end of anonymous namespace
| [
"[email protected]"
] | |
b085829bca87fc8f6731581259b726fb5e719b55 | f39e3ce8d2d474c430523d1df787f1adf92f2923 | /Union_find/main.cpp | 934932d1baaacd644bbeaa9e6ea34a106456fc6e | [] | no_license | CS1103/union-find-Piero16301 | 7d82a93a9896df175e6d054a0d0a672b12bb9c84 | ce61a311ed9d378ad61f22c9887b64fcaca66f07 | refs/heads/master | 2022-01-08T17:25:40.438178 | 2019-05-24T17:58:16 | 2019-05-24T17:58:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,634 | cpp | #include <iostream>
#include "UnionFind.h"
#include <stdio.h>
using namespace std;
int main()
{
int numElements, operation, element1, element2; // variables
const char* INPUTFILE = "uf-medium.in";
freopen(INPUTFILE, "r", stdin); // opening the file "uf-medium.in" in read mode with stdin as the stream
scanf("%d", &numElements); // reads the first number in the file and stores it in numElements
UnionFind *disjointSets = new UnionFind(numElements); // instantiate UnionFind and pass in the number of elements to the constructor
while (3 == scanf("%d %d %d", &operation, &element1, &element2)) // this is just a condition to ensure there is nothing wrong with the file
{
if (operation == -1 && element1 == -1 && element1 == -1) // break-condition when the inputs are -1 -1 -1, indicating end of the file
break;
else if (!operation) // Connect/Union. Predefined that when operation == 0, form a connection
{
disjointSets->Union(element1 - 1, element2 - 1); // I subtract 1 because the ith element has index i-1
}
else // Connected/Find Predefined that when operation == 1, determine if elements are connected and output T or F
{
if(disjointSets->IsConnected(element1-1,element2-1))
cout<<"T"<<endl;
else
cout<<"F"<<endl;
}
}
disjointSets->~UnionFind(); //clean up memory and destruct! boom
string eof;
cin>>eof; // This is used for IDEs that automatically close their console window after runtime, forcing them to wait for user input
return 0;
} | [
"[email protected]"
] | |
957948e19115020031a73ecff266cfc35bae5a0b | 6b40e9cba1dd06cd31a289adff90e9ea622387ac | /Develop/Server/MasterServer/unittest/TestGameServerLogin.cpp | 6a5723aad9cd46848fe531c74d9238ce605a0df3 | [] | no_license | AmesianX/SHZPublicDev | c70a84f9170438256bc9b2a4d397d22c9c0e1fb9 | 0f53e3b94a34cef1bc32a06c80730b0d8afaef7d | refs/heads/master | 2022-02-09T07:34:44.339038 | 2014-06-09T09:20:04 | 2014-06-09T09:20:04 | null | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 8,513 | cpp | #include "stdafx.h"
#include "ZTestHelper.h"
#include "MockLink.h"
#include "ZCommandTable.h"
#include "ZGameServerAcceptor.h"
#include "ZGameServerObjectManager.h"
#include "ZGameServerInfoManager.h"
#include "MockFieldInfoManager.h"
#include "ZTestWrapper.h"
#include "ZFixtureHelper.h"
#include "ZConfig.h"
SUITE(GameServerLogin)
{
struct FGameServerLogin : public FBaseMockLink2
{
FGameServerLogin()
{
SetupFieldInfo();
SetupServerInfo();
ZConfig::m_nMyWorldID = WORLD_ID;
ZConfig::m_nMyServerID = SERVER_ID;
}
~FGameServerLogin()
{
}
void SetupFieldInfo()
{
AddFieldInfo(107, L"FieldName1", L"", false, 3);
AddFieldInfo(108, L"FieldName2", L"", false, 3);
}
void SetupServerInfo()
{
// 필드 할당 --
// 107 -1,2,3
// 108 -3
//
AddGameServerInfo(SERVER_ID, 107, 3, 1, 2, 3);
AddGameServerInfo(SERVER_ID, 108, 1, 3);
}
bool CheckResponseCommand(MCommand* pCommand, MUID uidClient=MUID::ZERO)
{
if (pCommand->GetID() != MMC_COMM_RESPONSE_LOGIN_M2G) return false;
int nResult;
MUID uidAlloc;
uint8 nServerMode;
if (pCommand->GetParameter(&nResult, 0, MPT_INT)==false) return false;
if (pCommand->GetParameter(&uidAlloc, 1, MPT_UID)==false) return false;
if (pCommand->GetParameter(&nServerMode,2, MPT_UCHAR)==false) return false;
MCommandParameter* pParam = pCommand->GetParameter(3);
if(pParam->GetType()!=MPT_BLOB) return false;
TDMG_MANAGED_SHARED_FIELD* pManagedSharedFields = (TDMG_MANAGED_SHARED_FIELD*)pParam->GetPointer();
if (pParam->GetBlobCount() != 2) return false; // 107, 108
if (pManagedSharedFields[0].nFieldID != 107) return false;
if (pManagedSharedFields[0].nChannelCount != 3) return false;
if (pManagedSharedFields[0].nChannelID[0] != 1) return false;
if (pManagedSharedFields[0].nChannelID[1] != 2) return false;
if (pManagedSharedFields[0].nChannelID[2] != 3) return false;
if (pManagedSharedFields[1].nFieldID != 108) return false;
if (pManagedSharedFields[1].nChannelCount != 1) return false;
if (pManagedSharedFields[1].nChannelID[0] != 3) return false;
set<MUID> setUID;
if (pManagedSharedFields[0].uidField[0] != MUID::ZERO) setUID.insert(pManagedSharedFields[0].uidField[0]);
if (pManagedSharedFields[0].uidField[1] != MUID::ZERO) setUID.insert(pManagedSharedFields[0].uidField[1]);
if (pManagedSharedFields[0].uidField[2] != MUID::ZERO) setUID.insert(pManagedSharedFields[0].uidField[2]);
if (pManagedSharedFields[1].uidField[0] != MUID::ZERO) setUID.insert(pManagedSharedFields[1].uidField[0]);
if (setUID.size() != 4) return false;
return true;
}
static const int WORLD_ID = 100;
static const int SERVER_ID = 1;
};
TEST_FIXTURE(FGameServerLogin, TestCmdHandler_MMC_COMM_REQUEST_LOGIN_G2M)
{
MockLink* pLink = NewLink();
const wstring strServerName = L"GameServer1";
const int nServerType = SERVER_GAME;
const int nParamCommandVersion = SH_COMMAND_VERSION;
const int nWorldID = WORLD_ID;
const int nServerID = SERVER_ID;
MCommandResult nCommandResult = pLink->OnRecv(MMC_COMM_REQUEST_LOGIN_G2M, 5,
NEW_WSTR(strServerName.c_str()),
NEW_INT(nServerType),
NEW_INT(nWorldID),
NEW_INT(nServerID),
NEW_INT(nParamCommandVersion));
CHECK_EQUAL(CR_TRUE, nCommandResult);
CHECK_EQUAL(3, pLink->GetCommandCount()); // MMC_COMM_RESPONSE_LOGIN, MMC_FIELD_INFO_ALL, MMC_PARTY_INFO_ALL_RES
CHECK_EQUAL(MMC_COMM_RESPONSE_LOGIN_M2G, pLink->GetCommand(0).GetID());
CHECK_EQUAL(CR_SUCCESS, pLink->GetParam<int>(0, 0));
// CheckResponseCommand 함수에서 커맨드 모든 파라메타를 검사한다.
CHECK(CheckResponseCommand(&pLink->GetCommand(0)) == true);
}
TEST_FIXTURE(FGameServerLogin, TestCmdHandler_MMC_COMM_REQUEST_LOGIN_Failure_NotEqualCommandVersion)
{
MockLink* pLink = NewLink();
const wstring strServerName = L"GameServer1";
const int nServerType = SERVER_GAME;
const int nParamCommandVersion = SH_COMMAND_VERSION + 1;
const int nWorldID = WORLD_ID;
const int nServerID = SERVER_ID;
MCommandResult nCommandResult = pLink->OnRecv(MMC_COMM_REQUEST_LOGIN_G2M, 5,
NEW_WSTR(strServerName.c_str()),
NEW_INT(nServerType),
NEW_INT(nWorldID),
NEW_INT(nServerID),
NEW_INT(nParamCommandVersion));
CHECK_EQUAL(CR_TRUE, nCommandResult);
CHECK_EQUAL(1, pLink->GetCommandCount()); // MMC_COMM_RESPONSE_LOGIN_M2G
CHECK_EQUAL(MMC_COMM_RESPONSE_LOGIN_M2G, pLink->GetCommand(0).GetID());
CHECK_EQUAL(CRM_FAIL_LOGIN_COMMAND_INVALID_VERSION, pLink->GetParam<int>(0, 0));
// CheckResponseCommand 함수에서 커맨드 모든 파라메타를 검사한다.
CHECK(CheckResponseCommand(&pLink->GetCommand(0)) == false);
}
TEST_FIXTURE(FGameServerLogin, TestCmdHandler_MMC_COMM_REQUEST_LOGIN_Failure_InvalidWorldID)
{
MockLink* pLink = NewLink();
const wstring strServerName = L"GameServer1";
const int nServerType = SERVER_GAME;
const int nParamCommandVersion = SH_COMMAND_VERSION;
const int nInvalidWorldID = 234234;
const int nServerID = SERVER_ID;
MCommandResult nCommandResult = pLink->OnRecv(MMC_COMM_REQUEST_LOGIN_G2M, 5,
NEW_WSTR(strServerName.c_str()),
NEW_INT(nServerType),
NEW_INT(nInvalidWorldID),
NEW_INT(nServerID),
NEW_INT(nParamCommandVersion));
CHECK_EQUAL(1, pLink->GetCommandCount()); // MMC_COMM_RESPONSE_LOGIN_M2G
CHECK_EQUAL(MMC_COMM_RESPONSE_LOGIN_M2G, pLink->GetCommand(0).GetID());
CHECK_EQUAL(CRM_FAIL_LOGIN_INVALID_WORLD_ID, pLink->GetParam<int>(0, 0));
// CheckResponseCommand 함수에서 커맨드 모든 파라메타를 검사한다.
CHECK(CheckResponseCommand(&pLink->GetCommand(0)) == false);
}
TEST_FIXTURE(FGameServerLogin, TestCmdHandler_MMC_COMM_REQUEST_LOGIN_Failure_InvalidServerID)
{
MockLink* pLink = NewLink();
const wstring strServerName = L"GameServer1";
const int nServerType = SERVER_GAME;
const int nParamCommandVersion = SH_COMMAND_VERSION;
const int nWorldID = WORLD_ID;
const int nInvalidServerID = 0;
MCommandResult nCommandResult = pLink->OnRecv(MMC_COMM_REQUEST_LOGIN_G2M, 5,
NEW_WSTR(strServerName.c_str()),
NEW_INT(nServerType),
NEW_INT(nWorldID),
NEW_INT(nInvalidServerID),
NEW_INT(nParamCommandVersion));
CHECK_EQUAL(1, pLink->GetCommandCount()); // MMC_COMM_RESPONSE_LOGIN_M2G
CHECK_EQUAL(MMC_COMM_RESPONSE_LOGIN_M2G, pLink->GetCommand(0).GetID());
CHECK_EQUAL(CRM_FAIL_LOGIN_ACCEPT, pLink->GetParam<int>(0, 0));
// CheckResponseCommand 함수에서 커맨드 모든 파라메타를 검사한다.
CHECK(CheckResponseCommand(&pLink->GetCommand(0)) == false);
}
TEST_FIXTURE(FGameServerLogin, TestCmdHandler_MMC_COMM_REQUEST_LOGIN_G2M_Failure_Duplicated)
{
MockLink* pLink = NewLink();
const wstring strServerName = L"GameServer1";
const int nServerType = SERVER_GAME;
const int nParamCommandVersion = SH_COMMAND_VERSION;
const int nWorldID = WORLD_ID;
const int nServerID = SERVER_ID;
pLink->OnRecv(MMC_COMM_REQUEST_LOGIN_G2M, 5,
NEW_WSTR(strServerName.c_str()),
NEW_INT(nServerType),
NEW_INT(nWorldID),
NEW_INT(nServerID),
NEW_INT(nParamCommandVersion));
pLink->ResetCommands();
pLink->OnRecv(MMC_COMM_REQUEST_LOGIN_G2M, 5,
NEW_WSTR(strServerName.c_str()),
NEW_INT(nServerType),
NEW_INT(nWorldID),
NEW_INT(nServerID),
NEW_INT(nParamCommandVersion));
CHECK_EQUAL(1, pLink->GetCommandCount()); // MMC_COMM_RESPONSE_LOGIN_M2G
CHECK_EQUAL(MMC_COMM_RESPONSE_LOGIN_M2G, pLink->GetCommand(0).GetID());
CHECK_EQUAL(CRM_FAIL_LOGIN_ALREADY_EXIST, pLink->GetParam<int>(0, 0));
// CheckResponseCommand 함수에서 커맨드 모든 파라메타를 검사한다.
CHECK(CheckResponseCommand(&pLink->GetCommand(0)) == false);
}
TEST_FIXTURE(FGameServerLogin, TestServerObjectAcceptor)
{
MUID uidClient = ZTestHelper::NewUID();
int nServerID = SERVER_ID;
ZGameServerAcceptor acceptor(uidClient, nServerID);
bool bRet = acceptor.Accept();
CHECK_EQUAL(bRet, true);
CHECK_EQUAL(1, gmgr.pGameServerObjectManager->GetClientsCount());
std::auto_ptr<MCommand> pNewCommand(acceptor.MakeResponseCommand());
CHECK_EQUAL(MMC_COMM_RESPONSE_LOGIN_M2G, pNewCommand->GetID());
CHECK(CheckResponseCommand(pNewCommand.get(), uidClient) == true);
}
}
| [
"shzdev@8fd9ef21-cdc5-48af-8625-ea2f38c673c4"
] | shzdev@8fd9ef21-cdc5-48af-8625-ea2f38c673c4 |
af89f6b2b0f25cbabede06ef55dcebc3212fc9dc | 733a1e1950770be5323a53f3dc91b32e49e1a8d6 | /examples/RotaryEncoder/RotaryEncoder.ino | 0455a68cad755a3047dcfa9914ec4f6647328e51 | [
"MIT"
] | permissive | luni64/EncSim | 9e410a97a922d544ae49a5fb8c8fecdda779cf82 | f5d6a119700f17a72aff1988828086a85de4df34 | refs/heads/master | 2022-06-09T11:08:05.407196 | 2022-05-16T15:36:19 | 2022-05-16T15:36:19 | 93,673,420 | 13 | 4 | MIT | 2018-07-23T04:19:04 | 2017-06-07T19:48:09 | C++ | UTF-8 | C++ | false | false | 1,009 | ino | #include "EncSim.h"
EncSim encSim(0, 1, 2); // A=0, B=1, Z=2
constexpr float rpm = 800; // revolutions per minute
constexpr float ppr = 32768; // encoder pulses per revolution
constexpr float rps = rpm / 60; // revolution per second11
constexpr float freq = rps * ppr; // count frequency
void setup()
{
pinMode(LED_BUILTIN, OUTPUT);
while (!Serial) {}
Serial.printf("rpm:\t%8.2f 1/min\n", rpm);
Serial.printf("pps:\t%8.2f kHz\n", freq / 1000.0f);
Serial.printf("phase freq:\t%8.2f kHz\n", freq / 4000.0f);
Serial.printf("z-freq :\t%8.2f Hz\n", rps);
encSim
.begin()
.setFrequency(freq) // calculated above
.setPeriod(ppr) // set above
.setPhase(90) // 90° phase signal
.setTotalBounceDuration(0); // no bouncing
encSim.moveRelAsync(INT32_MAX); // run for some time INT32_MAX = 2147483647
}
void loop()
{
digitalToggleFast(LED_BUILTIN); // heart beat
delay(250);
} | [
"[email protected]"
] | |
5ddf4949c77ac0e16a3340eb0ca561b2ea71c7a8 | bd740071d2ba4fd074da483b7b7ae251e4426d3f | /WDProgrammer/WDProgrammer/Trie.h | d916688b2e3fbfcf7a53ddef52a618504104caf9 | [] | no_license | rangqiongliu/WDProgrammer | ba745fdf8f1f4aaa5e68b5f29a0adb3e83c6732c | 9feca538c82a6d7a4737ceaa27159f6940a16781 | refs/heads/master | 2021-05-01T09:38:22.596294 | 2018-04-08T07:57:45 | 2018-04-08T07:57:45 | 121,095,599 | 9 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,989 | h | /*
文件说明:Trie.h与Trie.cpp是为了声明和实现后缀树相关的一些算法
*/
#define _SILENCE_STDEXT_HASH_DEPRECATION_WARNINGS
#pragma once
#define INF 99999999
#include<iostream>
#include<typeinfo>
#include<bitset>
#include<vector>
#include<algorithm>
#include<time.h>
#include<fstream>
#include<Windows.h>
#include<hash_map>
using namespace std;
//以下代码为构建Trie树,只实现对字符串(a-z)的插入和查找。
//Trie数多用于大量数据的统计和查询,还有查询某个字符串是否是另一个字符串的前缀。
//优点:最大减少无谓的字符串比较
//缺点:当字符串集合中公共前缀较少时,会大量消耗内存空间
struct Trie_Node
{
bool isStr;
Trie_Node * Child[26];//每个节点有26个子节点
string sth;//这个变量也可以记录统计每个单词出现的频率
Trie_Node() : isStr(false) { memset(Child, NULL, sizeof(Child)); }
};
class Trie
{
public:
Trie() { root = new Trie_Node(); }
~Trie() { delete root; }
//构建前缀树
void Insert(const char *word);
//如果不存在字符串,则返回0,如果存在则返回1,如果只是某个字符串的前缀则返回2
int Check(const char *word);
//删除以某节点为父节点的后缀树
void delete_Trie(Trie_Node *Tree);
//构建后缀树
void InsertSufixTrie(const char *word);
//判断sour是否为des的子串,sour为待查询的字符串,des为目标字符串;如果des不存在Trie中,则默认会添加进Trie中。
bool isSubstr(const char *sour, const char *des);
//统计sour在des中重复的次数。sour为子串,des为目标字符串。如果des不存在Trie中,则默认会添加进Trie中。
int repeatNum(const char *sour, const char *des);
/*统计从某个节点开始的子树中,含终止符的个数*/
int getStrNum(Trie_Node * root);
private:
Trie_Node * root;
};////以上代码为构建Trie树(前缀或者后缀),实现对字符串(a-z)的插入和查找 | [
"Administrator@USER-20170927SL"
] | Administrator@USER-20170927SL |
11af509ec4f8b727ca10ec2046abd90b774363ee | 5a7d3db1f4dc544d47430dcecf9de5ae2990fe88 | /.emacs.d/undohist/!home!sirogami!programming!compe!algorithm!syakutori!1.cc | 19f3f4da7086544776c6e5db2c6744b50766fac1 | [] | no_license | sirogamichandayo/emacs_sirogami | d990da25e5b83b23799070b4d1b5c540b12023b9 | c646cfd1c4a69cef2762432ba4492e32c2c025c8 | refs/heads/master | 2023-01-24T12:38:56.308764 | 2020-12-07T10:42:35 | 2020-12-07T10:42:35 | 245,687,325 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,216 | cc |
((digest . "9acd560d2029288f847fdd3d23227336") (undo-list nil (580 . 582) nil ("-" . -579) ((marker . 582) . -1) ("-" . -580) ((marker . 582) . -1) 581 (t 24366 2723 441069 272000) nil (554 . 555) nil ("n" . -554) ((marker . 582) . -1) ((marker) . -1) 555 (t 24366 2696 481218 933000) nil (807 . 811) nil (819 . 820) nil (815 . 819) nil (813 . 815) nil (809 . 813) nil (807 . 809) nil (806 . 807) nil (804 . 806) nil (799 . 804) nil (792 . 794) (" " . 792) (797 . 798) (792 . 793) (" " . 792) ((marker . 582) . -2) ((marker . 792) . -2) ((marker . 792) . -2) (797 . 798) nil (794 . 797) nil (791 . 794) (" " . 791) ((marker . 582) . -2) 793 (t 24366 2691 925244 213000) nil (790 . 793) nil (783 . 784) nil ("left" . -783) ((marker . 582) . -4) 787 nil (788 . 789) nil (783 . 787) (782 . 784) ("[" . -782) (774 . 783) nil (773 . 774) (" x" . -773) (773 . 775) ("else" . 773) ((marker . 582) . -4) (769 . 773) 773 nil (769 . 773) nil (765 . 769) nil (764 . 765) nil (761 . 764) nil (760 . 761) nil (753 . 759) nil (752 . 754) ("(" . -752) (752 . 753) nil (749 . 752) nil (745 . 749) (" " . 745) ((marker . 582) . -3) 748 nil (744 . 748) nil (743 . 744) nil (737 . 742) nil (736 . 738) ("(" . -736) (736 . 737) nil (729 . 736) nil (641 . 642) nil (639 . 640) nil (639 . 640) (nil face font-lock-type-face 638 . 639) (nil fontified nil 638 . 639) (638 . 639) ("{" . -638) (638 . 639) nil (632 . 638) nil (629 . 632) nil (712 . 716) (" " . 712) ((marker . 582) . -3) 715 nil (711 . 715) nil (702 . 704) nil ("
" . 705) ((marker . 369) . -1) ((marker . 369) . -1) (" ++r;" . -705) ((marker . 582) . -8) 713 nil (712 . 713) nil (709 . 712) nil (704 . 709) nil (703 . 704) nil (701 . 702) (700 . 702) ("[" . -700) (696 . 701) nil ("+" . -696) ((marker . 582) . -1) 697 nil (692 . 697) nil (688 . 692) (687 . 692) nil (683 . 686) (" " . 683) (687 . 689) ("{" . -687) (687 . 688) nil (682 . 687) nil (678 . 681) nil (677 . 678) nil (676 . 677) nil (674 . 675) (673 . 675) ("[" . -673) (666 . 674) nil (640 . 641) nil ("n" . -640) ((marker . 582) . -1) 641 nil (508 . 509) nil ("n" . -508) ((marker . 582) . -1) 509 nil (543 . 544) nil ("n" . -543) ((marker . 582) . -1) 544 nil (521 . 522) nil ("n" . -521) ((marker . 582) . -1) 522 nil (661 . 662) nil ("n" . -661) ((marker . 582) . -1) 662 nil (660 . 666) nil (659 . 660) nil (657 . 659) nil (656 . 658) ("(" . -656) (656 . 657) nil (655 . 656) (" x" . -655) (655 . 657) ("while" . 655) ((marker . 582) . -5) (650 . 655) 655 nil (650 . 655) nil (647 . 650) (646 . 650) nil (643 . 645) (" " . 643) (646 . 648) ("{" . -646) (646 . 647) nil (642 . 646) nil (640 . 641) nil (639 . 640) nil (638 . 639) nil (637 . 638) nil (")" . -637) (637 . 638) (")" . -637) (637 . 638) (636 . 638) ("(" . -636) (636 . 637) nil (633 . 636) nil (630 . 633) nil (")
" . 631) (" for (ll l " . -631) ((marker . 582) . -12) ((marker . 825) . -2) ((marker . 825) . -2) 643 nil (" " . -643) ((marker . 582) . -1) 644 nil (641 . 644) nil (" " . -641) ((marker . 582) . -1) 642 nil (638 . 642) nil (637 . 639) ("(" . -637) (637 . 638) nil (633 . 637) nil (630 . 633) nil (")
" . 631) (" for (ll " . -631) ((marker . 582) . -10) 641 nil (638 . 641) nil (637 . 639) ("(" . -637) (637 . 638) nil (633 . 637) nil (624 . 625) nil ("l" . -624) ((marker . 582) . -1) 625 nil (630 . 633) nil ("
" . 631) (" while " . -631) ((marker . 582) . -8) 639 nil (638 . 639) (" x" . -638) (638 . 640) ("while" . 638) ((marker . 582) . -5) (633 . 638) 638 nil (633 . 638) nil (630 . 633) (" " . 630) ((marker . 582) . -2) 632 nil (629 . 632) nil (628 . 629) nil (626 . 627) nil (625 . 627) ("{" . -625) (625 . 626) nil (" " . -625) ((marker . 582) . -1) 626 nil (621 . 626) nil (618 . 621) nil (617 . 618) nil ("," . -617) ((marker . 582) . -1) (" " . -618) ((marker . 582) . -1) 619 nil (618 . 619) nil (617 . 618) nil (";" . -617) ((marker . 582) . -1) ((marker . 617) . -1) ((marker . 617) . -1) 618 nil (617 . 618) nil (615 . 616) nil (614 . 616) ("{" . -614) (614 . 615) nil (608 . 614) nil (605 . 608) (" " . 605) ((marker . 582) . -2) 607 nil (604 . 607) nil (568 . 569) nil (566 . 567) (565 . 567) ("[" . -565) (563 . 566) nil (561 . 563) nil (556 . 561) nil (553 . 555) nil (552 . 553) nil (551 . 552) nil (")" . -551) (551 . 552) (")" . -551) (551 . 552) (550 . 552) ("(" . -550) (550 . 551) nil (547 . 550) nil (546 . 547) nil (545 . 546) nil (543 . 544) nil (542 . 544) ("(" . -542) (542 . 543) nil (541 . 542) nil (540 . 541) nil (539 . 540) nil (537 . 539) nil (536 . 537) nil (530 . 536) nil (528 . 530) nil (562 . 563) nil (560 . 562) nil (558 . 560) nil (557 . 558) nil (553 . 557) nil (552 . 553) nil (548 . 552) nil (546 . 548) (545 . 548) nil (543 . 544) (" " . 543) (545 . 547) ("{" . -545) (545 . 546) nil (542 . 545) nil (538 . 541) nil (537 . 539) ("(" . -537) (537 . 538) nil (536 . 537) (" x" . -536) (536 . 538) ("while" . 536) ((marker . 582) . -5) (531 . 536) 536 nil (531 . 536) nil (529 . 531) (" " . 529) ((marker . 582) . -1) 530 nil (528 . 530) nil (527 . 528) nil (525 . 527) nil (523 . 525) nil (520 . 523) nil (518 . 520) nil (513 . 518) nil (512 . 513) nil (510 . 512) nil (509 . 510) nil (505 . 509) nil (503 . 505) nil (1 . 519) (t 24366 2035 828833 777000)))
| [
"[email protected]"
] | |
8cc573a97fe67b6a71594f94ad073cab8727fa39 | 8a8744104d9d2b50d350239dbc8a9f09a8ecc03a | /Code/CPlusPlus/Shared/FileIO/XML/HierarchyElement.cpp | b6902f77df72b24801bd9aab043010099952b7e1 | [] | no_license | JonnyRivers/rorn | fadd039b13fd95de5033d25e4552c456ab2eaa13 | ea3dab1d42838917c29d81f7ff92c11fc312a62e | refs/heads/master | 2016-08-12T19:55:18.729619 | 2014-09-11T21:20:30 | 2014-09-11T21:20:30 | 52,677,620 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,130 | cpp | #include "HierarchyElement.h"
using namespace Rorn::XML;
HierarchyElement::HierarchyElement(const char* name) : Element(name)
{
}
HierarchyElement& HierarchyElement::AddChildHierarchyElement(const char* name)
{
HierarchyElement* newElement = new HierarchyElement(name);
childElements_.push_back(std::shared_ptr<Element>(newElement));
return *newElement;
}
ValueElement& HierarchyElement::AddChildValueElement(const char* name, const char* value)
{
ValueElement* newElement = new ValueElement(name, value);
childElements_.push_back(std::shared_ptr<Element>(newElement));
return *newElement;
}
/*virtual*/ void HierarchyElement::SerializeDerived(Writer& writer) const
{
writer.IncreaseIndentLevel();
writer.WriteLine();
for(std::vector<std::shared_ptr<Element>>::const_iterator it = childElements_.begin() ; it != childElements_.end() ; ++it)
{
(*it)->Serialize(writer);
if(std::distance(it, childElements_.end()) > 1)
writer.WriteLine();// we need to decrease the indent level on the last one, so no new line
}
writer.DecreaseIndentLevel();
writer.WriteLine();
}
| [
"ca6jri@4fafbd65-2c19-2041-7f78-9da6aaec0f04"
] | ca6jri@4fafbd65-2c19-2041-7f78-9da6aaec0f04 |
10dd8064d69c5b4324aa83f69d1c02dd8d5c4f6e | 2a096864fab89532f8307a7e0bf05d6fb90febd5 | /GradeCluster.h | 9212d47525406d4b94e874bb004c5c051764af74 | [] | no_license | DouglasRoberts/GradeClusterCode | 00621b6a62e6b7925522de56502910c57be289b8 | 08903c144f38387dc4cd0eae565a194881e077fb | refs/heads/master | 2021-01-10T17:10:43.935442 | 2016-04-22T12:27:43 | 2016-04-22T12:27:43 | 52,461,171 | 1 | 0 | null | 2016-02-25T22:02:14 | 2016-02-24T17:29:30 | C | UTF-8 | C++ | false | false | 562 | h | #ifndef GRADECLUSTER_H
#define GRADECLUSTER_H
#include <TObject.h>
#include <TH1F.h>
#include <vector>
#include "SectionInfo.h"
// Grade cluster is basically a collection of section objects
class GradeCluster : public TObject {
public:
GradeCluster() : _hist(0) { }
GradeCluster(SectionInfo sect);
~GradeCluster() { }
void Merge(GradeCluster* otherCluster);
std::vector<SectionInfo> Cluster() {return _cluster;}
TH1F* gradeHist() {return _hist;}
private:
std::vector<SectionInfo> _cluster;
TH1F* _hist;
ClassDef(GradeCluster,2)
};
#endif | [
"[email protected]"
] | |
fa05a7d77ce266909fe7832d8f7123594c3a5bf1 | bf68b38598fe5c0deafd6d06456bd7f35c5c24af | /codeforces/practice/678B.cpp | ad4748219b20138e20ccab2ee0fa40dd37ab32dd | [] | no_license | manu-chroma/cp | f386604dc13a37a724683b55d8184585adf850f1 | 7e583ac80ba38f448e0f819b5cc088bfc53819ea | refs/heads/master | 2021-03-27T12:32:22.891265 | 2018-10-31T17:47:38 | 2018-10-31T17:47:38 | 44,018,280 | 1 | 0 | null | 2018-10-31T17:47:39 | 2015-10-10T16:28:33 | C++ | UTF-8 | C++ | false | false | 440 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long int li;
bool check_leap(li year) {
if(year % 400 == 0) return 1;
else if(year % 4 ==0 && year % 100 != 0) return 1;
return 0;
}
int main(int argc, char const *argv[])
{
ios_base::sync_with_stdio(false);
li year;
cin >> year;
int day = 0;
do {
if(check_leap(year)) day += 2;
else day++;
year++;
} while(day%8 != 0);
cout << --year << endl;
return 0;
}
| [
"[email protected]"
] | |
1fc2141e91f029f195f6f0e9893d11e16668e62f | 447ca7354a157d5f4af4e601024af8427adf093a | /Mntone.Nico.Renderer/Mntone.Nico.Renderer.Shared/native/comment_wrapper.h | bd48e1acfa52590a5dd01646c42a756d34d68fda | [] | no_license | mntone/OpenNiconicoCommentRenderer | 2a2331897c04b29bdc3135fd8a2b1d1737a0f6aa | 40160db896b9be57f7abc07e3d98ac4f9f1c567d | refs/heads/master | 2021-01-20T00:58:22.159477 | 2014-11-28T15:42:00 | 2014-11-28T15:42:00 | 16,856,269 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 652 | h | #pragma once
#include "comment_base.h"
#include "IComment.h"
namespace nico { namespace renderer {
class comment_wrapper final
: public comment_base
{
public:
comment_wrapper( ::Mntone::Nico::Renderer::IComment^ comment );
virtual const wchar_t* const value() const noexcept;
virtual size_t length() const noexcept;
virtual bool self() const noexcept;
virtual bool cyalume() const noexcept;
virtual comment_vertical_position_type vertical_position() const noexcept;
virtual comment_size_type size() const noexcept;
virtual comment_color color() const noexcept;
private:
::Mntone::Nico::Renderer::IComment^ comment_;
};
} } | [
"[email protected]"
] | |
74e155c6c4aab3a69e78d2abd776eb7483d8866c | c87f23b3dff4293de375307729dbd9b5a21db2ee | /src/vo_stereo_4.cpp | 6b3eaec271278511d515d80fcf81b047033065d5 | [
"Apache-2.0"
] | permissive | avi9700/sdd_vio | bceacab0473e4e94b9c6f208ebbefa85eba8c2fc | dcd8cbb3f140d4eb9569ede4e94c36cc818aa557 | refs/heads/master | 2023-03-27T12:00:32.429355 | 2021-03-22T17:22:30 | 2021-03-22T18:10:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23,564 | cpp | /*-------------------------------------------------------------
Copyright 2019 Wenxin Liu, Kartik Mohta, Giuseppe Loianno
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 "sdd_vio/vo_stereo.h"
#include <iostream>
#include "sdd_vio/utils/math_utils.h"
#include <algorithm>
#include <math.h>
#include <ros/ros.h>
#include <cmath>
#include <assert.h>
#include <boost/thread.hpp>
#include "sdd_vio/utils/ros_params_helper.h"
#include "sdd_vio/utils/timer.hpp"
#include <ctime>
#include <opencv2/core/eigen.hpp>
namespace sdd_vio {
/* extract high gradient pixels */
// Input: left image 'img0'
// Output: high gradient pixels mask 'G_binary', gradient mat 'Gx','Gy'
void VoStereo::extractFeats(const cv::Mat& img0, cv::Mat& G_binary, cv::Mat& Gx, cv::Mat& Gy, int ilay)
{
ROS_DEBUG_STREAM("extract-Feats: ----------");
/* get gradient - from the tracking base layer and each layer up */
ROS_DEBUG_STREAM("extract-Feats: get gradient");
cv::Mat Gx2, Gy2, G2, G;
cv::Sobel(img0, Gx, CV_32F, 1, 0, 3);
cv::Sobel(img0, Gy, CV_32F, 0, 1, 3);
cv::multiply(Gx, Gx, Gx2);
cv::multiply(Gy, Gy, Gy2);
cv::add(Gx2, Gy2, G2);
cv::sqrt(G2, G);
G = sdd_vio::adjustVis(G); // adjust to 0-255
G.convertTo(G, CV_8U);
// sdd_vio::showMatMinMax(G);
/* threshold gradient - on the base layer */
ROS_DEBUG_STREAM("extract-Feats: threshold gradient");
cv::adaptiveThreshold(G, G_binary, 255, cv::ADAPTIVE_THRESH_GAUSSIAN_C, cv::THRESH_BINARY, adapt_size_, adapt_thresh_);
// double thresh_otsu;
// thresh_otsu = cv::threshold(G, G_binary, 0, 255, cv::THRESH_OTSU);
// std::cout << "thresh otsu: " << thresh_otsu << std::endl;
// cv::threshold(G2, G2_binary, 254, 255, cv::THRESH_BINARY);
// /* prune function that changes G_binary to contain only selected points */
ROS_DEBUG_STREAM("extract-Feats: prune function");
if (use_gd_)
gd_[ilay]->prune(G,G_binary);
/* set margin - for selection not too close to the boundary */
// std::cout<<"G_Binar at 0,0: "<<G_binary.at(0,0)<<"\n";
int nrows = G_binary.rows;
int ncols = G_binary.cols;
G_binary.rowRange(0, feat_margin_).setTo(cv::Scalar(0));
G_binary.rowRange(nrows-feat_margin_, nrows).setTo(cv::Scalar(0));
G_binary.colRange(0, feat_margin_).setTo(cv::Scalar(0));
G_binary.colRange(ncols-feat_margin_, ncols).setTo(cv::Scalar(0));
}
/*
Fill out vectors given mask
Input:
img0: keyframe image
G_binary: binary mask of selected high gradient points
disp: disparity image
Gx: gradient of feature points in x direction
Gy: gradient of feature points in y direction
ilay: specifying the layer number
Output:
feat_pixels: the pixel coordinates of feature points
disp_vec: disparity of feature points
intensities: pixel intensity of feature points
Gx_vec: Gx of feature points
Gy_vec: Gy of feature points
num_pts: total number of feature points
*/
void VoStereo::fillVectors(const cv::Mat& img0, const cv::Mat& G_binary, const cv::Mat& disp,
const cv::Mat& Gx, const cv::Mat& Gy, std::vector<float>& disp_vec, vector_aligned<Eigen::Vector2i>& feat_pixels,
std::vector<float>& intensities, std::vector<float>& Gx_vec, std::vector<float>& Gy_vec, int& num_pts, int ilay)
{
disp_vec.clear();
feat_pixels.resize(0);
intensities.resize(0);
Gx_vec.resize(0);
Gy_vec.resize(0);
std::vector<cv::Point> high_gradient_pixels;
cv::findNonZero(G_binary, high_gradient_pixels);
int npts = high_gradient_pixels.size();
/* get disparity vector and filter out unwanted points */
for (int i=0; i<npts; ++i)
{
int x = high_gradient_pixels[i].x;
int y = high_gradient_pixels[i].y;
if (!inBound(x,y,0, ilay))
std::cout<< "not inbound!" << std::endl;
float d = disp.at<int16_t>(y,x)/16.0;
float gx = Gx.at<float>(y,x);
float gy = Gy.at<float>(y,x);
float intensity = float(img0.at<uchar>(y,x));
/* select valid disparity range */
if (d>disp_range_pyr_[ilay] && inBound(x,y,1,ilay)) {
disp_vec.push_back(d);
Eigen::Vector2i pixel(x,y);
feat_pixels.push_back(pixel);
Gx_vec.push_back(gx);
Gy_vec.push_back(gy);
intensities.push_back(intensity);
}
}
// showVecMinMax(Gx_);
// std::cout << "valid number of feature points: " << disp_vec.size() << std::endl;
// sdd_vio::showVecMinMax(disp_vec);
num_pts = disp_vec.size();
}
/*
Input:
Gx: gradient vector of feature points in x direction
Gy: gradient vector of feature points in y direction
fx: calibration param
fy: calibration param
feat_3D: feature point coordinates in 3D in keyframe
npts: umber of feature points
Output:
J: Jacobian matrix of the feature points
*/
void VoStereo::getJacobian(const std::vector<float>& Gx, const std::vector<float>& Gy,
float fx, float fy, const vector_aligned<Eigen::Vector3f>& feat_3D, Eigen::MatrixXf& J, int npts)
{
J.resize(npts,6);
Eigen::Matrix<float,1,6> J_i; // Jacobian for one point
Eigen::Matrix<float,1,2> J_grad; // gradient jacobian
Eigen::Matrix<float,2,3> J_proj; // projection jacobian
Eigen::Matrix<float,3,6> J_SE3; // exponential jacobian
for (int i=0; i<npts; ++i)
{
/* calculate for each point the 1x6 Jacobian */
float x = feat_3D[i](0);
float y = feat_3D[i](1);
float z = feat_3D[i](2);
J_grad(0,0) = Gx[i];
J_grad(0,1) = Gy[i];
J_proj(0,0) = fx/z;
J_proj(1,0) = 0;
J_proj(0,1) = 0;
J_proj(1,1) = fy/z;
J_proj(0,2) = -fx*x/(z*z);
J_proj(1,2) = -fy*y/(z*z);
Eigen::Matrix3f npHat;
npHat << 0,z,-y,-z,0,x,y,-x,0;
J_SE3 << Eigen::Matrix3f::Identity(3,3), npHat;
J_i = J_grad * J_proj * J_SE3;
// if (i==0) {
// std::cout<<"x,y,z:\n"<<x<<'\n'<<y<<'\n'<<z<<std::endl;
// std::cout<<"J_grad:\n"<<J_grad<<std::endl;
// std::cout<<"J_proj:\n"<<J_proj<<std::endl;
// std::cout<<"J_SE3:\n"<<J_SE3<<std::endl;
// std::cout<<"J_i:\n"<<J_i<<std::endl;
// }
/* assign J_i to J */
J.block<1,6>(i,0) = J_i;
}
} // void VoStereo::getJacobian
/*
Input:
img_curr: current frame image
T_curr: current optimized transformation T between current frame and keyframe
feat_3D: feature points in 3D in keyframe coordinates
npts: number of feature points in total in the keyframe
ilay: specifying the layer from image pyramid to get error from
intensities: intensities of feature points from keyframe
J: Jacobian calculated from keyframe on the feature points
Output:
feat_3D_curr: feature points in 3D in current frame coordinates
feat_pixels_curr: feature points in current frame pixel coordinates
npts_in: the number of points remaining in view
mask: vector of size feat_3D, 0 if not in view, 1 if in view
error: vector of intensity errors, size as feat_3D, only update the values when mask=1
J_masked: of size npts_in x 6, with only entries of mask=1
error_masked: of size npts_in x 6, with only entries of mask=1
W: diagonal weight matrix for robust estimation Huber weights
*/
void VoStereo::getError(const cv::Mat& img_curr, const Eigen::MatrixXf& J, const Eigen::Isometry3f& T_curr,
const vector_aligned<Eigen::Vector3f>& feat_3D, const std::vector<float>& intensities,
vector_aligned<Eigen::Vector3f>& feat_3D_curr, vector_aligned<Eigen::Vector2f>& feat_pixels_curr, Eigen::VectorXf& error,
Eigen::VectorXf& mask, const int npts, const int ilay, int& npts_in,
Eigen::MatrixXf& J_masked, Eigen::VectorXf& error_masked, Eigen::VectorXf& W)
{
/* Timer Template
ros::Time t1 = ros::Time::now();
ros::Time t2 = ros::Time::now();
ros::Duration duration = t2 - t1;
std::cout << "Time for sorting: " << duration.toSec() << std::endl;
*/
ROS_DEBUG_STREAM("get-Error: --------- ");
/* transformation of feat_3D into current camera frame and obtain feat_3D_curr */
transform3D(feat_3D, feat_3D_curr, T_curr, npts);
/* for debug - will print out info if nan values found */
bool feat3dhasnan = false;
bool feat3dcurrhasnan = false;
for (int i=0; i<npts; ++i){
if (std::isnan(feat_3D_curr[i](2)))
feat3dcurrhasnan = true;
if (std::isnan(feat_3D[i](2)))
feat3dhasnan = true;
}
if (feat3dhasnan == true)
std::cout << "feat_3D has nan"<< std::endl;
if (feat3dcurrhasnan == true){
std::cout << "feat_3D_curr has nan"<<std::endl;
// std::cout<<"T_curr: "<<'\n'<<T_curr<<std::endl;
}
/* for debug */
/* reproject into current camera image */
cam_->get2DPixels(feat_3D_curr, feat_pixels_curr, npts, ilay);
/* update error vector and mask */
npts_in = 0;
for (int i=0; i<npts; ++i) {
if (inBound(feat_pixels_curr[i](0),feat_pixels_curr[i](1),0, ilay)) {
error[i] = intensities[i]-interpolate(feat_pixels_curr[i](0),feat_pixels_curr[i](1),img_curr);
npts_in = npts_in+1;
mask[i] = 1;
}
else {
mask[i] = 0; // mark the point as out of bound and not to consider
}
}
/* fill in the masked Jacobian */
J_masked.resize(npts_in,6);
error_masked.resize(npts_in);
int ind = 0;
for (int i=0; i<npts; ++i) {
if (mask[i]!=0) {
J_masked.row(ind) = J.row(i);
error_masked[ind] = error[i];
ind++;
}
}
Eigen::VectorXf r = error_masked;
// Eigen::VectorXf r_abs = error_masked.cwiseAbs();
/* sort to find median - impossible for time */
// std::sort(r.data(),r.data()+r.size());
// std::sort(r_abs.data(),r_abs.data()+r_abs.size());
// int mid = (int)(npts_in/2);
// float r_med = r[mid-1];
// float r_abs_med = r_abs[mid-1];
// Eigen::VectorXf r_hat = error_masked.array() - r_med; // normalize by removing the median (original order)
// float sigma = 1.485 * r_abs_med; // median absolute deviation
float r_mean = r.mean();
Eigen::VectorXf r_hat = error_masked.array() - r_mean; // normalize by removing the mean (original order)
float sigma = sqrt(((r_hat.array()).square()).sum()/npts_in); // standard deviation
// std::cout << "sigma: " << sigma << std::endl;
W.resize(npts_in);
for (int i=0; i<npts_in; ++i) {
if (fabs(r_hat[i]) < 1.345*sigma)
W[i] = 1;
else
W[i] = (1.345*sigma)/fabs(r_hat[i]);
}
/* for debug */
if (J_masked.maxCoeff() > J.maxCoeff()){
std::cout << "ind: " << ind << std::endl;
std::cout << "npts_in: "<<npts_in<<std::endl;
std::cout << "mask_sum: "<<mask.sum()<<std::endl;
}
/* for debug */
}
/*
Input:
img_curr: current image
J: Jacobian calculated from last keyframe of size npts x 6
feat_pixels:
feat_3D: feature points in 3D in keyframe coordinates
intensities: pixel intensities of feat_3D points
npts: number of feature points in keyframe
max_iter: max number of iterations specified for the optimizer
ilay: specifying the layer in image pyramid
Updates:
T_curr: current optimized transformation from keyframe to current frame
error: intensity errors of size npts x 1
variance:
mask: 0 if not in current view, 1 if in view
*/
void VoStereo::optimize(const cv::Mat& img_curr, const Eigen::MatrixXf& J, Eigen::Isometry3f& T_curr, Eigen::VectorXf& error,
Eigen::VectorXf& variance, vector_aligned<Eigen::Vector2i>& feat_pixels, vector_aligned<Eigen::Vector3f>& feat_3D,
std::vector<float>& intensities, Eigen::VectorXf& mask, const int npts, int max_iter, int ilay)
{
ROS_DEBUG_STREAM("op-timize: ----------- ");
int npts_in; // number of points remained in view
perc_ = 1.; // percentage of points remained in view
float err, err_mean = 0, err_init, err_last, err_diff = 0;
vector_aligned<Eigen::Vector3f> feat_3D_curr; // 3D points in current camera's frame
vector_aligned<Eigen::Vector2f> feat_pixels_curr; // 2D pixel coordinates in current image
/* masked Jacobian matrix and error vector - remove points outside projection */
Eigen::MatrixXf J_masked;
Eigen::VectorXf error_masked;
Eigen::VectorXf W; // diagonal weight matrix for Huber estimation
Eigen::MatrixXf J_masked_weighted;
/* Levenberg Marquardt */
float lambda = lambda_; // initial lambda is equal to the initial one set
float up = up_factor_;
float down = down_factor_;
bool if_break = false;
for (int iter=0; iter<max_iter; ++iter)
{
// vis_curr = vis_curr.clone();
// vis_curr = vis_curr;
/* calculate error vector and update mask given initial transformation T_curr */
if (iter == 0) {
/*
Calculate errors and Jacobians for optimization
Inputs:
img_curr
J
T_curr
feat_3D
intensities
npts
ilay
Outputs:
npts_in: for statistics
J_masked: for Hessian calculation
error_masked: for Hessian calculation,
feat_pixels_curr: for visualization
Recalculate in every iteration:
error
mask
feat_3D_curr
*/
getError(img_curr, J, T_curr, feat_3D, intensities, feat_3D_curr, feat_pixels_curr, error, mask,
npts, ilay, npts_in, J_masked, error_masked, W);
ROS_DEBUG_STREAM("op-timize: initial error obtained ");
/* Monitoring
getting statistics for setting criteria for end of iterations:
percentage of points in view and current average error value */
perc_ = 100*npts_in/npts;
err = error_masked.transpose()*error_masked; // sum of square errors
err_mean = sqrt(err/npts_in); // NOTE: not technically mean, but mean on squares then do sqrt
err_init = err_mean;
// draw blue circles on vis_curr of all the points
if (use_opt_vis_){
for (int i=0; i<npts; ++i) {
cv::Point p(feat_pixels_curr[i](0),feat_pixels_curr[i](1));
cv::circle(vis_curr, p,1,cv::Scalar(255,0,0),0.5);
}
}
}
/* convert weight vector W to diagonal matrix */
// J_masked_weighted.resize(npts_in,6);
// for (int i=0; i<npts_in; ++i) {
// J_masked_weighted.row(i) = J_masked.row(i) * W[i];
// }
/* get H = J^t * W * J */
Eigen::MatrixXf H = J_masked.transpose() * W.asDiagonal() * J_masked;
// Eigen::MatrixXf H = J_masked_weighted.transpose() * J_masked;
/* get b = J^t * w * e */
Eigen::VectorXf b = J_masked.transpose() * (W.asDiagonal() * error_masked);
// Eigen::VectorXf b = J_masked_weighted.transpose() * error_masked;
ROS_DEBUG_STREAM("op-timize: Hessian obtained. ");
/* Monitoring */
err_last = err_mean;
/* LMA */
float mult = 1 + lambda;
bool ill = true; // if ill conditioned (error increase)
Eigen::Isometry3f T_temp;
int lmit = 0; // number of iterations while ill=true
while ((ill==true) && (iter<max_iter) && (lmit<5))
{
/* Get H based on LMA current damping parameter, multiply diagonal by mult */
for (int par=0; par<6; par++)
H(par,par) = H(par,par)*mult;
/* get delta increment */
Eigen::VectorXf delta;
delta = -H.ldlt().solve(b);
/* for debug - delta is valid */
if (std::isnan(delta(0)+delta(1)+delta(2)+delta(3)+delta(4)+delta(5))){
std::cout<<"delta:"<<'\n'<<delta<<std::endl;
std::cout<<"H"<<'\n'<<H<<std::endl;
std::cout<<"b"<<'\n'<<b<<std::endl;
showEigenInfo(J_masked);
showEigenInfo(error_masked);
showEigenInfo(J);
showEigenInfo(error);
}
/* for debug */
/* update current transformation */
T_temp = T_curr * (exp_SE3(delta).inverse());
/* calculate error vector and update mask given transformation */
getError(img_curr, J, T_temp, feat_3D, intensities, feat_3D_curr, feat_pixels_curr, error, mask,
npts, ilay, npts_in, J_masked, error_masked, W);
perc_ = 100*npts_in/npts;
err = error_masked.transpose()*error_masked;
err_mean = sqrt(err/npts_in);
/* get error increment */
err_diff = err_mean - err_last;
ill = (err_diff > 0); // if error larger than before, set ill = true, try increase lambda.
/* terminal output */
if (verbose_) {
std::cout << "iteration = "<<iter<<", lambda = "<<lambda<<", err = "<<
err_mean<<", derr = "<<err_diff<<std::endl;
}
/* if ill=true, higher lambda by up factor, count as one iteration */
if (ill) {
mult = (1+lambda*up)/(1+lambda);
lambda *= up;
iter++;
}
lmit++;
}
/* update T with the one that makes error smaller or the last try */
/* error and jacobians are already updated in the loop */
T_curr = T_temp;
/* if error doesn't get higher for quite some time, this term will bring lambda down eventually */
if (lambda > 1e-8) // make sure doesn't overflow
lambda *= (1/down);
/* if LM iterations didn't decrease the error, stop */
if (ill) {
// ROS_WARN_STREAM("bad convergence!");
if_break = true;
}
/* if error is decreased below target or reach max iterations */
if (-err_diff < target_derr_ || iter == max_iter-1)
if_break = true;
/* end of optimization */
if (if_break) {
ROS_INFO_STREAM("iteration "<<iter<<"--------");
ROS_INFO_STREAM("err/initial err: "<<err_mean<<"/"<<err_init);
// optimized position, draw green circles
if (use_opt_vis_) {
for (int i=0; i<npts; ++i) {
if (inBound(feat_pixels_curr[i](0),feat_pixels_curr[i](1),0,ilay)) {
cv::Point p(feat_pixels_curr[i](0),feat_pixels_curr[i](1));
cv::circle(vis_curr, p,1,cv::Scalar(0,255,0),0.5);
}
}
cv::imshow("current features", vis_curr);
cv::waitKey(1);
}
break;
}
} // for (int iter=0;
} //void VoStereo::op-timize
/*
Optimization for state x given current frame image using Ceres-Solver
x: 6x1 state vector. first three elements in so(3) of R_curr_, last three elements same as t_curr_
Ceres is using AutoDiff to find the Jacobians of photometric errors with respect to state x
Input:
img_curr: current left camera image
ilay: the layer that it is on (e.g. there're two layers in total, then 0 is the larger and 1 is the smaller)
Updates:
R_curr_: 3x3 rotation matrix from keyframe to current frame
t_curr_: 3x1 translation vector from keyframe to current frame
T_curr_: 4x4 SE3 transformation matrix from keyframe to current frame
*/
// void VoStereo::optimize_ceres(const cv::Mat& img_curr, int ilay)
// {
// // The variable to solve for with its initial value.
// Eigen::Matrix<double,3,1> phi_init = log_SO3<double>(R_curr_.cast<double>());
// double x[6] = {phi_init(0), phi_init(1), phi_init(2), t_curr_(0), t_curr_(1), t_curr_(2)};
// // Build the problem.
// ceres::Problem problem;
// // Set up the cost function (also known as residual). This uses
// // auto-differentiation to obtain the derivative (jacobian).
// ceres::CostFunction* cost_function =
// new ceres::AutoDiffCostFunction<pixelIntensityError, ceres::DYNAMIC, 6>(new pixelIntensityError(this, &img_curr, ilay), num_feat_pts_[ilay]);
// problem.AddResidualBlock(cost_function, NULL, x);
// // Run the solver!
// ceres::Solver::Options options;
// options.minimizer_progress_to_stdout = false;
// options.max_num_iterations = 30;
// ceres::Solver::Summary summary;
// ceres::Solve(options, &problem, &summary);
// std::cout << summary.BriefReport() << "\n";
//// std::cout << summary.FullReport() << "\n";
// /* construct R and t from x */
// Eigen::Matrix<float,3,1> phi, p; // state variables os so3 and translation
// phi(0) = x[0]; phi(1) = x[1]; phi(2) = x[2];
// p(0) = x[3]; p(1) = x[4]; p(2) = x[5];
// Eigen::Matrix<float,3,3> R_curr = exp_SO3<float>(phi);
// /* assign R_curr_ and t_curr_, T_curr_ with optimized values */
// R_curr_ = R_curr;
// t_curr_ = p;
// T_curr_ = TfromRt(R_curr, p);
// rot_curr_ = phi.norm();
// }
}
| [
"[email protected]"
] | |
8146683421467ea9922a86666d509d5d3cc7b4a1 | 302f4bda84739593ab952f01c9e38d512b0a7d73 | /ext/humblelogging-3.0.1/include/humblelogging/formatter/simpleformatter.h | 46c762837b716f51bf398f5e5185045db2320b44 | [
"Apache-2.0",
"ICU",
"BSD-3-Clause",
"BSL-1.0",
"X11",
"Beerware"
] | permissive | thomaskrause/graphANNIS | 649ae23dd74b57bcd8a699c1e309e74096be9db2 | 66d12bcfb0e0b9bfcdc2df8ffaa5ae8c84cc569c | refs/heads/develop | 2020-04-11T01:28:47.589724 | 2018-03-15T18:16:50 | 2018-03-15T18:16:50 | 40,169,698 | 9 | 3 | Apache-2.0 | 2018-07-28T20:18:41 | 2015-08-04T07:24:49 | C++ | UTF-8 | C++ | false | false | 555 | h | #ifndef HL_SIMPLEFORMATTER_H
#define HL_SIMPLEFORMATTER_H
#include "humblelogging/formatter.h"
HL_NAMESPACE_BEGIN
/*
SimpleFormatter formats messages in a fixed predefined format.
It is maintained and updated during the development process of the
library to always contain the newest information.
*/
class HUMBLE_EXPORT_API SimpleFormatter
: public Formatter
{
public:
SimpleFormatter();
virtual ~SimpleFormatter();
virtual Formatter* copy() const;
virtual std::string format(const LogEvent &logEvent) const;
};
HL_NAMESPACE_END
#endif | [
"[email protected]"
] | |
b88042275aa473289c541c844e5022c0bc44bac6 | d9f81d536aab8d00535fed9bfb463601321af248 | /JuceLibraryCode/modules/juce_gui_basics/native/juce_linux_Clipboard.cpp | 846ef0a69f642457d58ca0ecd959124d0c9a9abc | [] | no_license | teragonaudio/Convolver | 698a818a348a996e7527947abfe57e790030817d | 4d91e2383e3b7b17e5c4ce0c5aaf226d05ca64d1 | refs/heads/master | 2016-09-15T21:47:43.305102 | 2013-03-24T13:19:45 | 2013-03-24T13:19:45 | 8,984,945 | 8 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 10,205 | cpp | /*
==============================================================================
This file is part of the JUCE library - "Jules' Utility Class Extensions"
Copyright 2004-11 by Raw Material Software Ltd.
------------------------------------------------------------------------------
JUCE can be redistributed and/or modified under the terms of the GNU General
Public License (Version 2), as published by the Free Software Foundation.
A copy of the license is included in the JUCE distribution, or can be found
online at www.gnu.org/licenses.
JUCE 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 General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.rawmaterialsoftware.com/juce for more information.
==============================================================================
*/
extern Display* display;
extern Window juce_messageWindowHandle;
namespace ClipboardHelpers
{
static String localClipboardContent;
static Atom atom_UTF8_STRING;
static Atom atom_CLIPBOARD;
static Atom atom_TARGETS;
//==============================================================================
static void initSelectionAtoms()
{
static bool isInitialised = false;
if (! isInitialised)
{
atom_UTF8_STRING = XInternAtom (display, "UTF8_STRING", False);
atom_CLIPBOARD = XInternAtom (display, "CLIPBOARD", False);
atom_TARGETS = XInternAtom (display, "TARGETS", False);
}
}
//==============================================================================
// Read the content of a window property as either a locale-dependent string or an utf8 string
// works only for strings shorter than 1000000 bytes
static String readWindowProperty (Window window, Atom prop)
{
String returnData;
char* clipData;
Atom actualType;
int actualFormat;
unsigned long numItems, bytesLeft;
if (XGetWindowProperty (display, window, prop,
0L /* offset */, 1000000 /* length (max) */, False,
AnyPropertyType /* format */,
&actualType, &actualFormat, &numItems, &bytesLeft,
(unsigned char**) &clipData) == Success)
{
if (actualType == atom_UTF8_STRING && actualFormat == 8)
returnData = String::fromUTF8 (clipData, numItems);
else if (actualType == XA_STRING && actualFormat == 8)
returnData = String (clipData, numItems);
if (clipData != nullptr)
XFree (clipData);
jassert (bytesLeft == 0 || numItems == 1000000);
}
XDeleteProperty (display, window, prop);
return returnData;
}
//==============================================================================
// Send a SelectionRequest to the window owning the selection and waits for its answer (with a timeout) */
static bool requestSelectionContent (String& selectionContent, Atom selection, Atom requestedFormat)
{
Atom property_name = XInternAtom (display, "JUCE_SEL", false);
// The selection owner will be asked to set the JUCE_SEL property on the
// juce_messageWindowHandle with the selection content
XConvertSelection (display, selection, requestedFormat, property_name,
juce_messageWindowHandle, CurrentTime);
int count = 50; // will wait at most for 200 ms
while (--count >= 0)
{
XEvent event;
if (XCheckTypedWindowEvent (display, juce_messageWindowHandle, SelectionNotify, &event))
{
if (event.xselection.property == property_name)
{
jassert (event.xselection.requestor == juce_messageWindowHandle);
selectionContent = readWindowProperty (event.xselection.requestor,
event.xselection.property);
return true;
}
else
{
return false; // the format we asked for was denied.. (event.xselection.property == None)
}
}
// not very elegant.. we could do a select() or something like that...
// however clipboard content requesting is inherently slow on x11, it
// often takes 50ms or more so...
Thread::sleep (4);
}
return false;
}
//==============================================================================
// Called from the event loop in juce_linux_Messaging in response to SelectionRequest events
static void handleSelection (XSelectionRequestEvent& evt)
{
ClipboardHelpers::initSelectionAtoms();
// the selection content is sent to the target window as a window property
XSelectionEvent reply;
reply.type = SelectionNotify;
reply.display = evt.display;
reply.requestor = evt.requestor;
reply.selection = evt.selection;
reply.target = evt.target;
reply.property = None; // == "fail"
reply.time = evt.time;
HeapBlock <char> data;
int propertyFormat = 0;
size_t numDataItems = 0;
if (evt.selection == XA_PRIMARY || evt.selection == ClipboardHelpers::atom_CLIPBOARD)
{
if (evt.target == XA_STRING || evt.target == ClipboardHelpers::atom_UTF8_STRING)
{
// translate to utf8
numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsUTF8() + 1;
data.calloc (numDataItems + 1);
ClipboardHelpers::localClipboardContent.copyToUTF8 (data, numDataItems);
propertyFormat = 8; // bits/item
}
else if (evt.target == ClipboardHelpers::atom_TARGETS)
{
// another application wants to know what we are able to send
numDataItems = 2;
propertyFormat = 32; // atoms are 32-bit
data.calloc (numDataItems * 4);
Atom* atoms = reinterpret_cast<Atom*> (data.getData());
atoms[0] = ClipboardHelpers::atom_UTF8_STRING;
atoms[1] = XA_STRING;
evt.target = XA_ATOM;
}
}
else
{
DBG ("requested unsupported clipboard");
}
if (data != nullptr)
{
const size_t maxReasonableSelectionSize = 1000000;
// for very big chunks of data, we should use the "INCR" protocol , which is a pain in the *ss
if (evt.property != None && numDataItems < maxReasonableSelectionSize)
{
XChangeProperty (evt.display, evt.requestor,
evt.property, evt.target,
propertyFormat /* 8 or 32 */, PropModeReplace,
reinterpret_cast<const unsigned char*> (data.getData()), numDataItems);
reply.property = evt.property; // " == success"
}
}
XSendEvent (evt.display, evt.requestor, 0, NoEventMask, (XEvent*) &reply);
}
}
//==============================================================================
typedef void (*SelectionRequestCallback) (XSelectionRequestEvent&);
extern SelectionRequestCallback handleSelectionRequest;
struct ClipboardCallbackInitialiser
{
ClipboardCallbackInitialiser()
{
handleSelectionRequest = ClipboardHelpers::handleSelection;
}
};
static ClipboardCallbackInitialiser clipboardInitialiser;
//==============================================================================
void SystemClipboard::copyTextToClipboard (const String& clipText)
{
ClipboardHelpers::initSelectionAtoms();
ClipboardHelpers::localClipboardContent = clipText;
XSetSelectionOwner (display, XA_PRIMARY, juce_messageWindowHandle, CurrentTime);
XSetSelectionOwner (display, ClipboardHelpers::atom_CLIPBOARD, juce_messageWindowHandle, CurrentTime);
}
String SystemClipboard::getTextFromClipboard()
{
ClipboardHelpers::initSelectionAtoms();
/* 1) try to read from the "CLIPBOARD" selection first (the "high
level" clipboard that is supposed to be filled by ctrl-C
etc). When a clipboard manager is running, the content of this
selection is preserved even when the original selection owner
exits.
2) and then try to read from "PRIMARY" selection (the "legacy" selection
filled by good old x11 apps such as xterm)
*/
String content;
Atom selection = XA_PRIMARY;
Window selectionOwner = None;
if ((selectionOwner = XGetSelectionOwner (display, selection)) == None)
{
selection = ClipboardHelpers::atom_CLIPBOARD;
selectionOwner = XGetSelectionOwner (display, selection);
}
if (selectionOwner != None)
{
if (selectionOwner == juce_messageWindowHandle)
{
content = ClipboardHelpers::localClipboardContent;
}
else
{
// first try: we want an utf8 string
bool ok = ClipboardHelpers::requestSelectionContent (content, selection, ClipboardHelpers::atom_UTF8_STRING);
if (! ok)
{
// second chance, ask for a good old locale-dependent string ..
ok = ClipboardHelpers::requestSelectionContent (content, selection, XA_STRING);
}
}
}
return content;
}
| [
"[email protected]"
] | |
5816826b5d662789c4e3757f9f6f7e569f4facba | 67a9864d08bc737114fd797ec29afd9c4bea099b | /test01/recv.cpp | cd72fc71a55595bc9a1271b9a8ff7daa25881e50 | [] | no_license | TwTravel/SysCommuExp | 4106ce174ad6aa2b73501131a6201714c742e152 | cfb29a585e69ca5cbd0a6b7abf5712978bd2ea6d | refs/heads/master | 2020-03-28T01:10:11.412931 | 2018-09-05T20:13:41 | 2018-09-05T20:13:41 | 147,482,988 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 676 | cpp | #include <fcntl.h>
#include <sys/stat.h> /* For mode constants */
#include <mqueue.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#define MQNAME "/mqtest"
int main()
{
mqd_t mqd;
int ret;
unsigned int val;
char buf[BUFSIZ];
mqd = mq_open(MQNAME, O_RDWR);
if (mqd == -1) {
perror("mq_open()");
exit(1);
}
ret = mq_receive(mqd, buf, BUFSIZ, &val);
if (ret == -1) {
perror("mq_send()");
exit(1);
}
ret = mq_close(mqd);
if (ret == -1) {
perror("mp_close()");
exit(1);
}
printf("msq: %s, prio: %d\n", buf, val);
exit(0);
}
| [
"[email protected]"
] | |
1be133aa9f2c62fd916204333195302632691b89 | 9175e2be877446df8a11885dd8505c99fab76474 | /daq_device_filenumbers.h | 89e306ef369f8240250382b52f5832b32c771270 | [] | no_license | sPHENIX-Collaboration/rcdaq | 3f61bc32ff8451fc3bf478bf1089fb2c66563660 | 402b53bf7761b203808af13e04f22836711355e4 | refs/heads/master | 2023-08-02T13:31:59.139272 | 2023-07-25T12:51:57 | 2023-07-25T12:51:57 | 54,594,801 | 6 | 15 | null | 2023-07-25T12:51:58 | 2016-03-23T21:37:47 | C++ | UTF-8 | C++ | false | false | 753 | h | #ifndef __DAQ_DEVICE_FILENUMBERS__
#define __DAQ_DEVICE_FILENUMBERS__
#include <daq_device.h>
#include <stdio.h>
#include <string>
class daq_device_filenumbers: public daq_device {
public:
daq_device_filenumbers (const int eventtype,
const int subeventid, const char * fn,
const int delete_flag = 0,
const int maxlength = 256);
~daq_device_filenumbers();
void identify(std::ostream& os = std::cout) const;
int max_length(const int etype) const;
// functions to do the work
int put_data(const int etype, int * adr, const int length);
private:
subevtdata_ptr sevt;
unsigned int number_of_words;
int m_eventType;
int m_subeventid;
std::string filename;
int _maxlength;
int _delete_flag;
};
#endif
| [
"[email protected]"
] | |
6c5fdb1365092909a33d5c96e156a982b472f30a | b0825e22b4cc4a25b42248f88fbc826e5d799201 | /formulaparser.cpp | ff912440f18f74ff50c4fe17eacadb3934121bce | [
"MIT"
] | permissive | ekuester/GTK-Molecular-Formula-for-Chemists | ec539d583415ff6366211594651b2e430b952083 | 17eeda00ae70ce29afb2d01f69770b3b84b685c3 | refs/heads/master | 2020-03-31T03:56:41.649821 | 2018-11-01T11:07:19 | 2018-11-01T11:07:19 | 151,884,594 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,022 | cpp | /*
* File: formulaparser.cpp
* Author: kuestere
*
* Created on 29. September 2018, 16:04
*/
#include "formulaparser.h"
FormulaParser::FormulaParser(Glib::ustring input) {
formulaString = input; //std::vector<gunichar>(input.begin(), input.end());
// number of input characters
length = formulaString.size();
// iterator into the string
pointer = formulaString.begin();
endOfString = (pointer == formulaString.end());
}
FormulaParser::FormulaParser(const FormulaParser& orig) {
}
FormulaParser::~FormulaParser() {
}
void FormulaParser::advance() {
pointer++;
endOfString = (pointer == formulaString.end());
}
gunichar FormulaParser::fetch() {
return *pointer;
}
Glib::ustring FormulaParser::scanForBond() {
// scan for bond sign
if (!endOfString) {
gunichar bondChar = fetch();
switch (bondChar) {
case '-':
case '.':
case ':':
case '=':
case u'·':
// found bond sign
advance();
return Glib::ustring(1, bondChar);
default:
break;
}
}
return Glib::ustring();
}
bool FormulaParser::isDigit(gunichar c) {
switch (c) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return true;
default:
break;
}
return false;
}
int FormulaParser::scanForIndex() {
// scan for integer index, if no integer found, index is one
Glib::ustring indexString = Glib::ustring();
while (!endOfString) {
gunichar formulaChar = fetch();
if (isDigit(formulaChar)) {
indexString.append(1, formulaChar);
advance();
} else {
break;
}
}
if (!indexString.empty()) {
int index = stoi(indexString);
if (index > 0) {
return index;
}
// index 0 not allowed
return -1;
}
// no index means 1
return 1;
}
gunichar FormulaParser::scanForOpeningBracket() {
gunichar bracketChar = fetch();
switch (bracketChar) {
case '[':
case '(':
advance();
if (endOfString) {
//ErrorAlert(message: 2).show()
return 'q';
}
if (bracketChar == '[') {
return ']';
} else {
return ')';
}
default:
break;
}
return u'?';
}
bool FormulaParser::isCharClosingBracket(gunichar closing) {
if (!endOfString) {
gunichar bracketChar = fetch();
if (bracketChar == closing) {
advance();
return true;
}
}
return false;
}
bool FormulaParser::followsClosingBracket() {
gunichar bracketChar = fetch();
if ((bracketChar == u')') || (bracketChar == u']')) {
return true;
}
return false;
}
string FormulaParser::scanForElement() {
if (!endOfString) {
// parse one formula element containing an atomic symbol, index is set to one
string symbol = string();
gunichar upperChar = fetch();
switch (upperChar) {
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
advance();
symbol.append(1, upperChar);
break;
default:
return string();
}
// advance pointer but only if characters left
if (!endOfString) {
// now scan for one lowercase letter
gunichar lowerChar = fetch();
switch (lowerChar) {
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'r':
case 's':
case 't':
case 'u':
case 'w':
case 'y':
// found element symbol with upper and lower case letter
advance();
symbol.append(1, lowerChar);
break;
default:
break;
}
}
return {symbol};
}
return string();
}
| [
"[email protected]"
] | |
9e5a9af43a775e854d881b5665f259fd9f234248 | 0e986df223a073666515642a57c36a8fc426c535 | /pizjuce/midiChords/JuceLibraryCode/modules/juce_graphics/fonts/juce_TextLayout.cpp | 6fe8382b917d7410c342d3226652ceccd9a4257d | [] | no_license | CptanPanic/pizmidi | 49878f9312bce3f64cc51ee55092103db57acde7 | 9daf55ceff5d146dbbcc44ae6e78aea137598ebe | refs/heads/master | 2021-01-19T15:38:55.441104 | 2015-03-24T15:36:58 | 2015-03-24T15:36:58 | 32,807,602 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,293 | cpp | /*
==============================================================================
This file is part of the JUCE library - "Jules' Utility Class Extensions"
Copyright 2004-11 by Raw Material Software Ltd.
------------------------------------------------------------------------------
JUCE can be redistributed and/or modified under the terms of the GNU General
Public License (Version 2), as published by the Free Software Foundation.
A copy of the license is included in the JUCE distribution, or can be found
online at www.gnu.org/licenses.
JUCE 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 General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.rawmaterialsoftware.com/juce for more information.
==============================================================================
*/
TextLayout::Glyph::Glyph (const int glyphCode_, const Point<float>& anchor_, float width_) noexcept
: glyphCode (glyphCode_), anchor (anchor_), width (width_)
{
}
TextLayout::Glyph::Glyph (const Glyph& other) noexcept
: glyphCode (other.glyphCode), anchor (other.anchor), width (other.width)
{
}
TextLayout::Glyph& TextLayout::Glyph::operator= (const Glyph& other) noexcept
{
glyphCode = other.glyphCode;
anchor = other.anchor;
width = other.width;
return *this;
}
TextLayout::Glyph::~Glyph() noexcept {}
//==============================================================================
TextLayout::Run::Run() noexcept
: colour (0xff000000)
{
}
TextLayout::Run::Run (const Range<int>& range, const int numGlyphsToPreallocate)
: colour (0xff000000), stringRange (range)
{
glyphs.ensureStorageAllocated (numGlyphsToPreallocate);
}
TextLayout::Run::Run (const Run& other)
: font (other.font),
colour (other.colour),
glyphs (other.glyphs),
stringRange (other.stringRange)
{
}
TextLayout::Run::~Run() noexcept {}
//==============================================================================
TextLayout::Line::Line() noexcept
: ascent (0.0f), descent (0.0f), leading (0.0f)
{
}
TextLayout::Line::Line (const Range<int>& stringRange_, const Point<float>& lineOrigin_,
const float ascent_, const float descent_, const float leading_,
const int numRunsToPreallocate)
: stringRange (stringRange_), lineOrigin (lineOrigin_),
ascent (ascent_), descent (descent_), leading (leading_)
{
runs.ensureStorageAllocated (numRunsToPreallocate);
}
TextLayout::Line::Line (const Line& other)
: stringRange (other.stringRange), lineOrigin (other.lineOrigin),
ascent (other.ascent), descent (other.descent), leading (other.leading)
{
runs.addCopiesOf (other.runs);
}
TextLayout::Line::~Line() noexcept
{
}
Range<float> TextLayout::Line::getLineBoundsX() const noexcept
{
Range<float> range;
bool isFirst = true;
for (int i = runs.size(); --i >= 0;)
{
const Run& run = *runs.getUnchecked(i);
if (run.glyphs.size() > 0)
{
float minX = run.glyphs.getReference(0).anchor.x;
float maxX = minX;
for (int j = run.glyphs.size(); --j > 0;)
{
const Glyph& glyph = run.glyphs.getReference (j);
const float x = glyph.anchor.x;
minX = jmin (minX, x);
maxX = jmax (maxX, x + glyph.width);
}
if (isFirst)
{
isFirst = false;
range = Range<float> (minX, maxX);
}
else
{
range = range.getUnionWith (Range<float> (minX, maxX));
}
}
}
return range + lineOrigin.x;
}
//==============================================================================
TextLayout::TextLayout()
: width (0), justification (Justification::topLeft)
{
}
TextLayout::TextLayout (const TextLayout& other)
: width (other.width),
justification (other.justification)
{
lines.addCopiesOf (other.lines);
}
#if JUCE_COMPILER_SUPPORTS_MOVE_SEMANTICS
TextLayout::TextLayout (TextLayout&& other) noexcept
: lines (static_cast <OwnedArray<Line>&&> (other.lines)),
width (other.width),
justification (other.justification)
{
}
TextLayout& TextLayout::operator= (TextLayout&& other) noexcept
{
lines = static_cast <OwnedArray<Line>&&> (other.lines);
width = other.width;
justification = other.justification;
return *this;
}
#endif
TextLayout& TextLayout::operator= (const TextLayout& other)
{
width = other.width;
justification = other.justification;
lines.clear();
lines.addCopiesOf (other.lines);
return *this;
}
TextLayout::~TextLayout()
{
}
float TextLayout::getHeight() const noexcept
{
const Line* const lastLine = lines.getLast();
return lastLine != nullptr ? lastLine->lineOrigin.y + lastLine->descent
: 0;
}
TextLayout::Line& TextLayout::getLine (const int index) const
{
return *lines[index];
}
void TextLayout::ensureStorageAllocated (int numLinesNeeded)
{
lines.ensureStorageAllocated (numLinesNeeded);
}
void TextLayout::addLine (Line* line)
{
lines.add (line);
}
void TextLayout::draw (Graphics& g, const Rectangle<float>& area) const
{
const Point<float> origin (justification.appliedToRectangle (Rectangle<float> (width, getHeight()), area).getPosition());
LowLevelGraphicsContext& context = g.getInternalContext();
for (int i = 0; i < getNumLines(); ++i)
{
const Line& line = getLine (i);
const Point<float> lineOrigin (origin + line.lineOrigin);
for (int j = 0; j < line.runs.size(); ++j)
{
const Run& run = *line.runs.getUnchecked (j);
context.setFont (run.font);
context.setFill (run.colour);
for (int k = 0; k < run.glyphs.size(); ++k)
{
const Glyph& glyph = run.glyphs.getReference (k);
context.drawGlyph (glyph.glyphCode, AffineTransform::translation (lineOrigin.x + glyph.anchor.x,
lineOrigin.y + glyph.anchor.y));
}
}
}
}
void TextLayout::createLayout (const AttributedString& text, float maxWidth)
{
lines.clear();
width = maxWidth;
justification = text.getJustification();
if (! createNativeLayout (text))
createStandardLayout (text);
recalculateWidth (text);
}
//==============================================================================
namespace TextLayoutHelpers
{
struct FontAndColour
{
FontAndColour (const Font* font_) noexcept : font (font_), colour (0xff000000) {}
const Font* font;
Colour colour;
bool operator!= (const FontAndColour& other) const noexcept
{
return (font != other.font && *font != *other.font) || colour != other.colour;
}
};
struct RunAttribute
{
RunAttribute (const FontAndColour& fontAndColour_, const Range<int>& range_) noexcept
: fontAndColour (fontAndColour_), range (range_)
{}
FontAndColour fontAndColour;
Range<int> range;
};
struct Token
{
Token (const String& t, const Font& f, const Colour& c, const bool isWhitespace_)
: text (t), font (f), colour (c),
area (font.getStringWidthFloat (t), f.getHeight()),
isWhitespace (isWhitespace_),
isNewLine (t.containsChar ('\n') || t.containsChar ('\r'))
{}
const String text;
const Font font;
const Colour colour;
Rectangle<float> area;
int line;
float lineHeight;
const bool isWhitespace, isNewLine;
private:
Token& operator= (const Token&);
};
class TokenList
{
public:
TokenList() noexcept : totalLines (0) {}
void createLayout (const AttributedString& text, TextLayout& layout)
{
tokens.ensureStorageAllocated (64);
layout.ensureStorageAllocated (totalLines);
addTextRuns (text);
layoutRuns (layout.getWidth());
int charPosition = 0;
int lineStartPosition = 0;
int runStartPosition = 0;
ScopedPointer<TextLayout::Line> currentLine;
ScopedPointer<TextLayout::Run> currentRun;
bool needToSetLineOrigin = true;
for (int i = 0; i < tokens.size(); ++i)
{
const Token& t = *tokens.getUnchecked (i);
Array <int> newGlyphs;
Array <float> xOffsets;
t.font.getGlyphPositions (t.text.trimEnd(), newGlyphs, xOffsets);
if (currentRun == nullptr) currentRun = new TextLayout::Run();
if (currentLine == nullptr) currentLine = new TextLayout::Line();
if (newGlyphs.size() > 0)
{
currentRun->glyphs.ensureStorageAllocated (currentRun->glyphs.size() + newGlyphs.size());
const Point<float> tokenOrigin (t.area.getPosition().translated (0, t.font.getAscent()));
if (needToSetLineOrigin)
{
needToSetLineOrigin = false;
currentLine->lineOrigin = tokenOrigin;
}
const Point<float> glyphOffset (tokenOrigin - currentLine->lineOrigin);
for (int j = 0; j < newGlyphs.size(); ++j)
{
const float x = xOffsets.getUnchecked (j);
currentRun->glyphs.add (TextLayout::Glyph (newGlyphs.getUnchecked(j),
glyphOffset.translated (x, 0),
xOffsets.getUnchecked (j + 1) - x));
}
charPosition += newGlyphs.size();
}
if (t.isWhitespace || t.isNewLine)
++charPosition;
const Token* const nextToken = tokens [i + 1];
if (nextToken == nullptr) // this is the last token
{
addRun (*currentLine, currentRun.release(), t, runStartPosition, charPosition);
currentLine->stringRange = Range<int> (lineStartPosition, charPosition);
if (! needToSetLineOrigin)
layout.addLine (currentLine.release());
needToSetLineOrigin = true;
}
else
{
if (t.font != nextToken->font || t.colour != nextToken->colour)
{
addRun (*currentLine, currentRun.release(), t, runStartPosition, charPosition);
runStartPosition = charPosition;
}
if (t.line != nextToken->line)
{
if (currentRun == nullptr)
currentRun = new TextLayout::Run();
addRun (*currentLine, currentRun.release(), t, runStartPosition, charPosition);
currentLine->stringRange = Range<int> (lineStartPosition, charPosition);
if (! needToSetLineOrigin)
layout.addLine (currentLine.release());
runStartPosition = charPosition;
lineStartPosition = charPosition;
needToSetLineOrigin = true;
}
}
}
if ((text.getJustification().getFlags() & (Justification::right | Justification::horizontallyCentred)) != 0)
{
const float totalW = layout.getWidth();
const bool isCentred = (text.getJustification().getFlags() & Justification::horizontallyCentred) != 0;
for (int i = 0; i < layout.getNumLines(); ++i)
{
float dx = totalW - getLineWidth (i);
if (isCentred)
dx /= 2.0f;
layout.getLine(i).lineOrigin.x += dx;
}
}
}
private:
static void addRun (TextLayout::Line& glyphLine, TextLayout::Run* glyphRun,
const Token& t, const int start, const int end)
{
glyphRun->stringRange = Range<int> (start, end);
glyphRun->font = t.font;
glyphRun->colour = t.colour;
glyphLine.ascent = jmax (glyphLine.ascent, t.font.getAscent());
glyphLine.descent = jmax (glyphLine.descent, t.font.getDescent());
glyphLine.runs.add (glyphRun);
}
static int getCharacterType (const juce_wchar c) noexcept
{
if (c == '\r' || c == '\n')
return 0;
return CharacterFunctions::isWhitespace (c) ? 2 : 1;
}
void appendText (const AttributedString& text, const Range<int>& stringRange,
const Font& font, const Colour& colour)
{
const String stringText (text.getText().substring (stringRange.getStart(), stringRange.getEnd()));
String::CharPointerType t (stringText.getCharPointer());
String currentString;
int lastCharType = 0;
for (;;)
{
const juce_wchar c = t.getAndAdvance();
if (c == 0)
break;
const int charType = getCharacterType (c);
if (charType == 0 || charType != lastCharType)
{
if (currentString.isNotEmpty())
tokens.add (new Token (currentString, font, colour,
lastCharType == 2 || lastCharType == 0));
currentString = String::charToString (c);
if (c == '\r' && *t == '\n')
currentString += t.getAndAdvance();
}
else
{
currentString += c;
}
lastCharType = charType;
}
if (currentString.isNotEmpty())
tokens.add (new Token (currentString, font, colour, lastCharType == 2));
}
void layoutRuns (const float maxWidth)
{
float x = 0, y = 0, h = 0;
int i;
for (i = 0; i < tokens.size(); ++i)
{
Token& t = *tokens.getUnchecked(i);
t.area.setPosition (x, y);
t.line = totalLines;
x += t.area.getWidth();
h = jmax (h, t.area.getHeight());
const Token* const nextTok = tokens[i + 1];
if (nextTok == nullptr)
break;
if (t.isNewLine || ((! nextTok->isWhitespace) && x + nextTok->area.getWidth() > maxWidth))
{
setLastLineHeight (i + 1, h);
x = 0;
y += h;
h = 0;
++totalLines;
}
}
setLastLineHeight (jmin (i + 1, tokens.size()), h);
++totalLines;
}
void setLastLineHeight (int i, const float height) noexcept
{
while (--i >= 0)
{
Token& tok = *tokens.getUnchecked (i);
if (tok.line == totalLines)
tok.lineHeight = height;
else
break;
}
}
float getLineWidth (const int lineNumber) const noexcept
{
float maxW = 0;
for (int i = tokens.size(); --i >= 0;)
{
const Token& t = *tokens.getUnchecked (i);
if (t.line == lineNumber && ! t.isWhitespace)
maxW = jmax (maxW, t.area.getRight());
}
return maxW;
}
void addTextRuns (const AttributedString& text)
{
Font defaultFont;
Array<RunAttribute> runAttributes;
{
const int stringLength = text.getText().length();
int rangeStart = 0;
FontAndColour lastFontAndColour (nullptr);
// Iterate through every character in the string
for (int i = 0; i < stringLength; ++i)
{
FontAndColour newFontAndColour (&defaultFont);
const int numCharacterAttributes = text.getNumAttributes();
for (int j = 0; j < numCharacterAttributes; ++j)
{
const AttributedString::Attribute& attr = *text.getAttribute (j);
if (attr.range.contains (i))
{
if (attr.getFont() != nullptr) newFontAndColour.font = attr.getFont();
if (attr.getColour() != nullptr) newFontAndColour.colour = *attr.getColour();
}
}
if (i > 0 && (newFontAndColour != lastFontAndColour || i == stringLength - 1))
{
runAttributes.add (RunAttribute (lastFontAndColour,
Range<int> (rangeStart, (i < stringLength - 1) ? i : (i + 1))));
rangeStart = i;
}
lastFontAndColour = newFontAndColour;
}
}
for (int i = 0; i < runAttributes.size(); ++i)
{
const RunAttribute& r = runAttributes.getReference(i);
appendText (text, r.range, *(r.fontAndColour.font), r.fontAndColour.colour);
}
}
OwnedArray<Token> tokens;
int totalLines;
JUCE_DECLARE_NON_COPYABLE (TokenList);
};
}
//==============================================================================
void TextLayout::createLayoutWithBalancedLineLengths (const AttributedString& text, float maxWidth)
{
const float minimumWidth = maxWidth / 2.0f;
float bestWidth = maxWidth;
float bestLineProportion = 0.0f;
while (maxWidth > minimumWidth)
{
createLayout (text, maxWidth);
if (getNumLines() < 2)
return;
const float line1 = lines.getUnchecked (lines.size() - 1)->getLineBoundsX().getLength();
const float line2 = lines.getUnchecked (lines.size() - 2)->getLineBoundsX().getLength();
const float shortestLine = jmin (line1, line2);
const float prop = (shortestLine > 0) ? jmax (line1, line2) / shortestLine : 1.0f;
if (prop > 0.9f)
return;
if (prop > bestLineProportion)
{
bestLineProportion = prop;
bestWidth = maxWidth;
}
maxWidth -= 10.0f;
}
if (bestWidth != maxWidth)
createLayout (text, bestWidth);
}
//==============================================================================
void TextLayout::createStandardLayout (const AttributedString& text)
{
TextLayoutHelpers::TokenList l;
l.createLayout (text, *this);
}
void TextLayout::recalculateWidth (const AttributedString& text)
{
if (lines.size() > 0 && text.getReadingDirection() != AttributedString::rightToLeft)
{
Range<float> range (lines.getFirst()->getLineBoundsX());
for (int i = lines.size(); --i > 0;)
range = range.getUnionWith (lines.getUnchecked(i)->getLineBoundsX());
for (int i = lines.size(); --i >= 0;)
lines.getUnchecked(i)->lineOrigin.x -= range.getStart();
width = range.getLength();
}
}
| [
"[email protected]"
] | |
d16bf5daea616b5ea7c53dfccdf7e287090277fa | 0b3a494de55f0cb395266410bd243950df8868aa | /PA/PA5/WordCounts.h | fe247b6e36bc5c98e4a0230393c5696d1158c33e | [] | no_license | sgthun/253-PA | 846342ea5284113754d489090194cea4c40e6fe7 | 106e7464f58b744670a09a61f1dfa921ab7d4614 | refs/heads/master | 2021-01-23T14:30:33.142683 | 2018-02-09T05:09:22 | 2018-02-09T05:09:22 | 102,686,715 | 1 | 0 | null | 2018-02-09T05:06:51 | 2017-09-07T03:26:40 | C++ | UTF-8 | C++ | false | false | 1,210 | h | #ifndef WORD_COUNT_INCLUDE
#define WORD_COUNT_INCLUDE
#include<iostream>
#include<fstream>
#include<vector>
#include<algorithm>
#include<string>
#include<Word.h>
#include<regex>
#include<ParseBox.h>
#include<Stemmer.h>
#include<Replace.h>
using std::regex;
using std::istream;
using std::ostream;
using std::cout;
using std::cin;
using std::endl;
using std::cerr;
using std::vector;
using std::string;
class WordCounts {
public:
WordCounts(const Replace& exec):exceptionTable(exec){}
int scanFileIn(istream& inFile);
void sortList();
void printList();
void countWords();
int stringLength();
void splitAdd(string& word);
void add(string word);
void split(string word);
bool isAlphanum(string word);
int getFirstLegalPuncIndex(string word);
int getFirstLegalAlphIndex(string word);
bool isAlphaChar(char c);
bool propCap(string word);
bool puncOnlyEOS(string word);
void capitalFix();
void removeCapAmb();
void checkCaps();
private:
//regex alphaNumeric ("[a-zA-Z0-9']+");
vector<Word> wordList;
vector<string> stringList;
vector<int> capChecks;
int wordCount;
ParseBox regBox;
Stemmer stemBox;
Replace exceptionTable;
string tmp;
string addTmp;
string capTmp;
};
#endif
| [
"[email protected]"
] | |
c28b8d0ed5e47abf44d6c6c667ec6d8b680df672 | c342cde945ca48942743791ba9480a6231ddb9ee | /Extra/Modules/Example/script_Component.hpp | 6f652244bf525c8546fcc57d1dc767c3615661a7 | [] | no_license | GuzzenVonLidl/GW-Framework | 6ecf7bfcd64ea6a9d2358481e44f8ee4cbe10e6c | 737a88a3dfabd4805c7c5db63d386f9a52a6b8f4 | refs/heads/master | 2021-01-17T18:35:09.099253 | 2019-09-09T14:56:28 | 2019-09-09T14:56:28 | 61,488,807 | 1 | 8 | null | 2019-09-09T14:56:30 | 2016-06-19T16:16:12 | SQF | UTF-8 | C++ | false | false | 125 | hpp | #define DEBUG_MODE_FULL // Enables debug mode for the component
#define COMPONENT Example
#include "..\script_Component.hpp"
| [
"[email protected]"
] | |
386d7491667249c0429e7c83ce6b12a303225498 | fdcbe6a60d5bc5fc2c87f28d07f571be000f93db | /src/masternode.h | 98b6901a34cc5914293464b5047f6164e7dfbe83 | [
"MIT"
] | permissive | onlinesolutions/pura | 9ab4a62106765c5c7ca5d91adaee1e9ff27a404d | 845c6f1aec4b72c1394fb1ff8f87d1b85245b1e1 | refs/heads/master | 2022-01-05T01:09:10.096574 | 2019-06-28T15:59:18 | 2019-06-28T15:59:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,809 | h | // Copyright (c) 2014-2017 The Dash Core developers
// Copyright (c) 2017-2017 The Pura Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef MASTERNODE_H
#define MASTERNODE_H
#include "key.h"
#include "validation.h"
#include "spork.h"
class CMasternode;
class CMasternodeBroadcast;
static const int MASTERNODE_CHECK_SECONDS = 5;
static const int MASTERNODE_MIN_MNB_SECONDS = 5 * 60;
static const int MASTERNODE_MIN_MNP_SECONDS = 10 * 60;
static const int MASTERNODE_EXPIRATION_SECONDS = 65 * 60;
static const int MASTERNODE_WATCHDOG_MAX_SECONDS = 120 * 60;
static const int MASTERNODE_NEW_START_REQUIRED_SECONDS = 180 * 60;
static const int MASTERNODE_POSE_BAN_MAX_SCORE = 5;
//
// The Masternode Ping Class : Contains a different serialize method for sending pings from masternodes throughout the network
//
// sentinel version before sentinel ping implementation
#define DEFAULT_SENTINEL_VERSION 0x010001
class CMasternodePing
{
public:
CTxIn vin{};
uint256 blockHash{};
int64_t sigTime{}; //mnb message times
std::vector<unsigned char> vchSig{};
bool fSentinelIsCurrent = false; // true if last sentinel ping was actual
// MSB is always 0, other 3 bits corresponds to x.x.x version scheme
uint32_t nSentinelVersion{DEFAULT_SENTINEL_VERSION};
CMasternodePing() = default;
CMasternodePing(CTxIn& vinNew);
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
READWRITE(vin);
READWRITE(blockHash);
READWRITE(sigTime);
READWRITE(vchSig);
if(ser_action.ForRead() && (s.size() == 0))
{
fSentinelIsCurrent = false;
nSentinelVersion = DEFAULT_SENTINEL_VERSION;
return;
}
READWRITE(fSentinelIsCurrent);
READWRITE(nSentinelVersion);
}
uint256 GetHash() const
{
CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
ss << vin;
ss << sigTime;
return ss.GetHash();
}
bool IsExpired() const { return GetTime() - sigTime > MASTERNODE_NEW_START_REQUIRED_SECONDS; }
bool Sign(CKey& keyMasternode, CPubKey& pubKeyMasternode);
bool CheckSignature(CPubKey& pubKeyMasternode, int &nDos);
bool SimpleCheck(int& nDos);
bool CheckAndUpdate(CMasternode* pmn, bool fFromNewBroadcast, int& nDos);
void Relay();
};
inline bool operator==(const CMasternodePing& a, const CMasternodePing& b)
{
return a.vin == b.vin && a.blockHash == b.blockHash;
}
inline bool operator!=(const CMasternodePing& a, const CMasternodePing& b)
{
return !(a == b);
}
struct masternode_info_t
{
// Note: all these constructors can be removed once C++14 is enabled.
// (in C++11 the member initializers wrongly disqualify this as an aggregate)
masternode_info_t() = default;
masternode_info_t(masternode_info_t const&) = default;
masternode_info_t(int activeState, int protoVer, int64_t sTime) :
nActiveState{activeState}, nProtocolVersion{protoVer}, sigTime{sTime} {}
masternode_info_t(int activeState, int protoVer, int64_t sTime,
CTxIn const& vin, CService const& addr,
CPubKey const& pkCollAddr, CPubKey const& pkMN,
int64_t tWatchdogV = 0) :
nActiveState{activeState}, nProtocolVersion{protoVer}, sigTime{sTime},
vin{vin}, addr{addr},
pubKeyCollateralAddress{pkCollAddr}, pubKeyMasternode{pkMN},
nTimeLastWatchdogVote{tWatchdogV} {}
int nActiveState = 0;
int nProtocolVersion = 0;
int64_t sigTime = 0; //mnb message time
CTxIn vin{};
CService addr{};
CPubKey pubKeyCollateralAddress{};
CPubKey pubKeyMasternode{};
int64_t nTimeLastWatchdogVote = 0;
int64_t nLastDsq = 0; //the dsq count from the last dsq broadcast of this node
int64_t nTimeLastChecked = 0;
int64_t nTimeLastPaid = 0;
int64_t nTimeLastPing = 0; //* not in CMN
bool fInfoValid = false; //* not in CMN
};
//
// The Masternode Class. For managing the PrivatePay process. It contains the input of the 100000 PURA, signature to prove
// it's the one who own that ip address and code for calculating the payment election.
//
class CMasternode : public masternode_info_t
{
private:
// critical section to protect the inner data structures
mutable CCriticalSection cs;
public:
enum state {
MASTERNODE_PRE_ENABLED,
MASTERNODE_ENABLED,
MASTERNODE_EXPIRED,
MASTERNODE_OUTPOINT_SPENT,
MASTERNODE_UPDATE_REQUIRED,
MASTERNODE_WATCHDOG_EXPIRED,
MASTERNODE_NEW_START_REQUIRED,
MASTERNODE_POSE_BAN
};
enum CollateralStatus {
COLLATERAL_OK,
COLLATERAL_UTXO_NOT_FOUND,
COLLATERAL_INVALID_AMOUNT
};
CMasternodePing lastPing{};
std::vector<unsigned char> vchSig{};
int nCacheCollateralBlock{};
int nBlockLastPaid{};
int nPoSeBanScore{};
int nPoSeBanHeight{};
bool fAllowMixingTx{};
bool fUnitTest = false;
// KEEP TRACK OF GOVERNANCE ITEMS EACH MASTERNODE HAS VOTE UPON FOR RECALCULATION
std::map<uint256, int> mapGovernanceObjectsVotedOn;
CMasternode();
CMasternode(const CMasternode& other);
CMasternode(const CMasternodeBroadcast& mnb);
CMasternode(CService addrNew, CTxIn vinNew, CPubKey pubKeyCollateralAddressNew, CPubKey pubKeyMasternodeNew, int nProtocolVersionIn);
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
LOCK(cs);
READWRITE(vin);
READWRITE(addr);
READWRITE(pubKeyCollateralAddress);
READWRITE(pubKeyMasternode);
READWRITE(lastPing);
READWRITE(vchSig);
READWRITE(sigTime);
READWRITE(nLastDsq);
READWRITE(nTimeLastChecked);
READWRITE(nTimeLastPaid);
READWRITE(nTimeLastWatchdogVote);
READWRITE(nActiveState);
READWRITE(nCacheCollateralBlock);
READWRITE(nBlockLastPaid);
READWRITE(nProtocolVersion);
READWRITE(nPoSeBanScore);
READWRITE(nPoSeBanHeight);
READWRITE(fAllowMixingTx);
READWRITE(fUnitTest);
READWRITE(mapGovernanceObjectsVotedOn);
}
// CALCULATE A RANK AGAINST OF GIVEN BLOCK
arith_uint256 CalculateScore(const uint256& blockHash);
bool UpdateFromNewBroadcast(CMasternodeBroadcast& mnb);
static CollateralStatus CheckCollateral(CTxIn vin);
static CollateralStatus CheckCollateral(CTxIn vin, int& nHeight);
void Check(bool fForce = false);
bool IsBroadcastedWithin(int nSeconds) { return GetAdjustedTime() - sigTime < nSeconds; }
bool IsPingedWithin(int nSeconds, int64_t nTimeToCheckAt = -1)
{
if(lastPing == CMasternodePing()) return false;
if(nTimeToCheckAt == -1) {
nTimeToCheckAt = GetAdjustedTime();
}
return nTimeToCheckAt - lastPing.sigTime < nSeconds;
}
bool IsEnabled() { return nActiveState == MASTERNODE_ENABLED; }
bool IsPreEnabled() { return nActiveState == MASTERNODE_PRE_ENABLED; }
bool IsPoSeBanned() { return nActiveState == MASTERNODE_POSE_BAN; }
// NOTE: this one relies on nPoSeBanScore, not on nActiveState as everything else here
bool IsPoSeVerified() { return nPoSeBanScore <= -MASTERNODE_POSE_BAN_MAX_SCORE; }
bool IsExpired() { return nActiveState == MASTERNODE_EXPIRED; }
bool IsOutpointSpent() { return nActiveState == MASTERNODE_OUTPOINT_SPENT; }
bool IsUpdateRequired() { return nActiveState == MASTERNODE_UPDATE_REQUIRED; }
bool IsWatchdogExpired() { return nActiveState == MASTERNODE_WATCHDOG_EXPIRED; }
bool IsNewStartRequired() { return nActiveState == MASTERNODE_NEW_START_REQUIRED; }
static bool IsValidStateForAutoStart(int nActiveStateIn)
{
return nActiveStateIn == MASTERNODE_ENABLED ||
nActiveStateIn == MASTERNODE_PRE_ENABLED ||
nActiveStateIn == MASTERNODE_EXPIRED ||
nActiveStateIn == MASTERNODE_WATCHDOG_EXPIRED;
}
bool IsValidForPayment()
{
if(nActiveState == MASTERNODE_ENABLED) {
return true;
}
if(!sporkManager.IsSporkActive(SPORK_14_REQUIRE_SENTINEL_FLAG) &&
(nActiveState == MASTERNODE_WATCHDOG_EXPIRED)) {
return true;
}
return false;
}
/// Is the input associated with collateral public key? (and there is 100000 PURA - checking if valid masternode)
bool IsInputAssociatedWithPubkey();
bool IsValidNetAddr();
static bool IsValidNetAddr(CService addrIn);
void IncreasePoSeBanScore() { if(nPoSeBanScore < MASTERNODE_POSE_BAN_MAX_SCORE) nPoSeBanScore++; }
void DecreasePoSeBanScore() { if(nPoSeBanScore > -MASTERNODE_POSE_BAN_MAX_SCORE) nPoSeBanScore--; }
masternode_info_t GetInfo();
static std::string StateToString(int nStateIn);
std::string GetStateString() const;
std::string GetStatus() const;
int GetCollateralAge();
int GetLastPaidTime() { return nTimeLastPaid; }
int GetLastPaidBlock() { return nBlockLastPaid; }
void UpdateLastPaid(const CBlockIndex *pindex, int nMaxBlocksToScanBack);
// KEEP TRACK OF EACH GOVERNANCE ITEM INCASE THIS NODE GOES OFFLINE, SO WE CAN RECALC THEIR STATUS
void AddGovernanceVote(uint256 nGovernanceObjectHash);
// RECALCULATE CACHED STATUS FLAGS FOR ALL AFFECTED OBJECTS
void FlagGovernanceItemsAsDirty();
void RemoveGovernanceObject(uint256 nGovernanceObjectHash);
void UpdateWatchdogVoteTime(uint64_t nVoteTime = 0);
CMasternode& operator=(CMasternode const& from)
{
static_cast<masternode_info_t&>(*this)=from;
lastPing = from.lastPing;
vchSig = from.vchSig;
nCacheCollateralBlock = from.nCacheCollateralBlock;
nBlockLastPaid = from.nBlockLastPaid;
nPoSeBanScore = from.nPoSeBanScore;
nPoSeBanHeight = from.nPoSeBanHeight;
fAllowMixingTx = from.fAllowMixingTx;
fUnitTest = from.fUnitTest;
mapGovernanceObjectsVotedOn = from.mapGovernanceObjectsVotedOn;
return *this;
}
};
inline bool operator==(const CMasternode& a, const CMasternode& b)
{
return a.vin == b.vin;
}
inline bool operator!=(const CMasternode& a, const CMasternode& b)
{
return !(a.vin == b.vin);
}
//
// The Masternode Broadcast Class : Contains a different serialize method for sending masternodes through the network
//
class CMasternodeBroadcast : public CMasternode
{
public:
bool fRecovery;
CMasternodeBroadcast() : CMasternode(), fRecovery(false) {}
CMasternodeBroadcast(const CMasternode& mn) : CMasternode(mn), fRecovery(false) {}
CMasternodeBroadcast(CService addrNew, CTxIn vinNew, CPubKey pubKeyCollateralAddressNew, CPubKey pubKeyMasternodeNew, int nProtocolVersionIn) :
CMasternode(addrNew, vinNew, pubKeyCollateralAddressNew, pubKeyMasternodeNew, nProtocolVersionIn), fRecovery(false) {}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
READWRITE(vin);
READWRITE(addr);
READWRITE(pubKeyCollateralAddress);
READWRITE(pubKeyMasternode);
READWRITE(vchSig);
READWRITE(sigTime);
READWRITE(nProtocolVersion);
READWRITE(lastPing);
}
uint256 GetHash() const
{
CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
ss << vin;
ss << pubKeyCollateralAddress;
ss << sigTime;
return ss.GetHash();
}
/// Create Masternode broadcast, needs to be relayed manually after that
static bool Create(CTxIn vin, CService service, CKey keyCollateralAddressNew, CPubKey pubKeyCollateralAddressNew, CKey keyMasternodeNew, CPubKey pubKeyMasternodeNew, std::string &strErrorRet, CMasternodeBroadcast &mnbRet);
static bool Create(std::string strService, std::string strKey, std::string strTxHash, std::string strOutputIndex, std::string& strErrorRet, CMasternodeBroadcast &mnbRet, bool fOffline = false);
bool SimpleCheck(int& nDos);
bool Update(CMasternode* pmn, int& nDos);
bool CheckOutpoint(int& nDos);
bool Sign(CKey& keyCollateralAddress);
bool CheckSignature(int& nDos);
void Relay();
};
class CMasternodeVerification
{
public:
CTxIn vin1{};
CTxIn vin2{};
CService addr{};
int nonce{};
int nBlockHeight{};
std::vector<unsigned char> vchSig1{};
std::vector<unsigned char> vchSig2{};
CMasternodeVerification() = default;
CMasternodeVerification(CService addr, int nonce, int nBlockHeight) :
addr(addr),
nonce(nonce),
nBlockHeight(nBlockHeight)
{}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
READWRITE(vin1);
READWRITE(vin2);
READWRITE(addr);
READWRITE(nonce);
READWRITE(nBlockHeight);
READWRITE(vchSig1);
READWRITE(vchSig2);
}
uint256 GetHash() const
{
CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
ss << vin1;
ss << vin2;
ss << addr;
ss << nonce;
ss << nBlockHeight;
return ss.GetHash();
}
void Relay() const
{
CInv inv(MSG_MASTERNODE_VERIFY, GetHash());
g_connman->RelayInv(inv);
}
};
#endif
| [
"pura@pura-dev-final-01"
] | pura@pura-dev-final-01 |
c515e9bb40c98472ad0451232ae632ef0182cb2d | 63fe4641be323129ca73650526f5cb2ec8a77d98 | /Modulator/Unused/DacOut.h | 3731a297adc6de8a78ed560d2822a38c3fccb1f5 | [] | no_license | jbesemer/TeensyGenerators-pre-SharedLibrary | 0a5c69f399e20105d49c9379d84f980bd3d36e14 | 45e9c076241ae01803bcee45bb51ccccd7e79f67 | refs/heads/master | 2021-09-19T10:32:20.516210 | 2018-07-27T00:28:16 | 2018-07-27T00:28:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 728 | h | #pragma once
#include "Config.h"
// manage stimulus to a DAC channel, with output signal
// optionally scaled by an arbitrary gain factor
class DacOut
{
public:
static const float MAX_GAIN; // = 2.0;
static const float DEFAULT_GAIN; // = 1.0;
float Gain;
int TraceCount;
void SetGain( float gain ){
if( 0 < gain && gain <= MAX_GAIN )
Gain = gain;
else
Serial.println( "Gain must be between 0 and 2" );
TraceCount = 0;
}
DacOut() { SetGain( DEFAULT_GAIN ); }
DacOut( float gain ) { SetGain( gain ); }
virtual void Set( int value ){
int dac = (int)( value * Gain );
WriteDac( dac );
if( TraceCount > 0 ){
TraceCount--;
Trace( value, dac );
}
}
void Trace( int value, int dac );
};
| [
"[email protected]"
] | |
f6af4fa1eb28ebe4f9bf523f0a7324166f8f4f7b | 073292d823e8520e85c8940ee1afd3ec5f6599e8 | /cpptest/ta/cplus_ta.cpp | 3437109a21a66963055a7b948f93fc90cc12aab9 | [] | no_license | JohnyDev42/cppoptee | a24916371172d147b56591c7faa509b32ec089d3 | 390a6cdb509b48df1171009a43e1198ccda81df6 | refs/heads/master | 2020-04-03T09:01:36.699310 | 2018-10-29T04:29:46 | 2018-10-29T04:29:46 | 155,152,022 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,125 | cpp | /*
* Copyright (c) 2016, Linaro Limited
* 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 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.
*/
#define __CPLUSPLUS
#include <tee_internal_api.h>
#include <tee_internal_api_extensions.h>
#include <stdio.h>
#include <cplus_ta.h>
#include <iostream>
using namespsce std;
// #include <iostream>
class HELLO{
public:
HELLO()
{
IMSG("c++ feature added");
printf("Successfully.....\n");
printf("testing.....\n");
cout<< "iostream out working\n";
}
};
/*
* Called when the instance of the TA is created. This is the first call in
* the TA.
*/
TEE_Result TA_CreateEntryPoint(void)
{
DMSG("has been called");
return TEE_SUCCESS;
}
/*
* Called when the instance of the TA is destroyed if the TA has not
* crashed or panicked. This is the last call in the TA.
*/
void TA_DestroyEntryPoint(void)
{
DMSG("has been called");
}
/*
* Called when a new session is opened to the TA. *sess_ctx can be updated
* with a value to be able to identify this session in subsequent calls to the
* TA. In this function you will normally do the global initialization for the
* TA.
*/
TEE_Result TA_OpenSessionEntryPoint(uint32_t param_types,
TEE_Param __maybe_unused params[4],
void __maybe_unused **sess_ctx)
{
uint32_t exp_param_types = TEE_PARAM_TYPES(TEE_PARAM_TYPE_NONE,
TEE_PARAM_TYPE_NONE,
TEE_PARAM_TYPE_NONE,
TEE_PARAM_TYPE_NONE);
DMSG("has been called");
if (param_types != exp_param_types)
return TEE_ERROR_BAD_PARAMETERS;
/* Unused parameters */
(void)¶ms;
(void)&sess_ctx;
/*
* The DMSG() macro is non-standard, TEE Internal API doesn't
* specify any means to logging from a TA.
*/
// IMSG("Hello World!!\n");
/* If return value != TEE_SUCCESS the session will not be created. */
return TEE_SUCCESS;
}
/*
* Called when a session is closed, sess_ctx hold the value that was
* assigned by TA_OpenSessionEntryPoint().
*/
void TA_CloseSessionEntryPoint(void __maybe_unused *sess_ctx)
{
(void)&sess_ctx; /* Unused parameter */
IMSG("Goodbye!\n");
}
static TEE_Result cpptest(uint32_t param_types,
TEE_Param params[4])
{
uint32_t exp_param_types = TEE_PARAM_TYPES(TEE_PARAM_TYPE_VALUE_INOUT,
TEE_PARAM_TYPE_NONE,
TEE_PARAM_TYPE_NONE,
TEE_PARAM_TYPE_NONE);
if (param_types != exp_param_types)
return TEE_ERROR_BAD_PARAMETERS;
HELLO a;
return TEE_SUCCESS;
}
/*
* Called when a TA is invoked. sess_ctx hold that value that was
* assigned by TA_OpenSessionEntryPoint(). The rest of the paramters
* comes from normal world.
*/
TEE_Result TA_InvokeCommandEntryPoint(void __maybe_unused *sess_ctx,
uint32_t cmd_id,
uint32_t param_types, TEE_Param params[4])
{
(void)&sess_ctx; /* Unused parameter */
switch (cmd_id) {
case TA_CPLUS_CMD_TEST:
return cpptest(param_types, params);
default:
return TEE_ERROR_BAD_PARAMETERS;
}
}
| [
"[email protected]"
] | |
c2bf75e381cb80b8cb512a9cc23755cf826dc28a | dc9847a0fb25d50b99502491295a7f5e045aa315 | /myXml/PropertyChain.h | cef70870476d275166c7de57f842c31282d68eb5 | [] | no_license | OlehKostiv/MyXml | c76e9a398b270db0c0c097030fdf96f1872e2c0b | 027f8a4d13ee38e356340507b57cf0bfd0cb7110 | refs/heads/master | 2020-03-07T19:24:40.449163 | 2018-04-03T11:07:04 | 2018-04-03T11:07:04 | 127,669,531 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,651 | h | #pragma once
#include "Typedef.h"
namespace MyXml
{
class Property
{
public:
using Iter = Property * ;
Property(const Char* propName, const Char* propValue);
Property(const Char* propName, const Double propValue);
Property(const Char* propName, const Int propValue);
Property(Property&&);
~Property();
Char* ToCharStr() const;
Char* name = nullptr;
Char* text = nullptr;
Iter next = nullptr;
};
class PropertyChain
{
public:
PropertyChain& Append(Property*);
PropertyChain& Append(Property&&);
template <class...Args>
PropertyChain& Append(Property* p, Args...args) // appends backwards
{
return Append(p).Append(args...);
}
template <class...Args>
PropertyChain& Append(Property&& p, Args...args) // appends backwards
{
return Append(p).Append(args...);
}
~PropertyChain();
PropertyChain();
PropertyChain(Property*);
PropertyChain(Property&& rvalProp);
template <class...Args>
PropertyChain(Property* p, Args...args)
{
Append(p, args...);
}
template <class...Args>
PropertyChain(Property&& p, Args...args)
{
Append(p, args...);
}
PropertyChain(PropertyChain&& source);
PropertyChain& operator = (PropertyChain&& source);
Char* ToCharStr() const;
Bool IsEmpty() const;
const Property::Iter FirstProperty() const;
protected:
Property::Iter firstProperty;
};
} | [
"[email protected]"
] | |
149549fc8c7cd4e504a999ff18294b1a6477ae7d | e0f7813c9ca5f0f8b26141badc82c1f41b7dcadd | /Goonies/Projecte/Goonies/Bullet.cpp | 5ffc1295b6ddb713fc529645f5193afeb21ba069 | [] | no_license | gonzagod/VJ-Goonies | aea3912fd31643e3cf66341daa7017ca7f638b6b | df78bc63eee91b7c89b845d4f0fa16158696c566 | refs/heads/master | 2023-03-28T04:44:18.384352 | 2021-04-06T20:09:53 | 2021-04-06T20:09:53 | 344,786,192 | 0 | 0 | null | null | null | null | ISO-8859-2 | C++ | false | false | 2,295 | cpp | #include <cmath>
#include <iostream>
#include <GL/glew.h>
#include <GL/glut.h>
#include "Bullet.h"
#include "Game.h"
#include <crtdbg.h>
enum BulletAnims
{
ANIM,
};
void Bullet::init(const glm::ivec2 &tileMapPos, ShaderProgram &shaderProgram) {
movingL = false;
movingR = false;
alive = false;
bullet_speed = 4;
friendly = false;
spritesheet.loadFromFile("images/TheGoonies-MapTiles2.png", TEXTURE_PIXEL_FORMAT_RGBA);
sprite = Sprite::createSprite(glm::ivec2(16, 16), glm::vec2(0.0625, 0.0625), &spritesheet, &shaderProgram);
sprite->setNumberAnimations(1);
sprite->setAnimationSpeed(ANIM, 8);
sprite->addKeyframe(ANIM, glm::vec2(0.375f, 0.875f));
sprite->changeAnimation(0);
tileMapDispl = tileMapPos;
sprite->setPosition(glm::vec2(float(tileMapDispl.x + posBullet.x), float(tileMapDispl.y + posBullet.y)));
}
void Bullet::update(int deltaTime) {
if (movingL) {
if (!map->collisionMoveLeft(posBullet, glm::ivec2(16, 10)))
{
posBullet.x -= bullet_speed; //Moviment menys fluit perň més similar al joc real.
}
else {
movingL = false;
alive = false;
}
}
else if (movingR) {
if (!map->collisionMoveRight(posBullet, glm::ivec2(16, 10)))
{
posBullet.x += bullet_speed; //Moviment menys fluit perň més similar al joc real.
}
else {
movingR = false;
alive = false;
}
if (posBullet.x >= 576) alive = false;
}
sprite->setPosition(glm::vec2(float(tileMapDispl.x + posBullet.x), float(tileMapDispl.y + posBullet.y)));
}
void Bullet::render()
{
if (alive) {
sprite->setPosition(glm::vec2(float(tileMapDispl.x + posBullet.x), float(tileMapDispl.y + posBullet.y)));
sprite->render();
}
}
void Bullet::setTileMap(TileMap *tileMap)
{
map = tileMap;
}
void Bullet::setPosition(const glm::vec2 &pos)
{
posBullet = pos;
sprite->setPosition(glm::vec2(float(tileMapDispl.x + posBullet.x), float(tileMapDispl.y + posBullet.y)));
}
glm::ivec2 Bullet::getPosition()
{
return posBullet;
}
bool Bullet::is_Alive()
{
return alive;
}
void Bullet::player_hit() {
alive = false;
}
void Bullet::setDirection(bool side)
{
//true -> STAND_RIGHT || false -> STAND_LEFT
if (side) {
movingR = true;
movingL = false;
}
else {
movingL = true;
movingR = false;
}
alive = true;
}
void Bullet::setFriendly()
{
friendly = true;
}
| [
"[email protected]"
] | |
787f50936841a3f8ff59869a285b2cdb238af436 | f6cdb521f47d92ecc110bd476106325365f1ad6f | /src/core/kext/RemapFunc/ScrollWheelToScrollWheel.cpp | 9c99ae33243b61b43a9756fcd35d3e4189f36adb | [] | no_license | tylermenezes/KeyRemap4MacBook | cb878b0d38a02246cee68ea0d77e9f57a0612e3a | 779ea7b96b151061b4c6fe94b0a17be82aa82887 | refs/heads/master | 2021-01-18T02:51:39.588831 | 2014-02-17T07:39:36 | 2014-02-17T07:39:36 | 16,905,214 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,466 | cpp | #include <IOKit/IOLib.h>
#include "EventOutputQueue.hpp"
#include "IOLogWrapper.hpp"
#include "PointingRelativeToScroll.hpp"
#include "ScrollWheelToScrollWheel.hpp"
namespace org_pqrs_KeyRemap4MacBook {
namespace RemapFunc {
ScrollWheelToScrollWheel::ScrollWheelToScrollWheel(void) : index_(0)
{}
ScrollWheelToScrollWheel::~ScrollWheelToScrollWheel(void)
{}
void
ScrollWheelToScrollWheel::add(unsigned int datatype, unsigned int newval)
{
switch (datatype) {
case BRIDGE_DATATYPE_FLAGS:
{
switch (index_) {
case 0:
fromFlags_ = Flags(newval);
break;
default:
toFlags_ = Flags(newval);
break;
}
++index_;
break;
}
default:
IOLOG_ERROR("ScrollWheelToScrollWheel::add invalid datatype:%d\n", datatype);
break;
}
}
bool
ScrollWheelToScrollWheel::remap(RemapParams& remapParams)
{
Params_ScrollWheelEventCallback* params = remapParams.paramsUnion.get_Params_ScrollWheelEventCallback();
if (! params) return false;
if (remapParams.isremapped) return false;
if (! FlagStatus::makeFlags().isOn(fromFlags_)) return false;
remapParams.isremapped = true;
FlagStatus::temporary_decrease(fromFlags_);
FlagStatus::temporary_increase(toFlags_);
EventOutputQueue::FireScrollWheel::fire(*params);
RemapFunc::PointingRelativeToScroll::cancelScroll();
// We need to restore temporary flags.
// Because normal cursor move event don't restore temporary_count_.
// (See EventInputQueue::push_RelativePointerEventCallback.)
//
// ------------------------------------------------------------
// For example:
// This autogen changes option+scroll to scroll. (strip option modifier.)
// <autogen>__ScrollWheelToScrollWheel__ ModifierFlag::OPTION_L, ModifierFlag::NONE</autogen>
//
// Considering the following operation with this autogen, we need to restore temporary flags at (3).
// (1) option+left click
// (2) drag mouse (option+left drag)
// (3) scroll (strip option)
// (4) drag mouse (option+left drag)
// ------------------------------------------------------------
FlagStatus::temporary_decrease(toFlags_);
FlagStatus::temporary_increase(fromFlags_);
return true;
}
}
}
| [
"[email protected]"
] | |
7bf40f8e7044f282a2c6ab6c08e5cc84893d208f | 962476e8b1a5e1ddde58a980402541adf23a13bf | /LLY/LLY/render/PointLightingCommand.h | 51f53176226b57cc110d84a99ec2200121cafcc8 | [
"MIT"
] | permissive | ooeyusea/GameEngine | c9f925a5bc88d69b118d7a10dafeba72fcf82813 | 85e7ceef7ddf663f9601a8a8787e29e8e8cdb425 | refs/heads/master | 2021-01-02T08:52:39.788919 | 2015-07-06T14:00:07 | 2015-07-06T14:00:07 | 33,131,532 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 660 | h | #ifndef POINTLIGHTCOMMAND_H_
#define POINTLIGHTCOMMAND_H_
#include <glm/glm.hpp>
#include "LightingCommand.h"
namespace lly {
class Device;
class PointLightingCommand : public LightingCommand
{
public:
PointLightingCommand(const glm::vec4& color, const glm::vec3& position, float constant, float linear, float quadratic)
: _color(color), _position(position), _constant(constant), _linear(linear), _quadratic(quadratic)
{
}
virtual ~PointLightingCommand() {}
virtual void draw(Device& device);
private:
glm::vec4 _color;
glm::vec3 _position;
float _constant;
float _linear;
float _quadratic;
};
}
#endif //POINTLIGHTCOMMAND_H_
| [
"[email protected]"
] | |
e510b83eff61e107c28e3a836c832fbb18cd3572 | 141b07a7747a82ce589b6fa4e0d4c3f2f2fc8953 | /01-July-2021/reaching-points/Accepted/4-7-2021, 6:06:26 AM/Solution.cpp | 44382ed668b0a5c32dc1c4ecd5c1b2aaaca4989a | [] | no_license | tonymontaro/leetcode-submissions | f5f8b996868bfd63ddb43f3c98f8a7abef17927e | 146f435d9ab792e197e5f85f1f2f4451f5a75d3f | refs/heads/main | 2023-06-06T01:28:45.793095 | 2021-07-01T07:05:15 | 2021-07-01T07:05:15 | 381,935,473 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 660 | cpp | // https://leetcode.com/problems/reaching-points
class Solution {
public:
bool reachingPoints(int sx, int sy, int tx, int ty) {
while (tx > 0 && ty > 0) {
if (tx == sx && ty == sy)
return true;
if (tx < sx || ty < sy) return false;
int div = tx / ty;
if (tx >= ty) {
if (ty == sy && (tx - sx) % ty == 0) return true;
tx = tx - (div * ty);
} else {
if (tx == sx && (ty - sy) % tx == 0) return true;
div = ty / tx;
ty = ty - (div * tx);
}
}
return false;
}
};
| [
"[email protected]"
] | |
679acf6f530d9cd892ca5b971a071a2934ed1247 | 573a66e4f4753cc0f145de8d60340b4dd6206607 | /JS-CS-Detection-byExample/Dataset (ALERT 5 GB)/358137/2.0/pwsafe-2.0-src/AddDlg.cpp | d4ff662d5e2a2a5cda7d86edf2bfc5b44fa17dee | [
"Artistic-2.0",
"Artistic-1.0-Perl",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | mkaouer/Code-Smells-Detection-in-JavaScript | 3919ec0d445637a7f7c5f570c724082d42248e1b | 7130351703e19347884f95ce6d6ab1fb4f5cfbff | refs/heads/master | 2023-03-09T18:04:26.971934 | 2022-03-23T22:04:28 | 2022-03-23T22:04:28 | 73,915,037 | 8 | 3 | null | 2023-02-28T23:00:07 | 2016-11-16T11:47:44 | null | UTF-8 | C++ | false | false | 3,310 | cpp | /// \file AddDlg.cpp
//-----------------------------------------------------------------------------
#include "stdafx.h"
#include "PasswordSafe.h"
#include "ThisMfcApp.h"
#include "DboxMain.h"
#include "AddDlg.h"
#include "PwFont.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
//-----------------------------------------------------------------------------
CAddDlg::CAddDlg(CWnd* pParent)
: CDialog(CAddDlg::IDD, pParent), m_password(_T("")), m_notes(_T("")),
m_username(_T("")), m_title(_T("")), m_group(_T(""))
{
DBGMSG("CAddDlg()\n");
}
BOOL CAddDlg::OnInitDialog()
{
CDialog::OnInitDialog();
SetPasswordFont(GetDlgItem(IDC_PASSWORD));
return TRUE;
}
void CAddDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Text(pDX, IDC_PASSWORD, (CString&)m_password);
DDX_Text(pDX, IDC_NOTES, (CString&)m_notes);
DDX_Text(pDX, IDC_USERNAME, (CString&)m_username);
DDX_Text(pDX, IDC_TITLE, (CString&)m_title);
DDX_Text(pDX, IDC_GROUP, (CString&)m_group);
}
BEGIN_MESSAGE_MAP(CAddDlg, CDialog)
ON_BN_CLICKED(ID_HELP, OnHelp)
ON_BN_CLICKED(IDC_RANDOM, OnRandom)
END_MESSAGE_MAP()
void
CAddDlg::OnCancel()
{
app.m_pMainWnd = NULL;
CDialog::OnCancel();
}
void
CAddDlg::OnOK()
{
UpdateData(TRUE);
//Check that data is valid
if (m_title.IsEmpty())
{
AfxMessageBox(_T("This entry must have a title."));
((CEdit*)GetDlgItem(IDC_TITLE))->SetFocus();
return;
}
if (m_password.IsEmpty())
{
AfxMessageBox(_T("This entry must have a password."));
((CEdit*)GetDlgItem(IDC_PASSWORD))->SetFocus();
return;
}
//End check
DboxMain* pParent = (DboxMain*) GetParent();
ASSERT(pParent != NULL);
if (pParent->Find(m_title, m_username) != NULL)
{
CMyString temp =
"An item with Title \""
+ m_title + "\" and User Name \"" + m_username
+ "\" already exists.";
AfxMessageBox(temp);
((CEdit*)GetDlgItem(IDC_TITLE))->SetSel(MAKEWORD(-1, 0));
((CEdit*)GetDlgItem(IDC_TITLE))->SetFocus();
}
else
{
app.m_pMainWnd = NULL;
CDialog::OnOK();
}
}
void CAddDlg::OnHelp()
{
#if defined(POCKET_PC)
CreateProcess( _T("PegHelp.exe"), _T("pws_ce_help.html#adddata"), NULL, NULL, FALSE, 0, NULL, NULL, NULL, NULL );
#else
//WinHelp(0x2008E, HELP_CONTEXT);
::HtmlHelp(NULL,
"pwsafe.chm::/html/pws_add_data.htm",
HH_DISPLAY_TOPIC, 0);
#endif
}
void CAddDlg::OnRandom()
{
DboxMain* pParent = (DboxMain*) GetParent();
ASSERT(pParent != NULL);
CMyString temp = pParent->GetPassword();
UpdateData(TRUE);
int nResponse;
if (m_password.IsEmpty())
nResponse = IDYES;
else
{
CMyString msg;
msg = "The randomly generated password is: \""
+ temp
+ "\" \n(without the quotes). Would you like to use it?";
nResponse = MessageBox(msg, AfxGetAppName(),
MB_ICONEXCLAMATION|MB_YESNO);
}
if (nResponse == IDYES)
{
m_password = temp;
UpdateData(FALSE);
}
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
| [
"[email protected]"
] | |
66c8a974180782a22d5e1f5095e1058de1dca6c3 | 7d302735577aae9f62f34e8086e5935b43d593e7 | /DirectXGame/DirectXCore/MapReader/TmxPolygon.cpp | 76c624d4299acbd503474fbc9511f6f3387654cf | [
"MIT"
] | permissive | nguyenlamlll/DirectX-11-Game | c8f683d57f5d27a81e29aa616dce60a8e7d2b6b1 | 560ae6d9b44cef7882c5fc93192160fae7da791d | refs/heads/develop | 2020-03-28T10:47:31.633691 | 2018-12-03T14:14:46 | 2018-12-03T14:14:46 | 148,145,340 | 2 | 1 | MIT | 2018-12-16T05:02:34 | 2018-09-10T11:31:53 | C++ | UTF-8 | C++ | false | false | 2,155 | cpp | //-----------------------------------------------------------------------------
// TmxPolygon.cpp
//
// Copyright (c) 2010-2014, Tamir Atias
// 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.
//
// 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 TAMIR ATIAS 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.
//
// Author: Tamir Atias
//-----------------------------------------------------------------------------
#pragma warning(disable:4996)
#include "tinyxml2.h"
#include <cstdlib>
#include "TmxPolygon.h"
namespace Tmx
{
Polygon::Polygon()
: points()
{
}
void Polygon::Parse(const tinyxml2::XMLNode *polygonNode)
{
char *pointsLine = _strdup(polygonNode->ToElement()->Attribute("points"));
char *token = strtok(pointsLine, " ");
while (token)
{
Point point;
sscanf(token, "%f,%f", &point.x, &point.y);
points.push_back(point);
token = strtok(0, " ");
}
free(pointsLine);
}
}
| [
"[email protected]"
] | |
86ba940cc8183955b2e6087ca98196a3f5f2f7f8 | cfa270ec0c002f6a100619e25e372f6100e56187 | /src/interpol.h | 62b926fcd526519475c2984aa40bdecd0a1f1dd9 | [] | no_license | jaimedelacruz/stic | aa306e8bfef105fbe9c16f9cfa8b1261fc90a051 | 0f75048e8de49d9c9fd6f374fe94badcedc222f9 | refs/heads/master | 2023-06-08T00:48:33.598057 | 2023-06-01T12:37:53 | 2023-06-01T12:37:53 | 149,418,552 | 27 | 7 | null | 2021-06-19T12:09:22 | 2018-09-19T08:34:50 | C | UTF-8 | C++ | false | false | 14,543 | h | /*
Various interpolation routines
Coded by J. de la Cruz Rodriguez (ISP-SU 2015)
*/
#ifndef INTERPOL_H
#define INTERPOL_H
//
#include <math.h>
#include <algorithm>
#include <cstdio>
#include <vector>
#include "math_tools.h"
/* --------------------------------------------------------------------- */
template <class T> T harmonic_derivative2(const T odx, const T dx, const T ody, const T dy)
{
// It follows Steffen (1990), A&A 239, 443-450.
if((ody*dy) > 0.0){
T pi = (dy * odx + ody * dx) / (dx + odx);
T der = (mth::sign(dy) + mth::sign(ody)) * std::min(std::min(fabs(ody), fabs(dy)), 0.5*fabs(pi));
return der;
}else{
return T(0);
}
}
/* --------------------------------------------------------------------- */
template <class T> T harmonic_derivative(const T odx, const T dx, const T ody, const T dy)
{
if((ody*dy) > 0.0){
T lam = (1.0 + dx / (dx + odx)) * 0.33333333333333333333333333333;
T der = (ody*dy) / (lam*dy + (1.0-lam)*ody);
return der;
}else{
return T(0);
}
}
/* --------------------------------------------------------------------- */
/*
Piece-wise linear interpolation, with optinal
linear extrapolation outside the input range.
*/
template <class T, class U> void linpol(size_t ni, T *x, T *y, size_t nni, U *xx, U *yy, bool extrapolate = false){
unsigned n = (unsigned)ni, nn = (unsigned)nni;
//
// increasing or decreasing x?
//
bool dir = true;
if( (x[1]-x[0]) < 0 ) dir = false;
if(dir){
unsigned off = 0;
for(unsigned k = 1; k<n; k++){
// Coeffs.
double a = (y[k] - y[k-1]) / (x[k] - x[k-1]);
double b = y[k-1] - a * x[k-1];
// Check if there are points to compute
for(unsigned j = off; j<nn; j++){
if((xx[j] >= x[k-1]) && (xx[j] < x[k])){
yy[j] = a * xx[j] + b;
off++;
}
} // j
} // k
}else{
unsigned off = 0;
for(unsigned k = 1; k<n; k++){
// Coeffs.
double a = (y[k] - y[k-1]) / (x[k] - x[k-1]);
double b = y[k-1] - a * x[k-1];
// Check if there are points to compute
for(unsigned j = off; j<nn; j++){
if((xx[j] <= x[k-1]) && (xx[j] > x[k])){
yy[j] = a * xx[j] + b;
off++;
}
} // j
} // k
} // Else
double a0, a1, b0, b1;
if(extrapolate){
a0 = (y[1] - y[0]) / (x[1] - x[0]);
b0 = y[0] - a0 * x[0];
a1 = (y[n-1] - y[n-2]) / (x[n-1] - x[n-2]);
b1 = y[n-1] - a1 * x[n-1];
}else{
a0 = 0;
a1 = 0;
b0 = y[0];
b1 = y[n-1];
}
if(dir) for(unsigned k = 0; k<nn; k++){
if(xx[k] <= x[0]) yy[k] = a0 * xx[k] + b0;
if(xx[k] >= x[n-1]) yy[k] = a1 * xx[k] + b1;
}
else for(unsigned k = 0; k<nn; k++){
if(xx[k] >= x[0]) yy[k] = a0 * xx[k] + b0;
if(xx[k] <= x[n-1]) yy[k] = a1 * xx[k] + b1;
}
} // linpol
/* --------------------------------------------------------------------- */
template <class U, class T, class V> void hermpol2(const U n, const T *x, const T *y,
const U nn, const V *xx, V *yy,
const bool extrapolate = false)
{
// Third order Hermite interpolation
// It allows to set the detivatives to zero at the very last points
// or to extrapolate the last intervals using the keyword "extrapolate"
//
// It accepts any direction in the x, xx arrays as long as
// they monotonically increase or decrease.
//
// Coded by J. de la Cruz Rodriguez (ISP-SU 2018)
//
size_t n1 = (size_t)n, nn1 = (size_t)nn, off = 0,
istart = 1, iend = n1, di = 1;
bool dir = true;
if((x[n-1]-x[0]) < 0.0){
istart = n1-2;
iend = -1;
di = -1;
dir = false;
}
size_t is = 0, ie = nn, dd = 1;
if((xx[ie]-xx[is]) < 0.0){
is = nn1-1, ie = -1, dd = -1;
}
off = is;
T odx = x[istart]-x[istart-di], ody = (y[istart]-y[istart-di]) / odx, dx = 0.0, dy = 0.0,
oder = ((extrapolate)? ody : 0.0), der = 0.0;
// --- Interpolate in the domain --- //
for(size_t ii = istart; ii != iend; ii += di){
// Compute the derivative in the downwind interval.
// If we are in the last interval, check if we shoudl
// set the derivative to zero or not.
if(ii != (iend-di)){
dx = x[ii+di]-x[ii], dy = ( y[ii+di] - y[ii]) / dx;
der = harmonic_derivative(odx, dx, ody, dy);
}else
der = ((extrapolate)? dy : 0.0);
// Now perform the interpolation for all points inside each interval
for(size_t kk=off; kk != ie; kk += dd){
if((xx[kk] > x[ii-di]) && (xx[kk] <= x[ii])){
T u = (xx[kk] - x[ii-di]) / odx, // Normalized units
uu = u*u, uuu = uu*u;
yy[kk] = y[ii-di] * (1.0 - 3.0*uu + 2.0*uuu) + (3.0*uu - 2.0*uuu) * y[ii] +
(uuu - 2.0*uu + u) * odx * oder + (uuu - uu) * odx * der;
off += dd;
}
} // kk
odx = dx, ody = dy, oder = der;
} // ii
// --- Out of bound limits --- //
if(dir){
istart = 0, iend = n1-1, di = 1;
}else{
istart = n1-1, iend = 0, di = -1;
}
V a0=0, a1=0, b0=y[istart], b1=y[iend];
if(extrapolate){
a0 = (y[istart]-y[istart+di])/(x[istart]-x[istart+di]), b0 = y[istart]-a0*x[istart];
a1 = (y[iend]-y[iend-di])/(x[iend]-x[iend-di]), b1 = y[iend]-a1*x[iend];
}
for(size_t ii=is; ii != ie; ii += dd){
if(xx[ii] <= x[istart]) yy[ii] = a0 * xx[ii] + b0;
if(xx[ii] >= x[iend]) yy[ii] = a1 * xx[ii] + b1;
}
}
/*
Piece-wise Hermitian interpolation, with optional
linear extrapolation outside the input range.
Hermitian interpolant from Auer (2003), Formal Solution: Explicit answers.
*/
template <class T1, class T2> void hermpol(const size_t ni, const T1 *x, const T1 *y, const size_t nni, const T2 *xx, T2 *yy, bool extrapolate = false){
unsigned n = (unsigned)ni, nn = (unsigned)nni;
// Increasing x?
bool sign = true;
if( (x[1] - x[0]) < 0 ) sign = false;
// Init derivatives
double odx = x[1] - x[0];
double oder = ((extrapolate)?((y[1] - y[0]) / odx):0.0);
double ody = oder;
double dy = 0;
double der = 0;
double dx = 0;
unsigned off = 0;
if(sign){
for(unsigned k = 1; k<n; k++){
// Derivatives
if(k<(n-1)){
dx = x[k+1] - x[k];
dy = (y[k+1] - y[k]) / dx;
//if(dy*ody > 0) der = (dx * ody + odx * dy) / (dx + odx);
//double lambda = (1.0 + dx / (dx + odx)) / 3.0;
der = harmonic_derivative(odx, dx, ody, dy);
} else{
if(extrapolate) der = ody;
else der = 0.0;
}
// Check if there are points to compute
for(unsigned j = off; j<nn; j++){
if( (xx[j] >= x[k-1]) && (xx[j] < x[k]) ){
// Normalize interval units
double u = (xx[j] - x[k-1]) / odx;
double uu = u*u;
// Hermitian interpolant
yy[j] = y[k-1] * (1.0 - 3*uu + 2*uu*u) + (3*uu - 2*uu*u) * y[k] +
(uu*u - 2*uu + u) * odx * oder + (uu*u - uu) * odx * der;
off++;
}
} // j
// Store values
odx = dx;
ody = dy;
oder = der;
} // k
}else{
for(unsigned k = 1; k<n; k++){
// Derivatives
if(k<(n-1)){
dx = x[k+1] - x[k];
dy = (y[k+1] - y[k]) / dx;
//if(dy*ody > 0) der = (dx * ody + odx * dy) / (dx + odx);
der = harmonic_derivative(odx, dx, ody, dy);
} else{
if(extrapolate) der = ody;
else der = 0.0;
}
// Check if there are points to compute
for(unsigned j = off; j<nn; j++){
if( (xx[j] <= x[k-1]) && (xx[j] > x[k]) ){
double u = (xx[j] - x[k-1]) / odx;
double uu = u*u;
double uuu = uu*u;
yy[j] = y[k-1] * (1.0 - 3*uu + 2*uuu) + (3*uu - 2*uuu) * y[k] +
(uuu - 2*uu + u) * odx * oder + (uuu - uu) * odx * der;
off++;
}
} // j
odx = dx;
ody = dy;
oder = der;
} // k
}
//
// Points outside the x[0], x[n-1]?
//
double a0, a1, b0, b1;
if(extrapolate){
a0 = (y[1] - y[0]) / (x[1] - x[0]);
b0 = y[0] - a0 * x[0];
a1 = (y[n-1] - y[n-2]) / (x[n-1] - x[n-2]);
b1 = y[n-1] - a1 * x[n-1];
}else{
a0 = 0;
a1 = 0;
b0 = y[0];
b1 = y[n-1];
}
if(sign){
for(unsigned k = 0; k<nn; k++){
if(xx[k] <= (x[0])) yy[k] = a0 * xx[k] + b0;
if(xx[k] >= (x[n-1])) yy[k] = a1 * xx[k] + b1;
}
} else {
for(unsigned k = 0; k<nn; k++){
if(xx[k] >= (x[0])) yy[k] = a0 * xx[k] + b0;
if(xx[k] <= (x[n-1])) yy[k] = a1 * xx[k] + b1;
}
}
} // hermpol
/* --------------------------------------------------------------------- */
template <class T1, class T2> void cpol( T1 y, int nn, T2 *yy){
T2 dum = (T2)y;
for(int kk = 0; kk<nn; kk++) yy[kk] = dum;
}
/* --------------------------------------------------------------------- */
template <class T> T sqr(T var){
return var*var;
}
/* --------------------------------------------------------------------- */
template <class T> std::vector<double> parab_fit(T d, T e, T f, T yd, T ye, T yf){
std::vector<double> cf;
cf.resize(3,0.0);
cf[1] = ((yf - yd) - (f*f - d*d) * ((ye - yd) / (e*e - d*d)))/
((f - d) - (f*f - d*d) * ((e - d) / (e*e - d*d)));
cf[2] = ((ye - yd) - cf[1] * (e - d)) / (e*e - d*d);
cf[0] = yd - cf[1] * d - cf[2] * d*d;
return cf;
}
/* --------------------------------------------------------------------- */
template <class T1, class T2> void bezpol2(size_t ni, T1 *x, T1 *y, size_t nni, T2 *xx, T2 *yy, bool extrapolate = false){
unsigned n = (unsigned)ni, nn = (unsigned)nni;
// Increasing x?
bool sign = true;
if( (x[1] - x[0]) < 0 ) sign = false;
// Init derivatives
double odx = x[1] - x[0];
double oder = (y[1] - y[0]) / odx;
double ody = oder;
double dy = 0;
double der = 0;
double dx = 0;
unsigned off = 0;
if(sign){
for(unsigned k = 1; k<n; k++){
/* --- Compute centered derivatives --- */
if(k<(n-1)){
dx = x[k+1] - x[k];
dy = (y[k+1] - y[k]) / dx;
der = harmonic_derivative(odx, dx, ody, dy);
//der = (dy*ody) / ((1.0-lambda)*ody + lambda * dy);
} else der = ody;
/* --- Make a combined control point from the upwind and central points,
makes a very tight spline compared to only using one of the control points
--- */
double cntrl = 0.5 * ( (y[k-1] + 0.5*odx*oder) + (y[k] - 0.5*odx*der) );
/* --- Check if there are points to compute --- */
for(unsigned j = off; j<nn; j++){
if( (xx[j] >= x[k-1]) && (xx[j] < x[k]) ){
// Normalize interval units
double u = (xx[j] - x[k-1]) / odx;
double u1 = 1.0 - u;
// Quadratic Bezier interpolant
yy[j] = y[k-1]*u1*u1 + y[k]*u*u + 2.0*cntrl*u*u1;
off++;
}
} // j
/* --- Store values for next interval --- */
odx = dx;
ody = dy;
oder = der;
} // k
}else{
for(unsigned k = 1; k<n; k++){
// Derivatives
if(k<(n-1)){
dx = x[k+1] - x[k];
dy = (y[k+1] - y[k]) / dx;
der = harmonic_derivative(odx, dx, ody, dy);
//der = (dy*ody) / ((1.0-lambda)*ody + lambda * dy);
} else der = ody;
/* --- Make a combined control point from the upwind and central points,
makes a very tight spline compared to only using one of the control points
--- */
double cntrl = 0.5 * ( (y[k-1] + 0.5*odx*oder) + (y[k] - 0.5*odx*der) );
// Check if there are points to compute
for(unsigned j = off; j<nn; j++){
if( (xx[j] <= x[k-1]) && (xx[j] > x[k]) ){
double u = (xx[j] - x[k-1]) / odx;
double u1 = 1.0 - u;
// Quadratic Bezier interpolant
yy[j] = y[k-1]*u1*u1 + y[k]*u*u + 2.0*cntrl*u*u1;
off++;
}
} // j
odx = dx;
ody = dy;
oder = der;
} // k
}
//
// Points outside the x[0], x[n-1]?
//
double a0, a1, b0, b1;
if(extrapolate){
a0 = (y[1] - y[0]) / (x[1] - x[0]);
b0 = y[0] - a0 * x[0];
a1 = (y[n-1] - y[n-2]) / (x[n-1] - x[n-2]);
b1 = y[n-1] - a1 * x[n-1];
}else{
a0 = 0;
a1 = 0;
b0 = y[0];
b1 = y[n-1];
}
if(sign){
for(unsigned k = 0; k<nn; k++){
if(xx[k] <= (x[0])) yy[k] = a0 * xx[k] + b0;
if(xx[k] >= (x[n-1])) yy[k] = a1 * xx[k] + b1;
}
} else {
for(unsigned k = 0; k<nn; k++){
if(xx[k] >= (x[0])) yy[k] = a0 * xx[k] + b0;
if(xx[k] <= (x[n-1])) yy[k] = a1 * xx[k] + b1;
}
}
} // bezpol2
/* --------------------------------------------------------------------- */
template <class T1, class T2> void vlint(size_t n, T1 *x, T1 *y, size_t n1, T2 *xx, T2 *yy)
{
double x0=0.0, y0=0.0, x1=0.0, y1=0.0, dxu=0.0, dxd=0.0,
r=0.0, phi=0.0, der=0.0, u = 0.0;
size_t off = 0, off0 = 0, off1 = 0;
for(size_t ii=1;ii<(n-1); ii++){
/* --- Compute the derivative --- */
dxu = (x[ii]-x[ii-1])*0.5;
dxd = (x[ii+1]-x[ii])*0.5;
//
r = (y[ii]-y[ii-1])/(y[ii+1]-y[ii]);
if(!std::isfinite(r)) r = 0.0;
//
phi = (r + fabs(r)) / (1.0 + fabs(r));
der = phi * (y[ii+1]-y[ii]) / (dxd+dxu);
/* --- Now check if there are points in this interval --- */
bool first = true;
for(size_t jj=off; jj<n1; jj++){
if( (xx[jj] <= (x[ii]+dxd)) && (xx[jj] > (x[ii]-dxu)) ){
yy[jj] = der * (xx[jj]-x[ii]) + y[ii];
if((ii==1) && first) x0 = xx[jj], y0 = yy[jj];
x1 = xx[jj], y1 = yy[jj];
first = false;
off++;
} // if
}// jj
}// ii
/* --- Second interval ---*/
dxu = (x[n-1] - x[n-2]) * 0.5;
for(size_t jj=off;jj<n1; jj++){
if(xx[jj] >= (x[n-1]-dxu)) yy[jj] = (y[n-1]-y1)/(x[n-1]-x1) * (xx[jj]-x[n-1]) + y[n-1];
}
/* --- first interval --- */
dxd = (x[1] - x[0]) * 0.5;
der = (y[0]-y0)/(x[0]-x0);
for(size_t jj=0;jj<n1; jj++){
if(xx[jj] <= (x[0]+dxd)) yy[jj] = der * (xx[jj]-x[0]) + y[0];
else break;
}
}
/* --------------------------------------------------------------------- */
template <class T> void cent_der(size_t n, T *x, T *y, T *yp)
{
double odx = x[1]-x[0], dx = 0;
double oder = (y[1]-y[0])/odx, der = 0;
yp[0] = oder;
for(size_t ii=1;ii<(n-1); ii++){
dx = x[ii+1] - x[ii];
der = (y[ii+1] - y[ii]) / dx;
if(der*oder > 0.0){
double lambda = (1.0 + dx / (dx + odx)) / 3.0;
yp[ii] = (oder / (lambda * der + (1.0 - lambda) * oder)) * der;
} else yp[ii] = 0.0; // Set der to zero at extrema;
/* --- Save values --- */
oder = der, odx = dx;
}
yp[n-1] = oder;
}
#endif
| [
"[email protected]"
] | |
e44df664ad5562766352531e9e124caa2ed39f72 | 53bbde66a89cf44fa459509a0c5154df2a447494 | /detection/include/open_ptrack/detection/ground_segmentation.h | bcef04a38eb840c81a9b6891a7c207f23d4d46dc | [] | no_license | marketto89/open_ptrack | 0fb41c9d3047d79a0aa4116be9be73185ce2de86 | f3790b6aa1139f6b72c48ec43e8ee890e2fa704d | HEAD | 2019-07-06T15:58:08.375880 | 2017-09-26T21:34:58 | 2017-09-26T21:34:58 | 103,685,443 | 37 | 10 | null | null | null | null | UTF-8 | C++ | false | false | 9,938 | h | /*
* Software License Agreement (BSD License)
*
* Copyright (c) 2013-, Open Perception, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the copyright holder(s) nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Author: Matteo Munaro [[email protected]], Nicola Rist��
*
*/
#ifndef OPEN_PTRACK_DETECTION_GROUND_SEGMENTATION_H_
#define OPEN_PTRACK_DETECTION_GROUND_SEGMENTATION_H_
#include <Eigen/Eigen>
#include <visualization_msgs/MarkerArray.h>
#include <pcl/segmentation/organized_multi_plane_segmentation.h>
#include <pcl/features/integral_image_normal.h>
#include <pcl/features/normal_3d.h>
#include <pcl/sample_consensus/sac_model_plane.h>
#include <pcl/sample_consensus/ransac.h>
#include <pcl/filters/extract_indices.h>
#include <tf/transform_listener.h>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include<iostream>
#include<fstream>
namespace open_ptrack
{
namespace detection
{
template <typename PointT> class GroundplaneEstimation;
template <typename PointT>
/** \brief GroundplaneEstimation estimates the ground plane equation from a 3D point cloud */
class GroundplaneEstimation
{
public:
typedef pcl::PointCloud<PointT> PointCloud;
typedef boost::shared_ptr<PointCloud> PointCloudPtr;
typedef boost::shared_ptr<const PointCloud> PointCloudConstPtr;
/** \brief Constructor. */
GroundplaneEstimation (int ground_estimation_mode, bool remote_ground_selection);
/** \brief Destructor. */
virtual ~GroundplaneEstimation ();
/**
* \brief Set the pointer to the input cloud.
*
* \param[in] cloud A pointer to the input cloud.
*/
void
setInputCloud (PointCloudPtr& cloud);
/**
* \brief Return true if the cloud has ratio of NaN over total number of points greater than "max_ratio".
*
* \param[in] cloud The input cloud.
* \param[in] max_ratio The ratio of invalid points over which a cloud is considered as not valid.
*
* \return true if the cloud has ratio of NaN over total number of points greater than "max_ratio".
*/
bool
tooManyNaN (PointCloudConstPtr cloud, float max_ratio);
/**
* \brief Return true if the percentage of points with confidence below the confidence_threshold is greater than max_ratio.
*
* \param[in] confidence_image Image with confidence values for every pixel.
* \param[in] confidence_threshold Threshold on the confidence to consider a point as valid.
* \param[in] max_ratio The ratio of invalid points over which a cloud is considered as not valid.
*
* \return true if the cloud has ratio of NaN over total number of points greater than "max_ratio".
*/
bool
tooManyLowConfidencePoints (cv::Mat& confidence_image, int confidence_threshold, double max_ratio);
/**
* \brief Compute the ground plane coefficients from the transform between two reference frames.
*
* \param[in] camera_frame Camera frame id.
* \param[in] world_frame Ground frame id.
*
* \return Vector of ground plane coefficients.
*/
Eigen::VectorXf
computeFromTF (std::string camera_frame, std::string ground_frame);
/**
* \brief Compute the ground plane coefficients from the transform between two reference frames.
*
* \param[in] worldToCamTransform ROS transform between world frame and camera frame.
*
* \return Vector of ground plane coefficients.
*/
Eigen::VectorXf
computeFromTF (tf::Transform worldToCamTransform);
/**
* \brief Read the world to camera transform from file.
*
* \param[in] filename Filename listing camera poses for each camera.
* \param[in] camera_name Name of the camera for which the pose should be read.
*
* \return The world to camera transform.
*/
tf::Transform
readTFFromFile (std::string filename, std::string camera_name);
/**
* \brief Compute the ground plane coefficients.
*
* \return Vector of ground plane coefficients.
*/
Eigen::VectorXf
compute ();
/**
* \brief Compute the ground plane coefficients with the procedure used in multi-camera systems.
* \param[in] ground_from_extrinsic_calibration If true, exploit extrinsic calibration for estimatin the ground plane equation.
* \param[in] read_ground_from_file Flag stating if the ground should be read from file, if present.
* \param[in] pointcloud_topic Topic containing the point cloud.
* \param[in] sampling_factor Scale factor used to downsample the point cloud.
*
* \return Vector of ground plane coefficients.
*/
Eigen::VectorXf
computeMulticamera (bool ground_from_extrinsic_calibration, bool read_ground_from_file, std::string pointcloud_topic,
int sampling_factor, float voxel_size);
/**
* \brief Refine ground coefficients by iterating ground plane detection on the input cloud
*
* \param[in] cloud Input cloud.
* \param[in] num_iter Number of iterations.
* \param[in] inliers_threshold Distance threshold for selecting inliers.
* \param[in/out] Ground coefficients.
*
* return true if ground coefficients have been updated, false otherwise.
*/
bool
refineGround (int num_iter, float voxel_size, float inliers_threshold, Eigen::VectorXf& ground_coeffs_calib);
private:
/**
* \brief Callback listening to point clicking on PCL visualizer.
*
*/
static void
pp_callback (const pcl::visualization::PointPickingEvent& event, void* args);
/**
* \brief Mouse clicking callback on OpenCV images.
*/
static void
click_cb (int event, int x, int y, int flags, void* args);
/**
* \brief States which planar region is lower.
*
* \param[in] region1 First planar region.
* \param[in] region2 Second planar region.
*
* \return true if region2 is lower than region1.
*/
static bool
planeHeightComparator (pcl::PlanarRegion<PointT> region1, pcl::PlanarRegion<PointT> region2);
/**
* \brief Color the planar regions with different colors or the index-th planar region in red.
*
* \param[in] regions Vector of planar regions.
* \param[in] index If set and > 0, specify the index of the region to be colored in red. If not set, all regions are colored with different colors.
*
* \return The colored point cloud.
*/
pcl::PointCloud<pcl::PointXYZRGB>::Ptr
colorRegions (std::vector<pcl::PlanarRegion<PointT>,
Eigen::aligned_allocator<pcl::PlanarRegion<PointT> > > regions, int index = -1);
protected:
/** \brief Flag stating if ground should be estimated manually (0), semi-automatically (1) or automatically with validation (2) or fully automatically (3) */
int ground_estimation_mode_;
/** \brief Flag enabling manual ground selection via ssh */
bool remote_ground_selection_;
/** \brief pointer to the input cloud */
PointCloudPtr cloud_;
/** \brief structure used to pass arguments to the callback function */
struct callback_args{
pcl::PointCloud<pcl::PointXYZ>::Ptr clicked_points_3d;
pcl::visualization::PCLVisualizer* viewerPtr;
};
/** \brief structure used to pass arguments to the callback function */
struct callback_args_color{
pcl::PointCloud<pcl::PointXYZRGB>::Ptr clicked_points_3d;
pcl::visualization::PCLVisualizer* viewerPtr;
};
/** \brief structure used to pass arguments to the callback function associated to an image */
struct callback_args_image{
std::vector<cv::Point> clicked_points_2d;
bool selection_finished;
};
};
} /* namespace detection */
} /* namespace open_ptrack */
#include <open_ptrack/detection/impl/ground_segmentation.hpp>
#endif /* OPEN_PTRACK_DETECTION_GROUND_SEGMENTATION_H_ */
| [
"[email protected]"
] | |
61078836354271f0a70e80f95fd600ef6645622e | 41b4adb10cc86338d85db6636900168f55e7ff18 | /aws-cpp-sdk-iam/include/aws/iam/model/SimulateCustomPolicyResult.h | b6ddd43854d73cd7473aa942384a7224e84e215b | [
"JSON",
"MIT",
"Apache-2.0"
] | permissive | totalkyos/AWS | 1c9ac30206ef6cf8ca38d2c3d1496fa9c15e5e80 | 7cb444814e938f3df59530ea4ebe8e19b9418793 | refs/heads/master | 2021-01-20T20:42:09.978428 | 2016-07-16T00:03:49 | 2016-07-16T00:03:49 | 63,465,708 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 7,617 | h | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
#pragma once
#include <aws/iam/IAM_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/iam/model/ResponseMetadata.h>
#include <aws/iam/model/EvaluationResult.h>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Xml
{
class XmlDocument;
} // namespace Xml
} // namespace Utils
namespace IAM
{
namespace Model
{
/**
* <p>Contains the response to a successful <a>SimulatePrincipalPolicy</a> or
* <a>SimulateCustomPolicy</a> request.</p>
*/
class AWS_IAM_API SimulateCustomPolicyResult
{
public:
SimulateCustomPolicyResult();
SimulateCustomPolicyResult(const AmazonWebServiceResult<Aws::Utils::Xml::XmlDocument>& result);
SimulateCustomPolicyResult& operator=(const AmazonWebServiceResult<Aws::Utils::Xml::XmlDocument>& result);
/**
* <p>The results of the simulation.</p>
*/
inline const Aws::Vector<EvaluationResult>& GetEvaluationResults() const{ return m_evaluationResults; }
/**
* <p>The results of the simulation.</p>
*/
inline void SetEvaluationResults(const Aws::Vector<EvaluationResult>& value) { m_evaluationResults = value; }
/**
* <p>The results of the simulation.</p>
*/
inline void SetEvaluationResults(Aws::Vector<EvaluationResult>&& value) { m_evaluationResults = value; }
/**
* <p>The results of the simulation.</p>
*/
inline SimulateCustomPolicyResult& WithEvaluationResults(const Aws::Vector<EvaluationResult>& value) { SetEvaluationResults(value); return *this;}
/**
* <p>The results of the simulation.</p>
*/
inline SimulateCustomPolicyResult& WithEvaluationResults(Aws::Vector<EvaluationResult>&& value) { SetEvaluationResults(value); return *this;}
/**
* <p>The results of the simulation.</p>
*/
inline SimulateCustomPolicyResult& AddEvaluationResults(const EvaluationResult& value) { m_evaluationResults.push_back(value); return *this; }
/**
* <p>The results of the simulation.</p>
*/
inline SimulateCustomPolicyResult& AddEvaluationResults(EvaluationResult&& value) { m_evaluationResults.push_back(value); return *this; }
/**
* <p>A flag that indicates whether there are more items to return. If your results
* were truncated, you can make a subsequent pagination request using the
* <code>Marker</code> request parameter to retrieve more items. Note that IAM
* might return fewer than the <code>MaxItems</code> number of results even when
* there are more results available. We recommend that you check
* <code>IsTruncated</code> after every call to ensure that you receive all of your
* results.</p>
*/
inline bool GetIsTruncated() const{ return m_isTruncated; }
/**
* <p>A flag that indicates whether there are more items to return. If your results
* were truncated, you can make a subsequent pagination request using the
* <code>Marker</code> request parameter to retrieve more items. Note that IAM
* might return fewer than the <code>MaxItems</code> number of results even when
* there are more results available. We recommend that you check
* <code>IsTruncated</code> after every call to ensure that you receive all of your
* results.</p>
*/
inline void SetIsTruncated(bool value) { m_isTruncated = value; }
/**
* <p>A flag that indicates whether there are more items to return. If your results
* were truncated, you can make a subsequent pagination request using the
* <code>Marker</code> request parameter to retrieve more items. Note that IAM
* might return fewer than the <code>MaxItems</code> number of results even when
* there are more results available. We recommend that you check
* <code>IsTruncated</code> after every call to ensure that you receive all of your
* results.</p>
*/
inline SimulateCustomPolicyResult& WithIsTruncated(bool value) { SetIsTruncated(value); return *this;}
/**
* <p>When <code>IsTruncated</code> is <code>true</code>, this element is present
* and contains the value to use for the <code>Marker</code> parameter in a
* subsequent pagination request.</p>
*/
inline const Aws::String& GetMarker() const{ return m_marker; }
/**
* <p>When <code>IsTruncated</code> is <code>true</code>, this element is present
* and contains the value to use for the <code>Marker</code> parameter in a
* subsequent pagination request.</p>
*/
inline void SetMarker(const Aws::String& value) { m_marker = value; }
/**
* <p>When <code>IsTruncated</code> is <code>true</code>, this element is present
* and contains the value to use for the <code>Marker</code> parameter in a
* subsequent pagination request.</p>
*/
inline void SetMarker(Aws::String&& value) { m_marker = value; }
/**
* <p>When <code>IsTruncated</code> is <code>true</code>, this element is present
* and contains the value to use for the <code>Marker</code> parameter in a
* subsequent pagination request.</p>
*/
inline void SetMarker(const char* value) { m_marker.assign(value); }
/**
* <p>When <code>IsTruncated</code> is <code>true</code>, this element is present
* and contains the value to use for the <code>Marker</code> parameter in a
* subsequent pagination request.</p>
*/
inline SimulateCustomPolicyResult& WithMarker(const Aws::String& value) { SetMarker(value); return *this;}
/**
* <p>When <code>IsTruncated</code> is <code>true</code>, this element is present
* and contains the value to use for the <code>Marker</code> parameter in a
* subsequent pagination request.</p>
*/
inline SimulateCustomPolicyResult& WithMarker(Aws::String&& value) { SetMarker(value); return *this;}
/**
* <p>When <code>IsTruncated</code> is <code>true</code>, this element is present
* and contains the value to use for the <code>Marker</code> parameter in a
* subsequent pagination request.</p>
*/
inline SimulateCustomPolicyResult& WithMarker(const char* value) { SetMarker(value); return *this;}
inline const ResponseMetadata& GetResponseMetadata() const{ return m_responseMetadata; }
inline void SetResponseMetadata(const ResponseMetadata& value) { m_responseMetadata = value; }
inline void SetResponseMetadata(ResponseMetadata&& value) { m_responseMetadata = value; }
inline SimulateCustomPolicyResult& WithResponseMetadata(const ResponseMetadata& value) { SetResponseMetadata(value); return *this;}
inline SimulateCustomPolicyResult& WithResponseMetadata(ResponseMetadata&& value) { SetResponseMetadata(value); return *this;}
private:
Aws::Vector<EvaluationResult> m_evaluationResults;
bool m_isTruncated;
Aws::String m_marker;
ResponseMetadata m_responseMetadata;
};
} // namespace Model
} // namespace IAM
} // namespace Aws | [
"[email protected]"
] | |
cf8ce03217a8db2e923a1ebe73598bc615e78346 | af0ecafb5428bd556d49575da2a72f6f80d3d14b | /CodeJamCrawler/dataset/12_21260_41.cpp | 4590bdea60f12a25bc1318d9bac02402b5add780 | [] | no_license | gbrlas/AVSP | 0a2a08be5661c1b4a2238e875b6cdc88b4ee0997 | e259090bf282694676b2568023745f9ffb6d73fd | refs/heads/master | 2021-06-16T22:25:41.585830 | 2017-06-09T06:32:01 | 2017-06-09T06:32:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,085 | cpp | #include <cstdio>
#include <cmath>
#include <cstring>
#include <cstdlib>
#include <ctime>
#include <cassert>
#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <list>
#include <complex>
#pragma comment(linker, "/STACK:266777216")
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef pair<int,int> PII;
typedef vector<PII> VPII;
typedef vector<double> VD;
typedef pair<double,double> PDD;
const int inf=1000000000;
const LL INF=LL(inf)*inf;
const double eps=1e-9;
const double PI=2*acos(0.0);
#define bit(n) (1<<(n))
#define bit64(n) ((LL(1))<<(n))
#define pb push_back
#define sz size()
#define mp make_pair
#define cl clear()
#define all(a) (a).begin(),(a).end()
#define fill(ar,val) memset((ar),(val),sizeof (ar))
#define MIN(a,b) {if((a)>(b)) (a)=(b);}
#define MAX(a,b) {if((a)<(b)) (a)=(b);}
#define sqr(x) ((x)*(x))
#define X first
#define Y second
clock_t start=clock();
#define N 2020
int n;
int x[N];
int y[N];
bool bad;
void rec(int L,int R,int a,LL b,int c) // y[i] < (a*i+b)/c, L<=i<R, y[R] fixed
{
VI q;
int i;
for(i=L;i<R;i=x[i])
q.pb(i);
if(i>R)
{
bad=true;
return;
}
int j=R;
for(int h=q.sz;h--;)
{
i=q[h];
y[i]=(LL(a)*i+b-1)/c;
a=y[j]-y[i];
b=LL(j)*y[i]-LL(i)*y[j];
c=j-i;
if(i+1<j)
{
rec(i+1,j,a,b,c);
if(bad) return;
}
j=i;
}
}
int main()
{
freopen("C1.in","r",stdin);
freopen("C1.out","w",stdout);
int TST,tst=0;
for(scanf("%d",&TST);TST--;)
{
printf("Case #%d: ",++tst);
fprintf(stderr,"Case #%d:\n",tst);
scanf("%d",&n);
int i;
for(i=0;i<n-1;i++)
{
scanf("%d",x+i);
x[i]--;
}
y[n-1]=inf;
bad=false;
rec(0,n-1,0,inf,1);
if(bad) puts("Impossible"); else
{
for(i=0;i<n;i++)
printf("%d%c",y[i],i<n-1?' ':'\n');
}
}
fprintf(stderr,"time=%.3lfsec\n",0.001*(clock()-start));
return 0;
}
| [
"[email protected]"
] | |
e9a4c47c2b8cea82be3a5d607e0cb552e8358962 | dbc9e357622efe93f62486918e1599ce075bdc57 | /基线库/源代码/frontend/app/commu/prediction.h | 7ef7d77a455228f58fa92da04a6e2e8d3bb90c03 | [] | no_license | zhangzwwww/medlab | 9f75de0ec38ed4d05536204dabc58b6f8c22c6ad | adf2558b60fa6de049bd19f4707b1896006478d8 | refs/heads/master | 2023-02-16T18:54:27.924289 | 2021-01-12T08:03:36 | 2021-01-12T08:03:36 | 296,562,827 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 589 | h | #ifndef PREDICTION_H
#define PREDICTION_H
#include <QString>
#include <QVector>
#include <QNetworkAccessManager>
#include <QObject>
#include <QDir>
#include <QDataStream>
#include <QJsonObject>
#include <QJsonDocument>
#include <QByteArray>
#include "communhttp.h"
#include "urlbase.h"
class prediction
{
private:
static QString token;
public:
prediction();
// set the token for communication
static void set_token(QString t);
// predict tumor class of an image
static QString predictTumor(communhttp* requester, QString filepath);
};
#endif // PREDICTION_H
| [
"[email protected]"
] | |
80cee832ae83847daec00952e835f06cdf9645b3 | e2379fed9cea223af969616593527efe97d2a11d | /system/dev/ethernet/aml-dwmac/aml-dwmac.h | 321dfca32300607c718194cf6b4e4543207db8c8 | [
"BSD-3-Clause",
"MIT"
] | permissive | PeikanTsai/zircon | c6bb6977729de9ba536add9d488eb33688505be0 | 6b397a66c8a36b7d4488a8c965b518145942fe11 | refs/heads/master | 2020-03-17T21:47:36.529721 | 2018-09-01T00:12:50 | 2018-09-01T01:55:39 | 133,975,894 | 0 | 0 | null | 2018-05-18T15:58:41 | 2018-05-18T15:58:41 | null | UTF-8 | C++ | false | false | 5,393 | h | // Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#pragma once
#include <threads.h>
#include <ddk/device.h>
#include <ddk/io-buffer.h>
#include <ddk/protocol/gpio.h>
#include <ddk/protocol/test.h>
#include <ddktl/device.h>
#include <ddktl/protocol/ethernet.h>
#include <ddktl/protocol/test.h>
#include <fbl/mutex.h>
#include <fbl/unique_ptr.h>
#include <lib/zx/interrupt.h>
#include <lib/zx/vmo.h>
#include <zircon/compiler.h>
#include <zircon/types.h>
#include "pinned-buffer.h"
// clang-format off
typedef volatile struct dw_mac_regs {
uint32_t conf; /*0 0x00 */
uint32_t framefilt; /*1 0x04 */
uint32_t hashtablehigh; /*2 0x08 */
uint32_t hashtablelow; /*3 0x0c */
uint32_t miiaddr; /*4 0x10 */
uint32_t miidata; /*5 0x14 */
uint32_t flowcontrol; /*6 0x18 */
uint32_t vlantag; /*7 0x1c */
uint32_t version; /*8 0x20 */
uint32_t reserved_1[5]; /*9 - 13 */
uint32_t intreg; /*14 0x38 */
uint32_t intmask; /*15 0x3c */
uint32_t macaddr0hi; /*16 0x40 */
uint32_t macaddr0lo; /*17 0x44 */
uint32_t macaddr1hi; /*18 0x48 */
uint32_t macaddr1lo; /*19 0x4c */
uint32_t reserved_2[34]; /*18 - 53 */
uint32_t rgmiistatus; /*54 0xd8 */
} __PACKED dw_mac_regs_t;
// Offset of DMA regs into dwmac register block
#define DW_DMA_BASE_OFFSET (0x1000)
typedef volatile struct dw_dma_regs {
uint32_t busmode; /*0 0x00 */
uint32_t txpolldemand; /*1 0x04 */
uint32_t rxpolldemand; /*2 0x08 */
uint32_t rxdesclistaddr; /*3 0x0c */
uint32_t txdesclistaddr; /*4 0x10 */
uint32_t status; /*5 0x14 */
uint32_t opmode; /*6 0x18 */
uint32_t intenable; /*7 0x1c */
uint32_t missedframes; /*8 0x20 */
uint32_t rxwdt; /*9 0x24 */
uint32_t axibusmode; /*10 0x28 */
uint32_t axistatus; /*11 0x2c */
uint32_t reserved[6];
uint32_t currhosttxdesc; /*18 0x48 */
uint32_t currhostrxdesc; /*19 0x4c */
uint32_t currhosttxbuffaddr; /*20 0x50 */
uint32_t currhostrxbuffaddr; /*21 0x54 */
uint32_t hwfeature; /*22 0x58 */
} __PACKED dw_dma_regs_t;
//DMA transaction descriptors
typedef volatile struct dw_dmadescr {
uint32_t txrx_status;
uint32_t dmamac_cntl;
uint32_t dmamac_addr;
uint32_t dmamac_next;
} __ALIGNED(64) dw_dmadescr_t;
// clang-format on
namespace eth {
class AmlDWMacDevice : public ddk::Device<AmlDWMacDevice, ddk::Unbindable>,
public ddk::EthmacProtocol<AmlDWMacDevice> {
public:
AmlDWMacDevice(zx_device_t* device);
static zx_status_t Create(zx_device_t* device);
void DdkRelease();
void DdkUnbind();
zx_status_t EthmacQuery(uint32_t options, ethmac_info_t* info);
void EthmacStop() __TA_EXCLUDES(lock_);
zx_status_t EthmacStart(fbl::unique_ptr<ddk::EthmacIfcProxy> proxy) __TA_EXCLUDES(lock_);
zx_status_t EthmacQueueTx(uint32_t options, ethmac_netbuf_t* netbuf) __TA_EXCLUDES(lock_);
zx_status_t EthmacSetParam(uint32_t param, int32_t value, void* data);
zx_status_t MDIOWrite(uint32_t reg, uint32_t val);
zx_status_t MDIORead(uint32_t reg, uint32_t* val);
zx_handle_t EthmacGetBti();
private:
zx_status_t InitBuffers();
zx_status_t InitDevice();
zx_status_t DeInitDevice() __TA_REQUIRES(lock_);
zx_status_t InitPdev();
zx_status_t ShutDown() __TA_EXCLUDES(lock_);
void UpdateLinkStatus() __TA_REQUIRES(lock_);
void DumpRegisters();
void ReleaseBuffers();
void ProcRxBuffer(uint32_t int_status) __TA_EXCLUDES(lock_);
uint32_t DmaRxStatus();
void ResetPhy();
void ConfigPhy();
int Thread() __TA_EXCLUDES(lock_);
zx_status_t GetMAC(uint8_t* addr);
//Number each of tx/rx transaction descriptors
static constexpr uint32_t kNumDesc = 32;
//Size of each transaction buffer
static constexpr uint32_t kTxnBufSize = 2048;
dw_dmadescr_t* tx_descriptors_ = nullptr;
dw_dmadescr_t* rx_descriptors_ = nullptr;
fbl::RefPtr<PinnedBuffer> txn_buffer_;
fbl::RefPtr<PinnedBuffer> desc_buffer_;
uint8_t* tx_buffer_ = nullptr;
uint32_t curr_tx_buf_ = 0;
uint8_t* rx_buffer_ = nullptr;
uint32_t curr_rx_buf_ = 0;
// designware mac options
uint32_t options_ = 0;
// ethermac fields
uint32_t features_ = 0;
uint32_t mtu_ = 0;
uint8_t mac_[6] = {};
uint16_t mii_addr_ = 0;
zx::bti bti_;
zx::interrupt dma_irq_;
platform_device_protocol_t pdev_;
io_buffer_t periph_regs_iobuff_;
io_buffer_t hhi_regs_iobuff_;
io_buffer_t dwmac_regs_iobuff_;
dw_mac_regs_t* dwmac_regs_ = nullptr;
dw_dma_regs_t* dwdma_regs_ = nullptr;
gpio_protocol_t gpio_;
fbl::Mutex lock_;
fbl::unique_ptr<ddk::EthmacIfcProxy> ethmac_proxy_ __TA_GUARDED(lock_);
// Only accessed from Thread, so not locked.
bool online_ = false;
//statistics
uint32_t bus_errors_;
uint32_t tx_counter_ = 0;
uint32_t rx_packet_ = 0;
uint32_t loop_count_ = 0;
fbl::atomic<bool> running_;
thrd_t thread_;
};
} // namespace eth
| [
"[email protected]"
] | |
45b5a1d115cc6017269812a62047507f6b7d3708 | 88e7559cb127a916f8ede3e05a63cdabc1b6889e | /OpenGL_Engine/OpenGL_Engine/Mesh.h | bdab4bd19f27464a2af8c9de38e89baf8bd4cd7e | [] | no_license | BrentKingma/FirstGraphisEngine | 279ed65961c442415e96b47fccd72db684c0544e | 8aeea41ca086b19df2d22f19f2a7e1073fc8fd75 | refs/heads/master | 2020-03-17T04:44:42.893514 | 2018-06-20T00:27:22 | 2018-06-20T00:27:22 | 133,287,227 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 440 | h | #pragma once
#include <glm\glm.hpp>
class Mesh
{
public:
Mesh();
virtual ~Mesh();
struct Vertex
{
glm::vec4 m_position;
glm::vec4 m_normal;
glm::vec2 m_texCoord;
};
void initialiseQuad();
void initialise(unsigned int a_vertexCount, const Vertex* a_vertices, unsigned int a_indexCount = 0, unsigned int* a_indices = nullptr);
virtual void draw();
protected:
unsigned int triCount = 0;
unsigned int vao, vbo, ibo = 0;
};
| [
"[email protected]"
] | |
3ac38c4c12fa61986acf1dfdc867d74d411b6471 | b4df5647122716aac1e4e4a52887ce9df490b971 | /sources/Gateway/SettingsDialog.hpp | 19199ec04a9819530a5cf1f1b3987abc624bf727 | [] | no_license | palchukovsky/takion-bridge | 05ba2332f70e63d80ece8de381823c6def878b3f | 6656cb5184c0027c871ed0a67f186304abe436f8 | refs/heads/master | 2022-11-14T20:21:06.836723 | 2020-07-07T18:58:36 | 2020-07-07T18:58:36 | 277,354,182 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,239 | hpp | /**************************************************************************
* Created: 2013/04/18 23:47:12
* Author: Eugene V. Palchukovsky
* E-mail: [email protected]
* -------------------------------------------------------------------
* Project: Takion Bridge
**************************************************************************/
#pragma once
namespace TakionBridge { namespace Gateway {
class SettingDialog
: public TakionSettingPageBase,
public Observer {
public:
explicit SettingDialog(
TakionMainWnd *mainWnd,
TakionSettingTabDialog *parentTab);
public:
virtual HWND GetFirstTabControl();
virtual void UpdateSettings();
virtual void UpdateControls();
virtual void Leaving();
protected:
void UpdateConnections();
void UpdateConnection(const Connection* connection, bool isConnected);
virtual void DoDataExchange(CDataExchange* dx);
virtual BOOL OnInitDialog();
virtual void BeforeDestroy();
virtual void Notify(
const Message* message,
Observable* from,
const Message* info);
protected:
afx_msg HBRUSH OnCtlColor(CDC* dC, CWnd* wnd, UINT ctlColor);
afx_msg void OnSelchangeConnection();
DECLARE_MESSAGE_MAP()
private:
};
} }
| [
"[email protected]"
] | |
29cbfa85a67f62e3699a2a2d7383d64380878752 | d0fb46aecc3b69983e7f6244331a81dff42d9595 | /foas/include/alibabacloud/foas/model/GetInstanceCheckpointResult.h | e5ab093bbda4e73c5f4ecca4d82db9be41ddb2fc | [
"Apache-2.0"
] | permissive | aliyun/aliyun-openapi-cpp-sdk | 3d8d051d44ad00753a429817dd03957614c0c66a | e862bd03c844bcb7ccaa90571bceaa2802c7f135 | refs/heads/master | 2023-08-29T11:54:00.525102 | 2023-08-29T03:32:48 | 2023-08-29T03:32:48 | 115,379,460 | 104 | 82 | NOASSERTION | 2023-09-14T06:13:33 | 2017-12-26T02:53:27 | C++ | UTF-8 | C++ | false | false | 1,429 | h | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ALIBABACLOUD_FOAS_MODEL_GETINSTANCECHECKPOINTRESULT_H_
#define ALIBABACLOUD_FOAS_MODEL_GETINSTANCECHECKPOINTRESULT_H_
#include <string>
#include <vector>
#include <utility>
#include <alibabacloud/core/ServiceResult.h>
#include <alibabacloud/foas/FoasExport.h>
namespace AlibabaCloud
{
namespace Foas
{
namespace Model
{
class ALIBABACLOUD_FOAS_EXPORT GetInstanceCheckpointResult : public ServiceResult
{
public:
GetInstanceCheckpointResult();
explicit GetInstanceCheckpointResult(const std::string &payload);
~GetInstanceCheckpointResult();
std::string getCheckpoints()const;
protected:
void parse(const std::string &payload);
private:
std::string checkpoints_;
};
}
}
}
#endif // !ALIBABACLOUD_FOAS_MODEL_GETINSTANCECHECKPOINTRESULT_H_ | [
"[email protected]"
] | |
89de69eb36d23511c3b057e5d42fab2d07aff1d6 | 34b6e001c6bed62386250609a708790a5ec19d85 | /Stack/Redundant Brackets.cpp | 40f182bdbb3f1e9a2c8f2aed04b66fce88803661 | [] | no_license | alkamaazmi/Data-Structures-and-Algorithms | 339b3420ee947cd1ed62147210a9d810f4fb23ee | 059cbda5f39b59ac7bab07f156e0ea4fe1a6a703 | refs/heads/main | 2023-04-28T04:32:27.598565 | 2023-04-20T16:35:05 | 2023-04-20T16:35:05 | 329,375,922 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 861 | cpp | /*
* Redundant Brackets
* Given a string A denoting an expression. It contains the following operators '+', '-', '*', '/'.
* A set of parenthesis are redundant if the same sub-expression is surrounded by unnecessary or multiple brackets.
* Chech whether A has redundant braces or not.
* A will be always a valid expression.
*/
bool findRedundantBrackets(string &s)
{
int n=s.length();
stack<char> st;
for( int i=0;i<n;i++){
if(s[i]=='('||s[i]=='+'||s[i]=='-'||s[i]=='*'||s[i]=='/'){
st.push(s[i]);
}else if(s[i]==')'){
if(st.top()=='('){
return true;
}
else{
while(st.top()!='('){
st.pop();
}
st.pop();
}
}else{
continue;
}
}
return false;
}
| [
"[email protected]"
] | |
533cdf8243cbe759cf7339a5a73f753e5c770f03 | 47c42583c9375eae6b7bef66e6b23692e5312afd | /test_C_sharp/Cee_dll_test/Cee_dll_test/MathFunctions.h | 7db296d1b02c386dc62311f4828725c5555b3e67 | [] | no_license | stevesmth429/TestProject | 8a4a965a5f1141877eb7e938fe35b9cb327b7079 | 4a33f4019105b87e4fa17492fb8fd097c633a339 | refs/heads/master | 2020-03-26T18:29:56.701928 | 2018-08-25T20:16:42 | 2018-08-25T20:16:42 | 145,216,081 | 0 | 0 | null | 2018-08-25T20:16:42 | 2018-08-18T11:53:28 | C++ | UTF-8 | C++ | false | false | 232 | h | #pragma once
#include <stdexcept>
using namespace std;
class MyMathFuncs
{
public:
double Add(double a, double b);
double Subtract(double a, double b);
double Multiply(double a, double b);
double Divide(double a, double b);
}; | [
"[email protected]"
] | |
a2d2e84e42ff309702cc2181e0ed2be2214ae20e | c3e4cf2b4918b81ac895954ccbea72cf7992cbd5 | /hackerearth/contests/easy/one_string_no_trouble.cpp | 0e86bab8112876f6fbddeb8ec3eff42863dd47b0 | [] | no_license | championballer/PlacementPrep | 4bdce3f04dd7d576b4d838788798150a5c8a490f | e0a2aabff5423a66fb67bfb9e632022967266abc | refs/heads/master | 2020-04-05T17:40:34.758609 | 2019-12-08T06:16:43 | 2019-12-08T06:16:43 | 157,071,075 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 491 | cpp |
#include<bits/stdc++.h>
using namespace std;
int main()
{
string in;
cin>>in;
int mx = 1;
char prev = in[0];
int current_length = 1;
for(int i=1;i<in.length();i++)
{
if(in[i]!=prev)
{
current_length++;
if(current_length>mx)mx = current_length;
prev = in[i];
}
else
{
current_length=1;
prev = in[i];
}
}
cout<<mx<<endl;
} | [
"[email protected]"
] | |
112c3616b3cb6c675f88b9b52d773cd69f4f25c9 | 388779928a49328f53753b004dbd9040b6fac9a4 | /sketch_may16a/sketch_may16a.ino | 5235884103a8017240eedc53e49e7c5e20016e15 | [] | no_license | svollmer9/arduino-humidity-sensor | eed43a8d3bb7d896ba536d04ea69c3d90dda3ee7 | 91d256d4ab47636c5b4588d26a94b2a39d2ef487 | refs/heads/master | 2021-01-16T20:42:29.057362 | 2016-06-03T06:29:18 | 2016-06-03T06:29:18 | 60,323,166 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,077 | ino | #include <Wire.h>
int address1 = 0x27; //decimal address of sensor 1
unsigned long reading = 0;
float output = 0;
void setup() {
Serial.begin(9600);
Wire.begin(); // create a wire object
pinMode(SDA, INPUT);
pinMode(SCL, INPUT);
}
void loop() {
read_hum(address1);
}
int read_hum(int address) {
Wire.beginTransmission(address); // transmit to device #66
Wire.write(byte(255)); // sets register pointer to echo #1 register
Wire.endTransmission(); // stop transmitting
// step 4: request reading from sensor
Wire.requestFrom(address, 2); // request 2 bytes from slave device #112
// step 5: receive reading from sensor
if(2 <= Wire.available()) // if two bytes were received
{
reading = Wire.read(); // receive high byte (overwrites previous reading)
reading = reading << 6; // shift high byte to be high 8 bits
reading |= Wire.read(); // receive low byte as lower 8 bits
output = reading;
output = output*200/16382;
Serial.print(output); // print the reading
Serial.println(",");
}
delay(1000);
}
| [
"[email protected]"
] | |
b5b07b4c0ed9dc940b2800ee3c46ae4e6e192147 | 5456502f97627278cbd6e16d002d50f1de3da7bb | /chrome/browser/sync/test/integration/performance/extensions_sync_perf_test.cc | ef67c8370e4dfe04788f009a8bb0472a9d1329fe | [
"BSD-3-Clause"
] | permissive | TrellixVulnTeam/Chromium_7C66 | 72d108a413909eb3bd36c73a6c2f98de1573b6e5 | c8649ab2a0f5a747369ed50351209a42f59672ee | refs/heads/master | 2023-03-16T12:51:40.231959 | 2017-12-20T10:38:26 | 2017-12-20T10:38:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,933 | 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/macros.h"
#include "base/strings/stringprintf.h"
#include "chrome/browser/sync/test/integration/extensions_helper.h"
#include "chrome/browser/sync/test/integration/performance/sync_timing_helper.h"
#include "chrome/browser/sync/test/integration/profile_sync_service_harness.h"
#include "chrome/browser/sync/test/integration/sync_test.h"
using extensions_helper::AllProfilesHaveSameExtensions;
using extensions_helper::AllProfilesHaveSameExtensionsAsVerifier;
using extensions_helper::DisableExtension;
using extensions_helper::EnableExtension;
using extensions_helper::GetInstalledExtensions;
using extensions_helper::InstallExtension;
using extensions_helper::InstallExtensionsPendingForSync;
using extensions_helper::IsExtensionEnabled;
using extensions_helper::UninstallExtension;
using sync_timing_helper::PrintResult;
using sync_timing_helper::TimeMutualSyncCycle;
// TODO(braffert): Replicate these tests for apps.
static const int kNumExtensions = 150;
class ExtensionsSyncPerfTest : public SyncTest {
public:
ExtensionsSyncPerfTest()
: SyncTest(TWO_CLIENT),
extension_number_(0) {}
// Adds |num_extensions| new unique extensions to |profile|.
void AddExtensions(int profile, int num_extensions);
// Updates the enabled/disabled state for all extensions in |profile|.
void UpdateExtensions(int profile);
// Uninstalls all currently installed extensions from |profile|.
void RemoveExtensions(int profile);
// Returns the number of currently installed extensions for |profile|.
int GetExtensionCount(int profile);
private:
int extension_number_;
DISALLOW_COPY_AND_ASSIGN(ExtensionsSyncPerfTest);
};
void ExtensionsSyncPerfTest::AddExtensions(int profile, int num_extensions) {
for (int i = 0; i < num_extensions; ++i) {
InstallExtension(GetProfile(profile), extension_number_++);
}
}
void ExtensionsSyncPerfTest::UpdateExtensions(int profile) {
std::vector<int> extensions = GetInstalledExtensions(GetProfile(profile));
for (std::vector<int>::iterator it = extensions.begin();
it != extensions.end(); ++it) {
if (IsExtensionEnabled(GetProfile(profile), *it)) {
DisableExtension(GetProfile(profile), *it);
} else {
EnableExtension(GetProfile(profile), *it);
}
}
}
int ExtensionsSyncPerfTest::GetExtensionCount(int profile) {
return GetInstalledExtensions(GetProfile(profile)).size();
}
void ExtensionsSyncPerfTest::RemoveExtensions(int profile) {
std::vector<int> extensions = GetInstalledExtensions(GetProfile(profile));
for (std::vector<int>::iterator it = extensions.begin();
it != extensions.end(); ++it) {
UninstallExtension(GetProfile(profile), *it);
}
}
IN_PROC_BROWSER_TEST_F(ExtensionsSyncPerfTest, P0) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
int num_default_extensions = GetExtensionCount(0);
int expected_extension_count = num_default_extensions + kNumExtensions;
// TCM ID - 7563874.
AddExtensions(0, kNumExtensions);
base::TimeDelta dt = TimeMutualSyncCycle(GetClient(0), GetClient(1));
InstallExtensionsPendingForSync(GetProfile(1));
ASSERT_EQ(expected_extension_count, GetExtensionCount(1));
PrintResult("extensions", "add_extensions", dt);
// TCM ID - 7655397.
UpdateExtensions(0);
dt = TimeMutualSyncCycle(GetClient(0), GetClient(1));
ASSERT_EQ(expected_extension_count, GetExtensionCount(1));
PrintResult("extensions", "update_extensions", dt);
// TCM ID - 7567721.
RemoveExtensions(0);
dt = TimeMutualSyncCycle(GetClient(0), GetClient(1));
ASSERT_EQ(num_default_extensions, GetExtensionCount(1));
PrintResult("extensions", "delete_extensions", dt);
}
| [
"[email protected]"
] | |
e06b435057fe237912a74feb978ce10055ab1759 | 938e4888840de783c74cd6bcf0a44443472054dd | /gammacombo/include/PDF_GLWADS_Dpi_K3pi_Dmix.h | d3e9003f23a2b9e58fff33d9baee1fcc208ba950 | [] | no_license | ppodolsky/pygammacombo | 1922fb541a8d48f3b08558c1552053e2cf6017cd | fa52d2cda49694de36deb13e235f4e0801fd0fe5 | refs/heads/master | 2021-01-14T08:57:06.796747 | 2016-02-14T05:39:59 | 2016-02-14T05:39:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 784 | h | /**
* Gamma Combination
* Author: Till Moritz Karbach, [email protected]
* Date: August 2012
*
* Change to equations that consider D mixing.
*
**/
#ifndef PDF_GLWADS_Dpi_K3pi_Dmix_h
#define PDF_GLWADS_Dpi_K3pi_Dmix_h
#include "PDF_GLWADS_Dpi_K3pi.h"
#include "RooGLWADSDmixAcpVar.h"
#include "RooGLWADSDmixRpmVar.h"
#include "ParametersGammaCombo.h"
using namespace RooFit;
using namespace std;
using namespace Utils;
class PDF_GLWADS_Dpi_K3pi_Dmix : public PDF_GLWADS_Dpi_K3pi
{
public:
PDF_GLWADS_Dpi_K3pi_Dmix(config cObs=lumi1fb, config cErr=lumi1fb, config cCor=lumi1fb,
double Mxy=0, ParametersAbs* pars=0, TString d=".");
~PDF_GLWADS_Dpi_K3pi_Dmix();
void initParameters();
void initRelations();
private:
double _Mxy;
};
#endif
| [
"[email protected]"
] | |
ec5c740c4c1ee1843894d7123b0c0d6c7dd05650 | fc50a70aa8fddeeaff3074816b66e13b1637a1cc | /PersonDetection/src/seguimiento.cpp | a61344ad3d8ffd5503d66ddfef21792e6f9ae41c | [] | no_license | silverboy/PersonDetection | caf789d47a6d23e5b3a68fb0677c65950ef449ad | c83934b2a509404ae17ff9170e168b6d47cf28d0 | refs/heads/master | 2021-03-13T00:01:20.066778 | 2013-07-17T13:22:59 | 2013-07-17T13:22:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,132 | cpp | #include "seguimiento.h"
Cluster::Cluster(clusterType type, int index_inicio):
type(type),
index_inicio(index_inicio) {}
int Cluster::getIndex_inicio()
{
return index_inicio;
}
int Cluster::getNumPoint()
{
return n_point;
}
ArPose Cluster::getPoint()
{
return centro;
}
void Cluster::incrementar_puntos()
{
n_point++;
}
Seguimiento::Seguimiento()
{
pthread_mutex_init(&mutex,NULL);
//ctor
}
Seguimiento::~Seguimiento()
{
//dtor
}
void Seguimiento::calcularVariaciones(vector<double> distancias,vector<ArPoseWithTime> medidas)
{
if(distancias_ant.empty())
{
distancias_ant=distancias;
medidas_ant=medidas;
}
else
{
if(distancias.size() == distancias_ant.size())
{
pthread_mutex_lock(&mutex);
variaciones_dist.clear();
for(unsigned int i=0; i < distancias.size(); i++)
{
variaciones_dist.push_back(ArMath::fabs(distancias[i]-distancias_ant[i]));
}
pthread_mutex_unlock(&mutex);
variaciones_minimizadas=minimization(variaciones_dist,3);
}
else{
ArLog::log(ArLog::Normal ,"Warning: vector medidas distinto tamaño, variaciiones no calculadas\n");
}
}
}
void Seguimiento::actualizarMedidas(vector<double> distancias,vector<ArPoseWithTime> medidas){
distancias_ant=distancias;
medidas_ant=medidas;
}
void Seguimiento::printVariaciones(vector<ArPoseWithTime> medidas,ArPose goalPose)
{
pthread_mutex_lock(&mutex);
for(unsigned int i=0; i < variaciones_dist.size(); i++ )
{
sprintf(logBuffer, "Angulo anterior:%.2f actual:%.2f v:%.1f v_m:%.1f d_gP:%0.1f",medidas_ant[i].getTh(),
medidas[i].getTh(),variaciones_dist[i],variaciones_minimizadas[i],goalPose.findDistanceTo(medidas[i]));
ArLog::log(ArLog::Normal ,logBuffer);
}
pthread_mutex_unlock(&mutex);
}
void Seguimiento::agrupar()
{
// Vaciamos vector con los grupos
grupos.clear();
double a(100),b(1000),umbral(50);
// Minimo de puntos para considerar cluster
int min_n_point(3),n_point(0),index_inicio;
for(unsigned int i=0; i < variaciones_dist.size(); i++)
{
if(ArMath::fabs(variaciones_dist[i])>a && ArMath::fabs(variaciones_dist[i])<b)
{
if(n_point==0)
{
// Comienzo cluster
index_inicio=i;
n_point++;
}
else
{
//Hay un cluster comenzado, compruebo si pertenezco a el
if(ArMath::fabs(variaciones_dist[i]-variaciones_dist[i-1]) < umbral )
{
n_point++;
}
else
{
// Cierro el cluster actual y
}
}
}
}
}
bool Seguimiento::calcularGlobalPerception(vector<double> distancias, vector<ArPoseWithTime> medidas,double robotAngle ){
bool percepcion=false;
double d_max(4000),d_min(0),angle,mod,x(0),y(0);
double angleRange(30),sensorAngle;
globalPerception.clear();
globalPerceptionAngle.clear();
for(unsigned int i=0; i < distancias.size(); i++){
angle=medidas[i].getTh();
sensorAngle=ArMath::fabs(ArMath::subAngle(angle,robotAngle));
if(distancias[i] <= d_min && sensorAngle <= angleRange ){
globalPerception.push_back(1);
globalPerceptionAngle.push_back(angle);
x+=ArMath::cos(angle);
y+=ArMath::sin(angle);
}
else if(distancias[i] < d_max && sensorAngle <= angleRange){
mod=(d_max-distancias[i])/(d_max-d_min);
globalPerception.push_back(mod);
globalPerceptionAngle.push_back(angle);
x+=ArMath::cos(angle)*mod;
y+=ArMath::sin(angle)*mod;
}
}
if(!globalPerception.empty()){
ArPose origen(0,0,0);
goalAngle=origen.findAngleTo(ArPose(x,y,0));
percepcion=true;
}
return percepcion;
}
bool Seguimiento::calcularVariacionGlobalPerception(vector<ArPoseWithTime> medidas,double robotAngle,ArPose goalPose ){
bool percepcion=false;
double vd_max(200),vd_min(50),angle,mod,x(0),y(0),vd,goalDistance,factor;
double angleRange(180),sensorAngle;
variaciones_dist=variaciones_minimizadas;
globalPerception.clear();
globalPerceptionAngle.clear();
if(variaciones_dist.size() != medidas.size()){
ArLog::log(ArLog::Normal ,"Warning: No se pudo calcular variacion de global"
"perception, distinto tamaño vectores\n");
return percepcion;
}
for(unsigned int i=0; i < variaciones_dist.size(); i++){
angle=medidas[i].getTh();
goalDistance=goalPose.findDistanceTo(medidas[i]);
factor=calcularFactor(goalDistance);
//factor=1;
sensorAngle=ArMath::fabs(ArMath::subAngle(angle,robotAngle));
vd=ArMath::fabs(variaciones_dist[i]);
if(vd >= vd_max && sensorAngle <= angleRange && factor > 0){
globalPerception.push_back(1*factor);
globalPerceptionAngle.push_back(angle);
x+=ArMath::cos(angle)*factor;
y+=ArMath::sin(angle)*factor;
}
else if(vd > vd_min && sensorAngle <= angleRange && factor > 0){
mod=(vd - vd_min)/(vd_max-vd_min);
globalPerception.push_back(mod*factor);
globalPerceptionAngle.push_back(angle);
x+=ArMath::cos(angle)*mod*factor;
y+=ArMath::sin(angle)*mod*factor;
}
}
if(!globalPerception.empty()){
ArPose origen(0,0,0);
goalAngle=origen.findAngleTo(ArPose(x,y,0));
percepcion=true;
}
return percepcion;
}
double Seguimiento::calcularFactor(double distancia){
double d_max(800),factor;
if( distancia > d_max){
factor=0;
}
else{
factor=1 - distancia/d_max;
}
return factor;
}
void Seguimiento::printGlobalPerception(){
for(unsigned int i=0; i < globalPerception.size();i++){
sprintf(logBuffer, "Distancia: %f Angulo: %f\n",globalPerception[i],globalPerceptionAngle[i]);
ArLog::log(ArLog::Normal ,logBuffer);
}
}
double Seguimiento::getGoalAngle(){
return goalAngle;
}
template <class T> vector<T> Seguimiento::minimization(vector<T> v, int ventana)
{
vector<T> resultado;
int inicio,fin,media_ventana((ventana-1)/2),n(v.size());
T minimo;
for(int i=0; i < n; i++)
{
if(i < n - media_ventana)
{
inicio=max(0 , i - media_ventana);
fin=inicio + ventana - 1;
}
else
{
fin=min(n-1 , i + media_ventana);
inicio=fin - ventana + 1;
}
minimo=10000;
for(int j=inicio; j <= fin; j++ )
{
if(ArMath::fabs(v[j]) < ArMath::fabs(minimo))
{
minimo=v[j];
}
}
resultado.push_back(minimo);
}
return resultado;
}
| [
"[email protected]"
] | |
ba5435057e008840f7c637e1d01fae34bb1dcbbb | da72d7ffe4d158b226e3b3d9aabe900d0d232394 | /libc/test/src/__support/CPP/atomic_test.cpp | 548470f347999fc2aafb093117e914051c947b74 | [
"Apache-2.0",
"LLVM-exception",
"NCSA"
] | permissive | ddcc/llvm-project | 19eb04c2de679abaa10321cc0b7eab1ff4465485 | 9376ccc31a29f2b3f3b33d6e907599e8dd3b1503 | refs/heads/next | 2023-03-20T13:20:42.024563 | 2022-08-05T20:02:46 | 2022-08-05T19:14:06 | 225,963,333 | 0 | 0 | Apache-2.0 | 2021-08-12T21:45:43 | 2019-12-04T21:49:26 | C++ | UTF-8 | C++ | false | false | 1,117 | cpp | //===-- Unittests for Atomic ----------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "src/__support/CPP/atomic.h"
#include "utils/UnitTest/Test.h"
// Tests in this file do not test atomicity as it would require using
// threads, at which point it becomes a chicken and egg problem.
TEST(LlvmLibcAtomicTest, LoadStore) {
__llvm_libc::cpp::Atomic<int> aint(123);
ASSERT_EQ(aint.load(), 123);
aint.store(100);
ASSERT_EQ(aint.load(), 100);
aint = 1234; // Equivalent of store
ASSERT_EQ(aint.load(), 1234);
}
TEST(LlvmLibcAtomicTest, CompareExchangeStrong) {
int desired = 123;
__llvm_libc::cpp::Atomic<int> aint(desired);
ASSERT_TRUE(aint.compare_exchange_strong(desired, 100));
ASSERT_EQ(aint.load(), 100);
ASSERT_FALSE(aint.compare_exchange_strong(desired, 100));
ASSERT_EQ(aint.load(), 100);
}
| [
"[email protected]"
] | |
4e45990e3a6b79a36372ab704270e0b14ad5779e | b0da51354ec662292efe2339988545f4737a9553 | /code/extlibs/tinyxml/tinyxml.cc | 7286469a93cc2c8252fc6f6de998ae2767673944 | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] | permissive | Core-Game-Project-2016/nebula-trifid | 9a49d7ae5d896a28e11805ba1404b743add2e9d6 | 2f1b1d6986a049b4d133d65bef6c0aeb674e1a94 | refs/heads/master | 2021-01-22T00:29:10.314856 | 2016-05-27T23:05:01 | 2016-05-27T23:05:01 | 55,078,691 | 0 | 1 | null | 2016-05-20T15:32:12 | 2016-03-30T16:23:52 | C++ | UTF-8 | C++ | false | false | 34,036 | cc | /*
www.sourceforge.net/projects/tinyxml
Original code (2.0 and earlier )copyright (c) 2000-2002 Lee Thomason (www.grinninglizard.com)
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#include "stdneb.h"
#include <ctype.h>
#include "tinyxml.h"
#ifdef TIXML_USE_STL
#include <sstream>
#include <iostream>
#endif
bool TiXmlBase::condenseWhiteSpace = true;
void TiXmlBase::PutString( const TIXML_STRING& str, TIXML_OSTREAM* stream )
{
TIXML_STRING buffer;
PutString( str, &buffer );
(*stream) << buffer;
}
void TiXmlBase::PutString( const TIXML_STRING& str, TIXML_STRING* outString )
{
int i=0;
while( i<(int)str.length() )
{
unsigned char c = (unsigned char) str[i];
if ( c == '&'
&& i < ( (int)str.length() - 2 )
&& str[i+1] == '#'
&& str[i+2] == 'x' )
{
// Hexadecimal character reference.
// Pass through unchanged.
// © -- copyright symbol, for example.
//
// The -1 is a bug fix from Rob Laveaux. It keeps
// an overflow from happening if there is no ';'.
// There are actually 2 ways to exit this loop -
// while fails (error case) and break (semicolon found).
// However, there is no mechanism (currently) for
// this function to return an error.
while ( i<(int)str.length()-1 )
{
outString->append( str.c_str() + i, 1 );
++i;
if ( str[i] == ';' )
break;
}
}
else if ( c == '&' )
{
outString->append( entity[0].str, entity[0].strLength );
++i;
}
else if ( c == '<' )
{
outString->append( entity[1].str, entity[1].strLength );
++i;
}
else if ( c == '>' )
{
outString->append( entity[2].str, entity[2].strLength );
++i;
}
else if ( c == '\"' )
{
outString->append( entity[3].str, entity[3].strLength );
++i;
}
else if ( c == '\'' )
{
outString->append( entity[4].str, entity[4].strLength );
++i;
}
else if ( c < 32 )
{
// Easy pass at non-alpha/numeric/symbol
// Below 32 is symbolic.
char buf[ 32 ];
#if defined(TIXML_SNPRINTF)
TIXML_SNPRINTF( buf, sizeof(buf), "&#x%02X;", (unsigned) ( c & 0xff ) );
#else
sprintf( buf, "&#x%02X;", (unsigned) ( c & 0xff ) );
#endif
//*ME: warning C4267: convert 'size_t' to 'int'
//*ME: Int-Cast to make compiler happy ...
outString->append( buf, (int)strlen( buf ) );
++i;
}
else
{
//char realc = (char) c;
//outString->append( &realc, 1 );
*outString += (char) c; // somewhat more efficient function call.
++i;
}
}
}
// <-- Strange class for a bug fix. Search for STL_STRING_BUG
TiXmlBase::StringToBuffer::StringToBuffer( const TIXML_STRING& str )
{
buffer = new char[ str.length()+1 ];
if ( buffer )
{
strcpy( buffer, str.c_str() );
}
}
TiXmlBase::StringToBuffer::~StringToBuffer()
{
delete [] buffer;
}
// End strange bug fix. -->
TiXmlNode::TiXmlNode( NodeType _type ) : TiXmlBase()
{
parent = 0;
type = _type;
firstChild = 0;
lastChild = 0;
prev = 0;
next = 0;
}
TiXmlNode::~TiXmlNode()
{
TiXmlNode* node = firstChild;
TiXmlNode* temp = 0;
while ( node )
{
temp = node;
node = node->next;
delete temp;
}
}
void TiXmlNode::CopyTo( TiXmlNode* target ) const
{
target->SetValue (value.c_str() );
target->userData = userData;
}
void TiXmlNode::Clear()
{
TiXmlNode* node = firstChild;
TiXmlNode* temp = 0;
while ( node )
{
temp = node;
node = node->next;
delete temp;
}
firstChild = 0;
lastChild = 0;
}
TiXmlNode* TiXmlNode::LinkEndChild( TiXmlNode* node )
{
assert( node->parent == 0 || node->parent == this );
assert( node->GetDocument() == 0 || node->GetDocument() == this->GetDocument() );
node->parent = this;
node->prev = lastChild;
node->next = 0;
if ( lastChild )
lastChild->next = node;
else
firstChild = node; // it was an empty list.
lastChild = node;
return node;
}
TiXmlNode* TiXmlNode::InsertEndChild( const TiXmlNode& addThis )
{
TiXmlNode* node = addThis.Clone();
if ( !node )
return 0;
return LinkEndChild( node );
}
TiXmlNode* TiXmlNode::InsertBeforeChild( TiXmlNode* beforeThis, const TiXmlNode& addThis )
{
if ( !beforeThis || beforeThis->parent != this )
return 0;
TiXmlNode* node = addThis.Clone();
if ( !node )
return 0;
node->parent = this;
node->next = beforeThis;
node->prev = beforeThis->prev;
if ( beforeThis->prev )
{
beforeThis->prev->next = node;
}
else
{
assert( firstChild == beforeThis );
firstChild = node;
}
beforeThis->prev = node;
return node;
}
TiXmlNode* TiXmlNode::InsertAfterChild( TiXmlNode* afterThis, const TiXmlNode& addThis )
{
if ( !afterThis || afterThis->parent != this )
return 0;
TiXmlNode* node = addThis.Clone();
if ( !node )
return 0;
node->parent = this;
node->prev = afterThis;
node->next = afterThis->next;
if ( afterThis->next )
{
afterThis->next->prev = node;
}
else
{
assert( lastChild == afterThis );
lastChild = node;
}
afterThis->next = node;
return node;
}
TiXmlNode* TiXmlNode::ReplaceChild( TiXmlNode* replaceThis, const TiXmlNode& withThis )
{
if ( replaceThis->parent != this )
return 0;
TiXmlNode* node = withThis.Clone();
if ( !node )
return 0;
node->next = replaceThis->next;
node->prev = replaceThis->prev;
if ( replaceThis->next )
replaceThis->next->prev = node;
else
lastChild = node;
if ( replaceThis->prev )
replaceThis->prev->next = node;
else
firstChild = node;
delete replaceThis;
node->parent = this;
return node;
}
bool TiXmlNode::RemoveChild( TiXmlNode* removeThis )
{
if ( removeThis->parent != this )
{
assert( 0 );
return false;
}
if ( removeThis->next )
removeThis->next->prev = removeThis->prev;
else
lastChild = removeThis->prev;
if ( removeThis->prev )
removeThis->prev->next = removeThis->next;
else
firstChild = removeThis->next;
delete removeThis;
return true;
}
const TiXmlNode* TiXmlNode::FirstChild( const char * _value ) const
{
const TiXmlNode* node;
for ( node = firstChild; node; node = node->next )
{
if ( strcmp( node->Value(), _value ) == 0 )
return node;
}
return 0;
}
TiXmlNode* TiXmlNode::FirstChild( const char * _value )
{
TiXmlNode* node;
for ( node = firstChild; node; node = node->next )
{
if ( strcmp( node->Value(), _value ) == 0 )
return node;
}
return 0;
}
const TiXmlNode* TiXmlNode::LastChild( const char * _value ) const
{
const TiXmlNode* node;
for ( node = lastChild; node; node = node->prev )
{
if ( strcmp( node->Value(), _value ) == 0 )
return node;
}
return 0;
}
TiXmlNode* TiXmlNode::LastChild( const char * _value )
{
TiXmlNode* node;
for ( node = lastChild; node; node = node->prev )
{
if ( strcmp( node->Value(), _value ) == 0 )
return node;
}
return 0;
}
const TiXmlNode* TiXmlNode::IterateChildren( const TiXmlNode* previous ) const
{
if ( !previous )
{
return FirstChild();
}
else
{
assert( previous->parent == this );
return previous->NextSibling();
}
}
TiXmlNode* TiXmlNode::IterateChildren( TiXmlNode* previous )
{
if ( !previous )
{
return FirstChild();
}
else
{
assert( previous->parent == this );
return previous->NextSibling();
}
}
const TiXmlNode* TiXmlNode::IterateChildren( const char * val, const TiXmlNode* previous ) const
{
if ( !previous )
{
return FirstChild( val );
}
else
{
assert( previous->parent == this );
return previous->NextSibling( val );
}
}
TiXmlNode* TiXmlNode::IterateChildren( const char * val, TiXmlNode* previous )
{
if ( !previous )
{
return FirstChild( val );
}
else
{
assert( previous->parent == this );
return previous->NextSibling( val );
}
}
const TiXmlNode* TiXmlNode::NextSibling( const char * _value ) const
{
const TiXmlNode* node;
for ( node = next; node; node = node->next )
{
if ( strcmp( node->Value(), _value ) == 0 )
return node;
}
return 0;
}
TiXmlNode* TiXmlNode::NextSibling( const char * _value )
{
TiXmlNode* node;
for ( node = next; node; node = node->next )
{
if ( strcmp( node->Value(), _value ) == 0 )
return node;
}
return 0;
}
const TiXmlNode* TiXmlNode::PreviousSibling( const char * _value ) const
{
const TiXmlNode* node;
for ( node = prev; node; node = node->prev )
{
if ( strcmp( node->Value(), _value ) == 0 )
return node;
}
return 0;
}
TiXmlNode* TiXmlNode::PreviousSibling( const char * _value )
{
TiXmlNode* node;
for ( node = prev; node; node = node->prev )
{
if ( strcmp( node->Value(), _value ) == 0 )
return node;
}
return 0;
}
void TiXmlElement::RemoveAttribute( const char * name )
{
TIXML_STRING str( name );
TiXmlAttribute* node = attributeSet.Find( str );
if ( node )
{
attributeSet.Remove( node );
delete node;
}
}
const TiXmlElement* TiXmlNode::FirstChildElement() const
{
const TiXmlNode* node;
for ( node = FirstChild();
node;
node = node->NextSibling() )
{
if ( node->ToElement() )
return node->ToElement();
}
return 0;
}
TiXmlElement* TiXmlNode::FirstChildElement()
{
TiXmlNode* node;
for ( node = FirstChild();
node;
node = node->NextSibling() )
{
if ( node->ToElement() )
return node->ToElement();
}
return 0;
}
const TiXmlElement* TiXmlNode::FirstChildElement( const char * _value ) const
{
const TiXmlNode* node;
for ( node = FirstChild( _value );
node;
node = node->NextSibling( _value ) )
{
if ( node->ToElement() )
return node->ToElement();
}
return 0;
}
TiXmlElement* TiXmlNode::FirstChildElement( const char * _value )
{
TiXmlNode* node;
for ( node = FirstChild( _value );
node;
node = node->NextSibling( _value ) )
{
if ( node->ToElement() )
return node->ToElement();
}
return 0;
}
const TiXmlElement* TiXmlNode::NextSiblingElement() const
{
const TiXmlNode* node;
for ( node = NextSibling();
node;
node = node->NextSibling() )
{
if ( node->ToElement() )
return node->ToElement();
}
return 0;
}
TiXmlElement* TiXmlNode::NextSiblingElement()
{
TiXmlNode* node;
for ( node = NextSibling();
node;
node = node->NextSibling() )
{
if ( node->ToElement() )
return node->ToElement();
}
return 0;
}
const TiXmlElement* TiXmlNode::NextSiblingElement( const char * _value ) const
{
const TiXmlNode* node;
for ( node = NextSibling( _value );
node;
node = node->NextSibling( _value ) )
{
if ( node->ToElement() )
return node->ToElement();
}
return 0;
}
TiXmlElement* TiXmlNode::NextSiblingElement( const char * _value )
{
TiXmlNode* node;
for ( node = NextSibling( _value );
node;
node = node->NextSibling( _value ) )
{
if ( node->ToElement() )
return node->ToElement();
}
return 0;
}
const TiXmlDocument* TiXmlNode::GetDocument() const
{
const TiXmlNode* node;
for( node = this; node; node = node->parent )
{
if ( node->ToDocument() )
return node->ToDocument();
}
return 0;
}
TiXmlDocument* TiXmlNode::GetDocument()
{
TiXmlNode* node;
for( node = this; node; node = node->parent )
{
if ( node->ToDocument() )
return node->ToDocument();
}
return 0;
}
TiXmlElement::TiXmlElement (const char * _value)
: TiXmlNode( TiXmlNode::ELEMENT )
{
firstChild = lastChild = 0;
value = _value;
}
#ifdef TIXML_USE_STL
TiXmlElement::TiXmlElement( const std::string& _value )
: TiXmlNode( TiXmlNode::ELEMENT )
{
firstChild = lastChild = 0;
value = _value;
}
#endif
TiXmlElement::TiXmlElement( const TiXmlElement& copy)
: TiXmlNode( TiXmlNode::ELEMENT )
{
firstChild = lastChild = 0;
copy.CopyTo( this );
}
void TiXmlElement::operator=( const TiXmlElement& base )
{
ClearThis();
base.CopyTo( this );
}
TiXmlElement::~TiXmlElement()
{
ClearThis();
}
void TiXmlElement::ClearThis()
{
Clear();
while( attributeSet.First() )
{
TiXmlAttribute* node = attributeSet.First();
attributeSet.Remove( node );
delete node;
}
}
const char * TiXmlElement::Attribute( const char * name ) const
{
TIXML_STRING str( name );
const TiXmlAttribute* node = attributeSet.Find( str );
if ( node )
return node->Value();
return 0;
}
const char * TiXmlElement::Attribute( const char * name, int* i ) const
{
const char * s = Attribute( name );
if ( i )
{
if ( s )
*i = atoi( s );
else
*i = 0;
}
return s;
}
const char * TiXmlElement::Attribute( const char * name, double* d ) const
{
const char * s = Attribute( name );
if ( d )
{
if ( s )
*d = atof( s );
else
*d = 0;
}
return s;
}
int TiXmlElement::QueryIntAttribute( const char* name, int* ival ) const
{
TIXML_STRING str( name );
const TiXmlAttribute* node = attributeSet.Find( str );
if ( !node )
return TIXML_NO_ATTRIBUTE;
return node->QueryIntValue( ival );
}
int TiXmlElement::QueryDoubleAttribute( const char* name, double* dval ) const
{
TIXML_STRING str( name );
const TiXmlAttribute* node = attributeSet.Find( str );
if ( !node )
return TIXML_NO_ATTRIBUTE;
return node->QueryDoubleValue( dval );
}
void TiXmlElement::SetAttribute( const char * name, int val )
{
char buf[64];
#if defined(TIXML_SNPRINTF)
TIXML_SNPRINTF( buf, sizeof(buf), "%d", val );
#else
sprintf( buf, "%d", val );
#endif
SetAttribute( name, buf );
}
#ifdef TIXML_USE_STL
void TiXmlElement::SetAttribute( const std::string& name, int val )
{
std::ostringstream oss;
oss << val;
SetAttribute( name, oss.str() );
}
#endif
void TiXmlElement::SetDoubleAttribute( const char * name, double val )
{
char buf[256];
#if defined(TIXML_SNPRINTF)
TIXML_SNPRINTF( buf, sizeof(buf), "%f", val );
#else
sprintf( buf, "%f", val );
#endif
SetAttribute( name, buf );
}
void TiXmlElement::SetAttribute( const char * cname, const char * cvalue )
{
TIXML_STRING _name( cname );
TIXML_STRING _value( cvalue );
TiXmlAttribute* node = attributeSet.Find( _name );
if ( node )
{
node->SetValue( cvalue );
return;
}
TiXmlAttribute* attrib = new TiXmlAttribute( cname, cvalue );
if ( attrib )
{
attributeSet.Add( attrib );
}
else
{
TiXmlDocument* document = GetDocument();
if ( document ) document->SetError( TIXML_ERROR_OUT_OF_MEMORY, 0, 0, TIXML_ENCODING_UNKNOWN );
}
}
#ifdef TIXML_USE_STL
void TiXmlElement::SetAttribute( const std::string& name, const std::string& _value )
{
TiXmlAttribute* node = attributeSet.Find( name );
if ( node )
{
node->SetValue( _value );
return;
}
TiXmlAttribute* attrib = new TiXmlAttribute( name, _value );
if ( attrib )
{
attributeSet.Add( attrib );
}
else
{
TiXmlDocument* document = GetDocument();
if ( document ) document->SetError( TIXML_ERROR_OUT_OF_MEMORY, 0, 0, TIXML_ENCODING_UNKNOWN );
}
}
#endif
void TiXmlElement::Print(const Ptr<IO::TextWriter>& textWriter, int depth) const
{
n_assert(textWriter.isvalid());
int i;
for (i = 0; i < depth; i++)
{
textWriter->WriteString(" ");
}
textWriter->WriteFormatted("<%s", value.c_str());
const TiXmlAttribute* attrib;
for (attrib = attributeSet.First(); attrib; attrib = attrib->Next())
{
textWriter->WriteChar(' ');
attrib->Print(textWriter, depth);
}
// There are 3 different formatting approaches:
// 1) An element without children is printed as a <foo /> node
// 2) An element with only a text child is printed as <foo> text </foo>
// 3) An element with children is printed on multiple lines.
TiXmlNode* node;
if (!firstChild)
{
textWriter->WriteString(" />");
}
else if (firstChild == lastChild && firstChild->ToText())
{
textWriter->WriteChar('>');
firstChild->Print(textWriter, depth + 1);
textWriter->WriteFormatted("</%s>", value.c_str());
}
else
{
textWriter->WriteChar('>');
for (node = firstChild; node; node=node->NextSibling())
{
if (!node->ToText())
{
textWriter->WriteChar('\n');
}
node->Print(textWriter, depth+1);
}
textWriter->WriteChar('\n');
for(i=0; i<depth; ++i)
{
textWriter->WriteString(" ");
}
textWriter->WriteFormatted("</%s>", value.c_str());
}
}
void TiXmlElement::StreamOut( TIXML_OSTREAM * stream ) const
{
(*stream) << "<" << value;
const TiXmlAttribute* attrib;
for ( attrib = attributeSet.First(); attrib; attrib = attrib->Next() )
{
(*stream) << " ";
attrib->StreamOut( stream );
}
// If this node has children, give it a closing tag. Else
// make it an empty tag.
TiXmlNode* node;
if ( firstChild )
{
(*stream) << ">";
for ( node = firstChild; node; node=node->NextSibling() )
{
node->StreamOut( stream );
}
(*stream) << "</" << value << ">";
}
else
{
(*stream) << " />";
}
}
void TiXmlElement::CopyTo( TiXmlElement* target ) const
{
// superclass:
TiXmlNode::CopyTo( target );
// Element class:
// Clone the attributes, then clone the children.
const TiXmlAttribute* attribute = 0;
for( attribute = attributeSet.First();
attribute;
attribute = attribute->Next() )
{
target->SetAttribute( attribute->Name(), attribute->Value() );
}
TiXmlNode* node = 0;
for ( node = firstChild; node; node = node->NextSibling() )
{
target->LinkEndChild( node->Clone() );
}
}
TiXmlNode* TiXmlElement::Clone() const
{
TiXmlElement* clone = new TiXmlElement( Value() );
if ( !clone )
return 0;
CopyTo( clone );
return clone;
}
const char* TiXmlElement::GetText() const
{
const TiXmlNode* child = this->FirstChild();
if ( child ) {
const TiXmlText* childText = child->ToText();
if ( childText ) {
return childText->Value();
}
}
return 0;
}
TiXmlDocument::TiXmlDocument() : TiXmlNode( TiXmlNode::DOCUMENT )
{
tabsize = 4;
useMicrosoftBOM = false;
ClearError();
}
TiXmlDocument::TiXmlDocument( const TiXmlDocument& copy ) : TiXmlNode( TiXmlNode::DOCUMENT )
{
copy.CopyTo( this );
}
void TiXmlDocument::operator=( const TiXmlDocument& copy )
{
Clear();
copy.CopyTo( this );
}
bool TiXmlDocument::LoadStream(const Ptr<IO::Stream>& stream, TiXmlEncoding encoding)
{
if (!stream.isvalid())
{
SetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN );
return false;
}
// Delete the existing data:
Clear();
location.Clear();
// Get the file size, so we can pre-allocate the string. HUGE speed impact.
long length = stream->GetSize();
// Strange case, but good to handle up front.
if (length == 0)
{
SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN );
return false;
}
// If we have a file, assume it is all one big XML file, and read it in.
// The document parser may decide the document ends sooner than the entire file, however.
TIXML_STRING data;
data.reserve(length);
// Subtle bug here. TinyXml did use fgets. But from the XML spec:
// 2.11 End-of-Line Handling
// <snip>
// <quote>
// ...the XML processor MUST behave as if it normalized all line breaks in external
// parsed entities (including the document entity) on input, before parsing, by translating
// both the two-character sequence #xD #xA and any #xD that is not followed by #xA to
// a single #xA character.
// </quote>
//
// It is not clear fgets does that, and certainly isn't clear it works cross platform.
// Generally, you expect fgets to translate from the convention of the OS to the c/unix
// convention, and not work generally.
/*
while (fgets(buf, sizeof(buf), file))
{
data += buf;
}
*/
char* buf = new char[length+1];
buf[0] = 0;
if (stream->Read(buf, length) != length)
{
SetError(TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN);
return false;
}
const char* lastPos = buf;
const char* p = buf;
buf[length] = 0;
while( *p ) {
assert( p < (buf+length) );
if ( *p == 0xa ) {
// Newline character. No special rules for this. Append all the characters
// since the last string, and include the newline.
data.append( lastPos, (p-lastPos+1) ); // append, include the newline
++p; // move past the newline
lastPos = p; // and point to the new buffer (may be 0)
assert( p <= (buf+length) );
}
else if ( *p == 0xd ) {
// Carriage return. Append what we have so far, then
// handle moving forward in the buffer.
if ( (p-lastPos) > 0 ) {
data.append( lastPos, p-lastPos ); // do not add the CR
}
data += (char)0xa; // a proper newline
if ( *(p+1) == 0xa ) {
// Carriage return - new line sequence
p += 2;
lastPos = p;
assert( p <= (buf+length) );
}
else {
// it was followed by something else...that is presumably characters again.
++p;
lastPos = p;
assert( p <= (buf+length) );
}
}
else {
++p;
}
}
// Handle any left over characters.
if ( p-lastPos ) {
data.append( lastPos, p-lastPos );
}
delete [] buf;
buf = 0;
Parse( data.c_str(), 0, encoding );
if ( Error() )
return false;
else
return true;
}
bool TiXmlDocument::SaveStream(const Ptr<IO::Stream>& stream) const
{
Ptr<IO::TextWriter> textWriter = IO::TextWriter::Create();
textWriter->SetStream(stream);
if (textWriter->Open())
{
if (useMicrosoftBOM)
{
const unsigned char TIXML_UTF_LEAD_0 = 0xefU;
const unsigned char TIXML_UTF_LEAD_1 = 0xbbU;
const unsigned char TIXML_UTF_LEAD_2 = 0xbfU;
textWriter->WriteChar(TIXML_UTF_LEAD_0);
textWriter->WriteChar(TIXML_UTF_LEAD_1);
textWriter->WriteChar(TIXML_UTF_LEAD_2);
}
Print(textWriter, 0);
textWriter->Close();
}
return true;
}
void TiXmlDocument::CopyTo( TiXmlDocument* target ) const
{
TiXmlNode::CopyTo( target );
target->error = error;
target->errorDesc = errorDesc.c_str ();
TiXmlNode* node = 0;
for ( node = firstChild; node; node = node->NextSibling() )
{
target->LinkEndChild( node->Clone() );
}
}
TiXmlNode* TiXmlDocument::Clone() const
{
TiXmlDocument* clone = new TiXmlDocument();
if ( !clone )
return 0;
CopyTo( clone );
return clone;
}
void TiXmlDocument::Print(const Ptr<IO::TextWriter>& textWriter, int depth) const
{
const TiXmlNode* node;
for ( node=FirstChild(); node; node=node->NextSibling() )
{
node->Print(textWriter, depth);
textWriter->WriteChar('\n');
}
}
void TiXmlDocument::StreamOut( TIXML_OSTREAM * out ) const
{
const TiXmlNode* node;
for ( node=FirstChild(); node; node=node->NextSibling() )
{
node->StreamOut( out );
// Special rule for streams: stop after the root element.
// The stream in code will only read one element, so don't
// write more than one.
if ( node->ToElement() )
break;
}
}
const TiXmlAttribute* TiXmlAttribute::Next() const
{
// We are using knowledge of the sentinel. The sentinel
// have a value or name.
if ( next->value.empty() && next->name.empty() )
return 0;
return next;
}
TiXmlAttribute* TiXmlAttribute::Next()
{
// We are using knowledge of the sentinel. The sentinel
// have a value or name.
if ( next->value.empty() && next->name.empty() )
return 0;
return next;
}
const TiXmlAttribute* TiXmlAttribute::Previous() const
{
// We are using knowledge of the sentinel. The sentinel
// have a value or name.
if ( prev->value.empty() && prev->name.empty() )
return 0;
return prev;
}
TiXmlAttribute* TiXmlAttribute::Previous()
{
// We are using knowledge of the sentinel. The sentinel
// have a value or name.
if ( prev->value.empty() && prev->name.empty() )
return 0;
return prev;
}
void TiXmlAttribute::Print(const Ptr<IO::TextWriter>& textWriter, int /*depth*/ ) const
{
TIXML_STRING n, v;
PutString( name, &n );
PutString( value, &v );
if (value.find ('\"') == TIXML_STRING::npos)
textWriter->WriteFormatted("%s=\"%s\"", n.c_str(), v.c_str());
else
textWriter->WriteFormatted("%s='%s'", n.c_str(), v.c_str());
}
void TiXmlAttribute::StreamOut( TIXML_OSTREAM * stream ) const
{
if (value.find( '\"' ) != TIXML_STRING::npos)
{
PutString( name, stream );
(*stream) << "=" << "'";
PutString( value, stream );
(*stream) << "'";
}
else
{
PutString( name, stream );
(*stream) << "=" << "\"";
PutString( value, stream );
(*stream) << "\"";
}
}
int TiXmlAttribute::QueryIntValue( int* ival ) const
{
if ( sscanf( value.c_str(), "%d", ival ) == 1 )
return TIXML_SUCCESS;
return TIXML_WRONG_TYPE;
}
int TiXmlAttribute::QueryDoubleValue( double* dval ) const
{
if ( sscanf( value.c_str(), "%lf", dval ) == 1 )
return TIXML_SUCCESS;
return TIXML_WRONG_TYPE;
}
void TiXmlAttribute::SetIntValue( int _value )
{
char buf [64];
#if defined(TIXML_SNPRINTF)
TIXML_SNPRINTF(buf, sizeof(buf), "%d", _value);
#else
sprintf (buf, "%d", _value);
#endif
SetValue (buf);
}
void TiXmlAttribute::SetDoubleValue( double _value )
{
char buf [256];
#if defined(TIXML_SNPRINTF)
TIXML_SNPRINTF( buf, sizeof(buf), "%lf", _value);
#else
sprintf (buf, "%lf", _value);
#endif
SetValue (buf);
}
int TiXmlAttribute::IntValue() const
{
return atoi (value.c_str ());
}
double TiXmlAttribute::DoubleValue() const
{
return atof (value.c_str ());
}
TiXmlComment::TiXmlComment( const TiXmlComment& copy ) : TiXmlNode( TiXmlNode::COMMENT )
{
copy.CopyTo( this );
}
void TiXmlComment::operator=( const TiXmlComment& base )
{
Clear();
base.CopyTo( this );
}
void TiXmlComment::Print(const Ptr<IO::TextWriter>& textWriter, int depth) const
{
for ( int i=0; i<depth; i++ )
{
textWriter->WriteString(" ");
}
textWriter->WriteFormatted("<!--%s-->", value.c_str());
}
void TiXmlComment::StreamOut( TIXML_OSTREAM * stream ) const
{
(*stream) << "<!--";
//PutString( value, stream );
(*stream) << value;
(*stream) << "-->";
}
void TiXmlComment::CopyTo( TiXmlComment* target ) const
{
TiXmlNode::CopyTo( target );
}
TiXmlNode* TiXmlComment::Clone() const
{
TiXmlComment* clone = new TiXmlComment();
if ( !clone )
return 0;
CopyTo( clone );
return clone;
}
void TiXmlText::Print(const Ptr<IO::TextWriter>& textWriter, int depth) const
{
if (cdata)
{
int i;
textWriter->WriteChar('\n');
for (i=0; i<depth; i++)
{
textWriter->WriteString(" ");
}
textWriter->WriteFormatted("<![CDATA[%s]]>\n", value.c_str());
}
else
{
if (raw)
{
textWriter->WriteString(value.c_str());
}
else
{
TIXML_STRING buffer;
PutString( value, &buffer );
textWriter->WriteString(buffer.c_str());
}
}
}
void TiXmlText::StreamOut( TIXML_OSTREAM * stream ) const
{
if ( cdata )
{
(*stream) << "<![CDATA[" << value << "]]>";
}
else
{
PutString( value, stream );
}
}
void TiXmlText::CopyTo( TiXmlText* target ) const
{
TiXmlNode::CopyTo( target );
target->cdata = cdata;
}
TiXmlNode* TiXmlText::Clone() const
{
TiXmlText* clone = 0;
clone = new TiXmlText( "" );
if ( !clone )
return 0;
CopyTo( clone );
return clone;
}
TiXmlDeclaration::TiXmlDeclaration( const char * _version,
const char * _encoding,
const char * _standalone )
: TiXmlNode( TiXmlNode::DECLARATION )
{
version = _version;
encoding = _encoding;
standalone = _standalone;
}
#ifdef TIXML_USE_STL
TiXmlDeclaration::TiXmlDeclaration( const std::string& _version,
const std::string& _encoding,
const std::string& _standalone )
: TiXmlNode( TiXmlNode::DECLARATION )
{
version = _version;
encoding = _encoding;
standalone = _standalone;
}
#endif
TiXmlDeclaration::TiXmlDeclaration( const TiXmlDeclaration& copy )
: TiXmlNode( TiXmlNode::DECLARATION )
{
copy.CopyTo( this );
}
void TiXmlDeclaration::operator=( const TiXmlDeclaration& copy )
{
Clear();
copy.CopyTo( this );
}
void TiXmlDeclaration::Print(const Ptr<IO::TextWriter>& textWriter, int /*depth*/ ) const
{
textWriter->WriteString("<?xml ");
if ( !version.empty() )
textWriter->WriteFormatted("version=\"%s\" ", version.c_str ());
if ( !encoding.empty() )
textWriter->WriteFormatted("encoding=\"%s\" ", encoding.c_str ());
if ( !standalone.empty() )
textWriter->WriteFormatted("standalone=\"%s\" ", standalone.c_str ());
textWriter->WriteString("?>");
}
void TiXmlDeclaration::StreamOut( TIXML_OSTREAM * stream ) const
{
(*stream) << "<?xml ";
if ( !version.empty() )
{
(*stream) << "version=\"";
PutString( version, stream );
(*stream) << "\" ";
}
if ( !encoding.empty() )
{
(*stream) << "encoding=\"";
PutString( encoding, stream );
(*stream ) << "\" ";
}
if ( !standalone.empty() )
{
(*stream) << "standalone=\"";
PutString( standalone, stream );
(*stream) << "\" ";
}
(*stream) << "?>";
}
void TiXmlDeclaration::CopyTo( TiXmlDeclaration* target ) const
{
TiXmlNode::CopyTo( target );
target->version = version;
target->encoding = encoding;
target->standalone = standalone;
}
TiXmlNode* TiXmlDeclaration::Clone() const
{
TiXmlDeclaration* clone = new TiXmlDeclaration();
if ( !clone )
return 0;
CopyTo( clone );
return clone;
}
void TiXmlUnknown::Print(const Ptr<IO::TextWriter>& textWriter, int depth ) const
{
for ( int i=0; i<depth; i++ )
textWriter->WriteString(" ");
textWriter->WriteFormatted("<%s>", value.c_str());
}
void TiXmlUnknown::StreamOut( TIXML_OSTREAM * stream ) const
{
(*stream) << "<" << value << ">"; // Don't use entities here! It is unknown.
}
void TiXmlUnknown::CopyTo( TiXmlUnknown* target ) const
{
TiXmlNode::CopyTo( target );
}
TiXmlNode* TiXmlUnknown::Clone() const
{
TiXmlUnknown* clone = new TiXmlUnknown();
if ( !clone )
return 0;
CopyTo( clone );
return clone;
}
TiXmlAttributeSet::TiXmlAttributeSet()
{
sentinel.next = &sentinel;
sentinel.prev = &sentinel;
}
TiXmlAttributeSet::~TiXmlAttributeSet()
{
assert( sentinel.next == &sentinel );
assert( sentinel.prev == &sentinel );
}
void TiXmlAttributeSet::Add( TiXmlAttribute* addMe )
{
assert( !Find( TIXML_STRING( addMe->Name() ) ) ); // Shouldn't be multiply adding to the set.
addMe->next = &sentinel;
addMe->prev = sentinel.prev;
sentinel.prev->next = addMe;
sentinel.prev = addMe;
}
void TiXmlAttributeSet::Remove( TiXmlAttribute* removeMe )
{
TiXmlAttribute* node;
for( node = sentinel.next; node != &sentinel; node = node->next )
{
if ( node == removeMe )
{
node->prev->next = node->next;
node->next->prev = node->prev;
node->next = 0;
node->prev = 0;
return;
}
}
assert( 0 ); // we tried to remove a non-linked attribute.
}
const TiXmlAttribute* TiXmlAttributeSet::Find( const TIXML_STRING& name ) const
{
const TiXmlAttribute* node;
for( node = sentinel.next; node != &sentinel; node = node->next )
{
if ( node->name == name )
return node;
}
return 0;
}
TiXmlAttribute* TiXmlAttributeSet::Find( const TIXML_STRING& name )
{
TiXmlAttribute* node;
for( node = sentinel.next; node != &sentinel; node = node->next )
{
if ( node->name == name )
return node;
}
return 0;
}
#ifdef TIXML_USE_STL
TIXML_ISTREAM & operator >> (TIXML_ISTREAM & in, TiXmlNode & base)
{
TIXML_STRING tag;
tag.reserve( 8 * 1000 );
base.StreamIn( &in, &tag );
base.Parse( tag.c_str(), 0, TIXML_DEFAULT_ENCODING );
return in;
}
#endif
TIXML_OSTREAM & operator<< (TIXML_OSTREAM & out, const TiXmlNode & base)
{
base.StreamOut (& out);
return out;
}
#ifdef TIXML_USE_STL
std::string & operator<< (std::string& out, const TiXmlNode& base )
{
std::ostringstream os_stream( std::ostringstream::out );
base.StreamOut( &os_stream );
out.append( os_stream.str() );
return out;
}
#endif
TiXmlHandle TiXmlHandle::FirstChild() const
{
if ( node )
{
TiXmlNode* child = node->FirstChild();
if ( child )
return TiXmlHandle( child );
}
return TiXmlHandle( 0 );
}
TiXmlHandle TiXmlHandle::FirstChild( const char * value ) const
{
if ( node )
{
TiXmlNode* child = node->FirstChild( value );
if ( child )
return TiXmlHandle( child );
}
return TiXmlHandle( 0 );
}
TiXmlHandle TiXmlHandle::FirstChildElement() const
{
if ( node )
{
TiXmlElement* child = node->FirstChildElement();
if ( child )
return TiXmlHandle( child );
}
return TiXmlHandle( 0 );
}
TiXmlHandle TiXmlHandle::FirstChildElement( const char * value ) const
{
if ( node )
{
TiXmlElement* child = node->FirstChildElement( value );
if ( child )
return TiXmlHandle( child );
}
return TiXmlHandle( 0 );
}
TiXmlHandle TiXmlHandle::Child( int count ) const
{
if ( node )
{
int i;
TiXmlNode* child = node->FirstChild();
for ( i=0;
child && i<count;
child = child->NextSibling(), ++i )
{
// nothing
}
if ( child )
return TiXmlHandle( child );
}
return TiXmlHandle( 0 );
}
TiXmlHandle TiXmlHandle::Child( const char* value, int count ) const
{
if ( node )
{
int i;
TiXmlNode* child = node->FirstChild( value );
for ( i=0;
child && i<count;
child = child->NextSibling( value ), ++i )
{
// nothing
}
if ( child )
return TiXmlHandle( child );
}
return TiXmlHandle( 0 );
}
TiXmlHandle TiXmlHandle::ChildElement( int count ) const
{
if ( node )
{
int i;
TiXmlElement* child = node->FirstChildElement();
for ( i=0;
child && i<count;
child = child->NextSiblingElement(), ++i )
{
// nothing
}
if ( child )
return TiXmlHandle( child );
}
return TiXmlHandle( 0 );
}
TiXmlHandle TiXmlHandle::ChildElement( const char* value, int count ) const
{
if ( node )
{
int i;
TiXmlElement* child = node->FirstChildElement( value );
for ( i=0;
child && i<count;
child = child->NextSiblingElement( value ), ++i )
{
// nothing
}
if ( child )
return TiXmlHandle( child );
}
return TiXmlHandle( 0 );
}
| [
"[email protected]"
] | |
703119d8f258282094680671aaceb7b36f0035dc | 26dfd6763c2956f853a5ec631d829e193adc41e0 | /src/test/net_tests.cpp | 3b5f1f7a00dad371adcc9c316b12b8a64b192ae6 | [
"MIT"
] | permissive | pallas1/SUQA-0.17.1 | 205d1032b42fd2dcdc2f3299b3c0e9f3e7984196 | e95747262e4e8362a345e0662f0c951f07b7672f | refs/heads/master | 2020-04-16T03:01:52.810925 | 2019-06-23T21:22:14 | 2019-06-23T21:22:14 | 165,217,705 | 2 | 3 | MIT | 2019-06-23T21:22:15 | 2019-01-11T09:34:54 | C++ | UTF-8 | C++ | false | false | 7,276 | cpp | // Copyright (c) 2012-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <addrman.h>
#include <test/test_suqa.h>
#include <string>
#include <boost/test/unit_test.hpp>
#include <hash.h>
#include <serialize.h>
#include <streams.h>
#include <net.h>
#include <netbase.h>
#include <chainparams.h>
#include <util.h>
#include <memory>
class CAddrManSerializationMock : public CAddrMan
{
public:
virtual void Serialize(CDataStream& s) const = 0;
//! Ensure that bucket placement is always the same for testing purposes.
void MakeDeterministic()
{
nKey.SetNull();
insecure_rand = FastRandomContext(true);
}
};
class CAddrManUncorrupted : public CAddrManSerializationMock
{
public:
void Serialize(CDataStream& s) const override
{
CAddrMan::Serialize(s);
}
};
class CAddrManCorrupted : public CAddrManSerializationMock
{
public:
void Serialize(CDataStream& s) const override
{
// Produces corrupt output that claims addrman has 20 addrs when it only has one addr.
unsigned char nVersion = 1;
s << nVersion;
s << ((unsigned char)32);
s << nKey;
s << 10; // nNew
s << 10; // nTried
int nUBuckets = ADDRMAN_NEW_BUCKET_COUNT ^ (1 << 30);
s << nUBuckets;
CService serv;
Lookup("252.1.1.1", serv, 7777, false);
CAddress addr = CAddress(serv, NODE_NONE);
CNetAddr resolved;
LookupHost("252.2.2.2", resolved, false);
CAddrInfo info = CAddrInfo(addr, resolved);
s << info;
}
};
static CDataStream AddrmanToStream(CAddrManSerializationMock& _addrman)
{
CDataStream ssPeersIn(SER_DISK, CLIENT_VERSION);
ssPeersIn << Params().MessageStart();
ssPeersIn << _addrman;
std::string str = ssPeersIn.str();
std::vector<unsigned char> vchData(str.begin(), str.end());
return CDataStream(vchData, SER_DISK, CLIENT_VERSION);
}
BOOST_FIXTURE_TEST_SUITE(net_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(cnode_listen_port)
{
// test default
unsigned short port = GetListenPort();
BOOST_CHECK(port == Params().GetDefaultPort());
// test set port
unsigned short altPort = 12345;
gArgs.SoftSetArg("-port", std::to_string(altPort));
port = GetListenPort();
BOOST_CHECK(port == altPort);
}
BOOST_AUTO_TEST_CASE(caddrdb_read)
{
SetDataDir("caddrdb_read");
CAddrManUncorrupted addrmanUncorrupted;
addrmanUncorrupted.MakeDeterministic();
CService addr1, addr2, addr3;
Lookup("250.7.1.1", addr1, 8333, false);
Lookup("250.7.2.2", addr2, 9999, false);
Lookup("250.7.3.3", addr3, 9999, false);
// Add three addresses to new table.
CService source;
Lookup("252.5.1.1", source, 8333, false);
addrmanUncorrupted.Add(CAddress(addr1, NODE_NONE), source);
addrmanUncorrupted.Add(CAddress(addr2, NODE_NONE), source);
addrmanUncorrupted.Add(CAddress(addr3, NODE_NONE), source);
// Test that the de-serialization does not throw an exception.
CDataStream ssPeers1 = AddrmanToStream(addrmanUncorrupted);
bool exceptionThrown = false;
CAddrMan addrman1;
BOOST_CHECK(addrman1.size() == 0);
try {
unsigned char pchMsgTmp[4];
ssPeers1 >> pchMsgTmp;
ssPeers1 >> addrman1;
} catch (const std::exception& e) {
exceptionThrown = true;
}
BOOST_CHECK(addrman1.size() == 3);
BOOST_CHECK(exceptionThrown == false);
// Test that CAddrDB::Read creates an addrman with the correct number of addrs.
CDataStream ssPeers2 = AddrmanToStream(addrmanUncorrupted);
CAddrMan addrman2;
CAddrDB adb;
BOOST_CHECK(addrman2.size() == 0);
adb.Read(addrman2, ssPeers2);
BOOST_CHECK(addrman2.size() == 3);
}
BOOST_AUTO_TEST_CASE(caddrdb_read_corrupted)
{
SetDataDir("caddrdb_read_corrupted");
CAddrManCorrupted addrmanCorrupted;
addrmanCorrupted.MakeDeterministic();
// Test that the de-serialization of corrupted addrman throws an exception.
CDataStream ssPeers1 = AddrmanToStream(addrmanCorrupted);
bool exceptionThrown = false;
CAddrMan addrman1;
BOOST_CHECK(addrman1.size() == 0);
try {
unsigned char pchMsgTmp[4];
ssPeers1 >> pchMsgTmp;
ssPeers1 >> addrman1;
} catch (const std::exception& e) {
exceptionThrown = true;
}
// Even through de-serialization failed addrman is not left in a clean state.
BOOST_CHECK(addrman1.size() == 1);
BOOST_CHECK(exceptionThrown);
// Test that CAddrDB::Read leaves addrman in a clean state if de-serialization fails.
CDataStream ssPeers2 = AddrmanToStream(addrmanCorrupted);
CAddrMan addrman2;
CAddrDB adb;
BOOST_CHECK(addrman2.size() == 0);
adb.Read(addrman2, ssPeers2);
BOOST_CHECK(addrman2.size() == 0);
}
BOOST_AUTO_TEST_CASE(cnode_simple_test)
{
SOCKET hSocket = INVALID_SOCKET;
NodeId id = 0;
int height = 0;
in_addr ipv4Addr;
ipv4Addr.s_addr = 0xa0b0c001;
CAddress addr = CAddress(CService(ipv4Addr, 7777), NODE_NETWORK);
std::string pszDest;
bool fInboundIn = false;
// Test that fFeeler is false by default.
std::unique_ptr<CNode> pnode1(new CNode(id++, NODE_NETWORK, height, hSocket, addr, 0, 0, CAddress(), pszDest, fInboundIn));
BOOST_CHECK(pnode1->fInbound == false);
BOOST_CHECK(pnode1->fFeeler == false);
fInboundIn = true;
std::unique_ptr<CNode> pnode2(new CNode(id++, NODE_NETWORK, height, hSocket, addr, 1, 1, CAddress(), pszDest, fInboundIn));
BOOST_CHECK(pnode2->fInbound == true);
BOOST_CHECK(pnode2->fFeeler == false);
}
// prior to PR #14728, this test triggers an undefined behavior
BOOST_AUTO_TEST_CASE(ipv4_peer_with_ipv6_addrMe_test)
{
// set up local addresses; all that's necessary to reproduce the bug is
// that a normal IPv4 address is among the entries, but if this address is
// !IsRoutable the undefined behavior is easier to trigger deterministically
{
LOCK(cs_mapLocalHost);
in_addr ipv4AddrLocal;
ipv4AddrLocal.s_addr = 0x0100007f;
CNetAddr addr = CNetAddr(ipv4AddrLocal);
LocalServiceInfo lsi;
lsi.nScore = 23;
lsi.nPort = 42;
mapLocalHost[addr] = lsi;
}
// create a peer with an IPv4 address
in_addr ipv4AddrPeer;
ipv4AddrPeer.s_addr = 0xa0b0c001;
CAddress addr = CAddress(CService(ipv4AddrPeer, 7777), NODE_NETWORK);
std::unique_ptr<CNode> pnode = MakeUnique<CNode>(0, NODE_NETWORK, 0, INVALID_SOCKET, addr, 0, 0, CAddress{}, std::string{}, false);
pnode->fSuccessfullyConnected.store(true);
// the peer claims to be reaching us via IPv6
in6_addr ipv6AddrLocal;
memset(ipv6AddrLocal.s6_addr, 0, 16);
ipv6AddrLocal.s6_addr[0] = 0xcc;
CAddress addrLocal = CAddress(CService(ipv6AddrLocal, 7777), NODE_NETWORK);
pnode->SetAddrLocal(addrLocal);
// before patch, this causes undefined behavior detectable with clang's -fsanitize=memory
AdvertiseLocal(&*pnode);
// suppress no-checks-run warning; if this test fails, it's by triggering a sanitizer
BOOST_CHECK(1);
}
BOOST_AUTO_TEST_SUITE_END()
| [
"[email protected]"
] | |
eb2020b3fea760def6fa2032cb439dc18c5eda86 | e94d402c7e0142a88529f8bd14fe3142ee59c1e6 | /tools/Speer/src/Rate4SiteSource/nj.h | c5c3b179d847c5e2bb89f23ef0fa424e6e5d657c | [
"LicenseRef-scancode-us-govt-public-domain",
"LicenseRef-scancode-public-domain"
] | permissive | shivashamloo/tcp-follow_up | 91610204771ba99c87a210c8e513b1c511e69100 | e483db1b2768f882a837e6fca695939d26371c94 | refs/heads/master | 2020-07-22T09:26:33.309331 | 2020-04-15T20:00:51 | 2020-04-15T20:00:51 | 207,148,876 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,320 | h | // $Id: nj.h,v 1.1 2008/11/17 16:45:32 lanczyck Exp $
// version 1.00
// last modified 3 Nov 2002
#ifndef ___NJ
#define ___NJ
#include "definitions.h"
#include "tree.h"
#include "sequenceContainer.h"
#include "njConstrain.h"
#include "distances2Tree.h"
using namespace std;
class NJalg : public distances2Tree {
public:
virtual NJalg* clone() const {return new NJalg(*this);}
// changed from computeNJtree to computeTree for competability to "distances2Tree"
virtual tree computeTree(VVdouble distances, const vector<string>& names, const tree * const constriantTree = NULL);
tree startingTree(const vector<string>& names);
tree startingTree(const tree& inTree);
void NJiterate(tree& et,vector<tree::nodeP>& currentNodes,
VVdouble& distanceTable);
void NJiterate(tree& et,vector<tree::nodeP>& currentNodes,
VVdouble& distanceTable, njConstraint& njc);
void calc_M_matrix(vector<tree::nodeP>& currentNodes,
const VVdouble& distanceTable,
const Vdouble & r_values,
int& minRaw,int& minCol);
void calc_M_matrix(vector<tree::nodeP>& currentNodes,
const VVdouble& distanceTable,
const Vdouble & r_values,
int& minRaw,int& minCol, const njConstraint& njc);
Vdouble calc_r_values(vector<tree::nodeP>& currentNodes,const VVdouble& distanceTable);
tree::nodeP SeparateNodes(tree& et,tree::nodeP node1,tree::nodeP node2);
void update3taxaLevel(VVdouble& distanceTable,Vdouble & r_values,vector<tree::nodeP>& currentNodes);
void updateBranchDistance(const VVdouble& disT,
const Vdouble& rValues,
tree::nodeP nodeNew,
tree::nodeP nodeI,
tree::nodeP nodeJ,
int Iplace, int Jplace);
void UpdateDistanceTableAndCurrentNodes(vector<tree::nodeP>& currentNodes,
VVdouble& distanceTable,
tree::nodeP nodeI,
tree::nodeP nodeJ,
tree::nodeP theNewNode,
int Iplace, int Jplace);
};
/*
//explicit NJalg(const tree& inTree, const computeDistance* cd);
explicit NJalg();
tree getNJtree() const {return *_myET;}// return a copy...
void computeTree(const sequenceContainer& sd,const computeDistance* cd,const vector<MDOUBLE> * weights = NULL);
VVdouble getDistanceTable(vector<string>& names) {
names.erase(names.begin(),names.end());
names = _nodeNames;
return _startingDistanceTable;}
VVdouble getLTable(vector<string>& names) {
names.erase(names.begin(),names.end());
names = _nodeNames;
return LTable;}
private:
//void starTreeFromInputTree(const tree& inTree);
void starTreeFromInputsequenceContainer(const sequenceContainer& sd);
void GetDisTable(const sequenceContainer& sd,const vector<MDOUBLE> * weights);
MDOUBLE dis(const int i, const int j) const{
return (i<j) ? distanceTable[i][j] : distanceTable[j][i];
}
void findMinM(int& minRaw,int& minCol);
tree* _myET;
VVdouble distanceTable;
VVdouble Mmatrix;
Vdouble r_values;
vector<tree::nodeP> currentNodes;
const computeDistance* _cd;
VVdouble _startingDistanceTable; // for printing etc... not used by the algorithm.
vector<string> _nodeNames; // for printing etc... not used by the algorithm.
VVdouble LTable;// for printing etc... not used by the algorithm.
*/
#endif
| [
"[email protected]"
] | |
a556e6c71c9015242b1bf68f8084fbf8d0261ca1 | 3e1e19cd491ea63fe7fa093fd3e910b2658c39a8 | /STLTest/STLTest/suanfa.cpp | 68ea0bb88f1eaee15cca8a51751d0570d3080e65 | [] | no_license | wgysarm/study | 6127d7ed7b2311f880b65fd7160f864ab79ce525 | b61949a389a58fde0d80b420833fecf97c032555 | refs/heads/master | 2021-07-16T03:35:56.665178 | 2017-08-14T13:47:56 | 2017-08-14T13:47:56 | 94,952,997 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 151 | cpp |
#include <numeric>
#include <algorithm>
#include <functional>
#include "suanfa.h"
using namespace std;
void suanfatest(void)
{
return;
}
| [
"[email protected]"
] | |
fab2060bd1ef187604af79e089f02ca2ceab0339 | 8aa7bf7fcc0d1cb92e595ed360fe0b093505b082 | /ac_automata/AcAutomata/tests/DictTrie_test/DictTrie_test.cpp | d9690099e0bbe8c252ca56ee78f7cadb99078682 | [] | no_license | Ivanqi/algorithm | 63323f6afcfdeb496c43a65034ea77d338291cf6 | 7d43d9e97de232f69e4eb687ed84d90bd1397df8 | refs/heads/master | 2022-04-28T17:07:09.193488 | 2022-03-21T12:55:15 | 2022-03-21T12:55:15 | 199,848,944 | 7 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 2,753 | cpp | #include "DictTrie.h"
static const char* const DICT_FILE = "../testdata/extra_dict/dict.small.utf8";
static const char* const USER_FILE = "../testdata/userdict.utf8";
void test_case_1() {
DictTrie *trie;
trie = new DictTrie(DICT_FILE);
delete trie;
}
void test_case_2() {
string s1, s2;
DictTrie trie(DICT_FILE);
string word("来到");
RuneStrArray uni;
assert(DecodeRunesInString(word, uni));
const DictUnit *du = trie.Find(uni.begin(), uni.end());
assert(du != NULL);
assert(2u == du->word.size());
assert(26469u == du->word[0]);
assert(21040u == du->word[1]);
assert("v" == du->tag);
word = "清华大学";
LocalVector<pair<size_t, const DictUnit*>> res;
const char *words[] = {"清", "清华", "清华大学"};
for (size_t i = 0; i < sizeof(words) / sizeof(words[0]); i++) {
assert(DecodeRunesInString(words[i], uni));
res.push_back(make_pair(uni.size() - 1, trie.Find(uni.begin(), uni.end())));
}
vector<pair<size_t, const DictUnit*>> vec;
vector<struct Dag> dags;
assert(DecodeRunesInString(word, uni));
trie.Find(uni.begin(), uni.end(), dags);
assert(dags.size() == uni.size());
assert(dags.size() != 0u);
}
void test_case_3() {
DictTrie trie(DICT_FILE, USER_FILE);
string word = "云计算";
RuneStrArray unicode;
assert(DecodeRunesInString(word, unicode));
const DictUnit *unit = trie.Find(unicode.begin(), unicode.end());
assert(unit != NULL);
word = "蓝翔";
assert(DecodeRunesInString(word, unicode));
unit = trie.Find(unicode.begin(), unicode.end());
assert(unit != NULL);
assert(unit->tag == "nz");
word = "区块链";
assert(DecodeRunesInString(word, unicode));
unit = trie.Find(unicode.begin(), unicode.end());
assert(unit != NULL);
assert(unit->tag == "nz");
}
void test_case_4() {
DictTrie trie(DICT_FILE, USER_FILE, DictTrie::WordWeightMax);
string word = "云计算";
RuneStrArray unicode;
assert(DecodeRunesInString(word, unicode));
const DictUnit *unit = trie.Find(unicode.begin(), unicode.end());
assert(unit != NULL);
}
void test_case_5() {
DictTrie trie(DICT_FILE, USER_FILE);
{
string word = "清华大学";
RuneStrArray unicode;
assert(DecodeRunesInString(word, unicode));
vector<struct Dag> res;
trie.Find(unicode.begin(), unicode.end(), res);
size_t nexts_sizes[] = {3, 2, 2, 1};
assert(res.size() == sizeof(nexts_sizes) / sizeof(nexts_sizes[0]));
for (size_t i = 0; i < res.size(); i++) {
assert(res[i].nexts.size() == nexts_sizes[i]);
}
}
}
int main() {
test_case_4();
return 0;
} | [
"[email protected]"
] | |
af9cf356fb6c99cdf26147f717690f7baaaa5dc0 | 82eda2c5b00944ac23d67c607294687ff7db40e9 | /cpp/containertablemodel.cpp | 0693aaefac1660456e2013bfe64cd6b23f9a70f4 | [] | no_license | simoneBarco/Qt-project | f43e4b115e59aff5d3f7cb54eb0b92f3fd5cfef6 | bc7964093ecfce8e4376cb6da7bfabc479f06633 | refs/heads/master | 2020-04-07T16:48:54.734492 | 2018-04-10T10:03:54 | 2018-04-10T10:03:54 | 124,224,181 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,191 | cpp | #include "containertablemodel.h"
#include <QString>
#include <QDebug>
ContainerTableModel::ContainerTableModel(QObject* parent):
QAbstractTableModel(parent) {}
//ritorna il numero di righe per ogni tabella
int ContainerTableModel::rowCount(const QModelIndex &parent) const{
Q_UNUSED(parent);
if(this->objectName()==QString("tabModelC"))
return StaticCont::countC();
if(this->objectName()==QString("tabModelR"))
return StaticCont::countR();
if(this->objectName()==QString("tabModelS"))
return StaticCont::countS();
else
return StaticCont::getDb().size();
}
//ritorna il numero di colonne per ogni tabella
int ContainerTableModel::columnCount(const QModelIndex &parent) const{
Q_UNUSED(parent);
if(this->objectName() == QString("tabModelRis"))
return 5;
else
return 4;
}
//metodo per visualizzare i dati corretti per ogni riga
QVariant ContainerTableModel::data(const QModelIndex &index, int role) const{
int dim = 0;
if(this->objectName() == QString("tabModelC")){
dim = StaticCont::countC();
}
if(this->objectName() == QString("tabModelR")){
dim = StaticCont::countR();
}
if(this->objectName() == QString("tabModelS")){
dim = StaticCont::countS();
}
if(this->objectName() == QString("tabModelRis")){
dim = StaticCont::getDb().size();
}
if(!index.isValid()){
return QVariant();
}
if(index.row() >= dim || index.row() < 0){
return QVariant();
}
if(role == Qt::DisplayRole){
if(this->objectName() == QString("tabModelRis")){
int row2= index.row();
SmartP& punt = StaticCont::get_Ass(row2);
if(index.column() == 0)
return punt->getNome();
else if(index.column() == 1)
return QString::fromStdString(punt->getDataSt().toString("dd/MM/yyyy").toStdString());
else if(index.column() == 2)
return QString::fromStdString(punt->getDataSc().toString("dd/MM/yyyy").toStdString());
else if(index.column() == 3){
if(dynamic_cast<Casa*>(&(*punt)))
return "Casa";
if(dynamic_cast<RCAuto*>(&(*punt)))
return "RCAuto";
if(dynamic_cast<Sanitaria*>(&(*punt)))
return "Sanitaria";
}
else if(index.column() == 4){
if(dynamic_cast<Casa*>(&(*punt)))
return StaticCont::get_Ass(row2)->prezzoAnnuo();
if(dynamic_cast<RCAuto*>(&(*punt)))
return StaticCont::get_Ass(row2)->prezzoAnnuo();
if(dynamic_cast<Sanitaria*>(&(*punt)))
return StaticCont::get_Ass(row2)->prezzoAnnuo();
}
}
else{
int row2= 0;
if(this->objectName() == QString("tabModelC"))
row2= StaticCont::indexC(index.row());
if(this->objectName() == QString("tabModelR"))
row2= StaticCont::indexR(index.row());
if(this->objectName() == QString("tabModelS"))
row2= StaticCont::indexS(index.row());
SmartP& punt = StaticCont::get_Ass(row2);
if(index.column() == 0)
return punt->getNome();
else if(index.column() == 1)
return QString::fromStdString(punt->getDataSt().toString("dd/MM/yyyy").toStdString());
else if(index.column() == 2)
return QString::fromStdString(punt->getDataSc().toString("dd/MM/yyyy").toStdString());
else if(index.column() == 3){
if(dynamic_cast<Casa*>(&(*punt)))
return StaticCont::get_Ass(row2)->prezzoAnnuo();
if(dynamic_cast<RCAuto*>(&(*punt)))
return StaticCont::get_Ass(row2)->prezzoAnnuo();
if(dynamic_cast<Sanitaria*>(&(*punt)))
return StaticCont::get_Ass(row2)->prezzoAnnuo();
}
}
}
return QVariant();
}
Qt::ItemFlags ContainerTableModel::flags(const QModelIndex &index) const{
if(!index.isValid())
return Qt::ItemIsEnabled;
return QAbstractTableModel::flags(index) | Qt::ItemIsSelectable;
}
//per assegnare un intestazione ad ogni colonna
QVariant ContainerTableModel::headerData(int section, Qt::Orientation orientation, int role) const{
if(role == Qt::DisplayRole){
if(orientation == Qt::Horizontal){
if(this->objectName() == QString("tabModelRis")){
switch(section){
case 0:
return QString("Nome");
case 1:
return QString("Data Stipula");
case 2:
return QString("Data Scadenza");
case 3:
return QString("Tipo Assicurazione");
case 4:
return QString("Prezzo Annuo");
}
}
else{
switch(section){
case 0:
return QString("Nome");
case 1:
return QString("Data Stipula");
case 2:
return QString("Data Scadenza");
case 3:
return QString("Prezzo Annuo");
}
}
}
}
return QVariant();
}
//viene chiamato ogni volta che viene modificata una riga all'interno del container e permette l'aggiornamento dei dati
bool ContainerTableModel::setData(const QModelIndex &index, const QVariant &value, int role) {
if(index.isValid() && role == Qt::EditRole){
int rig = 0;
if(this->objectName() == QString("tabModelC"))
rig= StaticCont::indexC(index.row());
if(this->objectName() == QString("tabModelR"))
rig= StaticCont::indexR(index.row());
if(this->objectName() == QString("tabModelS"))
rig= StaticCont::indexS(index.row());
if(index.column() == 0){
if(value.toString().isEmpty())
StaticCont::get_Ass(rig)->setNome("NoName");
else
StaticCont::get_Ass(rig)->setNome(value.toString());
}
if(index.column() == 1){
if(value.toString().isEmpty())
StaticCont::get_Ass(rig)->setDataSt(QDate(1970,1,1));
else
StaticCont::get_Ass(rig)->setDataSt(value.toDate());
}
if(index.column() == 2){
if(value.toString().isEmpty())
StaticCont::get_Ass(rig)->setDataSc(QDate(1971,1,1));
else
StaticCont::get_Ass(rig)->setDataSc(value.toDate());
}
emit dataChanged(index, index);
return true;
}
return false;
}
//per inserire una nuova voce nella tabella
bool ContainerTableModel::insertAssicurazione(Assicurazione *ass){
beginInsertRows(QModelIndex(), 0, 0);
Assicurazione* a(ass);
StaticCont::getDb().add(a);
endInsertRows();
return true;
}
bool ContainerTableModel::insertCasa(){
return insertAssicurazione(new Casa);
}
bool ContainerTableModel::insertRCAuto(){
return insertAssicurazione(new RCAuto);
}
bool ContainerTableModel::insertSanit(){
return insertAssicurazione(new Sanitaria);
}
bool ContainerTableModel::removeRows(int pos, int rig, const QModelIndex &index){//SISTEMARE
Q_UNUSED(index);
int pos2;
if(this->objectName() == QString("tabModelC")){
pos2= StaticCont::indexC(pos);
}
if(this->objectName() == QString("tabModelR")){
pos2= StaticCont::indexR(pos);
}
if(this->objectName() == QString("tabModelS")){
pos2= StaticCont::indexS(pos);
}
beginRemoveRows(QModelIndex(), pos2, pos2 + rig -1);
for(int r = 0; r < rig; ++r){
SmartP& a = StaticCont::get_Ass(pos2);
StaticCont::getDb().removeOne(a);
}
endRemoveRows();
emit layoutChanged();
return true;
}
void ContainerTableModel::updateView(const QModelIndex &ind1, const QModelIndex &ind2){
emit dataChanged(ind1, ind2);
}
| [
"[email protected]"
] | |
ecd6d387caaa907ba1f518f3b006a9bc55ea334c | d4f74021c5527c0344072f09719d1497fb5562d1 | /Server-ArduinoClient/CLIENTE(arduino)/Arduino-ESP8266_libs-master/ESP8266_TCP.cpp | df5fea228cedf7060e84316a91b216c017ce2251 | [
"Apache-2.0"
] | permissive | CarlosSequi/TFG | f895d186234a07072e97e215a23d426e890f1b5a | 24deb9010b5aca1326accb986eeed945536f7745 | refs/heads/master | 2020-06-10T18:06:37.556770 | 2019-06-25T12:34:26 | 2019-06-25T12:34:26 | 193,700,763 | 0 | 1 | Apache-2.0 | 2019-10-27T18:53:07 | 2019-06-25T12:10:12 | C# | UTF-8 | C++ | false | false | 15,520 | cpp | /*
WiFlyTCP.h - WiFly Library for Arduino
*/
#include "ESP8266_TCP.h"
/*
* two-wire constructor.
* Sets which wires should control the motor.
*/
ESP8266_TCP::ESP8266_TCP() {
}
void ESP8266_TCP::begin(Stream *serial, Stream *serialDebug, int pinReset)
{
pinMode(pinReset, OUTPUT);
digitalWrite(pinReset, HIGH);
this->pinReset = pinReset;
this->serial = serial;
this->serialDebug = serialDebug;
this->isDebug = true;
this->TCPConnected = false;
this->clientId = -1;
this->clientMessage = "";
this->runningState = WIFI_STATE_UNAVAILABLE;
delay(2000);
//debug.begin(serialport);
//this->baudrate = baudrate; // which step the motor is on
//this->serialport = serialport;
//this->serialport.begin(serialport);
}
void ESP8266_TCP::begin(Stream *serial, int pinReset)
{
pinMode(pinReset, OUTPUT);
digitalWrite(pinReset, HIGH);
this->pinReset = pinReset;
this->serial = serial;
this->isDebug = false;
this->TCPConnected = false;
this->clientId = -1;
this->clientMessage = "";
this->runningState = WIFI_STATE_UNAVAILABLE;
delay(2000);
//debug.begin(serialport);
//this->baudrate = baudrate; // which step the motor is on
//this->serialport = serialport;
//this->serialport.begin(serialport);
}
bool ESP8266_TCP::test() {
clearBuffer();
write("AT");
String data = readData();
debugPrintln(data);
if(data.equals("")) {
debugPrintln("RESET");
hardReset();
return true;
}
data = readData();
debugPrintln(data);
if(data.equals("busy now ...")) {
debugPrintln("RESET");
hardReset();
return true;
}
return readData().equals("OK");
}
void ESP8266_TCP::reset() {
clearBuffer();
write("AT+RST");
waitingForReset();
}
void ESP8266_TCP::hardReset() {
digitalWrite(this->pinReset, LOW);
delay(1000);
digitalWrite(this->pinReset, HIGH);
waitingForHardReset();
}
void ESP8266_TCP::waitingForReset() {
while(true) {
if(available() > 0) {
String data = readData(1000);
debugPrintln(data);
if(data.substring(1, 4).equals("ets")) {
debugPrintln("RESET");
delay(2000);
clearBuffer();
return;
}
}
}
}
void ESP8266_TCP::waitingForReset(unsigned long timeout) {
unsigned long t = millis();
while(millis() - t < timeout) {
if(available() > 0) {
String data = readData(1000);
if(data.substring(1, 4).equals("ets")) {
debugPrintln("RESET");
delay(2000);
clearBuffer();
return;
}
}
}
}
void ESP8266_TCP::waitingForHardReset() {
unsigned long t = millis();
while(true) {
if(available() > 0) {
String data = readData(1000);
if(data.equals("ready")) {
debugPrintln("RESET");
delay(2000);
clearBuffer();
return;
}
}
}
}
String ESP8266_TCP::connectAccessPoint(String ssid, String pass) {
setMode(WIFI_MODE_STATION);
write("AT+CWJAP=\"" + ssid + "\",\"" + pass + "\"");
delay(2000);
debugPrintln(readData());
debugPrintln(readData());
debugPrintln(readData());
waitingForReset(1000);
String ip = waitingForJoin();
debugPrintln(readData());
debugPrintln(ip);
return ip;
}
String ESP8266_TCP::waitingForJoin() {
unsigned long timeout = 20000;
unsigned long t = millis();
while(millis() - t < timeout) {
clearBuffer();
write("AT+CIFSR");
readData();
String data = readData();
if(!data.equals("") && !data.equals("ERROR") && !data.equals("busy now ...")) {
debugPrintln(data);
return data;
}
debugPrint(".");
delay(500);
}
return "0.0.0.0";
}
bool ESP8266_TCP::setMode(int mode) {
clearBuffer();
write("AT+CWMODE=" + String(mode));
delay(500);
debugPrintln(readData());
String data = readData();
if(data.equals("no change")) {
debugPrintln("No Change");
return true;
} else if(data.equals("OK")) {
reset();
debugPrintln("OK");
return true;
}
data = readData();
debugPrintln(data);
if(data.equals("OK")) {
reset();
debugPrintln("OK");
return true;
}
return false;
}
bool ESP8266_TCP::setAP(String ssid, String pass, int channel) {
clearBuffer();
write("AT+CWSAP=\"" + ssid + "\",\"" + pass + "\"," + String(channel) + ",4");
debugPrintln(readData());
delay(4000);
debugPrintln(readData());
String data = readData();
debugPrintln(data);
return data.equals("OK");
}
bool ESP8266_TCP::isNewAPSetting(String ssid, String pass, int channel) {
clearBuffer();
write("AT+CWSAP?");
debugPrintln(readData());
String data = readData();
debugPrintln(data);
data = data.substring(8, data.length());
byte ssidLength = findChar(data, 0, '\"');
String ssidTmp = data.substring(0, ssidLength);
byte passLength = findChar(data, ssidLength + 3, '\"');
String passTmp = data.substring(ssidLength + 3, passLength);
byte channelLength = findChar(data, passLength + 2, ',');
int channelTmp = data.substring(passLength + 2, channelLength).toInt();
if(ssidTmp.equals(ssid) && passTmp.equals(pass) && channelTmp == channel) {
return true;
}
return false;
}
bool ESP8266_TCP::setMux(int mux) {
clearBuffer();
write("AT+CIPMUX=" + String(mux));
debugPrintln(readData());
String data = readData();
debugPrintln(data);
if(data.equals("no change") || data.equals("OK"))
return true;
data = readData();
debugPrintln(data);
return data.equals("OK");
}
bool ESP8266_TCP::enableTCPServer(int port) {
clearBuffer();
write("AT+CIPSERVER=1," + String(port));
debugPrintln(readData());
String data = readData();
debugPrintln(data);
if(data.equals("no change"))
return true;
data = readData();
debugPrintln(data);
return data.equals("OK");
}
void ESP8266_TCP::openAccessPoint(String ssid, String pass, int channel) {
if(!isNewAPSetting(ssid, pass, channel)) {
debugPrintln("SET NEW AP");
setAP(ssid, pass, channel);
reset();
}
setMode(WIFI_MODE_AP);
}
bool ESP8266_TCP::closeTCPServer() {
clearBuffer();
write("AT+CIPSERVER=0");
debugPrintln(readData());
debugPrintln(readData());
String data = readData();
debugPrintln(data);
return data.equals("OK");
}
/*
bool ESP8266_TCP::isTCPEnabled() {
clearBuffer();
write("AT+CIPMUX?");
debugPrintln(readData());
String data = readData();
debugPrintln(data);
return data.equals("+CIPMUX:1");
}*/
void ESP8266_TCP::closeTCPConnection() {
delay(1000);
clearBuffer();
write("AT+CIPCLOSE");
debugPrintln(readData());
}
void ESP8266_TCP::closeTCPConnection(int id) {
delay(1000);
clearBuffer();
write("AT+CIPCLOSE=" + String(id));
debugPrintln(readData());
}
void ESP8266_TCP::openTCPServer(int port, int timeout) {
setMux(WIFI_MUX_MULTI);
enableTCPServer(port);
setTCPTimeout(timeout);
}
bool ESP8266_TCP::setTCPTimeout(int timeout) {
clearBuffer();
write("AT+CIPSTO=" + String(timeout));
debugPrintln(readData());
debugPrintln(readData());
String data = readData();
debugPrintln(data);
return data.equals("OK");
}
void ESP8266_TCP::connectTCP(String ip, int port) {
clearBuffer();
write("AT+CIPSTART=\"TCP\",\"" + ip + "\"," + String(port) );
String data =readData();
data =readData();
debugPrintln(data);
int pos=data.indexOf("CONN");
if (pos>=0) {
setRunningState(WIFI_STATE_CONNECT);
}
else{
setRunningState(WIFI_STATE_UNAVAILABLE);
}
}
void ESP8266_TCP::waitingForTCPConnection() {
}
void ESP8266_TCP::setRunningState(int state) {
this->runningState = state;
}
int ESP8266_TCP::getRunningState() {
return this->runningState;
}
void ESP8266_TCP::flush() {
this->serial->flush();
}
int ESP8266_TCP::isNewDataComing(byte type) {
if(type == WIFI_CLIENT) {
String data = read();
if(!data.equals("")) {
if(data.substring(2, 6).equals("+IPD")) {
int lastPosition = findChar(data, 7, ':');
int length = data.substring(7, lastPosition).toInt() - 1;
lastPosition += 2;
this->clientMessage = data.substring(lastPosition, lastPosition + length);
return WIFI_NEW_MESSAGE;
} else if(data.substring(3, 6).equals("ets")) {
//debugPrintln("RESET");
delay(2000);
clear();
return WIFI_NEW_RESET;
} else if(data.substring(6, 12).equals("Unlink")
|| (data.substring(9, 15).equals("Unlink") && data.substring(2, 7).equals("ERROR"))) {
//debugPrintln("Disconnected");
this->TCPConnected = false;
setRunningState(WIFI_STATE_UNAVAILABLE);
return WIFI_NEW_DISCONNECTED;
} else if(data.substring(2, 4).equals("OK") && data.substring(6, 12).equals("Linked")) {
setRunningState(WIFI_STATE_IDLE);
//debugPrintln("Connected");
this->TCPConnected = true;
return WIFI_NEW_CONNECTED;
} else if(data.substring(2, 9).equals("SEND OK")) {
setRunningState(WIFI_STATE_IDLE);
//debugPrintln("Sent!!");
return WIFI_NEW_SEND_OK;
} else if(data.substring(0, 14).equals("ALREAY CONNECT")
&& data.substring(16, 17).equals("OK")
&& data.substring(19, 24).equals("Unlink")) {
this->TCPConnected = false;
setRunningState(WIFI_STATE_UNAVAILABLE);
return WIFI_NEW_DISCONNECTED;
} else if(data.substring(0, 14).equals("ALREAY CONNECT")) {
return WIFI_NEW_ALREADY_CONNECT;
} else {
//debugPrintln("******");
//debugPrintln(data);
this->clientMessage = data;
return WIFI_NEW_ETC;
}
}
return WIFI_NEW_NONE;
} else if(type == WIFI_SERVER) {
String data = read();
if(!data.equals("")) {
if(data.substring(2, 6).equals("+IPD")) {
this->clientId = data.substring(7, 8).toInt();
int lastPosition = findChar(data, 9, ':');
int length = data.substring(9, lastPosition).toInt() + 1;
if(data.charAt(lastPosition + 1) == '\n') {
this->clientMessage = data.substring(lastPosition + 2, lastPosition + length + 1);
} else {
this->clientMessage = data.substring(lastPosition + 1, lastPosition + length);
}
//this->clientMessage = data.substring(lastPosition + 1, lastPosition + length);
return WIFI_NEW_MESSAGE;
} else if(data.substring(3, 6).equals("ets")) {
//debugPrintln("RESET");
delay(2000);
clear();
return WIFI_NEW_RESET;
} else if((data.length() == 1 && data.charAt(0) == 0x0A)
|| (data.substring(2, 4).equals("OK") && data.substring(6, 12).equals("Unlink"))) {
//debugPrintln("Disconnected");
this->TCPConnected = false;
setRunningState(WIFI_STATE_UNAVAILABLE);
return WIFI_NEW_DISCONNECTED;
} else if(data.substring(0, 4).equals("Link")
|| data.substring(2, 4).equals("Link")
|| data.substring(5, 11).equals("Link")) {
setRunningState(WIFI_STATE_IDLE);
//debugPrintln("Connected");
this->TCPConnected = true;
return WIFI_NEW_CONNECTED;
} else if(data.substring(2, 9).equals("SEND OK")) {
delay(2000);
setRunningState(WIFI_STATE_IDLE);
//debugPrintln("Sent!!");
return WIFI_NEW_SEND_OK;
} else {
//debugPrintln("******");
//debugPrintln(data);
//debugPrintln(data.substring(2, 9));
debugPrintln("******");
//debugPrintln(data);
this->clientMessage = data;
debugPrintln(data.substring(2, 4));
debugPrintln(data.substring(6, 12));
return WIFI_NEW_ETC;
}
}
return WIFI_NEW_NONE;
/*
String data = read();
if(!data.equals("")) {
if(data.substring(2, 6).equals("+IPD")) {
this->clientId = data.substring(7, 8).toInt();
int lastPosition = findChar(data, 9, ':');
int length = data.substring(9, lastPosition).toInt();
lastPosition += 1;
this->clientMessage = data.substring(lastPosition + 1, lastPosition + length);
return true;
} else if(data.substring(3, 6).equals("ets")) {
debugPrintln("RESET");
delay(2000);
clear();
return true;
} else if(data.substring(6,12).equals("Unlink")) {
debugPrintln("Disconnected");
this->TCPConnected = false;
return true;
} else if(data.substring(0, 4).equals("Link")) {
debugPrintln("Connected");
this->TCPConnected = true;
//getClientList();
return true;
} else {
debugPrintln("ETC");
debugPrintln(data);
debugPrintln(data.substring(0, 3));
return true;
}
}
*/
return false;
}
}
int ESP8266_TCP::findChar(String str, int start, char c) {
for(int i = start ; i < str.length() ; i++) {
if(str.charAt(i) == c)
return i;
}
return -1;
}
int ESP8266_TCP::getId() {
return this->clientId;
}
String ESP8266_TCP::getMessage() {
return this->clientMessage;
}
void ESP8266_TCP::clearBuffer() {
while(available() > 0) {
serial->read();
}
}
void ESP8266_TCP::clear() {
clearBuffer();
this->clientId = -1;
this->clientMessage = "";
this->TCPConnected = false;
}
void ESP8266_TCP::debugPrintln(String str) {
if(this->isDebug)
serialDebug->println(str);
}
void ESP8266_TCP::debugPrint(String str) {
if(this->isDebug)
serialDebug->print(str);
}
String ESP8266_TCP::readData() {
String data = "";
while(available() > 0) {
char r = serial->read();
if (r == '\n') {
return data;
} else if(r == '\r') {
} else {
data += r;
}
}
return "";
}
void ESP8266_TCP::write(String str) {
this->serial->println(str);
flush();
delay(50);
}
bool ESP8266_TCP::send(String message) {
if(getRunningState() == WIFI_STATE_IDLE) {
debugPrintln("Send : " + message);
write("AT+CIPSEND=" + String(message.length() + 1));
serial->print(message + " ");
flush();
debugPrintln(readData());
debugPrintln(readData());
setRunningState(WIFI_STATE_SEND);
return true;
}
return false;
}
bool ESP8266_TCP::send(int id, String message) {
if(getRunningState() == WIFI_STATE_IDLE) {
debugPrintln("ID : " + String(id) + " Send : " + message);
clearBuffer();
write("AT+CIPSEND=" + String(id) + "," + String(message.length()));
serial->print(message);
flush();
debugPrintln(readData());
debugPrintln(readData());
setRunningState(WIFI_STATE_SEND);
return true;
}
return false;
//waitForSendStatus();
}
/*
bool ESP8266_TCP::waitForSendStatus() {
unsigned long timeout = 10000;
unsigned long t = millis();
while(millis() - t < timeout) {
if(available()) {
String status = readData(100);
if(status.equals("SEND OK") || status.equals("OK")) {
return true;
} else if(!status.equals("") && !status.substring(0, 2).equals("AT")
&& !status.substring(0, 1).equals(">")) {
return false;
}
}
}
return false;
}*/
void ESP8266_TCP::printClientList() {
clearBuffer();
write("AT+CWLIF");
delay(1000);
debugPrintln(readData(100));
debugPrintln(readData(100));
debugPrintln(readData(100));
debugPrintln(readData(100));
debugPrintln(readData(100));
debugPrintln(readData(100));
}
int ESP8266_TCP::available() {
return this->serial->available();
}
String ESP8266_TCP::read() {
String data = readTCPData();
if(data.equals("Unlink")) {
this->TCPConnected = false;
clearBuffer();
return "";
}
return data;
}
String ESP8266_TCP::readData(unsigned long timeout) {
String data = "";
unsigned long t = millis();
while(millis() - t < timeout) {
if(available() > 0) {
char r = serial->read();
if (r == '\n') {
return data;
} else if(r == '\r') {
} else {
data += r;
t = millis();
}
}
}
return "";
}
String ESP8266_TCP::readTCPData() {
unsigned long timeout = 100;
unsigned long t = millis();
String data = "";
while(millis() - t < timeout) {
if(available() > 0) {
char r = serial->read();
if(data.equals("Unlink")) {
return data;
} else {
data += r;
t = millis();
}
}
}
return data;
}
| [
"[email protected]"
] | |
a408867d00961c89c45f31096a7f575adea319ea | 6ac945be277eed33c654862128283fed6bb5d0d5 | /Lab_5/c/stack_with_queue.cpp | 2334f17a99251c8082f65bc4945337b417340954 | [] | no_license | JACK0YORK/Data-Structures-and-Algorithms | 370edb84ff1912f9d64498a7b0e3d1559b2f44f5 | a5703b043bf40f1af42959bc29e45732c879b08b | refs/heads/main | 2023-04-12T03:13:17.109243 | 2021-04-19T16:15:43 | 2021-04-19T16:15:43 | 328,751,965 | 0 | 0 | null | 2021-01-11T21:57:55 | 2021-01-11T18:11:34 | Java | UTF-8 | C++ | false | false | 732 | cpp | #include "queue.h"
template <typename T>
class StackWithQueue
{
my::Queue<T> *queue1 = new my::Queue<T>();
my::Queue<T> *queue2 = new my::Queue<T>();
public:
void push(T value)
{
queue2->enqueue(value);
while (!queue1->isEmpty())
{
queue2->enqueue(queue1->dequeue());
}
auto temp = queue1;
queue1 = queue2;
queue2 = temp;
}
T pop()
{
return queue1->dequeue();
}
T top()
{
return queue1->peek();
}
bool isEmpty()
{
return queue1->isEmpty();
}
int size()
{
return queue1->size();
}
char print()
{
queue1->print();
return 0;
}
};
| [
"[email protected]"
] | |
a27d30843bccf69d8c82ebc6631a93aee421f3d6 | a802488c68d5c8607e8d4696b8244eaacc9c3ac2 | /DK/DKFramework/DKSpline.h | 73574d9bf6370279576abbdd7e9fac555ad9de50 | [
"LGPL-2.0-or-later",
"BSD-3-Clause"
] | permissive | Hongtae/DKGL | e311c6e528349c8b9e7e8392f1d01ac976e76be1 | eb33d843622504cd6134accf08c8ec2c98794b55 | refs/heads/develop | 2023-04-28T22:02:44.866063 | 2023-01-14T02:11:30 | 2023-01-14T02:11:30 | 30,572,734 | 11 | 3 | BSD-3-Clause | 2023-01-18T03:02:10 | 2015-02-10T03:23:18 | C | UTF-8 | C++ | false | false | 3,208 | h | //
// File: DKSpline.h
// Author: Hongtae Kim ([email protected])
//
// Copyright (c) 2004-2016 Hongtae Kim. All rights reserved.
//
#pragma once
#include "../DKFoundation.h"
#include "DKVector2.h"
#include "DKVector3.h"
#pragma pack(push, 4)
namespace DKFramework
{
/// @brief spline class, calculates spline curve.
///
/// used to get smooth interpolated curve between points.
///
/// CatmullRom: The curve at two intersection points.
/// This spline creates a curve that connects two points.
/// Creates a curve between p1 and p2 at the given four points
/// (p0, p1, p2, p3).
///
/// - UniformCubic: Basis spline (B-spline)
/// This curve does not pass through the points.
/// the curve is completely contained in the convex hull of its control
/// points.
/// Creates a curve between p1 and p2 at the given four points
/// (p0, p1, p2, p3).
///
/// - Hermite: Calculates a curve with tangent vectors.
/// Creates a curve between p0 and p1 with given four points
/// (p0, p1, t0, t1).
/// Where t0 is a tangent vector of p0, and t1 is a tengent vector of p1
/// The tangent vector (t0, t1) can control the curve direction
/// and speed.
///
/// - Bezier: 3 degree bezier curve.
/// The curve is completely contained in the convex hull of its control
/// points.
/// Creates a curve between p0, p1, p2, p3 with the given four points
/// (p0, p1, p2, p3).
/// Where p1,p2 are control points, and the curve does not pass throuth
/// these points.
class DKGL_API DKSpline
{
public:
enum Type
{
CatmullRom = 0,
UniformCubic,
Hermite,
Bezier,
};
DKSpline();
DKSpline(float p0, float p1, float p2, float p3);
float Interpolate(float t, Type c) const;
union
{
struct
{
float point0;
float point1;
float point2;
float point3;
};
float points[4];
};
};
class DKSpline2
{
public:
DKSpline2()
:point0(0, 0), point1(0, 0), point2(0, 0), point3(0, 0)
{
}
DKSpline2(const DKVector2& p0, const DKVector2& p1, const DKVector2& p2, const DKVector2& p3)
: point0(p0), point1(p1), point2(p2), point3(p3)
{
}
DKVector2 Interpolate(float t, DKSpline::Type c) const
{
return DKVector2(
DKSpline(point0.x, point1.x, point2.x, point3.x).Interpolate(t, c),
DKSpline(point0.y, point1.y, point2.y, point3.y).Interpolate(t, c)
);
}
DKVector2 point0;
DKVector2 point1;
DKVector2 point2;
DKVector2 point3;
};
class DKSpline3
{
public:
DKSpline3()
:point0(0, 0, 0), point1(0, 0, 0), point2(0, 0, 0), point3(0, 0, 0)
{
}
DKSpline3(const DKVector3& p0, const DKVector3& p1, const DKVector3& p2, const DKVector3& p3)
: point0(p0), point1(p1), point2(p2), point3(p3)
{
}
DKVector3 Interpolate(float t, DKSpline::Type c) const
{
return DKVector3(
DKSpline(point0.x, point1.x, point2.x, point3.x).Interpolate(t, c),
DKSpline(point0.y, point1.y, point2.y, point3.y).Interpolate(t, c),
DKSpline(point0.z, point1.z, point2.z, point3.z).Interpolate(t, c)
);
}
DKVector3 point0;
DKVector3 point1;
DKVector3 point2;
DKVector3 point3;
};
}
#pragma pack(pop)
| [
"[email protected]"
] | |
3c67c3ed7a9300b89ea4bbde7d57e984302fb521 | 45d300db6d241ecc7ee0bda2d73afd011e97cf28 | /OTCDerivativesCalculatorModule/Project_Cpp/lib_static/FpmlSerialized/GenClass/built_in_type/XsdTypeNonPositiveInteger.hpp | d839d5596e3bfa4054cdc02305c604a24b42e753 | [] | no_license | fagan2888/OTCDerivativesCalculatorModule | 50076076f5634ffc3b88c52ef68329415725e22d | e698e12660c0c2c0d6899eae55204d618d315532 | refs/heads/master | 2021-05-30T03:52:28.667409 | 2015-11-27T06:57:45 | 2015-11-27T06:57:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,130 | hpp | #ifndef FpmlSerialized_XsdTypeNonPositiveInteger_hpp
#define FpmlSerialized_XsdTypeNonPositiveInteger_hpp
#include <string>
#include <iserialized.hpp>
#include <ql/time/date.hpp>
using namespace QuantLib;
namespace FpmlSerialized {
class XsdTypeNonPositiveInteger : public ISerialized {
public:
XsdTypeNonPositiveInteger(TiXmlNode* xmlNode)
: ISerialized(xmlNode){
TiXmlElement* xmlElem = xmlNode->ToElement();
const char *pKey = xmlElem->Value();
const char *pText = xmlElem->GetText();
if( pText ) { this->valueStr = pText; }
else if( xmlElem->NoChildren() ) { this->valueStr = "NULL ( empty value )"; }
else { this->valueStr = "NULL value ( Node has Children )"; }
#ifdef ConsolePrint
FileManager::instance().outFile_ << FileManager::instance().tap_.c_str() << " " << xmlNode->Value() << " : " << this->valueStr.c_str() << std::endl;
#endif
}
public:
std::string SValue(){return this->valueStr;}
double DValue(){return (double)(atof(this->valueStr.c_str()));}
int IValue(){return (int)(atoi(this->valueStr.c_str()));}
unsigned int UIValue(){return (unsigned int)(atoi(this->valueStr.c_str()));}
long LValue(){return (long)(atol(this->valueStr.c_str()));}
bool BValue()
{
std::string str = this->valueStr.c_str();
if(str == "true" || str == "1"){return true;}
else if(str == "false" || str == "0"){return false;}
else {return false;}
}
QuantLib::Date dateValue()
{
Year year = 1;
Month month = Month(1);
Day day = 1;
if( valueStr.length() == 10 ){
year = atoi(valueStr.substr(0,4).c_str());
month = Month(atoi(valueStr.substr(5,2).c_str()));;
day = atoi(valueStr.substr(8,4).c_str());;
}else
{
QL_FAIL(valueStr);
}
return Date(day,month,year);
}
private:
std::string valueStr;
};
}
#endif
| [
"[email protected]"
] | |
29ff1f6b46ead1ed493cfa9cd0e9c0ba6ed6df12 | 286bc6ecf3915f9820ed363f4812d076fd32d93e | /073. Search a 2D Matrix/TEST.cc | 536a7838d79f60235ce5a653dcc4c6326687972a | [
"MIT"
] | permissive | Rich-Leung/LeetCode | 10dc871a9ead28f7d12907484faac5bf4932bd85 | 6aa837257dd14d841d88689fc2d3b4b3522a96d4 | refs/heads/master | 2023-04-11T00:46:09.257728 | 2021-04-18T16:33:03 | 2021-04-18T16:33:03 | 359,196,268 | 0 | 0 | MIT | 2021-04-18T16:26:12 | 2021-04-18T16:26:12 | null | UTF-8 | C++ | false | false | 606 | cc | #define CATCH_CONFIG_MAIN
#include "../Catch/single_include/catch.hpp"
#include "solution.h"
TEST_CASE("Search a 2D Matrix", "[searchMatrix]")
{
Solution s;
SECTION( "1" )
{
std::vector<std::vector<int> > vec{{1,3,5,7},{10,11,16,20},{23,30,34,50}};
REQUIRE( s.searchMatrix(vec, 3) == true );
}
SECTION( "2" )
{
std::vector<std::vector<int> > vec{{1},{1}};
REQUIRE( s.searchMatrix(vec, 0) == false );
}
SECTION( "3" )
{
std::vector<std::vector<int> > vec{{1,3}};
REQUIRE( s.searchMatrix(vec, 0) == false );
}
}
| [
"[email protected]"
] | |
1bb3e2d06fae16a0dbe7f7c48376780900bf670d | fd83552af4723236e3badfdb5fb2dd9058378039 | /public/plagiarism_plugin/dataset/dataset_1/24 26 5114100188--tamagotchi.cpp | 6275bd6635ea267cc4ef01afc7ee7891cbbf55ce | [
"MIT"
] | permissive | laurensiusadi/elearning-pweb | 248086e0eb75c62f6d8ed104300645488d20ffa2 | c72ae1fc414895919ef71ae370686353d9086bce | refs/heads/master | 2020-04-06T04:43:39.941295 | 2017-03-27T09:58:31 | 2017-03-27T09:58:31 | 82,892,981 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,295 | cpp | #include <iostream>
#include <string>
#include <time.h>
#include <stdlib.h>
using namespace std;
class Petstat
{
public:
string nama;
int mandi;
int makan;
int main;
int obat;
int tidur;
int koin;
Petstat() {
}
void Menupet(Petstat pets)
{
cout << pets.nama << "'s status:\nCleanness : " << pets.mandi << "\nHunger : " << pets.makan << "\nHappiness : " << pets.main << "\nHealthy : " << pets.obat << "\nSleepy : " << pets.tidur << "\n\nYour coin: " << pets.koin << "\n\n";
}
void Stat()
{
if (pets.mandi <= 3)
{
cout << pets.nama << " is smell! Please clean it now!\n";
}
if (pets.makan <= 2)
{
cout << pets.nama << " is hungry. Feed it.\n";
}
if (pets.main <= 4)
{
cout << pets.nama << " feels lonely :(. Play with him/her now.\n";
}
if (pets.obat <= 3)
{
cout << pets.nama << " is sick! Give him/her medicine now!\n";
}
if (pets.tidur <= 2)
{
cout << pets.nama << " is sleepy. Let him/her sleep.\n";
}
}
void Petmandi()
{
if (pets.mandi + 2 <= 10)
{
pets.mandi += 2;
}
if (pets.makan - 2 >= 0)
{
pets.makan -= 2;
}
if (pets.main + 4 <= 10)
{
pets.main += 2;
}
if (pets.obat - 1 >= 0)
{
pets.obat--;
}
if (pets.tidur + 2 <= 10)
{
pets.tidur += 2;
}
if (pets.koin + 1 <= 10)
{
pets.koin++;
}
/*cout << "\nYou got a coin!!!\n";*/
cout << "Your pet is clean now.\n\n";
}
void Petmakan()
{
if (pets.mandi + 3 <= 10)
{
pets.mandi += 3;
}
if (pets.makan + 4 <= 10)
{
pets.makan += 4;
}
if (pets.obat + 1 <= 10)
{
pets.obat++;
}
if (pets.main - 2 >= 0)
{
pets.main -= 2;
}
if (pets.tidur - 2 >= 0)
{
pets.tidur -= 2;
}
if (pets.koin - 2 >= 0)
{
pets.koin -= 2;
}
cout << "You eat with your pet, your pet is full now.\n\n";
}
void Petmain()
{
if (pets.mandi - 2 >= 0)
{
pets.mandi -= 2;
}
if (pets.makan - 4 >= 0)
{
pets.makan -= 4;
}
if (pets.obat - 1 >= 0)
{
pets.obat--;
}
if (pets.main + 3 <= 10)
{
pets.main += 3;
}
if (pets.tidur - 3 >= 0)
{
pets.tidur -= 3;
}
if (pets.koin + 5 <= 10)
{
pets.koin += 5;
}
/*cout << "\nYeay! You got more coins!!!\n\n";*/
cout << "You play with your pet, your pet feels happy.\n\n";
}
void Petobat()
{
if (pets.mandi - 3 >= 0)
{
pets.mandi -= 3;
}
if (pets.makan + 1 <= 10)
{
pets.makan++;
}
if (pets.obat + 4 <= 10)
{
pets.obat += 4;
}
if (pets.main - 2 >= 0)
{
pets.main -= 2;
}
if (pets.tidur - 3 >= 0)
{
pets.tidur -= 3;
}
if (pets.koin - 3 >= 0)
{
pets.koin -= 3;
}
cout << "Your pet is healthy.\n\n";
}
void Petidur()
{
if (pets.mandi - 3 >= 0)
{
pets.mandi -= 3;
}
if (pets.makan - 3 >= 0)
{
pets.makan -= 3;
}
if (pets.obat + 1 <= 10)
{
pets.obat++;
}
if (pets.main - 2 >= 0)
{
pets.main -= 2;
}
if (pets.tidur + 5 <= 10)
{
pets.tidur += 5;
}
if (pets.koin + 2 <= 10)
{
pets.koin += 2;
}
/*cout << "\nYeay! You got more coins!!!\n\n";*/
cout << "Your pet is sleep now. Don't be noisy.\n\n";
}
};
int main()
{
Petstat pet;
int nilai = 1, menu;
cout << "*************** WELCOME ***************\n";
cout << "Insert your pet's name: ";
cin >> pet.nama;
srand(time(NULL));
pet.Petmandi = rand() % 11;
pet.Petmakan = rand() % 11;
pet.Petmain = rand() % 11;
pet.Petobat = rand() % 11;
pet.Petidur = rand() % 11;
pet.koin = 0;
cout << "Your pet's name is " << pet.nama << "\n\n";
pet.Menupet(pet);
while (nilai == 1)
{
cout << "\nWhat do you want to do with your pet?\n";
cout << "1. Clean your pet\n";
cout << "2. Feed your pet\n";
cout << "3. Play with your pet\n";
cout << "4. Give medicine to your pet\n";
cout << "5. Let it sleep\n";
cout << "6. Exit\n";
cout << "\nInsert your option : ";
cin >> menu;
if (menu == 1)
{
pet.Petmandi();
}
else if (menu == 2)
{
pet.Petmakan();
}
else if (menu == 3)
{
pet.Petmain();
}
else if (menu == 4)
{
pet.Petobat();
}
else if (menu == 5)
{
pet.Petidur();
}
else if (menu == 6)
{
nilai = 0;
cout << "\n*************** YOU LEAVE " << Pet.nama << "***************\n" << endl;
}
}
cout << "\n*************** GAME OVER ***************\n";
cin.get();
} | [
"[email protected]"
] | |
8f21a419671f97f31c463ac64cc690fd0e45df44 | 426be981352881138c26492c0cdc1107a9c0afa4 | /x-ees/src/main.cpp | 5a1a8efc21c97df8511b9ec1badfd95d751dcf5a | [] | no_license | OverfittingStudyRoom/x-trader | 491910f7284913330c4afac767c3c00893a9b9ba | 247d1043bbb98ee7d53b5de447904ebde186093c | refs/heads/master | 2023-03-31T13:01:38.097797 | 2020-03-12T12:29:37 | 2020-03-12T12:29:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,430 | cpp | #include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <dlfcn.h>
#include <string>
#include <signal.h> /* signal */
#include "vrt_value_obj.h"
#include "l1md_producer.h"
#include "fulldepthmd_producer.h"
#include "tunn_rpt_producer.h"
#include "uni_consumer.h"
#include "pos_calcu.h"
/* Note that the parameter for queue size is a power of 2. */
#define QUEUE_SIZE 32768
UniConsumer *uniConsumer = NULL;
FullDepthMDProducer *fulldepth_md_producer = NULL;
L1MDProducer *l1_md_producer = NULL;
TunnRptProducer *tunnRptProducer = NULL;
static void
SIG_handler(int s)
{
uniConsumer->Stop();
//exit(0); /* call exit for the signal */
}
int main(/*int argc, const char **argv*/)
{
// clog setting CLOG_LEVEL_WARNING
clog_set_minimum_level(CLOG_LEVEL_WARNING);
FILE *fp;/*文件指针*/
fp=fopen("./x-trader.log","w+");
Log::fp = fp;
struct clog_handler *clog_handler = clog_stream_handler_new_fp(fp, true, "%l %m");
clog_handler_push_process(clog_handler);
#ifdef LATENCY_MEASURE
clog_warning("latency measure on");
#else
clog_warning("latency measure off");
#endif
#ifdef COMPLIANCE_CHECK
clog_warning("COMPLIANCE_CHECK on");
#else
clog_warning("COMPLIANCE_CHECK off");
#endif
#ifdef PERSISTENCE_ENABLED
clog_warning("PERSISTENCE_ENABLED on");
#else
clog_warning("PERSISTENCE_ENABLEDon off");
#endif
struct sigaction SIGINT_act;
SIGINT_act.sa_handler = SIG_handler;
sigemptyset(&SIGINT_act.sa_mask);
SIGINT_act.sa_flags = 0;
sigaction(SIGUSR2, &SIGINT_act, NULL);
// version
clog_warning("version:x-ees_2019-3-20_r");
clog_warning("max contract count:%d",MAX_CONTRACT_COUNT );
struct vrt_queue *queue;
int64_t result;
rip_check(queue = vrt_queue_new("x-trader queue", vrt_hybrid_value_type(), QUEUE_SIZE));
tunnRptProducer = new TunnRptProducer(queue);
fulldepth_md_producer = new FullDepthMDProducer(queue);
l1_md_producer = new L1MDProducer(queue);
uniConsumer = new UniConsumer (queue, fulldepth_md_producer, l1_md_producer, tunnRptProducer);
uniConsumer->Start();
fflush (fp);
// free vrt_queue
vrt_queue_free(queue);
delete uniConsumer;
delete tunnRptProducer;
delete l1_md_producer;
delete fulldepth_md_producer;
// clog: free resources
pos_calc::destroy_instance();
clog_handler_free(clog_handler);
return 0;
}
| [
"[email protected]"
] | |
2e02caed82e179cabab459ad07bcfda752ab77b8 | 8a55bdec478d2fb48508deac13ca3aeeda46fa06 | /src/qt/receiverequestdialog.cpp | 83341d93ebb301830ab867d9c7fcbfa04884f4ff | [
"MIT"
] | permissive | hideoussquid/aureus-core-gui | 83b0525e1afa349e0834e1a3baed5534043cd689 | ce075f2f0f9c99a344a1b0629cfd891526daac7b | refs/heads/master | 2021-01-19T00:04:39.888184 | 2017-04-04T08:15:18 | 2017-04-04T08:15:18 | 87,142,504 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,067 | cpp | // Copyright (c) 2011-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "receiverequestdialog.h"
#include "ui_receiverequestdialog.h"
#include "aureusunits.h"
#include "guiconstants.h"
#include "guiutil.h"
#include "optionsmodel.h"
#include "walletmodel.h"
#include <QClipboard>
#include <QDrag>
#include <QMenu>
#include <QMimeData>
#include <QMouseEvent>
#include <QPixmap>
#if QT_VERSION < 0x050000
#include <QUrl>
#endif
#if defined(HAVE_CONFIG_H)
#include "config/aureus-config.h" /* for USE_QRCODE */
#endif
#ifdef USE_QRCODE
#include <qrencode.h>
#endif
QRImageWidget::QRImageWidget(QWidget *parent):
QLabel(parent), contextMenu(0)
{
contextMenu = new QMenu(this);
QAction *saveImageAction = new QAction(tr("&Save Image..."), this);
connect(saveImageAction, SIGNAL(triggered()), this, SLOT(saveImage()));
contextMenu->addAction(saveImageAction);
QAction *copyImageAction = new QAction(tr("&Copy Image"), this);
connect(copyImageAction, SIGNAL(triggered()), this, SLOT(copyImage()));
contextMenu->addAction(copyImageAction);
}
QImage QRImageWidget::exportImage()
{
if(!pixmap())
return QImage();
return pixmap()->toImage();
}
void QRImageWidget::mousePressEvent(QMouseEvent *event)
{
if(event->button() == Qt::LeftButton && pixmap())
{
event->accept();
QMimeData *mimeData = new QMimeData;
mimeData->setImageData(exportImage());
QDrag *drag = new QDrag(this);
drag->setMimeData(mimeData);
drag->exec();
} else {
QLabel::mousePressEvent(event);
}
}
void QRImageWidget::saveImage()
{
if(!pixmap())
return;
QString fn = GUIUtil::getSaveFileName(this, tr("Save QR Code"), QString(), tr("PNG Image (*.png)"), NULL);
if (!fn.isEmpty())
{
exportImage().save(fn);
}
}
void QRImageWidget::copyImage()
{
if(!pixmap())
return;
QApplication::clipboard()->setImage(exportImage());
}
void QRImageWidget::contextMenuEvent(QContextMenuEvent *event)
{
if(!pixmap())
return;
contextMenu->exec(event->globalPos());
}
ReceiveRequestDialog::ReceiveRequestDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::ReceiveRequestDialog),
model(0)
{
ui->setupUi(this);
#ifndef USE_QRCODE
ui->btnSaveAs->setVisible(false);
ui->lblQRCode->setVisible(false);
#endif
connect(ui->btnSaveAs, SIGNAL(clicked()), ui->lblQRCode, SLOT(saveImage()));
}
ReceiveRequestDialog::~ReceiveRequestDialog()
{
delete ui;
}
void ReceiveRequestDialog::setModel(OptionsModel *_model)
{
this->model = _model;
if (_model)
connect(_model, SIGNAL(displayUnitChanged(int)), this, SLOT(update()));
// update the display unit if necessary
update();
}
void ReceiveRequestDialog::setInfo(const SendCoinsRecipient &_info)
{
this->info = _info;
update();
}
void ReceiveRequestDialog::update()
{
if(!model)
return;
QString target = info.label;
if(target.isEmpty())
target = info.address;
setWindowTitle(tr("Request payment to %1").arg(target));
QString uri = GUIUtil::formatAureusURI(info);
ui->btnSaveAs->setEnabled(false);
QString html;
html += "<html><font face='verdana, arial, helvetica, sans-serif'>";
html += "<b>"+tr("Payment information")+"</b><br>";
html += "<b>"+tr("URI")+"</b>: ";
html += "<a href=\""+uri+"\">" + GUIUtil::HtmlEscape(uri) + "</a><br>";
html += "<b>"+tr("Address")+"</b>: " + GUIUtil::HtmlEscape(info.address) + "<br>";
if(info.amount)
html += "<b>"+tr("Amount")+"</b>: " + AureusUnits::formatHtmlWithUnit(model->getDisplayUnit(), info.amount) + "<br>";
if(!info.label.isEmpty())
html += "<b>"+tr("Label")+"</b>: " + GUIUtil::HtmlEscape(info.label) + "<br>";
if(!info.message.isEmpty())
html += "<b>"+tr("Message")+"</b>: " + GUIUtil::HtmlEscape(info.message) + "<br>";
ui->outUri->setText(html);
#ifdef USE_QRCODE
ui->lblQRCode->setText("");
if(!uri.isEmpty())
{
// limit URI length
if (uri.length() > MAX_URI_LENGTH)
{
ui->lblQRCode->setText(tr("Resulting URI too long, try to reduce the text for label / message."));
} else {
QRcode *code = QRcode_encodeString(uri.toUtf8().constData(), 0, QR_ECLEVEL_L, QR_MODE_8, 1);
if (!code)
{
ui->lblQRCode->setText(tr("Error encoding URI into QR Code."));
return;
}
QImage qrImage = QImage(code->width + 8, code->width + 8, QImage::Format_RGB32);
qrImage.fill(0xffffff);
unsigned char *p = code->data;
for (int y = 0; y < code->width; y++)
{
for (int x = 0; x < code->width; x++)
{
qrImage.setPixel(x + 4, y + 4, ((*p & 1) ? 0x0 : 0xffffff));
p++;
}
}
QRcode_free(code);
QImage qrAddrImage = QImage(QR_IMAGE_SIZE, QR_IMAGE_SIZE+20, QImage::Format_RGB32);
qrAddrImage.fill(0xffffff);
QPainter painter(&qrAddrImage);
painter.drawImage(0, 0, qrImage.scaled(QR_IMAGE_SIZE, QR_IMAGE_SIZE));
QFont font = GUIUtil::fixedPitchFont();
font.setPixelSize(12);
painter.setFont(font);
QRect paddedRect = qrAddrImage.rect();
paddedRect.setHeight(QR_IMAGE_SIZE+12);
painter.drawText(paddedRect, Qt::AlignBottom|Qt::AlignCenter, info.address);
painter.end();
ui->lblQRCode->setPixmap(QPixmap::fromImage(qrAddrImage));
ui->btnSaveAs->setEnabled(true);
}
}
#endif
}
void ReceiveRequestDialog::on_btnCopyURI_clicked()
{
GUIUtil::setClipboard(GUIUtil::formatAureusURI(info));
}
void ReceiveRequestDialog::on_btnCopyAddress_clicked()
{
GUIUtil::setClipboard(info.address);
}
| [
"[email protected]"
] | |
7f78735eb7c1368284a9aafaf1405e8e7ba7f377 | 30e354327aa7b0dc868bf9880e7cfa61635b6f6b | /libspaghetti/source/elements/ui/push_button.cc | df4a7a9851524f6a789ddd67172659acf395049b | [
"MIT"
] | permissive | daniildeveloperforks/spaghetti | 2d73953cf28fa654c561c246539f660e5383a4dd | 300160af2cfc4905ff99299c7887d88bfa500c2e | refs/heads/master | 2021-05-02T11:26:43.052587 | 2018-02-08T11:04:36 | 2018-02-08T11:04:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,689 | cc | // MIT License
//
// Copyright (c) 2017-2018 Artur Wyszyński, aljen at hitomi dot pl
//
// 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 "elements/ui/push_button.h"
namespace spaghetti::elements::ui {
PushButton::PushButton()
{
setMinInputs(0);
setMaxInputs(0);
setMinOutputs(1);
setMaxOutputs(1);
addOutput(ValueType::eBool, "State", IOSocket::eCanHoldBool | IOSocket::eCanChangeName);
}
void PushButton::toggle()
{
m_currentValue = !m_currentValue;
m_outputs[0].value = m_currentValue;
}
void PushButton::set(bool a_state)
{
m_currentValue = a_state;
m_outputs[0].value = m_currentValue;
}
} // namespace spaghetti::elements::ui
| [
"[email protected]"
] | |
219ee1d0d5cc5497c4e2d9b2bdf81cca4e4d12ab | 694c187c8a00bee8c670c1690170099bad9b16b3 | /prime_fibonacci.cpp | ce0f45632022b3a3cfbedc73ae3c0ed11896c349 | [] | no_license | ajayvenkat10/Competitive | 301f220b6d296f7e34328f192c43c4d7ef208cb1 | 14f2ecebe10eb19f72cc412dd0c414b3b1de9b4d | refs/heads/master | 2022-11-20T14:31:33.590099 | 2020-07-23T15:39:14 | 2020-07-23T15:39:14 | 281,599,951 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,586 | cpp | #include <bits/stdc++.h>
#include <cstdlib>
#include <math.h>
#include <cmath>
#include <string>
#define MAX 1000005
#define ll long long
using namespace std;
bool isPrime(ll num)
{
if(num < 2)
return(false);
for(ll i=2; i<sqrt(num)+1; i++)
{
if(num%i == 0)
return(false);
}
return(true);
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int primes1[1000], primes2[1000];
int n1,n2;
int ans;
cin>>n1>>n2;
int pos = 0;
int k = 0;
for(int i=n1; i<=n2; i++)
{
if(isPrime(i))
primes1[pos++] = i;
}
if(pos == 0)
ans = 0;
else
{
for(int i=0; i<pos; i++)
{
for(int j=0; j<pos; j++)
{
if(i!=j)
{
string a = to_string(primes1[i]);
string b = to_string(primes1[j]);
a = a+b;
int number = stoi((a));
cout<<number<<endl;
if(isPrime(number))
primes2[k++] = number;
}
}
}
std::set<int>s(begin(primes2), end(primes2));
if(s.size() == 0)
ans = 0;
else
{
ll x = *s.begin();
ll y = *s.rbegin();
ll z = 0;
for(ll i=2; i<s.size(); i++)
{
z = x+y;
x = y;
y = z;
}
ans = z;
}
}
cout<<ans<<endl;
return 0;
}
| [
"[email protected]"
] | |
0207ba4cf1985af746913d03f2adbf30c14f2ff2 | 9333a9fb1b3e4bd2cae2d735027658e9d2240205 | /Action.h | ce063b82e45b26aea0ec4c3164cc04469dcd4e8d | [] | no_license | legionth/DevGame | b17a4f5f5ac09df7deb36fc16d431cef11bc686e | e5fcce9daa1c6906f6af6a594fbbd20d9d6e1c52 | refs/heads/master | 2020-05-03T05:42:49.046030 | 2013-12-18T22:12:39 | 2013-12-18T22:12:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 294 | h | #pragma once
#include "Menu.h"
#include "Button.h"
class Game;
class Action : public Button
{
public:
Action(void);
Action(Menu* menu);
~Action(void);
void action(Game* game);
void draw(sf::RenderWindow* window);
void setName(std::string name);
private:
Menu* menu;
sf::Text *name;
};
| [
"[email protected]"
] | |
a4519c9c7e75587cd77aed47f4a725a63dfdb8cc | 25e7d840203e705c6a68aed079cc9844954b9536 | /aten/src/ATen/native/transformers/cuda/mem_eff_attention/kernel_forward.h | 9a544b0a8d459602071958ed73559d4bdeef7078 | [
"BSD-2-Clause",
"LicenseRef-scancode-secret-labs-2011",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"BSL-1.0",
"Apache-2.0"
] | permissive | yf225/pytorch | 874892cd9d0f7bb748e469cfca23a3f503ea4265 | 39590d06c563d830d02b9f94611ab01f07133c97 | refs/heads/main | 2023-07-24T06:17:16.324006 | 2023-04-24T18:22:54 | 2023-04-24T18:22:59 | 113,096,813 | 1 | 3 | NOASSERTION | 2023-08-29T18:46:16 | 2017-12-04T21:25:08 | Python | UTF-8 | C++ | false | false | 35,873 | h | #include <ATen/ATen.h>
#include <cmath>
#include <vector>
#include <cuda_fp16.h>
#include <ATen/cuda/CUDAContext.h>
#include <c10/cuda/CUDAGuard.h>
#include <cutlass/bfloat16.h>
#include <cutlass/gemm/gemm.h>
#include <cutlass/layout/matrix.h>
#include <cutlass/layout/vector.h>
#include <cutlass/numeric_types.h>
#include <cutlass/epilogue/threadblock/default_epilogue_simt.h>
#include <cutlass/epilogue/threadblock/default_epilogue_tensor_op.h>
#include <cutlass/epilogue/threadblock/default_epilogue_volta_tensor_op.h>
#include <cutlass/gemm/device/default_gemm_configuration.h>
#include <cutlass/gemm/kernel/default_gemm.h>
#include <cutlass/gemm/threadblock/default_mma.h>
#include <cutlass/gemm/threadblock/default_mma_core_simt.h>
#include <cutlass/gemm/threadblock/default_mma_core_sm70.h>
#include <cutlass/gemm/threadblock/default_mma_core_sm75.h>
#include <cutlass/gemm/threadblock/default_mma_core_sm80.h>
#include <cutlass/gemm/threadblock/threadblock_swizzle.h>
#include <cutlass/matrix_shape.h>
#include <cutlass/platform/platform.h>
#include <cutlass/transform/threadblock/predicated_tile_iterator.h>
#include <ATen/native/transformers/cuda/mem_eff_attention/debug_utils.h>
#include <ATen/native/transformers/cuda/mem_eff_attention/attention_scaling_coefs_updater.h>
#include <ATen/native/transformers/cuda/mem_eff_attention/epilogue_pipelined.h>
#include <ATen/native/transformers/cuda/mem_eff_attention/epilogue_rescale_output.h>
#include <ATen/native/transformers/cuda/mem_eff_attention/find_default_mma.h>
#include <ATen/native/transformers/cuda/mem_eff_attention/mma_from_smem.h>
#include <ATen/native/transformers/cuda/mem_eff_attention/gemm_kernel_utils.h>
#include <cinttypes>
using namespace gemm_kernel_utils;
namespace {
template <typename scalar_t, typename Arch>
constexpr int getWarpsPerSm() {
bool is_half = !std::is_same<scalar_t, float>::value;
if (Arch::kMinComputeCapability >= 80) {
return is_half ? 16 : 12;
}
return 12;
}
} // namespace
template <
// The datatype of Q/K/V
typename scalar_t_,
// Architecture we are targeting (eg `cutlass::arch::Sm80`)
typename ArchTag,
// If Q/K/V are correctly aligned in memory and we can run a fast kernel
bool isAligned_,
int64_t kQueriesPerBlock,
int64_t kKeysPerBlock,
bool kSingleValueIteration // = `value.shape[-1] <= kKeysPerBlock`
>
struct AttentionKernel {
using scalar_t = scalar_t_;
using accum_t = float;
using lse_scalar_t = float;
using output_t = scalar_t;
// Accumulator between 2 iterations
// Using `accum_t` improves perf on f16 at the cost of
// numerical errors
using output_accum_t = accum_t;
static constexpr bool kIsAligned = isAligned_;
static constexpr int32_t kAlignLSE = 32; // block size of backward
static constexpr bool kPreloadV = ArchTag::kMinComputeCapability >= 80 &&
cutlass::sizeof_bits<scalar_t>::value == 16;
static constexpr bool kKeepOutputInRF = kSingleValueIteration;
static constexpr bool kNeedsOutputAccumulatorBuffer =
!kKeepOutputInRF && !cutlass::platform::is_same<output_accum_t, output_t>::value;
static_assert(kQueriesPerBlock % 32 == 0, "");
static_assert(kKeysPerBlock % 32 == 0, "");
static constexpr int64_t kNumWarpsPerBlock =
kQueriesPerBlock * kKeysPerBlock / (32 * 32);
static constexpr int64_t kWarpSize = 32;
// Launch bounds
static constexpr int64_t kNumThreads = kWarpSize * kNumWarpsPerBlock;
static constexpr int64_t kMinBlocksPerSm =
getWarpsPerSm<scalar_t, ArchTag>() / kNumWarpsPerBlock;
struct Params {
// Input tensors
scalar_t* query_ptr; // [num_queries, num_heads, head_dim]
scalar_t* key_ptr; // [num_keys, num_heads, head_dim]
scalar_t* value_ptr; // [num_keys, num_heads, head_dim_value]
int32_t* cu_seqlens_q_ptr = nullptr;
int32_t* cu_seqlens_k_ptr = nullptr;
// Output tensors
output_t* output_ptr; // [num_queries, num_heads, head_dim_value]
output_accum_t*
output_accum_ptr; // [num_queries, num_heads, head_dim_value]
lse_scalar_t* logsumexp_ptr; // [num_heads, num_queries] - can be null
// Softmax Scale
accum_t scale;
// Dimensions/strides
int32_t head_dim;
int32_t head_dim_value;
int32_t num_queries;
int32_t num_keys;
int32_t num_heads = 1;
bool causal;
int32_t q_strideM;
int32_t k_strideM;
int32_t v_strideM;
// Everything below is only used in `advance_to_block`
// and shouldn't use registers
int32_t q_strideH;
int32_t k_strideH;
int32_t v_strideH;
int64_t q_strideB;
int64_t k_strideB;
int64_t v_strideB;
int32_t num_batches;
CUTLASS_HOST_DEVICE int32_t o_strideM() const {
return head_dim_value * num_heads;
}
// Moves pointers to what we should process
// Returns "false" if there is no work to do
CUTLASS_DEVICE bool advance_to_block() {
auto batch_id = blockIdx.z;
auto head_id = blockIdx.y;
auto query_start = blockIdx.x * kQueriesPerBlock;
auto lse_dim = ceil_div((int32_t)num_queries, kAlignLSE) * kAlignLSE;
int64_t q_start, k_start;
// Advance to current batch - in case of different sequence lengths
if (cu_seqlens_q_ptr != nullptr) {
assert(cu_seqlens_k_ptr != nullptr);
cu_seqlens_q_ptr += batch_id;
cu_seqlens_k_ptr += batch_id;
q_start = cu_seqlens_q_ptr[0];
k_start = cu_seqlens_k_ptr[0];
int64_t q_next_start = cu_seqlens_q_ptr[1];
int64_t k_next_start = cu_seqlens_k_ptr[1];
num_queries = q_next_start - q_start;
num_keys = k_next_start - k_start;
if (query_start >= num_queries) {
return false;
}
} else {
query_ptr += batch_id * q_strideB;
key_ptr += batch_id * k_strideB;
value_ptr += batch_id * v_strideB;
output_ptr += int64_t(batch_id * num_queries) * o_strideM();
if (output_accum_ptr != nullptr) {
output_accum_ptr += int64_t(batch_id * num_queries) * o_strideM();
}
q_start = 0;
k_start = 0;
}
// Advance to the current batch / head / query_start
query_ptr += (q_start + query_start) * q_strideM + head_id * q_strideH;
key_ptr += k_start * k_strideM + head_id * k_strideH;
value_ptr += k_start * v_strideM + head_id * v_strideH;
output_ptr += int64_t(q_start + query_start) * o_strideM() +
head_id * head_dim_value;
if (output_accum_ptr != nullptr) {
output_accum_ptr += int64_t(q_start + query_start) * o_strideM() +
head_id * head_dim_value;
} else {
// Accumulate directly in the destination buffer (eg for f32)
output_accum_ptr = (accum_t*)output_ptr;
}
if (logsumexp_ptr != nullptr) {
// lse[batch_id, head_id, query_start]
logsumexp_ptr +=
batch_id * lse_dim * num_heads + head_id * lse_dim + query_start;
}
num_queries -= query_start;
if (causal) {
num_keys = std::min(int32_t(query_start + kQueriesPerBlock), num_keys);
}
num_batches = 0; // no longer used after
// Make sure the compiler knows these variables are the same on all
// the threads of the warp.
query_ptr = warp_uniform(query_ptr);
key_ptr = warp_uniform(key_ptr);
value_ptr = warp_uniform(value_ptr);
output_ptr = warp_uniform(output_ptr);
output_accum_ptr = warp_uniform(output_accum_ptr);
logsumexp_ptr = warp_uniform(logsumexp_ptr);
num_queries = warp_uniform(num_queries);
num_keys = warp_uniform(num_keys);
head_dim = warp_uniform(head_dim);
head_dim_value = warp_uniform(head_dim_value);
return true;
}
__host__ dim3 getBlocksGrid() const {
return dim3(
ceil_div(num_queries, (int32_t)kQueriesPerBlock),
num_heads,
num_batches);
}
__host__ dim3 getThreadsGrid() const {
return dim3(kWarpSize, kNumWarpsPerBlock, 1);
}
};
struct MM0 {
/*
In this first matmul, we compute a block of `Q @ K.T`.
While the calculation result is still hot in registers, we update
`mi`, `m_prime`, `s_prime` in shared-memory, and then store this value
into a shared-memory ("AccumulatorSharedStorage") that is used later as
operand A for the second matmul (see MM1)
*/
using GemmType = DefaultGemmType<ArchTag, scalar_t>;
using OpClass = typename GemmType::OpClass;
using DefaultConfig =
typename cutlass::gemm::device::DefaultGemmConfiguration<
OpClass,
ArchTag,
scalar_t,
scalar_t,
scalar_t, // ElementC
accum_t // ElementAccumulator
>;
static constexpr int64_t kAlignmentA =
kIsAligned ? DefaultConfig::kAlignmentA : GemmType::kMinimumAlignment;
static constexpr int64_t kAlignmentB =
kIsAligned ? DefaultConfig::kAlignmentB : GemmType::kMinimumAlignment;
using ThreadblockShape = cutlass::gemm::
GemmShape<kQueriesPerBlock, kKeysPerBlock, GemmType::ThreadK>;
using WarpShape = cutlass::gemm::GemmShape<32, 32, GemmType::WarpK>;
using DefaultMma = typename cutlass::gemm::threadblock::FindDefaultMma<
scalar_t, // ElementA,
cutlass::layout::RowMajor, // LayoutA,
kAlignmentA,
scalar_t, // ElementB,
cutlass::layout::ColumnMajor, // LayoutB,
kAlignmentB,
accum_t,
cutlass::layout::RowMajor, // LayoutC,
OpClass,
ArchTag, // ArchTag
ThreadblockShape, // ThreadblockShape
WarpShape, // WarpShape
typename GemmType::InstructionShape, // InstructionShape
DefaultConfig::kStages, // Should use `DefaultConfig::kStages`, but that
// uses too much smem
typename GemmType::Operator // Operator
>::DefaultMma;
using MmaCore = typename DefaultMma::MmaCore;
using IteratorA = typename DefaultMma::IteratorA;
using IteratorB = typename DefaultMma::IteratorB;
using Mma = typename DefaultMma::ThreadblockMma;
using ScalingCoefsUpdater = typename DefaultAttentionScalingCoefsUpdater<
typename Mma::Operator::IteratorC,
accum_t,
kWarpSize>::Updater;
static_assert(
MmaCore::WarpCount::kM * MmaCore::WarpCount::kN *
MmaCore::WarpCount::kK ==
kNumWarpsPerBlock,
"");
// Epilogue to store to shared-memory in a format that we can use later for
// the second matmul
using B2bGemm = typename cutlass::gemm::threadblock::B2bGemm<
typename Mma::Operator::IteratorC,
typename Mma::Operator,
scalar_t,
WarpShape,
ThreadblockShape>;
using AccumulatorSharedStorage = typename B2bGemm::AccumulatorSharedStorage;
};
struct MM1 {
/**
Second matmul: perform `attn @ V` where `attn` is the attention (not
normalized) and stored in shared memory
*/
using GemmType = DefaultGemmType<ArchTag, scalar_t>;
using OpClass = typename GemmType::OpClass;
using DefaultConfig =
typename cutlass::gemm::device::DefaultGemmConfiguration<
OpClass,
ArchTag,
scalar_t,
scalar_t,
output_accum_t, // ElementC
accum_t // ElementAccumulator
>;
static constexpr int64_t kAlignmentA =
DefaultConfig::kAlignmentA; // from smem
static constexpr int64_t kAlignmentB =
kIsAligned ? DefaultConfig::kAlignmentB : GemmType::kMinimumAlignment;
using ThreadblockShape = cutlass::gemm::
GemmShape<kQueriesPerBlock, kKeysPerBlock, GemmType::ThreadK>;
using WarpShape = cutlass::gemm::GemmShape<32, 32, GemmType::WarpK>;
using InstructionShape = typename GemmType::InstructionShape;
using LayoutB = cutlass::layout::RowMajor;
using DefaultGemm = cutlass::gemm::kernel::DefaultGemm<
scalar_t, // ElementA,
cutlass::layout::RowMajor, // LayoutA,
kAlignmentA,
scalar_t, // ElementB,
LayoutB, // LayoutB,
kAlignmentB,
output_accum_t,
cutlass::layout::RowMajor, // LayoutC,
accum_t,
OpClass,
ArchTag,
ThreadblockShape,
WarpShape,
typename GemmType::InstructionShape,
typename DefaultConfig::EpilogueOutputOp,
void, // ThreadblockSwizzle - not used
DefaultConfig::kStages,
false, // SplitKSerial
typename GemmType::Operator>;
using DefaultMmaFromSmem =
typename cutlass::gemm::threadblock::DefaultMmaFromSharedMemory<
typename DefaultGemm::Mma,
typename MM0::AccumulatorSharedStorage>;
using Mma = typename DefaultMmaFromSmem::Mma;
using IteratorB = typename Mma::IteratorB;
using WarpCount = typename Mma::WarpCount;
static_assert(
WarpCount::kM * WarpCount::kN * WarpCount::kK == kNumWarpsPerBlock,
"");
using DefaultEpilogue = typename DefaultGemm::Epilogue;
using OutputTileIterator =
typename cutlass::epilogue::threadblock::PredicatedTileIterator<
typename DefaultEpilogue::OutputTileIterator::ThreadMap,
output_t>;
using OutputTileIteratorAccum =
typename cutlass::epilogue::threadblock::PredicatedTileIterator<
typename DefaultEpilogue::OutputTileIterator::ThreadMap,
output_accum_t>;
struct SharedStorageMM1 {
typename Mma::SharedStorage mm;
};
};
static constexpr int64_t kAlignmentQ = MM0::kAlignmentA;
static constexpr int64_t kAlignmentK = MM0::kAlignmentB;
static constexpr int64_t kAlignmentV = 1;
// Shared storage - depends on kernel params
struct ScalingCoefs {
cutlass::Array<accum_t, kQueriesPerBlock> m_prime;
cutlass::Array<accum_t, kQueriesPerBlock> s_prime;
cutlass::Array<accum_t, kQueriesPerBlock> mi;
};
struct SharedStorageEpilogueAtEnd : ScalingCoefs {
struct SharedStorageAfterMM0 {
// Everything here might be overwritten during MM0
typename MM0::AccumulatorSharedStorage si;
typename MM1::SharedStorageMM1 mm1;
};
union {
typename MM0::Mma::SharedStorage mm0;
SharedStorageAfterMM0 after_mm0;
typename MM1::DefaultEpilogue::SharedStorage epilogue;
};
CUTLASS_DEVICE typename MM1::DefaultEpilogue::SharedStorage&
epilogue_shared_storage() {
return epilogue;
}
};
struct SharedStorageEpilogueInLoop : ScalingCoefs {
struct SharedStorageAfterMM0 {
// Everything here might be overwritten during MM0
typename MM0::AccumulatorSharedStorage si;
typename MM1::SharedStorageMM1 mm1;
typename MM1::DefaultEpilogue::SharedStorage epilogue;
};
union {
typename MM0::Mma::SharedStorage mm0;
SharedStorageAfterMM0 after_mm0;
};
CUTLASS_DEVICE typename MM1::DefaultEpilogue::SharedStorage&
epilogue_shared_storage() {
return after_mm0.epilogue;
}
};
using SharedStorage = typename std::conditional<
kSingleValueIteration || kKeepOutputInRF,
SharedStorageEpilogueAtEnd,
SharedStorageEpilogueInLoop>::type;
static void __host__ check_supported(Params const& p) {
CHECK_ALIGNED_PTR(p.query_ptr, kAlignmentQ);
CHECK_ALIGNED_PTR(p.key_ptr, kAlignmentK);
CHECK_ALIGNED_PTR(p.value_ptr, kAlignmentV);
TORCH_CHECK(
p.head_dim % kAlignmentQ == 0, "query is not correctly aligned");
TORCH_CHECK(p.head_dim % kAlignmentK == 0, "key is not correctly aligned");
TORCH_CHECK(
p.head_dim_value % kAlignmentV == 0, "value is not correctly aligned");
}
static void CUTLASS_DEVICE attention_kernel(Params& p) {
// In this block, we will only ever:
// - read query[query_start:query_end, :]
// - write to output[query_start:query_end, :]
extern __shared__ char smem_buffer[];
SharedStorage& shared_storage = *((SharedStorage*)smem_buffer);
auto& m_prime = shared_storage.m_prime;
auto& s_prime = shared_storage.s_prime;
auto& si = shared_storage.after_mm0.si;
auto& mi = shared_storage.mi;
static_assert(kQueriesPerBlock < kNumWarpsPerBlock * kWarpSize, "");
if (thread_id() < kQueriesPerBlock) {
s_prime[thread_id()] = accum_t(0);
m_prime[thread_id()] = -std::numeric_limits<accum_t>::infinity();
mi[thread_id()] = -std::numeric_limits<accum_t>::infinity();
}
typename MM1::Mma::FragmentC accum_o;
accum_o.clear();
auto createOutputIter = [&](auto col) {
using OutputTileIterator = typename MM1::OutputTileIterator;
return OutputTileIterator(
typename OutputTileIterator::Params{(int32_t)p.o_strideM()},
p.output_ptr,
typename OutputTileIterator::TensorCoord{
p.num_queries, p.head_dim_value},
thread_id(),
{0, col});
};
auto createOutputAccumIter = [&](auto col) {
using OutputTileIteratorAccum = typename MM1::OutputTileIteratorAccum;
return OutputTileIteratorAccum(
typename OutputTileIteratorAccum::Params{(int32_t)p.o_strideM()},
p.output_accum_ptr,
typename OutputTileIteratorAccum::TensorCoord{
p.num_queries, p.head_dim_value},
thread_id(),
{0, col});
};
// Iterate through keys
for (int32_t iter_key_start = 0; iter_key_start < p.num_keys;
iter_key_start += kKeysPerBlock) {
int32_t problem_size_0_m =
std::min((int32_t)kQueriesPerBlock, p.num_queries);
int32_t problem_size_0_n =
std::min(int32_t(kKeysPerBlock), p.num_keys - iter_key_start);
int32_t const& problem_size_0_k = p.head_dim;
int32_t const& problem_size_1_m = problem_size_0_m;
int32_t const& problem_size_1_n = p.head_dim_value;
int32_t const& problem_size_1_k = problem_size_0_n;
auto prologueV = [&](int blockN) {
typename MM1::Mma::IteratorB iterator_V(
typename MM1::IteratorB::Params{MM1::LayoutB(p.v_strideM)},
p.value_ptr + iter_key_start * p.v_strideM,
{problem_size_1_k, problem_size_1_n},
thread_id(),
cutlass::MatrixCoord{0, blockN * MM1::Mma::Shape::kN});
MM1::Mma::prologue(
shared_storage.after_mm0.mm1.mm,
iterator_V,
thread_id(),
problem_size_1_k);
};
__syncthreads(); // Need to have shared memory initialized, and `m_prime`
// updated from end of prev iter
//
// MATMUL: Q.K_t
//
// Computes the block-matrix product of:
// (a) query[query_start:query_end, :]
// with
// (b) key[iter_key_start:iter_key_start + kKeysPerBlock]
// and stores that into `shared_storage.si`
//
// Compute threadblock location
cutlass::gemm::GemmCoord tb_tile_offset = {0, 0, 0};
cutlass::MatrixCoord tb_offset_A{
tb_tile_offset.m() * MM0::Mma::Shape::kM, tb_tile_offset.k()};
cutlass::MatrixCoord tb_offset_B{
tb_tile_offset.k(), tb_tile_offset.n() * MM0::Mma::Shape::kN};
// Construct iterators to A and B operands
typename MM0::IteratorA iterator_A(
typename MM0::IteratorA::Params(
typename MM0::MmaCore::LayoutA(p.q_strideM)),
p.query_ptr,
{problem_size_0_m, problem_size_0_k},
thread_id(),
tb_offset_A);
typename MM0::IteratorB iterator_B(
typename MM0::IteratorB::Params(
typename MM0::MmaCore::LayoutB(p.k_strideM)),
p.key_ptr + iter_key_start * p.k_strideM,
{problem_size_0_k, problem_size_0_n},
thread_id(),
tb_offset_B);
auto my_warp_id = warp_id();
auto my_lane_id = lane_id();
// Construct thread-scoped matrix multiply
typename MM0::Mma mma(
shared_storage.mm0, thread_id(), my_warp_id, my_lane_id);
typename MM0::Mma::FragmentC accum;
accum.clear();
auto gemm_k_iterations =
(problem_size_0_k + MM0::Mma::Shape::kK - 1) / MM0::Mma::Shape::kK;
// Compute threadblock-scoped matrix multiply-add
mma(gemm_k_iterations, accum, iterator_A, iterator_B, accum);
__syncthreads();
if (kPreloadV) {
prologueV(0);
}
typename MM0::Mma::Operator::IteratorC::TensorCoord
iteratorC_tile_offset = {
(tb_tile_offset.m() * MM0::Mma::WarpCount::kM) +
(my_warp_id % MM0::Mma::WarpCount::kM),
(tb_tile_offset.n() * MM0::Mma::WarpCount::kN) +
(my_warp_id / MM0::Mma::WarpCount::kM)};
// Mask out last if causal
if (p.causal && p.num_keys - iter_key_start <= kKeysPerBlock) {
auto query_start = blockIdx.x * kQueriesPerBlock;
auto lane_offset = MM0::ScalingCoefsUpdater::get_lane_offset(
lane_id(), warp_id(), iteratorC_tile_offset);
int32_t last_col;
MM0::ScalingCoefsUpdater::iterateRows(
lane_offset,
[&](int accum_m) {
last_col = query_start + accum_m - iter_key_start;
},
[&](int accum_m, int accum_n, int idx) {
if (accum_n > last_col) {
accum[idx] = -std::numeric_limits<accum_t>::infinity();
}
},
[&](int accum_m) {});
}
DISPATCH_BOOL(iter_key_start == 0, kIsFirst, ([&] {
DISPATCH_BOOL(
p.num_keys - iter_key_start >= kKeysPerBlock,
kFullColumns,
([&] {
// Update `mi` from accum stored in registers
// Also updates `accum` with accum[i] <-
// exp(accum[i] * scale
// - mi)
MM0::ScalingCoefsUpdater::update<
kQueriesPerBlock,
kFullColumns,
kIsFirst,
kKeepOutputInRF>(
accum_o,
accum,
mi,
m_prime,
s_prime,
lane_id(),
thread_id(),
warp_id(),
p.num_keys - iter_key_start,
iteratorC_tile_offset,
p.scale);
}));
}));
// Output results to shared-memory
int warp_idx_mn_0 = my_warp_id %
(MM0::Mma::Base::WarpCount::kM * MM0::Mma::Base::WarpCount::kN);
auto output_tile_coords = cutlass::MatrixCoord{
warp_idx_mn_0 % MM0::Mma::Base::WarpCount::kM,
warp_idx_mn_0 / MM0::Mma::Base::WarpCount::kM};
MM0::B2bGemm::accumToSmem(
shared_storage.after_mm0.si, accum, my_lane_id, output_tile_coords);
__syncthreads();
//
// MATMUL: Attn . V
// Run the matmul `attn @ V` for a block of attn and V.
// `attn` is read from shared memory (in `shared_storage_si`)
// `V` is read from global memory (with iterator_B)
//
const int64_t nBlockN = kSingleValueIteration
? 1
: ceil_div(
(int64_t)problem_size_1_n, int64_t(MM1::ThreadblockShape::kN));
for (int blockN = 0; blockN < nBlockN; ++blockN) {
int gemm_k_iterations =
(problem_size_1_k + MM1::Mma::Shape::kK - 1) / MM1::Mma::Shape::kK;
// Compute threadblock-scoped matrix multiply-add and store it in accum
// (in registers)
if (!kPreloadV) {
__syncthreads(); // we share shmem between mma and epilogue
}
typename MM1::Mma::IteratorB iterator_V(
typename MM1::IteratorB::Params{MM1::LayoutB(p.v_strideM)},
p.value_ptr + iter_key_start * p.v_strideM,
{problem_size_1_k, problem_size_1_n},
thread_id(),
cutlass::MatrixCoord{0, blockN * MM1::Mma::Shape::kN});
typename MM1::Mma mma_pv(
shared_storage.after_mm0.mm1.mm,
shared_storage.after_mm0.si,
(int)thread_id(),
(int)warp_id(),
(int)lane_id(),
(int)problem_size_1_k);
mma_pv.set_prologue_done(kPreloadV);
if (!kKeepOutputInRF) {
accum_o.clear();
}
mma_pv(gemm_k_iterations, accum_o, iterator_V, accum_o);
__syncthreads();
if (kPreloadV && !kSingleValueIteration && blockN + 1 < nBlockN) {
prologueV(blockN + 1);
}
if (!kKeepOutputInRF) {
DISPATCH_BOOL(
iter_key_start == 0, kIsFirst, ([&] {
DISPATCH_BOOL(
(iter_key_start + kKeysPerBlock) >= p.num_keys,
kIsLast,
([&] {
using DefaultEpilogue = typename MM1::DefaultEpilogue;
using DefaultOp =
typename MM1::DefaultConfig::EpilogueOutputOp;
using ElementCompute = typename DefaultOp::ElementCompute;
using EpilogueOutputOp = typename cutlass::epilogue::
thread::MemoryEfficientAttentionNormalize<
typename std::conditional<
kIsLast,
output_t,
output_accum_t>::type,
output_accum_t,
DefaultOp::kCount,
typename DefaultOp::ElementAccumulator,
ElementCompute,
kIsFirst,
kIsLast,
cutlass::Array<ElementCompute, kQueriesPerBlock>>;
using Epilogue = typename cutlass::epilogue::threadblock::
EpiloguePipelined<
typename DefaultEpilogue::Shape,
typename MM1::Mma::Operator,
DefaultEpilogue::kPartitionsK,
typename std::conditional<
kIsLast,
typename MM1::OutputTileIterator,
typename MM1::OutputTileIteratorAccum>::type,
typename DefaultEpilogue::
AccumulatorFragmentIterator,
typename DefaultEpilogue::WarpTileIterator,
typename DefaultEpilogue::SharedLoadIterator,
EpilogueOutputOp,
typename DefaultEpilogue::Padding,
DefaultEpilogue::kFragmentsPerIteration,
true, // IterationsUnroll
typename MM1::OutputTileIteratorAccum // Read
// iterator
>;
int col = blockN * MM1::Mma::Shape::kN;
auto source_iter = createOutputAccumIter(col);
auto dest_iter = call_conditional<
kIsLast,
decltype(createOutputIter),
decltype(createOutputAccumIter)>::
apply(createOutputIter, createOutputAccumIter, col);
EpilogueOutputOp rescale(s_prime, m_prime);
Epilogue epilogue(
shared_storage.epilogue_shared_storage(),
thread_id(),
warp_id(),
lane_id());
epilogue(rescale, dest_iter, accum_o, source_iter);
}));
}));
if (!kSingleValueIteration) {
__syncthreads();
}
}
}
__syncthreads(); // we modify `m_prime` after
}
if (kKeepOutputInRF) {
constexpr bool kIsFirst = true;
constexpr bool kIsLast = true;
using DefaultEpilogue = typename MM1::DefaultEpilogue;
using DefaultOp = typename MM1::DefaultConfig::EpilogueOutputOp;
using ElementCompute = typename DefaultOp::ElementCompute;
using EpilogueOutputOp =
typename cutlass::epilogue::thread::MemoryEfficientAttentionNormalize<
output_t, // output
output_accum_t, // source
DefaultOp::kCount,
typename DefaultOp::ElementAccumulator, // accum
output_accum_t, // compute
kIsFirst,
kIsLast,
cutlass::Array<ElementCompute, kQueriesPerBlock>>;
using Epilogue =
typename cutlass::epilogue::threadblock::EpiloguePipelined<
typename DefaultEpilogue::Shape,
typename MM1::Mma::Operator,
DefaultEpilogue::kPartitionsK,
typename MM1::OutputTileIterator, // destination
typename DefaultEpilogue::AccumulatorFragmentIterator,
typename DefaultEpilogue::WarpTileIterator,
typename DefaultEpilogue::SharedLoadIterator,
EpilogueOutputOp,
typename DefaultEpilogue::Padding,
DefaultEpilogue::kFragmentsPerIteration,
true, // IterationsUnroll
typename MM1::OutputTileIteratorAccum // source tile
>;
auto dest_iter = createOutputIter(0);
EpilogueOutputOp rescale(s_prime, m_prime);
Epilogue epilogue(
shared_storage.epilogue_shared_storage(),
thread_id(),
warp_id(),
lane_id());
epilogue(rescale, dest_iter, accum_o);
}
// 7. Calculate logsumexp
// To make the backward easier, we pad logsumexp with `inf`
// this avoids a few bound checks, and is not more expensive during fwd
static_assert(kQueriesPerBlock < kNumWarpsPerBlock * kWarpSize, "");
if (p.logsumexp_ptr && thread_id() < kQueriesPerBlock) {
auto lse_dim = ceil_div((int32_t)p.num_queries, kAlignLSE) * kAlignLSE;
if (thread_id() < p.num_queries) {
p.logsumexp_ptr[thread_id()] =
accum_t(mi[thread_id()]) + std::log(accum_t(s_prime[thread_id()]));
} else if (thread_id() < lse_dim) {
p.logsumexp_ptr[thread_id()] = std::numeric_limits<accum_t>::infinity();
}
}
}
static CUTLASS_DEVICE int8_t lane_id() {
return threadIdx.x;
}
static CUTLASS_DEVICE int8_t warp_id() {
return threadIdx.y;
}
static CUTLASS_DEVICE int16_t thread_id() {
return threadIdx.x + threadIdx.y * blockDim.x;
}
};
template <typename AK>
__global__ void __launch_bounds__(AK::kNumThreads, AK::kMinBlocksPerSm)
attention_kernel_batched(typename AK::Params params);
#define _ATTENTION_KERNEL_FORWARD_BEGIN(...) \
template <> \
__global__ void __launch_bounds__( \
__VA_ARGS__::kNumThreads, __VA_ARGS__::kMinBlocksPerSm) \
attention_kernel_batched<__VA_ARGS__>(typename __VA_ARGS__::Params p) { \
using Kernel = __VA_ARGS__;
#define _ATTENTION_KERNEL_FORWARD_END() }
#ifdef __CUDA_ARCH__
#define __CUDA_ARCH_OR_ZERO__ __CUDA_ARCH__
#else
#define __CUDA_ARCH_OR_ZERO__ 0
#endif
#define INSTANTIATE_ATTENTION_KERNEL_FORWARD( \
ARCH, \
SCALAR_T, \
IS_ALIGNED, \
QUERIES_PER_BLOCK, \
KEYS_PER_BLOCK, \
SINGLE_VALUE_ITER) \
_ATTENTION_KERNEL_FORWARD_BEGIN(AttentionKernel< \
SCALAR_T, \
cutlass::arch::Sm##ARCH, \
IS_ALIGNED, \
QUERIES_PER_BLOCK, \
KEYS_PER_BLOCK, \
SINGLE_VALUE_ITER>) \
if (!p.advance_to_block()) { \
return; \
} \
Kernel::attention_kernel(p); \
_ATTENTION_KERNEL_FORWARD_END();
#define INSTANTIATE_ATTENTION_KERNEL_FORWARD_DISABLED( \
ARCH, \
SCALAR_T, \
IS_ALIGNED, \
QUERIES_PER_BLOCK, \
KEYS_PER_BLOCK, \
SINGLE_VALUE_ITER) \
_ATTENTION_KERNEL_FORWARD_BEGIN(AttentionKernel< \
SCALAR_T, \
cutlass::arch::Sm##ARCH, \
IS_ALIGNED, \
QUERIES_PER_BLOCK, \
KEYS_PER_BLOCK, \
SINGLE_VALUE_ITER>) \
printf( \
"FATAL: this function is for sm%d, but was built for sm%d\n", \
int(ARCH), \
int(__CUDA_ARCH_OR_ZERO__)); \
_ATTENTION_KERNEL_FORWARD_END();
// On windows we don't build with /Zc:preprocessor
// See: https://stackoverflow.com/questions/5134523/msvc-doesnt-expand-va-args-correctly
#define EXPAND( x ) x
// All kernels are disabled by default
#define INSTANTIATE_ATTENTION_KERNEL_FORWARD_SM50(...) \
EXPAND(INSTANTIATE_ATTENTION_KERNEL_FORWARD_DISABLED(50, __VA_ARGS__))
#define INSTANTIATE_ATTENTION_KERNEL_FORWARD_SM70(...) \
EXPAND(INSTANTIATE_ATTENTION_KERNEL_FORWARD_DISABLED(70, __VA_ARGS__))
#define INSTANTIATE_ATTENTION_KERNEL_FORWARD_SM75(...) \
EXPAND(INSTANTIATE_ATTENTION_KERNEL_FORWARD_DISABLED(75, __VA_ARGS__))
#define INSTANTIATE_ATTENTION_KERNEL_FORWARD_SM80(...) \
EXPAND(INSTANTIATE_ATTENTION_KERNEL_FORWARD_DISABLED(80, __VA_ARGS__))
// Enable the right one based on __CUDA_ARCH__
#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ < 500
// "Need cuda arch at least 5.0"
#elif __CUDA_ARCH__ < 700
#undef INSTANTIATE_ATTENTION_KERNEL_FORWARD_SM50
#define INSTANTIATE_ATTENTION_KERNEL_FORWARD_SM50(...) \
EXPAND(INSTANTIATE_ATTENTION_KERNEL_FORWARD(50, __VA_ARGS__))
#elif __CUDA_ARCH__ < 750
#undef INSTANTIATE_ATTENTION_KERNEL_FORWARD_SM70
#define INSTANTIATE_ATTENTION_KERNEL_FORWARD_SM70(...) \
EXPAND(INSTANTIATE_ATTENTION_KERNEL_FORWARD(70, __VA_ARGS__))
#elif __CUDA_ARCH__ < 800
#undef INSTANTIATE_ATTENTION_KERNEL_FORWARD_SM75
#define INSTANTIATE_ATTENTION_KERNEL_FORWARD_SM75(...) \
EXPAND(INSTANTIATE_ATTENTION_KERNEL_FORWARD(75, __VA_ARGS__))
#elif __CUDA_ARCH__ >= 800
#undef INSTANTIATE_ATTENTION_KERNEL_FORWARD_SM80
#define INSTANTIATE_ATTENTION_KERNEL_FORWARD_SM80(...) \
EXPAND(INSTANTIATE_ATTENTION_KERNEL_FORWARD(80, __VA_ARGS__))
#endif
| [
"[email protected]"
] | |
39c71e662325908cdff0f37edc41377980f31075 | a2e8c052c9d5c98d172cbcfbb8b5e2d192209be6 | /cpp_interface/Plane.h | cc569359e7013bcf5b1ea9ec605f28b890b4a8f8 | [] | no_license | Nightstars/cpp_interface | 36ebbcfd5080b1dd18a5692fa8159b930012d718 | ab56058fbc964d1198b890801071aa19dd01acee | refs/heads/master | 2022-12-31T15:56:23.987193 | 2020-10-05T14:30:37 | 2020-10-05T14:30:37 | 301,439,426 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 254 | h | #pragma once
#include "Flyable.h"
#include <string>
using namespace std;
class Plane :
public Flyable
{
public:
Plane(string code);
//virtual void takeoff();
//virtual void land();
void printCode();
private:
string m_strCode;
};
| [
"christzhangowner#gmail.com"
] | christzhangowner#gmail.com |
5a5f65af209ae9019020feb9b18d552c5d616a52 | 3fb575bb55b7945755352b289e59e555ec756dfa | /lab6/reader.cpp | 04fe6412b71df278e84a83bfb48571c7ab70864e | [] | no_license | noukentosh/oslabs | 3ce4f01ec94d5264596e9d29918c718cdab7de6d | 3afd359edfdbe6d9780c567dea4e5339f918f9a7 | refs/heads/master | 2023-09-06T01:06:00.273914 | 2021-11-15T19:05:44 | 2021-11-15T19:05:44 | 418,998,595 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,879 | cpp | #include <iostream>
#include <fstream>
#include <thread>
#include <semaphore.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/socket.h>
#include <signal.h>
#define WRITERSEM "/labsem.writter"
#define READERSEM "/labsem.reader"
bool exitFlag;
sem_t *writerSem;
sem_t *readerSem;
int shmid;
int *sharedMem;
void exitAction () {
shmdt(sharedMem);
shmctl(shmid, IPC_RMID, NULL);
sem_close(writerSem);
sem_close(readerSem);
sem_unlink(WRITERSEM);
sem_unlink(READERSEM);
std::cout << "программа завершила работу" << std::endl;
exit(0);
}
void SIGINT_handler (int sig) {
if(sig == 2) exitAction();
}
int main (int argc, char *argv[]) {
if (signal(SIGINT, SIGINT_handler) == SIG_ERR) {
printf("SIGINT install error\n");
exit(1);
}
std::cout << "программа начала работу" << std::endl;
fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK);
exitFlag = false;
writerSem = sem_open(WRITERSEM, O_CREAT, 0777, 0);
readerSem = sem_open(READERSEM, O_CREAT, 0777, 1);
key_t sharedMemKey = ftok("./keylock", 1);
shmid = shmget(sharedMemKey, sizeof(int), IPC_CREAT | 0777);
if (shmid < 0) {
perror("shmget");
}
sharedMem = (int *)shmat(shmid, NULL, 0);
if (sharedMem == (void *)-1) {
perror("shmat");
}
int localVar;
while(!exitFlag) {
sem_wait(writerSem);
localVar = *sharedMem;
std::cout << "Результат работы функции: " << localVar << std::endl;
sem_post(readerSem);
if (getchar() != -1) {
exitFlag = true;
}
sleep(1);
}
shmdt(sharedMem);
shmctl(shmid, IPC_RMID, NULL);
sem_close(writerSem);
sem_close(readerSem);
sem_unlink(WRITERSEM);
sem_unlink(READERSEM);
std::cout << "программа завершила работу" << std::endl;
} | [
"[email protected]"
] | |
7f4ad17bba915e44e23bfa82f34387a8f85b693a | 2397de5d9bed9fe88e6848db61bad320639953f6 | /DSSG2017_gas_testbed/gas_testbed/gas_testbed.ino | cd53d98bb98581a24d361d26f3d62b023d8968b3 | [] | no_license | cledantec/Cycle-Atlanta-SLaB | 4cc612e4f9b1b3ecea3d344ea67afad2ac821867 | f31991923be0d20f611fecec13ba616f12b5781b | refs/heads/master | 2023-01-21T19:01:09.727073 | 2020-05-02T16:19:53 | 2020-05-02T16:19:53 | 88,667,150 | 4 | 3 | null | 2023-01-05T11:15:22 | 2017-04-18T20:22:28 | HTML | UTF-8 | C++ | false | false | 2,850 | ino | #include <Wire.h>
#include <Adafruit_ADS1015.h>
#include <stdio.h>
//for Gases sensor init
Adafruit_ADS1015 ads; // Construct an ads1015 at the default address: 0x48
Adafruit_ADS1015 ads2(0x49);
Adafruit_ADS1015 ads3(0x4A);
int resetPin = 12;
void setup() {
digitalWrite(resetPin, HIGH);
delay(200);
pinMode(resetPin, OUTPUT);
Wire.begin(); //join i2c bus
Serial.begin(9600, SERIAL_8N1);
ads.begin();
ads2.begin();
ads3.begin();
//ads.setGain(GAIN_ONE);
}
//GASES SENSORS
int16_t *get_gas_values() {
static int16_t values[6];
int Vx[4];
float Ix[4];
//initialising base voltage and current values for each gas
Vx[0] = 818; //12bit
Vx[1] = 823;
Vx[2] = 812;
Vx[3] = 810;
Ix[0] = 0.00000000475;
Ix[1] = 0.000000025;
Ix[2] = 0.000000032;
Ix[3] = 0.0000000040;
//adjusting sensor values
for (int i = 0; i < 6; i++) {
values[i] = ads.readADC_SingleEnded(i);
delay(10);
}
return values;
}
int16_t *get_gas_values2() {
static int16_t values2[6];
int Vx[4];
float Ix[4];
//initialising base voltage and current values for each gas
Vx[0] = 818; //12bit
Vx[1] = 823;
Vx[2] = 812;
Vx[3] = 810;
Ix[0] = 0.00000000475;
Ix[1] = 0.000000025;
Ix[2] = 0.000000032;
Ix[3] = 0.0000000040;
//adjusting sensor values
for (int i = 0; i < 6; i++) {
values2[i] = ads2.readADC_SingleEnded(i);
delay(10);
}
return values2;
}
int16_t *get_gas_values3() {
static int16_t values3[6];
int Vx[4];
float Ix[4];
//initialising base voltage and current values for each gas
Vx[0] = 818; //12bit
Vx[1] = 823;
Vx[2] = 812;
Vx[3] = 810;
Ix[0] = 0.00000000475;
Ix[1] = 0.000000025;
Ix[2] = 0.000000032;
Ix[3] = 0.0000000040;
//adjusting sensor values
for (int i = 0; i < 6; i++) {
values3[i] = ads3.readADC_SingleEnded(i);
delay(10);
}
return values3;
}
void print_gas() {
String gas[6];
gas[0] = "CO";
gas[1] = "SO";
gas[2] = "O3";
gas[3] = "NO";
gas[4] = "AA";
gas[5] = "BB";
int16_t *v = get_gas_values();
int16_t *v2 = get_gas_values2();
int16_t *v3 = get_gas_values3();
for (int i = 0; i < 5; i++) {
Serial.print(gas[i] + "_1 ");
Serial.print(v[i]);
Serial.print(" ");
}
for (int i = 0; i < 5; i++) {
Serial.print(gas[i] + "_2 ");
Serial.print(v2[i]);
Serial.print(" ");
}
for (int i = 0; i < 5; i++) {
Serial.print(gas[i] + "_3 ");
Serial.print(v3[i]);
Serial.print(" ");
}
}
void loop() {
int response = Serial.read();
if (response == 102){ // "f" means fail
digitalWrite(resetPin, LOW);
delay(20);
digitalWrite(resetPin, HIGH);
delay(200);
} else if (response == 103) { // "g" means good
print_gas();
Serial.println();
} else {
delay(200);
}
delay(20);
}
| [
"[email protected]"
] | |
c84c154ff1b252e4ec652589774d9faafa60a3df | 2e02f4a1333b593cd45ea6e8aadb21e1fb4b3e2f | /CodeForces/C/1472 C.cpp | f8a89b32abb15955dfc665d8bb69f978b90cd205 | [] | no_license | rahul-goel/CompetitiveProgramming | 33c42145a5807ce1e1b94334faeeb960ad381edb | 7c042b81dd9208137bbbd34e397baa55c85ff793 | refs/heads/master | 2022-09-25T04:26:16.173096 | 2022-09-05T18:26:23 | 2022-09-05T18:26:23 | 231,899,837 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,735 | cpp | /*
Created by Rahul Goel.
*/
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
/*******************************************************************************/
using namespace std;
using namespace __gnu_pbds;
template < typename T >
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
/*******************************************************************************/
using ll = long long;
using ld = long double;
const ll MOD = 1000000007;
// const ll MOD = 998244353;
const int INF = 1e9;
const ll LINF = 1e18;
/*******************************************************************************/
ll mod_sum() { return 0LL; }
template < typename T, typename... Args >
T mod_sum(T a, Args... args) { return ((a + mod_sum(args...))%MOD + MOD)%MOD; }
/*******************************************************************************/
ll mod_prod() { return 1LL; }
template< typename T, typename... Args >
T mod_prod(T a, Args... args) { return (a * mod_prod(args...))%MOD; }
/*******************************************************************************/
#ifdef ONLINE_JUDGE
#define endl '\n'
#endif
#define fastio ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define all(c) (c).begin(), (c).end()
#define present(c,x) ((c).find(x) != (c).end())
#define cpresent(c,x) (find(all(c),x) != (c).end())
#define uniq(c) (c).resize(distance((c).begin(), unique(all(c))))
#define min_pq(t) priority_queue < t, vector < t >, greater < t > >
#define max_pq(t) priority_queue < t >
#define pb push_back
#define ff first
#define ss second
/*******************************************************************************/
using pii = pair < ll, ll >;
using vi = vector < ll >;
using vb = vector < bool >;
using vvi = vector < vector < ll > >;
using vvb = vector < vector < bool > >;
using vpii = vector < pii >;
using vvpii = vector < vector < pii > >;
/*******************************************************************************/
//.-.. . -. -.- .- .. ... .-.. --- ...- .
/*
Code begins after this.
*/
ll solve() {
ll n;
cin >> n;
vector<ll> vec(n + 5);
for (ll i = 1; i <= n; i++) {
cin >> vec[i];
}
vector<ll> dp(n + 5);
for (ll i = n; i >= 1; i--) {
if (i + vec[i] > n) {
dp[i] = vec[i];
} else {
dp[i] += vec[i] + dp[vec[i] + i];
}
}
ll ans = *max_element(dp.begin() + 1, dp.begin() + n + 1);
cout << ans << endl;
return 0;
}
signed main() {
fastio;
ll t = 1;
cin >> t;
while (t--) {
solve();
}
return 0;
}
| [
"[email protected]"
] | |
61177c1d8a4ad083ed48a758ac0d72aa9ae10e79 | ba973f4a5041e981d7a693c0a3bb001224fb1d31 | /chrome/browser/extensions/api/instance_id/instance_id_apitest.cc | f967a3ee4763fb0bbb262bc730973c1b8161782d | [
"BSD-3-Clause"
] | permissive | jdragonbae/chromium | 8c7baf22e9e01ba7afd6e9c6eadb4e3075672e52 | b67648ad60a925974ba5ec5437fe946ea269ab2a | refs/heads/master | 2022-11-19T16:42:35.350469 | 2018-10-11T11:13:19 | 2018-10-11T11:13:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,655 | cc | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <memory>
#include <utility>
#include "base/macros.h"
#include "base/run_loop.h"
#include "chrome/browser/extensions/api/instance_id/instance_id_api.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_gcm_app_handler.h"
#include "chrome/browser/gcm/gcm_profile_service_factory.h"
#include "chrome/browser/gcm/instance_id/instance_id_profile_service_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/gcm_driver/fake_gcm_profile_service.h"
#include "components/gcm_driver/instance_id/fake_gcm_driver_for_instance_id.h"
#include "components/version_info/version_info.h"
#include "extensions/test/result_catcher.h"
using extensions::ResultCatcher;
namespace extensions {
class InstanceIDApiTest : public ExtensionApiTest {
public:
InstanceIDApiTest();
protected:
void SetUp() override;
void TearDown() override;
private:
DISALLOW_COPY_AND_ASSIGN(InstanceIDApiTest);
};
InstanceIDApiTest::InstanceIDApiTest() {
}
void InstanceIDApiTest::SetUp() {
gcm::GCMProfileServiceFactory::SetGlobalTestingFactory(
base::BindRepeating(&gcm::FakeGCMProfileService::Build));
ExtensionApiTest::SetUp();
}
void InstanceIDApiTest::TearDown() {
gcm::GCMProfileServiceFactory::SetGlobalTestingFactory(
BrowserContextKeyedServiceFactory::TestingFactory());
}
IN_PROC_BROWSER_TEST_F(InstanceIDApiTest, GetID) {
ASSERT_TRUE(RunExtensionTest("instance_id/get_id"));
}
IN_PROC_BROWSER_TEST_F(InstanceIDApiTest, GetCreationTime) {
ASSERT_TRUE(RunExtensionTest("instance_id/get_creation_time"));
}
IN_PROC_BROWSER_TEST_F(InstanceIDApiTest, DeleteID) {
ASSERT_TRUE(RunExtensionTest("instance_id/delete_id"));
}
IN_PROC_BROWSER_TEST_F(InstanceIDApiTest, GetToken) {
ASSERT_TRUE(RunExtensionTest("instance_id/get_token"));
}
IN_PROC_BROWSER_TEST_F(InstanceIDApiTest, DeleteToken) {
ASSERT_TRUE(RunExtensionTest("instance_id/delete_token"));
}
IN_PROC_BROWSER_TEST_F(InstanceIDApiTest, Incognito) {
ResultCatcher catcher;
catcher.RestrictToBrowserContext(profile());
ResultCatcher incognito_catcher;
incognito_catcher.RestrictToBrowserContext(
profile()->GetOffTheRecordProfile());
ASSERT_TRUE(RunExtensionTestIncognito("instance_id/incognito"));
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
EXPECT_TRUE(incognito_catcher.GetNextResult()) << incognito_catcher.message();
}
} // namespace extensions
| [
"[email protected]"
] | |
18e71155be973885734ddaded4ffc989b3d2b7b0 | 4d415255b193f9285c194de088b9cbf832a0a943 | /source/destroy_enemy_rate.cpp | 2323e56347de34adeddfda149422cb85399a383d | [] | no_license | yamikumo-DSD/my_game_project_unified | 6dd21e6c5f16c27e20c8e53cf23bb904ba773e8e | baeea3e0bfb0535e102e8f00decda92bce88a613 | refs/heads/master | 2020-04-05T23:47:36.931603 | 2016-11-18T08:25:10 | 2016-11-18T08:25:10 | 52,700,981 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,983 | cpp | //destroy_enemy_rate.cpp
#include "destroy_enemy_rate.h"
#include "decl_static_image_handler.h"
#include "image_pool.h"
#include <type_traits>
#include "lock_weight_to_rate.h"
#include "mathematics.h"
#include "print_digit.h"
#include <boost/lexical_cast.hpp>
#include "debug_value.h"
#include <boost/format.hpp>
#ifndef DER
#define DER DestroyEnemyRate::
#endif
namespace MyGameProject
{
struct DER Impl
{
STATIC_IMAGE_HANDLER(_period_img)
STATIC_IMAGE_HANDLER(_0_img)
STATIC_IMAGE_HANDLER(_1_img)
STATIC_IMAGE_HANDLER(_2_img)
STATIC_IMAGE_HANDLER(_3_img)
STATIC_IMAGE_HANDLER(_4_img)
STATIC_IMAGE_HANDLER(_5_img)
STATIC_IMAGE_HANDLER(_6_img)
STATIC_IMAGE_HANDLER(_7_img)
STATIC_IMAGE_HANDLER(_8_img)
STATIC_IMAGE_HANDLER(_9_img)
std::string rate_text;
Point2D pos;
int count{0};
int pal{255};
bool is_enable{true};
Impl(float _rate, Point2D _pos) noexcept
//:rate_text(boost::lexical_cast<std::string>(_rate)),
:rate_text(boost::str(boost::format("%.1f") % _rate)),
pos(_pos)
{}
};
DER DestroyEnemyRate(int _x, int _y, float _rate) noexcept
:pimpl(std::make_unique<Impl>(_rate, Point2D(static_cast<Real>(_x), static_cast<Real>(_y))))
{
}
DER ~DestroyEnemyRate(void) noexcept = default;
#ifndef ALIASES
#define ALIASES \
auto& count{pimpl->count}; \
auto& pos{pimpl->pos};
#endif
void DER draw(void) const noexcept
{
ALIASES;
if (count > 0)
{
for (int i = 0; i != 3; ++i)
{
try
{
print_digit
(
gp::level(28), static_cast<int>(pos.x() + 30 * i), static_cast<int>(pos.y()), 1.5, pimpl->pal, pimpl->rate_text[i],
Impl::_period_img(),
Impl::_0_img(), Impl::_1_img(), Impl::_2_img(), Impl::_3_img(), Impl::_4_img(),
Impl::_5_img(), Impl::_6_img(), Impl::_7_img(), Impl::_8_img(), Impl::_9_img()
);
}
catch (Unprintable)
{
}
}
}
}
void DER update(void) noexcept
{
ALIASES;
pos += Point2D(1, -1);
pimpl->pal -= 10;
if (count == 20) { pimpl->is_enable = false; }
++count;
}
bool DER get_flag(void) const noexcept { return pimpl->is_enable; }
template<typename String>
auto load_digit(String&& _path) noexcept
{
ImagePool::add(_path);
return ImagePool::get(std::forward<String>(_path));
}
void DER load_digit_images(void) noexcept
{
using namespace std::literals;
auto root{ "../../data/img/"s };
Impl::_period_img() = load_digit(root + "dot.png");
Impl::_0_img() = load_digit(root + "digit_000.png");
Impl::_1_img() = load_digit(root + "digit_001.png");
Impl::_2_img() = load_digit(root + "digit_002.png");
Impl::_3_img() = load_digit(root + "digit_003.png");
Impl::_4_img() = load_digit(root + "digit_004.png");
Impl::_5_img() = load_digit(root + "digit_005.png");
Impl::_6_img() = load_digit(root + "digit_006.png");
Impl::_7_img() = load_digit(root + "digit_007.png");
Impl::_8_img() = load_digit(root + "digit_008.png");
Impl::_9_img() = load_digit(root + "digit_009.png");
}
} | [
"やみくも"
] | やみくも |
39cb82aaf2425057c52ccaf546bfd5e4c1f9a1d2 | 739732d3a6b548404f432ad8ff918841249a18ec | /src/TransText/TextFormat.cc | 944faa8123aff2f550eccb125c8ac2a077e47380 | [] | no_license | yiique/TranslationSystemSimple | 9417e14c198c9622fbb9e1f046445ba1462b458f | 62a9eea538bae1739b7a4e2bfa39fd0e27d8967d | refs/heads/master | 2020-04-09T21:25:23.550131 | 2016-09-12T12:59:12 | 2016-09-12T12:59:12 | 68,007,511 | 0 | 0 | null | 2016-09-12T12:59:12 | 2016-09-12T12:37:25 | C++ | GB18030 | C++ | false | false | 2,342 | cc | #include "TextFormat.h"
#include "Common/f_utility.h"
#include <sstream>
void TextFormat::Clear()
{
for(size_t i=0; i<m_para_vec.size(); ++i)
{
delete m_para_vec[i];
}
m_para_vec.clear();
}
void TextFormat::Reset(const vector<string> & para_vec,
const vector<pair<size_t, size_t> > & pos_vec)
{
assert( para_vec.size() == pos_vec.size() );
vector<Para*> tmp_para_vec;
for(size_t i=0; i<para_vec.size(); ++i)
{
Para * pr = new Para;
pr->_content = para_vec[i];
pr->_offset = pos_vec[i].first;
pr->_len = pos_vec[i].second;
tmp_para_vec.push_back(pr);
}
if(false == check_format_info(tmp_para_vec))
{
lerr << "Check format failed. m_para_vec will be zero." << endl;
return;
}
this->Clear();
m_para_vec = tmp_para_vec;
}
bool TextFormat::check_format_info(vector<Para*> & para_vec)
{
//验证pos是否冲突,并对其按照offset排序
//Step.1 先排序
sort(para_vec.begin(), para_vec.end(), ParaInAhead());
//debug print
//for(size_t i=0; i<para_vec.size(); ++i)
//{
// lout << "para_vec.content = [" << para_vec[i]->_content << "]" << endl;
// lout << "para_vec.pos = [" << para_vec[i]->_offset << " , " << para_vec[i]->_len << "]" << endl;
//}
//Step.2 验证
size_t ahead_end = 0;
for(size_t i=0; i<para_vec.size(); ++i)
{
if(para_vec[i]->_offset < ahead_end)
{
lerr << " para_vec: i = " << i << " _offset = " << para_vec[i]->_offset << " ahead_end = " << ahead_end << endl;
return false;
}
else
ahead_end = para_vec[i]->_offset + para_vec[i]->_len;
}
return true;
}
void TextFormat::Serialization(string & data) const
{
stringstream ss;
for(size_t i=0; i<m_para_vec.size(); ++i)
{
ss << m_para_vec[i]->_offset << " " << m_para_vec[i]->_len << endl;
}
data = ss.str();
}
bool TextFormat::UnSerialization(const string & data)
{
this->Clear();
stringstream ss;
ss << data;
string line;
while(getline(ss, line))
{
vector<string> pos_vec;
split_string_by_blank(line.c_str(), pos_vec);
if(pos_vec.size() < 2)
return false;
Para * p_para = new Para();
p_para->_offset = str_2_num(pos_vec[0]);
p_para->_len = str_2_num(pos_vec[1]);
m_para_vec.push_back(p_para);
}
return check_format_info(m_para_vec);
}
| [
"[email protected]"
] | |
a1eaf2b508accde1d2dfcfba4149f488f0974fa7 | b22588340d7925b614a735bbbde1b351ad657ffc | /athena/Event/EventBookkeeperTPCnv/src/EventBookkeeper_p2.cxx | 40775bf3ff8ddd38d10eeea6d0a53425476f1fb1 | [] | no_license | rushioda/PIXELVALID_athena | 90befe12042c1249cbb3655dde1428bb9b9a42ce | 22df23187ef85e9c3120122c8375ea0e7d8ea440 | refs/heads/master | 2020-12-14T22:01:15.365949 | 2020-01-19T03:59:35 | 2020-01-19T03:59:35 | 234,836,993 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,842 | cxx | /*
Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
*/
///////////////////////////////////////////////////////////////////
// Author: David Cote, September 2008. <[email protected]>
///////////////////////////////////////////////////////////////////
#include "EventBookkeeperTPCnv/EventBookkeeper_p2.h"
EventBookkeeper_p2::EventBookkeeper_p2()
{
m_name="";
m_description="";
m_inputstream="";
m_outputstream="";
m_logic ="";
m_nAcceptedEvents=0;
m_nWeightedAcceptedEvents=0;
m_cycle=-1;
m_childrenEB = 0;
}
EventBookkeeper_p2::EventBookkeeper_p2( const EventBookkeeper_p2& rhs )
: m_childrenEB(0)
{
*this = rhs;
}
EventBookkeeper_p2& EventBookkeeper_p2::operator=( const EventBookkeeper_p2& rhs )
{
if (this != &rhs) {
m_name=rhs.m_name;
m_description=rhs.m_description;
m_inputstream=rhs.m_inputstream;
m_outputstream = rhs.m_outputstream;
m_logic = rhs.m_logic;
m_nAcceptedEvents=rhs.m_nAcceptedEvents;
m_nWeightedAcceptedEvents=rhs.m_nWeightedAcceptedEvents;
m_cycle=rhs.m_cycle;
//Make a new deep copy of the children by calling the constructor iteratively (as this becomes the new owner of these objects)
delete m_childrenEB;
if (!rhs.m_childrenEB)
m_childrenEB = 0;
else {
m_childrenEB = new std::vector<EventBookkeeper_p2*>;
for(unsigned int i=0; i<rhs.m_childrenEB->size(); i++){
EventBookkeeper_p2* child=new EventBookkeeper_p2(*rhs.m_childrenEB->at(i));
m_childrenEB->push_back(child);
}
}
}
return *this;
}
EventBookkeeper_p2::~EventBookkeeper_p2()
{
//Iteratively call the destructor of the children
if (m_childrenEB) {
for(unsigned int i=0; i<m_childrenEB->size(); i++){ delete m_childrenEB->at(i); }
m_childrenEB->clear();
delete m_childrenEB;
}
}
| [
"[email protected]"
] | |
159781d31d341a3b84808fe8ddf1c9b472579e1f | 7c9d3b1417ff6c822bf7ed5fcdb5053eec347e73 | /comms/include/blazingdb/manager/Manager.h | 79620040b2faa6ee7d9671b0974aae45f1ae2b2f | [
"Apache-2.0"
] | permissive | aocsa/blazingsql | e4bc19b39b3f0ecf8572f7f9be26c10367c71b41 | 0b18be9a15f1eac514a3c96831984984d0d30b55 | refs/heads/branch-0.12 | 2020-12-05T17:35:30.399878 | 2020-02-04T23:16:42 | 2020-02-04T23:16:42 | 232,191,410 | 1 | 0 | Apache-2.0 | 2020-04-20T18:57:02 | 2020-01-06T21:47:24 | C++ | UTF-8 | C++ | false | false | 1,022 | h | #pragma once
#include <memory>
#include <vector>
#include "blazingdb/manager/Cluster.h"
#include "blazingdb/manager/Context.h"
#include "blazingdb/transport/Client.h"
namespace blazingdb {
namespace manager {
class ManagerClient {
public:
virtual transport::Status Send(transport::Message& message) = 0;
};
/// \brief This is a server used only by the Orchestrator
///
/// This class will register the Node instances (i.e. RAL instances)
class Manager {
public:
Manager() = default;
virtual void Run() = 0;
virtual void Close() = 0;
virtual const Cluster& getCluster() const = 0;
virtual Context* generateContext(std::string logicalPlan, int clusterSize,
uint32_t context_token) = 0;
public:
static std::unique_ptr<Manager> MakeServer(int communicationTcpPort);
static std::unique_ptr<ManagerClient> MakeClient(const std::string& ip,
std::uint16_t port);
};
} // namespace manager
} // namespace blazingdb
| [
"[email protected]"
] | |
ad5605efd38208bbd5ed576db6f1608b7c595468 | 828d41a44551ec5c14be9af336872c0aca3f8a54 | /shared/src/Socket.cpp | 24a9db3e9e2502fbf971a1101f55e7e2e0174785 | [] | no_license | Petru98/MySSH | 895d455d4fa37f945e279015c376e7ac41802c0f | e4b35bb46a2ee2404040eeb62e5326444835e4c8 | refs/heads/master | 2021-03-24T13:15:48.666457 | 2018-01-18T11:27:54 | 2018-01-18T11:27:54 | 114,278,687 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,700 | cpp | #include <Socket.hpp>
#include <unistd.h>
#include <cstring>
#include <limits>
#include <cassert>
#include <algorithm>
Socket::Socket() : FileDescriptor(-1), family(INet)
{}
Socket::Socket(Socket&& that) : FileDescriptor(that.fd), family(that.family)
{
that.fd = -1;
}
Socket::Socket(int fd, int family) : FileDescriptor(fd), family(family)
{}
Socket::Socket(Protocols protocol, int family, int flags) : Socket()
{
this->create(protocol, family, flags);
}
Socket::~Socket()
{
this->close();
}
void Socket::create(Protocols protocol, int family, int flags)
{
if(this->isValid())
throw CreateError("the socket object was already created");
this->fd = socket(family, protocol | flags, 0);
if(this->fd == -1)
throw CreateError(errno, "could not create socket");
}
void Socket::close()
{
if(this->isValid())
{
::close(this->fd);
this->fd = -1;
}
}
bool Socket::isValid() const
{
return this->fd != -1;
}
uint16_t Socket::getPort() const
{
sockaddr_in sin;
socklen_t len = sizeof(sin);
if(getsockname(this->fd, reinterpret_cast<sockaddr*>(&sin), &len) == -1)
throw GetPortError(errno, "could not get the socket's port");
return ntohs(sin.sin_port);
}
void Socket::bind(uint16_t port, IpAddress address)
{
sockaddr_in addr = {};
addr.sin_family = this->family;
addr.sin_addr.s_addr = htonl(address.toInt());
addr.sin_port = htons(port);
if(::bind(this->fd, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) == -1)
throw BindError(errno, "could not bind the socket");
}
void Socket::listen(int max_pending_connections)
{
if(::listen(this->fd, max_pending_connections) == -1)
throw ListenError(errno, "could not listen to port with socket");
}
bool Socket::accept(IpAddress& address, uint16_t& port, Socket& sock)
{
sockaddr_in addr;
socklen_t len = sizeof(addr);
int new_sock = ::accept(this->fd, reinterpret_cast<sockaddr*>(&addr), &len);
if(new_sock == -1)
{
if(errno == EWOULDBLOCK || errno == EAGAIN)
return false;
throw AcceptError(errno, "could not accept a connection with socket");
}
address = ntohl(addr.sin_addr.s_addr);
port = ntohs(addr.sin_port);
sock.close();
sock.fd = new_sock;
sock.family = addr.sin_family;
return true;
}
bool Socket::connect(IpAddress address, uint16_t port)
{
sockaddr_in addr = {};
addr.sin_family = this->family;
addr.sin_addr.s_addr = htonl(address.toInt());
addr.sin_port = htons(port);
if(::connect(this->fd, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) == -1)
{
if(errno == EINPROGRESS)
return false;
throw ConnectError(errno, "could not connect with socket");
}
return true;
}
void Socket::sendRaw(const void* data, std::size_t size, int flags)
{
assert(data != nullptr || size == 0);
while(size > 0)
{
ssize_t sent = ::send(this->fd, data, size, flags);
if(sent == -1)
{
if(errno != EWOULDBLOCK && errno != EAGAIN)
throw SendError(errno, "could not send data with socket");
}
else
{
data = reinterpret_cast<const uint8_t*>(data) + sent;
size -= sent;
}
}
}
void Socket::recvRaw(void* data, std::size_t size, int flags)
{
assert(data != nullptr || size == 0);
while(size > 0)
{
ssize_t received = ::recv(this->fd, data, size, flags);
if(received == -1)
{
if(errno != EWOULDBLOCK && errno != EAGAIN)
throw ReceiveError(errno, "could not receive data with socket");
}
else
{
data = reinterpret_cast<uint8_t*>(data) + received;
size -= received;
}
}
}
void Socket::sendSize(std::size_t data, int flags)
{
typedef uint32_t fixed_size_t;
if(sizeof(std::size_t) > sizeof(fixed_size_t) && data > std::numeric_limits<fixed_size_t>::max())
throw SendError("could not send size because its value is too big");
const fixed_size_t size = hton(static_cast<fixed_size_t>(data));
return this->sendRaw(&size, sizeof(size), flags);
}
std::size_t Socket::recvSize(int flags)
{
typedef uint32_t fixed_size_t;
fixed_size_t size;
this->recvRaw(&size, sizeof(size), flags);
if(sizeof(std::size_t) < sizeof(fixed_size_t) && std::numeric_limits<std::size_t>::max() < size)
throw ReceiveError("could not receive size because its value is too big");
return static_cast<std::size_t>(ntoh(size));
}
void Socket::sendUnprocessed(const void* data, std::size_t size, int flags)
{
assert(data != nullptr || size == 0);
if(size == 0)
return;
this->sendSize(size, flags);
return this->sendRaw(data, size, flags);
}
std::size_t Socket::recvUnprocessed(void* data, std::size_t size, int flags)
{
assert(data != nullptr || size == 0);
if(size == 0)
return 0;
const std::size_t packet_size = this->recvSize(flags);
if(packet_size > size)
throw ReceiveError("packet size is bigger than the buffer size");
this->recvRaw(data, packet_size, flags);
return packet_size;
}
void Socket::send(const void* data, std::size_t size, int flags)
{
assert(data != nullptr || size == 0);
if(size == 0)
return;
this->onSend(reinterpret_cast<const uint8_t*>(data), size);
this->sendSize(size, flags);
return this->sendUnprocessed(this->buffer.data(), this->buffer.size(), flags);
}
std::size_t Socket::recv(void* data, std::size_t size, int flags)
{
assert(data != nullptr || size == 0);
if(size == 0)
return 0;
const std::size_t content_size = this->recvSize(flags);
if(content_size > size)
throw ReceiveError("packet content size is bigger than the buffer size");
this->recvUnprocessed(this->buffer, flags);
this->onReceive(reinterpret_cast<uint8_t*>(data), this->buffer.size());
return content_size;
}
void Socket::send8(uint8_t data, int flags)
{
data = hton(data);
this->send(&data, sizeof(data), flags);
}
void Socket::send16(uint16_t data, int flags)
{
data = hton(data);
this->send(&data, sizeof(data), flags);
}
void Socket::send32(uint32_t data, int flags)
{
data = hton(data);
this->send(&data, sizeof(data), flags);
}
void Socket::sendString(const char* data, std::size_t length, int flags)
{
assert(data != nullptr);
if(length == 0)
length = strlen(data);
this->send(data, length, flags);
}
void Socket::sendString(const std::string& data, int flags)
{
return this->sendString(data.c_str(), data.length(), flags);
}
uint8_t Socket::recv8(int flags)
{
uint8_t buffer;
this->recv(&buffer, sizeof(buffer), flags);
return ntoh(buffer);
}
uint16_t Socket::recv16(int flags)
{
uint16_t buffer;
this->recv(&buffer, sizeof(buffer), flags);
return ntoh(buffer);
}
uint32_t Socket::recv32(int flags)
{
uint32_t buffer;
this->recv(&buffer, sizeof(buffer), flags);
return ntoh(buffer);
}
std::size_t Socket::recvString(char* data, std::size_t size, int flags)
{
assert(data != nullptr || size == 0);
if(size == 0)
return 0;
this->recv(data, size - 1, flags);
data[size] = '\0';
return size;
}
std::size_t Socket::recvString(std::string& data, int flags)
{
return this->recv(data, flags);
}
void Socket::onSend(const uint8_t* data, std::size_t size)
{
this->buffer.assign(data, data + size);
}
void Socket::onReceive(uint8_t* data, std::size_t size)
{
size = this->buffer.size();
std::copy_n(this->buffer.data(), size, data);
}
| [
"[email protected]"
] | |
eb97b3bcff12f8d897a667f4f54f32aa28ac3fa6 | 4ecab1190b24f6866cb3b0e8c5d4a6e74d911c26 | /programs/spc/IITKWPCJ_generator.cpp | 08474ecbae52f13ab22c644d955db9cbb46e0d55 | [] | no_license | bhupkas/Backup | f15ccfa8bc44a2dc3544b204dfeaeea6d8728ded | 67d5343cf9de9267488414aa4da0eb2ada867464 | refs/heads/master | 2020-06-08T09:37:48.140088 | 2015-05-22T21:00:15 | 2015-05-22T21:00:15 | 32,330,228 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,410 | cpp | #define _CRT_SECURE_NO_WARNINGS
#pragma comment(linker, "/stack:16777216")
#include <string>
#include <vector>
#include <map>
#include <list>
#include <iterator>
#include <set>
#include <queue>
#include <iostream>
#include <sstream>
#include <stack>
#include <deque>
#include <cmath>
#include <memory.h>
#include <cstdlib>
#include <cstdio>
#include <cctype>
#include <algorithm>
#include <utility>
#include <time.h>
using namespace std;
#define FOR(i, a, b) for(int i = (a); i < (b); ++i)
#define RFOR(i, b, a) for(int i = (b) - 1; i >= (a); --i)
#define REP(i, N) FOR(i, 0, N)
#define RREP(i, N) RFOR(i, N, 0)
#define FILL(A,value) memset(A,value,sizeof(A))
#define ALL(V) V.begin(), V.end()
#define SZ(V) (int)V.size()
#define PB push_back
#define MP make_pair
#define Pi 3.14159265358979
typedef long long Int;
typedef unsigned long long UInt;
typedef vector <int> VI;
typedef pair <int, int> PII;
const Int INF = 1000000000000000001LL;
const int MAX = 1005;
int main(int argc, char *argv[])
{
freopen ("output.txt", "w", stdout);
//cout << "hi" << endl;
//cout << 1000 << endl;
// registerGen(argc, argv);
//cout << 100 << endl;
//for (int i = 0; i < 100; i++) {
// cout << rnd.next("[a-z]{1,10000}") << " ";
// cout << rnd.next("[a-z]{1,10000}") << endl;
//cout << rnd.next("[a-z]{1,100}")<<endl;
FOR(i,0,4997)
FOR(j,0,20)
cout<<(char)(j+'a');
cout<<endl;
return 0;
}
| [
"bhupendra@bhupkas.(none)"
] | bhupendra@bhupkas.(none) |
Subsets and Splits