hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
c86ef228a1768a8d75e5eb2b47155e9fe170a05d
15,229
cpp
C++
src/pair_go-contacts.cpp
luwei0917/GlpG_Nature_Communication
a7f4f8b526e633b158dc606050e8993d70734943
[ "MIT" ]
1
2018-11-28T15:04:55.000Z
2018-11-28T15:04:55.000Z
src/pair_go-contacts.cpp
luwei0917/GlpG_Nature_Communication
a7f4f8b526e633b158dc606050e8993d70734943
[ "MIT" ]
null
null
null
src/pair_go-contacts.cpp
luwei0917/GlpG_Nature_Communication
a7f4f8b526e633b158dc606050e8993d70734943
[ "MIT" ]
null
null
null
/* ---------------------------------------------------------------------- Copyright (2010) Aram Davtyan and Garegin Papoian Papoian's Group, University of Maryland at Collage Park http://papoian.chem.umd.edu/ Last Update: 12/01/2010 ------------------------------------------------------------------------- */ // pair_style gocontacts pair_gomodel_coeff.data 24 // pair_coeff * * 24 #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "pair_go-contacts.h" #include "atom.h" #include "atom_vec_awsemmd.h" #include "comm.h" #include "force.h" #include "update.h" #include "neigh_list.h" #include "memory.h" #include "error.h" #include "random_park.h" #include <fstream> #include <time.h> using std::ifstream; using namespace LAMMPS_NS; /* ---------------------------------------------------------------------- */ PairGoContacts::PairGoContacts(LAMMPS *lmp) : Pair(lmp) { } /* ---------------------------------------------------------------------- */ inline void PairGoContacts::print_log(char *line) { if (screen) fprintf(screen, line); if (logfile) fprintf(logfile, line); } PairGoContacts::~PairGoContacts() { if (allocated) { memory->destroy(setflag); memory->destroy(cut); memory->destroy(cutsq); if (contacts_flag) { memory->destroy(isNative); memory->destroy(sigma); memory->destroy(sigma_sq); } delete rand; } } /* ---------------------------------------------------------------------- */ /* Correlated noise generator for contact potential dev(t+dt) = dev(t) - 0.5*xi*(dev(t) + devp(t))*dt + w*sqrt(2*dt)*rand devp(t) = dev(t) - xi*dev(t)*dt + w*sqrt(2*dt)*rand The formula above was simplified to dev += (w*sqrt(2*dt)*rand - xi*dt*dev)*(1 - xi*dt/2) devA = w*sqrt(2*dt) devB = xi*dt devC = (1 - xi*dt/2) <dev(t)dev(t+dt)> = w^2/xi * Exp[-xi*dt] */ void PairGoContacts::compute_contact_deviation() { if (dev_type==DT_CORR) { if (update->ntimestep!=0) { rnd = rand->gaussian(); dev += (devA*rnd - devB*dev)*devC; } } else if (dev_type==DT_SIN) { dev = devA*sin(devB*update->ntimestep + devC); } else if (dev_type==DT_CONST) { dev = devA; } } void PairGoContacts::compute(int eflag, int vflag) { int i,j,ii,jj,inum,jnum,itype,jtype,sign,imol,jmol,ires,jres; double xtmp,ytmp,ztmp,delx,dely,delz,evdwl,fpair; double r,rsq,factor_lj,V; int *ilist,*jlist,*numneigh,**firstneigh; double sgrinv, sgrinv12, sgrinv10, contact_epsilon; evdwl = 0.0; if (eflag || vflag) ev_setup(eflag,vflag); else evflag = vflag_fdotr = 0; int ntypes = atom->ntypes; double **x = atom->x; double **f = atom->f; int *type = atom->type; int nlocal = atom->nlocal; int nall = nlocal + atom->nghost; double *special_lj = force->special_lj; int newton_pair = force->newton_pair; inum = list->inum; ilist = list->ilist; numneigh = list->numneigh; firstneigh = list->firstneigh; compute_contact_deviation(); // loop over neighbors of my atoms for (ii = 0; ii < inum; ii++) { i = ilist[ii]; xtmp = x[i][0]; ytmp = x[i][1]; ztmp = x[i][2]; itype = type[i]; jlist = firstneigh[i]; jnum = numneigh[i]; for (jj = 0; jj < jnum; jj++) { j = jlist[jj]; imol = atom->molecule[i]-1; jmol = atom->molecule[j]-1; ires = avec->residue[i]-1; jres = avec->residue[j]-1; if (abs(jres-ires)<=3) continue; if (j < nall) factor_lj = 1.0; else { factor_lj = special_lj[j/nall]; j %= nall; } delx = xtmp - x[j][0]; dely = ytmp - x[j][1]; delz = ztmp - x[j][2]; jtype = type[j]; rsq = delx*delx + dely*dely + delz*delz; if (rsq < cutsq[itype][jtype] && rsq<=sigma_sq[ires][jres]*9) { // if (rsq < cutsq[itype][jtype]) { // r = sqrt(rsq); sgrinv = sigma_sq[ires][jres]/rsq; sgrinv12 = pow(sgrinv, 6); sgrinv10 = pow(sgrinv, 5); if (isNative[ires][jres]) { contact_epsilon = epsilon; if (contacts_dev_flag) contact_epsilon = epsilon + dev; V = contact_epsilon*(5*sgrinv12 - 6*sgrinv10); fpair = 60*contact_epsilon*(sgrinv12 - sgrinv10)/rsq; } else { V = epsilon2*sgrinv12; fpair = 12*epsilon2*sgrinv12/rsq; } fpair *=factor_lj; V *= factor_lj; f[i][0] += fpair*delx; f[i][1] += fpair*dely; f[i][2] += fpair*delz; if (newton_pair || j < nlocal) { f[j][0] -= fpair*delx; f[j][1] -= fpair*dely; f[j][2] -= fpair*delz; } if (eflag) evdwl = V; if (evflag) ev_tally(i,j,nlocal,newton_pair, evdwl,0.0,fpair,delx,dely,delz); } } } if (vflag_fdotr) virial_fdotr_compute(); } /* ---------------------------------------------------------------------- allocate all arrays ------------------------------------------------------------------------- */ void PairGoContacts::allocate() { allocated = 1; int n = atom->ntypes; memory->create(setflag, n+1,n+1,"pair:setflag"); for (int i = 1; i <= n; i++) for (int j = i; j <= n; j++) setflag[i][j] = 0; memory->create(cut, n+1,n+1,"pair:cut"); memory->create(cutsq, n+1,n+1,"pair:cutsq"); rand = new RanPark(lmp,seed); } /* ---------------------------------------------------------------------- global settings ------------------------------------------------------------------------- */ void PairGoContacts::settings(int narg, char **arg) { if (narg != 2) error->all(FLERR,"Illegal pair_style command"); int i,j,len; len = strlen(arg[0]) + 1; parfile = new char[len]; strcpy(parfile, arg[0]); cut_global = atof(arg[1]); // reset cutoffs that have been explicitly set if (allocated) { for (i = 1; i <= atom->ntypes; i++) for (j = i+1; j <= atom->ntypes; j++) if (setflag[i][j]) cut[i][j] = cut_global; } // Read the parameter file // Initalize lj_contacts_flag = contacts_flag = contacts_dev_flag = 0; dev_type = DT_NONE; seed = time(NULL); // seed = 1; char varsection[100]; ifstream in(parfile); if (!in) error->all(FLERR,"Coefficient file was not found!"); while (!in.eof()) { in >> varsection; if (strcmp(varsection, "[Go-Model_LJ]")==0) { lj_contacts_flag = 1; print_log("LJ Go-Model flag on\n"); in >> epsilon >> epsilon2; } else if (strcmp(varsection, "[Contacts]")==0) { contacts_flag = 1; print_log("Contacts flag on\n"); in >> nres >> ncont; in >> sigma0; memory->create(isNative, nres+1,nres+1,"pair:isNative"); memory->create(sigma, nres+1,nres+1,"pair:sigma"); memory->create(sigma_sq, nres+1,nres+1,"pair:sigma_sq"); for (i=0;i<nres;++i) for (j=0;j<nres;++j) { isNative[i][j]=0; sigma[i][j]=sigma0; sigma_sq[i][j]=sigma0*sigma0; } int ires, jres; double rn; for (i=0; i<ncont;++i) { in >> ires >> jres >> rn; if (ires>=nres || jres>=nres || ires<0 || jres<0 || abs(jres-ires)<=3) error->all(FLERR,"Pair style go-contacts: wrong residue index in contact map file"); isNative[ires][jres] = isNative[jres][ires] = 1; sigma[ires][jres] = sigma[jres][ires] = rn; sigma_sq[ires][jres] = sigma_sq[jres][ires] = rn*rn; } } else if (strcmp(varsection, "[Contacts_Deviation]")==0) { contacts_dev_flag = 1; dev_type = DT_CORR; print_log("Contacts_Deviation flag on\n"); in >> sdivf; // Standart deviation in epsilon fractions in >> tcorr; // Correlation time in femtoseconds in >> dev0; // Deviation on t=0 } else if (strcmp(varsection, "[Harmonic_Contacts_Deviation]")==0) { contacts_dev_flag = 1; dev_type = DT_SIN; print_log("Harmonic_Contacts_Deviation flag on\n"); in >> sdivf; // Amplitud in >> tcorr; // Period in >> dev0; // Phase on t=0 in half periods } else if (strcmp(varsection, "[Constant_Contacts_Deviation]")==0) { contacts_dev_flag = 1; dev_type = DT_CONST; print_log("Constant_Contacts_Deviation flag on\n"); in >> sdivf; // Deviation in epsilon fractions } varsection[0]='\0'; } in.close(); print_log("\n"); if (dev_type==DT_CORR) { xi = 1/tcorr; w = sqrt(xi)*epsilon*sdivf; dev = dev0; devA = w*sqrt(2*update->dt); devB = xi*update->dt; devC = (1 - xi*update->dt/2); } else if (dev_type==DT_SIN) { devA = epsilon*sdivf/sqrt(0.5); devB = 2*M_PI*update->dt/tcorr; devC = M_PI*dev0; dev = devA*sin(devC); } else if (dev_type==DT_CONST) { dev = devA = epsilon*sdivf; } fout = fopen("forcesPGO.dat","w"); } /* ---------------------------------------------------------------------- set coeffs for one or more type pairs ------------------------------------------------------------------------- */ void PairGoContacts::coeff(int narg, char **arg) { if (narg != 2 && narg != 3) error->all(FLERR,"Incorrect args for pair coefficients"); if (!allocated) allocate(); int ilo,ihi,jlo,jhi; double cut_one; force->bounds(FLERR,arg[0],atom->ntypes,ilo,ihi); force->bounds(FLERR,arg[1],atom->ntypes,jlo,jhi); cut_one = cut_global; if (narg == 3) cut_one = atof(arg[2]); int count = 0; for (int i = ilo; i <= ihi; i++) { for (int j = MAX(jlo,i); j <= jhi; j++) { cut[i][j] = cut_one; setflag[i][j] = 1; count++; } } if (count == 0) error->all(FLERR,"Incorrect args for pair coefficients"); } /* ---------------------------------------------------------------------- init specific to this pair style ------------------------------------------------------------------------- */ void PairGoContacts::init_style() { avec = (AtomVecAWSEM *) atom->style_match("awsemmd"); if (!avec) error->all(FLERR,"Pair go-contacts requires atom style awsemmd"); neighbor->request(this,instance_me); } /* ---------------------------------------------------------------------- init for one type pair i,j and corresponding j,i ------------------------------------------------------------------------- */ double PairGoContacts::init_one(int i, int j) { if (setflag[i][j] == 0) { cut[i][j] = mix_distance(cut[i][i],cut[j][j]); } cut[j][i] = cut[i][j]; return cut[i][j]; } /* ---------------------------------------------------------------------- proc 0 writes to restart file ------------------------------------------------------------------------- */ void PairGoContacts::write_restart(FILE *fp) { write_restart_settings(fp); int i,j; for (i = 1; i <= atom->ntypes; i++) for (j = i; j <= atom->ntypes; j++) { fwrite(&setflag[i][j],sizeof(int),1,fp); if (setflag[i][j]) { fwrite(&cut[i][j],sizeof(double),1,fp); } } } /* ---------------------------------------------------------------------- proc 0 reads from restart file, bcasts ------------------------------------------------------------------------- */ void PairGoContacts::read_restart(FILE *fp) { read_restart_settings(fp); if (!allocated) allocate(); int i,j; int me = comm->me; for (i = 1; i <= atom->ntypes; i++) for (j = i; j <= atom->ntypes; j++) { if (me == 0) fread(&setflag[i][j],sizeof(int),1,fp); MPI_Bcast(&setflag[i][j],1,MPI_INT,0,world); if (setflag[i][j]) { if (me == 0) { fread(&cut[i][j],sizeof(double),1,fp); } MPI_Bcast(&cut[i][j],1,MPI_DOUBLE,0,world); } } } /* ---------------------------------------------------------------------- proc 0 writes to restart file ------------------------------------------------------------------------- */ void PairGoContacts::write_restart_settings(FILE *fp) { fwrite(&cut_global,sizeof(double),1,fp); fwrite(&mix_flag,sizeof(int),1,fp); fwrite(&dev_type,sizeof(int),1,fp); if (dev_type==DT_CORR) { int tseed=rand->state(); fwrite(&tseed,sizeof(int),1,fp); fwrite(&sdivf,sizeof(double),1,fp); fwrite(&tcorr,sizeof(double),1,fp); fwrite(&dev0,sizeof(double),1,fp); fwrite(&dev,sizeof(double),1,fp); } else if (dev_type==DT_SIN) { double tdev0=devB*update->ntimestep + devC; fwrite(&sdivf,sizeof(double),1,fp); fwrite(&tcorr,sizeof(double),1,fp); fwrite(&tdev0,sizeof(double),1,fp); fwrite(&dev,sizeof(double),1,fp); } else if (dev_type==DT_CONST) { fwrite(&sdivf,sizeof(double),1,fp); fwrite(&dev,sizeof(double),1,fp); } } /* ---------------------------------------------------------------------- proc 0 reads from restart file, bcasts ------------------------------------------------------------------------- */ void PairGoContacts::read_restart_settings(FILE *fp) { if (!allocated) allocate(); int r_dev_type, r_seed; double r_sdivf, r_tcorr, r_dev0, r_dev; if (comm->me == 0) { fread(&cut_global,sizeof(double),1,fp); fread(&mix_flag,sizeof(int),1,fp); fread(&r_dev_type,sizeof(int),1,fp); if (r_dev_type==DT_CORR) { fread(&r_seed,sizeof(int),1,fp); fread(&r_sdivf,sizeof(double),1,fp); fread(&r_tcorr,sizeof(double),1,fp); fread(&r_dev0,sizeof(double),1,fp); fread(&r_dev,sizeof(double),1,fp); } else if (r_dev_type==DT_SIN) { fread(&r_sdivf,sizeof(double),1,fp); fread(&r_tcorr,sizeof(double),1,fp); fread(&r_dev0,sizeof(double),1,fp); fread(&r_dev,sizeof(double),1,fp); } else if (r_dev_type==DT_CONST) { fread(&r_sdivf,sizeof(double),1,fp); fread(&r_dev,sizeof(double),1,fp); } if (contacts_dev_flag && r_dev_type==dev_type) { if (r_dev_type==DT_CORR) { rand->reset(r_seed); dev = r_dev; } else if (r_dev_type==DT_SIN) { devC = r_dev0; dev = devA*sin(devC); } else if (r_dev_type==DT_CONST) { // Nothing need to be done } } } MPI_Bcast(&cut_global,1,MPI_DOUBLE,0,world); MPI_Bcast(&mix_flag,1,MPI_INT,0,world); } /* ---------------------------------------------------------------------- */ double PairGoContacts::single(int i, int j, int itype, int jtype, double rsq, double factor_coul, double factor_lj, double &fforce) { double r,V,contact_epsilon; double sgrinv, sgrinv12, sgrinv10; int imol, jmol, ires, jres; imol = atom->molecule[i]-1; jmol = atom->molecule[j]-1; ires = avec->residue[i]-1; jres = avec->residue[j]-1; // || rsq>sigma_sq[ires][jres]*9 if (abs(jres-ires)<=3 || rsq>=cutsq[itype][jtype] || rsq>sigma_sq[ires][jres]*9) return 0.0; // r = sqrt(rsq); sgrinv = sigma_sq[ires][jres]/rsq; sgrinv12 = pow(sgrinv, 6); sgrinv10 = pow(sgrinv, 5); if (isNative[ires][jres]) { contact_epsilon = epsilon; if (contacts_dev_flag) contact_epsilon = epsilon + dev; V = contact_epsilon*(5*sgrinv12 - 6*sgrinv10); fforce = 60*contact_epsilon*(sgrinv12 - sgrinv10)/rsq; } else { V = epsilon2*sgrinv12; fforce = 12*epsilon2*sgrinv12/rsq; } fforce *= factor_lj; V *= factor_lj; return V; }
27.638838
118
0.522359
[ "model" ]
c871e1866354e98f554520b14ba832ffc970ca76
5,274
cc
C++
vod/src/model/GetMediaAuditResultTimelineResult.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
vod/src/model/GetMediaAuditResultTimelineResult.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
vod/src/model/GetMediaAuditResultTimelineResult.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * 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. */ #include <alibabacloud/vod/model/GetMediaAuditResultTimelineResult.h> #include <json/json.h> using namespace AlibabaCloud::Vod; using namespace AlibabaCloud::Vod::Model; GetMediaAuditResultTimelineResult::GetMediaAuditResultTimelineResult() : ServiceResult() {} GetMediaAuditResultTimelineResult::GetMediaAuditResultTimelineResult(const std::string &payload) : ServiceResult() { parse(payload); } GetMediaAuditResultTimelineResult::~GetMediaAuditResultTimelineResult() {} void GetMediaAuditResultTimelineResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto mediaAuditResultTimelineNode = value["MediaAuditResultTimeline"]; auto allPornNode = mediaAuditResultTimelineNode["Porn"]["PornItem"]; for (auto mediaAuditResultTimelineNodePornPornItem : allPornNode) { MediaAuditResultTimeline::PornItem pornItemObject; if(!mediaAuditResultTimelineNodePornPornItem["Label"].isNull()) pornItemObject.label = mediaAuditResultTimelineNodePornPornItem["Label"].asString(); if(!mediaAuditResultTimelineNodePornPornItem["Score"].isNull()) pornItemObject.score = mediaAuditResultTimelineNodePornPornItem["Score"].asString(); if(!mediaAuditResultTimelineNodePornPornItem["Timestamp"].isNull()) pornItemObject.timestamp = mediaAuditResultTimelineNodePornPornItem["Timestamp"].asString(); mediaAuditResultTimeline_.porn.push_back(pornItemObject); } auto allTerrorismNode = mediaAuditResultTimelineNode["Terrorism"]["TerrorismItem"]; for (auto mediaAuditResultTimelineNodeTerrorismTerrorismItem : allTerrorismNode) { MediaAuditResultTimeline::TerrorismItem terrorismItemObject; if(!mediaAuditResultTimelineNodeTerrorismTerrorismItem["Label"].isNull()) terrorismItemObject.label = mediaAuditResultTimelineNodeTerrorismTerrorismItem["Label"].asString(); if(!mediaAuditResultTimelineNodeTerrorismTerrorismItem["Score"].isNull()) terrorismItemObject.score = mediaAuditResultTimelineNodeTerrorismTerrorismItem["Score"].asString(); if(!mediaAuditResultTimelineNodeTerrorismTerrorismItem["Timestamp"].isNull()) terrorismItemObject.timestamp = mediaAuditResultTimelineNodeTerrorismTerrorismItem["Timestamp"].asString(); mediaAuditResultTimeline_.terrorism.push_back(terrorismItemObject); } auto allLogoNode = mediaAuditResultTimelineNode["Logo"]["LogoItem"]; for (auto mediaAuditResultTimelineNodeLogoLogoItem : allLogoNode) { MediaAuditResultTimeline::LogoItem logoItemObject; if(!mediaAuditResultTimelineNodeLogoLogoItem["Label"].isNull()) logoItemObject.label = mediaAuditResultTimelineNodeLogoLogoItem["Label"].asString(); if(!mediaAuditResultTimelineNodeLogoLogoItem["Score"].isNull()) logoItemObject.score = mediaAuditResultTimelineNodeLogoLogoItem["Score"].asString(); if(!mediaAuditResultTimelineNodeLogoLogoItem["Timestamp"].isNull()) logoItemObject.timestamp = mediaAuditResultTimelineNodeLogoLogoItem["Timestamp"].asString(); mediaAuditResultTimeline_.logo.push_back(logoItemObject); } auto allLiveNode = mediaAuditResultTimelineNode["Live"]["LiveItem"]; for (auto mediaAuditResultTimelineNodeLiveLiveItem : allLiveNode) { MediaAuditResultTimeline::LiveItem liveItemObject; if(!mediaAuditResultTimelineNodeLiveLiveItem["Label"].isNull()) liveItemObject.label = mediaAuditResultTimelineNodeLiveLiveItem["Label"].asString(); if(!mediaAuditResultTimelineNodeLiveLiveItem["Score"].isNull()) liveItemObject.score = mediaAuditResultTimelineNodeLiveLiveItem["Score"].asString(); if(!mediaAuditResultTimelineNodeLiveLiveItem["Timestamp"].isNull()) liveItemObject.timestamp = mediaAuditResultTimelineNodeLiveLiveItem["Timestamp"].asString(); mediaAuditResultTimeline_.live.push_back(liveItemObject); } auto allAdNode = mediaAuditResultTimelineNode["Ad"]["AdItem"]; for (auto mediaAuditResultTimelineNodeAdAdItem : allAdNode) { MediaAuditResultTimeline::AdItem adItemObject; if(!mediaAuditResultTimelineNodeAdAdItem["Label"].isNull()) adItemObject.label = mediaAuditResultTimelineNodeAdAdItem["Label"].asString(); if(!mediaAuditResultTimelineNodeAdAdItem["Score"].isNull()) adItemObject.score = mediaAuditResultTimelineNodeAdAdItem["Score"].asString(); if(!mediaAuditResultTimelineNodeAdAdItem["Timestamp"].isNull()) adItemObject.timestamp = mediaAuditResultTimelineNodeAdAdItem["Timestamp"].asString(); mediaAuditResultTimeline_.ad.push_back(adItemObject); } } GetMediaAuditResultTimelineResult::MediaAuditResultTimeline GetMediaAuditResultTimelineResult::getMediaAuditResultTimeline()const { return mediaAuditResultTimeline_; }
47.513514
129
0.813045
[ "model" ]
c872a3d640038550534c884e32adcec29d746091
10,857
cpp
C++
libs/geometry/example/with_external_libs/x04_wxwidgets_world_mapper.cpp
jmuskaan72/Boost
047e36c01841a8cd6a5c74d4e3034da46e327bc1
[ "BSL-1.0" ]
198
2015-01-13T05:47:18.000Z
2022-03-09T04:46:46.000Z
libs/geometry/example/with_external_libs/x04_wxwidgets_world_mapper.cpp
xiaoliang2121/Boost
fc90c3fde129c62565c023f091eddc4a7ed9902b
[ "BSL-1.0" ]
4
2015-03-19T08:23:23.000Z
2019-06-24T07:48:47.000Z
libs/geometry/example/with_external_libs/x04_wxwidgets_world_mapper.cpp
xiaoliang2121/Boost
fc90c3fde129c62565c023f091eddc4a7ed9902b
[ "BSL-1.0" ]
139
2015-01-15T20:09:31.000Z
2022-01-31T15:21:16.000Z
// Boost.Geometry (aka GGL, Generic Geometry Library) // // Copyright (c) 2010-2012 Barend Gehrels, Amsterdam, the Netherlands. // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // wxWidgets World Mapper example // #define EXAMPLE_WX_USE_GRAPHICS_CONTEXT 1 #include <fstream> #include <sstream> #include <boost/foreach.hpp> #include <boost/shared_ptr.hpp> #include <boost/scoped_array.hpp> #include <boost/geometry/geometry.hpp> #include <boost/geometry/geometries/geometries.hpp> #include <boost/geometry/geometries/point_xy.hpp> #include <boost/geometry/multi/geometries/multi_geometries.hpp> #include <boost/geometry/geometries/register/point.hpp> #include <boost/geometry/geometries/register/ring.hpp> #include <boost/geometry/extensions/algorithms/selected.hpp> // wxWidgets, if these headers are NOT found, adapt include path (and lib path) #include "wx/wx.h" #include "wx/math.h" #include "wx/stockitem.h" #ifdef EXAMPLE_WX_USE_GRAPHICS_CONTEXT #include "wx/graphics.h" #include "wx/dcgraph.h" #endif typedef boost::geometry::model::d2::point_xy<double> point_2d; typedef boost::geometry::model::multi_polygon < boost::geometry::model::polygon<point_2d> > country_type; // Adapt wxWidgets points to Boost.Geometry points such that they can be used // in e.g. transformations (see below) BOOST_GEOMETRY_REGISTER_POINT_2D(wxPoint, int, cs::cartesian, x, y) BOOST_GEOMETRY_REGISTER_POINT_2D(wxRealPoint, double, cs::cartesian, x, y) // wxWidgets draws using wxPoint*, so we HAVE to use that. // Therefore have to make a wxPoint* array // 1) compatible with Boost.Geometry // 2) compatible with Boost.Range (required by Boost.Geometry) // 3) compatible with std::back_inserter (required by Boost.Geometry) // For compatible 2): typedef std::pair<wxPoint*,wxPoint*> wxPointPointerPair; // For compatible 1): BOOST_GEOMETRY_REGISTER_RING(wxPointPointerPair); // For compatible 3): // Specialize back_insert_iterator for the wxPointPointerPair // (has to be done within "namespace std") namespace std { template <> class back_insert_iterator<wxPointPointerPair> : public std::iterator<std::output_iterator_tag, void, void, void, void> { public: typedef wxPointPointerPair container_type; explicit back_insert_iterator(wxPointPointerPair& x) : current(boost::begin(x)) , end(boost::end(x)) {} inline back_insert_iterator<wxPointPointerPair>& operator=(wxPoint const& value) { // Check if not passed beyond if (current != end) { *current++ = value; } return *this; } // Boiler-plate inline back_insert_iterator<wxPointPointerPair>& operator*() { return *this; } inline back_insert_iterator<wxPointPointerPair>& operator++() { return *this; } inline back_insert_iterator<wxPointPointerPair>& operator++(int) { return *this; } private: boost::range_iterator<wxPointPointerPair>::type current, end; }; } // namespace std // ---------------------------------------------------------------------------- // Read an ASCII file containing WKT's // ---------------------------------------------------------------------------- template <typename Geometry, typename Box> inline void read_wkt(std::string const& filename, std::vector<Geometry>& geometries, Box& box) { std::ifstream cpp_file(filename.c_str()); if (cpp_file.is_open()) { while (! cpp_file.eof() ) { std::string line; std::getline(cpp_file, line); if (! line.empty()) { Geometry geometry; boost::geometry::read_wkt(line, geometry); geometries.push_back(geometry); boost::geometry::expand(box, boost::geometry::return_envelope<Box>(geometry)); } } } } // ---------------------------------------------------------------------------- class HelloWorldFrame: public wxFrame { public: HelloWorldFrame(wxFrame *frame, wxString const& title, wxPoint const& pos, wxSize const& size); void OnCloseWindow(wxCloseEvent& ); void OnExit(wxCommandEvent& ); DECLARE_EVENT_TABLE() }; // ---------------------------------------------------------------------------- class HelloWorldCanvas: public wxWindow { public: HelloWorldCanvas(wxFrame *frame); private: void DrawCountries(wxDC& dc); void DrawCountry(wxDC& dc, country_type const& country); void OnPaint(wxPaintEvent& ); void OnMouseMove(wxMouseEvent&); typedef boost::geometry::strategy::transform::map_transformer < point_2d, wxPoint, true, true > map_transformer_type; typedef boost::geometry::strategy::transform::inverse_transformer < wxPoint, point_2d > inverse_transformer_type; boost::shared_ptr<map_transformer_type> m_map_transformer; boost::shared_ptr<inverse_transformer_type> m_inverse_transformer; boost::geometry::model::box<point_2d> m_box; std::vector<country_type> m_countries; int m_focus; wxBrush m_orange; wxFrame* m_owner; DECLARE_EVENT_TABLE() }; // ---------------------------------------------------------------------------- class HelloWorldApp: public wxApp { public: bool OnInit() { // Create the main frame window HelloWorldFrame *frame = new HelloWorldFrame(NULL, _T("Boost.Geometry for wxWidgets - Hello World!"), wxDefaultPosition, wxSize(640, 480)); wxMenu *file_menu = new wxMenu; file_menu->Append(wxID_EXIT, wxGetStockLabel(wxID_EXIT)); wxMenuBar* menuBar = new wxMenuBar; menuBar->Append(file_menu, _T("&File")); frame->SetMenuBar(menuBar); int width, height; frame->GetClientSize(&width, &height); (void) new HelloWorldCanvas(frame); // Show the frame frame->Show(true); return true; } }; // ---------------------------------------------------------------------------- HelloWorldFrame::HelloWorldFrame(wxFrame *frame, wxString const& title, wxPoint const& pos, wxSize const& size) : wxFrame(frame, wxID_ANY, title, pos, size, wxDEFAULT_FRAME_STYLE | wxFULL_REPAINT_ON_RESIZE ) { CreateStatusBar(2); } void HelloWorldFrame::OnExit(wxCommandEvent& ) { this->Destroy(); } void HelloWorldFrame::OnCloseWindow(wxCloseEvent& ) { static bool destroyed = false; if (! destroyed) { this->Destroy(); destroyed = true; } } // ---------------------------------------------------------------------------- HelloWorldCanvas::HelloWorldCanvas(wxFrame *frame) : wxWindow(frame, wxID_ANY) , m_owner(frame) , m_focus(-1) { boost::geometry::assign_inverse(m_box); read_wkt("../data/world.wkt", m_countries, m_box); m_orange = wxBrush(wxColour(255, 128, 0), wxSOLID); } void HelloWorldCanvas::OnMouseMove(wxMouseEvent &event) { namespace bg = boost::geometry; if (m_inverse_transformer) { // Boiler-plate wxWidgets code wxClientDC dc(this); PrepareDC(dc); m_owner->PrepareDC(dc); // Transform the point to Lon/Lat point_2d point; bg::transform(event.GetPosition(), point, *m_inverse_transformer); // Determine selected object int i = 0; int previous_focus = m_focus; m_focus = -1; BOOST_FOREACH(country_type const& country, m_countries) { if (bg::selected(country, point, 0)) { m_focus = i; } i++; } // On change: if (m_focus != previous_focus) { // Undraw old focus if (previous_focus >= 0) { dc.SetBrush(*wxWHITE_BRUSH); DrawCountry(dc, m_countries[previous_focus]); } // Draw new focus if (m_focus >= 0) { dc.SetBrush(m_orange); DrawCountry(dc, m_countries[m_focus]); } } // Create a string and set it in the status text std::ostringstream out; out << "Position: " << point.x() << ", " << point.y(); m_owner->SetStatusText(wxString(out.str().c_str(), wxConvUTF8)); } } void HelloWorldCanvas::OnPaint(wxPaintEvent& ) { #if defined(EXAMPLE_WX_USE_GRAPHICS_CONTEXT) wxPaintDC pdc(this); wxGCDC gdc(pdc); wxDC& dc = (wxDC&) gdc; #else wxPaintDC dc(this); #endif PrepareDC(dc); static bool running = false; if (! running) { running = true; // Update the transformers wxSize sz = dc.GetSize(); m_map_transformer.reset(new map_transformer_type(m_box, sz.x, sz.y)); m_inverse_transformer.reset(new inverse_transformer_type(*m_map_transformer)); DrawCountries(dc); running = false; } } void HelloWorldCanvas::DrawCountries(wxDC& dc) { namespace bg = boost::geometry; dc.SetBackground(*wxLIGHT_GREY_BRUSH); dc.Clear(); BOOST_FOREACH(country_type const& country, m_countries) { DrawCountry(dc, country); } if (m_focus != -1) { dc.SetBrush(m_orange); DrawCountry(dc, m_countries[m_focus]); } } void HelloWorldCanvas::DrawCountry(wxDC& dc, country_type const& country) { namespace bg = boost::geometry; BOOST_FOREACH(bg::model::polygon<point_2d> const& poly, country) { // Use only outer, holes are (for the moment) ignored. This would need // a holey-polygon compatible wx object std::size_t n = boost::size(poly.outer()); boost::scoped_array<wxPoint> points(new wxPoint[n]); wxPointPointerPair pair = std::make_pair(points.get(), points.get() + n); bg::transform(poly.outer(), pair, *m_map_transformer); dc.DrawPolygon(n, points.get()); } } // ---------------------------------------------------------------------------- BEGIN_EVENT_TABLE(HelloWorldFrame, wxFrame) EVT_CLOSE(HelloWorldFrame::OnCloseWindow) EVT_MENU(wxID_EXIT, HelloWorldFrame::OnExit) END_EVENT_TABLE() BEGIN_EVENT_TABLE(HelloWorldCanvas, wxWindow) EVT_PAINT(HelloWorldCanvas::OnPaint) EVT_MOTION(HelloWorldCanvas::OnMouseMove) END_EVENT_TABLE() IMPLEMENT_APP(HelloWorldApp)
27.838462
148
0.595284
[ "geometry", "object", "vector", "model", "transform" ]
c876e546b413ae7304dc2b15b497116ea4745a43
5,841
cpp
C++
gdrivehandler.cpp
ronzhinme/qtGDriveClient
326cd31e289dd15fb9fa6e026787487a8f04f28f
[ "MIT" ]
1
2021-11-24T12:02:46.000Z
2021-11-24T12:02:46.000Z
gdrivehandler.cpp
ronzhinme/qtGDriveClient
326cd31e289dd15fb9fa6e026787487a8f04f28f
[ "MIT" ]
null
null
null
gdrivehandler.cpp
ronzhinme/qtGDriveClient
326cd31e289dd15fb9fa6e026787487a8f04f28f
[ "MIT" ]
null
null
null
#include "gdrivehandler.h" #include "utils.h" #include <QNetworkReply> #include <QNetworkRequest> #include <QHttpPart> #include <QFile> #include <QDir> #include <QJsonDocument> #include <QJsonArray> #include <QJsonObject> #include <QMimeDatabase> const QString FILES_URL="https://www.googleapis.com/drive/v3/files"; const QString RESUMABLE_OPTION = "uploadType=resumable"; const QString UPLOAD_URL = "https://www.googleapis.com/upload/drive/v3/files"; GDriveHandler::GDriveHandler(QObject *parent) : QObject(parent) { m_manager.reset(new QNetworkAccessManager(this)); } bool GDriveHandler::isAccessManagerValid() { return m_manager.data() != nullptr; } QStringList GDriveHandler::getFiles() const { return m_files; } QString GDriveHandler::getToken() const { return m_token; } void GDriveHandler::setFiles(const QStringList &val) { m_files.clear(); m_files.append(val); Q_EMIT sigFilesChanged(); } void GDriveHandler::setToken(const QString &val) { m_token = val; Q_EMIT sigTokenChanged(); } void GDriveHandler::listFilesRequest() { if(!isAccessManagerValid()) return; QString tokenStr = "Bearer " + getToken(); QNetworkRequest newRequest(FILES_URL); newRequest.setRawHeader("Authorization", tokenStr.toUtf8()); newRequest.setRawHeader("Content-Type", "application/json; charset=utf-8"); newRequest.setRawHeader("Accept", "application/json"); QNetworkReply* reply = m_manager->get(newRequest); connect(reply, &QNetworkReply::finished, [reply, newRequest, this]() { int httpStatus = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); QNetworkReply::NetworkError err = reply->error(); if ((err != QNetworkReply::NoError) || (httpStatus == 0)) { #if defined (QT_DEBUG) qDebug() << "Error:" << err << " " << httpStatus; #endif Q_EMIT sigRequestError(RequestType::ListFile, QString(""), QString::number(httpStatus)); return; } QByteArray ret = reply->readAll(); reply->abort(); reply->deleteLater(); if (ret.isEmpty()) { return; } QJsonDocument jsdoc; jsdoc = QJsonDocument::fromJson(ret); QJsonObject jsobj = jsdoc.object(); if(!m_files.isEmpty()) { m_files.clear(); } for(auto i : jsobj["files"].toArray()) { auto fname = i.toObject()["name"].toString(); m_files.append(fname); Q_EMIT sigFilesChanged(); } Q_EMIT sigRequestCompleted(RequestType::ListFile); }); } void GDriveHandler::createNewFileRequest(const QUrl &itemUrl) { if(!isAccessManagerValid()) return; QString tokenStr = "Bearer " + getToken(); QList<QUrl> files; Utils::getFilesInDirectoryRecursive(itemUrl, files); for(auto f : files) { QNetworkRequest newRequest((QUrl(UPLOAD_URL +"?"+ RESUMABLE_OPTION))); newRequest.setRawHeader("Authorization", tokenStr.toUtf8()); newRequest.setRawHeader("Accept", "application/json"); newRequest.setRawHeader("Content-Type", "application/json"); QJsonObject jobj; jobj["name"] = QFileInfo(QFile(f.toLocalFile())).fileName(); QNetworkReply* reply = m_manager->post(newRequest, QJsonDocument(jobj).toJson()); connect(reply, &QNetworkReply::finished, [reply, newRequest, this, f]() { int httpStatus = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); QNetworkReply::NetworkError err = reply->error(); if ((err != QNetworkReply::NoError) || (httpStatus == 0)) { #if defined (QT_DEBUG) qDebug() << "Error:" << err << " " << httpStatus; #endif Q_EMIT sigRequestError(RequestType::CreateFile, f); } else { QByteArray ret = reply->readAll(); reply->abort(); reply->deleteLater(); auto location = reply->header(QNetworkRequest::LocationHeader); Q_EMIT sigRequestCompleted(RequestType::CreateFile, f, location.toString()); } }); } } void GDriveHandler::uploadItemRequest(const QUrl &itemUrl, const QUrl& remoteUrl) { if(!isAccessManagerValid()) return; QString tokenStr = "Bearer " + getToken(); QNetworkRequest newRequest(remoteUrl); auto file = new QFile(itemUrl.toLocalFile()); if(file->open(QIODevice::ReadOnly)) { QMimeDatabase mimeDB; QMimeType mime = mimeDB.mimeTypeForFile(file->fileName()); QByteArray mimeType = mime.name().toUtf8(); newRequest.setRawHeader("X-Upload-Content-Type", mimeType); newRequest.setRawHeader("Content-Length", QByteArray::number(file->size())); newRequest.setRawHeader("Content-Type", "application/json; charset=UTF-8"); newRequest.setRawHeader("Authorization", tokenStr.toUtf8()); QNetworkReply* reply = m_manager->put(newRequest, file->readAll()); file->close(); connect(reply, &QNetworkReply::finished, [reply, newRequest, this, itemUrl, remoteUrl]() { int httpStatus = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); QNetworkReply::NetworkError err = reply->error(); if ((err != QNetworkReply::NoError) || (httpStatus == 0)) { #if defined (QT_DEBUG) qDebug() << httpStatus << err; #endif Q_EMIT sigRequestError(RequestType::UploadFile, remoteUrl, itemUrl.toString()); } else { Q_EMIT sigRequestCompleted(RequestType::UploadFile, remoteUrl, itemUrl.toString()); } }); } }
30.421875
100
0.624893
[ "object" ]
c886d50b00821221402aa7a1525739af9b765d02
1,209
cc
C++
shell/main.cc
aminya/shell-plus-plus
ba5f50238cf3376850ba3e29f1a18c5b1204aa9a
[ "Apache-2.0" ]
98
2017-03-09T13:00:37.000Z
2022-03-07T11:20:52.000Z
shell/main.cc
aminya/shell-plus-plus
ba5f50238cf3376850ba3e29f1a18c5b1204aa9a
[ "Apache-2.0" ]
9
2019-05-23T08:32:03.000Z
2022-03-08T23:35:15.000Z
shell/main.cc
aminya/shell-plus-plus
ba5f50238cf3376850ba3e29f1a18c5b1204aa9a
[ "Apache-2.0" ]
11
2018-01-27T12:38:31.000Z
2021-10-13T05:31:05.000Z
// Copyright 2016 Alex Silva Torres // // 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 <iostream> #include <fstream> #include <sstream> #include <vector> #include <string> #include "runner.h" void help() { std::cerr << "shpp [file]\n"; } std::vector<std::string> Args(int argc, char **argv) { std::vector<std::string> args; if (argc > 1) { for (int i = 1; i < argc; i++) { args.push_back(std::string(argv[i])); } } return args; } int main(int argc, char **argv) { shpp::Runner runner; if (argc == 1) { runner.ExecInterative(); } else { std::vector<std::string> args = Args(argc, argv); runner.Exec(argv[1], std::move(args)); } return 0; }
23.705882
75
0.665012
[ "vector" ]
c88821149ca3449ad0b67749aaed660e497debfb
2,347
cxx
C++
panda/src/net/test_tcp_client.cxx
cmarshall108/panda3d-python3
8bea2c0c120b03ec1c9fd179701fdeb7510bb97b
[ "PHP-3.0", "PHP-3.01" ]
null
null
null
panda/src/net/test_tcp_client.cxx
cmarshall108/panda3d-python3
8bea2c0c120b03ec1c9fd179701fdeb7510bb97b
[ "PHP-3.0", "PHP-3.01" ]
null
null
null
panda/src/net/test_tcp_client.cxx
cmarshall108/panda3d-python3
8bea2c0c120b03ec1c9fd179701fdeb7510bb97b
[ "PHP-3.0", "PHP-3.01" ]
null
null
null
/** * PANDA 3D SOFTWARE * Copyright (c) Carnegie Mellon University. All rights reserved. * * All use of this software is subject to the terms of the revised BSD * license. You should have received a copy of this license along * with this source code in a file named "LICENSE." * * @file test_tcp_client.cxx * @author drose * @date 2000-02-09 */ #include "queuedConnectionManager.h" #include "queuedConnectionReader.h" #include "connectionWriter.h" #include "netAddress.h" #include "connection.h" #include "netDatagram.h" #include "datagram_ui.h" using std::cin; using std::cout; int main(int argc, char *argv[]) { if (argc != 3) { nout << "test_tcp_client host port\n"; exit(1); } std::string hostname = argv[1]; int port = atoi(argv[2]); NetAddress host; if (!host.set_host(hostname, port)) { nout << "Unknown host: " << hostname << "\n"; } QueuedConnectionManager cm; PT(Connection) c = cm.open_TCP_client_connection(host, 5000); if (c.is_null()) { nout << "No connection.\n"; exit(1); } nout << "Successfully opened TCP connection to " << hostname << " on port " << c->get_address().get_port() << " and IP " << c->get_address() << "\n"; QueuedConnectionReader reader(&cm, 0); reader.add_connection(c); ConnectionWriter writer(&cm, 0); NetDatagram datagram; cout << "Enter a datagram.\n"; cin >> datagram; bool lost_connection = false; while (!cin.fail() && !lost_connection) { // Send the datagram. writer.send(datagram, c); // Check for a lost connection. while (cm.reset_connection_available()) { PT(Connection) connection; if (cm.get_reset_connection(connection)) { nout << "Lost connection from " << connection->get_address() << "\n"; cm.close_connection(connection); if (connection == c) { lost_connection = true; } } } // Now poll for new datagrams on the socket. while (reader.data_available()) { if (reader.get_data(datagram)) { nout << "Got datagram " << datagram << "from " << datagram.get_address() << "\n"; datagram.dump_hex(nout); } } if (!lost_connection) { cout << "\nEnter a datagram.\n"; cin >> datagram; } } nout << "Exiting\n"; return (0); }
23.707071
70
0.612271
[ "3d" ]
c8885125431c46b11a776c7249c4532081f86ffc
1,436
cpp
C++
Engine/src/scene.cpp
julienbernat/dmri-explorer
32639916b0a95ecc2ae7484f9e1a084f84c3035a
[ "MIT" ]
null
null
null
Engine/src/scene.cpp
julienbernat/dmri-explorer
32639916b0a95ecc2ae7484f9e1a084f84c3035a
[ "MIT" ]
null
null
null
Engine/src/scene.cpp
julienbernat/dmri-explorer
32639916b0a95ecc2ae7484f9e1a084f84c3035a
[ "MIT" ]
null
null
null
#include <scene.h> #include <sh_field.h> #include <glm/gtx/transform.hpp> #include <utils.hpp> #include <application_state.h> namespace Slicer { Scene::Scene(const std::shared_ptr<ApplicationState>& state) :mState(state) ,mCoordinateSystem(new CoordinateSystem()) { } Scene::~Scene() { } void Scene::AddSHField() { // create a SH Field model mModels.push_back(std::shared_ptr<SHField>(new SHField(mState, mCoordinateSystem))); } void Scene::Render() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); for(auto model : mModels) { model->Draw(); } } void Scene::RotateCS(const glm::vec2& vec) { const float& rotationSpeed = mState->Window.RotationSpeed.Get(); const float dx = -vec.x * rotationSpeed; const float dy = -vec.y * rotationSpeed; glm::mat4 transform = glm::rotate(dx, glm::vec3(0.0, 1.0, 0.0)); transform = glm::rotate(dy, glm::vec3(1.0, 0.0, 0.0)) * transform; mCoordinateSystem->ApplyTransform(transform); } void Scene::TranslateCS(const glm::vec2& vec) { const float& translationSpeed = mState->Window.TranslationSpeed.Get(); const float dx = vec.x * translationSpeed; const float dy = vec.y * translationSpeed; const glm::mat4 transform = glm::translate(- dx * glm::vec3(1.0, 0.0, 0.0) + dy * glm::vec3(0.0, 1.0, 0.0)); mCoordinateSystem->ApplyTransform(transform); } } // namespace Slicer
26.592593
88
0.659471
[ "render", "model", "transform" ]
c88893a6e6c7b549e185b4378d5ab15abe47d55d
9,638
cpp
C++
Marlin/src/lcd/menu/game/snake.cpp
tom-2273/Tronxy_SKR_mini_E3_V20
bc4a8dc2c6c627e4bd7aa423794246f5b051448d
[ "CC0-1.0" ]
null
null
null
Marlin/src/lcd/menu/game/snake.cpp
tom-2273/Tronxy_SKR_mini_E3_V20
bc4a8dc2c6c627e4bd7aa423794246f5b051448d
[ "CC0-1.0" ]
null
null
null
Marlin/src/lcd/menu/game/snake.cpp
tom-2273/Tronxy_SKR_mini_E3_V20
bc4a8dc2c6c627e4bd7aa423794246f5b051448d
[ "CC0-1.0" ]
null
null
null
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program 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. * * This program 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 this program. If not, see <https://www.gnu.org/licenses/>. * */ #include "../../../inc/MarlinConfigPre.h" #if ENABLED(MARLIN_SNAKE) #include "game.h" #define SNAKE_BOX 4 #define HEADER_H (MENU_FONT_ASCENT - 2) #define SNAKE_WH (SNAKE_BOX + 1) #define IDEAL_L 2 #define IDEAL_R (LCD_PIXEL_WIDTH - 1 - 2) #define IDEAL_T (HEADER_H + 2) #define IDEAL_B (LCD_PIXEL_HEIGHT - 1 - 2) #define IDEAL_W (IDEAL_R - (IDEAL_L) + 1) #define IDEAL_H (IDEAL_B - (IDEAL_T) + 1) #define GAME_W int((IDEAL_W) / (SNAKE_WH)) #define GAME_H int((IDEAL_H) / (SNAKE_WH)) #define BOARD_W ((SNAKE_WH) * (GAME_W) + 1) #define BOARD_H ((SNAKE_WH) * (GAME_H) + 1) #define BOARD_L ((LCD_PIXEL_WIDTH - (BOARD_W) + 1) / 2) #define BOARD_R (BOARD_L + BOARD_W - 1) #define BOARD_T (((LCD_PIXEL_HEIGHT + IDEAL_T) - (BOARD_H)) / 2) #define BOARD_B (BOARD_T + BOARD_H - 1) #define GAMEX(X) (BOARD_L + ((X) * (SNAKE_WH))) #define GAMEY(Y) (BOARD_T + ((Y) * (SNAKE_WH))) #if SNAKE_BOX > 2 #define FOOD_WH SNAKE_BOX #else #define FOOD_WH 2 #endif #if SNAKE_BOX < 1 #define SNAKE_SIZ 1 #else #define SNAKE_SIZ SNAKE_BOX #endif constexpr fixed_t snakev = FTOF(0.20); snake_data_t &sdat = marlin_game_data.snake; // Remove the first pixel from the tail. // If needed, shift out the first segment. void shorten_tail() { pos_t &p = sdat.snake_tail[0], &q = sdat.snake_tail[1]; bool shift = false; if (p.x == q.x) { // Vertical line p.y += (q.y > p.y) ? 1 : -1; shift = p.y == q.y; } else { // Horizontal line p.x += (q.x > p.x) ? 1 : -1; shift = p.x == q.x; } if (shift) { sdat.head_ind--; LOOP_LE_N(i, sdat.head_ind) sdat.snake_tail[i] = sdat.snake_tail[i + 1]; } } // The food is on a line inline bool food_on_line() { LOOP_L_N(n, sdat.head_ind) { pos_t &p = sdat.snake_tail[n], &q = sdat.snake_tail[n + 1]; if (p.x == q.x) { if ((sdat.foodx == p.x - 1 || sdat.foodx == p.x) && WITHIN(sdat.foody, _MIN(p.y, q.y), _MAX(p.y, q.y))) return true; } else if ((sdat.foody == p.y - 1 || sdat.foody == p.y) && WITHIN(sdat.foodx, _MIN(p.x, q.x), _MAX(p.x, q.x))) return true; } return false; } // Add a new food blob void food_reset() { do { sdat.foodx = random(0, GAME_W); sdat.foody = random(0, GAME_H); } while (food_on_line()); } // Turn the snake cw or ccw inline void turn_snake(const bool cw) { sdat.snake_dir += cw ? 1 : -1; sdat.snake_dir &= 0x03; sdat.head_ind++; sdat.snake_tail[sdat.head_ind].x = FTOB(sdat.snakex); sdat.snake_tail[sdat.head_ind].y = FTOB(sdat.snakey); } // Reset the snake for a new game void snake_reset() { // Init the head and velocity sdat.snakex = BTOF(1); sdat.snakey = BTOF(GAME_H / 2); //snakev = FTOF(0.25); // Init the tail with a cw turn sdat.snake_dir = 0; sdat.head_ind = 0; sdat.snake_tail[0].x = 0; sdat.snake_tail[0].y = GAME_H / 2; turn_snake(true); // Clear food flag sdat.food_cnt = 5; // Clear the controls ui.encoderPosition = 0; sdat.old_encoder = 0; } // Check if head segment overlaps another bool snake_overlap() { // 4 lines must exist before a collision is possible if (sdat.head_ind < 4) return false; // Is the last segment crossing any others? const pos_t &h1 = sdat.snake_tail[sdat.head_ind - 1], &h2 = sdat.snake_tail[sdat.head_ind]; // VERTICAL head segment? if (h1.x == h2.x) { // Loop from oldest to segment two away from head LOOP_L_N(n, sdat.head_ind - 2) { // Segment p to q const pos_t &p = sdat.snake_tail[n], &q = sdat.snake_tail[n + 1]; if (p.x != q.x) { // Crossing horizontal segment if (WITHIN(h1.x, _MIN(p.x, q.x), _MAX(p.x, q.x)) && (h1.y <= p.y) == (h2.y >= p.y)) return true; } // Overlapping vertical segment else if (h1.x == p.x && _MIN(h1.y, h2.y) <= _MAX(p.y, q.y) && _MAX(h1.y, h2.y) >= _MIN(p.y, q.y)) return true; } } else { // Loop from oldest to segment two away from head LOOP_L_N(n, sdat.head_ind - 2) { // Segment p to q const pos_t &p = sdat.snake_tail[n], &q = sdat.snake_tail[n + 1]; if (p.y != q.y) { // Crossing vertical segment if (WITHIN(h1.y, _MIN(p.y, q.y), _MAX(p.y, q.y)) && (h1.x <= p.x) == (h2.x >= p.x)) return true; } // Overlapping horizontal segment else if (h1.y == p.y && _MIN(h1.x, h2.x) <= _MAX(p.x, q.x) && _MAX(h1.x, h2.x) >= _MIN(p.x, q.x)) return true; } } return false; } void SnakeGame::game_screen() { // Run the snake logic if (game_frame()) do { // Run logic twice for finer resolution // Move the snake's head one unit in the current direction const int8_t oldx = FTOB(sdat.snakex), oldy = FTOB(sdat.snakey); switch (sdat.snake_dir) { case 0: sdat.snakey -= snakev; break; case 1: sdat.snakex += snakev; break; case 2: sdat.snakey += snakev; break; case 3: sdat.snakex -= snakev; break; } const int8_t x = FTOB(sdat.snakex), y = FTOB(sdat.snakey); // If movement took place... if (oldx != x || oldy != y) { if (!WITHIN(x, 0, GAME_W - 1) || !WITHIN(y, 0, GAME_H - 1)) { game_state = 0; // Game Over _BUZZ(400, 40); // Bzzzt! break; // ...out of do-while } sdat.snake_tail[sdat.head_ind].x = x; sdat.snake_tail[sdat.head_ind].y = y; // Change snake direction if set const int8_t enc = int8_t(ui.encoderPosition), diff = enc - sdat.old_encoder; if (diff) { sdat.old_encoder = enc; turn_snake(diff > 0); } if (sdat.food_cnt) --sdat.food_cnt; else shorten_tail(); // Did the snake collide with itself or go out of bounds? if (snake_overlap()) { game_state = 0; // Game Over _BUZZ(400, 40); // Bzzzt! } // Is the snake at the food? else if (x == sdat.foodx && y == sdat.foody) { _BUZZ(5, 220); _BUZZ(5, 280); score++; sdat.food_cnt = 2; food_reset(); } } } while(0); u8g.setColorIndex(1); // Draw Score if (PAGE_UNDER(HEADER_H)) lcd_put_int(0, HEADER_H - 1, score); // DRAW THE PLAYFIELD BORDER u8g.drawFrame(BOARD_L - 2, BOARD_T - 2, BOARD_R - BOARD_L + 4, BOARD_B - BOARD_T + 4); // Draw the snake (tail) #if SNAKE_WH < 2 // At this scale just draw a line LOOP_L_N(n, sdat.head_ind) { const pos_t &p = sdat.snake_tail[n], &q = sdat.snake_tail[n + 1]; if (p.x == q.x) { const int8_t y1 = GAMEY(_MIN(p.y, q.y)), y2 = GAMEY(_MAX(p.y, q.y)); if (PAGE_CONTAINS(y1, y2)) u8g.drawVLine(GAMEX(p.x), y1, y2 - y1 + 1); } else if (PAGE_CONTAINS(GAMEY(p.y), GAMEY(p.y))) { const int8_t x1 = GAMEX(_MIN(p.x, q.x)), x2 = GAMEX(_MAX(p.x, q.x)); u8g.drawHLine(x1, GAMEY(p.y), x2 - x1 + 1); } } #elif SNAKE_WH == 2 // At this scale draw two lines LOOP_L_N(n, sdat.head_ind) { const pos_t &p = sdat.snake_tail[n], &q = sdat.snake_tail[n + 1]; if (p.x == q.x) { const int8_t y1 = GAMEY(_MIN(p.y, q.y)), y2 = GAMEY(_MAX(p.y, q.y)); if (PAGE_CONTAINS(y1, y2 + 1)) u8g.drawFrame(GAMEX(p.x), y1, 2, y2 - y1 + 1 + 1); } else { const int8_t py = GAMEY(p.y); if (PAGE_CONTAINS(py, py + 1)) { const int8_t x1 = GAMEX(_MIN(p.x, q.x)), x2 = GAMEX(_MAX(p.x, q.x)); u8g.drawFrame(x1, py, x2 - x1 + 1 + 1, 2); } } } #else // Draw a series of boxes LOOP_L_N(n, sdat.head_ind) { const pos_t &p = sdat.snake_tail[n], &q = sdat.snake_tail[n + 1]; if (p.x == q.x) { const int8_t y1 = _MIN(p.y, q.y), y2 = _MAX(p.y, q.y); if (PAGE_CONTAINS(GAMEY(y1), GAMEY(y2) + SNAKE_SIZ - 1)) { for (int8_t i = y1; i <= y2; ++i) { const int8_t y = GAMEY(i); if (PAGE_CONTAINS(y, y + SNAKE_SIZ - 1)) u8g.drawBox(GAMEX(p.x), y, SNAKE_SIZ, SNAKE_SIZ); } } } else { const int8_t py = GAMEY(p.y); if (PAGE_CONTAINS(py, py + SNAKE_SIZ - 1)) { const int8_t x1 = _MIN(p.x, q.x), x2 = _MAX(p.x, q.x); for (int8_t i = x1; i <= x2; ++i) u8g.drawBox(GAMEX(i), py, SNAKE_SIZ, SNAKE_SIZ); } } } #endif // Draw food const int8_t fy = GAMEY(sdat.foody); if (PAGE_CONTAINS(fy, fy + FOOD_WH - 1)) { const int8_t fx = GAMEX(sdat.foodx); u8g.drawFrame(fx, fy, FOOD_WH, FOOD_WH); if (FOOD_WH == 5) u8g.drawPixel(fx + 2, fy + 2); } // Draw GAME OVER if (!game_state) draw_game_over(); // A click always exits this game if (ui.use_click()) exit_game(); } void SnakeGame::enter_game() { init_game(1, game_screen); // 1 = Game running snake_reset(); food_reset(); } #endif // MARLIN_SNAKE
29.746914
116
0.586429
[ "3d" ]
c88f617a93a943ced892a9f276251e484a87a1a4
659
hpp
C++
include/mgard-x/MDR-X/ErrorCollector/ErrorCollectorInterface.hpp
JieyangChen7/MGARD
acec8facae1e2767a3adff2bb3c30f3477e69bdb
[ "Apache-2.0" ]
null
null
null
include/mgard-x/MDR-X/ErrorCollector/ErrorCollectorInterface.hpp
JieyangChen7/MGARD
acec8facae1e2767a3adff2bb3c30f3477e69bdb
[ "Apache-2.0" ]
null
null
null
include/mgard-x/MDR-X/ErrorCollector/ErrorCollectorInterface.hpp
JieyangChen7/MGARD
acec8facae1e2767a3adff2bb3c30f3477e69bdb
[ "Apache-2.0" ]
null
null
null
#ifndef _MDR_ERROR_COLLECTOR_INTERFACE_HPP #define _MDR_ERROR_COLLECTOR_INTERFACE_HPP namespace mgard_x { namespace MDR { namespace concepts { // Error estimator: estimate impact of level errors on the final error template <typename T> class ErrorCollectorInterface { public: virtual ~ErrorCollectorInterface() = default; virtual std::vector<double> collect_level_error(T const *data, SIZE n, int num_bitplanes, T max_level_error) const = 0; virtual void print() const = 0; }; } // namespace concepts } // namespace MDR } // namespace mgard_x #endif
29.954545
79
0.660091
[ "vector" ]
c890db3ed08c02faefe2f039158ffcd242a50774
11,065
cc
C++
chrome/browser/ui/webui/ntp/ntp_login_handler.cc
MIPS/external-chromium_org
e31b3128a419654fd14003d6117caa8da32697e7
[ "BSD-3-Clause" ]
2
2017-03-21T23:19:25.000Z
2019-02-03T05:32:47.000Z
chrome/browser/ui/webui/ntp/ntp_login_handler.cc
carlosavignano/android_external_chromium_org
2b5652f7889ccad0fbdb1d52b04bad4c23769547
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/ui/webui/ntp/ntp_login_handler.cc
carlosavignano/android_external_chromium_org
2b5652f7889ccad0fbdb1d52b04bad4c23769547
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
3
2017-07-31T19:09:52.000Z
2019-01-04T18:48:50.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/ntp/ntp_login_handler.h" #include <string> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/metrics/histogram.h" #include "base/prefs/pref_notifier.h" #include "base/prefs/pref_service.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_info_cache.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/profiles/profile_metrics.h" #include "chrome/browser/signin/signin_manager.h" #include "chrome/browser/signin/signin_manager_factory.h" #include "chrome/browser/signin/signin_promo.h" #include "chrome/browser/sync/profile_sync_service.h" #include "chrome/browser/sync/profile_sync_service_factory.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/chrome_pages.h" #include "chrome/browser/ui/webui/ntp/new_tab_ui.h" #include "chrome/browser/web_resource/promo_resource_service.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" #include "content/public/browser/notification_details.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" #include "content/public/common/page_zoom.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "net/base/escape.h" #include "skia/ext/image_operations.h" #include "ui/base/l10n/l10n_util.h" #include "ui/gfx/canvas.h" #include "ui/gfx/image/image.h" #include "ui/webui/web_ui_util.h" using content::OpenURLParams; using content::Referrer; namespace { SkBitmap GetGAIAPictureForNTP(const gfx::Image& image) { // This value must match the width and height value of login-status-icon // in new_tab.css. const int kLength = 27; SkBitmap bmp = skia::ImageOperations::Resize(*image.ToSkBitmap(), skia::ImageOperations::RESIZE_BEST, kLength, kLength); gfx::Canvas canvas(gfx::Size(kLength, kLength), ui::SCALE_FACTOR_100P, false); canvas.DrawImageInt(gfx::ImageSkia::CreateFrom1xBitmap(bmp), 0, 0); // Draw a gray border on the inside of the icon. SkColor color = SkColorSetARGB(83, 0, 0, 0); canvas.DrawRect(gfx::Rect(0, 0, kLength - 1, kLength - 1), color); return canvas.ExtractImageRep().sk_bitmap(); } // Puts the |content| into a span with the given CSS class. string16 CreateSpanWithClass(const string16& content, const std::string& css_class) { return ASCIIToUTF16("<span class='" + css_class + "'>") + net::EscapeForHTML(content) + ASCIIToUTF16("</span>"); } } // namespace NTPLoginHandler::NTPLoginHandler() { } NTPLoginHandler::~NTPLoginHandler() { } void NTPLoginHandler::RegisterMessages() { PrefService* pref_service = Profile::FromWebUI(web_ui())->GetPrefs(); username_pref_.Init(prefs::kGoogleServicesUsername, pref_service, base::Bind(&NTPLoginHandler::UpdateLogin, base::Unretained(this))); signin_allowed_pref_.Init(prefs::kSigninAllowed, pref_service, base::Bind(&NTPLoginHandler::UpdateLogin, base::Unretained(this))); registrar_.Add(this, chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED, content::NotificationService::AllSources()); web_ui()->RegisterMessageCallback("initializeSyncLogin", base::Bind(&NTPLoginHandler::HandleInitializeSyncLogin, base::Unretained(this))); web_ui()->RegisterMessageCallback("showSyncLoginUI", base::Bind(&NTPLoginHandler::HandleShowSyncLoginUI, base::Unretained(this))); web_ui()->RegisterMessageCallback("loginMessageSeen", base::Bind(&NTPLoginHandler::HandleLoginMessageSeen, base::Unretained(this))); web_ui()->RegisterMessageCallback("showAdvancedLoginUI", base::Bind(&NTPLoginHandler::HandleShowAdvancedLoginUI, base::Unretained(this))); } void NTPLoginHandler::Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { if (type == chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED) { UpdateLogin(); } else { NOTREACHED(); } } void NTPLoginHandler::HandleInitializeSyncLogin(const ListValue* args) { UpdateLogin(); } void NTPLoginHandler::HandleShowSyncLoginUI(const ListValue* args) { Profile* profile = Profile::FromWebUI(web_ui()); std::string username = profile->GetPrefs()->GetString( prefs::kGoogleServicesUsername); content::WebContents* web_contents = web_ui()->GetWebContents(); Browser* browser = chrome::FindBrowserWithWebContents(web_contents); if (!browser) return; if (username.empty()) { #if !defined(OS_ANDROID) // The user isn't signed in, show the sign in promo. if (signin::ShouldShowPromo(profile)) { signin::Source source = (web_contents->GetURL().spec() == chrome::kChromeUIAppsURL) ? signin::SOURCE_APPS_PAGE_LINK : signin::SOURCE_NTP_LINK; chrome::ShowBrowserSignin(browser, source); RecordInHistogram(NTP_SIGN_IN_PROMO_CLICKED); } #endif } else if (args->GetSize() == 4 && chrome::IsCommandEnabled(browser, IDC_SHOW_AVATAR_MENU)) { // The user is signed in, show the profiles menu. double x = 0; double y = 0; double width = 0; double height = 0; bool success = args->GetDouble(0, &x); DCHECK(success); success = args->GetDouble(1, &y); DCHECK(success); success = args->GetDouble(2, &width); DCHECK(success); success = args->GetDouble(3, &height); DCHECK(success); double zoom = content::ZoomLevelToZoomFactor(web_contents->GetZoomLevel()); gfx::Rect rect(x * zoom, y * zoom, width * zoom, height * zoom); browser->window()->ShowAvatarBubble(web_ui()->GetWebContents(), rect); ProfileMetrics::LogProfileOpenMethod(ProfileMetrics::NTP_AVATAR_BUBBLE); } } void NTPLoginHandler::RecordInHistogram(int type) { // Invalid type to record. if (type < NTP_SIGN_IN_PROMO_VIEWED || type > NTP_SIGN_IN_PROMO_CLICKED) { NOTREACHED(); } else { UMA_HISTOGRAM_ENUMERATION("SyncPromo.NTPPromo", type, NTP_SIGN_IN_PROMO_BUCKET_BOUNDARY); } } void NTPLoginHandler::HandleLoginMessageSeen(const ListValue* args) { Profile::FromWebUI(web_ui())->GetPrefs()->SetBoolean( prefs::kSignInPromoShowNTPBubble, false); NewTabUI* ntp_ui = NewTabUI::FromWebUIController(web_ui()->GetController()); // When instant extended is enabled, there may not be a NewTabUI object. if (ntp_ui) ntp_ui->set_showing_sync_bubble(true); } void NTPLoginHandler::HandleShowAdvancedLoginUI(const ListValue* args) { Browser* browser = chrome::FindBrowserWithWebContents(web_ui()->GetWebContents()); if (browser) chrome::ShowBrowserSignin(browser, signin::SOURCE_NTP_LINK); } void NTPLoginHandler::UpdateLogin() { Profile* profile = Profile::FromWebUI(web_ui()); std::string username = profile->GetPrefs()->GetString( prefs::kGoogleServicesUsername); string16 header, sub_header; std::string icon_url; if (!username.empty()) { ProfileInfoCache& cache = g_browser_process->profile_manager()->GetProfileInfoCache(); size_t profile_index = cache.GetIndexOfProfileWithPath(profile->GetPath()); if (profile_index != std::string::npos) { // Only show the profile picture and full name for the single profile // case. In the multi-profile case the profile picture is visible in the // title bar and the full name can be ambiguous. if (cache.GetNumberOfProfiles() == 1) { string16 name = cache.GetGAIANameOfProfileAtIndex(profile_index); if (!name.empty()) header = CreateSpanWithClass(name, "profile-name"); const gfx::Image* image = cache.GetGAIAPictureOfProfileAtIndex(profile_index); if (image) icon_url = webui::GetBitmapDataUrl(GetGAIAPictureForNTP(*image)); } if (header.empty()) header = CreateSpanWithClass(UTF8ToUTF16(username), "profile-name"); } } else { #if !defined(OS_ANDROID) // Android uses a custom sign in promo. if (signin::ShouldShowPromo(profile)) { string16 signed_in_link = l10n_util::GetStringUTF16( IDS_SYNC_PROMO_NOT_SIGNED_IN_STATUS_LINK); signed_in_link = CreateSpanWithClass(signed_in_link, "link-span"); header = l10n_util::GetStringFUTF16( IDS_SYNC_PROMO_NOT_SIGNED_IN_STATUS_HEADER, l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_NAME)); sub_header = l10n_util::GetStringFUTF16( IDS_SYNC_PROMO_NOT_SIGNED_IN_STATUS_SUB_HEADER, signed_in_link); // Record that the user was shown the promo. RecordInHistogram(NTP_SIGN_IN_PROMO_VIEWED); } #endif } StringValue header_value(header); StringValue sub_header_value(sub_header); StringValue icon_url_value(icon_url); base::FundamentalValue is_user_signed_in(!username.empty()); web_ui()->CallJavascriptFunction("ntp.updateLogin", header_value, sub_header_value, icon_url_value, is_user_signed_in); } // static bool NTPLoginHandler::ShouldShow(Profile* profile) { #if defined(OS_CHROMEOS) // For now we don't care about showing sync status on Chrome OS. The promo // UI and the avatar menu don't exist on that platform. return false; #else SigninManager* signin = SigninManagerFactory::GetForProfile(profile); return !profile->IsOffTheRecord() && signin && signin->IsSigninAllowed(); #endif } // static void NTPLoginHandler::GetLocalizedValues(Profile* profile, DictionaryValue* values) { PrefService* prefs = profile->GetPrefs(); bool hide_sync = !prefs->GetBoolean(prefs::kSignInPromoShowNTPBubble); string16 message = hide_sync ? string16() : l10n_util::GetStringFUTF16(IDS_SYNC_PROMO_NTP_BUBBLE_MESSAGE, l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_NAME)); values->SetString("login_status_message", message); values->SetString("login_status_url", hide_sync ? std::string() : chrome::kSyncLearnMoreURL); values->SetString("login_status_advanced", hide_sync ? string16() : l10n_util::GetStringUTF16(IDS_SYNC_PROMO_NTP_BUBBLE_ADVANCED)); values->SetString("login_status_dismiss", hide_sync ? string16() : l10n_util::GetStringUTF16(IDS_SYNC_PROMO_NTP_BUBBLE_OK)); }
38.420139
79
0.709173
[ "object" ]
c8929e87a0418edd7268ec1f2f894a307a2e39b9
4,457
cpp
C++
Application/source/ui/Theme.cpp
tallbl0nde/TriPlayer
737adfdfcea89924286b1cd13ec47a9ebaffda96
[ "MIT" ]
106
2020-11-01T09:58:37.000Z
2022-03-26T10:44:26.000Z
Application/source/ui/Theme.cpp
PoloNX/TriPlayer
39deb363472d518163aa48ff066477cc69495467
[ "MIT" ]
30
2020-11-01T11:21:48.000Z
2022-02-01T23:09:47.000Z
Application/source/ui/Theme.cpp
PoloNX/TriPlayer
39deb363472d518163aa48ff066477cc69495467
[ "MIT" ]
15
2020-11-02T12:06:03.000Z
2021-08-05T14:22:39.000Z
#include "lang/Lang.hpp" #include <numbers> #include "ui/Theme.hpp" std::string Theme::colourToString(const Colour c) { std::string str; switch (c) { case Theme::Colour::Red: str = "Theme.Red"_lang; break; case Theme::Colour::Orange: str = "Theme.Orange"_lang; break; case Theme::Colour::Yellow: str = "Theme.Yellow"_lang; break; case Theme::Colour::Green: str = "Theme.Green"_lang; break; case Theme::Colour::Blue: str = "Theme.Blue"_lang; break; case Theme::Colour::Purple: str = "Theme.Purple"_lang; break; case Theme::Colour::Pink: str = "Theme.Pink"_lang; break; } return str; } Theme::Theme() { this->accentColour = Colour::Blue; this->bottomBG_ = Aether::Colour{25, 25, 25, 166}; this->popupBG_ = Aether::Colour{30, 30, 30, 255}; this->sideBG_ = Aether::Colour{17, 17, 17, 128}; this->muted_ = Aether::Colour{120, 120, 120, 255}; this->muted2_ = Aether::Colour{54, 54, 54, 255}; this->FG_ = Aether::Colour{255, 255, 255, 255}; this->selected_ = Aether::Colour{255, 255, 255, 35}; } void Theme::setAccent(Colour c) { this->accentColour = c; } Aether::Colour Theme::bottomBG() { return this->bottomBG_; } Aether::Colour Theme::popupBG() { return this->popupBG_; } Aether::Colour Theme::sideBG() { return this->sideBG_; } Aether::Colour Theme::muted() { return this->muted_; } Aether::Colour Theme::muted2() { return this->muted2_; } Aether::Colour Theme::FG() { return this->FG_; } Aether::Colour Theme::accent() { switch (this->accentColour) { case Colour::Red: return Aether::Colour{255, 35, 55, 255}; break; case Colour::Orange: return Aether::Colour{255, 120, 30, 255}; break; case Colour::Yellow: return Aether::Colour{255, 255, 50, 255}; break; case Colour::Green: return Aether::Colour{50, 255, 100, 255}; break; case Colour::Blue: return Aether::Colour{85, 255, 255, 255}; break; case Colour::Purple: return Aether::Colour{190, 70, 245, 255}; break; case Colour::Pink: return Aether::Colour{255, 125, 255, 255}; break; } return Aether::Colour{255, 255, 255, 255}; } Aether::Colour Theme::selected() { return this->selected_; } std::function<Aether::Colour(uint32_t)> Theme::highlightFunc() { // Copy colours in case object is destroyed Aether::Colour h1 = Aether::Colour{255, 255, 255, 255}; Aether::Colour h2 = Aether::Colour{255, 255, 255, 255}; switch (this->accentColour) { case Colour::Red: h1 = Aether::Colour{140, 10, 10, 255}; h2 = Aether::Colour{255, 25, 25, 255}; break; case Colour::Orange: h1 = Aether::Colour{150, 50, 0, 255}; h2 = Aether::Colour{255, 95, 15, 255}; break; case Colour::Yellow: h1 = Aether::Colour{140, 140, 0, 255}; h2 = Aether::Colour{255, 255, 40, 255}; break; case Colour::Green: h1 = Aether::Colour{10, 135, 60, 255}; h2 = Aether::Colour{50, 255, 80, 255}; break; case Colour::Blue: h1 = Aether::Colour{0, 150, 190, 255}; h2 = Aether::Colour{0, 250, 250, 255}; break; case Colour::Purple: h1 = Aether::Colour{105, 25, 140, 255}; h2 = Aether::Colour{220, 90, 255, 255}; break; case Colour::Pink: h1 = Aether::Colour{170, 50, 170, 255}; h2 = Aether::Colour{255, 105, 245, 255}; break; } return [h1, h2](uint32_t t) { Aether::Colour col = {0, 0, 0, 0}; col.setR(h1.r() + ((h2.r() - h1.r()) * (0.5 * sin(1.8 * std::numbers::pi * (t/1000.0)) + 0.5))); col.setG(h1.g() + ((h2.g() - h1.g()) * (0.5 * sin(1.8 * std::numbers::pi * (t/1000.0)) + 0.5))); col.setB(h1.b() + ((h2.b() - h1.b()) * (0.5 * sin(1.8 * std::numbers::pi * (t/1000.0)) + 0.5))); col.setA(h1.a() + ((h2.a() - h1.a()) * (0.5 * sin(1.8 * std::numbers::pi * (t/1000.0)) + 0.5))); return col; }; }
27.012121
104
0.516715
[ "object" ]
c89380ce40b6a02d01b0018b1250317df24e1ce6
53,529
cpp
C++
inference-engine/src/legacy_api/src/net_pass.cpp
cwzrad/openvino
ae4bd370eac7c695bd797a31e62317d328dbe742
[ "Apache-2.0" ]
null
null
null
inference-engine/src/legacy_api/src/net_pass.cpp
cwzrad/openvino
ae4bd370eac7c695bd797a31e62317d328dbe742
[ "Apache-2.0" ]
null
null
null
inference-engine/src/legacy_api/src/net_pass.cpp
cwzrad/openvino
ae4bd370eac7c695bd797a31e62317d328dbe742
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2018-2020 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "net_pass.h" #include <algorithm> #include <memory> #include <set> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <utility> #include <map> #include <vector> #include "blob_factory.hpp" #include "details/ie_cnn_network_tools.h" #include "cnn_network_impl.hpp" #include "cnn_network_ngraph_impl.hpp" #include "graph_tools.hpp" #include "ie_layers_internal.hpp" #include "ie_memcpy.h" #include "precision_utils.h" #include "ie_legacy_itt.hpp" namespace InferenceEngine { namespace NetPass { template <typename T, typename P> inline bool one_of(T val, P item) { return val == item; } template <typename T, typename P, typename... Args> inline bool one_of(T val, P item, Args... item_others) { return val == item || one_of(val, item_others...); } /************************************************************/ /**** TI Utils ********************************************/ /************************************************************/ static std::vector<DataPtr> getAllInputs(const std::vector<DataPtr>& heads) { CNNLayerSet inputLayers; std::unordered_set<CNNLayer*> allLayers; // Define all start layers for (const auto& data : heads) { auto& secondLayers = getInputTo(data); if (secondLayers.empty()) continue; details::UnorderedDFS( allLayers, secondLayers.begin()->second, [&](CNNLayerPtr layer) { if (layer->insData.empty()) { inputLayers.insert(layer); } }, false); } std::vector<DataPtr> res = heads; // Add fake input data to point on not achievable // layers from head (like const placeholders) for (auto& starter : inputLayers) { DataPtr holder(new Data(starter->name + ":input_holder", starter->precision)); getInputTo(holder)[starter->name] = starter; res.push_back(holder); } return res; } std::vector<CNNLayerPtr> TIBodySortTopologically(const TensorIterator::Body& body) { std::vector<CNNLayerPtr> all_layers; auto all_input_layers = getAllInputs(body.inputs); CNNNetForestDFS( all_input_layers, [&](CNNLayerPtr current) { all_layers.push_back(current); }, false); std::reverse(all_layers.begin(), all_layers.end()); return all_layers; } TensorIterator::Body CopyTIBody(const TensorIterator::Body& body, std::string suffix) { struct NoneStruct {}; auto cp = [&](CNNLayerPtr lp) { return injectData<NoneStruct>(lp); }; const auto all_orig = TIBodySortTopologically(body); std::unordered_map<CNNLayer*, CNNLayerPtr> old2new_l; for (const auto& orig : all_orig) { old2new_l[orig.get()] = cp(orig); } std::unordered_map<Data*, DataPtr> old2new_d; for (auto& in : body.inputs) { auto new_data = std::make_shared<Data>(*in.get()); for (auto& to : getInputTo(new_data)) to.second = old2new_l[to.second.get()]; old2new_d[in.get()] = new_data; } for (const auto& old : all_orig) { auto& new_one = old2new_l[old.get()]; // remap output data for (int i = 0; i < old->outData.size(); i++) { auto old_data = old->outData[i]; auto new_data = new_one->outData[i]; getCreatorLayer(new_data) = CNNLayerWeakPtr(new_one); old2new_d[old_data.get()] = new_data; for (auto& to : getInputTo(new_data)) to.second = old2new_l[to.second.get()]; } // remap input data for (int i = 0; i < old->insData.size(); i++) { auto old_data = old->insData[i].lock(); auto new_data = old2new_d.at(old_data.get()); new_one->insData[i] = new_data; } } // Add suffix if (!suffix.empty()) { for (auto& kvp : old2new_l) { auto layer = kvp.second; auto old_name = layer->name; layer->name += suffix; for (auto& ins : layer->insData) { getInputTo(ins.lock()).erase(old_name); getInputTo(ins.lock())[layer->name] = layer; } } for (auto& kvp : old2new_d) kvp.second->setName(kvp.second->getName() + suffix); } TensorIterator::Body res; for (auto& in : body.inputs) res.inputs.emplace_back(old2new_d[in.get()]); for (auto& out : body.outputs) res.outputs.emplace_back(old2new_d[out.get()]); // Fake holder. // The graph itself is a shared_ptr set where parent holds child. // Res.inputs vector hold head of graph and all nodes should be // achievable for oriented search started from that. But place // const holder has no input and cannot be achieved. So we need // to hold then in other way. // // Let's add one more Data object which has no representation in // original network. It will hold all unreachable const placeholder // nodes. // std::unordered_set<CNNLayerPtr> already_on_hold; for (auto &in : res.inputs) { // fake holder Data should have UNSPECIFIED precision if (in->getPrecision() == Precision::UNSPECIFIED) { for (const auto &kvp : getInputTo(in)) { already_on_hold.emplace(kvp.second); } } } std::vector<CNNLayerPtr> to_hold; for (auto& kvp : old2new_l) { auto layer = kvp.second; // layer has no parent Data object and is not on hold if (layer->insData.empty() && !already_on_hold.count(layer)) to_hold.emplace_back(layer); } if (!to_hold.empty()) { // detect existing holder or create new one if (res.inputs.back()->getPrecision() != Precision::UNSPECIFIED || res.inputs.back()->getDims().size() != 0) { res.inputs.emplace_back(new Data("const_holder", Precision::UNSPECIFIED)); } auto holder = res.inputs.back(); for (auto layer : to_hold) { getInputTo(holder)[layer->name] = layer; } } return res; } /************************************************************/ /**** TI rule helpers *************************************/ /************************************************************/ inline bool is_full_ranged(const TensorIterator::PortMap& rule, const DataPtr& data) { if (!data) THROW_IE_EXCEPTION << "Internal error. data == nullptr"; if (rule.axis == -1 || !one_of(rule.stride, 1, -1)) return false; auto& shape = data->getDims(); int size = shape[rule.axis]; int begin = rule.start >= 0 ? rule.start : size + rule.start + 1; int end = rule.end >= 0 ? rule.end : size + rule.end + 1; return (rule.stride == 1) ? begin == 0 && end == size : begin == size && end == 0; } using RuleSet = std::vector<TensorIterator::PortMap>; using RuleClassSet = std::tuple<RuleSet, RuleSet, RuleSet>; /** * @brief Helper to split port mapping rules to three group * * first_class - which has iteration component * second_class - which has no iteration and there are no backedge connection to the same port * third_class - which has no iteration and has corresponding backedge * * @param ti TensorIterator layer to analyze * @return tuple with three classes of port map rule */ static RuleClassSet classifyInputRules(const TensorIterator& ti) { RuleSet first_class_rules, second_class_rules, third_class_rules; std::set<int> ports_with_backedge; for (const auto& back_edge : ti.back_edges) ports_with_backedge.insert(back_edge.to); for (const auto& rule : ti.input_port_map) { if (rule.axis != -1) first_class_rules.push_back(rule); else if (!ports_with_backedge.count(rule.to)) second_class_rules.push_back(rule); else third_class_rules.push_back(rule); } return RuleClassSet {first_class_rules, second_class_rules, third_class_rules}; } static RuleClassSet classifyOutputRules(const TensorIterator& ti) { RuleSet first_class_rules, second_class_rules, third_class_rules; std::set<int> ports_with_backedge; for (const auto& back_edge : ti.back_edges) ports_with_backedge.insert(back_edge.from); for (const auto& rule : ti.output_port_map) { if (rule.axis != -1) first_class_rules.push_back(rule); else if (!ports_with_backedge.count(rule.to)) second_class_rules.push_back(rule); else third_class_rules.push_back(rule); } return RuleClassSet {first_class_rules, second_class_rules, third_class_rules}; } /** * Merge slave connections into master data * * @param master * @param slave */ void CombineData(DataPtr& master, DataPtr& slave) { for (auto& kvp : getInputTo(slave)) { auto& slave_layer = kvp.second; for (auto& slv_ins_wptr : slave_layer->insData) { auto slv_ins = slv_ins_wptr.lock(); // Replace slave ptr with master if (slv_ins == slave) slv_ins_wptr = master; } getInputTo(master)[slave_layer->name] = slave_layer; } } /** * Preserve output data name and update output data map of the network * * @param in_data name to update * @param out_data name to preserve * @param net output data map to update with in_data */ template <typename NET> void SaveOutputDataName(InferenceEngine::DataPtr in_data, InferenceEngine::DataPtr out_data, NET &net) { // TODO: update outputs of the network if out_data was output if (getInputTo(out_data).empty()) { auto data_name = out_data->getName(); in_data->setName(data_name); } } /** * void SaveOutputDataName(InferenceEngine::DataPtr in_data, InferenceEngine::DataPtr out_data, NET &net), where * NET = ICNNNetwork */ void SaveOutputDataName(InferenceEngine::DataPtr in_data, InferenceEngine::DataPtr out_data, ICNNNetwork& net) { if (getInputTo(out_data).empty()) { InferenceEngine::OutputsDataMap outputs_data_map; net.getOutputsInfo(outputs_data_map); auto out_data_name = out_data->getName(); in_data->setName(out_data_name); if (outputs_data_map.count(out_data_name)) { auto parent_layer_ptr = getCreatorLayer(in_data).lock(); IE_ASSERT(parent_layer_ptr != nullptr); auto parent_layer_name = parent_layer_ptr->name; size_t in_data_out_index = 0; for (size_t ind = 0; ind < parent_layer_ptr->outData.size(); ++ind) { if (parent_layer_ptr->outData[ind] == in_data) { in_data_out_index = ind; } } net.addOutput(parent_layer_name, in_data_out_index); } } } /** * Remove layer form graph * May be applied only for inplace layer. One input, one output, * with same tensor descriptors. * * @param layer to remove from graph */ template <typename NET> void RemoveLayer(CNNLayerPtr& layer, NET &net) { IE_ASSERT(layer->insData.size() == 1); IE_ASSERT(layer->outData.size() == 1); auto in_data = layer->input(); auto out_data = layer->outData[0]; IE_ASSERT(in_data->getTensorDesc() == out_data->getTensorDesc()); auto &input_to_map = getInputTo(in_data); auto self_found = std::find_if(input_to_map.begin(), input_to_map.end(), [&layer] (const std::pair<std::string, CNNLayerPtr> &kvp) { return kvp.second == layer; }); IE_ASSERT(self_found != input_to_map.end()); // detach layer from input data input_to_map.erase(self_found); // transfer output connections into parent data CombineData(in_data, out_data); // save name for output data and update network output SaveOutputDataName(in_data, out_data, net); } /************************************************************/ /**** Converter Passes ************************************/ /************************************************************/ static std::string cell_name(RNNSequenceLayer::CellType type) { std::string res; switch (type) { case RNNSequenceLayer::LSTM: res = "LSTM"; break; case RNNSequenceLayer::GRU: case RNNSequenceLayer::GRU_LBR: res = "GRU"; break; case RNNSequenceLayer::RNN: res = "RNN"; break; } return res; } template <typename N> bool convertToRNNSeq(CNNLayerPtr cur, const N& net) { if (cur->type != "TensorIterator") return true; auto ti = std::dynamic_pointer_cast<TensorIterator>(cur); IE_ASSERT(ti) << "Cannot cast object with type TensorIterator to TensorIterator object"; auto all_body_layers = TIBodySortTopologically(ti->body); // Check if body is: squeeze -> lstm_cell -> unsqueeze if (all_body_layers.size() != 3 || all_body_layers[0]->type != "Reshape" || !one_of(all_body_layers[1]->type, "GRUCell", "RNNCell", "LSTMCell") || all_body_layers[2]->type != "Reshape") return false; auto rsp1 = std::dynamic_pointer_cast<ReshapeLayer>(all_body_layers[0]); auto cell = std::dynamic_pointer_cast<RNNCellBase>(all_body_layers[1]); auto rsp2 = std::dynamic_pointer_cast<ReshapeLayer>(all_body_layers[2]); IE_ASSERT(rsp1); IE_ASSERT(cell); IE_ASSERT(rsp2); int NS = (cell->cellType == RNNSequenceLayer::LSTM) ? 2 : 1; // number of states IE_ASSERT(cell->insData.size() == NS + 1); // {data, state1, [state2]} IE_ASSERT(cell->outData.size() == NS); // {state1, [state2]} if (getCreatorLayer(cell->insData[0].lock()).lock() != rsp1 || getInputTo(cell->outData[0]).begin()->second != rsp2) return false; // Check port mapping auto _indx_in = [&](const std::vector<DataPtr>& scope, const DataPtr& data) { int indx = std::find(scope.begin(), scope.end(), data) - scope.begin(); return indx == scope.size() ? -1 : indx; }; int in_dt_idx = _indx_in(ti->body.inputs, rsp1->insData[0].lock()); int in_hs_idx = _indx_in(ti->body.inputs, cell->insData[1].lock()); int in_cs_idx = NS == 2 ? _indx_in(ti->body.inputs, cell->insData[2].lock()) : -1; int out_dt_idx = _indx_in(ti->body.outputs, rsp2->outData[0]); int out_hs_idx = _indx_in(ti->body.outputs, cell->outData[0]); int out_cs_idx = NS == 2 ? _indx_in(ti->body.outputs, cell->outData[1]) : -1; // indexes should be [0,1,2] : sum == 3 or [0,1,-1] : sum == 0 int sum = (NS - 1) * 3; if (in_hs_idx + in_cs_idx + in_dt_idx != sum || out_hs_idx + out_cs_idx + out_dt_idx != sum) return false; std::map<int, TensorIterator::PortMap> i2map, o2map, be2map; for (auto& m : ti->input_port_map) i2map[m.to] = m; for (auto& m : ti->output_port_map) o2map[m.to] = m; for (auto& m : ti->back_edges) be2map[m.to] = m; if (!one_of(i2map.size(), NS + 1, 1) || !one_of(o2map.size(), NS + 1, 1) || !one_of(be2map.size(), NS)) return false; auto in_iter_rule = i2map[in_dt_idx]; auto in_iter_data = ti->insData[in_iter_rule.from].lock(); auto out_iter_rule = o2map[out_dt_idx]; auto out_iter_data = ti->outData[out_iter_rule.from]; // TI iterates only for full range of tensor if (!is_full_ranged(in_iter_rule, in_iter_data) || !is_full_ranged(out_iter_rule, out_iter_data)) return false; // supported only same axis and strides for in/out data tensors if (in_iter_rule.axis != out_iter_rule.axis || in_iter_rule.stride != out_iter_rule.stride) return false; // supported only firs and second dim for LSTM-Sequence if (!one_of(in_iter_rule.axis, 0, 1)) return false; bool no_init_state = i2map.size() == 1; bool no_last_state = o2map.size() == 1; if (!no_init_state && (i2map[in_hs_idx].axis != -1 || (NS == 2 && i2map[in_cs_idx].axis != -1))) return false; if (!no_last_state && (o2map[out_hs_idx].axis != -1 || (NS == 2 && o2map[out_cs_idx].axis != -1))) return false; std::vector<int> i_order {i2map[in_dt_idx].from}; if (!no_init_state) i_order.push_back(i2map[in_hs_idx].from); if (!no_init_state && NS == 2) i_order.push_back(i2map[in_cs_idx].from); std::vector<int> o_order {o2map[out_dt_idx].from}; if (!no_last_state) o_order.push_back(o2map[out_hs_idx].from); if (!no_last_state && NS == 2) o_order.push_back(o2map[out_cs_idx].from); // need swap an i/o ports if it is not in natural order std::string name = cell->name + "_sequence"; std::string type = cell_name(cell->cellType) + "Sequence"; auto rnn = std::make_shared<RNNSequenceLayer>(LayerParams {name, type, cell->precision}); rnn->axis = in_iter_rule.axis; rnn->direction = in_iter_rule.stride == 1 ? RNNSequenceLayer::FWD : RNNSequenceLayer::BWD; // copy base RNN cell fields rnn->cellType = cell->cellType; rnn->_weights = cell->_weights; rnn->_biases = cell->_biases; rnn->blobs["weights"] = rnn->_weights; rnn->blobs["biases"] = rnn->_biases; rnn->blobs = cell->blobs; rnn->activations = cell->activations; rnn->activation_alpha = cell->activation_alpha; rnn->activation_beta = cell->activation_beta; rnn->hidden_size = cell->hidden_size; rnn->clip = cell->clip; for (int i : i_order) { auto in_data = ti->insData[i].lock(); getInputTo(in_data).erase(ti->name); getInputTo(in_data)[rnn->name] = rnn; rnn->insData.push_back(in_data); } for (int i : o_order) { rnn->outData.push_back(ti->outData[i]); getCreatorLayer(rnn->outData.back()) = rnn; } return true; } bool unrollTI(CNNLayerPtr cur, ICNNNetwork& net) { auto inet = dynamic_cast<details::CNNNetworkImpl*>(&net); IE_ASSERT(inet != nullptr); if (cur->type != "TensorIterator") return true; auto ti = std::dynamic_pointer_cast<TensorIterator>(cur); IE_ASSERT(ti) << "Cannot cast object with type TensorIterator to TensorIterator object"; int num = getNumIteration(*ti); // -1 means inconsistent TI if (num == -1) return false; // TODO: better to throw exception const auto& body = ti->body; std::vector<TensorIterator::Body> body_list(num); for (int i = 0; i < num; i++) { // copy with additional suffix to each object name body_list[i] = CopyTIBody(body, ":" + std::to_string(i)); auto holder = body_list[i].inputs.back(); if (holder->getPrecision() == Precision::UNSPECIFIED) { for (auto kvp : getInputTo(holder)) { inet->addLayer(kvp.second); } } } RuleSet first_class, second_class, third_class; std::tie(first_class, second_class, third_class) = classifyInputRules(*ti); /** Clean links on TI */ for (auto& ins : ti->insData) getInputTo(ins.lock()).erase(ti->name); for (auto& outs : ti->outData) getCreatorLayer(outs).reset(); /** FIRST class comes */ for (int i = 0; i < first_class.size(); i++) { auto& rule = first_class[i]; auto in_data = ti->insData[rule.from].lock(); std::string name = ti->name + ":in_split_" + std::to_string(i); auto split = std::make_shared<SplitLayer>(LayerParams {name, "Split", cur->precision}); split->_axis = rule.axis; split->outData.resize(num); split->insData.emplace_back(in_data); getInputTo(in_data)[split->name] = split; for (int j = 0; j < num; j++) { auto body_idx = rule.stride == 1 ? j : num - 1 - j; auto& chunk = body_list[body_idx].inputs[rule.to]; getCreatorLayer(chunk) = split; split->outData[j] = chunk; } } /** SECOND class come on */ for (const auto& rule : second_class) { auto in_data = ti->insData[rule.from].lock(); for (int j = 0; j < num; j++) { auto& chunk = body_list[j].inputs[rule.to]; CombineData(in_data, chunk); } } /** BACK EDGES that's your time */ for (const auto& rule : ti->back_edges) { for (int i = 1; i < num; i++) { auto& from_data = body_list[i - 1].outputs[rule.from]; auto& to_data = body_list[i].inputs[rule.to]; CombineData(from_data, to_data); } } /** THIRD class end up */ for (const auto& rule : third_class) { // first iteration auto from_data = ti->insData[rule.from].lock(); auto& to_data = body_list[0].inputs[rule.to]; CombineData(from_data, to_data); } /** And the same actions for outputs connections */ std::tie(first_class, second_class, third_class) = classifyOutputRules(*ti); /** FIRST class comes */ for (int i = 0; i < first_class.size(); i++) { auto& rule = first_class[i]; auto out_data = ti->outData[rule.from]; std::string name = ti->name + ":out_concat_" + std::to_string(i); auto concat = std::make_shared<ConcatLayer>(LayerParams {name, "Concat", cur->precision}); concat->_axis = rule.axis; concat->insData.resize(num); concat->outData.emplace_back(out_data); getCreatorLayer(out_data) = concat; for (int j = 0; j < num; j++) { auto body_idx = rule.stride == 1 ? j : num - 1 - j; auto& chunk = body_list[body_idx].outputs[rule.to]; getInputTo(chunk)[concat->name] = concat; concat->insData[j] = chunk; } } /** SECOND class come on */ for (const auto& rule : second_class) { auto out_data = ti->outData[rule.from]; for (int j = 0; j < num; j++) { auto& chunk = body_list[j].outputs[rule.to]; CombineData(chunk, out_data); } } /** THIRD class end up */ for (const auto& rule : third_class) { // first iteration auto& from_data = ti->outData[rule.from]; auto& to_data = body_list[num - 1].outputs[rule.to]; auto parent = getCreatorLayer(to_data).lock(); std::replace(parent->outData.begin(), parent->outData.end(), to_data, from_data); getCreatorLayer(from_data) = parent; CombineData(from_data, to_data); } return true; } /************************************************************/ /**** Builder helpers ************************************/ /************************************************************/ static CNNLayerPtr _concat(std::string name, Precision prc, SizeVector dims, int num) { auto res = std::make_shared<ConcatLayer>(LayerParams {name, "Concat", prc}); res->_axis = 1; res->insData.resize(num); res->outData.resize(1); auto out_data = DataPtr(new Data(name, TensorDesc {prc, dims, TensorDesc::getLayoutByDims(dims)})); getCreatorLayer(out_data) = res; res->outData[0] = out_data; return res; } static CNNLayerPtr _split(std::string name, Precision prc, SizeVector dims, int num) { auto res = std::make_shared<SplitLayer>(LayerParams {name, "Split", prc}); res->_axis = 1; res->params["axis"] = std::to_string(res->_axis); res->insData.resize(1); res->outData.resize(num); for (int i = 0; i < num; i++) { auto out_data = DataPtr( new Data(name + "_part_" + std::to_string(i), TensorDesc {prc, dims, TensorDesc::getLayoutByDims(dims)})); getCreatorLayer(out_data) = res; res->outData[i] = out_data; } return res; } static CNNLayerPtr _fc(std::string name, Precision prc, SizeVector dims, Blob::Ptr& W, Blob::Ptr& B) { auto res = std::make_shared<FullyConnectedLayer>(LayerParams {name, "FullyConnected", prc}); res->_weights = W; res->_biases = B; res->_out_num = dims[1]; res->blobs["weights"] = W; res->blobs["biases"] = B; res->params["out-size"] = std::to_string(dims[1]); res->insData.resize(1); res->outData.resize(1); auto out_data = DataPtr(new Data(name, TensorDesc {prc, dims, TensorDesc::getLayoutByDims(dims)})); getCreatorLayer(out_data) = res; res->outData[0] = out_data; return res; } static std::shared_ptr<ClampLayer> _act(std::string name, Precision prc, SizeVector dims, std::string type) { auto res = std::make_shared<ClampLayer>(LayerParams {name, type, prc}); res->params["type"] = type; res->insData.resize(1); res->outData.resize(1); auto out_data = DataPtr(new Data(name, TensorDesc {prc, dims, TensorDesc::getLayoutByDims(dims)})); getCreatorLayer(out_data) = res; res->outData[0] = out_data; return res; } static CNNLayerPtr _pwr(std::string name, Precision prc, SizeVector dims, float scale, float shift) { auto res = std::make_shared<PowerLayer>(LayerParams {name, "Power", prc}); res->power = 1.0; res->scale = scale; res->offset = shift; res->params["power"] = CNNLayer::ie_serialize_float(res->power); res->params["scale"] = CNNLayer::ie_serialize_float(res->scale); res->params["shift"] = CNNLayer::ie_serialize_float(res->offset); res->insData.resize(1); res->outData.resize(1); auto out_data = DataPtr(new Data(name, TensorDesc {prc, dims, TensorDesc::getLayoutByDims(dims)})); getCreatorLayer(out_data) = res; res->outData[0] = out_data; return res; } static CNNLayerPtr _eltw(std::string name, Precision prc, SizeVector dims, std::string type) { auto res = std::make_shared<EltwiseLayer>(LayerParams {name, "Eltwise", prc}); res->params["operation"] = type; res->_operation = type == "sum" ? EltwiseLayer::Sum : EltwiseLayer::Prod; res->insData.resize(2); res->outData.resize(1); auto out_data = DataPtr(new Data(name, TensorDesc {prc, dims, TensorDesc::getLayoutByDims(dims)})); getCreatorLayer(out_data) = res; res->outData[0] = out_data; return res; } static std::shared_ptr<ReshapeLayer> _resh(std::string name, Precision prc, SizeVector dims) { auto res = std::make_shared<ReshapeLayer>(LayerParams {name, "Reshape", prc}); res->insData.resize(1); res->outData.resize(1); auto out_data = DataPtr(new Data(name, TensorDesc {prc, dims, TensorDesc::getLayoutByDims(dims)})); getCreatorLayer(out_data) = res; res->outData[0] = out_data; return res; } static std::shared_ptr<RNNCellBase> _cell(std::string name, Precision prc, SizeVector data_dims, SizeVector state_dims, RNNSequenceLayer::CellType type) { std::shared_ptr<RNNCellBase> res; size_t NS = 1; switch (type) { case RNNSequenceLayer::LSTM: res = std::make_shared<LSTMCell>(LayerParams {name, "LSTMCell", prc}); NS = 2; break; case RNNSequenceLayer::GRU: case RNNSequenceLayer::GRU_LBR: res = std::make_shared<GRUCell>(LayerParams {name, "GRUCell", prc}); break; case RNNSequenceLayer::RNN: res = std::make_shared<RNNCell>(LayerParams {name, "RNNCell", prc}); break; } res->cellType = type; res->insData.resize(1 + NS); res->outData.resize(NS); auto out_data = DataPtr(new Data(name + ":out_data", TensorDesc {prc, data_dims, TensorDesc::getLayoutByDims(data_dims)})); getCreatorLayer(out_data) = res; res->outData[0] = out_data; for (size_t i = 0; i < NS; i++) { auto out_state = DataPtr(new Data(name + ":out_state_" + std::to_string(i), TensorDesc {prc, state_dims, TensorDesc::getLayoutByDims(state_dims)})); getCreatorLayer(out_state) = res; res->outData[i] = out_state; } return res; } static std::shared_ptr<TensorIterator> _ti(std::string name, Precision prc, size_t NS) { auto res = std::make_shared<TensorIterator>(LayerParams {name, "TensorIterator", prc}); res->insData.resize(1 + NS); res->outData.resize(1 + NS); return res; } static void _link(CNNLayerPtr src, CNNLayerPtr dst, size_t src_port = 0, size_t dst_port = 0) { auto data = src->outData[src_port]; getInputTo(data)[dst->name] = dst; dst->insData[dst_port] = data; } static void _link(DataPtr& data, CNNLayerPtr dst, size_t dst_port = 0) { getInputTo(data)[dst->name] = dst; dst->insData[dst_port] = data; } /** Link nodes with clipping data if required (clip_val != 0.0) */ static void _link_with_clip(CNNLayerPtr src, CNNLayerPtr dst, const float clip_val, size_t src_port = 0, size_t dst_port = 0) { if (clip_val == 0.0f) { _link(src, dst, src_port, dst_port); } else { auto clip_name = dst->name + "_clip"; auto clip_prc = dst->precision; auto clip_shape = src->outData[src_port]->getTensorDesc().getDims(); auto clip = _act(clip_name, clip_prc, clip_shape, "clamp"); clip->params["min"] = CNNLayer::ie_serialize_float(-clip_val); clip->params["max"] = CNNLayer::ie_serialize_float(clip_val); clip->min_value = -clip_val; clip->max_value = clip_val; _link(src, clip, src_port, 0); _link(clip, dst, 0, dst_port); } } static Blob::Ptr wrap_as_tensor(Blob::Ptr src, SizeVector dims) { auto res = make_blob_with_precision( TensorDesc {src->getTensorDesc().getPrecision(), dims, TensorDesc::getLayoutByDims(dims)}, src->buffer()); IE_ASSERT(src->size() == res->size()); return res; } static Blob::Ptr make_region_copy(Blob::Ptr src, SizeVector region, SizeVector offset) { IE_ASSERT(region.size() == offset.size()); IE_ASSERT(region.size() == src->getTensorDesc().getDims().size()); auto res = make_plain_blob(src->getTensorDesc().getPrecision(), region); res->allocate(); size_t elem_size = src->getTensorDesc().getPrecision().size(); auto src_ptr = src->buffer().as<uint8_t*>(); auto dst_ptr = res->buffer().as<uint8_t*>(); auto& dd = src->getTensorDesc().getDims(); SizeVector src_dims {1, 1, 1}; std::copy(dd.begin(), dd.end(), src_dims.end() - dd.size()); SizeVector dims {1, 1, 1}; std::copy(region.begin(), region.end(), dims.end() - region.size()); SizeVector off {0, 0, 0}; std::copy(offset.begin(), offset.end(), off.end() - offset.size()); const auto D1 = dims[0]; const auto D2 = dims[1]; const auto D3 = dims[2]; const auto off1 = off[0]; const auto off2 = off[1]; const auto off3 = off[2]; const auto str1 = src_dims[1] * src_dims[2]; const auto str2 = src_dims[2]; for (size_t d1 = 0; d1 < D1; d1++) for (size_t d2 = 0; d2 < D2; d2++) { auto off_src = (off1 + d1) * str1 + (off2 + d2) * str2 + off3; auto off_dst = d1 * D2 * D3 + d2 * D3; ie_memcpy(dst_ptr + off_dst * elem_size, res->byteSize(), src_ptr + off_src * elem_size, D3 * elem_size); } return res; } static bool unrollRNNCellBody(CNNLayerPtr cur) { if (cur->type != "RNNCell") return true; auto cell = std::dynamic_pointer_cast<RNNCellBase>(cur); IE_ASSERT(cell) << "Cannot cast object with type ***Cell to WeightableLayer object"; auto name = cell->name; auto in_data = cell->insData[0].lock(); auto in_h_state = cell->insData[1].lock(); auto out_h_state = cell->outData[0]; auto d_dims = in_data->getTensorDesc().getDims(); auto s_dims = in_h_state->getTensorDesc().getDims(); size_t N = d_dims[0]; size_t D = d_dims[1]; size_t S = s_dims[1]; auto prc = cell->precision; /** Release links on TI */ for (auto& ins : cell->insData) getInputTo(ins.lock()).erase(cell->name); for (auto& outs : cell->outData) getCreatorLayer(outs).reset(); // operations auto concat = _concat(name + ":concat", prc, {N, D + S}, 2); auto fc = _fc(name + ":fc", prc, {N, S}, cell->_weights, cell->_biases); auto act = _act(name + ":act", prc, {N, S}, cell->activations[0]); // Connection _link(in_data, concat, 0); _link(in_h_state, concat, 1); _link(concat, fc); _link_with_clip(fc, act, cell->clip); // Output act->outData[0] = out_h_state; getCreatorLayer(out_h_state) = act; return true; } static bool unrollLSTMCellBody(CNNLayerPtr cur) { if (cur->type != "LSTMCell") return true; auto cell = std::dynamic_pointer_cast<RNNCellBase>(cur); IE_ASSERT(cell) << "Cannot cast object with type ***Cell to WeightableLayer object"; auto name = cell->name; auto in_data = cell->insData[0].lock(); auto in_h_state = cell->insData[1].lock(); auto in_c_state = cell->insData[2].lock(); auto out_h_state = cell->outData[0]; auto out_c_state = cell->outData[1]; auto d_dims = in_data->getTensorDesc().getDims(); auto s_dims = in_h_state->getTensorDesc().getDims(); size_t N = d_dims[0]; size_t D = d_dims[1]; size_t S = s_dims[1]; size_t G = 4; auto prc = cell->precision; /** Release links on TI */ for (auto& ins : cell->insData) getInputTo(ins.lock()).erase(cell->name); for (auto& outs : cell->outData) getCreatorLayer(outs).reset(); // operations auto concat = _concat(name + ":concat", prc, {N, D + S}, 2); auto split = _split(name + ":split", prc, {N, S}, G); auto fc = _fc(name + ":fc", prc, {N, S * G}, cell->_weights, cell->_biases); const std::string _f = cell->activations[0], _g = cell->activations[1], _h = cell->activations[2]; auto act_f = _act(name + ":act_f", prc, {N, S}, _f); auto act_i = _act(name + ":act_i", prc, {N, S}, _f); auto act_c = _act(name + ":act_c", prc, {N, S}, _g); auto act_o = _act(name + ":act_o", prc, {N, S}, _f); auto act_x = _act(name + ":act_x", prc, {N, S}, _h); auto mul_ic = _eltw(name + ":mul_ic", prc, {N, S}, "mul"); auto mul_f = _eltw(name + ":mul_f", prc, {N, S}, "mul"); auto sum = _eltw(name + ":sum", prc, {N, S}, "sum"); auto mul = _eltw(name + ":mul", prc, {N, S}, "mul"); // Connection _link(in_data, concat, 0); _link(in_h_state, concat, 1); _link(concat, fc); _link_with_clip(fc, split, cell->clip); _link(split, act_f, 0, 0); _link(split, act_i, 1, 0); _link(split, act_c, 2, 0); _link(split, act_o, 3, 0); _link(act_i, mul_ic, 0, 0); _link(act_c, mul_ic, 0, 1); _link(act_f, mul_f, 0, 0); _link(in_c_state, mul_f, 1); _link(mul_f, sum, 0, 0); _link(mul_ic, sum, 0, 1); _link(sum, act_x); _link(act_x, mul, 0, 0); _link(act_o, mul, 0, 1); // Output mul->outData[0] = out_h_state; getCreatorLayer(out_h_state) = mul; CombineData(out_c_state, sum->outData[0]); sum->outData[0] = out_c_state; getCreatorLayer(out_c_state) = sum; return true; } static bool unrollGRUCellBody(CNNLayerPtr cur, bool linear_before_reset = false) { if (cur->type != "GRUCell") return true; auto cell = std::dynamic_pointer_cast<GRUCell>(cur); IE_ASSERT(cell) << "Cannot cast object with type ***Cell to WeightableLayer object"; auto name = cell->name; auto in_data = cell->insData[0].lock(); auto in_h_state = cell->insData[1].lock(); auto out_h_state = cell->outData[0]; auto d_dims = in_data->getTensorDesc().getDims(); auto s_dims = in_h_state->getTensorDesc().getDims(); size_t N = d_dims[0]; size_t D = d_dims[1]; size_t S = s_dims[1]; // Split weights UR and O gates. Original gates are URO size_t bG = linear_before_reset ? 4 : 3; auto orig_W = wrap_as_tensor(cell->_weights, {3, S, D + S}); auto orig_B = wrap_as_tensor(cell->_biases, {bG, S}); auto ur_W = make_region_copy(orig_W, {2, S, D + S}, {0, 0, 0}); auto o_W = make_region_copy(orig_W, {1, S, D + S}, {2, 0, 0}); auto ur_B = make_region_copy(orig_B, {2, S}, {0, 0}); auto o_B = make_region_copy(orig_B, {1, S}, {2, 0}); auto prc = cell->precision; /** Release links on TI */ for (auto& ins : cell->insData) getInputTo(ins.lock()).erase(cell->name); for (auto& outs : cell->outData) getCreatorLayer(outs).reset(); // operations auto concat = _concat(name + ":concat", prc, {N, D + S}, 2); auto split = _split(name + ":split", prc, {N, S}, 2); auto fc_ur = _fc(name + ":fc_ur", prc, {N, S * 2}, ur_W, ur_B); const std::string _f = cell->activations[0], _g = cell->activations[1]; auto act_ur = _act(name + ":act_ur", prc, {N, 2 * S}, _f); auto act_o = _act(name + ":act_o", prc, {N, S}, _g); auto mul_u = _eltw(name + ":mul_u", prc, {N, S}, "mul"); auto mul_r = _eltw(name + ":mul_r", prc, {N, S}, "mul"); auto pwr_m1 = _pwr(name + ":pwr", prc, {N, S}, -1.0, 1.0); auto mul = _eltw(name + ":mul", prc, {N, S}, "mul"); auto sum = _eltw(name + ":sum", prc, {N, S}, "sum"); /** * - zt = _f(Wz*[Xt + Ht-1] + Bz) * - rt = _f(Wr*[Xt + Ht-1] + Br) * - ht = _g(Wh*[Xt + (rt (.) Ht-1)] + Bh) # default, when linear_before_reset = 0 * - ht = _g(Whw*Xt + Bhw + (rt (.) (Whr*Ht-1 + Bhr))) # when linear_before_reset != 0 * - Ht = (1 - zt) (.) ht + zt (.) Ht-1 */ _link(in_data, concat, 0); _link(in_h_state, concat, 1); _link(concat, fc_ur); _link_with_clip(fc_ur, act_ur, cell->clip); _link(act_ur, split); // split[0] - zt, split[1] - rt if (linear_before_reset) { auto lbr_B = wrap_as_tensor(orig_B, {4, S}); auto whw_W = make_region_copy(o_W, {1, S, D}, {0, 0, 0}); auto whr_W = make_region_copy(o_W, {1, S, S}, {0, 0, D}); auto whw_B = make_region_copy(lbr_B, {1, S}, {2, 0}); auto whr_B = make_region_copy(lbr_B, {1, S}, {3, 0}); auto fc_whr = _fc(name + ":fc_whr", prc, {N, S}, whr_W, whr_B); auto fc_whw = _fc(name + ":fc_whw", prc, {N, S}, whw_W, whw_B); auto sum_h = _eltw(name + ":sum_h", prc, {N, S}, "sum"); _link(in_h_state, fc_whr); // Whr*Ht-1 + Bhr _link(fc_whr, mul_r, 0); // _link(split, mul_r, 1, 1); // rt (.) (Whr*Ht-1 + Bhr) _link(in_data, fc_whw); // Whw*Xt + Bhw _link(fc_whw, sum_h, 0, 0); // _link(mul_r, sum_h, 0, 1); // Whw*Xt + Bhw + (rt (.) (Whr*Ht-1 + Bhr)) _link_with_clip(sum_h, act_o, cell->clip); // _g(Whw*Xt + Bhw + (rt (.) (Whr*Ht-1 + Bhr))) } else { auto fc_wh = _fc(name + ":fc_o", prc, {N, S}, o_W, o_B); auto concat_h = _concat(name + ":concat_h", prc, {N, D + S}, 2); _link(split, mul_r, 1, 0); // _link(in_h_state, mul_r, 1); // rt (.) Ht-1 _link(in_data, concat_h, 0); // _link(mul_r, concat_h, 0, 1); // [Xt + (rt (.) Ht-1)] _link(concat_h, fc_wh); // Wh*[Xt + (rt (.) Ht-1)] + Bh _link_with_clip(fc_wh, act_o, cell->clip); // _g(Wh*[Xt + (rt (.) Ht-1)] + Bh) } _link(split, pwr_m1, 0, 0); // 1 - zt _link(act_o, mul, 0, 0); // _link(pwr_m1, mul, 0, 1); // (1 - zt) (.) ht _link(split, mul_u, 0, 0); // _link(in_h_state, mul_u, 1); // zt (.) Ht-1 _link(mul, sum, 0, 0); // _link(mul_u, sum, 0, 1); // (1 - zt) (.) ht + zt (.) Ht-1 // Output sum->outData[0] = out_h_state; getCreatorLayer(out_h_state) = sum; return true; } static bool unrollCell(CNNLayerPtr cur) { auto cell = std::dynamic_pointer_cast<RNNCellBase>(cur); switch (cell->cellType) { case RNNCellBase::LSTM: return unrollLSTMCellBody(cur); case RNNCellBase::GRU: return unrollGRUCellBody(cur); case RNNCellBase::GRU_LBR: return unrollGRUCellBody(cur, true); case RNNCellBase::RNN: return unrollRNNCellBody(cur); } return false; } static bool unrollSeq(CNNLayerPtr cur) { if (!one_of(cur->type, "LSTMSequence", "GRUSequence", "RNNSequence")) return true; auto seq = std::dynamic_pointer_cast<RNNSequenceLayer>(cur); IE_ASSERT(seq) << "Cannot cast object with type ***Sequence to RNNSequenceLayer object"; auto name = seq->name; auto in_data = seq->insData[0].lock(); auto in_h_state = seq->insData[1].lock(); auto out_data = seq->outData[0]; auto in_d_dims = in_data->getTensorDesc().getDims(); auto state_dims = in_h_state->getTensorDesc().getDims(); auto out_d_dims = out_data->getTensorDesc().getDims(); const int axis = seq->axis; const auto direct = seq->direction; const auto prc = seq->precision; /** Release links on Seq */ for (auto& ins : seq->insData) getInputTo(ins.lock()).erase(seq->name); for (auto& outs : seq->outData) getCreatorLayer(outs).reset(); /** Body subgraph*/ auto in_d_body_dims = in_d_dims; in_d_body_dims[axis] = 1; auto in_d_body_squeeze_dims = in_d_dims; in_d_body_squeeze_dims.erase(in_d_body_squeeze_dims.begin() + axis); auto out_d_body_dims = out_d_dims; out_d_body_dims[axis] = 1; auto out_d_body_squeeze_dims = out_d_dims; out_d_body_squeeze_dims.erase(out_d_body_squeeze_dims.begin() + axis); auto body_in_data = DataPtr( new Data(name + ":data_in", TensorDesc {prc, in_d_body_dims, TensorDesc::getLayoutByDims(in_d_body_dims)})); auto resh1 = _resh(name + ":resh1", prc, in_d_body_squeeze_dims); auto cell = _cell(name + ":cell", prc, out_d_body_squeeze_dims, state_dims, seq->cellType); auto resh2 = _resh(name + ":resh2", prc, out_d_body_dims); _link(body_in_data, resh1); _link(resh1, cell); _link(cell, resh2); cell->_weights = seq->_weights; cell->_biases = seq->_biases; cell->blobs["weights"] = cell->_weights; cell->blobs["biases"] = cell->_biases; cell->hidden_size = seq->hidden_size; cell->clip = seq->clip; cell->activations = seq->activations; cell->activation_alpha = seq->activation_alpha; cell->activation_beta = seq->activation_beta; const size_t NS = cell->outData.size(); // num of state /** TI layer */ auto ti = _ti(name + ":ti", prc, NS); _link(in_data, ti, 0); ti->outData[0] = out_data; getCreatorLayer(out_data) = ti; ti->body.inputs.push_back(body_in_data); ti->body.outputs.push_back(resh2->outData[0]); int start = direct == RNNSequenceLayer::FWD ? 0 : -1; int end = direct == RNNSequenceLayer::FWD ? -1 : 0; int step = direct == RNNSequenceLayer::FWD ? 1 : -1; ti->input_port_map.push_back({0, 0, axis, step, start, end, 1}); ti->output_port_map.push_back({0, 0, axis, step, start, end, 1}); for (size_t i = 0; i < NS; i++) { auto in_state = seq->insData[1 + i].lock(); _link(in_state, ti, 1 + i); auto out_state = seq->outData[1 + i]; ti->outData[1 + i] = out_state; getCreatorLayer(out_state) = ti; auto body_in_state = DataPtr(new Data(name + ":state_in_" + std::to_string(i), TensorDesc {prc, state_dims, TensorDesc::getLayoutByDims(state_dims)})); _link(body_in_state, cell, 1 + i); ti->body.inputs.push_back(body_in_state); ti->body.outputs.push_back(cell->outData[i]); const int ii = 1 + static_cast<int>(i); ti->input_port_map.push_back({ii, ii, -1, 0, 0, 0, 0}); ti->output_port_map.push_back({ii, ii, -1, 0, 0, 0, 0}); ti->back_edges.push_back({ii, ii, -1, 0, 0, 0, 0}); } return true; } /************************************************************/ /**** Converter API ***************************************/ /************************************************************/ template <typename N> std::vector<CNNLayerPtr> TopolSort(const N& net); template <> std::vector<CNNLayerPtr> TopolSort(const ICNNNetwork& net) { return details::CNNNetSortTopologically(net); } template <> std::vector<CNNLayerPtr> TopolSort(const TensorIterator::Body& net) { return details::CNNSubnetSortTopologically({net.inputs, net.outputs}); } template <> std::vector<CNNLayerPtr> TopolSort(const details::CNNSubnet& net) { return details::CNNSubnetSortTopologically(net); } void restore_net_consistency(ICNNNetwork& net) { auto inet = dynamic_cast<details::CNNNetworkImpl*>(&net); IE_ASSERT(inet != nullptr); // At first all layers should be available via findByName() api. // In other words all layers should be present in internal map<name, layer> IE_SUPPRESS_DEPRECATED_START for (auto& l : TopolSort(net)) { inet->addLayer(l); } IE_SUPPRESS_DEPRECATED_END } template <typename N, typename T> bool ApplyForAll(N& net, T action) { auto all_layers = TopolSort(net); bool sts = true; for (auto& layer : all_layers) sts &= action(layer, net); return sts; } template <typename N, typename T, typename P> bool ApplyForAll_if(N& net, T action, P pred) { auto all_layers = TopolSort(net); bool sts = true; for (auto& layer : all_layers) if (pred(layer)) sts &= action(layer); return sts; } bool CombineRNNSeq(ICNNNetwork& net) { auto res = ApplyForAll(net, convertToRNNSeq<ICNNNetwork>); restore_net_consistency(net); return res; } bool CombineRNNSeq(TensorIterator::Body& net) { return ApplyForAll(net, convertToRNNSeq<TensorIterator::Body>); } bool UnrollTI(ICNNNetwork& net) { auto res = ApplyForAll(net, unrollTI); restore_net_consistency(net); return res; } template <typename NET> bool UnrollRNN_if_impl(NET& net, const std::function<bool(const RNNCellBase&)> pred) { // Filter layers by RNN specific type auto _seq_pred = [&](CNNLayerPtr layer) { auto rnn = std::dynamic_pointer_cast<RNNSequenceLayer>(layer); if (!rnn) return false; return pred(*rnn.get()); }; auto _cell_pred = [&](CNNLayerPtr layer) { auto rnn = std::dynamic_pointer_cast<RNNCellBase>(layer); if (!rnn || !one_of(rnn->type, "LSTMCell", "GRUCell", "RNNCell")) return false; return pred(*rnn.get()); }; bool res = true; res &= ApplyForAll_if(net, unrollSeq, _seq_pred); res &= ApplyForAll_if(net, unrollCell, _cell_pred); return res; } bool UnrollRNN_if(ICNNNetwork& net, const std::function<bool(const RNNCellBase&)> pred) { auto res = UnrollRNN_if_impl(net, pred); restore_net_consistency(net); return res; } bool UnrollRNN_if(TensorIterator::Body& net, const std::function<bool(const RNNCellBase&)> pred) { return UnrollRNN_if_impl(net, pred); } /** * =========================== * Precision conversion passes * =========================== */ namespace { template <Precision::ePrecision PREC_FROM, Precision::ePrecision PREC_TO> void convertArrayPrecision(typename PrecisionTrait<PREC_TO>::value_type* dst, const typename PrecisionTrait<PREC_FROM>::value_type* src, size_t nelem) { using dst_type = typename PrecisionTrait<PREC_TO>::value_type; for (size_t i = 0; i < nelem; i++) { dst[i] = PrecisionUtils::saturate_cast<dst_type>(src[i]); } } template <> void convertArrayPrecision<Precision::FP16, Precision::FP32>(float* dst, const short* src, size_t nelem) { PrecisionUtils::f16tof32Arrays(dst, src, nelem, 1.0f, 0.0f); } template <Precision::ePrecision PREC_FROM, Precision::ePrecision PREC_TO> Blob::Ptr convertBlobPrecision(const Blob::Ptr& blob) { using from_d_type = typename PrecisionTrait<PREC_FROM>::value_type; using to_d_type = typename PrecisionTrait<PREC_TO>::value_type; auto tensor_desc = blob->getTensorDesc(); Blob::Ptr new_blob = make_shared_blob<to_d_type>(TensorDesc {PREC_TO, tensor_desc.getDims(), tensor_desc.getLayout()}); new_blob->allocate(); auto target = new_blob->buffer().as<to_d_type*>(); auto source = blob->buffer().as<from_d_type*>(); convertArrayPrecision<PREC_FROM, PREC_TO>(target, source, blob->size()); return new_blob; } // forward declaration to use in convertLayerPrecision<>() template <Precision::ePrecision PREC_FROM, Precision::ePrecision PREC_TO, typename NET> void convertPrecisionForAll(NET &net); template <Precision::ePrecision PREC_FROM, Precision::ePrecision PREC_TO> void convertLayerPrecision(const CNNLayerPtr& layer) { for (auto &out_data : layer->outData) { if (PREC_FROM == out_data->getPrecision()) out_data->setPrecision(PREC_TO); } for (auto &in_data : layer->insData) { if (PREC_FROM == in_data.lock()->getPrecision()) in_data.lock()->setPrecision(PREC_TO); } if (layer->precision == PREC_FROM) layer->precision = PREC_TO; if (HasInternalSubnet(layer)) { // apply the same conversion pass for internal graph auto layer_subnet = GetInternalSubnet(layer); convertPrecisionForAll<PREC_FROM, PREC_TO>(layer_subnet); } auto wLayer = dynamic_cast<InferenceEngine::WeightableLayer *>(layer.get()); if (wLayer) { if (wLayer->_weights && wLayer->_weights->getTensorDesc().getPrecision() == PREC_FROM) { wLayer->_weights = convertBlobPrecision<PREC_FROM, PREC_TO>(wLayer->_weights); } if (wLayer->_biases && wLayer->_biases->getTensorDesc().getPrecision() == PREC_FROM) { wLayer->_biases = convertBlobPrecision<PREC_FROM, PREC_TO>(wLayer->_biases); } } for (auto &blob : layer->blobs) { auto &data = blob.second; if (nullptr != data) { if (data->getTensorDesc().getPrecision() == PREC_FROM) { data = convertBlobPrecision<PREC_FROM, PREC_TO>(data); } } } } template <typename NET> void fixConvertLayers(NET &net) { std::vector<CNNLayerPtr> to_remove; auto all_layers = TopolSort(net); for (auto &layer : all_layers) { if (layer->type == "Convert") { auto out_precision = layer->outData[0]->getPrecision(); auto in_precision = layer->input()->getPrecision(); // Restore destination_type attribute after conversion auto found = layer->params.find("precision"); IE_ASSERT(found != layer->params.end()); found->second = out_precision.name(); // Remove convert layer if it do nothing. After type conversion pass // some convert layers may lose actuality. if (in_precision == out_precision) { to_remove.push_back(layer); } } } for (auto &layer : to_remove) { RemoveLayer(layer, net); } } template <Precision::ePrecision PREC_FROM, Precision::ePrecision PREC_TO, typename NET> void convertPrecisionForAll(NET &net) { auto all_layers = TopolSort(net); for (auto &layer : all_layers) { convertLayerPrecision<PREC_FROM, PREC_TO>(layer); } fixConvertLayers(net); } } // namespace bool HasInternalSubnet(const CNNLayerPtr &layer) { return layer->type == "TensorIterator" && dynamic_cast<TensorIterator*>(layer.get()) != nullptr; } details::CNNSubnet GetInternalSubnet(const CNNLayerPtr &layer) { if (layer->type == "TensorIterator") { auto ti = static_cast<TensorIterator*>(layer.get()); IE_ASSERT(ti); return {ti->body.inputs, ti->body.outputs}; } return {}; } void ConvertPrecision(ICNNNetwork& net, Precision from, Precision to) { OV_ITT_SCOPED_TASK(itt::domains::IELegacy, "NetPass::ConvertPrecision"); auto compare = getPrecisionMask(from, to); switch (compare) { case getPrecisionMask(Precision::U32, Precision::I32): convertPrecisionForAll<Precision::U32, Precision::I32>(net); break; case getPrecisionMask(Precision::U64, Precision::I32): convertPrecisionForAll<Precision::U64, Precision::I32>(net); break; case getPrecisionMask(Precision::I64, Precision::I32): convertPrecisionForAll<Precision::I64, Precision::I32>(net); break; case getPrecisionMask(Precision::BOOL, Precision::U8): convertPrecisionForAll<Precision::BOOL, Precision::U8>(net); break; case getPrecisionMask(Precision::BOOL, Precision::I32): convertPrecisionForAll<Precision::BOOL, Precision::I32>(net); break; case getPrecisionMask(Precision::FP16, Precision::FP32): convertPrecisionForAll<Precision::FP16, Precision::FP32>(net); break; case getPrecisionMask(Precision::U8, Precision::I32): convertPrecisionForAll<Precision::U8, Precision::I32>(net); break; case getPrecisionMask(Precision::U16, Precision::I32): convertPrecisionForAll<Precision::U16, Precision::I32>(net); break; default: THROW_IE_EXCEPTION << "Precision conversion from " << from << " to " << to << " currently is not supported. You may expand precision" " conversion pass."; } } void ConvertIOPrecision(ICNNNetwork& net, Precision from, Precision to) { InputsDataMap inputDataMap; net.getInputsInfo(inputDataMap); for (auto & i : inputDataMap) { if (i.second->getPrecision() == from) { i.second->setPrecision(to); } } OutputsDataMap outputDataMap; net.getOutputsInfo(outputDataMap); for (auto & i : outputDataMap) { if (i.second->getPrecision() == from) { i.second->setPrecision(to); } } } } // namespace NetPass } // namespace InferenceEngine
35.449669
123
0.61292
[ "object", "shape", "vector" ]
c8938b45e5bb2958ed66b8299305541213269ea8
17,794
cxx
C++
Common/DataModel/vtkAMRUtilities.cxx
LongerVisionUSA/VTK
1170774b6611c71b95c28bb821d51c2c18ff091f
[ "BSD-3-Clause" ]
null
null
null
Common/DataModel/vtkAMRUtilities.cxx
LongerVisionUSA/VTK
1170774b6611c71b95c28bb821d51c2c18ff091f
[ "BSD-3-Clause" ]
null
null
null
Common/DataModel/vtkAMRUtilities.cxx
LongerVisionUSA/VTK
1170774b6611c71b95c28bb821d51c2c18ff091f
[ "BSD-3-Clause" ]
null
null
null
/*========================================================================= Program: Visualization Toolkit Module: vtkAMRUtilities.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkAMRUtilities.h" #include "vtkAMRBox.h" #include "vtkAMRInformation.h" #include "vtkCellData.h" #include "vtkCompositeDataIterator.h" #include "vtkDataArray.h" #include "vtkFieldData.h" #include "vtkOverlappingAMR.h" #include "vtkPointData.h" #include "vtkStructuredData.h" #include "vtkUniformGrid.h" #include "vtkUnsignedCharArray.h" #include <cassert> #include <cmath> #include <limits> #define IMIN(ext) ext[0] #define IMAX(ext) ext[1] #define JMIN(ext) ext[2] #define JMAX(ext) ext[3] #define KMIN(ext) ext[4] #define KMAX(ext) ext[5] //------------------------------------------------------------------------------ void vtkAMRUtilities::PrintSelf(std::ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); } //------------------------------------------------------------------------------ bool vtkAMRUtilities::HasPartiallyOverlappingGhostCells(vtkOverlappingAMR* amr) { assert("pre: input AMR data is nullptr" && (amr != nullptr)); int numLevels = static_cast<int>(amr->GetNumberOfLevels()); int levelIdx = numLevels - 1; for (; levelIdx > 0; --levelIdx) { int r = amr->GetRefinementRatio(levelIdx); unsigned int numDataSets = amr->GetNumberOfDataSets(levelIdx); for (unsigned int dataIdx = 0; dataIdx < numDataSets; ++dataIdx) { const vtkAMRBox& myBox = amr->GetAMRInfo()->GetAMRBox(levelIdx, dataIdx); const int* lo = myBox.GetLoCorner(); int hi[3]; myBox.GetValidHiCorner(hi); vtkAMRBox coarsenedBox = myBox; coarsenedBox.Coarsen(r); // Detecting partially overlapping boxes is based on the following: // Cell location k at level L-1 holds the range [k*r,k*r+(r-1)] of // level L, where r is the refinement ratio. Consequently, if the // min extent of the box is greater than k*r or if the max extent // of the box is less than k*r+(r-1), then the grid partially overlaps. for (int i = 0; i < 3; ++i) { if (myBox.EmptyDimension(i)) { continue; } int minRange[2]; minRange[0] = coarsenedBox.GetLoCorner()[i] * r; minRange[1] = coarsenedBox.GetLoCorner()[i] * r + (r - 1); if (lo[i] > minRange[0]) { return true; } int coarseHi[3]; coarsenedBox.GetValidHiCorner(coarseHi); int maxRange[2]; maxRange[0] = coarseHi[i] * r; maxRange[1] = coarseHi[i] * r + (r - 1); if (hi[i] < maxRange[1]) { return true; } } // END for all dimensions } // END for all data at the current level } // END for all levels return false; } //------------------------------------------------------------------------------ void vtkAMRUtilities::CopyFieldData( vtkFieldData* target, vtkIdType targetIdx, vtkFieldData* source, vtkIdType sourceIdx) { assert("pre: target should not be nullptr" && (target != nullptr)); assert("pre: source should not be nullptr" && (source != nullptr)); assert("pre: number of arrays between source and target does not match!" && (source->GetNumberOfArrays() == target->GetNumberOfArrays())); for (int arrayIdx = 0; arrayIdx < source->GetNumberOfArrays(); ++arrayIdx) { vtkDataArray* targetArray = target->GetArray(arrayIdx); vtkDataArray* srcArray = source->GetArray(arrayIdx); assert("pre: target array is nullptr!" && (targetArray != nullptr)); assert("pre: source array is nullptr!" && (srcArray != nullptr)); assert("pre: target/source array number of components mismatch!" && (targetArray->GetNumberOfComponents() == srcArray->GetNumberOfComponents())); assert("pre: target/source array names mismatch!" && (strcmp(targetArray->GetName(), srcArray->GetName()) == 0)); assert("pre: source index is out-of-bounds" && (sourceIdx >= 0) && (sourceIdx < srcArray->GetNumberOfTuples())); assert("pre: target index is out-of-bounds" && (targetIdx >= 0) && (targetIdx < targetArray->GetNumberOfTuples())); // copy the tuple from the source array targetArray->SetTuple(targetIdx, sourceIdx, srcArray); } // END for all arrays } //------------------------------------------------------------------------------ void vtkAMRUtilities::CopyFieldsWithinRealExtent( int realExtent[6], vtkUniformGrid* ghostedGrid, vtkUniformGrid* strippedGrid) { assert("pre: input ghost grid is nullptr" && (ghostedGrid != nullptr)); assert("pre: input stripped grid is nullptr" && (strippedGrid != nullptr)); // STEP 0: Initialize the unghosted grid fields (point/cell data) strippedGrid->GetPointData()->CopyAllOn(); strippedGrid->GetPointData()->CopyAllocate( ghostedGrid->GetPointData(), strippedGrid->GetNumberOfPoints()); strippedGrid->GetCellData()->CopyAllOn(); strippedGrid->GetCellData()->CopyAllocate( ghostedGrid->GetCellData(), strippedGrid->GetNumberOfCells()); // STEP 1: Ensure each array has the right number of tuples, for some reason // CopyAllocate does not allocate the arrays with the prescribed size. int arrayIdx = 0; for (; arrayIdx < strippedGrid->GetPointData()->GetNumberOfArrays(); ++arrayIdx) { strippedGrid->GetPointData()->GetArray(arrayIdx)->SetNumberOfTuples( strippedGrid->GetNumberOfPoints()); } // END for all node arrays for (; arrayIdx < strippedGrid->GetCellData()->GetNumberOfArrays(); ++arrayIdx) { strippedGrid->GetCellData()->GetArray(arrayIdx)->SetNumberOfTuples( strippedGrid->GetNumberOfCells()); } // END for all cell arrays // STEP 2: Get the data-description int dataDescription = vtkStructuredData::GetDataDescriptionFromExtent(realExtent); // NOTE: a mismatch in the description here is possible but, very unlikely. // For example, consider a grid on the XY-PLANE that is padded with ghost // nodes along the z-dimension. Consequently, the ghosted grid will have // a 3-D data-description and the unghosted grid will be 2-D. Again, although // possible, this is not a realistic use-case. We will just catch this error // here and fix if we ever come across such use-case. assert("pre: description of ghosted and non-ghosted grid mismatch!" && (dataDescription == vtkStructuredData::GetDataDescription(ghostedGrid->GetDimensions()))); // STEP 3: Get the corresponding cell-extent for accessing cell fields int realCellExtent[6]; vtkStructuredData::GetCellExtentFromPointExtent(realExtent, realCellExtent, dataDescription); // STEP 4: Loop through all real nodes/cells and copy the fields onto the // stripped grid. int ijk[3]; int lijk[3]; for (int i = IMIN(realExtent); i <= IMAX(realExtent); ++i) { for (int j = JMIN(realExtent); j <= JMAX(realExtent); ++j) { for (int k = KMIN(realExtent); k <= KMAX(realExtent); ++k) { // Vectorize i,j,k ijk[0] = i; ijk[1] = j; ijk[2] = k; // Compute the local i,j,k on the un-ghosted grid vtkStructuredData::GetLocalStructuredCoordinates(ijk, realExtent, lijk, dataDescription); // Compute the source index w.r.t. the ghosted grid dimensions vtkIdType sourceIdx = vtkStructuredData::ComputePointId(ghostedGrid->GetDimensions(), ijk, dataDescription); // Compute the target index w.r.t the real extent vtkIdType targetIdx = vtkStructuredData::ComputePointIdForExtent(realExtent, ijk, dataDescription); // Copy node-centered data vtkAMRUtilities::CopyFieldData( strippedGrid->GetPointData(), targetIdx, ghostedGrid->GetPointData(), sourceIdx); // If within the cell-extent, copy cell-centered data if ((i >= IMIN(realCellExtent)) && (i <= IMAX(realCellExtent)) && (j >= JMIN(realCellExtent)) && (j <= JMAX(realCellExtent)) && (k >= KMIN(realCellExtent)) && (k <= KMAX(realCellExtent))) { // Compute the source cell index w.r.t. the ghosted grid vtkIdType sourceCellIdx = vtkStructuredData::ComputeCellId(ghostedGrid->GetDimensions(), ijk, dataDescription); // Compute the target cell index w.r.t. the un-ghosted grid vtkIdType targetCellIdx = vtkStructuredData::ComputeCellId(strippedGrid->GetDimensions(), lijk, dataDescription); // Copy cell-centered data vtkAMRUtilities::CopyFieldData( strippedGrid->GetCellData(), targetCellIdx, ghostedGrid->GetCellData(), sourceCellIdx); } // END if within the cell extent } // END for all k } // END for all j } // END for all i } //------------------------------------------------------------------------------ vtkUniformGrid* vtkAMRUtilities::StripGhostLayersFromGrid(vtkUniformGrid* grid, int ghost[6]) { assert("pre: input grid is nullptr" && (grid != nullptr)); // STEP 0: Get the grid properties, i.e., origin, dims, extent, etc. double origin[3]; double spacing[3]; int dims[3]; int ghostedGridDims[3]; grid->GetOrigin(origin); grid->GetSpacing(spacing); grid->GetDimensions(ghostedGridDims); grid->GetDimensions(dims); int copyExtent[6]; grid->GetExtent(copyExtent); // STEP 1: Adjust origin, copyExtent, dims according to the supplied ghost // vector. for (int i = 0; i < 3; ++i) { if (ghost[i * 2] > 0) { copyExtent[i * 2] += ghost[i * 2]; dims[i] -= ghost[i * 2]; origin[i] += ghost[i * 2] * spacing[i]; } if (ghost[i * 2 + 1] > 0) { dims[i] -= ghost[i * 2 + 1]; copyExtent[i * 2 + 1] -= ghost[i * 2 + 1]; } } // END for all dimensions // STEP 2: Initialize the unghosted grid vtkUniformGrid* myGrid = vtkUniformGrid::New(); myGrid->Initialize(); myGrid->SetOrigin(origin); myGrid->SetSpacing(spacing); myGrid->SetDimensions(dims); // STEP 3: Copy the field data within the real extent vtkAMRUtilities::CopyFieldsWithinRealExtent(copyExtent, grid, myGrid); return (myGrid); } //------------------------------------------------------------------------------ void vtkAMRUtilities::StripGhostLayers( vtkOverlappingAMR* ghostedAMRData, vtkOverlappingAMR* strippedAMRData) { assert("pre: input AMR data is nullptr" && (ghostedAMRData != nullptr)); assert("pre: outputAMR data is nullptr" && (strippedAMRData != nullptr)); double spacing[3]; if (!vtkAMRUtilities::HasPartiallyOverlappingGhostCells(ghostedAMRData)) { strippedAMRData->ShallowCopy(ghostedAMRData); return; } // TODO: At some point we should check for overlapping cells within the // same level, e.g., consider a level 0 with 2 abutting blocks that is // ghosted by N !!!! std::vector<int> blocksPerLevel(ghostedAMRData->GetNumberOfLevels()); for (unsigned int i = 0; i < blocksPerLevel.size(); i++) { blocksPerLevel[i] = ghostedAMRData->GetNumberOfDataSets(i); } strippedAMRData->Initialize(static_cast<int>(blocksPerLevel.size()), &blocksPerLevel[0]); strippedAMRData->SetOrigin(ghostedAMRData->GetOrigin()); strippedAMRData->SetGridDescription(ghostedAMRData->GetGridDescription()); ghostedAMRData->GetSpacing(0, spacing); strippedAMRData->SetSpacing(0, spacing); unsigned int dataIdx = 0; for (; dataIdx < ghostedAMRData->GetNumberOfDataSets(0); ++dataIdx) { vtkUniformGrid* grid = ghostedAMRData->GetDataSet(0, dataIdx); const vtkAMRBox& box = ghostedAMRData->GetAMRBox(0, dataIdx); strippedAMRData->SetAMRBox(0, dataIdx, box); strippedAMRData->SetDataSet(0, dataIdx, grid); } // END for all data at level 0 int ghost[6]; unsigned int levelIdx = 1; for (; levelIdx < ghostedAMRData->GetNumberOfLevels(); ++levelIdx) { dataIdx = 0; ghostedAMRData->GetSpacing(levelIdx, spacing); strippedAMRData->SetSpacing(levelIdx, spacing); for (; dataIdx < ghostedAMRData->GetNumberOfDataSets(levelIdx); ++dataIdx) { vtkUniformGrid* grid = ghostedAMRData->GetDataSet(levelIdx, dataIdx); int r = ghostedAMRData->GetRefinementRatio(levelIdx); vtkAMRBox myBox = ghostedAMRData->GetAMRBox(levelIdx, dataIdx); vtkAMRBox strippedBox = myBox; strippedBox.RemoveGhosts(r); strippedAMRData->SetAMRBox(levelIdx, dataIdx, strippedBox); if (grid != nullptr) { myBox.GetGhostVector(r, ghost); vtkUniformGrid* strippedGrid = vtkAMRUtilities::StripGhostLayersFromGrid(grid, ghost); assert(strippedBox == vtkAMRBox(strippedGrid->GetOrigin(), strippedGrid->GetDimensions(), strippedGrid->GetSpacing(), strippedAMRData->GetOrigin(), strippedGrid->GetGridDescription())); strippedAMRData->SetAMRBox(levelIdx, dataIdx, strippedBox); strippedAMRData->SetDataSet(levelIdx, dataIdx, strippedGrid); strippedGrid->Delete(); } } // END for all data at the given level } // END for all levels } //------------------------------------------------------------------------------ void vtkAMRUtilities::BlankCells(vtkOverlappingAMR* amr) { vtkAMRInformation* info = amr->GetAMRInfo(); if (!info->HasRefinementRatio()) { info->GenerateRefinementRatio(); } if (!info->HasChildrenInformation()) { info->GenerateParentChildInformation(); } std::vector<int> processorMap; processorMap.resize(amr->GetTotalNumberOfBlocks(), -1); vtkSmartPointer<vtkCompositeDataIterator> iter; iter.TakeReference(amr->NewIterator()); iter->SkipEmptyNodesOn(); for (iter->GoToFirstItem(); !iter->IsDoneWithTraversal(); iter->GoToNextItem()) { unsigned int index = iter->GetCurrentFlatIndex(); processorMap[index] = 0; } unsigned int numLevels = info->GetNumberOfLevels(); for (unsigned int i = 0; i < numLevels; i++) { BlankGridsAtLevel(amr, i, info->GetChildrenAtLevel(i), processorMap); } } //------------------------------------------------------------------------------ void vtkAMRUtilities::BlankGridsAtLevel(vtkOverlappingAMR* amr, int levelIdx, std::vector<std::vector<unsigned int>>& children, const std::vector<int>& processMap) { unsigned int numDataSets = amr->GetNumberOfDataSets(levelIdx); int N; for (unsigned int dataSetIdx = 0; dataSetIdx < numDataSets; dataSetIdx++) { const vtkAMRBox& box = amr->GetAMRBox(levelIdx, dataSetIdx); vtkUniformGrid* grid = amr->GetDataSet(levelIdx, dataSetIdx); if (grid == nullptr) { continue; } N = grid->GetNumberOfCells(); vtkUnsignedCharArray* ghosts = vtkUnsignedCharArray::New(); ghosts->SetNumberOfTuples(N); ghosts->FillComponent(0, 0); ghosts->SetName(vtkDataSetAttributes::GhostArrayName()); if (children.size() > dataSetIdx) { std::vector<unsigned int>& dsChildren = children[dataSetIdx]; std::vector<unsigned int>::iterator iter; // For each higher res box fill in the cells that // it covers for (iter = dsChildren.begin(); iter != dsChildren.end(); ++iter) { vtkAMRBox ibox; int childGridIndex = amr->GetCompositeIndex(levelIdx + 1, *iter); if (processMap[childGridIndex] < 0) { continue; } if (amr->GetAMRInfo()->GetCoarsenedAMRBox(levelIdx + 1, *iter, ibox)) { bool shouldBeTrue = ibox.Intersect(box); assert(shouldBeTrue); // if the boxes don't intersect, there is a bug (void)shouldBeTrue; // to avoid warning in release const int* loCorner = ibox.GetLoCorner(); int hi[3]; ibox.GetValidHiCorner(hi); for (int iz = loCorner[2]; iz <= hi[2]; iz++) { for (int iy = loCorner[1]; iy <= hi[1]; iy++) { for (int ix = loCorner[0]; ix <= hi[0]; ix++) { vtkIdType id = vtkAMRBox::GetCellLinearIndex(box, ix, iy, iz, grid->GetDimensions()); ghosts->SetValue(id, ghosts->GetValue(id) | vtkDataSetAttributes::REFINEDCELL); } // END for x } // END for y } // END for z } } // Processing all higher boxes for a specific coarse grid } if (grid->GetCellData()->HasArray(vtkDataSetAttributes::GhostArrayName())) { MergeGhostArrays( grid->GetCellData()->GetArray(vtkDataSetAttributes::GhostArrayName()), ghosts); } grid->GetCellData()->AddArray(ghosts); ghosts->Delete(); } } //------------------------------------------------------------------------------ void vtkAMRUtilities::MergeGhostArrays(vtkDataArray* existingArray, vtkUnsignedCharArray* ghosts) { vtkUnsignedCharArray* existingGhostArray = vtkUnsignedCharArray::SafeDownCast(existingArray); if (existingGhostArray != nullptr) { for (int valueIndex = 0; valueIndex < ghosts->GetNumberOfValues(); valueIndex++) { unsigned char ghostValue = ghosts->GetValue(valueIndex); unsigned char existingGhostValue = existingGhostArray->GetValue(valueIndex); // Clear the REFINEDCELL flag that is transient and not expected at this step. unsigned char filteredValue = existingGhostValue & ~vtkDataSetAttributes::REFINEDCELL; unsigned char mergedValue = ghostValue | filteredValue; ghosts->SetValue(valueIndex, mergedValue); } } }
38.102784
99
0.637631
[ "vector" ]
c89537fc0aed0a4fe8b2a44dd4fafd6567288dee
5,029
cpp
C++
VC2010Samples/MFC/WindowsTouch/TouchDemo/TouchDemo.cpp
alonmm/VCSamples
6aff0b4902f5027164d593540fcaa6601a0407c3
[ "MIT" ]
300
2019-05-09T05:32:33.000Z
2022-03-31T20:23:24.000Z
VC2010Samples/MFC/WindowsTouch/TouchDemo/TouchDemo.cpp
JaydenChou/VCSamples
9e1d4475555b76a17a3568369867f1d7b6cc6126
[ "MIT" ]
9
2016-09-19T18:44:26.000Z
2018-10-26T10:20:05.000Z
VC2010Samples/MFC/WindowsTouch/TouchDemo/TouchDemo.cpp
JaydenChou/VCSamples
9e1d4475555b76a17a3568369867f1d7b6cc6126
[ "MIT" ]
633
2019-05-08T07:34:12.000Z
2022-03-30T04:38:28.000Z
// This is a part of the Microsoft Foundation Classes C++ library. // Copyright (C) Microsoft Corporation // All rights reserved. // // This source code is only intended as a supplement to the // Microsoft Foundation Classes Reference and related // electronic documentation provided with the library. // See these sources for detailed information regarding the // Microsoft Foundation Classes product. // TouchDemo.cpp : Defines the class behaviors for the application. // #include "stdafx.h" #include "afxwinappex.h" #include "TouchDemo.h" #include "MainFrm.h" #include "TouchDemoDoc.h" #include "TouchDemoView.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CTouchDemoApp BEGIN_MESSAGE_MAP(CTouchDemoApp, CWinAppEx) ON_COMMAND(ID_APP_ABOUT, &CTouchDemoApp::OnAppAbout) // Standard file based document commands ON_COMMAND(ID_FILE_NEW, &CWinAppEx::OnFileNew) ON_COMMAND(ID_FILE_OPEN, &CWinAppEx::OnFileOpen) // Standard print setup command ON_COMMAND(ID_FILE_PRINT_SETUP, &CWinAppEx::OnFilePrintSetup) END_MESSAGE_MAP() // CTouchDemoApp construction CTouchDemoApp::CTouchDemoApp() { m_bHiColorIcons = TRUE; m_nTouchses = ::GetSystemMetrics(SM_MAXIMUMTOUCHES); // support Restart Manager m_dwRestartManagerSupportFlags = AFX_RESTART_MANAGER_SUPPORT_ALL_ASPECTS; // TODO: add construction code here, // Place all significant initialization in InitInstance } // The one and only CTouchDemoApp object CTouchDemoApp theApp; // CTouchDemoApp initialization BOOL CTouchDemoApp::InitInstance() { // InitCommonControlsEx() is required on Windows XP if an application // manifest specifies use of ComCtl32.dll version 6 or later to enable // visual styles. Otherwise, any window creation will fail. INITCOMMONCONTROLSEX InitCtrls; InitCtrls.dwSize = sizeof(InitCtrls); // Set this to include all the common control classes you want to use // in your application. InitCtrls.dwICC = ICC_WIN95_CLASSES; InitCommonControlsEx(&InitCtrls); CWinAppEx::InitInstance(); // Initialize OLE libraries if (!AfxOleInit()) { AfxMessageBox(IDP_OLE_INIT_FAILED); return FALSE; } AfxEnableControlContainer(); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need // Change the registry key under which our settings are stored // TODO: You should modify this string to be something appropriate // such as the name of your company or organization SetRegistryKey(_T("Local AppWizard-Generated Applications")); LoadStdProfileSettings(4); // Load standard INI file options (including MRU) InitContextMenuManager(); InitKeyboardManager(); InitTooltipManager(); CMFCToolTipInfo ttParams; ttParams.m_bVislManagerTheme = TRUE; theApp.GetTooltipManager()->SetTooltipParams(AFX_TOOLTIP_TYPE_ALL, RUNTIME_CLASS(CMFCToolTipCtrl), &ttParams); // Register the application's document templates. Document templates // serve as the connection between documents, frame windows and views CSingleDocTemplate* pDocTemplate; pDocTemplate = new CSingleDocTemplate( IDR_MAINFRAME, RUNTIME_CLASS(CTouchDemoDoc), RUNTIME_CLASS(CMainFrame), // main SDI frame window RUNTIME_CLASS(CTouchDemoView)); if (!pDocTemplate) return FALSE; AddDocTemplate(pDocTemplate); // Parse command line for standard shell commands, DDE, file open CCommandLineInfo cmdInfo; ParseCommandLine(cmdInfo); // Dispatch commands specified on the command line. Will return FALSE if // app was launched with /RegServer, /Register, /Unregserver or /Unregister. if (!ProcessShellCommand(cmdInfo)) return FALSE; // The one and only window has been initialized, so show and update it m_pMainWnd->ShowWindow(SW_SHOW); m_pMainWnd->UpdateWindow(); // call DragAcceptFiles only if there's a suffix // In an SDI app, this should occur after ProcessShellCommand if (m_nTouchses < 2) { AfxMessageBox(_T("This hardware doesn't support Windows Touch.")); } return TRUE; } // CAboutDlg dialog used for App About class CAboutDlg : public CDialog { public: CAboutDlg(); // Dialog Data enum { IDD = IDD_ABOUTBOX }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Implementation protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) END_MESSAGE_MAP() // App command to run the dialog void CTouchDemoApp::OnAppAbout() { CAboutDlg aboutDlg; aboutDlg.DoModal(); } // CTouchDemoApp customization load/save methods void CTouchDemoApp::PreLoadState() { BOOL bNameValid; CString strName; bNameValid = strName.LoadString(IDS_EDIT_MENU); ASSERT(bNameValid); GetContextMenuManager()->AddMenu(strName, IDR_POPUP_EDIT); } void CTouchDemoApp::LoadCustomState() { } void CTouchDemoApp::SaveCustomState() { } // CTouchDemoApp message handlers
26.468421
78
0.773315
[ "object" ]
c89745d5d51ca8f50431f92a03364d5a0663b3f4
2,263
cc
C++
caffe2/mkl/utils/mkl_memory.cc
freedomtan/caffe2
e1f614a5f8ae92f4ecb828e1d5f84d2cd1fe12bd
[ "Apache-2.0" ]
585
2015-08-10T02:48:52.000Z
2021-12-01T08:46:59.000Z
caffe2/mkl/utils/mkl_memory.cc
PDFxy/caffe2
28523ff1ff33f18eaf8b04cc4e0f308826e1861a
[ "Apache-2.0" ]
23
2015-08-30T11:54:51.000Z
2017-03-06T03:01:07.000Z
caffe2/mkl/utils/mkl_memory.cc
PDFxy/caffe2
28523ff1ff33f18eaf8b04cc4e0f308826e1861a
[ "Apache-2.0" ]
183
2015-08-10T02:49:04.000Z
2021-12-01T08:47:13.000Z
/** * Copyright (c) 2016-present, Facebook, Inc. * * 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 "caffe2/mkl/mkl_utils.h" #include "caffe2/core/init.h" #include "caffe2/core/tensor.h" #ifdef CAFFE2_HAS_MKL_DNN CAFFE2_DEFINE_bool( caffe2_mkl_implicit_layout_change, false, "Controls the behavior when we call View() on an MKLMemory: if it is set " "true, then the View() function will actually change the underlying " "storage. If it is set false, an implicit copy is triggered but the " "original storage is not affected." ); namespace caffe2 { CAFFE_KNOWN_TYPE(mkl::MKLMemory<float>); CAFFE_KNOWN_TYPE(mkl::MKLMemory<double>); template <typename T> static vector<TIndex> GetMKLTensorInfo( const void* c, bool* shares_data, size_t* capacity, DeviceOption* device) { const mkl::MKLMemory<T>* tc = static_cast<const mkl::MKLMemory<T>*>(c); // it's too hard to get sharing info from mkl::MKLMemory *shares_data = false; *capacity = tc->size() * sizeof(T); device->set_device_type(MKLDNN); device->set_cuda_gpu_id(0); return tc->dims(); } template <typename T> static TypeMeta GetMKLTensorType(const void*) { return TypeMeta::Make<T>(); } template <typename T> static void RegisterForType() { RegisterTypeCallFunction( TypeMeta::Id<mkl::MKLMemory<T>>(), GetMKLTensorType<T>); RegisterTensorInfoFunction( TypeMeta::Id<mkl::MKLMemory<T>>(), GetMKLTensorInfo<T>); } static bool Caffe2InitializeMKL(int*, char***) { RegisterForType<float>(); RegisterForType<double>(); return true; } REGISTER_CAFFE2_INIT_FUNCTION( InitMKLDNNContext, &Caffe2InitializeMKL, "Register wrappers for MKLContext"); } // namespace caffe2 #endif // CAFFE2_HAS_MKL_DNN
28.64557
78
0.72205
[ "vector" ]
c89ac06d550b14842a25baa7faa1abafe514379e
3,966
cpp
C++
hphp/compiler/expression/query_expression.cpp
dolfly/hhvm
2153ed0f4a010e412902388341435a9d517cf3e3
[ "PHP-3.01", "Zend-2.0" ]
1
2020-08-06T16:16:58.000Z
2020-08-06T16:16:58.000Z
hphp/compiler/expression/query_expression.cpp
1mr3yn/hhvm
7eb3262d3d1f2b64b288b6be790cf1c9d372c9cb
[ "PHP-3.01", "Zend-2.0" ]
null
null
null
hphp/compiler/expression/query_expression.cpp
1mr3yn/hhvm
7eb3262d3d1f2b64b288b6be790cf1c9d372c9cb
[ "PHP-3.01", "Zend-2.0" ]
null
null
null
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-2013 Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/compiler/expression/query_expression.h" #include "hphp/compiler/expression/simple_query_clause.h" #include "hphp/compiler/analysis/code_error.h" #include "hphp/runtime/base/complex-types.h" using namespace HPHP; /////////////////////////////////////////////////////////////////////////////// // constructors/destructors QueryOrderby::QueryOrderby(EXPRESSION_CONSTRUCTOR_BASE_PARAMETERS) : Expression(EXPRESSION_CONSTRUCTOR_BASE_PARAMETER_VALUES) { m_expressions = nullptr; } ExpressionPtr QueryOrderby::clone() { assert(false); return nullptr; } /////////////////////////////////////////////////////////////////////////////// // parser functions /////////////////////////////////////////////////////////////////////////////// // static analysis functions void QueryOrderby::analyzeProgram(AnalysisResultPtr ar) { for (unsigned int i = 0; i < m_expressions->getCount(); i++) { (*m_expressions)[i]->analyzeProgram(ar); } } ConstructPtr QueryOrderby::getNthKid(int n) const { if (n < (int)m_expressions->getCount()) { return (*m_expressions)[n]; } return ConstructPtr(); } int QueryOrderby::getKidCount() const { return m_expressions->getCount(); } void QueryOrderby::setNthKid(int n, ConstructPtr cp) { int m = m_expressions->getCount(); if (n >= m) { assert(false); } else { (*m_expressions)[n] = dynamic_pointer_cast<Expression>(cp); } } TypePtr QueryOrderby::inferTypes(AnalysisResultPtr ar, TypePtr type, bool coerce) { for (unsigned int i = 0; i < m_expressions->getCount(); i++) { if (ExpressionPtr e = (*m_expressions)[i]) { e->inferAndCheck(ar, Type::Some, false); } } return Type::Object; } ExpressionPtr QueryExpression::getCollection() const { assert(m_expressions->getCount() > 0); assert((*m_expressions)[0]->getKindOf() == Expression::KindOfFromClause); auto fromClause = static_pointer_cast<FromClause>((*m_expressions)[0]); return fromClause->getExpression(); } /////////////////////////////////////////////////////////////////////////////// void QueryOrderby::outputCodeModel(CodeGenerator &cg) { if (this->getKindOf() == Expression::KindOfOrderbyClause) { cg.printObjectHeader("OrderbyClause", 2); } else { cg.printObjectHeader("QueryExpression", 2); } cg.printPropertyHeader("clauses"); m_expressions->outputCodeModel(cg); cg.printPropertyHeader("sourceLocation"); cg.printLocation(this->getLocation()); cg.printObjectFooter(); } /////////////////////////////////////////////////////////////////////////////// // code generation functions void QueryOrderby::outputPHP(CodeGenerator &cg, AnalysisResultPtr ar) { if (this->getKindOf() == Expression::KindOfOrderbyClause) { cg_printf("orderby "); } for (unsigned int i = 0; i < m_expressions->getCount(); i++) { if (ExpressionPtr e = (*m_expressions)[i]) { e->outputPHP(cg, ar); if (i > 0) cg_printf(" "); } } }
33.897436
79
0.546646
[ "object" ]
c89f7665a3358282f59b7447c9572a1f874b4ab7
5,231
cpp
C++
Class6/DS02_icp06_maxFlow_sol.cpp
A2Zntu/DSPA
955202438ef2e0c963f98a0666cb6e7e30aa3e7a
[ "MIT" ]
null
null
null
Class6/DS02_icp06_maxFlow_sol.cpp
A2Zntu/DSPA
955202438ef2e0c963f98a0666cb6e7e30aa3e7a
[ "MIT" ]
null
null
null
Class6/DS02_icp06_maxFlow_sol.cpp
A2Zntu/DSPA
955202438ef2e0c963f98a0666cb6e7e30aa3e7a
[ "MIT" ]
null
null
null
#include<iostream> #include<vector> #include<iomanip> using namespace std; const int VERY_LARGE = 999999; class Path { private: vector<int> nodes; int capacity; public: Path(); Path(int aNode); Path(Path aShorterPath, int aNode, int capacity); int getTail(); int getCapacity(); vector<int> getNodes(); void print(); }; Path::Path() : capacity(VERY_LARGE) { } Path::Path(int aNode) : capacity(VERY_LARGE) { this->nodes.push_back(aNode); } Path::Path(Path aShorterPath, int aNode, int capacity) { for(int i = 0; i < aShorterPath.nodes.size(); i++) this->nodes.push_back(aShorterPath.nodes[i]); this->nodes.push_back(aNode); this->capacity = capacity; } void Path::print() { if(this->nodes.size() == 0) cout << "<empty>" << endl; else { cout << "Path: " << endl; for(int i = 0; i < this->nodes.size() - 1; i++) cout << this->nodes[i] << ","; cout << this->nodes.back() << ";"; cout << this->capacity << endl; } } int Path::getTail() { return this->nodes.back(); } int Path::getCapacity() { return this->capacity; } vector<int> Path::getNodes() { return this->nodes; } class Network { private: int n; int** resCap; public: Network(int n); void adjustArcCap(int node1, int node2, int capacity); void print(); vector<Path> getNextWithResCap(Path aPath); Path getAnAugmentingPath(); void sendOnce(Path anAugPath); int maxFlow(Network &emptyNetwork); ~Network(); }; Network::Network(int n) : n(n) { this->resCap = new int*[this->n]; for(int i = 0; i < this->n; i++) { this->resCap[i] = new int[this->n]; for(int j = 0; j < this->n; j++) this->resCap[i][j] = 0; } } void Network::adjustArcCap(int node1, int node2, int capacity) { this->resCap[node1][node2] += capacity; } void Network::print() { for(int i = 0; i < this->n; i++) { for(int j = 0; j < this->n; j++) cout << setw(2) << this->resCap[i][j] << " "; cout << endl; } } // input: a path of length L // output: a vector of paths of length L + 1 // precondition: aPath is really a path in this network vector<Path> Network::getNextWithResCap(Path aPath) { vector<Path> longerPaths; int tail = aPath.getTail(); for(int i = 0; i < this->n; i++) { if(this->resCap[tail][i] > 0) { int oldCap = aPath.getCapacity(); int newCap = oldCap; if(this->resCap[tail][i] < oldCap) newCap = this->resCap[tail][i]; Path p(aPath, i, newCap); longerPaths.push_back(p); } } return longerPaths; } // this function does not check whether a path visits a visited node Path Network::getAnAugmentingPath() { // find an augmenting path through BFS vector<Path> pathQueue; Path start(0); pathQueue.push_back(start); Path anAugmentingPath; bool keepGoing = true; while(keepGoing && pathQueue.size() > 0) { Path cur = pathQueue.front(); pathQueue.erase(pathQueue.begin()); vector<Path> curPlusOne = this->getNextWithResCap(cur); for(int i = 0; i < curPlusOne.size(); i++) { // whether the tail is a visited node should be checked below // cout << "..." << curPlusOne[i].getTail() << endl; if(curPlusOne[i].getTail() == n - 1) { anAugmentingPath = curPlusOne[i]; keepGoing = false; break; } else pathQueue.push_back(curPlusOne[i]); } // cout << "===============\n"; // for(int i = 0; i < pathQueue.size(); i++) // pathQueue[i].print(); } return anAugmentingPath; } void Network::sendOnce(Path anAugPath) { int flow = anAugPath.getCapacity(); vector<int> nodes = anAugPath.getNodes(); int nodeCnt = nodes.size(); for(int i = 0; i < nodes.size() - 1; i++) { // forward: send something and decrease capacity this->adjustArcCap(nodes[i], nodes[i + 1], -flow); // backward: add capacity this->adjustArcCap(nodes[i + 1], nodes[i], flow); } } int Network::maxFlow(Network &emptyNetwork) { Path anAugPath = this->getAnAugmentingPath(); anAugPath.print(); int maxFlowAmount = 0; while(anAugPath.getCapacity() < VERY_LARGE) { // if capacity == VERY_LARGE which means the anAugPath is an empty path, then stop. maxFlowAmount += anAugPath.getCapacity(); this->sendOnce(anAugPath); emptyNetwork.sendOnce(anAugPath); cout << "++++++++++++++++ net +++++++++++++++++++" << endl; this->print(); cout << "================= EmptyNetWork ===================" << endl; emptyNetwork.print(); anAugPath = this->getAnAugmentingPath(); anAugPath.print(); } // clear positive values; flip negative values for(int i = 0; i < emptyNetwork.n; i++) { for(int j = 0; j < emptyNetwork.n; j++) { if(emptyNetwork.resCap[i][j] > 0) emptyNetwork.resCap[i][j] = 0; else if(emptyNetwork.resCap[i][j] < 0) emptyNetwork.resCap[i][j] *= -1; } } return maxFlowAmount; } Network::~Network() { for(int i = 0; i < this->n; i++) delete [] resCap[i]; delete [] resCap; } int main() { // initializing the original network int n = 0, m = 0; cin >> n >> m; Network net(n); for(int i = 0; i < m; i++) { int u = 0, v = 0, capacity = 0; cin >> u >> v >> capacity; net.adjustArcCap(u, v, capacity); } net.print(); Network emptyNetwork(n); int maxFlowAmount = net.maxFlow(emptyNetwork); cout << "maxFlowAmount: " << maxFlowAmount << endl; emptyNetwork.print(); return 0; }
23.146018
130
0.623399
[ "vector" ]
c8a1c44e16d8b2515855b7670ca4bfacbcabdb5d
7,884
cc
C++
caffe2/operators/top_k.cc
fxlambda-twickly5/caffe-lambda
30fad32c8fb97e46c4af0f827a16a0e4f5d55271
[ "MIT" ]
40
2017-09-03T13:23:42.000Z
2021-02-03T23:59:28.000Z
caffe2/operators/top_k.cc
fxlambda-twickly5/caffe-lambda
30fad32c8fb97e46c4af0f827a16a0e4f5d55271
[ "MIT" ]
1
2017-12-15T09:49:26.000Z
2018-01-21T10:54:36.000Z
caffe2/operators/top_k.cc
fxlambda-twickly5/caffe-lambda
30fad32c8fb97e46c4af0f827a16a0e4f5d55271
[ "MIT" ]
6
2017-09-01T22:12:44.000Z
2018-10-12T13:14:25.000Z
#include "caffe2/operators/top_k.h" #include "caffe2/proto/caffe2.pb.h" namespace caffe2 { namespace { template <typename T> struct ValueCmp { bool operator()( const std::pair<T, TIndex>& lhs, const std::pair<T, TIndex>& rhs) { return ( lhs.first > rhs.first || (lhs.first == rhs.first && lhs.second < rhs.second)); } }; // Define these two names to allow lookup into the 2d tensors like // mytensor(i, j) template <typename T> using EigenMatrixMapRowMajor = Eigen::Map< Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>; template <typename T> using ConstEigenMatrixMapRowMajor = Eigen::Map< const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>; } // namespace template <typename T, class Context> bool TopKOp<T, Context>::RunOnDevice() { auto& input = Input(0); auto* values = Output(0); auto* indices = Output(1); auto* flatten_indices = OutputSize() > 2 ? Output(2) : nullptr; vector<TIndex> in_dims = input.dims(); // Linearize input tensor except for last dimension // e.g. [3, 4, 5] -> [12, 5] // [5] -> [5] CAFFE_ENFORCE( in_dims.back() >= k_, "k argment should not be greater than last dim"); vector<TIndex> linear_shape = {size_to_dim_(in_dims.size() - 1, in_dims), in_dims[in_dims.size() - 1]}; auto input_map = ConstEigenMatrixMapRowMajor<T>( static_cast<const T*>(input.raw_data()), linear_shape[0], linear_shape[1]); // Resize output tensors to be the same shape as the linearized input except // for the last dimension, which will be of size k. E.x. for an input tensor // of shape [3, 4, 5] and k=2, both of these will be shape [3, 4, 2] vector<TIndex> output_linear_shape = {linear_shape[0], k_}; values->Resize(output_linear_shape); indices->Resize(output_linear_shape); if (flatten_indices) { flatten_indices->Resize(linear_shape[0] * k_); } // Use Eigen maps to allow indexing into the 2d tensors like values_map(i,j) auto values_map = EigenMatrixMapRowMajor<T>( values->template mutable_data<T>(), linear_shape[0], k_); auto indices_map = EigenMatrixMapRowMajor<TIndex>( indices->template mutable_data<TIndex>(), linear_shape[0], k_); auto* flatten_indices_data = flatten_indices ? flatten_indices->template mutable_data<TIndex>() : nullptr; TIndex flatten_offset = 0; // Sort preserving indices for (TIndex i = 0; i < linear_shape[0]; ++i) { // Build a min-heap, the heap element is pair of (value, idx) // the top of the heap is the smallest value std::priority_queue< std::pair<T, TIndex>, std::vector<std::pair<T, TIndex>>, ValueCmp<T>> PQ; // Maintain the size of heap to be less or equal to k_, so the // heap will hold the k_ largest values for (TIndex j = 0; j < linear_shape[1]; ++j) { const auto value = input_map(i, j); if (PQ.size() < k_ || value > PQ.top().first) { PQ.push(std::make_pair(value, j)); } if (PQ.size() > k_) { PQ.pop(); } } for (TIndex j = 0; j < k_; ++j) { auto& pqElem = PQ.top(); values_map(i, k_ - j - 1) = pqElem.first; indices_map(i, k_ - j - 1) = pqElem.second; if (flatten_indices_data) { flatten_indices_data[k_ - j - 1] = pqElem.second + flatten_offset; } PQ.pop(); } if (flatten_indices_data) { flatten_indices_data += k_; } flatten_offset += linear_shape[1]; } // Reshape output tensors to [a_1, a_2, ..., a_n, k] auto out_dims = in_dims; out_dims[out_dims.size() - 1] = k_; values->Reshape(out_dims); indices->Reshape(out_dims); return true; } template <typename T, class Context> bool TopKGradientOp<T, Context>::RunOnDevice() { auto& values = Input(0); auto& indices = Input(1); auto& original_input = Input(2); auto* output = Output(0); vector<TIndex> in_dims = values.dims(); // Linearize input tensor except for last dimension // e.g. [3, 4, 5] -> [12, 5] // [5] -> [5] vector<TIndex> linear_shape = {size_to_dim_(in_dims.size() - 1, in_dims), in_dims[in_dims.size() - 1]}; auto values_map = ConstEigenMatrixMapRowMajor<T>( static_cast<const T*>(values.raw_data()), linear_shape[0], linear_shape[1]); auto indices_map = ConstEigenMatrixMapRowMajor<TIndex>( static_cast<const TIndex*>(indices.raw_data()), linear_shape[0], linear_shape[1]); // Resize output tensors to be as orignial_input size and initialized with 0 vector<TIndex> original_dims = original_input.dims(); output->Resize(original_dims); T* output_data = output->template mutable_data<T>(); memset(output_data, 0, output->nbytes()); // Use Eigen maps to allow indexing into the 2d tensors auto output_map = EigenMatrixMapRowMajor<T>( output_data, linear_shape[0], original_dims.back()); for (TIndex i = 0; i < linear_shape[0]; ++i) { for (TIndex j = 0; j < linear_shape[1]; ++j) { output_map(i, indices_map(i, j)) = values_map(i, j); } } return true; } namespace { REGISTER_CPU_OPERATOR(TopK, TopKOp<float, CPUContext>); REGISTER_CPU_OPERATOR(TopKGradient, TopKGradientOp<float, CPUContext>); OPERATOR_SCHEMA(TopK) .NumInputs(1) .NumOutputs(2, 3) .TensorInferenceFunction([](const OperatorDef& def, const vector<TensorShape>& in) { vector<TensorShape> out = {in[0], in[0]}; ArgumentHelper helper(def); auto k = helper.GetSingleArgument("k", -1); auto dims_size = in[0].dims_size(); out[0].set_dims(dims_size - 1, k); out[1].set_dims(dims_size - 1, k); out[1].set_data_type(TensorProto_DataType_INT32); if (def.output_size() > 2) { TensorShape flatten_indices_shape; flatten_indices_shape.set_data_type(TensorProto_DataType_INT32); flatten_indices_shape.add_dims( std::accumulate( in[0].dims().begin(), in[0].dims().end() - 1, 1, std::multiplies<long>()) * k); out.push_back(flatten_indices_shape); } return out; }) .SetDoc(R"DOC( Retrieve the top-K elements for the last dimension. Given an input tensor of shape [a_1, a_2, ..., a_n, r] and integer argument k, return two outputs: -Value tensor of shape [a_1, a_2, ..., a_n, k] which contains the values of the top k elements along the last dimension -Index tensor of shape [a_1, a_2, ..., a_n, k] which contains the indices of the top k elements (original indices from the input tensor). Given two equivalent values, this operator uses the indices along the last dim- ension as a tiebreaker. That is, the element with the lower index will appear first. )DOC") .Input(0, "X", "Tensor of shape [a_1, a_2, ..., a_n, r]") .Output( 0, "Values", "Tensor of shape [a_1, a_2, ..., a_n, k] containing" " top K values from the input tensor") .Output( 1, "Indices", "Tensor of shape [a_1, a_2, ..., a_n, k] containing" " the corresponding input tensor indices for the top K values.") .Output( 2, "Flatten indices", "Tensor of shape [a_1 * a_2 * ... * a_n * k] containing the indices " "into the flatten input") .Arg("k", "Number of top elements to retrieve"); OPERATOR_SCHEMA(TopKGradient).NumInputs(3).NumOutputs(1); class GetTopKGradient : public GradientMakerBase { using GradientMakerBase::GradientMakerBase; vector<OperatorDef> GetGradientDefs() override { return SingleGradientDef( "TopKGradient", "", vector<string>{GO(0), O(1), I(0)}, vector<string>{GI(0)}); } }; REGISTER_GRADIENT(TopK, GetTopKGradient); } // namespace } // namespace caffe2
33.548936
79
0.634196
[ "shape", "vector" ]
c8a46317fa19300136769a4e1c29a04912e78612
64,556
cpp
C++
Src/Analysis/MOATAnalyzer.cpp
lbianchi-lbl/psuade-lite
09d7ca75aba8a9e31e1fb5c3e134af046fca3460
[ "Apache-2.0" ]
1
2021-03-10T23:25:30.000Z
2021-03-10T23:25:30.000Z
Src/Analysis/MOATAnalyzer.cpp
lbianchi-lbl/psuade-lite
09d7ca75aba8a9e31e1fb5c3e134af046fca3460
[ "Apache-2.0" ]
3
2021-03-10T22:10:32.000Z
2022-01-14T04:31:05.000Z
Src/Analysis/MOATAnalyzer.cpp
lbianchi-lbl/psuade-lite
09d7ca75aba8a9e31e1fb5c3e134af046fca3460
[ "Apache-2.0" ]
1
2021-02-24T22:59:02.000Z
2021-02-24T22:59:02.000Z
// ************************************************************************ // Copyright (c) 2007 Lawrence Livermore National Security, LLC. // Produced at the Lawrence Livermore National Laboratory. // Written by the PSUADE team. // All rights reserved. // // Please see the COPYRIGHT and LICENSE file for the copyright notice, // disclaimer, contact information and the GNU Lesser General Public License. // // PSUADE is free software; you can redistribute it and/or modify it under the // terms of the GNU Lesser General Public License (as published by the Free // Software Foundation) version 2.1 dated February 1999. // // PSUADE 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 terms and conditions of the GNU Lesser // General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program; if not, write to the Free Software Foundation, // Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // ************************************************************************ // Functions for the class MOATAnalyzer // AUTHOR : CHARLES TONG // DATE : 2004 // ************************************************************************ #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <math.h> #include <algorithm> #include <fstream> #include <iostream> #include <sstream> using namespace std; #include "MOATConstraints.h" #include "PsuadeUtil.h" #include "sysdef.h" #include "MOATAnalyzer.h" #include "BinomialAnalyzer.h" #include "BootstrapAnalyzer.h" #include "Psuade.h" #include "Globals.h" #include "PrintingTS.h" #define PABS(x) (((x) > 0.0) ? (x) : -(x)) // ************************************************************************ // constructor // ------------------------------------------------------------------------ MOATAnalyzer::MOATAnalyzer() : Analyzer(), nInputs_(0), nOutputs_(0), nSamples_(0), outputID_(0) { setName("MOAT"); } // ************************************************************************ // destructor // ------------------------------------------------------------------------ MOATAnalyzer::~MOATAnalyzer() { } // ************************************************************************ // perform analysis (for library call only) // ------------------------------------------------------------------------ void MOATAnalyzer::analyze(int nInps, int nSamp, double *lbs, double *ubs, double *X, double *Y) { aData adata; adata.nInputs_ = nInps; adata.nOutputs_ = 1; adata.nSamples_ = nSamp; adata.iLowerB_ = lbs; adata.iUpperB_ = ubs; adata.sampleInputs_ = X; adata.sampleOutputs_ = Y; adata.outputID_ = 0; adata.printLevel_ = 0; analyze(adata); } // ************************************************************************ // perform analysis // ------------------------------------------------------------------------ double MOATAnalyzer::analyze(aData &adata) { int ii, jj, diffIndex; int iD, index, n1, n2, flag, actualPaths, sigFlag; int diffCnt, itemp, iaCnt, iD2, nPaths, ip, printLevel; double *X, *Y, *XLower, *XUpper; double xtemp1, xtemp2, ytemp1, ytemp2, scale, dtemp, dtemp2, thresh; double dsum, dstdev, binMax=-1.0e35, binMin=1.0e35; char winput[500], pString[499]; PsuadeData *ioPtr; BinomialAnalyzer binAnalyzer; BootstrapAnalyzer bsAnalyzer; aData bData; pData qData; MOATConstraints *constrPtr; psVector YY,YG,XG,YB,Xbase,XSort,YSort,sortedModifiedMeans; psVector indexes; psIVector counts, indexTrack; // --------------------------------------------------------------- // display header // --------------------------------------------------------------- printLevel = adata.printLevel_; if (isScreenDumpModeOn()) { printAsterisks(PL_INFO, 0); printOutTS(PL_INFO,"* Morris Screening \n"); printEquals(PL_INFO, 0); if (printLevel > 0) { printOutTS(PL_INFO,"* Use printlevel to show more analysis info.\n"); printOutTS(PL_INFO,"* Use ana_expert to turn on other plot options:\n"); printOutTS(PL_INFO,"* - e.g. scatter plots gives gradient details\n"); printOutTS(PL_INFO,"* - e.g. screen plots gives gradients vs stdev\n"); } } // --------------------------------------------------------------- // extract test information and data // --------------------------------------------------------------- nInputs_ = adata.nInputs_; nOutputs_ = adata.nOutputs_; nSamples_ = adata.nSamples_; XLower = adata.iLowerB_; XUpper = adata.iUpperB_; X = adata.sampleInputs_; Y = adata.sampleOutputs_; outputID_ = adata.outputID_; ioPtr = adata.ioPtr_; if (adata.inputPDFs_ != NULL) { n1 = 0; for (ii = 0; ii < nInputs_; ii++) n1 += adata.inputPDFs_[ii]; if (n1 > 0 && isScreenDumpModeOn()) { printOutTS(PL_INFO, "MOATAnalysis INFO: some inputs have non-uniform PDFs,\n"); printOutTS(PL_INFO, " but they are not relevant in this analysis\n"); printOutTS(PL_INFO, " (the sample should have been generated\n"); printOutTS(PL_INFO, " with the desired distributions earlier.)\n"); } } if (ioPtr != NULL) ioPtr->getParameter("input_names", qData); if (nInputs_ <= 0 || nSamples_ <= 0 || nOutputs_ <= 0 || outputID_ < 0 || outputID_ >= nOutputs_) { printOutTS(PL_ERROR, "MOATAnalysis ERROR: invalid arguments.\n"); printOutTS(PL_ERROR, " nInputs = %d\n", nInputs_); printOutTS(PL_ERROR, " nOutputs = %d\n", nOutputs_); printOutTS(PL_ERROR, " nSamples = %d\n", nSamples_); printOutTS(PL_ERROR, " outputID = %d\n", outputID_+1); exit(1); } n1 = 0; for (iD = 0; iD < nSamples_; iD++) if (Y[iD*nOutputs_+outputID_] == PSUADE_UNDEFINED) n1++; if (n1 > 0 && isScreenDumpModeOn()) { printOutTS(PL_INFO,"MOATAnalysis INFO: %d invalid data points.\n",n1); printOutTS(PL_INFO," These invalid points will not be analyzed.\n"); } XSort.setLength(nSamples_); for (ii = 0; ii < nInputs_; ii++) { for (iD = 0; iD < nSamples_; iD++) XSort[iD] = X[iD*nInputs_+ii]; sortDbleList(nSamples_, XSort.getDVector()); dtemp = XSort[nSamples_-1] - XSort[0]; dtemp2 = XUpper[ii] - XLower[ii]; if (isScreenDumpModeOn() && PABS(dtemp-dtemp2) > 1.0e-6) { printOutTS(PL_WARN, "MOATAnalyzer WARNING: input and data range mismatch but there\n"); printOutTS(PL_WARN, " is no need to be alarmed, as this may be the\n"); printOutTS(PL_WARN, " result of applying MOAT constraints. However, it\n"); printOutTS(PL_WARN, " may also be due to applying input transformation\n"); printOutTS(PL_WARN, " in which case you need to make proper changes.\n"); printOutTS(PL_WARN, " Diagnostics: \n"); printOutTS(PL_WARN, " Input %3d: original vs new ranges = %e %e\n", ii+1, dtemp2, dtemp); } } constrPtr = NULL; if (ioPtr != NULL) { constrPtr = new MOATConstraints(); constrPtr->initialize(ioPtr); } YY.setLength(nSamples_); YG.setLength(nSamples_); XG.setLength(nSamples_); for (iD = 0; iD < nSamples_; iD++) YY[iD] = Y[nOutputs_*iD+outputID_]; counts.setLength(nInputs_); means_.setLength(nInputs_); stds_.setLength(nInputs_); modifiedMeans_.setLength(nInputs_); modifiedStds_.setLength(nInputs_); indexesSortedByModifiedMeans_.setLength(nInputs_); indexTrack.setLength(nSamples_); for (iD = 0; iD < nSamples_; iD++) indexTrack[iD] = -1; Xbase.setLength(nSamples_); indexTrack[0] = -1; for (iD = 1; iD < nSamples_; iD++) { if (isScreenDumpModeOn() && (printLevel > 3) && (iD % 10 == 0)) printOutTS(PL_INFO, "MOATAnalysis: processing sample %d\n", iD+1); Xbase[iD] = 0.0; ytemp1 = YY[iD-1]; ytemp2 = YY[iD]; diffCnt = 0; for (ii = 0; ii < nInputs_; ii++) { xtemp1 = X[(iD-1)*nInputs_+ii]; xtemp2 = X[iD*nInputs_+ii]; if (xtemp1 != xtemp2 && ytemp1 != PSUADE_UNDEFINED && ytemp2 != PSUADE_UNDEFINED) { diffCnt++; diffIndex = ii; } } if (diffCnt == 1) { indexTrack[iD] = diffIndex; xtemp1 = X[(iD-1)*nInputs_+diffIndex]; xtemp2 = X[iD*nInputs_+diffIndex]; flag = 1; if (constrPtr != NULL) scale = constrPtr->getScale(&X[iD*nInputs_],diffIndex,flag); if (flag == 1) scale = XUpper[diffIndex] - XLower[diffIndex]; else if (isScreenDumpModeOn() && printLevel > 3) { printOutTS(PL_INFO, "MOATAnalysis: sample group %d, ", iD+1); printOutTS(PL_INFO, "input %d, scale = %e\n", diffIndex, scale); } YG[iD] = (ytemp2-ytemp1)/(xtemp2-xtemp1)*scale; if (xtemp2 > xtemp1) XG[iD] = xtemp2; else XG[iD] = xtemp1; counts[diffIndex]++; if (xtemp2 > xtemp1) Xbase[iD] = xtemp1; else Xbase[iD] = xtemp2; } else { YG[iD] = PSUADE_UNDEFINED; indexTrack[iD] = -1; } } if (nSamples_ / (nInputs_+1) * (nInputs_+1) == nSamples_) { for (iD = 0; iD < nSamples_; iD+=(nInputs_+1)) indexTrack[iD] = -1; } for (iD = 0; iD < nSamples_; iD++) { if (YG[iD] != PSUADE_UNDEFINED) { index = indexTrack[iD]; if (index >= 0) { means_[index] += YG[iD]; modifiedMeans_[index] += PABS(YG[iD]); } } } for (ii = 0; ii < nInputs_; ii++) { if (counts[ii] > 0) { means_[ii] /= (double) counts[ii]; modifiedMeans_[ii] /= (double) counts[ii]; } else { printOutTS(PL_INFO, "MOATAnalysis analyze: no data point for input %d\n",ii+1); means_[ii] = 0.0; modifiedMeans_[ii] = 0.0; } } for (iD = 0; iD < nSamples_; iD++) { if (YG[iD] != PSUADE_UNDEFINED) { index = indexTrack[iD]; if (index >= 0) { stds_[index] += (YG[iD] - means_[index])*(YG[iD] - means_[index]); modifiedStds_[index] += (PABS(YG[iD]) - modifiedMeans_[index])* (PABS(YG[iD]) - modifiedMeans_[index]); } } } for (ii = 0; ii < nInputs_; ii++) { if (counts[ii] > 1) { stds_[ii] /= (double) (counts[ii] - 1); modifiedStds_[ii] /= (double) (counts[ii] - 1); } else { printOutTS(PL_INFO, "MOATAnalysis analyze: %d data points for input %d\n", counts[ii],ii+1); stds_[ii] = 0.0; modifiedStds_[ii] = 0.0; } if (stds_[ii] < 0.0) stds_[ii] = -sqrt(-stds_[ii]); else stds_[ii] = sqrt(stds_[ii]); if (modifiedStds_[ii] < 0) modifiedStds_[ii] = -sqrt(-modifiedStds_[ii]); else modifiedStds_[ii] = sqrt(modifiedStds_[ii]); } n1 = 0; for (ii = 0; ii < nInputs_; ii++) n1 += counts[ii]; if (n1 <= 0) { if (constrPtr != NULL) delete constrPtr; printOutTS(PL_INFO,"MOATAnalysis INFO: probably not an MOAT sample.\n"); return 1; } if (isScreenDumpModeOn()) { printEquals(PL_INFO, 0); printOutTS(PL_INFO,"* MOAT Analysis using unmodified gradients\n"); printDashes(PL_INFO, 0); for (ii = 0; ii < nInputs_; ii++) printOutTS(PL_INFO,"Input %3d (unmod. mean & std) = %12.4e %12.4e\n", ii+1, means_[ii], stds_[ii]); printEquals(PL_INFO, 0); printOutTS(PL_INFO,"* MOAT Analysis using modified gradients\n"); printDashes(PL_INFO, 0); for (ii = 0; ii < nInputs_; ii++) printOutTS(PL_INFO,"Input %3d (mod. mean & std) = %12.4e %12.4e\n", ii+1, modifiedMeans_[ii], stds_[ii]); printAsterisks(PL_INFO, 0); } pData *pPtr = NULL; if (ioPtr != NULL) { pPtr = ioPtr->getAuxData(); pPtr->nDbles_ = nInputs_; pPtr->dbleArray_ = new double[nInputs_]; for (ii = 0; ii < nInputs_; ii++) pPtr->dbleArray_[ii] = modifiedMeans_[ii]; } // --------------------------------------------------------------- // create matlab files // --------------------------------------------------------------- if (isScreenDumpModeOn()) { if (psAnaExpertMode_ == 1) createScreenDiagramFile(nSamples_, nInputs_, YG.getDVector(), indexTrack.getIVector(), modifiedMeans_.getDVector(), stds_.getDVector(), outputID_,qData.strArray_); if (psAnaExpertMode_ == 1) createScatterFile(nSamples_,nInputs_,YG.getDVector(), Xbase.getDVector(), indexTrack.getIVector(), qData.strArray_); createBootstrapFile(nSamples_, nInputs_,YG.getDVector(), Xbase.getDVector(), indexTrack.getIVector(), qData.strArray_); } // --------------------------------------------------------------- // sorted list // --------------------------------------------------------------- indexes.setLength(nInputs_); sortedModifiedMeans.setLength(nInputs_); for (ii = 0; ii < nInputs_; ii++) sortedModifiedMeans[ii] = modifiedMeans_[ii]; for (ii = 0; ii < nInputs_; ii++) indexes[ii] = ii; sortDbleList2(nInputs_, sortedModifiedMeans.getDVector(), indexes.getDVector()); for (ii = 0; ii < nInputs_; ii++) indexesSortedByModifiedMeans_[ii] = (int) indexes[ii]; if (isScreenDumpModeOn()) { printOutTS(PL_INFO, "* MOAT Analysis (ordered based on modified means of gradients)\n"); printDashes(PL_INFO, 0); for (ii = nInputs_-1; ii >= 0; ii--) { iD = indexesSortedByModifiedMeans_[ii]; itemp = counts[iD] - 1; printOutTS(PL_INFO, "%6d: Input %3d (mu*, sigma, dof) = %12.4e %12.4e %d\n", nInputs_-ii,iD+1, sortedModifiedMeans[ii], stds_[iD], itemp); } printEquals(PL_INFO, 0); } // --------------------------------------------------------------- // further analysis based on standard error of means // --------------------------------------------------------------- psVector sigma1LowerBounds, sigma1UpperBounds; psVector sigma2LowerBounds, sigma2UpperBounds; if ((printLevel > 1) && isScreenDumpModeOn()) { sigma1LowerBounds.setLength(nInputs_); sigma1UpperBounds.setLength(nInputs_); for (ii = 0; ii < 11; ii++) printOutTS(PL_INFO, "-"); printOutTS(PL_INFO, " MOAT Analysis (ordered) : +- 1 sigma "); for (ii = 0; ii < 11; ii++) printOutTS(PL_INFO, "-"); printOutTS(PL_INFO, "\n"); printDashes(PL_INFO, 0); for (ii = nInputs_-1; ii >= 0; ii--) { iD = indexesSortedByModifiedMeans_[ii]; if (counts[iD] > 1) dtemp = sqrt((double) counts[iD] - 1.0); else dtemp = 1.0; sigma1LowerBounds[ii]=sortedModifiedMeans[ii]-modifiedStds_[iD]/dtemp; sigma1UpperBounds[ii]=sortedModifiedMeans[ii]+modifiedStds_[iD]/dtemp; printOutTS(PL_INFO, "Input %3d bounds = %12.4e %12.4e\n", iD+1, sigma1LowerBounds[ii], sigma1UpperBounds[ii]); if (printLevel > 2 && ii > 0) { iD2 = indexesSortedByModifiedMeans_[ii-1]; if (counts[iD2-1] > 1) dtemp2 = sqrt((double) counts[iD2-1] - 1.0); else dtemp2 = 1.0; if ((sortedModifiedMeans[ii]-modifiedStds_[iD]/dtemp) > (sortedModifiedMeans[ii-1]+modifiedStds_[iD2]/dtemp2)) { printOutTS(PL_INFO, "=============> Input %3d is different from input %3d\n", iD+1, iD2+1); printOutTS(PL_INFO, "==> since their 1-sigma intervals do not overlap.\n"); } } } printEquals(PL_INFO, 0); sigma2LowerBounds.setLength(nInputs_); sigma2UpperBounds.setLength(nInputs_); printOutTS(PL_INFO,"* MOAT Analysis (ordered) : +- 2 sigma\n"); printDashes(PL_INFO, 0); for (ii = nInputs_-1; ii >= 0; ii--) { iD = indexesSortedByModifiedMeans_[ii]; if (counts[iD] > 1) dtemp = sqrt((double) counts[iD] - 1.0); else dtemp = 1.0; sigma2LowerBounds[ii] = sortedModifiedMeans[ii] - 2.0*modifiedStds_[iD]/dtemp; sigma2UpperBounds[ii] = sortedModifiedMeans[ii] + 2.0*modifiedStds_[iD]/dtemp; printOutTS(PL_INFO, "Input %3d bounds = %12.4e %12.4e\n", iD+1, sigma2LowerBounds[ii], sigma2UpperBounds[ii]); if (printLevel > 2 && ii > 0) { iD2 = indexesSortedByModifiedMeans_[ii-1]; if (counts[iD2-1] > 1) dtemp2 = sqrt((double) counts[iD2-1] - 1.0); else dtemp2 = 1.0; if ((sortedModifiedMeans[ii]-2.0*modifiedStds_[iD]/dtemp) > (sortedModifiedMeans[ii-1]+2.0*modifiedStds_[iD2]/dtemp2)) { printOutTS(PL_INFO, "=============> Input %3d is different from input %3d.\n", iD+1, iD2+1); printOutTS(PL_INFO, "==> since their 2-sigma intervals do not overlap.\n"); } } } } if (isScreenDumpModeOn() == 0 && psAnaExpertMode_ == 1) { printEquals(PL_INFO, 0); printOutTS(PL_INFO,"Interaction analysis computes the std dev. of "); printOutTS(PL_INFO,"the gradients at fixed\n"); printOutTS(PL_INFO,"fixed values of the inputs. This will yield "); printOutTS(PL_INFO,"interaction information of\n"); printOutTS(PL_INFO,"this parameters with the others.\n"); sprintf(pString,"Perform MOAT interaction study ? (y or n) "); getString(pString, winput); if (winput[0] == 'y') { printAsterisks(PL_INFO, 0); for (ii = 0; ii < 17; ii++) printOutTS(PL_INFO, "*"); printOutTS(PL_INFO, " MOAT Interaction Analysis "); for (ii = 0; ii < 17; ii++) printOutTS(PL_INFO, "*"); printOutTS(PL_INFO, "\n"); printDashes(PL_INFO, 0); printOutTS(PL_INFO, "** No data for input means ==> no interaction info.\n"); printOutTS(PL_INFO, "** Small stdev means (crudely) ==> little interaction.\n"); nPaths = nSamples_ / (nInputs_ + 1); for (ii = 0; ii < nInputs_; ii++) { n1 = 0; for (iD = 0; iD < nSamples_; iD++) if (indexTrack[iD] == ii) n1++; if (n1 > nPaths) nPaths = n1; } XSort.setLength(nPaths); YSort.setLength(nPaths); for (ii = 0; ii < nInputs_; ii++) { actualPaths = 0; for (iD = 0; iD < nSamples_; iD++) { if (indexTrack[iD] == ii && YG[iD] != PSUADE_UNDEFINED) { XSort[actualPaths] = XG[iD]; YSort[actualPaths] = PABS(YG[iD]); actualPaths++; } } sortDbleList2(actualPaths,XSort.getDVector(),YSort.getDVector()); ip = 0; iaCnt = 0; dstdev = 0.0; while (ip < actualPaths) { n1 = ip; for (ip = n1+1; ip < actualPaths; ip++) if (XSort[ip] != XSort[ip-1]) break; n2 = ip; if ((n2 - n1) >= 2) { dsum = 0.0; for (iD = n1; iD < n2; iD++) dsum += YSort[iD]; dsum /= (double) (n2-n1); dtemp = 0.0; for (iD = n1; iD < n2; iD++) dtemp += (YSort[iD] - dsum) * (YSort[iD] - dsum); dtemp /= (double) (n2-n1-1); dtemp = sqrt(dtemp); dstdev += dtemp; iaCnt++; if (printLevel > 3) printOutTS(PL_INFO, "Input %3d stdev at %12.4e = %12.4e (%d) \n", ii+1, XSort[n1], dtemp, n2-n1); } else { if (printLevel > 3) printOutTS(PL_INFO, "Input %3d stdev at %12.4e = not available (%d).\n", ii+1, XSort[n1], n2-n1); } } if (iaCnt > 0) printOutTS(PL_INFO, "Input %3d average interaction measure (std dev) = %11.3e\n", ii+1, dstdev/iaCnt); } } } if (isScreenDumpModeOn() == 0 && psAnaExpertMode_ == 1) { printEquals(PL_INFO, 0); printOutTS(PL_INFO,"Hypothesis tests may be used for testing whether "); printOutTS(PL_INFO,"an input is likely a\n"); printOutTS(PL_INFO,"significant input given a gradient threshold to"); printOutTS(PL_INFO,"indicate significance.\n"); sprintf(pString, "Perform hypothesis tests ? (y or n) "); getString(pString, winput); if (winput[0] == 'y') { printAsterisks(PL_INFO, 0); printOutTS(PL_INFO,"* MOAT Hypothesis Tests\n"); printDashes(PL_INFO, 0); printOutTS(PL_INFO, "* This consists of 2 tests: \n"); printOutTS(PL_INFO, "* (1) bootstrap confidence interval test (95 %%) \n"); printOutTS(PL_INFO, "* (2) binomial test (90 %%) \n"); printOutTS(PL_INFO, "* If either test indicates significance, the corresponding\n"); printOutTS(PL_INFO, "* input will be declared significant.\n"); printDashes(PL_INFO, 0); for (ii = 0; ii < nInputs_; ii++) { if (sortedModifiedMeans[ii] > binMax) binMax = sortedModifiedMeans[ii]; if (sortedModifiedMeans[ii] < binMin) binMin = sortedModifiedMeans[ii]; } sprintf(pString,"Enter significance threshold (min,max = %e %e): ", binMin, binMax); thresh = binMin - 1.0; while (thresh < binMin || thresh > binMax) thresh = getDouble(pString); YB.setLength(nSamples_/(nInputs_+1)*100); bData.nOutputs_ = 1; bData.outputID_ = 0; bData.sampleOutputs_ = YB.getDVector(); bData.analysisThreshold_ = thresh; bData.printLevel_ = 0; for (ii = 0; ii < nInputs_; ii++) { printOutTS(PL_INFO, ">>>>>> MOAT hypothesis tests for INPUT %3d : \n", ii+1); sigFlag = 0; actualPaths = 0; for (iD = 0; iD < nSamples_; iD++) { if (YG[iD] != PSUADE_UNDEFINED) { index = indexTrack[iD]; if (index == ii) YB[actualPaths++] = PABS(YG[iD]); } } bData.nSamples_ = actualPaths; dtemp = bsAnalyzer.analyze(bData); if (dtemp > thresh) sigFlag = 1; if (printLevel > 1) { printOutTS(PL_INFO, " ---- Bootstrap confidence interval = [0, %e] (>? %e)", dtemp, thresh); if (sigFlag == 1) printOutTS(PL_INFO, " **"); printOutTS(PL_INFO, "\n"); } jj = actualPaths; for (iD = 0; iD < actualPaths; iD++) { if (YB[iD] > 1.5*thresh) { dtemp = YB[iD]; while (dtemp > 1.5*thresh) { YB[jj++] = 1.5 * thresh; dtemp -= (1.5 * thresh); if (jj >= (nSamples_/nInputs_+1)*100) { printOutTS(PL_ERROR, "MOATAnalysis ERROR: binomial test.\n"); exit(1); } } } } actualPaths = jj; bData.nSamples_ = actualPaths; dtemp = binAnalyzer.analyze(bData); if (dtemp > 0.1) sigFlag++; if (printLevel > 1) printOutTS(PL_INFO, " --- Binomial test ERROR = %4.1f %% if declared insignificant\n", 100.0*dtemp); if (sigFlag > 0) printOutTS(PL_INFO, "<<<<<< INPUT %3d IS SIGNIFICANT (%d) **************\n", ii+1,sigFlag); else printOutTS(PL_INFO, "<<<<<< INPUT %3d IS NOT significant\n", ii+1); } bData.sampleOutputs_ = NULL; } printAsterisks(PL_INFO,0); } if (constrPtr != NULL) delete constrPtr; return 0.0; } // ************************************************************************ // functions for getting results // ------------------------------------------------------------------------ double MOATAnalyzer::get_mean(int ind) { if (ind < 0 || ind >= nInputs_) { printf("MOATAnalyzer ERROR: get_mean index error.\n"); return 0.0; } if(means_.length() <= ind) { printf("MOATAnalyzer ERROR: get_mean has no value.\n"); return 0.0; } return means_[ind]; } // ------------------------------------------------------------------------ double MOATAnalyzer::get_stdev(int ind) { if (ind < 0 || ind >= nInputs_) { printf("MOATAnalyzer ERROR: get_stdev index error.\n"); return 0.0; } if(stds_.length() <= ind) { printf("MOATAnalyzer ERROR: get_stdev has no value.\n"); return 0.0; } return stds_[ind]; } // ------------------------------------------------------------------------ double MOATAnalyzer::get_modifiedMean(int ind) { if (ind < 0 || ind >= nInputs_) { printf("MOATAnalyzer ERROR: get_modifiedMean index error.\n"); return 0.0; } if(modifiedMeans_.length() <= ind) { printf("MOATAnalyzer ERROR: get_modifiedMean has no value.\n"); return 0.0; } return modifiedMeans_[ind]; } // ------------------------------------------------------------------------ double MOATAnalyzer::get_modifiedStdev(int ind) { if (ind < 0 || ind >= nInputs_) { printf("MOATAnalyzer ERROR: get_modifiedStdev index error.\n"); return 0.0; } if(modifiedStds_.length() <= ind) { printf("MOATAnalyzer ERROR: get_modifiedStdev has no value.\n"); return 0.0; } return modifiedStds_[ind]; } // ************************************************************************ // create Morris diagram matlab/scilab file // ------------------------------------------------------------------------ int MOATAnalyzer::createScreenDiagramFile(int nSamples, int nInputs, double *Y, int *indices, double *modifiedMeans, double *stds, int outputID, char **iNames) { int iD, ii, index, cnt; char winput[500], moatFile[500], pString[500]; FILE *fp; printOutTS(PL_INFO,"Screening diagram plots std devs of the gradients\n"); printOutTS(PL_INFO,"against modified means. It thus provides another\n"); printOutTS(PL_INFO,"perspective of viewing the parameter importance.\n"); sprintf(pString,"Create screening diagram? (y or n) "); getString(pString, winput); if (winput[0] != 'y') return 0; sprintf(pString,"matlab/scilab screen diagram file name (no extension): "); getString(pString, moatFile); cnt = strlen(moatFile); if (cnt > 500) { printOutTS(PL_ERROR, "ERROR: file name too long.\n"); exit(1); } moatFile[cnt-1] = '.'; if (psPlotTool_ == 1) { moatFile[cnt] = 's'; moatFile[cnt+1] = 'c'; moatFile[cnt+2] = 'i'; moatFile[cnt+3] = '\0'; } else { moatFile[cnt] = 'm'; moatFile[cnt+1] = '\0'; } fp = fopen(moatFile, "w"); if (fp == NULL) { printOutTS(PL_ERROR, "MOATAnalyzer: cannot open MOAT plot file %s\n", moatFile); return 0; } if (psPlotTool_ == 1) { fprintf(fp, "// Morris one-at-a-time screening plots\n"); fprintf(fp, "// Z contains the gradient data\n"); fprintf(fp, "// C contains the number of data for each input\n"); fprintf(fp, "// turn plotAll on or off\n"); } else { fprintf(fp, "%% Morris one-at-a-time screening plots\n"); fprintf(fp, "%% Z contains the gradient data\n"); fprintf(fp, "%% C contains the number of data for each input\n"); fprintf(fp, "%% turn plotAll on or off\n"); } fprintf(fp, "maxFlag = 0;\n"); fprintf(fp, "plotAll = 1;\n"); fprintf(fp, "Z = zeros(%d,%d);\n",nInputs,nSamples/(nInputs+1)); fprintf(fp, "C = zeros(%d,1);\n",nInputs); fwritePlotCLF(fp); for (iD = 0; iD < nSamples; iD++) { if (Y[iD] != PSUADE_UNDEFINED) { index = indices[iD]; if (index >= 0) { fprintf(fp, "C(%d) = C(%d) + 1;\n", index+1, index+1); fprintf(fp, "Z(%d,C(%d)) = %24.16e;\n",index+1,index+1,Y[iD]); } } } if (iNames == NULL) { fprintf(fp, "Str = {"); for (ii = 0; ii < nInputs-1; ii++) fprintf(fp,"'X%d',",ii+1); fprintf(fp,"'X%d'};\n",nInputs); } else { fprintf(fp, "Str = {"); for (ii = 0; ii < nInputs-1; ii++) { if (iNames[ii] != NULL) fprintf(fp,"'%s',",iNames[ii]); else fprintf(fp,"'X%d',",ii+1); } if (iNames[nInputs-1] != NULL) fprintf(fp,"'%s'};\n",iNames[nInputs-1]); else fprintf(fp,"'X%d'};\n",nInputs); } if (psPlotTool_ == 1) { fprintf(fp, "// compute max and min for axis \n"); fprintf(fp, "// XM : for computing mean \n"); fprintf(fp, "// Xm : for computing max \n"); fprintf(fp, "// XX : for computing modified mean \n"); fprintf(fp, "// VV : counts for each input \n"); fprintf(fp, "// YY : standard deviation for each input \n"); } else { fprintf(fp, "%% compute max and min for axis \n"); fprintf(fp, "%% XM : for computing mean \n"); fprintf(fp, "%% Xm : for computing max \n"); fprintf(fp, "%% XX : for computing modified mean \n"); fprintf(fp, "%% VV : counts for each input \n"); fprintf(fp, "%% YY : standard deviation for each input \n"); } fprintf(fp, "nn = %d;\n",nInputs); fprintf(fp, "XX = zeros(nn,1);\n"); fprintf(fp, "XM = zeros(nn,1);\n"); fprintf(fp, "Xm = zeros(nn,1);\n"); fprintf(fp, "YY = zeros(nn,1);\n"); fprintf(fp, "for jj = 1 : nn\n"); fprintf(fp, " VV = zeros(nn,1);\n"); fprintf(fp, " for kk = 1 : C(jj)\n"); fprintf(fp, " if (VV(jj) <= C(jj))\n"); fprintf(fp, " if (abs(Z(jj,kk)) > Xm(jj))\n"); fprintf(fp, " Xm(jj) = abs(Z(jj,kk));\n"); fprintf(fp, " end;\n"); fprintf(fp, " XM(jj) = XM(jj) + Z(jj,kk);\n"); fprintf(fp, " XX(jj) = XX(jj) + abs(Z(jj,kk));\n"); fprintf(fp, " VV(jj) = VV(jj) + 1;\n"); fprintf(fp, " end;\n"); fprintf(fp, " end;\n"); fprintf(fp, " if (VV(jj) > 0)\n"); fprintf(fp, " XM(jj) = XM(jj) / VV(jj);\n"); fprintf(fp, " XX(jj) = XX(jj) / VV(jj);\n"); fprintf(fp, " end;\n"); fprintf(fp, " VV = zeros(nn,1);\n"); fprintf(fp, " for kk = 1 : C(jj)\n"); fprintf(fp, " if (VV(jj) <= C(jj))\n"); fprintf(fp, " YY(jj) = YY(jj) + (Z(jj,kk)-XM(jj))^2;\n"); fprintf(fp, " VV(jj) = VV(jj) + 1;\n"); fprintf(fp, " end;\n"); fprintf(fp, " end;\n"); fprintf(fp, " if (VV(jj) > 1)\n"); fprintf(fp, " YY(jj) = sqrt(YY(jj) / (VV(jj)-1));\n"); fprintf(fp, " end;\n"); fprintf(fp, "end;\n"); if (psPlotTool_ == 1) fprintf(fp, "// plot sequence of Morris plot\n"); else fprintf(fp, "%% plot sequence of Morris plot\n"); fprintf(fp, "last = max(C);\n"); fprintf(fp, "inc = floor((last - 2)/3);\n"); fprintf(fp, "if (inc < 1)\n"); fprintf(fp, " inc = 1;\n"); fprintf(fp, "end;\n"); fprintf(fp, "list = [last : -inc : 2];\n"); fprintf(fp, "if (length(list) > 4)\n"); fprintf(fp, " list = list(1:4);\n"); fprintf(fp, "end;\n"); if (psPlotTool_ == 1) fprintf(fp, "list = gsort(list,'g','i');\n"); else fprintf(fp, "list = sort(list);\n"); fprintf(fp, "list = unique(list);\n"); fprintf(fp, "count = length(list);\n"); fprintf(fp, "if (plotAll == 1)\n"); if (psPlotTool_ == 1) fprintf(fp, "scf(1)\n"); else fprintf(fp, "figure(1)\n"); fprintf(fp, "for mm = 1 : count\n"); fprintf(fp, " ii = list(mm);\n"); fprintf(fp, " XX = zeros(nn,1);\n"); fprintf(fp, " XM = zeros(nn,1);\n"); fprintf(fp, " YY = zeros(nn,1);\n"); fprintf(fp, " VV = zeros(nn,1);\n"); fprintf(fp, " for jj = 1 : nn\n"); fprintf(fp, " cnt = 0;\n"); fprintf(fp, " for kk = 1 : ii\n"); fprintf(fp, " if (cnt <= C(jj))\n"); fprintf(fp, " XM(jj) = XM(jj) + Z(jj,kk);\n"); fprintf(fp, " XX(jj) = XX(jj) + abs(Z(jj,kk));\n"); fprintf(fp, " cnt = cnt + 1;\n"); fprintf(fp, " end;\n"); fprintf(fp, " end;\n"); fprintf(fp, " if (cnt > 0)\n"); fprintf(fp, " XM(jj) = XM(jj) / cnt;\n"); fprintf(fp, " XX(jj) = XX(jj) / cnt;\n"); fprintf(fp, " end;\n"); fprintf(fp, " cnt = 0;\n"); fprintf(fp, " for kk = 1 : ii\n"); fprintf(fp, " if (cnt <= C(jj))\n"); fprintf(fp, " YY(jj) = YY(jj) + (Z(jj,kk)-XM(jj))^2;\n"); fprintf(fp, " cnt = cnt + 1;\n"); fprintf(fp, " end;\n"); fprintf(fp, " end;\n"); fprintf(fp, " if (cnt > 1)\n"); fprintf(fp, " YY(jj) = sqrt(YY(jj) / (cnt-1));\n"); fprintf(fp, " end;\n"); fprintf(fp, " end;\n"); fprintf(fp, " subplot(2,2,mm) \n"); fprintf(fp, " bar(XX,0.8)\n"); fwritePlotAxes(fp); fprintf(fp," pStr=sprintf('%%d replications',list(mm));\n"); if (psPlotTool_ == 1) { fprintf(fp, " a = gca();\n"); fprintf(fp, " a.title.text = pStr;\n"); fprintf(fp, " a.title.font_size = 3;\n"); fprintf(fp, " a.title.font_style = 4;\n"); } else fprintf(fp," title(pStr);\n"); fprintf(fp,"Xmin = min(XX) - (max(XX) - min(XX)) * 0.1;\n"); fprintf(fp,"Xmax = max(XX) + (max(XX) - min(XX)) * 0.1;\n"); if (psPlotTool_ == 1) { fprintf(fp, " a=gca();\n"); fprintf(fp, " a.data_bounds=[0, Xmin; nn+1, Xmax];\n"); fprintf(fp, " a.x_ticks(2) = [1:nn]';\n"); fprintf(fp, " a.x_ticks(3) = Str';\n"); fprintf(fp, " a.x_label.font_size = 3;\n"); fprintf(fp, " a.x_label.font_style = 4;\n"); } else { fprintf(fp," axis([0 nn+1 Xmin Xmax])\n"); fprintf(fp, " set(gca,'XTickLabel',[]);\n"); fprintf(fp, " th=text(1:nn, repmat(Xmin-0.1*(Xmax-Xmin),nn,1),Str,"); fprintf(fp, "'HorizontalAlignment','left','rotation',90);\n"); fprintf(fp, " set(th, 'fontsize', 12)\n"); fprintf(fp, " set(th, 'fontweight', 'bold')\n"); } fwritePlotYLabel(fp, "Modified Means (of gradients)"); fprintf(fp, "end;\n"); if (psPlotTool_ == 1) fprintf(fp, "scf(2)\n"); else fprintf(fp, "figure(2)\n"); fprintf(fp, "for mm = 1 : count\n"); fprintf(fp, " ii = list(mm);\n"); fprintf(fp, " XX = zeros(nn,1);\n"); fprintf(fp, " XM = zeros(nn,1);\n"); fprintf(fp, " YY = zeros(nn,1);\n"); fprintf(fp, " VV = zeros(nn,1);\n"); fprintf(fp, " for jj = 1 : nn\n"); fprintf(fp, " cnt = 0;\n"); fprintf(fp, " for kk = 1 : ii\n"); fprintf(fp, " if (cnt <= C(jj))\n"); fprintf(fp, " XM(jj) = XM(jj) + Z(jj,kk);\n"); fprintf(fp, " XX(jj) = XX(jj) + abs(Z(jj,kk));\n"); fprintf(fp, " cnt = cnt + 1;\n"); fprintf(fp, " end;\n"); fprintf(fp, " end;\n"); fprintf(fp, " if (cnt > 0)\n"); fprintf(fp, " XM(jj) = XM(jj) / cnt;\n"); fprintf(fp, " XX(jj) = XX(jj) / cnt;\n"); fprintf(fp, " end;\n"); fprintf(fp, " cnt = 0;\n"); fprintf(fp, " for kk = 1 : ii\n"); fprintf(fp, " if (cnt <= C(jj))\n"); fprintf(fp, " YY(jj) = YY(jj) + (Z(jj,kk)-XM(jj))^2;\n"); fprintf(fp, " cnt = cnt + 1;\n"); fprintf(fp, " end;\n"); fprintf(fp, " end;\n"); fprintf(fp, " if (cnt > 1)\n"); fprintf(fp, " YY(jj) = sqrt(YY(jj) / (cnt-1));\n"); fprintf(fp, " end;\n"); fprintf(fp, " end;\n"); fprintf(fp, " subplot(2,2,mm) \n"); fprintf(fp, " bar(YY,0.8)\n"); fprintf(fp," Ymin = 0.0;\n"); fprintf(fp," Ymax = max(YY) + (max(YY) - min(YY)) * 0.1;\n"); fwritePlotAxes(fp); if (psPlotTool_ == 1) { fprintf(fp, "a=gca();\n"); fprintf(fp, "a.data_bounds=[0, Ymin; nn+1, Ymax];\n"); fprintf(fp, " a.x_ticks(2) = [1:nn]';\n"); fprintf(fp, " a.x_ticks(3) = Str';\n"); fprintf(fp, " a.x_label.font_size = 3;\n"); fprintf(fp, " a.x_label.font_style = 4;\n"); } else { fprintf(fp," axis([0 nn+1 Ymin Ymax])\n"); fprintf(fp, " set(gca,'XTickLabel',[]);\n"); fprintf(fp, " th=text(1:nn, repmat(Ymin-0.1*(Ymax-Ymin),nn,1),Str,"); fprintf(fp, "'HorizontalAlignment','left','rotation',90);\n"); fprintf(fp, " set(th, 'fontsize', 12)\n"); fprintf(fp, " set(th, 'fontweight', 'bold')\n"); } fwritePlotYLabel(fp, "Std. Devs."); fprintf(fp," pStr=sprintf('%%d replications',list(mm));\n"); if (psPlotTool_ == 1) { fprintf(fp, "a = gca();\n"); fprintf(fp, "a.title.text = pStr;\n"); fprintf(fp, "a.title.font_size = 3;\n"); fprintf(fp, "a.title.font_style = 4;\n"); } else fprintf(fp," title(pStr);\n"); fprintf(fp, "end;\n"); fprintf(fp, "end;\n"); fprintf(fp, "if (plotAll == 1)\n"); if (psPlotTool_ == 1) fprintf(fp, "scf(3)\n"); else fprintf(fp, "figure(3)\n"); fprintf(fp, "end;\n"); fprintf(fp, "Y = [\n"); for (ii = 0; ii < nInputs; ii++) fprintf(fp, "%24.16e\n", stds[ii]); fprintf(fp, "];\n"); fprintf(fp, "X = [\n"); for (ii = 0; ii < nInputs; ii++) fprintf(fp, "%24.16e\n", modifiedMeans[ii]); fprintf(fp, "];\n"); fprintf(fp, "plot(X,Y,'*','MarkerSize',12)\n"); if (psPlotTool_ == 1) { fprintf(fp, "a=gca();\n"); printf("Morris scilab plot: labels to be put in later.\n"); } else { fprintf(fp, "text(X*1.01,Y,{"); if (iNames != NULL) { for (ii = 0; ii < nInputs-1; ii++) fprintf(fp, "'%s',",iNames[ii]); fprintf(fp, "'%s'},'FontWeight','bold','FontSize',12)\n", iNames[nInputs-1]); } else { for (ii = 0; ii < nInputs-1; ii++) fprintf(fp, "'X%d',",ii+1); fprintf(fp, "'X%d'},'FontWeight','bold','FontSize',12)\n",nInputs); } } fprintf(fp, "Xmin = min(X) - (max(X) - min(X)) * 0.1;\n"); fprintf(fp, "Ymin = min(Y) - (max(Y) - min(Y)) * 0.1;\n"); fprintf(fp, "Xmax = max(X) + (max(X) - min(X)) * 0.1;\n"); fprintf(fp, "Ymax = max(Y) + (max(Y) - min(Y)) * 0.1;\n"); if (psPlotTool_ == 1) { fprintf(fp, "a=gca();\n"); fprintf(fp, "a.data_bounds=[Xmin, Ymin; Xmax, Ymax];\n"); } else fprintf(fp, "axis([Xmin Xmax Ymin Ymax])\n"); fwritePlotAxes(fp); fwritePlotXLabel(fp, "Modified Means (of gradients)"); fwritePlotYLabel(fp, "Std Deviations (of gradients)"); sprintf(pString, "Modified Morris Diagram for Output %d", outputID+1); fwritePlotTitle(fp, pString); fprintf(fp, "if (maxFlag == 1)\n"); if (psPlotTool_ == 1) fprintf(fp, " scf(4)\n"); else fprintf(fp, " figure(4)\n"); fprintf(fp, " bar(Xm, 0.8)\n"); fprintf(fp," Ymin = 0.0;\n"); fprintf(fp," Ymax = max(YY) + (max(YY) - min(YY)) * 0.1;\n"); fwritePlotAxes(fp); if (psPlotTool_ == 1) { fprintf(fp, " a=gca();\n"); fprintf(fp, " a.data_bounds=[0, Ymin; nn+1, Ymax];\n"); fprintf(fp, " a.x_ticks(2) = [1:nn]';\n"); fprintf(fp, " a.x_ticks(3) = Str';\n"); fprintf(fp, " a.x_label.font_size = 3;\n"); fprintf(fp, " a.x_label.font_style = 4;\n"); } else { fprintf(fp, " axis([0 nn+1 Ymin Ymax])\n"); fprintf(fp, " set(gca,'XTickLabel',[]);\n"); fprintf(fp, " th=text(1:nn, repmat(Ymin-0.1*(Ymax-Ymin),nn,1),Str,"); fprintf(fp, "'HorizontalAlignment','left','rotation',90);\n"); fprintf(fp, " set(th, 'fontsize', 12)\n"); fprintf(fp, " set(th, 'fontweight', 'bold')\n"); } fwritePlotYLabel(fp, " Max Absolute Gradients"); fprintf(fp, "end;\n"); printOutTS(PL_INFO, "MOAT screening diagram file = %s\n", moatFile); fclose(fp); printEquals(PL_INFO, 0); return 0; } // ************************************************************************ // create scatter plot matlab file // ------------------------------------------------------------------------ int MOATAnalyzer::createScatterFile(int nSamples, int nInputs, double *Y, double *X, int *indices, char **iNames) { int iD, cnt, ii; char winput[500], scatterFile[500], pString[500]; FILE *fp; printOutTS(PL_INFO,"Scatter plot gives yet another way of examining\n"); printOutTS(PL_INFO,"parameter importance. It gives you details on the\n"); printOutTS(PL_INFO,"individual gradients used to compute the means. It\n"); printOutTS(PL_INFO,"can help detect outliers, trends, and interactions.\n"); printOutTS(PL_INFO,"E.g. if a gradient for one input is way off, then\n"); printOutTS(PL_INFO," it may be an outlier.\n"); printOutTS(PL_INFO,"E.g. if the red and green points are clustered\n"); printOutTS(PL_INFO," tightly together, then this input is linear.\n"); printOutTS(PL_INFO,"E.g. if the red and green points are clustered\n"); printOutTS(PL_INFO," tightly but the red and green clusters are\n"); printOutTS(PL_INFO," clearly separated, then there is likely to be\n"); printOutTS(PL_INFO," self-nonlinearity in this input, but it has\n"); printOutTS(PL_INFO," little interaction with other inputs.\n"); printOutTS(PL_INFO,"E.g. if the red and green points are widely spread\n"); printOutTS(PL_INFO," and are not clearly separated, no conclusion\n"); printOutTS(PL_INFO," can be made.\n"); printOutTS(PL_INFO,"Color to level mapping :\n"); printOutTS(PL_INFO,"low to high: red, green, blue, magenta, cyan dots\n"); printOutTS(PL_INFO,"low to high: red, green, blue, magenta, cyan 'x'\n"); sprintf(pString,"Create scatter plot ? (y or n) "); getString(pString, winput); if (winput[0] != 'y') return 0; sprintf(pString, "Enter matlab/scilab scatter plot file name (no extension): "); getString(pString, scatterFile); cnt = strlen(scatterFile); if (cnt > 500) { printOutTS(PL_ERROR, "ERROR: file name too long.\n"); exit(1); } scatterFile[cnt-1] = '.'; if (psPlotTool_ == 1) { scatterFile[cnt] = 's'; scatterFile[cnt+1] = 'c'; scatterFile[cnt+2] = 'i'; scatterFile[cnt+3] = '\0'; } else { scatterFile[cnt] = 'm'; scatterFile[cnt+1] = '\0'; } fp = fopen(scatterFile, "w"); if (fp == NULL) { printOutTS(PL_ERROR,"MOATAnalysis: cannot open scatterplot file %s\n", scatterFile); return 0; } if (psPlotTool_ == 1) { fprintf(fp, "// This file contains individual gradient info.\n"); fprintf(fp, "// The gradients are normalized for the range.\n"); fprintf(fp, "// To display only the important inputs, first\n"); fprintf(fp, "// create and run the bootstrapped analysis\n"); fprintf(fp, "// which creates an I2 array. \n"); } else { fprintf(fp, "%% This file contains individual gradient info.\n"); fprintf(fp, "%% The gradients are normalized for the range.\n"); fprintf(fp, "%% To display only the important inputs, first\n"); fprintf(fp, "%% create and run the bootstrapped analysis\n"); fprintf(fp, "%% which creates an I2 array. \n"); } fprintf(fp, "sortFlag = 0;\n"); fprintf(fp, "if (sortFlag == 1);\n"); fprintf(fp, " nn = length(I2);\n"); fprintf(fp, "else\n"); fprintf(fp, " nn = %d;\n", nInputs); fprintf(fp, "end\n"); fprintf(fp, "A = [\n"); for (iD = 1; iD < nSamples; iD++) { if (Y[iD] != PSUADE_UNDEFINED) fprintf(fp,"%4d %24.16e %24.16e %d\n",indices[iD]+1,Y[iD],X[iD],iD+1); } fprintf(fp, "];\n"); if (iNames == NULL) { fprintf(fp, "Str = {"); for (ii = 0; ii < nInputs-1; ii++) fprintf(fp,"'X%d',",ii+1); fprintf(fp,"'X%d'};\n",nInputs); } else { fprintf(fp, "Str = {"); for (ii = 0; ii < nInputs-1; ii++) { if (iNames[ii] != NULL) fprintf(fp,"'%s',",iNames[ii]); else fprintf(fp,"'X%d',",ii+1); } if (iNames[nInputs-1] != NULL) fprintf(fp,"'%s'};\n",iNames[nInputs-1]); else fprintf(fp,"'X%d'};\n",nInputs); } fprintf(fp, "if (sortFlag == 1);\n"); fprintf(fp, " Str = Str(I2);\n"); fprintf(fp, "end\n"); fwritePlotCLF(fp); if (psPlotTool_ == 1) fprintf(fp, "set(gca(),\"auto_clear\",\"off\")\n"); else fprintf(fp, "hold on\n"); fprintf(fp, "ymin = min(A(:,2));\n"); fprintf(fp, "ymax = max(A(:,2));\n"); if (psPlotTool_ == 1) { fprintf(fp, "a=gca();\n"); fprintf(fp, "a.data_bounds=[0, ymin; nn+1, ymax];\n"); fprintf(fp, "newtick = a.x_ticks;\n"); fprintf(fp, "newtick(2) = [1:nn]';\n"); fprintf(fp, "newtick(3) = Str';\n"); fprintf(fp, "a.x_ticks = newtick;\n"); fprintf(fp, "a.x_label.font_size = 3;\n"); fprintf(fp, "a.x_label.font_style = 4;\n"); } else { fprintf(fp, "axis([0 nn+1 ymin ymax])\n"); fprintf(fp, "set(gca,'XTickLabel',[]);\n"); fprintf(fp, "th=text(1:nn, repmat(ymin-0.05*(ymax-ymin),nn,1),Str,"); fprintf(fp, "'HorizontalAlignment','left','rotation',90);\n"); fprintf(fp, "set(th, 'fontsize', 12)\n"); fprintf(fp, "set(th, 'fontweight', 'bold')\n"); } fprintf(fp, "for ii2 = 1 : nn\n"); fprintf(fp, " if (sortFlag == 1)\n"); fprintf(fp, " ii = I2(ii2);\n"); fprintf(fp, " else\n"); fprintf(fp, " ii = ii2;\n"); fprintf(fp, " end;\n"); fprintf(fp, " inds = find(A(:,1)==ii);\n"); fprintf(fp, " leng = length(inds);\n"); fprintf(fp, " if (leng > 0)\n"); if (psPlotTool_ == 1) fprintf(fp, " [AA,II] = gsort(A(inds,3),'g','i');\n"); else fprintf(fp, " [AA,II] = sort(A(inds,3));\n"); fprintf(fp, " if (sortFlag == 1)\n"); fprintf(fp, " xx = ii2;\n"); fprintf(fp, " else\n"); fprintf(fp, " xx = A(inds(II(1)),1);\n"); fprintf(fp, " end;\n"); fprintf(fp, " yy = A(inds(II(1)),2);\n"); fprintf(fp, " plot(xx,yy,'r.','MarkerSize',24)\n"); fprintf(fp, " for jj = 2 : leng\n"); fprintf(fp, " x1 = A(inds(II(jj)),3);\n"); fprintf(fp, " x2 = A(inds(II(jj-1)),3);\n"); fprintf(fp, " if x1 ~= x2\n"); fprintf(fp, " break;\n"); fprintf(fp, " else\n"); fprintf(fp, " if (sortFlag == 1)\n"); fprintf(fp, " xx = ii2;\n"); fprintf(fp, " else\n"); fprintf(fp, " xx = A(inds(II(jj)),1);\n"); fprintf(fp, " end;\n"); fprintf(fp, " yy = A(inds(II(jj)),2);\n"); fprintf(fp, " plot(xx,yy,'r.','MarkerSize',24)\n"); fprintf(fp, " if (jj == leng)\n"); fprintf(fp, " jj = jj + 1;\n"); fprintf(fp, " end;\n"); fprintf(fp, " end;\n"); fprintf(fp, " end;\n"); fprintf(fp, " if (jj <= leng)\n"); fprintf(fp, " if (sortFlag == 1)\n"); fprintf(fp, " xx = ii2;\n"); fprintf(fp, " else\n"); fprintf(fp, " xx = A(inds(II(jj)),1);\n"); fprintf(fp, " end;\n"); fprintf(fp, " yy = A(inds(II(jj)),2);\n"); fprintf(fp, " plot(xx+0.1,yy,'g.','MarkerSize',24)\n"); fprintf(fp, " end;\n"); fprintf(fp, " for kk = jj+1 : leng\n"); fprintf(fp, " x1 = A(inds(II(kk)),3);\n"); fprintf(fp, " x2 = A(inds(II(kk-1)),3);\n"); fprintf(fp, " if x1 ~= x2\n"); fprintf(fp, " break;\n"); fprintf(fp, " else\n"); fprintf(fp, " if (sortFlag == 1)\n"); fprintf(fp, " xx = ii2;\n"); fprintf(fp, " else\n"); fprintf(fp, " xx = A(inds(II(kk)),1);\n"); fprintf(fp, " end;\n"); fprintf(fp, " yy = A(inds(II(kk)),2);\n"); fprintf(fp, " plot(xx+0.1,yy,'g.','MarkerSize',24)\n"); fprintf(fp, " if (kk == leng)\n"); fprintf(fp, " kk = kk + 1;\n"); fprintf(fp, " end;\n"); fprintf(fp, " end;\n"); fprintf(fp, " end;\n"); fprintf(fp, " if (kk <= leng)\n"); fprintf(fp, " if (sortFlag == 1)\n"); fprintf(fp, " xx = ii2;\n"); fprintf(fp, " else\n"); fprintf(fp, " xx = A(inds(II(kk)),1);\n"); fprintf(fp, " end;\n"); fprintf(fp, " yy = A(inds(II(kk)),2);\n"); fprintf(fp, " plot(xx+0.2,yy,'b.','MarkerSize',24)\n"); fprintf(fp, " end;\n"); fprintf(fp, " for jj = kk+1 : leng\n"); fprintf(fp, " x1 = A(inds(II(jj)),3);\n"); fprintf(fp, " x2 = A(inds(II(jj-1)),3);\n"); fprintf(fp, " if x1 ~= x2\n"); fprintf(fp, " break;\n"); fprintf(fp, " else\n"); fprintf(fp, " if (sortFlag == 1)\n"); fprintf(fp, " xx = ii2;\n"); fprintf(fp, " else\n"); fprintf(fp, " xx = A(inds(II(jj)),1);\n"); fprintf(fp, " end;\n"); fprintf(fp, " yy = A(inds(II(jj)),2);\n"); fprintf(fp, " plot(xx+0.2,yy,'b.','MarkerSize',24)\n"); fprintf(fp, " if (jj == leng)\n"); fprintf(fp, " jj = jj + 1;\n"); fprintf(fp, " end;\n"); fprintf(fp, " end;\n"); fprintf(fp, " end;\n"); fprintf(fp, " if (jj <= leng)\n"); fprintf(fp, " xx = A(inds(II(jj)),1);\n"); fprintf(fp, " if (sortFlag == 1)\n"); fprintf(fp, " xx = ii2;\n"); fprintf(fp, " else\n"); fprintf(fp, " xx = A(inds(II(jj)),1);\n"); fprintf(fp, " end;\n"); fprintf(fp, " yy = A(inds(II(jj)),2);\n"); fprintf(fp, " plot(xx+0.3,yy,'m.','MarkerSize',24)\n"); fprintf(fp, " end;\n"); fprintf(fp, " for kk = jj+1 : leng\n"); fprintf(fp, " x1 = A(inds(II(kk)),3);\n"); fprintf(fp, " x2 = A(inds(II(kk-1)),3);\n"); fprintf(fp, " if x1 ~= x2\n"); fprintf(fp, " break;\n"); fprintf(fp, " else\n"); fprintf(fp, " if (sortFlag == 1)\n"); fprintf(fp, " xx = ii2;\n"); fprintf(fp, " else\n"); fprintf(fp, " xx = A(inds(II(kk)),1);\n"); fprintf(fp, " end;\n"); fprintf(fp, " yy = A(inds(II(kk)),2);\n"); fprintf(fp, " plot(xx+0.3,yy,'m.','MarkerSize',24)\n"); fprintf(fp, " if (kk == leng)\n"); fprintf(fp, " kk = kk + 1;\n"); fprintf(fp, " end;\n"); fprintf(fp, " end;\n"); fprintf(fp, " end;\n"); fprintf(fp, " if (jj <= leng)\n"); fprintf(fp, " xx = A(inds(II(jj)),1);\n"); fprintf(fp, " if (sortFlag == 1)\n"); fprintf(fp, " xx = ii2;\n"); fprintf(fp, " else\n"); fprintf(fp, " xx = A(inds(II(jj)),1);\n"); fprintf(fp, " end;\n"); fprintf(fp, " yy = A(inds(II(jj)),2);\n"); fprintf(fp, " plot(xx+0.4,yy,'rx','MarkerSize',16)\n"); fprintf(fp, " end;\n"); fprintf(fp, " for kk = jj+1 : leng\n"); fprintf(fp, " x1 = A(inds(II(kk)),3);\n"); fprintf(fp, " x2 = A(inds(II(kk-1)),3);\n"); fprintf(fp, " if x1 ~= x2\n"); fprintf(fp, " break;\n"); fprintf(fp, " else\n"); fprintf(fp, " if (sortFlag == 1)\n"); fprintf(fp, " xx = ii2;\n"); fprintf(fp, " else\n"); fprintf(fp, " xx = A(inds(II(kk)),1);\n"); fprintf(fp, " end;\n"); fprintf(fp, " yy = A(inds(II(kk)),2);\n"); fprintf(fp, " plot(xx+0.4,yy,'rx','MarkerSize',16)\n"); fprintf(fp, " if (kk == leng)\n"); fprintf(fp, " kk = kk + 1;\n"); fprintf(fp, " end;\n"); fprintf(fp, " end;\n"); fprintf(fp, " end;\n"); fprintf(fp, " if (jj <= leng)\n"); fprintf(fp, " xx = A(inds(II(jj)),1);\n"); fprintf(fp, " if (sortFlag == 1)\n"); fprintf(fp, " xx = ii2;\n"); fprintf(fp, " else\n"); fprintf(fp, " xx = A(inds(II(jj)),1);\n"); fprintf(fp, " end;\n"); fprintf(fp, " yy = A(inds(II(jj)),2);\n"); fprintf(fp, " plot(xx+0.4,yy,'gx','MarkerSize',16)\n"); fprintf(fp, " end;\n"); fprintf(fp, " for kk = jj+1 : leng\n"); fprintf(fp, " x1 = A(inds(II(kk)),3);\n"); fprintf(fp, " x2 = A(inds(II(kk-1)),3);\n"); fprintf(fp, " if x1 ~= x2\n"); fprintf(fp, " break;\n"); fprintf(fp, " else\n"); fprintf(fp, " if (sortFlag == 1)\n"); fprintf(fp, " xx = ii2;\n"); fprintf(fp, " else\n"); fprintf(fp, " xx = A(inds(II(kk)),1);\n"); fprintf(fp, " end;\n"); fprintf(fp, " yy = A(inds(II(kk)),2);\n"); fprintf(fp, " plot(xx+0.4,yy,'gx','MarkerSize',16)\n"); fprintf(fp, " if (kk == leng)\n"); fprintf(fp, " kk = kk + 1;\n"); fprintf(fp, " end;\n"); fprintf(fp, " end;\n"); fprintf(fp, " end;\n"); fprintf(fp, " if (jj <= leng)\n"); fprintf(fp, " xx = A(inds(II(jj)),1);\n"); fprintf(fp, " if (sortFlag == 1)\n"); fprintf(fp, " xx = ii2;\n"); fprintf(fp, " else\n"); fprintf(fp, " xx = A(inds(II(jj)),1);\n"); fprintf(fp, " end;\n"); fprintf(fp, " yy = A(inds(II(jj)),2);\n"); fprintf(fp, " plot(xx+0.5,yy,'bx','MarkerSize',16)\n"); fprintf(fp, " end;\n"); fprintf(fp, " for kk = jj+1 : leng\n"); fprintf(fp, " x1 = A(inds(II(kk)),3);\n"); fprintf(fp, " x2 = A(inds(II(kk-1)),3);\n"); fprintf(fp, " if x1 ~= x2\n"); fprintf(fp, " break;\n"); fprintf(fp, " else\n"); fprintf(fp, " if (sortFlag == 1)\n"); fprintf(fp, " xx = ii2;\n"); fprintf(fp, " else\n"); fprintf(fp, " xx = A(inds(II(kk)),1);\n"); fprintf(fp, " end;\n"); fprintf(fp, " yy = A(inds(II(kk)),2);\n"); fprintf(fp, " plot(xx+0.5,yy,'bx','MarkerSize',16)\n"); fprintf(fp, " if (kk == leng)\n"); fprintf(fp, " kk = kk + 1;\n"); fprintf(fp, " end;\n"); fprintf(fp, " end;\n"); fprintf(fp, " end;\n"); fprintf(fp, " if (jj <= leng)\n"); fprintf(fp, " xx = A(inds(II(jj)),1);\n"); fprintf(fp, " if (sortFlag == 1)\n"); fprintf(fp, " xx = ii2;\n"); fprintf(fp, " else\n"); fprintf(fp, " xx = A(inds(II(jj)),1);\n"); fprintf(fp, " end;\n"); fprintf(fp, " yy = A(inds(II(jj)),2);\n"); fprintf(fp, " plot(xx+0.6,yy,'mx','MarkerSize',16)\n"); fprintf(fp, " end;\n"); fprintf(fp, " for kk = jj+1 : leng\n"); fprintf(fp, " x1 = A(inds(II(kk)),3);\n"); fprintf(fp, " x2 = A(inds(II(kk-1)),3);\n"); fprintf(fp, " if x1 ~= x2\n"); fprintf(fp, " break;\n"); fprintf(fp, " else\n"); fprintf(fp, " if (sortFlag == 1)\n"); fprintf(fp, " xx = ii2;\n"); fprintf(fp, " else\n"); fprintf(fp, " xx = A(inds(II(kk)),1);\n"); fprintf(fp, " end;\n"); fprintf(fp, " yy = A(inds(II(kk)),2);\n"); fprintf(fp, " plot(xx+0.6,yy,'mx','MarkerSize',16)\n"); fprintf(fp, " if (kk == leng)\n"); fprintf(fp, " kk = kk + 1;\n"); fprintf(fp, " end;\n"); fprintf(fp, " end;\n"); fprintf(fp, " end;\n"); fprintf(fp, " if (jj <= leng)\n"); fprintf(fp, " xx = A(inds(II(jj)),1);\n"); fprintf(fp, " if (sortFlag == 1)\n"); fprintf(fp, " xx = ii2;\n"); fprintf(fp, " else\n"); fprintf(fp, " xx = A(inds(II(jj)),1);\n"); fprintf(fp, " end;\n"); fprintf(fp, " yy = A(inds(II(jj)),2);\n"); fprintf(fp, " plot(xx+0.7,yy,'cx','MarkerSize',16)\n"); fprintf(fp, " end;\n"); fprintf(fp, " for kk = jj+1 : leng\n"); fprintf(fp, " x1 = A(inds(II(kk)),3);\n"); fprintf(fp, " x2 = A(inds(II(kk-1)),3);\n"); fprintf(fp, " if x1 ~= x2\n"); fprintf(fp, " break;\n"); fprintf(fp, " else\n"); fprintf(fp, " if (sortFlag == 1)\n"); fprintf(fp, " xx = ii2;\n"); fprintf(fp, " else\n"); fprintf(fp, " xx = A(inds(II(kk)),1);\n"); fprintf(fp, " end;\n"); fprintf(fp, " yy = A(inds(II(kk)),2);\n"); fprintf(fp, " plot(xx+0.7,yy,'cx','MarkerSize',16)\n"); fprintf(fp, " if (kk == leng)\n"); fprintf(fp, " kk = kk + 1;\n"); fprintf(fp, " end;\n"); fprintf(fp, " end;\n"); fprintf(fp, " end;\n"); fprintf(fp, " if (kk <= leng)\n"); fprintf(fp, " for jj = kk : leng\n"); fprintf(fp, " if (sortFlag == 1)\n"); fprintf(fp, " xx = ii2;\n"); fprintf(fp, " else\n"); fprintf(fp, " xx = A(inds(II(jj)),1);\n"); fprintf(fp, " end;\n"); fprintf(fp, " yy = A(inds(II(jj)),2);\n"); fprintf(fp, " plot(xx+0.8,yy,'k.','MarkerSize',24)\n"); fprintf(fp, " end;\n"); fprintf(fp, " end;\n"); fprintf(fp, " end;\n"); fprintf(fp, "end;\n"); fprintf(fp, "for ii2 = 1 : nn\n"); fprintf(fp, " if (sortFlag == 1)\n"); fprintf(fp, " ii = I2(ii2);\n"); fprintf(fp, " else\n"); fprintf(fp, " ii = ii2;\n"); fprintf(fp, " end;\n"); fprintf(fp, " inds = find(A(:,1)==ii);\n"); fprintf(fp, " if length(inds) > 0\n"); fprintf(fp, " asum = sum(A(inds,2))/length(inds);\n"); if (psPlotTool_ == 1) fprintf(fp, " plot(ii2,asum,'kp','MarkerSize',15);\n"); else fprintf(fp, " plot(ii2,asum,'kh','MarkerSize',15);\n"); fprintf(fp, " end;\n"); fprintf(fp, "end;\n"); fwritePlotAxes(fp); fwritePlotYLabel(fp, "Individual Gradients"); fwritePlotTitle(fp, "Scatter Plots of Gradients (lo to hi: r,g,b,m,c)"); fprintf(fp,"disp('from lo to hi : red,green,blue,magenta,cyan, ..')\n"); fprintf(fp, "disp('hexagrams: means of the gradients')\n"); if (psPlotTool_ == 1) fprintf(fp, "set(gca(),\"auto_clear\",\"on\")\n"); else fprintf(fp, "hold off\n"); fclose(fp); printOutTS(PL_INFO, "MOAT scatter plot file = %s.\n", scatterFile); printEquals(PL_INFO, 0); return 0; } // ************************************************************************ // create bootstrap mean plot matlab file // ------------------------------------------------------------------------ int MOATAnalyzer::createBootstrapFile(int nSamples, int nInputs, double *Y, double *X, int *indices, char **iNames) { int nReps, ii, is, jj, ib, input, count, index; double **YGs; char winput[500], bootstrapFile[500], pString[500]; FILE *fp; psIVector validCnts; psVector means, stds, bArray; // range check nInputs by Bill Oliver if (nInputs <= 0) { printOutTS(PL_ERROR, "nInputs is <= 0 in file %s, line %d. Returning -1\n", __FILE__, __LINE__); return -1; } printf("MOATAnalyzer: Creating modified mean plot ... \n"); if (psPlotTool_ == 1) strcpy(bootstrapFile, "scilabmoatbs.sci"); else strcpy(bootstrapFile, "matlabmoatbs.m"); fp = fopen(bootstrapFile, "w"); if (fp == NULL) { printOutTS(PL_ERROR, "MOATAnalysis: cannot write to plot file %s\n", bootstrapFile); return 0; } nReps = nSamples / (nInputs + 1); validCnts.setLength(nInputs); for (is = 0; is < nSamples; is++) { if (Y[is] != PSUADE_UNDEFINED && indices[is] >= 0) validCnts[indices[is]]++; } for (ii = 0; ii < nInputs; ii++) if (validCnts[ii] > nReps) nReps = validCnts[ii]; YGs = new double*[nInputs]; checkAllocate(YGs, "YGs in MOAT::createBootstrapFile"); for (ii = 0; ii < nInputs; ii++) { if (validCnts[ii] > 0) YGs[ii] = new double[validCnts[ii]]; else YGs[ii] = NULL; } for (ii = 0; ii < nInputs; ii++) validCnts[ii] = 0; for (is = 0; is < nSamples; is++) { if (Y[is] != PSUADE_UNDEFINED && indices[is] >= 0) { input = indices[is]; count = validCnts[input]++; YGs[input][count] = PABS(Y[is]); } } bArray.setLength(1000); means.setLength(nInputs); stds.setLength(nInputs); for (ii = 0; ii < nInputs; ii++) { if (validCnts[ii] >= 4) { for (ib = 0; ib < 1000; ib++) { bArray[ib] = 0.0; for (jj = 0; jj < validCnts[ii]; jj++) { index = PSUADE_rand() % validCnts[ii]; bArray[ib] += YGs[ii][index]; } bArray[ib] /= validCnts[ii]; } means[ii] = 0.0; for (ib = 0; ib < 1000; ib++) means[ii] += bArray[ib]; means[ii] /= 1000.0; stds[ii] = 0.0; for (ib = 0; ib < 1000; ib++) stds[ii] += pow(bArray[ib] - means[ii], 2.0); stds[ii] /= (1000.0 - 1.0); stds[ii] = sqrt(stds[ii]); } else { printOutTS(PL_WARN, "MOATAnalysis WARNING: input %d needs >= 4 replications\n", ii+1); printOutTS(PL_WARN, " to perform bootstrapping.\n"); stds[ii] = 0.0; means[ii] = 0.0; for (jj = 0; jj < validCnts[ii]; jj++) means[ii] += YGs[ii][jj]; if (validCnts[ii] > 0) means[ii] /= (double) validCnts[ii]; } } sprintf(pString,"This file contains modified means of gradients"); fwriteComment(fp, pString); sprintf(pString,"and also their spreads based on bootstraping."); fwriteComment(fp, pString); sprintf(pString,"to select the most important ones to display,"); fwriteComment(fp, pString); sprintf(pString,"set sortFlag = 1 and set nn to be the number"); fwriteComment(fp, pString); sprintf(pString,"of inputs to display.\n"); fwriteComment(fp, pString); fprintf(fp, "sortFlag = 0;\n"); fprintf(fp, "nn = %d;\n", nInputs); fprintf(fp, "Means = [\n"); for (ii = 0; ii < nInputs; ii++) fprintf(fp,"%24.16e\n", means[ii]); fprintf(fp, "];\n"); fprintf(fp, "Stds = [\n"); for (ii = 0; ii < nInputs; ii++) fprintf(fp,"%24.16e\n", stds[ii]); fprintf(fp, "];\n"); if (iNames == NULL) { fprintf(fp, " Str = {"); for (ii = 0; ii < nInputs-1; ii++) fprintf(fp,"'X%d',",ii+1); fprintf(fp,"'X%d'};\n",nInputs); } else { fprintf(fp, " Str = {"); for (ii = 0; ii < nInputs-1; ii++) { if (iNames[ii] != NULL) fprintf(fp,"'%s',",iNames[ii]); else fprintf(fp,"'X%d',",ii+1); } if (iNames[nInputs-1] != NULL) fprintf(fp,"'%s'};\n",iNames[nInputs-1]); else fprintf(fp,"'X%d'};\n",nInputs); } fwritePlotCLF(fp); fprintf(fp, "if (sortFlag == 1)\n"); if (psPlotTool_ == 1) fprintf(fp, " [Means, I2] = gsort(Means,'g','d');\n"); else fprintf(fp, " [Means, I2] = sort(Means,'descend');\n"); fprintf(fp, " Stds = Stds(I2);\n"); fprintf(fp, " I2 = I2(1:nn);\n"); fprintf(fp, " Means = Means(1:nn);\n"); fprintf(fp, " Stds = Stds(1:nn);\n"); fprintf(fp, " Str = Str(I2);\n"); fprintf(fp, "end\n"); fprintf(fp, "ymin = min(Means-Stds);\n"); fprintf(fp, "ymax = max(Means+Stds);\n"); fprintf(fp, "h2 = 0.05 * (ymax - ymin);\n"); fprintf(fp, "bar(Means,0.8);\n"); fprintf(fp, "for ii = 1:nn\n"); fprintf(fp, " if (ii == 1)\n"); if (psPlotTool_ == 1) fprintf(fp, " set(gca(),\"auto_clear\",\"off\")\n"); else fprintf(fp, " hold on\n"); fprintf(fp, " end;\n"); fprintf(fp, " XX = [ii ii];\n"); fprintf(fp, " YY = [Means(ii)-Stds(ii) Means(ii)+Stds(ii)];\n"); fprintf(fp, " plot(XX,YY,'-ko','LineWidth',3.0,'MarkerEdgeColor',"); fprintf(fp, "'k','MarkerFaceColor','g','MarkerSize',12)\n"); fprintf(fp, "end;\n"); if (psPlotTool_ == 1) { fprintf(fp, "a=gca();\n"); fprintf(fp, "a.data_bounds=[0, ymin; nn+1, ymax];\n"); fprintf(fp, "a.x_ticks(2) = [1:nn]';\n"); fprintf(fp, "a.x_ticks(3) = Str';\n"); fprintf(fp, "a.x_label.font_size = 3;\n"); fprintf(fp, "a.x_label.font_style = 4;\n"); } else { fprintf(fp, "axis([0 nn+1 ymin ymax])\n"); fprintf(fp, "set(gca,'XTickLabel',[]);\n"); fprintf(fp, "th=text(1:nn, repmat(ymin-0.05*(ymax-ymin),nn,1),Str,"); fprintf(fp, "'HorizontalAlignment','left','rotation',90);\n"); fprintf(fp, "set(th, 'fontsize', 12)\n"); fprintf(fp, "set(th, 'fontweight', 'bold')\n"); } fwritePlotAxes(fp); fwritePlotTitle(fp,"Modified Means Plot (bootstrap)"); fwritePlotYLabel(fp, "Modified Means (of gradients)"); if (psPlotTool_ == 1) fprintf(fp, " set(gca(),\"auto_clear\",\"on\")\n"); else fprintf(fp, " hold off\n"); fclose(fp); printOutTS(PL_INFO, "MOAT bootstrap plot file = %s.\n", bootstrapFile); printEquals(PL_INFO, 0); for (ii = 0; ii < nInputs; ii++) if (YGs[ii] != NULL) delete [] YGs[ii]; delete [] YGs; return 0; } // ************************************************************************ // equal operator // ------------------------------------------------------------------------ MOATAnalyzer& MOATAnalyzer::operator=(const MOATAnalyzer &) { printOutTS(PL_ERROR, "MOATAnalysis operator= ERROR: operation not allowed.\n"); exit(1); return (*this); }
36.226712
78
0.512981
[ "3d" ]
c8a4859d4a1616e60ba247325efa6fb7db3ef95d
30,954
cpp
C++
engine/decision_strategies/source/NPCDecisionStrategy.cpp
prolog/shadow-of-the-wyrm
a1312c3e9bb74473f73c4e7639e8bd537f10b488
[ "MIT" ]
60
2019-08-21T04:08:41.000Z
2022-03-10T13:48:04.000Z
engine/decision_strategies/source/NPCDecisionStrategy.cpp
prolog/shadow-of-the-wyrm
a1312c3e9bb74473f73c4e7639e8bd537f10b488
[ "MIT" ]
3
2021-03-18T15:11:14.000Z
2021-10-20T12:13:07.000Z
engine/decision_strategies/source/NPCDecisionStrategy.cpp
prolog/shadow-of-the-wyrm
a1312c3e9bb74473f73c4e7639e8bd537f10b488
[ "MIT" ]
8
2019-11-16T06:29:05.000Z
2022-01-23T17:33:43.000Z
#include "ActionTextKeys.hpp" #include "Amulet.hpp" #include "AttackNPCMagicDecision.hpp" #include "CoordUtils.hpp" #include "Commands.hpp" #include "CommandCustomValues.hpp" #include "Conversion.hpp" #include "CoordUtils.hpp" #include "CreatureProperties.hpp" #include "CreatureTileSafetyChecker.hpp" #include "CreatureUtils.hpp" #include "CurrentCreatureAbilities.hpp" #include "DecisionScript.hpp" #include "DecisionStrategyProperties.hpp" #include "Game.hpp" #include "HostilityManager.hpp" #include "IMessageManager.hpp" #include "ItemProperties.hpp" #include "Log.hpp" #include "MagicalAbilityChecker.hpp" #include "MapUtils.hpp" #include "MessageManagerFactory.hpp" #include "NPCDecisionStrategy.hpp" #include "NPCDropDecisionStrategy.hpp" #include "NPCMagicDecisionFactory.hpp" #include "NPCPickupDecisionStrategy.hpp" #include "NPCUseEquipItemDecisionStrategy.hpp" #include "RaceConstants.hpp" #include "RangedCombatApplicabilityChecker.hpp" #include "RangedCombatUtils.hpp" #include "RaceManager.hpp" #include "Ring.hpp" #include "RNG.hpp" #include "SearchStrategyFactory.hpp" #include "Spellbook.hpp" #include "SpellShapeFactory.hpp" #include "ThreatConstants.hpp" #include "Wand.hpp" #include "WeaponManager.hpp" using namespace std; const int NPCDecisionStrategy::PERCENT_CHANCE_USE_ITEM = 40; const int NPCDecisionStrategy::PERCENT_CHANCE_PICK_UP_USEFUL_ITEM = 75; const int NPCDecisionStrategy::PERCENT_CHANCE_DROP_ITEM = 90; const int NPCDecisionStrategy::PERCENT_CHANCE_ADVANCE_TOWARDS_TARGET = 85; const int NPCDecisionStrategy::PERCENT_CHANCE_CONSIDER_USING_MAGIC = 75; const int NPCDecisionStrategy::PERCENT_CHANCE_CONSIDER_RANGED_COMBAT = 80; const int NPCDecisionStrategy::PERCENT_CHANCE_BREED = 15; NPCDecisionStrategy::NPCDecisionStrategy(ControllerPtr new_controller) : DecisionStrategy(new_controller) { } // By default, always get/pick up/etc the maximum. uint NPCDecisionStrategy::get_count(const uint max_count) { return max_count; } bool NPCDecisionStrategy::get_confirmation(const bool confirmation_default_value, const bool require_proper_selection) { return true; } void NPCDecisionStrategy::set_fov_map(MapPtr new_fov_map) { current_fov_map = new_fov_map; update_threats_if_shopkeeper(current_fov_map); } void NPCDecisionStrategy::update_threats_if_shopkeeper(MapPtr current_fov_map) { if (current_fov_map != nullptr && String::to_bool(get_property(DecisionStrategyProperties::DECISION_STRATEGY_SHOPKEEPER))) { CreatureMap potential_thieves = current_fov_map->get_creatures(); for (const auto& pt_pair : potential_thieves) { CreaturePtr creature = pt_pair.second; if (creature != nullptr && creature->has_unpaid_items() && !threat_ratings.has_threat(creature->get_id()).first) { MapPtr current_map = Game::instance().get_current_map(); Coordinate creature_coord = current_map->get_location(creature->get_id()); // If the creature has unpaid items and is standard outside of a shop // perimeter, become hostile. if (!MapUtils::is_in_shop_or_adjacent(current_map, creature_coord).first) { threat_ratings.add_threat(creature->get_id(), ThreatConstants::INITIAL_THREAT_RATING); IMessageManager& manager = MM::instance(); manager.add_new_message(StringTable::get(ActionTextKeys::ACTION_ENRAGED_SHOPKEEPER)); manager.send(); } } } } } // The basic decision structure for NPCs. The individual get_decision_for functions are pure virtual within this class, // and implemented by concrete decision strategies. CommandPtr NPCDecisionStrategy::get_nonmap_decision(const bool reprompt_on_cmd_not_found, const string& this_creature_id, CommandFactory* command_factory, KeyboardCommandMap* keyboard_commands, int* key_p, const bool refresh_window) { MapPtr nullmap; return get_decision(reprompt_on_cmd_not_found, this_creature_id, command_factory, keyboard_commands, nullmap, key_p); } CommandPtr NPCDecisionStrategy::get_decision(const bool reprompt_on_cmd_not_found, const string& this_creature_id, CommandFactory* command_factory, KeyboardCommandMap* keyboard_commands, MapPtr view_map, int* key_p) { CommandPtr command; CommandFactoryType factory_type = command_factory->get_factory_type(); switch(factory_type) { case CommandFactoryType::COMMAND_FACTORY_TYPE_MAP: command = get_decision_for_map(this_creature_id, command_factory, keyboard_commands, view_map); break; case CommandFactoryType::COMMAND_FACTORY_TYPE_INVENTORY: command = get_decision_for_inventory(command_factory, keyboard_commands); break; case CommandFactoryType::COMMAND_FACTORY_TYPE_EQUIPMENT: command = get_decision_for_equipment(command_factory, keyboard_commands); break; case CommandFactoryType::COMMAND_FACTORY_TYPE_SELECT_TILE: command = get_decision_for_tile_selection(command_factory, keyboard_commands); break; default: break; } return command; } CommandPtr NPCDecisionStrategy::get_decision_for_map(const std::string& this_creature_id, CommandFactory* command_factory, KeyboardCommandMap* keyboard_commands, MapPtr view_map) { CommandPtr command; if (view_map) { update_threats_based_on_fov(this_creature_id, view_map); if (has_movement_orders() == false) { command = get_use_item_decision(this_creature_id, view_map); } if (has_movement_orders() == false) { if (command == nullptr) { command = get_drop_decision(this_creature_id, view_map); } } if (has_movement_orders() == false) { if (command == nullptr) { // Is there something useful to pick up? Humanoids will pick up wands // if they know what they do, if the wands cause damage command = get_pick_up_decision(this_creature_id, view_map); } } // If the creature has any spells, consider casting a spell, based on // low health, nearby hostile creatures, etc. if (has_movement_orders() == false) { if (command == nullptr) { command = get_magic_decision(this_creature_id, view_map); } } // Breed, potentially. // Movement orders can't override this. if (command == nullptr) { command = get_breed_decision(this_creature_id, view_map); } if (has_movement_orders() == false) { // Attack if threatened. if (command == nullptr) { command = get_ranged_attack_decision(this_creature_id, view_map); } } if (has_movement_orders() == false) { if (command == nullptr) { command = get_attack_decision(this_creature_id, view_map); } } if (has_movement_orders() == false) { // If not threatened, try a custom (script-based) decision. if (command == nullptr) { command = get_custom_decision(this_creature_id, view_map); } } // If no custom decisions fired, attempt movement. if (command == nullptr && can_move()) { command = get_movement_decision(this_creature_id, view_map); } } // If we can't move, or there are no adjacent coordinates to which the NPC can move, // the command will be a search command - that can always be done, and will always // advance to the next turn. if (!command) { command = std::make_unique<SearchCommand>(-1); } return command; } // Decide whether or not to cast a spell. CommandPtr NPCDecisionStrategy::get_magic_decision(const string& this_creature_id, MapPtr view_map) { CommandPtr magic_command; INPCMagicDecisionPtr npc_magic_decision; bool suppress_magic = String::to_bool(get_property(DecisionStrategyProperties::DECISION_STRATEGY_SUPPRESS_MAGIC)); if (view_map != nullptr && !suppress_magic) { CreaturePtr creature = view_map->get_creature(this_creature_id); CurrentCreatureAbilities cca; Game& game = Game::instance(); const SpellMap& spell_map = game.get_spells_ref(); const set<string> creature_threats = threat_ratings.get_true_threats_without_level(); std::vector<std::pair<std::string, Direction>> potential_spells; MagicalAbilityChecker mac; if (creature != nullptr && cca.can_speak(creature)) { SpellKnowledge& sk = creature->get_spell_knowledge_ref(); if (sk.get_knows_spells() && RNG::percent_chance(PERCENT_CHANCE_CONSIDER_USING_MAGIC)) { SpellKnowledgeMap skm = sk.get_spell_knowledge_map(); for (const auto& skm_pair : skm) { const auto& s_it = spell_map.find(skm_pair.first); if (skm_pair.second.get_castings() > 0) { if (s_it == spell_map.end()) { Log::instance().error("Spell ID " + skm_pair.first + " not found for creature base ID " + creature->get_original_id()); continue; } else { const Spell& spell = s_it->second; // Only consider the spell if the creature actually has enough // AP to cast it! if (mac.has_sufficient_power(creature, spell)) { npc_magic_decision = NPCMagicDecisionFactory::create_npc_magic_decision(spell.get_magic_classification()); if (npc_magic_decision != nullptr) { pair<bool, Direction> decision_details = npc_magic_decision->decide(creature, view_map, spell, creature_threats); if (npc_magic_decision && decision_details.first) { potential_spells.push_back(make_pair(spell.get_spell_id(), decision_details.second)); } } } } } } } } if (potential_spells.size() > 0) { std::shuffle(potential_spells.begin(), potential_spells.end(), RNG::get_engine()); pair<string, Direction> spell_to_cast = potential_spells.at(0); // Create the spell command, adding properties to set the spell details. magic_command = make_unique<CastSpellCommand>(-1); magic_command->set_custom_value(CommandCustomValues::COMMAND_CUSTOM_VALUES_SELECTED_SPELL_ID, spell_to_cast.first); magic_command->set_custom_value(CommandCustomValues::COMMAND_CUSTOM_VALUES_DIRECTION, to_string(static_cast<int>(spell_to_cast.second))); } } return magic_command; } // Get the decision for what to attack. CommandPtr NPCDecisionStrategy::get_attack_decision(const string& this_creature_id, MapPtr view_map) { CommandPtr no_attack; // Iterate through the threats in order of threatiness ThreatMap threat_map = threat_ratings.get_all_threats(); ThreatMap::const_reverse_iterator t_it = threat_map.rbegin(); if (view_map != nullptr) { Coordinate c_this = view_map->get_location(this_creature_id); TilePtr this_tile = view_map->at(c_this); if (this_tile != nullptr) { CreaturePtr this_cr = this_tile->get_creature(); // Ensure that we only attack legitimate threats. // Creatures may dislike other creatures, but that won't cause them to attack. while (t_it != threat_map.rend() && t_it->first > ThreatConstants::DISLIKE_THREAT_RATING) { set<string> creature_ids = t_it->second; vector<pair<string, int>> threat_distances = get_creatures_by_distance(this_cr, view_map, creature_ids); for (const auto& td_pair : threat_distances) { string threatening_creature_id = td_pair.first; // Check the view map to see if the creature exists if (view_map->has_creature(threatening_creature_id)) { // Check if adjacent to this_creature_id Coordinate c_threat = view_map->get_location(threatening_creature_id); if (CoordUtils::are_coordinates_adjacent(c_this, c_threat)) { Direction direction = CoordUtils::get_direction(c_this, c_threat); // create movement command, return. CommandPtr command = std::make_unique<AttackCommand>(direction, -1); return command; } else { // If the creature is hostile, and the target is generally far away, // advance towards the target, but only do so with a certain // probability, to allow for other actions (script decisions, etc). if (can_move() && RNG::percent_chance(PERCENT_CHANCE_ADVANCE_TOWARDS_TARGET) && this_cr != nullptr) { SearchStrategyPtr ss = SearchStrategyFactory::create_search_strategy(SearchType::SEARCH_TYPE_UNIFORM_COST, this_cr); // JCD FIXME WAS BFS... Direction direction = CoordUtils::get_direction(c_this, ss->search(view_map, c_this, c_threat)); if (direction != Direction::DIRECTION_NULL) { CommandPtr command = std::make_unique<MovementCommand>(direction, -1); return command; } } } } } // Try the next threat level. t_it++; } } } return no_attack; } // If the creature is a breeder, consider whether or not to breed. CommandPtr NPCDecisionStrategy::get_breed_decision(const string& this_creature_id, MapPtr view_map) { CommandPtr no_breed; bool breeds = String::to_bool(get_property(DecisionStrategyProperties::DECISION_STRATEGY_BREEDS)); if (breeds && RNG::percent_chance(PERCENT_CHANCE_BREED)) { // Only breed if there's at least one threatening creature in the // creature's view map. set<string> all_threats = threat_ratings.get_true_threats_without_level(); bool threat_nearby = false; for (const string& threat_id : all_threats) { if (view_map->has_creature(threat_id)) { threat_nearby = true; break; } } if (!threat_nearby) { return no_breed; } TileDirectionMap tdm = MapUtils::get_adjacent_tiles_to_creature(view_map, view_map->get_creature(this_creature_id)); for (const auto& tdm_pair : tdm) { TilePtr tile = tdm_pair.second; if (tile != nullptr && tile->has_creature() == false) { CommandPtr breed = std::make_unique<BreedCommand>(-1); return breed; } } } return no_breed; } // Potentially do a ranged attack CommandPtr NPCDecisionStrategy::get_ranged_attack_decision(const string& this_creature_id, MapPtr view_map) { CommandPtr no_attack; ThreatMap threat_map = threat_ratings.get_all_threats(); ThreatMap::const_reverse_iterator t_it = threat_map.rbegin(); if (view_map != nullptr) { Coordinate c_this = view_map->get_location(this_creature_id); TilePtr this_tile = view_map->at(c_this); if (this_tile != nullptr) { CreaturePtr this_cr = this_tile->get_creature(); RangedCombatApplicabilityChecker rcac; if (rcac.can_creature_do_ranged_combat(this_cr).first && RNG::percent_chance(PERCENT_CHANCE_CONSIDER_RANGED_COMBAT)) { while (t_it != threat_map.rend() && t_it->first > ThreatConstants::DISLIKE_THREAT_RATING) { set<string> creature_ids = t_it->second; vector<pair<string, int>> threat_distances = get_creatures_by_distance(this_cr, view_map, creature_ids); for (const auto& td_pair : threat_distances) { string threatening_creature_id = td_pair.first; Coordinate threat_c = view_map->get_location(threatening_creature_id); if (RangedCombatUtils::is_coord_in_range(threat_c, view_map) && RangedCombatUtils::is_coordinate_obstacle_free(this_cr, c_this, threat_c, view_map)) { TargetMap& tm = this_cr->get_target_map_ref(); tm[to_string(static_cast<int>(AttackType::ATTACK_TYPE_RANGED))] = make_pair(threatening_creature_id, threat_c); CommandPtr command = std::make_unique<FireMissileCommand>(-1); command->set_custom_value(CommandCustomValues::COMMAND_CUSTOM_VALUES_SKIP_TARGETTING, std::to_string(true)); return command; } } // Try the next threat level. t_it++; } } } } return no_attack; } // Get a custom decision (script-based) CommandPtr NPCDecisionStrategy::get_custom_decision(const string& this_creature_id, MapPtr view_map) { CommandPtr command; if (view_map != nullptr) { CreaturePtr creature = view_map->get_creature(this_creature_id); if (creature != nullptr) { ScriptDetails decision_script_details = creature->get_event_script(CreatureEventScripts::CREATURE_EVENT_SCRIPT_DECISION); string decision_script = decision_script_details.get_script(); if (!decision_script.empty() && RNG::percent_chance(decision_script_details.get_chance())) { Game& game = Game::instance(); ScriptEngine& se = game.get_script_engine_ref(); DecisionScript ds; ActionCostValue acv = ds.execute(se, decision_script, creature); if (acv > 0) { command = std::make_unique<CustomScriptCommand>(); command->set_custom_value(CommandCustomValues::COMMAND_CUSTOM_VALUES_ACTION_COST_VALUE, std::to_string(acv)); } } } } return command; } // Get the decision for where to move. // Move stupidly (randomly) when no threat is present. CommandPtr NPCDecisionStrategy::get_movement_decision(const string& this_creature_id, MapPtr view_map) { CommandPtr movement_command; Game& game = Game::instance(); MapPtr current_map = game.get_current_map(); if (current_map != nullptr) { Coordinate this_creature_coords = current_map->get_location(this_creature_id); TilePtr this_creature_tile = current_map->at(this_creature_coords); CreaturePtr this_creature = this_creature_tile->get_creature(); // Is the creature a sentinel? Sentinels are just NPCs that stay in one // place, moving only to pursue when attacked. bool sentinel = String::to_bool(get_property(DecisionStrategyProperties::DECISION_STRATEGY_SENTINEL)); bool ordered_sentinel = String::to_bool(get_property(DecisionStrategyProperties::DECISION_STRATEGY_ORDERED_SENTINEL)); if ((sentinel || ordered_sentinel) && this_creature && MapUtils::hostile_creature_exists(this_creature_id, view_map) == false) { return movement_command; } string follow_id = get_property(DecisionStrategyProperties::DECISION_STRATEGY_FOLLOW_CREATURE_ID); string at_ease = get_property(DecisionStrategyProperties::DECISION_STRATEGY_AT_EASE); string leader_id; if (this_creature != nullptr) { leader_id = this_creature->get_additional_property(CreatureProperties::CREATURE_PROPERTIES_LEADER_ID); } if (!at_ease.empty()) { movement_command = get_follow_direction(view_map, this_creature, this_creature_coords, leader_id); if (movement_command != nullptr) { return movement_command; } } else if (!follow_id.empty()) { movement_command = get_follow_direction(view_map, this_creature, this_creature_coords, follow_id); if (movement_command != nullptr) { return movement_command; } } string search_pct = get_property(DecisionStrategyProperties::DECISION_STRATEGY_SEARCH_PCT); if (!search_pct.empty()) { if (RNG::percent_chance(String::to_int(search_pct))) { movement_command = std::make_unique<SearchCommand>(-1); return movement_command; } } // If the creature has automove coordinates, favour those. Coordinate am_c = get_automove_coords(); if (am_c != CoordUtils::end()) { Coordinate c_this = view_map->get_location(this_creature_id); TilePtr this_tile = view_map->at(c_this); if (this_tile != nullptr) { CreaturePtr this_cr = this_tile->get_creature(); SearchStrategyPtr ss = SearchStrategyFactory::create_search_strategy(SearchType::SEARCH_TYPE_ASTAR, this_cr); Direction direction = CoordUtils::get_direction(c_this, ss->search(view_map, c_this, am_c)); if (direction != Direction::DIRECTION_NULL) { CommandPtr command = std::make_unique<MovementCommand>(direction, -1); return command; } } } Dimensions current_dimensions = current_map->size(); int this_row = this_creature_coords.first; int this_col = this_creature_coords.second; vector<Coordinate> adjacent_coordinates = CoordUtils::get_adjacent_map_coordinates(current_dimensions, this_row, this_col); vector<Coordinate> choice_coordinates = get_adjacent_safe_coordinates_without_creatures(current_map, adjacent_coordinates, this_creature); // If the creature is a shopkeeper, prefer movement on to shop tiles when // in a shop. bool shopkeeper = String::to_bool(get_property(DecisionStrategyProperties::DECISION_STRATEGY_SHOPKEEPER)); if (shopkeeper && MapUtils::is_in_shop_or_adjacent(current_map, current_map->get_location(this_creature_id)).first) { std::shuffle(choice_coordinates.begin(), choice_coordinates.end(), RNG::get_engine()); for (const Coordinate& cc : choice_coordinates) { if (MapUtils::is_in_shop_or_adjacent(current_map, cc).first) { movement_command = std::make_unique<MovementCommand>(CoordUtils::get_direction(this_creature_coords, cc), -1); break; } } } else { // Pick a random empty coordinate. if (!choice_coordinates.empty()) { Coordinate movement_coord = choice_coordinates.at(RNG::range(0, choice_coordinates.size() - 1)); Direction direction = CoordUtils::get_direction(this_creature_coords, movement_coord); movement_command = std::make_unique<MovementCommand>(direction, -1); } } } return movement_command; } CommandPtr NPCDecisionStrategy::get_pick_up_decision(const string& this_creature_id, MapPtr view_map) { CommandPtr pu_cmd; Game& game = Game::instance(); MapPtr map = game.get_current_map(); if (map != nullptr && RNG::percent_chance(PERCENT_CHANCE_PICK_UP_USEFUL_ITEM)) { CreaturePtr creature = map->get_creature(this_creature_id); if (creature != nullptr) { RaceManager rm; string race_id = creature->get_race_id(); Race* race = rm.get_race(race_id); bool humanoid = rm.is_race_or_descendent(race_id, RaceConstants::RACE_CONSTANTS_RACE_ID_HUMANOID); if (creature != nullptr && humanoid && race->get_corporeal().get_current()) { NPCPickupDecisionStrategy pu_strat; pu_cmd = pu_strat.decide(creature, map); } } } return pu_cmd; } CommandPtr NPCDecisionStrategy::get_drop_decision(const string& this_creature_id, MapPtr view_map) { CommandPtr drop_cmd; Game& game = Game::instance(); MapPtr map = game.get_current_map(); if (map != nullptr && RNG::percent_chance(PERCENT_CHANCE_DROP_ITEM)) { CreaturePtr creature = map->get_creature(this_creature_id); if (creature != nullptr) { NPCDropDecisionStrategy drop; drop_cmd = drop.decide(creature, map); } } return drop_cmd; } CommandPtr NPCDecisionStrategy::get_use_item_decision(const string& this_creature_id, MapPtr view_map) { CommandPtr use_cmd; Game& game = Game::instance(); MapPtr map = game.get_current_map(); if (map != nullptr && RNG::percent_chance(PERCENT_CHANCE_USE_ITEM)) { CreaturePtr creature = map->get_creature(this_creature_id); if (creature != nullptr) { NPCUseEquipItemDecisionStrategy ue; use_cmd = ue.decide(creature, map); } } return use_cmd; } // Get a list of the adjacent coordinates that do not contain creatures vector<Coordinate> NPCDecisionStrategy::get_adjacent_safe_coordinates_without_creatures(MapPtr current_map, const vector<Coordinate>& all_adjacent_coordinates, CreaturePtr this_creature) { CreatureTileSafetyChecker safety_checker; vector<Coordinate> coords_without_creatures; for (const Coordinate& c : all_adjacent_coordinates) { // Don't move if there's a creature on that coordinate. TilePtr adjacent_tile = current_map->at(c.first, c.second); if (adjacent_tile != nullptr) { if (adjacent_tile->has_creature() || (!safety_checker.is_tile_safe_for_creature(this_creature, adjacent_tile))) { continue; } else { coords_without_creatures.push_back(c); } } } return coords_without_creatures; } bool NPCDecisionStrategy::has_movement_orders() const { string follow = get_property(DecisionStrategyProperties::DECISION_STRATEGY_FOLLOW_CREATURE_ID); bool has_orders = (!follow.empty()); return has_orders; } CommandPtr NPCDecisionStrategy::get_follow_direction(MapPtr view_map, CreaturePtr this_creature, const Coordinate& this_creature_coords, const string& follow_id) { CommandPtr command; Coordinate c_follow = view_map->get_location(follow_id); if (!CoordUtils::are_coordinates_adjacent(this_creature_coords, c_follow)) { SearchStrategyPtr ss = SearchStrategyFactory::create_search_strategy(SearchType::SEARCH_TYPE_UNIFORM_COST, this_creature); Direction direction = CoordUtils::get_direction(this_creature_coords, ss->search(view_map, this_creature_coords, c_follow)); if (direction != Direction::DIRECTION_NULL) { command = std::make_unique<MovementCommand>(direction, -1); } } return command; } void NPCDecisionStrategy::update_threats_based_on_fov(const std::string& this_creature_id, MapPtr view_map) { update_threats_with_contraband(this_creature_id, view_map); update_threats_to_leader(this_creature_id, view_map); remove_threats_with_same_deity(this_creature_id, view_map); } void NPCDecisionStrategy::update_threats_with_contraband(const std::string& this_creature_id, MapPtr view_map) { Game& game = Game::instance(); MapPtr current_map = game.get_current_map(); bool attack_contraband = String::to_bool(get_property(DecisionStrategyProperties::DECISION_STRATEGY_ATTACK_CONTRABAND)); if (attack_contraband && current_map != nullptr && view_map != nullptr) { const CreatureMap& creatures = view_map->get_creatures_ref(); CreaturePtr this_creature = current_map->get_creature(this_creature_id); HostilityManager hm; for (const auto& c_pair : creatures) { if (c_pair.second && c_pair.second->has_item_with_property(ItemProperties::ITEM_PROPERTIES_CONTRABAND) && !this_creature->hostile_to(c_pair.second->get_id())) { string msg = ActionTextKeys::get_npc_contraband_message(this_creature->get_description_sid()); IMessageManager& manager = MM::instance(MessageTransmit::FOV, c_pair.second, c_pair.second->get_is_player()); manager.add_new_message(msg); manager.send(); hm.set_hostility_to_creature(this_creature, c_pair.second->get_id(), ThreatConstants::ACTIVE_THREAT_RATING); } } } } void NPCDecisionStrategy::update_threats_to_leader(const std::string& this_creature_id, MapPtr view_map) { Game& game = Game::instance(); MapPtr current_map = game.get_current_map(); if (current_map != nullptr) { CreaturePtr this_creature = current_map->get_creature(this_creature_id); if (this_creature != nullptr) { // Have we been ordered to attack by our leader? If so, find all the // threats to that creature, and attack one. string attack_threaten_id = get_property(DecisionStrategyProperties::DECISION_STRATEGY_ATTACK_CREATURES_THREATENING_ID); string leader_id = this_creature->get_additional_property(CreatureProperties::CREATURE_PROPERTIES_LEADER_ID); string at_ease = get_property(DecisionStrategyProperties::DECISION_STRATEGY_AT_EASE); if (view_map != nullptr && (!attack_threaten_id.empty() || !at_ease.empty())) { CreatureMap creatures = view_map->get_creatures(); vector<string> leader_attackers; for (const pair<string, CreaturePtr>& c_pair : creatures) { if (c_pair.second->get_decision_strategy()->get_threats_ref().has_threat(leader_id).first) { string threat_id = c_pair.second->get_id(); if (!threat_ratings.has_threat(threat_id).first) { HostilityManager hm; hm.set_hostility_to_creature(this_creature, threat_id, ThreatConstants::ACTIVE_THREAT_RATING); } // Break so that the creature is only focused on one creature // attacking their leader at a time. break; } } } } } } void NPCDecisionStrategy::remove_threats_with_same_deity(const std::string& this_creature_id, MapPtr view_map) { Game& game = Game::instance(); MapPtr current_map = game.get_current_map(); if (current_map != nullptr && game.do_deities_exist()) { CreaturePtr this_creature = current_map->get_creature(this_creature_id); if (this_creature != nullptr && view_map != nullptr) { string deity_id = this_creature->get_religion_ref().get_active_deity_id(); if (!deity_id.empty()) { CreatureMap creatures = view_map->get_creatures(); for (const pair<string, CreaturePtr>& c_pair : creatures) { CreaturePtr creature = c_pair.second; if (creature != nullptr) { bool apostate = String::to_bool(creature->get_additional_property(CreatureProperties::CREATURE_PROPERTIES_APOSTATE)); auto t_details = this_creature->get_decision_strategy()->get_threats_ref().has_threat(c_pair.first); if (t_details.first && t_details.second < ThreatConstants::ACTIVE_THREAT_RATING && !apostate && deity_id == c_pair.second->get_religion_ref().get_active_deity_id()) { HostilityManager hm; hm.remove_hostility_to_creature(this_creature, c_pair.first); } } } } } } } vector<pair<string, int>> NPCDecisionStrategy::get_creatures_by_distance(CreaturePtr creature, MapPtr view_map, const set<string>& creature_ids) { vector<pair<string, int>> cdist; if (creature != nullptr && view_map != nullptr) { Coordinate cr_coord = view_map->get_location(creature->get_id()); for (const string& cr_id : creature_ids) { if (view_map->has_location(cr_id)) { Coordinate threat_coord = view_map->get_location(cr_id); cdist.push_back(make_pair(cr_id, CoordUtils::chebyshev_distance(cr_coord, threat_coord))); } } std::sort(cdist.begin(), cdist.end(), [](const auto& c1, const auto& c2) { return (c1.second < c2.second); }); } return cdist; }
34.27907
232
0.697939
[ "vector" ]
c8a74673c83ae9ddf568ec4ee0b09143aebf09a0
2,077
hpp
C++
libs/render/include/hamon/render/vulkan/pipeline_vertex_input_state.hpp
shibainuudon/HamonEngine
508a69b0cf589ccb2e5d403ce9e78ff2b85cc058
[ "MIT" ]
null
null
null
libs/render/include/hamon/render/vulkan/pipeline_vertex_input_state.hpp
shibainuudon/HamonEngine
508a69b0cf589ccb2e5d403ce9e78ff2b85cc058
[ "MIT" ]
21
2022-03-02T13:11:59.000Z
2022-03-30T15:12:41.000Z
libs/render/include/hamon/render/vulkan/pipeline_vertex_input_state.hpp
shibainuudon/HamonEngine
508a69b0cf589ccb2e5d403ce9e78ff2b85cc058
[ "MIT" ]
null
null
null
/** * @file pipeline_vertex_input_state.hpp * * @brief PipelineVertexInputState */ #ifndef HAMON_RENDER_VULKAN_PIPELINE_VERTEX_INPUT_STATE_HPP #define HAMON_RENDER_VULKAN_PIPELINE_VERTEX_INPUT_STATE_HPP #include <hamon/render/vulkan/vulkan.hpp> #include <hamon/render/vulkan/format.hpp> #include <hamon/render/vertex_layout.hpp> namespace hamon { inline namespace render { namespace vulkan { class PipelineVertexInputState { public: explicit PipelineVertexInputState(render::VertexLayout const& layout) { { ::VkVertexInputBindingDescription desc; desc.binding = 0; desc.stride = static_cast<std::uint32_t>(layout.GetBytes()); desc.inputRate = VK_VERTEX_INPUT_RATE_VERTEX; m_bindings.push_back(desc); } std::uint32_t i = 0; for (auto const& attr : layout.GetAttributes()) { ::VkVertexInputAttributeDescription desc; desc.location = i; desc.binding = 0; desc.format = vulkan::Format(attr.type, attr.element_num); desc.offset = static_cast<std::uint32_t>(attr.offset); m_attributes.push_back(desc); ++i; } m_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; m_info.pNext = nullptr; m_info.flags = 0; m_info.vertexBindingDescriptionCount = static_cast<std::uint32_t>(m_bindings.size()); m_info.pVertexBindingDescriptions = m_bindings.data(); m_info.vertexAttributeDescriptionCount = static_cast<std::uint32_t>(m_attributes.size()); m_info.pVertexAttributeDescriptions = m_attributes.data(); } ::VkPipelineVertexInputStateCreateInfo const& Get(void) const { return m_info; } private: ::VkPipelineVertexInputStateCreateInfo m_info{}; std::vector<::VkVertexInputBindingDescription> m_bindings; std::vector<::VkVertexInputAttributeDescription> m_attributes; }; } // namespace vulkan } // inline namespace render } // namespace hamon #endif // HAMON_RENDER_VULKAN_PIPELINE_VERTEX_INPUT_STATE_HPP
27.693333
102
0.705826
[ "render", "vector" ]
c8a7d78eccec5d6b7a11d03e23aaeb485e9de4bd
9,155
cpp
C++
services/formmgr/test/unittest/fms_form_provider_mgr_test/fms_form_provider_mgr_test.cpp
openharmony-sig-ci/appexecfwk_standard
609acd8632803202bd8af4c2a6bfc99ecf61ea2e
[ "Apache-2.0" ]
null
null
null
services/formmgr/test/unittest/fms_form_provider_mgr_test/fms_form_provider_mgr_test.cpp
openharmony-sig-ci/appexecfwk_standard
609acd8632803202bd8af4c2a6bfc99ecf61ea2e
[ "Apache-2.0" ]
null
null
null
services/formmgr/test/unittest/fms_form_provider_mgr_test/fms_form_provider_mgr_test.cpp
openharmony-sig-ci/appexecfwk_standard
609acd8632803202bd8af4c2a6bfc99ecf61ea2e
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * 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 <gtest/gtest.h> #include "form_ams_helper.h" #include "form_bms_helper.h" #define private public #include "form_data_mgr.h" #include "form_db_cache.h" #include "form_refresh_limiter.h" #include "form_host_interface.h" #include "form_mgr.h" #undef private #include "form_mgr_service.h" #include "form_provider_mgr.h" #include "if_system_ability_manager.h" #include "inner_bundle_info.h" #include "ipc_skeleton.h" #include "iservice_registry.h" #include "mock_ability_manager.h" #include "mock_bundle_manager.h" #include "mock_form_host_client.h" #include "permission/permission_kit.h" #include "permission/permission.h" #include "running_process_info.h" #include "system_ability_definition.h" using namespace testing::ext; using namespace OHOS; using namespace OHOS::AppExecFwk; using namespace OHOS::Security; namespace { const std::string PERMISSION_NAME_REQUIRE_FORM = "ohos.permission.REQUIRE_FORM"; const std::string PARAM_PROVIDER_PACKAGE_NAME = "com.form.provider.app.test.abiliy"; const std::string FORM_PROVIDER_BUNDLE_NAME = "com.form.provider.service"; const std::string PARAM_PROVIDER_MODULE_NAME = "com.form.provider.app.test.abiliy"; const std::string FORM_PROVIDER_ABILITY_NAME = "com.form.provider.app.test.abiliy"; const std::string PARAM_FORM_NAME = "com.form.name.test"; const std::string FORM_JS_COMPOMENT_NAME = "jsComponentName"; const std::string FORM_PROVIDER_MODULE_SOURCE_DIR = ""; const std::string FORM_HOST_BUNDLE_NAME = "com.form.host.app"; const std::string DEVICE_ID = "ohos-phone1"; const std::string DEF_LABEL1 = "PermissionFormRequireGrant"; class FmsFormProviderMgrTest : public testing::Test { public: static void SetUpTestCase(); static void TearDownTestCase(); void SetUp(); void TearDown(); protected: sptr<MockFormHostClient> token_; std::shared_ptr<FormMgrService> formyMgrServ_ = DelayedSingleton<FormMgrService>::GetInstance(); sptr<BundleMgrService> mockBundleMgr_; sptr<MockAbilityMgrService> mockAbilityMgrServ_; }; void FmsFormProviderMgrTest::SetUpTestCase() {} void FmsFormProviderMgrTest::TearDownTestCase() {} void FmsFormProviderMgrTest::SetUp() { // APP_LOGI("fms_form_mgr_client_test_001 setup"); formyMgrServ_->OnStart(); mockBundleMgr_ = new (std::nothrow) BundleMgrService(); EXPECT_TRUE(mockBundleMgr_ != nullptr); FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); mockAbilityMgrServ_ = new (std::nothrow) MockAbilityMgrService(); FormAmsHelper::GetInstance().SetAbilityManager(mockAbilityMgrServ_); // APP_LOGI("fms_form_mgr_client_test_001 FormMgrService started"); token_ = new (std::nothrow) MockFormHostClient(); // Permission install std::vector<Permission::PermissionDef> permList; Permission::PermissionDef permDef; permDef.permissionName = PERMISSION_NAME_REQUIRE_FORM; permDef.bundleName = FORM_PROVIDER_BUNDLE_NAME; permDef.grantMode = Permission::GrantMode::USER_GRANT; permDef.availableScope = Permission::AvailableScope::AVAILABLE_SCOPE_ALL; permDef.label = DEF_LABEL1; permDef.labelId = 1; permDef.description = DEF_LABEL1; permDef.descriptionId = 1; permList.emplace_back(permDef); Permission::PermissionKit::AddDefPermissions(permList); Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, {PERMISSION_NAME_REQUIRE_FORM}, 0); Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); } void FmsFormProviderMgrTest::TearDown() {} /* * Feature: FmsFormProviderMgr * Function: FormMgr * SubFunction: AcquireForm Function * FunctionPoints: FormMgr AcquireForm interface * EnvConditions: Mobile that can run ohos test framework * CaseDescription: Verify if AcquireForm works with invalid formid. */ HWTEST_F(FmsFormProviderMgrTest, AcquireForm_001, TestSize.Level0) { GTEST_LOG_(INFO) << "fms_form_mgr_provider_test_001 start"; int64_t formId = 0x114514aa00000000; FormProviderInfo formProviderInfo; EXPECT_EQ(ERR_FORM_INVALID_PARAM, FormProviderMgr::GetInstance().AcquireForm(-114514L, formProviderInfo)); int callingUid {0}; FormItemInfo record; record.SetFormId(formId); FormRecord realFormRecord = FormDataMgr::GetInstance().AllotFormRecord(record, callingUid); FormItemInfo info; FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId, callingUid); GTEST_LOG_(INFO) << "fms_form_mgr_provider_test_001 end"; } /* * Feature: FmsFormProviderMgr * Function: FormMgr * SubFunction: AcquireForm Function * FunctionPoints: FormMgr AcquireForm interface * EnvConditions: Mobile that can run ohos test framework * CaseDescription: Verify if AcquireForm works without formrecord. */ HWTEST_F(FmsFormProviderMgrTest, AcquireForm_002, TestSize.Level0) { GTEST_LOG_(INFO) << "fms_form_mgr_provider_test_002 start"; int64_t formId = 0x11451aaa00000000; FormProviderInfo formProviderInfo; EXPECT_EQ(ERR_APPEXECFWK_FORM_INFO_NOT_EXIST,FormProviderMgr::GetInstance().AcquireForm(formId,formProviderInfo)); int callingUid {0}; FormItemInfo record; record.SetFormId(formId); FormRecord realFormRecord = FormDataMgr::GetInstance().AllotFormRecord(record, callingUid); FormItemInfo info; FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId, callingUid); GTEST_LOG_(INFO) << "fms_form_mgr_provider_test_002 end"; } /* * Feature: FmsFormProviderMgr * Function: FormMgr * SubFunction: AcquireForm Function * FunctionPoints: FormMgr AcquireForm interface * EnvConditions: Mobile that can run ohos test framework * CaseDescription: Verify if AcquireForm works without form host record. */ HWTEST_F(FmsFormProviderMgrTest, AcquireForm_003, TestSize.Level0) { GTEST_LOG_(INFO) << "fms_form_mgr_provider_test_003 start"; int64_t formId = 0x1145aaaa00000000; FormProviderInfo formProviderInfo; int callingUid {0}; FormItemInfo record; record.SetFormId(formId); FormRecord realFormRecord = FormDataMgr::GetInstance().AllotFormRecord(record, callingUid); EXPECT_EQ(ERR_APPEXECFWK_FORM_HOST_INFO_NOT_EXIST, FormProviderMgr::GetInstance().AcquireForm(formId,formProviderInfo)); FormItemInfo info; FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId, callingUid); GTEST_LOG_(INFO) << "fms_form_mgr_provider_test_003 end"; } /* * Feature: FmsFormProviderMgr * Function: FormMgr * SubFunction: RefreshForm Function * FunctionPoints: FormMgr RefreshForm interface * EnvConditions: Mobile that can run ohos test framework * CaseDescription: Verify if RefreshForm works without form host record. */ HWTEST_F(FmsFormProviderMgrTest, RefreshForm_001, TestSize.Level0) { GTEST_LOG_(INFO) << "fms_form_mgr_provider_test_004 start"; int64_t formId = 0x1145aaaa00001200; Want want; int callingUid {0}; EXPECT_EQ(ERR_APPEXECFWK_FORM_INFO_NOT_EXIST, FormProviderMgr::GetInstance().RefreshForm(formId, want)); FormItemInfo record; record.SetFormId(formId); record.SetModuleName(PARAM_FORM_NAME); record.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); FormRecord realFormRecord = FormDataMgr::GetInstance().AllotFormRecord(record, callingUid); FormItemInfo info; FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId, callingUid); GTEST_LOG_(INFO) << "fms_form_mgr_provider_test_004 end"; } /* * Feature: FmsFormProviderMgr * Function: FormMgr * SubFunction: RefreshForm Function * FunctionPoints: FormMgr RefreshForm interface * EnvConditions: Mobile that can run ohos test framework * CaseDescription: Verify if RefreshForm works without form host record. */ HWTEST_F(FmsFormProviderMgrTest, RefreshForm_002, TestSize.Level0) { GTEST_LOG_(INFO) << "fms_form_mgr_provider_test_005 start"; int64_t formId = 0x114514aa00000000; Want want; want.SetParam(Constants::KEY_IS_TIMER, true); int callingUid {0}; FormItemInfo record; record.SetFormId(formId); record.SetModuleName(PARAM_FORM_NAME); record.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); FormRecord realFormRecord = FormDataMgr::GetInstance().AllotFormRecord(record, callingUid); FormItemInfo info; FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId, callingUid); EXPECT_EQ(ERR_APPEXECFWK_FORM_SUPPLIER_DEL_FAIL, FormProviderMgr::GetInstance().RefreshForm(formId, want)); GTEST_LOG_(INFO) << "fms_form_mgr_provider_test_005 end"; } }
37.215447
118
0.775751
[ "vector" ]
c8a879af8d5e59f8c2846184aa559ce5956b4df6
2,158
cpp
C++
OpenGLWindow/mainwindow.cpp
bigbao9494/qtExample
7089c911d82873eb3631ee79ecc846f476b170ad
[ "MIT" ]
39
2017-04-15T01:00:03.000Z
2021-11-27T03:28:35.000Z
OpenGLWindow/mainwindow.cpp
Heacker-c/qtExample
7089c911d82873eb3631ee79ecc846f476b170ad
[ "MIT" ]
null
null
null
OpenGLWindow/mainwindow.cpp
Heacker-c/qtExample
7089c911d82873eb3631ee79ecc846f476b170ad
[ "MIT" ]
63
2016-11-04T15:41:42.000Z
2022-02-22T05:35:50.000Z
#include "mainwindow.h" MainWindow::MainWindow(QWidget *parent) { // We must call setSurfaceType(QWindow::OpenGLSurface) to tell Qt we prefer to use OpenGL to render the images to screen, instead of QPainter. setSurfaceType(QWindow::OpenGLSurface); QSurfaceFormat format; format.setProfile(QSurfaceFormat::CompatibilityProfile); format.setVersion(2, 1); // OpenGL 2.1 setFormat(format); context = new QOpenGLContext; context->setFormat(format); context->create(); context->makeCurrent(this); openGLFunctions = context->functions(); } MainWindow::~MainWindow() { } void MainWindow::initializeGL() { resizeGL(this->width(), this->height()); } void MainWindow::resizeGL(int w, int h) { // Initialize Projection Matrix glMatrixMode(GL_PROJECTION); glLoadIdentity(); glViewport(0, 0, w, h); qreal aspectRatio = qreal(w) / qreal(h); glOrtho(-1 * aspectRatio, 1 * aspectRatio, -1, 1, 1, -1); } void MainWindow::paintGL() { //The geometric primitive types supported by OpenGL are points, lines, linestrips, line loops, //polygons, quads, quad strips, triangles, triangle strips, and triangle fans. // Initialize clear color (cornflower blue) glClearColor(0.39f, 0.58f, 0.93f, 1.f); // Clear color buffer glClear(GL_COLOR_BUFFER_BIT); glBegin(GL_QUADS); glVertex2f(-0.5f, -0.5f); glVertex2f(0.5f, -0.5f); glVertex2f(0.5f, 0.5f); glVertex2f(-0.5f, 0.5f); glEnd(); glBegin(GL_QUADS); glColor3f(1.f, 0.f, 0.f); glVertex2f(-0.8f, -0.8f); glColor3f(1.f, 1.f, 0.f); glVertex2f(0.3f, -0.8f); glColor3f(0.f, 1.f, 0.f); glVertex2f(0.3f, 0.3f); glColor3f(0.f, 0.f, 1.f); glVertex2f(-0.8f, 0.3f); glEnd(); glBegin(GL_TRIANGLES); glColor3f(1.f, 0.f, 0.f); glVertex2f(-0.4f, -0.4f); glColor3f(0.f, 1.f, 0.f); glVertex2f(0.8f, -0.1f); glColor3f(0.f, 0.f, 1.f); glVertex2f(-0.1f, 0.8f); glEnd(); glFlush(); } void MainWindow::paintEvent(QPaintEvent *event) { paintGL(); } void MainWindow::resizeEvent(QResizeEvent *event) { resizeGL(this->width(), this->height()); this->update(); }
25.093023
146
0.650602
[ "render" ]
c8ad24a19befd6c85261f85ed79ae4f59daa2195
2,647
cpp
C++
Google/CodeJam/2022/Qualification/ChainReactions/main.cpp
bergolho1337/Competitive-Programming
f68475b3ca8cadeeb1bf7ad8cd5ea4154055d92b
[ "MIT" ]
null
null
null
Google/CodeJam/2022/Qualification/ChainReactions/main.cpp
bergolho1337/Competitive-Programming
f68475b3ca8cadeeb1bf7ad8cd5ea4154055d92b
[ "MIT" ]
null
null
null
Google/CodeJam/2022/Qualification/ChainReactions/main.cpp
bergolho1337/Competitive-Programming
f68475b3ca8cadeeb1bf7ad8cd5ea4154055d92b
[ "MIT" ]
null
null
null
// Wrong Answer, but why ??? #include <bits/stdc++.h> using namespace std; class Node { public: int id; uint32_t fun; bool is_initiator; Node *parent; public: Node () { this->id = -1; this->is_initiator = true; this->parent = nullptr; } void print () { printf("|| %d [%u] {%d} || --> ",\ this->id,this->fun,this->is_initiator); if (this->parent) { printf("|| %d ||\n",this->parent->id); } else { printf("\n"); } } }; // DEBUG void print_machine (vector<Node> mac) { for (int i = 0; i < mac.size(); i++) { mac[i].print(); } } // DEBUG void print_permutation (vector<int> arr) { for (int i = 0; i < arr.size(); i++) { printf("%d ",arr[i]); } printf("\n"); } uint32_t trigger (Node node, vector<bool> &taken) { uint32_t max_value = 0; Node *ptr = &node; while (ptr && !taken[ptr->id-1]) { if (ptr->fun > max_value) { max_value = ptr->fun; } taken[ptr->id-1] = true; ptr = ptr->parent; } return max_value; } vector<int> get_initiators (vector<Node> mac) { vector<int> out; for (int i = 0; i < mac.size(); i++) { if (mac[i].is_initiator) out.push_back(i); } return out; } int main () { int T; scanf("%d",&T); for (int k = 0; k < T; k++) { int N, F, P; scanf("%d",&N); vector<Node> mac; mac.assign(N,Node()); for (int i = 0; i < N; i++) { scanf("%u",&F); mac[i].id = i+1; mac[i].fun = F; } for (int i = 0; i < N; i++) { scanf("%d",&P); if (P != 0) { mac[i].parent = &mac[P-1]; mac[P-1].is_initiator = false; } } uint32_t ans = 0; vector<int> initiators = get_initiators(mac); do { vector<bool> taken(N); //print_permutation(initiators); uint32_t sum = 0; for (int i = 0; i < initiators.size(); i++) { uint32_t fun = trigger(mac[initiators[i]],taken); sum += fun; } //printf(" --> %u\n",sum); if (sum > ans) { ans = sum; } } while ( std::next_permutation(initiators.begin(),initiators.end()) ); //print_machine(mac); //printf("\n"); printf("Case #%d: %u\n",k+1,ans); } return 0; }
23.424779
79
0.418965
[ "vector" ]
c8ad60e6bcef870b3ce72c60918a31a15d784c4f
552
hpp
C++
libs/projectile/include/sge/projectile/shape/detail/index_container.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
libs/projectile/include/sge/projectile/shape/detail/index_container.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
libs/projectile/include/sge/projectile/shape/detail/index_container.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef SGE_PROJECTILE_SHAPE_DETAIL_INDEX_CONTAINER_HPP_INCLUDED #define SGE_PROJECTILE_SHAPE_DETAIL_INDEX_CONTAINER_HPP_INCLUDED #include <fcppt/config/external_begin.hpp> #include <vector> #include <fcppt/config/external_end.hpp> namespace sge::projectile::shape::detail { using index_container = std::vector<int>; } #endif
26.285714
64
0.768116
[ "shape", "vector" ]
c8b40c76fa4ba7bde0e6080d50431d498a76294e
7,484
cpp
C++
libcaf_net/src/ip.cpp
seewpx/actor-framework
65ecf35317b81d7a211848d59e734f43483fe410
[ "BSD-3-Clause" ]
null
null
null
libcaf_net/src/ip.cpp
seewpx/actor-framework
65ecf35317b81d7a211848d59e734f43483fe410
[ "BSD-3-Clause" ]
null
null
null
libcaf_net/src/ip.cpp
seewpx/actor-framework
65ecf35317b81d7a211848d59e734f43483fe410
[ "BSD-3-Clause" ]
null
null
null
// This file is part of CAF, the C++ Actor Framework. See the file LICENSE in // the main distribution directory for license terms and copyright or visit // https://github.com/actor-framework/actor-framework/blob/master/LICENSE. #include "caf/net/ip.hpp" #include "caf/config.hpp" #include "caf/detail/socket_sys_includes.hpp" #include "caf/error.hpp" #include "caf/ip_address.hpp" #include "caf/ip_subnet.hpp" #include "caf/ipv4_address.hpp" #include "caf/logger.hpp" #include "caf/string_algorithms.hpp" #include <cstddef> #include <string> #include <string_view> #include <utility> #include <vector> #ifdef CAF_WINDOWS # ifndef _WIN32_WINNT # define _WIN32_WINNT 0x0600 # endif # include <iphlpapi.h> # include <winsock.h> #else # include <ifaddrs.h> # include <net/if.h> # include <netdb.h> # include <sys/ioctl.h> #endif #ifndef HOST_NAME_MAX # define HOST_NAME_MAX 255 #endif namespace caf::net::ip { namespace { // Dummy port to resolve empty string with getaddrinfo. constexpr std::string_view dummy_port = "42"; constexpr std::string_view localhost = "localhost"; void* fetch_in_addr(int family, sockaddr* addr) { if (family == AF_INET) return &reinterpret_cast<sockaddr_in*>(addr)->sin_addr; return &reinterpret_cast<sockaddr_in6*>(addr)->sin6_addr; } int fetch_addr_str(char (&buf)[INET6_ADDRSTRLEN], sockaddr* addr) { if (addr == nullptr) return AF_UNSPEC; auto family = addr->sa_family; auto in_addr = fetch_in_addr(family, addr); return (family == AF_INET || family == AF_INET6) && inet_ntop(family, in_addr, buf, INET6_ADDRSTRLEN) == buf ? family : AF_UNSPEC; } #ifdef CAF_WINDOWS template <class F> void for_each_adapter(F f, bool is_link_local = false) { using adapters_ptr = std::unique_ptr<IP_ADAPTER_ADDRESSES, void (*)(void*)>; ULONG len = 0; if (GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX, nullptr, nullptr, &len) != ERROR_BUFFER_OVERFLOW) { CAF_LOG_ERROR("failed to get adapter addresses buffer length"); return; } auto adapters = adapters_ptr{ reinterpret_cast<IP_ADAPTER_ADDRESSES*>(::malloc(len)), free}; if (!adapters) { CAF_LOG_ERROR("malloc failed"); return; } // TODO: The Microsoft WIN32 API example propopses to try three times, other // examples online just perform the call once. If we notice the call to be // unreliable, we might adapt that behavior. if (GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX, nullptr, adapters.get(), &len) != ERROR_SUCCESS) { CAF_LOG_ERROR("failed to get adapter addresses"); return; } char ip_buf[INET6_ADDRSTRLEN]; char name_buf[HOST_NAME_MAX]; std::vector<std::pair<std::string, ip_address>> interfaces; for (auto* it = adapters.get(); it != nullptr; it = it->Next) { memset(name_buf, 0, HOST_NAME_MAX); WideCharToMultiByte(CP_ACP, 0, it->FriendlyName, wcslen(it->FriendlyName), name_buf, HOST_NAME_MAX, nullptr, nullptr); std::string name{name_buf}; for (auto* addr = it->FirstUnicastAddress; addr != nullptr; addr = addr->Next) { memset(ip_buf, 0, INET6_ADDRSTRLEN); getnameinfo(addr->Address.lpSockaddr, addr->Address.iSockaddrLength, ip_buf, sizeof(ip_buf), nullptr, 0, NI_NUMERICHOST); ip_address ip; if (!is_link_local && starts_with(ip_buf, "fe80:")) { CAF_LOG_DEBUG("skipping link-local address: " << ip_buf); continue; } else if (auto err = parse(ip_buf, ip)) continue; f(name_buf, ip); } } } #else // CAF_WINDOWS template <class F> void for_each_adapter(F f, bool is_link_local = false) { ifaddrs* tmp = nullptr; if (getifaddrs(&tmp) != 0) return; std::unique_ptr<ifaddrs, decltype(freeifaddrs)*> addrs{tmp, freeifaddrs}; char buffer[INET6_ADDRSTRLEN]; std::vector<std::pair<std::string, ip_address>> interfaces; for (auto i = addrs.get(); i != nullptr; i = i->ifa_next) { auto family = fetch_addr_str(buffer, i->ifa_addr); if (family != AF_UNSPEC) { ip_address ip; if (!is_link_local && starts_with(buffer, "fe80:")) { CAF_LOG_DEBUG("skipping link-local address: " << buffer); continue; } else if (auto err = parse(buffer, ip)) { CAF_LOG_ERROR("could not parse into ip address " << buffer); continue; } f({i->ifa_name, strlen(i->ifa_name)}, ip); } } } #endif // CAF_WINDOWS } // namespace std::vector<ip_address> resolve(std::string_view host) { addrinfo hint; memset(&hint, 0, sizeof(hint)); hint.ai_socktype = SOCK_STREAM; hint.ai_family = AF_UNSPEC; if (host.empty()) hint.ai_flags = AI_PASSIVE; addrinfo* tmp = nullptr; std::string host_str{host.begin(), host.end()}; if (getaddrinfo(host.empty() ? nullptr : host_str.c_str(), host.empty() ? dummy_port.data() : nullptr, &hint, &tmp) != 0) return {}; std::unique_ptr<addrinfo, decltype(freeaddrinfo)*> addrs{tmp, freeaddrinfo}; char buffer[INET6_ADDRSTRLEN]; std::vector<ip_address> results; for (auto i = addrs.get(); i != nullptr; i = i->ai_next) { auto family = fetch_addr_str(buffer, i->ai_addr); if (family != AF_UNSPEC) { ip_address ip; if (auto err = parse(buffer, ip)) CAF_LOG_ERROR("could not parse IP address: " << buffer); else results.emplace_back(ip); } } // TODO: Should we just prefer ipv6 or use a config option? // std::stable_sort(std::begin(results), std::end(results), // [](const ip_address& lhs, const ip_address& rhs) { // return !lhs.embeds_v4() && rhs.embeds_v4(); // }); return results; } std::vector<ip_address> resolve(ip_address host) { return resolve(to_string(host)); } std::vector<ip_address> local_addresses(std::string_view host) { ip_address host_ip; std::vector<ip_address> results; if (host.empty()) { for_each_adapter( [&](std::string_view, ip_address ip) { results.push_back(ip); }); } else if (host == localhost) { auto v6_local = ip_address{{0}, {0x1}}; auto v4_local = ip_address{make_ipv4_address(127, 0, 0, 1)}; for_each_adapter([&](std::string_view, ip_address ip) { if (ip == v4_local || ip == v6_local) results.push_back(ip); }); } else if (auto err = parse(host, host_ip)) { for_each_adapter([&](std::string_view iface, ip_address ip) { if (iface == host) results.push_back(ip); }); } else { return local_addresses(host_ip); } return results; } std::vector<ip_address> local_addresses(ip_address host) { static auto v6_any = ip_address{{0}, {0}}; static auto v4_any = ip_address{make_ipv4_address(0, 0, 0, 0)}; if (host == v4_any || host == v6_any) return resolve(""); auto link_local = ip_address({0xfe, 0x8, 0x0, 0x0}, {0x0, 0x0, 0x0, 0x0}); auto ll_prefix = ip_subnet(link_local, 10); // Unless explicitly specified we are going to skip link-local addresses. auto is_link_local = ll_prefix.contains(host); std::vector<ip_address> results; for_each_adapter( [&](std::string_view, ip_address ip) { if (host == ip) results.push_back(ip); }, is_link_local); return results; } std::string hostname() { char buf[HOST_NAME_MAX + 1]; buf[HOST_NAME_MAX] = '\0'; gethostname(buf, HOST_NAME_MAX); return buf; } } // namespace caf::net::ip
31.982906
80
0.65767
[ "vector" ]
c8bce813ec15e95f8a301578f72c3a7d87f17037
5,729
cpp
C++
src/ParticleFilter.cpp
ryuichiueda/raspimouse_gamepad_teach_and_replay_sparse_urg
91cba3cca2a759abd29897a4dd52a7b5eadc6d5d
[ "BSD-3-Clause" ]
null
null
null
src/ParticleFilter.cpp
ryuichiueda/raspimouse_gamepad_teach_and_replay_sparse_urg
91cba3cca2a759abd29897a4dd52a7b5eadc6d5d
[ "BSD-3-Clause" ]
null
null
null
src/ParticleFilter.cpp
ryuichiueda/raspimouse_gamepad_teach_and_replay_sparse_urg
91cba3cca2a759abd29897a4dd52a7b5eadc6d5d
[ "BSD-3-Clause" ]
null
null
null
#include <vector> #include "Particle.h" #include "ParticleFilter.h" #include "Observation.h" #include "Episodes.h" using namespace std; ParticleFilter::ParticleFilter(int num, Episodes *ep) { double w = 1.0/num; Particle p(w); for(int i=0;i<num;i++){ particles.push_back(p); } episodes = ep; } void ParticleFilter::init(void) { double w = 1.0/particles.size(); for(auto &p : particles){ p.pos = prob.uniformRandInt(0,episodes->data.size()-2); p.weight = w; } } void ParticleFilter::print(void) { int i = 0; for(auto &p : particles){ if(p.pos >= 0){ auto d = episodes->data[p.pos]; cout << d.str() << endl; i++; } if(i==10) return; } } Action ParticleFilter::modeParticle(Episodes *ep) { double fw = 0.0; double rot = 0.0; double max = 0.0; cout << "mode particle" << endl; for(auto &p : particles){ auto e = ep->actionAt(p.pos); if(max < p.weight){ max = p.weight; fw = e->linear_x; rot = e->angular_z; } } Action a; a.linear_x = fw; a.angular_z = rot; return a; } Action ParticleFilter::mode(Episodes *ep) { for(auto &p : particles){ auto e = ep->At(p.pos); e->counter = 0; } for(auto &p : particles){ auto e = ep->At(p.pos); e->counter++; } int max = 0; Action *mode_a; for(auto &p : particles){ auto e = ep->At(p.pos); if(e->counter > max){ max = e->counter; mode_a = ep->actionAt(p.pos+1); } e->counter = 0; } Action a; a.linear_x = mode_a->linear_x; a.angular_z = mode_a->angular_z; return a; } Action ParticleFilter::average(Episodes *ep) { double fw = 0.0; double rot = 0.0; cout << "avg" << endl; for(auto &p : particles){ auto e = ep->actionAt(p.pos+1); fw += p.weight * e->linear_x; rot += p.weight * e->angular_z; } Action a; a.linear_x = fw; a.angular_z = rot; return a; } Action ParticleFilter::sensorUpdate(Observation *obs, Action *act, Episodes *ep, raspimouse_gamepad_teach_and_replay_sparse_urg::PFoEOutput *out) { out->eta = 0.0; cout << "obs likelihood" << endl; for(auto &p : particles){ double h = likelihood(episodes->obsAt(p.pos),obs); //double h = likelihood(episodes->obsAt(p.pos),obs, episodes->actionAt(p.pos), act); p.weight *= h; out->eta += p.weight; } /* cout << "mode particle" << endl; double max = 0.0; Particle *max_p = NULL; for(auto &p : particles){ if(max < p.weight){ max = p.weight; max_p = &p; } } out->particles_pos.push_back(max_p->pos); return modeParticle(ep); */ normalize(); resampling(&particles); //cout << "OUTPUT " << fw << " " << rot << endl; for(auto &p : particles){ out->particles_pos.push_back(p.pos); } cout << "mode" << endl; return mode(ep); // cout << "avg" << endl; // return average(ep); } double ParticleFilter::likelihood(Observation *past, Observation *last) { double diff[4] = { past->log_lf - last->log_lf, past->log_ls - last->log_ls, past->log_rs - last->log_rs, past->log_rf - last->log_rf }; /* double diff[4] = { past->lf - last->lf, past->ls - last->ls, past->rs - last->rs, past->rf - last->rf }; //cout << diff[1] << '\t' << diff[2] << endl; double diff[4] = { (past->lf + past->rf) - (last->lf + last->rf), ((past->lf + past->rf) + (last->lf + last->rf)), (past->ls + past->rs) - (last->ls + last->rs), ((past->ls + past->rs) + (last->ls + last->rs)) }; */ /* double ans = 1.0; double sigma = 300; double coef = 1.0 / (sqrt(2*sigma*sigma)); for(double &d : diff){ ans *= coef * exp( -(d*d) / (2*sigma*sigma)); } */ double ans = 1.0; for(double &d : diff){ ans /= (1 + fabs(d)/1000); } return ans; } double ParticleFilter::likelihood(Observation *past, Observation *last, Action *past_a, Action *last_a) { double diff[4] = { past->log_lf - last->log_lf, past->log_ls - last->log_ls, past->log_rs - last->log_rs, past->log_rf - last->log_rf }; double ans = 1.0; for(double &d : diff){ ans /= (1 + fabs(d)); } ans /= (1 + 0.2*fabs(past_a->linear_x - last_a->linear_x)); ans /= (1 + 0.2*fabs(past_a->angular_z - last_a->angular_z)); return ans; } void ParticleFilter::resampling(vector<Particle> *ps) { vector<Particle> prev; std::shuffle(ps->begin(),ps->end(),std::mt19937()); double suweighteight = 0.0; int num = (int)ps->size(); for(int i = 0;i < num ;i++){ ps->at(i).weight += suweighteight; suweighteight = ps->at(i).weight; prev.push_back(ps->at(i)); } double step = suweighteight / num; int* choice = new int[num]; //double accum = prob.uniformRand(0.0,1.0) / num; double accum = step * prob.uniformRand(0.0,0.999999999); int j = 0; for(int i=0;i<num;i++){ while(prev[j].weight <= accum) j++; if(j == num) j--; accum += step; choice[i] = j; } for(int i=0;i<num;i++){ int j = choice[i]; ps->at(i) = prev[j]; ps->at(i).weight = 1.0/num; } delete [] choice; } void ParticleFilter::normalize(void) { double eta = 0.0; for(auto &p : particles) eta += p.weight; cout << "eta: " << eta << endl; for(auto &p : particles) p.weight /= eta; } void ParticleFilter::motionUpdate(Episodes *ep) { /* cout << "no odom" << endl; init(); */ cout << "odom" << endl; for(auto &p : particles){ if(rand() % 10 == 0){ p.pos = prob.uniformRandInt(0,episodes->data.size()-2); continue; } int r = rand() % 3; if(r==0) p.pos++; else if(r==1) p.pos += 2; if(p.pos >= ep->data.size()-1) p.pos = prob.uniformRandInt(0,episodes->data.size()-2); } }
21.376866
145
0.56502
[ "vector" ]
c8bd5999acb2147a690ea9d76246cf144db73632
2,317
cpp
C++
src/benchmark.cpp
ppwwyyxx/haDNN
d5e3bd0acc9cf95d8dc6b87f370cf45364bd5db0
[ "MIT" ]
23
2016-05-11T04:08:51.000Z
2020-12-14T06:59:45.000Z
src/benchmark.cpp
ppwwyyxx/haDNN
d5e3bd0acc9cf95d8dc6b87f370cf45364bd5db0
[ "MIT" ]
1
2018-09-27T10:13:03.000Z
2018-09-27T10:13:03.000Z
src/benchmark.cpp
ppwwyyxx/haDNN
d5e3bd0acc9cf95d8dc6b87f370cf45364bd5db0
[ "MIT" ]
7
2016-08-12T00:01:24.000Z
2019-11-06T13:49:36.000Z
//File: benchmark.cpp //Author: Yuxin Wu <ppwwyyxx@gmail.com> #include <vector> #include "lib/utils.hh" #include "lib/debugutils.hh" #include "testing.hh" #include "layers/everything.hh" #include "network.hh" using namespace std; using namespace Halide; using namespace hadnn; vector<Image<float>> random_conv_param(int Cin, int Cout, int k) { return {random_image({k, k, Cout, Cin}), random_image({Cout})}; } void benchmark_speed_test_conv_hwcn(int B, int H, int W, int k, int cin, int cout) { ImageParam par(type_of<float>(), 4); Input input{par}; { Sequential net(input); net.add<Conv2D>(random_conv_param(cin, cout, k), PaddingMode::SAME); net.default_sched(); // auto& O = net.get_output(); // O.print_loop_nest(); speedtest_single_input(par, net.get_output(), {B, cin, W, H}, {B, cout, W, H}, "ConvHWCN"); } } void benchmark_speed_test_conv_nchw(int B, int H, int W, int k, int cin, int cout) { ImageParam par(type_of<float>(), 4); Input input{par}; Sequential net(input); net.add<Conv2DNCHW>(random_conv_param(cin, cout, k), PaddingMode::SAME) .add<ReLU>(); net.default_sched(); P("NCHW:"); speedtest_single_input(par, net.get_output(), {W, H, cin, B}, {W, H, cout, B}); } void benchmark_speed_test_conv_nchw_fft(int B, int H, int W, int k, int cin, int cout) { ImageParam par(type_of<float>(), 4); Input input{par}; // int B = 64; // int H = 48, W = 48; Conv2DNCHWFFT l(&input, random_conv_param(cin, cout, k), {H, W}, PaddingMode::SAME); l.default_sched(); // auto& O = l.get_output(); // O.print_loop_nest(); speedtest_single_input(par, l.get_output(), {W, H, cin, B}, {W, H, cout, B}, "NCHWFFT"); } int main(int argc, char const *argv[]) { if (argc != 8) { printf("Usage: < normal_hwcn normal_nchw fft_nchw > B H W k cin cout\n"); return -1; } const char* type = argv[1]; int B = atoi(argv[2]); int H = atoi(argv[3]); int W = atoi(argv[4]); int k = atoi(argv[5]); int cin = atoi(argv[6]); int cout = atoi(argv[7]); if (strcmp(type, "normal_hwcn") == 0) { benchmark_speed_test_conv_hwcn(B, H, W, k, cin, cout); } if (strcmp(type, "normal_nchw") == 0) { benchmark_speed_test_conv_nchw(B, H, W, k, cin, cout); } if (strcmp(type, "fft_nchw") == 0) { benchmark_speed_test_conv_nchw_fft(B, H, W, k, cin, cout); } return 0; }
26.329545
89
0.656452
[ "vector" ]
c8ccaa17c09e7ffd1f79c8cf190c27c487a03b44
2,404
hpp
C++
src/websocketpp_02/src/shared_const_buffer.hpp
tdfischer/rippled
399c43cae6e90a428e9ce6a988123972b0f03c99
[ "BSL-1.0" ]
89
2015-04-23T20:24:58.000Z
2022-03-20T12:35:30.000Z
src/websocketpp_02/src/shared_const_buffer.hpp
tdfischer/rippled
399c43cae6e90a428e9ce6a988123972b0f03c99
[ "BSL-1.0" ]
14
2020-05-25T15:42:18.000Z
2022-03-20T12:44:56.000Z
src/websocketpp_02/src/shared_const_buffer.hpp
tdfischer/rippled
399c43cae6e90a428e9ce6a988123972b0f03c99
[ "BSL-1.0" ]
41
2015-01-19T05:26:34.000Z
2022-02-23T03:47:39.000Z
/* * Copyright (c) 2011, Peter Thorson. 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 WebSocket++ Project 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 PETER THORSON 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. * */ #ifndef SHARED_CONST_BUFFER_HPP #define SHARED_CONST_BUFFER_HPP #include <boost/asio.hpp> #include <boost/shared_ptr.hpp> #include <string> #include <vector> namespace websocketpp_02 { class shared_const_buffer { public: explicit shared_const_buffer(const std::string &data) : m_data(new std::vector<char>(data.begin(), data.end())), m_buffer(boost::asio::buffer(*m_data)) {} public: typedef boost::asio::const_buffer value_type; typedef const boost::asio::const_buffer *const_iterator; const boost::asio::const_buffer *begin() const { return &m_buffer; } const boost::asio::const_buffer *end() const { return &m_buffer + 1; } private: boost::shared_ptr< std::vector<char> > m_data; boost::asio::const_buffer m_buffer; }; } // namespace websocketpp_02 #endif // SHARED_CONST_BUFFER_HPP
42.175439
116
0.746672
[ "vector" ]
c8d242281233263a91ee00c0d088ac3e1b10a892
1,197
cpp
C++
src/evl/utils/event_utils.cpp
EventVisionLibrary/evl
57496ae11b07aa55e42a59b1766c7db83aea095a
[ "BSD-3-Clause" ]
19
2018-06-01T09:06:38.000Z
2021-07-19T08:52:22.000Z
src/evl/utils/event_utils.cpp
EventVisionLibrary/evl
57496ae11b07aa55e42a59b1766c7db83aea095a
[ "BSD-3-Clause" ]
26
2018-06-16T09:27:23.000Z
2019-07-09T05:52:27.000Z
src/evl/utils/event_utils.cpp
EventVisionLibrary/evl
57496ae11b07aa55e42a59b1766c7db83aea095a
[ "BSD-3-Clause" ]
6
2018-06-03T06:49:29.000Z
2021-07-01T09:25:14.000Z
// Copyright 2018 Event Vision Library. #include "event_utils.hpp" #include <iostream> #include <vector> #include <opencv2/core/core.hpp> #include <evl/core/types.hpp> namespace evl { void printEvent(EventTuple x) { std::cout << ' ' << std::get<0>(x) << ' ' << \ std::get<1>(x) << ' ' << std::get<2>(x) << ' ' << \ std::get<3>(x) << std::endl; } cv::Mat convertEventsToMat(std::vector<EventTuple> events, bool with_pol) { int W = 240; int H = 180; cv::Mat src; if (with_pol) { src = cv::Mat::zeros(H, W, CV_8UC3); } else { src = cv::Mat::zeros(H, W, CV_8UC1); } for (auto iter = events.begin(); iter != events.end(); ++iter) { int x = std::get<1>(*iter); int y = std::get<2>(*iter); if (with_pol) { bool pol = std::get<3>(*iter); cv::Vec3b *p = src.ptr<cv::Vec3b>(y, x); if (pol) { *p = cv::Vec3b(0, 0, 255); // +1 -> red } else { *p = cv::Vec3b(255, 0, 0); // -1 -> blue } } else { unsigned char *p = src.ptr<unsigned char>(y, x); *p = 255; } } return src; } } // namespace evl
26.6
75
0.481203
[ "vector" ]
c8d341408df1a333a32d80e59855e96718935a93
3,956
cpp
C++
client/src/client_server_connection.cpp
HeroesOfSecurity/SecureSender
33e44d474c2bc6f4e80c3bb1860a6d08afda4dd6
[ "MIT" ]
1
2018-01-07T03:57:27.000Z
2018-01-07T03:57:27.000Z
client/src/client_server_connection.cpp
HeroesOfSecurity/SecureSender
33e44d474c2bc6f4e80c3bb1860a6d08afda4dd6
[ "MIT" ]
10
2016-03-22T16:02:45.000Z
2016-05-12T21:06:34.000Z
client/src/client_server_connection.cpp
HeroesOfSecurity/SecureSender
33e44d474c2bc6f4e80c3bb1860a6d08afda4dd6
[ "MIT" ]
null
null
null
#include "include/client_server_connection.h" #include <iostream> #include <stdlib.h> #include <string> #include <include/session.h> #include <qt5/QtNetwork/QTcpSocket> #include <qt5/QtCore/QCoreApplication> #include <qt5/QtNetwork/QHostAddress> #include <qt5/QtCore/QJsonArray> #include <qt5/QtCore/QJsonObject> #include <qt5/QtCore/QJsonDocument> #include <qt5/QtCore/QString> #include <mbedtls/entropy_poll.h> #include <mbedtls/entropy.h> #include <mbedtls/ctr_drbg.h> #include <mbedtls/pk.h> using namespace std; ClientServerConnection::ClientServerConnection(QObject *parent) { server_soc = new QSslSocket(this); crypto = new Crypto(); } ClientServerConnection::~ClientServerConnection(){ } bool ClientServerConnection::connect_to_server() { server_soc->connectToHost(QHostAddress(QString(SERVER_IP)), SERVER_PORT); if (!server_soc->waitForConnected()) { qDebug() << "Could not connect to server"; return false; } qDebug() << "Connection to server SUCCESFUL"; return true; } void ClientServerConnection::disconnect() { if(is_connected()) { server_soc->disconnectFromHost(); //delete server_soc; //server_soc = nullptr; qDebug() << "Disconnected from server"; } } bool ClientServerConnection::is_connected() { return server_soc->state() == QTcpSocket::ConnectedState; } int ClientServerConnection::sign_in(string &username, string &password){ QJsonObject mes; mes.insert("function", QJsonValue(QString::fromStdString("sign_in"))); mes.insert("arguments", QJsonValue(QJsonArray::fromStringList({QString::fromStdString(username), QString::fromStdString(password)}))); send(mes); QJsonObject json = respond(); int res = json["result"].toInt(); if(res) { qDebug() << "Authentication failed"; } else { qDebug() << "You have been authenticated"; } return res; } int ClientServerConnection::sign_up(string username, string password){ QJsonObject mes; mes.insert("function", QJsonValue(QString::fromStdString("sign_up"))); mes.insert("arguments", QJsonValue(QJsonArray::fromStringList({QString::fromStdString(username), QString::fromStdString(password)}))); send(mes); QJsonObject json = respond(); int res = json["result"].toInt(); if(res) { qDebug() << "Can't create account"; } else { qDebug() << "Account has been created"; } return res; } std::vector<User> ClientServerConnection::get_online_users(){ QJsonObject mes; mes.insert("function", QJsonValue(QString::fromStdString("online_users"))); mes.insert("arguments", QJsonValue()); send(mes); qDebug() << "Call Online Users"; QJsonObject json = respond(); vector<User> v; if(json["users"].isArray()){ QJsonArray users = json["users"].toArray(); foreach (QJsonValue user, users) { QJsonObject obj = user.toObject(); User u(obj["username"].toString().toStdString(), obj["ip_address"].toString().toStdString()); v.push_back(u); } } return v; } void ClientServerConnection::send(QJsonObject &mes){ QByteArray arr; QJsonDocument js(mes); arr = js.toJson(); server_soc->write(arr); server_soc->waitForBytesWritten(); server_soc->flush(); } QJsonObject ClientServerConnection::respond(){ server_soc->waitForReadyRead(); QByteArray arr = server_soc->readAll(); server_soc->flush(); QJsonObject json = QJsonDocument::fromJson(arr).object(); return json; } int ClientServerConnection::logout(std::string username){ QJsonObject mes; mes.insert("function", QJsonValue(QString::fromStdString("logout"))); mes.insert("arguments", QJsonValue(QJsonArray::fromStringList({QString::fromStdString(username)}))); send(mes); QJsonObject json = respond(); int res = json["result"].toInt(); return res; }
27.282759
138
0.674419
[ "object", "vector" ]
c8d53164fdb6be1c772bb3d1eba549bd3bad7d9b
11,150
cc
C++
external_parser/parse_example_binary.cc
peterychang/reinforcement_learning
dcf9b979b6cb31ea83cbe704681f138e3244249a
[ "MIT" ]
63
2018-10-22T17:11:02.000Z
2021-12-08T17:26:41.000Z
external_parser/parse_example_binary.cc
peterychang/reinforcement_learning
dcf9b979b6cb31ea83cbe704681f138e3244249a
[ "MIT" ]
160
2018-10-09T02:34:57.000Z
2022-03-31T15:43:48.000Z
external_parser/parse_example_binary.cc
zwd-ms/reinforcement_learning
ec756b96a6e2a774ee710201857c78105012474c
[ "MIT" ]
36
2018-10-08T21:44:05.000Z
2022-03-22T16:20:03.000Z
// Copyright (c) by respective owners including Yahoo!, Microsoft, and // individual contributors. All rights reserved. Released under a BSD (revised) // license as described in the file LICENSE. #include <cfloat> #include <fstream> #include <iostream> #include "action_score.h" #include "best_constant.h" #include "cb.h" #include "constant.h" #include "example.h" #include "flatbuffers/flatbuffers.h" #include "global_data.h" #include "io/logger.h" #include "joiners/example_joiner.h" #include "memory.h" #include "parse_example_binary.h" // TODO need to check if errors will be detected from stderr/stdout/other and // use appropriate logger // helpers start bool read_payload_type(io_buf &input, unsigned int &payload_type) { char *line = nullptr; auto len = input.buf_read(line, sizeof(unsigned int)); if (len < sizeof(unsigned int) || line == nullptr) { if (len == 0) { // when we are trying to fetch the next payload and we find out that there // is nothing left to read the file doesn't have to necessarily contain an // EOF payload_type = MSG_TYPE_EOF; return true; } return false; } payload_type = *reinterpret_cast<const unsigned int *>(line); return true; } bool read_payload_size(io_buf &input, uint32_t &payload_size) { char *line = nullptr; auto len = input.buf_read(line, sizeof(uint32_t)); if (len < sizeof(uint32_t) || line == nullptr) { return false; } payload_size = *reinterpret_cast<const uint32_t *>(line); return true; } bool read_payload(io_buf &input, char *&payload, uint32_t payload_size) { char *line = nullptr; auto len = input.buf_read(line, payload_size); if (len < payload_size || line == nullptr) { return false; } payload = line; return true; } bool read_padding(io_buf &input, uint32_t previous_payload_size, uint32_t &padding_bytes) { char *line = nullptr; padding_bytes = previous_payload_size % 8; if (padding_bytes > 0) { // read and discard padding bytes return read_payload(input, line, padding_bytes); } return true; } // helpers end namespace VW { namespace external { binary_parser::binary_parser(std::unique_ptr<i_joiner> &&joiner) : _example_joiner(std::move(joiner)), _payload(nullptr), _payload_size(0), _total_size_read(0) {} binary_parser::~binary_parser() {} bool binary_parser::read_version(io_buf &input) { _payload = nullptr; const uint32_t buffer_length = 4 * sizeof(char); if (!read_payload(input, _payload, buffer_length)) { VW::io::logger::log_critical("Failed to read payload while reading file " "version, after having read [{}] " "bytes from the file", _total_size_read); return false; } _total_size_read += buffer_length; _payload_size = 0; // this is used but the padding code, make it do the right thing. if (*_payload != BINARY_PARSER_VERSION) { VW::io::logger::log_critical( "File version [{}] does not match the parser version [{}]", static_cast<size_t>(*_payload), BINARY_PARSER_VERSION); return false; } return true; } bool binary_parser::read_header(io_buf &input) { _payload = nullptr; // read header size if (!read_payload_size(input, _payload_size)) { VW::io::logger::log_critical( "Failed to read header message payload size, after having read " "[{}] bytes from the file", _total_size_read); return false; } _total_size_read += sizeof(_payload_size); // read the payload if (!read_payload(input, _payload, _payload_size)) { VW::io::logger::log_critical( "Failed to read header message payload of size [{}], after having read " "[{}] bytes from the file", _payload_size, _total_size_read); return false; } _total_size_read += _payload_size; // TODO:: consume header return true; } bool binary_parser::skip_over_unknown_payload(io_buf &input) { _payload = nullptr; if (!read_payload_size(input, _payload_size)) { VW::io::logger::log_critical( "Failed to read unknown message payload size, after having read " "[{}] bytes from the file", _total_size_read); return false; } _total_size_read += sizeof(_payload_size); if (!read_payload(input, _payload, _payload_size)) { VW::io::logger::log_critical("Failed to read unknown message payload of " "size [{}], after having read " "[{}] bytes from the file", _payload_size, _total_size_read); return false; } _total_size_read += _payload_size; return true; } bool binary_parser::read_checkpoint_msg(io_buf &input) { _payload = nullptr; if (!read_payload_size(input, _payload_size)) { VW::io::logger::log_critical( "Failed to read checkpoint message payload size, after having read " "[{}] bytes from the file", _total_size_read); return false; } _total_size_read += sizeof(_payload_size); if (!read_payload(input, _payload, _payload_size)) { VW::io::logger::log_critical( "Failed to read reward message payload of size [{}], after having read " "[{}] bytes from the file", _payload_size, _total_size_read); return false; } _total_size_read += _payload_size; // TODO: fb verification: what if verification fails, crash or default to // something sensible? auto checkpoint_info = flatbuffers::GetRoot<v2::CheckpointInfo>(_payload); _example_joiner->set_reward_function(checkpoint_info->reward_function_type()); _example_joiner->set_default_reward(checkpoint_info->default_reward()); _example_joiner->set_learning_mode_config( checkpoint_info->learning_mode_config()); _example_joiner->set_problem_type_config( checkpoint_info->problem_type_config()); _example_joiner->set_use_client_time(checkpoint_info->use_client_time()); return true; } bool binary_parser::read_regular_msg(io_buf &input, v_array<example *> &examples, bool &ignore_msg) { _payload = nullptr; ignore_msg = false; if (!read_payload_size(input, _payload_size)) { VW::io::logger::log_warn( "Failed to read regular message payload size, after having read " "[{}] bytes from the file", _total_size_read); return false; } _total_size_read += sizeof(_payload_size); if (!read_payload(input, _payload, _payload_size)) { VW::io::logger::log_warn("Failed to read regular message payload of " "size [{}], after having read " "[{}] bytes from the file", _payload_size, _total_size_read); return false; } _total_size_read += _payload_size; if (!_example_joiner->joiner_ready()) { VW::io::logger::log_warn( "Read regular message before any checkpoint data " "after having read [{}] bytes from the file. Events will be ignored.", _total_size_read); ignore_msg = true; return true; } auto joined_payload = flatbuffers::GetRoot<v2::JoinedPayload>(_payload); auto verifier = flatbuffers::Verifier(reinterpret_cast<const uint8_t *>(_payload), static_cast<size_t>(_payload_size)); if (!joined_payload->Verify(verifier)) { VW::io::logger::log_warn( "JoinedPayload of size [{}] verification failed after having read [{}] " "bytes from the file, skipping JoinedPayload", _payload_size, _total_size_read); return false; } _example_joiner->on_new_batch(); for (const auto *event : *joined_payload->events()) { // process and group events in batch if (!_example_joiner->process_event(*event)) { VW::io::logger::log_error("Processing of an event from JoinedPayload " "failed after having read [{}] " "bytes from the file, skipping JoinedPayload", _total_size_read); return false; } } _example_joiner->on_batch_read(); return process_next_in_batch(examples); } bool binary_parser::process_next_in_batch(v_array<example *> &examples) { while (_example_joiner->processing_batch()) { if (_example_joiner->process_joined(examples)) { return true; } else if (!_example_joiner->current_event_is_skip_learn()) { VW::io::logger::log_warn( "Processing of a joined event from a JoinedEvent " "failed after having read [{}] " "bytes from the file, proceeding to next message", _total_size_read); } // else skip learn event, just process next event } // nothing form the current batch was processed, need to read next msg return false; } bool binary_parser::advance_to_next_payload_type(io_buf &input, unsigned int &payload_type) { // read potential excess padding after last payload read uint32_t padding; if (!read_padding(input, _payload_size, padding)) { VW::io::logger::log_critical( "Failed to read padding of size [{}], after having read " "[{}] bytes from the file", padding, _total_size_read); return false; } _total_size_read += padding; if (!read_payload_type(input, payload_type)) { VW::io::logger::log_critical( "Failed to read next payload type from file, after having read " "[{}] bytes from the file", _total_size_read); return false; } _total_size_read += sizeof(payload_type); return true; } void binary_parser::persist_metrics( std::vector<std::pair<std::string, size_t>> &) { _example_joiner->persist_metrics(); } bool binary_parser::parse_examples(vw *, io_buf &io_buf, v_array<example *> &examples) { if (process_next_in_batch(examples)) { return true; } unsigned int payload_type; while (advance_to_next_payload_type(io_buf, payload_type)) { switch (payload_type) { case MSG_TYPE_FILEMAGIC: { if (!read_version(io_buf)) { return false; } break; } case MSG_TYPE_HEADER: { if (!read_header(io_buf)) { return false; } break; } case MSG_TYPE_CHECKPOINT: { if (!read_checkpoint_msg(io_buf)) { return false; } break; } case MSG_TYPE_REGULAR: { bool ignore_msg = false; if (read_regular_msg(io_buf, examples, ignore_msg)) { if (!ignore_msg) { return true; } } break; } case MSG_TYPE_EOF: { return false; } default: { VW::io::logger::log_warn( "Payload type not recognized [0x{:x}], after having read [{}] " "bytes from the file, attempting to skip payload", payload_type, _total_size_read); if (!skip_over_unknown_payload(io_buf)) { return false; } continue; } } } return false; } } // namespace external } // namespace VW
30.053908
80
0.64287
[ "vector" ]
c8d76d36029bd290b72a5bfce3e0f84d4acae09c
14,513
cpp
C++
src/Ethereum/ABI/ParamStruct.cpp
hnord-vdx/wallet-core
21b3db0240622234d05854263b9e125c1001e870
[ "MIT" ]
263
2019-02-14T22:45:57.000Z
2019-08-07T14:47:58.000Z
src/Ethereum/ABI/ParamStruct.cpp
hnord-vdx/wallet-core
21b3db0240622234d05854263b9e125c1001e870
[ "MIT" ]
414
2019-02-16T21:19:32.000Z
2019-08-07T19:09:45.000Z
src/Ethereum/ABI/ParamStruct.cpp
hnord-vdx/wallet-core
21b3db0240622234d05854263b9e125c1001e870
[ "MIT" ]
172
2019-02-18T03:36:55.000Z
2019-08-07T08:48:05.000Z
// Copyright © 2017-2022 Trust Wallet. // // This file is part of Trust. The full Trust copyright notice, including // terms governing use, modification, and redistribution, is contained in the // file LICENSE at the root of the source code distribution tree. #include "ParamStruct.h" #include "ValueEncoder.h" #include "ParamFactory.h" #include "ParamAddress.h" #include <Hash.h> #include <HexCoding.h> #include <nlohmann/json.hpp> #include <cassert> #include <string> using namespace TW::Ethereum::ABI; using namespace TW; using json = nlohmann::json; static const Data EipStructPrefix = parse_hex("1901"); static const auto Eip712Domain = "EIP712Domain"; std::string ParamNamed::getType() const { return _param->getType() + " " + _name; } ParamSetNamed::~ParamSetNamed() { _params.clear(); } /// Returns the index of the parameter int ParamSetNamed::addParam(const std::shared_ptr<ParamNamed>& param) { if (param.get() == nullptr) { return -1; } assert(param.get() != nullptr); _params.push_back(param); return static_cast<int>(_params.size() - 1); } void ParamSetNamed::addParams(const std::vector<std::shared_ptr<ParamNamed>>& params) { for (auto p : params) { addParam(p); } } std::string ParamSetNamed::getType() const { std::string t = "("; int cnt = 0; for (auto p : _params) { if (cnt++ > 0) { t += ","; } t += p->getType(); } t += ")"; return t; } Data ParamSetNamed::encodeHashes() const { Data hashes; for (auto p: _params) { append(hashes, p->hashStruct()); } return hashes; } std::string ParamSetNamed::getExtraTypes(std::vector<std::string>& ignoreList) const { std::string types; for (auto& p: _params) { auto pType = p->_param->getType(); if (std::find(ignoreList.begin(), ignoreList.end(), pType) == ignoreList.end()) { types += p->getExtraTypes(ignoreList); ignoreList.push_back(pType); } } return types; } std::shared_ptr<ParamNamed> ParamSetNamed::findParamByName(const std::string& name) const { for (auto& p: _params) { if (p->_name == name) { return p; } } return nullptr; } Data ParamStruct::hashType() const { return Hash::keccak256(TW::data(encodeType())); } Data ParamStruct::encodeHashes() const { Data hashes; Data paramsHashes = _params.encodeHashes(); if (paramsHashes.size() > 0) { auto fullType = encodeType(); hashes = Hash::keccak256(TW::data(fullType)); append(hashes, paramsHashes); } return hashes; } Data ParamStruct::hashStruct() const { Data hash(32); Data hashes = encodeHashes(); if (hashes.size() > 0) { hash = Hash::keccak256(hashes); } return hash; } std::string ParamStruct::getExtraTypes(std::vector<std::string>& ignoreList) const { std::string types; if (std::find(ignoreList.begin(), ignoreList.end(), _name) == ignoreList.end()) { types += _name + _params.getType(); ignoreList.push_back(_name); } types += _params.getExtraTypes(ignoreList); return types; } Data ParamStruct::hashStructJson(const std::string& messageJson) { auto message = json::parse(messageJson, nullptr, false); if (message.is_discarded()) { throw std::invalid_argument("Could not parse Json"); } if (!message.is_object()) { throw std::invalid_argument("Expecting Json object"); } if (!message.contains("primaryType") || !message["primaryType"].is_string()) { throw std::invalid_argument("Top-level string field 'primaryType' missing"); } if (!message.contains("domain") || !message["domain"].is_object()) { throw std::invalid_argument("Top-level object field 'domain' missing"); } if (!message.contains("message") || !message["message"].is_object()) { throw std::invalid_argument("Top-level object field 'message' missing"); } if (!message.contains("types") || !message["types"].is_object()) { throw std::invalid_argument("Top-level object field 'types' missing"); } // concatenate hashes Data hashes = EipStructPrefix; auto domainStruct = makeStruct( Eip712Domain, message["domain"].dump(), message["types"].dump()); if (domainStruct) { TW::append(hashes, domainStruct->hashStruct()); auto messageStruct = makeStruct( message["primaryType"].get<std::string>(), message["message"].dump(), message["types"].dump()); if (messageStruct) { TW::append(hashes, messageStruct->hashStruct()); return Hash::keccak256(hashes); } } return {}; // fallback } std::shared_ptr<ParamStruct> findType(const std::string& typeName, const std::vector<std::shared_ptr<ParamStruct>>& types) { for (auto& t: types) { if (t->getType() == typeName) { return t; } } return nullptr; } std::shared_ptr<ParamStruct> ParamStruct::makeStruct(const std::string& structType, const std::string& valueJson, const std::string& typesJson) { try { // parse types auto types = makeTypes(typesJson); // find type info auto typeInfo = findType(structType, types); if (!typeInfo) { throw std::invalid_argument("Type not found, " + structType); } auto values = json::parse(valueJson, nullptr, false); if (values.is_discarded()) { throw std::invalid_argument("Could not parse value Json"); } if (!values.is_object()) { throw std::invalid_argument("Expecting object"); } std::vector<std::shared_ptr<ParamNamed>> params; const auto& typeParams = typeInfo->getParams(); // iterate through the type; order is important and field order in the value json is not defined for (int i = 0; i < typeParams.getCount(); ++i) { auto name = typeParams.getParam(i)->getName(); auto type = typeParams.getParam(i)->getParam()->getType(); // look for it in value (may throw) auto value = values[name]; // first try simple params auto paramVal = ParamFactory::make(type); if (paramVal) { if (!values.is_null()) { std::string valueString = value.is_string() ? value.get<std::string>() : value.dump(); if (!paramVal->setValueJson(valueString)) { throw std::invalid_argument("Could not set type for param " + name); } } params.push_back(std::make_shared<ParamNamed>(name, paramVal)); } else if (type.length() >= 2 && type.substr(type.length() - 2, 2) == "[]") { // array of struct auto arrayType = type.substr(0, type.length() - 2); auto subTypeInfo = findType(arrayType, types); if (!subTypeInfo) { throw std::invalid_argument("Could not find type for array sub-struct " + arrayType); } if (!value.is_array()) { throw std::invalid_argument("Value must be array for type " + type); } std::vector<std::shared_ptr<ParamBase>> paramsArray; if (value.size() == 0) { // empty array auto subStruct = makeStruct(arrayType, "{}", typesJson); if (!subStruct) { throw std::invalid_argument("Could not process array sub-struct " + arrayType + " " + "{}"); } assert(subStruct); auto tmp = std::make_shared<ParamArray>(paramsArray); tmp->setProto(subStruct); params.push_back(std::make_shared<ParamNamed>(name, tmp)); } else { for (const auto& e: value) { auto subStruct = makeStruct(arrayType, e.dump(), typesJson); if (!subStruct) { throw std::invalid_argument("Could not process array sub-struct " + arrayType + " " + e.dump()); } assert(subStruct); paramsArray.push_back(subStruct); } params.push_back(std::make_shared<ParamNamed>(name, std::make_shared<ParamArray>(paramsArray))); } } else { // try if sub struct auto subTypeInfo = findType(type, types); if (!subTypeInfo) { throw std::invalid_argument("Could not find type for sub-struct " + type); } if (value.is_null()) { params.push_back(std::make_shared<ParamNamed>(name, std::make_shared<ParamStruct>(type, std::vector<std::shared_ptr<ParamNamed>>{}))); } else { auto subStruct = makeStruct(type, value.dump(), typesJson); if (!subStruct) { throw std::invalid_argument("Could not process sub-struct " + type); } assert(subStruct); params.push_back(std::make_shared<ParamNamed>(name, subStruct)); } } } return std::make_shared<ParamStruct>(structType, params); } catch (const std::invalid_argument& ex) { throw; } catch (const std::exception& ex) { throw std::invalid_argument(std::string("Could not process Json: ") + ex.what()); } catch (...) { throw std::invalid_argument("Could not process Json"); } } std::shared_ptr<ParamStruct> ParamStruct::makeType(const std::string& structName, const std::string& structJson, const std::vector<std::shared_ptr<ParamStruct>>& extraTypes, bool ignoreMissingType) { try { if (structName.empty()) { throw std::invalid_argument("Missing type name"); } auto jsonValue = json::parse(structJson, nullptr, false); if (jsonValue.is_discarded()) { throw std::invalid_argument("Could not parse type Json"); } if (!jsonValue.is_array()) { throw std::invalid_argument("Expecting array"); } std::vector<std::shared_ptr<ParamNamed>> params; for(auto& p2: jsonValue) { auto name = p2["name"].get<std::string>(); auto type = p2["type"].get<std::string>(); if (name.empty() || type.empty()) { throw std::invalid_argument("Expecting 'name' and 'type', in " + structName); } auto named = ParamFactory::makeNamed(name, type); if (named) { // simple type (incl. array of simple type) params.push_back(named); } else if (type == structName) { // recursive to self params.push_back(std::make_shared<ParamNamed>(name, std::make_shared<ParamStruct>(type, std::vector<std::shared_ptr<ParamNamed>>{}))); } else if (type.length() >= 2 && type.substr(type.length() - 2, 2) == "[]") { // array of struct auto arrayType = type.substr(0, type.length() - 2); if (ignoreMissingType) { params.push_back(std::make_shared<ParamNamed>(name, std::make_shared<ParamArray>(std::make_shared<ParamStruct>(arrayType, std::vector<std::shared_ptr<ParamNamed>>{})))); } else { // try array struct from extra types auto p2struct = findType(arrayType, extraTypes); if (!p2struct) { throw std::invalid_argument("Unknown struct array type " + arrayType); } params.push_back(std::make_shared<ParamNamed>(name, std::make_shared<ParamArray>(p2struct))); } } else { if (ignoreMissingType) { params.push_back(std::make_shared<ParamNamed>(name, std::make_shared<ParamStruct>(type, std::vector<std::shared_ptr<ParamNamed>>{}))); } else { // try struct from extra types auto p2struct = findType(type, extraTypes); if (!p2struct) { throw std::invalid_argument("Unknown type " + type); } params.push_back(std::make_shared<ParamNamed>(name, p2struct)); } } } if (params.size() == 0) { throw std::invalid_argument("No valid params found"); } return std::make_shared<ParamStruct>(structName, params); } catch (const std::invalid_argument& ex) { throw; } catch (const std::exception& ex) { throw std::invalid_argument(std::string("Could not process Json: ") + ex.what()); } catch (...) { throw std::invalid_argument("Could not process Json"); } } std::vector<std::shared_ptr<ParamStruct>> ParamStruct::makeTypes(const std::string& structTypes) { try { auto jsonValue = json::parse(structTypes, nullptr, false); if (jsonValue.is_discarded()) { throw std::invalid_argument("Could not parse types Json"); } if (!jsonValue.is_object()) { throw std::invalid_argument("Expecting object"); } // do it in 2 passes, as type order may be undefined std::vector<std::shared_ptr<ParamStruct>> types1; for (json::iterator it = jsonValue.begin(); it != jsonValue.end(); it++) { // may throw auto struct1 = makeType(it.key(), it.value().dump(), {}, true); types1.push_back(struct1); } std::vector<std::shared_ptr<ParamStruct>> types2; for (json::iterator it = jsonValue.begin(); it != jsonValue.end(); it++) { // may throw auto struct1 = makeType(it.key(), it.value().dump(), types1, false); types2.push_back(struct1); } return types2; } catch (const std::invalid_argument& ex) { throw; } catch (const std::exception& ex) { throw std::invalid_argument(std::string("Could not process Json: ") + ex.what()); } catch (...) { throw std::invalid_argument("Could not process Json"); } }
39.330623
199
0.564253
[ "object", "vector" ]
c8d9fdefa4e81fea9e59228ed1cc206ecf890fc1
15,002
cpp
C++
mysql-server/storage/ndb/src/cw/cpcd/APIService.cpp
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/storage/ndb/src/cw/cpcd/APIService.cpp
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/storage/ndb/src/cw/cpcd/APIService.cpp
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
/* Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. This program 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, version 2.0, for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <socket_io.h> #include <NdbOut.hpp> #include <Parser.hpp> #include <Properties.hpp> #include <NdbMutex.h> #include <OutputStream.hpp> #include "APIService.hpp" #include "CPCD.hpp" /** const char * name; const char * realName; const Type type; const ArgType argType; const ArgRequired argRequired; const ArgMinMax argMinMax; const int minVal; const int maxVal; void (T::* function)(const class Properties & args); const char * description; */ #define CPCD_CMD(name, fun, desc) \ { \ name, 0, ParserRow<CPCDAPISession>::Cmd, \ ParserRow<CPCDAPISession>::String, \ ParserRow<CPCDAPISession>::Optional, \ ParserRow<CPCDAPISession>::IgnoreMinMax, 0, 0, fun, desc, 0 \ } #define CPCD_ARG(name, type, opt, desc) \ { \ name, 0, ParserRow<CPCDAPISession>::Arg, ParserRow<CPCDAPISession>::type, \ ParserRow<CPCDAPISession>::opt, \ ParserRow<CPCDAPISession>::IgnoreMinMax, 0, 0, 0, desc, 0 \ } #define CPCD_ARG2(name, type, opt, min, max, desc) \ { \ name, 0, ParserRow<CPCDAPISession>::Arg, ParserRow<CPCDAPISession>::type, \ ParserRow<CPCDAPISession>::opt, \ ParserRow<CPCDAPISession>::IgnoreMinMax, min, max, 0, desc, 0 \ } #define CPCD_END() \ { \ 0, 0, ParserRow<CPCDAPISession>::End, ParserRow<CPCDAPISession>::Int, \ ParserRow<CPCDAPISession>::Optional, \ ParserRow<CPCDAPISession>::IgnoreMinMax, 0, 0, 0, 0, 0 \ } #define CPCD_CMD_ALIAS(name, realName, fun) \ { \ name, realName, ParserRow<CPCDAPISession>::CmdAlias, \ ParserRow<CPCDAPISession>::Int, ParserRow<CPCDAPISession>::Optional, \ ParserRow<CPCDAPISession>::IgnoreMinMax, 0, 0, 0, 0, 0 \ } #define CPCD_ARG_ALIAS(name, realName, fun) \ { \ name, realName, ParserRow<CPCDAPISession>::ArgAlias, \ ParserRow<CPCDAPISession>::Int, ParserRow<CPCDAPISession>::Optional, \ ParserRow<CPCDAPISession>::IgnoreMinMax, 0, 0, 0, 0, 0 \ } const ParserRow<CPCDAPISession> commands[] = { CPCD_CMD("define process", &CPCDAPISession::defineProcess, ""), CPCD_ARG("id", Int, Optional, "Id of process."), CPCD_ARG("name", String, Mandatory, "Name of process"), CPCD_ARG("group", String, Mandatory, "Group of process"), CPCD_ARG("env", LongString, Optional, "Environment variables for process"), CPCD_ARG("path", String, Mandatory, "Path to binary"), CPCD_ARG("args", LongString, Optional, "Arguments to process"), CPCD_ARG("type", String, Mandatory, "Type of process"), CPCD_ARG("cwd", String, Mandatory, "Working directory of process"), CPCD_ARG("owner", String, Mandatory, "Owner of process"), CPCD_ARG("runas", String, Optional, "Run as user"), CPCD_ARG("cpuset", LongString, Optional, "CPU affinity set"), CPCD_ARG("stdout", String, Optional, "Redirection of stdout"), CPCD_ARG("stderr", String, Optional, "Redirection of stderr"), CPCD_ARG("stdin", String, Optional, "Redirection of stderr"), CPCD_ARG("ulimit", String, Optional, "ulimit"), CPCD_ARG("shutdown", String, Optional, "shutdown options"), CPCD_CMD("undefine process", &CPCDAPISession::undefineProcess, ""), CPCD_CMD_ALIAS("undef", "undefine process", 0), CPCD_ARG("id", Int, Mandatory, "Id of process"), CPCD_ARG_ALIAS("i", "id", 0), CPCD_CMD("start process", &CPCDAPISession::startProcess, ""), CPCD_ARG("id", Int, Mandatory, "Id of process"), CPCD_CMD("stop process", &CPCDAPISession::stopProcess, ""), CPCD_ARG("id", Int, Mandatory, "Id of process"), CPCD_CMD("list processes", &CPCDAPISession::listProcesses, ""), CPCD_CMD("show version", &CPCDAPISession::showVersion, ""), CPCD_CMD("select protocol", &CPCDAPISession::selectProtocol, ""), CPCD_ARG("version", Int, Mandatory, "Protocol version to use"), CPCD_END()}; CPCDAPISession::CPCDAPISession(NDB_SOCKET_TYPE sock, CPCD &cpcd) : SocketServer::Session(sock), m_cpcd(cpcd), m_protocol_version(1) { m_input = new SocketInputStream(sock, 7 * 24 * 60 * 60000); m_output = new SocketOutputStream(sock); m_parser = new Parser<CPCDAPISession>(commands, *m_input); } CPCDAPISession::CPCDAPISession(FILE *f, CPCD &cpcd) : SocketServer::Session(ndb_socket_create_invalid()), m_cpcd(cpcd), m_protocol_version(1) { m_input = new FileInputStream(f); m_parser = new Parser<CPCDAPISession>(commands, *m_input); m_output = 0; } CPCDAPISession::~CPCDAPISession() { delete m_input; delete m_parser; if (m_output) delete m_output; } void CPCDAPISession::runSession() { Parser_t::Context ctx; while (!m_stop) { m_parser->run(ctx, *this); if (ctx.m_currentToken == 0) break; m_input->reset_timeout(); m_output->reset_timeout(); switch (ctx.m_status) { case Parser_t::Ok: for (unsigned i = 0; i < ctx.m_aliasUsed.size(); i++) ndbout_c("Used alias: %s -> %s", ctx.m_aliasUsed[i]->name, ctx.m_aliasUsed[i]->realName); break; case Parser_t::NoLine: case Parser_t::EmptyLine: break; default: break; } } ndb_socket_close(m_socket); ndb_socket_invalidate(&m_socket); } void CPCDAPISession::stopSession() { CPCD::RequestStatus rs; for (unsigned i = 0; i < m_temporaryProcesses.size(); i++) { Uint32 id = m_temporaryProcesses[i]; m_cpcd.stopProcess(id, getSessionid(), &rs); m_cpcd.undefineProcess(id, getSessionid(), &rs); } } void CPCDAPISession::loadFile() { Parser_t::Context ctx; while (!m_stop) { m_parser->run(ctx, *this); if (ctx.m_currentToken == 0) break; switch (ctx.m_status) { case Parser_t::Ok: for (unsigned i = 0; i < ctx.m_aliasUsed.size(); i++) ndbout_c("Used alias: %s -> %s", ctx.m_aliasUsed[i]->name, ctx.m_aliasUsed[i]->realName); break; case Parser_t::NoLine: case Parser_t::EmptyLine: break; default: break; } } } void CPCDAPISession::defineProcess(Parser_t::Context & /* unused */, const class Properties &args) { int id; CPCD::RequestStatus rs; bool ret = m_cpcd.defineProcess(args, getSessionid(), &rs, &id); if (!m_cpcd.loadingProcessList) { m_output->println("define process"); m_output->println("status: %d", rs.getStatus()); if (ret == true) { m_output->println("id: %d", id); BaseString procType; args.get("type", procType); CPCD::ProcessType processType(procType.c_str()); if (processType == CPCD::ProcessType::TEMPORARY) { m_temporaryProcesses.push_back(id); } } else { m_output->println("errormessage: %s", rs.getErrMsg()); } m_output->println("%s", ""); } } void CPCDAPISession::undefineProcess(Parser_t::Context & /* unused */, const class Properties &args) { Uint32 id; CPCD::RequestStatus rs; args.get("id", &id); bool ret = m_cpcd.undefineProcess(id, getSessionid(), &rs); for (unsigned i = 0; i < m_temporaryProcesses.size(); i++) { if (static_cast<int>(id) == m_temporaryProcesses[i]) { m_temporaryProcesses.erase(i); break; } } m_output->println("undefine process"); m_output->println("id: %d", id); m_output->println("status: %d", rs.getStatus()); if (!ret) m_output->println("errormessage: %s", rs.getErrMsg()); m_output->println("%s", ""); } void CPCDAPISession::startProcess(Parser_t::Context & /* unused */, const class Properties &args) { Uint32 id; CPCD::RequestStatus rs; args.get("id", &id); const int ret = m_cpcd.startProcess(id, getSessionid(), &rs); if (!m_cpcd.loadingProcessList) { m_output->println("start process"); m_output->println("id: %d", id); m_output->println("status: %d", rs.getStatus()); if (!ret) m_output->println("errormessage: %s", rs.getErrMsg()); m_output->println("%s", ""); } } void CPCDAPISession::stopProcess(Parser_t::Context & /* unused */, const class Properties &args) { Uint32 id; CPCD::RequestStatus rs; args.get("id", &id); int ret = m_cpcd.stopProcess(id, getSessionid(), &rs); m_output->println("stop process"); m_output->println("id: %d", id); m_output->println("status: %d", rs.getStatus()); if (!ret) m_output->println("errormessage: %s", rs.getErrMsg()); m_output->println("%s", ""); } static const char *propToString(Properties *prop, const char *key) { static char buf[32]; const char *retval = NULL; PropertiesType pt; prop->getTypeOf(key, &pt); switch (pt) { case PropertiesType_Uint32: Uint32 val; prop->get(key, &val); BaseString::snprintf(buf, sizeof buf, "%d", val); retval = buf; break; case PropertiesType_char: const char *str; prop->get(key, &str); retval = str; break; default: BaseString::snprintf(buf, sizeof buf, "(unknown)"); retval = buf; } return retval; } void CPCDAPISession::printProperty(Properties *prop, const char *key) { m_output->println("%s: %s", key, propToString(prop, key)); } void CPCDAPISession::printLongString(const char *key, const char *value) { size_t remaining = strlen(value); bool append = false; do { const char *fmt = (append ? "+%s:\"%.*s\"\n" : "%s:\"%.*s\"\n"); const int reserved_bytes_for_format = 5; // 2 x '"', ':', '\n', '\0' const int reserved_byte_for_plus_sign = 1; const size_t keylen = strlen(key); size_t size = Parser_t::Context::MaxParseBytes - keylen - reserved_bytes_for_format; size -= append ? reserved_byte_for_plus_sign : 0; if (size > remaining) { size = remaining; } m_output->print(fmt, key, (int)size, value); value += size; remaining -= size; append = true; } while (remaining > 0); } void CPCDAPISession::listProcesses(Parser_t::Context & /* unused */, const class Properties & /* unused */) { m_cpcd.m_processes.lock(); MutexVector<CPCD::Process *> *proclist = m_cpcd.getProcessList(); m_output->println("start processes"); m_output->println("%s", ""); for (unsigned i = 0; i < proclist->size(); i++) { CPCD::Process *p = (*proclist)[i]; m_output->println("process"); m_output->println("id: %d", p->m_id); m_output->println("name: %s", p->m_name.c_str()); m_output->println("path: %s", p->m_path.c_str()); printLongString("args", p->m_args.c_str()); m_output->println("type: %s", p->m_type.c_str()); m_output->println("cwd: %s", p->m_cwd.c_str()); printLongString("env", p->m_env.c_str()); m_output->println("owner: %s", p->m_owner.c_str()); m_output->println("group: %s", p->m_group.c_str()); m_output->println("runas: %s", p->m_runas.c_str()); if (may_print_process_cpuset()) { printLongString("cpuset", p->m_cpuset.c_str()); } m_output->println("stdin: %s", p->m_stdin.c_str()); m_output->println("stdout: %s", p->m_stdout.c_str()); m_output->println("stderr: %s", p->m_stderr.c_str()); m_output->println("ulimit: %s", p->m_ulimit.c_str()); m_output->println("shutdown: %s", p->m_shutdown_options.c_str()); switch (p->m_status) { case STOPPED: m_output->println("status: stopped"); break; case STARTING: m_output->println("status: starting"); break; case RUNNING: m_output->println("status: running"); break; case STOPPING: m_output->println("status: stopping"); break; } m_output->println("%s", ""); } m_output->println("end processes"); m_output->println("%s", ""); m_cpcd.m_processes.unlock(); } void CPCDAPISession::showVersion(Parser_t::Context & /* unused */, const class Properties &args) { CPCD::RequestStatus rs; m_output->println("show version"); m_output->println("compile time: %s %s", __DATE__, __TIME__); m_output->println("supported protocol: %u", CPCD::CPC_PROTOCOL_VERSION); m_output->println("effective protocol: %u", m_protocol_version); m_output->println("%s", ""); } void CPCDAPISession::selectProtocol(Parser_t::Context & /* unused */, const class Properties &args) { Uint32 version; CPCD::RequestStatus rs; args.get("version", &version); if (version < 1) { rs.err(Error, "Invalid protocol version"); } else if (version > CPCD::CPC_PROTOCOL_VERSION) { rs.err(Error, "Unsupported protocol version"); } else { m_protocol_version = version; } m_output->println("select protocol"); m_output->println("status: %d", rs.getStatus()); if (rs.getStatus() != 0) m_output->println("errormessage: %s", rs.getErrMsg()); m_output->println("%s", ""); } template class Vector<ParserRow<CPCDAPISession> const *>;
34.807425
79
0.602986
[ "vector" ]
c8df10590ee8bb7a7605cb0e84010f21adb37c40
1,957
cpp
C++
src/swagger/converters/cpu.cpp
gchagnotSpt/openperf
0ae14cb7a685b1b059f707379773fb3bcb421d40
[ "Apache-2.0" ]
null
null
null
src/swagger/converters/cpu.cpp
gchagnotSpt/openperf
0ae14cb7a685b1b059f707379773fb3bcb421d40
[ "Apache-2.0" ]
null
null
null
src/swagger/converters/cpu.cpp
gchagnotSpt/openperf
0ae14cb7a685b1b059f707379773fb3bcb421d40
[ "Apache-2.0" ]
null
null
null
#include "cpu.hpp" #include "swagger/v1/model/CpuGenerator.h" #include "swagger/v1/model/BulkCreateCpuGeneratorsRequest.h" #include "swagger/v1/model/BulkDeleteCpuGeneratorsRequest.h" #include "swagger/v1/model/BulkStartCpuGeneratorsRequest.h" #include "swagger/v1/model/BulkStopCpuGeneratorsRequest.h" #include "swagger/v1/model/CpuGeneratorResult.h" namespace swagger::v1::model { void from_json(const nlohmann::json& j, CpuGenerator& generator) { if (j.find("id") != j.end()) { generator.setId(j.at("id")); } if (j.find("running") != j.end()) { generator.setRunning(j.at("running")); } auto gc = CpuGeneratorConfig(); gc.fromJson(const_cast<nlohmann::json&>(j.at("config"))); generator.setConfig(std::make_shared<CpuGeneratorConfig>(gc)); } void from_json(const nlohmann::json& j, BulkCreateCpuGeneratorsRequest& request) { request.getItems().clear(); nlohmann::json jsonArray; for (auto& item : const_cast<nlohmann::json&>(j).at("items")) { if (item.is_null()) { continue; } else { std::shared_ptr<CpuGenerator> newItem(new CpuGenerator()); from_json(item, *newItem); request.getItems().push_back(newItem); } } } void from_json(const nlohmann::json& j, BulkDeleteCpuGeneratorsRequest& request) { request.fromJson(const_cast<nlohmann::json&>(j)); } void from_json(const nlohmann::json& j, BulkStartCpuGeneratorsRequest& request) { request.fromJson(const_cast<nlohmann::json&>(j)); } void from_json(const nlohmann::json& j, BulkStopCpuGeneratorsRequest& request) { request.fromJson(const_cast<nlohmann::json&>(j)); } void from_json(const nlohmann::json& j, CpuGeneratorResult& result) { result.fromJson(const_cast<nlohmann::json&>(j)); auto stats = std::make_shared<CpuGeneratorStats>(); stats->fromJson(const_cast<nlohmann::json&>(j).at("stats")); result.setStats(stats); } } // namespace swagger::v1::model
32.081967
80
0.699029
[ "model" ]
c8e2462c0122a53458421baa942446f2466b14d1
18,814
cpp
C++
src/core/src/op/util/detection_output_base.cpp
ytorzuk-altran/openvino
68d460a3bb578a738ba0e4d0e1f2e321afa73ab0
[ "Apache-2.0" ]
1
2021-04-20T08:14:51.000Z
2021-04-20T08:14:51.000Z
src/core/src/op/util/detection_output_base.cpp
ytorzuk-altran/openvino
68d460a3bb578a738ba0e4d0e1f2e321afa73ab0
[ "Apache-2.0" ]
55
2020-11-17T15:07:52.000Z
2022-03-29T07:34:17.000Z
src/core/src/op/util/detection_output_base.cpp
ytorzuk-altran/openvino
68d460a3bb578a738ba0e4d0e1f2e321afa73ab0
[ "Apache-2.0" ]
1
2022-03-27T06:37:35.000Z
2022-03-27T06:37:35.000Z
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "ngraph/op/util/detection_output_base.hpp" #include <ngraph/validation_util.hpp> #include "ngraph/op/concat.hpp" #include "ngraph/op/constant.hpp" #include "ngraph/op/squeeze.hpp" #include "ngraph/runtime/host_tensor.hpp" #include "ngraph/shape.hpp" using namespace std; using namespace ov::op::util; DetectionOutputBase::DetectionOutputBase(const ov::OutputVector& args) : Op(args) {} ov::Dimension DetectionOutputBase::compute_num_classes(const AttributesBase& attrs) { Dimension num_classes = Dimension::dynamic(); NODE_VALIDATION_CHECK(this, 3 <= get_input_size() && get_input_size() <= 5, "A number of arguments must be greater than or equal to 3 and less than or equal to 5. Got " + std::to_string(get_input_size())); const ov::PartialShape& box_logits_pshape = get_input_partial_shape(0); const ov::PartialShape& class_preds_pshape = get_input_partial_shape(1); const ov::PartialShape& proposals_pshape = get_input_partial_shape(2); ov::PartialShape ad_class_preds_shape = ov::PartialShape::dynamic(); ov::PartialShape ad_box_preds_shape = ov::PartialShape::dynamic(); if (box_logits_pshape.rank().is_static()) { NODE_VALIDATION_CHECK( this, box_logits_pshape.rank().get_length() == 2, "Box logits rank must be 2. Got " + std::to_string(box_logits_pshape.rank().get_length())); } if (class_preds_pshape.rank().is_static()) { NODE_VALIDATION_CHECK( this, class_preds_pshape.rank().get_length() == 2, "Class predictions rank must be 2. Got " + std::to_string(class_preds_pshape.rank().get_length())); } if (proposals_pshape.rank().is_static()) { NODE_VALIDATION_CHECK(this, proposals_pshape.rank().get_length() == 3, "Proposals rank must be 3. Got " + std::to_string(proposals_pshape.rank().get_length())); } if (get_input_size() >= 4) { ad_class_preds_shape = get_input_partial_shape(3); if (ad_class_preds_shape.rank().is_static()) { NODE_VALIDATION_CHECK(this, ad_class_preds_shape.rank().get_length() == 2, "Additional class predictions rank must be 2. Got " + std::to_string(ad_class_preds_shape.rank().get_length())); } } if (get_input_size() == 5) { ad_box_preds_shape = get_input_partial_shape(4); if (ad_box_preds_shape.rank().is_static()) { NODE_VALIDATION_CHECK(this, ad_box_preds_shape.rank().get_length() == 2, "Additional box predictions rank must be 2. Got " + std::to_string(ad_box_preds_shape.rank().get_length())); } } int prior_box_size = attrs.normalized ? 4 : 5; Dimension num_prior_boxes = Dimension::dynamic(); // try to deduce a number of prior boxes if (num_prior_boxes.is_dynamic() && proposals_pshape.rank().is_static() && proposals_pshape[2].is_static()) { NODE_VALIDATION_CHECK(this, proposals_pshape[2].get_length() % prior_box_size == 0, "Proposals' third dimension must be a multiply of prior_box_size (" + std::to_string(prior_box_size) + "). Current value is: ", proposals_pshape[2].get_length(), "."); num_prior_boxes = proposals_pshape[2].get_length() / prior_box_size; NODE_VALIDATION_CHECK( this, num_prior_boxes.get_length() > 0, "A number of prior boxes must be greater zero. Got: " + std::to_string(num_prior_boxes.get_length())); } if (num_prior_boxes.is_dynamic() && ad_class_preds_shape.rank().is_static() && ad_class_preds_shape[1].is_static()) { NODE_VALIDATION_CHECK( this, ad_class_preds_shape[1].get_length() % 2 == 0, "Additional class predictions second dimension must be a multiply of 2. Current value is: ", ad_class_preds_shape[1].get_length(), "."); num_prior_boxes = ad_class_preds_shape[1].get_length() / 2; NODE_VALIDATION_CHECK( this, num_prior_boxes.get_length() > 0, "A number of prior boxes must be greater zero. Got: " + std::to_string(num_prior_boxes.get_length())); } // try to deduce a number of classes if (num_classes.is_dynamic() && num_prior_boxes.is_static() && class_preds_pshape.rank().is_static() && class_preds_pshape[1].is_static()) { NODE_VALIDATION_CHECK(this, class_preds_pshape[1].get_length() % num_prior_boxes.get_length() == 0, "Class predictions second dimension must be a multiply of num_prior_boxes (" + std::to_string(num_prior_boxes.get_length()) + "). Current value is: ", class_preds_pshape[1].get_length(), "."); num_classes = class_preds_pshape[1].get_length() / num_prior_boxes.get_length(); } if (num_classes.is_dynamic() && num_prior_boxes.is_static() && box_logits_pshape.rank().is_static() && box_logits_pshape[1].is_static() && !attrs.share_location) { NODE_VALIDATION_CHECK(this, box_logits_pshape[1].get_length() % (num_prior_boxes.get_length() * 4) == 0, "Box logits second dimension must be a multiply of num_prior_boxes * 4 (" + std::to_string(num_prior_boxes.get_length() * 4) + "). Current value is: ", box_logits_pshape[1].get_length(), "."); num_classes = box_logits_pshape[1].get_length() / (num_prior_boxes.get_length() * 4); } if (num_classes.is_dynamic() && num_prior_boxes.is_static() && ad_box_preds_shape.is_static() && ad_box_preds_shape[1].is_static() && !attrs.share_location) { NODE_VALIDATION_CHECK( this, ad_box_preds_shape[1].get_length() % (num_prior_boxes.get_length() * 4) == 0, "Additional box predictions second dimension must be a multiply of num_prior_boxes * 4 (" + std::to_string(num_prior_boxes.get_length() * 4) + "). Current value is: ", ad_box_preds_shape[1].get_length(), "."); num_classes = ad_box_preds_shape[1].get_length() / (num_prior_boxes.get_length() * 4); } return num_classes; } void DetectionOutputBase::validate_and_infer_types_base(const DetectionOutputBase::AttributesBase& attrs, ov::Dimension num_classes) { NODE_VALIDATION_CHECK(this, attrs.keep_top_k.size() > 0, "keep_top_k attribute must be provided"); NODE_VALIDATION_CHECK( this, attrs.code_type == "caffe.PriorBoxParameter.CORNER" || attrs.code_type == "caffe.PriorBoxParameter.CENTER_SIZE", "code_type must be either \"caffe.PriorBoxParameter.CORNER\" or " "\"caffe.PriorBoxParameter.CENTER_SIZE\""); auto box_logits_et = get_input_element_type(0); NODE_VALIDATION_CHECK(this, box_logits_et.is_real(), "Box logits' data type must be floating point. Got " + box_logits_et.get_type_name()); auto class_preds_et = get_input_element_type(1); NODE_VALIDATION_CHECK(this, class_preds_et == box_logits_et, "Class predictions' data type must be the same as box logits type (" + box_logits_et.get_type_name() + "). Got " + class_preds_et.get_type_name()); auto proposals_et = get_input_element_type(2); NODE_VALIDATION_CHECK(this, proposals_et.is_real(), "Proposals' data type must be floating point. Got " + proposals_et.get_type_name()); const ov::PartialShape& box_logits_pshape = get_input_partial_shape(0); const ov::PartialShape& class_preds_pshape = get_input_partial_shape(1); const ov::PartialShape& proposals_pshape = get_input_partial_shape(2); // deduce a number of classes for DetectionOutput-8 if (num_classes.is_dynamic()) { num_classes = compute_num_classes(attrs); } Dimension num_loc_classes = attrs.share_location ? 1 : num_classes; int prior_box_size = attrs.normalized ? 4 : 5; Dimension num_images = Dimension::dynamic(); Dimension num_prior_boxes = Dimension::dynamic(); if (box_logits_pshape.rank().is_static()) { NODE_VALIDATION_CHECK( this, box_logits_pshape.rank().get_length() == 2, "Box logits rank must be 2. Got " + std::to_string(box_logits_pshape.rank().get_length())); num_images = box_logits_pshape[0]; if (box_logits_pshape[1].is_static() && num_loc_classes.is_static()) { NODE_VALIDATION_CHECK(this, (box_logits_pshape[1].get_length() % (num_loc_classes.get_length() * 4)) == 0, "Box logits' second dimension must be a multiply of num_loc_classes * 4 (" + std::to_string(num_loc_classes.get_length() * 4) + "). Current value is: ", box_logits_pshape[1].get_length(), "."); num_prior_boxes = box_logits_pshape[1].get_length() / (num_loc_classes.get_length() * 4); } } if (class_preds_pshape.rank().is_static()) { NODE_VALIDATION_CHECK( this, class_preds_pshape.rank().get_length() == 2, "Class predictions rank must be 2. Got " + std::to_string(class_preds_pshape.rank().get_length())); if (num_images.is_dynamic() && class_preds_pshape[0].is_static()) { num_images = class_preds_pshape[0]; } else { NODE_VALIDATION_CHECK(this, class_preds_pshape[0].compatible(num_images), "Class predictions' first dimension is not compatible with batch size."); } if (class_preds_pshape[1].is_static()) { if (num_prior_boxes.is_dynamic() && num_classes.is_static()) { NODE_VALIDATION_CHECK(this, class_preds_pshape[1].get_length() % num_classes.get_length() == 0, "Class predictions' second dimension must be a multiply of num_classes (" + std::to_string(num_classes.get_length()) + "). Current value is: ", class_preds_pshape[1].get_length(), "."); num_prior_boxes = class_preds_pshape[1].get_length() / num_classes.get_length(); } else if (num_classes.is_static()) { int num_prior_boxes_val = num_prior_boxes.get_length(); NODE_VALIDATION_CHECK( this, class_preds_pshape[1].get_length() == num_prior_boxes_val * num_classes.get_length(), "Class predictions' second dimension must be equal to num_prior_boxes * " "num_classes (" + std::to_string(num_prior_boxes_val * num_classes.get_length()) + "). Current value is: ", class_preds_pshape[1].get_length(), "."); } } } if (proposals_pshape.rank().is_static()) { NODE_VALIDATION_CHECK(this, proposals_pshape.rank().get_length() == 3, "Proposals rank must be 3. Got " + std::to_string(proposals_pshape.rank().get_length())); if (num_images.is_static() && proposals_pshape[0].is_static()) { int64_t proposals_1st_dim = proposals_pshape[0].get_length(); int64_t num_images_val = num_images.get_length(); NODE_VALIDATION_CHECK(this, proposals_1st_dim == 1 || proposals_1st_dim == num_images_val, "Proposals' first dimension is must be equal to either batch size (" + std::to_string(num_images_val) + ") or 1. Got: " + std::to_string(proposals_1st_dim) + "."); } if (proposals_pshape[1].is_static()) { size_t proposals_expected_2nd_dim = attrs.variance_encoded_in_target ? 1 : 2; NODE_VALIDATION_CHECK(this, proposals_pshape[1].compatible(proposals_expected_2nd_dim), "Proposals' second dimension is mismatched. Current value is: ", proposals_pshape[1].get_length(), ", expected: ", proposals_expected_2nd_dim, "."); } if (proposals_pshape[2].is_static()) { if (num_prior_boxes.is_dynamic()) { NODE_VALIDATION_CHECK(this, proposals_pshape[2].get_length() % prior_box_size == 0, "Proposals' third dimension must be a multiply of prior_box_size (" + std::to_string(prior_box_size) + "). Current value is: ", proposals_pshape[2].get_length(), "."); num_prior_boxes = proposals_pshape[2].get_length() / prior_box_size; } else { int num_prior_boxes_val = num_prior_boxes.get_length(); NODE_VALIDATION_CHECK(this, proposals_pshape[2].get_length() == num_prior_boxes_val * prior_box_size, "Proposals' third dimension must be equal to num_prior_boxes " "* prior_box_size (" + std::to_string(num_prior_boxes_val * prior_box_size) + "). Current value is: ", proposals_pshape[2].get_length(), "."); } } } if (get_input_size() > 3) { auto aux_class_preds_et = get_input_element_type(3); NODE_VALIDATION_CHECK(this, aux_class_preds_et == class_preds_et, "Additional class predictions' data type must be the same as class " "predictions data type (" + class_preds_et.get_type_name() + "). Got " + aux_class_preds_et.get_type_name()); auto aux_box_preds_et = get_input_element_type(4); NODE_VALIDATION_CHECK(this, aux_box_preds_et == box_logits_et, "Additional box predictions' data type must be the same as box logits data type (" + box_logits_et.get_type_name() + "). Got " + aux_box_preds_et.get_type_name()); const ov::PartialShape& aux_class_preds_pshape = get_input_partial_shape(3); const ov::PartialShape& aux_box_preds_pshape = get_input_partial_shape(4); if (aux_class_preds_pshape.rank().is_static()) { NODE_VALIDATION_CHECK(this, aux_class_preds_pshape[0].compatible(num_images), "Additional class predictions' first dimension must be " "compatible with batch size."); if (num_prior_boxes.is_static()) { int num_prior_boxes_val = num_prior_boxes.get_length(); NODE_VALIDATION_CHECK(this, aux_class_preds_pshape[1].get_length() == num_prior_boxes_val * 2, "Additional class predictions' second dimension must be equal to " "num_prior_boxes * 2 (" + std::to_string(num_prior_boxes_val * 2) + "). Got " + std::to_string(aux_class_preds_pshape[1].get_length()) + "."); } } NODE_VALIDATION_CHECK(this, aux_box_preds_pshape.compatible(box_logits_pshape), "Additional box predictions' shape must be compatible with box logits shape."); } std::vector<Dimension> output_shape{1, 1}; if (attrs.keep_top_k[0] > 0) { output_shape.push_back(num_images * attrs.keep_top_k[0]); } else if (attrs.top_k > 0 && num_classes.is_static()) { output_shape.push_back(num_images * attrs.top_k * num_classes); } else if (num_classes.is_static()) { output_shape.push_back(num_images * num_prior_boxes * num_classes); } else { output_shape.push_back(Dimension::dynamic()); } output_shape.emplace_back(7); set_output_type(0, box_logits_et, output_shape); } bool ov::op::util::DetectionOutputBase::visit_attributes_base(AttributeVisitor& visitor, DetectionOutputBase::AttributesBase& attrs) { visitor.on_attribute("background_label_id", attrs.background_label_id); visitor.on_attribute("top_k", attrs.top_k); visitor.on_attribute("variance_encoded_in_target", attrs.variance_encoded_in_target); visitor.on_attribute("keep_top_k", attrs.keep_top_k); visitor.on_attribute("code_type", attrs.code_type); visitor.on_attribute("share_location", attrs.share_location); visitor.on_attribute("nms_threshold", attrs.nms_threshold); visitor.on_attribute("confidence_threshold", attrs.confidence_threshold); visitor.on_attribute("clip_after_nms", attrs.clip_after_nms); visitor.on_attribute("clip_before_nms", attrs.clip_before_nms); visitor.on_attribute("decrease_label_id", attrs.decrease_label_id); visitor.on_attribute("normalized", attrs.normalized); visitor.on_attribute("input_height", attrs.input_height); visitor.on_attribute("input_width", attrs.input_width); visitor.on_attribute("objectness_score", attrs.objectness_score); return true; }
55.173021
120
0.577389
[ "shape", "vector" ]
c8ea2a5b83ffcf445c5ef02ed7917c18375cf0ec
12,527
cpp
C++
src/mlpack/methods/range_search/range_search_main.cpp
jmlevin7878/mlpack
7fe38005d86b77293f728c34ca176224bdff9ee8
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
src/mlpack/methods/range_search/range_search_main.cpp
jmlevin7878/mlpack
7fe38005d86b77293f728c34ca176224bdff9ee8
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
src/mlpack/methods/range_search/range_search_main.cpp
jmlevin7878/mlpack
7fe38005d86b77293f728c34ca176224bdff9ee8
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
/** * @file range_search_main.cpp * @author Ryan Curtin * @author Matthew Amidon * * Implementation of the RangeSearch executable. Allows some number of standard * options. */ #include <mlpack/core.hpp> #include <mlpack/core/metrics/lmetric.hpp> #include <mlpack/core/tree/cover_tree.hpp> #include "range_search.hpp" #include "rs_model.hpp" using namespace std; using namespace mlpack; using namespace mlpack::range; using namespace mlpack::tree; using namespace mlpack::metric; // Information about the program itself. PROGRAM_INFO("Range Search", "This program implements range search with a Euclidean distance metric. " "For a given query point, a given range, and a given set of reference " "points, the program will return all of the reference points with distance " "to the query point in the given range. This is performed for an entire " "set of query points. You may specify a separate set of reference and query" " points, or only a reference set -- which is then used as both the " "reference and query set. The given range is taken to be inclusive (that " "is, points with a distance exactly equal to the minimum and maximum of the" " range are included in the results)." "\n\n" "For example, the following will calculate the points within the range [2, " "5] of each point in 'input.csv' and store the distances in 'distances.csv'" " and the neighbors in 'neighbors.csv':" "\n\n" "$ range_search --min=2 --max=5 --reference_file=input.csv\n" " --distances_file=distances.csv --neighbors_file=neighbors.csv" "\n\n" "The output files are organized such that line i corresponds to the points " "found for query point i. Because sometimes 0 points may be found in the " "given range, lines of the output files may be empty. The points are not " "ordered in any specific manner." "\n\n" "Because the number of points returned for each query point may differ, the" " resultant CSV-like files may not be loadable by many programs. However, " "at this time a better way to store this non-square result is not known. " "As a result, any output files will be written as CSVs in this manner, " "regardless of the given extension."); // Define our input parameters that this program will take. PARAM_STRING("reference_file", "File containing the reference dataset.", "r", ""); PARAM_STRING("distances_file", "File to output distances into.", "d", ""); PARAM_STRING("neighbors_file", "File to output neighbors into.", "n", ""); // The option exists to load or save models. PARAM_STRING("input_model_file", "File containing pre-trained range search " "model.", "m", ""); PARAM_STRING("output_model_file", "If specified, the range search model will be" " saved to the given file.", "M", ""); // The user may specify a query file of query points and a range to search for. PARAM_STRING("query_file", "File containing query points (optional).", "q", ""); PARAM_DOUBLE("max", "Upper bound in range (if not specified, +inf will be " "used.", "U", 0.0); PARAM_DOUBLE("min", "Lower bound in range.", "L", 0.0); // The user may specify the type of tree to use, and a few parameters for tree // building. PARAM_STRING("tree_type", "Type of tree to use: 'kd', 'cover', 'r', 'r-star', " "'x', 'ball', 'hilbert-r', 'r-plus', 'r-plus-plus'.", "t", "kd"); PARAM_INT("leaf_size", "Leaf size for tree building (used for kd-trees, R " "trees, R* trees, X trees, Hilbert R trees, R+ trees and R++ trees).", "l", 20); PARAM_FLAG("random_basis", "Before tree-building, project the data onto a " "random orthogonal basis.", "R"); PARAM_INT("seed", "Random seed (if 0, std::time(NULL) is used).", "s", 0); // Search settings. PARAM_FLAG("naive", "If true, O(n^2) naive mode is used for computation.", "N"); PARAM_FLAG("single_mode", "If true, single-tree search is used (as opposed to " "dual-tree search).", "s"); typedef RangeSearch<> RSType; typedef CoverTree<EuclideanDistance, RangeSearchStat> CoverTreeType; typedef RangeSearch<EuclideanDistance, arma::mat, StandardCoverTree> RSCoverType; int main(int argc, char *argv[]) { // Give CLI the command line parameters the user passed in. CLI::ParseCommandLine(argc, argv); if (CLI::GetParam<int>("seed") != 0) math::RandomSeed((size_t) CLI::GetParam<int>("seed")); else math::RandomSeed((size_t) std::time(NULL)); // A user cannot specify both reference data and a model. if (CLI::HasParam("reference_file") && CLI::HasParam("input_model_file")) Log::Fatal << "Only one of --reference_file (-r) or --input_model_file (-m)" << " may be specified!" << endl; // A user must specify one of them... if (!CLI::HasParam("reference_file") && !CLI::HasParam("input_model_file")) Log::Fatal << "No model specified (--input_model_file) and no reference " << "data specified (--reference_file)! One must be provided." << endl; if (CLI::HasParam("input_model_file")) { // Notify the user of parameters that will be ignored. if (CLI::HasParam("tree_type")) Log::Warn << "--tree_type (-t) will be ignored because --input_model_file" << " is specified." << endl; if (CLI::HasParam("leaf_size")) Log::Warn << "--leaf_size (-l) will be ignored because --input_model_file" << " is specified." << endl; if (CLI::HasParam("random_basis")) Log::Warn << "--random_basis (-R) will be ignored because " << "--input_model_file is specified." << endl; if (CLI::HasParam("naive")) Log::Warn << "--naive (-N) will be ignored because --input_model_file is " << "specified." << endl; } // The user must give something to do... if (!CLI::HasParam("min") && !CLI::HasParam("max") && !CLI::HasParam("output_model_file")) Log::Warn << "Neither --min, --max, nor --output_model_file are specified, " << "so no results from this program will be saved!" << endl; // If the user specifies a range but not output files, they should be warned. if ((CLI::HasParam("min") || CLI::HasParam("max")) && !(CLI::HasParam("neighbors_file") || CLI::HasParam("distances_file"))) Log::Warn << "Neither --neighbors_file nor --distances_file is specified, " << "so the range search results will not be saved!" << endl; // If the user specifies output files but no range, they should be warned. if ((CLI::HasParam("neighbors_file") || CLI::HasParam("distances_file")) && !(CLI::HasParam("min") || CLI::HasParam("max"))) Log::Warn << "An output file for range search is given (--neighbors_file " << "or --distances_file), but range search is not being performed " << "because neither --min nor --max are specified! No results will be " << "saved." << endl; // Sanity check on leaf size. int lsInt = CLI::GetParam<int>("leaf_size"); if (lsInt < 1) Log::Fatal << "Invalid leaf size: " << lsInt << ". Must be greater than 0." << endl; // We either have to load the reference data, or we have to load the model. RSModel rs; const bool naive = CLI::HasParam("naive"); const bool singleMode = CLI::HasParam("single_mode"); if (CLI::HasParam("reference_file")) { // Get all the parameters. const string referenceFile = CLI::GetParam<string>("reference_file"); const string treeType = CLI::GetParam<string>("tree_type"); const bool randomBasis = CLI::HasParam("random_basis"); RSModel::TreeTypes tree = RSModel::KD_TREE; if (treeType == "kd") tree = RSModel::KD_TREE; else if (treeType == "cover") tree = RSModel::COVER_TREE; else if (treeType == "r") tree = RSModel::R_TREE; else if (treeType == "r-star") tree = RSModel::R_STAR_TREE; else if (treeType == "ball") tree = RSModel::BALL_TREE; else if (treeType == "x") tree = RSModel::X_TREE; else if (treeType == "hilbert-r") tree = RSModel::HILBERT_R_TREE; else if (treeType == "r-plus") tree = RSModel::R_PLUS_TREE; else if (treeType == "r-plus-plus") tree = RSModel::R_PLUS_PLUS_TREE; else Log::Fatal << "Unknown tree type '" << treeType << "; valid choices are " << "'kd', 'cover', 'r', 'r-star', 'x', 'ball', 'hilbert-r', " << "'r-plus' and 'r-plus-plus'." << endl; rs.TreeType() = tree; rs.RandomBasis() = randomBasis; arma::mat referenceSet; data::Load(referenceFile, referenceSet, true); Log::Info << "Loaded reference data from '" << referenceFile << "' (" << referenceSet.n_rows << "x" << referenceSet.n_cols << ")." << endl; const size_t leafSize = size_t(lsInt); rs.BuildModel(std::move(referenceSet), leafSize, naive, singleMode); } else { // Load the model from file. const string inputModelFile = CLI::GetParam<string>("input_model_file"); data::Load(inputModelFile, "rs_model", rs, true); // Fatal on failure. Log::Info << "Loaded range search model from '" << inputModelFile << "' (" << "trained on " << rs.Dataset().n_rows << "x" << rs.Dataset().n_cols << " dataset)." << endl; // Adjust singleMode and naive if necessary. rs.SingleMode() = CLI::HasParam("single_mode"); rs.Naive() = CLI::HasParam("naive"); rs.LeafSize() = size_t(lsInt); } // Perform search, if desired. if (CLI::HasParam("min") || CLI::HasParam("max")) { const string queryFile = CLI::GetParam<string>("query_file"); const double min = CLI::GetParam<double>("min"); const double max = CLI::HasParam("max") ? CLI::GetParam<double>("max") : DBL_MAX; math::Range r(min, max); arma::mat queryData; if (queryFile != "") { data::Load(queryFile, queryData, true); Log::Info << "Loaded query data from '" << queryFile << "' (" << queryData.n_rows << "x" << queryData.n_cols << ")." << endl; } // Naive mode overrides single mode. if (singleMode && naive) Log::Warn << "--single_mode ignored because --naive is present." << endl; // Now run the search. vector<vector<size_t>> neighbors; vector<vector<double>> distances; if (CLI::HasParam("query_file")) rs.Search(std::move(queryData), r, neighbors, distances); else rs.Search(r, neighbors, distances); Log::Info << "Search complete." << endl; // Save output, if desired. We have to do this by hand. if (CLI::HasParam("distances_file")) { const string distancesFile = CLI::GetParam<string>("distances_file"); fstream distancesStr(distancesFile.c_str(), fstream::out); if (!distancesStr.is_open()) { Log::Warn << "Cannot open file '" << distancesFile << "' to save output" << " distances to!" << endl; } else { // Loop over each point. for (size_t i = 0; i < distances.size(); ++i) { // Store the distances of each point. We may have 0 points to store, // so we must account for that possibility. for (size_t j = 0; j + 1 < distances[i].size(); ++j) distancesStr << distances[i][j] << ", "; if (distances[i].size() > 0) distancesStr << distances[i][distances[i].size() - 1]; distancesStr << endl; } distancesStr.close(); } } if (CLI::HasParam("neighbors_file")) { const string neighborsFile = CLI::GetParam<string>("neighbors_file"); fstream neighborsStr(neighborsFile.c_str(), fstream::out); if (!neighborsStr.is_open()) { Log::Warn << "Cannot open file '" << neighborsFile << "' to save output" << " neighbor indices to!" << endl; } else { // Loop over each point. for (size_t i = 0; i < neighbors.size(); ++i) { // Store the neighbors of each point. We may have 0 points to store, // so we must account for that possibility. for (size_t j = 0; j + 1 < neighbors[i].size(); ++j) neighborsStr << neighbors[i][j] << ", "; if (neighbors[i].size() > 0) neighborsStr << neighbors[i][neighbors[i].size() - 1]; neighborsStr << endl; } neighborsStr.close(); } } } // Save the output model, if desired. if (CLI::HasParam("output_model_file")) { const string outputModelFile = CLI::GetParam<string>("output_model_file"); data::Save(outputModelFile, "rs_model", rs); } }
39.393082
80
0.628642
[ "vector", "model" ]
c8ec0dc37d4d2ab2d5dab1ed0881168e66617179
3,672
cc
C++
test/enc_dec_test.cc
gh-andre/fmtlog
9b221cc177b86265b4f679df41d4147ac2f2f770
[ "MIT" ]
null
null
null
test/enc_dec_test.cc
gh-andre/fmtlog
9b221cc177b86265b4f679df41d4147ac2f2f770
[ "MIT" ]
null
null
null
test/enc_dec_test.cc
gh-andre/fmtlog
9b221cc177b86265b4f679df41d4147ac2f2f770
[ "MIT" ]
null
null
null
#include "../fmtlog.h" #include <fmt/ranges.h> #include <assert.h> #include <iostream> using namespace std; using namespace fmt::literals; struct MyType { MyType(int val) : v(val) {} ~MyType() { dtor_cnt++; // fmt::print("dtor_cnt: {}\n", dtor_cnt); } int v; static int dtor_cnt; }; int MyType::dtor_cnt = 0; template<> struct fmt::formatter<MyType> : formatter<int> { // parse is inherited from formatter<string_view>. template<typename FormatContext> auto format(const MyType& val, FormatContext& ctx) { return formatter<int>::format(val.v, ctx); } }; struct MovableType { public: MovableType(int v = 0) : val{MyType(v)} {} std::vector<MyType> val; }; template<> struct fmt::formatter<MovableType> : formatter<int> { // parse is inherited from formatter<string_view>. template<typename FormatContext> auto format(const MovableType& val, FormatContext& ctx) { return formatter<int>::format(val.val[0].v, ctx); } }; template<typename S, typename... Args> void test(const S& format, Args&&... args) { fmt::detail::check_format_string<Args...>(format); auto sv = fmt::to_string_view(format); size_t formatted_size = fmt::formatted_size(fmt::runtime(sv), std::forward<Args>(args)...); string ans = fmt::format(fmt::runtime(sv), std::forward<Args>(args)...); assert(ans.size() == formatted_size); auto unnamed_format = fmtlog::unNameFormat<false>(sv, nullptr, args...); fmt::print("unnamed_format: {}\n", unnamed_format); size_t cstringSizes[1000]; char buf[1024]; int allocSize = fmtlog::getArgSizes<0>(cstringSizes, args...); const char* ret = fmtlog::encodeArgs<0>(cstringSizes, buf, std::forward<Args>(args)...); // fmt::print("=========\n"); assert(ret - buf == allocSize); fmtlog::MemoryBuffer buffer; int argIdx = -1; std::vector<fmt::basic_format_arg<fmtlog::Context>> format_args; ret = fmtlog::formatTo<Args...>(unnamed_format, buf, buffer, argIdx, format_args); assert(ret - buf == allocSize); string_view res(buffer.data(), buffer.size()); fmt::print("res: {}\n", res); fmt::print("ans: {}\n", ans); assert(res == ans); } int main() { char cstring[100] = "cstring cstring"; const char* p = "haha"; const char* pcstring = cstring; string str("str"); char ch = 'f'; char& ch2 = ch; int i = 5; int& ri = i; double d = 3.45; float f = 55.2; uint16_t short_int = 2222; test("test basic types: {}, {}, {}, {}, {}, {}, {}, {}, {:.1f}, {}, {}, {}, {}, {}, {}, {}", cstring, p, pcstring, "wow", 'a', 5, str, string_view(str), 1.34, ch, ch2, i, ri, d, f, short_int); test("test positional, {one}, {two:>5}, {three}, {four}, {0:.1f}", 5.012, "three"_a = 3, "two"_a = "two", "one"_a = string("one"), "four"_a = string("4")); test("test dynamic spec: {:.{}f}, {:*^30}", 3.14, 1, "centered"); test("test positional spec: int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}", 42); test("test custom types: {}, {}, {}", MyType(1), MyType(2), MovableType(3)); test("test ranges: {}, {}", vector<int>{1, 2, 3}, vector<MyType>{4, 5, 6}); int dtor_cnt; { MovableType val(123); dtor_cnt = MyType::dtor_cnt; test("test copy: {}", val); assert(MyType::dtor_cnt == dtor_cnt + 1); assert(val.val.size() == 1); dtor_cnt = MyType::dtor_cnt; } assert(MyType::dtor_cnt == dtor_cnt + 1); { MovableType val(456); dtor_cnt = MyType::dtor_cnt; test("test move: {}", std::move(val)); assert(MyType::dtor_cnt == dtor_cnt + 1); assert(val.val.size() == 0); dtor_cnt = MyType::dtor_cnt; } assert(MyType::dtor_cnt == dtor_cnt); fmt::print("tests passed\n"); return 0; }
28.246154
116
0.614107
[ "vector" ]
c8eca5c27be34c3469cd7df4cb060cf4a32f4c51
1,547
cpp
C++
src/negllc_step.cpp
xf3086/GenieR
d28a56413a260540fdf7ba2d9ace2145319758f5
[ "MIT" ]
1
2019-04-13T03:22:11.000Z
2019-04-13T03:22:11.000Z
src/negllc_step.cpp
xf3086/GenieR
d28a56413a260540fdf7ba2d9ace2145319758f5
[ "MIT" ]
7
2018-05-04T15:39:07.000Z
2018-06-13T15:49:58.000Z
src/negllc_step.cpp
xf3086/GenieR
d28a56413a260540fdf7ba2d9ace2145319758f5
[ "MIT" ]
3
2016-10-14T07:15:47.000Z
2020-10-17T05:40:16.000Z
#include <Rcpp.h> using namespace Rcpp; //' Function to calculate the loglikelihood of a step coalescent model //' @param parr A parameter vector for population size ,change time and propotion to population size prior to change. //' @param t A sampling and coalescent time vector. //' @param A A lineages vector //' @author Fei Xiang (\email{xf3087@@gmail.com}) //' @return loglikelihood of a exponential coalescent model. //' @useDynLib genieR //' @importFrom Rcpp sourceCpp //' @examples //' library(ape) //' t1=rcoal(20) //' x=att(t1) //' negllc_step(c(1,1,.1), x$t, x$A) //' library(minqa) //' bobyqa(c(1,2,1),negllc_step,lower=0,upper=Inf,t=x$t,A=x$A) //' Geniefit(t1,Model="step",start=c(10,2,1),upper=Inf,lower=0) //' library(dfoptim) //' nmkb(c(1,2,10),negllc_step,lower=0,upper=Inf,t=x$t,A=x$A) //' @export // [[Rcpp::export]] double negllc_step(NumericVector parr, NumericVector t, NumericVector A){ // Initialization int nint = t.size()-1; double ll = 0.0; double N0=parr[0]; double f=parr[1]; double x=parr[2]; double intval, integrand; int a, ch; // Main loop for(int i=0;i<nint;i++){ a=A[i]; ch=a*(a-1)/2; if (t[i+1]<x) { integrand=N0; intval=(t[i+1]-t[i])/N0; } else if (t[i]>x) { integrand=N0*f; intval=(t[i+1]-t[i])/N0/f; } else if (t[i]<x) { integrand=N0*f; intval=(x-t[i])/N0+(t[i+1]-x)/N0/f; } if(A[i+1]==(A[i]-1)){ ll = ll + log(ch)-log(integrand)-ch*intval; }else{ ll = ll -ch*intval; } } return(-ll); }
24.555556
117
0.604396
[ "vector", "model" ]
c8ed24c82b53579a003752dbcf3f19b4d499b99f
11,984
cpp
C++
app/src/main/cpp/sample/BezierCurveSample.cpp
zhangfuwen/NDK_OpenGLES_3_0
6ee05ae3fea2e8c120c810f2fd9bd7ffa4bb1d73
[ "Apache-2.0" ]
null
null
null
app/src/main/cpp/sample/BezierCurveSample.cpp
zhangfuwen/NDK_OpenGLES_3_0
6ee05ae3fea2e8c120c810f2fd9bd7ffa4bb1d73
[ "Apache-2.0" ]
null
null
null
app/src/main/cpp/sample/BezierCurveSample.cpp
zhangfuwen/NDK_OpenGLES_3_0
6ee05ae3fea2e8c120c810f2fd9bd7ffa4bb1d73
[ "Apache-2.0" ]
null
null
null
/** * * Created by 公众号:字节流动 on 2020/4/18. * https://github.com/githubhaohao/NDK_OpenGLES_3_0 * 最新文章首发于公众号:字节流动,有疑问或者技术交流可以添加微信 Byte-Flow ,领取视频教程, 拉你进技术交流群 * * */ #include <glm/gtc/matrix_transform.hpp> #include "BezierCurveSample.h" #include "../util/GLUtils.h" //#define DRAW_POINTS #define POINTS_NUM 256 #define POINTS_PRE_TRIANGLES 3 BezierCurveSample::BezierCurveSample() { m_SamplerLoc = GL_NONE; m_MVPMatLoc = GL_NONE; m_TextureId = GL_NONE; m_VaoId = GL_NONE; m_AngleX = 0; m_AngleY = 0; m_ScaleX = 1.0f; m_ScaleY = 1.0f; m_pCoordSystemSample = new CoordSystemSample(); m_FrameIndex = 0; } BezierCurveSample::~BezierCurveSample() { NativeImageUtil::FreeNativeImage(&m_RenderImage); if (m_pCoordSystemSample != nullptr) { delete m_pCoordSystemSample; m_pCoordSystemSample = nullptr; } } void BezierCurveSample::Init() { if (m_ProgramObj) return; if (m_pCoordSystemSample != nullptr) { m_pCoordSystemSample->Init(); } char vShaderStr[] = "#version 300 es\n" "layout(location = 0) in float a_tData;\n" "uniform vec4 u_StartEndPoints;\n" "uniform vec4 u_ControlPoints;\n" "uniform mat4 u_MVPMatrix;\n" "uniform float u_Offset;\n" "\n" "vec2 bezier3(in vec2 p0, in vec2 p1, in vec2 p2, in vec2 p3, in float t){\n" " float tt = (1.0 - t) * (1.0 -t);\n" " return tt * (1.0 -t) *p0 + 3.0 * t * tt * p1 + 3.0 * t *t *(1.0 -t) *p2 + t *t *t *p3;\n" "}\n" "\n" "vec2 bezier3_(in vec2 p0, in vec2 p1, in vec2 p2, in vec2 p3, in float t)\n" "{\n" " vec2 q0 = mix(p0, p1, t);\n" " vec2 q1 = mix(p1, p2, t);\n" " vec2 q2 = mix(p2, p3, t);\n" "\n" " vec2 r0 = mix(q0, q1, t);\n" " vec2 r1 = mix(q1, q2, t);\n" "\n" " return mix(r0, r1, t);\n" "}\n" "\n" "void main() {\n" "\n" " vec4 pos;\n" " pos.w = 1.0;\n" "\n" " vec2 p0 = u_StartEndPoints.xy;\n" " vec2 p3 = u_StartEndPoints.zw;\n" "\n" " vec2 p1 = u_ControlPoints.xy;\n" " vec2 p2 = u_ControlPoints.zw;\n" "\n" " p0.y *= u_Offset;\n" " p1.y *= u_Offset;\n" " p2.y *= u_Offset;\n" " p3.y *= u_Offset;\n" "\n" " float t = a_tData;\n" "\n" " vec2 point = bezier3_(p0, p1, p2, p3, t);\n" "\n" " if (t < 0.0)\n" " {\n" " pos.xy = vec2(0.0, 0.0);\n" " }\n" " else\n" " {\n" " pos.xy = point;\n" " }\n" " gl_PointSize = 4.0;\n" " gl_Position = u_MVPMatrix * pos;\n" "}"; char fShaderStr[] = "#version 300 es\n" "precision mediump float;\n" "layout(location = 0) out vec4 outColor;\n" "uniform vec4 u_Color;\n" "void main()\n" "{\n" " //outColor = texture(s_TextureMap, v_texCoord);\n" " outColor = u_Color;\n" "}"; m_ProgramObj = GLUtils::CreateProgram(vShaderStr, fShaderStr, m_VertexShader, m_FragmentShader); if (!m_ProgramObj) { LOGCATE("BezierCurveSample::Init create program fail"); } int tDataSize = POINTS_NUM * POINTS_PRE_TRIANGLES; float *p_tData = new float[tDataSize]; for (int i = 0; i < tDataSize; i += POINTS_PRE_TRIANGLES) { #ifdef DRAW_POINTS float t0 = (float) i / tDataSize; float t1 = (float) (i + 1) / tDataSize; float t2 = (float) (i + 2) / tDataSize; p_tData[i] = t0; p_tData[i + 1] = t1; p_tData[i + 2] = t2; #else float t = (float) i / tDataSize; float t1 = (float) (i + 3) / tDataSize; p_tData[i] = t; p_tData[i + 1] = t1; p_tData[i + 2] = -1; #endif } // Generate VBO Ids and load the VBOs with data glGenBuffers(1, &m_VboId); glBindBuffer(GL_ARRAY_BUFFER, m_VboId); glBufferData(GL_ARRAY_BUFFER, sizeof(float) * tDataSize, p_tData, GL_STATIC_DRAW); delete[] p_tData; // Generate VAO Id glGenVertexArrays(1, &m_VaoId); glBindVertexArray(m_VaoId); glBindBuffer(GL_ARRAY_BUFFER, m_VboId); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 1, GL_FLOAT, GL_FALSE, sizeof(GLfloat), (const void *) 0); glBindBuffer(GL_ARRAY_BUFFER, GL_NONE); glBindVertexArray(GL_NONE); } void BezierCurveSample::LoadImage(NativeImage *pImage) { LOGCATE("BezierCurveSample::LoadImage pImage = %p", pImage->ppPlane[0]); if (m_pCoordSystemSample != nullptr) { m_pCoordSystemSample->LoadImage(pImage); } } void BezierCurveSample::Draw(int screenW, int screenH) { LOGCATE("BezierCurveSample::Draw()"); if (m_pCoordSystemSample != nullptr) { //m_pCoordSystemSample->Draw(screenW, screenH); } glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClearColor(0.1, 0.1, 0.1, 0.1); if (m_ProgramObj == GL_NONE) return; m_FrameIndex++; UpdateMVPMatrix(m_MVPMatrix, m_AngleX, m_AngleY, (float) screenW / screenH); // Use the program object glUseProgram(m_ProgramObj); glEnable(GL_BLEND); glBlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_COLOR, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); // Screen blend mode glBlendEquationSeparate(GL_FUNC_ADD, GL_FUNC_ADD); glBindVertexArray(m_VaoId); //draw one GLUtils::setMat4(m_ProgramObj, "u_MVPMatrix", m_MVPMatrix); GLUtils::setVec4(m_ProgramObj, "u_StartEndPoints", glm::vec4(-1, 0, 1, 0)); GLUtils::setVec4(m_ProgramObj, "u_ControlPoints", glm::vec4(-0.04f, 0.99f, 0.0f, 0.99f)); GLUtils::setVec4(m_ProgramObj, "u_Color", glm::vec4(1.0f, 0.3f, 0.0f, 1.0f)); float offset = (m_FrameIndex % 100) * 1.0f / 100; offset = (m_FrameIndex / 100) % 2 == 1 ? (1 - offset) : offset; GLUtils::setFloat(m_ProgramObj, "u_Offset", offset); DrawArray(); UpdateMVPMatrix(m_MVPMatrix, 180, m_AngleY, (float) screenW / screenH); GLUtils::setMat4(m_ProgramObj, "u_MVPMatrix", m_MVPMatrix); DrawArray(); //draw two int newIndex = m_FrameIndex + 33; offset = (newIndex % 100) * 1.0f / 100; offset = (newIndex / 100) % 2 == 1 ? (1 - offset) : offset; GLUtils::setFloat(m_ProgramObj, "u_Offset", offset); GLUtils::setVec4(m_ProgramObj, "u_Color", glm::vec4(0.0f, 0.3f, 0.8f, 1.0f)); GLUtils::setVec4(m_ProgramObj, "u_ControlPoints", glm::vec4(-0.8f, 0.99f, 0.0f, 0.0f)); UpdateMVPMatrix(m_MVPMatrix, m_AngleX, m_AngleY, (float) screenW / screenH); GLUtils::setMat4(m_ProgramObj, "u_MVPMatrix", m_MVPMatrix); DrawArray(); UpdateMVPMatrix(m_MVPMatrix, 180, m_AngleY, (float) screenW / screenH); GLUtils::setMat4(m_ProgramObj, "u_MVPMatrix", m_MVPMatrix); DrawArray(); //draw three newIndex = newIndex + 33; offset = (newIndex % 100) * 1.0f / 100; offset = (newIndex / 100) % 2 == 1 ? (1 - offset) : offset; GLUtils::setFloat(m_ProgramObj, "u_Offset", offset); GLUtils::setVec4(m_ProgramObj, "u_Color", glm::vec4(0.1f, 0.6f, 0.3f, 1.0f)); GLUtils::setVec4(m_ProgramObj, "u_ControlPoints", glm::vec4(0.0f, 0.0f, 0.8f, 0.99f)); UpdateMVPMatrix(m_MVPMatrix, m_AngleX, m_AngleY, (float) screenW / screenH); GLUtils::setMat4(m_ProgramObj, "u_MVPMatrix", m_MVPMatrix); DrawArray(); UpdateMVPMatrix(m_MVPMatrix, 180, m_AngleY, (float) screenW / screenH); GLUtils::setMat4(m_ProgramObj, "u_MVPMatrix", m_MVPMatrix); DrawArray(); //draw four newIndex = newIndex + 33; offset = (newIndex % 100) * 1.0f / 100; offset = (newIndex / 100) % 2 == 1 ? (1 - offset) : offset; GLUtils::setFloat(m_ProgramObj, "u_Offset", offset); GLUtils::setVec4(m_ProgramObj, "u_Color", glm::vec4(1.0f, 0.0f, 0.3f, 1.0f)); GLUtils::setVec4(m_ProgramObj, "u_ControlPoints", glm::vec4(-0.2f, 0.99f, 0.0f, 0.0f)); UpdateMVPMatrix(m_MVPMatrix, m_AngleX, m_AngleY, (float) screenW / screenH); GLUtils::setMat4(m_ProgramObj, "u_MVPMatrix", m_MVPMatrix); DrawArray(); UpdateMVPMatrix(m_MVPMatrix, 180, m_AngleY, (float) screenW / screenH); GLUtils::setMat4(m_ProgramObj, "u_MVPMatrix", m_MVPMatrix); DrawArray(); //draw five newIndex = newIndex + 33; offset = (newIndex % 100) * 1.0f / 100; offset = (newIndex / 100) % 2 == 1 ? (1 - offset) : offset; GLUtils::setFloat(m_ProgramObj, "u_Offset", offset); GLUtils::setVec4(m_ProgramObj, "u_Color", glm::vec4(1.0f, 0.0f, 0.0f, 1.0f)); GLUtils::setVec4(m_ProgramObj, "u_ControlPoints", glm::vec4(0.0f, 0.0f, 0.2f, 0.99f)); UpdateMVPMatrix(m_MVPMatrix, m_AngleX, m_AngleY, (float) screenW / screenH); GLUtils::setMat4(m_ProgramObj, "u_MVPMatrix", m_MVPMatrix); DrawArray(); UpdateMVPMatrix(m_MVPMatrix, 180, m_AngleY, (float) screenW / screenH); GLUtils::setMat4(m_ProgramObj, "u_MVPMatrix", m_MVPMatrix); DrawArray(); glDisable(GL_BLEND); } void BezierCurveSample::Destroy() { if (m_ProgramObj) { glDeleteProgram(m_ProgramObj); glDeleteBuffers(1, &m_VboId); glDeleteVertexArrays(1, &m_VaoId); } if (m_pCoordSystemSample != nullptr) { m_pCoordSystemSample->Destroy(); } } /** * @param angleX 绕X轴旋转度数 * @param angleY 绕Y轴旋转度数 * @param ratio 宽高比 * */ void BezierCurveSample::UpdateMVPMatrix(glm::mat4 &mvpMatrix, int angleX, int angleY, float ratio) { LOGCATE("BezierCurveSample::UpdateMVPMatrix angleX = %d, angleY = %d, ratio = %f", angleX, angleY, ratio); angleX = angleX % 360; angleY = angleY % 360; //转化为弧度角 float radiansX = static_cast<float>(MATH_PI / 180.0f * angleX); float radiansY = static_cast<float>(MATH_PI / 180.0f * angleY); // Projection matrix glm::mat4 Projection = glm::ortho(-1.0f, 1.0f, -1.0f, 1.0f, 0.1f, 100.0f); //glm::mat4 Projection = glm::frustum(-ratio, ratio, -1.0f, 1.0f, 4.0f, 100.0f); //glm::mat4 Projection = glm::perspective(45.0f, ratio, 0.1f, 100.f); // View matrix glm::mat4 View = glm::lookAt( glm::vec3(0, 0, 4), // Camera is at (0,0,1), in World Space glm::vec3(0, 0, 0), // and looks at the origin glm::vec3(0, 1, 0) // Head is up (set to 0,-1,0 to look upside-down) ); // Model matrix glm::mat4 Model = glm::mat4(1.0f); Model = glm::scale(Model, glm::vec3(m_ScaleX, m_ScaleY, 1.0f)); Model = glm::rotate(Model, radiansX, glm::vec3(1.0f, 0.0f, 0.0f)); Model = glm::rotate(Model, radiansY, glm::vec3(0.0f, 1.0f, 0.0f)); Model = glm::translate(Model, glm::vec3(0.0f, 0.0f, 0.0f)); mvpMatrix = Projection * View * Model; } void BezierCurveSample::UpdateTransformMatrix(float rotateX, float rotateY, float scaleX, float scaleY) { GLSampleBase::UpdateTransformMatrix(rotateX, rotateY, scaleX, scaleY); m_AngleX = static_cast<int>(rotateX); m_AngleY = static_cast<int>(rotateY); m_ScaleX = scaleX; m_ScaleY = scaleY; if (m_pCoordSystemSample != nullptr) { m_pCoordSystemSample->UpdateTransformMatrix(rotateX, rotateY, scaleX, scaleY); } } void BezierCurveSample::DrawArray() { #ifdef DRAW_POINTS glDrawArrays(GL_POINTS, 0, POINTS_NUM * TRIANGLES_PER_POINT); #else glDrawArrays(GL_TRIANGLES, 0, POINTS_NUM * POINTS_PRE_TRIANGLES); glDrawArrays(GL_LINES, 0, POINTS_NUM * POINTS_PRE_TRIANGLES); #endif }
32.743169
109
0.588201
[ "object", "model" ]
c8ee1455ad1be3f69926874b80fc211650ca7c75
5,858
hpp
C++
include/UnityEngine/ProBuilder/TriggerBehaviour.hpp
sc2ad/BeatSaber-Quest-Codegen
ba8acaae541cfe1161e05fbc3bf87f4bc46bc4ab
[ "Unlicense" ]
23
2020-08-07T04:09:00.000Z
2022-03-31T22:10:29.000Z
include/UnityEngine/ProBuilder/TriggerBehaviour.hpp
sc2ad/BeatSaber-Quest-Codegen
ba8acaae541cfe1161e05fbc3bf87f4bc46bc4ab
[ "Unlicense" ]
6
2021-09-29T23:47:31.000Z
2022-03-30T20:49:23.000Z
include/UnityEngine/ProBuilder/TriggerBehaviour.hpp
sc2ad/BeatSaber-Quest-Codegen
ba8acaae541cfe1161e05fbc3bf87f4bc46bc4ab
[ "Unlicense" ]
17
2020-08-20T19:36:52.000Z
2022-03-30T18:28:24.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/byref.hpp" // Including type: UnityEngine.ProBuilder.EntityBehaviour #include "UnityEngine/ProBuilder/EntityBehaviour.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: UnityEngine::SceneManagement namespace UnityEngine::SceneManagement { // Forward declaring type: Scene struct Scene; // Forward declaring type: LoadSceneMode struct LoadSceneMode; } // Completed forward declares // Type namespace: UnityEngine.ProBuilder namespace UnityEngine::ProBuilder { // Forward declaring type: TriggerBehaviour class TriggerBehaviour; } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(UnityEngine::ProBuilder::TriggerBehaviour); DEFINE_IL2CPP_ARG_TYPE(UnityEngine::ProBuilder::TriggerBehaviour*, "UnityEngine.ProBuilder", "TriggerBehaviour"); // Type namespace: UnityEngine.ProBuilder namespace UnityEngine::ProBuilder { // Size: 0x19 #pragma pack(push, 1) // Autogenerated type: UnityEngine.ProBuilder.TriggerBehaviour // [TokenAttribute] Offset: FFFFFFFF // [DisallowMultipleComponent] Offset: FFFFFFFF class TriggerBehaviour : public UnityEngine::ProBuilder::EntityBehaviour { public: // public System.Void .ctor() // Offset: 0x24D85CC // Implemented from: UnityEngine.ProBuilder.EntityBehaviour // Base method: System.Void EntityBehaviour::.ctor() // Base method: System.Void MonoBehaviour::.ctor() // Base method: System.Void Behaviour::.ctor() // Base method: System.Void Component::.ctor() // Base method: System.Void Object::.ctor() // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static TriggerBehaviour* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::ProBuilder::TriggerBehaviour::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<TriggerBehaviour*, creationType>())); } // public override System.Void Initialize() // Offset: 0x24D8274 // Implemented from: UnityEngine.ProBuilder.EntityBehaviour // Base method: System.Void EntityBehaviour::Initialize() void Initialize(); // public override System.Void OnEnterPlayMode() // Offset: 0x24D846C // Implemented from: UnityEngine.ProBuilder.EntityBehaviour // Base method: System.Void EntityBehaviour::OnEnterPlayMode() void OnEnterPlayMode(); // public override System.Void OnSceneLoaded(UnityEngine.SceneManagement.Scene scene, UnityEngine.SceneManagement.LoadSceneMode mode) // Offset: 0x24D851C // Implemented from: UnityEngine.ProBuilder.EntityBehaviour // Base method: System.Void EntityBehaviour::OnSceneLoaded(UnityEngine.SceneManagement.Scene scene, UnityEngine.SceneManagement.LoadSceneMode mode) void OnSceneLoaded(UnityEngine::SceneManagement::Scene scene, UnityEngine::SceneManagement::LoadSceneMode mode); }; // UnityEngine.ProBuilder.TriggerBehaviour #pragma pack(pop) } #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: UnityEngine::ProBuilder::TriggerBehaviour::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: UnityEngine::ProBuilder::TriggerBehaviour::Initialize // Il2CppName: Initialize template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::ProBuilder::TriggerBehaviour::*)()>(&UnityEngine::ProBuilder::TriggerBehaviour::Initialize)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::ProBuilder::TriggerBehaviour*), "Initialize", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::ProBuilder::TriggerBehaviour::OnEnterPlayMode // Il2CppName: OnEnterPlayMode template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::ProBuilder::TriggerBehaviour::*)()>(&UnityEngine::ProBuilder::TriggerBehaviour::OnEnterPlayMode)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::ProBuilder::TriggerBehaviour*), "OnEnterPlayMode", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::ProBuilder::TriggerBehaviour::OnSceneLoaded // Il2CppName: OnSceneLoaded template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::ProBuilder::TriggerBehaviour::*)(UnityEngine::SceneManagement::Scene, UnityEngine::SceneManagement::LoadSceneMode)>(&UnityEngine::ProBuilder::TriggerBehaviour::OnSceneLoaded)> { static const MethodInfo* get() { static auto* scene = &::il2cpp_utils::GetClassFromName("UnityEngine.SceneManagement", "Scene")->byval_arg; static auto* mode = &::il2cpp_utils::GetClassFromName("UnityEngine.SceneManagement", "LoadSceneMode")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::ProBuilder::TriggerBehaviour*), "OnSceneLoaded", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{scene, mode}); } };
56.326923
266
0.747695
[ "object", "vector" ]
c8f0636113aac94dabacd137eb379bafa56c7f95
251
cc
C++
Ray.cc
KXue/CLRT
2b2dcb3addf5f638cda86fb03322779e0a33aee1
[ "MIT" ]
null
null
null
Ray.cc
KXue/CLRT
2b2dcb3addf5f638cda86fb03322779e0a33aee1
[ "MIT" ]
null
null
null
Ray.cc
KXue/CLRT
2b2dcb3addf5f638cda86fb03322779e0a33aee1
[ "MIT" ]
null
null
null
#include "geometry.hpp" #include <iostream> Ray::Ray(Vec_3t origin, Vec_3t dir) : m_origin(Vec_3t(origin)), m_dir(Vec_3t(dir)){}; Ray::~Ray(){}; Vec_3t Ray::GetDirection() const { return m_dir; }; Vec_3t Ray::GetOrigin() const { return m_origin; };
27.888889
85
0.693227
[ "geometry" ]
c8f1e31513e0bcb413eb92da1010500c703a3bd3
1,653
hpp
C++
src/closed/closed.hpp
shunjilin/SlidingTilesPuzzle
cff6e75b58ee41c379f97b20c89d50d8d4d8c416
[ "MIT" ]
4
2018-08-28T12:27:44.000Z
2018-12-06T15:14:14.000Z
src/closed/closed.hpp
shunjilin/24Puzzle
cff6e75b58ee41c379f97b20c89d50d8d4d8c416
[ "MIT" ]
1
2019-06-13T16:11:42.000Z
2019-07-04T11:50:39.000Z
src/closed/closed.hpp
shunjilin/24Puzzle
cff6e75b58ee41c379f97b20c89d50d8d4d8c416
[ "MIT" ]
1
2018-12-04T12:35:04.000Z
2018-12-04T12:35:04.000Z
#ifndef CLOSED_HPP #define CLOSED_HPP #include <unordered_set> #include <vector> #include <algorithm> #include <ostream> /* Minimal Closed List Implementation * Requires node to have default hasher for equality comparison. */ template <typename Node> struct Closed { std::unordered_set<Node> closed; // returns true if node needs to be expanded, // insert node if not already exist in closed, or if lower f-val than // existing closed node bool insert(Node node); // given node, return path in closed list by tracing parent nodes // assumes node is in the closed list; otherwise returns empty path std::vector<Node> getPath(Node const &node) const; }; template <typename Node> bool Closed<Node>::insert(Node node) { auto found = closed.find(node); if (found != closed.end()) { if (getF(node) >= getF(*found)) { return false; } closed.erase(found); // reopening } closed.insert(std::move(node)); return true; } template <typename Node> std::vector<Node> Closed<Node>::getPath(Node const &node) const { std::vector<Node> path; auto found = closed.find(node); while (found != closed.end()) { path.push_back(*found); auto parent = getParent(*found); if (!parent.has_value()) { break; } found = closed.find(*parent); } std::reverse(path.begin(), path.end()); return path; } template <typename Node> std::ostream &operator<<(std::ostream& os, Closed<Node> const & closed) { os << "closed list load factor: " << closed.closed.load_factor() << "\n"; return os; } #endif
25.828125
73
0.637024
[ "vector" ]
c8f50dc21375bf8541e388076d16c4495f351c6b
14,198
cpp
C++
exportNF/release/windows/obj/src/lime/net/_HTTPRequest/AbstractHTTPRequest.cpp
theblobscp/NekoFreakMod-FridayNightFunkin
232bcb08234cfe881fd6d52b13e6ae443e105fd1
[ "BSD-3-Clause" ]
null
null
null
exportNF/release/windows/obj/src/lime/net/_HTTPRequest/AbstractHTTPRequest.cpp
theblobscp/NekoFreakMod-FridayNightFunkin
232bcb08234cfe881fd6d52b13e6ae443e105fd1
[ "BSD-3-Clause" ]
null
null
null
exportNF/release/windows/obj/src/lime/net/_HTTPRequest/AbstractHTTPRequest.cpp
theblobscp/NekoFreakMod-FridayNightFunkin
232bcb08234cfe881fd6d52b13e6ae443e105fd1
[ "BSD-3-Clause" ]
null
null
null
// Generated by Haxe 4.2.1+bf9ff69 #include <hxcpp.h> #ifndef INCLUDED_haxe_IMap #include <haxe/IMap.h> #endif #ifndef INCLUDED_haxe_ds_StringMap #include <haxe/ds/StringMap.h> #endif #ifndef INCLUDED_haxe_io_Bytes #include <haxe/io/Bytes.h> #endif #ifndef INCLUDED_lime__internal_backend_native_NativeHTTPRequest #include <lime/_internal/backend/native/NativeHTTPRequest.h> #endif #ifndef INCLUDED_lime_app_Future #include <lime/app/Future.h> #endif #ifndef INCLUDED_lime_net_HTTPRequestHeader #include <lime/net/HTTPRequestHeader.h> #endif #ifndef INCLUDED_lime_net__HTTPRequest_AbstractHTTPRequest #include <lime/net/_HTTPRequest/AbstractHTTPRequest.h> #endif #ifndef INCLUDED_lime_net__IHTTPRequest #include <lime/net/_IHTTPRequest.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_bc0cf2bf735ddd18_49_new,"lime.net._HTTPRequest.AbstractHTTPRequest","new",0x2f7ffcbb,"lime.net._HTTPRequest.AbstractHTTPRequest.new","lime/net/HTTPRequest.hx",49,0x339db723) HX_LOCAL_STACK_FRAME(_hx_pos_bc0cf2bf735ddd18_70_cancel,"lime.net._HTTPRequest.AbstractHTTPRequest","cancel",0x9e11abff,"lime.net._HTTPRequest.AbstractHTTPRequest.cancel","lime/net/HTTPRequest.hx",70,0x339db723) HX_LOCAL_STACK_FRAME(_hx_pos_bc0cf2bf735ddd18_76_load,"lime.net._HTTPRequest.AbstractHTTPRequest","load",0x5f323d6b,"lime.net._HTTPRequest.AbstractHTTPRequest.load","lime/net/HTTPRequest.hx",76,0x339db723) namespace lime{ namespace net{ namespace _HTTPRequest{ void AbstractHTTPRequest_obj::__construct(::String uri){ HX_GC_STACKFRAME(&_hx_pos_bc0cf2bf735ddd18_49_new) HXLINE( 50) this->uri = uri; HXLINE( 52) this->contentType = HX_("application/x-www-form-urlencoded",9e,61,91,fa); HXLINE( 53) this->followRedirects = true; HXLINE( 54) this->enableResponseHeaders = false; HXLINE( 55) this->formData = ::haxe::ds::StringMap_obj::__alloc( HX_CTX ); HXLINE( 56) this->headers = ::Array_obj< ::Dynamic>::__new(0); HXLINE( 57) this->method = HX_("GET",76,1c,36,00); HXLINE( 58) this->timeout = 30000; HXLINE( 59) this->withCredentials = false; HXLINE( 62) this->_hx___backend = ::lime::_internal::backend::native::NativeHTTPRequest_obj::__alloc( HX_CTX ); HXLINE( 63) this->_hx___backend->init(::hx::ObjectPtr<OBJ_>(this)); } Dynamic AbstractHTTPRequest_obj::__CreateEmpty() { return new AbstractHTTPRequest_obj; } void *AbstractHTTPRequest_obj::_hx_vtable = 0; Dynamic AbstractHTTPRequest_obj::__Create(::hx::DynamicArray inArgs) { ::hx::ObjectPtr< AbstractHTTPRequest_obj > _hx_result = new AbstractHTTPRequest_obj(); _hx_result->__construct(inArgs[0]); return _hx_result; } bool AbstractHTTPRequest_obj::_hx_isInstanceOf(int inClassId) { return inClassId==(int)0x00000001 || inClassId==(int)0x09b24b15; } static ::lime::net::_IHTTPRequest_obj _hx_lime_net__HTTPRequest_AbstractHTTPRequest__hx_lime_net__IHTTPRequest= { ( void (::hx::Object::*)())&::lime::net::_HTTPRequest::AbstractHTTPRequest_obj::cancel, }; void *AbstractHTTPRequest_obj::_hx_getInterface(int inHash) { switch(inHash) { case (int)0x154a91b5: return &_hx_lime_net__HTTPRequest_AbstractHTTPRequest__hx_lime_net__IHTTPRequest; } #ifdef HXCPP_SCRIPTABLE return super::_hx_getInterface(inHash); #else return 0; #endif } void AbstractHTTPRequest_obj::cancel(){ HX_STACKFRAME(&_hx_pos_bc0cf2bf735ddd18_70_cancel) HXDLIN( 70) this->_hx___backend->cancel(); } HX_DEFINE_DYNAMIC_FUNC0(AbstractHTTPRequest_obj,cancel,(void)) ::lime::app::Future AbstractHTTPRequest_obj::load(::String uri){ HX_STACKFRAME(&_hx_pos_bc0cf2bf735ddd18_76_load) HXDLIN( 76) return null(); } HX_DEFINE_DYNAMIC_FUNC1(AbstractHTTPRequest_obj,load,return ) ::hx::ObjectPtr< AbstractHTTPRequest_obj > AbstractHTTPRequest_obj::__new(::String uri) { ::hx::ObjectPtr< AbstractHTTPRequest_obj > __this = new AbstractHTTPRequest_obj(); __this->__construct(uri); return __this; } ::hx::ObjectPtr< AbstractHTTPRequest_obj > AbstractHTTPRequest_obj::__alloc(::hx::Ctx *_hx_ctx,::String uri) { AbstractHTTPRequest_obj *__this = (AbstractHTTPRequest_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(AbstractHTTPRequest_obj), true, "lime.net._HTTPRequest.AbstractHTTPRequest")); *(void **)__this = AbstractHTTPRequest_obj::_hx_vtable; __this->__construct(uri); return __this; } AbstractHTTPRequest_obj::AbstractHTTPRequest_obj() { } void AbstractHTTPRequest_obj::__Mark(HX_MARK_PARAMS) { HX_MARK_BEGIN_CLASS(AbstractHTTPRequest); HX_MARK_MEMBER_NAME(contentType,"contentType"); HX_MARK_MEMBER_NAME(data,"data"); HX_MARK_MEMBER_NAME(enableResponseHeaders,"enableResponseHeaders"); HX_MARK_MEMBER_NAME(followRedirects,"followRedirects"); HX_MARK_MEMBER_NAME(formData,"formData"); HX_MARK_MEMBER_NAME(headers,"headers"); HX_MARK_MEMBER_NAME(method,"method"); HX_MARK_MEMBER_NAME(responseData,"responseData"); HX_MARK_MEMBER_NAME(responseHeaders,"responseHeaders"); HX_MARK_MEMBER_NAME(responseStatus,"responseStatus"); HX_MARK_MEMBER_NAME(timeout,"timeout"); HX_MARK_MEMBER_NAME(uri,"uri"); HX_MARK_MEMBER_NAME(userAgent,"userAgent"); HX_MARK_MEMBER_NAME(withCredentials,"withCredentials"); HX_MARK_MEMBER_NAME(_hx___backend,"__backend"); HX_MARK_END_CLASS(); } void AbstractHTTPRequest_obj::__Visit(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(contentType,"contentType"); HX_VISIT_MEMBER_NAME(data,"data"); HX_VISIT_MEMBER_NAME(enableResponseHeaders,"enableResponseHeaders"); HX_VISIT_MEMBER_NAME(followRedirects,"followRedirects"); HX_VISIT_MEMBER_NAME(formData,"formData"); HX_VISIT_MEMBER_NAME(headers,"headers"); HX_VISIT_MEMBER_NAME(method,"method"); HX_VISIT_MEMBER_NAME(responseData,"responseData"); HX_VISIT_MEMBER_NAME(responseHeaders,"responseHeaders"); HX_VISIT_MEMBER_NAME(responseStatus,"responseStatus"); HX_VISIT_MEMBER_NAME(timeout,"timeout"); HX_VISIT_MEMBER_NAME(uri,"uri"); HX_VISIT_MEMBER_NAME(userAgent,"userAgent"); HX_VISIT_MEMBER_NAME(withCredentials,"withCredentials"); HX_VISIT_MEMBER_NAME(_hx___backend,"__backend"); } ::hx::Val AbstractHTTPRequest_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 3: if (HX_FIELD_EQ(inName,"uri") ) { return ::hx::Val( uri ); } break; case 4: if (HX_FIELD_EQ(inName,"data") ) { return ::hx::Val( data ); } if (HX_FIELD_EQ(inName,"load") ) { return ::hx::Val( load_dyn() ); } break; case 6: if (HX_FIELD_EQ(inName,"method") ) { return ::hx::Val( method ); } if (HX_FIELD_EQ(inName,"cancel") ) { return ::hx::Val( cancel_dyn() ); } break; case 7: if (HX_FIELD_EQ(inName,"headers") ) { return ::hx::Val( headers ); } if (HX_FIELD_EQ(inName,"timeout") ) { return ::hx::Val( timeout ); } break; case 8: if (HX_FIELD_EQ(inName,"formData") ) { return ::hx::Val( formData ); } break; case 9: if (HX_FIELD_EQ(inName,"userAgent") ) { return ::hx::Val( userAgent ); } if (HX_FIELD_EQ(inName,"__backend") ) { return ::hx::Val( _hx___backend ); } break; case 11: if (HX_FIELD_EQ(inName,"contentType") ) { return ::hx::Val( contentType ); } break; case 12: if (HX_FIELD_EQ(inName,"responseData") ) { return ::hx::Val( responseData ); } break; case 14: if (HX_FIELD_EQ(inName,"responseStatus") ) { return ::hx::Val( responseStatus ); } break; case 15: if (HX_FIELD_EQ(inName,"followRedirects") ) { return ::hx::Val( followRedirects ); } if (HX_FIELD_EQ(inName,"responseHeaders") ) { return ::hx::Val( responseHeaders ); } if (HX_FIELD_EQ(inName,"withCredentials") ) { return ::hx::Val( withCredentials ); } break; case 21: if (HX_FIELD_EQ(inName,"enableResponseHeaders") ) { return ::hx::Val( enableResponseHeaders ); } } return super::__Field(inName,inCallProp); } ::hx::Val AbstractHTTPRequest_obj::__SetField(const ::String &inName,const ::hx::Val &inValue,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 3: if (HX_FIELD_EQ(inName,"uri") ) { uri=inValue.Cast< ::String >(); return inValue; } break; case 4: if (HX_FIELD_EQ(inName,"data") ) { data=inValue.Cast< ::haxe::io::Bytes >(); return inValue; } break; case 6: if (HX_FIELD_EQ(inName,"method") ) { method=inValue.Cast< ::String >(); return inValue; } break; case 7: if (HX_FIELD_EQ(inName,"headers") ) { headers=inValue.Cast< ::Array< ::Dynamic> >(); return inValue; } if (HX_FIELD_EQ(inName,"timeout") ) { timeout=inValue.Cast< int >(); return inValue; } break; case 8: if (HX_FIELD_EQ(inName,"formData") ) { formData=inValue.Cast< ::haxe::ds::StringMap >(); return inValue; } break; case 9: if (HX_FIELD_EQ(inName,"userAgent") ) { userAgent=inValue.Cast< ::String >(); return inValue; } if (HX_FIELD_EQ(inName,"__backend") ) { _hx___backend=inValue.Cast< ::lime::_internal::backend::native::NativeHTTPRequest >(); return inValue; } break; case 11: if (HX_FIELD_EQ(inName,"contentType") ) { contentType=inValue.Cast< ::String >(); return inValue; } break; case 12: if (HX_FIELD_EQ(inName,"responseData") ) { responseData=inValue.Cast< ::Dynamic >(); return inValue; } break; case 14: if (HX_FIELD_EQ(inName,"responseStatus") ) { responseStatus=inValue.Cast< int >(); return inValue; } break; case 15: if (HX_FIELD_EQ(inName,"followRedirects") ) { followRedirects=inValue.Cast< bool >(); return inValue; } if (HX_FIELD_EQ(inName,"responseHeaders") ) { responseHeaders=inValue.Cast< ::Array< ::Dynamic> >(); return inValue; } if (HX_FIELD_EQ(inName,"withCredentials") ) { withCredentials=inValue.Cast< bool >(); return inValue; } break; case 21: if (HX_FIELD_EQ(inName,"enableResponseHeaders") ) { enableResponseHeaders=inValue.Cast< bool >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } void AbstractHTTPRequest_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_("contentType",93,3c,7b,2a)); outFields->push(HX_("data",2a,56,63,42)); outFields->push(HX_("enableResponseHeaders",82,32,47,05)); outFields->push(HX_("followRedirects",26,5a,40,75)); outFields->push(HX_("formData",8e,d5,80,56)); outFields->push(HX_("headers",46,52,08,63)); outFields->push(HX_("method",e1,f6,5a,09)); outFields->push(HX_("responseData",4b,05,e9,c4)); outFields->push(HX_("responseHeaders",c5,0d,ca,43)); outFields->push(HX_("responseStatus",93,60,a4,78)); outFields->push(HX_("timeout",a1,1a,f7,d8)); outFields->push(HX_("uri",6c,2b,59,00)); outFields->push(HX_("userAgent",7a,f0,12,c8)); outFields->push(HX_("withCredentials",56,86,c4,ca)); outFields->push(HX_("__backend",f4,0c,d6,7c)); super::__GetFields(outFields); }; #ifdef HXCPP_SCRIPTABLE static ::hx::StorageInfo AbstractHTTPRequest_obj_sMemberStorageInfo[] = { {::hx::fsString,(int)offsetof(AbstractHTTPRequest_obj,contentType),HX_("contentType",93,3c,7b,2a)}, {::hx::fsObject /* ::haxe::io::Bytes */ ,(int)offsetof(AbstractHTTPRequest_obj,data),HX_("data",2a,56,63,42)}, {::hx::fsBool,(int)offsetof(AbstractHTTPRequest_obj,enableResponseHeaders),HX_("enableResponseHeaders",82,32,47,05)}, {::hx::fsBool,(int)offsetof(AbstractHTTPRequest_obj,followRedirects),HX_("followRedirects",26,5a,40,75)}, {::hx::fsObject /* ::haxe::ds::StringMap */ ,(int)offsetof(AbstractHTTPRequest_obj,formData),HX_("formData",8e,d5,80,56)}, {::hx::fsObject /* ::Array< ::Dynamic> */ ,(int)offsetof(AbstractHTTPRequest_obj,headers),HX_("headers",46,52,08,63)}, {::hx::fsString,(int)offsetof(AbstractHTTPRequest_obj,method),HX_("method",e1,f6,5a,09)}, {::hx::fsObject /* ::Dynamic */ ,(int)offsetof(AbstractHTTPRequest_obj,responseData),HX_("responseData",4b,05,e9,c4)}, {::hx::fsObject /* ::Array< ::Dynamic> */ ,(int)offsetof(AbstractHTTPRequest_obj,responseHeaders),HX_("responseHeaders",c5,0d,ca,43)}, {::hx::fsInt,(int)offsetof(AbstractHTTPRequest_obj,responseStatus),HX_("responseStatus",93,60,a4,78)}, {::hx::fsInt,(int)offsetof(AbstractHTTPRequest_obj,timeout),HX_("timeout",a1,1a,f7,d8)}, {::hx::fsString,(int)offsetof(AbstractHTTPRequest_obj,uri),HX_("uri",6c,2b,59,00)}, {::hx::fsString,(int)offsetof(AbstractHTTPRequest_obj,userAgent),HX_("userAgent",7a,f0,12,c8)}, {::hx::fsBool,(int)offsetof(AbstractHTTPRequest_obj,withCredentials),HX_("withCredentials",56,86,c4,ca)}, {::hx::fsObject /* ::lime::_internal::backend::native::NativeHTTPRequest */ ,(int)offsetof(AbstractHTTPRequest_obj,_hx___backend),HX_("__backend",f4,0c,d6,7c)}, { ::hx::fsUnknown, 0, null()} }; static ::hx::StaticInfo *AbstractHTTPRequest_obj_sStaticStorageInfo = 0; #endif static ::String AbstractHTTPRequest_obj_sMemberFields[] = { HX_("contentType",93,3c,7b,2a), HX_("data",2a,56,63,42), HX_("enableResponseHeaders",82,32,47,05), HX_("followRedirects",26,5a,40,75), HX_("formData",8e,d5,80,56), HX_("headers",46,52,08,63), HX_("method",e1,f6,5a,09), HX_("responseData",4b,05,e9,c4), HX_("responseHeaders",c5,0d,ca,43), HX_("responseStatus",93,60,a4,78), HX_("timeout",a1,1a,f7,d8), HX_("uri",6c,2b,59,00), HX_("userAgent",7a,f0,12,c8), HX_("withCredentials",56,86,c4,ca), HX_("__backend",f4,0c,d6,7c), HX_("cancel",7a,ed,33,b8), HX_("load",26,9a,b7,47), ::String(null()) }; ::hx::Class AbstractHTTPRequest_obj::__mClass; void AbstractHTTPRequest_obj::__register() { AbstractHTTPRequest_obj _hx_dummy; AbstractHTTPRequest_obj::_hx_vtable = *(void **)&_hx_dummy; ::hx::Static(__mClass) = new ::hx::Class_obj(); __mClass->mName = HX_("lime.net._HTTPRequest.AbstractHTTPRequest",49,83,86,4f); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &::hx::Class_obj::GetNoStaticField; __mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField; __mClass->mStatics = ::hx::Class_obj::dupFunctions(0 /* sStaticFields */); __mClass->mMembers = ::hx::Class_obj::dupFunctions(AbstractHTTPRequest_obj_sMemberFields); __mClass->mCanCast = ::hx::TCanCast< AbstractHTTPRequest_obj >; #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = AbstractHTTPRequest_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = AbstractHTTPRequest_obj_sStaticStorageInfo; #endif ::hx::_hx_RegisterClass(__mClass->mName, __mClass); } } // end namespace lime } // end namespace net } // end namespace _HTTPRequest
42.636637
211
0.742217
[ "object" ]
c8f86bbec03b62607f4dc1e9089f901cbef500e1
5,629
cpp
C++
samples/SimpleTexturedDirectx11/SimpleTexturedDirectx11/ModelLoader.cpp
stoopdapoop/assimp
ced3fb59a4958cf1cb321a5710a2e7b1f3215d44
[ "BSD-3-Clause" ]
4
2021-01-09T02:18:48.000Z
2022-03-08T04:34:16.000Z
samples/SimpleTexturedDirectx11/SimpleTexturedDirectx11/ModelLoader.cpp
stoopdapoop/assimp
ced3fb59a4958cf1cb321a5710a2e7b1f3215d44
[ "BSD-3-Clause" ]
null
null
null
samples/SimpleTexturedDirectx11/SimpleTexturedDirectx11/ModelLoader.cpp
stoopdapoop/assimp
ced3fb59a4958cf1cb321a5710a2e7b1f3215d44
[ "BSD-3-Clause" ]
1
2021-01-09T00:57:10.000Z
2021-01-09T00:57:10.000Z
#include "ModelLoader.h" ModelLoader::ModelLoader() : dev_(nullptr), devcon_(nullptr), meshes_(), directory_(), textures_loaded_(), hwnd_(nullptr) { // empty } ModelLoader::~ModelLoader() { // empty } bool ModelLoader::Load(HWND hwnd, ID3D11Device * dev, ID3D11DeviceContext * devcon, std::string filename) { Assimp::Importer importer; const aiScene* pScene = importer.ReadFile(filename, aiProcess_Triangulate | aiProcess_ConvertToLeftHanded); if (pScene == NULL) return false; this->directory_ = filename.substr(0, filename.find_last_of("/\\")); this->dev_ = dev; this->devcon_ = devcon; this->hwnd_ = hwnd; processNode(pScene->mRootNode, pScene); return true; } void ModelLoader::Draw(ID3D11DeviceContext * devcon) { for (size_t i = 0; i < meshes_.size(); ++i ) { meshes_[i].Draw(devcon); } } std::string textype; Mesh ModelLoader::processMesh(aiMesh * mesh, const aiScene * scene) { // Data to fill std::vector<VERTEX> vertices; std::vector<UINT> indices; std::vector<Texture> textures; if (mesh->mMaterialIndex >= 0) { aiMaterial* mat = scene->mMaterials[mesh->mMaterialIndex]; if (textype.empty()) { textype = determineTextureType(scene, mat); } } // Walk through each of the mesh's vertices for (UINT i = 0; i < mesh->mNumVertices; i++) { VERTEX vertex; vertex.X = mesh->mVertices[i].x; vertex.Y = mesh->mVertices[i].y; vertex.Z = mesh->mVertices[i].z; if (mesh->mTextureCoords[0]) { vertex.texcoord.x = (float)mesh->mTextureCoords[0][i].x; vertex.texcoord.y = (float)mesh->mTextureCoords[0][i].y; } vertices.push_back(vertex); } for (UINT i = 0; i < mesh->mNumFaces; i++) { aiFace face = mesh->mFaces[i]; for (UINT j = 0; j < face.mNumIndices; j++) indices.push_back(face.mIndices[j]); } if (mesh->mMaterialIndex >= 0) { aiMaterial* material = scene->mMaterials[mesh->mMaterialIndex]; std::vector<Texture> diffuseMaps = this->loadMaterialTextures(material, aiTextureType_DIFFUSE, "texture_diffuse", scene); textures.insert(textures.end(), diffuseMaps.begin(), diffuseMaps.end()); } return Mesh(dev_, vertices, indices, textures); } std::vector<Texture> ModelLoader::loadMaterialTextures(aiMaterial * mat, aiTextureType type, std::string typeName, const aiScene * scene) { std::vector<Texture> textures; for (UINT i = 0; i < mat->GetTextureCount(type); i++) { aiString str; mat->GetTexture(type, i, &str); // Check if texture was loaded before and if so, continue to next iteration: skip loading a new texture bool skip = false; for (UINT j = 0; j < textures_loaded_.size(); j++) { if (std::strcmp(textures_loaded_[j].path.c_str(), str.C_Str()) == 0) { textures.push_back(textures_loaded_[j]); skip = true; // A texture with the same filepath has already been loaded, continue to next one. (optimization) break; } } if (!skip) { // If texture hasn't been loaded already, load it HRESULT hr; Texture texture; if (textype == "embedded compressed texture") { int textureindex = getTextureIndex(&str); texture.texture = getTextureFromModel(scene, textureindex); } else { std::string filename = std::string(str.C_Str()); filename = directory_ + '/' + filename; std::wstring filenamews = std::wstring(filename.begin(), filename.end()); hr = CreateWICTextureFromFile(dev_, devcon_, filenamews.c_str(), nullptr, &texture.texture); if (FAILED(hr)) MessageBox(hwnd_, "Texture couldn't be loaded", "Error!", MB_ICONERROR | MB_OK); } texture.type = typeName; texture.path = str.C_Str(); textures.push_back(texture); this->textures_loaded_.push_back(texture); // Store it as texture loaded for entire model, to ensure we won't unnecesery load duplicate textures. } } return textures; } void ModelLoader::Close() { for (auto& t : textures_loaded_) t.Release(); for (size_t i = 0; i < meshes_.size(); i++) { meshes_[i].Close(); } } void ModelLoader::processNode(aiNode * node, const aiScene * scene) { for (UINT i = 0; i < node->mNumMeshes; i++) { aiMesh* mesh = scene->mMeshes[node->mMeshes[i]]; meshes_.push_back(this->processMesh(mesh, scene)); } for (UINT i = 0; i < node->mNumChildren; i++) { this->processNode(node->mChildren[i], scene); } } std::string ModelLoader::determineTextureType(const aiScene * scene, aiMaterial * mat) { aiString textypeStr; mat->GetTexture(aiTextureType_DIFFUSE, 0, &textypeStr); std::string textypeteststr = textypeStr.C_Str(); if (textypeteststr == "*0" || textypeteststr == "*1" || textypeteststr == "*2" || textypeteststr == "*3" || textypeteststr == "*4" || textypeteststr == "*5") { if (scene->mTextures[0]->mHeight == 0) { return "embedded compressed texture"; } else { return "embedded non-compressed texture"; } } if (textypeteststr.find('.') != std::string::npos) { return "textures are on disk"; } return "."; } int ModelLoader::getTextureIndex(aiString * str) { std::string tistr; tistr = str->C_Str(); tistr = tistr.substr(1); return stoi(tistr); } ID3D11ShaderResourceView * ModelLoader::getTextureFromModel(const aiScene * scene, int textureindex) { HRESULT hr; ID3D11ShaderResourceView *texture; int* size = reinterpret_cast<int*>(&scene->mTextures[textureindex]->mWidth); hr = CreateWICTextureFromMemory(dev_, devcon_, reinterpret_cast<unsigned char*>(scene->mTextures[textureindex]->pcData), *size, nullptr, &texture); if (FAILED(hr)) MessageBox(hwnd_, "Texture couldn't be created from memory!", "Error!", MB_ICONERROR | MB_OK); return texture; }
29.941489
160
0.677918
[ "mesh", "vector", "model" ]
c8fac17e3de22fcd23242a5a6b7875fd3a775e1e
5,542
cc
C++
extensions/renderer/user_script_set_manager.cc
google-ar/chromium
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
777
2017-08-29T15:15:32.000Z
2022-03-21T05:29:41.000Z
extensions/renderer/user_script_set_manager.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
66
2017-08-30T18:31:18.000Z
2021-08-02T10:59:35.000Z
extensions/renderer/user_script_set_manager.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
123
2017-08-30T01:19:34.000Z
2022-03-17T22:55:31.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "extensions/renderer/user_script_set_manager.h" #include "base/memory/ptr_util.h" #include "components/crx_file/id_util.h" #include "content/public/renderer/render_thread.h" #include "extensions/common/extension_messages.h" #include "extensions/renderer/dispatcher.h" #include "extensions/renderer/script_injection.h" #include "extensions/renderer/user_script_set.h" #include "ipc/ipc_message.h" #include "ipc/ipc_message_macros.h" namespace extensions { UserScriptSetManager::UserScriptSetManager() : activity_logging_enabled_(false) { content::RenderThread::Get()->AddObserver(this); } UserScriptSetManager::~UserScriptSetManager() { } void UserScriptSetManager::AddObserver(Observer* observer) { observers_.AddObserver(observer); } void UserScriptSetManager::RemoveObserver(Observer* observer) { observers_.RemoveObserver(observer); } std::unique_ptr<ScriptInjection> UserScriptSetManager::GetInjectionForDeclarativeScript( int script_id, content::RenderFrame* render_frame, int tab_id, const GURL& url, const std::string& extension_id) { UserScriptSet* user_script_set = GetProgrammaticScriptsByHostID(HostID(HostID::EXTENSIONS, extension_id)); if (!user_script_set) return std::unique_ptr<ScriptInjection>(); return user_script_set->GetDeclarativeScriptInjection( script_id, render_frame, tab_id, UserScript::BROWSER_DRIVEN, url, activity_logging_enabled_); } bool UserScriptSetManager::OnControlMessageReceived( const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(UserScriptSetManager, message) IPC_MESSAGE_HANDLER(ExtensionMsg_UpdateUserScripts, OnUpdateUserScripts) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void UserScriptSetManager::GetAllInjections( std::vector<std::unique_ptr<ScriptInjection>>* injections, content::RenderFrame* render_frame, int tab_id, UserScript::RunLocation run_location) { static_scripts_.GetInjections(injections, render_frame, tab_id, run_location, activity_logging_enabled_); for (UserScriptSetMap::iterator it = programmatic_scripts_.begin(); it != programmatic_scripts_.end(); ++it) { it->second->GetInjections(injections, render_frame, tab_id, run_location, activity_logging_enabled_); } } void UserScriptSetManager::GetAllActiveExtensionIds( std::set<std::string>* ids) const { DCHECK(ids); static_scripts_.GetActiveExtensionIds(ids); for (UserScriptSetMap::const_iterator it = programmatic_scripts_.begin(); it != programmatic_scripts_.end(); ++it) { it->second->GetActiveExtensionIds(ids); } } UserScriptSet* UserScriptSetManager::GetProgrammaticScriptsByHostID( const HostID& host_id) { UserScriptSetMap::const_iterator it = programmatic_scripts_.find(host_id); return it != programmatic_scripts_.end() ? it->second.get() : NULL; } void UserScriptSetManager::OnUpdateUserScripts( base::SharedMemoryHandle shared_memory, const HostID& host_id, const std::set<HostID>& changed_hosts, bool whitelisted_only) { if (!base::SharedMemory::IsHandleValid(shared_memory)) { NOTREACHED() << "Bad scripts handle"; return; } for (const HostID& host_id : changed_hosts) { if (host_id.type() == HostID::EXTENSIONS && !crx_file::id_util::IdIsValid(host_id.id())) { NOTREACHED() << "Invalid extension id: " << host_id.id(); return; } } UserScriptSet* scripts = NULL; if (!host_id.id().empty()) { // The expectation when there is a host that "owns" this shared // memory region is that the |changed_hosts| is either the empty list // or just the owner. CHECK(changed_hosts.size() <= 1); if (programmatic_scripts_.find(host_id) == programmatic_scripts_.end()) { scripts = programmatic_scripts_ .insert(std::make_pair(host_id, base::MakeUnique<UserScriptSet>())) .first->second.get(); } else { scripts = programmatic_scripts_[host_id].get(); } } else { scripts = &static_scripts_; } DCHECK(scripts); // If no hosts are included in the set, that indicates that all // hosts were updated. Add them all to the set so that observers and // individual UserScriptSets don't need to know this detail. const std::set<HostID>* effective_hosts = &changed_hosts; std::set<HostID> all_hosts; if (changed_hosts.empty()) { // The meaning of "all hosts(extensions)" varies, depending on whether some // host "owns" this shared memory region. // No owner => all known hosts. // Owner => just the owner host. if (host_id.id().empty()) { std::set<std::string> extension_ids = RendererExtensionRegistry::Get()->GetIDs(); for (const std::string& extension_id : extension_ids) all_hosts.insert(HostID(HostID::EXTENSIONS, extension_id)); } else { all_hosts.insert(host_id); } effective_hosts = &all_hosts; } if (scripts->UpdateUserScripts(shared_memory, *effective_hosts, whitelisted_only)) { for (auto& observer : observers_) observer.OnUserScriptsUpdated(*effective_hosts); } } } // namespace extensions
34.42236
79
0.702093
[ "vector" ]
c8fcaf33fced9a71da91a159477f5e9d974f8830
1,105
hpp
C++
code/utility/SpriteSheetLoader.hpp
jacmoe/pxlwolf
15e4437ba490724e8e8db59722b4d603ad08a056
[ "MIT" ]
4
2020-12-31T00:01:32.000Z
2021-11-20T15:39:46.000Z
code/utility/SpriteSheetLoader.hpp
jacmoe/pxlwolf
15e4437ba490724e8e8db59722b4d603ad08a056
[ "MIT" ]
null
null
null
code/utility/SpriteSheetLoader.hpp
jacmoe/pxlwolf
15e4437ba490724e8e8db59722b4d603ad08a056
[ "MIT" ]
1
2021-11-10T16:55:09.000Z
2021-11-10T16:55:09.000Z
/*# This file is part of the # ██████╗ ██╗ ██╗██╗ ██╗ ██╗ ██████╗ ██╗ ███████╗ # ██╔══██╗╚██╗██╔╝██║ ██║ ██║██╔═══██╗██║ ██╔════╝ # ██████╔╝ ╚███╔╝ ██║ ██║ █╗ ██║██║ ██║██║ █████╗ # ██╔═══╝ ██╔██╗ ██║ ██║███╗██║██║ ██║██║ ██╔══╝ # ██║ ██╔╝ ██╗███████╗╚███╔███╔╝╚██████╔╝███████╗██║ # ╚═╝ ╚═╝ ╚═╝╚══════╝ ╚══╝╚══╝ ╚═════╝ ╚══════╝╚═╝ # project # # https://github.com/jacmoe/pxlwolf # # (c) 2020 - 2021 Jacob Moena # # MIT License #*/ #pragma once #include <vector> #include <string> #include <unordered_map> #include <SFML/Graphics.hpp> #include "RectAnimation.hpp" namespace utility { class SpriteSheetLoader { public: SpriteSheetLoader(); ~SpriteSheetLoader(); bool load(const std::string& sprite_definition_file); inline const auto& getAnimations() { return m_animations; } private: std::unordered_map<std::string, std::pair<utility::RectAnimation, sf::Time>> m_animations; int m_rows; int m_cols; int m_width; int m_height; }; }
25.113636
98
0.422624
[ "vector" ]
c8fcc0ed38fbf7e8be66467be0cb8bfabbe18ffb
8,860
cc
C++
chrome/browser/ash/child_accounts/secondary_account_consent_logger_unittest.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-10-18T02:33:40.000Z
2020-10-18T02:33:40.000Z
chrome/browser/ash/child_accounts/secondary_account_consent_logger_unittest.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
3
2021-05-17T16:28:52.000Z
2021-05-21T22:42:22.000Z
chrome/browser/ash/child_accounts/secondary_account_consent_logger_unittest.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ash/child_accounts/secondary_account_consent_logger.h" #include <vector> #include "ash/constants/ash_pref_names.h" #include "base/json/json_reader.h" #include "base/strings/string_util.h" #include "base/syslog_logging.h" #include "base/test/mock_callback.h" #include "base/test/task_environment.h" #include "components/prefs/testing_pref_service.h" #include "components/signin/public/identity_manager/account_info.h" #include "components/signin/public/identity_manager/consent_level.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/signin/public/identity_manager/identity_test_environment.h" #include "net/base/net_errors.h" #include "net/http/http_status_code.h" #include "services/network/public/cpp/shared_url_loader_factory.h" #include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h" #include "services/network/test/test_url_loader_factory.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace { constexpr char kAccountEmail[] = "user@gmail.com"; constexpr char kSecondaryEmail[] = "secondary@gmail.com"; constexpr char kParentObfuscatedGaiaId[] = "parent-obfuscated-gaia-id"; constexpr char kReAuthProofToken[] = "re-auth-proof-token"; constexpr char kChromeSyncId[] = "test-chrome-id"; constexpr char kRequestBodyTemplate[] = R"({ "chrome_os_consent": { "chrome_os_unicorn_edu_coexistence_id": "$1", "secondary_account_email": "$2", "parent_id": "$3", "parent_rapt": "$4", "text_version": "$5" }, "person_id": "me" })"; constexpr char kConsentScreenTextVersion[] = "v2353089"; std::string GetTestRequestBody( const std::string& chrome_os_unicorn_edu_coexistence_id, const std::string& secondary_account_email, const std::string& parent_id, const std::string& parent_rapt, const std::string& text_version) { std::vector<std::string> params; params.push_back(chrome_os_unicorn_edu_coexistence_id); params.push_back(secondary_account_email); params.push_back(parent_id); params.push_back(parent_rapt); params.push_back(text_version); return base::ReplaceStringPlaceholders(kRequestBodyTemplate, params, nullptr); } } // namespace class SecondaryAccountConsentLoggerTest : public testing::Test { public: SecondaryAccountConsentLoggerTest() = default; void SetUp() { SecondaryAccountConsentLogger::RegisterPrefs(local_state_.registry()); local_state_.SetUserPref(ash::prefs::kEduCoexistenceId, std::make_unique<base::Value>(kChromeSyncId)); } void CreateLogger() { logger_ = std::make_unique<SecondaryAccountConsentLogger>( identity_test_env_.identity_manager(), base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>( &test_url_loader_factory_), &local_state_, kSecondaryEmail, kParentObfuscatedGaiaId, kReAuthProofToken, base::BindOnce(&SecondaryAccountConsentLoggerTest::OnConsentLogged, base::Unretained(this))); } MOCK_METHOD(void, OnConsentLogged, (SecondaryAccountConsentLogger::Result result), ()); void CreateAndStartLogging() { if (logger_ == nullptr) { CreateLogger(); } logger_->StartLogging(); } CoreAccountInfo SetPrimaryAccount() { return identity_test_env_.SetPrimaryAccount(kAccountEmail, signin::ConsentLevel::kSignin); } void IssueRefreshTokenForPrimaryAccount() { identity_test_env_.MakePrimaryAccountAvailable( kAccountEmail, signin::ConsentLevel::kSignin); } void SendResponse(int net_error, int response_code) { logger_->OnSimpleLoaderCompleteInternal(net_error, response_code); } void WaitForAccessTokenRequestAndIssueToken() { identity_test_env_.WaitForAccessTokenRequestIfNecessaryAndRespondWithToken( identity_test_env_.identity_manager()->GetPrimaryAccountId( signin::ConsentLevel::kSignin), "access_token", base::Time::Now() + base::TimeDelta::FromHours(1)); } base::DictionaryValue CreateRequestBody() { return logger_->CreateRequestBody(); } protected: base::test::SingleThreadTaskEnvironment task_environment_; signin::IdentityTestEnvironment identity_test_env_; network::TestURLLoaderFactory test_url_loader_factory_; private: TestingPrefServiceSimple local_state_; std::unique_ptr<SecondaryAccountConsentLogger> logger_; }; TEST_F(SecondaryAccountConsentLoggerTest, LoggingSuccess) { IssueRefreshTokenForPrimaryAccount(); CreateAndStartLogging(); WaitForAccessTokenRequestAndIssueToken(); EXPECT_CALL(*this, OnConsentLogged(SecondaryAccountConsentLogger::Result::kSuccess)); SendResponse(net::OK, net::HTTP_OK); } TEST_F(SecondaryAccountConsentLoggerTest, NetworkError) { IssueRefreshTokenForPrimaryAccount(); CreateAndStartLogging(); WaitForAccessTokenRequestAndIssueToken(); EXPECT_CALL(*this, OnConsentLogged( SecondaryAccountConsentLogger::Result::kNetworkError)); SendResponse(-320 /*INVALID_RESPONSE*/, net::HTTP_OK); } TEST_F(SecondaryAccountConsentLoggerTest, ResponceError) { IssueRefreshTokenForPrimaryAccount(); CreateAndStartLogging(); WaitForAccessTokenRequestAndIssueToken(); EXPECT_CALL(*this, OnConsentLogged( SecondaryAccountConsentLogger::Result::kNetworkError)); SendResponse(net::OK, 400 /*BAD_REQUEST*/); } TEST_F(SecondaryAccountConsentLoggerTest, TokenError) { IssueRefreshTokenForPrimaryAccount(); CreateAndStartLogging(); // On failure to get an access token we expect a token error. EXPECT_CALL(*this, OnConsentLogged( SecondaryAccountConsentLogger::Result::kTokenError)); identity_test_env_.WaitForAccessTokenRequestIfNecessaryAndRespondWithError( identity_test_env_.identity_manager()->GetPrimaryAccountId( signin::ConsentLevel::kSignin), GoogleServiceAuthError(GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS)); } TEST_F(SecondaryAccountConsentLoggerTest, SuccessAfterWaitingForRefreshToken) { // Early set the primary account so that the fetcher is created with a proper // account_id. We don't use IssueRefreshToken() as it also sets a refresh // token for the primary account and that's something we don't want for this // test. CoreAccountInfo account_info = SetPrimaryAccount(); CreateAndStartLogging(); // Since there is no refresh token yet, we should not get a request for an // access token at this point. base::MockCallback<base::OnceClosure> access_token_requested; EXPECT_CALL(access_token_requested, Run()).Times(0); identity_test_env_.SetCallbackForNextAccessTokenRequest( access_token_requested.Get()); // In this case we don't directly call IssueRefreshToken() as it sets the // primary account. We already have a primary account set so we cannot set // another one. identity_test_env_.SetRefreshTokenForAccount(account_info.account_id); // Do reset the callback for access token request before using the Wait* APIs. identity_test_env_.SetCallbackForNextAccessTokenRequest(base::OnceClosure()); WaitForAccessTokenRequestAndIssueToken(); EXPECT_CALL(*this, OnConsentLogged(SecondaryAccountConsentLogger::Result::kSuccess)); SendResponse(net::OK, net::HTTP_OK); } TEST_F(SecondaryAccountConsentLoggerTest, NoRefreshToken) { // Set the primary account before creating the fetcher to allow it to properly // retrieve the primary account_id from IdentityManager. We don't call // IssueRefreshToken because we don't want it to precisely issue a refresh // token for the primary account, just set it. SetPrimaryAccount(); CreateAndStartLogging(); identity_test_env_.MakeAccountAvailable(kSecondaryEmail); // Credentials for a different user should be ignored, i.e. not result in a // request for an access token. base::MockCallback<base::OnceClosure> access_token_requested; EXPECT_CALL(access_token_requested, Run()).Times(0); identity_test_env_.SetCallbackForNextAccessTokenRequest( access_token_requested.Get()); } TEST_F(SecondaryAccountConsentLoggerTest, RequestBody) { CoreAccountInfo account_info = SetPrimaryAccount(); CreateLogger(); absl::optional<base::Value> test_request_body = base::JSONReader::Read(GetTestRequestBody( kChromeSyncId, kSecondaryEmail, kParentObfuscatedGaiaId, kReAuthProofToken, kConsentScreenTextVersion)); base::DictionaryValue request_body = CreateRequestBody(); EXPECT_EQ(test_request_body.value(), request_body); }
38.859649
80
0.756998
[ "vector" ]
7404cd058477b32c73cce0f8470ac42729bcb784
3,427
cpp
C++
tdd_cpp/gtest_sample/gmock_sample.cpp
changsin/TDD
c819355ad18561f17c07feab456d78dcb1c5e34d
[ "MIT" ]
1
2021-04-30T00:26:25.000Z
2021-04-30T00:26:25.000Z
tdd_cpp/gtest_sample/gmock_sample.cpp
changsin/TDD
c819355ad18561f17c07feab456d78dcb1c5e34d
[ "MIT" ]
null
null
null
tdd_cpp/gtest_sample/gmock_sample.cpp
changsin/TDD
c819355ad18561f17c07feab456d78dcb1c5e34d
[ "MIT" ]
2
2021-05-11T23:49:47.000Z
2021-05-12T23:46:16.000Z
#include <iostream> #include <vector> #include <time.h> #include <gtest/gtest.h> #include <gmock/gmock.h> using namespace std; using ::testing::AtLeast; using ::testing::Return; using ::testing::_; /** * Inspired by https://youtu.be/dLB2aDasVTg **/ class DataBaseConnect { public: virtual bool login(string username, string password) { return true; } virtual bool logout(string username) { return true; } virtual int getRecordCount() { return 1; } virtual int fetchRecord(int id) { srand(time(NULL)); int rvalue = rand() % 3; if (rvalue == 2) { return -1; } return id * 2; } }; class MockDB : public DataBaseConnect { public: MOCK_METHOD0(getRecordCount, int()); MOCK_METHOD1(fetchRecord, int(int)); MOCK_METHOD1(logout, bool(string username)); MOCK_METHOD2(login, bool(string username, string password)); }; class MyService { const int MAX_RETRIES = 2; public: MyService(DataBaseConnect& dbC) : dbC(dbC) {} bool init(string username, string password) { int retryCount = 0; bool retValue = dbC.login(username, password); while (!retValue && retryCount < MAX_RETRIES) { cout << "DB Login failed. Trying again..." << endl; retValue = dbC.login(username, password); retryCount++; } return retValue; } int fetchRecord(int id) { return dbC.fetchRecord(id); } private: DataBaseConnect& dbC; }; TEST(TestRealDB, FlakyConnections) { DataBaseConnect realDB; MyService service(realDB); bool retvalue = service.init("john", "password"); EXPECT_EQ(retvalue, true); int record = service.fetchRecord(12); ASSERT_GT(record, 0); } TEST(TestMockDB, StableConnections) { MockDB mockDB; MyService service(mockDB); EXPECT_CALL(mockDB, login("John", "password")) .WillOnce(Return(true)); bool retValue = service.init("John", "password"); EXPECT_EQ(retValue, true); //ON_CALL(mockDB, fetchRecord(12)).WillByDefault(Return(24)); EXPECT_CALL(mockDB, fetchRecord(12)).WillRepeatedly(Return(24)); int record = service.fetchRecord(12); cout << "####Record is " << record << endl; EXPECT_GT(record, 0); } TEST(TestMockDB, InvalidLogin) { MockDB mockDB; MyService service(mockDB); EXPECT_CALL(mockDB, login(_, _)) .Times(3) .WillOnce(Return(false)) .WillOnce(Return(false)) .WillOnce(Return(false)); bool retValue = service.init("hn", "password"); EXPECT_EQ(retValue, false); EXPECT_CALL(mockDB, fetchRecord(12)).WillRepeatedly(Return(-1)); int record = service.fetchRecord(12); cout << "####Record is " << record << endl; EXPECT_EQ(record, -1); } TEST(MyDBTest, LoginTest) { MockDB mockDB; MyService service(mockDB); //EXPECT_CALL(mockDB, login("John", "password")) // //.Times(2) // .WillRepeatedly(Return(true)); ON_CALL(mockDB, login(_, _)).WillByDefault(Return(true)); bool retValue = service.init("John", "password"); EXPECT_EQ(retValue, true); } TEST(MyDBTest, LoginRetry) { MockDB mockDB; MyService service(mockDB); EXPECT_CALL(mockDB, login("John", "password")) .Times(2) .WillOnce(Return(false)) .WillOnce(Return(true)); bool retValue = service.init("John", "password"); EXPECT_EQ(retValue, true); }
25.574627
73
0.634374
[ "vector" ]
74060de37e79ee0c6d4bf0903d51099c8a0cde0a
26,484
cpp
C++
tf2_src/utils/xbox/xbox_loader/xmvhelper.cpp
d3fc0n6/TeamFortress2
1b81dded673d49adebf4d0958e52236ecc28a956
[ "MIT" ]
4
2021-10-03T05:16:55.000Z
2021-12-28T16:49:27.000Z
tf2_src/utils/xbox/xbox_loader/xmvhelper.cpp
Counter2828/TeamFortress2
1b81dded673d49adebf4d0958e52236ecc28a956
[ "MIT" ]
null
null
null
tf2_src/utils/xbox/xbox_loader/xmvhelper.cpp
Counter2828/TeamFortress2
1b81dded673d49adebf4d0958e52236ecc28a956
[ "MIT" ]
3
2022-02-02T18:09:58.000Z
2022-03-06T18:54:39.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// //----------------------------------------------------------------------------- // File: WMVPlayer.cpp // // Desc: This helper class provides simple WMV decoding and playback // functionality. It will be expanded as new playback methods are // exposed // // Hist: 2.7.03 - Created, based on work by Jeff Sullivan // // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #include "xbox_loader.h" #include <xtl.h> #include "XMVHelper.h" #include "XBUtil.h" #include <stdio.h> // Funtion Prototypes for packet loading functions for loading from a file. HRESULT CALLBACK GetNextPacket( DWORD dwContext, void **ppPacket, DWORD* pOffsetToNextPacket ); HRESULT CALLBACK ReleasePreviousPacket( DWORD dwContext, LONGLONG llNextReadByteOffset, DWORD dwNextPacketSize ); // Funtion Prototypes for packet loading functions for loading from a block of memory. HRESULT CALLBACK GetNextMemoryPacket( DWORD dwContext, void **ppPacket, DWORD* pOffsetToNextPacket ); HRESULT CALLBACK ReleasePreviousMemoryPacket( DWORD dwContext, LONGLONG llNextReadByteOffset, DWORD dwNextPacketSize ); //----------------------------------------------------------------------------- // Name: CXMVPlayer() // Desc: Constructor for CXMVPlayer //----------------------------------------------------------------------------- CXMVPlayer::CXMVPlayer() { m_pXMVDecoder = NULL; ZeroMemory( &m_VideoDesc, sizeof( m_VideoDesc ) ); ZeroMemory( &m_AudioDesc, sizeof( m_AudioDesc ) ); for ( UINT i=0; i<XMVPLAYER_NUMTEXTURES; i++ ) { m_pTextures[i] = NULL; } m_dwCurrentFrame = -1; // Will be zero after we decode the first frame. m_bPlaying = FALSE; m_bOverlaysEnabled = FALSE; m_loadContext.hFile = INVALID_HANDLE_VALUE; m_loadContext.pInputBuffer = 0; m_physicalBuffer = 0; m_bError = FALSE; } //----------------------------------------------------------------------------- // Name: ~CXMVPlayer() // Desc: Destructor for CXMVPlayer //----------------------------------------------------------------------------- CXMVPlayer::~CXMVPlayer() { Destroy(); } //----------------------------------------------------------------------------- // Name: Destroy() // Desc: Free all resources and clear are resource pointers and handles. //----------------------------------------------------------------------------- HRESULT CXMVPlayer::Destroy() { // Disable overlays if we were using them. if ( m_bOverlaysEnabled ) { m_pDevice->EnableOverlay( FALSE ); m_bOverlaysEnabled = FALSE; } // Free the XMV decoder. if ( NULL != m_pXMVDecoder ) { m_pXMVDecoder->CloseDecoder(); m_pXMVDecoder = NULL; } ZeroMemory( &m_VideoDesc, sizeof( m_VideoDesc ) ); ZeroMemory( &m_AudioDesc, sizeof( m_AudioDesc ) ); // Release our textures. for ( UINT i=0; i<XMVPLAYER_NUMTEXTURES; i++ ) { if ( m_pTextures[i] ) m_pTextures[i]->Release(); m_pTextures[i] = 0; } m_dwCurrentFrame = -1; m_dwStartTime = 0; m_bPlaying = FALSE; // Release any file handles we were using. if( INVALID_HANDLE_VALUE != m_loadContext.hFile ) { CloseHandle( m_loadContext.hFile ); m_loadContext.hFile = INVALID_HANDLE_VALUE; } // Free up memory used for playing a movie from memory. if ( m_loadContext.pInputBuffer ) { free( m_loadContext.pInputBuffer ); m_loadContext.pInputBuffer = 0; } // Be sure to release the physical memory last! if( m_physicalBuffer ) { XPhysicalFree( m_physicalBuffer ); m_physicalBuffer = 0; } return S_OK; } //----------------------------------------------------------------------------- // Name: FinishOpeningFile() // Desc: Helper function for the three Open functions. Enables the audio streams, // initializes the video descriptor, and allocates textures if needed. //----------------------------------------------------------------------------- HRESULT CXMVPlayer::FinishOpeningFile( D3DFORMAT format, LPDIRECT3DDEVICE8 pDevice, BOOL bAllocateTextures ) { assert( format == D3DFMT_YUY2 || format == D3DFMT_LIN_A8R8G8B8 ); assert( XMVPLAYER_NUMTEXTURES >= 2); HRESULT hr = S_OK; m_pXMVDecoder->GetVideoDescriptor( &m_VideoDesc ); // Enable the audio streams for ( unsigned i=0; i < m_VideoDesc.AudioStreamCount; i++ ) { m_pXMVDecoder->GetAudioDescriptor( i, &m_AudioDesc ); hr = m_pXMVDecoder->EnableAudioStream( i, 0, NULL, NULL); if ( FAILED( hr ) ) { XBUtil_DebugPrint( "Unable to enable audio stream 0 (error %x)\n", hr ); Destroy(); return hr; } } for ( int i = 0; i < XMVPLAYER_NUMTEXTURES; i++ ) { m_pTextures[i] = 0; if ( bAllocateTextures ) { hr = pDevice->CreateTexture( m_VideoDesc.Width, m_VideoDesc.Height, 1, 0, format, 0, &m_pTextures[i] ); if ( FAILED( hr ) ) { XBUtil_DebugPrint( "Unable to create texture %d (error %x)\n", i, hr ); Destroy(); return hr; } } } // Initialize what texture we are decoding to, if decoding for texture mapping. m_nDecodeTextureIndex = 0; // Initialize the various texture pointers for use when decoding for overlays. pShowingTexture = m_pTextures[0]; pDecodingTexture = m_pTextures[1]; pSubmittedTexture = 0; m_bPlaying = TRUE; m_dwStartTime = GetTickCount(); return hr; } //----------------------------------------------------------------------------- // Name: OpenFile() // Desc: Create an XMV decoder object that reads from a file. //----------------------------------------------------------------------------- HRESULT CXMVPlayer::OpenFile( const CHAR* lpFilename, D3DFORMAT format, LPDIRECT3DDEVICE8 pDevice, BOOL bAllocateTextures ) { HRESULT hr = S_OK; m_bError = FALSE; if ( NULL == lpFilename || NULL == pDevice ) { XBUtil_DebugPrint( "Bad parameter to OpenFile()\n" ); m_bError = TRUE; return E_FAIL; } hr = XMVDecoder_CreateDecoderForFile( XMVFLAG_SYNC_ON_NEXT_VBLANK, ( CHAR* )lpFilename, &m_pXMVDecoder ); if ( FAILED( hr ) ) { XBUtil_DebugPrint( "Unable to create XMV Decoder for %s (error: %x)\n", lpFilename, hr ); m_bError = TRUE; return hr; } hr = FinishOpeningFile( format, pDevice, bAllocateTextures ); if ( FAILED( hr ) ) { m_bError = TRUE; } return hr; } //----------------------------------------------------------------------------- // Name: OpenFileForPackets() // Desc: Create an XMV decoder object that uses the packet reading interface. // Currently this just reads from a file, but it can be altered to read from // custom formats, start partway through a file, etc. //----------------------------------------------------------------------------- HRESULT CXMVPlayer::OpenFileForPackets( const CHAR* lpFilename, D3DFORMAT format, LPDIRECT3DDEVICE8 pDevice, BOOL bAllocateTextures ) { HRESULT hr = S_OK; // We need to read in the first 4K of data for the XMV player to initialize // itself from. This is most conveniently read as an array of DWORDS. DWORD first4Kbytes[4096 / sizeof( DWORD )]; // Clear entire context struct to zero ZeroMemory( &m_loadContext, sizeof( m_loadContext ) ); // Open the input file. m_loadContext.hFile = CreateFile( lpFilename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED | FILE_FLAG_NO_BUFFERING, NULL ); if( m_loadContext.hFile == INVALID_HANDLE_VALUE ) { Destroy(); return E_INVALIDARG; } // Read the first page from the file. We opened it for // overlapped IO so we do a pair of reads. m_loadContext.Overlapped.Offset = 0; m_loadContext.Overlapped.OffsetHigh = 0; // Start the read. if( 0 == ReadFile( m_loadContext.hFile, first4Kbytes, sizeof( first4Kbytes ), NULL, &m_loadContext.Overlapped ) ) { if( GetLastError() != ERROR_IO_PENDING ) { Destroy(); return E_FAIL; } } // Wait for the read to finish. DWORD dwBytesRead; if( !GetOverlappedResult( m_loadContext.hFile, &m_loadContext.Overlapped, &dwBytesRead, TRUE ) ) { Destroy(); return E_FAIL; } // Check size to make sure input is a valid XMV file. if( dwBytesRead != 4096 ) { Destroy(); return E_FAIL; } // Create an XMV decoder hr = XMVDecoder_CreateDecoderForPackets( XMVFLAG_SYNC_ON_NEXT_VBLANK, first4Kbytes, ( DWORD )&m_loadContext, GetNextPacket, ReleasePreviousPacket, &m_pXMVDecoder ); if( FAILED( hr ) ) { Destroy(); return E_FAIL; } // The size of the first packet and the minimum size of the two packet buffers are stored in the // second and third DWORDS of the file. From xmv.h: // * DWORD NextPacketSize // The size of the next packet // * DWORD ThisPacketSize // The size of this packet // * DWORD MaxPacketSize // The size of the largest packet in the file DWORD dwThisPacketSize = first4Kbytes[1]; DWORD dwRequiredPacketSize = first4Kbytes[2]; // Check for illegal parameters. if( dwThisPacketSize > dwRequiredPacketSize ) { Destroy(); return E_FAIL; } // XPhysicalAlloc is used so that 5.1 or compressed audio streams can be played. m_physicalBuffer = ( BYTE* )XPhysicalAlloc( dwRequiredPacketSize * 2, MAXULONG_PTR, 0, PAGE_READWRITE ); // Save our information. m_loadContext.dwPacketSize = dwRequiredPacketSize; m_loadContext.pLoadingPacket = m_physicalBuffer; m_loadContext.pDecodingPacket = m_physicalBuffer + dwRequiredPacketSize; // Read the first packet. We wind up re-reading the first 4096 // bytes but it makes the logic for figuring out how much we read // a little bit easier... m_loadContext.Overlapped.Offset = 0; m_loadContext.Overlapped.OffsetHigh = 0; if( 0 == ReadFile( m_loadContext.hFile, m_physicalBuffer, dwThisPacketSize, NULL, &m_loadContext.Overlapped ) ) { if( GetLastError() != ERROR_IO_PENDING ) { Destroy(); return E_FAIL; } } // Note - at this point the preceding read has *not* necessarily completed. // Don't try reading anything from that buffer until GetNextPacket has been // successfully called. hr = FinishOpeningFile( format, pDevice, bAllocateTextures ); return hr; } //----------------------------------------------------------------------------- // Name: OpenMovieFromMemory() // Desc: Create an XMV decoder object that uses the packet reading interface to // read from a block of memory. To simplify the memory management this function // also allocates this block of memory and initializes it from a file. //----------------------------------------------------------------------------- HRESULT CXMVPlayer::OpenMovieFromMemory( const CHAR* lpFilename, D3DFORMAT format, LPDIRECT3DDEVICE8 pDevice, BOOL bAllocateTextures ) { HRESULT hr = S_OK; m_bError = FALSE; // Read the entire file into memory. void* data; hr = XBUtil_LoadFile( lpFilename, &data, &m_loadContext.inputSize ); if ( FAILED( hr ) ) { m_bError = TRUE; return hr; } m_loadContext.pInputBuffer = ( BYTE* )data; // Check size to make sure input is a valid XMV file. if( m_loadContext.inputSize < 4096 ) { Destroy(); m_bError = TRUE; return E_FAIL; } // Get a DWORD pointer to the first 4K - needed by CreateDecoderForPackets DWORD* first4Kbytes = ( DWORD* )data; // Create an XMV decoder hr = XMVDecoder_CreateDecoderForPackets( XMVFLAG_SYNC_ON_NEXT_VBLANK, first4Kbytes, ( DWORD )&m_loadContext, GetNextMemoryPacket, ReleasePreviousMemoryPacket, &m_pXMVDecoder ); if ( FAILED( hr ) ) { Destroy(); m_bError = TRUE; return E_FAIL; } // The size of the first packet and the minimum size of the two packet buffers are stored in the // second and third DWORDS of the file. From xmv.h: // * DWORD NextPacketSize // The size of the next packet // * DWORD ThisPacketSize // The size of this packet // * DWORD MaxPacketSize // The size of the largest packet in the file DWORD dwThisPacketSize = first4Kbytes[1]; DWORD dwRequiredPacketSize = first4Kbytes[2]; // Check for illegal parameters. if( dwThisPacketSize > dwRequiredPacketSize ) { Destroy(); m_bError = TRUE; return E_FAIL; } // XPhysicalAlloc is used so that 5.1 or compressed audio streams can be played. m_physicalBuffer = ( BYTE* )XPhysicalAlloc( dwRequiredPacketSize * 2, MAXULONG_PTR, 0, PAGE_READWRITE ); // Save our information for the callback functions. // The size of our two memory blocks. m_loadContext.dwPacketSize = dwRequiredPacketSize; // The addresses of our two memory blocks. m_loadContext.pLoadingPacket = m_physicalBuffer; m_loadContext.pDecodingPacket = m_physicalBuffer + dwRequiredPacketSize; // Information about the block of memory the movie is stored in. m_loadContext.pInputBuffer = ( BYTE* )data; m_loadContext.inputSize = m_loadContext.inputSize; m_loadContext.readOffset = 0; m_loadContext.currentPacketSize = dwThisPacketSize; hr = FinishOpeningFile( format, pDevice, bAllocateTextures ); if ( FAILED( hr ) ) { m_bError = TRUE; } return hr; } //----------------------------------------------------------------------------- // Name: AdvanceFrameForTexturing() // Desc: Unpack the appropriate frames of data for use as textures. //----------------------------------------------------------------------------- LPDIRECT3DTEXTURE8 CXMVPlayer::AdvanceFrameForTexturing( LPDIRECT3DDEVICE8 pDevice ) { // You must pass bAllocateTextures==TRUE to Open if you're going to use GetTexture/AdvanceFrame. assert( m_pTextures[0] ); LPDIRECT3DSURFACE8 pSurface; pDecodingTexture->GetSurfaceLevel( 0, &pSurface ); // Decode some information to the current draw texture. XMVRESULT xr = XMV_NOFRAME; m_pXMVDecoder->GetNextFrame( pSurface, &xr, NULL ); switch ( xr ) { case XMV_NOFRAME: // Do nothing - we didn't get a frame. break; case XMV_NEWFRAME: ++m_dwCurrentFrame; // GetNextFrame produced a new frame. So, the texture we were decoding // to becomes available for drawing as a texture. pShowingTexture = pDecodingTexture; // Setup for decoding to the next texture. m_nDecodeTextureIndex = ( m_nDecodeTextureIndex + 1 ) % XMVPLAYER_NUMTEXTURES; pDecodingTexture = m_pTextures[ m_nDecodeTextureIndex ]; break; case XMV_ENDOFFILE: m_bPlaying = FALSE; break; case XMV_FAIL: // Data corruption or file read error. We'll treat that the same as // end of file. m_bPlaying = FALSE; m_bError = TRUE; break; } SAFE_RELEASE( pSurface ); // If we haven't decoded the first frame then return zero. if ( m_dwCurrentFrame < 0 ) return 0; return pShowingTexture; } //----------------------------------------------------------------------------- // Name: AdvanceFrameForOverlays() // Desc: Unpack the appropriate frames of data for use as an overlay. //----------------------------------------------------------------------------- LPDIRECT3DTEXTURE8 CXMVPlayer::AdvanceFrameForOverlays( LPDIRECT3DDEVICE8 pDevice ) { // You must pass bAllocateTextures==TRUE to Open if you're going to use GetTexture/AdvanceFrame. assert( m_pTextures[0] ); // You have to call CXMVPlayer::EnableOverlays() if you are going to use overlays. assert( m_bOverlaysEnabled ); // If a texture has been submitted to be used as an overlay then we have to // wait for GetUpdateOverlayState() to return TRUE before we can assume that // the previous texture has *stopped* being displayed. Once GetUpdateOverlayState() // returns TRUE then we know that pSubmittedTexture is being displayed, which // means that, pShowingTexture is available as a decoding target. if ( pSubmittedTexture ) { // If GetOverlayUpdateStatus() returns FALSE then we can still proceed and // call GetNextFrame(), but we will pass NULL for the surface parameter. // Some work will still be done, but none of the surfaces will be altered. if ( pDevice->GetOverlayUpdateStatus() ) { // The call to UpdateOverlay() with pSubmittedTexture must have taken // effect now, so pShowingTexture is available as a decoding target. assert( !pDecodingTexture ); pDecodingTexture = pShowingTexture; pShowingTexture = pSubmittedTexture; pSubmittedTexture = NULL; } } LPDIRECT3DSURFACE8 pSurface = NULL; if ( pDecodingTexture ) pDecodingTexture->GetSurfaceLevel( 0, &pSurface ); // Decode some information to the current draw texture, which may be NULL. // pDecodingTexture will be NULL if one texture has been submitted as a new // overlay but the other one is still being displayed as an overlay. // If pSurface is NULL GetNextFrame() will still do some work. XMVRESULT xr = XMV_NOFRAME; m_pXMVDecoder->GetNextFrame( pSurface, &xr, NULL ); switch ( xr ) { case XMV_NOFRAME: // Do nothing - we didn't get a frame. break; case XMV_NEWFRAME: ++m_dwCurrentFrame; // GetNextFrame produced a new frame. So, the texture we were decoding // to becomes available for displaying as an overlay. // The other texture is not ready to be a decoding target. It is still // being displayed as an overlay. So, we assign the newly decoded // texture to pSubmittedTexture for the program to submit as an overlay, // but we don't yet move the previously submitted texture from pShowing // to pDecoding. That happens on a subsequent call to this function, after // GetOverlayUpdateStatus() returns TRUE to tell us that there are no // overlay swaps pending. assert( pDecodingTexture ); assert( !pSubmittedTexture ); pSubmittedTexture = pDecodingTexture; pDecodingTexture = NULL; break; case XMV_ENDOFFILE: m_bPlaying = FALSE; break; case XMV_FAIL: // Data corruption or file read error. We'll treat that the same as // end of file. m_bPlaying = FALSE; m_bError = TRUE; break; } SAFE_RELEASE( pSurface ); // If we just unpacked a new frame then we return that texture // and the program must call UpdateOverlay() with the surface // from that texture. // If we didn't unpack a frame then the program should do nothing - // the previous overlay will continue to be displayed. if ( XMV_NEWFRAME == xr ) return pSubmittedTexture; // No new frame to display. return 0; } //----------------------------------------------------------------------------- // Name: TerminatePlayback() // Desc: Calls XMVDecoder::TerminatePlayback() //----------------------------------------------------------------------------- void CXMVPlayer::TerminatePlayback() { m_pXMVDecoder->TerminatePlayback(); } //----------------------------------------------------------------------------- // Name: Play() // Desc: Calls XMVDecoder::Play() to play the entire movie. //----------------------------------------------------------------------------- HRESULT CXMVPlayer::Play( DWORD Flags, RECT* pRect ) { // You have to call Open before calling Play. assert( m_pXMVDecoder ); // Don't pass bAllocateTextures==TRUE to Open if you're going to use Play. assert( !m_pTextures[0] ); return m_pXMVDecoder->Play( Flags, pRect ); } //----------------------------------------------------------------------------- // Name: EnableOverlays() // Desc: Enable the overlay planes for playing the movie in them, and record // that the overlays should be disabled when Destroy() is called. //----------------------------------------------------------------------------- void CXMVPlayer::EnableOverlays( LPDIRECT3DDEVICE8 pDevice ) { m_pDevice = pDevice; pDevice->EnableOverlay( TRUE ); m_bOverlaysEnabled = TRUE; } //----------------------------------------------------------------------------- // Name: GetNextPacket() // Desc: Callback function to get next packet from a file //----------------------------------------------------------------------------- static HRESULT CALLBACK GetNextPacket( DWORD dwContext, VOID** ppPacket, DWORD* pOffsetToNextPacket ) { LOAD_CONTEXT* pContext = ( LOAD_CONTEXT* )dwContext; if( NULL == pContext ) return E_FAIL; // If the next packet is fully loaded then return it, // otherwise return NULL. DWORD dwBytesRead; if( GetOverlappedResult( pContext->hFile, &pContext->Overlapped, &dwBytesRead, FALSE ) ) { // Make the old decoding packet pending. pContext->pPendingReleasePacket = pContext->pDecodingPacket; pContext->pDecodingPacket = pContext->pLoadingPacket; pContext->pLoadingPacket = NULL; // Offset to the next packet. *pOffsetToNextPacket = dwBytesRead; // Set *ppPacket to the data we just loaded. *ppPacket = pContext->pDecodingPacket; } else { DWORD dwError = GetLastError(); // If we're waiting on the IO to finish, just do nothing. if( dwError != ERROR_IO_INCOMPLETE ) return HRESULT_FROM_WIN32( dwError ); *ppPacket = NULL; *pOffsetToNextPacket = 0; } return S_OK; } //----------------------------------------------------------------------------- // Name: ReleasePreviousPacket() // Desc: Callback function to release previous packet from a file //----------------------------------------------------------------------------- static HRESULT CALLBACK ReleasePreviousPacket( DWORD dwContext, LONGLONG llNextReadByteOffset, DWORD dwNextPacketSize ) { LOAD_CONTEXT* pContext = ( LOAD_CONTEXT* )dwContext; if( NULL == pContext ) return E_FAIL; if( dwNextPacketSize != 0 ) { // Start the next load. pContext->Overlapped.Offset = ( DWORD )( llNextReadByteOffset & 0xFFFFFFFF ); pContext->Overlapped.OffsetHigh = ( DWORD )( llNextReadByteOffset >> 32 ); // Check for bad input file - buffer overrun if( dwNextPacketSize > pContext->dwPacketSize ) return E_FAIL; pContext->pLoadingPacket = pContext->pPendingReleasePacket; pContext->pPendingReleasePacket = NULL; if( 0 == ReadFile( pContext->hFile, pContext->pLoadingPacket, dwNextPacketSize, NULL, &pContext->Overlapped ) ) { if( GetLastError() != ERROR_IO_PENDING ) return HRESULT_FROM_WIN32( GetLastError() ); } } return S_OK; } //----------------------------------------------------------------------------- // Name: GetNextMemoryPacket() // Desc: Callback function to get next packet from a file, // and setup for the next packet. //----------------------------------------------------------------------------- static HRESULT CALLBACK GetNextMemoryPacket( DWORD dwContext, VOID** ppPacket, DWORD* pOffsetToNextPacket ) { LOAD_CONTEXT* pContext = ( LOAD_CONTEXT* )dwContext; if( NULL == pContext ) return E_FAIL; DWORD dwBytesRead = pContext->inputSize - pContext->readOffset; if ( pContext->currentPacketSize < dwBytesRead ) dwBytesRead = pContext->currentPacketSize; memcpy( pContext->pLoadingPacket, pContext->pInputBuffer + pContext->readOffset , dwBytesRead ); pContext->readOffset +=dwBytesRead; // Swap pointers so that next time we load it goes into the other packet block. BYTE* temp = pContext->pLoadingPacket; pContext->pLoadingPacket = pContext->pDecodingPacket; pContext->pDecodingPacket = temp; // Offset to the next packet. *pOffsetToNextPacket = dwBytesRead; // Set *ppPacket to the data we just loaded. *ppPacket = pContext->pDecodingPacket; return S_OK; } //----------------------------------------------------------------------------- // Name: ReleasePreviousMemoryPacket() // Desc: Callback function to release previous packet from a block of memory, // and setup for the next packet. //----------------------------------------------------------------------------- static HRESULT CALLBACK ReleasePreviousMemoryPacket( DWORD dwContext, LONGLONG llNextReadByteOffset, DWORD dwNextPacketSize ) { LOAD_CONTEXT* pContext = ( LOAD_CONTEXT* )dwContext; if( NULL == pContext ) return E_FAIL; // Check for bad input file - buffer overrun if( dwNextPacketSize > pContext->dwPacketSize ) return E_FAIL; // Record the size of the next packet we are supposed to read, for GetNextMemoryPacket. pContext->currentPacketSize = dwNextPacketSize; return S_OK; }
33.56654
135
0.578123
[ "object" ]
740945931de6d248f28eb8756a30aafd96960f17
3,041
hpp
C++
src/generator/gsql_parser/gsql_parser/gsql_q_set.hpp
ostri/dbgen3
3430ef64f51d551a7ec4356daf52f80940ad7343
[ "Apache-2.0" ]
null
null
null
src/generator/gsql_parser/gsql_parser/gsql_q_set.hpp
ostri/dbgen3
3430ef64f51d551a7ec4356daf52f80940ad7343
[ "Apache-2.0" ]
null
null
null
src/generator/gsql_parser/gsql_parser/gsql_q_set.hpp
ostri/dbgen3
3430ef64f51d551a7ec4356daf52f80940ad7343
[ "Apache-2.0" ]
null
null
null
#ifndef GSQL_Q_SET_HPP #define GSQL_Q_SET_HPP #include <map> #include "gsql_parser/gsql_q.hpp" #include "utility_classes/multi_line.hpp" namespace dbgen3 { using q_dic_t = std::map<std::string, int>; // string q.ID() int index in vector using q_vec_t = std::vector<gsql_q>; class gsql_q_set { public: gsql_q_set() = default; ~gsql_q_set() = default; gsql_q_set(const gsql_q_set&) = delete; gsql_q_set(gsql_q_set&&) = default; gsql_q_set& operator=(const gsql_q_set&) = default; gsql_q_set& operator=(gsql_q_set&&) = default; /// @name getters //@{ std::string header_str(int offs) const; const multi_line& header_multi_line() const; str_t dump() const; str_t dump(int offs) const; str_t id() const; str_t namespace_str() const; gsql_q& q_vec(std::size_t ndx); const gsql_q& q_vec(std::size_t ndx) const; q_vec_t& q_vec(); const q_vec_t& q_vec() const; //@} /// @name setters //@{ void set_header(const std::string& header_str); void set_id(const std::string& id); bool q_insert(const gsql_q& q); std::string dump(cstr_t msg) const; std::string dump(cstr_t a_msg, int offs) const; //@} private: multi_line header_; //!< contents of the header of query set (q-set) std::string id_; //!< q_set unique id; if not provided the basename of gsql filename q_dic_t q_dic_; //!< dictionary of query ids q_vec_t q_vec_; //!< vector of all query definitions }; /// fetch header as a string inline std::string gsql_q_set::header_str(int offs) const { return header_.dump("", offs); } /// fetch header as multiline vector inline const multi_line& gsql_q_set::header_multi_line() const { return header_; } inline std::string gsql_q_set::dump() const { return dump("", 0); } inline std::string gsql_q_set::dump(int offs) const { return dump("", offs); } inline std::string gsql_q_set::id() const { return this->id_; } /// set id of the query set inline void gsql_q_set::set_id(const std::string& id) { this->id_ = id; } inline bool gsql_q_set::q_insert(const gsql_q& q) { q_vec_.emplace_back(q); const auto [key, sts] = q_dic_.emplace(q.id(), q_vec_.size() - 1); return sts; } inline std::string gsql_q_set::dump(cstr_t msg) const { return dump(msg, 0); } inline std::string gsql_q_set::dump(cstr_t a_msg, int offs) const { std::string s; if (! a_msg.empty()) s += out::sl(a_msg, offs); s += out::sl("query-set:", offs); s += out::sl("{", offs); s += out::sl(" id: '" + id_ + "'", offs); s += out::sl(" header:", offs); s += out::sl(" {", offs); s += header_.dump("", offs + 4); s += out::sl(" }", offs); for (auto const& val : q_vec_) { s += val.dump(offs + 2); } s += out::sl("}", offs); return s; }; }; // namespace dbgen3 #endif // GSQL_Q_SET_HPP
32.698925
94
0.599803
[ "vector" ]
740b71c92eafa2d5336d1a991b066ad30612e4d1
13,092
hpp
C++
include/UnityEngine/UI/Dropdown_DropdownItem.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/UnityEngine/UI/Dropdown_DropdownItem.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/UnityEngine/UI/Dropdown_DropdownItem.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
1
2022-03-30T21:07:35.000Z
2022-03-30T21:07:35.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: UnityEngine.UI.Dropdown #include "UnityEngine/UI/Dropdown.hpp" // Including type: UnityEngine.MonoBehaviour #include "UnityEngine/MonoBehaviour.hpp" // Including type: UnityEngine.EventSystems.ICancelHandler #include "UnityEngine/EventSystems/ICancelHandler.hpp" // Including type: UnityEngine.EventSystems.IPointerEnterHandler #include "UnityEngine/EventSystems/IPointerEnterHandler.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: UnityEngine::UI namespace UnityEngine::UI { // Forward declaring type: Text class Text; // Forward declaring type: Image class Image; // Forward declaring type: Toggle class Toggle; } // Forward declaring namespace: UnityEngine namespace UnityEngine { // Forward declaring type: RectTransform class RectTransform; } // Forward declaring namespace: UnityEngine::EventSystems namespace UnityEngine::EventSystems { // Forward declaring type: PointerEventData class PointerEventData; // Forward declaring type: BaseEventData class BaseEventData; } // Completed forward declares #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::UnityEngine::UI::Dropdown::DropdownItem); DEFINE_IL2CPP_ARG_TYPE(::UnityEngine::UI::Dropdown::DropdownItem*, "UnityEngine.UI", "Dropdown/DropdownItem"); // Type namespace: UnityEngine.UI namespace UnityEngine::UI { // Size: 0x38 #pragma pack(push, 1) // Autogenerated type: UnityEngine.UI.Dropdown/UnityEngine.UI.DropdownItem // [TokenAttribute] Offset: FFFFFFFF class Dropdown::DropdownItem : public ::UnityEngine::MonoBehaviour/*, public ::UnityEngine::EventSystems::ICancelHandler, public ::UnityEngine::EventSystems::IPointerEnterHandler*/ { public: public: // private UnityEngine.UI.Text m_Text // Size: 0x8 // Offset: 0x18 ::UnityEngine::UI::Text* m_Text; // Field size check static_assert(sizeof(::UnityEngine::UI::Text*) == 0x8); // private UnityEngine.UI.Image m_Image // Size: 0x8 // Offset: 0x20 ::UnityEngine::UI::Image* m_Image; // Field size check static_assert(sizeof(::UnityEngine::UI::Image*) == 0x8); // private UnityEngine.RectTransform m_RectTransform // Size: 0x8 // Offset: 0x28 ::UnityEngine::RectTransform* m_RectTransform; // Field size check static_assert(sizeof(::UnityEngine::RectTransform*) == 0x8); // private UnityEngine.UI.Toggle m_Toggle // Size: 0x8 // Offset: 0x30 ::UnityEngine::UI::Toggle* m_Toggle; // Field size check static_assert(sizeof(::UnityEngine::UI::Toggle*) == 0x8); public: // Creating interface conversion operator: operator ::UnityEngine::EventSystems::ICancelHandler operator ::UnityEngine::EventSystems::ICancelHandler() noexcept { return *reinterpret_cast<::UnityEngine::EventSystems::ICancelHandler*>(this); } // Creating interface conversion operator: operator ::UnityEngine::EventSystems::IPointerEnterHandler operator ::UnityEngine::EventSystems::IPointerEnterHandler() noexcept { return *reinterpret_cast<::UnityEngine::EventSystems::IPointerEnterHandler*>(this); } // Deleting conversion operator: operator ::System::IntPtr constexpr operator ::System::IntPtr() const noexcept = delete; // Get instance field reference: private UnityEngine.UI.Text m_Text [[deprecated("Use field access instead!")]] ::UnityEngine::UI::Text*& dyn_m_Text(); // Get instance field reference: private UnityEngine.UI.Image m_Image [[deprecated("Use field access instead!")]] ::UnityEngine::UI::Image*& dyn_m_Image(); // Get instance field reference: private UnityEngine.RectTransform m_RectTransform [[deprecated("Use field access instead!")]] ::UnityEngine::RectTransform*& dyn_m_RectTransform(); // Get instance field reference: private UnityEngine.UI.Toggle m_Toggle [[deprecated("Use field access instead!")]] ::UnityEngine::UI::Toggle*& dyn_m_Toggle(); // public UnityEngine.UI.Text get_text() // Offset: 0x16D7F7C ::UnityEngine::UI::Text* get_text(); // public System.Void set_text(UnityEngine.UI.Text value) // Offset: 0x16D7F84 void set_text(::UnityEngine::UI::Text* value); // public UnityEngine.UI.Image get_image() // Offset: 0x16D7F8C ::UnityEngine::UI::Image* get_image(); // public System.Void set_image(UnityEngine.UI.Image value) // Offset: 0x16D7F94 void set_image(::UnityEngine::UI::Image* value); // public UnityEngine.RectTransform get_rectTransform() // Offset: 0x16D7F9C ::UnityEngine::RectTransform* get_rectTransform(); // public System.Void set_rectTransform(UnityEngine.RectTransform value) // Offset: 0x16D7FA4 void set_rectTransform(::UnityEngine::RectTransform* value); // public UnityEngine.UI.Toggle get_toggle() // Offset: 0x16D7FAC ::UnityEngine::UI::Toggle* get_toggle(); // public System.Void set_toggle(UnityEngine.UI.Toggle value) // Offset: 0x16D7FB4 void set_toggle(::UnityEngine::UI::Toggle* value); // public System.Void .ctor() // Offset: 0x16D80F4 template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static Dropdown::DropdownItem* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("::UnityEngine::UI::Dropdown::DropdownItem::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<Dropdown::DropdownItem*, creationType>())); } // public System.Void OnPointerEnter(UnityEngine.EventSystems.PointerEventData eventData) // Offset: 0x16D7FBC void OnPointerEnter(::UnityEngine::EventSystems::PointerEventData* eventData); // public System.Void OnCancel(UnityEngine.EventSystems.BaseEventData eventData) // Offset: 0x16D8044 void OnCancel(::UnityEngine::EventSystems::BaseEventData* eventData); }; // UnityEngine.UI.Dropdown/UnityEngine.UI.DropdownItem #pragma pack(pop) static check_size<sizeof(Dropdown::DropdownItem), 48 + sizeof(::UnityEngine::UI::Toggle*)> __UnityEngine_UI_Dropdown_DropdownItemSizeCheck; static_assert(sizeof(Dropdown::DropdownItem) == 0x38); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: UnityEngine::UI::Dropdown::DropdownItem::get_text // Il2CppName: get_text template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::UnityEngine::UI::Text* (UnityEngine::UI::Dropdown::DropdownItem::*)()>(&UnityEngine::UI::Dropdown::DropdownItem::get_text)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::Dropdown::DropdownItem*), "get_text", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::UI::Dropdown::DropdownItem::set_text // Il2CppName: set_text template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::UI::Dropdown::DropdownItem::*)(::UnityEngine::UI::Text*)>(&UnityEngine::UI::Dropdown::DropdownItem::set_text)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("UnityEngine.UI", "Text")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::Dropdown::DropdownItem*), "set_text", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: UnityEngine::UI::Dropdown::DropdownItem::get_image // Il2CppName: get_image template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::UnityEngine::UI::Image* (UnityEngine::UI::Dropdown::DropdownItem::*)()>(&UnityEngine::UI::Dropdown::DropdownItem::get_image)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::Dropdown::DropdownItem*), "get_image", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::UI::Dropdown::DropdownItem::set_image // Il2CppName: set_image template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::UI::Dropdown::DropdownItem::*)(::UnityEngine::UI::Image*)>(&UnityEngine::UI::Dropdown::DropdownItem::set_image)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("UnityEngine.UI", "Image")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::Dropdown::DropdownItem*), "set_image", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: UnityEngine::UI::Dropdown::DropdownItem::get_rectTransform // Il2CppName: get_rectTransform template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::UnityEngine::RectTransform* (UnityEngine::UI::Dropdown::DropdownItem::*)()>(&UnityEngine::UI::Dropdown::DropdownItem::get_rectTransform)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::Dropdown::DropdownItem*), "get_rectTransform", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::UI::Dropdown::DropdownItem::set_rectTransform // Il2CppName: set_rectTransform template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::UI::Dropdown::DropdownItem::*)(::UnityEngine::RectTransform*)>(&UnityEngine::UI::Dropdown::DropdownItem::set_rectTransform)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("UnityEngine", "RectTransform")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::Dropdown::DropdownItem*), "set_rectTransform", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: UnityEngine::UI::Dropdown::DropdownItem::get_toggle // Il2CppName: get_toggle template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::UnityEngine::UI::Toggle* (UnityEngine::UI::Dropdown::DropdownItem::*)()>(&UnityEngine::UI::Dropdown::DropdownItem::get_toggle)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::Dropdown::DropdownItem*), "get_toggle", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::UI::Dropdown::DropdownItem::set_toggle // Il2CppName: set_toggle template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::UI::Dropdown::DropdownItem::*)(::UnityEngine::UI::Toggle*)>(&UnityEngine::UI::Dropdown::DropdownItem::set_toggle)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("UnityEngine.UI", "Toggle")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::Dropdown::DropdownItem*), "set_toggle", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: UnityEngine::UI::Dropdown::DropdownItem::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: UnityEngine::UI::Dropdown::DropdownItem::OnPointerEnter // Il2CppName: OnPointerEnter template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::UI::Dropdown::DropdownItem::*)(::UnityEngine::EventSystems::PointerEventData*)>(&UnityEngine::UI::Dropdown::DropdownItem::OnPointerEnter)> { static const MethodInfo* get() { static auto* eventData = &::il2cpp_utils::GetClassFromName("UnityEngine.EventSystems", "PointerEventData")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::Dropdown::DropdownItem*), "OnPointerEnter", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{eventData}); } }; // Writing MetadataGetter for method: UnityEngine::UI::Dropdown::DropdownItem::OnCancel // Il2CppName: OnCancel template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::UI::Dropdown::DropdownItem::*)(::UnityEngine::EventSystems::BaseEventData*)>(&UnityEngine::UI::Dropdown::DropdownItem::OnCancel)> { static const MethodInfo* get() { static auto* eventData = &::il2cpp_utils::GetClassFromName("UnityEngine.EventSystems", "BaseEventData")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::Dropdown::DropdownItem*), "OnCancel", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{eventData}); } };
56.431034
228
0.74091
[ "vector" ]
740bcae65ffcf39b5b948c6dc540d389f8eb9694
6,168
cpp
C++
gstarlocalserver/gstarlocalserver.cpp
echowalways/GStarLocalServer
e9c5c63330c531e7a5782e5e60418cccd9c06466
[ "BSD-3-Clause" ]
null
null
null
gstarlocalserver/gstarlocalserver.cpp
echowalways/GStarLocalServer
e9c5c63330c531e7a5782e5e60418cccd9c06466
[ "BSD-3-Clause" ]
null
null
null
gstarlocalserver/gstarlocalserver.cpp
echowalways/GStarLocalServer
e9c5c63330c531e7a5782e5e60418cccd9c06466
[ "BSD-3-Clause" ]
1
2018-09-15T00:15:39.000Z
2018-09-15T00:15:39.000Z
#include "gstarlocalserver.h" #include "gstarlocalserver_p.h" #include <QtCore/QLoggingCategory> #include "gstarlocalglobal.h" Q_LOGGING_CATEGORY(qlcStarLocalServer, "GStarLocalServer") // class GStarLocalServer GStarLocalServer::GStarLocalServer(QObject *parent) : QObject(*new GStarLocalServerPrivate(), parent) { setServer(qobject_cast<QLocalServer *>(parent)); } GStarLocalServer::GStarLocalServer(QLocalServer *server, QObject *parent) : QObject(*new GStarLocalServerPrivate(), parent) { setServer(server); } void GStarLocalServer::setServer(QLocalServer *server) { Q_D(GStarLocalServer); if (server == d->server) { return; } // 处理旧服务器信息. QLocalServer *oldServer = d->server.data(); if (0 != oldServer) { disconnect(oldServer, SIGNAL(destroyed()), this, SLOT(_q_destroyed())); disconnect(oldServer, SIGNAL(newConnection()), this, SLOT(_q_newConnection())); } // 设置智能指针. d->server = server; // 处理新服务器信息. QLocalServer *newServer = d->server.data(); if (0 != newServer) { connect(newServer, SIGNAL(destroyed()), this, SLOT(_q_destroyed())); connect(newServer, SIGNAL(newConnection()), this, SLOT(_q_newConnection())); } } QLocalServer *GStarLocalServer::server() const { Q_D(const GStarLocalServer); return d->server.data(); } // class GStarLocalServerPrivate GStarLocalServerPrivate::GStarLocalServerPrivate() : idGenerator(1) { } GStarLocalServerPrivate::~GStarLocalServerPrivate() { } void GStarLocalServerPrivate::_q_destroyed() { Q_Q(GStarLocalServer); QLocalServer *server = qobject_cast<QLocalServer *>(q->sender()); Q_ASSERT_X(0 != server, "GStarLocalServer", "Invalid sender object."); } void GStarLocalServerPrivate::_q_newConnection() { Q_Q(GStarLocalServer); while (server->hasPendingConnections()) { QLocalSocket *newSocket = server->nextPendingConnection(); if (0 != newSocket) { QObject::connect(newSocket, SIGNAL(error(QLocalSocket::LocalSocketError)), q, SLOT(_q_error(QLocalSocket::LocalSocketError))); QObject::connect(newSocket, SIGNAL(readyRead()), q, SLOT(_q_readyRead())); for (; ; ++idGenerator) { if ((idGenerator != 0) && !connections.contains(idGenerator)) { qCDebug(qlcStarLocalServer) << "New connection:" << idGenerator; connections.insert(idGenerator, newSocket); nameMapping.insert(newSocket, idGenerator); ++idGenerator; break; } } } } } void GStarLocalServerPrivate::_q_error(QLocalSocket::LocalSocketError) { Q_Q(GStarLocalServer); QLocalSocket *socket = qobject_cast<QLocalSocket *>(q->sender()); Q_ASSERT_X(0 != socket, "GStarLocalServer", "Invalid sender object."); removeSocket(socket); } void GStarLocalServerPrivate::_q_readyRead() { Q_Q(GStarLocalServer); QLocalSocket *socket = qobject_cast<QLocalSocket *>(q->sender()); Q_ASSERT_X(0 != socket, "GStarLocalServer", "Invalid sender object."); if (buffer.isNull()) { buffer.reset(new char[MAX_CHUNK_SIZE]); } GStarChunkHeader &chunkHeader = chunkHeaders[socket]; while (socket->bytesAvailable()) { if (chunkHeader.isValid()) { if (socket->bytesAvailable() >= chunkHeader.chunkSize()) { const qint64 actualSize = socket->read(buffer.data(), chunkHeader.chunkSize()); if (chunkHeader.chunkSize() != actualSize) { removeSocket(socket); return; } dispatch(socket, chunkHeader); chunkHeader.reset(); } else { break; } } else { if (socket->bytesAvailable() >= chunkHeader.size()) { const qint64 actualSize = socket->read(chunkHeader.data(), chunkHeader.size()); if (chunkHeader.size() != actualSize) { removeSocket(socket); return; } } else { break; } } } } void GStarLocalServerPrivate::dispatch(QLocalSocket *sender, const GStarChunkHeader &chunkHeader) { if (chunkHeader.protocol() == GStarChunkHeader::PostChunkData) { SocketId senderId = nameMapping.value(sender); if (!senderId) { qCDebug(qlcStarLocalServer) << "Invalid sender id."; return; } GStarChunkHeader postChunkHeader; postChunkHeader.set(senderId, chunkHeader.protocol(), chunkHeader.chunkSize(), chunkHeader.chunkIndex()); if (chunkHeader.targetId()) { QLocalSocket *socket = connections.value(chunkHeader.targetId()); if (socket) { post(socket, postChunkHeader); } } else { Q_FOREACH(QLocalSocket *socket, connections) { if (sender == socket) { post(socket, postChunkHeader); } } } } else if (chunkHeader.protocol() == GStarChunkHeader::GetAllSocketIds) { ; } } void GStarLocalServerPrivate::post(QLocalSocket *socket, const GStarChunkHeader &chunkHeader) { qint64 actualSize = socket->write(chunkHeader.constData(), chunkHeader.size()); if (chunkHeader.size() != actualSize) { removeSocket(socket); return; } actualSize = socket->write(buffer.data(), chunkHeader.chunkSize()); if (chunkHeader.chunkSize() != actualSize) { removeSocket(socket); return; } } void GStarLocalServerPrivate::removeSocket(QLocalSocket *socket) { qCDebug(qlcStarLocalServer) << socket->error(); socket->close(); chunkHeaders.remove(socket); connections.remove(nameMapping.take(socket)); } // class moc_gstarlocalserver.cpp #include "moc_gstarlocalserver.cpp"
28.82243
97
0.60214
[ "object" ]
740c3e235f9101ae1a1a1f6fbde0a658af070337
5,966
hpp
C++
include/ginkgo/core/base/composition.hpp
flipflapflop/ginkgo
876234e142a0f5bb2a85bb1dd2cc488c3c5d6206
[ "BSD-3-Clause" ]
null
null
null
include/ginkgo/core/base/composition.hpp
flipflapflop/ginkgo
876234e142a0f5bb2a85bb1dd2cc488c3c5d6206
[ "BSD-3-Clause" ]
null
null
null
include/ginkgo/core/base/composition.hpp
flipflapflop/ginkgo
876234e142a0f5bb2a85bb1dd2cc488c3c5d6206
[ "BSD-3-Clause" ]
null
null
null
/*******************************<GINKGO LICENSE>****************************** Copyright (c) 2017-2019, the Ginkgo authors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************<GINKGO LICENSE>*******************************/ #ifndef GKO_CORE_BASE_COMPOSITION_HPP_ #define GKO_CORE_BASE_COMPOSITION_HPP_ #include <vector> #include <ginkgo/core/base/executor.hpp> #include <ginkgo/core/base/lin_op.hpp> namespace gko { /** * The Composition class can be used to compose linear operators `op1, op2, ..., * opn` and obtain the operator `op1 * op2 * ... * opn`. * * @tparam ValueType precision of input and result vectors * * @ingroup LinOp */ template <typename ValueType = default_precision> class Composition : public EnableLinOp<Composition<ValueType>>, public EnableCreateMethod<Composition<ValueType>> { friend class EnablePolymorphicObject<Composition, LinOp>; friend class EnableCreateMethod<Composition>; public: using value_type = ValueType; /** * Returns a list of operators of the composition. * * @return a list of operators */ const std::vector<std::shared_ptr<const LinOp>> &get_operators() const noexcept { return operators_; } protected: /** * Creates an empty operator composition (0x0 operator). * * @param exec Executor associated to the composition */ explicit Composition(std::shared_ptr<const Executor> exec) : EnableLinOp<Composition>(exec) {} /** * Creates a composition of operators using the operators in a range. * * @tparam Iterator a class representing iterators over the * perators of the linear combination * * @param begin iterator pointing to the first operator * @param end iterator pointing behind the last operator */ template <typename Iterator, typename = xstd::void_t< typename std::iterator_traits<Iterator>::iterator_category>> explicit Composition(Iterator begin, Iterator end) : EnableLinOp<Composition>([&] { if (begin == end) { throw OutOfBoundsError(__FILE__, __LINE__, 1, 0); } return (*begin)->get_executor(); }()), operators_(begin, end) { this->set_size(gko::dim<2>{operators_.front()->get_size()[0], operators_.back()->get_size()[1]}); for (size_type i = 1; i < operators_.size(); ++i) { GKO_ASSERT_CONFORMANT(operators_[i - 1], operators_[i]); } } /** * Creates a composition of operators using the specified list of operators. * * @tparam Rest types of trailing parameters * * @param oper the first operator * @param rest remainging operators */ template <typename... Rest> explicit Composition(std::shared_ptr<const LinOp> oper, Rest &&... rest) : Composition(std::forward<Rest>(rest)...) { GKO_ASSERT_CONFORMANT(oper, operators_[0]); operators_.insert(begin(operators_), oper); this->set_size(gko::dim<2>{operators_.front()->get_size()[0], operators_.back()->get_size()[1]}); } /** * Creates a composition of operators using the specified list of operators. * * @param oper the first operator * * @note this is the base case of the template constructor * Composition(std::shared_ptr<const LinOp>, Rest &&...) */ explicit Composition(std::shared_ptr<const LinOp> oper) : EnableLinOp<Composition>(oper->get_executor(), oper->get_size()), operators_{oper} {} void apply_impl(const LinOp *b, LinOp *x) const override; void apply_impl(const LinOp *alpha, const LinOp *b, const LinOp *beta, LinOp *x) const override; private: std::vector<std::shared_ptr<const LinOp>> operators_; // TODO: solve race conditions when multithreading mutable struct cache_struct { cache_struct() = default; ~cache_struct() = default; cache_struct(const cache_struct &other) {} cache_struct &operator=(const cache_struct &other) { return *this; } // TODO: reduce the amount of intermediate vectors we need (careful -- // not all of them are of the same size) std::vector<std::unique_ptr<LinOp>> intermediate; } cache_; }; } // namespace gko #endif // GKO_CORE_BASE_COMPOSITION_HPP_
35.094118
80
0.659403
[ "vector" ]
740de00c6fab3921041559f4d5c60d1a69759792
4,844
hxx
C++
main/slideshow/source/inc/subsettableshapemanager.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/slideshow/source/inc/subsettableshapemanager.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/slideshow/source/inc/subsettableshapemanager.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 INCLUDED_SLIDESHOW_SUBSETTABLESHAPEMANAGER_HXX #define INCLUDED_SLIDESHOW_SUBSETTABLESHAPEMANAGER_HXX #include "shapemanager.hxx" #include "intrinsicanimationeventhandler.hxx" #include <boost/shared_ptr.hpp> /* Definition of SubsettableShapeManager interface */ namespace slideshow { namespace internal { class DocTreeNode; class AttributableShape; /** SubsettableShapeManager interface Implementers of this interface manage creation and revocation of shape subsets. Shape subsets are shapes that represent (and animate) only parts of an original's shape content. */ class SubsettableShapeManager : public ShapeManager { public: /** Query a subset of the given original shape This method queries a new (but not necessarily unique) shape, which displays only the given subset of the original one. Calling this method multiple times with the same original shape and DocTreeNode content always returns the same shape. Requesting a subset from an original shape leads to the original shape ceasing to display the subsetted content. In other words, shape content is always displayed in exactly one shape. @param rOrigShape The shape the subset is to be created for @param rSubsetShape The subset to display in the generated shape. */ virtual boost::shared_ptr<AttributableShape> getSubsetShape( const boost::shared_ptr<AttributableShape>& rOrigShape, const DocTreeNode& rTreeNode ) = 0; /** Revoke a previously queried subset shape. With this method, a previously requested subset shape is revoked again. If the last client revokes a given subset, it will cease to be displayed, and the original shape will again show the subset data. @param rOrigShape The shape the subset was created from @param rSubsetShape The subset created from rOrigShape */ virtual void revokeSubset( const boost::shared_ptr<AttributableShape>& rOrigShape, const boost::shared_ptr<AttributableShape>& rSubsetShape ) = 0; // Evil hackish way of getting intrinsic animation slide-wise /** Register an event handler that will be called when user paint parameters change. @param rHandler Handler to call when a shape listener changes */ virtual void addIntrinsicAnimationHandler( const IntrinsicAnimationEventHandlerSharedPtr& rHandler ) = 0; virtual void removeIntrinsicAnimationHandler( const IntrinsicAnimationEventHandlerSharedPtr& rHandler ) = 0; /** Notify that shape-intrinsic animations are now enabled. @return true, if this event was processed by anybody. If false is returned, no handler processed this event (and probably, nothing will happen at all) */ virtual bool notifyIntrinsicAnimationsEnabled() = 0; /** Notify that shape-intrinsic animations are now disabled. @return true, if this event was processed by anybody. If false is returned, no handler processed this event (and probably, nothing will happen at all) */ virtual bool notifyIntrinsicAnimationsDisabled() = 0; }; typedef ::boost::shared_ptr< SubsettableShapeManager > SubsettableShapeManagerSharedPtr; } } #endif /* INCLUDED_SLIDESHOW_SUBSETTABLESHAPEMANAGER_HXX */
39.382114
120
0.63398
[ "shape" ]
740e2acba9555a5c3cc41472aafe9442f045d8e3
50,597
cpp
C++
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/os/BaseBundle.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/os/BaseBundle.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/os/BaseBundle.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //========================================================================= #include "Elastos.Droid.Content.h" #include "Elastos.Droid.Os.h" #include "elastos/droid/os/BaseBundle.h" #include <elastos/core/CoreUtils.h> #include <elastos/core/StringBuilder.h> #include <elastos/utility/logging/Logger.h> #include "elastos/droid/utility/CArrayMap.h" #include "elastos/droid/utility/CSparseArray.h" #include <utils/CallStack.h> #include <binder/Parcel.h> using Elastos::Core::CoreUtils; using Elastos::Core::StringBuilder; using Elastos::Core::CByte; using Elastos::Core::CChar32; using Elastos::Core::CBoolean; using Elastos::Core::CInteger16; using Elastos::Core::CInteger32; using Elastos::Core::CInteger64; using Elastos::Core::CFloat; using Elastos::Core::CDouble; using Elastos::Core::CString; using Elastos::Core::EIID_ICharSequence; using Elastos::Utility::Logging::Logger; using Elastos::Utility::CArrayList; using Elastos::Utility::IList; using Elastos::Utility::IIterator; using Elastos::Utility::IMapEntry; using Elastos::Droid::Utility::CArrayMap; using Elastos::Droid::Utility::CSparseArray; using Elastos::Droid::Utility::ISparseArray; namespace Elastos { namespace Droid { namespace Os { AutoPtr<IParcel> InitEMPTY_PARCEL() { AutoPtr<IParcel> empty; CParcel::New((IParcel**)&empty); return empty; } CAR_INTERFACE_IMPL(BaseBundle, Object, IBaseBundle) const String BaseBundle::TAG("BaseBundle"); const Boolean BaseBundle::DEBUG = FALSE; const Int32 BaseBundle::BUNDLE_MAGIC = 0x4C444E42; // 'B' 'N' 'D' 'L' const AutoPtr<IParcel> BaseBundle::EMPTY_PARCEL = InitEMPTY_PARCEL(); const Int32 BaseBundle::VAL_NULL = -1; const Int32 BaseBundle::VAL_NOT_NULL = 0; const Int32 BaseBundle::VAL_STRING = 1; const Int32 BaseBundle::VAL_INTEGER32 = 2; const Int32 BaseBundle::VAL_MAP = 3; const Int32 BaseBundle::VAL_BUNDLE = 4; const Int32 BaseBundle::VAL_PARCELABLE = 5; const Int32 BaseBundle::VAL_INTEGER16 = 6; const Int32 BaseBundle::VAL_INTEGER64 = 7; const Int32 BaseBundle::VAL_FLOAT = 8; const Int32 BaseBundle::VAL_DOUBLE = 9; const Int32 BaseBundle::VAL_BOOLEAN = 10; const Int32 BaseBundle::VAL_CHARSEQUENCE = 11; const Int32 BaseBundle::VAL_LIST = 12; const Int32 BaseBundle::VAL_SPARSEARRAY = 13; const Int32 BaseBundle::VAL_BYTEARRAY = 14; const Int32 BaseBundle::VAL_STRINGARRAY = 15; const Int32 BaseBundle::VAL_IBINDER = 16; const Int32 BaseBundle::VAL_PARCELABLEARRAY = 17; const Int32 BaseBundle::VAL_OBJECTARRAY = 18; const Int32 BaseBundle::VAL_INTARRAY = 19; const Int32 BaseBundle::VAL_LONGARRAY = 20; const Int32 BaseBundle::VAL_BYTE = 21; const Int32 BaseBundle::VAL_SERIALIZABLE = 22; const Int32 BaseBundle::VAL_SPARSEBOOLEANARRAY = 23; const Int32 BaseBundle::VAL_BOOLEANARRAY = 24; const Int32 BaseBundle::VAL_CHARSEQUENCEARRAY = 25; const Int32 BaseBundle::VAL_ARRAYOF = 26; BaseBundle::BaseBundle() { } ECode BaseBundle::constructor( /* [in] */ IClassLoader* loader, /* [in] */ Int32 capacity) { if (capacity > 0) { CArrayMap::New(capacity, (IArrayMap**)&mMap); } else { CArrayMap::New((IArrayMap**)&mMap); } mClassLoader = loader; return NOERROR; } ECode BaseBundle::constructor() { return constructor((IClassLoader*)NULL, 0); } ECode BaseBundle::constructor( /* [in] */ IParcel* parcelledData) { return ReadFromParcelInner(parcelledData); } ECode BaseBundle::constructor( /* [in] */ IParcel* parcelledData, /* [in] */ Int32 length) { return ReadFromParcelInner(parcelledData, length); } ECode BaseBundle::constructor( /* [in] */ IClassLoader* loader) { return constructor(loader, 0); } ECode BaseBundle::constructor( /* [in] */ Int32 capacity) { return constructor((IClassLoader*)NULL, capacity); } ECode BaseBundle::constructor( /* [in] */ IBaseBundle* bundle) { BaseBundle* b = (BaseBundle*)bundle; if (b->mParcelledData != NULL) { if (b->mParcelledData == EMPTY_PARCEL) { mParcelledData = EMPTY_PARCEL; } else { CParcel::New((IParcel**)&mParcelledData); Int32 size; b->mParcelledData->GetDataSize(&size); mParcelledData->AppendFrom(b->mParcelledData, 0, size); mParcelledData->SetDataPosition(0); } } else { mParcelledData = NULL; } mMap = NULL; if (b->mMap != NULL) { CArrayMap::New(b->mMap, (IArrayMap**)&mMap); } mClassLoader = b->mClassLoader; mJavaData = b->mJavaData; return NOERROR; } ECode BaseBundle::GetPairValue( /* [out] */ String* str) { VALIDATE_NOT_NULL(str) *str = String(NULL); Unparcel(); Int32 size; mMap->GetSize(&size); if (size > 1) { Logger::W(TAG, "getPairValue() used on Bundle with multiple pairs."); } if (size == 0) { return NOERROR; } AutoPtr<IInterface> obj; mMap->GetValueAt(0, (IInterface**)&obj); if (obj == NULL) { return NOERROR; } else if (ICharSequence::Probe(obj) == NULL) { TypeWarning(String("getPairValue()"), String("String")); return NOERROR; } ICharSequence::Probe(obj)->ToString(str); return NOERROR; } ECode BaseBundle::SetClassLoader( /* [in] */ IClassLoader* loader) { mClassLoader = loader; return NOERROR; } ECode BaseBundle::GetClassLoader( /* [out] */ IClassLoader** loader) { VALIDATE_NOT_NULL(loader) if (mClassLoader == NULL) { mClassLoader = Object::GetClassLoader(TO_IINTERFACE(this)); } *loader = mClassLoader; REFCOUNT_ADD(*loader) return NOERROR; } void BaseBundle::Unparcel() { if (mParcelledData == NULL) { if (DEBUG) Logger::D(TAG, "Unparcel %p : no parcelled data", this); return; } if (mParcelledData == EMPTY_PARCEL) { if (DEBUG) Logger::D(TAG, "Unparcel %p : empty", this); if (mMap == NULL) { CArrayMap::New(1, (IArrayMap**)&mMap); } else { mMap->Erase(); } mParcelledData = NULL; return; } Int32 N; mParcelledData->ReadInt32(&N); if (DEBUG) Logger::D(TAG, "Unparcel %p: reading %d maps.", this, N); if (N < 0) { return; } if (mMap == NULL) { CArrayMap::New(N, (IArrayMap**)&mMap); } else { mMap->Erase(); mMap->EnsureCapacity(N); } ReadArrayMapInternal(mParcelledData, mMap, N, mClassLoader); //mParcelledData->Recycle(); mParcelledData = NULL; if (DEBUG) Logger::D(TAG, "Unparcel %p: final map: %p", this, mMap.Get()); } ECode BaseBundle::IsParcelled( /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result) *result = mParcelledData != NULL; return NOERROR; } ECode BaseBundle::GetSize( /* [out] */ Int32 * size) { VALIDATE_NOT_NULL(size) Unparcel(); return mMap->GetSize(size); } ECode BaseBundle::IsEmpty( /* [out] */ Boolean* empty) { VALIDATE_NOT_NULL(empty) Unparcel(); return mMap->IsEmpty(empty); } ECode BaseBundle::Clear() { Unparcel(); return mMap->Clear(); } ECode BaseBundle::ContainsKey( /* [in] */ const String& key, /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result) Unparcel(); AutoPtr<ICharSequence> keyObj = CoreUtils::Convert(key); return mMap->ContainsKey(keyObj, result); } ECode BaseBundle::Get( /* [in] */ const String& key, /* [out] */ IInterface** obj) { VALIDATE_NOT_NULL(obj) Unparcel(); AutoPtr<ICharSequence> keyObj = CoreUtils::Convert(key); return mMap->Get(keyObj, obj); } ECode BaseBundle::Remove( /* [in] */ const String& key) { Unparcel(); AutoPtr<ICharSequence> keyObj = CoreUtils::Convert(key); return mMap->Remove(keyObj); } ECode BaseBundle::PutAll( /* [in] */ IPersistableBundle* bundle) { Unparcel(); BaseBundle* bb = (BaseBundle*)bundle; bb->Unparcel(); return mMap->PutAll(IMap::Probe(bb->mMap)); } ECode BaseBundle::PutAll( /* [in] */ IMap* map) { Unparcel(); return mMap->PutAll(map); } ECode BaseBundle::GetKeySet( /* [out] */ ISet** set) { VALIDATE_NOT_NULL(set) Unparcel(); return mMap->GetKeySet(set); } ECode BaseBundle::PutBoolean( /* [in] */ const String& key, /* [in] */ Boolean value) { assert(key != NULL); Unparcel(); AutoPtr<ICharSequence> keyObj = CoreUtils::Convert(key); AutoPtr<IBoolean> valueObj = CoreUtils::Convert(value); return mMap->Put(keyObj.Get(), valueObj.Get()); } ECode BaseBundle::PutByte( /* [in] */ const String& key, /* [in] */ Byte value) { assert(key != NULL); Unparcel(); AutoPtr<ICharSequence> keyObj = CoreUtils::Convert(key); AutoPtr<IByte> valueObj = CoreUtils::ConvertByte(value); return mMap->Put(keyObj.Get(), valueObj.Get()); } ECode BaseBundle::PutChar( /* [in] */ const String& key, /* [in] */ Char32 value) { assert(key != NULL); Unparcel(); AutoPtr<ICharSequence> keyObj = CoreUtils::Convert(key); AutoPtr<IChar32> valueObj = CoreUtils::ConvertChar32(value); return mMap->Put(keyObj.Get(), valueObj.Get()); } ECode BaseBundle::PutInt16( /* [in] */ const String& key, /* [in] */ Int16 value) { assert(key != NULL); Unparcel(); AutoPtr<ICharSequence> keyObj = CoreUtils::Convert(key); AutoPtr<IInteger16> valueObj = CoreUtils::Convert(value); return mMap->Put(keyObj.Get(), valueObj.Get()); } ECode BaseBundle::PutInt32( /* [in] */ const String& key, /* [in] */ Int32 value) { assert(key != NULL); Unparcel(); AutoPtr<ICharSequence> keyObj = CoreUtils::Convert(key); AutoPtr<IInteger32> valueObj = CoreUtils::Convert(value); return mMap->Put(keyObj.Get(), valueObj.Get()); } ECode BaseBundle::PutInt64( /* [in] */ const String& key, /* [in] */ Int64 value) { assert(key != NULL); Unparcel(); AutoPtr<ICharSequence> keyObj = CoreUtils::Convert(key); AutoPtr<IInteger64> valueObj = CoreUtils::Convert(value); return mMap->Put(keyObj.Get(), valueObj.Get()); } ECode BaseBundle::PutFloat( /* [in] */ const String& key, /* [in] */ Float value) { assert(key != NULL); Unparcel(); AutoPtr<ICharSequence> keyObj = CoreUtils::Convert(key); AutoPtr<IFloat> valueObj = CoreUtils::Convert(value); return mMap->Put(keyObj.Get(), valueObj.Get()); } ECode BaseBundle::PutDouble( /* [in] */ const String& key, /* [in] */ Double value) { assert(key != NULL); Unparcel(); AutoPtr<ICharSequence> keyObj = CoreUtils::Convert(key); AutoPtr<IDouble> valueObj = CoreUtils::Convert(value); return mMap->Put(keyObj.Get(), valueObj.Get());} ECode BaseBundle::PutString( /* [in] */ const String& key, /* [in] */ const String& value) { assert(key != NULL); Unparcel(); AutoPtr<ICharSequence> keyObj = CoreUtils::Convert(key); AutoPtr<ICharSequence> valueObj = CoreUtils::Convert(value); return mMap->Put(keyObj.Get(), valueObj.Get()); } ECode BaseBundle::PutCharSequence( /* [in] */ const String& key, /* [in] */ ICharSequence* value) { assert(key != NULL); Unparcel(); AutoPtr<ICharSequence> keyObj = CoreUtils::Convert(key); return mMap->Put(keyObj.Get(), value); } ECode BaseBundle::PutIntegerArrayList( /* [in] */ const String& key, /* [in] */ IArrayList* value) { assert(key != NULL); Unparcel(); AutoPtr<ICharSequence> keyObj = CoreUtils::Convert(key); return mMap->Put(keyObj.Get(), value); } ECode BaseBundle::PutStringArrayList( /* [in] */ const String& key, /* [in] */ IArrayList* value) { assert(key != NULL); Unparcel(); AutoPtr<ICharSequence> keyObj = CoreUtils::Convert(key); return mMap->Put(keyObj.Get(), value); } ECode BaseBundle::PutCharSequenceArrayList( /* [in] */ const String& key, /* [in] */ IArrayList* value) { assert(key != NULL); Unparcel(); AutoPtr<ICharSequence> keyObj = CoreUtils::Convert(key); return mMap->Put(keyObj.Get(), value); } ECode BaseBundle::PutSerializable( /* [in] */ const String& key, /* [in] */ ISerializable* value) { assert(key != NULL); Unparcel(); AutoPtr<ICharSequence> keyObj = CoreUtils::Convert(key); return mMap->Put(keyObj.Get(), value); } ECode BaseBundle::PutBooleanArray( /* [in] */ const String& key, /* [in] */ ArrayOf<Boolean>* value) { assert(key != NULL); Unparcel(); AutoPtr<ICharSequence> keyObj = CoreUtils::Convert(key); AutoPtr<IArrayOf> valueObj = CoreUtils::Convert(value); return mMap->Put(keyObj.Get(), valueObj.Get()); } ECode BaseBundle::PutByteArray( /* [in] */ const String& key, /* [in] */ ArrayOf<Byte>* value) { assert(key != NULL); Unparcel(); AutoPtr<ICharSequence> keyObj = CoreUtils::Convert(key); AutoPtr<IArrayOf> valueObj = CoreUtils::ConvertByteArray(value); return mMap->Put(keyObj.Get(), valueObj.Get()); } ECode BaseBundle::PutCharArray( /* [in] */ const String& key, /* [in] */ ArrayOf<Char32>* value) { assert(key != NULL); Unparcel(); AutoPtr<ICharSequence> keyObj = CoreUtils::Convert(key); AutoPtr<IArrayOf> valueObj = CoreUtils::ConvertChar32Array(value); return mMap->Put(keyObj.Get(), valueObj.Get()); } ECode BaseBundle::PutInt16Array( /* [in] */ const String& key, /* [in] */ ArrayOf<Int16>* value) { assert(key != NULL); Unparcel(); AutoPtr<ICharSequence> keyObj = CoreUtils::Convert(key); AutoPtr<IArrayOf> valueObj = CoreUtils::Convert(value); return mMap->Put(keyObj.Get(), valueObj.Get()); } ECode BaseBundle::PutInt32Array( /* [in] */ const String& key, /* [in] */ ArrayOf<Int32>* value) { assert(key != NULL); Unparcel(); AutoPtr<ICharSequence> keyObj = CoreUtils::Convert(key); AutoPtr<IArrayOf> valueObj = CoreUtils::Convert(value); return mMap->Put(keyObj.Get(), valueObj.Get()); } ECode BaseBundle::PutInt64Array( /* [in] */ const String& key, /* [in] */ ArrayOf<Int64>* value) { assert(key != NULL); Unparcel(); AutoPtr<ICharSequence> keyObj = CoreUtils::Convert(key); AutoPtr<IArrayOf> valueObj = CoreUtils::Convert(value); return mMap->Put(keyObj.Get(), valueObj.Get()); } ECode BaseBundle::PutFloatArray( /* [in] */ const String& key, /* [in] */ ArrayOf<Float>* value) { assert(key != NULL); Unparcel(); AutoPtr<ICharSequence> keyObj = CoreUtils::Convert(key); AutoPtr<IArrayOf> valueObj = CoreUtils::Convert(value); return mMap->Put(keyObj.Get(), valueObj.Get()); } ECode BaseBundle::PutDoubleArray( /* [in] */ const String& key, /* [in] */ ArrayOf<Double>* value) { assert(key != NULL); Unparcel(); AutoPtr<ICharSequence> keyObj = CoreUtils::Convert(key); AutoPtr<IArrayOf> valueObj = CoreUtils::Convert(value); return mMap->Put(keyObj.Get(), valueObj.Get()); } ECode BaseBundle::PutStringArray( /* [in] */ const String& key, /* [in] */ ArrayOf<String>* value) { assert(key != NULL); Unparcel(); AutoPtr<ICharSequence> keyObj = CoreUtils::Convert(key); AutoPtr<IArrayOf> valueObj = CoreUtils::Convert(value); return mMap->Put(keyObj.Get(), valueObj.Get()); } ECode BaseBundle::PutCharSequenceArray( /* [in] */ const String& key, /* [in] */ ArrayOf<ICharSequence*>* value) { Unparcel(); AutoPtr<ICharSequence> keyObj = CoreUtils::Convert(key); AutoPtr<IArrayOf> arrObj = CoreUtils::Convert(value, EIID_ICharSequence); return mMap->Put(keyObj.Get(), arrObj.Get()); } void BaseBundle::TypeWarning( /* [in] */ const String& key, /* [in] */ const String& className) { StringBuilder sb("Error: Attempt to cast generated internal exception, Key: "); sb.Append(key); sb.Append(", className: "); sb.Append(className); Logger::W(TAG, sb.ToString()); android::CallStack stack; stack.update(); Logger::W(TAG, "backtrace:%s\n", stack.toString("").string()); assert(0 && "Please fix error!"); } AutoPtr<IInterface> BaseBundle::GetValue( /* [in] */ const String& key) { AutoPtr<ICharSequence> keyObj = CoreUtils::Convert(key); AutoPtr<IInterface> obj; mMap->Get(keyObj.Get(), (IInterface**)&obj); return obj; } ECode BaseBundle::GetBoolean( /* [in] */ const String& key, /* [out] */ Boolean* value) { return GetBoolean(key, FALSE, value); } ECode BaseBundle::GetBoolean( /* [in] */ const String& key, /* [in] */ Boolean defaultValue, /* [out] */ Boolean* value) { VALIDATE_NOT_NULL(value) *value = defaultValue; Unparcel(); AutoPtr<IInterface> obj = GetValue(key); if (obj == NULL) { return NOERROR; } IBoolean* o = IBoolean::Probe(obj); if (o == NULL) { TypeWarning(key, String("IBoolean")); return NOERROR; } return o->GetValue(value); } ECode BaseBundle::GetByte( /* [in] */ const String& key, /* [out] */ Byte* value) { return GetByte(key, (Byte)0, value); } ECode BaseBundle::GetByte( /* [in] */ const String& key, /* [in] */ Byte defaultValue, /* [out] */ Byte* value) { VALIDATE_NOT_NULL(value) *value = defaultValue; Unparcel(); AutoPtr<IInterface> obj = GetValue(key); if (obj == NULL) { return NOERROR; } IByte* o = IByte::Probe(obj); if (o == NULL) { TypeWarning(key, String("IByte")); return NOERROR; } return o->GetValue(value); } ECode BaseBundle::GetChar( /* [in] */ const String& key, /* [out] */ Char32* value) { return GetChar(key, (Char32)0, value); } ECode BaseBundle::GetChar( /* [in] */ const String& key, /* [in] */ Char32 defaultValue, /* [out] */ Char32* value) { VALIDATE_NOT_NULL(value) *value = defaultValue; Unparcel(); AutoPtr<IInterface> obj = GetValue(key); if (obj == NULL) { return NOERROR; } IChar32* o = IChar32::Probe(obj); if (o == NULL) { TypeWarning(key, String("IChar32")); return NOERROR; } return o->GetValue(value); } ECode BaseBundle::GetInt16( /* [in] */ const String& key, /* [out] */ Int16* value) { return GetInt16(key, 0, value); } ECode BaseBundle::GetInt16( /* [in] */ const String& key, /* [in] */ Int16 defaultValue, /* [out] */ Int16* value) { VALIDATE_NOT_NULL(value) *value = defaultValue; Unparcel(); AutoPtr<IInterface> obj = GetValue(key); if (obj == NULL) { return NOERROR; } IInteger16* o = IInteger16::Probe(obj); if (o == NULL) { TypeWarning(key, String("IInteger16")); return NOERROR; } return o->GetValue(value); } ECode BaseBundle::GetInt32( /* [in] */ const String& key, /* [out] */ Int32* value) { return GetInt32(key, 0, value); } ECode BaseBundle::GetInt32( /* [in] */ const String& key, /* [in] */ Int32 defaultValue, /* [out] */ Int32* value) { VALIDATE_NOT_NULL(value) *value = defaultValue; Unparcel(); AutoPtr<IInterface> obj = GetValue(key); if (obj == NULL) { return NOERROR; } IInteger32* o = IInteger32::Probe(obj); if (o == NULL) { TypeWarning(key, String("IInteger32")); return NOERROR; } return o->GetValue(value); } ECode BaseBundle::GetInt64( /* [in] */ const String& key, /* [out] */ Int64* value) { return GetInt64(key, 0, value); } ECode BaseBundle::GetInt64( /* [in] */ const String& key, /* [in] */ Int64 defaultValue, /* [out] */ Int64* value) { VALIDATE_NOT_NULL(value) *value = defaultValue; Unparcel(); AutoPtr<IInterface> obj = GetValue(key); if (obj == NULL) { return NOERROR; } IInteger64* o = IInteger64::Probe(obj); if (o == NULL) { TypeWarning(key, String("IInteger64")); return NOERROR; } return o->GetValue(value); } ECode BaseBundle::GetFloat( /* [in] */ const String& key, /* [out] */ Float* value) { return GetFloat(key, 0, value); } ECode BaseBundle::GetFloat( /* [in] */ const String& key, /* [in] */ Float defaultValue, /* [out] */ Float* value) { VALIDATE_NOT_NULL(value) *value = defaultValue; Unparcel(); AutoPtr<IInterface> obj = GetValue(key); if (obj == NULL) { return NOERROR; } IFloat* o = IFloat::Probe(obj); if (o == NULL) { TypeWarning(key, String("IFloat")); return NOERROR; } return o->GetValue(value); } ECode BaseBundle::GetDouble( /* [in] */ const String& key, /* [out] */ Double* value) { return GetDouble(key, 0, value); } ECode BaseBundle::GetDouble( /* [in] */ const String& key, /* [in] */ Double defaultValue, /* [out] */ Double* value) { VALIDATE_NOT_NULL(value) *value = defaultValue; Unparcel(); AutoPtr<IInterface> obj = GetValue(key); if (obj == NULL) { return NOERROR; } IDouble* o = IDouble::Probe(obj); if (o == NULL) { TypeWarning(key, String("IDouble")); return NOERROR; } return o->GetValue(value); } ECode BaseBundle::GetString( /* [in] */ const String& key, /* [out] */ String* value) { VALIDATE_NOT_NULL(value) *value = String(NULL); Unparcel(); AutoPtr<IInterface> obj = GetValue(key); if (obj == NULL) { return NOERROR; } ICharSequence* o = ICharSequence::Probe(obj); if (o == NULL) { TypeWarning(key, String("ICharSequence")); return NOERROR; } return o->ToString(value); } ECode BaseBundle::GetString( /* [in] */ const String& key, /* [in] */ const String& defaultValue, /* [out] */ String* value) { VALIDATE_NOT_NULL(value) *value = defaultValue; Unparcel(); AutoPtr<IInterface> obj = GetValue(key); if (obj == NULL) { return NOERROR; } ICharSequence* o = ICharSequence::Probe(obj); if (o == NULL) { TypeWarning(key, String("ICharSequence")); return NOERROR; } return o->ToString(value); } ECode BaseBundle::GetCharSequence( /* [in] */ const String& key, /* [out] */ ICharSequence** value) { VALIDATE_NOT_NULL(value) *value = NULL; Unparcel(); AutoPtr<IInterface> obj = GetValue(key); if (obj == NULL) { return NOERROR; } ICharSequence* o = ICharSequence::Probe(obj); if (o == NULL) { TypeWarning(key, String("ICharSequence")); return NOERROR; } *value = o; REFCOUNT_ADD(*value); return NOERROR; } ECode BaseBundle::GetCharSequence( /* [in] */ const String& key, /* [in] */ ICharSequence* defaultValue, /* [out] */ ICharSequence** value) { VALIDATE_NOT_NULL(value) Unparcel(); AutoPtr<IInterface> obj = GetValue(key); if (obj == NULL) { *value = defaultValue; REFCOUNT_ADD(*value); return NOERROR; } ICharSequence* o = ICharSequence::Probe(obj); if (o == NULL) { TypeWarning(key, String("ICharSequence")); *value = defaultValue; REFCOUNT_ADD(*value); return NOERROR; } *value = o; REFCOUNT_ADD(*value); return NOERROR; } ECode BaseBundle::GetSerializable( /* [in] */ const String& key, /* [out] */ ISerializable** value) { VALIDATE_NOT_NULL(value) *value = NULL; Unparcel(); AutoPtr<IInterface> obj = GetValue(key); if (obj == NULL) { return NOERROR; } ISerializable* o = ISerializable::Probe(obj); if (o == NULL) { TypeWarning(key, String("ISerializable")); return NOERROR; } *value = o; REFCOUNT_ADD(*value); return NOERROR; } ECode BaseBundle::GetIntegerArrayList( /* [in] */ const String& key, /* [out] */ IArrayList** value) { VALIDATE_NOT_NULL(value) *value = NULL; Unparcel(); AutoPtr<IInterface> obj = GetValue(key); if (obj == NULL) { return NOERROR; } IArrayList* o = IArrayList::Probe(obj); if (o == NULL) { TypeWarning(key, String("IArrayList<IInteger32>")); return NOERROR; } *value = o; REFCOUNT_ADD(*value); return NOERROR; } ECode BaseBundle::GetStringArrayList( /* [in] */ const String& key, /* [out] */ IArrayList** value) { VALIDATE_NOT_NULL(value) *value = NULL; Unparcel(); AutoPtr<IInterface> obj = GetValue(key); if (obj == NULL) { return NOERROR; } IArrayList* o = IArrayList::Probe(obj); if (o == NULL) { TypeWarning(key, String("IArrayList<ICharSequence>")); return NOERROR; } *value = o; REFCOUNT_ADD(*value); return NOERROR; } ECode BaseBundle::GetCharSequenceArrayList( /* [in] */ const String& key, /* [out] */ IArrayList** value) { VALIDATE_NOT_NULL(value) *value = NULL; Unparcel(); AutoPtr<IInterface> obj = GetValue(key); if (obj == NULL) { return NOERROR; } IArrayList* o = IArrayList::Probe(obj); if (o == NULL) { TypeWarning(key, String("IArrayList<ICharSequence>")); return NOERROR; } *value = o; REFCOUNT_ADD(*value); return NOERROR; } AutoPtr<IArrayOf> BaseBundle::GetIArrayOf( /* [in] */ const String& key, /* [in] */ const String& className) { AutoPtr<IInterface> obj = GetValue(key); if (obj == NULL) { return NULL; } AutoPtr<IArrayOf> arrayOf = IArrayOf::Probe(obj); if (arrayOf == NULL) { TypeWarning(key, className); return NULL; } return arrayOf; } ECode BaseBundle::GetBooleanArray( /* [in] */ const String& key, /* [out, callee] */ ArrayOf<Boolean>** value) { VALIDATE_NOT_NULL(value) *value = NULL; Unparcel(); AutoPtr<IArrayOf> arrObj = GetIArrayOf(key, String("BooleanArray")); AutoPtr<ArrayOf<Boolean> > array; if (arrObj) { Int32 length; arrObj->GetLength(&length); array = ArrayOf<Boolean>::Alloc(length); IBoolean* o; for (Int32 i = 0; i < length; ++i) { Boolean item = FALSE; AutoPtr<IInterface> obj; arrObj->Get(i, (IInterface**)&obj); o = IBoolean::Probe(obj); if (o != NULL) { o->GetValue(&item); } array->Set(i, item); } } *value = array; REFCOUNT_ADD(*value); return NOERROR; } ECode BaseBundle::GetByteArray( /* [in] */ const String& key, /* [out, callee] */ ArrayOf<Byte>** value) { VALIDATE_NOT_NULL(value) *value = NULL; Unparcel(); AutoPtr<IArrayOf> arrObj = GetIArrayOf(key, String("IArrayOf<IByte>")); AutoPtr<ArrayOf<Byte> > array; if (arrObj) { Int32 length; arrObj->GetLength(&length); array = ArrayOf<Byte>::Alloc(length); IByte* o; for (Int32 i = 0; i < length; ++i) { Byte item = 0; AutoPtr<IInterface> obj; arrObj->Get(i, (IInterface**)&obj); o = IByte::Probe(obj); if (o != NULL) { o->GetValue(&item); } array->Set(i, item); } } *value = array; REFCOUNT_ADD(*value); return NOERROR; } ECode BaseBundle::GetInt16Array( /* [in] */ const String& key, /* [out, callee] */ ArrayOf<Int16>** value) { VALIDATE_NOT_NULL(value) *value = NULL; Unparcel(); AutoPtr<IArrayOf> arrObj = GetIArrayOf(key, String("IArrayOf<IInteger16>")); AutoPtr<ArrayOf<Int16> > array; if (arrObj) { Int32 length; arrObj->GetLength(&length); array = ArrayOf<Int16>::Alloc(length); IInteger16* o; for (Int32 i = 0; i < length; ++i) { Int16 item = 0; AutoPtr<IInterface> obj; arrObj->Get(i, (IInterface**)&obj); o = IInteger16::Probe(obj); if (o != NULL) { o->GetValue(&item); } array->Set(i, item); } } *value = array; REFCOUNT_ADD(*value); return NOERROR; } ECode BaseBundle::GetCharArray( /* [in] */ const String& key, /* [out, callee] */ ArrayOf<Char32>** value) { VALIDATE_NOT_NULL(value) *value = NULL; Unparcel(); AutoPtr<IArrayOf> arrObj = GetIArrayOf(key, String("IArrayOf<IChar32>")); AutoPtr<ArrayOf<Char32> > array; if (arrObj) { Int32 length; arrObj->GetLength(&length); array = ArrayOf<Char32>::Alloc(length); IChar32* o; for (Int32 i = 0; i < length; ++i) { Char32 item = 0; AutoPtr<IInterface> obj; arrObj->Get(i, (IInterface**)&obj); o = IChar32::Probe(obj); if (o != NULL) { o->GetValue(&item); } array->Set(i, item); } } *value = array; REFCOUNT_ADD(*value); return NOERROR; } ECode BaseBundle::GetInt32Array( /* [in] */ const String& key, /* [out, callee] */ ArrayOf<Int32>** value) { VALIDATE_NOT_NULL(value) *value = NULL; Unparcel(); AutoPtr<IArrayOf> arrObj = GetIArrayOf(key, String("IArrayOf<IInteger32>")); AutoPtr<ArrayOf<Int32> > array; if (arrObj) { Int32 length; arrObj->GetLength(&length); array = ArrayOf<Int32>::Alloc(length); IInteger32* o; for (Int32 i = 0; i < length; ++i) { Int32 item = 0; AutoPtr<IInterface> obj; arrObj->Get(i, (IInterface**)&obj); o = IInteger32::Probe(obj); if (o != NULL) { o->GetValue(&item); } array->Set(i, item); } } *value = array; REFCOUNT_ADD(*value); return NOERROR; } ECode BaseBundle::GetInt64Array( /* [in] */ const String& key, /* [out, callee] */ ArrayOf<Int64>** value) { VALIDATE_NOT_NULL(value) *value = NULL; Unparcel(); AutoPtr<IArrayOf> arrObj = GetIArrayOf(key, String("IArrayOf<IInteger64>")); AutoPtr<ArrayOf<Int64> > array; if (arrObj) { Int32 length; arrObj->GetLength(&length); array = ArrayOf<Int64>::Alloc(length); IInteger64* o; for (Int32 i = 0; i < length; ++i) { Int64 item = 0; AutoPtr<IInterface> obj; arrObj->Get(i, (IInterface**)&obj); o = IInteger64::Probe(obj); if (o != NULL) { o->GetValue(&item); } array->Set(i, item); } } *value = array; REFCOUNT_ADD(*value); return NOERROR; } ECode BaseBundle::GetFloatArray( /* [in] */ const String& key, /* [out, callee] */ ArrayOf<Float>** value) { VALIDATE_NOT_NULL(value) *value = NULL; Unparcel(); AutoPtr<IArrayOf> arrObj = GetIArrayOf(key, String("IArrayOf<IFloat>")); AutoPtr<ArrayOf<Float> > array; if (arrObj) { Int32 length; arrObj->GetLength(&length); array = ArrayOf<Float>::Alloc(length); IFloat* o; for (Int32 i = 0; i < length; ++i) { Float item = 0; AutoPtr<IInterface> obj; arrObj->Get(i, (IInterface**)&obj); o = IFloat::Probe(obj); if (o != NULL) { o->GetValue(&item); } array->Set(i, item); } } *value = array; REFCOUNT_ADD(*value); return NOERROR; } ECode BaseBundle::GetDoubleArray( /* [in] */ const String& key, /* [out, callee] */ ArrayOf<Double>** value) { VALIDATE_NOT_NULL(value) *value = NULL; Unparcel(); AutoPtr<IArrayOf> arrObj = GetIArrayOf(key, String("IArrayOf<IDouble>")); AutoPtr<ArrayOf<Double> > array; if (arrObj) { Int32 length; arrObj->GetLength(&length); array = ArrayOf<Double>::Alloc(length); IDouble* o; for (Int32 i = 0; i < length; ++i) { Double item = 0; AutoPtr<IInterface> obj; arrObj->Get(i, (IInterface**)&obj); o = IDouble::Probe(obj); if (o != NULL) { o->GetValue(&item); } array->Set(i, item); } } *value = array; REFCOUNT_ADD(*value); return NOERROR; } ECode BaseBundle::GetStringArray( /* [in] */ const String& key, /* [out, callee] */ ArrayOf<String>** value) { VALIDATE_NOT_NULL(value) *value = NULL; Unparcel(); AutoPtr<IArrayOf> arrObj = GetIArrayOf(key, String("IArrayOf<ICharSequence>")); AutoPtr<ArrayOf<String> > array; if (arrObj) { Int32 length; arrObj->GetLength(&length); array = ArrayOf<String>::Alloc(length); ICharSequence* csq; for (Int32 i = 0; i < length; ++i) { String item; AutoPtr<IInterface> obj; arrObj->Get(i, (IInterface**)&obj); csq = ICharSequence::Probe(obj); if (csq != NULL) { csq->ToString(&item); } array->Set(i, item); } } *value = array; REFCOUNT_ADD(*value); return NOERROR; } ECode BaseBundle::GetCharSequenceArray( /* [in] */ const String& key, /* [out, callee] */ ArrayOf<ICharSequence*>** value) { VALIDATE_NOT_NULL(value) *value = NULL; Unparcel(); AutoPtr<IArrayOf> arrObj = GetIArrayOf(key, String("IArrayOf<ICharSequence>")); AutoPtr<ArrayOf<ICharSequence*> > array; if (arrObj) { Int32 length; arrObj->GetLength(&length); array = ArrayOf<ICharSequence*>::Alloc(length); for (Int32 i = 0; i < length; ++i) { AutoPtr<IInterface> obj; arrObj->Get(i, (IInterface**)&obj); array->Set(i, ICharSequence::Probe(obj)); } } *value = array; REFCOUNT_ADD(*value); return NOERROR; } ECode BaseBundle::WriteValue( /* [in] */ IParcel* dest, /* [in] */ IInterface* obj) { if (obj == NULL) { dest->WriteInt32(VAL_NULL); return NOERROR; } // else if (v instanceof String) { // writeInt(VAL_STRING); // writeString((String) v); // } else if (IInteger32::Probe(obj) != NULL) { Int32 v; IInteger32::Probe(obj)->GetValue(&v); dest->WriteInt32(VAL_INTEGER32); dest->WriteInt32(v); return NOERROR; } // else if (IMap::Probe(obj) != NULL) { // // writeInt(VAL_MAP); // // writeMap((Map) v); // Logger::I(TAG, " ======================= BaseBundle::WriteValue IMap! ============"); // return NOERROR; // } else if (IBundle::Probe(obj) != NULL) { // // Must be before Parcelable dest->WriteInt32(VAL_BUNDLE); dest->WriteInterfacePtr(obj); return NOERROR; } else if (IParcelable::Probe(obj) != NULL) { dest->WriteInt32(VAL_PARCELABLE); dest->WriteInterfacePtr(obj); return NOERROR; } else if (IInteger16::Probe(obj) != NULL) { Int16 v; IInteger16::Probe(obj)->GetValue(&v); dest->WriteInt32(VAL_INTEGER16); dest->WriteInt32((Int32)v); return NOERROR; } else if (IInteger64::Probe(obj) != NULL) { Int64 v; IInteger64::Probe(obj)->GetValue(&v); dest->WriteInt32(VAL_INTEGER64); dest->WriteInt64(v); return NOERROR; } else if (IFloat::Probe(obj) != NULL) { Float v; IFloat::Probe(obj)->GetValue(&v); dest->WriteInt32(VAL_FLOAT); dest->WriteFloat(v); return NOERROR; } else if (IDouble::Probe(obj) != NULL) { Double v; IDouble::Probe(obj)->GetValue(&v); dest->WriteInt32(VAL_DOUBLE); dest->WriteDouble(v); return NOERROR; } else if (IBoolean::Probe(obj) != NULL) { Boolean v; IBoolean::Probe(obj)->GetValue(&v); dest->WriteInt32(VAL_BOOLEAN); dest->WriteInt32(v ? 1 : 0); return NOERROR; } else if (ICharSequence::Probe(obj) != NULL) { // Must be after String String v; ICharSequence::Probe(obj)->ToString(&v); dest->WriteInt32(VAL_CHARSEQUENCE); // writeCharSequence((CharSequence) v); dest->WriteString(v); return NOERROR; } else if (IArrayOf::Probe(obj) != NULL){ AutoPtr<IArrayOf> array = IArrayOf::Probe(obj); Int32 size = 0; array->GetLength(&size); dest->WriteInt32(VAL_ARRAYOF); InterfaceID iid; array->GetTypeId(&iid); dest->WriteEMuid(iid); dest->WriteInt32(size); for (Int32 i = 0; i < size; ++i) { AutoPtr<IInterface> elem; array->Get(i, (IInterface**)&elem); WriteValue(dest, elem); } return NOERROR; } else if (IList::Probe(obj) != NULL) { dest->WriteInt32(VAL_LIST); // writeList((List) v); AutoPtr<IList> list = IList::Probe(obj); Int32 N; list->GetSize(&N); dest->WriteInt32(N); Int32 i = 0; while (i < N) { AutoPtr<IInterface> elem; list->Get(i, (IInterface**)&elem); WriteValue(dest, elem); i++; } return NOERROR; } else if (ISparseArray::Probe(obj) != NULL) { dest->WriteInt32(VAL_SPARSEARRAY); // WriteSparseArray((SparseArray) v); // if (val == NULL) { // dest->WriteInt32(-1); // return NOERROR; // } AutoPtr<ISparseArray> o = ISparseArray::Probe(obj); Int32 N = 0; o->GetSize(&N); dest->WriteInt32(N); Int32 i = 0, k = 0; while (i < N) { o->KeyAt(i, &k); dest->WriteInt32(k); AutoPtr<IInterface> v; o->ValueAt(i, (IInterface**)&v); WriteValue(dest, v); i++; } return NOERROR; } // else if (v instanceof boolean[]) { // writeInt(VAL_BOOLEANARRAY); // writeBooleanArray((boolean[]) v); // } // else if (v instanceof byte[]) { // writeInt(VAL_BYTEARRAY); // writeByteArray((byte[]) v); // } // else if (v instanceof String[]) { // writeInt(VAL_STRINGARRAY); // writeStringArray((String[]) v); // } // else if (v instanceof CharSequence[]) { // // Must be after String[] and before Object[] // writeInt(VAL_CHARSEQUENCEARRAY); // writeCharSequenceArray((CharSequence[]) v); // } else if (IBinder::Probe(obj) != NULL) { dest->WriteInt32(VAL_IBINDER); dest->WriteInterfacePtr(obj); return NOERROR; } // else if (v instanceof Parcelable[]) { // writeInt(VAL_PARCELABLEARRAY); // writeParcelableArray((Parcelable[]) v, 0); // } // else if (v instanceof Object[]) { // writeInt(VAL_OBJECTARRAY); // writeArray((Object[]) v); // } // else if (v instanceof int[]) { // writeInt(VAL_INTARRAY); // writeIntArray((int[]) v); // } // else if (v instanceof long[]) { // writeInt(VAL_LONGARRAY); // writeLongArray((long[]) v); // } else if (IByte::Probe(obj) != NULL) { Byte v; IByte::Probe(obj)->GetValue(&v); dest->WriteInt32(VAL_BYTE); dest->WriteInt32((Int32)v); return NOERROR; } // else if (v instanceof Serializable) { // // Must be last // writeInt(VAL_SERIALIZABLE); // writeSerializable((Serializable) v); // } else { Logger::D(TAG, "Unable to marshal value %p, obj=[%s]", obj, TO_CSTR(obj)); android::CallStack stack; stack.update(); Logger::W(TAG, "backtrace:%s\n", stack.toString("").string()); assert(0); return E_RUNTIME_EXCEPTION; } return NOERROR; } AutoPtr<IInterface> BaseBundle::ReadValue( /* [in] */ IParcel* source, /* [in] */ const String& keyStr) { Int32 type; source->ReadInt32(&type); switch (type) { case VAL_NULL: return NULL; // case VAL_STRING: // return readString(); case VAL_INTEGER32: { Int32 v; source->ReadInt32(&v); AutoPtr<IInteger32> obj; CInteger32::New(v, (IInteger32**)&obj); return obj; } // case VAL_MAP: // return readHashMap(loader); case VAL_PARCELABLE:{ AutoPtr<IParcelable> obj; source->ReadInterfacePtr((Handle32*)&obj); if(obj == NULL){ Logger::E(TAG, "Read IParcelable got null"); } return obj; } case VAL_INTEGER16: { Int32 v; source->ReadInt32(&v); Int16 sv = (Int16)v; AutoPtr<IInteger16> obj; CInteger16::New(sv, (IInteger16**)&obj); return obj; } case VAL_INTEGER64: { Int64 v; source->ReadInt64(&v); AutoPtr<IInteger64> obj; CInteger64::New(v, (IInteger64**)&obj); return obj; } case VAL_FLOAT: { Float v; source->ReadFloat(&v); AutoPtr<IFloat> obj; CFloat::New(v, (IFloat**)&obj); return obj; } case VAL_DOUBLE: { Double v; source->ReadDouble(&v); AutoPtr<IDouble> obj; CDouble::New(v, (IDouble**)&obj); return obj; } case VAL_BOOLEAN: { Int32 v; source->ReadInt32(&v); AutoPtr<IBoolean> obj; CBoolean::New(v == 1, (IBoolean**)&obj); return obj; } case VAL_CHARSEQUENCE: { String v; source->ReadString(&v); AutoPtr<ICharSequence> obj; CString::New(v, (ICharSequence**)&obj); return obj; } case VAL_LIST:{ Int32 N; source->ReadInt32(&N); if (N < 0) { return NULL; } AutoPtr<IList> list; CArrayList::New(N, (IList**)&list); while (N > 0) { AutoPtr<IInterface> value = ReadValue(source, keyStr); list->Add(value); N--; } return list; } // case VAL_BOOLEANARRAY: // return createBooleanArray(); // case VAL_BYTEARRAY: // return createByteArray(); // case VAL_STRINGARRAY: // return readStringArray(); // case VAL_CHARSEQUENCEARRAY: // return readCharSequenceArray(); case VAL_IBINDER: { AutoPtr<IBinder> obj; source->ReadInterfacePtr((Handle32*)&obj); if(obj == NULL){ Logger::E(TAG, "Read IBinder got null"); } return obj; } // case VAL_OBJECTARRAY: // return readArray(loader); // case VAL_INTARRAY: // return createIntArray(); // case VAL_LONGARRAY: // return createLongArray(); case VAL_BYTE: { Int32 v; source->ReadInt32(&v); AutoPtr<IByte> obj; CByte::New((Byte)v, (IByte**)&obj); return obj; } // case VAL_SERIALIZABLE: // return readSerializable(); // case VAL_PARCELABLEARRAY: // return readParcelableArray(loader); case VAL_ARRAYOF: { InterfaceID iid; source->ReadEMuid(&iid); Int32 size = 0; source->ReadInt32(&size); AutoPtr<IArrayOf> array; CArrayOf::New(iid, size, (IArrayOf**)&array); for (Int32 i = 0; i < size; ++i) { AutoPtr<IInterface> elem = ReadValue(source, keyStr); array->Set(i, elem); } return array; } case VAL_SPARSEARRAY: { Int32 N = 0; source->ReadInt32(&N); if (N < 0) { return NULL; } AutoPtr<ISparseArray> sa; CSparseArray::New(N, (ISparseArray**)&sa); while (N > 0) { Int32 key = 0; source->ReadInt32(&key); AutoPtr<IInterface> value = ReadValue(source, keyStr); //Log.i(TAG, "Unmarshalling key=" + key + " value=" + value); sa->Append(key, value); N--; } return sa; } // case VAL_SPARSEBOOLEANARRAY: // return readSparseBooleanArray(); case VAL_BUNDLE:{ AutoPtr<IParcelable> obj; source->ReadInterfacePtr((Handle32*)&obj); if(obj == NULL){ Logger::E(TAG, "Read IBundle got null"); } return obj; } default: Logger::D(TAG, "- Unmarshalling unknown type code %d for key: %s", type, keyStr.string()); android::CallStack stack; stack.update(); Logger::W(TAG, "backtrace:%s\n", stack.toString("").string()); assert(0); } return NULL; } ECode BaseBundle::ReadArrayMapInternal( /* [in] */ IParcel* source, /* [in] */ IArrayMap* arrayMap, /* [in] */ Int32 size, /* [in] */ IClassLoader* classLoader) { String key; AutoPtr<ICharSequence> keyObj; AutoPtr<IInterface> valueObj; //Logger::E(TAG, "line:%d, func:%s, size:%d\n", __LINE__, __func__, size); while (size > 0) { source->ReadString(&key); //Logger::E(TAG, "line:%d, func:%s, key:%s\n", __LINE__, __func__, key.string()); keyObj = CoreUtils::Convert(key); valueObj = ReadValue(source, key); arrayMap->Put(keyObj.Get(), valueObj.Get()); size--; } return NOERROR; } ECode BaseBundle::WriteArrayMapInternal( /* [in] */ IParcel* dest, /* [in] */ IArrayMap* map) { assert(map != NULL); Int32 size = 0; map->GetSize(&size); dest->WriteInt32(size); if (size > 0) { AutoPtr<ISet> outset; map->GetEntrySet((ISet**)&outset); AutoPtr<IIterator> it; outset->GetIterator((IIterator**)&it); Boolean hasNext = FALSE; String key; while ((it->HasNext(&hasNext), hasNext)) { AutoPtr<IInterface> outface; it->GetNext((IInterface**)&outface); AutoPtr<IMapEntry> entry = IMapEntry::Probe(outface); AutoPtr<IInterface> obj; entry->GetKey((IInterface**)&obj); assert(ICharSequence::Probe(obj) != NULL); ICharSequence::Probe(obj)->ToString(&key); dest->WriteString(key); obj = NULL; entry->GetValue((IInterface**)&obj); WriteValue(dest, obj); } } return NOERROR; } ECode BaseBundle::WriteToParcelInner( /* [in] */ IParcel* dest) { Int32 length = 0; if (mParcelledData != NULL) { if (mParcelledData == EMPTY_PARCEL) { dest->WriteInt32(0); } else { mParcelledData->GetDataSize(&length); dest->WriteInt32(length); dest->WriteInt32(BUNDLE_MAGIC); // 'B' 'N' 'D' 'L' dest->AppendFrom(mParcelledData, 0, length); } } else { // Special case for empty bundles. Int32 size = 0; if (mMap) { mMap->GetSize(&size); } if (size == 0) { dest->WriteInt32(0); } else { Int32 lengthPos; dest->GetDataPosition(&lengthPos); dest->WriteInt32(-1); // dummy, will hold length dest->WriteInt32(BUNDLE_MAGIC); // 'B' 'N' 'D' 'L' Int32 startPos, endPos; dest->GetDataPosition(&startPos); WriteArrayMapInternal(dest, mMap); dest->GetDataPosition(&endPos); // Backpatch length dest->SetDataPosition(lengthPos); length = endPos - startPos; dest->WriteInt32(length); dest->SetDataPosition(endPos); } } if (length != 0) { if (mJavaData != NULL) { dest->WriteInt32(mJavaData->GetLength()); dest->WriteArrayOf((Handle32)mJavaData.Get()); } else { dest->WriteInt32(0); } } return NOERROR; } ECode BaseBundle::ReadFromParcelInner( /* [in] */ IParcel* parcel) { Int32 length; parcel->ReadInt32(&length); if (length < 0) { // throw new RuntimeException("Bad length in parcel: " + length); return E_RUNTIME_EXCEPTION; } FAIL_RETURN(ReadFromParcelInner(parcel, length)); return NOERROR; } ECode BaseBundle::ReadFromParcelInner( /* [in] */ IParcel* source, /* [in] */ Int32 length) { if (length == 0) { // Empty Bundle or end of data. mParcelledData = EMPTY_PARCEL; return NOERROR; } android::Parcel* parcel; source->GetDataPayload((Handle32*)&parcel); Int32 magic; source->ReadInt32(&magic); if (magic != BUNDLE_MAGIC) { //noinspection ThrowableInstanceNeverThrown // String st = Log.getStackTraceString(new RuntimeException()); // Log.e("Bundle", "readBundle: bad magic number"); // Log.e("Bundle", "readBundle: trace = " + st); Logger::E(TAG, "Bad magic number for Bundle: 0x%08x", magic); return E_ILLEGAL_STATE_EXCEPTION; } // Advance within this Parcel Int32 offset; source->GetDataPosition(&offset); source->SetDataPosition(offset + length); mParcelledData = NULL; CParcel::New((IParcel**)&mParcelledData); mParcelledData->SetDataPosition(0); mParcelledData->AppendFrom(source, offset, length); mParcelledData->SetDataPosition(0); Int32 javaDataLength; source->ReadInt32(&javaDataLength); if (javaDataLength > 0) { AutoPtr<ArrayOf<Byte> > data; source->ReadArrayOf((Handle32*)&data); mJavaData = data; } return NOERROR; } ECode BaseBundle::SetJavaData( /* [in] */ ArrayOf<Byte>* data) { mJavaData = data; return NOERROR; } ECode BaseBundle::GetJavaData( /* [out, callee] */ ArrayOf<Byte>** data) { VALIDATE_NOT_NULL(data) *data = mJavaData; REFCOUNT_ADD(*data) return NOERROR; } } // namespace Os } // namespace Droid } // namespace Elastos
25.854369
98
0.575686
[ "object" ]
740e90fe32f4afd7e2761fcc6e6ff07d8199daa4
8,518
cpp
C++
vs2017/ui/GeneratedFiles5555/Debug/moc_GroupNotice.cpp
cheechang/cppcc
0292e9a9b27e0579970c83b4f6a75dcdae1558bf
[ "MIT" ]
null
null
null
vs2017/ui/GeneratedFiles5555/Debug/moc_GroupNotice.cpp
cheechang/cppcc
0292e9a9b27e0579970c83b4f6a75dcdae1558bf
[ "MIT" ]
null
null
null
vs2017/ui/GeneratedFiles5555/Debug/moc_GroupNotice.cpp
cheechang/cppcc
0292e9a9b27e0579970c83b4f6a75dcdae1558bf
[ "MIT" ]
null
null
null
/**************************************************************************** ** Meta object code from reading C++ file 'GroupNotice.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.14.2) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include <memory> #include "../../mainwindow/contact/group/GroupNotice.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'GroupNotice.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.14.2. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED struct qt_meta_stringdata_ui__GroupNotice_t { QByteArrayData data[17]; char stringdata0[278]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_ui__GroupNotice_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_ui__GroupNotice_t qt_meta_stringdata_ui__GroupNotice = { { QT_MOC_LITERAL(0, 0, 15), // "ui::GroupNotice" QT_MOC_LITERAL(1, 16, 9), // "startChat" QT_MOC_LITERAL(2, 26, 0), // "" QT_MOC_LITERAL(3, 27, 27), // "CSharedPtr<data::ChatInfo>&" QT_MOC_LITERAL(4, 55, 21), // "signalSerGetGroupInfo" QT_MOC_LITERAL(5, 77, 24), // "CSharedPtr<data::Group>&" QT_MOC_LITERAL(6, 102, 25), // "signalSerNoticePushResult" QT_MOC_LITERAL(7, 128, 20), // "signalSerGetGroupMem" QT_MOC_LITERAL(8, 149, 4), // "code" QT_MOC_LITERAL(9, 154, 13), // "data::Member&" QT_MOC_LITERAL(10, 168, 3), // "mem" QT_MOC_LITERAL(11, 172, 14), // "onMaxChatCheck" QT_MOC_LITERAL(12, 187, 15), // "onSerPushNotice" QT_MOC_LITERAL(13, 203, 20), // "onSerCancelNoticeBtn" QT_MOC_LITERAL(14, 224, 14), // "onSerNoticeBtn" QT_MOC_LITERAL(15, 239, 21), // "onSerNoticePushResult" QT_MOC_LITERAL(16, 261, 16) // "onSerGetGroupMem" }, "ui::GroupNotice\0startChat\0\0" "CSharedPtr<data::ChatInfo>&\0" "signalSerGetGroupInfo\0CSharedPtr<data::Group>&\0" "signalSerNoticePushResult\0" "signalSerGetGroupMem\0code\0data::Member&\0" "mem\0onMaxChatCheck\0onSerPushNotice\0" "onSerCancelNoticeBtn\0onSerNoticeBtn\0" "onSerNoticePushResult\0onSerGetGroupMem" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_ui__GroupNotice[] = { // content: 8, // revision 0, // classname 0, 0, // classinfo 10, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 4, // signalCount // signals: name, argc, parameters, tag, flags 1, 1, 64, 2, 0x06 /* Public */, 4, 2, 67, 2, 0x06 /* Public */, 6, 1, 72, 2, 0x06 /* Public */, 7, 2, 75, 2, 0x06 /* Public */, // slots: name, argc, parameters, tag, flags 11, 0, 80, 2, 0x0a /* Public */, 12, 0, 81, 2, 0x0a /* Public */, 13, 0, 82, 2, 0x0a /* Public */, 14, 0, 83, 2, 0x0a /* Public */, 15, 1, 84, 2, 0x0a /* Public */, 16, 2, 87, 2, 0x0a /* Public */, // signals: parameters QMetaType::Void, 0x80000000 | 3, 2, QMetaType::Void, QMetaType::Int, 0x80000000 | 5, 2, 2, QMetaType::Void, QMetaType::Int, 2, QMetaType::Void, QMetaType::Int, 0x80000000 | 9, 8, 10, // slots: parameters QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Int, 2, QMetaType::Void, QMetaType::Int, 0x80000000 | 9, 8, 10, 0 // eod }; void ui::GroupNotice::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { auto *_t = static_cast<GroupNotice *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->startChat((*reinterpret_cast< CSharedPtr<data::ChatInfo>(*)>(_a[1]))); break; case 1: _t->signalSerGetGroupInfo((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< CSharedPtr<data::Group>(*)>(_a[2]))); break; case 2: _t->signalSerNoticePushResult((*reinterpret_cast< int(*)>(_a[1]))); break; case 3: _t->signalSerGetGroupMem((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< data::Member(*)>(_a[2]))); break; case 4: _t->onMaxChatCheck(); break; case 5: _t->onSerPushNotice(); break; case 6: _t->onSerCancelNoticeBtn(); break; case 7: _t->onSerNoticeBtn(); break; case 8: _t->onSerNoticePushResult((*reinterpret_cast< int(*)>(_a[1]))); break; case 9: _t->onSerGetGroupMem((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< data::Member(*)>(_a[2]))); break; default: ; } } else if (_c == QMetaObject::IndexOfMethod) { int *result = reinterpret_cast<int *>(_a[0]); { using _t = void (GroupNotice::*)(CSharedPtr<data::ChatInfo> & ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&GroupNotice::startChat)) { *result = 0; return; } } { using _t = void (GroupNotice::*)(int , CSharedPtr<data::Group> & ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&GroupNotice::signalSerGetGroupInfo)) { *result = 1; return; } } { using _t = void (GroupNotice::*)(int ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&GroupNotice::signalSerNoticePushResult)) { *result = 2; return; } } { using _t = void (GroupNotice::*)(int , data::Member & ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&GroupNotice::signalSerGetGroupMem)) { *result = 3; return; } } } } QT_INIT_METAOBJECT const QMetaObject ui::GroupNotice::staticMetaObject = { { QMetaObject::SuperData::link<TWidget::staticMetaObject>(), qt_meta_stringdata_ui__GroupNotice.data, qt_meta_data_ui__GroupNotice, qt_static_metacall, nullptr, nullptr } }; const QMetaObject *ui::GroupNotice::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *ui::GroupNotice::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_ui__GroupNotice.stringdata0)) return static_cast<void*>(this); return TWidget::qt_metacast(_clname); } int ui::GroupNotice::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = TWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 10) qt_static_metacall(this, _c, _id, _a); _id -= 10; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 10) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 10; } return _id; } // SIGNAL 0 void ui::GroupNotice::startChat(CSharedPtr<data::ChatInfo> & _t1) { void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(std::addressof(_t1))) }; QMetaObject::activate(this, &staticMetaObject, 0, _a); } // SIGNAL 1 void ui::GroupNotice::signalSerGetGroupInfo(int _t1, CSharedPtr<data::Group> & _t2) { void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(std::addressof(_t1))), const_cast<void*>(reinterpret_cast<const void*>(std::addressof(_t2))) }; QMetaObject::activate(this, &staticMetaObject, 1, _a); } // SIGNAL 2 void ui::GroupNotice::signalSerNoticePushResult(int _t1) { void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(std::addressof(_t1))) }; QMetaObject::activate(this, &staticMetaObject, 2, _a); } // SIGNAL 3 void ui::GroupNotice::signalSerGetGroupMem(int _t1, data::Member & _t2) { void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(std::addressof(_t1))), const_cast<void*>(reinterpret_cast<const void*>(std::addressof(_t2))) }; QMetaObject::activate(this, &staticMetaObject, 3, _a); } QT_WARNING_POP QT_END_MOC_NAMESPACE
37.196507
171
0.611763
[ "object" ]
741143ec9044c6a55465ea40075572bf416d34bf
40,355
cpp
C++
ql/cashflows/conundrumpricer.cpp
sfondi/QuantLib
8a2449d2fb470a7d47a55d3e99c5dace749709c9
[ "BSD-3-Clause" ]
41
2016-03-19T02:31:54.000Z
2022-01-20T13:23:20.000Z
ql/cashflows/conundrumpricer.cpp
sfondi/QuantLib
8a2449d2fb470a7d47a55d3e99c5dace749709c9
[ "BSD-3-Clause" ]
1
2015-02-02T20:32:43.000Z
2015-02-02T20:32:43.000Z
ql/cashflows/conundrumpricer.cpp
sfondi/QuantLib
8a2449d2fb470a7d47a55d3e99c5dace749709c9
[ "BSD-3-Clause" ]
22
2016-03-17T14:14:36.000Z
2022-03-28T10:33:19.000Z
/* Copyright (C) 2006 Giorgio Facchinetti Copyright (C) 2006 Mario Pucci This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <quantlib-dev@lists.sf.net>. The license is also available online at <http://quantlib.org/license.shtml>. This program 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 license for more details. */ /*! \file conundrumpricer.hpp \brief */ #include <ql/cashflows/conundrumpricer.hpp> #include <ql/math/integrals/kronrodintegral.hpp> #include <ql/math/distributions/normaldistribution.hpp> #include <ql/pricingengines/blackformula.hpp> #include <ql/math/solvers1d/newton.hpp> #include <ql/termstructures/volatility/smilesection.hpp> #include <ql/cashflows/cmscoupon.hpp> #include <ql/termstructures/yieldtermstructure.hpp> #include <ql/quotes/simplequote.hpp> #include <ql/indexes/swapindex.hpp> #include <ql/indexes/interestrateindex.hpp> #include <ql/time/schedule.hpp> #include <ql/instruments/vanillaswap.hpp> #if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8)) || (__GNUC__ > 4)) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-local-typedefs" #endif #include <boost/bind.hpp> #if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8)) || (__GNUC__ > 4)) #pragma GCC diagnostic pop #endif namespace QuantLib { //===========================================================================// // BlackVanillaOptionPricer // //===========================================================================// BlackVanillaOptionPricer::BlackVanillaOptionPricer( Rate forwardValue, Date expiryDate, const Period& swapTenor, const boost::shared_ptr<SwaptionVolatilityStructure>& volatilityStructure) : forwardValue_(forwardValue), expiryDate_(expiryDate), swapTenor_(swapTenor), volatilityStructure_(volatilityStructure), smile_(volatilityStructure_->smileSection(expiryDate_, swapTenor_)) { } Real BlackVanillaOptionPricer::operator()(Real strike, Option::Type optionType, Real deflator) const { const Real variance = smile_->variance(strike); return deflator * blackFormula(optionType, strike, forwardValue_, std::sqrt(variance)); } //===========================================================================// // HaganPricer // //===========================================================================// HaganPricer::HaganPricer( const Handle<SwaptionVolatilityStructure>& swaptionVol, GFunctionFactory::YieldCurveModel modelOfYieldCurve, const Handle<Quote>& meanReversion) : CmsCouponPricer(swaptionVol), modelOfYieldCurve_(modelOfYieldCurve), cutoffForCaplet_(2), cutoffForFloorlet_(0), meanReversion_(meanReversion) { registerWith(meanReversion_); } void HaganPricer::initialize(const FloatingRateCoupon& coupon){ coupon_ = dynamic_cast<const CmsCoupon*>(&coupon); QL_REQUIRE(coupon_, "CMS coupon needed"); gearing_ = coupon_->gearing(); spread_ = coupon_->spread(); Time accrualPeriod = coupon_->accrualPeriod(); QL_REQUIRE(accrualPeriod != 0.0, "null accrual period"); fixingDate_ = coupon_->fixingDate(); paymentDate_ = coupon_->date(); const boost::shared_ptr<SwapIndex>& swapIndex = coupon_->swapIndex(); rateCurve_ = *(swapIndex->forwardingTermStructure()); Date today = Settings::instance().evaluationDate(); if(paymentDate_ > today) discount_ = rateCurve_->discount(paymentDate_); else discount_= 1.; spreadLegValue_ = spread_ * accrualPeriod * discount_; if (fixingDate_ > today){ swapTenor_ = swapIndex->tenor(); boost::shared_ptr<VanillaSwap> swap = swapIndex->underlyingSwap(fixingDate_); swapRateValue_ = swap->fairRate(); static const Spread bp = 1.0e-4; annuity_ = std::fabs(swap->fixedLegBPS()/bp); Size q = swapIndex->fixedLegTenor().frequency(); const Schedule& schedule = swap->fixedSchedule(); const DayCounter& dc = swapIndex->dayCounter(); //const DayCounter dc = coupon.dayCounter(); Time startTime = dc.yearFraction(rateCurve_->referenceDate(), swap->startDate()); Time swapFirstPaymentTime = dc.yearFraction(rateCurve_->referenceDate(), schedule.date(1)); Time paymentTime = dc.yearFraction(rateCurve_->referenceDate(), paymentDate_); Real delta = (paymentTime-startTime) / (swapFirstPaymentTime-startTime); switch (modelOfYieldCurve_) { case GFunctionFactory::Standard: gFunction_ = GFunctionFactory::newGFunctionStandard(q, delta, swapTenor_.length()); break; case GFunctionFactory::ExactYield: gFunction_ = GFunctionFactory::newGFunctionExactYield(*coupon_); break; case GFunctionFactory::ParallelShifts: { Handle<Quote> nullMeanReversionQuote(boost::shared_ptr<Quote>(new SimpleQuote(0.0))); gFunction_ = GFunctionFactory::newGFunctionWithShifts(*coupon_, nullMeanReversionQuote); } break; case GFunctionFactory::NonParallelShifts: gFunction_ = GFunctionFactory::newGFunctionWithShifts(*coupon_, meanReversion_); break; default: QL_FAIL("unknown/illegal gFunction type"); } vanillaOptionPricer_= boost::shared_ptr<VanillaOptionPricer>(new BlackVanillaOptionPricer(swapRateValue_, fixingDate_, swapTenor_, *swaptionVolatility())); } } Real HaganPricer::meanReversion() const { return meanReversion_->value();} Rate HaganPricer::swapletRate() const { return swapletPrice()/(coupon_->accrualPeriod()*discount_); } Real HaganPricer::capletPrice(Rate effectiveCap) const { // caplet is equivalent to call option on fixing Date today = Settings::instance().evaluationDate(); if (fixingDate_ <= today) { // the fixing is determined const Rate Rs = std::max(coupon_->swapIndex()->fixing(fixingDate_)-effectiveCap, 0.); Rate price = (gearing_*Rs)*(coupon_->accrualPeriod()*discount_); return price; } else { Real cutoffNearZero = 1e-10; Real capletPrice = 0; if (effectiveCap < cutoffForCaplet_) { Rate effectiveStrikeForMax = std::max(effectiveCap,cutoffNearZero); capletPrice = optionletPrice(Option::Call, effectiveStrikeForMax); } return gearing_ * capletPrice; } } Rate HaganPricer::capletRate(Rate effectiveCap) const { return capletPrice(effectiveCap)/(coupon_->accrualPeriod()*discount_); } Real HaganPricer::floorletPrice(Rate effectiveFloor) const { // floorlet is equivalent to put option on fixing Date today = Settings::instance().evaluationDate(); if (fixingDate_ <= today) { // the fixing is determined const Rate Rs = std::max(effectiveFloor-coupon_->swapIndex()->fixing(fixingDate_),0.); Rate price = (gearing_*Rs)*(coupon_->accrualPeriod()*discount_); return price; } else { Real cutoffNearZero = 1e-10; Real floorletPrice = 0; if (effectiveFloor > cutoffForFloorlet_){ Rate effectiveStrikeForMin = std::max(effectiveFloor,cutoffNearZero); floorletPrice=optionletPrice(Option::Put, effectiveStrikeForMin); } return gearing_ * floorletPrice; } } Rate HaganPricer::floorletRate(Rate effectiveFloor) const { return floorletPrice(effectiveFloor)/(coupon_->accrualPeriod()*discount_); } //===========================================================================// // NumericHaganPricer // //===========================================================================// namespace { class VariableChange { public: VariableChange(boost::function<Real (Real)>& f, Real a, Real b, Size k) : a_(a), width_(b-a), f_(f), k_(k) {} Real value(Real x) const { Real newVar; Real temp = width_; for (Size i = 1; i < k_ ; ++i) { temp *= x; } newVar = a_ + x* temp; return f_(newVar) * k_* temp; } private: Real a_, width_; boost::function<Real (Real)> f_; Size k_; }; class Spy { public: Spy(boost::function<Real (Real)> f) : f_(f) {} Real value(Real x){ abscissas.push_back(x); Real value = f_(x); functionValues.push_back(value); return value; } private: boost::function<Real (Real)> f_; std::vector<Real> abscissas; std::vector<Real> functionValues; }; } NumericHaganPricer::NumericHaganPricer( const Handle<SwaptionVolatilityStructure>& swaptionVol, GFunctionFactory::YieldCurveModel modelOfYieldCurve, const Handle<Quote>& meanReversion, Real lowerLimit, Real upperLimit, Real precision, Real hardUpperLimit) : HaganPricer(swaptionVol, modelOfYieldCurve, meanReversion), upperLimit_(upperLimit), lowerLimit_(lowerLimit), requiredStdDeviations_(8), precision_(precision), refiningIntegrationTolerance_(.0001), hardUpperLimit_(hardUpperLimit) { } Real NumericHaganPricer::integrate(Real a, Real b, const ConundrumIntegrand& integrand) const { Real result =.0; //double abserr =.0; //double alpha = 1.0; //double epsabs = precision_; //double epsrel = 1.0; // we are interested only in absolute precision //size_t neval =0; // we use the non adaptive algorithm only for semi infinite interval if (a>0){ // we estimate the actual boudary by testing integrand values Real upperBoundary = 2*a; while(integrand(upperBoundary)>precision_) upperBoundary *=2.0; // sometimes b < a because of a wrong estimation of b based on stdev if (b > a) upperBoundary = std::min(upperBoundary, b); boost::function<Real (Real)> f; GaussKronrodNonAdaptive gaussKronrodNonAdaptive(precision_, 1000000, 1.0); // if the integration intervall is wide enough we use the // following change variable x -> a + (b-a)*(t/(a-b))^3 upperBoundary = std::max(a,std::min(upperBoundary, hardUpperLimit_)); if (upperBoundary > 2*a){ Size k = 3; boost::function<Real (Real)> temp = boost::ref(integrand); VariableChange variableChange(temp, a, upperBoundary, k); f = boost::bind(&VariableChange::value, &variableChange, _1); result = gaussKronrodNonAdaptive(f, .0, 1.0); } else { f = boost::ref(integrand); result = gaussKronrodNonAdaptive(f, a, upperBoundary); } // if the expected precision has not been reached we use the old algorithm if (!gaussKronrodNonAdaptive.integrationSuccess()){ const GaussKronrodAdaptive integrator(precision_, 100000); b = std::max(a,std::min(b, hardUpperLimit_)); result = integrator(integrand,a , b); } } else { // if a < b we use the old algorithm b = std::max(a,std::min(b,hardUpperLimit_)); const GaussKronrodAdaptive integrator(precision_, 100000); result = integrator(integrand,a , b); } return result; } Real NumericHaganPricer::optionletPrice( Option::Type optionType, Real strike) const { boost::shared_ptr<ConundrumIntegrand> integrand(new ConundrumIntegrand(vanillaOptionPricer_, rateCurve_, gFunction_, fixingDate_, paymentDate_, annuity_, swapRateValue_, strike, optionType)); stdDeviationsForUpperLimit_= requiredStdDeviations_; Real a, b, integralValue; if (optionType==Option::Call) { upperLimit_ = resetUpperLimit(stdDeviationsForUpperLimit_); // while(upperLimit_ <= strike){ // stdDeviationsForUpperLimit_ += 1.; // upperLimit_ = resetUpperLimit(stdDeviationsForUpperLimit_); // } integralValue = integrate(strike, upperLimit_, *integrand); //refineIntegration(integralValue, *integrand); } else { a = std::min(strike, lowerLimit_); b = strike; integralValue = integrate(a, b, *integrand); } Real dFdK = integrand->firstDerivativeOfF(strike); Real swaptionPrice = (*vanillaOptionPricer_)(strike, optionType, annuity_); // v. HAGAN, Conundrums..., formule 2.17a, 2.18a return coupon_->accrualPeriod() * (discount_/annuity_) * ((1 + dFdK) * swaptionPrice + optionType*integralValue); } Real NumericHaganPricer::swapletPrice() const { Date today = Settings::instance().evaluationDate(); if (fixingDate_ <= today) { // the fixing is determined const Rate Rs = coupon_->swapIndex()->fixing(fixingDate_); Rate price = (gearing_*Rs + spread_)*(coupon_->accrualPeriod()*discount_); return price; } else { Real atmCapletPrice = optionletPrice(Option::Call, swapRateValue_); Real atmFloorletPrice = optionletPrice(Option::Put, swapRateValue_); return gearing_ *(coupon_->accrualPeriod()* discount_ * swapRateValue_ + atmCapletPrice - atmFloorletPrice) + spreadLegValue_; } } Real NumericHaganPricer::refineIntegration(Real integralValue, const ConundrumIntegrand& integrand) const { Real percDiff = 1000.; while(std::fabs(percDiff) < refiningIntegrationTolerance_){ stdDeviationsForUpperLimit_ += 1.; Real lowerLimit = upperLimit_; upperLimit_ = resetUpperLimit(stdDeviationsForUpperLimit_); Real diff = integrate(lowerLimit, upperLimit_,integrand); percDiff = diff/integralValue; integralValue += diff; } return integralValue; } Real NumericHaganPricer::resetUpperLimit( Real stdDeviationsForUpperLimit) const { //return 1.0; Real variance = swaptionVolatility()->blackVariance(fixingDate_,swapTenor_,swapRateValue_); return swapRateValue_ * std::exp(stdDeviationsForUpperLimit*std::sqrt(variance)); } //===========================================================================// // ConundrumIntegrand // //===========================================================================// NumericHaganPricer::ConundrumIntegrand::ConundrumIntegrand( const boost::shared_ptr<VanillaOptionPricer>& o, const boost::shared_ptr<YieldTermStructure>&, const boost::shared_ptr<GFunction>& gFunction, Date fixingDate, Date paymentDate, Real annuity, Real forwardValue, Real strike, Option::Type optionType) : vanillaOptionPricer_(o), forwardValue_(forwardValue), annuity_(annuity), fixingDate_(fixingDate), paymentDate_(paymentDate), strike_(strike), optionType_(optionType), gFunction_(gFunction) {} void NumericHaganPricer::ConundrumIntegrand::setStrike(Real strike) { strike_ = strike; } Real NumericHaganPricer::ConundrumIntegrand::strike() const { return strike_; } Real NumericHaganPricer::ConundrumIntegrand::annuity() const { return annuity_; } Date NumericHaganPricer::ConundrumIntegrand::fixingDate() const { return fixingDate_; } Real NumericHaganPricer::ConundrumIntegrand::functionF (const Real x) const { const Real Gx = gFunction_->operator()(x); const Real GR = gFunction_->operator()(forwardValue_); return (x - strike_) * (Gx/GR - 1.0); } Real NumericHaganPricer::ConundrumIntegrand::firstDerivativeOfF (const Real x) const { const Real Gx = gFunction_->operator()(x); const Real GR = gFunction_->operator()(forwardValue_) ; const Real G1 = gFunction_->firstDerivative(x); return (Gx/GR - 1.0) + G1/GR * (x - strike_); } Real NumericHaganPricer::ConundrumIntegrand::secondDerivativeOfF (const Real x) const { const Real GR = gFunction_->operator()(forwardValue_) ; const Real G1 = gFunction_->firstDerivative(x); const Real G2 = gFunction_->secondDerivative(x); return 2.0 * G1/GR + (x - strike_) * G2/GR; } Real NumericHaganPricer::ConundrumIntegrand::operator()(Real x) const { const Real option = (*vanillaOptionPricer_)(x, optionType_, annuity_); return option * secondDerivativeOfF(x); } //===========================================================================// // AnalyticHaganPricer // //===========================================================================// AnalyticHaganPricer::AnalyticHaganPricer( const Handle<SwaptionVolatilityStructure>& swaptionVol, GFunctionFactory::YieldCurveModel modelOfYieldCurve, const Handle<Quote>& meanReversion) : HaganPricer(swaptionVol, modelOfYieldCurve, meanReversion) { } //Hagan, 3.5b, 3.5c Real AnalyticHaganPricer::optionletPrice(Option::Type optionType, Real strike) const { Real variance = swaptionVolatility()->blackVariance(fixingDate_, swapTenor_, swapRateValue_); Real firstDerivativeOfGAtForwardValue = gFunction_->firstDerivative( swapRateValue_); Real price = 0; Real CK = (*vanillaOptionPricer_)(strike, optionType, annuity_); price += (discount_/annuity_)*CK; const Real sqrtSigma2T = std::sqrt(variance); const Real lnRoverK = std::log(swapRateValue_/strike); const Real d32 = (lnRoverK+1.5*variance)/sqrtSigma2T; const Real d12 = (lnRoverK+.5*variance)/sqrtSigma2T; const Real dminus12 = (lnRoverK-.5*variance)/sqrtSigma2T; CumulativeNormalDistribution cumulativeOfNormal; const Real N32 = cumulativeOfNormal(optionType*d32); const Real N12 = cumulativeOfNormal(optionType*d12); const Real Nminus12 = cumulativeOfNormal(optionType*dminus12); price += optionType * firstDerivativeOfGAtForwardValue * annuity_ * swapRateValue_ * (swapRateValue_ * std::exp(variance) * N32- (swapRateValue_+strike) * N12 + strike * Nminus12); price *= coupon_->accrualPeriod(); return price; } //Hagan 3.4c Real AnalyticHaganPricer::swapletPrice() const { Date today = Settings::instance().evaluationDate(); if (fixingDate_ <= today) { // the fixing is determined const Rate Rs = coupon_->swapIndex()->fixing(fixingDate_); Rate price = (gearing_*Rs + spread_)*(coupon_->accrualPeriod()*discount_); return price; } else { Real variance(swaptionVolatility()->blackVariance(fixingDate_, swapTenor_, swapRateValue_)); Real firstDerivativeOfGAtForwardValue(gFunction_->firstDerivative( swapRateValue_)); Real price = 0; price += discount_*swapRateValue_; price += firstDerivativeOfGAtForwardValue*annuity_*swapRateValue_* swapRateValue_*(std::exp(variance)-1.); return gearing_ * price * coupon_->accrualPeriod() + spreadLegValue_; } } //===========================================================================// // GFunctionStandard // //===========================================================================// Real GFunctionFactory::GFunctionStandard::operator()(Real x) { Real n = static_cast<Real>(swapLength_) * q_; return x / std::pow((1.0 + x/q_), delta_) * 1.0 / (1.0 - 1.0 / std::pow((1.0 + x/q_), n)); } Real GFunctionFactory::GFunctionStandard::firstDerivative(Real x) { Real n = static_cast<Real>(swapLength_) * q_; Real a = 1.0 + x / q_; Real AA = a - delta_/q_ * x; Real B = std::pow(a,(n - delta_ - 1.0))/(std::pow(a,n) - 1.0); Real secNum = n * x * std::pow(a,(n-1.0)); Real secDen = q_ * std::pow(a, delta_) * (std::pow(a, n) - 1.0) * (std::pow(a, n) - 1.0); Real sec = secNum / secDen; return AA * B - sec; } Real GFunctionFactory::GFunctionStandard::secondDerivative(Real x) { Real n = static_cast<Real>(swapLength_) * q_; Real a = 1.0 + x/q_; Real AA = a - delta_/q_ * x; Real A1 = (1.0 - delta_)/q_; Real B = std::pow(a,(n - delta_ - 1.0))/(std::pow(a,n) - 1.0); Real Num = (1.0 + delta_ - n) * std::pow(a, (n-delta_-2.0)) - (1.0 + delta_) * std::pow(a, (2.0*n-delta_-2.0)); Real Den = (std::pow(a, n) - 1.0) * (std::pow(a, n) - 1.0); Real B1 = 1.0 / q_ * Num / Den; Real C = x / std::pow(a, delta_); Real C1 = (std::pow(a, delta_) - delta_ /q_ * x * std::pow(a, (delta_ - 1.0))) / std::pow(a, 2 * delta_); Real D = std::pow(a, (n-1.0))/ ((std::pow(a, n) - 1.0) * (std::pow(a, n) - 1.0)); Real D1 = ((n - 1.0) * std::pow(a, (n-2.0)) * (std::pow(a, n) - 1.0) - 2 * n * std::pow(a, (2 * (n-1.0)))) / (q_ * (std::pow(a, n) - 1.0)*(std::pow(a, n) - 1.0)*(std::pow(a, n) - 1.0)); return A1 * B + AA * B1 - n/q_ * (C1 * D + C * D1); } boost::shared_ptr<GFunction> GFunctionFactory::newGFunctionStandard(Size q, Real delta, Size swapLength) { return boost::shared_ptr<GFunction>(new GFunctionStandard(q, delta, swapLength)); } //===========================================================================// // GFunctionExactYield // //===========================================================================// GFunctionFactory::GFunctionExactYield::GFunctionExactYield(const CmsCoupon& coupon){ const boost::shared_ptr<SwapIndex>& swapIndex = coupon.swapIndex(); const boost::shared_ptr<VanillaSwap>& swap = swapIndex->underlyingSwap(coupon.fixingDate()); const Schedule& schedule = swap->fixedSchedule(); Handle<YieldTermStructure> rateCurve = swapIndex->forwardingTermStructure(); const DayCounter& dc = swapIndex->dayCounter(); Real swapStartTime = dc.yearFraction(rateCurve->referenceDate(), schedule.startDate()); Real swapFirstPaymentTime = dc.yearFraction(rateCurve->referenceDate(), schedule.date(1)); Real paymentTime = dc.yearFraction(rateCurve->referenceDate(), coupon.date()); delta_ = (paymentTime-swapStartTime) / (swapFirstPaymentTime-swapStartTime); const Leg& fixedLeg(swap->fixedLeg()); Size n = fixedLeg.size(); accruals_.reserve(n); for (Size i=0; i<n; ++i) { boost::shared_ptr<Coupon> coupon = boost::dynamic_pointer_cast<Coupon>(fixedLeg[i]); accruals_.push_back(coupon->accrualPeriod()); } } Real GFunctionFactory::GFunctionExactYield::operator()(Real x) { Real product = 1.; for(Size i=0; i<accruals_.size(); i++) { product *= 1./(1.+ accruals_[i]*x); } return x*std::pow(1.+ accruals_[0]*x,-delta_)*(1./(1.-product)); } Real GFunctionFactory::GFunctionExactYield::firstDerivative(Real x) { Real c = -1.; Real derC = 0.; std::vector<Real> b; b.reserve(accruals_.size()); for (Size i=0; i<accruals_.size(); i++) { Real temp = 1.0/(1.0+ accruals_[i]*x); b.push_back(temp); c *= temp; derC += accruals_[i]*temp; } c += 1.; c = 1./c; derC *= (c-c*c); return -delta_*accruals_[0]*std::pow(b[0],delta_+1.)*x*c+ std::pow(b[0],delta_)*c+ std::pow(b[0],delta_)*x*derC; //Real dx = 1.0e-8; //return (operator()(x+dx)-operator()(x-dx))/(2.0*dx); } Real GFunctionFactory::GFunctionExactYield::secondDerivative(Real x) { Real c = -1.; Real sum = 0.; Real sumOfSquare = 0.; std::vector<Real> b; b.reserve(accruals_.size()); for(Size i=0; i<accruals_.size(); i++) { Real temp = 1.0/(1.0+ accruals_[i]*x); b.push_back(temp); c *= temp; sum += accruals_[i]*temp; sumOfSquare += std::pow(accruals_[i]*temp, 2.0); } c += 1.; c = 1./c; Real derC =sum*(c-c*c); return (-delta_*accruals_[0]*std::pow(b[0],delta_+1.)*c+ std::pow(b[0],delta_)*derC)* (-delta_*accruals_[0]*b[0]*x + 1. + x*(1.-c)*sum)+ std::pow(b[0],delta_)*c*(delta_*std::pow(accruals_[0]*b[0],2.)*x - delta_* accruals_[0]*b[0] - x*derC*sum + (1.-c)*sum - x*(1.-c)*sumOfSquare); //Real dx = 1.0e-8; //return (firstDerivative(x+dx)-firstDerivative(x-dx))/(2.0*dx); } boost::shared_ptr<GFunction> GFunctionFactory::newGFunctionExactYield(const CmsCoupon& coupon) { return boost::shared_ptr<GFunction>(new GFunctionExactYield(coupon)); } //===========================================================================// // GFunctionWithShifts // //===========================================================================// GFunctionFactory::GFunctionWithShifts::GFunctionWithShifts( const CmsCoupon& coupon, const Handle<Quote>& meanReversion) : meanReversion_(meanReversion), calibratedShift_(0.03), tmpRs_(10000000.0), accuracy_( 1.0e-14) { const boost::shared_ptr<SwapIndex>& swapIndex = coupon.swapIndex(); const boost::shared_ptr<VanillaSwap>& swap = swapIndex->underlyingSwap(coupon.fixingDate()); swapRateValue_ = swap->fairRate(); objectiveFunction_ = boost::shared_ptr<ObjectiveFunction>(new ObjectiveFunction(*this, swapRateValue_)); const Schedule& schedule = swap->fixedSchedule(); Handle<YieldTermStructure> rateCurve = swapIndex->forwardingTermStructure(); const DayCounter& dc = swapIndex->dayCounter(); swapStartTime_ = dc.yearFraction(rateCurve->referenceDate(), schedule.startDate()); discountAtStart_ = rateCurve->discount(schedule.startDate()); Real paymentTime = dc.yearFraction(rateCurve->referenceDate(), coupon.date()); shapedPaymentTime_ = shapeOfShift(paymentTime); const Leg& fixedLeg(swap->fixedLeg()); Size n = fixedLeg.size(); accruals_.reserve(n); shapedSwapPaymentTimes_.reserve(n); swapPaymentDiscounts_.reserve(n); for(Size i=0; i<n; ++i) { boost::shared_ptr<Coupon> coupon = boost::dynamic_pointer_cast<Coupon>(fixedLeg[i]); accruals_.push_back(coupon->accrualPeriod()); const Date paymentDate(coupon->date()); const double swapPaymentTime(dc.yearFraction(rateCurve->referenceDate(), paymentDate)); shapedSwapPaymentTimes_.push_back(shapeOfShift(swapPaymentTime)); swapPaymentDiscounts_.push_back(rateCurve->discount(paymentDate)); } discountRatio_ = swapPaymentDiscounts_.back()/discountAtStart_; } Real GFunctionFactory::GFunctionWithShifts::operator()(Real Rs) { const Real calibratedShift = calibrationOfShift(Rs); return Rs* functionZ(calibratedShift); } Real GFunctionFactory::GFunctionWithShifts::functionZ(Real x) { return std::exp(-shapedPaymentTime_*x) / (1.-discountRatio_*std::exp(-shapedSwapPaymentTimes_.back()*x)); } Real GFunctionFactory::GFunctionWithShifts::derRs_derX(Real x) { Real sqrtDenominator = 0; Real derSqrtDenominator = 0; for(Size i=0; i<accruals_.size(); i++) { sqrtDenominator += accruals_[i]*swapPaymentDiscounts_[i] *std::exp(-shapedSwapPaymentTimes_[i]*x); derSqrtDenominator -= shapedSwapPaymentTimes_[i]* accruals_[i]*swapPaymentDiscounts_[i] *std::exp(-shapedSwapPaymentTimes_[i]*x); } const Real denominator = sqrtDenominator* sqrtDenominator; Real numerator = 0; numerator += shapedSwapPaymentTimes_.back()* swapPaymentDiscounts_.back()* std::exp(-shapedSwapPaymentTimes_.back()*x)*sqrtDenominator; numerator -= (discountAtStart_ - swapPaymentDiscounts_.back()* std::exp(-shapedSwapPaymentTimes_.back()*x))* derSqrtDenominator; QL_REQUIRE(denominator!=0, "GFunctionWithShifts::derRs_derX: denominator == 0"); return numerator/denominator; } Real GFunctionFactory::GFunctionWithShifts::der2Rs_derX2(Real x) { Real denOfRfunztion = 0.; Real derDenOfRfunztion = 0.; Real der2DenOfRfunztion = 0.; for(Size i=0; i<accruals_.size(); i++) { denOfRfunztion += accruals_[i]*swapPaymentDiscounts_[i] *std::exp(-shapedSwapPaymentTimes_[i]*x); derDenOfRfunztion -= shapedSwapPaymentTimes_[i]* accruals_[i]*swapPaymentDiscounts_[i] *std::exp(-shapedSwapPaymentTimes_[i]*x); der2DenOfRfunztion+= shapedSwapPaymentTimes_[i]*shapedSwapPaymentTimes_[i]* accruals_[i]* swapPaymentDiscounts_[i]*std::exp(-shapedSwapPaymentTimes_[i]*x); } const Real denominator = std::pow(denOfRfunztion, 4); Real numOfDerR = 0; numOfDerR += shapedSwapPaymentTimes_.back()* swapPaymentDiscounts_.back()* std::exp(-shapedSwapPaymentTimes_.back()*x)*denOfRfunztion; numOfDerR -= (discountAtStart_ - swapPaymentDiscounts_.back()* std::exp(-shapedSwapPaymentTimes_.back()*x))* derDenOfRfunztion; const Real denOfDerR = std::pow(denOfRfunztion,2); Real derNumOfDerR = 0.; derNumOfDerR -= shapedSwapPaymentTimes_.back()*shapedSwapPaymentTimes_.back()* swapPaymentDiscounts_.back()* std::exp(-shapedSwapPaymentTimes_.back()*x)*denOfRfunztion; derNumOfDerR += shapedSwapPaymentTimes_.back()* swapPaymentDiscounts_.back()* std::exp(-shapedSwapPaymentTimes_.back()*x)*derDenOfRfunztion; derNumOfDerR -= (shapedSwapPaymentTimes_.back()*swapPaymentDiscounts_.back()* std::exp(-shapedSwapPaymentTimes_.back()*x))* derDenOfRfunztion; derNumOfDerR -= (discountAtStart_ - swapPaymentDiscounts_.back()* std::exp(-shapedSwapPaymentTimes_.back()*x))* der2DenOfRfunztion; const Real derDenOfDerR = 2*denOfRfunztion*derDenOfRfunztion; const Real numerator = derNumOfDerR*denOfDerR -numOfDerR*derDenOfDerR; QL_REQUIRE(denominator!=0, "GFunctionWithShifts::der2Rs_derX2: denominator == 0"); return numerator/denominator; } Real GFunctionFactory::GFunctionWithShifts::derZ_derX(Real x) { const Real sqrtDenominator = (1.-discountRatio_*std::exp(-shapedSwapPaymentTimes_.back()*x)); const Real denominator = sqrtDenominator* sqrtDenominator; QL_REQUIRE(denominator!=0, "GFunctionWithShifts::derZ_derX: denominator == 0"); Real numerator = 0; numerator -= shapedPaymentTime_* std::exp(-shapedPaymentTime_*x)* sqrtDenominator; numerator -= shapedSwapPaymentTimes_.back()* std::exp(-shapedPaymentTime_*x)* (1.-sqrtDenominator); return numerator/denominator; } Real GFunctionFactory::GFunctionWithShifts::der2Z_derX2(Real x) { const Real denOfZfunction = (1.-discountRatio_*std::exp(-shapedSwapPaymentTimes_.back()*x)); const Real derDenOfZfunction = shapedSwapPaymentTimes_.back()*discountRatio_*std::exp(-shapedSwapPaymentTimes_.back()*x); const Real denominator = std::pow(denOfZfunction, 4); QL_REQUIRE(denominator!=0, "GFunctionWithShifts::der2Z_derX2: denominator == 0"); Real numOfDerZ = 0; numOfDerZ -= shapedPaymentTime_* std::exp(-shapedPaymentTime_*x)* denOfZfunction; numOfDerZ -= shapedSwapPaymentTimes_.back()* std::exp(-shapedPaymentTime_*x)* (1.-denOfZfunction); const Real denOfDerZ = std::pow(denOfZfunction,2); const Real derNumOfDerZ = (-shapedPaymentTime_* std::exp(-shapedPaymentTime_*x)* (-shapedPaymentTime_+(shapedPaymentTime_*discountRatio_- shapedSwapPaymentTimes_.back()*discountRatio_)* std::exp(-shapedSwapPaymentTimes_.back()*x)) -shapedSwapPaymentTimes_.back()*std::exp(-shapedPaymentTime_*x)* (shapedPaymentTime_*discountRatio_- shapedSwapPaymentTimes_.back()*discountRatio_)* std::exp(-shapedSwapPaymentTimes_.back()*x)); const Real derDenOfDerZ = 2*denOfZfunction*derDenOfZfunction; const Real numerator = derNumOfDerZ*denOfDerZ -numOfDerZ*derDenOfDerZ; return numerator/denominator; } Real GFunctionFactory::GFunctionWithShifts::firstDerivative(Real Rs) { //Real dRs = 1.0e-8; //return (operator()(Rs+dRs)-operator()(Rs-dRs))/(2.0*dRs); const Real calibratedShift = calibrationOfShift(Rs); return functionZ(calibratedShift) + Rs * derZ_derX(calibratedShift)/derRs_derX(calibratedShift); } Real GFunctionFactory::GFunctionWithShifts::secondDerivative(Real Rs) { //Real dRs = 1.0e-8; //return (firstDerivative(Rs+dRs)-firstDerivative(Rs-dRs))/(2.0*dRs); const Real calibratedShift = calibrationOfShift(Rs); return 2.*derZ_derX(calibratedShift)/derRs_derX(calibratedShift) + Rs * der2Z_derX2(calibratedShift)/std::pow(derRs_derX(calibratedShift),2.)- Rs * derZ_derX(calibratedShift)*der2Rs_derX2(calibratedShift)/ std::pow(derRs_derX(calibratedShift),3.); } Real GFunctionFactory::GFunctionWithShifts::ObjectiveFunction::operator ()(const Real& x) const { Real result = 0; derivative_ = 0; for(Size i=0; i<o_.accruals_.size(); i++) { Real temp = o_.accruals_[i]*o_.swapPaymentDiscounts_[i] *std::exp(-o_.shapedSwapPaymentTimes_[i]*x); result += temp; derivative_ -= o_.shapedSwapPaymentTimes_[i] * temp; } result *= Rs_; derivative_ *= Rs_; Real temp = o_.swapPaymentDiscounts_.back() * std::exp(-o_.shapedSwapPaymentTimes_.back()*x); result += temp-o_.discountAtStart_; derivative_ -= o_.shapedSwapPaymentTimes_.back()*temp; return result; } Real GFunctionFactory::GFunctionWithShifts::ObjectiveFunction::derivative(const Real&) const { return derivative_; } void GFunctionFactory::GFunctionWithShifts::ObjectiveFunction::setSwapRateValue(Real x) { Rs_ = x; } Real GFunctionFactory::GFunctionWithShifts::shapeOfShift(Real s) const { const Real x(s-swapStartTime_); Real meanReversion = meanReversion_->value(); if(meanReversion>0) { return (1.-std::exp(-meanReversion*x))/meanReversion; } else { return x; } } Real GFunctionFactory::GFunctionWithShifts::calibrationOfShift(Real Rs){ if(Rs!=tmpRs_){ Real initialGuess, N=0, D=0; for(Size i=0; i<accruals_.size(); i++) { N+=accruals_[i]*swapPaymentDiscounts_[i]; D+=accruals_[i]*swapPaymentDiscounts_[i]*shapedSwapPaymentTimes_[i]; } N *= Rs; D *= Rs; N += accruals_.back() * swapPaymentDiscounts_.back() - objectiveFunction_->gFunctionWithShifts().discountAtStart_; D += accruals_.back() * swapPaymentDiscounts_.back()* shapedSwapPaymentTimes_.back(); initialGuess = N/D; objectiveFunction_->setSwapRateValue(Rs); Newton solver; solver.setMaxEvaluations(1000); // these boundaries migth not be big enough if the volatility // of big swap rate values is too high . In this case the G function // is not even integrable, so better to fix the vol than increasing // these values const Real lower = -20, upper = 20.; try { calibratedShift_ = solver.solve(*objectiveFunction_, accuracy_, std::max( std::min(initialGuess, upper*.99), lower*.99), lower, upper); } catch (std::exception& e) { QL_FAIL("meanReversion: " << meanReversion_->value() << ", swapRateValue: " << swapRateValue_ << ", swapStartTime: " << swapStartTime_ << ", shapedPaymentTime: " << shapedPaymentTime_ << "\n error message: " << e.what()); } tmpRs_=Rs; } return calibratedShift_; } boost::shared_ptr<GFunction> GFunctionFactory::newGFunctionWithShifts(const CmsCoupon& coupon, const Handle<Quote>& meanReversion) { return boost::shared_ptr<GFunction>(new GFunctionWithShifts(coupon, meanReversion)); } }
43.439182
129
0.572841
[ "vector" ]
74115fc4ea33de2d3f0c88a9e0de6ae6207af55d
2,831
hpp
C++
include/HSGIL/window/inputControl.hpp
AsulconS/MAVeD
f52b88c929873c025df4e2f07164fdfa07b05b95
[ "Zlib" ]
1
2020-08-14T04:48:10.000Z
2020-08-14T04:48:10.000Z
include/HSGIL/window/inputControl.hpp
AsulconS/MAVeD
f52b88c929873c025df4e2f07164fdfa07b05b95
[ "Zlib" ]
null
null
null
include/HSGIL/window/inputControl.hpp
AsulconS/MAVeD
f52b88c929873c025df4e2f07164fdfa07b05b95
[ "Zlib" ]
null
null
null
/******************************************************************************** * * * HSGIL - Handy Scalable Graphics Integration Library * * Copyright (c) 2020 Adrian Bedregal and Gabriela Chipana * * * * 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. * * * ********************************************************************************/ #ifndef HSGIL_INPUT_CONTROL_HPP #define HSGIL_INPUT_CONTROL_HPP #include <HSGIL/core/config.hpp> #include <HSGIL/core/common.hpp> #include <HSGIL/math/mUtils.hpp> #include <HSGIL/window/iInputControl.hpp> namespace gil { /** * @brief InputControl Class that is an input controller with a magnitude * clamped between -1.0f and 1.0f, its aimed to be some axis or direction * handler (i.e. movement, rotation, physics). */ class HSGIL_API InputControl : public IInputControl { public: /** * @brief Construct a new Input Control object * */ InputControl(); /** * @brief Destroy the Input Control object * */ virtual ~InputControl(); /** * @brief Adds an amount to its magnitude * * @param amount */ virtual void accum(const float amount) override; /** * @brief Get the Magnitude of the control * * @return float */ virtual float getMagnitude() override; }; } // namespace gil #endif // HSGIL_INPUT_CONTROL_HPP
39.319444
82
0.49947
[ "object" ]
741297f4e205554174f33c63565122a97b182d0a
321
cc
C++
UX/src/Cursor.cc
frankencode/CoreComponents
4c66d7ff9fc5be19222906ba89ba0e98951179de
[ "Zlib" ]
1
2019-07-29T04:07:29.000Z
2019-07-29T04:07:29.000Z
UX/src/Cursor.cc
frankencode/CoreComponents
4c66d7ff9fc5be19222906ba89ba0e98951179de
[ "Zlib" ]
null
null
null
UX/src/Cursor.cc
frankencode/CoreComponents
4c66d7ff9fc5be19222906ba89ba0e98951179de
[ "Zlib" ]
1
2020-03-04T17:13:04.000Z
2020-03-04T17:13:04.000Z
/* * Copyright (C) 2020 Frank Mertens. * * Distribution and use is allowed under the terms of the zlib license * (see cc/LICENSE-zlib). * */ #include <cc/Cursor> #include <cc/Application> namespace cc { Cursor::Cursor(CursorShape shape) { *this = Application{}.me().createCursor(shape); } } // namespace cc
16.05
70
0.676012
[ "shape" ]
74134a25de98ff29a16ad2e3b55cc1e39fdc3729
7,801
cc
C++
opensfm/src/geometry/src/triangulation.cc
ricklentz/OpenSfM
b44b5f2b533b6fce8055b3a5a98a59bc22ae2cf6
[ "BSD-2-Clause" ]
2
2022-01-27T07:05:44.000Z
2022-03-01T01:10:14.000Z
opensfm/src/geometry/src/triangulation.cc
ricklentz/OpenSfM
b44b5f2b533b6fce8055b3a5a98a59bc22ae2cf6
[ "BSD-2-Clause" ]
null
null
null
opensfm/src/geometry/src/triangulation.cc
ricklentz/OpenSfM
b44b5f2b533b6fce8055b3a5a98a59bc22ae2cf6
[ "BSD-2-Clause" ]
1
2022-03-01T01:10:15.000Z
2022-03-01T01:10:15.000Z
#include <ceres/cost_function.h> #include <ceres/rotation.h> #include <ceres/tiny_solver.h> #include <ceres/tiny_solver_cost_function_adapter.h> #include <foundation/types.h> #include <geometry/transformations_functions.h> #include <geometry/triangulation.h> #include <math.h> double AngleBetweenVectors(const Eigen::Vector3d &u, const Eigen::Vector3d &v) { double c = (u.dot(v)) / sqrt(u.dot(u) * v.dot(v)); if (std::fabs(c) >= 1.0) return 0.0; else return acos(c); } Eigen::Vector4d TriangulateBearingsDLTSolve( const Eigen::Matrix<double, Eigen::Dynamic, 3> &bearings, const std::vector<Eigen::Matrix<double, 3, 4>> &Rts) { const int nviews = bearings.rows(); assert(nviews == Rts.size()); Eigen::MatrixXd A(2 * nviews, 4); for (int i = 0; i < nviews; i++) { A.row(2 * i) = bearings(i, 0) * Rts[i].row(2) - bearings(i, 2) * Rts[i].row(0); A.row(2 * i + 1) = bearings(i, 1) * Rts[i].row(2) - bearings(i, 2) * Rts[i].row(1); } Eigen::JacobiSVD<Eigen::MatrixXd> mySVD(A, Eigen::ComputeFullV); Eigen::Vector4d worldPoint; worldPoint[0] = mySVD.matrixV()(0, 3); worldPoint[1] = mySVD.matrixV()(1, 3); worldPoint[2] = mySVD.matrixV()(2, 3); worldPoint[3] = mySVD.matrixV()(3, 3); return worldPoint; } namespace geometry { std::pair<bool, Eigen::Vector3d> TriangulateBearingsDLT( const std::vector<Eigen::Matrix<double, 3, 4>> &Rts, const Eigen::Matrix<double, Eigen::Dynamic, 3> &bearings, double threshold, double min_angle) { const int count = Rts.size(); Eigen::MatrixXd world_bearings(count, 3); bool angle_ok = false; for (int i = 0; i < count && !angle_ok; ++i) { const Eigen::Matrix<double, 3, 4> Rt = Rts[i]; world_bearings.row(i) = Rt.block<3, 3>(0, 0).transpose() * bearings.row(i).transpose(); for (int j = 0; j < i && !angle_ok; ++j) { const double angle = AngleBetweenVectors(world_bearings.row(i), world_bearings.row(j)); if (angle >= min_angle) { angle_ok = true; } } } if (!angle_ok) { return std::make_pair(false, Eigen::Vector3d()); } Eigen::Vector4d X = TriangulateBearingsDLTSolve(bearings, Rts); X /= X(3); for (int i = 0; i < count; ++i) { const Eigen::Vector3d projected = Rts[i] * X; if (AngleBetweenVectors(projected, bearings.row(i)) > threshold) { return std::make_pair(false, Eigen::Vector3d()); } } return std::make_pair(true, X.head<3>()); } std::vector<std::pair<bool, Eigen::Vector3d>> TriangulateTwoBearingsMidpointMany( const Eigen::Matrix<double, Eigen::Dynamic, 3> &bearings1, const Eigen::Matrix<double, Eigen::Dynamic, 3> &bearings2, const Eigen::Matrix3d &rotation, const Eigen::Vector3d &translation) { std::vector<std::pair<bool, Eigen::Vector3d>> triangulated(bearings1.rows()); Eigen::Matrix<double, 2, 3> os, bs; os.row(0) = Eigen::Vector3d::Zero(); os.row(1) = translation; for (int i = 0; i < bearings1.rows(); ++i) { bs.row(0) = bearings1.row(i); bs.row(1) = rotation * bearings2.row(i).transpose(); triangulated[i] = TriangulateTwoBearingsMidpointSolve(os, bs); } return triangulated; } std::pair<bool, Eigen::Vector3d> TriangulateBearingsMidpoint( const Eigen::Matrix<double, Eigen::Dynamic, 3> &centers, const Eigen::Matrix<double, Eigen::Dynamic, 3> &bearings, const std::vector<double> &threshold_list, double min_angle) { const int count = centers.rows(); // Check angle between rays bool angle_ok = false; for (int i = 0; i < count && !angle_ok; ++i) { for (int j = 0; j < i && !angle_ok; ++j) { const auto angle = AngleBetweenVectors(bearings.row(i), bearings.row(j)); if (angle >= min_angle) { angle_ok = true; } } } if (!angle_ok) { return std::make_pair(false, Eigen::Vector3d()); } // Triangulate const auto X = TriangulateBearingsMidpointSolve(centers, bearings); // Check reprojection error for (int i = 0; i < count; ++i) { const Eigen::Vector3d projected = X - centers.row(i).transpose(); const Eigen::Vector3d measured = bearings.row(i); if (AngleBetweenVectors(projected, measured) > threshold_list[i]) { return std::make_pair(false, Eigen::Vector3d()); } } return std::make_pair(true, X.head<3>()); } Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> EpipolarAngleTwoBearingsMany( const Eigen::Matrix<float, Eigen::Dynamic, 3> &bearings1, const Eigen::Matrix<float, Eigen::Dynamic, 3> &bearings2, const Eigen::Matrix3f &rotation, const Eigen::Vector3f &translation) { const auto translation_normalized = translation.normalized(); const auto bearings2_world = bearings2 * rotation.transpose(); const auto count1 = bearings1.rows(); Eigen::Matrix<float, Eigen::Dynamic, 3> epi1(count1, 3); for (int i = 0; i < count1; ++i) { const Vec3f bearing = bearings1.row(i); epi1.row(i) = translation_normalized.cross(bearing).normalized(); } const auto count2 = bearings2.rows(); Eigen::Matrix<float, Eigen::Dynamic, 3> epi2(count2, 3); for (int i = 0; i < count2; ++i) { const Vec3f bearing = bearings2_world.row(i); epi2.row(i) = translation_normalized.cross(bearing).normalized(); } Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> symmetric_epi = (((epi1 * bearings2_world.transpose()).array().abs() + (bearings1 * epi2.transpose()).array().abs()) / 2.0); return M_PI / 2.0 - symmetric_epi.array().acos(); } struct BearingErrorCost : public ceres::CostFunction { constexpr static int Size = 3; BearingErrorCost(const MatX3d &centers, const MatX3d &bearings, const Vec3d &point) : centers_(centers), bearings_(bearings), point_(point) { mutable_parameter_block_sizes()->push_back(Size); set_num_residuals(bearings_.rows() * 3); } bool Evaluate(double const *const *parameters, double *residuals, double **jacobians) const override { const double *point = parameters[0]; for (int i = 0; i < bearings_.rows(); ++i) { const Vec3d &center = centers_.row(i); const Vec3d &bearing = bearings_.row(i); /* Error only */ double *dummy = nullptr; double projected[] = {point[0] - center(0), point[1] - center(1), point[2] - center(2)}; if (!jacobians) { geometry::Normalize::Forward(&projected[0], dummy, &projected[0]); } else { constexpr int JacobianSize = Size * Size; double jacobian[JacobianSize]; geometry::Normalize::ForwardDerivatives<double, true>( &projected[0], dummy, &projected[0], &jacobian[0]); double *jac_point = jacobians[0]; if (jac_point) { for (int j = 0; j < Size; ++j) { for (int k = 0; k < Size; ++k) { jac_point[i * JacobianSize + j * Size + k] = jacobian[j * Size + k]; } } } } // The error is the difference between the predicted and observed position for (int j = 0; j < Size; ++j) { residuals[i * 3 + j] = (projected[j] - bearing[j]); } } return true; } const MatX3d &centers_; const MatX3d &bearings_; const Vec3d &point_; }; constexpr int BearingErrorCost::Size; Vec3d PointRefinement(const MatX3d &centers, const MatX3d &bearings, const Vec3d &point, int iterations) { using BearingCostFunction = ceres::TinySolverCostFunctionAdapter<Eigen::Dynamic, 3>; BearingErrorCost cost(centers, bearings, point); BearingCostFunction f(cost); Vec3d refined = point; ceres::TinySolver<BearingCostFunction> solver; solver.options.max_num_iterations = iterations; solver.Solve(f, &refined); return refined; } } // namespace geometry
34.065502
80
0.636585
[ "geometry", "vector" ]
7413a1f09e30ba288788ec955196e0bf19c169c0
10,345
cpp
C++
src/qt/walletcontroller.cpp
XziimP/bitgesell
cdf1295f44e840e5603b22f2c2cdfec9572c7bcf
[ "MIT" ]
4
2020-05-14T11:49:20.000Z
2022-01-19T19:54:54.000Z
src/qt/walletcontroller.cpp
XSWLO/bitcoin
b931f61b9ab098ea4ea8fbe4cbf0b03c566c3f63
[ "MIT" ]
125
2020-01-16T11:02:04.000Z
2022-03-24T12:27:13.000Z
src/qt/walletcontroller.cpp
XSWLO/bitcoin
b931f61b9ab098ea4ea8fbe4cbf0b03c566c3f63
[ "MIT" ]
9
2020-04-06T14:31:16.000Z
2021-09-30T07:50:29.000Z
// Copyright (c) 2019 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 <qt/walletcontroller.h> #include <qt/askpassphrasedialog.h> #include <qt/createwalletdialog.h> #include <qt/guiconstants.h> #include <qt/guiutil.h> #include <qt/walletmodel.h> #include <interfaces/handler.h> #include <interfaces/node.h> #include <util/string.h> #include <wallet/wallet.h> #include <algorithm> #include <QApplication> #include <QMessageBox> #include <QMutexLocker> #include <QThread> #include <QTimer> #include <QWindow> WalletController::WalletController(interfaces::Node& node, const PlatformStyle* platform_style, OptionsModel* options_model, QObject* parent) : QObject(parent) , m_activity_thread(new QThread(this)) , m_activity_worker(new QObject) , m_node(node) , m_platform_style(platform_style) , m_options_model(options_model) { m_handler_load_wallet = m_node.handleLoadWallet([this](std::unique_ptr<interfaces::Wallet> wallet) { getOrCreateWallet(std::move(wallet)); }); for (std::unique_ptr<interfaces::Wallet>& wallet : m_node.getWallets()) { getOrCreateWallet(std::move(wallet)); } m_activity_worker->moveToThread(m_activity_thread); m_activity_thread->start(); } // Not using the default destructor because not all member types definitions are // available in the header, just forward declared. WalletController::~WalletController() { m_activity_thread->quit(); m_activity_thread->wait(); delete m_activity_worker; } std::vector<WalletModel*> WalletController::getOpenWallets() const { QMutexLocker locker(&m_mutex); return m_wallets; } std::map<std::string, bool> WalletController::listWalletDir() const { QMutexLocker locker(&m_mutex); std::map<std::string, bool> wallets; for (const std::string& name : m_node.listWalletDir()) { wallets[name] = false; } for (WalletModel* wallet_model : m_wallets) { auto it = wallets.find(wallet_model->wallet().getWalletName()); if (it != wallets.end()) it->second = true; } return wallets; } void WalletController::closeWallet(WalletModel* wallet_model, QWidget* parent) { QMessageBox box(parent); box.setWindowTitle(tr("Close wallet")); box.setText(tr("Are you sure you wish to close the wallet <i>%1</i>?").arg(GUIUtil::HtmlEscape(wallet_model->getDisplayName()))); box.setInformativeText(tr("Closing the wallet for too long can result in having to resync the entire chain if pruning is enabled.")); box.setStandardButtons(QMessageBox::Yes|QMessageBox::Cancel); box.setDefaultButton(QMessageBox::Yes); if (box.exec() != QMessageBox::Yes) return; // First remove wallet from node. wallet_model->wallet().remove(); // Now release the model. removeAndDeleteWallet(wallet_model); } WalletModel* WalletController::getOrCreateWallet(std::unique_ptr<interfaces::Wallet> wallet) { QMutexLocker locker(&m_mutex); // Return model instance if exists. if (!m_wallets.empty()) { std::string name = wallet->getWalletName(); for (WalletModel* wallet_model : m_wallets) { if (wallet_model->wallet().getWalletName() == name) { return wallet_model; } } } // Instantiate model and register it. WalletModel* wallet_model = new WalletModel(std::move(wallet), m_node, m_platform_style, m_options_model, nullptr); // Handler callback runs in a different thread so fix wallet model thread affinity. wallet_model->moveToThread(thread()); wallet_model->setParent(this); m_wallets.push_back(wallet_model); // WalletModel::startPollBalance needs to be called in a thread managed by // Qt because of startTimer. Considering the current thread can be a RPC // thread, better delegate the calling to Qt with Qt::AutoConnection. const bool called = QMetaObject::invokeMethod(wallet_model, "startPollBalance"); assert(called); connect(wallet_model, &WalletModel::unload, [this, wallet_model] { // Defer removeAndDeleteWallet when no modal widget is active. // TODO: remove this workaround by removing usage of QDiallog::exec. if (QApplication::activeModalWidget()) { connect(qApp, &QApplication::focusWindowChanged, wallet_model, [this, wallet_model]() { if (!QApplication::activeModalWidget()) { removeAndDeleteWallet(wallet_model); } }, Qt::QueuedConnection); } else { removeAndDeleteWallet(wallet_model); } }); // Re-emit coinsSent signal from wallet model. connect(wallet_model, &WalletModel::coinsSent, this, &WalletController::coinsSent); // Notify walletAdded signal on the GUI thread. Q_EMIT walletAdded(wallet_model); return wallet_model; } void WalletController::removeAndDeleteWallet(WalletModel* wallet_model) { // Unregister wallet model. { QMutexLocker locker(&m_mutex); m_wallets.erase(std::remove(m_wallets.begin(), m_wallets.end(), wallet_model)); } Q_EMIT walletRemoved(wallet_model); // Currently this can trigger the unload since the model can hold the last // CWallet shared pointer. delete wallet_model; } WalletControllerActivity::WalletControllerActivity(WalletController* wallet_controller, QWidget* parent_widget) : QObject(wallet_controller) , m_wallet_controller(wallet_controller) , m_parent_widget(parent_widget) { } WalletControllerActivity::~WalletControllerActivity() { delete m_progress_dialog; } void WalletControllerActivity::showProgressDialog(const QString& label_text) { m_progress_dialog = new QProgressDialog(m_parent_widget); m_progress_dialog->setLabelText(label_text); m_progress_dialog->setRange(0, 0); m_progress_dialog->setCancelButton(nullptr); m_progress_dialog->setWindowModality(Qt::ApplicationModal); GUIUtil::PolishProgressDialog(m_progress_dialog); } CreateWalletActivity::CreateWalletActivity(WalletController* wallet_controller, QWidget* parent_widget) : WalletControllerActivity(wallet_controller, parent_widget) { m_passphrase.reserve(MAX_PASSPHRASE_SIZE); } CreateWalletActivity::~CreateWalletActivity() { delete m_create_wallet_dialog; delete m_passphrase_dialog; } void CreateWalletActivity::askPassphrase() { m_passphrase_dialog = new AskPassphraseDialog(AskPassphraseDialog::Encrypt, m_parent_widget, &m_passphrase); m_passphrase_dialog->setWindowModality(Qt::ApplicationModal); m_passphrase_dialog->show(); connect(m_passphrase_dialog, &QObject::destroyed, [this] { m_passphrase_dialog = nullptr; }); connect(m_passphrase_dialog, &QDialog::accepted, [this] { createWallet(); }); connect(m_passphrase_dialog, &QDialog::rejected, [this] { Q_EMIT finished(); }); } void CreateWalletActivity::createWallet() { showProgressDialog(tr("Creating Wallet <b>%1</b>...").arg(m_create_wallet_dialog->walletName().toHtmlEscaped())); std::string name = m_create_wallet_dialog->walletName().toStdString(); uint64_t flags = 0; if (m_create_wallet_dialog->isDisablePrivateKeysChecked()) { flags |= WALLET_FLAG_DISABLE_PRIVATE_KEYS; } if (m_create_wallet_dialog->isMakeBlankWalletChecked()) { flags |= WALLET_FLAG_BLANK_WALLET; } QTimer::singleShot(500, worker(), [this, name, flags] { std::unique_ptr<interfaces::Wallet> wallet; WalletCreationStatus status = node().createWallet(m_passphrase, flags, name, m_error_message, m_warning_message, wallet); if (status == WalletCreationStatus::SUCCESS) m_wallet_model = m_wallet_controller->getOrCreateWallet(std::move(wallet)); QTimer::singleShot(500, this, &CreateWalletActivity::finish); }); } void CreateWalletActivity::finish() { m_progress_dialog->hide(); if (!m_error_message.empty()) { QMessageBox::critical(m_parent_widget, tr("Create wallet failed"), QString::fromStdString(m_error_message)); } else if (!m_warning_message.empty()) { QMessageBox::warning(m_parent_widget, tr("Create wallet warning"), QString::fromStdString(Join(m_warning_message, "\n"))); } if (m_wallet_model) Q_EMIT created(m_wallet_model); Q_EMIT finished(); } void CreateWalletActivity::create() { m_create_wallet_dialog = new CreateWalletDialog(m_parent_widget); m_create_wallet_dialog->setWindowModality(Qt::ApplicationModal); m_create_wallet_dialog->show(); connect(m_create_wallet_dialog, &QObject::destroyed, [this] { m_create_wallet_dialog = nullptr; }); connect(m_create_wallet_dialog, &QDialog::rejected, [this] { Q_EMIT finished(); }); connect(m_create_wallet_dialog, &QDialog::accepted, [this] { if (m_create_wallet_dialog->isEncryptWalletChecked()) { askPassphrase(); } else { createWallet(); } }); } OpenWalletActivity::OpenWalletActivity(WalletController* wallet_controller, QWidget* parent_widget) : WalletControllerActivity(wallet_controller, parent_widget) { } void OpenWalletActivity::finish() { m_progress_dialog->hide(); if (!m_error_message.empty()) { QMessageBox::critical(m_parent_widget, tr("Open wallet failed"), QString::fromStdString(m_error_message)); } else if (!m_warning_message.empty()) { QMessageBox::warning(m_parent_widget, tr("Open wallet warning"), QString::fromStdString(Join(m_warning_message, "\n"))); } if (m_wallet_model) Q_EMIT opened(m_wallet_model); Q_EMIT finished(); } void OpenWalletActivity::open(const std::string& path) { QString name = path.empty() ? QString("["+tr("default wallet")+"]") : QString::fromStdString(path); showProgressDialog(tr("Opening Wallet <b>%1</b>...").arg(name.toHtmlEscaped())); QTimer::singleShot(0, worker(), [this, path] { std::unique_ptr<interfaces::Wallet> wallet = node().loadWallet(path, m_error_message, m_warning_message); if (wallet) m_wallet_model = m_wallet_controller->getOrCreateWallet(std::move(wallet)); QTimer::singleShot(0, this, &OpenWalletActivity::finish); }); }
34.483333
141
0.711455
[ "vector", "model" ]
741d253debaf24775ed2604d3d1b9d777d7ae063
81,198
hpp
C++
src/io/file.hpp
tcpan/bliss
0062fe91fdeef66fce4d1e897c15318241130277
[ "Apache-2.0" ]
16
2016-06-07T22:12:02.000Z
2021-12-15T12:40:52.000Z
src/io/file.hpp
tcpan/bliss
0062fe91fdeef66fce4d1e897c15318241130277
[ "Apache-2.0" ]
1
2017-11-13T20:59:33.000Z
2018-12-14T16:40:01.000Z
src/io/file.hpp
tcpan/bliss
0062fe91fdeef66fce4d1e897c15318241130277
[ "Apache-2.0" ]
7
2016-08-19T21:31:41.000Z
2021-12-19T14:58:45.000Z
/* * Copyright 2015 Georgia Institute of Technology * * 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. */ /* * file.hpp * * @note special notes for Lustre: * from http://www.nas.nasa.gov/hecc/support/kb/lustre-best-practices_226.html * from http://www.opensfs.org/wp-content/uploads/2014/04/D1_S8_Lustre2.5PerformanceEvaluation.pdf. IOPS limited. * 1. avoid repeated stat - e.g. used for getting file size. lustre IOS is limited. possible symptom: some processes may not find the file * 2. avoid multiple processes opening same file at the same time. symptom: some processes may not find the file. aggregating is better * 3. open once, close once, instead of repeated open * 4. stripe align IO requests (default page size is 4K for mmap, so is already aligned, but need to prefetch) * 5. unlocked read. * * based on this https://www.nics.tennessee.edu/computing-resources/file-systems/io-lustre-tips * it appears that strip size of 32MB is best. * * Created on: Feb 28, 2016 * Author: tpan */ #ifndef FILE_HPP_ #define FILE_HPP_ #include "bliss-config.hpp" #include <string> #include <cstring> // memcpy, strerror #include <ios> // ios_base::failure #include <iostream> // ios_base::failure #include <unistd.h> // sysconf, usleep, lseek, #include <sys/mman.h> // mmap #include <fcntl.h> // for open64 and close #include <sstream> // stringstream #include <exception> // std exception #if defined(USE_MPI) #include <mpi.h> #endif // mxx #include <mxx/collective.hpp> #include <mxx/shift.hpp> #include <io/io_exception.hpp> #include <io/file_loader.hpp> #include <io/fastq_loader.hpp> #include <io/fasta_loader.hpp> #include <io/unix_domain_socket.h> #include <partition/range.hpp> #include <utils/exception_handling.hpp> #include <utils/memory_usage.hpp> // define so that pread64 can support reading larger than int bytes. // http://www.ibm.com/support/knowledgecenter/ssw_i5_54/apis/pread64.htm #define _LARGE_FILE_API // DONE: directly expose the mmapped region (possible a variant for mmap without caching.) // DONE: large number of PARALLEL FOPEN AND FREAD is not good. mmap is okay because of common file descriptor between processes? can that be guaranteed? or is it okay because of open? // lseek and read may be better, provide the same file descriptor can be used for processes on the same node. // TODO: read then shuffle boundaries for partitioned file, FASTQ case. // TODO: change file open behavior to reduce congestion. - open when using, retry until success. // DONE: util to clear linux disk cache http://www.linuxatemyram.com/play.html, or O_DIRECT is supposed to bypass cache, // but seems to carry a lot of complications. // mmap_file // mmap range: whole file, access region, or sliding window? // first, mmap will adapt to physical memory available. mmapping more than physical + swap is okay // second. maxrss reporting includes mmapped region, up to physical memory, but actual application memory use is lower. // a. whole large file by each process - The TLB table will contain Page Table Entries for whole mapped range. // b. regions of interest - TLB may still be somewhat large, and is dependent on size of input and num procs. // http://stackoverflow.com/questions/8506366/does-mmap-with-map-noreserve-reserve-physical-memory // https://forums.freebsd.org/threads/48980/ // c. sliding mmapped window may reduce number of Page Table Entries and thus invalidation for other processes. // overhead of map/unmap is potentially expensive. no test to indicate this is beneficial, so don't do it. // CONCLUSION: map access region. // concurrent access to same file: // open64 is used with mmap. fds are assigned sequentially and separately by each process. if they are the same, it's coincidental. // confirmed via mpirun -np 4 on 1 node // multiple calls create multiple open file descriptions for same inode, and each can seek/etc. // sharing file descriptor via unix socket results in same thing as dup(2), // since offset is shared, need to use pread, which does not modify the file descriptor // http://stackoverflow.com/questions/1997622/can-i-open-a-socket-and-pass-it-to-another-process-in-linux // http://blog.varunajayasiri.com/passing-file-descriptors-between-processes-using-sendmsg-and-recvmsg // http://www.thomasstover.com/uds.html // testing with 4096 procs still appears to work correctly for mmap. 2 possibilities : // 1. kernel is aggregating the "open files" - perhaps at inode level? // 2. lustre allows more concurrent file descriptors (from open64) than FILE streams (from fopen)? untested and unlikely. // mapping same region of same file will return different virtual address in process space. if same, coincidental? // however, the physical memory for the mapping is shared if MAP_SHARED is used. // https://www.mkssoftware.com/docs/man3/mmap.3.asp // each proc is going to read different pages. so this does not matter. // CONCLUSION: the number of concurrent open file descriptors is an issue. See TODO below // MAP_SHARED can exceed physical + swap memory. MAP_PRIVATE requires reservation. // on linux, MAP_PRIVATE + MAP_NORESERVE allows swapspace overcommitting. // http://stackoverflow.com/questions/7222164/mmap-an-entire-large-file // MAP_NORESERVE prevents allocating swap (swap is more relevant to write). // http://stackoverflow.com/questions/8506366/does-mmap-with-map-noreserve-reserve-physical-memory // CONCLUSION: use MAP_SHARED | MAP_NORESERVE // largest file size for mmap? length up to size_t, but is probably limited by addressable memory addresses + ulimit. // CONCLUSION: change nothing here. // DONE: minimize the number of open files. // 1 proc per node open file. then // 1. share file descriptor, or // 2. mmap cache/fread on 1 and share (require contiguous, and idle C-1 cores, communication at worst shared mem at best) // 3. don't open file multiple times. // 4. serialize/space out file open over time. // delay, // open only when doing something // 5. map remains even when file is closed. // chose 1. // DONE: other things to change: // 1. DONE. for mmap, reuse file handle/mmap, and mremap as needed (not needed). // 2. DONE. use open/lseek/pread instead of fopen/fseek/fread/ // // DONE: open/lseek/read instead of fopen/fseek/fread // DONE: refactored mmap_file with a mapped_data object // DONE: remove 1 extra mmap from FASTQParser partitioned_file // TODO: move file open/close to closer to actual reading // close right after map, before unmap // DONE: copy file descriptor to processes - only 1 on each node opens. // all closes (same behavior as when using dup) // require sequential constructors to reuse fd. // NOTE: fread will move the fd, so sharing a file descriptor does not work. // NOTE: pread64 can only read 2GB chunks at a time. offset is 64bit though. namespace bliss { namespace io { /** * @brief loaded file data. */ struct file_data { using container = std::vector<unsigned char>; using iterator = typename container::iterator; using const_iterator = typename container::const_iterator; // type of ranges using range_type = ::bliss::partition::range<size_t>; // range from which the data came range_type parent_range_bytes; // range loaded in memory. INCLUDES OVERLAP range_type in_mem_range_bytes; // valid range for this. EXCLUDES OVERLAP range_type valid_range_bytes; // storage for actual data container data; /// beginning of the valid range iterator begin() { return data.begin() + valid_range_bytes.start - in_mem_range_bytes.start; } /// end of valid range iterator end() { return data.begin() + valid_range_bytes.end - in_mem_range_bytes.start; } /// beginning of the valid range const_iterator cbegin() const { return data.cbegin() + valid_range_bytes.start - in_mem_range_bytes.start; } /// end of valid range const_iterator cend() const { return data.cbegin() + valid_range_bytes.end - in_mem_range_bytes.start; } /// start of inmem range iterator in_mem_begin() { return data.begin(); } /// end of in mem range iterator in_mem_end() { return data.end(); } /// start of inmem range const_iterator in_mem_cbegin() const { return data.cbegin(); } /// end of in mem range const_iterator in_mem_cend() const { return data.cend(); } range_type getRange() const { return valid_range_bytes; } }; /** * mmapped data. wrapper for moving it around. */ class mapped_data { protected: /// pointer to mapped address unsigned char * data; /// range type using range_type = ::bliss::partition::range<size_t>; /// mapped range range_type range_bytes; const size_t page_size; public: /** * @brief map the specified portion of the file to memory. * @note AGNOSTIC of overlaps * @param range_bytes range specifying the portion of the file to map. */ mapped_data(int const & _fd, range_type const & target) : data(nullptr), range_bytes(0, 0), page_size(sysconf(_SC_PAGE_SIZE)) { // if no file if (_fd == -1) { throw ::bliss::utils::make_exception<::bliss::io::IOException>("ERROR: map: file is not yet open."); } if (target.size() == 0) { // print error through exception. std::cout << "WARN: map: zero bytes in range" << std::endl; return; } // get start and end positions that are page aligned. range_bytes.start = range_type::align_to_page(target, page_size); range_bytes.end = target.end; // okay for end not to align - made 0. // NOT using MAP_POPULATE. (SLOW) no need to prefault the entire range - use read ahead from madvice. // NOTE HUGETLB not supported for file mapping, only anonymous. also, kernel has to enable it and system has to have it reserved, // MAP_SHARED so that we don't have CoW (no private instance) (potential sharing between processes?) slightly slower by 1%? // MAP_NORESERVE so that swap is not allocated. data = (unsigned char*)mmap64(nullptr, range_bytes.size(), PROT_READ, MAP_SHARED | MAP_NORESERVE, _fd, range_bytes.start); // if mmap failed, if (data == MAP_FAILED) { // print error through exception. std::stringstream ss; int myerr = errno; ss << "ERROR in mmap: " << myerr << ": " << strerror(myerr); throw ::bliss::utils::make_exception<::bliss::io::IOException>(ss.str()); } // set the madvice info. SEQUENTIAL vs RANDOM does not appear to make a difference in running time. int madv_result = madvise(data, range_bytes.size(), MADV_SEQUENTIAL | MADV_WILLNEED); if ( madv_result == -1 ) { std::stringstream ss; int myerr = errno; ss << "ERROR in madvise: " << myerr << ": " << strerror(myerr); throw ::bliss::utils::make_exception<bliss::io::IOException>(ss.str()); } // for testing //std::cout << "serial fd=" << _fd << " mapped region = " << range_bytes << " pointer is " << (const void*)data << ::std::endl; } ~mapped_data() { // unmap it. if ((data != nullptr) && (range_bytes.size() > 0)) { munmap(data, range_bytes.size()); data = nullptr; range_bytes.start = range_bytes.end; } } // copy constructor and assignment operators are deleted. mapped_data(mapped_data const & other) = delete; mapped_data& operator=(mapped_data const & other) = delete; mapped_data(mapped_data && other) : data(other.data), range_bytes(other.range_bytes), page_size(other.page_size) { other.data = nullptr; other.range_bytes.start = other.range_bytes.end; } mapped_data& operator=(mapped_data && other) { // first unmap if ((data != nullptr) && (range_bytes.size() > 0)) munmap(data, range_bytes.size()); // then move other to here. data = other.data; other.data = nullptr; range_bytes = other.range_bytes; other.range_bytes.start = other.range_bytes.end; return *this; } /// accessor for mapped data unsigned char * const & get_data() const { return data; } /// explicit cast operator explicit operator unsigned char *() const { return data; } /// accessor for mapped data range range_type const & get_range() const { return range_bytes; } /// get the size of this mapping. size_t size() const { return range_bytes.size(); } /// accessor for page size. size_t const & get_page_size() const { return page_size; } }; /// base class to wrap a file object with structured data or bytes class base_file { public: /// flag to indicate read /// flag to indicate write using range_type = ::bliss::partition::range<size_t>; protected: /// name of file. std::string filename; /// file descriptor int fd; /// size of file in bytes range_type file_range_bytes; /// virtual function for computing the size of a file. size_t get_file_size() { if (this->filename.length() == 0) return 0UL; // printf("base file get_file_size\n"); // get the file size. struct stat64 filestat; // get the file state int ret = stat64(filename.c_str(), &filestat); // handle any error if (ret < 0) { ::std::stringstream ss; int myerr = errno; ss << "ERROR : bliss::io::base_file::get_file_size: [" << filename << "] " << myerr << ": " << strerror(myerr); throw ::bliss::utils::make_exception<::bliss::io::IOException>(ss.str()); } return static_cast<size_t>(filestat.st_size); } /// opens a file. side effect computes size of the file. void open_file() { //printf("open seq file\n"); if (this->filename.length() == 0) return; // first close file. this->close_file(); // open the file and get a handle. this->fd = open64(this->filename.c_str(), O_RDONLY); if (this->fd == -1) { this->file_range_bytes.end = 0; // if open failed, throw exception. ::std::stringstream ss; int myerr = errno; ss << "ERROR in base_file open: [" << this->filename << "] error " << myerr << ": " << strerror(myerr); throw ::bliss::utils::make_exception<::bliss::io::IOException>(ss.str()); } } /// funciton for closing a file void close_file() { if (this->fd >= 0) { close(this->fd); this->fd = -1; this->file_range_bytes.end = 0; } } /** * @brief initializes a file for reading/writing. for use when the size is already obtained, as in the compositional parallel file case. * @note do not call get_file_size here because * parallel_file inherits this class and defines a parallel get_file_size. * we want to call this constructor from subclass. * * @param _filename name of file to open * @param _file_size size of file, previously obtained. */ base_file(std::string const & _filename, size_t const & _file_size, size_t const & delay_ms = 0) : filename(_filename), fd(-1), file_range_bytes(0, _file_size) { if (delay_ms > 0) usleep(delay_ms * 1000UL); this->open_file(); }; /** * @brief constructor that takes an existing open file descriptor and size. * @param _fd open file descriptor * @param _file_size size of file, previously obtained. */ base_file(int const & _fd, size_t const & _file_size) : filename(::std::string()), fd(dup(_fd)), file_range_bytes(0, _file_size) {}; public: /** * @brief bulk load all the data and return it in a newly constructed vector * @param range_bytes range to read, in bytes * @return vector containing data as bytes. */ virtual typename ::bliss::io::file_data::container read_range(range_type const & range_bytes) { typename ::bliss::io::file_data::container out; this->read_range(out, range_bytes); return out; } /** * @brief bulk load all the data and return it in a newly constructed vector. reuse vector * @note virtual so different file reading mechanisms can be defined * @param range_bytes range to read, in bytes * @param output vector containing data as bytes. */ virtual range_type read_range(typename ::bliss::io::file_data::container & output, range_type const & range_bytes) = 0; /// flag to indicate read /// flag to indicate write /** * @brief initializes a file for reading/writing * @note do not call get_file_size here because * parallel_file inherits this class and defines a parallel get_file_size. * we want to call this constructor from subclass. * * @param _filename name of file to open */ base_file(std::string const & _filename) : filename(_filename), fd(-1), file_range_bytes(0, 0) { this->file_range_bytes.end = this->get_file_size(); this->open_file(); }; /// default destructor virtual ~base_file() { this->close_file(); }; /** * @brief read the whole file * @return file_data object containing data and various ranges. */ ::bliss::io::file_data read_file() { file_data out; read_file(out); return out; } /** * @brief read the whole file. reuse allocated file_data object. * @note virtual so that parallel readers can compute range to read. * @param output file_data object containing data and various ranges. */ virtual void read_file(::bliss::io::file_data & output) { output.in_mem_range_bytes = output.valid_range_bytes = this->read_range(output.data, file_range_bytes); output.parent_range_bytes = file_range_bytes; } /// get file size size_t size() { return file_range_bytes.end; }; /// get file name ::std::string const & get_filename() const { return filename; }; }; /** * @brief subclass for memmapped file */ class mmap_file : public ::bliss::io::base_file { // share open and close with file class. protected: /// BASE type using BASE = ::bliss::io::base_file; public: // this is needed to prevent overload name hiding. see http://stackoverflow.com/questions/888235/overriding-a-bases-overloaded-function-in-c/888337#888337 using BASE::read_range; /** * bulk load all the data and return it in pre-allocated vector * @param output vector where the results are to be stored. */ virtual typename BASE::range_type read_range(typename ::bliss::io::file_data::container & output, typename BASE::range_type const & range_bytes) { typename BASE::range_type file_range = BASE::range_type::intersect(range_bytes, this->file_range_bytes); output.clear(); if (file_range.size() == 0) { return file_range; } // map mapped_data md(this->fd, file_range); // unsigned char * md_data = md.get_data(); typename BASE::range_type mapped_range = md.get_range(); if (md.size() == 0) { std::cout << "WARNING: mapped data size is 0" << std::endl; return mapped_range; } if (md_data == nullptr) { throw std::logic_error("ERROR: mapped data is null, but mapped range size is larger than 0"); } // ensure the portion to copy is within the mapped region. typename BASE::range_type target = BASE::range_type::intersect(mapped_range, range_bytes); if (target.size() == 0) { // print error through exception. std::cout << "WARNING: read_range: requested " << range_bytes << " not in mapped " << mapped_range << std::endl; return target; } // resize output's capacity if (output.capacity() < target.size()) output.resize(target.size()); // copy the data into memory. vector is contiguous, so this is okay. memmove(output.data(), md_data + (target.start - mapped_range.start), target.size()); return target; // unmap when go out of scope. } inline mapped_data map(typename BASE::range_type const & range_bytes) { return mapped_data(this->fd, BASE::range_type::intersect(range_bytes, this->file_range_bytes)); } /** * initializes a file for reading/writing via memmap * @param _filename name of file to open */ mmap_file(std::string const & _filename) : ::bliss::io::base_file(_filename) { // // for testing: multiple processes on the same node maps to the same ptr address // map(this->file_range_bytes); // std::cout << " serial fd = " << this->fd << " mapped region = " << mapped_range_bytes << " pointer is " << (const void*)mapped_data << std::endl; // unmap(); }; /** * initializes a file for reading/writing via memmap. for use by parallel file (composition) * @param _filename name of file to open * @param _file_size previously determined file size. */ mmap_file(std::string const & _filename, size_t const & _file_size, size_t const & delay_ms = 0) : ::bliss::io::base_file(_filename, _file_size, delay_ms) {} /** * initializes a file for reading/writing via memmap. for use by parallel file (composition) * @param _filename name of file to open * @param _file_size previously determined file size. */ mmap_file(int const & _fd, size_t const & _file_size) : ::bliss::io::base_file(_fd, _file_size) {} /// default destructor virtual ~mmap_file() { }; // this is needed to prevent overload name hiding. see http://stackoverflow.com/questions/888235/overriding-a-bases-overloaded-function-in-c/888337#888337 using BASE::read_file; }; /** * @brief file wrapper that uses c stdio calls. has buffering. */ class stdio_file : public ::bliss::io::base_file { protected: using BASE = ::bliss::io::base_file; // file handle; FILE *fp; /// virtual function for opening a file. side effect computes size of the file. void open_file_stream() { // printf("open seq file stream\n"); fp = fdopen(dup(this->fd), "r"); // make a copy of file descriptor first. this allows closing file pointer. if (fp == nullptr) { this->file_range_bytes.end = 0; // if open failed, throw exception. ::std::stringstream ss; int myerr = errno; ss << "ERROR in stdio_file open: this->fd " << this->fd << " error " << myerr << ": " << strerror(myerr); throw ::bliss::utils::make_exception<::bliss::io::IOException>(ss.str()); } } /// virtual funciton for closing a file void close_file_stream() { if (fp != nullptr) { fclose(fp); // okay to close since fd is dup'ed fp = nullptr; // this->fd = -1; // this->file_range_bytes.end = 0; } } public: // this is needed to prevent overload name hiding. see http://stackoverflow.com/questions/888235/overriding-a-bases-overloaded-function-in-c/888337#888337 using BASE::read_range; using BASE::size; /** * @brief bulk load all the data and return it in a newly constructed vector. reuse vector * @note virtual so different file reading mechanisms can be defined AND parallel * @param range_bytes range to read, in bytes * @param output vector containing data as bytes. */ virtual range_type read_range(typename ::bliss::io::file_data::container & output, range_type const & range_bytes) { this->open_file_stream(); // ensure the portion to copy is within the mapped region. typename BASE::range_type target = BASE::range_type::intersect(this->file_range_bytes, range_bytes); if (target.size() == 0) { // print error through exception. std::cout << "WARNING: read_range: requested " << range_bytes << " not in file " << file_range_bytes << std::endl; output.clear(); return target; } // use fseek instead lseek to preserve buffering. int res = fseeko64(fp, target.start, SEEK_SET); if ( res == -1 ) { std::stringstream ss; int myerr = errno; ss << "ERROR: fseeko64: file " << this->filename << " error " << myerr << ": " << strerror(myerr); throw ::bliss::utils::make_exception<bliss::io::IOException>(ss.str()); } // std::cout << "curr pos in fd is " << ftell(this->fp) << std::endl; // resize output's capacity if (output.capacity() < target.size()) output.resize(target.size()); size_t read = fread_unlocked(output.data(), 1, target.size(), fp); if ((read == 0) && (target.size() > 0)) { std::stringstream ss; int myerr = errno; ss << "ERROR: fread: file " << this->filename << " error " << myerr << ": " << strerror(myerr); throw ::bliss::utils::make_exception<bliss::io::IOException>(ss.str()); } // std::cout << "curr pos in fd after read is " << ftell(this->fp) << std::endl; this->close_file_stream(); // std::cout << "read " << target << std::endl; return target; } /** * initializes a file for reading/writing * @param _filename name of file to open */ stdio_file(std::string const & _filename) : ::bliss::io::base_file(_filename), fp(nullptr) {}; /** * initializes a file for reading/writing. for use by a parallel file (composition pattern) * @param _filename name of file to open * @param _file_size previously computed file size. */ stdio_file(std::string const & _filename, size_t const & _file_size, size_t const & delay_ms) : ::bliss::io::base_file(_filename, _file_size, delay_ms), fp(nullptr) {}; /** * initializes a file for reading/writing. for use by a parallel file (composition pattern) * @param _fd previously opened file descriptor. * @param _file_size previously computed file size. */ stdio_file(int const & _fd, size_t const & _file_size) : ::bliss::io::base_file(_fd, _file_size), fp(nullptr) { }; /// destructor virtual ~stdio_file() { this->close_file_stream(); }; // this is needed to prevent overload name hiding. see http://stackoverflow.com/questions/888235/overriding-a-bases-overloaded-function-in-c/888337#888337 using BASE::read_file; }; /** * @brief file wrapper that uses c stdio calls. has buffering. */ class posix_file : public ::bliss::io::base_file { protected: using BASE = ::bliss::io::base_file; public: // this is needed to prevent overload name hiding. see http://stackoverflow.com/questions/888235/overriding-a-bases-overloaded-function-in-c/888337#888337 using BASE::read_range; /** * @brief bulk load all the data and return it in a newly constructed vector. reuse vector * @note virtual so different file reading mechanisms can be defined AND parallel * @param range_bytes range to read, in bytes * @param output vector containing data as bytes. * @return the range for the read data. */ virtual range_type read_range(typename ::bliss::io::file_data::container & output, range_type const & range_bytes) { if (this->fd == -1) { throw ::bliss::utils::make_exception<std::logic_error>("ERROR: read_range: file pointer is null"); } // ensure the portion to copy is within the mapped region. typename BASE::range_type target = BASE::range_type::intersect(this->file_range_bytes, range_bytes); if (target.size() == 0) { // print error through exception. std::cout << "WARNING: read_range: requested " << range_bytes << " not in file " << this->file_range_bytes << std::endl; output.clear(); return target; } // // use fseek instead lseek to preserve buffering. // int res = lseek64(this->fd, target.start, SEEK_SET); // if ( res == -1 ) { // std::stringstream ss; // int myerr = errno; // ss << "ERROR: lseek64: file " << this->filename << " error " << myerr << ": " << strerror(myerr); // // throw ::bliss::utils::make_exception<bliss::io::IOException>(ss.str()); // } //std::cout << "curr pos in fd is " << lseek64(this->fd, 0, SEEK_CUR) << ::std::endl; // resize output's capacity if (output.capacity() < target.size()) output.resize(target.size()); size_t s = 0; long count; //pread64 can only read 2GB at a time for (; s < target.size(); ) { count = pread64(this->fd, output.data() + s, std::min(1UL << 30, target.size() - s ), static_cast<__off64_t>(target.start + s)); if (count < 0) { std::stringstream ss; int myerr = errno; ss << "ERROR: pread64: file " << this->filename << " error " << myerr << ": " << strerror(myerr); throw ::bliss::utils::make_exception<bliss::io::IOException>(ss.str()); } s += count; } if (s != target.size()) { std::stringstream ss; ss << "ERROR: pread64: file " << this->filename << " read " << s << " less than range: " << target.size(); throw ::bliss::utils::make_exception<bliss::io::IOException>(ss.str()); } return target; } /** * initializes a file for reading/writing * @param _filename name of file to open */ posix_file(std::string const & _filename) : ::bliss::io::base_file(_filename) {}; /** * initializes a file for reading/writing. for use by a parallel file (composition pattern) * @param _filename name of file to open * @param _file_size previously computed file size. */ posix_file(std::string const & _filename, size_t const & _file_size, size_t const & delay_ms) : ::bliss::io::base_file(_filename, _file_size, delay_ms) {}; /** * initializes a file for reading/writing. for use by a parallel file (composition pattern) * @param _fd previously opened file descriptor * @param _file_size previously computed file size. */ posix_file(int const & _fd, size_t const & _file_size) : ::bliss::io::base_file(_fd, _file_size) {}; /// destructor virtual ~posix_file() {}; // this is needed to prevent overload name hiding. see http://stackoverflow.com/questions/888235/overriding-a-bases-overloaded-function-in-c/888337#888337 using BASE::read_file; }; #ifdef USE_MPI namespace parallel { class base_file : public ::bliss::io::base_file { protected: using BASE = ::bliss::io::base_file; using range_type = typename BASE::range_type; /// communicator used. object instead of being a reference - lifetime of a src comm temp object in constructor is just that of the constructor call. const ::mxx::comm comm; /// compute file size in parallel (1 proc, then broadcast. size_t get_file_size() { size_t file_size = 0; // rank 0 gets the size. if (comm.rank() == 0) { // printf("parallel base file get_file_size\n"); file_size = BASE::get_file_size(); } // then broadcast. if (comm.size() > 1) MPI_Bcast(&file_size, 1, MPI_UNSIGNED_LONG, 0, comm); return file_size; } base_file(::mxx::comm const & _comm = ::mxx::comm()) : ::bliss::io::base_file(static_cast<int>(-1), static_cast<size_t>(0)), // will find real size very soon comm(_comm.copy()) { // _comm could be a temporary constructed from MPI_Comm. }; public: // this is needed to prevent overload name hiding. see http://stackoverflow.com/questions/888235/overriding-a-bases-overloaded-function-in-c/888337#888337 using BASE::read_range; /** * @brief constructor * @note _comm could be a temporary constructed from MPI_Comm. in which case, the lifetime is the call of the constructor. * to save it, we cannot just save the reference - the underlying object would go out of scope and die. * we have to copy it. ::mxx::comm does not have copy constructor, but has explict copy function and move constructor. so use them. * note that copy function is collective. move constructor is not collective, so it could cause deadlock. * @param _filename name of file to open * @param _comm MPI communicator to use. */ base_file(std::string const & _filename, ::mxx::comm const & _comm = ::mxx::comm()) : ::bliss::io::base_file(static_cast<int>(-1), static_cast<size_t>(0)), // will find real size very soon comm(_comm.copy()) { // _comm could be a temporary constructed from MPI_Comm. std::move not needed. copy elision is in effect. this->filename = _filename; this->file_range_bytes.end = this->get_file_size(); this->BASE::open_file(); }; /// destructor virtual ~base_file() {}; // will call super's unmap. // this is needed to prevent overload name hiding. see http://stackoverflow.com/questions/888235/overriding-a-bases-overloaded-function-in-c/888337#888337 using BASE::read_file; }; class base_shared_fd_file : public ::bliss::io::parallel::base_file { protected: using BASE = ::bliss::io::parallel::base_file; using range_type = typename BASE::range_type; /// opens a file. side effect computes size of the file. void open_file() { // first split the communicator // if (this->comm.rank() == 0) printf("open parallel file, grouped by node\n"); ::mxx::comm shared = this->comm.split_shared(); if (shared.rank() == 0) { this->::bliss::io::base_file::open_file(); // fd is populated on shared comm rank 0. } int id = ::mxx::allreduce(this->comm.rank(), [](int const & x, int const & y){ return ::std::min(x, y); }, shared); shared.barrier(); if (shared.size() > 1) { // if we have more than 1, then we broadcast the file id via interprocess communicator, so that // all mpi processes on the same node share the same file handle. ::bliss::io::util::broadcast_file_descriptor(this->fd, id, shared.size(), shared.rank()); if (this->comm.rank() == id) printf("broadcasting file descriptor %d from rank G%d N%d to rest.\n", this->fd, id, shared.rank()); } // that's it. //std::cout << "after copying, curr pos in fd is " << lseek64(this->fd, 0, SEEK_CUR) << std::endl; shared.barrier(); } public: // this is needed to prevent overload name hiding. see http://stackoverflow.com/questions/888235/overriding-a-bases-overloaded-function-in-c/888337#888337 using BASE::read_range; /** * @brief constructor * @note _comm could be a temporary constructed from MPI_Comm. in which case, the lifetime is the call of the constructor. * to save it, we cannot just save the reference - the underlying object would go out of scope and die. * we have to copy it. ::mxx::comm does not have copy constructor, but has explict copy function and move constructor. so use them. * note that copy function is collective. move constructor is not collective, so it could cause deadlock. * @param _filename name of file to open * @param _comm MPI communicator to use. */ base_shared_fd_file(std::string const & _filename, ::mxx::comm const & _comm = ::mxx::comm()) : ::bliss::io::parallel::base_file(_comm) { // _comm could be a temporary constructed from MPI_Comm. this->filename = _filename; this->file_range_bytes.end = this->BASE::get_file_size(); this->open_file(); }; /// destructor virtual ~base_shared_fd_file() { this->close_file(); }; // will call super's close. // this is needed to prevent overload name hiding. see http://stackoverflow.com/questions/888235/overriding-a-bases-overloaded-function-in-c/888337#888337 using BASE::read_file; }; template <typename FileReader, template <typename> class FileParser = ::bliss::io::BaseFileParser, typename BaseType = ::bliss::io::parallel::base_file > class partitioned_file : public BaseType { protected: using BASE = BaseType; using range_type = typename ::bliss::io::base_file::range_type; using FileParserType = FileParser<typename ::bliss::io::file_data::const_iterator >; /// FileReader FileReader reader; /// overlap amount const size_t overlap; /// partitioner to use. ::bliss::partition::BlockPartitioner<typename BASE::range_type> partitioner; /** * @brief partitions the specified range by the number of processes in communicator * @note does not add overlap. this is strictly for block partitioning a range. * if overlap is needed, use the overload version. * @note assumes input parameter is in memory and inside file. */ typename BASE::range_type partition(typename BASE::range_type const & range_bytes) { typename BASE::range_type target = BASE::range_type::intersect(range_bytes, this->file_range_bytes); if (this->comm.size() == 1) { return target; } partitioner.configure(target, this->comm.size()); return partitioner.getNext(this->comm.rank()); // typename BASE::range_type result = partitioner.getNext(this->comm.rank()); // // std::cout << "rank = " << this->comm.rank() << " range " << result << std::endl; // return result; } /** * @brief partition the in mem valid range by the number of processes in communicator * @note overlap is added to the end of the result ranges. This may make the result extend * beyong initial in_mem_range. * @note assumes that both input parameters are within file range and in memory. * @return pair of ranges, first range is the in memory, partitioned, second range is the valid range. * */ ::std::pair<typename BASE::range_type, typename BASE::range_type> overlapped_partition(typename BASE::range_type const & in_mem_range_bytes, typename BASE::range_type const & valid_range_bytes) { // ::std::cout << "rank " << this->comm.rank() << " partition comm_size " << this->comm.size() << ::std::endl; // std::cout << " partition comm object at " << &(this->comm) << " for this " << this << std::endl; // std::cout << " partition comm is set to world ? " << (MPI_COMM_WORLD == this->comm ? "y" : "n") << std::endl; typename BASE::range_type in_mem = BASE::range_type::intersect(in_mem_range_bytes, this->file_range_bytes); // and restrict valid to in memory data. typename BASE::range_type valid = BASE::range_type::intersect(valid_range_bytes, in_mem); // single process, just return if (this->comm.size() == 1) { return ::std::make_pair(in_mem, valid); } // === multi process. // partition valid range partitioner.configure(valid, this->comm.size()); valid = partitioner.getNext(this->comm.rank()); // compute the in mem range. extend by overlap typename BASE::range_type in_mem_valid = valid; in_mem_valid.end += overlap; in_mem_valid.intersect(in_mem); return ::std::make_pair(in_mem_valid, valid); } public: // this is needed to prevent overload name hiding. see http://stackoverflow.com/questions/888235/overriding-a-bases-overloaded-function-in-c/888337#888337 using BASE::read_range; /** * @brief bulk load the data and return it in a newly constructed vector. block decomposes the range. reuse vector. no overlap * @note virtual so other overloads of this function can also block decompose the range. * @param range_bytes range to read, in bytes * @param output vector containing data as bytes. */ virtual typename BASE::range_type read_range(typename ::bliss::io::file_data::container & output, typename BASE::range_type const & range_bytes) { // first get rough partition typename BASE::range_type target = partition(range_bytes); // then read the range via sequential version reader.read_range(output, target); return target; } /** * @brief constructor * @param _filename name of file to open * @param _comm MPI communicator to use. */ partitioned_file(std::string const & _filename, size_t const & _overlap = 0UL, ::mxx::comm const & _comm = ::mxx::comm()) : BaseType(_filename, _comm), reader(this->fd, this->file_range_bytes.end), overlap(_overlap) {}; /// destructor virtual ~partitioned_file() {}; // will call super's unmap. // this is needed to prevent overload name hiding. see http://stackoverflow.com/questions/888235/overriding-a-bases-overloaded-function-in-c/888337#888337 using BASE::read_file; /** * @brief read the whole file. reuse allocated file_data object. * @note virtual so that parallel readers can compute range to read. * @param output file_data object containing data and various ranges. */ virtual void read_file(::bliss::io::file_data & output) { typename BASE::range_type in_mem_partitioned; typename BASE::range_type valid_partitioned; ::std::tie(in_mem_partitioned, valid_partitioned) = overlapped_partition(this->file_range_bytes, this->file_range_bytes); // std::cout << " rank " << this->comm.rank() << " PRIMARY : in mem " << output.in_mem_range_bytes << " valid " << output.valid_range_bytes << std::endl; // then read the range via sequential version output.in_mem_range_bytes = reader.read_range(output.data, in_mem_partitioned); output.valid_range_bytes = valid_partitioned; output.parent_range_bytes = this->file_range_bytes; } // std::string get_class_name() { // return std::string("partitioned_file<...>"); // } // }; template <typename FileReader, typename BaseType> class partitioned_file<FileReader, ::bliss::io::FASTQParser, BaseType > : public BaseType { protected: using BASE = BaseType; using FileParserType = ::bliss::io::FASTQParser<typename ::bliss::io::file_data::const_iterator >; using range_type = typename ::bliss::io::base_file::range_type; /// FileReader FileReader reader; /// overlap amount const size_t overlap; /// partitioner to use. ::bliss::partition::BlockPartitioner<typename BASE::range_type> partitioner; /** * @brief partitions the specified range by the number of processes in communicator * @note does not add overlap. this is strictly for block partitioning a range. * if overlap is needed, use the overload version. * @note assumes input parameter is in memory and inside file. */ typename BASE::range_type partition(typename BASE::range_type const & range_bytes) { typename BASE::range_type target = BASE::range_type::intersect(range_bytes, this->file_range_bytes); if (this->comm.size() == 1) { return target; } partitioner.configure(target, this->comm.size()); return partitioner.getNext(this->comm.rank()); // typename BASE::range_type result = partitioner.getNext(this->comm.rank()); // // std::cout << "rank = " << this->comm.rank() << " range " << result << std::endl; // return result; } /** * @brief partition the in mem valid range by the number of processes in communicator * @note overlap is added to the end of the result ranges. This may make the result extend * beyong initial in_mem_range. * @note assumes that both input parameters are within file range and in memory. * @return pair of ranges, first range is the in memory, partitioned, second range is the valid range. */ ::std::pair<typename BASE::range_type, typename BASE::range_type> overlapped_partition(typename BASE::range_type const & in_mem_range_bytes, typename BASE::range_type const & valid_range_bytes) { // ::std::cout << "rank " << this->comm.rank() << " partition comm_size " << this->comm.size() << ::std::endl; // std::cout << " partition comm object at " << &(this->comm) << " for this " << this << std::endl; // std::cout << " partition comm is set to world ? " << (MPI_COMM_WORLD == this->comm ? "y" : "n") << std::endl; typename BASE::range_type in_mem = BASE::range_type::intersect(in_mem_range_bytes, this->file_range_bytes); // and restrict valid to in memory data. typename BASE::range_type valid = BASE::range_type::intersect(valid_range_bytes, in_mem); // single process, just return if (this->comm.size() == 1) { return ::std::make_pair(in_mem, valid); } // === multi process. // partition valid range partitioner.configure(valid, this->comm.size()); valid = partitioner.getNext(this->comm.rank()); // compute the in mem range. extend by overlap typename BASE::range_type in_mem_valid = valid; in_mem_valid.end += overlap; in_mem_valid.intersect(in_mem); return ::std::make_pair(in_mem_valid, valid); } public: // this is needed to prevent overload name hiding. see http://stackoverflow.com/questions/888235/overriding-a-bases-overloaded-function-in-c/888337#888337 using BASE::read_range; /** * @brief bulk load the data and return it in a newly constructed vector. block decomposes the range. reuse vector. no overlap * @note virtual so other overloads of this function can also block decompose the range. * @param range_bytes range to read, in bytes * @param output vector containing data as bytes. */ virtual typename BASE::range_type read_range(typename ::bliss::io::file_data::container & output, typename BASE::range_type const & range_bytes) { // first get rough partition typename BASE::range_type target = partition(range_bytes); // then read the range via sequential version reader.read_range(output, target); return target; } /** * @brief constructor * @param _filename name of file to open * @param _comm MPI communicator to use. */ partitioned_file(std::string const & _filename, size_t const & _overlap = 0UL, ::mxx::comm const & _comm = ::mxx::comm()) : BaseType(_filename, _comm), reader(this->fd, this->file_range_bytes.end), overlap(0UL) {}; /// destructor virtual ~partitioned_file() {}; // will call super's unmap. // this is needed to prevent overload name hiding. see http://stackoverflow.com/questions/888235/overriding-a-bases-overloaded-function-in-c/888337#888337 using BASE::read_file; /** * @brief read the whole file. reuse allocated file_data object. * @note virtual so that parallel readers can compute range to read. * same as mpiio file's read_file * @param output file_data object containing data and various ranges. */ virtual void read_file(::bliss::io::file_data & output) { // std::cout << " rank " << this->comm.rank() << " FASTQ: in mem " << output.in_mem_range_bytes << " valid " << output.valid_range_bytes << std::endl; // overlap is set to page size, so output will have sufficient space. // note that this is same behavior as the serial mmap_file // then read the range via sequential version range_type partition_range = read_range(output.data, this->file_range_bytes); // std::cout << "rank " << this->comm.rank() << " read " << partition_range << std::endl; // std::ostream_iterator<unsigned char> oit(std::cout, ""); // std::copy(output.data.begin(), output.data.begin() + 100, oit); // std::cout << std::endl; range_type in_mem = partition_range; in_mem.end = in_mem.start + output.data.size(); // std::cout << "rank " << this->comm.rank() << " in mem " << in_mem << std::endl; // std::cout << "rank " << this->comm.rank() << " overlap " << this->overlap << std::endl; // now search for the true start. FileParserType parser; // mark the first entry found. size_t real_start = parser.init_parser(output.in_mem_cbegin(), this->file_range_bytes, in_mem, partition_range, this->comm); // std::cout << "rank " << this->comm.rank() << " real start " << real_start << std::endl; // std::cout << "rank " << this->comm.rank() << " data size before remove overlap " << output.data.size() << std::endl; // now clear the region outside of the block range (the overlap portion) if (output.data.size() > partition_range.size()) { output.data.erase(output.data.begin() + partition_range.size(), output.data.end()); } // std::cout << "rank " << this->comm.rank() << " data size after remove overlap " << output.data.size() << std::endl; // ==== shift values to the left (as vector?) // actually, not shift. need to do all to all - if a rank found no internal starts // first compute the target proc id via exscan bool not_found = (real_start >= partition_range.end); // if real start is outside of partition, not found real_start = std::min(real_start, partition_range.end); int target_rank = not_found ? 0 : this->comm.rank(); target_rank = ::mxx::exscan(target_rank, [](int const & x, int const & y) { return (x < y) ? y : x; }, this->comm); // std::cout << "rank " << this->comm.rank() << " adjusted real start " << real_start << std::endl; // std::cout << "rank " << this->comm.rank() << " target rank " << target_rank << std::endl; // MPI 2 does not have neighbor_ collective operations, so we can't create // graph with sparse edges. in any case, the amount of data we send should be // small so alltoallv should be enough std::vector<size_t> send_counts(this->comm.size(), 0); if (this->comm.rank() > 0) send_counts[target_rank] = real_start - in_mem.start; // copy the region to shift typename ::bliss::io::file_data::container shifted = ::mxx::all2allv(output.data, send_counts, this->comm); output.data.insert(output.data.end(), shifted.begin(), shifted.end()); // std::cout << "rank " << this->comm.rank() << " shifted " << shifted.size() << std::endl; // std::cout << "rank " << this->comm.rank() << " new data size " << output.data.size() << std::endl; // adjust the ranges. output.in_mem_range_bytes = partition_range; output.in_mem_range_bytes.end = partition_range.start + output.data.size(); // std::cout << "rank " << this->comm.rank() << " final in mem " << output.in_mem_range_bytes << std::endl; output.valid_range_bytes.start = real_start; output.valid_range_bytes.end = not_found ? partition_range.end : output.in_mem_range_bytes.end; // std::cout << "rank " << this->comm.rank() << "/" << this->comm.size() << " final valid " << output.valid_range_bytes << std::endl; output.parent_range_bytes = this->file_range_bytes; // std::cout << "rank " << this->comm.rank() << " file " << output.parent_range_bytes << std::endl; } // std::string get_class_name() { // return std::string("partitioned_file<FASTQ>"); // } }; template <typename FileReader, typename BaseType> class partitioned_file<FileReader, ::bliss::io::FASTAParser, BaseType > : public BaseType { protected: using BASE = BaseType; using FileParserType = ::bliss::io::FASTAParser<typename ::bliss::io::file_data::const_iterator>; using range_type = typename ::bliss::io::base_file::range_type; /// FileReader FileReader reader; /// overlap amount const size_t overlap; /// partitioner to use. ::bliss::partition::BlockPartitioner<typename BASE::range_type> partitioner; /** * @brief partitions the specified range by the number of processes in communicator * @note does not add overlap. this is strictly for block partitioning a range. * if overlap is needed, use the overload version. * @note assumes input parameter is in memory and inside file. */ typename BASE::range_type partition(typename BASE::range_type const & range_bytes) { typename BASE::range_type target = BASE::range_type::intersect(range_bytes, this->file_range_bytes); if (this->comm.size() == 1) { return target; } partitioner.configure(target, this->comm.size()); return partitioner.getNext(this->comm.rank()); // typename BASE::range_type result = partitioner.getNext(this->comm.rank()); // // std::cout << "rank = " << this->comm.rank() << " range " << result << std::endl; // return result; } /** * @brief partition the in mem valid range by the number of processes in communicator * @note overlap is added to the end of the result ranges. This may make the result extend * beyong initial in_mem_range. * @note assumes that both input parameters are within file range and in memory. * @return pair of ranges, first range is the in memory, partitioned, second range is the valid range. */ ::std::pair<typename BASE::range_type, typename BASE::range_type> overlapped_partition(typename BASE::range_type const & in_mem_range_bytes, typename BASE::range_type const & valid_range_bytes) { // ::std::cout << "rank " << this->comm.rank() << " partition comm_size " << this->comm.size() << ::std::endl; // std::cout << " partition comm object at " << &(this->comm) << " for this " << this << std::endl; // std::cout << " partition comm is set to world ? " << (MPI_COMM_WORLD == this->comm ? "y" : "n") << std::endl; typename BASE::range_type in_mem = BASE::range_type::intersect(in_mem_range_bytes, this->file_range_bytes); // and restrict valid to in memory data. typename BASE::range_type valid = BASE::range_type::intersect(valid_range_bytes, in_mem); // single process, just return if (this->comm.size() == 1) { return ::std::make_pair(in_mem, valid); } // === multi process. // partition valid range partitioner.configure(valid, this->comm.size()); valid = partitioner.getNext(this->comm.rank()); // compute the in mem range. extend by overlap typename BASE::range_type in_mem_valid = valid; in_mem_valid.end += 2 * overlap; in_mem_valid.intersect(in_mem); return ::std::make_pair(in_mem_valid, valid); } public: // this is needed to prevent overload name hiding. see http://stackoverflow.com/questions/888235/overriding-a-bases-overloaded-function-in-c/888337#888337 using BASE::read_range; /** * @brief bulk load the data and return it in a newly constructed vector. block decomposes the range. reuse vector. no overlap * @note virtual so other overloads of this function can also block decompose the range. * @param range_bytes range to read, in bytes * @param output vector containing data as bytes. */ virtual typename BASE::range_type read_range(typename ::bliss::io::file_data::container & output, typename BASE::range_type const & range_bytes) { // first get rough partition typename BASE::range_type target = partition(range_bytes); // then read the range via sequential version reader.read_range(output, target); return target; } /** * @brief constructor * @param _filename name of file to open * @param _comm MPI communicator to use. */ partitioned_file(std::string const & _filename, size_t const & _overlap = 0UL, ::mxx::comm const & _comm = ::mxx::comm()) : BaseType(_filename, _comm), reader(this->fd, this->file_range_bytes.end), overlap(_overlap) {}; /// destructor virtual ~partitioned_file() {}; // will call super's unmap. // this is needed to prevent overload name hiding. see http://stackoverflow.com/questions/888235/overriding-a-bases-overloaded-function-in-c/888337#888337 using BASE::read_file; /** * @brief read the whole file. reuse allocated file_data object. * @note virtual so that parallel readers can compute range to read. * same as mpiio file's read_file * @param output file_data object containing data and various ranges. */ virtual void read_file(::bliss::io::file_data & output) { // overlap is set to page size, so output will have sufficient space. // note that this is same behavior as the serial mmap_file // then read the range via sequential version ::std::tie(output.in_mem_range_bytes, output.valid_range_bytes) = overlapped_partition(this->file_range_bytes, this->file_range_bytes); // std::cout << " rank " << this->comm.rank() << " FASTA: in mem " << output.in_mem_range_bytes << " valid " << output.valid_range_bytes << std::endl; // then read the range via sequential version output.in_mem_range_bytes = reader.read_range(output.data, output.in_mem_range_bytes); output.parent_range_bytes = this->file_range_bytes; // std::cout << "rank " << this->comm.rank() << " read " << partition_range << std::endl; // std::ostream_iterator<unsigned char> oit(std::cout, ""); // std::copy(output.data.begin(), output.data.begin() + 100, oit); // std::cout << std::endl; // std::cout << "rank " << this->comm.rank() << " in mem " << in_mem << std::endl; // std::cout << "rank " << this->comm.rank() << " overlap " << this->overlap << std::endl; // now search for the true start. FileParserType parser; // mark the first entry found. size_t overlap_end = parser.find_overlap_end(output.in_mem_cbegin(), output.parent_range_bytes, output.in_mem_range_bytes, output.valid_range_bytes.end, overlap); // erase the extra. output.in_mem_range_bytes.end = overlap_end; output.data.erase(output.data.begin() + output.in_mem_range_bytes.size(), output.data.end()); // std::cout << "rank " << this->comm.rank() << "/" << this->comm.size() << " final valid " << output.valid_range_bytes << std::endl; // std::cout << "rank " << this->comm.rank() << " file " << output.parent_range_bytes << std::endl; } // std::string get_class_name() { // return std::string("partitioned_file<FASTA>"); // } }; /// disable shared fd for stdio file. template <template <typename> class FileParser> class partitioned_file<::bliss::io::stdio_file, FileParser, ::bliss::io::parallel::base_shared_fd_file > { private: partitioned_file(std::string const & _filename, size_t const & _overlap = 0UL, ::mxx::comm const & _comm = ::mxx::comm()) { // static_assert(false, "ERROR: stdio_file is not compatible with base_shared_fd_file, as there is no fread that will maintain the old position"); } partitioned_file() { // static_assert(false, "ERROR: stdio_file is not compatible with base_shared_fd_file, as there is no fread that will maintain the old position"); }; ~partitioned_file() {}; // std::string get_class_name() { // return std::string("partitioned_file<stdio_file>"); // } }; // multilevel parallel file io relies on MPIIO. template <template <typename> class FileParser = ::bliss::io::BaseFileParser > class mpiio_base_file : public ::bliss::io::base_file { static_assert(sizeof(MPI_Offset) > 4, "ERROR: MPI_Offset is defined as an integer 4 bytes or less. Do not use mpiio_file "); protected: using BASE = ::bliss::io::base_file; /// overlap amount const size_t overlap; /// communicator used. object instead of being a reference - lifetime of a src comm temp object in constructor is just that of the constructor call. const ::mxx::comm comm; /// MPI file handle MPI_File fh; /// partitioner to use. ::bliss::partition::BlockPartitioner<range_type> partitioner; std::string get_error_string(std::string const & op_name, int const & return_val) { char error_string[BUFSIZ]; int length_of_error_string, error_class; std::stringstream ss; MPI_Error_class(return_val, &error_class); MPI_Error_string(error_class, error_string, &length_of_error_string); ss << "ERROR in mpiio: rank " << comm.rank() << " " << op_name << " " << this->filename << " error: " << error_string << std::endl; return ss.str(); } std::string get_error_string(std::string const & op_name, int const & return_val, MPI_Status const & stat) { char error_string[BUFSIZ]; int length_of_error_string, error_class; std::stringstream ss; MPI_Error_class(return_val, &error_class); MPI_Error_string(error_class, error_string, &length_of_error_string); ss << "ERROR in mpiio: rank " << comm.rank() << " " << op_name << " " << this->filename << " error: " << return_val << " [" << error_string << "]"; // // status.MPI_ERROR does not appear to be decodable by error_class. google search did not find how to decode it. // MPI_Error_class(stat.MPI_ERROR, &error_class); // MPI_Error_string(error_class, error_string, &length_of_error_string); ss << " MPI_Status error: [" << stat.MPI_ERROR << "]" << std::endl; return ss.str(); } /// MPI_IO get file size size_t get_file_size() { // if (comm.rank() == 0) printf("mpiio base file get_file_size\n"); if (fh == MPI_FILE_NULL) { std::stringstream ss; ss << "ERROR in mpiio: rank " << comm.rank() << " file " << this->filename << " not yet open " << std::endl; throw ::bliss::utils::make_exception<::bliss::io::IOException>(ss.str()); } MPI_Offset s; int res = MPI_File_get_size(fh, &s); if (res != MPI_SUCCESS) { throw ::bliss::utils::make_exception<::bliss::io::IOException>(get_error_string("get_size", res)); } return static_cast<size_t>(s); } /// opens a file. side effect computes size of the file. void open_file() { // if (this->comm.rank() == 0) printf("open mpiio file\n"); // first clear previously open file close_file(); // open the file int res = MPI_File_open(this->comm, const_cast<char *>(this->filename.c_str()), MPI_MODE_RDONLY, MPI_INFO_NULL, &fh); if (res != MPI_SUCCESS) { throw ::bliss::utils::make_exception<::bliss::io::IOException>(get_error_string("open", res)); } // ensure atomicity is turned off MPI_File_set_atomicity(fh, 0); } /// funciton for closing a file void close_file() { if (fh != MPI_FILE_NULL) { int res = MPI_File_close(&fh); if (res != MPI_SUCCESS) { throw ::bliss::utils::make_exception<::bliss::io::IOException>(get_error_string("close", res)); } fh = MPI_FILE_NULL; } } public: // this is needed to prevent overload name hiding. see http://stackoverflow.com/questions/888235/overriding-a-bases-overloaded-function-in-c/888337#888337 using BASE::read_range; using FileParserType = FileParser<typename ::bliss::io::file_data::const_iterator>; /** * @brief bulk load the data and return it in a newly constructed vector. block decomposes the range. reuse vector * @note virtual so other overloads of this function can also block decompose the range. * @param range_bytes range to read, in bytes * @param output vector containing data as bytes. */ virtual range_type read_range(typename ::bliss::io::file_data::container & output, range_type const & range_bytes) { if (fh == MPI_FILE_NULL) { std::stringstream ss; ss << "ERROR in mpiio: rank " << comm.rank() << " file " << this->filename << " not yet open " << std::endl; throw ::bliss::utils::make_exception<::bliss::io::IOException>(ss.str()); } // ensure valid range is used. range_type target = BASE::range_type::intersect(range_bytes, this->file_range_bytes); // do equal partition if (comm.size() > 1) { partitioner.configure(target, comm.size()); target = partitioner.getNext(comm.rank()); } // compute the size to read. range_type read_range = target; read_range.end += std::is_same<FileParser<typename bliss::io::file_data::const_iterator>, ::bliss::io::FASTAParser<typename bliss::io::file_data::const_iterator> >::value ? 2 * this->overlap : this->overlap; read_range.intersect(this->file_range_bytes); output.resize(read_range.size()); // set size for reading. // then read the file using mpiio MPI_Status stat; // NOTE: file offset is in units of byte (up to size_t). number of elements to read has type int. size_t step_size = 1UL << 30 ; // using 2^30 vs 2^31-2^15 does not make a huge performance difference (will only matter for low proc count anyways) size_t rem = read_range.size() % step_size; // size_t steps = read_range.size() / step_size; int count = 0; int res = MPI_SUCCESS; // ======= DOES NOT WORK. number of elements has type int. // res =MPI_File_read_at_all(fh, read_range.start, output.data(), read_range.size(), MPI_BYTE, &stat); // if (res != MPI_SUCCESS) throw ::bliss::utils::make_exception<::bliss::io::IOException>(get_error_string("read", res, stat)); // ======= DOES NOT WORK to read rem first as BYTES, then read rest as 1GB blocks. rem reads okay, but the first byte for big type fails. // res = MPI_File_read_at_all(fh, read_range.start, output.data(), rem, MPI_BYTE, &stat); // if (res != MPI_SUCCESS) throw ::bliss::utils::make_exception<::bliss::io::IOException>(get_error_string("read", res, stat)); // // count is okay here. // res = MPI_Get_count(&stat, MPI_BYTE, &count); // if (res != MPI_SUCCESS) throw ::bliss::utils::make_exception<::bliss::io::IOException>(get_error_string("count", res)); // if (static_cast<size_t>(count) != rem) { // std::stringstream ss; // ss << "ERROR in mpiio: rank " << comm.rank() << " remainder read error. request " << rem << " bytes got " << count << " bytes" << std::endl; // throw ::bliss::utils::make_exception<::bliss::io::IOException>(ss.str()); // } // // // now read the big data type (size of 1GB) // if (steps > 0) { // ::mxx::datatype dt = ::mxx::get_datatype<unsigned char>().contiguous(step_size); // make element 2^30 in size. // res = MPI_File_read_at_all(fh, read_range.start + rem, output.data() + rem, // steps, dt.type(), &stat); // if (res != MPI_SUCCESS) throw ::bliss::utils::make_exception<::bliss::io::IOException>(get_error_string("read", res, stat)); // // count comes back as -32677. // res = MPI_Get_count(&stat, dt.type(), &count); // if (res != MPI_SUCCESS) throw ::bliss::utils::make_exception<::bliss::io::IOException>(get_error_string("read", res)); // if (static_cast<size_t>(count) != steps) { // std::stringstream ss; // ss << "ERROR in mpiio: rank " << comm.rank() << " remainder read error. request " << steps << " 2^30 byte blocks got " << count << " blocks" << std::endl; // throw ::bliss::utils::make_exception<::bliss::io::IOException>(ss.str()); // } // } // ============== does not work to read big data type first then rem. // if (steps > 0) { // // first blocks failed - reads a vector of 0's // ::mxx::datatype dt = ::mxx::get_datatype<unsigned char>().contiguous(step_size); // make element 2^30 in size. // res = MPI_File_read_at_all(fh, read_range.start, output.data(), // steps, dt.type(), &stat); // if (res != MPI_SUCCESS) throw ::bliss::utils::make_exception<::bliss::io::IOException>(get_error_string("read", res, stat)); // // get count got -32766. // res = MPI_Get_count(&stat, dt.type(), &count); // if (res != MPI_SUCCESS) throw ::bliss::utils::make_exception<::bliss::io::IOException>(get_error_string("read", res)); // if (static_cast<size_t>(count) != steps) { // std::stringstream ss; // ss << "ERROR in mpiio: rank " << comm.rank() << " remainder read error. request " << steps << " 2^30 byte blocks got " << count << " blocks" << std::endl; // throw ::bliss::utils::make_exception<::bliss::io::IOException>(ss.str()); // } // } // res = MPI_File_read_at_all(fh, read_range.start + steps * step_size, output.data() + steps * step_size, rem, MPI_BYTE, &stat); // if (res != MPI_SUCCESS) throw ::bliss::utils::make_exception<::bliss::io::IOException>(get_error_string("read", res, stat)); // res = MPI_Get_count(&stat, MPI_BYTE, &count); // if (res != MPI_SUCCESS) throw ::bliss::utils::make_exception<::bliss::io::IOException>(get_error_string("read", res)); // if (static_cast<size_t>(count) != rem) { // std::stringstream ss; // ss << "ERROR in mpiio: rank " << comm.rank() << " remainder read error. request " << rem << " bytes got " << count << " bytes" << std::endl; // throw ::bliss::utils::make_exception<::bliss::io::IOException>(ss.str()); // } // ========= Single big data type that is the whole size does not work. hangs when nprocs = 1 and for nprocs = 2, does not appear to populate data at all // ::mxx::datatype dt = ::mxx::get_datatype<unsigned char>().contiguous(read_range.size()); // make element the whole range in size. // res = MPI_File_read_at_all(fh, read_range.start, output.data(), 1, dt.type(), &stat); // if (res != MPI_SUCCESS) throw ::bliss::utils::make_exception<::bliss::io::IOException>(get_error_string("read", res, stat)); // // // getCount returns -32766, so cannot be used. // res = MPI_Get_count(&stat, dt.type(), &count); // if (res != MPI_SUCCESS) throw ::bliss::utils::make_exception<::bliss::io::IOException>(get_error_string("read", res)); // if (static_cast<size_t>(count) != read_range.size()) { // std::stringstream ss; // ss << "ERROR in mpiio: rank " << comm.rank() << " remainder read error. request " << read_range.size() << " bytes got " << count << " bytes" << std::endl; // throw ::bliss::utils::make_exception<::bliss::io::IOException>(ss.str()); // } // =========== iterative works size_t iter_step_size; // since collective, first get the maximum read size. size_t max_read_size = read_range.size(); max_read_size = ::mxx::allreduce(max_read_size, [](size_t const & x, size_t const & y){ return ::std::max(x, y); }, this->comm); // compute the steps for from the max and local_steps size_t steps = (max_read_size + step_size - 1) >> 30; size_t local_full_steps = read_range.size() >> 30; size_t offset = 0; for (size_t s = 0; s < steps; ++s) { // compute the iter_step_size. // below local_full_steps, full step size. // at local full steps (== last step), read_range.size() % step_size; // above local full steps, 0. iter_step_size = (s < local_full_steps) ? step_size : (s == local_full_steps) ? rem : 0; res = MPI_File_read_at_all(fh, read_range.start + offset, output.data() + offset, iter_step_size, MPI_BYTE, &stat); offset += iter_step_size; if (res != MPI_SUCCESS) throw ::bliss::utils::make_exception<::bliss::io::IOException>(get_error_string("read", res, stat)); res = MPI_Get_count(&stat, MPI_BYTE, &count); if (res != MPI_SUCCESS) throw ::bliss::utils::make_exception<::bliss::io::IOException>(get_error_string("read count", res, stat)); if (static_cast<size_t>(count) != iter_step_size) { std::stringstream ss; ss << "ERROR in mpiio: rank " << comm.rank() << " remainder read error. request " << iter_step_size << " bytes got " << count << " bytes" << std::endl; throw ::bliss::utils::make_exception<::bliss::io::IOException>(ss.str()); } } // std::cout << "rank " << comm.rank() << " done reading " << read_range << std::endl; return target; } mpiio_base_file(::std::string const & _filename, size_t const _overlap = 0UL, ::mxx::comm const & _comm = ::mxx::comm()) : BASE(static_cast<int>(-1), static_cast<size_t>(0)), overlap(_overlap), comm(_comm.copy()), fh(MPI_FILE_NULL) { this->filename = _filename; this->open_file(); this->file_range_bytes.end = this->get_file_size(); // call after opening file }; ~mpiio_base_file() { this->close_file(); }; // this is needed to prevent overload name hiding. see http://stackoverflow.com/questions/888235/overriding-a-bases-overloaded-function-in-c/888337#888337 using BASE::read_file; }; /** * parallel file abstraction for MPIIO, block partition with overlap */ template <template <typename> class FileParser = ::bliss::io::BaseFileParser > class mpiio_file : public ::bliss::io::parallel::mpiio_base_file<FileParser> { protected: using BASE = ::bliss::io::parallel::mpiio_base_file<FileParser>; public: // this is needed to prevent overload name hiding. see http://stackoverflow.com/questions/888235/overriding-a-bases-overloaded-function-in-c/888337#888337 using BASE::read_range; using FileParserType = typename BASE::FileParserType; mpiio_file(::std::string const & _filename, size_t const & _overlap = 0UL, ::mxx::comm const & _comm = ::mxx::comm()) : BASE(_filename, _overlap, _comm) {}; ~mpiio_file() {}; // this is needed to prevent overload name hiding. see http://stackoverflow.com/questions/888235/overriding-a-bases-overloaded-function-in-c/888337#888337 using BASE::read_file; /** * @brief read the whole file. reuse allocated file_data object. * @note virtual so that parallel readers can compute range to read. * @param output file_data object containing data and various ranges. */ virtual void read_file(::bliss::io::file_data & output) { // std::cout << "mpiio_file primary template read_file" << std::endl; // then read the range via sequential version output.valid_range_bytes = read_range(output.data, this->file_range_bytes); // overlap is part of the read so there is no left shift needed. // set up the ranges. output.in_mem_range_bytes = output.valid_range_bytes; output.in_mem_range_bytes.end += this->overlap; output.in_mem_range_bytes.intersect(this->file_range_bytes); output.parent_range_bytes = this->file_range_bytes; } // std::string get_class_name() { // return std::string("mpiio_file<...>"); // } }; /** * parallel file abstraction for MPIIO. FASTQParser, which searches the input. */ template <> class mpiio_file<::bliss::io::FASTQParser> : public ::bliss::io::parallel::mpiio_base_file<::bliss::io::FASTQParser> { protected: using BASE = ::bliss::io::parallel::mpiio_base_file<::bliss::io::FASTQParser> ; public: // this is needed to prevent overload name hiding. see http://stackoverflow.com/questions/888235/overriding-a-bases-overloaded-function-in-c/888337#888337 using BASE::read_range; using FileParserType = typename BASE::FileParserType; mpiio_file(::std::string const & _filename, size_t const & _overlap = 0UL, ::mxx::comm const & _comm = ::mxx::comm()) : BASE(_filename, 0UL, _comm) {}; // specify 1 page worth as overlap ~mpiio_file() { }; // this is needed to prevent overload name hiding. see http://stackoverflow.com/questions/888235/overriding-a-bases-overloaded-function-in-c/888337#888337 using BASE::read_file; /** * @brief read the whole file. reuse allocated file_data object. * @note virtual so that parallel readers can compute range to read. * @param output file_data object containing data and various ranges. */ virtual void read_file(::bliss::io::file_data & output) { // std::cout << "mpiio_file fastq templated read_file" << std::endl; // overlap is set to page size, so output will have sufficient space. // note that this is same behavior as the serial mmap_file // then read the range via sequential version range_type partition_range = read_range(output.data, this->file_range_bytes); // std::cout << "rank " << this->comm.rank() << " read " << partition_range << std::endl; // std::ostream_iterator<unsigned char> oit(std::cout, ""); // std::copy(output.data.begin(), output.data.begin() + 100, oit); // std::cout << std::endl; range_type in_mem = partition_range; in_mem.end = in_mem.start + output.data.size(); // std::cout << "rank " << this->comm.rank() << " in mem " << in_mem << std::endl; // std::cout << "rank " << this->comm.rank() << " overlap " << this->overlap << std::endl; // now search for the true start. FileParserType parser; // mark the first entry found. size_t real_start = parser.init_parser(output.in_mem_cbegin(), this->file_range_bytes, in_mem, partition_range, this->comm); // std::cout << "rank " << this->comm.rank() << " real start " << real_start << std::endl; // std::cout << "rank " << this->comm.rank() << " data size before remove overlap " << output.data.size() << std::endl; // now clear the region outside of the block range (the overlap portion) if (output.data.size() > partition_range.size()) { output.data.erase(output.data.begin() + partition_range.size(), output.data.end()); } // std::cout << "rank " << this->comm.rank() << " data size after remove overlap " << output.data.size() << std::endl; // ==== shift values to the left (as vector?) // actually, not shift. need to do all to all - if a rank found no internal starts // first compute the target proc id via exscan bool not_found = (real_start >= partition_range.end); // if real start is outside of partition, not found real_start = std::min(real_start, partition_range.end); int target_rank = not_found ? 0 : this->comm.rank(); target_rank = ::mxx::exscan(target_rank, [](int const & x, int const & y) { return (x < y) ? y : x; }, this->comm); // std::cout << "rank " << this->comm.rank() << " adjusted real start " << real_start << std::endl; // std::cout << "rank " << this->comm.rank() << " target rank " << target_rank << std::endl; // MPI 2 does not have neighbor_ collective operations, so we can't create // graph with sparse edges. in any case, the amount of data we send should be // small so alltoallv should be enough std::vector<size_t> send_counts(this->comm.size(), 0); if (this->comm.rank() > 0) send_counts[target_rank] = real_start - in_mem.start; // copy the region to shift typename ::bliss::io::file_data::container shifted = ::mxx::all2allv(output.data, send_counts, this->comm); output.data.insert(output.data.end(), shifted.begin(), shifted.end()); // std::cout << "rank " << this->comm.rank() << " shifted " << shifted.size() << std::endl; // std::cout << "rank " << this->comm.rank() << " new data size " << output.data.size() << std::endl; // adjust the ranges. output.in_mem_range_bytes = partition_range; output.in_mem_range_bytes.end = partition_range.start + output.data.size(); // std::cout << "rank " << this->comm.rank() << " final in mem " << output.in_mem_range_bytes << std::endl; output.valid_range_bytes.start = real_start; output.valid_range_bytes.end = not_found ? partition_range.end : output.in_mem_range_bytes.end; // std::cout << "rank " << this->comm.rank() << "/" << this->comm.size() << " final valid " << output.valid_range_bytes << std::endl; output.parent_range_bytes = this->file_range_bytes; // std::cout << "rank " << this->comm.rank() << " file " << output.parent_range_bytes << std::endl; } // std::string get_class_name() { // return std::string("mpiio_file<FASTQ>"); // } }; /** * parallel file abstraction for MPIIO. FASTQParser, which searches the input. */ template <> class mpiio_file<::bliss::io::FASTAParser > : public ::bliss::io::parallel::mpiio_base_file<::bliss::io::FASTAParser > { protected: using BASE = ::bliss::io::parallel::mpiio_base_file<::bliss::io::FASTAParser > ; public: // this is needed to prevent overload name hiding. see http://stackoverflow.com/questions/888235/overriding-a-bases-overloaded-function-in-c/888337#888337 using BASE::read_range; using FileParserType = typename BASE::FileParserType; mpiio_file(::std::string const & _filename, size_t const & _overlap = 0UL, ::mxx::comm const & _comm = ::mxx::comm()) : BASE(_filename, _overlap, _comm) {}; // specify 1 page worth as overlap ~mpiio_file() { }; // this is needed to prevent overload name hiding. see http://stackoverflow.com/questions/888235/overriding-a-bases-overloaded-function-in-c/888337#888337 using BASE::read_file; /** * @brief read the whole file. reuse allocated file_data object. * @note virtual so that parallel readers can compute range to read. * @param output file_data object containing data and various ranges. */ virtual void read_file(::bliss::io::file_data & output) { // std::cout << "mpiio_file fasta templated read_file" << std::endl; // overlap is set to page size, so output will have sufficient space. // note that this is same behavior as the serial mmap_file // then read the range via sequential version // then read the range via sequential version output.valid_range_bytes = read_range(output.data, this->file_range_bytes); // overlap is part of the read so there is no left shift needed. // set up the ranges. output.in_mem_range_bytes = output.valid_range_bytes; output.in_mem_range_bytes.end += 2 * this->overlap; output.in_mem_range_bytes.intersect(this->file_range_bytes); output.parent_range_bytes = this->file_range_bytes; // std::cout << "rank " << this->comm.rank() << " read " << partition_range << std::endl; // std::ostream_iterator<unsigned char> oit(std::cout, ""); // std::copy(output.data.begin(), output.data.begin() + 100, oit); // std::cout << std::endl; // std::cout << "rank " << this->comm.rank() << " in mem " << in_mem << std::endl; // std::cout << "rank " << this->comm.rank() << " overlap " << this->overlap << std::endl; // now search for the true start. FileParserType parser; // mark the first entry found. size_t overlap_end = parser.find_overlap_end(output.in_mem_cbegin(), output.parent_range_bytes, output.in_mem_range_bytes, output.valid_range_bytes.end, overlap); // erase the extra. output.in_mem_range_bytes.end = overlap_end; output.data.erase(output.data.begin() + output.in_mem_range_bytes.size(), output.data.end()); // std::cout << "rank " << this->comm.rank() << "/" << this->comm.size() << " final valid " << output.valid_range_bytes << std::endl; // std::cout << "rank " << this->comm.rank() << " file " << output.parent_range_bytes << std::endl; } //std::string get_class_name() { // return std::string("mpiio_file<FASTA>"); //} }; } // namespace parallel #endif // USE_MPI } // io } // bliss #endif /* FILE_HPP_ */
36.891413
209
0.674155
[ "object", "vector" ]
7420e159456ae8c363dd4805a42487c9d5bba857
25,778
cpp
C++
llvm/lib/InterfaceStub/ELFObjHandler.cpp
lxbndr/llvm-project
2b715b15f5f4c6dd60f05d1b62f9c404e8b56e34
[ "Apache-2.0" ]
null
null
null
llvm/lib/InterfaceStub/ELFObjHandler.cpp
lxbndr/llvm-project
2b715b15f5f4c6dd60f05d1b62f9c404e8b56e34
[ "Apache-2.0" ]
null
null
null
llvm/lib/InterfaceStub/ELFObjHandler.cpp
lxbndr/llvm-project
2b715b15f5f4c6dd60f05d1b62f9c404e8b56e34
[ "Apache-2.0" ]
null
null
null
//===- ELFObjHandler.cpp --------------------------------------------------===// // // 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 "llvm/InterfaceStub/ELFObjHandler.h" #include "llvm/InterfaceStub/IFSStub.h" #include "llvm/MC/StringTableBuilder.h" #include "llvm/Object/Binary.h" #include "llvm/Object/ELFObjectFile.h" #include "llvm/Object/ELFTypes.h" #include "llvm/Support/Errc.h" #include "llvm/Support/Error.h" #include "llvm/Support/FileOutputBuffer.h" #include "llvm/Support/MathExtras.h" #include "llvm/Support/MemoryBuffer.h" using llvm::object::ELFObjectFile; using namespace llvm; using namespace llvm::object; using namespace llvm::ELF; namespace llvm { namespace ifs { // Simple struct to hold relevant .dynamic entries. struct DynamicEntries { uint64_t StrTabAddr = 0; uint64_t StrSize = 0; Optional<uint64_t> SONameOffset; std::vector<uint64_t> NeededLibNames; // Symbol table: uint64_t DynSymAddr = 0; // Hash tables: Optional<uint64_t> ElfHash; Optional<uint64_t> GnuHash; }; /// This initializes an ELF file header with information specific to a binary /// dynamic shared object. /// Offsets, indexes, links, etc. for section and program headers are just /// zero-initialized as they will be updated elsewhere. /// /// @param ElfHeader Target ELFT::Ehdr to populate. /// @param Machine Target architecture (e_machine from ELF specifications). template <class ELFT> static void initELFHeader(typename ELFT::Ehdr &ElfHeader, uint16_t Machine) { memset(&ElfHeader, 0, sizeof(ElfHeader)); // ELF identification. ElfHeader.e_ident[EI_MAG0] = ElfMagic[EI_MAG0]; ElfHeader.e_ident[EI_MAG1] = ElfMagic[EI_MAG1]; ElfHeader.e_ident[EI_MAG2] = ElfMagic[EI_MAG2]; ElfHeader.e_ident[EI_MAG3] = ElfMagic[EI_MAG3]; ElfHeader.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32; bool IsLittleEndian = ELFT::TargetEndianness == support::little; ElfHeader.e_ident[EI_DATA] = IsLittleEndian ? ELFDATA2LSB : ELFDATA2MSB; ElfHeader.e_ident[EI_VERSION] = EV_CURRENT; ElfHeader.e_ident[EI_OSABI] = ELFOSABI_NONE; // Remainder of ELF header. ElfHeader.e_type = ET_DYN; ElfHeader.e_machine = Machine; ElfHeader.e_version = EV_CURRENT; ElfHeader.e_ehsize = sizeof(typename ELFT::Ehdr); ElfHeader.e_phentsize = sizeof(typename ELFT::Phdr); ElfHeader.e_shentsize = sizeof(typename ELFT::Shdr); } namespace { template <class ELFT> struct OutputSection { using Elf_Shdr = typename ELFT::Shdr; std::string Name; Elf_Shdr Shdr; uint64_t Addr; uint64_t Offset; uint64_t Size; uint64_t Align; uint32_t Index; bool NoBits = true; }; template <class T, class ELFT> struct ContentSection : public OutputSection<ELFT> { T Content; ContentSection() { this->NoBits = false; } }; // This class just wraps StringTableBuilder for the purpose of adding a // default constructor. class ELFStringTableBuilder : public StringTableBuilder { public: ELFStringTableBuilder() : StringTableBuilder(StringTableBuilder::ELF) {} }; template <class ELFT> class ELFSymbolTableBuilder { public: using Elf_Sym = typename ELFT::Sym; ELFSymbolTableBuilder() { Symbols.push_back({}); } void add(size_t StNameOffset, uint64_t StSize, uint8_t StBind, uint8_t StType, uint8_t StOther, uint16_t StShndx) { Elf_Sym S{}; S.st_name = StNameOffset; S.st_size = StSize; S.st_info = (StBind << 4) | (StType & 0xf); S.st_other = StOther; S.st_shndx = StShndx; Symbols.push_back(S); } size_t getSize() const { return Symbols.size() * sizeof(Elf_Sym); } void write(uint8_t *Buf) const { memcpy(Buf, Symbols.data(), sizeof(Elf_Sym) * Symbols.size()); } private: llvm::SmallVector<Elf_Sym, 8> Symbols; }; template <class ELFT> class ELFDynamicTableBuilder { public: using Elf_Dyn = typename ELFT::Dyn; size_t addAddr(uint64_t Tag, uint64_t Addr) { Elf_Dyn Entry; Entry.d_tag = Tag; Entry.d_un.d_ptr = Addr; Entries.push_back(Entry); return Entries.size() - 1; } void modifyAddr(size_t Index, uint64_t Addr) { Entries[Index].d_un.d_ptr = Addr; } size_t addValue(uint64_t Tag, uint64_t Value) { Elf_Dyn Entry; Entry.d_tag = Tag; Entry.d_un.d_val = Value; Entries.push_back(Entry); return Entries.size() - 1; } void modifyValue(size_t Index, uint64_t Value) { Entries[Index].d_un.d_val = Value; } size_t getSize() const { // Add DT_NULL entry at the end. return (Entries.size() + 1) * sizeof(Elf_Dyn); } void write(uint8_t *Buf) const { memcpy(Buf, Entries.data(), sizeof(Elf_Dyn) * Entries.size()); // Add DT_NULL entry at the end. memset(Buf + sizeof(Elf_Dyn) * Entries.size(), 0, sizeof(Elf_Dyn)); } private: llvm::SmallVector<Elf_Dyn, 8> Entries; }; template <class ELFT> class ELFStubBuilder { public: using Elf_Ehdr = typename ELFT::Ehdr; using Elf_Shdr = typename ELFT::Shdr; using Elf_Phdr = typename ELFT::Phdr; using Elf_Sym = typename ELFT::Sym; using Elf_Addr = typename ELFT::Addr; using Elf_Dyn = typename ELFT::Dyn; ELFStubBuilder(const ELFStubBuilder &) = delete; ELFStubBuilder(ELFStubBuilder &&) = default; explicit ELFStubBuilder(const IFSStub &Stub) { DynSym.Name = ".dynsym"; DynSym.Align = sizeof(Elf_Addr); DynStr.Name = ".dynstr"; DynStr.Align = 1; DynTab.Name = ".dynamic"; DynTab.Align = sizeof(Elf_Addr); ShStrTab.Name = ".shstrtab"; ShStrTab.Align = 1; // Populate string tables. for (const IFSSymbol &Sym : Stub.Symbols) DynStr.Content.add(Sym.Name); for (const std::string &Lib : Stub.NeededLibs) DynStr.Content.add(Lib); if (Stub.SoName) DynStr.Content.add(Stub.SoName.getValue()); std::vector<OutputSection<ELFT> *> Sections = {&DynSym, &DynStr, &DynTab, &ShStrTab}; const OutputSection<ELFT> *LastSection = Sections.back(); // Now set the Index and put sections names into ".shstrtab". uint64_t Index = 1; for (OutputSection<ELFT> *Sec : Sections) { Sec->Index = Index++; ShStrTab.Content.add(Sec->Name); } ShStrTab.Content.finalize(); ShStrTab.Size = ShStrTab.Content.getSize(); DynStr.Content.finalize(); DynStr.Size = DynStr.Content.getSize(); // Populate dynamic symbol table. for (const IFSSymbol &Sym : Stub.Symbols) { uint8_t Bind = Sym.Weak ? STB_WEAK : STB_GLOBAL; // For non-undefined symbols, value of the shndx is not relevant at link // time as long as it is not SHN_UNDEF. Set shndx to 1, which // points to ".dynsym". uint16_t Shndx = Sym.Undefined ? SHN_UNDEF : 1; DynSym.Content.add(DynStr.Content.getOffset(Sym.Name), Sym.Size, Bind, convertIFSSymbolTypeToELF(Sym.Type), 0, Shndx); } DynSym.Size = DynSym.Content.getSize(); // Poplulate dynamic table. size_t DynSymIndex = DynTab.Content.addAddr(DT_SYMTAB, 0); size_t DynStrIndex = DynTab.Content.addAddr(DT_STRTAB, 0); DynTab.Content.addValue(DT_STRSZ, DynSym.Size); for (const std::string &Lib : Stub.NeededLibs) DynTab.Content.addValue(DT_NEEDED, DynStr.Content.getOffset(Lib)); if (Stub.SoName) DynTab.Content.addValue(DT_SONAME, DynStr.Content.getOffset(Stub.SoName.getValue())); DynTab.Size = DynTab.Content.getSize(); // Calculate sections' addresses and offsets. uint64_t CurrentOffset = sizeof(Elf_Ehdr); for (OutputSection<ELFT> *Sec : Sections) { Sec->Offset = alignTo(CurrentOffset, Sec->Align); Sec->Addr = Sec->Offset; CurrentOffset = Sec->Offset + Sec->Size; } // Fill Addr back to dynamic table. DynTab.Content.modifyAddr(DynSymIndex, DynSym.Addr); DynTab.Content.modifyAddr(DynStrIndex, DynStr.Addr); // Write section headers of string tables. fillSymTabShdr(DynSym, SHT_DYNSYM); fillStrTabShdr(DynStr, SHF_ALLOC); fillDynTabShdr(DynTab); fillStrTabShdr(ShStrTab); // Finish initializing the ELF header. initELFHeader<ELFT>(ElfHeader, static_cast<uint16_t>(Stub.Target.Arch.getValue())); ElfHeader.e_shstrndx = ShStrTab.Index; ElfHeader.e_shnum = LastSection->Index + 1; ElfHeader.e_shoff = alignTo(LastSection->Offset + LastSection->Size, sizeof(Elf_Addr)); } size_t getSize() const { return ElfHeader.e_shoff + ElfHeader.e_shnum * sizeof(Elf_Shdr); } void write(uint8_t *Data) const { write(Data, ElfHeader); DynSym.Content.write(Data + DynSym.Shdr.sh_offset); DynStr.Content.write(Data + DynStr.Shdr.sh_offset); DynTab.Content.write(Data + DynTab.Shdr.sh_offset); ShStrTab.Content.write(Data + ShStrTab.Shdr.sh_offset); writeShdr(Data, DynSym); writeShdr(Data, DynStr); writeShdr(Data, DynTab); writeShdr(Data, ShStrTab); } private: Elf_Ehdr ElfHeader; ContentSection<ELFStringTableBuilder, ELFT> DynStr; ContentSection<ELFStringTableBuilder, ELFT> ShStrTab; ContentSection<ELFSymbolTableBuilder<ELFT>, ELFT> DynSym; ContentSection<ELFDynamicTableBuilder<ELFT>, ELFT> DynTab; template <class T> static void write(uint8_t *Data, const T &Value) { *reinterpret_cast<T *>(Data) = Value; } void fillStrTabShdr(ContentSection<ELFStringTableBuilder, ELFT> &StrTab, uint32_t ShFlags = 0) const { StrTab.Shdr.sh_type = SHT_STRTAB; StrTab.Shdr.sh_flags = ShFlags; StrTab.Shdr.sh_addr = StrTab.Addr; StrTab.Shdr.sh_offset = StrTab.Offset; StrTab.Shdr.sh_info = 0; StrTab.Shdr.sh_size = StrTab.Size; StrTab.Shdr.sh_name = ShStrTab.Content.getOffset(StrTab.Name); StrTab.Shdr.sh_addralign = StrTab.Align; StrTab.Shdr.sh_entsize = 0; StrTab.Shdr.sh_link = 0; } void fillSymTabShdr(ContentSection<ELFSymbolTableBuilder<ELFT>, ELFT> &SymTab, uint32_t ShType) const { SymTab.Shdr.sh_type = ShType; SymTab.Shdr.sh_flags = SHF_ALLOC; SymTab.Shdr.sh_addr = SymTab.Addr; SymTab.Shdr.sh_offset = SymTab.Offset; // Only non-local symbols are included in the tbe file, so .dynsym only // contains 1 local symbol (the undefined symbol at index 0). The sh_info // should always be 1. SymTab.Shdr.sh_info = 1; SymTab.Shdr.sh_size = SymTab.Size; SymTab.Shdr.sh_name = this->ShStrTab.Content.getOffset(SymTab.Name); SymTab.Shdr.sh_addralign = SymTab.Align; SymTab.Shdr.sh_entsize = sizeof(Elf_Sym); SymTab.Shdr.sh_link = this->DynStr.Index; } void fillDynTabShdr( ContentSection<ELFDynamicTableBuilder<ELFT>, ELFT> &DynTab) const { DynTab.Shdr.sh_type = SHT_DYNAMIC; DynTab.Shdr.sh_flags = SHF_ALLOC; DynTab.Shdr.sh_addr = DynTab.Addr; DynTab.Shdr.sh_offset = DynTab.Offset; DynTab.Shdr.sh_info = 0; DynTab.Shdr.sh_size = DynTab.Size; DynTab.Shdr.sh_name = this->ShStrTab.Content.getOffset(DynTab.Name); DynTab.Shdr.sh_addralign = DynTab.Align; DynTab.Shdr.sh_entsize = sizeof(Elf_Dyn); DynTab.Shdr.sh_link = this->DynStr.Index; } uint64_t shdrOffset(const OutputSection<ELFT> &Sec) const { return ElfHeader.e_shoff + Sec.Index * sizeof(Elf_Shdr); } void writeShdr(uint8_t *Data, const OutputSection<ELFT> &Sec) const { write(Data + shdrOffset(Sec), Sec.Shdr); } }; /// This function takes an error, and appends a string of text to the end of /// that error. Since "appending" to an Error isn't supported behavior of an /// Error, this function technically creates a new error with the combined /// message and consumes the old error. /// /// @param Err Source error. /// @param After Text to append at the end of Err's error message. Error appendToError(Error Err, StringRef After) { std::string Message; raw_string_ostream Stream(Message); Stream << Err; Stream << " " << After; consumeError(std::move(Err)); return createError(Stream.str()); } template <class ELFT> class DynSym { using Elf_Shdr_Range = typename ELFT::ShdrRange; using Elf_Shdr = typename ELFT::Shdr; public: static Expected<DynSym> create(const ELFFile<ELFT> &ElfFile, const DynamicEntries &DynEnt) { Expected<Elf_Shdr_Range> Shdrs = ElfFile.sections(); if (!Shdrs) return Shdrs.takeError(); return DynSym(ElfFile, DynEnt, *Shdrs); } Expected<const uint8_t *> getDynSym() { if (DynSymHdr) return ElfFile.base() + DynSymHdr->sh_offset; return getDynamicData(DynEnt.DynSymAddr, "dynamic symbol table"); } Expected<StringRef> getDynStr() { if (DynSymHdr) return ElfFile.getStringTableForSymtab(*DynSymHdr, Shdrs); Expected<const uint8_t *> DataOrErr = getDynamicData( DynEnt.StrTabAddr, "dynamic string table", DynEnt.StrSize); if (!DataOrErr) return DataOrErr.takeError(); return StringRef(reinterpret_cast<const char *>(*DataOrErr), DynEnt.StrSize); } private: DynSym(const ELFFile<ELFT> &ElfFile, const DynamicEntries &DynEnt, Elf_Shdr_Range Shdrs) : ElfFile(ElfFile), DynEnt(DynEnt), Shdrs(Shdrs), DynSymHdr(findDynSymHdr()) {} const Elf_Shdr *findDynSymHdr() { for (const Elf_Shdr &Sec : Shdrs) if (Sec.sh_type == SHT_DYNSYM) { // If multiple .dynsym are present, use the first one. // This behavior aligns with llvm::object::ELFFile::getDynSymtabSize() return &Sec; } return nullptr; } Expected<const uint8_t *> getDynamicData(uint64_t EntAddr, StringRef Name, uint64_t Size = 0) { Expected<const uint8_t *> SecPtr = ElfFile.toMappedAddr(EntAddr); if (!SecPtr) return appendToError( SecPtr.takeError(), ("when locating " + Name + " section contents").str()); Expected<const uint8_t *> SecEndPtr = ElfFile.toMappedAddr(EntAddr + Size); if (!SecEndPtr) return appendToError( SecEndPtr.takeError(), ("when locating " + Name + " section contents").str()); return *SecPtr; } const ELFFile<ELFT> &ElfFile; const DynamicEntries &DynEnt; Elf_Shdr_Range Shdrs; const Elf_Shdr *DynSymHdr; }; } // end anonymous namespace /// This function behaves similarly to StringRef::substr(), but attempts to /// terminate the returned StringRef at the first null terminator. If no null /// terminator is found, an error is returned. /// /// @param Str Source string to create a substring from. /// @param Offset The start index of the desired substring. static Expected<StringRef> terminatedSubstr(StringRef Str, size_t Offset) { size_t StrEnd = Str.find('\0', Offset); if (StrEnd == StringLiteral::npos) { return createError( "String overran bounds of string table (no null terminator)"); } size_t StrLen = StrEnd - Offset; return Str.substr(Offset, StrLen); } /// This function populates a DynamicEntries struct using an ELFT::DynRange. /// After populating the struct, the members are validated with /// some basic correctness checks. /// /// @param Dyn Target DynamicEntries struct to populate. /// @param DynTable Source dynamic table. template <class ELFT> static Error populateDynamic(DynamicEntries &Dyn, typename ELFT::DynRange DynTable) { if (DynTable.empty()) return createError("No .dynamic section found"); // Search .dynamic for relevant entries. bool FoundDynStr = false; bool FoundDynStrSz = false; bool FoundDynSym = false; for (auto &Entry : DynTable) { switch (Entry.d_tag) { case DT_SONAME: Dyn.SONameOffset = Entry.d_un.d_val; break; case DT_STRTAB: Dyn.StrTabAddr = Entry.d_un.d_ptr; FoundDynStr = true; break; case DT_STRSZ: Dyn.StrSize = Entry.d_un.d_val; FoundDynStrSz = true; break; case DT_NEEDED: Dyn.NeededLibNames.push_back(Entry.d_un.d_val); break; case DT_SYMTAB: Dyn.DynSymAddr = Entry.d_un.d_ptr; FoundDynSym = true; break; case DT_HASH: Dyn.ElfHash = Entry.d_un.d_ptr; break; case DT_GNU_HASH: Dyn.GnuHash = Entry.d_un.d_ptr; } } if (!FoundDynStr) { return createError( "Couldn't locate dynamic string table (no DT_STRTAB entry)"); } if (!FoundDynStrSz) { return createError( "Couldn't determine dynamic string table size (no DT_STRSZ entry)"); } if (!FoundDynSym) { return createError( "Couldn't locate dynamic symbol table (no DT_SYMTAB entry)"); } if (Dyn.SONameOffset.hasValue() && *Dyn.SONameOffset >= Dyn.StrSize) { return createStringError(object_error::parse_failed, "DT_SONAME string offset (0x%016" PRIx64 ") outside of dynamic string table", *Dyn.SONameOffset); } for (uint64_t Offset : Dyn.NeededLibNames) { if (Offset >= Dyn.StrSize) { return createStringError(object_error::parse_failed, "DT_NEEDED string offset (0x%016" PRIx64 ") outside of dynamic string table", Offset); } } return Error::success(); } /// This function creates an IFSSymbol and populates all members using /// information from a binary ELFT::Sym. /// /// @param SymName The desired name of the IFSSymbol. /// @param RawSym ELFT::Sym to extract symbol information from. template <class ELFT> static IFSSymbol createELFSym(StringRef SymName, const typename ELFT::Sym &RawSym) { IFSSymbol TargetSym{std::string(SymName)}; uint8_t Binding = RawSym.getBinding(); if (Binding == STB_WEAK) TargetSym.Weak = true; else TargetSym.Weak = false; TargetSym.Undefined = RawSym.isUndefined(); TargetSym.Type = convertELFSymbolTypeToIFS(RawSym.st_info); if (TargetSym.Type == IFSSymbolType::Func) { TargetSym.Size = 0; } else { TargetSym.Size = RawSym.st_size; } return TargetSym; } /// This function populates an IFSStub with symbols using information read /// from an ELF binary. /// /// @param TargetStub IFSStub to add symbols to. /// @param DynSym Range of dynamic symbols to add to TargetStub. /// @param DynStr StringRef to the dynamic string table. template <class ELFT> static Error populateSymbols(IFSStub &TargetStub, const typename ELFT::SymRange DynSym, StringRef DynStr) { // Skips the first symbol since it's the NULL symbol. for (auto RawSym : DynSym.drop_front(1)) { // If a symbol does not have global or weak binding, ignore it. uint8_t Binding = RawSym.getBinding(); if (!(Binding == STB_GLOBAL || Binding == STB_WEAK)) continue; // If a symbol doesn't have default or protected visibility, ignore it. uint8_t Visibility = RawSym.getVisibility(); if (!(Visibility == STV_DEFAULT || Visibility == STV_PROTECTED)) continue; // Create an IFSSymbol and populate it with information from the symbol // table entry. Expected<StringRef> SymName = terminatedSubstr(DynStr, RawSym.st_name); if (!SymName) return SymName.takeError(); IFSSymbol Sym = createELFSym<ELFT>(*SymName, RawSym); TargetStub.Symbols.push_back(std::move(Sym)); // TODO: Populate symbol warning. } return Error::success(); } /// Returns a new IFSStub with all members populated from an ELFObjectFile. /// @param ElfObj Source ELFObjectFile. template <class ELFT> static Expected<std::unique_ptr<IFSStub>> buildStub(const ELFObjectFile<ELFT> &ElfObj) { using Elf_Dyn_Range = typename ELFT::DynRange; using Elf_Sym_Range = typename ELFT::SymRange; using Elf_Sym = typename ELFT::Sym; std::unique_ptr<IFSStub> DestStub = std::make_unique<IFSStub>(); const ELFFile<ELFT> &ElfFile = ElfObj.getELFFile(); // Fetch .dynamic table. Expected<Elf_Dyn_Range> DynTable = ElfFile.dynamicEntries(); if (!DynTable) { return DynTable.takeError(); } // Collect relevant .dynamic entries. DynamicEntries DynEnt; if (Error Err = populateDynamic<ELFT>(DynEnt, *DynTable)) return std::move(Err); Expected<DynSym<ELFT>> EDynSym = DynSym<ELFT>::create(ElfFile, DynEnt); if (!EDynSym) return EDynSym.takeError(); Expected<StringRef> EDynStr = EDynSym->getDynStr(); if (!EDynStr) return EDynStr.takeError(); StringRef DynStr = *EDynStr; // Populate Arch from ELF header. DestStub->Target.Arch = static_cast<IFSArch>(ElfFile.getHeader().e_machine); DestStub->Target.BitWidth = convertELFBitWidthToIFS(ElfFile.getHeader().e_ident[EI_CLASS]); DestStub->Target.Endianness = convertELFEndiannessToIFS(ElfFile.getHeader().e_ident[EI_DATA]); DestStub->Target.ObjectFormat = "ELF"; // Populate SoName from .dynamic entries and dynamic string table. if (DynEnt.SONameOffset.hasValue()) { Expected<StringRef> NameOrErr = terminatedSubstr(DynStr, *DynEnt.SONameOffset); if (!NameOrErr) { return appendToError(NameOrErr.takeError(), "when reading DT_SONAME"); } DestStub->SoName = std::string(*NameOrErr); } // Populate NeededLibs from .dynamic entries and dynamic string table. for (uint64_t NeededStrOffset : DynEnt.NeededLibNames) { Expected<StringRef> LibNameOrErr = terminatedSubstr(DynStr, NeededStrOffset); if (!LibNameOrErr) { return appendToError(LibNameOrErr.takeError(), "when reading DT_NEEDED"); } DestStub->NeededLibs.push_back(std::string(*LibNameOrErr)); } // Populate Symbols from .dynsym table and dynamic string table. Expected<uint64_t> SymCount = ElfFile.getDynSymtabSize(); if (!SymCount) return SymCount.takeError(); if (*SymCount > 0) { // Get pointer to in-memory location of .dynsym section. Expected<const uint8_t *> DynSymPtr = EDynSym->getDynSym(); if (!DynSymPtr) return appendToError(DynSymPtr.takeError(), "when locating .dynsym section contents"); Elf_Sym_Range DynSyms = ArrayRef<Elf_Sym>( reinterpret_cast<const Elf_Sym *>(*DynSymPtr), *SymCount); Error SymReadError = populateSymbols<ELFT>(*DestStub, DynSyms, DynStr); if (SymReadError) return appendToError(std::move(SymReadError), "when reading dynamic symbols"); } return std::move(DestStub); } /// This function opens a file for writing and then writes a binary ELF stub to /// the file. /// /// @param FilePath File path for writing the ELF binary. /// @param Stub Source InterFace Stub to generate a binary ELF stub from. template <class ELFT> static Error writeELFBinaryToFile(StringRef FilePath, const IFSStub &Stub, bool WriteIfChanged) { ELFStubBuilder<ELFT> Builder{Stub}; // Write Stub to memory first. std::vector<uint8_t> Buf(Builder.getSize()); Builder.write(Buf.data()); if (WriteIfChanged) { if (ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrError = MemoryBuffer::getFile(FilePath)) { // Compare Stub output with existing Stub file. // If Stub file unchanged, abort updating. if ((*BufOrError)->getBufferSize() == Builder.getSize() && !memcmp((*BufOrError)->getBufferStart(), Buf.data(), Builder.getSize())) return Error::success(); } } Expected<std::unique_ptr<FileOutputBuffer>> BufOrError = FileOutputBuffer::create(FilePath, Builder.getSize()); if (!BufOrError) return createStringError(errc::invalid_argument, toString(BufOrError.takeError()) + " when trying to open `" + FilePath + "` for writing"); // Write binary to file. std::unique_ptr<FileOutputBuffer> FileBuf = std::move(*BufOrError); memcpy(FileBuf->getBufferStart(), Buf.data(), Buf.size()); return FileBuf->commit(); } Expected<std::unique_ptr<IFSStub>> readELFFile(MemoryBufferRef Buf) { Expected<std::unique_ptr<Binary>> BinOrErr = createBinary(Buf); if (!BinOrErr) { return BinOrErr.takeError(); } Binary *Bin = BinOrErr->get(); if (auto Obj = dyn_cast<ELFObjectFile<ELF32LE>>(Bin)) { return buildStub(*Obj); } else if (auto Obj = dyn_cast<ELFObjectFile<ELF64LE>>(Bin)) { return buildStub(*Obj); } else if (auto Obj = dyn_cast<ELFObjectFile<ELF32BE>>(Bin)) { return buildStub(*Obj); } else if (auto Obj = dyn_cast<ELFObjectFile<ELF64BE>>(Bin)) { return buildStub(*Obj); } return createStringError(errc::not_supported, "unsupported binary format"); } // This function wraps the ELFT writeELFBinaryToFile() so writeBinaryStub() // can be called without having to use ELFType templates directly. Error writeBinaryStub(StringRef FilePath, const IFSStub &Stub, bool WriteIfChanged) { assert(Stub.Target.Arch); assert(Stub.Target.BitWidth); assert(Stub.Target.Endianness); if (Stub.Target.BitWidth == IFSBitWidthType::IFS32) { if (Stub.Target.Endianness == IFSEndiannessType::Little) { return writeELFBinaryToFile<ELF32LE>(FilePath, Stub, WriteIfChanged); } else { return writeELFBinaryToFile<ELF32BE>(FilePath, Stub, WriteIfChanged); } } else { if (Stub.Target.Endianness == IFSEndiannessType::Little) { return writeELFBinaryToFile<ELF64LE>(FilePath, Stub, WriteIfChanged); } else { return writeELFBinaryToFile<ELF64BE>(FilePath, Stub, WriteIfChanged); } } llvm_unreachable("invalid binary output target"); } } // end namespace ifs } // end namespace llvm
35.119891
80
0.678486
[ "object", "vector" ]
7427ae0c7aa9a19966968541223927c58afc3de9
6,787
cpp
C++
depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qttools/src/designer/src/lib/sdk/abstractdialoggui.cpp
GrinCash/Grinc-core
1377979453ba84082f70f9c128be38e57b65a909
[ "MIT" ]
null
null
null
depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qttools/src/designer/src/lib/sdk/abstractdialoggui.cpp
GrinCash/Grinc-core
1377979453ba84082f70f9c128be38e57b65a909
[ "MIT" ]
null
null
null
depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qttools/src/designer/src/lib/sdk/abstractdialoggui.cpp
GrinCash/Grinc-core
1377979453ba84082f70f9c128be38e57b65a909
[ "MIT" ]
null
null
null
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the Qt Designer of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:GPL-EXCEPT$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 as published by the Free Software ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "abstractdialoggui_p.h" QT_BEGIN_NAMESPACE /*! \class QDesignerDialogGuiInterface \since 4.4 \internal \brief The QDesignerDialogGuiInterface allows integrations of \QD to replace the message boxes displayed by \QD by custom dialogs. \inmodule QtDesigner QDesignerDialogGuiInterface provides virtual functions that can be overwritten to display message boxes and file dialogs. \sa QMessageBox, QFileDialog */ /*! \enum QDesignerDialogGuiInterface::Message This enum specifies the context from within the message box is called. \value FormLoadFailureMessage Loading of a form failed \value UiVersionMismatchMessage Attempt to load a file created with an old version of Designer \value ResourceLoadFailureMessage Resources specified in a file could not be found \value TopLevelSpacerMessage Spacer items detected on a container without layout \value PropertyEditorMessage Messages of the propert yeditor \value SignalSlotEditorMessage Messages of the signal / slot editor \value FormEditorMessage Messages of the form editor \value PreviewFailureMessage A preview could not be created \value PromotionErrorMessage Messages related to promotion of a widget \value ResourceEditorMessage Messages of the resource editor \value ScriptDialogMessage Messages of the script dialog \value SignalSlotDialogMessage Messages of the signal slot dialog \value OtherMessage Unspecified context */ /*! Constructs a QDesignerDialogGuiInterface object. */ QDesignerDialogGuiInterface::QDesignerDialogGuiInterface() { } /*! Destroys the QDesignerDialogGuiInterface object. */ QDesignerDialogGuiInterface::~QDesignerDialogGuiInterface() { } /*! \fn QMessageBox::StandardButton QDesignerDialogGuiInterface::message(QWidget *parent, Message context, QMessageBox::Icon icon, const QString &title, const QString &text, QMessageBox::StandardButtons buttons, QMessageBox::StandardButton defaultButton) Opens a message box as child of \a parent within the context \a context, using \a icon, \a title, \a text, \a buttons and \a defaultButton and returns the button chosen by the user. */ /*! \fn QString QDesignerDialogGuiInterface::getExistingDirectory(QWidget *parent, const QString &caption, const QString &dir, QFileDialog::Options options) Opens a file dialog as child of \a parent using the parameters \a caption, \a dir and \a options that prompts the user for an existing directory. Returns a directory selected by the user. */ /*! \fn QString QDesignerDialogGuiInterface::getOpenFileName(QWidget *parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedFilter, QFileDialog::Options) Opens a file dialog as child of \a parent using the parameters \a caption, \a dir, \a filter, \a selectedFilter and \a options that prompts the user for an existing file. Returns a file selected by the user. */ /*! \fn QStringList QDesignerDialogGuiInterface::getOpenFileNames(QWidget *parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedFilter, QFileDialog::Options) Opens a file dialog as child of \a parent using the parameters \a caption, \a dir, \a filter, \a selectedFilter and \a options that prompts the user for a set of existing files. Returns one or more existing files selected by the user. */ /*! Opens a file dialog with image browsing capabilities as child of \a parent using the parameters \a caption, \a dir, \a filter, \a selectedFilter and \a options that prompts the user for an existing file. Returns a file selected by the user. The default implementation simply calls getOpenFileName(). On platforms that do not support an image preview in the QFileDialog, the function can be reimplemented to provide an image browser. \since 4.5 */ QString QDesignerDialogGuiInterface::getOpenImageFileName(QWidget *parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedFilter, QFileDialog::Options options) { return getOpenFileName(parent, caption, dir, filter, selectedFilter, options); } /*! Opens a file dialog with image browsing capabilities as child of \a parent using the parameters \a caption, \a dir, \a filter, \a selectedFilter and \a options that prompts the user for a set of existing files. Returns one or more existing files selected by the user. The default implementation simply calls getOpenFileNames(). On platforms that do not support an image preview in the QFileDialog, the function can be reimplemented to provide an image browser. \since 4.5 */ QStringList QDesignerDialogGuiInterface::getOpenImageFileNames(QWidget *parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedFilter, QFileDialog::Options options) { return getOpenFileNames(parent, caption, dir, filter, selectedFilter, options); } /*! \fn QString QDesignerDialogGuiInterface::getSaveFileName(QWidget *parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedFilter, QFileDialog::Options) Opens a file dialog as child of \a parent using the parameters \a caption, \a dir, \a filter, \a selectedFilter and \a options that prompts the user for a file. Returns a file selected by the user. The file does not have to exist. */ QT_END_NAMESPACE
45.550336
254
0.741712
[ "object" ]
742c14bcf90d201ff2f783d39468fce022a12ad0
565
cpp
C++
problems/task_scheduler/solution.cpp
sauravchandra1/Leetcode
be89c7d8d93083326a94906a28bfad2342aa1dfe
[ "MIT" ]
null
null
null
problems/task_scheduler/solution.cpp
sauravchandra1/Leetcode
be89c7d8d93083326a94906a28bfad2342aa1dfe
[ "MIT" ]
null
null
null
problems/task_scheduler/solution.cpp
sauravchandra1/Leetcode
be89c7d8d93083326a94906a28bfad2342aa1dfe
[ "MIT" ]
null
null
null
class Solution { public: int leastInterval(vector<char>& tasks, int n) { const int N = 26; vector<int> vec(N, 0); for (auto v : tasks) vec[v - 'A']++; int _max = *max_element(vec.begin(), vec.end()); int ans = tasks.size(); int tt = (_max - 1) * n; bool ok = true; for (int i = 0; i < N; i++) { if (ok && vec[i] == _max) { ok = false; continue; } tt -= min(_max - 1, vec[i]); } return max(ans, ans + tt); } };
28.25
56
0.414159
[ "vector" ]
742d29327f19b72d579cbfd48b37bd99f2d6ccbe
7,816
cpp
C++
Editor/ModelImporter_OBJ.cpp
ValtoGameEngines/WickedEngine
1831df147c24fe1bbbe3aeddf98da3535284ade8
[ "Zlib", "MIT" ]
1
2020-09-07T23:12:17.000Z
2020-09-07T23:12:17.000Z
Editor/ModelImporter_OBJ.cpp
ValtoGameEngines/WickedEngine
1831df147c24fe1bbbe3aeddf98da3535284ade8
[ "Zlib", "MIT" ]
null
null
null
Editor/ModelImporter_OBJ.cpp
ValtoGameEngines/WickedEngine
1831df147c24fe1bbbe3aeddf98da3535284ade8
[ "Zlib", "MIT" ]
1
2020-06-29T07:54:10.000Z
2020-06-29T07:54:10.000Z
#include "stdafx.h" #include "wiScene.h" #include "ModelImporter.h" #define TINYOBJLOADER_IMPLEMENTATION #include "tiny_obj_loader.h" #include <istream> #include <streambuf> using namespace std; using namespace wiGraphics; using namespace wiScene; using namespace wiECS; struct membuf : std::streambuf { membuf(char* begin, char* end) { this->setg(begin, begin, end); } }; // Custom material file reader: class MaterialFileReader : public tinyobj::MaterialReader { public: explicit MaterialFileReader(const std::string& mtl_basedir) : m_mtlBaseDir(mtl_basedir) {} virtual ~MaterialFileReader() {} virtual bool operator()(const std::string& matId, std::vector<tinyobj::material_t>* materials, std::map<std::string, int>* matMap, std::string* err) { std::string filepath; if (!m_mtlBaseDir.empty()) { filepath = std::string(m_mtlBaseDir) + matId; } else { filepath = matId; } std::vector<uint8_t> filedata; if (!wiHelper::FileRead(filepath, filedata)) { std::stringstream ss; ss << "WARN: Material file [ " << filepath << " ] not found." << std::endl; if (err) { (*err) += ss.str(); } return false; } membuf sbuf((char*)filedata.data(), (char*)filedata.data() + filedata.size()); std::istream matIStream(&sbuf); std::string warning; LoadMtl(matMap, materials, &matIStream, &warning); if (!warning.empty()) { if (err) { (*err) += warning; } } return true; } private: std::string m_mtlBaseDir; }; // Transform the data from OBJ space to engine-space: static const bool transform_to_LH = true; void ImportModel_OBJ(const std::string& fileName, Scene& scene) { string directory, name; wiHelper::SplitPath(fileName, directory, name); wiHelper::RemoveExtensionFromFileName(name); tinyobj::attrib_t obj_attrib; vector<tinyobj::shape_t> obj_shapes; vector<tinyobj::material_t> obj_materials; string obj_errors; std::vector<uint8_t> filedata; bool success = wiHelper::FileRead(fileName, filedata); if (success) { membuf sbuf((char*)filedata.data(), (char*)filedata.data() + filedata.size()); std::istream in(&sbuf); MaterialFileReader matFileReader(directory); success = tinyobj::LoadObj(&obj_attrib, &obj_shapes, &obj_materials, &obj_errors, &in, &matFileReader, true); } else { obj_errors = "Failed to read file: " + fileName; } if (!obj_errors.empty()) { wiBackLog::post(obj_errors.c_str()); } if (success) { // Load material library: vector<Entity> materialLibrary = {}; for (auto& obj_material : obj_materials) { Entity materialEntity = scene.Entity_CreateMaterial(obj_material.name); MaterialComponent& material = *scene.materials.GetComponent(materialEntity); material.baseColor = XMFLOAT4(obj_material.diffuse[0], obj_material.diffuse[1], obj_material.diffuse[2], 1); material.baseColorMapName = obj_material.diffuse_texname; material.displacementMapName = obj_material.displacement_texname; material.emissiveColor.x = obj_material.emission[0]; material.emissiveColor.y = obj_material.emission[1]; material.emissiveColor.z = obj_material.emission[2]; material.emissiveColor.w = max(obj_material.emission[0], max(obj_material.emission[1], obj_material.emission[2])); material.refractionIndex = obj_material.ior; material.metalness = obj_material.metallic; material.normalMapName = obj_material.normal_texname; material.surfaceMapName = obj_material.specular_texname; material.roughness = obj_material.roughness; if (material.normalMapName.empty()) { material.normalMapName = obj_material.bump_texname; } if (material.surfaceMapName.empty()) { material.surfaceMapName = obj_material.specular_highlight_texname; } if (!material.surfaceMapName.empty()) { material.surfaceMap = wiResourceManager::Load(directory + material.surfaceMapName); } if (!material.baseColorMapName.empty()) { material.baseColorMap = wiResourceManager::Load(directory + material.baseColorMapName); } if (!material.normalMapName.empty()) { material.normalMap = wiResourceManager::Load(directory + material.normalMapName); } if (!material.displacementMapName.empty()) { material.displacementMap = wiResourceManager::Load(directory + material.displacementMapName); } materialLibrary.push_back(materialEntity); // for subset-indexing... } if (materialLibrary.empty()) { // Create default material if nothing was found: Entity materialEntity = scene.Entity_CreateMaterial("OBJImport_defaultMaterial"); MaterialComponent& material = *scene.materials.GetComponent(materialEntity); materialLibrary.push_back(materialEntity); // for subset-indexing... } // Load objects, meshes: for (auto& shape : obj_shapes) { Entity objectEntity = scene.Entity_CreateObject(shape.name); Entity meshEntity = scene.Entity_CreateMesh(shape.name + "_mesh"); ObjectComponent& object = *scene.objects.GetComponent(objectEntity); MeshComponent& mesh = *scene.meshes.GetComponent(meshEntity); object.meshID = meshEntity; unordered_map<int, int> registered_materialIndices = {}; unordered_map<size_t, uint32_t> uniqueVertices = {}; for (size_t i = 0; i < shape.mesh.indices.size(); i += 3) { tinyobj::index_t reordered_indices[] = { shape.mesh.indices[i + 0], shape.mesh.indices[i + 1], shape.mesh.indices[i + 2], }; // todo: option param would be better bool flipCulling = false; if (flipCulling) { reordered_indices[1] = shape.mesh.indices[i + 2]; reordered_indices[2] = shape.mesh.indices[i + 1]; } for (auto& index : reordered_indices) { XMFLOAT3 pos = XMFLOAT3( obj_attrib.vertices[index.vertex_index * 3 + 0], obj_attrib.vertices[index.vertex_index * 3 + 1], obj_attrib.vertices[index.vertex_index * 3 + 2] ); XMFLOAT3 nor = XMFLOAT3(0, 0, 0); if (!obj_attrib.normals.empty()) { nor = XMFLOAT3( obj_attrib.normals[index.normal_index * 3 + 0], obj_attrib.normals[index.normal_index * 3 + 1], obj_attrib.normals[index.normal_index * 3 + 2] ); } XMFLOAT2 tex = XMFLOAT2(0, 0); if (index.texcoord_index >= 0 && !obj_attrib.texcoords.empty()) { tex = XMFLOAT2( obj_attrib.texcoords[index.texcoord_index * 2 + 0], 1 - obj_attrib.texcoords[index.texcoord_index * 2 + 1] ); } int materialIndex = max(0, shape.mesh.material_ids[i / 3]); // this indexes the material library if (registered_materialIndices.count(materialIndex) == 0) { registered_materialIndices[materialIndex] = (int)mesh.subsets.size(); mesh.subsets.push_back(MeshComponent::MeshSubset()); mesh.subsets.back().materialID = materialLibrary[materialIndex]; mesh.subsets.back().indexOffset = (uint32_t)mesh.indices.size(); } if (transform_to_LH) { pos.z *= -1; nor.z *= -1; } // eliminate duplicate vertices by means of hashing: size_t vertexHash = 0; wiHelper::hash_combine(vertexHash, index.vertex_index); wiHelper::hash_combine(vertexHash, index.normal_index); wiHelper::hash_combine(vertexHash, index.texcoord_index); wiHelper::hash_combine(vertexHash, materialIndex); if (uniqueVertices.count(vertexHash) == 0) { uniqueVertices[vertexHash] = (uint32_t)mesh.vertex_positions.size(); mesh.vertex_positions.push_back(pos); mesh.vertex_normals.push_back(nor); mesh.vertex_uvset_0.push_back(tex); } mesh.indices.push_back(uniqueVertices[vertexHash]); mesh.subsets.back().indexCount++; } } mesh.CreateRenderData(); } scene.Update(0); } else { wiHelper::messageBox("OBJ import failed! Check backlog for errors!", "Error!"); } }
29.49434
117
0.694985
[ "mesh", "object", "shape", "vector", "transform" ]
742fd008ddaab736c3f92316e98044490528a176
9,498
cpp
C++
Jsmn/Object.cpp
3nprob/clboss
0435b6c074347ce82e490a5988534054e9d7348d
[ "MIT" ]
108
2020-10-01T17:12:40.000Z
2022-03-30T09:18:03.000Z
Jsmn/Object.cpp
3nprob/clboss
0435b6c074347ce82e490a5988534054e9d7348d
[ "MIT" ]
94
2020-10-03T13:40:30.000Z
2022-03-30T09:18:00.000Z
Jsmn/Object.cpp
3nprob/clboss
0435b6c074347ce82e490a5988534054e9d7348d
[ "MIT" ]
17
2020-10-29T13:27:59.000Z
2022-03-18T13:05:03.000Z
#include<assert.h> #include<sstream> #include"Jsmn/Detail/EndAdvancer.hpp" #include"Jsmn/Detail/ParseResult.hpp" #include"Jsmn/Detail/Str.hpp" #include"Jsmn/Detail/Token.hpp" #include"Jsmn/Detail/Type.hpp" #include"Jsmn/Object.hpp" #include"Jsmn/Parser.hpp" #include"Util/Str.hpp" namespace Jsmn { class Object::Impl { private: std::shared_ptr<Detail::ParseResult> parse_result; unsigned int i; unsigned int i_end; Detail::Token& token() { return parse_result->tokens[i]; } Detail::Token const& token() const { return parse_result->tokens[i]; } char const& at(size_t i) const { return parse_result->orig_string[i]; } std::string at(size_t b, size_t e) const { auto sb = parse_result->orig_string.cbegin(); return std::string(sb + b, sb + e); } public: Impl( std::shared_ptr<Detail::ParseResult> parse_result_ , unsigned int i_ ) : parse_result(std::move(parse_result_)) , i(i_) , i_end(i_ + 1) { if (type() == Detail::Array) { auto& tok = token(); Detail::Token const* tokptr = &tok + 1; for (auto step = 0; step < tok.size; ++step) Detail::Token::next(tokptr); i_end = tokptr - &parse_result->tokens[0]; } } Detail::Type type() const { return token().type; } char first_char() const { return at(token().start); } explicit operator bool() const { auto& tok = token(); if (tok.type != Detail::Primitive) throw TypeError(); auto c = at(tok.start); if (c == 'n' || c == 'f') return false; if (c == 't') return true; /* Other primitive. */ throw TypeError(); } explicit operator std::string() const { auto& tok = token(); if (tok.type != Detail::String) throw TypeError(); return Detail::Str::from_escaped(at(tok.start, tok.end)); } explicit operator double() const { auto& tok = token(); if (tok.type != Detail::Primitive) throw TypeError(); auto c = at(tok.start); if (c == 'n' || c == 'f' || c == 't') throw TypeError(); return Detail::Str::to_double(at(tok.start, tok.end)); } std::string direct_text() const { auto& tok = token(); return at(tok.start, tok.end); } void direct_text(char const*& t, std::size_t& len) const { auto& tok = token(); t = &at(tok.start); len = tok.end - tok.start; } /* Object/Array. */ std::size_t size() const { auto& tok = token(); switch (tok.type) { case Detail::Array: case Detail::Object: break; default: throw TypeError(); } return tok.size; } /* Object. */ std::vector<std::string> keys() const { auto& tok = token(); if (tok.type != Detail::Object) throw TypeError(); auto ret = std::vector<std::string>(); auto tokptr = &tok + 1; for (auto i = 0; i < tok.size; ++i, ++tokptr, Detail::Token::next(tokptr)) { auto ekey = at(tokptr->start, tokptr->end); auto key = Detail::Str::from_escaped(ekey); ret.push_back(key); } return ret; } bool has(std::string const& s) const { auto& tok = token(); if (tok.type != Detail::Object) throw TypeError(); auto tokptr = &tok + 1; for (auto i = 0; i < tok.size; ++i, ++tokptr, Detail::Token::next(tokptr)) { auto ekey = at(tokptr->start, tokptr->end); auto key = Detail::Str::from_escaped(ekey); if (key == s) return true; } return false; } std::shared_ptr<Impl> operator[](std::string const& s) const { auto& tok = token(); if (tok.type != Detail::Object) throw TypeError(); auto tokptr = &tok + 1; for (auto i = int(0); i < tok.size; ++i, ++tokptr, Detail::Token::next(tokptr)) { auto ekey = at(tokptr->start, tokptr->end); auto key = Detail::Str::from_escaped(ekey); if (key == s) { ++tokptr; return std::make_shared<Impl>( parse_result , tokptr - &parse_result->tokens[0] ); } } return nullptr; } /* Array. */ std::shared_ptr<Impl> operator[](std::size_t i) const { auto& tok = token(); if (tok.type != Detail::Array) throw TypeError(); if (int(i) >= tok.size) return nullptr; auto tokptr = &tok + 1; for (auto step = 0; step < int(i); ++step) Detail::Token::next(tokptr); return std::make_shared<Impl>( parse_result , tokptr - &parse_result->tokens[0] ); } Detail::Iterator begin() const { return Detail::Iterator(parse_result, i + 1); } Detail::Iterator end() const { return Detail::Iterator(parse_result, i_end); } }; Object::Object() : pimpl(nullptr) { } Object::Object( std::shared_ptr<Detail::ParseResult> parse_result , unsigned int i ) : pimpl(std::make_shared<Impl>(std::move(parse_result), i)) {} bool Object::is_null() const { if (!pimpl) return true; return pimpl->type() == Detail::Primitive && pimpl->first_char() == 'n'; } bool Object::is_boolean() const { if (!pimpl) return false; auto c = pimpl->first_char(); return pimpl->type() == Detail::Primitive && ((c == 'f') || (c == 't')); } bool Object::is_string() const { if (!pimpl) return false; return pimpl->type() == Detail::String; } bool Object::is_object() const { /* null is not considered an object, unlike JavaScript. */ if (!pimpl) return false; return pimpl->type() == Detail::Object; } bool Object::is_array() const { if (!pimpl) return false; return pimpl->type() == Detail::Array; } bool Object::is_number() const { if (!pimpl) return false; auto c = pimpl->first_char(); return pimpl->type() == Detail::Primitive && ((c != 't') && (c != 'f') && (c != 'n')) ; } Object::operator bool() const { if (!pimpl) return false; return (bool) (*pimpl); } Object::operator std::string() const { if (!pimpl) throw TypeError(); return (std::string) (*pimpl); } Object::operator double() const { if (!pimpl) throw TypeError(); return (double) (*pimpl); } std::size_t Object::size() const { if (!pimpl) throw TypeError(); return pimpl->size(); } std::vector<std::string> Object::keys() const { if (!pimpl) throw TypeError(); return pimpl->keys(); } bool Object::has(std::string const& s) const { if (!pimpl) throw TypeError(); return pimpl->has(s); } Object Object::operator[](std::string const& s) const { if (!pimpl) throw TypeError(); auto ret = Object(); ret.pimpl = (*pimpl)[s]; return ret; } Object Object::operator[](std::size_t i) const { if (!pimpl) throw TypeError(); auto ret = Object(); ret.pimpl = (*pimpl)[i]; return ret; } std::string Object::direct_text() const { if (!pimpl) return "null"; return pimpl->direct_text(); } void Object::direct_text(char const*& t, std::size_t& len) const { if (!pimpl) { auto static const text = "null"; t = text; len = 4; return; } return pimpl->direct_text(t, len); } Detail::Iterator Object::begin() const { if (!pimpl) throw TypeError(); return pimpl->begin(); } Detail::Iterator Object::end() const { if (!pimpl) throw TypeError(); return pimpl->end(); } /* Implements indented printing. */ namespace { void print_indent(std::ostream& os, std::size_t indent) { for (auto i = std::size_t(0); i < indent; ++i) os << "\t"; } void print( std::ostream& os , std::size_t indent , Jsmn::Object const& o ) { if (o.is_null()) { os << "null"; } else if (o.is_boolean()) { os << (o ? "true" : "false"); } else if (o.is_string()) { os << '"' << Detail::Str::to_escaped((std::string) o) << '"'; } else if (o.is_object()) { auto keys = o.keys(); if (keys.size() == 0) { os << "{ }"; } else { os << "{" << std::endl; for (auto i = std::size_t(0); i < keys.size(); ++i) { print_indent(os, indent + 1); auto& key = keys[i]; os << '"' << Detail::Str::to_escaped(key) << '"' << " : " ; auto value = o[key]; print(os, indent + 1, value); if (i != keys.size() - 1) os << ','; os << std::endl; } print_indent(os, indent); os << "}"; } } else if (o.is_array()) { if (o.size() == 0) { os << "[ ]"; } else { os << '[' << std::endl; for (auto i = std::size_t(0); i < o.size(); ++i) { print_indent(os, indent + 1); auto value = o[i]; print(os, indent + 1, value); if (i != o.size() - 1) os << ','; os << std::endl; } print_indent(os, indent); os << ']'; } } else if (o.is_number()) { os << o.direct_text(); } else { /* Impossible. */ assert(0 == 1); } } } std::ostream& operator<<(std::ostream& os, Jsmn::Object const& o) { print(os, 0, o); return os; } namespace { /* Reads characters from an input stream, saving them in a buffer that * will later be fed into a Jsmn::Parser. */ class StreamSourceReader : public Detail::SourceReader { private: std::istream& is; std::string buffer; public: explicit StreamSourceReader(std::istream& is_) : is(is_), buffer("") { } std::pair<bool, char> read() { auto c = char('0'); if (!is || is.eof()) return std::make_pair(false, '0'); is.read(&c, 1); buffer.push_back(c); return std::make_pair(true, c); } std::string get_buffer() { auto ret = std::move(buffer); buffer = ""; return ret; } }; } std::istream& operator>>(std::istream& is, Jsmn::Object& o) { auto started = false; StreamSourceReader ssr(is); Detail::EndAdvancer ender(ssr); Jsmn::Parser parser; is >> std::ws; for(;;) { if (!is || is.eof()) { if (!started) return is; throw std::runtime_error("Unexpected end-of-file."); } started = true; ender.scan(); auto ret = parser.feed(ssr.get_buffer()); assert(ret.size() < 2); if (ret.size() != 0) { o = std::move(ret[0]); return is; } } } }
21.586364
83
0.596126
[ "object", "vector" ]
743304e1bc9c4fe5155b48cde59a0fb7f7c4c260
814
cc
C++
gpu/demos/framework/demo.cc
Scopetta197/chromium
b7bf8e39baadfd9089de2ebdc0c5d982de4a9820
[ "BSD-3-Clause" ]
212
2015-01-31T11:55:58.000Z
2022-02-22T06:35:11.000Z
gpu/demos/framework/demo.cc
1065672644894730302/Chromium
239dd49e906be4909e293d8991e998c9816eaa35
[ "BSD-3-Clause" ]
5
2015-03-27T14:29:23.000Z
2019-09-25T13:23:12.000Z
gpu/demos/framework/demo.cc
1065672644894730302/Chromium
239dd49e906be4909e293d8991e998c9816eaa35
[ "BSD-3-Clause" ]
221
2015-01-07T06:21:24.000Z
2022-02-11T02:51:12.000Z
// Copyright (c) 2010 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 "gpu/demos/framework/demo.h" #include "gpu/demos/framework/demo_factory.h" namespace gpu { namespace demos { Demo::Demo() : width_(0), height_(0), last_draw_time_(0) { } Demo::~Demo() { } void Demo::Draw() { float elapsed_sec = 0.0f; clock_t current_time = clock(); if (last_draw_time_ != 0) { elapsed_sec = static_cast<float>(current_time - last_draw_time_) / CLOCKS_PER_SEC; } last_draw_time_ = current_time; Render(elapsed_sec); } bool Demo::IsAnimated() { return false; } void Demo::Resize(int width, int height) { width_ = width; height_ = height; } } // namespace demos } // namespace gpu
20.35
73
0.687961
[ "render" ]
293dc51864c67b1b36bfd8efc2c80c3adda62ef7
75,716
cpp
C++
Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendGraphWidget.cpp
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
1
2022-01-31T08:15:30.000Z
2022-01-31T08:15:30.000Z
Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendGraphWidget.cpp
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
3
2021-09-08T03:41:27.000Z
2022-03-12T01:01:29.000Z
Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendGraphWidget.cpp
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
null
null
null
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <AzQtComponents/Utilities/Conversions.h> #include <EMotionFX/CommandSystem/Source/AnimGraphConnectionCommands.h> #include <EMotionFX/CommandSystem/Source/AnimGraphNodeCommands.h> #include <EMotionFX/CommandSystem/Source/AnimGraphNodeGroupCommands.h> #include <EMotionFX/CommandSystem/Source/MotionSetCommands.h> #include <EMotionFX/Source/AnimGraphExitNode.h> #include <EMotionFX/Source/AnimGraphMotionNode.h> #include <EMotionFX/Source/AnimGraphNodeGroup.h> #include <EMotionFX/Source/AnimGraphObjectFactory.h> #include <EMotionFX/Source/AnimGraphStateMachine.h> #include <EMotionFX/Source/MotionManager.h> #include <EMotionFX/Source/AnimGraphExitNode.h> #include <Editor/AnimGraphEditorBus.h> #include <EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphActionManager.h> #include <EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphModel.h> #include <EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphPlugin.h> #include <EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AttributesWindow.h> #include <EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendGraphViewWidget.h> #include <EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendGraphWidget.h> #include <EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendTreeVisualNode.h> #include <EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/GraphNode.h> #include <EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NavigationHistory.h> #include <EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NodeConnection.h> #include <EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NodeGraph.h> #include <MCore/Source/ReflectionSerializer.h> #include <MCore/Source/StandardHeaders.h> #include <MysticQt/Source/KeyboardShortcutManager.h> #include <MCore/Source/LogManager.h> // qt includes #include <QDropEvent> #include <QMessageBox> #include <QMimeData> #include <QMouseEvent> #include <QToolTip> #include <QWidget> namespace EMStudio { // constructor BlendGraphWidget::BlendGraphWidget(AnimGraphPlugin* plugin, QWidget* parent) : NodeGraphWidget(plugin, nullptr, parent) , m_contextMenuEventMousePos(0, 0) , m_doubleClickHappened(false) { m_moveGroup.SetGroupName("Move anim graph nodes"); setAutoFillBackground(false); setAttribute(Qt::WA_OpaquePaintEvent); connect(&plugin->GetAnimGraphModel(), &AnimGraphModel::rowsInserted, this, &BlendGraphWidget::OnRowsInserted); connect(&plugin->GetAnimGraphModel(), &AnimGraphModel::dataChanged, this, &BlendGraphWidget::OnDataChanged); connect(&plugin->GetAnimGraphModel(), &AnimGraphModel::rowsAboutToBeRemoved, this, &BlendGraphWidget::OnRowsAboutToBeRemoved); connect(&plugin->GetAnimGraphModel(), &AnimGraphModel::FocusChanged, this, &BlendGraphWidget::OnFocusChanged); connect(&plugin->GetAnimGraphModel().GetSelectionModel(), &QItemSelectionModel::selectionChanged, this, &BlendGraphWidget::OnSelectionModelChanged); } // when dropping stuff in our window void BlendGraphWidget::dropEvent(QDropEvent* event) { // dont accept dragging/drop from and to yourself if (event->source() == this) { event->ignore(); return; } if (!m_activeGraph || !m_plugin->GetActionFilter().m_createNodes || m_activeGraph->IsInReferencedGraph()) { event->ignore(); return; } // only accept copy actions if (event->dropAction() != Qt::CopyAction || event->mimeData()->hasText() == false) { event->ignore(); return; } // if we have text, get it AZStd::string dropText = FromQtString(event->mimeData()->text()); MCore::CommandLine commandLine(dropText.c_str()); // calculate the drop position QPoint offset = LocalToGlobal(event->pos()); QModelIndex targetModelIndex; if (GetActiveGraph()) { targetModelIndex = GetActiveGraph()->GetModelIndex(); } MCore::CommandGroup commandGroup("Add motion nodes"); // check if the drag & drop is coming from an external window if (commandLine.CheckIfHasParameter("window")) { AZStd::vector<AZStd::string> droppedLines; AzFramework::StringFunc::Tokenize(dropText.c_str(), droppedLines, "\n", false, true); for (const AZStd::string& droppedLine : droppedLines) { MCore::CommandLine currentCommandLine(droppedLine.c_str()); // get the name of the window where the drag came from AZStd::string dragWindow; currentCommandLine.GetValue("window", "", dragWindow); // drag&drop coming from the motion set window from the standard plugins if (dragWindow == "MotionSetWindow") { AZStd::string motionId; currentCommandLine.GetValue("motionNameID", "", motionId); EMotionFX::AnimGraphMotionNode tempMotionNode; AZStd::vector<AZStd::string> motionIds; motionIds.emplace_back(motionId); tempMotionNode.SetMotionIds(motionIds); AZ::Outcome<AZStd::string> serializedMotionNode = MCore::ReflectionSerializer::Serialize(&tempMotionNode); if (serializedMotionNode.IsSuccess()) { if (targetModelIndex.isValid()) { EMotionFX::AnimGraphNode* currentNode = targetModelIndex.data(AnimGraphModel::ROLE_NODE_POINTER).value<EMotionFX::AnimGraphNode*>(); CommandSystem::CreateAnimGraphNode(&commandGroup, currentNode->GetAnimGraph(), "BlendTreeMotionNode", "Motion", currentNode, offset.x(), offset.y(), serializedMotionNode.GetValue()); // setup the offset for the next motion offset.setY(offset.y() + 60); } } } // drag&drop coming from the motion window from the standard plugins if (dragWindow == "MotionWindow") { // get the motion id and the corresponding motion object const uint32 motionID = currentCommandLine.GetValueAsInt("motionID", MCORE_INVALIDINDEX32); EMotionFX::Motion* motion = EMotionFX::GetMotionManager().FindMotionByID(motionID); if (!motion) { QMessageBox::warning(this, "Cannot Complete Drop Operation", QString("Motion id '%1' not found.").arg(motionID)); event->ignore(); return; } // get the anim graph instance from the current actor instance and check if it is valid if (!targetModelIndex.isValid()) { QMessageBox::warning(this, "Cannot Complete Drop Operation", "Please create an anim graph before dropping the motion."); event->ignore(); return; } // Get the motion set from the anim graph instance. EMotionFX::AnimGraphInstance* animGraphInstance = targetModelIndex.data(AnimGraphModel::ROLE_ANIM_GRAPH_INSTANCE).value<EMotionFX::AnimGraphInstance*>(); EMotionFX::MotionSet* motionSet = nullptr; if (animGraphInstance) { motionSet = animGraphInstance->GetMotionSet(); } else { // In case no anim graph is currently playing, use the selection from the node inspector. EMotionFX::AnimGraphEditorRequestBus::BroadcastResult(motionSet, &EMotionFX::AnimGraphEditorRequests::GetSelectedMotionSet); if (!motionSet) { // In case no motion set is selected and there is only one loaded, use that. if (EMotionFX::GetMotionManager().GetNumMotionSets() == 1) { motionSet = EMotionFX::GetMotionManager().GetMotionSet(0); } } } if (!motionSet) { QMessageBox::warning(this, "No Motion Set Selected", "Cannot drop the motion to the anim graph. Please assign a motion set to the anim graph first."); event->ignore(); return; } // try to find the motion entry for the given motion EMotionFX::MotionSet::MotionEntry* motionEntry = motionSet->FindMotionEntry(motion); if (motionEntry) { EMotionFX::AnimGraphMotionNode tempMotionNode; AZStd::vector<AZStd::string> motionIds; motionIds.emplace_back(motionEntry->GetId()); tempMotionNode.SetMotionIds(motionIds); AZ::Outcome<AZStd::string> serializedContent = MCore::ReflectionSerializer::SerializeMembersExcept(&tempMotionNode, {"childNodes", "connections", "transitions"}); if (serializedContent.IsSuccess()) { EMotionFX::AnimGraphNode* currentNode = targetModelIndex.data(AnimGraphModel::ROLE_NODE_POINTER).value<EMotionFX::AnimGraphNode*>(); CommandSystem::CreateAnimGraphNode(&commandGroup, currentNode->GetAnimGraph(), azrtti_typeid<EMotionFX::AnimGraphMotionNode>(), "Motion", currentNode, offset.x(), offset.y(), serializedContent.GetValue()); // setup the offset for the next motion offset.setY(offset.y() + 60); } } else { if (QMessageBox::warning(this, "Motion Not Part Of Motion Set", "Do you want the motion to be automatically added to the active motion set? When pressing no the drop action will be canceled.", QMessageBox::Yes | QMessageBox::No) == QMessageBox::No) { event->ignore(); return; } // Build a list of unique string id values from all motion set entries. AZStd::vector<AZStd::string> idStrings; motionSet->BuildIdStringList(idStrings); // remove the media root folder from the absolute motion filename so that we get the relative one to the media root folder AZStd::string motionEntryFileName = motion->GetFileName(); EMotionFX::GetEMotionFX().GetFilenameRelativeToMediaRoot(&motionEntryFileName); if (EMotionFX::MotionSet::MotionEntry::CheckIfIsAbsoluteFilename(motionEntryFileName.c_str())) { AZStd::string text = AZStd::string::format("Some of the motions are located outside of the asset folder of your project:\n\n%s\n\nThis means that the motion set cannot store relative filenames and will hold absolute filenames.", EMotionFX::GetEMotionFX().GetMediaRootFolder()); QMessageBox::warning(this, "Warning", text.c_str()); } const AZStd::string idString = CommandSystem::AddMotionSetEntry(motionSet->GetID(), "", idStrings, motionEntryFileName.c_str()); EMotionFX::AnimGraphMotionNode tempMotionNode; AZStd::vector<AZStd::string> motionIds; motionIds.emplace_back(idString); tempMotionNode.SetMotionIds(motionIds); AZ::Outcome<AZStd::string> serializedMotionNode = MCore::ReflectionSerializer::Serialize(&tempMotionNode); if (serializedMotionNode.IsSuccess()) { EMotionFX::AnimGraphNode* currentNode = targetModelIndex.data(AnimGraphModel::ROLE_NODE_POINTER).value<EMotionFX::AnimGraphNode*>(); CommandSystem::CreateAnimGraphNode(&commandGroup, currentNode->GetAnimGraph(), azrtti_typeid<EMotionFX::AnimGraphMotionNode>(), "Motion", currentNode, offset.x(), offset.y(), serializedMotionNode.GetValue()); // setup the offset for the next motion offset.setY(offset.y() + 60); } } } } } // default handling, we're drag & dropping from the palette window else { AZStd::vector<AZStd::string> parts; AzFramework::StringFunc::Tokenize(dropText.c_str(), parts, ";", false, true); if (parts.size() != 3) { MCore::LogError("BlendGraphWidget::dropEvent() - Incorrect syntax using drop data '%s'", FromQtString(event->mimeData()->text()).c_str()); event->ignore(); return; } AZStd::string commandString; AZStd::string resultString; EMotionFX::AnimGraphNode* currentNode = targetModelIndex.data(AnimGraphModel::ROLE_NODE_POINTER).value<EMotionFX::AnimGraphNode*>(); if (!currentNode) { event->ignore(); return; } // build the name prefix AZStd::string& namePrefix = parts[2]; AzFramework::StringFunc::Strip(namePrefix, MCore::CharacterConstants::space, true /* case sensitive */); const AZ::TypeId typeId = AZ::TypeId::CreateString(parts[1].c_str(), parts[1].size()); CommandSystem::CreateAnimGraphNode(&commandGroup, currentNode->GetAnimGraph(), typeId, namePrefix, currentNode, offset.x(), offset.y()); } if (!commandGroup.IsEmpty()) { AZStd::string result; if (!GetCommandManager()->ExecuteCommandGroup(commandGroup, result)) { AZ_Error("EMotionFX", false, result.c_str()); } } event->accept(); } bool BlendGraphWidget::OnEnterDropEvent(QDragEnterEvent* event, EMotionFX::AnimGraphNode* currentNode, NodeGraph* activeGraph) { if (event->mimeData()->hasText() == false) { return false; } // if we have text, get it AZStd::string dropText = FromQtString(event->mimeData()->text()); MCore::CommandLine commandLine(dropText.c_str()); // check if the drag & drop is coming from an external window if (commandLine.CheckIfHasParameter("window")) { // in case the current node is nullptr and the active graph is a valid graph it means we are showing the root graph if (currentNode == nullptr) { QMessageBox::warning(GetMainWindow(), "Cannot Drop Motion", "Either there is no node shown or you are trying to add a motion to the root level which is not possible."); return false; } // check if we need to prevent dropping of non-state machine nodes if (azrtti_typeid(currentNode) == azrtti_typeid<EMotionFX::AnimGraphStateMachine>() || azrtti_typeid(currentNode) == azrtti_typeid<EMotionFX::BlendTree>()) { return true; } return false; } AZStd::vector<AZStd::string> parts; AzFramework::StringFunc::Tokenize(dropText.c_str(), parts, MCore::CharacterConstants::semiColon, true /* keep empty strings */, true /* keep space strings */); if (parts.size() != 3) { //MCore::LogError("BlendGraphWidget::dropEvent() - Incorrect syntax using drop data '%s'", FromQtString(event->mimeData()->text()).AsChar()); return false; } if (parts[0].find("EMotionFX::AnimGraphNode") != 0) { return false; } // check if the dropped node is a state machine node bool canActAsState = false; const AZ::TypeId typeId = AZ::TypeId::CreateString(parts[1].c_str(), parts[1].size()); if (!typeId.IsNull()) { EMotionFX::AnimGraphObject* registeredObject = EMotionFX::AnimGraphObjectFactory::Create(typeId); MCORE_ASSERT(azrtti_istypeof<EMotionFX::AnimGraphNode>(registeredObject)); EMotionFX::AnimGraphNode* registeredNode = static_cast<EMotionFX::AnimGraphNode*>(registeredObject); if (registeredNode->GetCanActAsState()) { canActAsState = true; } delete registeredObject; } // in case the current node is nullptr and the active graph is a valid graph it means we are showing the root graph if (currentNode == nullptr) { if (activeGraph) { // only state machine nodes are allowed in the root graph if (canActAsState) { return true; } } } else { // check if we need to prevent dropping of non-state machine nodes if (azrtti_typeid(currentNode) == azrtti_typeid<EMotionFX::AnimGraphStateMachine>()) { if (canActAsState) { return true; } } else { return true; } } return false; } // drag enter void BlendGraphWidget::dragEnterEvent(QDragEnterEvent* event) { //MCore::LogDebug("BlendGraphWidget::dragEnter"); if (GetActiveGraph()) { EMotionFX::AnimGraphNode* currentNode = GetActiveGraph()->GetModelIndex().data(AnimGraphModel::ROLE_NODE_POINTER).value<EMotionFX::AnimGraphNode*>(); bool acceptEnterEvent = OnEnterDropEvent(event, currentNode, GetActiveGraph()); if (acceptEnterEvent) { event->accept(); return; } } event->ignore(); } // drag leave void BlendGraphWidget::dragLeaveEvent(QDragLeaveEvent* event) { //MCore::LogDebug("BlendGraphWidget::dragLeave"); event->accept(); } // moving around while dragging void BlendGraphWidget::dragMoveEvent(QDragMoveEvent* event) { MCORE_UNUSED(event); // MCore::LogDebug("BlendGraphWidget::dragMove"); } void BlendGraphWidget::OnContextMenuCreateNode() { NodeGraph* nodeGraph = GetActiveGraph(); if (!nodeGraph) { return; } AZ_Assert(sender()->inherits("QAction"), "Expected being called from a QAction"); QAction* action = qobject_cast<QAction*>(sender()); // calculate the position const QPoint offset = SnapLocalToGrid(LocalToGlobal(m_contextMenuEventMousePos)); // build the name prefix and create the node const AZStd::string typeString = FromQtString(action->whatsThis()); AZStd::string namePrefix = FromQtString(action->data().toString()); AzFramework::StringFunc::Strip(namePrefix, MCore::CharacterConstants::space, true /* case sensitive */); const AZ::TypeId typeId = AZ::TypeId::CreateString(typeString.c_str(), typeString.size()); const QModelIndex modelIndex = nodeGraph->GetModelIndex(); EMotionFX::AnimGraphNode* currentNode = modelIndex.data(AnimGraphModel::ROLE_NODE_POINTER).value<EMotionFX::AnimGraphNode*>(); CommandSystem::CreateAnimGraphNode(/*commandGroup=*/nullptr, currentNode->GetAnimGraph(), typeId, namePrefix, currentNode, offset.x(), offset.y()); } bool BlendGraphWidget::CheckIfIsStateMachine() { NodeGraph* nodeGraph = GetActiveGraph(); const QModelIndex modelIndex = nodeGraph->GetModelIndex(); const EMotionFX::AnimGraphNode* animGraphNode = modelIndex.data(AnimGraphModel::ROLE_NODE_POINTER).value<EMotionFX::AnimGraphNode*>(); return (azrtti_typeid(animGraphNode) == azrtti_typeid<EMotionFX::AnimGraphStateMachine>()); } // enable or disable all selected transitions void BlendGraphWidget::SetSelectedTransitionsEnabled(bool isEnabled) { // only allowed when a state machine is currently being showed if (!CheckIfIsStateMachine()) { return; } // gather the selected transitions AZStd::vector<NodeConnection*> selectedTransitions = GetActiveGraph()->GetSelectedNodeConnections(); if (!selectedTransitions.empty()) { MCore::CommandGroup commandGroup("Enable/disable transitions", static_cast<uint32>(selectedTransitions.size())); // iterate through the selected transitions and and enable or disable them for (NodeConnection* selectedTransition : selectedTransitions) { // get the transition and its visual representation StateConnection* visualTransition = static_cast<StateConnection*>(selectedTransition); EMotionFX::AnimGraphStateTransition* transition = FindTransitionForConnection(visualTransition); // get the target node EMotionFX::AnimGraphNode* targetNode = transition->GetTargetNode(); if (targetNode == nullptr) { MCore::LogError("Cannot enable/disable transition with id %s. Target node is invalid.", transition->GetId().ToString().c_str()); continue; } // get the parent node of the target node EMotionFX::AnimGraphNode* parentNode = targetNode->GetParentNode(); if (parentNode == nullptr || (parentNode && azrtti_typeid(parentNode) != azrtti_typeid<EMotionFX::AnimGraphStateMachine>())) { MCore::LogError("Cannot enable/disable transition with id %s. Parent node is invalid.", transition->GetId().ToString().c_str()); continue; } CommandSystem::AdjustTransition(transition, !isEnabled, /*sourceNode=*/AZStd::nullopt, /*targetNode=*/AZStd::nullopt, /*startOffsetXY=*/AZStd::nullopt, AZStd::nullopt, /*endOffsetXY=*/AZStd::nullopt, AZStd::nullopt, /*attributesString=*/AZStd::nullopt, /*serializedMembers=*/AZStd::nullopt, &commandGroup); } AZStd::string resultString; if (!GetCommandManager()->ExecuteCommandGroup(commandGroup, resultString)) { if (resultString.size() > 0) { MCore::LogError(resultString.c_str()); } } } } void BlendGraphWidget::OnContextMenuEvent(QPoint mousePos, QPoint globalMousePos, const AnimGraphActionFilter& actionFilter) { if (!m_allowContextMenu) { return; } NodeGraph* nodeGraph = GetActiveGraph(); if (!nodeGraph) { return; } // Early out in case we're adjusting or creating a new connection. Elsewise the user can open the context menu and // delete selected nodes while creating a new connection. if (nodeGraph->GetIsCreatingConnection() || nodeGraph->GetIsRelinkingConnection() || nodeGraph->GetRepositionedTransitionHead() || nodeGraph->GetRepositionedTransitionTail()) { return; } m_contextMenuEventMousePos = mousePos; const AZStd::vector<EMotionFX::AnimGraphNode*> selectedAnimGraphNodes = nodeGraph->GetSelectedAnimGraphNodes(); const AZStd::vector<NodeConnection*> selectedConnections = nodeGraph->GetSelectedNodeConnections(); const QPoint globalPos = LocalToGlobal(mousePos); const bool mouseOverAnySelectedConnection = AZStd::any_of(selectedConnections.begin(), selectedConnections.end(), [globalPos](NodeConnection* connection) { return connection->CheckIfIsCloseTo(globalPos); }); if (selectedAnimGraphNodes.empty() && !selectedConnections.empty() && mouseOverAnySelectedConnection) { QMenu menu(this); QString removeConnectionActionName; const QString pluralPostfix = selectedConnections.size() == 1 ? "" : "s"; // Handle transitions in case the node graph is representing a state machine. if (CheckIfIsStateMachine()) { removeConnectionActionName = QString("Remove transition%1").arg(pluralPostfix); bool hasDisabledConnection = false; bool hasEnabledConnection = false; for (NodeConnection* connection : selectedConnections) { if (connection->GetIsDisabled()) { hasDisabledConnection = true; } else { hasEnabledConnection = true; } } // Show enable transitions menu entry in case there is at least one disabled transition in the selected ones. if (actionFilter.m_editNodes && hasDisabledConnection) { QAction* enableConnectionAction = menu.addAction(QString("Enable transition%1").arg(pluralPostfix)); connect(enableConnectionAction, &QAction::triggered, this, &BlendGraphWidget::EnableSelectedTransitions); } if (actionFilter.m_editNodes && hasEnabledConnection) { QAction* disableConnectionAction = menu.addAction(QString("Disable transition%1").arg(pluralPostfix)); connect(disableConnectionAction, &QAction::triggered, this, &BlendGraphWidget::DisableSelectedTransitions); } if (actionFilter.m_copyAndPaste && selectedConnections.size() == 1) { EMotionFX::AnimGraphStateTransition* transition = FindTransitionForConnection(selectedConnections[0]); if (transition) { m_plugin->GetAttributesWindow()->AddTransitionCopyPasteMenuEntries(&menu); } } } // Handle blend tree connections in case the node graph is representing a blend tree. else { removeConnectionActionName = QString("Remove connection%1").arg(pluralPostfix); } if (actionFilter.m_delete && !m_activeGraph->IsInReferencedGraph()) { QAction* removeConnectionAction = menu.addAction(removeConnectionActionName); connect(removeConnectionAction, &QAction::triggered, this, static_cast<void (BlendGraphWidget::*)()>(&BlendGraphWidget::DeleteSelectedItems)); } menu.exec(globalMousePos); } else { OnContextMenuEvent(this, mousePos, globalMousePos, m_plugin, selectedAnimGraphNodes, true, false, actionFilter); } } void BlendGraphWidget::mouseDoubleClickEvent(QMouseEvent* event) { if (m_activeGraph == nullptr) { return; } m_doubleClickHappened = true; NodeGraphWidget::mouseDoubleClickEvent(event); GraphNode* node = m_activeGraph->FindNode(event->pos()); if (node) { const QModelIndex nodeModelIndex = node->GetModelIndex(); EMotionFX::AnimGraphNode* animGraphNode = nodeModelIndex.data(AnimGraphModel::ROLE_NODE_POINTER).value<EMotionFX::AnimGraphNode*>(); if (animGraphNode) { if (animGraphNode->GetHasVisualGraph()) { if (!node->GetIsInsideArrowRect(m_mousePos)) { m_plugin->GetAnimGraphModel().Focus(nodeModelIndex); } } } } event->accept(); } void BlendGraphWidget::mousePressEvent(QMouseEvent* event) { m_doubleClickHappened = false; NodeGraphWidget::mousePressEvent(event); } void BlendGraphWidget::mouseReleaseEvent(QMouseEvent* event) { //MCore::LogError("mouse release"); if (m_doubleClickHappened == false) { if (event->button() == Qt::RightButton) { OnContextMenuEvent(event->pos(), event->globalPos(), m_plugin->GetActionFilter()); //setCursor( Qt::ArrowCursor ); } } NodeGraphWidget::mouseReleaseEvent(event); //setCursor( Qt::ArrowCursor ); m_doubleClickHappened = false; } // start moving void BlendGraphWidget::OnMoveStart() { m_moveGroup.RemoveAllCommands(); } // moved a node void BlendGraphWidget::OnMoveNode(GraphNode* node, int32 x, int32 y) { // build the command string const EMotionFX::AnimGraphNode* animGraphNode = node->GetModelIndex().data(AnimGraphModel::ROLE_NODE_POINTER).value<EMotionFX::AnimGraphNode*>(); const AZStd::string moveString = AZStd::string::format("AnimGraphAdjustNode -animGraphID %i -name \"%s\" -xPos %d -yPos %d -updateAttributes false", animGraphNode->GetAnimGraph()->GetID(), animGraphNode->GetName(), x, y); // add it to the group m_moveGroup.AddCommandString(moveString); } // end moving void BlendGraphWidget::OnMoveEnd() { AZStd::string resultString; // execute the command if (GetCommandManager()->ExecuteCommandGroup(m_moveGroup, resultString) == false) { if (resultString.size() > 0) { MCore::LogError(resultString.c_str()); } } } void BlendGraphWidget::OnSelectionModelChanged(const QItemSelection& selected, const QItemSelection& deselected) { // To avoid getting the view out of sync, we are going to collect the selected/deselected items // by GraphNode. We collect all the nodes by parent and then skip the GraphNodes we don't have. // First element of the pair is the selected list, second element is the deselected list using IndexListByIndex = AZStd::unordered_map<QModelIndex, AZStd::pair<QModelIndexList, QModelIndexList>, QModelIndexHash>; IndexListByIndex itemsByParent; for (const QItemSelectionRange& selectedRange : selected) { const QModelIndexList indexes = selectedRange.indexes(); for (const QModelIndex& selectedIndex : indexes) { QModelIndex parent = selectedIndex.model()->parent(selectedIndex); if (selectedIndex.data(AnimGraphModel::ROLE_MODEL_ITEM_TYPE).value<AnimGraphModel::ModelItemType>() == AnimGraphModel::ModelItemType::CONNECTION) { // if the item is a connection, we need send it to the graph of the parent of the node that // contains the connection (the parent of the parent) parent = parent.model()->parent(parent); } itemsByParent[parent].first.push_back(selectedIndex); } } for (const QItemSelectionRange& deselectedRange : deselected) { const QModelIndexList indexes = deselectedRange.indexes(); for (const QModelIndex& deselectedIndex : indexes) { QModelIndex parent = deselectedIndex.model()->parent(deselectedIndex); if (deselectedIndex.data(AnimGraphModel::ROLE_MODEL_ITEM_TYPE).value<AnimGraphModel::ModelItemType>() == AnimGraphModel::ModelItemType::CONNECTION) { // if the item is a connection, we need send it to the graph of the parent of the node that // contains the connection (the parent of the parent) parent = parent.model()->parent(parent); } itemsByParent[parent].second.push_back(deselectedIndex); } } } void BlendGraphWidget::ProcessFrame(bool redraw) { // get the active graph NodeGraph* activeGraph = GetActiveGraph(); if (activeGraph) { activeGraph->UpdateVisualGraphFlags(); } if (redraw) { update(); } } // change the final node (node may not be nullptr) void BlendGraphWidget::SetVirtualFinalNode(const QModelIndex& nodeModelIndex) { if (nodeModelIndex.isValid()) { const QModelIndex parent = nodeModelIndex.parent(); NodeGraphByModelIndex::const_iterator it = m_nodeGraphByModelIndex.find(parent); if (it != m_nodeGraphByModelIndex.end()) { EMotionFX::AnimGraphNode* parentNode = it->first.data(AnimGraphModel::ROLE_NODE_POINTER).value<EMotionFX::AnimGraphNode*>(); if (azrtti_typeid(parentNode) == azrtti_typeid<EMotionFX::BlendTree>()) { EMotionFX::AnimGraphNode* node = nodeModelIndex.data(AnimGraphModel::ROLE_NODE_POINTER).value<EMotionFX::AnimGraphNode*>(); EMotionFX::BlendTree* blendTree = static_cast<EMotionFX::BlendTree*>(parentNode); // update all graph node opacity values it->second->RecursiveSetOpacity(blendTree->GetFinalNode(), 0.065f); it->second->RecursiveSetOpacity(node, 1.0f); if (node != blendTree->GetFinalNode()) { GraphNode* graphNode = it->second->FindGraphNode(nodeModelIndex); graphNode->SetBorderColor(QColor(0, 255, 0)); } } } } } // check if a connection is valid or not bool BlendGraphWidget::CheckIfIsCreateConnectionValid(AZ::u16 portNr, GraphNode* portNode, NodePort* port, bool isInputPort) { MCORE_UNUSED(port); MCORE_ASSERT(m_activeGraph); GraphNode* sourceNode = m_activeGraph->GetCreateConnectionNode(); GraphNode* targetNode = portNode; // don't allow connection to itself if (sourceNode == targetNode) { return false; } // if we're not dealing with state nodes if (sourceNode->GetType() != StateGraphNode::TYPE_ID || targetNode->GetType() != StateGraphNode::TYPE_ID) { // dont allow to connect an input port to another input port or output port to another output port if (isInputPort == m_activeGraph->GetCreateConnectionIsInputPort()) { return false; } } // if this were states, it's all fine if (sourceNode->GetType() == StateGraphNode::TYPE_ID || targetNode->GetType() == StateGraphNode::TYPE_ID) { return CheckIfIsValidTransition(sourceNode, targetNode); } // check if there is already a connection in the port MCORE_ASSERT(portNode->GetType() == BlendTreeVisualNode::TYPE_ID); MCORE_ASSERT(sourceNode->GetType() == BlendTreeVisualNode::TYPE_ID); BlendTreeVisualNode* targetBlendNode; BlendTreeVisualNode* sourceBlendNode; AZ::u16 sourcePortNr; AZ::u16 targetPortNr; // make sure the input always comes from the source node if (isInputPort) { sourceBlendNode = static_cast<BlendTreeVisualNode*>(sourceNode); targetBlendNode = static_cast<BlendTreeVisualNode*>(targetNode); sourcePortNr = m_activeGraph->GetCreateConnectionPortNr(); targetPortNr = portNr; } else { sourceBlendNode = static_cast<BlendTreeVisualNode*>(targetNode); targetBlendNode = static_cast<BlendTreeVisualNode*>(sourceNode); sourcePortNr = portNr; targetPortNr = m_activeGraph->GetCreateConnectionPortNr(); } EMotionFX::AnimGraphNode::Port& sourcePort = sourceBlendNode->GetEMFXNode()->GetOutputPort(sourcePortNr); EMotionFX::AnimGraphNode::Port& targetPort = targetBlendNode->GetEMFXNode()->GetInputPort(targetPortNr); // if the port data types are not compatible, don't allow the connection if (sourcePort.CheckIfIsCompatibleWith(targetPort) == false) { return false; } EMotionFX::AnimGraphNode* parentNode = targetBlendNode->GetEMFXNode()->GetParentNode(); EMotionFX::BlendTree* blendTree = static_cast<EMotionFX::BlendTree*>(parentNode); if (blendTree->ConnectionWillProduceCycle(sourceBlendNode->GetEMFXNode(), targetBlendNode->GetEMFXNode())) { return false; } return true; } bool BlendGraphWidget::CheckIfIsValidTransition(GraphNode* sourceState, [[maybe_unused]] GraphNode* targetState) { if (azrtti_typeid(static_cast<AnimGraphVisualNode*>(sourceState)->GetEMFXNode()) == azrtti_typeid<EMotionFX::AnimGraphExitNode>()) { return false; } return true; } bool BlendGraphWidget::CheckIfIsValidTransitionSource(GraphNode* sourceState) { if (azrtti_typeid(static_cast<AnimGraphVisualNode*>(sourceState)->GetEMFXNode()) == azrtti_typeid<EMotionFX::AnimGraphExitNode>()) { return false; } return true; } EMotionFX::AnimGraphStateTransition* BlendGraphWidget::FindTransitionForConnection(NodeConnection* connection) const { if (connection) { if (connection->GetModelIndex().data(AnimGraphModel::ROLE_MODEL_ITEM_TYPE).value<AnimGraphModel::ModelItemType>() == AnimGraphModel::ModelItemType::TRANSITION) { return connection->GetModelIndex().data(AnimGraphModel::ROLE_TRANSITION_POINTER).value<EMotionFX::AnimGraphStateTransition*>(); } } return nullptr; } EMotionFX::BlendTreeConnection* BlendGraphWidget::FindBlendTreeConnection(NodeConnection* connection) const { if (connection) { if (connection->GetModelIndex().data(AnimGraphModel::ROLE_MODEL_ITEM_TYPE).value<AnimGraphModel::ModelItemType>() == AnimGraphModel::ModelItemType::CONNECTION) { return connection->GetModelIndex().data(AnimGraphModel::ROLE_CONNECTION_POINTER).value<EMotionFX::BlendTreeConnection*>(); } } return nullptr; } // create the connection void BlendGraphWidget::OnCreateConnection(AZ::u16 sourcePortNr, GraphNode* sourceNode, bool sourceIsInputPort, AZ::u16 targetPortNr, GraphNode* targetNode, bool targetIsInputPort, const QPoint& startOffset, const QPoint& endOffset) { MCORE_UNUSED(targetIsInputPort); MCORE_ASSERT(m_activeGraph); GraphNode* realSourceNode; GraphNode* realTargetNode; AZ::u16 realInputPortNr; AZ::u16 realOutputPortNr; if (sourceIsInputPort) { realSourceNode = targetNode; realTargetNode = sourceNode; realOutputPortNr = targetPortNr; realInputPortNr = sourcePortNr; } else { realSourceNode = sourceNode; realTargetNode = targetNode; realOutputPortNr = sourcePortNr; realInputPortNr = targetPortNr; } const EMotionFX::AnimGraphNode* targetAnimGraphNode = targetNode->GetModelIndex().data(AnimGraphModel::ROLE_NODE_POINTER).value<EMotionFX::AnimGraphNode*>(); MCore::CommandGroup commandGroup; AZStd::string command; // Check if there already is a connection plugged into the port where we want to put our new connection in. NodeConnection* existingConnection = m_activeGraph->FindInputConnection(realTargetNode, realInputPortNr); // Special case for state nodes. AZ::TypeId transitionType = AZ::TypeId::CreateNull(); if (sourceNode->GetType() == StateGraphNode::TYPE_ID && targetNode->GetType() == StateGraphNode::TYPE_ID) { transitionType = azrtti_typeid<EMotionFX::AnimGraphStateTransition>(); realInputPortNr = 0; realOutputPortNr = 0; commandGroup.SetGroupName("Create state machine transition"); } else { // Check if there already is a connection and remove it in this case. if (existingConnection) { commandGroup.SetGroupName("Replace blend tree connection"); command = AZStd::string::format("AnimGraphRemoveConnection -animGraphID %i -sourceNode \"%s\" -sourcePort %d -targetNode \"%s\" -targetPort %d", targetAnimGraphNode->GetAnimGraph()->GetID(), existingConnection->GetSourceNode()->GetName(), existingConnection->GetOutputPortNr(), existingConnection->GetTargetNode()->GetName(), existingConnection->GetInputPortNr()); commandGroup.AddCommandString(command); } else { commandGroup.SetGroupName("Create blend tree connection"); } } if (transitionType.IsNull()) { command = AZStd::string::format("AnimGraphCreateConnection -animGraphID %i -sourceNode \"%s\" -targetNode \"%s\" -sourcePort %d -targetPort %d -startOffsetX %d -startOffsetY %d -endOffsetX %d -endOffsetY %d", targetAnimGraphNode->GetAnimGraph()->GetID(), realSourceNode->GetName(), realTargetNode->GetName(), realOutputPortNr, realInputPortNr, startOffset.x(), startOffset.y(), endOffset.x(), endOffset.y()); } else { command = AZStd::string::format("AnimGraphCreateConnection -animGraphID %i -sourceNode \"%s\" -targetNode \"%s\" -sourcePort %d -targetPort %d -startOffsetX %d -startOffsetY %d -endOffsetX %d -endOffsetY %d -transitionType \"%s\"", targetAnimGraphNode->GetAnimGraph()->GetID(), realSourceNode->GetName(), realTargetNode->GetName(), realOutputPortNr, realInputPortNr, startOffset.x(), startOffset.y(), endOffset.x(), endOffset.y(), transitionType.ToString<AZStd::string>().c_str()); } commandGroup.AddCommandString(command); AZStd::string result; if (!EMStudio::GetCommandManager()->ExecuteCommandGroup(commandGroup, result)) { AZ_Error("EMotionFX", false, result.c_str()); } } // curved connection when creating a new one? bool BlendGraphWidget::CreateConnectionMustBeCurved() { if (m_activeGraph == nullptr) { return true; } if (m_activeGraph->GetCreateConnectionNode()->GetType() == StateGraphNode::TYPE_ID) { return false; } return true; } // show helper connection suggestion lines when creating a new connection? bool BlendGraphWidget::CreateConnectionShowsHelpers() { if (m_activeGraph == nullptr) { return true; } if (m_activeGraph->GetCreateConnectionNode()->GetType() == StateGraphNode::TYPE_ID) { return false; } return true; } // delete all selected items void BlendGraphWidget::DeleteSelectedItems() { DeleteSelectedItems(GetActiveGraph()); } void BlendGraphWidget::DeleteSelectedItems(NodeGraph* nodeGraph) { if (!nodeGraph) { return; } // Do not allow to delete nodes or connections when creating or relinking connections or transitions. // In this case the delete operation will cancel the create or relink operation. if (nodeGraph->GetIsCreatingConnection() || nodeGraph->GetIsRelinkingConnection() || nodeGraph->GetRepositionedTransitionHead() || nodeGraph->GetRepositionedTransitionTail()) { nodeGraph->StopCreateConnection(); nodeGraph->StopRelinkConnection(); nodeGraph->StopReplaceTransitionHead(); nodeGraph->StopReplaceTransitionTail(); return; } MCore::CommandGroup commandGroup("Delete selected anim graph items"); AZStd::vector<EMotionFX::BlendTreeConnection*> connectionList; AZStd::vector<EMotionFX::AnimGraphStateTransition*> transitionList; AZStd::vector<EMotionFX::AnimGraphNode*> nodeList; connectionList.reserve(256); transitionList.reserve(256); nodeList.reserve(256); // Delete all selected connections in the graph view first. AZStd::string commandString, sourceNodeName; AZ::u32 numDeletedConnections = 0; const AZStd::vector<NodeConnection*> selectedConnections = GetActiveGraph()->GetSelectedNodeConnections(); for (NodeConnection* selectedConnection : selectedConnections) { EMotionFX::AnimGraphStateTransition* emfxTransition = FindTransitionForConnection(selectedConnection); if (emfxTransition) { CommandSystem::DeleteStateTransition(&commandGroup, emfxTransition, transitionList); numDeletedConnections++; } else { EMotionFX::BlendTreeConnection* emfxConnection = FindBlendTreeConnection(selectedConnection); EMotionFX::AnimGraphNode* emfxTargetNode = selectedConnection->GetTargetNode()->GetModelIndex().data(AnimGraphModel::ROLE_NODE_POINTER).value<EMotionFX::AnimGraphNode*>(); if (emfxConnection && emfxTargetNode) { CommandSystem::DeleteConnection(&commandGroup, emfxTargetNode, emfxConnection, connectionList); numDeletedConnections++; } } } // Prepare the list of nodes to remove. AZStd::vector<AZStd::string> selectedNodeNames; const AZStd::vector<GraphNode*> selectedNodes = GetActiveGraph()->GetSelectedGraphNodes(); for (GraphNode* graphNode : selectedNodes) { selectedNodeNames.emplace_back(graphNode->GetName()); } EMotionFX::AnimGraphNode* parentNode = GetActiveGraph()->GetModelIndex().data(AnimGraphModel::ROLE_NODE_POINTER).value<EMotionFX::AnimGraphNode*>(); CommandSystem::DeleteNodes(&commandGroup, parentNode->GetAnimGraph(), selectedNodeNames, nodeList, connectionList, transitionList); AZStd::string result; if (!EMStudio::GetCommandManager()->ExecuteCommandGroup(commandGroup, result)) { AZ_Error("EMotionFX", false, result.c_str()); } } // some node collapsed void BlendGraphWidget::OnNodeCollapsed(GraphNode* node, bool isCollapsed) { if (node->GetType() == BlendTreeVisualNode::TYPE_ID) { BlendTreeVisualNode* blendNode = static_cast<BlendTreeVisualNode*>(node); blendNode->GetEMFXNode()->SetIsCollapsed(isCollapsed); } } // left-clicked on a node while shift pressed void BlendGraphWidget::OnShiftClickedNode(GraphNode* node) { // when we are dealing with a state node if (node->GetType() == StateGraphNode::TYPE_ID) { EMotionFX::AnimGraphInstance* animGraphInstance = GetActiveGraph()->GetModelIndex().data(AnimGraphModel::ROLE_ANIM_GRAPH_INSTANCE).value<EMotionFX::AnimGraphInstance*>(); if (animGraphInstance) { animGraphInstance->TransitionToState(node->GetName()); } } } void BlendGraphWidget::OnNodeGroupSelected() { assert(sender()->inherits("QAction")); QAction* action = qobject_cast<QAction*>(sender()); // find the selected node const QItemSelection selection = m_plugin->GetAnimGraphModel().GetSelectionModel().selection(); const QModelIndexList selectionList = selection.indexes(); if (selectionList.empty()) { return; } const EMotionFX::AnimGraphNode* parentNode = GetActiveGraph()->GetModelIndex().data(AnimGraphModel::ROLE_NODE_POINTER).value<EMotionFX::AnimGraphNode*>(); EMotionFX::AnimGraph* animGraph = parentNode->GetAnimGraph(); if (!animGraph) { return; } // get the node group name from the action and search the node group EMotionFX::AnimGraphNodeGroup* newNodeGroup; if (action->data().toInt() == 0) { newNodeGroup = nullptr; } else { const AZStd::string nodeGroupName = FromQtString(action->text()); newNodeGroup = animGraph->FindNodeGroupByName(nodeGroupName.c_str()); } MCore::CommandGroup commandGroup("Adjust anim graph node group"); AZStd::vector<AZStd::string> nodeNames; for (const QModelIndex& selectedIndex : selectionList) { // Skip transitions and blend tree connections. if (selectedIndex.data(AnimGraphModel::ROLE_MODEL_ITEM_TYPE).value<AnimGraphModel::ModelItemType>() != AnimGraphModel::ModelItemType::NODE) { continue; } EMotionFX::AnimGraphNode* selectedNode = selectedIndex.data(AnimGraphModel::ROLE_NODE_POINTER).value<EMotionFX::AnimGraphNode*>(); EMotionFX::AnimGraphNodeGroup* nodeGroup = animGraph->FindNodeGroupForNode(selectedNode); if (nodeGroup) { auto* command = aznew CommandSystem::CommandAnimGraphAdjustNodeGroup( GetCommandManager()->FindCommand(CommandSystem::CommandAnimGraphAdjustNodeGroup::s_commandName), /*animGraphId = */ animGraph->GetID(), /*name = */ nodeGroup->GetNameString(), /*visible = */ AZStd::nullopt, /*newName = */ AZStd::nullopt, /*nodeNames = */ {{selectedNode->GetNameString()}}, /*nodeAction = */ CommandSystem::CommandAnimGraphAdjustNodeGroup::NodeAction::Remove ); commandGroup.AddCommand(command); } nodeNames.emplace_back(selectedNode->GetName()); } if (!nodeNames.empty()) { nodeNames.pop_back(); } if (newNodeGroup) { auto* command = aznew CommandSystem::CommandAnimGraphAdjustNodeGroup( GetCommandManager()->FindCommand(CommandSystem::CommandAnimGraphAdjustNodeGroup::s_commandName), /*animGraphId = */ animGraph->GetID(), /*name = */ newNodeGroup->GetNameString(), /*visible = */ AZStd::nullopt, /*newName = */ AZStd::nullopt, /*nodeNames = */ nodeNames, /*nodeAction = */ CommandSystem::CommandAnimGraphAdjustNodeGroup::NodeAction::Add ); commandGroup.AddCommand(command); } AZStd::string outResult; if (!GetCommandManager()->ExecuteCommandGroup(commandGroup, outResult)) { AZ_Error("EMotionFX", false, outResult.c_str()); } } bool BlendGraphWidget::PreparePainting() { // skip rendering in case rendering is disabled if (m_plugin->GetDisableRendering()) { return false; } if (m_activeGraph) { // enable or disable graph animation m_activeGraph->SetUseAnimation(m_plugin->GetAnimGraphOptions().GetGraphAnimation()); } // pass down the show fps options flag NodeGraphWidget::SetShowFPS(m_plugin->GetAnimGraphOptions().GetShowFPS()); return true; } // enable or disable node visualization void BlendGraphWidget::OnVisualizeToggle(GraphNode* node, bool visualizeEnabled) { //if (node->GetType() == BlendTreeVisualNode::TYPE_ID) { BlendTreeVisualNode* blendNode = static_cast<BlendTreeVisualNode*>(node); blendNode->GetEMFXNode()->SetVisualization(visualizeEnabled); } } // enable or disable the node void BlendGraphWidget::OnEnabledToggle(GraphNode* node, bool enabled) { if (node->GetType() == BlendTreeVisualNode::TYPE_ID) { BlendTreeVisualNode* blendNode = static_cast<BlendTreeVisualNode*>(node); blendNode->GetEMFXNode()->SetIsEnabled(enabled); } } // change visualize options void BlendGraphWidget::OnSetupVisualizeOptions(GraphNode* node) { BlendTreeVisualNode* blendNode = static_cast<BlendTreeVisualNode*>(node); m_plugin->GetActionManager().ShowNodeColorPicker(blendNode->GetEMFXNode()); } bool BlendGraphWidget::event(QEvent* event) { if (event->type() == QEvent::ToolTip) { QHelpEvent* helpEvent = static_cast<QHelpEvent*>(event); QFontMetrics fontMetrics(QToolTip::font()); QFont boldFont = QToolTip::font(); boldFont.setBold(true); QFontMetrics boldFontMetrics(boldFont); if (m_activeGraph) { AZStd::string toolTipString; QPoint localPos = helpEvent->pos(); QPoint globalPos = LocalToGlobal(localPos); QPoint tooltipPos = helpEvent->globalPos(); // find the connection at the mouse position NodeConnection* connection = m_activeGraph->FindConnection(globalPos); if (connection) { bool conditionFound = false; if (connection->GetType() == StateConnection::TYPE_ID) { StateConnection* stateConnection = static_cast<StateConnection*>(connection); EMotionFX::AnimGraphTransitionCondition* condition = stateConnection->FindCondition(globalPos); if (condition) { AZStd::string tempConditionString; condition->GetTooltip(&tempConditionString); toolTipString = "<qt>"; toolTipString += tempConditionString; toolTipString += "</qt>"; conditionFound = true; } } // get the output and the input port numbers const AZ::u16 outputPortNr = connection->GetOutputPortNr(); const AZ::u16 inputPortNr = connection->GetInputPortNr(); // show connection or state transition tooltip if (conditionFound == false) { GraphNode* sourceNode = connection->GetSourceNode(); GraphNode* targetNode = connection->GetTargetNode(); // prepare the colors QColor sourceColor, targetColor; if (sourceNode) { sourceColor = sourceNode->GetBaseColor(); } if (targetNode) { targetColor = targetNode->GetBaseColor(); } // prepare the node names AZStd::string sourceNodeName, targetNodeName; if (sourceNode) { sourceNodeName = sourceNode->GetName(); } if (targetNode) { targetNodeName = targetNode->GetName(); } //sourceNodeName.ConvertToNonBreakingHTMLSpaces(); //targetNodeName.ConvertToNonBreakingHTMLSpaces(); // check if we are dealing with a node inside a blend tree if (sourceNode && sourceNode->GetType() == BlendTreeVisualNode::TYPE_ID) { // type cast it to a blend graph node and get the corresponding emfx node BlendTreeVisualNode* blendSourceNode = static_cast<BlendTreeVisualNode*>(sourceNode); EMotionFX::AnimGraphNode* sourceEMFXNode = blendSourceNode->GetEMFXNode(); // prepare the port names AZStd::string outputPortName, inputPortName; if (sourceNode) { outputPortName = sourceNode->GetOutputPort(outputPortNr)->GetName(); } if (targetNode) { inputPortName = targetNode->GetInputPort(inputPortNr)->GetName(); } //outputPortName.ConvertToNonBreakingHTMLSpaces(); //inputPortName.ConvertToNonBreakingHTMLSpaces(); int columnSourceWidth = boldFontMetrics.horizontalAdvance(sourceNodeName.c_str()) + boldFontMetrics.horizontalAdvance(" ") + fontMetrics.horizontalAdvance("(Port: ") + fontMetrics.horizontalAdvance(outputPortName.c_str()) + fontMetrics.horizontalAdvance(")"); int columnTargetWidth = boldFontMetrics.horizontalAdvance(targetNodeName.c_str()) + boldFontMetrics.horizontalAdvance(" ") + fontMetrics.horizontalAdvance("(Port: ") + fontMetrics.horizontalAdvance(inputPortName.c_str()) + fontMetrics.horizontalAdvance(")"); // construct the html tooltip string toolTipString += AZStd::string::format("<qt><table border=\"0\"><tr><td width=\"%i\"><p style=\"color:rgb(%i,%i,%i)\"><b>%s </b>(Port: %s)</p></td> <td>to</td> <td width=\"%i\"><p style=\"color:rgb(%i,%i,%i)\"><b>%s </b>(Port: %s)</p></td></tr>", columnSourceWidth, sourceColor.red(), sourceColor.green(), sourceColor.blue(), sourceNodeName.c_str(), outputPortName.c_str(), columnTargetWidth, targetColor.red(), targetColor.green(), targetColor.blue(), targetNodeName.c_str(), inputPortName.c_str()); // now check if the connection is coming from a parameter node if (azrtti_typeid(sourceEMFXNode) == azrtti_typeid<EMotionFX::BlendTreeParameterNode>()) { EMotionFX::BlendTreeParameterNode* parameterNode = static_cast<EMotionFX::BlendTreeParameterNode*>(sourceEMFXNode); // get the parameter index from the port where the connection starts uint32 parameterIndex = parameterNode->GetParameterIndex(outputPortNr); if (parameterIndex != MCORE_INVALIDINDEX32) { // get access to the parameter name and add it to the tool tip EMotionFX::AnimGraph* animGraph = parameterNode->GetAnimGraph(); const EMotionFX::Parameter* parameter = animGraph->FindValueParameter(parameterIndex); toolTipString += "\n<qt><table border=\"0\"><tr>"; toolTipString += AZStd::string::format("<td><p style=\"color:rgb(80, 80, 80)\"><b>Parameter:</b></p></td><td><p style=\"color:rgb(115, 115, 115)\">%s</p></td>", parameter->GetName().c_str()); toolTipString += "</tr></table></qt>"; } } } // state machine node else { toolTipString = "<qt><table><tr>"; // construct the html tooltip string if (sourceNode && targetNode) { toolTipString += AZStd::string::format("<td width=\"%i\"><b><p style=\"color:rgb(%i,%i,%i)\">%s</p></b></td> <td>to</td> <td width=\"%i\"><b><nobr><p style=\"color:rgb(%i,%i,%i)\">%s</p></nobr></b></td>", boldFontMetrics.horizontalAdvance(sourceNodeName.c_str()), sourceColor.red(), sourceColor.green(), sourceColor.blue(), sourceNodeName.c_str(), boldFontMetrics.horizontalAdvance(targetNodeName.c_str()), targetColor.red(), targetColor.green(), targetColor.blue(), targetNodeName.c_str()); } else if (targetNode) { toolTipString += AZStd::string::format("<td>to</td> <td width=\"%i\"><b><p style=\"color:rgb(%i,%i,%i)\">%s</p></b></td>", boldFontMetrics.horizontalAdvance(targetNodeName.c_str()), targetColor.red(), targetColor.green(), targetColor.blue(), targetNodeName.c_str()); } toolTipString += "</tr></table></qt>"; } } } GraphNode* node = m_activeGraph->FindNode(localPos); EMotionFX::AnimGraphNode* animGraphNode = nullptr; if (node) { BlendTreeVisualNode* blendNode = static_cast<BlendTreeVisualNode*>(node); animGraphNode = blendNode->GetEMFXNode(); AZStd::string tempString; toolTipString = "<qt><table border=\"0\">"; // node name toolTipString += AZStd::string::format("<tr><td><b>Name:</b></td><td><nobr>%s</nobr></td></tr>", animGraphNode->GetName()); // node palette name toolTipString += AZStd::string::format("<tr><td><b>Type:</b></td><td><nobr>%s</nobr></td></tr>", animGraphNode->GetPaletteName()); if (animGraphNode->GetCanHaveChildren()) { // child nodes toolTipString += AZStd::string::format("<tr><td><b><nobr>Child Nodes:</nobr></b></td><td>%zu</td></tr>", animGraphNode->GetNumChildNodes()); // recursive child nodes toolTipString += AZStd::string::format("<tr><td width=\"140\"><b><nobr>Recursive Child Nodes:</nobr></b></td><td>%zu</td></tr>", animGraphNode->RecursiveCalcNumNodes()); } // states if (node->GetType() == StateGraphNode::TYPE_ID) { // get access to the state machine EMotionFX::AnimGraphStateMachine* stateMachine = nullptr; EMotionFX::AnimGraphNode* parentNode = animGraphNode->GetParentNode(); if (parentNode && azrtti_typeid(parentNode) == azrtti_typeid<EMotionFX::AnimGraphStateMachine>()) { stateMachine = static_cast<EMotionFX::AnimGraphStateMachine*>(parentNode); } // incoming transitions toolTipString += AZStd::string::format("<tr><td><b>Incoming Transitions:</b></td><td>%i</td></tr>", stateMachine->CalcNumIncomingTransitions(animGraphNode)); // outgoing transitions toolTipString += AZStd::string::format("<tr><td width=\"130\"><b>Outgoing Transitions:</b></td><td>%i</td></tr>", stateMachine->CalcNumOutgoingTransitions(animGraphNode)); } // complete the table toolTipString += "</table></qt>"; } if (!toolTipString.empty()) { QRect toolTipRect(globalPos.x() - 4, globalPos.y() - 4, 8, 8); QToolTip::showText(tooltipPos, toolTipString.c_str(), this, toolTipRect); } return NodeGraphWidget::event(event); } } return NodeGraphWidget::event(event); } void BlendGraphWidget::ReplaceTransition(NodeConnection* connection, QPoint oldStartOffset, QPoint oldEndOffset, GraphNode* oldSourceNode, GraphNode* oldTargetNode, GraphNode* newSourceNode, GraphNode* newTargetNode) { if (connection->GetType() != StateConnection::TYPE_ID) { return; } StateConnection* stateConnection = static_cast<StateConnection*>(connection); EMotionFX::AnimGraphStateTransition* transition = connection->GetModelIndex().data(AnimGraphModel::ROLE_TRANSITION_POINTER).value<EMotionFX::AnimGraphStateTransition*>(); AZStd::optional<AZStd::string> newSourceNodeName = AZStd::nullopt; if (newSourceNode) { newSourceNodeName = newSourceNode->GetNameString(); } AZStd::optional<AZStd::string> newTargetNodeName = AZStd::nullopt; if (newTargetNode) { newTargetNodeName = newTargetNode->GetNameString(); } const AZ::s32 newStartOffsetX = transition->GetVisualStartOffsetX(); const AZ::s32 newStartOffsetY = transition->GetVisualStartOffsetY(); const AZ::s32 newEndOffsetX = transition->GetVisualEndOffsetX(); const AZ::s32 newEndOffsetY = transition->GetVisualEndOffsetY(); m_activeGraph->StopReplaceTransitionHead(); m_activeGraph->StopReplaceTransitionTail(); // Reset the visual transition before calling the actual command so that undo captures the right previous values. stateConnection->SetSourceNode(oldSourceNode); stateConnection->SetTargetNode(oldTargetNode); transition->SetVisualOffsets(oldStartOffset.x(), oldStartOffset.y(), oldEndOffset.x(), oldEndOffset.y()); if (m_activeGraph->GetReplaceTransitionValid()) { CommandSystem::AdjustTransition(transition, /*isDisabled=*/AZStd::nullopt, newSourceNodeName, newTargetNodeName, newStartOffsetX, newStartOffsetY, newEndOffsetX, newEndOffsetY); } } void BlendGraphWidget::OnRowsInserted(const QModelIndex& parent, int first, int last) { // Here we could be receiving connections, transitions or nodes being inserted into // the model. // For nodes, we need to locate the parent NodeGraph and insert elements. // For connections, we need to locate the parent Node. With the parent node, we can // locate the parent NodeGraph // For transitions, the parent index is the state machine therefore we can locate // the parent NodeGraph directly. // So, only for connections we need to do something special. For transitions and nodes // we just locate the NodeGraph through the parent index. For connections we locate the // parent index of "parent" and then use that to locate the NodeGraph. // We only update if we have the NodeGraph cached, if the NodeGraph is not cached, next // time that we focus on it, it will create the whole structure. if (parent.isValid()) { const QModelIndex grandParent = parent.model()->parent(parent); NodeGraphByModelIndex::iterator itGrandParent = m_nodeGraphByModelIndex.find(grandParent); NodeGraphByModelIndex::iterator itParent = m_nodeGraphByModelIndex.find(parent); if (itGrandParent == m_nodeGraphByModelIndex.end() && itParent == m_nodeGraphByModelIndex.end()) { return; // early out if we dont have any of those cached } QModelIndexList modelIndexesForGrandParent; QModelIndexList modelIndexesForParent; for (int row = first; row <= last; ++row) { const QModelIndex childModelIndex = parent.model()->index(row, 0, parent); const AnimGraphModel::ModelItemType type = childModelIndex.data(AnimGraphModel::ROLE_MODEL_ITEM_TYPE).value<AnimGraphModel::ModelItemType>(); switch (type) { case AnimGraphModel::ModelItemType::NODE: case AnimGraphModel::ModelItemType::TRANSITION: default: modelIndexesForParent.push_back(childModelIndex); break; case AnimGraphModel::ModelItemType::CONNECTION: modelIndexesForGrandParent.push_back(childModelIndex); break; } } if (!modelIndexesForGrandParent.empty() && itGrandParent != m_nodeGraphByModelIndex.end()) { itGrandParent->second->OnRowsInserted(modelIndexesForGrandParent); } if (!modelIndexesForParent.empty() && itParent != m_nodeGraphByModelIndex.end()) { itParent->second->OnRowsInserted(modelIndexesForParent); } } } void BlendGraphWidget::OnRowsAboutToBeRemoved(const QModelIndex& parent, int first, int last) { // Remove the graphs, if it is not in our cache, then it is not removed, if it is, its removed if (parent.isValid()) { const QModelIndex grandParent = parent.model()->parent(parent); NodeGraphByModelIndex::iterator itGrandParent = m_nodeGraphByModelIndex.find(grandParent); NodeGraphByModelIndex::iterator itParent = m_nodeGraphByModelIndex.find(parent); if (itGrandParent == m_nodeGraphByModelIndex.end() && itParent == m_nodeGraphByModelIndex.end()) { return; // early out if we dont have any of those cached } QModelIndexList modelIndexesForGrandParent; QModelIndexList modelIndexesForParent; for (int row = first; row <= last; ++row) { const QModelIndex childModelIndex = parent.model()->index(row, 0, parent); const AnimGraphModel::ModelItemType type = childModelIndex.data(AnimGraphModel::ROLE_MODEL_ITEM_TYPE).value<AnimGraphModel::ModelItemType>(); switch (type) { case AnimGraphModel::ModelItemType::NODE: case AnimGraphModel::ModelItemType::TRANSITION: default: modelIndexesForParent.push_back(childModelIndex); break; case AnimGraphModel::ModelItemType::CONNECTION: modelIndexesForGrandParent.push_back(childModelIndex); break; } } if (!modelIndexesForGrandParent.empty() && itGrandParent != m_nodeGraphByModelIndex.end()) { itGrandParent->second->OnRowsAboutToBeRemoved(modelIndexesForGrandParent); } if (!modelIndexesForParent.empty() && itParent != m_nodeGraphByModelIndex.end()) { itParent->second->OnRowsAboutToBeRemoved(modelIndexesForParent); } // Check if we have any node graph stored for those nodes for (const QModelIndex& modelIndex : modelIndexesForParent) { m_nodeGraphByModelIndex.erase(modelIndex); } } } void BlendGraphWidget::OnDataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight, const QVector<int>& roles) { const QItemSelectionRange range(topLeft, bottomRight); const QModelIndexList changedIndexes = range.indexes(); for (const QModelIndex& changed : changedIndexes) { QModelIndex parentGraph = changed.model()->parent(changed); const AnimGraphModel::ModelItemType itemType = changed.data(AnimGraphModel::ROLE_MODEL_ITEM_TYPE).value<AnimGraphModel::ModelItemType>(); if (itemType == AnimGraphModel::ModelItemType::CONNECTION) { parentGraph = parentGraph.model()->parent(parentGraph); } NodeGraphByModelIndex::iterator itParent = m_nodeGraphByModelIndex.find(parentGraph); if (itParent != m_nodeGraphByModelIndex.end()) // otherwise we dont have the graph cached { itParent->second->OnDataChanged(changed, roles); } } } void BlendGraphWidget::OnFocusChanged(const QModelIndex& newFocusIndex, const QModelIndex& newFocusParent, const QModelIndex& oldFocusIndex, const QModelIndex& oldFocusParent) { AZ_UNUSED(oldFocusIndex); if (newFocusParent.isValid()) { if (newFocusParent != oldFocusParent) { // Parent changed, we need to dive into that parent AZStd::pair<NodeGraphByModelIndex::iterator, bool> inserted = m_nodeGraphByModelIndex.emplace(newFocusParent, AZStd::make_unique<NodeGraph>(newFocusParent, this)); NodeGraph& nodeGraph = *inserted.first->second; if (inserted.second) { nodeGraph.Reinit(); } SetActiveGraph(&nodeGraph); } if (newFocusIndex != newFocusParent) { // We are focusing on a node inside a blendtree/statemachine/referencenode GraphNode* graphNode = m_activeGraph->FindGraphNode(newFocusIndex); m_activeGraph->ZoomOnRect(graphNode->GetRect(), geometry().width(), geometry().height(), true); } } else { SetActiveGraph(nullptr); } } } // namespace EMStudio #include <EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/moc_BlendGraphWidget.cpp>
43.995352
528
0.58866
[ "geometry", "object", "vector", "model", "3d" ]
293ed06675ae9e62a92822a6b3f298deff5d5061
1,883
cpp
C++
dynamic programming/leet_Code_Dynamic_Programming/5_longest_palindromic_substring.cpp
Hadleyhzy/data_structure_and_algorithm
0e610ba78dcb216323d9434a0f182756780ce5c0
[ "MIT" ]
1
2020-10-12T19:18:19.000Z
2020-10-12T19:18:19.000Z
dynamic programming/leet_Code_Dynamic_Programming/5_longest_palindromic_substring.cpp
Hadleyhzy/data_structure_and_algorithm
0e610ba78dcb216323d9434a0f182756780ce5c0
[ "MIT" ]
null
null
null
dynamic programming/leet_Code_Dynamic_Programming/5_longest_palindromic_substring.cpp
Hadleyhzy/data_structure_and_algorithm
0e610ba78dcb216323d9434a0f182756780ce5c0
[ "MIT" ]
1
2020-10-12T19:18:04.000Z
2020-10-12T19:18:04.000Z
// // 5_longest_palindromic_substring.cpp // leet_Code_Dynamic_Programming // // Created by Hadley on 14.07.20. // Copyright © 2020 Hadley. All rights reserved. // #include <stdio.h> #include <algorithm> #include <iostream> #include <vector> #include <string> #include <unordered_map> #include <stack> #include <cstring> #include <queue> #include <functional> #include <numeric> using namespace std; class Solution { public: string longString(string s){ if(s.size()==1)return s; for(auto l=s.size();l>1;l--){ for(int i=0;i<=s.size()-l;i++){ string temp=s.substr(i,l); string rtemp=temp; reverse(rtemp.begin(), rtemp.end()); if(temp==rtemp)return temp; } } return string(1,s[0]); } string longestPalindrome(string s) { if(s.empty())return ""; return longString(s); } }; class Solution1 { public: string longestPalindrome(string s) { if(s.empty())return ""; bool table[s.size()][s.size()]; memset(table, false, sizeof(table)); int max_length=1; int start_index=0; for(int i=0;i<s.size();i++){ table[i][i]=true; } for(int i=0;i<s.size()-1;i++){ if(s[i]==s[i+1]){ table[i][i+1]=true; max_length=2; start_index=i; } } for(int l=3;l<=s.size();l++){ for(int i=0;i<s.size()-l+1;i++){ if(table[i+1][i+l-2]&&s[i]==s[i+l-1]){ table[i][i+l-1]=true; if(l>max_length){ max_length=l; start_index=i; } } } } return s.substr(start_index,max_length); } };
23.5375
54
0.47743
[ "vector" ]
2940f8a886b07f571b6fcfeca9761524e458c1e0
14,230
cpp
C++
src/test/operators/delete_test.cpp
youri-k/hyrise
cafd12ed3dc9da425b0139ad68d95a86cd9fc91c
[ "MIT" ]
null
null
null
src/test/operators/delete_test.cpp
youri-k/hyrise
cafd12ed3dc9da425b0139ad68d95a86cd9fc91c
[ "MIT" ]
null
null
null
src/test/operators/delete_test.cpp
youri-k/hyrise
cafd12ed3dc9da425b0139ad68d95a86cd9fc91c
[ "MIT" ]
null
null
null
#include <limits> #include <memory> #include <string> #include <utility> #include <vector> #include "base_test.hpp" #include "concurrency/transaction_context.hpp" #include "hyrise.hpp" #include "operators/delete.hpp" #include "operators/get_table.hpp" #include "operators/insert.hpp" #include "operators/print.hpp" #include "operators/table_scan.hpp" #include "operators/table_wrapper.hpp" #include "operators/update.hpp" #include "operators/validate.hpp" #include "statistics/table_statistics.hpp" #include "storage/table.hpp" #include "types.hpp" namespace opossum { class OperatorsDeleteTest : public BaseTest { protected: void SetUp() override { _table_name = "table_a"; _table2_name = "table_b"; _table = load_table("resources/test_data/tbl/int_float.tbl"); _table2 = load_table("resources/test_data/tbl/int_int3.tbl", 3); // Delete Operator works with the Storage Manager, so the test table must also be known to the StorageManager Hyrise::get().storage_manager.add_table(_table_name, _table); Hyrise::get().storage_manager.add_table(_table2_name, _table2); } std::string _table_name, _table2_name; std::shared_ptr<Table> _table, _table2; void helper(bool commit); }; void OperatorsDeleteTest::helper(bool commit) { auto transaction_context = Hyrise::get().transaction_manager.new_transaction_context(AutoCommit::No); // Selects two out of three rows. auto gt = std::make_shared<GetTable>(_table_name); gt->execute(); auto table_scan = create_table_scan(gt, ColumnID{1}, PredicateCondition::GreaterThan, 456.7f); table_scan->execute(); auto delete_op = std::make_shared<Delete>(table_scan); delete_op->set_transaction_context(transaction_context); delete_op->execute(); EXPECT_EQ(_table->get_chunk(ChunkID{0})->mvcc_data()->get_tid(0u), transaction_context->transaction_id()); EXPECT_EQ(_table->get_chunk(ChunkID{0})->mvcc_data()->get_tid(1u), 0u); EXPECT_EQ(_table->get_chunk(ChunkID{0})->mvcc_data()->get_tid(2u), transaction_context->transaction_id()); auto expected_end_cid = CommitID{0u}; if (commit) { transaction_context->commit(); expected_end_cid = transaction_context->commit_id(); } else { transaction_context->rollback(RollbackReason::User); expected_end_cid = MvccData::MAX_COMMIT_ID; } EXPECT_EQ(_table->get_chunk(ChunkID{0})->mvcc_data()->get_end_cid(0u), expected_end_cid); EXPECT_EQ(_table->get_chunk(ChunkID{0})->mvcc_data()->get_end_cid(1u), MvccData::MAX_COMMIT_ID); EXPECT_EQ(_table->get_chunk(ChunkID{0})->mvcc_data()->get_end_cid(2u), expected_end_cid); auto expected_tid = commit ? transaction_context->transaction_id() : 0u; EXPECT_EQ(_table->get_chunk(ChunkID{0})->mvcc_data()->get_tid(0u), expected_tid); EXPECT_EQ(_table->get_chunk(ChunkID{0})->mvcc_data()->get_tid(1u), 0u); EXPECT_EQ(_table->get_chunk(ChunkID{0})->mvcc_data()->get_tid(2u), expected_tid); } TEST_F(OperatorsDeleteTest, ExecuteAndCommit) { helper(true); } TEST_F(OperatorsDeleteTest, ExecuteAndAbort) { helper(false); } TEST_F(OperatorsDeleteTest, DetectDirtyWrite) { auto t1_context = Hyrise::get().transaction_manager.new_transaction_context(AutoCommit::No); auto t2_context = Hyrise::get().transaction_manager.new_transaction_context(AutoCommit::No); auto gt = std::make_shared<GetTable>(_table_name); gt->execute(); auto table_scan1 = create_table_scan(gt, ColumnID{0}, PredicateCondition::Equals, "123"); auto expected_result = create_table_scan(gt, ColumnID{0}, PredicateCondition::NotEquals, "123"); auto table_scan2 = create_table_scan(gt, ColumnID{0}, PredicateCondition::LessThan, "1234"); table_scan1->execute(); expected_result->execute(); table_scan2->execute(); EXPECT_EQ(table_scan1->get_output()->chunk_count(), 1u); EXPECT_EQ(table_scan1->get_output()->get_chunk(ChunkID{0})->column_count(), 2u); auto delete_op1 = std::make_shared<Delete>(table_scan1); delete_op1->set_transaction_context(t1_context); auto delete_op2 = std::make_shared<Delete>(table_scan2); delete_op2->set_transaction_context(t2_context); delete_op1->execute(); delete_op2->execute(); EXPECT_FALSE(delete_op1->execute_failed()); EXPECT_TRUE(delete_op2->execute_failed()); // Sneaking in a test for the OperatorPerformanceData here, which doesn't really make sense to be tested without an // operator: { const auto& performance_data_1 = delete_op1->performance_data(); EXPECT_TRUE(performance_data_1.executed); EXPECT_GT(performance_data_1.walltime.count(), 0); EXPECT_FALSE(performance_data_1.has_output); const auto& performance_data_2 = delete_op2->performance_data(); EXPECT_TRUE(performance_data_2.executed); EXPECT_GT(performance_data_2.walltime.count(), 0); EXPECT_FALSE(performance_data_2.has_output); } // MVCC commit. t1_context->commit(); t2_context->rollback(RollbackReason::Conflict); // Get validated table which should have only one row deleted. auto t_context = Hyrise::get().transaction_manager.new_transaction_context(AutoCommit::No); auto gt_post_delete = std::make_shared<GetTable>(_table_name); gt_post_delete->execute(); auto validate = std::make_shared<Validate>(gt_post_delete); validate->set_transaction_context(t_context); validate->execute(); EXPECT_TABLE_EQ_UNORDERED(validate->get_output(), expected_result->get_output()); } TEST_F(OperatorsDeleteTest, EmptyDelete) { auto tx_context_modification = Hyrise::get().transaction_manager.new_transaction_context(AutoCommit::No); auto gt = std::make_shared<GetTable>(_table_name); gt->execute(); auto table_scan = create_table_scan(gt, ColumnID{0}, PredicateCondition::Equals, "112233"); table_scan->execute(); EXPECT_EQ(table_scan->get_output()->chunk_count(), 0u); auto delete_op = std::make_shared<Delete>(table_scan); delete_op->set_transaction_context(tx_context_modification); delete_op->execute(); EXPECT_FALSE(delete_op->execute_failed()); // MVCC commit. tx_context_modification->commit(); // Get validated table which should be the original one auto tx_context_verification = Hyrise::get().transaction_manager.new_transaction_context(AutoCommit::No); auto gt_post_delete = std::make_shared<GetTable>(_table_name); gt_post_delete->execute(); auto validate = std::make_shared<Validate>(gt_post_delete); validate->set_transaction_context(tx_context_verification); validate->execute(); EXPECT_TABLE_EQ_UNORDERED(validate->get_output(), gt_post_delete->get_output()); } TEST_F(OperatorsDeleteTest, UpdateAfterDeleteFails) { auto t1_context = Hyrise::get().transaction_manager.new_transaction_context(AutoCommit::No); auto t2_context = Hyrise::get().transaction_manager.new_transaction_context(AutoCommit::No); auto gt = std::make_shared<GetTable>(_table_name); gt->execute(); auto validate1 = std::make_shared<Validate>(gt); validate1->set_transaction_context(t1_context); auto validate2 = std::make_shared<Validate>(gt); validate2->set_transaction_context(t2_context); validate1->execute(); validate2->execute(); auto delete_op = std::make_shared<Delete>(validate1); delete_op->set_transaction_context(t1_context); delete_op->execute(); t1_context->commit(); EXPECT_FALSE(delete_op->execute_failed()); // this update tries to update the values that have been deleted in another transaction and should fail. auto update_op = std::make_shared<Update>(_table_name, validate2, validate2); update_op->set_transaction_context(t2_context); update_op->execute(); EXPECT_TRUE(update_op->execute_failed()); t2_context->rollback(RollbackReason::Conflict); } TEST_F(OperatorsDeleteTest, DeleteOwnInsert) { // We are testing a couple of things here: // (1) When a transaction deletes a row that it inserted itself, it should no longer be visible to itself // (2) When that transaction rolls back, the row should be invisible to a second transaction // (3) The same should be the case if the transaction commits // For that purpose, we run the insert, delete, scan routine twice, once where we abort the transaction (inserted // and deleted value 456.7), and once where we commit it (inserted and deleted value 457.7) for (const auto value : {456.7f, 457.7f}) { auto context = Hyrise::get().transaction_manager.new_transaction_context(AutoCommit::No); auto values_to_insert = load_table("resources/test_data/tbl/int_float3.tbl"); auto table_name_for_insert = "bla"; Hyrise::get().storage_manager.add_table(table_name_for_insert, values_to_insert); auto insert_get_table = std::make_shared<GetTable>(table_name_for_insert); insert_get_table->execute(); auto insert = std::make_shared<Insert>(_table_name, insert_get_table); insert->set_transaction_context(context); insert->execute(); auto gt = std::make_shared<GetTable>(_table_name); gt->execute(); auto validate1 = std::make_shared<Validate>(gt); validate1->set_transaction_context(context); validate1->execute(); auto table_scan1 = create_table_scan(validate1, ColumnID{1}, PredicateCondition::Equals, value); table_scan1->execute(); EXPECT_EQ(table_scan1->get_output()->row_count(), 2); auto delete_op = std::make_shared<Delete>(table_scan1); delete_op->set_transaction_context(context); delete_op->execute(); auto gt_post_delete = std::make_shared<GetTable>(_table_name); gt_post_delete->execute(); auto validate2 = std::make_shared<Validate>(gt_post_delete); validate2->set_transaction_context(context); validate2->execute(); auto table_scan2 = create_table_scan(validate2, ColumnID{1}, PredicateCondition::Equals, value); table_scan2->execute(); EXPECT_EQ(table_scan2->get_output()->row_count(), 0); if (value == 456.7f) { context->rollback(RollbackReason::User); } else { context->commit(); } Hyrise::get().storage_manager.drop_table(table_name_for_insert); } { auto context = Hyrise::get().transaction_manager.new_transaction_context(AutoCommit::No); auto gt2 = std::make_shared<GetTable>(_table_name); gt2->execute(); auto validate1 = std::make_shared<Validate>(gt2); validate1->set_transaction_context(context); validate1->execute(); auto expected_result = load_table("resources/test_data/tbl/int_float_deleted.tbl"); EXPECT_TABLE_EQ_UNORDERED(validate1->get_output(), expected_result); context->rollback(RollbackReason::User); } } // This test uses the transaction context after its already been committed on behalf of every // read/write operator and the read only operators Validate and GetTable TEST_F(OperatorsDeleteTest, UseTransactionContextAfterCommit) { auto t1_context = Hyrise::get().transaction_manager.new_transaction_context(AutoCommit::No); auto gt = std::make_shared<GetTable>(_table_name); gt->execute(); auto validate1 = std::make_shared<Validate>(gt); validate1->set_transaction_context(t1_context); validate1->execute(); auto delete_op = std::make_shared<Delete>(validate1); delete_op->set_transaction_context(t1_context); delete_op->execute(); t1_context->commit(); auto delete_op2 = std::make_shared<Delete>(validate1); delete_op->set_transaction_context(t1_context); EXPECT_THROW(delete_op->execute(), std::logic_error); } TEST_F(OperatorsDeleteTest, RunOnUnvalidatedTable) { if (!HYRISE_DEBUG) GTEST_SKIP(); auto get_table = std::make_shared<GetTable>(_table_name); get_table->execute(); const auto table_scan = create_table_scan(get_table, ColumnID{0}, PredicateCondition::LessThan, 10000); table_scan->execute(); auto t1_context = Hyrise::get().transaction_manager.new_transaction_context(AutoCommit::No); auto delete_op1 = std::make_shared<Delete>(table_scan); delete_op1->set_transaction_context(t1_context); // This one works and deletes some rows delete_op1->execute(); t1_context->commit(); auto t2_context = Hyrise::get().transaction_manager.new_transaction_context(AutoCommit::No); auto delete_op2 = std::make_shared<Delete>(table_scan); delete_op2->set_transaction_context(t2_context); // This one should fail because the rows should have been filtered out by a validate and should not be visible // to the delete operator in the first place. EXPECT_THROW(delete_op2->execute(), std::logic_error); t2_context->rollback(RollbackReason::Conflict); } TEST_F(OperatorsDeleteTest, PrunedInputTable) { // Test that the input table of Delete can reference either a stored table or a pruned version of a stored table // (i.e., a table containing a subset of the chunks of the stored table) auto transaction_context = Hyrise::get().transaction_manager.new_transaction_context(AutoCommit::No); // Create the values_to_delete table via Chunk pruning and a Table Scan const auto get_table_op = std::make_shared<GetTable>("table_b", std::vector{ChunkID{1}}, std::vector<ColumnID>{}); get_table_op->execute(); const auto table_scan = create_table_scan(get_table_op, ColumnID{0}, PredicateCondition::LessThan, 5); table_scan->execute(); const auto delete_op = std::make_shared<Delete>(table_scan); delete_op->set_transaction_context(transaction_context); delete_op->execute(); EXPECT_FALSE(delete_op->execute_failed()); transaction_context->commit(); const auto expected_end_cid = transaction_context->commit_id(); EXPECT_EQ(_table2->get_chunk(ChunkID{0})->mvcc_data()->get_end_cid(0u), expected_end_cid); EXPECT_EQ(_table2->get_chunk(ChunkID{0})->mvcc_data()->get_end_cid(1u), expected_end_cid); EXPECT_EQ(_table2->get_chunk(ChunkID{0})->mvcc_data()->get_end_cid(2u), MvccData::MAX_COMMIT_ID); EXPECT_EQ(_table2->get_chunk(ChunkID{1})->mvcc_data()->get_end_cid(0u), MvccData::MAX_COMMIT_ID); EXPECT_EQ(_table2->get_chunk(ChunkID{1})->mvcc_data()->get_end_cid(1u), MvccData::MAX_COMMIT_ID); EXPECT_EQ(_table2->get_chunk(ChunkID{1})->mvcc_data()->get_end_cid(2u), MvccData::MAX_COMMIT_ID); EXPECT_EQ(_table2->get_chunk(ChunkID{2})->mvcc_data()->get_end_cid(0u), MvccData::MAX_COMMIT_ID); EXPECT_EQ(_table2->get_chunk(ChunkID{2})->mvcc_data()->get_end_cid(1u), expected_end_cid); } } // namespace opossum
38.048128
117
0.754111
[ "vector" ]
294667718744ee97007442d127c88d5aa494b2d1
3,892
cpp
C++
src/engine/dog.cpp
saltares/grannys-bloodbath
6c124ec77c19d81e81b2325bb633fd0d9c236c60
[ "MIT" ]
1
2018-12-31T12:44:57.000Z
2018-12-31T12:44:57.000Z
src/engine/dog.cpp
saltares/grannys-bloodbath
6c124ec77c19d81e81b2325bb633fd0d9c236c60
[ "MIT" ]
null
null
null
src/engine/dog.cpp
saltares/grannys-bloodbath
6c124ec77c19d81e81b2325bb633fd0d9c236c60
[ "MIT" ]
1
2018-12-31T12:45:02.000Z
2018-12-31T12:45:02.000Z
#include <iostream> #include <vector> #include <string> #include <SDL/SDL.h> #include "dog.h" #include "zombie.h" #include "parser.h" #include "resourcemngr.h" #include "granny.h" #include "enemy.h" using namespace std; Dog::Dog(Game *g):Enemy(g){ energy = 0; force = 0; } Dog::Dog(Game *g, const char *path, int x, int y):Enemy(g){ this->x = x; this->y = y; old_x = x; old_y = y; Parser parser(path); parser.get_attribute("code", parser.find("zombie"), &image_code); parser.get_attribute("vx", parser.find("zombie"), &vx); parser.get_attribute("vx", parser.find("zombie"), &vx0); parser.get_attribute("vy", parser.find("zombie"), &vy0); parser.get_attribute("energy", parser.find("zombie"), &energy); parser.get_attribute("force", parser.find("zombie"), &force); parser.get_attribute("attackdelay", parser.find("zombie"), &attack_delay); image = resource->image(image_code); parse_basic_info(parser); vector<ticpp::Element*> sounds; string code, situation; parser.find("sound", sounds, parser.find("sounds")); for(vector<ticpp::Element*>::iterator i = sounds.begin(); i != sounds.end(); ++i){ situation = parser.get_attribute("situation", *i); code = parser.get_attribute("code", *i); if(situation == "hurt"){ hurt = resource->sound(code); hurt_code = code; } } // Primero mira a la izquierda direction = true; } Dog::~Dog(){ } Actor* Dog::clone(int x1, int y1){ Dog *z = new Dog(g); z->image_code = image_code; z->image = resource->image(image_code); z->hurt_code = hurt_code; z->hurt = resource->sound(hurt_code); z->attack_delay = attack_delay; z->actual_delay = actual_delay; z->energy = energy; z->force = force; z->vx = vx; z->vy = vy; z->x = x1; z->y = y1; z->old_x = x1; z->old_y = y1; z->vx0 = vx0; z->vy0 = vy0; z->collision_map = collision_map; z->collision_map_inverted = collision_map_inverted; z->real_dimensions = real_dimensions; z->real_dimensions_inverted = real_dimensions_inverted; //Asignamos animaciones. for(Animations::iterator i = animations.begin(); i != animations.end(); ++i) z->animations[i->first] = new Animation(*(i->second)); return z; } void Dog::collides(Actor& a){ Granny *granny_aux; try{ granny_aux = static_cast<Granny*>(&a); }catch(const std::bad_cast e){ std::cout<<e.what()<<std::endl; } if(state != DAMAGED && state != DIE && state != ERASE){ --energy; if(energy > 0) state = DAMAGED; else state = DIE; } } void Dog::update(){ if(state != previous_state && state != ERASE){ previous_state = state; animations[state]->restart(); vy = 0; } switch(state){ case NORMAL: normal_state(); break; case JUMP: jumping_state(); break; case MOVE: moving_state(); break; case DAMAGED: damaged_state(); break; case DIE: death_state(); break; default: break; } } void Dog::normal_state(){ state = MOVE; } void Dog::moving_state(){ animations[MOVE]->update(); /*if(!g->on_ground(*this,x+(vx*10),y)){ if(direction) direction = false; else direction = true; vx = image->width()/2; }*/ /*if(direction){ if(!g->on_ground(*this, x-image->width()/2, y)){ change_direction(); } } else{ if(!g->on_ground(*this, x+image->width()*2, y)){ change_direction(); } }*/ if(direction){ if(!g->on_ground(*this, x-vx-20, y)){ change_direction(); } } else{ if(!g->on_ground(*this, x+vx+20, y)){ change_direction(); } } /*if(!g->on_ground(*this, x+vx, y)) direction = !direction;*/ if(direction) move(x-vx, y); else move(x+vx, y); vx = vx0; } void Dog::damaged_state(){ if(animations[DAMAGED]->update()) state = NORMAL; } void Dog::death_state(){ if(animations[DIE]->update()) state = ERASE; } void Dog::jumping_state(){ move(x,y+vy); vy+=2; if(vy >= vy0) vy = vy0; }
17.531532
83
0.623073
[ "vector" ]
29468fb9aceb3afc1712a1ed674df5b0cc3b6423
3,933
hpp
C++
hpx/runtime/agas/big_boot_barrier.hpp
McKillroy/hpx
f1bcb93f90a0b3c96e5fb3423028f0347f17f943
[ "BSL-1.0" ]
null
null
null
hpx/runtime/agas/big_boot_barrier.hpp
McKillroy/hpx
f1bcb93f90a0b3c96e5fb3423028f0347f17f943
[ "BSL-1.0" ]
null
null
null
hpx/runtime/agas/big_boot_barrier.hpp
McKillroy/hpx
f1bcb93f90a0b3c96e5fb3423028f0347f17f943
[ "BSL-1.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2011 Bryce Lelbach // Copyright (c) 2007-2017 Hartmut Kaiser // // SPDX-License-Identifier: BSL-1.0 // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) //////////////////////////////////////////////////////////////////////////////// #if !defined(HPX_0C9D09E0_725D_4FA6_A879_8226DE97C6B9) #define HPX_0C9D09E0_725D_4FA6_A879_8226DE97C6B9 #include <hpx/config.hpp> #if defined(HPX_HAVE_NETWORKING) #include <hpx/assertion.hpp> #include <hpx/synchronization/spinlock.hpp> #include <hpx/runtime.hpp> #include <hpx/runtime/naming/address.hpp> #include <hpx/runtime/parcelset_fwd.hpp> #include <hpx/util/connection_cache.hpp> #include <hpx/io_service/io_service_pool.hpp> #include <hpx/util_fwd.hpp> #include <boost/lockfree/queue.hpp> #include <condition_variable> #include <cstddef> #include <cstdint> #include <mutex> #include <string> #include <type_traits> #include <utility> #include <vector> #include <hpx/config/warnings_prefix.hpp> namespace hpx { namespace agas { struct notification_header; struct HPX_EXPORT big_boot_barrier { public: HPX_NON_COPYABLE(big_boot_barrier); private: parcelset::parcelport* pp; parcelset::endpoints_type const& endpoints; service_mode const service_type; parcelset::locality const bootstrap_agas; std::condition_variable cond; std::mutex mtx; std::size_t connected; boost::lockfree::queue<util::unique_function_nonser<void()>* > thunks; std::vector<parcelset::endpoints_type> localities; void spin(); void notify(); public: struct scoped_lock { private: big_boot_barrier& bbb; public: scoped_lock( big_boot_barrier& bbb_ ) : bbb(bbb_) { bbb.mtx.lock(); } ~scoped_lock() { bbb.notify(); } }; big_boot_barrier( parcelset::parcelport* pp_ , parcelset::endpoints_type const& endpoints_ , util::runtime_configuration const& ini_ ); ~big_boot_barrier() { util::unique_function_nonser<void()>* f; while (thunks.pop(f)) delete f; } parcelset::locality here() { return bootstrap_agas; } parcelset::endpoints_type const &get_endpoints() { return endpoints; } template <typename Action, typename... Args> void apply( std::uint32_t source_locality_id , std::uint32_t target_locality_id , parcelset::locality dest , Action act , Args &&... args); template <typename Action, typename... Args> void apply_late( std::uint32_t source_locality_id , std::uint32_t target_locality_id , parcelset::locality const & dest , Action act , Args &&... args); void apply_notification( std::uint32_t source_locality_id , std::uint32_t target_locality_id , parcelset::locality const& dest , notification_header&& hdr); void wait_bootstrap(); void wait_hosted(std::string const& locality_name, naming::address::address_type primary_ns_ptr, naming::address::address_type symbol_ns_ptr); // no-op on non-bootstrap localities void trigger(); void add_thunk(util::unique_function_nonser<void()>* f); void add_locality_endpoints(std::uint32_t locality_id, parcelset::endpoints_type const& endpoints); }; HPX_EXPORT void create_big_boot_barrier( parcelset::parcelport* pp_ , parcelset::endpoints_type const& endpoints_ , util::runtime_configuration const& ini_ ); HPX_EXPORT void destroy_big_boot_barrier(); HPX_EXPORT big_boot_barrier& get_big_boot_barrier(); }} #include <hpx/config/warnings_suffix.hpp> #endif #endif // HPX_0C9D09E0_725D_4FA6_A879_8226DE97C6B9
25.211538
80
0.661327
[ "vector" ]
294b9ecb8db553666fbdea0048fcdd60c0e33ee2
3,676
hxx
C++
generated/include/vnx/PlayerBase.hxx
madMAx43v3r/vnx-base
564928e6ed06f60b31bd8af88385caea522ab8ff
[ "Apache-2.0" ]
null
null
null
generated/include/vnx/PlayerBase.hxx
madMAx43v3r/vnx-base
564928e6ed06f60b31bd8af88385caea522ab8ff
[ "Apache-2.0" ]
2
2022-02-07T05:19:09.000Z
2022-03-24T18:44:37.000Z
generated/include/vnx/PlayerBase.hxx
madMAx43v3r/vnx-base
564928e6ed06f60b31bd8af88385caea522ab8ff
[ "Apache-2.0" ]
1
2022-01-22T21:30:26.000Z
2022-01-22T21:30:26.000Z
// AUTO GENERATED by vnxcppcodegen #ifndef INCLUDE_vnx_PlayerBase_HXX_ #define INCLUDE_vnx_PlayerBase_HXX_ #include <vnx/package.hxx> #include <vnx/Module.h> #include <vnx/RecordHeader.hxx> #include <vnx/TopicPtr.hpp> namespace vnx { class VNX_EXPORT PlayerBase : public ::vnx::Module { public: ::vnx::TopicPtr output_status = "vnx.player_status"; std::vector<std::string> files; int32_t interval_ms = 100; int32_t max_time_gap_ms = 5000; vnx::float64_t play_speed = 1; vnx::bool_t is_default_enable = true; vnx::bool_t is_blocking = false; vnx::bool_t is_repeat = false; vnx::bool_t is_autostart = false; vnx::bool_t is_autoclose = false; vnx::bool_t is_autoshutdown = false; std::map<::vnx::TopicPtr, ::vnx::TopicPtr> topic_map; typedef ::vnx::Module Super; static const vnx::Hash64 VNX_TYPE_HASH; static const vnx::Hash64 VNX_CODE_HASH; static constexpr uint64_t VNX_TYPE_ID = 0x18af8c0a3c1bbcull; PlayerBase(const std::string& _vnx_name); vnx::Hash64 get_type_hash() const override; std::string get_type_name() const override; const vnx::TypeCode* get_type_code() const override; void read(std::istream& _in) override; void write(std::ostream& _out) const override; template<typename T> void accept_generic(T& _visitor) const; void accept(vnx::Visitor& _visitor) const override; vnx::Object to_object() const override; void from_object(const vnx::Object& object) override; vnx::Variant get_field(const std::string& name) const override; void set_field(const std::string& name, const vnx::Variant& value) override; friend std::ostream& operator<<(std::ostream& _out, const PlayerBase& _value); friend std::istream& operator>>(std::istream& _in, PlayerBase& _value); static const vnx::TypeCode* static_get_type_code(); static std::shared_ptr<vnx::TypeCode> static_create_type_code(); protected: using Super::handle; virtual ::vnx::RecordHeader get_info() const = 0; virtual void play() = 0; virtual void pause() = 0; virtual void toggle() = 0; virtual void stop() = 0; virtual void set_speed(const vnx::float64_t& speed) = 0; virtual void seek_by_count(const int64_t& delta_count) = 0; virtual void seek_by_time(const int64_t& delta_us) = 0; virtual void seek_to_position(const vnx::float64_t& position) = 0; virtual void seek_to_time(const int64_t& time_us) = 0; void vnx_handle_switch(std::shared_ptr<const vnx::Value> _value) override; std::shared_ptr<vnx::Value> vnx_call_switch(std::shared_ptr<const vnx::Value> _method, const vnx::request_id_t& _request_id) override; }; template<typename T> void PlayerBase::accept_generic(T& _visitor) const { _visitor.template type_begin<PlayerBase>(12); _visitor.type_field("output_status", 0); _visitor.accept(output_status); _visitor.type_field("files", 1); _visitor.accept(files); _visitor.type_field("interval_ms", 2); _visitor.accept(interval_ms); _visitor.type_field("max_time_gap_ms", 3); _visitor.accept(max_time_gap_ms); _visitor.type_field("play_speed", 4); _visitor.accept(play_speed); _visitor.type_field("is_default_enable", 5); _visitor.accept(is_default_enable); _visitor.type_field("is_blocking", 6); _visitor.accept(is_blocking); _visitor.type_field("is_repeat", 7); _visitor.accept(is_repeat); _visitor.type_field("is_autostart", 8); _visitor.accept(is_autostart); _visitor.type_field("is_autoclose", 9); _visitor.accept(is_autoclose); _visitor.type_field("is_autoshutdown", 10); _visitor.accept(is_autoshutdown); _visitor.type_field("topic_map", 11); _visitor.accept(topic_map); _visitor.template type_end<PlayerBase>(12); } } // namespace vnx namespace vnx { } // vnx #endif // INCLUDE_vnx_PlayerBase_HXX_
33.724771
135
0.758977
[ "object", "vector" ]
294bcd70fb02178e733632cd98aa9f345daf6832
7,585
cpp
C++
MeshTools/FEElementData.cpp
chunkeey/FEBioStudio
f342d4ac2bc3581db792373c4265454109af92b3
[ "MIT" ]
27
2020-06-25T06:34:52.000Z
2022-03-11T08:58:57.000Z
MeshTools/FEElementData.cpp
chunkeey/FEBioStudio
f342d4ac2bc3581db792373c4265454109af92b3
[ "MIT" ]
42
2020-06-15T18:40:57.000Z
2022-03-24T05:38:54.000Z
MeshTools/FEElementData.cpp
chunkeey/FEBioStudio
f342d4ac2bc3581db792373c4265454109af92b3
[ "MIT" ]
12
2020-06-27T13:58:57.000Z
2022-03-24T05:39:10.000Z
/*This file is part of the FEBio Studio source code and is licensed under the MIT license listed below. See Copyright-FEBio-Studio.txt for details. Copyright (c) 2020 University of Utah, The Trustees of Columbia University in the City of New York, and others. 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 "stdafx.h" #include "FEElementData.h" #include <MeshLib/FEMesh.h> #include <GeomLib/GObject.h> #include "GModel.h" #include "GGroup.h" //----------------------------------------------------------------------------- FEElementData::FEElementData(FEMesh* mesh) : FEMeshData(FEMeshData::ELEMENT_DATA) { m_scale = 1.0; m_part = nullptr; SetMesh(mesh); } //----------------------------------------------------------------------------- void FEElementData::Create(FEMesh* pm, FEPart* part, FEMeshData::DATA_TYPE dataType) { SetMesh(pm); m_part = part; m_data.assign(part->size(), 0.0); } //----------------------------------------------------------------------------- FEElementData::FEElementData(const FEElementData& d) : FEMeshData(FEMeshData::ELEMENT_DATA) { SetMesh(d.GetMesh()); SetName(d.GetName()); m_data = d.m_data; m_part = d.m_part; } //----------------------------------------------------------------------------- FEElementData& FEElementData::operator = (const FEElementData& d) { SetName(d.GetName()); SetMesh(d.GetMesh()); m_data = d.m_data; m_part = d.m_part; return (*this); } //----------------------------------------------------------------------------- void FEElementData::FillRandomBox(double fmin, double fmax) { int N = (int)m_data.size(); for (int i = 0; i<N; ++i) { double f = (double)rand() / (double)RAND_MAX; double v = fmin + (fmax - fmin)*f; m_data[i] = v; } } //----------------------------------------------------------------------------- void FEElementData::SetScaleFactor(double s) { m_scale = s; } //----------------------------------------------------------------------------- double FEElementData::GetScaleFactor() const { return m_scale; } //----------------------------------------------------------------------------- void FEElementData::Save(OArchive& ar) { const string& dataName = GetName(); const char* szname = dataName.c_str(); ar.WriteChunk(CID_MESH_DATA_NAME, szname); ar.WriteChunk(CID_MESH_DATA_TYPE, (int)m_dataType); ar.WriteChunk(CID_MESH_DATA_SCALE, m_scale); // Parts must be saved first so that the number of elements in the part can be // queried before the data is read during the load operation. ar.BeginChunk(CID_MESH_DATA_PART); { m_part->Save(ar); } ar.EndChunk(); int NE = m_part->size(); ar.WriteChunk(CID_MESH_DATA_VALUES, &m_data[0], NE); } //----------------------------------------------------------------------------- void FEElementData::Load(IArchive& ar) { GObject* po = GetMesh()->GetGObject(); while (IArchive::IO_OK == ar.OpenChunk()) { int nid = ar.GetChunkID(); if (nid == CID_MESH_DATA_NAME) { char szname[256]; ar.read(szname); SetName(szname); } else if (nid == CID_MESH_DATA_TYPE) { int dType; ar.read(dType); m_dataType = (FEMeshData::DATA_TYPE) dType; } else if (nid == CID_MESH_DATA_SCALE) { ar.read(m_scale); } else if (nid == CID_MESH_DATA_PART) { m_part = new FEPart(po); m_part->Load(ar); } else if (nid == CID_MESH_DATA_VALUES) { int NE = m_part->size(); m_data.resize(NE); ar.read(&m_data[0], NE); } ar.CloseChunk(); } } //============================================================================= FEPartData::FEPartData(FEMesh* mesh) : FEMeshData(FEMeshData::PART_DATA) { SetMesh(mesh); m_maxElemItems = 1; } FEPartData::FEPartData(const FEPartData& d) : FEMeshData(FEMeshData::PART_DATA) { } FEPartData& FEPartData::operator = (const FEPartData& d) { return *this; } // create a data field bool FEPartData::Create(const vector<int>& partList, FEMeshData::DATA_TYPE dataType, FEMeshData::DATA_FORMAT dataFmt) { FEMesh* mesh = GetMesh(); assert(mesh); m_data.clear(); m_part = partList; int NE = mesh->Elements(); int maxNodes = 0; int nsize = 0; for (int i = 0; i < partList.size(); ++i) { int pid = partList[i]; for (int i = 0; i < NE; ++i) { FEElement& el = mesh->Element(i); if (el.m_gid == pid) { int nn = el.Nodes(); if (nn > maxNodes) maxNodes = nn; nsize++; } } } m_dataFmt = dataFmt; if (dataFmt == DATA_ITEM) { m_maxElemItems = 1; } else if (dataFmt == DATA_MULT) { m_maxElemItems = maxNodes; nsize *= maxNodes; } m_data.resize(nsize); return true; } FEElemList* FEPartData::BuildElemList() { FEMesh* mesh = GetMesh(); assert(mesh); FEElemList* elemList = new FEElemList; int NE = mesh->Elements(); for (int i = 0; i < m_part.size(); ++i) { int pid = m_part[i]; for (int j = 0; j < NE; ++j) { FEElement& el = mesh->Element(j); if (el.m_gid == pid) { elemList->Add(mesh, &el, j); } } } return elemList; } GPartList* FEPartData::GetPartList(FEModel* fem) { GObject* po = GetMesh()->GetGObject(); GPartList* partList = new GPartList(fem); for (int i = 0; i < m_part.size(); ++i) { GPart* pg = po->Part(m_part[i]); partList->add(pg->GetID()); } return partList; } // size of data field int FEPartData::Size() const { return (int)m_data.size(); } void FEPartData::Save(OArchive& ar) { const string& dataName = GetName(); const char* szname = dataName.c_str(); ar.WriteChunk(CID_MESH_DATA_NAME, szname); ar.WriteChunk(CID_MESH_DATA_TYPE, (int)m_dataType); ar.WriteChunk(CID_MESH_DATA_FORMAT, (int)m_dataFmt); ar.WriteChunk(CID_MESH_DATA_DPI, (int)m_maxElemItems); // Parts must be saved first so that the number of elements in the part can be // queried before the data is read during the load operation. ar.WriteChunk(CID_MESH_DATA_PART, m_part); ar.WriteChunk(CID_MESH_DATA_VALUES, m_data); } void FEPartData::Load(IArchive& ar) { GObject* po = GetMesh()->GetGObject(); while (IArchive::IO_OK == ar.OpenChunk()) { int nid = ar.GetChunkID(); if (nid == CID_MESH_DATA_NAME) { char szname[256]; ar.read(szname); SetName(szname); } else if (nid == CID_MESH_DATA_TYPE) { int dType; ar.read(dType); m_dataType = (FEMeshData::DATA_TYPE) dType; } else if (nid == CID_MESH_DATA_FORMAT) { int fType; ar.read(fType); m_dataFmt = (FEMeshData::DATA_FORMAT) fType; } else if (nid == CID_MESH_DATA_DPI) { ar.read(m_maxElemItems); } else if (nid == CID_MESH_DATA_PART) { ar.read(m_part); } else if (nid == CID_MESH_DATA_VALUES) { ar.read(m_data); } ar.CloseChunk(); } }
24.626623
117
0.617535
[ "mesh", "vector" ]
294dce89a745e6bc238aa3147c5ab7c8876bd667
3,796
cpp
C++
codeforces/E - Company/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
codeforces/E - Company/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
codeforces/E - Company/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: kzvd4729 created: Nov/15/2018 20:15 * solution_verdict: Accepted language: GNU C++14 * run_time: 561 ms memory_used: 25200 KB * problem: https://codeforces.com/contest/1062/problem/E ****************************************************************************************/ #include<bits/stdc++.h> #define long long long using namespace std; const int N=1e5; int n,sp[N+2][22],parent[N+2],level[N+2]; int ent[N+2],tim; vector<int>adj[N+2]; struct segment { int vl,id; }seg_mn[5*N+2],seg_mx[5*N+2]; void build_mn(int node,int lo,int hi) { if(lo==hi) { seg_mn[node]={ent[lo],lo}; return ; } int md=(lo+hi)/2; build_mn(node*2,lo,md); build_mn(node*2+1,md+1,hi); if(seg_mn[node*2].vl<seg_mn[node*2+1].vl) seg_mn[node]=seg_mn[node*2]; else seg_mn[node]=seg_mn[node*2+1]; } segment qry_mn(int node,int lo,int hi,int lt,int rt) { if(lo>rt||hi<lt)return {N+2,0}; if(lo>=lt&&hi<=rt)return seg_mn[node]; int md=(lo+hi)/2; segment p1=qry_mn(node*2,lo,md,lt,rt); segment p2=qry_mn(node*2+1,md+1,hi,lt,rt); if(p1.vl<p2.vl)return p1; else return p2; } void build_mx(int node,int lo,int hi) { if(lo==hi) { seg_mx[node]={ent[lo],lo}; return ; } int md=(lo+hi)/2; build_mx(node*2,lo,md); build_mx(node*2+1,md+1,hi); if(seg_mx[node*2].vl>seg_mx[node*2+1].vl) seg_mx[node]=seg_mx[node*2]; else seg_mx[node]=seg_mx[node*2+1]; } segment qry_mx(int node,int lo,int hi,int lt,int rt) { if(lo>rt||hi<lt)return {0,0}; if(lo>=lt&&hi<=rt)return seg_mx[node]; int md=(lo+hi)/2; segment p1=qry_mx(node*2,lo,md,lt,rt); segment p2=qry_mx(node*2+1,md+1,hi,lt,rt); if(p1.vl>p2.vl)return p1; else return p2; } void dfs(int node,int par,int lv) { parent[node]=par;level[node]=lv; ent[node]=++tim; for(auto x:adj[node]) dfs(x,node,lv+1); } void build_sparse(void) { memset(sp,-1,sizeof(sp)); for(int i=1;i<=n;i++) sp[i][0]=parent[i]; for(int j=1;j<=20;j++) { for(int i=1;i<=n;i++) { if(sp[i][j-1]!=-1) sp[i][j]=sp[sp[i][j-1]][j-1]; } } } int lca(int u,int v) { if(level[u]<level[v])swap(u,v); for(int i=20;i>=0;i--) { if(sp[u][i]==-1)continue; if(level[sp[u][i]]>=level[v]) u=sp[u][i]; } if(u==v)return u; for(int i=20;i>=0;i--) { if(sp[u][i]==-1||sp[v][i]==-1)continue; if(sp[u][i]==sp[v][i])continue; u=sp[u][i];v=sp[v][i]; } return parent[u]; } segment do_min(int lt,int rt) { segment p1,p2,p3,p4,p5; p1=qry_mn(1,1,n,lt,rt);p2=qry_mx(1,1,n,lt,rt); if(p1.id+1<=rt) p3=qry_mn(1,1,n,p1.id+1,rt); else p3={N+2,0}; if(p1.id-1>=lt) p4=qry_mn(1,1,n,lt,p1.id-1); else p4={N+2,0}; if(p3.vl<p4.vl)p5=p3; else p5=p4; return {lca(p5.id,p2.id),p1.id}; } segment do_max(int lt,int rt) { segment p1,p2,p3,p4,p5; p1=qry_mn(1,1,n,lt,rt);p2=qry_mx(1,1,n,lt,rt); if(p2.id+1<=rt) p3=qry_mx(1,1,n,p2.id+1,rt); else p3={0,0}; if(p2.id-1>=lt) p4=qry_mx(1,1,n,lt,p2.id-1); else p4={0,0}; if(p3.vl>p4.vl)p5=p3; else p5=p4; return {lca(p5.id,p1.id),p2.id}; } int main() { ios_base::sync_with_stdio(0);cin.tie(0); int q;cin>>n>>q; for(int i=2;i<=n;i++) { int p;cin>>p; adj[p].push_back(i); } dfs(1,-1,0);build_sparse(); build_mn(1,1,n);build_mx(1,1,n); while(q--) { int lt,rt;cin>>lt>>rt; segment p1=do_min(lt,rt); segment p2=do_max(lt,rt); if(level[p1.vl]>level[p2.vl]) cout<<p1.id<<" "<<level[p1.vl]<<"\n"; else cout<<p2.id<<" "<<level[p2.vl]<<"\n"; } return 0; }
24.649351
111
0.524499
[ "vector" ]
295022c9d94ebc94b8b019c7c9a9dcfb1734725c
2,375
cpp
C++
codes/HDU/hdu4777.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/HDU/hdu4777.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/HDU/hdu4777.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
#include <cstdio> #include <cstring> #include <cmath> #include <vector> #include <algorithm> using namespace std; const int maxn = 200005; int np, pri[maxn], vis[maxn]; void prime_table(int n) { np = 0; for (int i = 2; i <= n; i++) { if (vis[i]) continue; pri[np++] = i; for (int j = i * 2; j <= n; j += i) vis[j] = 1; } vis[1] = 1; } #define lowbit(x) ((x)&(-x)) struct Seg { int l, r, id; Seg (int l = 0, int r = 0, int id = 0) { this->l = l; this->r = r; this->id = id; } friend bool operator < (const Seg& a, const Seg& b) { return a.r < b.r; } }; int N, M, L[maxn], P[maxn]; int fenw[maxn], ans[maxn]; vector<int> g[maxn]; vector<Seg> vec, que; inline void add (int x, int d) { if (x <= 0) return; while (x <= N) { fenw[x] += d; x += lowbit(x); } } inline int sum (int x) { int ret = 0; while (x) { ret += fenw[x]; x -= lowbit(x); } return ret; } void init () { vec.clear(); que.clear(); int x; for (int i = 1; i <= N; i++) { scanf("%d", &x); g[i].clear(); for (int j = 0; j < np; j++) { if (x % pri[j] == 0) { g[i].push_back(pri[j]); while (x % pri[j] == 0) x /= pri[j]; } if (vis[x] == 0) { g[i].push_back(x); break; } } } for (int i = 0; i < maxn; i++) P[i] = 0; for (int i = 1; i <= N; i++) { int tmp = 0; for (int j = 0; j < g[i].size(); j++) { tmp = max(tmp, P[g[i][j]]); P[g[i][j]] = i; } L[i] = tmp; vec.push_back(Seg(tmp, i, 0)); } for (int i = 0; i < maxn; i++) P[i] = N + 1; for (int i = N; i; i--) { int tmp = N + 1; for (int j = 0; j < g[i].size(); j++) { tmp = min(tmp, P[g[i][j]]); P[g[i][j]] = i; } vec.push_back(Seg(i, tmp, 1)); } int l, r; for (int i = 1; i <= M; i++) { scanf("%d%d", &l, &r); que.push_back(Seg(l, r, i)); } } void solve () { sort(que.begin(), que.end()); sort(vec.begin(), vec.end()); memset(fenw, 0, sizeof(fenw)); int mv = 0; for (int i = 0; i < que.size(); i++) { while (mv < vec.size() && vec[mv].r <= que[i].r) { add(vec[mv].l, 1); if (vec[mv].id) add(L[vec[mv].l], -1); mv++; } int tmp = sum(que[i].r) - sum(que[i].l - 1); ans[que[i].id] = que[i].r - que[i].l + 1 - tmp; } } int main () { prime_table(maxn); while (scanf("%d%d", &N, &M) == 2 && N + M) { init(); solve(); for (int i = 1; i <= M; i++) printf("%d\n", ans[i]); } return 0; }
17.086331
54
0.466105
[ "vector" ]
295098ed41183a548e43d7c53a171b51c24f33f2
21,321
cpp
C++
llvm/tools/llvm-objcopy/MachO/MachOWriter.cpp
acidburn0zzz/llvm-project
7ca7a2547f00e34f5ec91be776a1d0bbca74b7a9
[ "Apache-2.0" ]
2,338
2018-06-19T17:34:51.000Z
2022-03-31T11:00:37.000Z
llvm/tools/llvm-objcopy/MachO/MachOWriter.cpp
acidburn0zzz/llvm-project
7ca7a2547f00e34f5ec91be776a1d0bbca74b7a9
[ "Apache-2.0" ]
3,740
2019-01-23T15:36:48.000Z
2022-03-31T22:01:13.000Z
llvm/tools/llvm-objcopy/MachO/MachOWriter.cpp
acidburn0zzz/llvm-project
7ca7a2547f00e34f5ec91be776a1d0bbca74b7a9
[ "Apache-2.0" ]
500
2019-01-23T07:49:22.000Z
2022-03-30T02:59:37.000Z
//===- MachOWriter.cpp ------------------------------------------*- C++ -*-===// // // 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 "MachOWriter.h" #include "MachOLayoutBuilder.h" #include "Object.h" #include "llvm/ADT/STLExtras.h" #include "llvm/BinaryFormat/MachO.h" #include "llvm/Object/MachO.h" #include "llvm/Support/Errc.h" #include "llvm/Support/ErrorHandling.h" #include <memory> using namespace llvm; using namespace llvm::objcopy::macho; size_t MachOWriter::headerSize() const { return Is64Bit ? sizeof(MachO::mach_header_64) : sizeof(MachO::mach_header); } size_t MachOWriter::loadCommandsSize() const { return O.Header.SizeOfCmds; } size_t MachOWriter::symTableSize() const { return O.SymTable.Symbols.size() * (Is64Bit ? sizeof(MachO::nlist_64) : sizeof(MachO::nlist)); } size_t MachOWriter::totalSize() const { // Going from tail to head and looking for an appropriate "anchor" to // calculate the total size assuming that all the offsets are either valid // ("true") or 0 (0 indicates that the corresponding part is missing). SmallVector<size_t, 7> Ends; if (O.SymTabCommandIndex) { const MachO::symtab_command &SymTabCommand = O.LoadCommands[*O.SymTabCommandIndex] .MachOLoadCommand.symtab_command_data; if (SymTabCommand.symoff) Ends.push_back(SymTabCommand.symoff + symTableSize()); if (SymTabCommand.stroff) Ends.push_back(SymTabCommand.stroff + SymTabCommand.strsize); } if (O.DyLdInfoCommandIndex) { const MachO::dyld_info_command &DyLdInfoCommand = O.LoadCommands[*O.DyLdInfoCommandIndex] .MachOLoadCommand.dyld_info_command_data; if (DyLdInfoCommand.rebase_off) { assert((DyLdInfoCommand.rebase_size == O.Rebases.Opcodes.size()) && "Incorrect rebase opcodes size"); Ends.push_back(DyLdInfoCommand.rebase_off + DyLdInfoCommand.rebase_size); } if (DyLdInfoCommand.bind_off) { assert((DyLdInfoCommand.bind_size == O.Binds.Opcodes.size()) && "Incorrect bind opcodes size"); Ends.push_back(DyLdInfoCommand.bind_off + DyLdInfoCommand.bind_size); } if (DyLdInfoCommand.weak_bind_off) { assert((DyLdInfoCommand.weak_bind_size == O.WeakBinds.Opcodes.size()) && "Incorrect weak bind opcodes size"); Ends.push_back(DyLdInfoCommand.weak_bind_off + DyLdInfoCommand.weak_bind_size); } if (DyLdInfoCommand.lazy_bind_off) { assert((DyLdInfoCommand.lazy_bind_size == O.LazyBinds.Opcodes.size()) && "Incorrect lazy bind opcodes size"); Ends.push_back(DyLdInfoCommand.lazy_bind_off + DyLdInfoCommand.lazy_bind_size); } if (DyLdInfoCommand.export_off) { assert((DyLdInfoCommand.export_size == O.Exports.Trie.size()) && "Incorrect trie size"); Ends.push_back(DyLdInfoCommand.export_off + DyLdInfoCommand.export_size); } } if (O.DySymTabCommandIndex) { const MachO::dysymtab_command &DySymTabCommand = O.LoadCommands[*O.DySymTabCommandIndex] .MachOLoadCommand.dysymtab_command_data; if (DySymTabCommand.indirectsymoff) Ends.push_back(DySymTabCommand.indirectsymoff + sizeof(uint32_t) * O.IndirectSymTable.Symbols.size()); } if (O.CodeSignatureCommandIndex) { const MachO::linkedit_data_command &LinkEditDataCommand = O.LoadCommands[*O.CodeSignatureCommandIndex] .MachOLoadCommand.linkedit_data_command_data; if (LinkEditDataCommand.dataoff) Ends.push_back(LinkEditDataCommand.dataoff + LinkEditDataCommand.datasize); } if (O.DataInCodeCommandIndex) { const MachO::linkedit_data_command &LinkEditDataCommand = O.LoadCommands[*O.DataInCodeCommandIndex] .MachOLoadCommand.linkedit_data_command_data; if (LinkEditDataCommand.dataoff) Ends.push_back(LinkEditDataCommand.dataoff + LinkEditDataCommand.datasize); } if (O.LinkerOptimizationHintCommandIndex) { const MachO::linkedit_data_command &LinkEditDataCommand = O.LoadCommands[*O.LinkerOptimizationHintCommandIndex] .MachOLoadCommand.linkedit_data_command_data; if (LinkEditDataCommand.dataoff) Ends.push_back(LinkEditDataCommand.dataoff + LinkEditDataCommand.datasize); } if (O.FunctionStartsCommandIndex) { const MachO::linkedit_data_command &LinkEditDataCommand = O.LoadCommands[*O.FunctionStartsCommandIndex] .MachOLoadCommand.linkedit_data_command_data; if (LinkEditDataCommand.dataoff) Ends.push_back(LinkEditDataCommand.dataoff + LinkEditDataCommand.datasize); } // Otherwise, use the last section / reloction. for (const LoadCommand &LC : O.LoadCommands) for (const std::unique_ptr<Section> &S : LC.Sections) { if (!S->hasValidOffset()) { assert((S->Offset == 0) && "Skipped section's offset must be zero"); assert((S->isVirtualSection() || S->Size == 0) && "Non-zero-fill sections with zero offset must have zero size"); continue; } assert((S->Offset != 0) && "Non-zero-fill section's offset cannot be zero"); Ends.push_back(S->Offset + S->Size); if (S->RelOff) Ends.push_back(S->RelOff + S->NReloc * sizeof(MachO::any_relocation_info)); } if (!Ends.empty()) return *std::max_element(Ends.begin(), Ends.end()); // Otherwise, we have only Mach header and load commands. return headerSize() + loadCommandsSize(); } void MachOWriter::writeHeader() { MachO::mach_header_64 Header; Header.magic = O.Header.Magic; Header.cputype = O.Header.CPUType; Header.cpusubtype = O.Header.CPUSubType; Header.filetype = O.Header.FileType; Header.ncmds = O.Header.NCmds; Header.sizeofcmds = O.Header.SizeOfCmds; Header.flags = O.Header.Flags; Header.reserved = O.Header.Reserved; if (IsLittleEndian != sys::IsLittleEndianHost) MachO::swapStruct(Header); auto HeaderSize = Is64Bit ? sizeof(MachO::mach_header_64) : sizeof(MachO::mach_header); memcpy(Buf->getBufferStart(), &Header, HeaderSize); } void MachOWriter::writeLoadCommands() { uint8_t *Begin = reinterpret_cast<uint8_t *>(Buf->getBufferStart()) + headerSize(); for (const LoadCommand &LC : O.LoadCommands) { // Construct a load command. MachO::macho_load_command MLC = LC.MachOLoadCommand; switch (MLC.load_command_data.cmd) { case MachO::LC_SEGMENT: if (IsLittleEndian != sys::IsLittleEndianHost) MachO::swapStruct(MLC.segment_command_data); memcpy(Begin, &MLC.segment_command_data, sizeof(MachO::segment_command)); Begin += sizeof(MachO::segment_command); for (const std::unique_ptr<Section> &Sec : LC.Sections) writeSectionInLoadCommand<MachO::section>(*Sec, Begin); continue; case MachO::LC_SEGMENT_64: if (IsLittleEndian != sys::IsLittleEndianHost) MachO::swapStruct(MLC.segment_command_64_data); memcpy(Begin, &MLC.segment_command_64_data, sizeof(MachO::segment_command_64)); Begin += sizeof(MachO::segment_command_64); for (const std::unique_ptr<Section> &Sec : LC.Sections) writeSectionInLoadCommand<MachO::section_64>(*Sec, Begin); continue; } #define HANDLE_LOAD_COMMAND(LCName, LCValue, LCStruct) \ case MachO::LCName: \ assert(sizeof(MachO::LCStruct) + LC.Payload.size() == \ MLC.load_command_data.cmdsize); \ if (IsLittleEndian != sys::IsLittleEndianHost) \ MachO::swapStruct(MLC.LCStruct##_data); \ memcpy(Begin, &MLC.LCStruct##_data, sizeof(MachO::LCStruct)); \ Begin += sizeof(MachO::LCStruct); \ if (!LC.Payload.empty()) \ memcpy(Begin, LC.Payload.data(), LC.Payload.size()); \ Begin += LC.Payload.size(); \ break; // Copy the load command as it is. switch (MLC.load_command_data.cmd) { default: assert(sizeof(MachO::load_command) + LC.Payload.size() == MLC.load_command_data.cmdsize); if (IsLittleEndian != sys::IsLittleEndianHost) MachO::swapStruct(MLC.load_command_data); memcpy(Begin, &MLC.load_command_data, sizeof(MachO::load_command)); Begin += sizeof(MachO::load_command); if (!LC.Payload.empty()) memcpy(Begin, LC.Payload.data(), LC.Payload.size()); Begin += LC.Payload.size(); break; #include "llvm/BinaryFormat/MachO.def" } } } template <typename StructType> void MachOWriter::writeSectionInLoadCommand(const Section &Sec, uint8_t *&Out) { StructType Temp; assert(Sec.Segname.size() <= sizeof(Temp.segname) && "too long segment name"); assert(Sec.Sectname.size() <= sizeof(Temp.sectname) && "too long section name"); memset(&Temp, 0, sizeof(StructType)); memcpy(Temp.segname, Sec.Segname.data(), Sec.Segname.size()); memcpy(Temp.sectname, Sec.Sectname.data(), Sec.Sectname.size()); Temp.addr = Sec.Addr; Temp.size = Sec.Size; Temp.offset = Sec.Offset; Temp.align = Sec.Align; Temp.reloff = Sec.RelOff; Temp.nreloc = Sec.NReloc; Temp.flags = Sec.Flags; Temp.reserved1 = Sec.Reserved1; Temp.reserved2 = Sec.Reserved2; if (IsLittleEndian != sys::IsLittleEndianHost) MachO::swapStruct(Temp); memcpy(Out, &Temp, sizeof(StructType)); Out += sizeof(StructType); } void MachOWriter::writeSections() { for (const LoadCommand &LC : O.LoadCommands) for (const std::unique_ptr<Section> &Sec : LC.Sections) { if (!Sec->hasValidOffset()) { assert((Sec->Offset == 0) && "Skipped section's offset must be zero"); assert((Sec->isVirtualSection() || Sec->Size == 0) && "Non-zero-fill sections with zero offset must have zero size"); continue; } assert(Sec->Offset && "Section offset can not be zero"); assert((Sec->Size == Sec->Content.size()) && "Incorrect section size"); memcpy(Buf->getBufferStart() + Sec->Offset, Sec->Content.data(), Sec->Content.size()); for (size_t Index = 0; Index < Sec->Relocations.size(); ++Index) { RelocationInfo RelocInfo = Sec->Relocations[Index]; if (!RelocInfo.Scattered && !RelocInfo.IsAddend) { const uint32_t SymbolNum = RelocInfo.Extern ? (*RelocInfo.Symbol)->Index : (*RelocInfo.Sec)->Index; RelocInfo.setPlainRelocationSymbolNum(SymbolNum, IsLittleEndian); } if (IsLittleEndian != sys::IsLittleEndianHost) MachO::swapStruct( reinterpret_cast<MachO::any_relocation_info &>(RelocInfo.Info)); memcpy(Buf->getBufferStart() + Sec->RelOff + Index * sizeof(MachO::any_relocation_info), &RelocInfo.Info, sizeof(RelocInfo.Info)); } } } template <typename NListType> void writeNListEntry(const SymbolEntry &SE, bool IsLittleEndian, char *&Out, uint32_t Nstrx) { NListType ListEntry; ListEntry.n_strx = Nstrx; ListEntry.n_type = SE.n_type; ListEntry.n_sect = SE.n_sect; ListEntry.n_desc = SE.n_desc; ListEntry.n_value = SE.n_value; if (IsLittleEndian != sys::IsLittleEndianHost) MachO::swapStruct(ListEntry); memcpy(Out, reinterpret_cast<const char *>(&ListEntry), sizeof(NListType)); Out += sizeof(NListType); } void MachOWriter::writeStringTable() { if (!O.SymTabCommandIndex) return; const MachO::symtab_command &SymTabCommand = O.LoadCommands[*O.SymTabCommandIndex] .MachOLoadCommand.symtab_command_data; uint8_t *StrTable = (uint8_t *)Buf->getBufferStart() + SymTabCommand.stroff; LayoutBuilder.getStringTableBuilder().write(StrTable); } void MachOWriter::writeSymbolTable() { if (!O.SymTabCommandIndex) return; const MachO::symtab_command &SymTabCommand = O.LoadCommands[*O.SymTabCommandIndex] .MachOLoadCommand.symtab_command_data; char *SymTable = (char *)Buf->getBufferStart() + SymTabCommand.symoff; for (auto Iter = O.SymTable.Symbols.begin(), End = O.SymTable.Symbols.end(); Iter != End; Iter++) { SymbolEntry *Sym = Iter->get(); uint32_t Nstrx = LayoutBuilder.getStringTableBuilder().getOffset(Sym->Name); if (Is64Bit) writeNListEntry<MachO::nlist_64>(*Sym, IsLittleEndian, SymTable, Nstrx); else writeNListEntry<MachO::nlist>(*Sym, IsLittleEndian, SymTable, Nstrx); } } void MachOWriter::writeRebaseInfo() { if (!O.DyLdInfoCommandIndex) return; const MachO::dyld_info_command &DyLdInfoCommand = O.LoadCommands[*O.DyLdInfoCommandIndex] .MachOLoadCommand.dyld_info_command_data; char *Out = (char *)Buf->getBufferStart() + DyLdInfoCommand.rebase_off; assert((DyLdInfoCommand.rebase_size == O.Rebases.Opcodes.size()) && "Incorrect rebase opcodes size"); memcpy(Out, O.Rebases.Opcodes.data(), O.Rebases.Opcodes.size()); } void MachOWriter::writeBindInfo() { if (!O.DyLdInfoCommandIndex) return; const MachO::dyld_info_command &DyLdInfoCommand = O.LoadCommands[*O.DyLdInfoCommandIndex] .MachOLoadCommand.dyld_info_command_data; char *Out = (char *)Buf->getBufferStart() + DyLdInfoCommand.bind_off; assert((DyLdInfoCommand.bind_size == O.Binds.Opcodes.size()) && "Incorrect bind opcodes size"); memcpy(Out, O.Binds.Opcodes.data(), O.Binds.Opcodes.size()); } void MachOWriter::writeWeakBindInfo() { if (!O.DyLdInfoCommandIndex) return; const MachO::dyld_info_command &DyLdInfoCommand = O.LoadCommands[*O.DyLdInfoCommandIndex] .MachOLoadCommand.dyld_info_command_data; char *Out = (char *)Buf->getBufferStart() + DyLdInfoCommand.weak_bind_off; assert((DyLdInfoCommand.weak_bind_size == O.WeakBinds.Opcodes.size()) && "Incorrect weak bind opcodes size"); memcpy(Out, O.WeakBinds.Opcodes.data(), O.WeakBinds.Opcodes.size()); } void MachOWriter::writeLazyBindInfo() { if (!O.DyLdInfoCommandIndex) return; const MachO::dyld_info_command &DyLdInfoCommand = O.LoadCommands[*O.DyLdInfoCommandIndex] .MachOLoadCommand.dyld_info_command_data; char *Out = (char *)Buf->getBufferStart() + DyLdInfoCommand.lazy_bind_off; assert((DyLdInfoCommand.lazy_bind_size == O.LazyBinds.Opcodes.size()) && "Incorrect lazy bind opcodes size"); memcpy(Out, O.LazyBinds.Opcodes.data(), O.LazyBinds.Opcodes.size()); } void MachOWriter::writeExportInfo() { if (!O.DyLdInfoCommandIndex) return; const MachO::dyld_info_command &DyLdInfoCommand = O.LoadCommands[*O.DyLdInfoCommandIndex] .MachOLoadCommand.dyld_info_command_data; char *Out = (char *)Buf->getBufferStart() + DyLdInfoCommand.export_off; assert((DyLdInfoCommand.export_size == O.Exports.Trie.size()) && "Incorrect export trie size"); memcpy(Out, O.Exports.Trie.data(), O.Exports.Trie.size()); } void MachOWriter::writeIndirectSymbolTable() { if (!O.DySymTabCommandIndex) return; const MachO::dysymtab_command &DySymTabCommand = O.LoadCommands[*O.DySymTabCommandIndex] .MachOLoadCommand.dysymtab_command_data; uint32_t *Out = (uint32_t *)(Buf->getBufferStart() + DySymTabCommand.indirectsymoff); for (const IndirectSymbolEntry &Sym : O.IndirectSymTable.Symbols) { uint32_t Entry = (Sym.Symbol) ? (*Sym.Symbol)->Index : Sym.OriginalIndex; if (IsLittleEndian != sys::IsLittleEndianHost) sys::swapByteOrder(Entry); *Out++ = Entry; } } void MachOWriter::writeLinkData(Optional<size_t> LCIndex, const LinkData &LD) { if (!LCIndex) return; const MachO::linkedit_data_command &LinkEditDataCommand = O.LoadCommands[*LCIndex].MachOLoadCommand.linkedit_data_command_data; char *Out = (char *)Buf->getBufferStart() + LinkEditDataCommand.dataoff; assert((LinkEditDataCommand.datasize == LD.Data.size()) && "Incorrect data size"); memcpy(Out, LD.Data.data(), LD.Data.size()); } void MachOWriter::writeCodeSignatureData() { return writeLinkData(O.CodeSignatureCommandIndex, O.CodeSignature); } void MachOWriter::writeDataInCodeData() { return writeLinkData(O.DataInCodeCommandIndex, O.DataInCode); } void MachOWriter::writeLinkerOptimizationHint() { return writeLinkData(O.LinkerOptimizationHintCommandIndex, O.LinkerOptimizationHint); } void MachOWriter::writeFunctionStartsData() { return writeLinkData(O.FunctionStartsCommandIndex, O.FunctionStarts); } void MachOWriter::writeTail() { typedef void (MachOWriter::*WriteHandlerType)(void); typedef std::pair<uint64_t, WriteHandlerType> WriteOperation; SmallVector<WriteOperation, 7> Queue; if (O.SymTabCommandIndex) { const MachO::symtab_command &SymTabCommand = O.LoadCommands[*O.SymTabCommandIndex] .MachOLoadCommand.symtab_command_data; if (SymTabCommand.symoff) Queue.push_back({SymTabCommand.symoff, &MachOWriter::writeSymbolTable}); if (SymTabCommand.stroff) Queue.push_back({SymTabCommand.stroff, &MachOWriter::writeStringTable}); } if (O.DyLdInfoCommandIndex) { const MachO::dyld_info_command &DyLdInfoCommand = O.LoadCommands[*O.DyLdInfoCommandIndex] .MachOLoadCommand.dyld_info_command_data; if (DyLdInfoCommand.rebase_off) Queue.push_back( {DyLdInfoCommand.rebase_off, &MachOWriter::writeRebaseInfo}); if (DyLdInfoCommand.bind_off) Queue.push_back({DyLdInfoCommand.bind_off, &MachOWriter::writeBindInfo}); if (DyLdInfoCommand.weak_bind_off) Queue.push_back( {DyLdInfoCommand.weak_bind_off, &MachOWriter::writeWeakBindInfo}); if (DyLdInfoCommand.lazy_bind_off) Queue.push_back( {DyLdInfoCommand.lazy_bind_off, &MachOWriter::writeLazyBindInfo}); if (DyLdInfoCommand.export_off) Queue.push_back( {DyLdInfoCommand.export_off, &MachOWriter::writeExportInfo}); } if (O.DySymTabCommandIndex) { const MachO::dysymtab_command &DySymTabCommand = O.LoadCommands[*O.DySymTabCommandIndex] .MachOLoadCommand.dysymtab_command_data; if (DySymTabCommand.indirectsymoff) Queue.emplace_back(DySymTabCommand.indirectsymoff, &MachOWriter::writeIndirectSymbolTable); } if (O.CodeSignatureCommandIndex) { const MachO::linkedit_data_command &LinkEditDataCommand = O.LoadCommands[*O.CodeSignatureCommandIndex] .MachOLoadCommand.linkedit_data_command_data; if (LinkEditDataCommand.dataoff) Queue.emplace_back(LinkEditDataCommand.dataoff, &MachOWriter::writeCodeSignatureData); } if (O.DataInCodeCommandIndex) { const MachO::linkedit_data_command &LinkEditDataCommand = O.LoadCommands[*O.DataInCodeCommandIndex] .MachOLoadCommand.linkedit_data_command_data; if (LinkEditDataCommand.dataoff) Queue.emplace_back(LinkEditDataCommand.dataoff, &MachOWriter::writeDataInCodeData); } if (O.LinkerOptimizationHintCommandIndex) { const MachO::linkedit_data_command &LinkEditDataCommand = O.LoadCommands[*O.LinkerOptimizationHintCommandIndex] .MachOLoadCommand.linkedit_data_command_data; if (LinkEditDataCommand.dataoff) Queue.emplace_back(LinkEditDataCommand.dataoff, &MachOWriter::writeLinkerOptimizationHint); } if (O.FunctionStartsCommandIndex) { const MachO::linkedit_data_command &LinkEditDataCommand = O.LoadCommands[*O.FunctionStartsCommandIndex] .MachOLoadCommand.linkedit_data_command_data; if (LinkEditDataCommand.dataoff) Queue.emplace_back(LinkEditDataCommand.dataoff, &MachOWriter::writeFunctionStartsData); } llvm::sort(Queue, [](const WriteOperation &LHS, const WriteOperation &RHS) { return LHS.first < RHS.first; }); for (auto WriteOp : Queue) (this->*WriteOp.second)(); } Error MachOWriter::finalize() { return LayoutBuilder.layout(); } Error MachOWriter::write() { size_t TotalSize = totalSize(); Buf = WritableMemoryBuffer::getNewMemBuffer(TotalSize); if (!Buf) return createStringError(errc::not_enough_memory, "failed to allocate memory buffer of " + Twine::utohexstr(TotalSize) + " bytes"); memset(Buf->getBufferStart(), 0, totalSize()); writeHeader(); writeLoadCommands(); writeSections(); writeTail(); // TODO: Implement direct writing to the output stream (without intermediate // memory buffer Buf). Out.write(Buf->getBufferStart(), Buf->getBufferSize()); return Error::success(); }
38.347122
80
0.673092
[ "object" ]
29561cb9adc030e8c966c53c1d2c86fc8ef68c4b
5,247
cpp
C++
aws-cpp-sdk-sqs/source/model/MessageSystemAttributeValue.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-sqs/source/model/MessageSystemAttributeValue.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-sqs/source/model/MessageSystemAttributeValue.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-12-30T04:25:33.000Z
2021-12-30T04:25:33.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/sqs/model/MessageSystemAttributeValue.h> #include <aws/core/utils/xml/XmlSerializer.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <aws/core/utils/HashingUtils.h> #include <utility> using namespace Aws::Utils::Xml; using namespace Aws::Utils; namespace Aws { namespace SQS { namespace Model { MessageSystemAttributeValue::MessageSystemAttributeValue() : m_stringValueHasBeenSet(false), m_binaryValueHasBeenSet(false), m_stringListValuesHasBeenSet(false), m_binaryListValuesHasBeenSet(false), m_dataTypeHasBeenSet(false) { } MessageSystemAttributeValue::MessageSystemAttributeValue(const XmlNode& xmlNode) : m_stringValueHasBeenSet(false), m_binaryValueHasBeenSet(false), m_stringListValuesHasBeenSet(false), m_binaryListValuesHasBeenSet(false), m_dataTypeHasBeenSet(false) { *this = xmlNode; } MessageSystemAttributeValue& MessageSystemAttributeValue::operator =(const XmlNode& xmlNode) { XmlNode resultNode = xmlNode; if(!resultNode.IsNull()) { XmlNode stringValueNode = resultNode.FirstChild("StringValue"); if(!stringValueNode.IsNull()) { m_stringValue = Aws::Utils::Xml::DecodeEscapedXmlText(stringValueNode.GetText()); m_stringValueHasBeenSet = true; } XmlNode binaryValueNode = resultNode.FirstChild("BinaryValue"); if(!binaryValueNode.IsNull()) { m_binaryValue = HashingUtils::Base64Decode(Aws::Utils::Xml::DecodeEscapedXmlText(binaryValueNode.GetText())); m_binaryValueHasBeenSet = true; } XmlNode stringListValuesNode = resultNode.FirstChild("StringListValue"); if(!stringListValuesNode.IsNull()) { XmlNode stringListValueMember = stringListValuesNode; while(!stringListValueMember.IsNull()) { m_stringListValues.push_back(stringListValueMember.GetText()); stringListValueMember = stringListValueMember.NextNode("StringListValue"); } m_stringListValuesHasBeenSet = true; } XmlNode binaryListValuesNode = resultNode.FirstChild("BinaryListValue"); if(!binaryListValuesNode.IsNull()) { XmlNode binaryListValueMember = binaryListValuesNode; while(!binaryListValueMember.IsNull()) { binaryListValueMember = binaryListValueMember.NextNode("BinaryListValue"); } m_binaryListValuesHasBeenSet = true; } XmlNode dataTypeNode = resultNode.FirstChild("DataType"); if(!dataTypeNode.IsNull()) { m_dataType = Aws::Utils::Xml::DecodeEscapedXmlText(dataTypeNode.GetText()); m_dataTypeHasBeenSet = true; } } return *this; } void MessageSystemAttributeValue::OutputToStream(Aws::OStream& oStream, const char* location, unsigned index, const char* locationValue) const { if(m_stringValueHasBeenSet) { oStream << location << index << locationValue << ".StringValue=" << StringUtils::URLEncode(m_stringValue.c_str()) << "&"; } if(m_binaryValueHasBeenSet) { oStream << location << index << locationValue << ".BinaryValue=" << StringUtils::URLEncode(HashingUtils::Base64Encode(m_binaryValue).c_str()) << "&"; } if(m_stringListValuesHasBeenSet) { unsigned stringListValuesIdx = 1; for(auto& item : m_stringListValues) { oStream << location << index << locationValue << ".StringListValue." << stringListValuesIdx++ << "=" << StringUtils::URLEncode(item.c_str()) << "&"; } } if(m_binaryListValuesHasBeenSet) { unsigned binaryListValuesIdx = 1; for(auto& item : m_binaryListValues) { oStream << location << index << locationValue << ".BinaryListValue." << binaryListValuesIdx++ << "=" << StringUtils::URLEncode(HashingUtils::Base64Encode(item).c_str()) << "&"; } } if(m_dataTypeHasBeenSet) { oStream << location << index << locationValue << ".DataType=" << StringUtils::URLEncode(m_dataType.c_str()) << "&"; } } void MessageSystemAttributeValue::OutputToStream(Aws::OStream& oStream, const char* location) const { if(m_stringValueHasBeenSet) { oStream << location << ".StringValue=" << StringUtils::URLEncode(m_stringValue.c_str()) << "&"; } if(m_binaryValueHasBeenSet) { oStream << location << ".BinaryValue=" << StringUtils::URLEncode(HashingUtils::Base64Encode(m_binaryValue).c_str()) << "&"; } if(m_stringListValuesHasBeenSet) { unsigned stringListValuesIdx = 1; for(auto& item : m_stringListValues) { oStream << location << ".StringListValue." << stringListValuesIdx++ << "=" << StringUtils::URLEncode(item.c_str()) << "&"; } } if(m_binaryListValuesHasBeenSet) { unsigned binaryListValuesIdx = 1; for(auto& item : m_binaryListValues) { oStream << location << ".BinaryListValue." << binaryListValuesIdx++ << "=" << StringUtils::URLEncode(HashingUtils::Base64Encode(item).c_str()) << "&"; } } if(m_dataTypeHasBeenSet) { oStream << location << ".DataType=" << StringUtils::URLEncode(m_dataType.c_str()) << "&"; } } } // namespace Model } // namespace SQS } // namespace Aws
31.419162
184
0.69373
[ "model" ]
2957f6dec65ecb54f744705db3878a4a58673010
193
cpp
C++
JanuaEngine/Core/Plane.cpp
gigc/Janua
cbcc8ad0e9501e1faef5b37a964769970aa3d236
[ "MIT", "Unlicense" ]
98
2015-01-13T16:23:23.000Z
2022-02-14T21:51:07.000Z
JanuaEngine/Core/Plane.cpp
gigc/Janua
cbcc8ad0e9501e1faef5b37a964769970aa3d236
[ "MIT", "Unlicense" ]
1
2016-06-30T22:07:54.000Z
2016-06-30T22:07:54.000Z
JanuaEngine/Core/Plane.cpp
gigc/Janua
cbcc8ad0e9501e1faef5b37a964769970aa3d236
[ "MIT", "Unlicense" ]
13
2015-08-26T11:19:08.000Z
2021-07-12T03:41:50.000Z
#include "StdAfx.h" #include "Plane.h" Plane::Plane(const Vector3f p_normal, float p_d) : normal( p_normal), d(p_d) { //TODO: check the normal is a unit vector. } Plane::~Plane(void) { }
12.866667
76
0.668394
[ "vector" ]
295b55831cf55ef0c520b39c4333857f9e21d7c7
2,020
cpp
C++
opencl_caffe/src/nodelet.cpp
gachiemchiep/ros_opencl_caffe
cceb5f64be5e58054fc4d70095c6961e5279a17a
[ "Apache-2.0" ]
null
null
null
opencl_caffe/src/nodelet.cpp
gachiemchiep/ros_opencl_caffe
cceb5f64be5e58054fc4d70095c6961e5279a17a
[ "Apache-2.0" ]
null
null
null
opencl_caffe/src/nodelet.cpp
gachiemchiep/ros_opencl_caffe
cceb5f64be5e58054fc4d70095c6961e5279a17a
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2017 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <string> #include <pluginlib/class_list_macros.h> #include "opencl_caffe/detector_gpu.h" #include "opencl_caffe/nodelet.h" PLUGINLIB_EXPORT_CLASS(opencl_caffe::Nodelet, nodelet::Nodelet) namespace opencl_caffe { void Nodelet::onInit() { ros::NodeHandle pnh = getPrivateNodeHandle(); opencl_caffe::DetectorConfig config; if (!pnh.getParam("net_config_path", config.config)) { ROS_WARN("param net_cfg_path not set, use default"); } if (!pnh.getParam("weights_path", config.model)) { ROS_WARN("param weights_path not set, use default"); } if (!pnh.getParam("labels_path", config.classes)) { ROS_WARN("param labels_path not set, use default"); } loadResources(config); pub_ = getNodeHandle().advertise<object_msgs::ObjectsInBoxes>("inference", 1); } void Nodelet::cbImage(const sensor_msgs::ImagePtr image_msg) { object_msgs::ObjectsInBoxes objects; if (detector_->runInference(image_msg, objects)) { pub_.publish(objects); } else { ROS_ERROR("Inference failed."); } } void Nodelet::loadResources(const opencl_caffe::DetectorConfig& config) { detector_.reset(new DetectorGpu()); sub_.shutdown(); if (detector_->loadResources(config)) { sub_ = getNodeHandle().subscribe("/usb_cam/image_raw", 1, &Nodelet::cbImage, this); } else { ROS_FATAL("Load resource failed."); ros::shutdown(); } } } // namespace opencl_caffe
26.933333
87
0.718317
[ "model" ]
295c6164839738c79e522054cd7e0f0c44944bc9
15,690
hpp
C++
mysql-server/storage/ndb/test/include/NdbHistory.hpp
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/storage/ndb/test/include/NdbHistory.hpp
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/storage/ndb/test/include/NdbHistory.hpp
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
/* Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. This program 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, version 2.0, for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef NDBT_HISTORY_HPP #define NDBT_HISTORY_HPP #include <Vector.hpp> #include <NdbMutex.h> /** * Class for giving e.g. a set of steps their own * id out of a range of 0..totalWorkers * * Handy for e.g. subdividing a range of records * amongst a variable number of workers * * Usage : * WorkerIdentifier() * Repeat * init(totalWorkers) * Repeat * getNextWorkerId() * getTotalWorkers() * ... */ class WorkerIdentifier : public NdbLockable { Uint32 m_totalWorkers; Uint32 m_nextWorker; public: WorkerIdentifier(); void init(const Uint32 totalWorkers); Uint32 getTotalWorkers() const; Uint32 getNextWorkerId(); }; /** * EpochRange * * A representation of a range of epochs * This is useful when comparing versions between * multiple histories * * Epoch range has an open start and closed end * * [start, end) * * start = 11/20 * end = 12/3 * * includes * 11/20,11/21,...11/0xffffffff,12/0,12/1 * * does not include * <= 11/19 >= 12/3 * * Two ranges intersect if they have any epochs * in common */ struct EpochRange { static const Uint64 MAX_EPOCH = 0xffffffffffffffffULL; /* Start is included */ Uint64 m_start; /* End is not included */ Uint64 m_end; EpochRange intersect(const EpochRange& other) const { EpochRange i; i.m_start = MAX(m_start, other.m_start); i.m_end = MIN(m_end, other.m_end); return i; } bool isEmpty() const { return (m_start >= m_end); } bool spansGciBoundary() const { /* Does this range span at least one GCI ? */ assert(m_end > m_start); return ((m_end >> 32) > (m_start >> 32)); } static Uint32 hi(const Uint64 epoch) { return Uint32(epoch>>32); } static Uint32 lo(const Uint64 epoch) { return Uint32(epoch & 0xffffffff); } void dump() const; }; /** * EpochRangeSet * * Set of EpochRanges of interest. * * This is useful for describing consistent points in * history when some condition was true * * Not guaranteed that all contained ranges are unique or * disjoint with each other */ struct EpochRangeSet { Vector<EpochRange> m_ranges; /** * Add an epochRange to an EpochRangeSet */ void addEpochRange(const EpochRange& er) { m_ranges.push_back(er); } /** * Does this EpochRangeSet describe any range * of epochs? */ bool isEmpty() const { for (Uint32 i=0; i<m_ranges.size(); i++) { if (!m_ranges[i].isEmpty()) { return false; } } return true; } /** * Create an EpochRangeSet which contains the * set of intersecting epoch ranges in two * input EpochRanges */ static EpochRangeSet intersect(const EpochRangeSet& a, const EpochRangeSet& b) { EpochRangeSet result; /* Try to intersect every range in A with * every range in B, and keep the non-empty * results */ for (Uint32 ai = 0; ai < a.m_ranges.size(); ai++) { for (Uint32 bi = 0; bi < b.m_ranges.size(); bi++) { const EpochRange& erA = a.m_ranges[ai]; const EpochRange& erB = b.m_ranges[bi]; const EpochRange intersection = erA.intersect(erB); if (!intersection.isEmpty()) { result.addEpochRange(intersection); } } } return result; } void dump() const { for (Uint32 i=0; i<m_ranges.size(); i++) { m_ranges[i].dump(); } } }; /** * RecordRange * * Contiguous range of logical tuple ids */ struct RecordRange { Uint32 m_start; Uint32 m_len; RecordRange(const Uint32 start, const Uint32 len) : m_start(start), m_len(len) {} }; /** * NdbHistory * * Class for tracking and inspecting a history of changes to * a range of rows. * The granularity of the history collected can be configured * to adjust the cost of history tracking. * * Intended to be maintained on a unique range of rows from a * single thread at a time. */ class NdbHistory { public: /** * RecordState * * Logical state of a record covering * existence and value (if exists). * Future : Include uncertainty about * commit states for use with * disconnection or isolation tests. */ struct RecordState { enum RowState { RS_NOT_EXISTS = 0, RS_EXISTS = 1 }; Uint32 m_state; Uint32 m_updatesValue; bool equal(const RecordState& other) const; }; /** * Version * * Set of row states for a range, * describing a snapshot of the version of * the data for that range. */ class Version { public: RecordRange m_range; RecordState* m_states; /* Create empty version for range */ Version(RecordRange range); /* Create version for range same as an existing one */ Version(const Version* other); // TODO : Create version from subrange of another version /* Release version storage */ ~Version(); /** Version modification **/ /* Assign row states from another version, ranges must align */ void assign(const Version* other); /** * setRows * * Set the updates values of the row(s) to the passed value * Row range must be contained within the version's range */ void setRows(const Uint32 start, const Uint32 updatesValue, const Uint32 len = 1); /** * clearRows * * Clears (marks as deleted) the row(s) in the passed range. * The passed range must be contained within the version's * range */ void clearRows(const Uint32 start, const Uint32 len = 1); /** * diffRowCount * * return count of rows which differ between * two versions of the same row range */ Uint32 diffRowCount(const Version* other) const; /** * equal * * return true if both versions are equal */ bool equal(const Version* other) const; /** * dump * * Helper for dumping a version * When full = false, only contiguous subranges are output */ void dump(bool full=false, const char* indent = "") const; /** * dumpDiff * * Helper for dumping a diff between two versions */ void dumpDiff(const Version* other) const; private: void setRowsImpl(const Uint32 start, const Uint32 rowState, const Uint32 updatesValue, const Uint32 len); }; /** * VersionType * * Type of version relative to other versions in * the history of a range */ enum VersionType { VT_LATEST, // Version contains latest changes VT_END_OF_GCI, // Version contains end-of-GCI consistent state VT_END_OF_EPOCH, // Version contains end-of-epoch consistent state VT_OTHER // Version is none of the above }; static const char* getVersionTypeName(const VersionType vt); /** * VersionMeta * * Metadata concerning a version stored in a history * TODO Consider/add rollback + unknown outcome types */ struct VersionMeta { Uint64 m_number; /* Sequential number of version in history */ VersionType m_type; /* Type of version in this history */ Uint64 m_latest_epoch; /* Epoch of most recent change in this version */ /* Dump VersionMeta */ void dump() const; }; /** * Granularity * * Granularity at which distinct versions are kept * in the history. * When a change to a range is added, it will either * be merged into the description of the latest version * or it will cause the a new version description to * be allocated. * This is decided based on the change epoch and the * Granularity of the history. * Note that only changes result in history being * recorded. Where there is no change for multiple * epochs or GCIs, nothing will be recorded. * * Note on epoch and GCI numbers : * The last recorded version with a given epoch or * GCI number is the final state associated with * that epoch or GCI in the history. * These last states are marked in the history with * their version type * If the rows are unchanged for some time then * of course the same version may be in-force for * several epochs * * * GR_LATEST_ONLY * Only latest version (1 version) * LATEST : (1 : 22) (2 : 22) (3 : 44) ... 53/6 * * GR_LATEST_GCI * Latest version + last in GCI versions * LATEST : (1 : 22) (2 : 22) (3 : 44) ... 53/6 * GCI : (1 : 21) (2 : 21) (3 : 43) ... 52/19 * GCI : (1 : 21) (2 : 20) (3 : 41) ... 51/19 * GCI : (1 : 21) (2 : 19) (3 : 40) ... 50/19 * ... * * GR_LATEST_GCI_EPOCH * Latest version + last in GCI + last in Epoch versions * LATEST : (1 : 22) (2 : 22) (3 : 44) ... 53/6 * EPOCH : (1 : 22) (2 : 21) (3 : 44) ... 53/5 * EPOCH : (1 : 22) (2 : 21) (3 : 44) ... 54/2 * ... * GCI : (1 : 21) (2 : 21) (3 : 43) ... 52/19 * EPOCH : (1 : 21) (2 : 21) (3 : 42) ... 52/18 * EPOCH : ... * ... * GCI : (1 : 21) (2 : 20) (3 : 41) ... 51/19 * EPOCH : ... * ... * * GR_ALL * All versions * LATEST : (1 : 22) (2 : 22) (3 : 44) ... 53/6 * OTHER : (1 : 22) (2 : 22) (3 : 44) ... 53/6 * OTHER : (1 : 22) (2 : 22) (3 : 44) ... 53/6 * ... * EPOCH : (1 : 22) (2 : 21) (3 : 44) ... 53/5 * OTHER ... * OTHER ... * ... * EPOCH : (1 : 22) (2 : 21) (3 : 44) ... 54/2 * ... * GCI : (1 : 21) (2 : 21) (3 : 43) ... 52/19 * ... */ enum Granularity { GR_LATEST_ONLY, GR_LATEST_GCI, GR_LATEST_GCI_EPOCH, GR_ALL }; static const char* getGranularityName(const Granularity gr); /** Creation + Deletion **/ /** * Create an NdbHistory for recording versions of rows in the given * range, at the given granularity * * TODO : Bound history length by # versions, #GCIs, # epochs, manually # etc */ NdbHistory(const Granularity granularity, const RecordRange range); ~NdbHistory(); /** Modification **/ /** * checkVersionBoundary * * Method which checks whether a commit in the passed epoch * represents a version boundary between the previous history * and the new commit according to the history's recording * granularity. * * If true is returned then a new version should be used for * the new commit, and the type of the last version is * updated. * If false is returned, the type of the last version is * unmodified */ bool checkVersionBoundary(const Uint64 epoch, VersionType& lastVersionType) const; /** * commitVersion * * This method is used to add a committed version * to the history. * The new version will be recorded according to * the history's granularity. * * This generally results in the Version state * being copied. * * Note that one way to optimise performance if * necessary could be to guard calls to this * method using checkVersionBoundary(), so that * only versions which are significant to the * history's granularity are recorded. * * Other potential optimisations : * - Track/copy only modified subrange */ // TODO : Add rollback + unknown result recording variants void commitVersion(const Version* version, Uint64 commitEpoch); /** Analysis **/ /** * getLatestVersion() * * This method returns a pointer to the latest version * stored in the history. * Will return NULL for an empty history. */ const Version* getLatestVersion() const; /** * VersionIterator * * Iterator for iterating over the recorded version(s) * in ascending order, oldest to latest * NULL is returned at the end, per version metadata * is put into the passed referenced variable. */ class VersionIterator { public: VersionIterator(const NdbHistory& history); const Version* next(VersionMeta& vm); void reset(); private: const NdbHistory& m_history; Uint32 m_index; }; /** * VersionMatchIterator * * Iterator for iterating over the recorded version(s) * in ascending order, looking for versions matching * the version passed in as match. * Note that there can be 0, 1 or multiple matching * versions. */ class VersionMatchIterator { public: VersionMatchIterator(const NdbHistory& history, const Version* match); const Version* next(VersionMeta& vm); void reset(); private: VersionIterator m_vi; const Version* m_match; }; /** * MatchingEpochRangeIterator * * Iterator for iterating over the recorded version(s) * in ascending order, returning ranges of epochs which * contain versions which match the passed version. * Note that only matches spanning epoch boundaries * are considered - matches contained within an epoch * are filtered out. */ class MatchingEpochRangeIterator { public: MatchingEpochRangeIterator(const NdbHistory& history, const Version* match); bool next(EpochRange& er); void reset(); private: VersionIterator m_vi; const Version* m_match; }; /** * Find the first closest matching version in history * according to the diffRowCount method on Version * * Useful for debugging version mismatches. * See also dumpClosestMatch below */ const Version* findFirstClosestMatch(const Version* match, VersionMeta& vm) const; /** * dump * * Helper for dumping out a history * full gives all version info as well as summary */ void dump(const bool full = false) const; /** * dumpClosestMatch * * Helper for dumping out closest matching version * in history */ void dumpClosestMatch(const Version* target) const; /** Public member vars */ const Granularity m_granularity; const RecordRange m_range; private: /** * StoredVersion * Internal structure used to track versions */ struct StoredVersion { VersionMeta m_meta; Version* m_version; }; Vector<StoredVersion> m_storedVersions; Uint64 m_nextNumber; }; #endif
24.401244
84
0.619503
[ "vector" ]
295de3df548a9e9264c9810348c51922b3f537c0
2,082
cc
C++
src/attributes_builder.cc
istio/old_mixerclient_repo
b8948db16760777aadab04198e810250e4ec5e16
[ "Apache-2.0" ]
3
2018-06-26T08:36:49.000Z
2019-05-31T22:34:11.000Z
src/attributes_builder.cc
yangminzhu/mixerclient
b8948db16760777aadab04198e810250e4ec5e16
[ "Apache-2.0" ]
null
null
null
src/attributes_builder.cc
yangminzhu/mixerclient
b8948db16760777aadab04198e810250e4ec5e16
[ "Apache-2.0" ]
5
2018-03-28T15:54:34.000Z
2020-11-15T16:07:57.000Z
/* Copyright 2017 Istio Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "include/attributes_builder.h" #include <arpa/inet.h> namespace istio { namespace mixer_client { namespace { // Pilot mesh attributes with the suffix will be treated as ipv4. // They will use BYTES attribute type. const std::string kIPSuffix = ".ip"; } // namespace // Mesh attributes from Pilot are all string type. // The attributes with ".ip" suffix will be treated // as ipv4 and use BYTES attribute type. void AttributesBuilder::AddIpOrString(const std::string& name, const std::string& value) { // Check with ".ip" suffix, if (name.length() <= kIPSuffix.length() || name.compare(name.length() - kIPSuffix.length(), kIPSuffix.length(), kIPSuffix) != 0) { AddString(name, value); return; } if (value.empty()) { AddBytes(name, value); return; } in_addr ipv4_bytes; if (inet_pton(AF_INET, value.c_str(), &ipv4_bytes) == 1) { AddBytes(name, std::string(reinterpret_cast<const char*>(&ipv4_bytes), sizeof(ipv4_bytes))); return; } in6_addr ipv6_bytes; if (inet_pton(AF_INET6, value.c_str(), &ipv6_bytes) == 1) { AddBytes(name, std::string(reinterpret_cast<const char*>(&ipv6_bytes), sizeof(ipv6_bytes))); return; } GOOGLE_LOG(ERROR) << "Could not convert to ip: " << name << ": " << value; AddString(name, value); } } // namespace mixer_client } // namespace istio
32.030769
76
0.659462
[ "mesh" ]
295e4d78f08f59b06750b78038891b4a82c1cab3
1,545
cpp
C++
examples/chord_hop_distribution.cpp
veluca93/distributedsim
577663527a003f321b9b4d33c4f703b56f7da54b
[ "Apache-2.0" ]
1
2017-07-18T03:20:56.000Z
2017-07-18T03:20:56.000Z
examples/chord_hop_distribution.cpp
veluca93/distributedsim
577663527a003f321b9b4d33c4f703b56f7da54b
[ "Apache-2.0" ]
null
null
null
examples/chord_hop_distribution.cpp
veluca93/distributedsim
577663527a003f321b9b4d33c4f703b56f7da54b
[ "Apache-2.0" ]
null
null
null
#include "chord.hpp" template<> std::atomic<long long> Node<std::size_t>::queued_messages{0}; template<> std::atomic<long long> Node<std::size_t>::all_messages{0}; int main(int argc, char** argv) { if (argc < 4) { std::cerr << "Usage: " << argv[0] << " b n m" << std::endl; return 1; } uint64_t bits = atoi(argv[1]); uint64_t nodes = atoi(argv[2]); uint64_t messages = atoi(argv[3]); std::vector<std::atomic<uint64_t>> counts(bits+1); std::atomic<uint64_t> received_messages{0}; auto complete_callback = [&](const Node<std::size_t>* n, Message<std::size_t> msg) { counts[msg.get_hops()]++; received_messages++; }; HardwareManager<std::size_t> hwm(1<<bits, std::thread::hardware_concurrency(), 0); for (unsigned i=0; i<nodes; i++) { hwm.add_node<ChordNode>(hwm.gen_id(), bits, complete_callback); //std::cerr << "Added node " << i << std::endl; } hwm.run(); for (unsigned i=0; i<messages; i++) { hwm.gen_message(hwm.get_random_node()); //std::cerr << "Generated message " << i << std::endl; } while (received_messages != messages) { using namespace std::literals::chrono_literals; std::this_thread::sleep_for(10ms); } hwm.stop(); std::cout.precision(3); std::cout << (long long)Node<std::size_t>::all_messages << " events processed" << std::endl; for (unsigned i=1; i<bits+1; i++) { std::cout << 1.0*counts[i]/received_messages << " "; } std::cout << std::endl; }
35.113636
96
0.591586
[ "vector" ]
295edb835bae4616a338f03178c488d9cccb7731
3,937
cpp
C++
groups/csa/csamisc/csamisc_hashptr.cpp
hyrosen/bde_verify
c2db13c9f1649806bfd9155e2bffcbbcf9d54918
[ "Apache-2.0" ]
null
null
null
groups/csa/csamisc/csamisc_hashptr.cpp
hyrosen/bde_verify
c2db13c9f1649806bfd9155e2bffcbbcf9d54918
[ "Apache-2.0" ]
null
null
null
groups/csa/csamisc/csamisc_hashptr.cpp
hyrosen/bde_verify
c2db13c9f1649806bfd9155e2bffcbbcf9d54918
[ "Apache-2.0" ]
null
null
null
// csamisc_hashptr.cpp -*-C++-*- #include <clang/AST/ASTContext.h> #include <clang/AST/Decl.h> #include <clang/AST/DeclBase.h> #include <clang/AST/Expr.h> #include <clang/AST/Type.h> #include <clang/ASTMatchers/ASTMatchFinder.h> #include <clang/ASTMatchers/ASTMatchers.h> #include <clang/ASTMatchers/ASTMatchersInternal.h> #include <clang/ASTMatchers/ASTMatchersMacros.h> #include <csabase_analyser.h> #include <csabase_registercheck.h> #include <csabase_util.h> #include <llvm/ADT/Optional.h> #include <llvm/ADT/VariadicFunction.h> #include <utils/event.hpp> #include <utils/function.hpp> #include <string> namespace csabase { class PPObserver; } namespace csabase { class Visitor; } using namespace csabase; using namespace clang; using namespace clang::ast_matchers; using namespace clang::ast_matchers::internal; // ---------------------------------------------------------------------------- static std::string const check_name("hash-pointer"); // ---------------------------------------------------------------------------- namespace { struct report // Callback object for detecting calls to std::hash<const char *>(). { Analyser& d_analyser; report(Analyser& analyser); // Initialize an object of this type. void operator()(); // Callback for the end of the translation unit. void match_hash_char_ptr(const BoundNodes &nodes); // Callback when matching calls are found. }; report::report(Analyser& analyser) : d_analyser(analyser) { } internal::DynTypedMatcher hash_char_ptr_matcher() // Return an AST matcher which looks for calls to std::hash<Type *>. { return decl(forEachDescendant( callExpr( callee(functionDecl( hasName("operator()"), parameterCountIs(1), hasParent(recordDecl(hasName("std::hash"))), hasParameter( 0, hasType(pointerType(unless(anyOf( pointee(asString("void")), pointee(asString("const void")), pointee(asString("volatile void")), pointee(asString("const volatile void")))))))))) .bind("hash"))); } void report::match_hash_char_ptr(const BoundNodes &nodes) { const CallExpr *hash = nodes.getNodeAs<CallExpr>("hash"); d_analyser.report(hash, check_name, "HC01", "Hash will depend only on the pointer value, not the " "contents, of the argument"); } void report::operator()() { MatchFinder mf; OnMatch<report, &report::match_hash_char_ptr> m1(this); mf.addDynamicMatcher(hash_char_ptr_matcher(), &m1); mf.match(*d_analyser.context()->getTranslationUnitDecl(), *d_analyser.context()); } void subscribe(Analyser& analyser, Visitor& visitor, PPObserver& observer) // Hook up the callback functions. { analyser.onTranslationUnitDone += report(analyser); } } // close anonymous namespace // ---------------------------------------------------------------------------- static RegisterCheck c1(check_name, &subscribe); // ---------------------------------------------------------------------------- // Copyright (C) 2014 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ----------------------------------
32.53719
79
0.601727
[ "object" ]
2960bd9c876ee70a537d5519e1dd5dd825d60944
7,319
cpp
C++
src/Tests/testPseudoLikelihood.cpp
andreas-hjortgaard/master_thesis
bb03ca9fc030c5142a7dde2ec80a85abc06e2cfb
[ "MIT" ]
null
null
null
src/Tests/testPseudoLikelihood.cpp
andreas-hjortgaard/master_thesis
bb03ca9fc030c5142a7dde2ec80a85abc06e2cfb
[ "MIT" ]
null
null
null
src/Tests/testPseudoLikelihood.cpp
andreas-hjortgaard/master_thesis
bb03ca9fc030c5142a7dde2ec80a85abc06e2cfb
[ "MIT" ]
1
2018-10-20T00:43:36.000Z
2018-10-20T00:43:36.000Z
/* Conditional Random Fields for Object Localization * Master thesis source code * * Authors: * Andreas Christian Eilschou (jwb226@alumni.ku.dk) * Andreas Hjortgaard Danielsen (gxn961@alumni.ku.dk) * * Department of Computer Science * University of Copenhagen * Denmark * * Date: 27-08-2012 */ #include <cstdio> #include <cstdlib> #include <iostream> #include <fstream> #include "Types.h" #include "DataManager.h" #include "ObjectiveFunctions/PseudoLikelihood.h" #include "ObjectiveFunctions/PseudoLikelihoodGradient.h" #include "Learning/LBFGS.h" #include "Measures/LossMeasures.h" using namespace std; //int testPseudoLikelihood() { int main(int argc, char **argv) { short stepSize = 16; // stepSize = 1 to use ESS. Otherwise use sliding window int computeFiniteDifferenceGradient = 1; int computeWeights = 0; int computeLossOfWeights = 0; // initialize data manager DataManager dataman; try { //dataman.loadImages("../pascal/USURF3K/", "subsets/train_width_height.txt"); //dataman.loadBboxes("../pascal/Annotations/ess/bicycle_train.ess"); dataman.loadImages("../cows-train/EUCSURF-3000/", "../subsets/cows_train_width_height.txt"); dataman.loadBboxes("../cows-train/Annotations/TUcow_train.ess"); } catch (int e) { if (e == FILE_NOT_FOUND) { fprintf(stderr, "There was a problem opening a file!\n"); return -1; } } ConditionalRandomField crf(&dataman); crf.setStepSize(stepSize); // create log-likelihood objective function with regularization PseudoLikelihood loglik(&dataman, &crf); loglik.setLambda(1000.0);//(2.0); no regularization PseudoLikelihoodGradient loglikgrad(&dataman, &crf); loglikgrad.setLambda(1000.0);//(2.0); no regularization cout << "StepSize: " << loglik.getStepSize() << " " << loglikgrad.getStepSize() << endl; // set random weights int num_weights = 3000; Weights w(num_weights); // initialize weights between -1 and 1 srand(time(NULL)); rand(); for (int i=0; i<num_weights; i++) { w[i] = 0.0 + i*0.00001; //((double) rand() / RAND_MAX)*2 - 1; } crf.setWeights(w); printf("%d\n", num_weights); // test evaluate printf("Computing pseudo-log-likelihood...\n"); double fval = loglik.evaluate(w); printf("Pseudo-Loglikelihood = %.6f\n", fval); printf("Computing gradient...\n"); Dvector grad(num_weights); loglikgrad.evaluate(grad, w); printf("Gradient = (%.2f, %.2f, %.2f, ...)\n", grad[0], grad[1], grad[2]); // print gradient //for (size_t i=0; i<num_weights; i++) { // printf("grad[%d] = %.6f\n", (int) i, grad[i]); //} if(computeFiniteDifferenceGradient) { printf("Computing finite difference approximation...\n"); double h, fx; Dvector wh(w); Dvector fdgrad(num_weights); Dvector fxh(num_weights); h = 1e-8; //num_weights = 10; // new w for (int i=0; i<num_weights; i++) { printf("%i\n", i); wh[i] += h; fxh[i] = loglik.evaluate(wh); wh[i] -= h; } fx = loglik.evaluate(w); // compute and print gradient double tol = 0.1; for (int i=0; i<num_weights; i++) { fdgrad[i] = (fxh[i] - fx)/h; if ((grad[i] - fdgrad[i] > tol) || (fdgrad[i] - grad[i] > tol)) { printf("Gradient approximation differs with more than %.6f:\n\t grad[%d] = %.6f\t fdgrad[%d] = %.6f\n", tol, i, grad[i], i, fdgrad[i]); } } printf("Done!\n"); } if (computeWeights) { double startTimeComputeWeights = gettime(); // train parameters with BFGS LBFGS lbfgs(&loglik, &loglikgrad); Weights w_new(num_weights, 0.0); printf("Learning parameters with LBFGS...\n"); try { w_new = lbfgs.learnWeights(w); } catch (int e) { if (e == ROUNDOFF_ERROR) { fprintf(stderr, "BFGS::learnWeights threw a round-off error!\n"); return ROUNDOFF_ERROR; } if (e == DIM_ERROR) { fprintf(stderr, "BFGS::learnWeights threw a dimensionality error!\n"); return DIM_ERROR; } if (e == NOT_A_NUMBER) { fprintf(stderr, "BFGS::learnWeights threw a NAN error!\n"); return NOT_A_NUMBER; } } double endTimeComputeWeights = gettime(); printf("Computing weights took %.6f seconds.\n", endTimeComputeWeights - startTimeComputeWeights); // print result //for (size_t i=0; i<10; i++) { // printf("w[%d] = %.6f\n", (int) i, w_new[i]); //} ofstream weight_file("pseudo_likelihood_weights_cow.txt"); if (!weight_file) { cerr << "Could not open file weights.txt" << endl; } // store result in file for (int i=0; i<num_weights; i++) { //printf("w[%d] = %.6f\n", (int) i, w_new[i]); weight_file << w_new[i] << endl; } weight_file.close(); cout << "Done!" << endl; } if (computeLossOfWeights) { string pathImages = "../cows-train/EUCSURF-3000/"; string pathSubset = "../subsets/cows_train_width_height.txt"; string pathBboxes = "../cows-train/Annotations/TUcow_train.ess"; string pathWeights = "pseudo_likelihood_weights_cow.txt"; DataManager lossDataMan(pathImages, pathBboxes, pathSubset, pathWeights); string plotName = "test_output"; printRecallOverlap(plotName, lossDataMan, stepSize, true); /* //string pathImages = "../pascal/USURF3K/"; //string pathSubset = "subsets/val_width_height.txt"; //string pathBboxes = "../pascal/Annotations/ess/bicycle_val.ess"; //string pathWeights = "pseudo_likelihood_weights_bicycle.txt"; //string pathImages = "../pascal/USURF3K/"; //string pathSubset = "subsets/train_width_height.txt"; //string pathBboxes = "../pascal/Annotations/ess/bicycle_train.ess"; //string pathWeights = "../pascal/Weights/bicycle2006-w.txt"; //string pathWeights = "../pascal/Weights/bicycle2006-w.txt"; DataManager lossDataMan(pathImages, pathBboxes, pathSubset, pathWeights); //srand(time(NULL)); rand(); // initialize weights between -1 and 1 //for (int i=0; i<num_weights; i++) { // w[i] = ((double) rand() / RAND_MAX)*2 - 1; //} //lossDataMan.setWeights(w); double averageAreaOverlap = computeAverageAreaOverlap(lossDataMan, SearchIx(), stepSize); fprintf(stdout, "Average Area Overlap is: %.6f\n", averageAreaOverlap); RecallOverlap recallOverlap = computeRecallOverlap(lossDataMan, SearchIx(), stepSize); fprintf(stdout, "Area under recall-overlap curve: %.6f\n\n", recallOverlap.AUC); //fprintf(stdout, "Size of overlap vector: %d\n", (int)recallOverlap.overlap.size()); //fprintf(stdout, "Size of recall vector: %d\n", (int)recallOverlap.recall.size()); // Draw a very nice plot with GNUPLOT! string plotName = "test_output"; try { Gnuplot g1("lines"); cout << "*** plotting recall-overlap curve" << endl; ostringstream os; os << "Recall-overlap curve\\n(AUC: " << recallOverlap.AUC << ")"; string AUCString = os.str(); g1.set_title(AUCString); cout << endl << endl << "*** save to ps " << endl; g1.savetops(plotName); g1.set_grid(); g1.set_xlabel("Minimum overlap").set_ylabel("Recall"); g1.plot_xy(recallOverlap.overlap,recallOverlap.recall,"Recall-overlap"); } catch (GnuplotException ge) { cerr << ge.what() << endl; }*/ } return 0; }
29.631579
146
0.641754
[ "object", "vector" ]
296131b4d7e23a6564e0467fc8cdf28020e4e923
29,247
hpp
C++
ext/mummer/sparseSA.hpp
at-cg/ChainX
d93974af881ec29bfe0227ae8113ebcf6af630cc
[ "Apache-2.0" ]
3
2021-07-26T12:12:29.000Z
2022-01-18T13:46:10.000Z
ext/mummer/sparseSA.hpp
AT-CG/ChainX
2b4c902a8981eceda17e72dc7409f744ad3a0bc3
[ "Apache-2.0" ]
null
null
null
ext/mummer/sparseSA.hpp
AT-CG/ChainX
2b4c902a8981eceda17e72dc7409f744ad3a0bc3
[ "Apache-2.0" ]
null
null
null
#ifndef __sparseSA_hpp__ #define __sparseSA_hpp__ #include <vector> #include <string> #include <fstream> #include <iostream> #include <algorithm> #include <limits> #include <type_traits> #include <limits.h> #include <cstring> #include <cassert> #include <cmath> #include "48bit_index.hpp" #include "openmp_qsort.hpp" namespace mummer { namespace mummer { static const unsigned int BITADD[256] = { UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX,//0-9 UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX,//10-19 UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX,//20-29 UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX,//30-39 UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX,//40-49 UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX,//50-59 UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, 0, UINT_MAX, 1, UINT_MAX, UINT_MAX,//60-69 65:A, 67:C UINT_MAX, 2, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX,//70-79 71:G UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, 3, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX,//80-89 84:T UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, 0, UINT_MAX, 1, //90-99 97:a, 99: c UINT_MAX, UINT_MAX, UINT_MAX, 2, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX,//100-109 103:g UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, 3, UINT_MAX, UINT_MAX, UINT_MAX,//110-119 116:t UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX,//120-129 UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX,//130-139 UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX,//140-149 UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX,//150-159 UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX,//160-169 UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX,//170-179 UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX,//180-189 UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX,//190-199 UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX,//200-209 UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX,//210-219 UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX,//220-229 UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX,//230-239 UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX,//240-249 UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX, UINT_MAX };//250-255 // Either a vector of 32-bits offsets, or 48-bits. struct vector_32_48 { std::vector<int> small; // Suffix array. fortyeight_index<int64_t> large; bool is_small; void resize(size_t N, bool force_large = false) { is_small = !force_large && (N < ((size_t)1 << 31)); if(is_small) small.resize(N); else large.resize(N); } size_t size() const { return is_small ? small.size() : large.size(); } long operator[](size_t i) const { return is_small ? small[i] : large[i]; } vector_32_48() = default; vector_32_48(const std::string& path) { load(path); } bool save(std::ostream&& os) const; inline bool save(const std::string& path) const { return save(std::ofstream(path)); } bool load(std::istream&& is); inline bool load(const std::string& path) { return load(std::ifstream(path)); } }; // Stores the LCP array in an unsigned char (0-255). Values larger // than or equal to 255 are stored in a sorted array. // Simulates a vector<int> LCP; struct vec_uchar { typedef unsigned char small_type; typedef unsigned int large_type; static const large_type max = std::numeric_limits<small_type>::max(); struct item_t{ item_t() = default; item_t(size_t i) : idx(i) { } item_t(size_t i, large_type v) : idx(i), val(v) { } size_t idx; large_type val; bool operator < (const item_t& t) const { return idx < t.idx; } bool operator==(const item_t& t) const { return idx == t.idx && val == t.val; } }; static inline bool first_comp(const item_t& a, const item_t& b) { return a.idx + a.val < b.idx + b.val || (a.idx + a.val == b.idx + b.val && a.idx < b.idx); } typedef std::vector<item_t> item_vector; std::vector<small_type> vec; // LCP values from 0-65534 item_vector M; vector_32_48* sa; vec_uchar(vector_32_48& sa_) : vec(sa_.size(), 0), sa(&sa_) { } vec_uchar(vec_uchar&& rhs, vector_32_48& sa_) : vec(std::move(rhs.vec)) , M(std::move(rhs.M)) , sa(&sa_) { } vec_uchar(const std::string& path, vector_32_48& sa_) : sa(&sa_) { load(path); } void resize(size_t N) { vec.resize(N, 0); } // Vector X[i] notation to get LCP values. large_type operator[] (size_t idx) const { const large_type res = vec[idx]; if(res != max) return res; idx = (*sa)[idx]; auto it = upper_bound(M.begin(), M.end(), item_t(idx)); assert(it != M.begin()); --it; return it->val - (idx - it->idx); } // Actually set LCP values, distingushes large and small LCP // values. void set(size_t idx, large_type v, item_vector& M_) { if(v < max) { vec[idx] = v; } else { vec[idx] = max; M_.push_back(item_t((*sa)[idx], v)); } } inline void set(size_t idx, large_type v) { set(idx, v, M); } // Once all the values are set, call init. This will assure the // values >= 255 are sorted by index for fast retrieval. The values // are compacted into ranges. void init(); // Same as init, but for multi-threaded version. Merge M vectors. void init_merge(const std::vector<item_vector>& Ms); bool save(std::ostream&& os) const; inline bool save(const std::string& path) const { return save(std::ofstream(path)); } bool load(std::istream&& is); inline bool load(const std::string& path) { return load(std::ifstream(path)); } long index_size_in_bytes() const { long indexSize = 0L; indexSize += sizeof(vec) + vec.capacity()*sizeof(small_type); indexSize += sizeof(M) + M.capacity()*(sizeof(size_t)+sizeof(large_type)); return indexSize; } }; // Match find by findMEM. struct match_t { match_t() : ref(0), query(0), len(0) { } match_t(long r, long q, long l) : ref(r), query(q), len(l) { } long ref; // position in reference sequence long query; // position in query long len; // length of match }; // XXX: Work around essamem bug for now: do not allow length to hang // of passed the end of query. inline match_t make_match(long r, long q, long l, long max) { return match_t(r, q, std::max((long)0, std::min(l, max - q))); } struct saTuple_t { saTuple_t(): left(0), right(0) {} saTuple_t(unsigned int l, unsigned int r): left(l), right(r) {} unsigned int left; unsigned int right; bool operator==(const saTuple_t& rhs) const { return left == rhs.left && right == rhs.right; } }; // depth : [start...end] struct interval_t { interval_t() : depth(-1), start(1), end(0) { } interval_t(long s, long e, long d) : depth(d), start(s), end(e) { } void reset(long e) { start = 0; end = e; depth = 0; } long depth, start, end; long size() const { return end - start + 1; } }; struct bounded_string { const char* const s_; const size_t al_; // actual length size_t l_; // length rounded to K static long compute_l(size_t l, long K) { return l + K + (l % K != 0 ? K - (l % K) : 0); } bounded_string(const char* s, size_t l, long K) : s_(s) , al_(l) , l_(compute_l(l, K)) { } bounded_string(const std::string s, long K) : bounded_string(s.c_str(), s.size(), K) { } bounded_string(const char* s, long K) : bounded_string(s, strlen(s), K) { } void set_k(long K) { l_ = compute_l(al_, K); } char operator[](size_t i) const { if(__builtin_expect(i < al_, 1)) return s_[i]; return '$'; } size_t size() const noexcept { return l_; } size_t length() const noexcept { return l_; } size_t capacity() const noexcept { return l_; } std::string substr (size_t pos = 0, size_t len = std::string::npos) const { pos = std::min(pos, al_); return std::string(std::min(pos, al_), std::min(len, al_ - pos)); } const char* operator+(size_t offset) const { return s_ + offset; } }; // Auxilliary information about sparseSA struct sparseSA_aux { long N; //!< Length of the sequence. long K; // suffix sampling, K = 1 every suffix, K = 2 every other suffix, K = 3, every 3rd sffix long logN; // ceil(log(N)) long NKm1; // N/K - 1 bool _4column; // Use 4 column output format. bool hasSufLink; bool hasChild; bool hasKmer; long kMerSize; int sparseMult; bool nucleotidesOnly; sparseSA_aux() = default; sparseSA_aux(long N_, long K_, bool __4column, bool child_, bool suflink_, bool kmer_, long kMerSize_, int sparseMult_, bool nucleotidesOnly_) : N(N_) , K(K_) , logN((long)std::ceil(std::log(N/K) / std::log(2.0))) , NKm1(N/K-1) , _4column(__4column) , hasSufLink(suflink_) , hasChild(child_) , hasKmer(kmer_) , kMerSize(kMerSize_) , sparseMult(sparseMult_) , nucleotidesOnly(nucleotidesOnly_) { } sparseSA_aux(const std::string& path) { load(path); } bool save(std::ostream&& os) const; bool save(const std::string& path) const { return save(std::ofstream(path)); } bool load(std::istream&& is); bool load(const std::string& path) { return load(std::ifstream(path)); } }; struct sparseSA : sparseSA_aux { bounded_string S; //!< Reference to sequence data. vector_32_48 SA; // Suffix array. vector_32_48 ISA; // Inverse suffix array vec_uchar LCP; // Simulates a vector<int> LCP. std::vector<int> CHILD; //child table std::vector<saTuple_t> KMR; //fields for lookup table of sa intervals to a certain small depth long kMerTableSize; long index_size_in_bytes() const ; // Constructor builds sparse suffix array. sparseSA(bounded_string&& S_, bool __4column, long K_, bool suflink_, bool child_, bool kmer_, int sparseMult_, int kMerSize_, bool nucleotidesOnly_); sparseSA(const char* S_, size_t Slen, bool __4column, long K_, bool suflink_, bool child_, bool kmer_, int sparseMult_, int kMerSize_, bool nucleotidesOnly_) : sparseSA(bounded_string(S_, Slen, K_), __4column, K_, suflink_, child_, kmer_, sparseMult_, kMerSize_, nucleotidesOnly_) { } sparseSA(const std::string& S_, bool __4column, long K_, bool suflink_, bool child_, bool kmer_, int sparseMult_, int kMerSize_, bool nucleotidesOnly_) : sparseSA(S_.c_str(), S_.length(), __4column, K_, suflink_, child_, kmer_, sparseMult_, kMerSize_, nucleotidesOnly_) { } // Constructor load sparse suffix array from file sparseSA(const char* S_, size_t Slen, const std::string& prefix) : S(S_, Slen, 1) , LCP(SA) { load(prefix); S.set_k(K); } sparseSA(const std::string& S_, const std::string& prefix) : sparseSA(S_.c_str(), S_.length(), prefix) { } sparseSA(sparseSA&& rhs) : sparseSA_aux(rhs) , S(rhs.S) , SA(std::move(rhs.SA)) , ISA(std::move(rhs.ISA)) , LCP(std::move(rhs.LCP), SA) , CHILD(std::move(rhs.CHILD)) , KMR(std::move(rhs.KMR)) , kMerTableSize(rhs.kMerTableSize) { } static sparseSA create_auto(const char* S, size_t Slen, int min_len, bool nucleotidesOnly_, int K = 1, bool off48 = false); // Modified Kasai et all for LCP computation. void computeLCP(); //Modified Abouelhoda et all for CHILD Computation. void computeChild(); //build look-up table for sa intervals of kmers up to some depth void computeKmer(); // Not used at this point // Radix sort required to construct transformed text for sparse SA construction. // void radixStep(int *t_new, int *SA, long &bucketNr, long *BucketBegin, long l, long r, long h); // Binary search for left boundry of interval. inline long bsearch_left(char c, long i, long s, long e) const; // Binary search for right boundry of interval. inline long bsearch_right(char c, long i, long s, long e) const; // Simple suffix array search. bool search(const char* P, size_t Plen, long &start, long &end) const; inline bool search(std::string &P, long &start, long &end) const { return search(P.c_str(), P.length(), start, end); } // Simple top down traversal of a suffix array. inline bool top_down(char c, long i, long &start, long &end) const; inline bool top_down_faster(char c, long i, long &start, long &end) const; inline bool top_down_child(char c, interval_t &cur) const; // Traverse pattern P starting from a given prefix and interval // until mismatch or min_len characters reached. void traverse(const char* P, size_t Plen, long prefix, interval_t &cur, int min_len) const; void traverse(const std::string &P, long prefix, interval_t &cur, int min_len) const { traverse(P.c_str(), P.length(), prefix, cur, min_len); } void traverse_faster(const char* P, size_t Plen, const long prefix, interval_t &cur, int min_len) const; void traverse_faster(const std::string &P,const long prefix, interval_t &cur, int min_len) const { traverse_faster(P.c_str(), P.length(), prefix, cur, min_len); } // Simulate a suffix link. bool suffixlink(interval_t &m) const; // Expand ISA/LCP interval. Used to simulate suffix links. inline bool expand_link(interval_t &link) const { long thresh = 2 * link.depth * logN, exp = 0; // Threshold link expansion. long start = link.start; long end = link.end; while(LCP[start] >= link.depth) { exp++; if(exp >= thresh) return false; start--; } while(end < NKm1 && LCP[end+1] >= link.depth) { exp++; if(exp >= thresh) return false; end++; } link.start = start; link.end = end; return true; } // Given a position i in S, finds a left maximal match of minimum // length within K steps. When flip_forward is true, the match // coordinates are flipped (presumably P is reversed complemented) template<typename Output> void find_Lmaximal(const char* P, size_t Plen, long prefix, long i, long len, int min_len, bool flip_forward, Output out) const; template<typename Output> void find_Lmaximal(const std::string &P, long prefix, long i, long len, int min_len, bool flip_forward, Output out) const { find_Lmaximal(P.c_str(), P.length(), prefix, i, len, min_len, flip_forward, out); } // NOTE: min_len must be > 1 template<typename Output> void findMAM_each(const char* P, size_t Plen, int min_len, bool flip_forward, Output out) const; template<typename Output> void findMAM_each(const std::string& P, int min_len, bool flip_forward, Output out) const { findMAM_each(P.c_str(), P.length(), min_len, flip_forward, out); } void findMAM(const char* P, size_t Plen, int min_len, bool flip_forward, std::vector<match_t>& matches) const { findMAM_each(P, Plen, min_len, flip_forward, [&](const match_t& m) { matches.push_back(m); }); } void findMAM(const std::string &P, int min_len, bool flip_forward, std::vector<match_t>& matches) const { findMAM(P.c_str(), P.length(), min_len, flip_forward, matches); } // Returns true if the position p1 in the query pattern and p2 in // the reference is left maximal. template<typename STRING> inline bool is_leftmaximal(const STRING& P, long p1, long p2) const { return p1 == 0 || p2 == 0 || P[p1 - 1] != S[p2 - 1]; } // Maximal Almost-Unique Match (MAM). Match is unique in the indexed // sequence S. as computed by MUMmer version 2 by Salzberg // et. al. Note this is a "one-sided" query. It "streams" the query // P throught he index. Consequently, repeats can occur in the // pattern P. void MAM(const std::string& P, int min_len, bool flip_forward, std::vector<match_t>& matches) const { if(K != 1) return; // Only valid for full suffix array. findMAM(P, min_len, flip_forward, matches); } void MAM(const char* P, size_t Plen, int min_len, bool flip_forward, std::vector<match_t>& matches) const { if(K != 1) return; // Only valid for full suffix array. findMAM(P, Plen, min_len, flip_forward, matches); } // Given an interval where the given prefix is matched up to a // mismatch, find all MEMs up to a minimum match depth. template<typename Output> void collectMEMs_each(const char* P, size_t Plen, long prefix, interval_t mli, interval_t xmi, int min_len, bool flip_forward, Output out) const; template<typename Output> void collectMEMs_each(const std::string &P, long prefix, interval_t mli, interval_t xmi, int min_len, bool flip_forward, Output out) const { collectMEMs_each(P.c_str(), P.length(), prefix, mli, xmi, min_len, flip_forward, out); } // Find all MEMs given a prefix pattern offset k. template<typename Output> void findMEM_k_each(const char* P, size_t Plen, long k, int min_len, bool flip_forward, Output out) const; // Find Maximal Exact Matches (MEMs) template<typename Output> void findMEM_each(const char* P, size_t Plen, int min_len, bool flip_forward, Output out) const { for(int k = 0; k < K; k++) findMEM_k_each(P, Plen, k, min_len, flip_forward, out); } template<typename Output> void findMEM_each(const std::string &P, int min_len, bool flip_forward, Output out) const { findMEM_each(P.c_str(), P.length(), min_len, flip_forward, out); } void MEM(const char* P, size_t Plen, int min_len, bool flip_forward, std::vector<match_t>& matches) const { findMEM_each(P, Plen, min_len, flip_forward, [&](const match_t& m) { matches.push_back(m); }); } void MEM(const std::string &P, int min_len, bool flip_forward, std::vector<match_t>& matches) const { MEM(P.c_str(), P.length(), min_len, flip_forward, matches); } // Maximal Unique Match (MUM) template<typename Output> void findMUM_each(const char* P, size_t Plen, int min_len, bool flip_forward, Output out) const; template<typename Output> void findMUM_each(const std::string &P, int min_len, bool flip_forward, Output out) const { findMUM_each(P.c_str(), P.length(), min_len, flip_forward, out); } void MUM(const std::string &P, int min_len, bool flip_forward, std::vector<match_t>& matches) const { findMUM_each(P, min_len, flip_forward, [&](const match_t& m) { matches.push_back(m); }); } //save index to files bool save(const std::string &prefix) const; //load index from file bool load(const std::string &prefix); //construct void construct(bool off48 = false); }; // Like the sparseSA, but also know the position of the sub-sequences // and can print a proper match. class sparseSAMatch : public sparseSA { const std::vector<std::string>& descr; // Descriptions of concatenated sequences. const std::vector<long>& startpos; // Lengths of concatenated sequences. const long maxdescrlen; // Maximum length of the sequence description, used for formatting. const bool printSubstring; // const bool printRevCompForw; public: sparseSAMatch(const std::string& S_, const std::vector<std::string>& descr_, const std::vector<long>& startpos_, bool __4column, long K_, bool suflink_, bool child_, bool kmer_, int sparseMult_, int kMerSize_, bool printSubstring_, bool nucleotidesOnly_); long index_size_in_bytes() const; // Maps a hit in the concatenated sequence set to a position in that sequence. void from_set(long hit, long &seq, long &seqpos) const; // Prints match to cout. void print_match(std::ostream& os, match_t m) const; // void print_match(match_t m, std::vector<match_t> &buf) const; // buffered version void print_match(std::ostream& os, std::string meta, bool rc) const; // buffered version // Print MAMs void findMAM(const std::string &P, int min_len, bool flip_forward, std::ostream& os) const { findMAM_each(P, min_len, flip_forward, [&](const match_t& m) { print_match(os, m); }); } void MAM(const std::string& P, int min_len, bool flip_forward, std::ostream& os) const { if(sparseSA::K != 1) return; // Only valid for full suffix array. findMAM(P, min_len, flip_forward, os); } void MAM(const std::string& P, int min_len, bool flip_forward, std::vector<match_t>& matches) const { sparseSA::MAM(P, min_len, flip_forward, matches); } // Print MEMs void MEM(const std::string &P, int min_len, bool flip_forward, std::ostream& os) const { findMEM_each(P, min_len, flip_forward, [&](const match_t& m) { print_match(os, m); }); } void MEM(const std::string &P, int min_len, bool flip_forward, std::vector<match_t>& matches) const { sparseSA::MEM(P, min_len, flip_forward, matches); } // Print MUMs void MUM(const std::string &P, int min_len, bool flip_forward, std::ostream& os) const { findMUM_each(P, min_len, flip_forward, [&](const match_t& m) { print_match(os, m); }); } void MUM(const std::string &P, int min_len, bool flip_forward, std::vector<match_t>& matches) const { sparseSA::MUM(P, min_len, flip_forward, matches); } }; // // Implementation of templated methods // // Finds maximal almost-unique matches (MAMs) These can repeat in the // given query pattern P, but occur uniquely in the indexed reference S. template<typename Output> void sparseSA::findMAM_each(const char* P, size_t Plen, int min_len, bool flip_forward, Output out) const { interval_t cur(0, N-1, 0); long prefix = 0; while(prefix < (long)Plen) { // Traverse SA top down until mismatch or full string is matched. if(hasChild) traverse_faster(P, Plen, prefix, cur, Plen); else traverse(P, Plen, prefix, cur, Plen); if(cur.depth <= 1) { cur.depth = 0; cur.start = 0; cur.end = N-1; prefix++; continue; } if(cur.size() == 1 && cur.depth >= min_len) { if(is_leftmaximal(P, prefix, SA[cur.start])) { // Yes, it's a MAM. // match_t m(SA[cur.start], prefix, cur.depth); // if(flip_forward) m.query = Plen-1-prefix; // out(m); // XXX: until essamem bug is fixed out(make_match(SA[cur.start], !flip_forward ? prefix : (long)Plen-1-prefix, cur.depth, Plen)); } } do { cur.depth = cur.depth-1; cur.start = ISA[SA[cur.start] + 1]; cur.end = ISA[SA[cur.end] + 1]; prefix++; if( cur.depth == 0 || !expand_link(cur) ) { cur.depth = 0; cur.start = 0; cur.end = N-1; break; } } while(cur.depth > 0 && cur.size() == 1); } // currentCount = memCount; } // Maximal Unique Match (MUM) template<typename Output> void sparseSA::findMUM_each(const char* P, size_t Plen, int min_len, bool flip_forward, Output out) const { // Find unique MEMs. std::vector<match_t> matches; MAM(P, Plen, min_len, flip_forward, matches); // memCount=0; struct by_ref { bool operator() (const match_t &a, const match_t &b) const { return (a.ref == b.ref) ? a.len > b.len : a.ref < b.ref; } }; // Adapted from Stephan Kurtz's code in cleanMUMcand.c in MUMMer v3.20. long currentright, dbright = 0; bool ignorecurrent, ignoreprevious = false; sort(matches.begin(), matches.end(), by_ref()); for(long i = 0; i < (long)matches.size(); i++) { ignorecurrent = false; currentright = matches[i].ref + matches[i].len - 1; if(dbright > currentright) ignorecurrent = true; else { if(dbright == currentright) { ignorecurrent = true; if(!ignoreprevious && matches[i-1].ref == matches[i].ref) ignoreprevious = true; } else { dbright = currentright; } } if(i > 0 && !ignoreprevious) out(matches[i-1]); ignoreprevious = ignorecurrent; } if(!ignoreprevious && !matches.empty()) out(matches.back()); } // For a given offset in the prefix k, find all MEMs. template<typename Output> void sparseSA::findMEM_k_each(const char* P, size_t Plen, long k, int min_len, bool flip_forward, Output out) const { if(k < 0 || k >= K) { std::cerr << "Invalid k " << k << " [0, " << K << "]" << std::endl; return; } // Offset all intervals at different start points. long prefix = k; interval_t mli(0,N/K-1,0); // min length interval interval_t xmi(0,N/K-1,0); // max match interval // Right-most match used to terminate search. const int min_lenK = min_len - (sparseMult*K-1); while( prefix <= (long)Plen - min_lenK) {//BUGFIX: used to be "prefix <= (long)P.length() - (K-k0)" if(hasChild) traverse_faster(P, Plen, prefix, mli, min_lenK); // Traverse until minimum length matched. else traverse(P, Plen, prefix, mli, min_lenK); // Traverse until minimum length matched. if(mli.depth > xmi.depth) xmi = mli; if(mli.depth <= 1) { mli.reset(N/K-1); xmi.reset(N/K-1); prefix+=sparseMult*K; continue; } if(mli.depth >= min_lenK) { if(hasChild) traverse_faster(P, Plen, prefix, xmi, Plen); // Traverse until mismatch. else traverse(P, Plen, prefix, xmi, Plen); // Traverse until mismatch. collectMEMs_each(P, Plen, prefix, mli, xmi, min_len, flip_forward, out); // Using LCP info to find MEM length. // When using ISA/LCP trick, depth = depth - K. prefix += K. prefix+=sparseMult*K; if( !hasSufLink ){ mli.reset(N/K-1); xmi.reset(N/K-1); continue; } else{ int i = 0; bool succes = true; while(i < sparseMult && (succes = suffixlink(mli))){ suffixlink(xmi); i++; } if(!succes){ mli.reset(N/K-1); xmi.reset(N/K-1); continue; } } } else { // When using ISA/LCP trick, depth = depth - K. prefix += K. prefix+=sparseMult*K; if( !hasSufLink) { mli.reset(N/K-1); xmi.reset(N/K-1); continue; } else{ int i = 0; bool succes = true; while(i < sparseMult && (succes = suffixlink(mli))){ i++; } if(!succes){ mli.reset(N/K-1); xmi.reset(N/K-1); continue; } xmi = mli; } } } } // Use LCP information to locate right maximal matches. Test each for // left maximality. template<typename Output> void sparseSA::collectMEMs_each(const char* P, size_t Plen, long prefix, interval_t mli, interval_t xmi, int min_len, bool flip_forward, Output out) const { // All of the suffixes in xmi's interval are right maximal. for(long i = xmi.start; i <= xmi.end; i++) find_Lmaximal(P, Plen, prefix, SA[i], xmi.depth, min_len, flip_forward, out); if(mli.start == xmi.start && mli.end == xmi.end) return; while(xmi.depth >= mli.depth) { // Attempt to "unmatch" xmi using LCP information. if(xmi.end+1 < N/K) xmi.depth = std::max(LCP[xmi.start], LCP[xmi.end+1]); else xmi.depth = LCP[xmi.start]; // If unmatched XMI is > matched depth from mli, then examine rmems. if(xmi.depth >= mli.depth) { // Scan RMEMs to the left, check their left maximality.. while(LCP[xmi.start] >= xmi.depth) { xmi.start--; find_Lmaximal(P, Plen, prefix, SA[xmi.start], xmi.depth, min_len, flip_forward, out); } // Find RMEMs to the right, check their left maximality. while(xmi.end+1 < N/K && LCP[xmi.end+1] >= xmi.depth) { xmi.end++; find_Lmaximal(P, Plen, prefix, SA[xmi.end], xmi.depth, min_len, flip_forward, out); } } } } // Finds left maximal matches given a right maximal match at position i. template<typename Output> void sparseSA::find_Lmaximal(const char* P, size_t Plen, long prefix, long i, long len, int min_len, bool flip_forward, Output out) const { // Advance to the left up to K steps. for(long k = 0; k < sparseMult*K; k++) { // If we reach the end or a mismatch, and the match is long enough, print. if(prefix == 0 || i == 0 || P[prefix-1] != S[i-1]) { if(len >= min_len) { // out(match_t(i, !flip_forward ? prefix : (long)Plen-1-prefix, len)); // XXX: until essamem bug is fixed out(make_match(i, !flip_forward ? prefix : (long)Plen-1-prefix, len, Plen)); } return; // Reached mismatch, done. } prefix--; i--; len++; // Continue matching. } } } // namespace mummer } // namespace mummer #endif // __sparseSA_hpp__
39.791837
139
0.656649
[ "vector" ]
2961beeadc7241203fbfff75767a3ae1a0ba0fc3
3,111
cpp
C++
example/standalone/001_hello_glut_glew.cpp
jnbrq/oglplus
2e072e91292643e0871565ae5147584403846290
[ "BSL-1.0" ]
null
null
null
example/standalone/001_hello_glut_glew.cpp
jnbrq/oglplus
2e072e91292643e0871565ae5147584403846290
[ "BSL-1.0" ]
null
null
null
example/standalone/001_hello_glut_glew.cpp
jnbrq/oglplus
2e072e91292643e0871565ae5147584403846290
[ "BSL-1.0" ]
null
null
null
/** * @example standalone/001_hello_glut_glew.cpp * @brief Shows the basic usage of OGLplus with GLUT and GLEW. * * See the @ref oglplus_tut_001_glut_glew tutorial for a detailed explanation * of the source code of this example. * * Copyright 2008-2015 Matus Chochlik. Distributed under the Boost * Software License, Version 1.0. (See accompanying file * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #include <cassert> #include <iostream> #include <GL/glew.h> #include <GL/glut.h> #include <oglplus/all.hpp> #include <oglplus/opt/resources.hpp> #include <oglplus/text/font2d.hpp> class Example { private: GLint width, height; oglplus::ResourceFile font_file; oglplus::text::Font2D font; oglplus::Context gl; oglplus::Texture tex; oglplus::Framebuffer fbo; public: Example(GLint w, GLint h) : width(w) , height(h) , font_file("fonts", "FreeSans", ".ttf") , font(font_file) { using namespace oglplus; tex.Bind(TextureTarget::Rectangle); fbo.Bind(FramebufferTarget::Read); PrepareText(); } void PrepareText(void) { using namespace oglplus; text::CodePoints code_points = text::UTF8ToCodePoints("Hello World!"); text::Font2D::Layout layout = font.MakeLayout(code_points); std::size_t font_size = height-1; std::vector<unsigned char> buffer(width*height, 0x00); font.Render(font_size, layout, buffer.data(), width, height); Texture::Image2D( TextureTarget::Rectangle, 0, PixelDataInternalFormat::Red, width, height, 0, PixelDataFormat::Red, PixelDataType::UnsignedByte, buffer.data() ); Framebuffer::AttachTexture( FramebufferTarget::Read, FramebufferAttachment::Color, tex, 0 ); } void Display(void) { using namespace oglplus; gl.BlitFramebuffer( 0, 0, width, height, 0, height, width, 0, BufferSelectBit::ColorBuffer, BlitFilter::Nearest ); } }; class SingleExample { private: static Example*& SingleInstance(void) { static Example* test = nullptr; return test; } SingleExample(const SingleExample&); public: SingleExample(GLint width, GLint height) { assert(!SingleInstance()); SingleInstance() = new Example(width, height); } ~SingleExample(void) { assert(SingleInstance()); delete SingleInstance(); SingleInstance() = nullptr; } static void Display(void) { assert(SingleInstance()); SingleInstance()->Display(); glutSwapBuffers(); } }; int main(int argc, char* argv[]) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA); GLint width = 800; GLint height = 150; glutInitWindowSize(width, height); glutInitWindowPosition(100,100); glutCreateWindow("OGLplus+GLUT+GLEW"); if(glewInit() == GLEW_OK) try { glGetError(); SingleExample example(width, height); glutDisplayFunc(&SingleExample::Display); glutMainLoop(); return 0; } catch(oglplus::Error& err) { std::cerr << "Error (in " << (err.GLFunc()?err.GLFunc():"N/A") << "'): " << err.what() << " [" << err.SourceFile() << ":" << err.SourceLine() << "] " << std::endl; } return 1; }
18.628743
78
0.682096
[ "render", "vector" ]
29654e43ce43ed0585ded9f3fbae3e948aaf81fb
10,303
cc
C++
src/stack/mac/amc/AmcPilotAuto.cc
talal00/Simu5G
ffbdda3e4cd873b49d7022912fe25e39d1a503e8
[ "Intel" ]
58
2021-04-15T09:20:26.000Z
2022-03-31T08:52:23.000Z
src/stack/mac/amc/AmcPilotAuto.cc
talal00/Simu5G
ffbdda3e4cd873b49d7022912fe25e39d1a503e8
[ "Intel" ]
34
2021-05-14T15:05:36.000Z
2022-03-31T20:51:33.000Z
src/stack/mac/amc/AmcPilotAuto.cc
talal00/Simu5G
ffbdda3e4cd873b49d7022912fe25e39d1a503e8
[ "Intel" ]
30
2021-04-16T05:46:13.000Z
2022-03-28T15:26:29.000Z
// // Simu5G // // Authors: Giovanni Nardini, Giovanni Stea, Antonio Virdis (University of Pisa) // // This file is part of a software released under the license included in file // "license.pdf". Please read LICENSE and README files before using it. // The above files and the present reference are part of the software itself, // and cannot be removed from it. // #include "stack/mac/amc/AmcPilotAuto.h" using namespace inet; const UserTxParams& AmcPilotAuto::computeTxParams(MacNodeId id, const Direction dir, double carrierFrequency) { EV << NOW << " AmcPilot" << getName() << "::computeTxParams for UE " << id << ", direction " << dirToA(dir) << endl; // Check if user transmission parameters have been already allocated if(amc_->existTxParams(id, dir, carrierFrequency)) { EV << NOW << " AmcPilot" << getName() << "::computeTxParams The Information for this user have been already assigned \n"; return amc_->getTxParams(id, dir, carrierFrequency); } // TODO make it configurable from NED // default transmission mode TxMode txMode = TRANSMIT_DIVERSITY; /** * Select the band which has the best summary * Note: this pilot is not DAS aware, so only MACRO antenna * is used. */ const LteSummaryFeedback& sfb = amc_->getFeedback(id, MACRO, txMode, dir, carrierFrequency); if (TxMode(txMode)==MULTI_USER) // Initialize MuMiMoMatrix amc_->muMimoMatrixInit(dir,id); sfb.print(0,id,dir,txMode,"AmcPilotAuto::computeTxParams"); // get a vector of CQI over first CW std::vector<Cqi> summaryCqi = sfb.getCqi(0); // get the usable bands for this user UsableBands* usableB = nullptr; getUsableBands(id, usableB); Band chosenBand = 0; double chosenCqi = 0; // double max = 0; BandSet bandSet; /// TODO collapse the following part into a single part (e.g. do not fork on mode_ or usableBandsList_ size) // check which CQI computation policy is to be used if(mode_ == MAX_CQI) { // if there are no usable bands, compute the final CQI through all the bands if (usableB == nullptr || usableB->empty()) { chosenBand = 0; chosenCqi = summaryCqi.at(chosenBand); unsigned int bands = summaryCqi.size();// number of bands // computing MAX for(Band b = 1; b < bands; ++b) { // For all Bands double s = (double)summaryCqi.at(b); if(chosenCqi < s) { chosenBand = b; chosenCqi = s; } Band cellWiseBand = amc_->getCellInfo()->getCellwiseBand(carrierFrequency, b); bandSet.insert(cellWiseBand); } EV << NOW <<" AmcPilotAuto::computeTxParams - no UsableBand available for this user." << endl; } else { // TODO Add MIN and MEAN cqi computation methods unsigned int bandIt = 0; unsigned short currBand = (*usableB)[bandIt]; chosenBand = currBand; chosenCqi = summaryCqi.at(currBand); for(; bandIt < usableB->size(); ++bandIt) { currBand = (*usableB)[bandIt]; // For all available band double s = (double)summaryCqi.at(currBand); if(chosenCqi < s) { chosenBand = currBand; chosenCqi = s; } Band cellWiseBand = amc_->getCellInfo()->getCellwiseBand(carrierFrequency, currBand); bandSet.insert(cellWiseBand); } EV << NOW <<" AmcPilotAuto::computeTxParams - UsableBand of size " << usableB->size() << " available for this user" << endl; } } else if(mode_ == MIN_CQI) { // if there are no usable bands, compute the final CQI through all the bands if (usableB == nullptr || usableB->empty()) { chosenBand = 0; chosenCqi = summaryCqi.at(chosenBand); unsigned int bands = summaryCqi.size();// number of bands // computing MIN for(Band b = 1; b < bands; ++b) { // For all LBs double s = (double)summaryCqi.at(b); if(chosenCqi > s) { chosenBand = b; chosenCqi = s; } Band cellWiseBand = amc_->getCellInfo()->getCellwiseBand(carrierFrequency, b); bandSet.insert(cellWiseBand); } EV << NOW <<" AmcPilotAuto::computeTxParams - no UsableBand available for this user." << endl; } else { unsigned int bandIt = 0; unsigned short currBand = (*usableB)[bandIt]; chosenBand = currBand; chosenCqi = summaryCqi.at(currBand); for(; bandIt < usableB->size(); ++bandIt) { currBand = (*usableB)[bandIt]; // For all available band double s = (double)summaryCqi.at(currBand); if(chosenCqi > s) { chosenBand = currBand; chosenCqi = s; } Band cellWiseBand = amc_->getCellInfo()->getCellwiseBand(carrierFrequency, currBand); bandSet.insert(cellWiseBand); } EV << NOW <<" AmcPilotAuto::computeTxParams - UsableBand of size " << usableB->size() << " available for this user" << endl; } } else if(mode_ == ROBUST_CQI) { int target = 0; int s; unsigned int bands = summaryCqi.size();// number of bands EV << "AmcPilotAuto::computeTxParams - computing ROBUST CQI" << endl; // computing MIN for(Band b = 0; b < bands; ++b) { // For all LBs s = summaryCqi.at(b); target += s; } target = target/bands; EV << "\t target value[" << target << "]" << endl; for(Band b = 0; b < bands; ++b) { if( summaryCqi.at(b) >= target ) { EV << b << ")" << summaryCqi.at(b) << "yes" << endl; Band cellWiseBand = amc_->getCellInfo()->getCellwiseBand(carrierFrequency, b); bandSet.insert(cellWiseBand); } else EV << b << ")" << summaryCqi.at(b) << "no" << endl; } chosenBand = 0; chosenCqi = target; } else if (mode_ == AVG_CQI) { // MEAN cqi computation method chosenCqi = getBinder()->meanCqi(sfb.getCqi(0),id,dir); for (Band i = 0; i < sfb.getCqi(0).size(); ++i) { Band cellWiseBand = amc_->getCellInfo()->getCellwiseBand(carrierFrequency, i); bandSet.insert(cellWiseBand); } chosenBand = 0; } else if (mode_ == MEDIAN_CQI) { // MEAN cqi computation method chosenCqi = getBinder()->medianCqi(sfb.getCqi(0),id,dir); for (Band i = 0; i < sfb.getCqi(0).size(); ++i) { Band cellWiseBand = amc_->getCellInfo()->getCellwiseBand(carrierFrequency, i); bandSet.insert(cellWiseBand); } chosenBand = 0; } // Set user transmission parameters only for the best band UserTxParams info; info.writeTxMode(txMode); info.writeRank(sfb.getRi()); info.writeCqi(std::vector<Cqi>(1, chosenCqi)); info.writePmi(sfb.getPmi(chosenBand)); info.writeBands(bandSet); RemoteSet antennas; antennas.insert(MACRO); info.writeAntennas(antennas); // DEBUG EV << NOW << " AmcPilot" << getName() << "::computeTxParams NEW values assigned! - CQI =" << chosenCqi << "\n"; info.print("AmcPilotAuto::computeTxParams"); return amc_->setTxParams(id, dir, info, carrierFrequency); } std::vector<Cqi> AmcPilotAuto::getMultiBandCqi(MacNodeId id , const Direction dir, double carrierFrequency) { EV << NOW << " AmcPilot" << getName() << "::getMultiBandCqi for UE " << id << ", direction " << dirToA(dir) << endl; // TODO make it configurable from NED // default transmission mode TxMode txMode = TRANSMIT_DIVERSITY; /** * Select the band which has the best summary * Note: this pilot is not DAS aware, so only MACRO antenna * is used. */ const LteSummaryFeedback& sfb = amc_->getFeedback(id, MACRO, txMode, dir, carrierFrequency); // get a vector of CQI over first CW return sfb.getCqi(0); } void AmcPilotAuto::setUsableBands(MacNodeId id , UsableBands usableBands) { EV << NOW << " AmcPilotAuto::setUsableBands - setting Usable bands: for node " << id<< " [" ; for(unsigned int i = 0 ; i<usableBands.size() ; ++i) { EV << usableBands[i] << ","; } EV << "]"<<endl; UsableBandsList::iterator it = usableBandsList_.find(id); // if usable bands for this node are already setm delete it (probably unnecessary) if(it!=usableBandsList_.end()) usableBandsList_.erase(id); usableBandsList_.insert(std::pair<MacNodeId,UsableBands>(id,usableBands)); } bool AmcPilotAuto::getUsableBands(MacNodeId id, UsableBands*& uBands) { EV << NOW << " AmcPilotAuto::getUsableBands - getting Usable bands for node " << id; bool found = false; UsableBandsList::iterator it = usableBandsList_.find(id); if(it!=usableBandsList_.end()) { found = true; } else { // usable bands for this id not found if (getNodeTypeById(id) == UE) { // if it is a UE, look for its serving cell MacNodeId cellId = getBinder()->getNextHop(id); it = usableBandsList_.find(cellId); if(it!=usableBandsList_.end()) found = true; } } if (found) { uBands = &(it->second); EV << " [" ; for(unsigned int i = 0 ; i < it->second.size() ; ++i) { EV << it->second[i] << ","; } EV << "]"<<endl; return true; } EV << " [All bands are usable]" << endl ; uBands = nullptr; return false; }
33.891447
136
0.555469
[ "vector" ]
296bdaf755974cbb899cd65c398a166b5c1899e7
12,022
cc
C++
zircon/kernel/arch/arm64/hypervisor/vcpu.cc
wwjiang007/fuchsia-1
0db66b52b5bcd3e27c8b8c2163925309e8522f94
[ "BSD-2-Clause" ]
210
2019-02-05T12:45:09.000Z
2022-03-28T07:59:06.000Z
zircon/kernel/arch/arm64/hypervisor/vcpu.cc
wwjiang007/fuchsia-1
0db66b52b5bcd3e27c8b8c2163925309e8522f94
[ "BSD-2-Clause" ]
5
2019-12-04T15:13:37.000Z
2020-02-19T08:11:38.000Z
zircon/kernel/arch/arm64/hypervisor/vcpu.cc
wwjiang007/fuchsia-1
0db66b52b5bcd3e27c8b8c2163925309e8522f94
[ "BSD-2-Clause" ]
73
2019-03-06T18:55:23.000Z
2022-03-26T12:04:51.000Z
// Copyright 2017 The Fuchsia Authors // // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file or at // https://opensource.org/licenses/MIT #include <bits.h> #include <lib/fit/defer.h> #include <lib/ktrace.h> #include <zircon/errors.h> #include <zircon/syscalls/hypervisor.h> #include <arch/hypervisor.h> #include <arch/ops.h> #include <dev/interrupt/arm_gic_common.h> #include <dev/interrupt/arm_gic_hw_interface.h> #include <hypervisor/cpu.h> #include <hypervisor/guest_physical_address_space.h> #include <hypervisor/ktrace.h> #include <kernel/event.h> #include <kernel/percpu.h> #include <kernel/stats.h> #include <platform/timer.h> #include <vm/physmap.h> #include <vm/pmm.h> #include "el2_cpu_state_priv.h" #include "vmexit_priv.h" static constexpr uint32_t kGichHcrEn = 1u << 0; static constexpr uint32_t kGichHcrUie = 1u << 1; static constexpr uint32_t kGichMisrU = 1u << 1; static constexpr uint32_t kSpsrDaif = 0b1111 << 6; static constexpr uint32_t kSpsrEl1h = 0b0101; static constexpr uint32_t kSpsrNzcv = 0b1111 << 28; static uint64_t vmpidr_of(uint8_t vpid, uint64_t mpidr) { return (vpid - 1) | (mpidr & 0xffffff00fe000000); } template <typename F> static bool for_each_lr(IchState* ich_state, F function) { for (uint8_t i = 0; i < ich_state->num_lrs; i++) { if (BIT(ich_state->elrsr, i)) { continue; } InterruptState state; uint32_t vector = gic_get_vector_from_lr(ich_state->lr[i], &state); zx_status_t status = function(i, state, vector); if (status == ZX_ERR_STOP) { return false; } } return true; } static void gich_maybe_interrupt(GichState* gich_state, IchState* ich_state) { // From ARM GIC v3/v4, Section 4.8: If, on a particular CPU interface, // multiple pending interrupts have the same priority, and have sufficient // priority for the interface to signal them to the PE, it is IMPLEMENTATION // DEFINED how the interface selects which interrupt to signal. // // If interrupts are of the same priority, we can choose whatever ordering // we prefer when populating the LRs. for (uint64_t elrsr = ich_state->elrsr; elrsr != 0;) { uint32_t vector = 0; hypervisor::InterruptType type = gich_state->Pop(&vector); if (type == hypervisor::InterruptType::INACTIVE) { // There are no more pending interrupts. break; } uint32_t lr_index = __builtin_ctzl(elrsr); bool hw = type == hypervisor::InterruptType::PHYSICAL; // From ARM GIC v3/v4, Section 4.8: If the GIC implements fewer than 256 // priority levels, the low-order bits of the priority fields are // RAZ/WI. // ... // In the GIC prioritization scheme, lower numbers have higher priority. // // We may have as few as 16 priority levels, so step by 16 to the next // lowest priority in order to prioritise SGIs and PPIs over SPIs. uint8_t prio = vector < GIC_BASE_SPI ? 0 : 0x10; InterruptState state = InterruptState::PENDING; if (gich_state->InListRegister(vector)) { bool skip = for_each_lr(ich_state, [&](uint8_t i, InterruptState s, uint32_t v) { if (v != vector || s != InterruptState::ACTIVE) { return ZX_ERR_NEXT; } // If the interrupt is active, change its state to pending and active. state = InterruptState::PENDING_AND_ACTIVE; lr_index = i; return ZX_ERR_STOP; }); if (skip) { // Skip an interrupt if it is in an LR, and its state is not changing. continue; } } ich_state->lr[lr_index] = gic_get_lr_from_vector(hw, prio, state, vector); elrsr &= ~(1u << lr_index); } } GichState::GichState() { zx_status_t status = lr_tracker_.Reset(kNumInterrupts); // `lr_tracker_` uses static storage, so `Reset` cannot fail. DEBUG_ASSERT(status == ZX_OK); } void GichState::TrackAllListRegisters(IchState* ich_state) { lr_tracker_.ClearAll(); for_each_lr(ich_state, [this](uint8_t i, InterruptState s, uint32_t v) { lr_tracker_.SetOne(v); return ZX_ERR_NEXT; }); } static VcpuExit vmexit_interrupt_ktrace_meta(uint32_t misr) { if (misr & kGichMisrU) { return VCPU_UNDERFLOW_MAINTENANCE_INTERRUPT; } return VCPU_PHYSICAL_INTERRUPT; } AutoGich::AutoGich(IchState* ich_state, bool pending) : ich_state_(ich_state) { // From ARM GIC v3/v4, Section 8.4.5: Underflow Interrupt Enable. Enables // the signaling of a maintenance interrupt when the List registers are // empty, or hold only one valid entry. // // We use it when there are not enough free LRs to inject all pending // interrupts, so when guest finishes processing most of them, a maintenance // interrupt will cause VM exit and will give us a chance to inject the // remaining interrupts. The point of this is to reduce latency when // processing interrupts. uint32_t gich_hcr = kGichHcrEn; if (pending && ich_state_->num_lrs > 1) { gich_hcr |= kGichHcrUie; } DEBUG_ASSERT(!arch_ints_disabled()); int_state_ = arch_interrupt_save(); arch_set_blocking_disallowed(true); gic_write_gich_state(ich_state_, gich_hcr); } AutoGich::~AutoGich() { DEBUG_ASSERT(arch_ints_disabled()); gic_read_gich_state(ich_state_); arch_set_blocking_disallowed(false); arch_interrupt_restore(int_state_); } // Returns the number of active priorities registers, based on the number of // preemption bits. // // From ARM GIC v2, Section 5.3.2: In GICv2, the only valid value is 5 bits. // // From ARM GIC v3/v4, Section 8.4.2: If 5 bits of preemption are implemented // (bits [7:3] of priority), then there are 32 preemption levels... If 6 bits of // preemption are implemented (bits [7:2] of priority), then there are 64 // preemption levels... If 7 bits of preemption are implemented (bits [7:1] of // priority), then there are 128 preemption levels... static uint8_t num_aprs(uint8_t num_pres) { return static_cast<uint8_t>(1u << (num_pres - 5u)); } // static zx_status_t Vcpu::Create(Guest* guest, zx_vaddr_t entry, ktl::unique_ptr<Vcpu>* out) { hypervisor::GuestPhysicalAddressSpace* gpas = guest->AddressSpace(); if (entry >= gpas->size()) { return ZX_ERR_INVALID_ARGS; } uint8_t vpid; zx_status_t status = guest->AllocVpid(&vpid); if (status != ZX_OK) { return status; } auto free_vpid = fit::defer([guest, vpid]() { guest->FreeVpid(vpid); }); Thread* thread = Thread::Current::Get(); if (thread->vcpu()) { return ZX_ERR_BAD_STATE; } fbl::AllocChecker ac; ktl::unique_ptr<Vcpu> vcpu(new (&ac) Vcpu(guest, vpid, thread)); if (!ac.check()) { return ZX_ERR_NO_MEMORY; } free_vpid.cancel(); status = vcpu->el2_state_.Alloc(); if (status != ZX_OK) { return status; } vcpu->el2_state_->guest_state.system_state.elr_el2 = entry; vcpu->el2_state_->guest_state.system_state.spsr_el2 = kSpsrDaif | kSpsrEl1h; const uint64_t mpidr = __arm_rsr64("mpidr_el1"); vcpu->el2_state_->guest_state.system_state.vmpidr_el2 = vmpidr_of(vpid, mpidr); vcpu->el2_state_->host_state.system_state.vmpidr_el2 = mpidr; const uint8_t num_lrs = gic_get_num_lrs(); vcpu->el2_state_->ich_state.num_aprs = num_aprs(gic_get_num_pres()); vcpu->el2_state_->ich_state.num_lrs = num_lrs; vcpu->el2_state_->ich_state.vmcr = gic_default_gich_vmcr(); vcpu->el2_state_->ich_state.elrsr = (1ul << num_lrs) - 1; vcpu->hcr_ = HCR_EL2_VM | HCR_EL2_PTW | HCR_EL2_FMO | HCR_EL2_IMO | HCR_EL2_AMO | HCR_EL2_TWI | HCR_EL2_TWE | HCR_EL2_TSC | HCR_EL2_TSW | HCR_EL2_TVM | HCR_EL2_RW; *out = ktl::move(vcpu); return ZX_OK; } Vcpu::Vcpu(Guest* guest, uint8_t vpid, Thread* thread) : guest_(guest), vpid_(vpid), thread_(thread), last_cpu_(thread->LastCpu()) { thread->set_vcpu(true); // We have to disable thread safety analysis because it's not smart enough to // realize that SetMigrateFn will always be called with the ThreadLock. thread->SetMigrateFn([this](Thread* thread, auto stage) TA_NO_THREAD_SAFETY_ANALYSIS { MigrateCpu(thread, stage); }); } Vcpu::~Vcpu() { { // Taking the ThreadLock guarantees that thread_ isn't going to be freed // while we access it. Guard<MonitoredSpinLock, IrqSave> guard{ThreadLock::Get(), SOURCE_TAG}; Thread* thread = thread_.load(); if (thread != nullptr) { thread->set_vcpu(false); // Clear the migration function, so that |thread_| does not reference // |this| after destruction of the VCPU. thread->SetMigrateFnLocked(nullptr); } } __UNUSED zx_status_t status = guest_->FreeVpid(vpid_); DEBUG_ASSERT(status == ZX_OK); } void Vcpu::MigrateCpu(Thread* thread, Thread::MigrateStage stage) { switch (stage) { case Thread::MigrateStage::Before: break; case Thread::MigrateStage::After: // After thread migration, update the |last_cpu_| for Vcpu::Interrupt(). last_cpu_.store(thread->LastCpuLocked()); break; case Thread::MigrateStage::Exiting: // When the thread is exiting, set |last_cpu_| to INVALID_CPU and // |thread_| to nullptr. last_cpu_.store(INVALID_CPU); thread_.store(nullptr); break; } } zx_status_t Vcpu::Resume(zx_port_packet_t* packet) { Thread* current_thread = Thread::Current::Get(); if (current_thread != thread_) { return ZX_ERR_BAD_STATE; } const ArchVmAspace& aspace = *guest_->AddressSpace()->arch_aspace(); zx_paddr_t vttbr = arm64_vttbr(aspace.arch_asid(), aspace.arch_table_phys()); GuestState* guest_state = &el2_state_->guest_state; IchState* ich_state = &el2_state_->ich_state; zx_status_t status; do { timer_maybe_interrupt(guest_state, &gich_state_); gich_maybe_interrupt(&gich_state_, ich_state); { AutoGich auto_gich(ich_state, gich_state_.Pending()); ktrace(TAG_VCPU_ENTER, 0, 0, 0, 0); GUEST_STATS_INC(vm_entries); running_.store(true); status = arm64_el2_resume(vttbr, el2_state_.PhysicalAddress(), hcr_); running_.store(false); GUEST_STATS_INC(vm_exits); } gich_state_.TrackAllListRegisters(ich_state); if (status == ZX_ERR_NEXT) { // We received a physical interrupt. If it was due to the thread // being killed, then we should exit with an error, otherwise return // to the guest. ktrace_vcpu_exit(vmexit_interrupt_ktrace_meta(ich_state->misr), guest_state->system_state.elr_el2); status = current_thread->signals() & THREAD_SIGNAL_KILL ? ZX_ERR_CANCELED : ZX_OK; GUEST_STATS_INC(interrupts); } else if (status == ZX_OK) { status = vmexit_handler(&hcr_, guest_state, &gich_state_, guest_->AddressSpace(), guest_->Traps(), packet); } else { ktrace_vcpu_exit(VCPU_FAILURE, guest_state->system_state.elr_el2); dprintf(INFO, "VCPU resume failed: %d\n", status); } } while (status == ZX_OK); return status == ZX_ERR_NEXT ? ZX_OK : status; } void Vcpu::Interrupt(uint32_t vector, hypervisor::InterruptType type) { gich_state_.Interrupt(vector, type); if (running_.load()) { mp_interrupt(MP_IPI_TARGET_MASK, cpu_num_to_mask(last_cpu_.load())); } } zx_status_t Vcpu::ReadState(zx_vcpu_state_t* state) const { if (Thread::Current::Get() != thread_) { return ZX_ERR_BAD_STATE; } ASSERT(sizeof(state->x) >= sizeof(el2_state_->guest_state.x)); memcpy(state->x, el2_state_->guest_state.x, sizeof(el2_state_->guest_state.x)); state->sp = el2_state_->guest_state.system_state.sp_el1; state->cpsr = el2_state_->guest_state.system_state.spsr_el2 & kSpsrNzcv; return ZX_OK; } zx_status_t Vcpu::WriteState(const zx_vcpu_state_t& state) { if (Thread::Current::Get() != thread_) { return ZX_ERR_BAD_STATE; } ASSERT(sizeof(el2_state_->guest_state.x) >= sizeof(state.x)); memcpy(el2_state_->guest_state.x, state.x, sizeof(state.x)); el2_state_->guest_state.system_state.sp_el1 = state.sp; el2_state_->guest_state.system_state.spsr_el2 |= state.cpsr & kSpsrNzcv; return ZX_OK; }
36.102102
97
0.700383
[ "vector" ]
29794e11e6507a7646c22490ab584e5c459cb811
17,604
cpp
C++
src/one-solver-anneal.cpp
quantumz-io/oneSolver
a5c3b3a2ce1eef3e237f121a836bb8a5f8aeac51
[ "MIT" ]
1
2021-09-30T13:27:38.000Z
2021-09-30T13:27:38.000Z
src/one-solver-anneal.cpp
quantumz-io/oneSolver
a5c3b3a2ce1eef3e237f121a836bb8a5f8aeac51
[ "MIT" ]
null
null
null
src/one-solver-anneal.cpp
quantumz-io/oneSolver
a5c3b3a2ce1eef3e237f121a836bb8a5f8aeac51
[ "MIT" ]
5
2020-12-23T12:36:41.000Z
2022-02-21T08:35:16.000Z
/*! file one-solver-anneal.cpp * * @copyright Licensed under MIT license by hyperQ – Ewa Hendzel * */ #include <boost/program_options.hpp> #include <fstream> #include <iostream> #include <ctime> #include <random> #include <mpi.h> #include "CL/sycl.hpp" #include "helpers/devices.hpp" #include "helpers/qubo_helpers.hpp" #include "model/qubo.hpp" #include "model/solution.hpp" #include "simulated_annealing/annealing.hpp" #define SEED 1234 namespace po = boost::program_options; namespace sycl = cl::sycl; using queue_ptr = std::unique_ptr<sycl::queue>; /*! * @brief Constructs a linear beta schedule. * * @param a reference to a vector for storing the schedule * @param minimum value of beta in the annealing schedule. * @param maximum value of beta in the annealing schedule. * @param number of iterations of the algorithm. * * @returns returns schedule. */ void construct_linear_beta_schedule(std::vector<double> &schedule, double beta_min, double beta_max, uint num_iter) { for (auto i = 0; i < num_iter; i++) { schedule[i] = beta_min + beta_max * i / static_cast<double>(num_iter - 1); } } /*! * @brief Constructs a geometric beta schedule. * * @param a reference to a vector for storing the schedule * @param minimum value of beta in the annealing schedule. * @param maximum value of beta in the annealing schedule. * @param number of iterations of the algorithm. * */ void construct_geometric_beta_schedule(std::vector<double> &schedule, double beta_min, double beta_max, uint num_iter) { schedule[0] = beta_min; auto alpha = pow(beta_max / beta_min, 1.0 / (num_iter - 1)); for (auto i = 1; i < num_iter; i++) { schedule[i] = (schedule[i - 1]) * alpha; } } /*! * @brief Compute QUBO solution in a give solution space on a given device. * * @param Instance of the proble to solve. * @param Accelerator device type. * @param beta schedule type linear or geometric. * @param seed for random number generator. * @param minimum value of beta in the annealing schedule. * @param maximum value of beta in the annealing schedule. * @param number of iterations of the algorithm. * @param number of trajectories to try. * * @returns solution to the given QUBO problem and acclerator device name. */ std::tuple<qubo::Solution, std::string> sycl_native_anneal(qubo::QUBOModel<int, double> instance, std::string device_type, std::string schedule_type, std::uint64_t seed, double beta_min, double beta_max, uint num_iter, uint num_tries) { queue_ptr q_ptr; std::string accl_device_name; try { q_ptr = queue_ptr( new sycl::queue(*devices::construct_device_selector(device_type))); } catch (std::runtime_error) { std::cerr << "No devices of given type could be initialized." << std::endl; } accl_device_name = q_ptr->get_device().get_info<sycl::info::device::name>(); // std::cout << "Node ID [" << machine_name << "], " << "Rank [" << rank << "], " << "Using device: " // << q_ptr->get_device().get_info<sycl::info::device::name>() // << std::endl; std::vector<double> beta_schedule(num_iter); if (schedule_type == "linear") { construct_linear_beta_schedule(beta_schedule, beta_min, beta_max, num_iter); } else { construct_geometric_beta_schedule(beta_schedule, beta_min, beta_max, num_iter); } auto solution = sa::anneal(instance, *q_ptr, beta_schedule, seed, num_iter, num_tries); return {solution, accl_device_name}; } /*! * @brief Parse command line. * @param argument count. * @param arguments array. * * @returns returns input file name, output file name, device type, beta_min, beta_max, * number of iteration and number of tries. */ std::tuple<std::string, std::string, std::string, std::string, double, double, uint, uint> parse_cmd_line_anneal(int argc, char *argv[]) { std::string input_file; std::string output_file; std::string schedule_type; std::string device_type; uint num_iter; uint num_tries; double beta_min, beta_max; po::options_description options("Allowed options"); options.add_options()("help", "produce help message")( "input", po::value<std::string>(&input_file), "input file")( "output", po::value<std::string>(&output_file), "output file")( "num-iter", po::value<uint>(&num_iter)->default_value(100), "number of iterations of the algorithm")( "num-tries", po::value<uint>(&num_tries)->default_value(100), "number of trajectories to try")( "schedule-type", po::value<std::string>(&schedule_type)->default_value("geometric"), "type of beta schedule to use, either linear or geometric")( "beta-min", po::value<double>(&beta_min)->default_value(0.1), "minimum value of beta in the annealing schedule (default 0.1)")( "beta-max", po::value<double>(&beta_max)->default_value(1.0), "maximum value of beta in the annealing schedule (default 1.0)")( "device-type", po::value<std::string>(&device_type)->default_value("host"), "device type to use (cpu, gpu or host)"); po::variables_map vm; po::store(po::parse_command_line(argc, argv, options), vm); po::notify(vm); if (vm.count("help")) { std::cout << options << std::endl; MPI_Abort(MPI_COMM_WORLD, MPI_SUCCESS); } if (!vm.count("input")) { throw std::runtime_error("No input file provided."); } if (!vm.count("output")) { throw std::runtime_error("No output file provided."); } if (device_type != "cpu" && device_type != "gpu" && device_type != "host") { throw std::runtime_error("Unknown device type: " + device_type); } if (schedule_type != "linear" && schedule_type != "geometric") { throw std::runtime_error("Unknown beta schedule: " + schedule_type); } if (beta_max < 0 || beta_min < 0) { throw std::runtime_error("Invalid schedule, both ends of beta range need to be positive."); } if (beta_min >= beta_max) { throw std::runtime_error("Invalid schedule, initial beta is not lesser than final beta."); } return {input_file, output_file, device_type, schedule_type, beta_min, beta_max, num_iter, num_tries}; } int main(int argc, char *argv[]) { const clock_t begin_time = clock(); char machine_name[MPI_MAX_PROCESSOR_NAME]; int name_len = 0; int rank = 0; const int root_rank = 0; // Rank zero process. int min_energy_process_rank = 0; // Rank of process with minimum energy. int num_procs = 0; int size = 0; long long int msg_size = 0; std::string input_file; std::string output_file; std::string schedule_type; std::string device_type; std::vector<char> msg_buff; std::uint64_t *seed_buff = NULL; std::uint64_t seed; uint num_iter; uint num_tries; uint param_buff[2]; double beta_min, beta_max; double beta_buff[2]; qubo::QUBOModel<int, double> instance; try { // Start MPI. if (MPI_Init(&argc, &argv) != MPI_SUCCESS) { throw std::runtime_error("Failed to initialize MPI\n"); } // Create the communicator, and retrieve the number of MPI ranks. MPI_Comm_size(MPI_COMM_WORLD, &num_procs); // Determine the rank number. MPI_Comm_rank(MPI_COMM_WORLD, &rank); // Get the machine name. MPI_Get_processor_name(machine_name, &name_len); if (rank == root_rank) { // Parse command line to get the parameters. std::tie(input_file, output_file, device_type, schedule_type, beta_min, beta_max, num_iter, num_tries) = parse_cmd_line_anneal(argc, argv); std::cout << "Reading input from: " << input_file << std::endl; std::cout << "Output will be saved to: " << output_file << std::endl; std::cout << "Schedule type: " << schedule_type << std::endl; std::cout << "Beta range: [" << beta_min << ", " << beta_max << "]" << std::endl; std::cout << "Number of iterations: " << num_iter << std::endl; std::cout << "Number of tries: " << num_tries << std::endl; std::ifstream qubo_file(input_file); if (!qubo_file) { std::cerr << "can not open input file: " << input_file << std::endl; return -1; } qubo_file.unsetf(std::ios::skipws); instance = qubo::QUBOModel<int, double>::load(qubo_file); std::ostringstream oss; // save data to archive { boost::archive::text_oarchive ar(oss); // write class instance to archive ar << instance; // archive and stream closed when destructors are called. } #ifdef DEBUG std::cout << "sSize: " << oss.str().size() << std::endl; std::cout << "sData: " << oss.str().c_str() << std::endl; #endif msg_buff.assign(oss.str().c_str(), oss.str().c_str() + oss.str().size() +1); msg_size = oss.str().size(); } // Send QUBOModel instance to all the proecesses. if (MPI_Bcast(&msg_size, 1, MPI_LONG_LONG_INT, root_rank, MPI_COMM_WORLD) != MPI_SUCCESS) { throw std::runtime_error("MPI broadcast failed\n"); } if (rank != root_rank) { msg_buff.resize(msg_size); } if (MPI_Bcast(msg_buff.data(), msg_size, MPI_CHAR, root_rank, MPI_COMM_WORLD) != MPI_SUCCESS) { throw std::runtime_error("MPI broadcast failed\n"); } if (rank != root_rank) { if (msg_buff.size() > 0) { std::istringstream iss(std::string(msg_buff.data(), msg_buff.size())); #ifdef DEBUG std::cout << "rSize: " << iss.str().size() << std::endl; std::cout << "rData: " << iss.str().c_str() << std::endl; #endif { boost::archive::text_iarchive ar(iss); ar >> instance; } } } // Send device_type to all the processes. if (rank == root_rank) { msg_size = device_type.size(); msg_buff.assign(device_type.c_str(),device_type.c_str() + device_type.size() +1); } if (MPI_Bcast(&msg_size, 1, MPI_LONG_LONG_INT, root_rank, MPI_COMM_WORLD) != MPI_SUCCESS) { throw std::runtime_error("MPI broadcast failed\n"); } if (rank != root_rank) { msg_buff.resize(msg_size); } if (MPI_Bcast(msg_buff.data(), msg_size, MPI_CHAR, root_rank, MPI_COMM_WORLD) != MPI_SUCCESS) { throw std::runtime_error("MPI broadcast failed\n"); } if (rank != root_rank) { device_type = std::string(&msg_buff[0], msg_size); #ifdef DEBUG std::cout << "device_type: " << device_type << std::endl; #endif } // Send schedule_type to all the processes. if (rank == root_rank) { msg_size = schedule_type.size(); msg_buff.assign(schedule_type.c_str(),schedule_type.c_str() + schedule_type.size() +1); } if (MPI_Bcast(&msg_size, 1, MPI_LONG_LONG_INT, root_rank, MPI_COMM_WORLD) != MPI_SUCCESS) { throw std::runtime_error("MPI broadcast failed\n"); } if (rank != root_rank) { msg_buff.resize(msg_size); } if (MPI_Bcast(msg_buff.data(), msg_size, MPI_CHAR, root_rank, MPI_COMM_WORLD) != MPI_SUCCESS) { throw std::runtime_error("MPI broadcast failed\n"); } if (rank != root_rank) { schedule_type = std::string(&msg_buff[0], msg_size); #ifdef DEBUG std::cout << "schedule_type: " << schedule_type << std::endl; #endif } // Send beta_min and beta_max to all the processes. if(rank == root_rank){ beta_buff[0] = beta_min; beta_buff[1] = beta_max; } if (MPI_Bcast(&beta_buff, 2, MPI::DOUBLE, root_rank, MPI_COMM_WORLD) != MPI_SUCCESS) { throw std::runtime_error("MPI broadcast failed\n"); } if (rank != root_rank) { beta_min = beta_buff[0]; beta_max = beta_buff[1]; #ifdef DEBUG std::cout << "Beta range: [" << beta_min << ", " << beta_max << "]" << std::endl; #endif } // Send num_iter and num_tries to all the processes. if (rank == root_rank) { param_buff[0] = num_iter; param_buff[1] = num_tries; } if (MPI_Bcast(&param_buff, 2, MPI_UNSIGNED, root_rank, MPI_COMM_WORLD) != MPI_SUCCESS) { throw std::runtime_error("MPI broadcast failed\n"); } if (rank != root_rank) { num_iter = param_buff[0]; num_tries = param_buff[1]; #ifdef DEBUG std::cout << "Number of iterations: " << num_iter << std::endl; std::cout << "Number of tries: " << num_tries << std::endl; #endif } // Send the seed for random number generator to all the processes. if (rank == root_rank) { seed_buff = new std::uint64_t[num_procs]; // Seed generation using mt19937_64 i.e 64 bit Mersenne Twister by Matsumoto, 2000. //std::random_device rd; // for non-deterministic generator uncomment this line and std::mt19937_64 gen(SEED); // replace SEED with rd() in mersenne twister. for (auto i=0; i < num_procs; ++i) { seed_buff[i] = gen(); #ifdef DEBUG std::cout << "seed: " << seed_buff[i] << std::endl; #endif } } if (MPI_Scatter(seed_buff, 1, MPI_INT64_T, &seed, 1, MPI_INT64_T, root_rank, MPI_COMM_WORLD) != MPI_SUCCESS) { throw std::runtime_error("MPI scatter failed\n"); } if (rank == root_rank) { delete [] seed_buff; } #ifdef DEBUG std::cout << "seed: " << seed << std::endl; #endif auto [solution, accl_device_name] = sycl_native_anneal(instance, device_type, schedule_type, seed, beta_min, beta_max, num_iter, num_tries); if(rank == root_rank){ //std::unique_ptr<char> log_buff_ptr(new char[100]); MPI_Status status; int msg_length; //char log_buff_ptr[100]; std::cout << "Node ID [" << machine_name << "], " << "Rank [" << rank << "], " << "Using device: " << accl_device_name << std::endl; for(auto rank_indx = 1; rank_indx < num_procs; ++rank_indx){ MPI_Probe(rank_indx, 1, MPI_COMM_WORLD, &status); MPI_Get_count(&status, MPI_CHAR, &msg_length); std::unique_ptr<char> log_buff_ptr(new char[msg_length]{}); MPI_Recv(log_buff_ptr.get(), msg_length, MPI_CHAR, rank_indx, 1 , MPI_COMM_WORLD, MPI_STATUS_IGNORE); std::string log_msg(log_buff_ptr.get()); //std::cout << log_buff_ptr.get() << std::endl; std::cout << log_msg; } }else{ std::ostringstream log_stream; log_stream << "Node ID [" << machine_name << "], " << "Rank [" << rank << "], " << "Using device: " << accl_device_name << std::endl; MPI_Send(log_stream.str().c_str(), log_stream.str().size(), MPI_CHAR, root_rank, 1, MPI_COMM_WORLD); } std::unique_ptr<double> energy_buff_ptr(new double[num_procs]); if (MPI_Gather(&solution.energy, 1, MPI_DOUBLE, energy_buff_ptr.get(), 1, MPI_DOUBLE, root_rank, MPI_COMM_WORLD) != MPI_SUCCESS) { throw std::runtime_error("MPI gather failed\n"); } if (rank == root_rank) { std::vector<double> energies(&energy_buff_ptr.get()[0], &energy_buff_ptr.get()[num_procs]); auto min_energy = std::min_element(energies.begin(), energies.end()); auto min_idx_energy = std::distance(energies.begin(), min_energy); #ifdef DEBUG std::cout << "min_energy: " << energies[min_idx_energy] << std::endl; #endif solution.energy = energies[min_idx_energy]; min_energy_process_rank = min_idx_energy; } if (MPI_Bcast(&min_energy_process_rank, 1, MPI_INT, root_rank, MPI_COMM_WORLD) != MPI_SUCCESS) { throw std::runtime_error("MPI broadcast failed\n"); } if ((min_energy_process_rank != root_rank) && (rank == min_energy_process_rank)) { auto state = solution.state; if (MPI_Send(state.data(), state.size(), MPI_CHAR, root_rank, 0, MPI_COMM_WORLD) != MPI_SUCCESS) { throw std::runtime_error("MPI send failed\n"); } } if (rank == root_rank) { if (min_energy_process_rank != 0) { MPI_Status status; int msg_length; // Probe msg size MPI_Probe(min_energy_process_rank, 0, MPI_COMM_WORLD, &status); MPI_Get_count(&status, MPI_CHAR, &msg_length); std::unique_ptr<char> buff_ptr(new char[msg_length]{}); if (MPI_Recv(buff_ptr.get(), msg_length, MPI_CHAR, min_energy_process_rank, root_rank, MPI_COMM_WORLD, MPI_STATUS_IGNORE) != MPI_SUCCESS) { throw std::runtime_error("MPI receive failed\n"); } //std::cout << buff_ptr.get(); #ifdef DEBUG std::cout << "Min Energy State: "; for (auto i = 0; i < solution.state.size(); ++i) { std::cout << (int)buff_ptr.get()[i] << " "; } std::cout << std::endl; #endif for (auto i=0; i < solution.state.size(); ++i ) { solution.state[i] = buff_ptr.get()[i]; } } #ifdef DEBUG std::cout << "Min Energy State: " for (auto i = 0; i < solution.state.size(); ++i) { std::cout << (int)solution.state[i] << " "; } std::cout << std::endl; #endif std::ofstream results_file(output_file); solution.save(results_file); results_file.close(); } } catch (std::exception &e) { std::cerr << "error: " << e.what() << "\n"; MPI_Abort(MPI_COMM_WORLD, EXIT_FAILURE); } catch (...) { std::cerr << "Exception of unknown type!\n"; } if (rank == root_rank) { std::cout << "Calculation time [s]: "<< float( clock () - begin_time ) / CLOCKS_PER_SEC << "\n"; } MPI_Finalize(); return 0; }
33.59542
234
0.62696
[ "vector", "model" ]
297c69fe5d435cd30069aed2e6ae0834a3106031
4,918
cc
C++
FWCore/Framework/src/EDFilter.cc
singh-ramanpreet/cmssw
1644d7ba76b05a4a9260ceb90a635f11023674dd
[ "Apache-2.0" ]
null
null
null
FWCore/Framework/src/EDFilter.cc
singh-ramanpreet/cmssw
1644d7ba76b05a4a9260ceb90a635f11023674dd
[ "Apache-2.0" ]
null
null
null
FWCore/Framework/src/EDFilter.cc
singh-ramanpreet/cmssw
1644d7ba76b05a4a9260ceb90a635f11023674dd
[ "Apache-2.0" ]
null
null
null
/*---------------------------------------------------------------------- ----------------------------------------------------------------------*/ #include "FWCore/Framework/interface/EDFilter.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/LuminosityBlock.h" #include "FWCore/Framework/interface/Run.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/Framework/src/edmodule_mightGet_config.h" #include "FWCore/Framework/src/EventSignalsSentry.h" #include "FWCore/Framework/interface/TransitionInfoTypes.h" #include "FWCore/ServiceRegistry/interface/ESParentContext.h" #include "SharedResourcesRegistry.h" #include "FWCore/ParameterSet/interface/ConfigurationDescriptions.h" #include "FWCore/ParameterSet/interface/ParameterSetDescription.h" namespace edm { EDFilter::EDFilter() : ProducerBase(), moduleDescription_(), previousParentage_(), previousParentageId_() { SharedResourcesRegistry::instance()->registerSharedResource(SharedResourcesRegistry::kLegacyModuleResourceName); } EDFilter::~EDFilter() {} bool EDFilter::doEvent(EventTransitionInfo const& info, ActivityRegistry* act, ModuleCallingContext const* mcc) { bool rc = false; Event e(info, moduleDescription_, mcc); e.setConsumer(this); e.setProducer(this, &previousParentage_); e.setSharedResourcesAcquirer(&resourceAcquirer_); EventSignalsSentry sentry(act, mcc); ESParentContext parentC(mcc); rc = this->filter( e, EventSetup{ info, static_cast<unsigned int>(Transition::Event), esGetTokenIndices(Transition::Event), parentC, false}); commit_(e, &previousParentageId_); return rc; } void EDFilter::doBeginJob() { std::vector<std::string> res = {SharedResourcesRegistry::kLegacyModuleResourceName}; resourceAcquirer_ = SharedResourcesRegistry::instance()->createAcquirer(res); this->beginJob(); } void EDFilter::doEndJob() { this->endJob(); } void EDFilter::doBeginRun(RunTransitionInfo const& info, ModuleCallingContext const* mcc) { Run r(info, moduleDescription_, mcc, false); r.setConsumer(this); Run const& cnstR = r; ESParentContext parentC(mcc); this->beginRun(cnstR, EventSetup{info, static_cast<unsigned int>(Transition::BeginRun), esGetTokenIndices(Transition::BeginRun), parentC, false}); commit_(r); return; } void EDFilter::doEndRun(RunTransitionInfo const& info, ModuleCallingContext const* mcc) { Run r(info, moduleDescription_, mcc, true); r.setConsumer(this); Run const& cnstR = r; ESParentContext parentC(mcc); this->endRun( cnstR, EventSetup{ info, static_cast<unsigned int>(Transition::EndRun), esGetTokenIndices(Transition::EndRun), parentC, false}); commit_(r); return; } void EDFilter::doBeginLuminosityBlock(LumiTransitionInfo const& info, ModuleCallingContext const* mcc) { LuminosityBlock lb(info, moduleDescription_, mcc, false); lb.setConsumer(this); LuminosityBlock const& cnstLb = lb; ESParentContext parentC(mcc); this->beginLuminosityBlock(cnstLb, EventSetup{info, static_cast<unsigned int>(Transition::BeginLuminosityBlock), esGetTokenIndices(Transition::BeginLuminosityBlock), parentC, false}); commit_(lb); } void EDFilter::doEndLuminosityBlock(LumiTransitionInfo const& info, ModuleCallingContext const* mcc) { LuminosityBlock lb(info, moduleDescription_, mcc, true); lb.setConsumer(this); LuminosityBlock const& cnstLb = lb; ESParentContext parentC(mcc); this->endLuminosityBlock(cnstLb, EventSetup{info, static_cast<unsigned int>(Transition::EndLuminosityBlock), esGetTokenIndices(Transition::EndLuminosityBlock), parentC, false}); commit_(lb); return; } void EDFilter::doRespondToOpenInputFile(FileBlock const& fb) { respondToOpenInputFile(fb); } void EDFilter::doRespondToCloseInputFile(FileBlock const& fb) { respondToCloseInputFile(fb); } void EDFilter::fillDescriptions(ConfigurationDescriptions& descriptions) { ParameterSetDescription desc; desc.setUnknown(); descriptions.addDefault(desc); } void EDFilter::prevalidate(ConfigurationDescriptions& iConfig) { edmodule_mightGet_config(iConfig); } static const std::string kBaseType("EDFilter"); const std::string& EDFilter::baseType() { return kBaseType; } } // namespace edm
39.031746
121
0.645791
[ "vector" ]
297d8f96bfdfba3e2ef2439eff806c253e56db6c
215,553
cpp
C++
src/condor_unit_tests/OTEST_Env.cpp
pavlo-svirin/htcondor
9e00a5874cc2579f5fdc81bb778f540b40b48c87
[ "Apache-2.0" ]
null
null
null
src/condor_unit_tests/OTEST_Env.cpp
pavlo-svirin/htcondor
9e00a5874cc2579f5fdc81bb778f540b40b48c87
[ "Apache-2.0" ]
null
null
null
src/condor_unit_tests/OTEST_Env.cpp
pavlo-svirin/htcondor
9e00a5874cc2579f5fdc81bb778f540b40b48c87
[ "Apache-2.0" ]
null
null
null
/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * 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. * ***************************************************************/ /* Test the Env implementation. */ #include "condor_common.h" #include "condor_debug.h" #include "condor_config.h" #include "function_test_driver.h" #include "unit_test_utils.h" #include "emit.h" #include "condor_attributes.h" #include "env.h" #include <string> static bool test_count_0(void); static bool test_count_1(void); static bool test_count_many(void); static bool test_clear_empty(void); static bool test_clear_non_empty(void); static bool test_mf_v1r_or_v2q_ret_null(void); static bool test_mf_v1r_or_v2q_detect_v1r(void); static bool test_mf_v1r_or_v2q_detect_v2q(void); static bool test_mf_v1r_or_v2q_add_null(void); static bool test_mf_v2q_ret_null(void); static bool test_mf_v2q_ret_valid(void); static bool test_mf_v2q_ret_invalid_quotes(void); static bool test_mf_v2q_ret_invalid_quotes_end(void); static bool test_mf_v2q_ret_invalid_trail(void); static bool test_mf_v2q_ret_invalid_name(void); static bool test_mf_v2q_ret_invalid_delim(void); static bool test_mf_v2q_error_invalid_quotes(void); static bool test_mf_v2q_error_invalid_quotes_end(void); static bool test_mf_v2q_error_invalid_trail(void); static bool test_mf_v2q_error_invalid_name(void); static bool test_mf_v2q_error_invalid_delim(void); static bool test_mf_v2q_add_null(void); static bool test_mf_v2q_add_invalid_delim_var(void); static bool test_mf_v2q_add_invalid_quotes(void); static bool test_mf_v2q_add_invalid_quotes_end(void); static bool test_mf_v2q_add_invalid_trail(void); static bool test_mf_v2q_add(void); static bool test_mf_v2q_replace(void); static bool test_mf_v2q_replace_v1r(void); static bool test_mf_v2q_replace_add(void); static bool test_mf_v2q_replace_add_v1r(void); static bool test_mf_v2r_ret_null(void); static bool test_mf_v2r_ret_valid(void); static bool test_mf_v2r_ret_invalid_name(void); static bool test_mf_v2r_ret_invalid_delim(void); static bool test_mf_v2r_error_invalid_name(void); static bool test_mf_v2r_error_invalid_delim(void); static bool test_mf_v2r_add_null(void); static bool test_mf_v2r_add_invalid(void); static bool test_mf_v2r_add(void); static bool test_mf_v2r_replace(void); static bool test_mf_v2r_replace_v1r(void); static bool test_mf_v2r_replace_add(void); static bool test_mf_v2r_replace_add_v1r(void); static bool test_mf_v1r_ret_null(void); static bool test_mf_v1r_ret_valid(void); static bool test_mf_v1r_ret_invalid_name(void); static bool test_mf_v1r_ret_invalid_delim(void); static bool test_mf_v1r_error_invalid_name(void); static bool test_mf_v1r_error_invalid_delim(void); static bool test_mf_v1r_add_null(void); static bool test_mf_v1r_add_invalid(void); static bool test_mf_v1r_add(void); static bool test_mf_v1r_replace(void); static bool test_mf_v1r_replace_v2r(void); static bool test_mf_v1r_replace_v2q(void); static bool test_mf_v1r_replace_add(void); static bool test_mf_v1r_replace_add_v2r(void); static bool test_mf_v1r_replace_add_v2q(void); static bool test_mf_v1or2_r_ret_null(void); static bool test_mf_v1or2_r_detect_v1r(void); static bool test_mf_v1or2_r_detect_v2r(void); static bool test_mf_v1or2_r_add_null(void); static bool test_mf_v1or2_r_add_v2r(void); static bool test_mf_str_array_ret_null(void); static bool test_mf_str_array_ret_valid(void); static bool test_mf_str_array_ret_invalid_name(void); static bool test_mf_str_array_ret_invalid_delim(void); static bool test_mf_str_array_add_null(void); static bool test_mf_str_array_add_invalid(void); static bool test_mf_str_array_add(void); static bool test_mf_str_array_replace(void); static bool test_mf_str_array_replace_add(void); static bool test_mf_str_ret_null(void); static bool test_mf_str_ret_valid(void); static bool test_mf_str_ret_invalid_name(void); static bool test_mf_str_ret_invalid_delim(void); static bool test_mf_str_add_null(void); static bool test_mf_str_add_invalid_name(void); static bool test_mf_str_add_invalid_delim(void); static bool test_mf_str_add(void); static bool test_mf_str_replace(void); static bool test_mf_str_replace_add(void); static bool test_mf_env_add_empty(void); static bool test_mf_env_add_one(void); static bool test_mf_env_add_many(void); static bool test_mf_env_replace(void); static bool test_mf_env_replace_v1_v2(void); static bool test_mf_env_replace_v2_v1(void); static bool test_mf_env_replace_add(void); static bool test_mf_env_replace_add_v1_v2(void); static bool test_mf_env_replace_add_v2_v1(void); static bool test_mf_env_itself(void); static bool test_mf_ad_ret_null(void); static bool test_mf_ad_ret_v1r_valid(void); static bool test_mf_ad_ret_v2r_valid(void); static bool test_mf_ad_ret_valid_define(void); static bool test_mf_ad_ret_v1r_invalid_name(void); static bool test_mf_ad_ret_v1r_invalid_delim(void); static bool test_mf_ad_ret_v2r_invalid_name(void); static bool test_mf_ad_ret_v2r_invalid_delim(void); static bool test_mf_ad_error_v1r_invalid_name(void); static bool test_mf_ad_error_v1r_invalid_delim(void); static bool test_mf_ad_error_v2r_invalid_name(void); static bool test_mf_ad_error_v2r_invalid_delim(void); static bool test_mf_ad_add_null(void); static bool test_mf_ad_add_define(void); static bool test_mf_ad_add_v1r_one(void); static bool test_mf_ad_add_v1r_many(void); static bool test_mf_ad_add_v2r_one(void); static bool test_mf_ad_add_v2r_many(void); static bool test_mf_ad_v1r_replace(void); static bool test_mf_ad_v2r_replace(void); static bool test_mf_ad_v1r_replace_add(void); static bool test_mf_ad_v2r_replace_add(void); static bool test_set_env_with_error_message_ret_null(void); static bool test_set_env_with_error_message_ret_valid(void); static bool test_set_env_with_error_message_ret_invalid_name(void); static bool test_set_env_with_error_message_ret_invalid_delim(void); static bool test_set_env_with_error_message_err_invalid_name(void); static bool test_set_env_with_error_message_err_invalid_delim(void); static bool test_set_env_with_error_message_add_null(void); static bool test_set_env_with_error_message_add_invalid_delim(void); static bool test_set_env_with_error_message_add_invalid_var(void); static bool test_set_env_with_error_message_add(void); static bool test_set_env_with_error_message_replace(void); static bool test_set_env_str_ret_null(void); static bool test_set_env_str_ret_valid(void); static bool test_set_env_str_ret_invalid_name(void); static bool test_set_env_str_ret_invalid_delim(void); static bool test_set_env_str_add_null(void); static bool test_set_env_str_add_invalid(void); static bool test_set_env_str_add(void); static bool test_set_env_str_replace(void); static bool test_set_env_str_str_ret_null_var(void); static bool test_set_env_str_str_ret_null_val(void); static bool test_set_env_str_str_ret_valid(void); static bool test_set_env_str_str_add_null_var(void); static bool test_set_env_str_str_add_null_val(void); static bool test_set_env_str_str_add(void); static bool test_set_env_str_str_replace(void); static bool test_set_env_mystr_ret_empty_var(void); static bool test_set_env_mystr_ret_empty_val(void); static bool test_set_env_mystr_ret_valid(void); static bool test_set_env_mystr_add_empty_var(void); static bool test_set_env_mystr_add_empty_val(void); static bool test_set_env_mystr_add(void); static bool test_set_env_mystr_replace(void); static bool test_insert_env_into_classad_v1_empty(void); static bool test_insert_env_into_classad_v2_empty(void); static bool test_insert_env_into_classad_v1_v1_replace(void); static bool test_insert_env_into_classad_v1_v2_replace(void); static bool test_insert_env_into_classad_v2_v1_replace(void); static bool test_insert_env_into_classad_v2_v2_replace(void); static bool test_insert_env_into_classad_version_v1(void); static bool test_insert_env_into_classad_version_v1_os_winnt(void); static bool test_insert_env_into_classad_version_v1_os_win32(void); static bool test_insert_env_into_classad_version_v1_os_unix(void); static bool test_insert_env_into_classad_version_v1_semi(void); static bool test_insert_env_into_classad_version_v1_line(void); static bool test_insert_env_into_classad_version_v1_current(void); static bool test_insert_env_into_classad_version_v1_error_v2(void); static bool test_insert_env_into_classad_version_v1_error(void); static bool test_insert_env_into_classad_version_v2(void); static bool test_condor_version_requires_v1_false(void); static bool test_condor_version_requires_v1_true(void); static bool test_condor_version_requires_v1_this(void); static bool test_get_delim_str_v2_raw_return_empty(void); static bool test_get_delim_str_v2_raw_return_v1(void); static bool test_get_delim_str_v2_raw_return_v2(void); static bool test_get_delim_str_v2_raw_result_empty(void); static bool test_get_delim_str_v2_raw_result_v1(void); static bool test_get_delim_str_v2_raw_result_v2(void); static bool test_get_delim_str_v2_raw_result_add(void); static bool test_get_delim_str_v2_raw_result_replace(void); static bool test_get_delim_str_v2_raw_result_add_replace(void); static bool test_get_delim_str_v2_raw_mark_empty(void); static bool test_get_delim_str_v2_raw_mark_v1(void); static bool test_get_delim_str_v2_raw_mark_v2(void); static bool test_get_delim_str_v1_raw_return_empty(void); static bool test_get_delim_str_v1_raw_return_v1(void); static bool test_get_delim_str_v1_raw_return_v2(void); static bool test_get_delim_str_v1_raw_return_delim(void); static bool test_get_delim_str_v1_raw_error_delim(void); static bool test_get_delim_str_v1_raw_result_empty(void); static bool test_get_delim_str_v1_raw_result_v1(void); static bool test_get_delim_str_v1_raw_result_v2(void); static bool test_get_delim_str_v1_raw_result_add(void); static bool test_get_delim_str_v1_raw_result_replace(void); static bool test_get_delim_str_v1_raw_result_add_replace(void); static bool test_get_delim_str_v1or2_raw_ad_return_empty(void); static bool test_get_delim_str_v1or2_raw_ad_return_v1(void); static bool test_get_delim_str_v1or2_raw_ad_return_v2(void); static bool test_get_delim_str_v1or2_raw_ad_return_invalid_v1(void); static bool test_get_delim_str_v1or2_raw_ad_return_invalid_v2(void); static bool test_get_delim_str_v1or2_raw_ad_error_v1(void); static bool test_get_delim_str_v1or2_raw_ad_error_v2(void); static bool test_get_delim_str_v1or2_raw_ad_result_empty(void); static bool test_get_delim_str_v1or2_raw_ad_result_v1(void); static bool test_get_delim_str_v1or2_raw_ad_result_v2(void); static bool test_get_delim_str_v1or2_raw_ad_result_replace(void); static bool test_get_delim_str_v1or2_raw_return_empty(void); static bool test_get_delim_str_v1or2_raw_return_v1(void); static bool test_get_delim_str_v1or2_raw_return_v2(void); static bool test_get_delim_str_v1or2_raw_result_empty(void); static bool test_get_delim_str_v1or2_raw_result_v1(void); static bool test_get_delim_str_v1or2_raw_result_v2(void); static bool test_get_delim_str_v1or2_raw_result_add(void); static bool test_get_delim_str_v1or2_raw_result_replace(void); static bool test_get_delim_str_v1or2_raw_result_add_replace(void); static bool test_get_delim_str_v2_quoted_return_empty(void); static bool test_get_delim_str_v2_quoted_return_v1(void); static bool test_get_delim_str_v2_quoted_return_v2(void); static bool test_get_delim_str_v2_quoted_result_empty(void); static bool test_get_delim_str_v2_quoted_result_v1(void); static bool test_get_delim_str_v2_quoted_result_v2(void); static bool test_get_delim_str_v2_quoted_result_add(void); static bool test_get_delim_str_v2_quoted_result_replace(void); static bool test_get_delim_str_v2_quoted_result_add_replace(void); static bool test_get_delim_str_v1r_or_v2q_return_empty(void); static bool test_get_delim_str_v1r_or_v2q_return_v1(void); static bool test_get_delim_str_v1r_or_v2q_return_v2(void); static bool test_get_delim_str_v1r_or_v2q_result_empty(void); static bool test_get_delim_str_v1r_or_v2q_result_v1(void); static bool test_get_delim_str_v1r_or_v2q_result_v2(void); static bool test_get_delim_str_v1r_or_v2q_result_add(void); static bool test_get_delim_str_v1r_or_v2q_result_replace(void); static bool test_get_delim_str_v1r_or_v2q_result_add_replace(void); static bool test_get_string_array_empty(void); static bool test_get_string_array_v1(void); static bool test_get_string_array_v2(void); static bool test_get_string_array_add(void); static bool test_get_string_array_replace(void); static bool test_get_string_array_add_replace(void); static bool test_get_env_bool_return_empty_empty(void); static bool test_get_env_bool_return_empty_not(void); static bool test_get_env_bool_return_hit_one(void); static bool test_get_env_bool_return_hit_all(void); static bool test_get_env_bool_value_miss(void); static bool test_get_env_bool_value_hit_one(void); static bool test_get_env_bool_value_hit_all(void); static bool test_is_safe_env_v1_value_false_null(void); static bool test_is_safe_env_v1_value_false_semi(void); static bool test_is_safe_env_v1_value_false_newline(void); static bool test_is_safe_env_v1_value_false_param(void); static bool test_is_safe_env_v1_value_true_one(void); static bool test_is_safe_env_v1_value_true_quotes(void); static bool test_is_safe_env_v2_value_false_null(void); static bool test_is_safe_env_v2_value_false_newline(void); static bool test_is_safe_env_v2_value_true_one(void); static bool test_is_safe_env_v2_value_true_many(void); static bool test_get_env_v1_delim_param_winnt(void); static bool test_get_env_v1_delim_param_win32(void); static bool test_get_env_v1_delim_param_unix(void); static bool test_is_v2_quoted_string_false_v1(void); static bool test_is_v2_quoted_string_false_v2(void); static bool test_is_v2_quoted_string_true(void); static bool test_v2_quoted_to_v2_raw_return_false_miss_end(void); static bool test_v2_quoted_to_v2_raw_return_false_trail(void); static bool test_v2_quoted_to_v2_raw_return_true(void); static bool test_v2_quoted_to_v2_raw_return_true_semi(void); static bool test_v2_quoted_to_v2_raw_error_miss_end(void); static bool test_v2_quoted_to_v2_raw_error_trail(void); static bool test_v2_quoted_to_v2_raw_result(void); static bool test_v2_quoted_to_v2_raw_result_semi(void); static bool test_input_was_v1_false_empty(void); static bool test_input_was_v1_false_v2q_or(void); static bool test_input_was_v1_false_v2q(void); static bool test_input_was_v1_false_v2r_or(void); static bool test_input_was_v1_false_v2r(void); static bool test_input_was_v1_false_array(void); static bool test_input_was_v1_false_str(void); static bool test_input_was_v1_false_env(void); static bool test_input_was_v1_false_ad(void); static bool test_input_was_v1_true_v1r_or(void); static bool test_input_was_v1_true_v1r(void); static bool test_input_was_v1_true_ad(void); #ifdef WIN32 #define V1_ENV_DELIM "|" #else #define V1_ENV_DELIM ";" #endif #define V1_ENV_DELIM_NIX ";" #define V1_ENV_DELIM_WIN "|" //char* constants static const char *V1R = "one=1" V1_ENV_DELIM "two=2" V1_ENV_DELIM "three=3", //V1Raw format *V1R_NIX = "one=1;two=2;three=3", *V1R_WIN = "one=1|two=2|three=3", *V1R_MISS_NAME = "=1" V1_ENV_DELIM "two=2" V1_ENV_DELIM "three=3", *V1R_MISS_DELIM = "one1" V1_ENV_DELIM "two=2" V1_ENV_DELIM "three=3", *V1R_MISS_BOTH = "=1" V1_ENV_DELIM "two2" V1_ENV_DELIM "three=3", *V2R ="one=1 two=2 three=3", //V2Raw format *V2R_MISS_NAME ="=1 two=2 three=3", *V2R_MISS_DELIM ="one1 two=2 three=3", *V2R_MISS_BOTH ="=1 two2 three=3", *ARRAY_SKIP_BAD_STR = "one=1 two2 three=3", *V2R_SEMI ="one=1 two=2 three=3 semi=" V1_ENV_DELIM, *V2R_MARK =" one=1 two=2 three=3 semi=" V1_ENV_DELIM , *V2Q ="\"one=1 two=2 three=3\"", //V2Quoted format *V2Q_MISS_NAME = "\"=1 two=2 three=3\"", *V2Q_MISS_DELIM = "\"one1 two=2 three=3\"", *V2Q_MISS_BOTH = "\"=1 two2 three=3\"", *V2Q_MISS_END = "\"one=1 two=2 three=3", *V2Q_TRAIL = "\"one=1 two=2 three=3\"extra=stuff", *V2Q_SEMI ="\"one=1 two=2 three=3 semi=" V1_ENV_DELIM "\"", *V2Q_DELIM_SEMI = "\"one=1" V1_ENV_DELIM "two=2" V1_ENV_DELIM "three=3\"", *V1R_ADD = "four=4" V1_ENV_DELIM "five=5", //V1Raw format *V2R_ADD = "four=4 five=5", //V2Raw format *V1R_REP = "one=10" V1_ENV_DELIM "two=200" V1_ENV_DELIM "three=3000", //V1Raw format // *V1R_REP_NIX = "one=10;two=200;three=3000", *V1R_REP_WIN = "one=10|two=200|three=3000", *V2R_REP = "one=10 two=200 three=3000", //V2Raw format *V2R_REP_SEMI = "one=10 two=200 three=3000 semi=" V1_ENV_DELIM, *V2Q_REP = "\"one=10 two=200 three=3000\"", //V2Quoted format *V2Q_REP_SEMI = "\"one=10 two=200 three=3000 semi=" V1_ENV_DELIM "\"", *V1R_REP_ADD = "one=10" V1_ENV_DELIM "two=200" V1_ENV_DELIM "three=3000" V1_ENV_DELIM "four=4" V1_ENV_DELIM "five=5", //V1Raw format *V2R_REP_ADD = "one=10 two=200 three=3000 four=4 five=5", //V2Raw format *V2R_REP_ADD_SEMI = "one=10 two=200 three=3000 four=4 five=5 semi=" V1_ENV_DELIM, *V2Q_REP_ADD = "\"one=10 two=200 three=3000 four=4 five=5\"", //V2Quoted *V2Q_REP_ADD_SEMI = "\"one=10 two=200 three=3000 four=4 five=5 semi=" V1_ENV_DELIM "\"", *AD = "\tone=1\n\t\ttwo=2\n\t\tthree=3", //ClassAd string *AD_V1 = "\tEnv = \"one=1" V1_ENV_DELIM "two=2" V1_ENV_DELIM "three=3\"", //ClassAd with V1 Env *AD_V1_WIN = "\tEnv = \"one=1|two=2|three=3\"\nEnvDelim = \"|\"", *AD_V1_MISS_NAME = "\tEnv = \"=1" V1_ENV_DELIM "two=2" V1_ENV_DELIM "three=3\"", *AD_V1_MISS_DELIM = "\tEnv = \"one1" V1_ENV_DELIM "two=2" V1_ENV_DELIM "three=3\"", *AD_V1_MISS_BOTH = "\tEnv = \"=1" V1_ENV_DELIM "two2" V1_ENV_DELIM "three=3\"", *AD_V1_REP = "\tEnv = \"one=10" V1_ENV_DELIM "two=200" V1_ENV_DELIM "three=3000\"", *AD_V1_REP_ADD = "\tEnv = \"one=10" V1_ENV_DELIM "two=200" V1_ENV_DELIM "three=3000" V1_ENV_DELIM "four=4" V1_ENV_DELIM "five=5\"", *AD_V2 = "\tEnvironment = \"one=1 two=2 three=3\"", //ClassAd with V2 Env *AD_V2_MISS_NAME = "\tEnvironment = \"=1 two=2 three=3\"", *AD_V2_MISS_DELIM = "\tEnvironment = \"one1 two=2 three=3\"", *AD_V2_MISS_BOTH = "\tEnvironment = \"=1 two2 three=3\"", *AD_V2_REP = "\tEnvironment = \"one=10 two=200 three=3000\"", *AD_V2_REP_ADD = "\tEnvironment = \"one=10 two=200 three=3000 four=4 " "five=5\"", *AD_V2_SEMI = "\tEnvironment = \"one=1 two=2 three=3 semi=" V1_ENV_DELIM "\"", *ONE = "one=1", //Single Env Var string *ONE_MISS_NAME = "=1", *ONE_MISS_DELIM = "one1", *ONE_MISS_VAL = "one=", *ONE_REP = "one=10", *NULL_DELIM = "one=1\0two=2\0three=3\0", //NULL-Delimited string *NULL_DELIM_MISS_NAME = "=1\0two=2\0three=3\0", *NULL_DELIM_MISS_DELIM = "one1\0two=2\0three=3\0", *NULL_DELIM_REP = "one=10\0two=200\0three=3000\0", *NULL_DELIM_REP_ADD = "one=10\0two=200\0three=3000\0four=4\0five=5\0", *EMPTY = ""; //char** constants static const char *ARRAY[] = {"one=1", "two=2", "three=3", ""}, *ARRAY_MISS_NAME[] = {"=1", "two=2", "three=3", ""}, *ARRAY_MISS_DELIM[] = {"one1", "two=2", "three=3", ""}, *ARRAY_SKIP_BAD[] = {"one=1", "two2", "three=3", ""}, *ARRAY_SKIP_BAD_CLEAN[] = {"one=1", "three=3", ""}, *ARRAY_REP[] = {"one=10", "two=200", "three=3000", ""}, *ARRAY_REP_ADD[] = {"one=10", "two=200", "three=3000", "four=4", "five=5", ""}; //MyString constants static const MyString ADD("one=1 two=2 three=3"), ADD_SEMI("one=1 two=2 three=3 semi=;"), REP("one=10 two=200 three=3000"), REP_SEMI("one=10 two=200 three=3000 semi=;"), REP_ADD("one=10 two=200 three=3000 four=4 five=5"), REP_ADD_SEMI("one=10 two=200 three=3000 four=4 five=5 semi=;"); bool OTEST_Env(void) { emit_object("Env"); emit_comment("The Env object maintains a collection of environment " "settings, e.g. for a process that we are about to exec. Environment " "values may be fed into the Env object in several formats."); emit_comment("Many of the tests use getDelimitedStringForDisplay() to " "compare the contents of the Env so any issues with that may cause " "other tests to fail."); emit_comment("Although the EXPECTED OUTPUT and ACTUAL OUTPUT may not " "be identical for some tests, they contain the same variables and " "values just in a different order which doesn't matter"); FunctionDriver driver; driver.register_function(test_count_0); driver.register_function(test_count_1); driver.register_function(test_count_many); driver.register_function(test_clear_empty); driver.register_function(test_clear_non_empty); driver.register_function(test_mf_v1r_or_v2q_ret_null); driver.register_function(test_mf_v1r_or_v2q_detect_v1r); driver.register_function(test_mf_v1r_or_v2q_detect_v2q); driver.register_function(test_mf_v1r_or_v2q_add_null); driver.register_function(test_mf_v2q_ret_null); driver.register_function(test_mf_v2q_ret_valid); driver.register_function(test_mf_v2q_ret_invalid_quotes); driver.register_function(test_mf_v2q_ret_invalid_quotes_end); driver.register_function(test_mf_v2q_ret_invalid_trail); driver.register_function(test_mf_v2q_ret_invalid_name); driver.register_function(test_mf_v2q_ret_invalid_delim); driver.register_function(test_mf_v2q_error_invalid_quotes); driver.register_function(test_mf_v2q_error_invalid_quotes_end); driver.register_function(test_mf_v2q_error_invalid_trail); driver.register_function(test_mf_v2q_error_invalid_name); driver.register_function(test_mf_v2q_error_invalid_delim); driver.register_function(test_mf_v2q_add_null); driver.register_function(test_mf_v2q_add_invalid_delim_var); driver.register_function(test_mf_v2q_add_invalid_quotes); driver.register_function(test_mf_v2q_add_invalid_quotes_end); driver.register_function(test_mf_v2q_add_invalid_trail); driver.register_function(test_mf_v2q_add); driver.register_function(test_mf_v2q_replace); driver.register_function(test_mf_v2q_replace_v1r); driver.register_function(test_mf_v2q_replace_add); driver.register_function(test_mf_v2q_replace_add_v1r); driver.register_function(test_mf_v2r_ret_null); driver.register_function(test_mf_v2r_ret_valid); driver.register_function(test_mf_v2r_ret_invalid_name); driver.register_function(test_mf_v2r_ret_invalid_delim); driver.register_function(test_mf_v2r_error_invalid_name); driver.register_function(test_mf_v2r_error_invalid_delim); driver.register_function(test_mf_v2r_add_null); driver.register_function(test_mf_v2r_add_invalid); driver.register_function(test_mf_v2r_add); driver.register_function(test_mf_v2r_replace); driver.register_function(test_mf_v2r_replace_v1r); driver.register_function(test_mf_v2r_replace_add); driver.register_function(test_mf_v2r_replace_add_v1r); driver.register_function(test_mf_v1r_ret_null); driver.register_function(test_mf_v1r_ret_valid); driver.register_function(test_mf_v1r_ret_invalid_name); driver.register_function(test_mf_v1r_ret_invalid_delim); driver.register_function(test_mf_v1r_error_invalid_name); driver.register_function(test_mf_v1r_error_invalid_delim); driver.register_function(test_mf_v1r_add_null); driver.register_function(test_mf_v1r_add_invalid); driver.register_function(test_mf_v1r_add); driver.register_function(test_mf_v1r_replace); driver.register_function(test_mf_v1r_replace_v2r); driver.register_function(test_mf_v1r_replace_v2q); driver.register_function(test_mf_v1r_replace_add); driver.register_function(test_mf_v1r_replace_add_v2r); driver.register_function(test_mf_v1r_replace_add_v2q); driver.register_function(test_mf_v1or2_r_ret_null); driver.register_function(test_mf_v1or2_r_detect_v1r); driver.register_function(test_mf_v1or2_r_detect_v2r); driver.register_function(test_mf_v1or2_r_add_null); driver.register_function(test_mf_v1or2_r_add_v2r); driver.register_function(test_mf_str_array_ret_null); driver.register_function(test_mf_str_array_ret_valid); driver.register_function(test_mf_str_array_ret_invalid_name); driver.register_function(test_mf_str_array_ret_invalid_delim); driver.register_function(test_mf_str_array_add_null); driver.register_function(test_mf_str_array_add_invalid); driver.register_function(test_mf_str_array_add); driver.register_function(test_mf_str_array_replace); driver.register_function(test_mf_str_array_replace_add); driver.register_function(test_mf_str_ret_null); driver.register_function(test_mf_str_ret_valid); driver.register_function(test_mf_str_ret_invalid_name); driver.register_function(test_mf_str_ret_invalid_delim); driver.register_function(test_mf_str_add_null); driver.register_function(test_mf_str_add_invalid_name); driver.register_function(test_mf_str_add_invalid_delim); driver.register_function(test_mf_str_add); driver.register_function(test_mf_str_replace); driver.register_function(test_mf_str_replace_add); driver.register_function(test_mf_env_add_empty); driver.register_function(test_mf_env_add_one); driver.register_function(test_mf_env_add_many); driver.register_function(test_mf_env_replace); driver.register_function(test_mf_env_replace_v1_v2); driver.register_function(test_mf_env_replace_v2_v1); driver.register_function(test_mf_env_replace_add); driver.register_function(test_mf_env_replace_add_v1_v2); driver.register_function(test_mf_env_replace_add_v2_v1); driver.register_function(test_mf_env_itself); driver.register_function(test_mf_ad_ret_null); driver.register_function(test_mf_ad_ret_v1r_valid); driver.register_function(test_mf_ad_ret_v2r_valid); driver.register_function(test_mf_ad_ret_valid_define); driver.register_function(test_mf_ad_ret_v1r_invalid_name); driver.register_function(test_mf_ad_ret_v1r_invalid_delim); driver.register_function(test_mf_ad_ret_v2r_invalid_name); driver.register_function(test_mf_ad_ret_v2r_invalid_delim); driver.register_function(test_mf_ad_error_v1r_invalid_name); driver.register_function(test_mf_ad_error_v1r_invalid_delim); driver.register_function(test_mf_ad_error_v2r_invalid_name); driver.register_function(test_mf_ad_error_v2r_invalid_delim); driver.register_function(test_mf_ad_add_null); driver.register_function(test_mf_ad_add_define); driver.register_function(test_mf_ad_add_v1r_one); driver.register_function(test_mf_ad_add_v1r_many); driver.register_function(test_mf_ad_add_v2r_one); driver.register_function(test_mf_ad_add_v2r_many); driver.register_function(test_mf_ad_v1r_replace); driver.register_function(test_mf_ad_v2r_replace); driver.register_function(test_mf_ad_v1r_replace_add); driver.register_function(test_mf_ad_v2r_replace_add); driver.register_function(test_set_env_with_error_message_ret_null); driver.register_function(test_set_env_with_error_message_ret_valid); driver.register_function(test_set_env_with_error_message_ret_invalid_name); driver.register_function(test_set_env_with_error_message_ret_invalid_delim); driver.register_function(test_set_env_with_error_message_err_invalid_name); driver.register_function(test_set_env_with_error_message_err_invalid_delim); driver.register_function(test_set_env_with_error_message_add_null); driver.register_function(test_set_env_with_error_message_add_invalid_delim); driver.register_function(test_set_env_with_error_message_add_invalid_var); driver.register_function(test_set_env_with_error_message_add); driver.register_function(test_set_env_with_error_message_replace); driver.register_function(test_set_env_str_ret_null); driver.register_function(test_set_env_str_ret_valid); driver.register_function(test_set_env_str_ret_invalid_name); driver.register_function(test_set_env_str_ret_invalid_delim); driver.register_function(test_set_env_str_add_null); driver.register_function(test_set_env_str_add_invalid); driver.register_function(test_set_env_str_add); driver.register_function(test_set_env_str_replace); driver.register_function(test_set_env_str_str_ret_null_var); driver.register_function(test_set_env_str_str_ret_null_val); driver.register_function(test_set_env_str_str_ret_valid); driver.register_function(test_set_env_str_str_add_null_var); driver.register_function(test_set_env_str_str_add_null_val); driver.register_function(test_set_env_str_str_add); driver.register_function(test_set_env_str_str_replace); driver.register_function(test_set_env_mystr_ret_empty_var); driver.register_function(test_set_env_mystr_ret_empty_val); driver.register_function(test_set_env_mystr_ret_valid); driver.register_function(test_set_env_mystr_add_empty_var); driver.register_function(test_set_env_mystr_add_empty_val); driver.register_function(test_set_env_mystr_add); driver.register_function(test_set_env_mystr_replace); driver.register_function(test_insert_env_into_classad_v1_empty); driver.register_function(test_insert_env_into_classad_v2_empty); driver.register_function(test_insert_env_into_classad_v1_v1_replace); driver.register_function(test_insert_env_into_classad_v1_v2_replace); driver.register_function(test_insert_env_into_classad_v2_v1_replace); driver.register_function(test_insert_env_into_classad_v2_v2_replace); driver.register_function(test_insert_env_into_classad_version_v1); driver.register_function(test_insert_env_into_classad_version_v1_os_winnt); driver.register_function(test_insert_env_into_classad_version_v1_os_win32); driver.register_function(test_insert_env_into_classad_version_v1_os_unix); driver.register_function(test_insert_env_into_classad_version_v1_semi); driver.register_function(test_insert_env_into_classad_version_v1_line); driver.register_function(test_insert_env_into_classad_version_v1_current); driver.register_function(test_insert_env_into_classad_version_v1_error_v2); driver.register_function(test_insert_env_into_classad_version_v1_error); driver.register_function(test_insert_env_into_classad_version_v2); driver.register_function(test_condor_version_requires_v1_false); driver.register_function(test_condor_version_requires_v1_true); driver.register_function(test_condor_version_requires_v1_this); driver.register_function(test_get_delim_str_v2_raw_return_empty); driver.register_function(test_get_delim_str_v2_raw_return_v1); driver.register_function(test_get_delim_str_v2_raw_return_v2); driver.register_function(test_get_delim_str_v2_raw_result_empty); driver.register_function(test_get_delim_str_v2_raw_result_v1); driver.register_function(test_get_delim_str_v2_raw_result_v2); driver.register_function(test_get_delim_str_v2_raw_result_add); driver.register_function(test_get_delim_str_v2_raw_result_replace); driver.register_function(test_get_delim_str_v2_raw_result_add_replace); driver.register_function(test_get_delim_str_v2_raw_mark_empty); driver.register_function(test_get_delim_str_v2_raw_mark_v1); driver.register_function(test_get_delim_str_v2_raw_mark_v2); driver.register_function(test_get_delim_str_v1_raw_return_empty); driver.register_function(test_get_delim_str_v1_raw_return_v1); driver.register_function(test_get_delim_str_v1_raw_return_v2); driver.register_function(test_get_delim_str_v1_raw_return_delim); driver.register_function(test_get_delim_str_v1_raw_error_delim); driver.register_function(test_get_delim_str_v1_raw_result_empty); driver.register_function(test_get_delim_str_v1_raw_result_v1); driver.register_function(test_get_delim_str_v1_raw_result_v2); driver.register_function(test_get_delim_str_v1_raw_result_add); driver.register_function(test_get_delim_str_v1_raw_result_replace); driver.register_function(test_get_delim_str_v1_raw_result_add_replace); driver.register_function(test_get_delim_str_v1or2_raw_ad_return_empty); driver.register_function(test_get_delim_str_v1or2_raw_ad_return_v1); driver.register_function(test_get_delim_str_v1or2_raw_ad_return_v2); driver.register_function(test_get_delim_str_v1or2_raw_ad_return_invalid_v1); driver.register_function(test_get_delim_str_v1or2_raw_ad_return_invalid_v2); driver.register_function(test_get_delim_str_v1or2_raw_ad_error_v1); driver.register_function(test_get_delim_str_v1or2_raw_ad_error_v2); driver.register_function(test_get_delim_str_v1or2_raw_ad_result_empty); driver.register_function(test_get_delim_str_v1or2_raw_ad_result_v1); driver.register_function(test_get_delim_str_v1or2_raw_ad_result_v2); driver.register_function(test_get_delim_str_v1or2_raw_ad_result_replace); driver.register_function(test_get_delim_str_v1or2_raw_return_empty); driver.register_function(test_get_delim_str_v1or2_raw_return_v1); driver.register_function(test_get_delim_str_v1or2_raw_return_v2); driver.register_function(test_get_delim_str_v1or2_raw_result_empty); driver.register_function(test_get_delim_str_v1or2_raw_result_v1); driver.register_function(test_get_delim_str_v1or2_raw_result_v2); driver.register_function(test_get_delim_str_v1or2_raw_result_add); driver.register_function(test_get_delim_str_v1or2_raw_result_replace); driver.register_function(test_get_delim_str_v1or2_raw_result_add_replace); driver.register_function(test_get_delim_str_v2_quoted_return_empty); driver.register_function(test_get_delim_str_v2_quoted_return_v1); driver.register_function(test_get_delim_str_v2_quoted_return_v2); driver.register_function(test_get_delim_str_v2_quoted_result_empty); driver.register_function(test_get_delim_str_v2_quoted_result_v1); driver.register_function(test_get_delim_str_v2_quoted_result_v2); driver.register_function(test_get_delim_str_v2_quoted_result_add); driver.register_function(test_get_delim_str_v2_quoted_result_replace); driver.register_function(test_get_delim_str_v2_quoted_result_add_replace); driver.register_function(test_get_delim_str_v1r_or_v2q_return_empty); driver.register_function(test_get_delim_str_v1r_or_v2q_return_v1); driver.register_function(test_get_delim_str_v1r_or_v2q_return_v2); driver.register_function(test_get_delim_str_v1r_or_v2q_result_empty); driver.register_function(test_get_delim_str_v1r_or_v2q_result_v1); driver.register_function(test_get_delim_str_v1r_or_v2q_result_v2); driver.register_function(test_get_delim_str_v1r_or_v2q_result_add); driver.register_function(test_get_delim_str_v1r_or_v2q_result_replace); driver.register_function(test_get_delim_str_v1r_or_v2q_result_add_replace); driver.register_function(test_get_string_array_empty); driver.register_function(test_get_string_array_v1); driver.register_function(test_get_string_array_v2); driver.register_function(test_get_string_array_add); driver.register_function(test_get_string_array_replace); driver.register_function(test_get_string_array_add_replace); driver.register_function(test_get_env_bool_return_empty_empty); driver.register_function(test_get_env_bool_return_empty_not); driver.register_function(test_get_env_bool_return_hit_one); driver.register_function(test_get_env_bool_return_hit_all); driver.register_function(test_get_env_bool_value_miss); driver.register_function(test_get_env_bool_value_hit_one); driver.register_function(test_get_env_bool_value_hit_all); driver.register_function(test_is_safe_env_v1_value_false_null); driver.register_function(test_is_safe_env_v1_value_false_semi); driver.register_function(test_is_safe_env_v1_value_false_newline); driver.register_function(test_is_safe_env_v1_value_false_param); driver.register_function(test_is_safe_env_v1_value_true_one); driver.register_function(test_is_safe_env_v1_value_true_quotes); driver.register_function(test_is_safe_env_v2_value_false_null); driver.register_function(test_is_safe_env_v2_value_false_newline); driver.register_function(test_is_safe_env_v2_value_true_one); driver.register_function(test_is_safe_env_v2_value_true_many); driver.register_function(test_get_env_v1_delim_param_winnt); driver.register_function(test_get_env_v1_delim_param_win32); driver.register_function(test_get_env_v1_delim_param_unix); driver.register_function(test_is_v2_quoted_string_false_v1); driver.register_function(test_is_v2_quoted_string_false_v2); driver.register_function(test_is_v2_quoted_string_true); driver.register_function(test_v2_quoted_to_v2_raw_return_false_miss_end); driver.register_function(test_v2_quoted_to_v2_raw_return_false_trail); driver.register_function(test_v2_quoted_to_v2_raw_return_true); driver.register_function(test_v2_quoted_to_v2_raw_return_true_semi); driver.register_function(test_v2_quoted_to_v2_raw_error_miss_end); driver.register_function(test_v2_quoted_to_v2_raw_error_trail); driver.register_function(test_v2_quoted_to_v2_raw_result); driver.register_function(test_v2_quoted_to_v2_raw_result_semi); driver.register_function(test_input_was_v1_false_empty); driver.register_function(test_input_was_v1_false_v2q_or); driver.register_function(test_input_was_v1_false_v2q); driver.register_function(test_input_was_v1_false_v2r_or); driver.register_function(test_input_was_v1_false_v2r); driver.register_function(test_input_was_v1_false_array); driver.register_function(test_input_was_v1_false_str); driver.register_function(test_input_was_v1_false_env); driver.register_function(test_input_was_v1_false_ad); driver.register_function(test_input_was_v1_true_v1r_or); driver.register_function(test_input_was_v1_true_v1r); driver.register_function(test_input_was_v1_true_ad); return driver.do_all_functions(); } static bool test_count_0() { emit_test("Test that Count() returns 0 for an Env object with 0 " "environment variables."); Env env; int expect = 0; int actual = env.Count(); emit_output_expected_header(); emit_retval("%d", expect); emit_output_actual_header(); emit_retval("%d", actual); if(actual != expect) { FAIL; } PASS; } static bool test_count_1() { emit_test("Test that Count() returns 1 for an Env object with 1 " "environment variable after adding one with SetEnv()."); Env env; env.SetEnv("one", "1"); int expect = 1; int actual = env.Count(); emit_output_expected_header(); emit_retval("%d", expect); emit_output_actual_header(); emit_retval("%d", actual); if(actual != expect) { FAIL; } PASS; } static bool test_count_many() { emit_test("Test that Count() returns the correct number of environment " "varaibles after adding many variables with MergeFromV2Raw()."); Env env; env.MergeFromV2Raw(V2R, NULL); int expect = 3; int actual = env.Count(); emit_output_expected_header(); emit_retval("%d", expect); emit_output_actual_header(); emit_retval("%d", actual); if(actual != expect) { FAIL; } PASS; } static bool test_clear_empty() { emit_test("Test Clear() on an empty Env object."); Env env; env.Clear(); int expect = 0; int actual = env.Count(); emit_output_expected_header(); emit_param("Count", "%d", expect); emit_output_actual_header(); emit_param("Count", "%d", actual); if(actual != expect) { FAIL; } PASS; } static bool test_clear_non_empty() { emit_test("Test Clear() on a non-empty Env object."); Env env; env.MergeFromV2Raw(V2R, NULL); env.Clear(); int expect = 0; int actual = env.Count(); emit_output_expected_header(); emit_param("Count", "%d", expect); emit_output_actual_header(); emit_param("Count", "%d", actual); if(actual != expect) { FAIL; } PASS; } static bool test_mf_v1r_or_v2q_ret_null() { emit_test("Test that MergeFromV1RawOrV2Quoted() returns true when passed " "a NULL string."); Env env; bool expect = true; bool actual = env.MergeFromV1RawOrV2Quoted(NULL, NULL); emit_input_header(); emit_param("STRING", "%s", "NULL"); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_mf_v1r_or_v2q_detect_v1r() { emit_test("Test that MergeFromV1RawOrV2Quoted() correctly handles a V1Raw" "string by checking that InputWasV1() returns true."); emit_comment("MergeFromV1RaworV2Quoted() just calls MergeFromV1Raw(), " "which is tested below."); Env env; bool expect = true; env.MergeFromV1RawOrV2Quoted(V1R, NULL); bool actual = env.InputWasV1(); emit_input_header(); emit_param("STRING", "%s", V1R); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("InputWasV1()", "%s", tfstr(expect)); emit_output_actual_header(); emit_retval("InputWasV1()", "%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_mf_v1r_or_v2q_detect_v2q() { emit_test("Test that MergeFromV1RawOrV2Quoted() correctly handles a " "V2Quoted string by checking that InputWasV1() returns false."); emit_comment("MergeFromV1RaworV2Quoted() just calls MergeFromVqQuoted(), " "which is tested below."); Env env; bool expect = false; env.MergeFromV1RawOrV2Quoted(V2Q_SEMI, NULL); bool actual = env.InputWasV1(); emit_input_header(); emit_param("STRING", "%s", V2Q_SEMI); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("InputWasV1()", "%s", tfstr(expect)); emit_output_actual_header(); emit_retval("InputWasV1()", "%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_mf_v1r_or_v2q_add_null() { emit_test("Test that MergeFromV1RawOrV2Quoted() doesn't add any " "environment variables for a NULL string."); Env env; MyString actual; env.MergeFromV1RawOrV2Quoted(NULL, NULL); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("STRING", "%s", "NULL"); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("Env", "%s", EMPTY); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(actual != EMPTY) { FAIL; } PASS; } static bool test_mf_v2q_ret_null() { emit_test("Test that MergeFromV2Quoted() returns true when passed a NULL " "string."); Env env; bool expect = true; bool actual = env.MergeFromV2Quoted(NULL, NULL); emit_input_header(); emit_param("STRING", "%s", "NULL"); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_mf_v2q_ret_valid() { emit_test("Test that MergeFromV2Quoted() returns true when passed a valid" " V2Quoted string."); Env env; bool expect = true; bool actual = env.MergeFromV2Quoted(V2Q, NULL); emit_input_header(); emit_param("STRING", "%s", V2Q); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_mf_v2q_ret_invalid_quotes() { emit_test("Test that MergeFromV2Quoted() returns false when passed an " "invalid V2Quoted string due to no quotes."); Env env; bool expect = false; bool actual = env.MergeFromV2Quoted(V2R, NULL); emit_input_header(); emit_param("STRING", "%s", V2R); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_mf_v2q_ret_invalid_quotes_end() { emit_test("Test that MergeFromV2Quoted() returns false when passed an " "invalid V2Quoted string due missing quotes at the end."); Env env; bool expect = false; bool actual = env.MergeFromV2Quoted(V2Q_MISS_END, NULL); emit_input_header(); emit_param("STRING", "%s", V2Q_MISS_END); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_mf_v2q_ret_invalid_trail() { emit_test("Test that MergeFromV2Quoted() returns false when passed an " "invalid V2Quoted string due to trailing characters after the quotes."); Env env; bool expect = false; bool actual = env.MergeFromV2Quoted(V2Q_TRAIL, NULL); emit_input_header(); emit_param("STRING", "%s", V2Q_TRAIL); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_mf_v2q_ret_invalid_name() { emit_test("Test that MergeFromV2Quoted() returns false when passed an " "invalid V2Quoted string due to a missing variable name."); Env env; bool expect = false; bool actual = env.MergeFromV2Quoted(V2Q_MISS_NAME, NULL); emit_input_header(); emit_param("STRING", "%s", V2Q_MISS_NAME); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_mf_v2q_ret_invalid_delim() { emit_test("Test that MergeFromV2Quoted() returns false when passed an " "invalid V2Quoted string due to a missing delimiter."); Env env; bool expect = false; bool actual = env.MergeFromV2Quoted(V2Q_MISS_DELIM, NULL); emit_input_header(); emit_param("STRING", "%s", V2Q_MISS_DELIM); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_mf_v2q_error_invalid_quotes() { emit_test("Test that MergeFromV2Quoted() generates an error message for " "an invalid V2Quoted string due to no quotes."); emit_comment("This test just checks if the error message is not empty."); Env env; MyString actual; env.MergeFromV2Quoted(V1R, &actual); emit_input_header(); emit_param("STRING", "%s", V1R); emit_param("MyString", "%s", ""); emit_output_actual_header(); emit_param("Error Message", "%s", actual.Value()); if(actual.IsEmpty()) { FAIL; } PASS; } static bool test_mf_v2q_error_invalid_quotes_end() { emit_test("Test that MergeFromV2Quoted() generates an error message for " "an invalid V2Quoted string due to missing quotes at the end."); emit_comment("This test just checks if the error message is not empty."); Env env; MyString actual; env.MergeFromV2Quoted(V2Q_MISS_END, &actual); emit_input_header(); emit_param("STRING", "%s", V2Q_MISS_END); emit_param("MyString", "%s", ""); emit_output_actual_header(); emit_param("Error Message", "%s", actual.Value()); if(actual.IsEmpty()) { FAIL; } PASS; } static bool test_mf_v2q_error_invalid_trail() { emit_test("Test that MergeFromV2Quoted() generates an error message for " "an invalid V2Quoted string due to trailing characters after the " "quotes."); emit_comment("This test just checks if the error message is not empty."); Env env; MyString actual; env.MergeFromV2Quoted(V2Q_TRAIL, &actual); emit_input_header(); emit_param("STRING", "%s", V2Q_TRAIL); emit_param("MyString", "%s", ""); emit_output_actual_header(); emit_param("Error Message", "%s", actual.Value()); if(actual.IsEmpty()) { FAIL; } PASS; } static bool test_mf_v2q_error_invalid_name() { emit_test("Test that MergeFromV2Quoted() generates an error message for " "an invalid V2Quoted string due to a missing variable name."); emit_comment("This test just checks if the error message is not empty."); Env env; MyString actual; env.MergeFromV2Quoted(V2Q_MISS_NAME, &actual); emit_input_header(); emit_param("STRING", "%s", V2Q_MISS_NAME); emit_param("MyString", "%s", ""); emit_output_actual_header(); emit_param("Error Message", "%s", actual.Value()); if(actual.IsEmpty()) { FAIL; } PASS; } static bool test_mf_v2q_error_invalid_delim() { emit_test("Test that MergeFromV2Quoted() generates an error message for " "an invalid V2Quoted string due to a missing delimiter."); emit_comment("This test just checks if the error message is not empty."); Env env; MyString actual; env.MergeFromV2Quoted(V2Q_MISS_DELIM, &actual); emit_input_header(); emit_param("STRING", "%s", V2Q_MISS_DELIM); emit_param("MyString", "%s", ""); emit_output_actual_header(); emit_param("Error Message", "%s", actual.Value()); if(actual.IsEmpty()) { FAIL; } PASS; } static bool test_mf_v2q_add_null() { emit_test("Test that MergeFromV2Quoted() doesn't add the environment " "variables for a NULL string."); Env env; MyString actual; env.MergeFromV2Quoted(NULL, NULL); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("STRING", "%s", "NULL"); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("Env", "%s", EMPTY); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(actual != EMPTY) { FAIL; } PASS; } static bool test_mf_v2q_add_invalid_delim_var() { emit_test("Test that MergeFromV2Quoted() doesn't add the environment " "variables for an invalid V2Quoted string with a missing delimiter and " "a missing variable name."); Env env; MyString actual; env.MergeFromV2Quoted(V2Q_MISS_BOTH, NULL); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("STRING", "%s", V2Q_MISS_BOTH); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("Env", "%s", EMPTY); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(actual != EMPTY) { FAIL; } PASS; } static bool test_mf_v2q_add_invalid_quotes() { emit_test("Test that MergeFromV2Quoted() doesn't add the environment " "variables for an invalid V2Quoted string due to missing quotes."); Env env; MyString actual; env.MergeFromV2Quoted(V2R, NULL); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("STRING", "%s", V2R); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("Env", "%s", EMPTY); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(actual != EMPTY) { FAIL; } PASS; } static bool test_mf_v2q_add_invalid_quotes_end() { emit_test("Test that MergeFromV2Quoted() doesn't add the environment " "variables for an invalid V2Quoted string due to missing quotes at the " "end."); Env env; MyString actual; env.MergeFromV2Quoted(V2Q_MISS_END, NULL); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("STRING", "%s", V2Q_MISS_END); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("Env", "%s", EMPTY); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(actual != EMPTY) { FAIL; } PASS; } static bool test_mf_v2q_add_invalid_trail() { emit_test("Test that MergeFromV2Quoted() doesn't add the environment " "variables for an invalid V2Quoted string due to trailing characters " "after the quotes at the end."); Env env; MyString actual; env.MergeFromV2Quoted(V2Q_TRAIL, NULL); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("STRING", "%s", V2Q_TRAIL); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("Env", "%s", EMPTY); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(actual != EMPTY) { FAIL; } PASS; } static bool test_mf_v2q_add() { emit_test("Test that MergeFromV2Quoted() adds the environment variables " "for a valid V2Quoted string."); Env env; MyString actual; env.MergeFromV2Quoted(V2Q, NULL); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("STRING", "%s", V2Q); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("Env", "%s", V2R); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(!strings_similar(actual.Value(), V2R)) { FAIL; } PASS; } static bool test_mf_v2q_replace() { emit_test("Test that MergeFromV2Quoted() replaces the environment " "variables for a valid V2Quoted string."); Env env; MyString actual; env.MergeFromV2Quoted(V2Q, NULL); env.MergeFromV2Quoted(V2Q_REP, NULL); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("Env", "%s", V2Q); emit_param("STRING", "%s", V2Q_REP); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("Env", "%s", V2R_REP); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(!strings_similar(actual.Value(), V2R_REP)) { FAIL; } PASS; } static bool test_mf_v2q_replace_v1r() { emit_test("Test that MergeFromV2Quoted() replaces the environment " "variables for a valid V2Quoted string on an Env object originally " "constructed from a V1Raw string."); Env env; MyString actual; env.MergeFromV1Raw(V1R, NULL); env.MergeFromV2Quoted(V2Q_REP_SEMI, NULL); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("Env", "%s", V1R); emit_param("STRING", "%s", V2Q_REP_SEMI); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("Env", "%s", V2R_REP_SEMI); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(!strings_similar(actual.Value(), V2R_REP_SEMI)) { FAIL; } PASS; } static bool test_mf_v2q_replace_add() { emit_test("Test that MergeFromV2Quoted() replaces some environment " "variables and also adds new ones for a valid V2Quoted string."); Env env; MyString actual; env.MergeFromV2Quoted(V2Q, NULL); env.MergeFromV2Quoted(V2Q_REP_ADD, NULL); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("Env", "%s", V2Q); emit_param("STRING", "%s", V2Q_REP_ADD); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("Env", "%s", V2R_REP_ADD); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(!strings_similar(actual.Value(), V2R_REP_ADD)) { FAIL; } PASS; } static bool test_mf_v2q_replace_add_v1r() { emit_test("Test that MergeFromV2Quoted() replaces some environment " "variables and also adds new ones for a valid V2Quoted string on an Env" " object originally constructed from a V1Raw string."); Env env; MyString actual; env.MergeFromV1Raw(V1R, NULL); env.MergeFromV2Quoted(V2Q_REP_ADD_SEMI, NULL); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("Env", "%s", V1R); emit_param("STRING", "%s", V2Q_REP_ADD_SEMI); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("Env", "%s", V2R_REP_ADD_SEMI); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(!strings_similar(actual.Value(), V2R_REP_ADD_SEMI)) { FAIL; } PASS; } static bool test_mf_v2r_ret_null() { emit_test("Test that MergeFromV2Raw() returns true when passed a NULL " "string."); Env env; bool expect = true; bool actual = env.MergeFromV2Raw(NULL, NULL); emit_input_header(); emit_param("STRING", "%s", "NULL"); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_mf_v2r_ret_valid() { emit_test("Test that MergeFromV2Raw() returns true when passed a valid " "V2Raw string."); Env env; bool expect = true; bool actual = env.MergeFromV2Raw(V2R, NULL); emit_input_header(); emit_param("STRING", "%s", V2R); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_mf_v2r_ret_invalid_name() { emit_test("Test that MergeFromV2Raw() returns false when passed an " "invalid V2Raw string due to a missing variable name."); Env env; bool expect = false; bool actual = env.MergeFromV2Raw(V2R_MISS_NAME, NULL); emit_input_header(); emit_param("STRING", "%s", V2R_MISS_NAME); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_mf_v2r_ret_invalid_delim() { emit_test("Test that MergeFromV2Raw() returns false when passed an " "invalid V2Raw string due to a missing delimiter."); Env env; bool expect = false; bool actual = env.MergeFromV2Raw(V2R_MISS_DELIM, NULL); emit_input_header(); emit_param("STRING", "%s", V2R_MISS_DELIM); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_mf_v2r_error_invalid_name() { emit_test("Test that MergeFromV2Raw() generates an error message for " "an invalid V2Raw string due to a missing variable name."); emit_comment("This test just checks if the error message is not empty."); Env env; MyString actual; env.MergeFromV2Raw(V2R_MISS_NAME, &actual); emit_input_header(); emit_param("STRING", "%s", V2R_MISS_NAME); emit_param("MyString", "%s", ""); emit_output_actual_header(); emit_param("Error Message", "%s", actual.Value()); if(actual.IsEmpty()) { FAIL; } PASS; } static bool test_mf_v2r_error_invalid_delim() { emit_test("Test that MergeFromV2Raw() generates an error message for " "an invalid V2Raw string due to a missing delimiter."); emit_comment("This test just checks if the error message is not empty."); Env env; MyString actual; env.MergeFromV2Raw(V2R_MISS_DELIM, &actual); emit_input_header(); emit_param("STRING", "%s", V2R_MISS_DELIM); emit_param("MyString", "%s", ""); emit_output_actual_header(); emit_param("Error Message", "%s", actual.Value()); if(actual.IsEmpty()) { FAIL; } PASS; } static bool test_mf_v2r_add_null() { emit_test("Test that MergeFromV2Raw() doesn't add the environment " "variable for a NULL string."); Env env; MyString actual; env.MergeFromV2Raw(NULL, NULL); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("STRING", "%s", "NULL"); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("Env", "%s", EMPTY); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(actual != EMPTY) { FAIL; } PASS; } static bool test_mf_v2r_add_invalid() { emit_test("Test that MergeFromV2Raw() doesn't add the environment " "variables for an invalid V2Raw string."); Env env; MyString actual; env.MergeFromV2Raw(V2R_MISS_BOTH, NULL); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("STRING", "%s", V2R_MISS_BOTH); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("Env", "%s", EMPTY); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(actual != EMPTY) { FAIL; } PASS; } static bool test_mf_v2r_add() { emit_test("Test that MergeFromV2Raw() adds the environment variables " "for a valid V2Raw string."); Env env; MyString actual; env.MergeFromV2Raw(V2R, NULL); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("STRING", "%s", V2R); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("Env", "%s", V2R); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(!strings_similar(actual.Value(), V2R)) { FAIL; } PASS; } static bool test_mf_v2r_replace() { emit_test("Test that MergeFromV2Raw() replaces the environment " "variables for a valid V2Raw string."); Env env; MyString actual; env.MergeFromV2Raw(V2R, NULL); env.MergeFromV2Raw(V2R_REP, NULL); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("Env", "%s", V2R); emit_param("STRING", "%s", V2R_REP); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("Env", "%s", V2R_REP); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(!strings_similar(actual.Value(), V2R_REP)) { FAIL; } PASS; } static bool test_mf_v2r_replace_v1r() { emit_test("Test that MergeFromV2Raw() replaces the environment " "variables for a valid V2Raw string on an Env object originally " "constructed from a V1Raw string."); Env env; MyString actual; env.MergeFromV1Raw(V1R, NULL); env.MergeFromV2Raw(V2R_REP_SEMI, NULL); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("Env", "%s", V1R); emit_param("STRING", "%s", V2R_REP_SEMI); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("Env", "%s", V2R_REP_SEMI); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(!strings_similar(actual.Value(), V2R_REP_SEMI)) { FAIL; } PASS; } static bool test_mf_v2r_replace_add() { emit_test("Test that MergeFromV2Raw() replaces some environment " "variables and also adds new ones for a valid V2Raw string."); Env env; MyString actual; env.MergeFromV2Raw(V2R, NULL); env.MergeFromV2Raw(V2R_REP_ADD, NULL); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("Env", "%s", V2R); emit_param("STRING", "%s", V2R_REP_ADD); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("Env", "%s", V2R_REP_ADD); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(!strings_similar(actual.Value(), V2R_REP_ADD)) { FAIL; } PASS; } static bool test_mf_v2r_replace_add_v1r() { emit_test("Test that MergeFromV2Raw() replaces some environment " "variables and also adds new ones for a valid V2Raw string on an Env " "object originally constructed from a V1Raw string."); Env env; MyString actual; env.MergeFromV1Raw(V1R, NULL); env.MergeFromV2Raw(V2R_REP_ADD_SEMI, NULL); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("Env", "%s", V1R); emit_param("STRING", "%s", V2R_REP_ADD_SEMI); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("Env", "%s", V2R_REP_ADD_SEMI); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(!strings_similar(actual.Value(), V2R_REP_ADD_SEMI)) { FAIL; } PASS; } static bool test_mf_v1r_ret_null() { emit_test("Test that MergeFromV1Raw() returns true when passed a NULL " "string."); Env env; bool expect = true; bool actual = env.MergeFromV1Raw(NULL, NULL); emit_input_header(); emit_param("STRING", "%s", "NULL"); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_mf_v1r_ret_valid() { emit_test("Test that MergeFromV1Raw() returns true when passed a valid " "V1Raw string."); Env env; bool expect = true; bool actual = env.MergeFromV1Raw(V1R, NULL); emit_input_header(); emit_param("STRING", "%s", V1R); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_mf_v1r_ret_invalid_name() { emit_test("Test that MergeFromV1Raw() returns false when passed an " "invalid V1Raw string due to a missing variable name."); Env env; bool expect = false; bool actual = env.MergeFromV1Raw(V1R_MISS_NAME, NULL); emit_input_header(); emit_param("STRING", "%s", V1R_MISS_NAME); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_mf_v1r_ret_invalid_delim() { emit_test("Test that MergeFromV1Raw() returns false when passed an " "invalid V1Raw string due to a missing delimiter."); Env env; bool expect = false; bool actual = env.MergeFromV1Raw(V1R_MISS_DELIM, NULL); emit_input_header(); emit_param("STRING", "%s", V1R_MISS_DELIM); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_mf_v1r_error_invalid_name() { emit_test("Test that MergeFromV1Raw() generates an error message for " "an invalid V1Raw string due to a missing variable name."); emit_comment("This test just checks if the error message is not empty."); Env env; MyString actual; env.MergeFromV1Raw(V1R_MISS_NAME, &actual); emit_input_header(); emit_param("STRING", "%s", V1R_MISS_NAME); emit_param("MyString", "%s", ""); emit_output_actual_header(); emit_param("Error Message", "%s", actual.Value()); if(actual.IsEmpty()) { FAIL; } PASS; } static bool test_mf_v1r_error_invalid_delim() { emit_test("Test that MergeFromV1Raw() generates an error message for " "an invalid V1Raw string due to a missing delimiter."); emit_comment("This test just checks if the error message is not empty."); Env env; MyString actual; env.MergeFromV1Raw(V1R_MISS_DELIM, &actual); emit_input_header(); emit_param("STRING", "%s", V1R_MISS_DELIM); emit_param("MyString", "%s", ""); emit_output_actual_header(); emit_param("Error Message", "%s", actual.Value()); if(actual.IsEmpty()) { FAIL; } PASS; } static bool test_mf_v1r_add_null() { emit_test("Test that MergeFromV1Raw() doesn't add the environment " "variable for a NULL string."); Env env; MyString actual; env.MergeFromV1Raw(NULL, NULL); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("STRING", "%s", "NULL"); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("Env", "%s", EMPTY); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(actual != EMPTY) { FAIL; } PASS; } static bool test_mf_v1r_add_invalid() { emit_test("Test that MergeFromV1Raw() doesn't add the environment " "variables for an invalid V1Raw string."); Env env; MyString actual; env.MergeFromV1Raw(V1R_MISS_BOTH, NULL); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("STRING", "%s", V1R_MISS_BOTH); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("Env", "%s", EMPTY); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(actual != EMPTY) { FAIL; } PASS; } static bool test_mf_v1r_add() { emit_test("Test that MergeFromV1Raw() adds the environment variables " "for a valid V1Raw string."); Env env; MyString actual; env.MergeFromV1Raw(V1R, NULL); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("STRING", "%s", V1R); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("Env", "%s", V2R); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(!strings_similar(actual.Value(), V2R)) { FAIL; } PASS; } static bool test_mf_v1r_replace() { emit_test("Test that MergeFromV1Raw() replaces the environment " "variables for a valid V1Raw string."); Env env; MyString actual; env.MergeFromV1Raw(V1R, NULL); env.MergeFromV1Raw(V1R_REP, NULL); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("Env", "%s", V1R); emit_param("STRING", "%s", V1R_REP); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("Env", "%s", V2R_REP); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(!strings_similar(actual.Value(), V2R_REP)) { FAIL; } PASS; } static bool test_mf_v1r_replace_v2r() { emit_test("Test that MergeFromV1Raw() replaces the environment " "variables for a valid V1Raw string on an Env object originally " "constructed from a V2Raw string."); Env env; MyString actual; env.MergeFromV2Raw(V2R_SEMI, NULL); env.MergeFromV1Raw(V1R_REP, NULL); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("Env", "%s", V2R_SEMI); emit_param("STRING", "%s", V1R_REP); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("Env", "%s", V2R_REP_SEMI); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(!strings_similar(actual.Value(), V2R_REP_SEMI)) { FAIL; } PASS; } static bool test_mf_v1r_replace_v2q() { emit_test("Test that MergeFromV1Raw() replaces the environment " "variables for a valid V1Raw string on an Env object originally " "constructed from a V2Quoted string."); Env env; MyString actual; env.MergeFromV2Quoted(V2Q_SEMI, NULL); env.MergeFromV1Raw(V1R_REP, NULL); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("Env", "%s", V2Q_SEMI); emit_param("STRING", "%s", V1R_REP); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("Env", "%s", V2R_REP_SEMI); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(!strings_similar(actual.Value(), V2R_REP_SEMI)) { FAIL; } PASS; } static bool test_mf_v1r_replace_add() { emit_test("Test that MergeFromV1Raw() replaces some environment " "variables and also adds new ones for a valid V1Raw string."); Env env; MyString actual; env.MergeFromV1Raw(V1R, NULL); env.MergeFromV1Raw(V1R_REP_ADD, NULL); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("Env", "%s", V1R); emit_param("STRING", "%s", V1R_REP_ADD); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("Env", "%s", V2R_REP_ADD); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(!strings_similar(actual.Value(), V2R_REP_ADD)) { FAIL; } PASS; } static bool test_mf_v1r_replace_add_v2r() { emit_test("Test that MergeFromV1Raw() replaces some environment " "variables and also adds new ones for a valid V1Raw string on an Env " "object originally constructed from a V2Raw string."); Env env; MyString actual; env.MergeFromV2Raw(V2R_SEMI, NULL); env.MergeFromV1Raw(V1R_REP_ADD, NULL); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("Env", "%s", V2R_SEMI); emit_param("STRING", "%s", V1R_REP_ADD); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("Env", "%s", V2R_REP_ADD_SEMI); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(!strings_similar(actual.Value(), V2R_REP_ADD_SEMI)) { FAIL; } PASS; } static bool test_mf_v1r_replace_add_v2q() { emit_test("Test that MergeFromV1Raw() replaces some environment " "variables and also adds new ones for a valid V1Raw string on an Env " "object originally constructed from a V2Quoted string."); Env env; MyString actual; env.MergeFromV2Quoted(V2Q_SEMI, NULL); env.MergeFromV1Raw(V1R_REP_ADD, NULL); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("Env", "%s", V2Q_SEMI); emit_param("STRING", "%s", V1R_REP_ADD); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("Env", "%s", V2R_REP_ADD_SEMI); emit_output_actual_header(); emit_param("Env after", "%s", actual.Value()); if(!strings_similar(actual.Value(), V2R_REP_ADD_SEMI)) { FAIL; } PASS; } static bool test_mf_v1or2_r_ret_null() { emit_test("Test that MergeFromV1or2Raw() returns true when passed " "a NULL string."); Env env; bool expect = true; bool actual = env.MergeFromV1or2Raw(NULL, NULL); emit_input_header(); emit_param("STRING", "%s", "NULL"); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_mf_v1or2_r_detect_v1r() { emit_test("Test that MergeFromV1or2Raw() correctly handles a V1Raw " "string by checking that InputWasV1() returns true."); emit_comment("MergeFromV1or2Raw() just calls MergeFromV1Raw(), which was " "tested above."); Env env; bool expect = true; env.MergeFromV1or2Raw(V1R, NULL); bool actual =env.InputWasV1(); emit_input_header(); emit_param("STRING", "%s", V1R); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("InputWasV1()", "%s", tfstr(expect)); emit_output_actual_header(); emit_param("InputWasV1()", "%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_mf_v1or2_r_detect_v2r() { emit_test("Test that MergeFromV1or2Raw() correctly handles a V1Raw " "string by checking that InputWasV1() returns true."); emit_comment("MergeFromV1or2Raw() just calls MergeFromV2Raw(), which was " "tested above."); Env env; bool expect = false; env.MergeFromV1or2Raw(V2R_MARK, NULL); bool actual =env.InputWasV1(); emit_input_header(); emit_param("STRING", "%s", V2R_MARK); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("InputWasV1()", "%s", tfstr(expect)); emit_output_actual_header(); emit_param("InputWasV1()", "%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_mf_v1or2_r_add_null() { emit_test("Test that MergeFromV1or2Raw() doesn't add any environment " "variables for a NULL string."); Env env; MyString actual; env.MergeFromV1or2Raw(NULL, NULL); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("STRING", "%s", "NULL"); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("Env", "%s", EMPTY); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(actual != EMPTY) { FAIL; } PASS; } static bool test_mf_v1or2_r_add_v2r() { emit_test("Test that MergeFromV1or2Raw() adds the environment variables " "for a valid V2Raw with the V2Raw environment marker."); emit_comment("We need to make sure MergeFromV2Raw() correctly handles the" " V2Raw environment marker."); Env env; MyString actual; env.MergeFromV1or2Raw(V2R_MARK, NULL); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("STRING", "%s", V2R_MARK); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("Env", "%s", V2R); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(!strings_similar(actual.Value(), V2R_SEMI)) { FAIL; } PASS; } static bool test_mf_str_array_ret_null() { emit_test("Test that MergeFrom() returns false when passed a NULL string " "array."); Env env; const char** str = NULL; bool expect = false; bool actual = env.MergeFrom(str); emit_input_header(); emit_param("STRING ARRAY", "%s", "NULL"); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_mf_str_array_ret_valid() { emit_test("Test that MergeFrom() returns true when passed a valid string " "array."); Env env; MyString temp; bool expect = true; bool actual = env.MergeFrom(ARRAY); env.getDelimitedStringForDisplay(&temp); emit_input_header(); emit_param("STRING ARRAY", "%s", V2R); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); emit_param("Env", "%s", temp.Value()); if(actual != expect) { FAIL; } PASS; } static bool test_mf_str_array_ret_invalid_name() { emit_test("Test that MergeFrom() returns false when passed a invalid " "string array due to a missing variable name."); Env env; bool expect = false; bool actual = env.MergeFrom(ARRAY_MISS_NAME); emit_input_header(); emit_param("STRING ARRAY", "%s", V2R_MISS_NAME); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_mf_str_array_ret_invalid_delim() { emit_test("Test that MergeFrom() returns false when passed a invalid " "string array due to a missing delimiter."); Env env; bool expect = false; bool actual = env.MergeFrom(ARRAY_MISS_DELIM); emit_input_header(); emit_param("STRING ARRAY", "%s", V2R_MISS_DELIM); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_mf_str_array_add_null() { emit_test("Test that MergeFrom() doesn't add the environment variables " "for a NULL string array."); Env env; MyString actual; const char** str = NULL; env.MergeFrom(str); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("Env", "%s", ""); emit_param("STRING ARRAY", "%s", "NULL"); emit_output_expected_header(); emit_param("Env", "%s", EMPTY); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(actual != EMPTY) { FAIL; } PASS; } static bool test_mf_str_array_add_invalid() { emit_test("Test that MergeFrom() skips invalid entries but adds valid " "entries for an invalid string array."); Env env; MyString actual; Env expected_env; MyString expected; env.MergeFrom(ARRAY_SKIP_BAD); env.getDelimitedStringForDisplay(&actual); expected_env.MergeFrom(ARRAY_SKIP_BAD_CLEAN); expected_env.getDelimitedStringForDisplay(&expected); emit_input_header(); emit_param("Env", "%s", ""); emit_param("STRING ARRAY", "%s", ARRAY_SKIP_BAD_STR); emit_output_expected_header(); emit_param("Env", "%s", expected.Value()); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(actual != expected) { FAIL; } PASS; } static bool test_mf_str_array_add() { emit_test("Test that MergeFrom() adds the environment variables for a " "valid string array."); Env env; MyString actual; env.MergeFrom(ARRAY); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("Env", "%s", ""); emit_param("STRING ARRAY", "%s", V2R); emit_output_expected_header(); emit_param("Env", "%s", V2R); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(!strings_similar(&actual, &ADD)) { FAIL; } PASS; } static bool test_mf_str_array_replace() { emit_test("Test that MergeFrom() replaces the environment variables for " "a valid string array."); Env env; MyString actual; env.MergeFrom(ARRAY); env.MergeFrom(ARRAY_REP); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("Env", "%s", V2R); emit_param("STRING ARRAY", "%s", V2R_REP); emit_output_expected_header(); emit_param("Env", "%s", V2R_REP); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(!strings_similar(&actual, &REP)) { FAIL; } PASS; } static bool test_mf_str_array_replace_add() { emit_test("Test that MergeFrom() replaces the values of some of the " "environment variables and also adds new ones for a valid string " "array."); Env env; MyString actual; env.MergeFrom(ARRAY); env.MergeFrom(ARRAY_REP_ADD); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("Env", "%s", V2R); emit_param("STRING ARRAY", "%s", V2R_REP_ADD); emit_output_expected_header(); emit_param("Env", "%s", V2R_REP_ADD); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(!strings_similar(&actual, &REP_ADD)) { FAIL; } PASS; } static bool test_mf_str_ret_null() { emit_test("Test that MergeFrom() returns false when passed a NULL " "string."); Env env; const char* str = NULL; bool expect = false; bool actual = env.MergeFrom(str); emit_input_header(); emit_param("STRING", "%s", "NULL"); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_mf_str_ret_valid() { emit_test("Test that MergeFrom() returns true when passed a valid NULL-" "delimited string."); Env env; bool expect = true; bool actual = env.MergeFrom(NULL_DELIM); emit_input_header(); emit_param("STRING", "%s", V2R); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_mf_str_ret_invalid_name() { emit_test("Test that MergeFrom() returns true when passed an invalid " "NULL-delimited string due to a missing variable name."); emit_comment("MergeFrom() will ignore errors from SetEnv() and insert " "what it can."); Env env; bool expect = true; bool actual = env.MergeFrom(NULL_DELIM_MISS_NAME); emit_input_header(); emit_param("STRING", "%s", V2R_MISS_NAME); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_mf_str_ret_invalid_delim() { emit_test("Test that MergeFrom() true when passed an invalid " "NULL-delimited string due to a missing delimiter."); emit_comment("MergeFrom() will ignore errors from SetEnv() and insert " "what it can."); Env env; bool expect = true; bool actual = env.MergeFrom(NULL_DELIM_MISS_DELIM); emit_input_header(); emit_param("STRING", "%s", V2R_MISS_DELIM); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_mf_str_add_null() { emit_test("Test that MergeFrom() doesn't add any environment variables " "for a NULL string."); Env env; MyString actual; const char* str = NULL; env.MergeFrom(str); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("STRING", "%s", "NULL"); emit_output_expected_header(); emit_param("Env", "%s", EMPTY); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(actual != EMPTY) { FAIL; } PASS; } static bool test_mf_str_add_invalid_name() { emit_test("Test that MergeFrom() doesn't add the environment variable " "with a missing variable name, but still adds the valid variables."); emit_comment("MergeFrom() will ignore errors from SetEnv() and insert " "what it can."); Env env; MyString actual; env.MergeFrom(NULL_DELIM_MISS_NAME); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("STRING", "%s", V2R_MISS_NAME); emit_output_expected_header(); emit_param("Env", "%s", "two=2 three=3"); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(!strings_similar(actual.Value(), "two=2 three=3")) { FAIL; } PASS; } static bool test_mf_str_add_invalid_delim() { emit_test("Test that MergeFrom() doesn't add the environment variable " "with a missing delimiter, but still adds the valid variables."); emit_comment("MergeFrom() will ignore errors from SetEnv() and insert " "what it can."); Env env; MyString actual; env.MergeFrom(NULL_DELIM_MISS_DELIM); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("STRING", "%s", V2R_MISS_DELIM); emit_output_expected_header(); emit_param("Env", "%s", "two=2 three=3"); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(!strings_similar(actual.Value(), "two=2 three=3")) { FAIL; } PASS; } static bool test_mf_str_add() { emit_test("Test that MergeFrom() adds the environment variables for a " "valid NULL-delimited string."); Env env; MyString actual; env.MergeFrom(NULL_DELIM); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("STRING", "%s", V2R); emit_output_expected_header(); emit_param("Env", "%s", V2R); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(!strings_similar(actual.Value(), V2R)) { FAIL; } PASS; } static bool test_mf_str_replace() { emit_test("Test that MergeFrom() replaces the environment variables for a" " valid NULL-delimited string."); Env env; MyString actual; env.MergeFrom(NULL_DELIM); env.MergeFrom(NULL_DELIM_REP); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("STRING", "%s", V2R); emit_param("STRING", "%s", V2R_REP); emit_output_expected_header(); emit_param("Env", "%s", V2R_REP); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(!strings_similar(actual.Value(), V2R_REP)) { FAIL; } PASS; } static bool test_mf_str_replace_add() { emit_test("Test that MergeFrom() replaces and adds environment variables " "for a valid NULL-delimited string."); Env env; MyString actual; env.MergeFrom(NULL_DELIM); env.MergeFrom(NULL_DELIM_REP_ADD); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("STRING", "%s", V2R); emit_param("STRING", "%s", V2R_REP_ADD); emit_output_expected_header(); emit_param("Env", "%s", V2R_REP); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(!strings_similar(actual.Value(), V2R_REP_ADD)) { FAIL; } PASS; } static bool test_mf_env_add_empty() { emit_test("Test that MergeFrom() doesn't add the environment variables " "when passed an empty Env."); Env env1, env2; MyString actual; env1.MergeFrom(env2); env1.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("Env", "%s", ""); emit_param("Env Parameter", "%s", ""); emit_output_expected_header(); emit_param("Env", "%s", EMPTY); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(actual != EMPTY) { FAIL; } PASS; } static bool test_mf_env_add_one() { emit_test("Test that MergeFrom() adds the environment variables when " "passed an Env with one variable."); Env env1, env2; MyString actual; env2.MergeFromV2Raw(ONE, NULL); env1.MergeFrom(env2); env1.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("Env", "%s", ""); emit_param("Env Parameter", "%s", ONE); emit_output_expected_header(); emit_param("Env", "%s", ONE); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(actual != ONE) { FAIL; } PASS; } static bool test_mf_env_add_many() { emit_test("Test that MergeFrom() adds the environment variables when " "passed an Env with many variables."); Env env1, env2; MyString actual; env2.MergeFromV2Raw(V2R, NULL); env1.MergeFrom(env2); env1.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("Env", "%s", ""); emit_param("Env Parameter", "%s", V2R); emit_output_expected_header(); emit_param("Env", "%s", V2R); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(!strings_similar(actual.Value(), V2R)) { FAIL; } PASS; } static bool test_mf_env_replace() { emit_test("Test that MergeFrom() replaces the environment variables when " "passed an Env with many variables."); Env env1, env2; MyString actual; env1.MergeFromV2Raw(V2R, NULL); env2.MergeFromV2Raw(V2R_REP, NULL); env1.MergeFrom(env2); env1.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("Env", "%s", V2R); emit_param("Env Parameter", "%s", V2R_REP); emit_output_expected_header(); emit_param("Env", "%s", V2R_REP); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(!strings_similar(actual.Value(), V2R_REP)) { FAIL; } PASS; } static bool test_mf_env_replace_v1_v2() { emit_test("Test that MergeFrom() replaces the environment variables on an" " Env object originally constructed from a V1Raw string when passed an " "Env constructed from a V2Raw string."); Env env1, env2; MyString actual; env1.MergeFromV1Raw(V1R, NULL); env2.MergeFromV2Raw(V2R_REP_SEMI, NULL); env1.MergeFrom(env2); env1.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("Env", "%s", V1R); emit_param("Env Parameter", "%s", V2R_REP_SEMI); emit_output_expected_header(); emit_param("Env", "%s", V2R_REP_SEMI); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(!strings_similar(actual.Value(), V2R_REP_SEMI)) { FAIL; } PASS; } static bool test_mf_env_replace_v2_v1() { emit_test("Test that MergeFrom() replaces the environment variables on an" " Env object originally constructed from a V2Raw string when passed an " "Env constructed from a V1Raw string."); Env env1, env2; MyString actual; env1.MergeFromV2Raw(V2R_SEMI, NULL); env2.MergeFromV1Raw(V1R_REP, NULL); env1.MergeFrom(env2); env1.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("Env", "%s", V2R_SEMI); emit_param("Env Parameter", "%s", V1R_REP); emit_output_expected_header(); emit_param("Env", "%s", V1R_REP); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(!strings_similar(actual.Value(), V2R_REP_SEMI)) { FAIL; } PASS; } static bool test_mf_env_replace_add() { emit_test("Test that MergeFrom() replaces some of the environment " "variables and adds new ones when passed an Env with many variables."); Env env1, env2; MyString actual; MyString rep; env1.MergeFromV2Raw(V2R, NULL); env2.MergeFromV2Raw(V2R_REP_ADD, NULL); env1.MergeFrom(env2); env1.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("Env", "%s", V2R); emit_param("Env Parameter", "%s", V2R_REP_ADD); emit_output_expected_header(); emit_param("Env", "%s", V2R_REP); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(!strings_similar(actual.Value(), V2R_REP_ADD)) { FAIL; } PASS; } static bool test_mf_env_replace_add_v1_v2() { emit_test("Test that MergeFrom() replaces some of the environment " "variables and adds new ones on an Env object originally constructed " "from a V1Raw string when passed an Env constructed from a V2Raw " "string."); Env env1, env2; MyString actual; env1.MergeFromV1Raw(V1R, NULL); env2.MergeFromV2Raw(V2R_REP_ADD_SEMI, NULL); env1.MergeFrom(env2); env1.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("Env", "%s", V1R); emit_param("Env Parameter", "%s", V2R_REP_ADD_SEMI); emit_output_expected_header(); emit_param("Env", "%s", V2R_REP_ADD_SEMI); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(!strings_similar(actual.Value(), V2R_REP_ADD_SEMI)) { FAIL; } PASS; } static bool test_mf_env_replace_add_v2_v1() { emit_test("Test that MergeFrom() replaces some of the environment " "variables and adds new ones on an Env object originally constructed " "from a V2Raw string when passed an Env constructed from a V1Raw " "string."); Env env1, env2; MyString actual; env1.MergeFromV2Raw(V2R_SEMI, NULL); env2.MergeFromV1Raw(V1R_REP_ADD, NULL); env1.MergeFrom(env2); env1.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("Env", "%s", V2R_SEMI); emit_param("Env Parameter", "%s", V1R_REP_ADD); emit_output_expected_header(); emit_param("Env", "%s", V2R_REP_ADD_SEMI); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(!strings_similar(actual.Value(), V2R_REP_ADD_SEMI)) { FAIL; } PASS; } static bool test_mf_env_itself() { emit_test("Test that MergeFrom() doesn't add the environment variables " "when passed itself."); Env env; MyString actual; env.MergeFromV2Raw(V2R, NULL); env.MergeFrom(env); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("Env", "%s", V2R); emit_param("Env Parameter", "%s", V2R); emit_output_expected_header(); emit_param("Env", "%s", V2R); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(!strings_similar(actual.Value(), V2R)) { FAIL; } PASS; } static bool test_mf_ad_ret_null() { emit_test("Test that MergeFrom() returns true when passed a NULL " "ClassAd."); Env env; bool expect = true; bool actual = env.MergeFrom(NULL, NULL); emit_input_header(); emit_param("ClassAd", "%s", "NULL"); emit_param("MyString", "%s", "NULL"); emit_param("CONSTANT", "%s", ATTR_JOB_ENVIRONMENT2); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_mf_ad_ret_v1r_valid() { emit_test("Test that MergeFrom() returns true when passed a valid " "ClassAd that uses V1Raw."); Env env; ClassAd classad; initAdFromString(AD_V1, classad); bool expect = true; bool actual = env.MergeFrom(&classad, NULL); emit_input_header(); emit_param("ClassAd", "%s", AD_V1); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_mf_ad_ret_v2r_valid() { emit_test("Test that MergeFrom() returns true when passed a valid " "ClassAd that uses V2Raw."); Env env; ClassAd classad; initAdFromString(AD_V2, classad); bool expect = true; bool actual = env.MergeFrom(&classad, NULL); emit_input_header(); emit_param("ClassAd", "%s", AD_V2); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_mf_ad_ret_valid_define() { emit_test("Test that MergeFrom() returns true when passed a valid " "ClassAd that doesn't define an Environment"); Env env; ClassAd classad; initAdFromString(AD, classad); bool expect = true; bool actual = env.MergeFrom(&classad, NULL); emit_input_header(); emit_param("ClassAd", "%s", AD); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_mf_ad_ret_v1r_invalid_name() { emit_test("Test that MergeFrom() returns false when passed an invalid " "ClassAd that uses V1Raw due to a missing variable name."); Env env; ClassAd classad; initAdFromString(AD_V1_MISS_NAME, classad); bool expect = false; bool actual = env.MergeFrom(&classad, NULL); emit_input_header(); emit_param("ClassAd", "%s", AD_V1_MISS_NAME); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_mf_ad_ret_v1r_invalid_delim() { emit_test("Test that MergeFrom() returns false when passed an invalid " "ClassAd that uses V1Raw due to a missing delimiter."); Env env; ClassAd classad; initAdFromString(AD_V1_MISS_DELIM, classad); bool expect = false; bool actual = env.MergeFrom(&classad, NULL); emit_input_header(); emit_param("ClassAd", "%s", AD_V1_MISS_DELIM); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_mf_ad_ret_v2r_invalid_name() { emit_test("Test that MergeFrom() returns false when passed a invalid " "ClassAd that uses V2Raw due to a missing variable name."); Env env; ClassAd classad; initAdFromString(AD_V2_MISS_NAME, classad); bool expect = false; bool actual = env.MergeFrom(&classad, NULL); emit_input_header(); emit_param("ClassAd", "%s", AD_V2_MISS_NAME); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_mf_ad_ret_v2r_invalid_delim() { emit_test("Test that MergeFrom() returns false when passed a invalid " "ClassAd that uses V2Raw due to a missing delimiter."); Env env; ClassAd classad; initAdFromString(AD_V2_MISS_DELIM, classad); bool expect = false; bool actual = env.MergeFrom(&classad, NULL); emit_input_header(); emit_param("ClassAd", "%s", AD_V2_MISS_DELIM); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_mf_ad_error_v1r_invalid_name() { emit_test("Test that MergeFrom() generates an error message for an " "invalid ClassAd that uses V1Raw due to a missing variable name."); emit_comment("This test just checks if the error message is not empty."); Env env; MyString actual; ClassAd classad; initAdFromString(AD_V1_MISS_NAME, classad); env.MergeFrom(&classad, &actual); emit_input_header(); emit_param("ClassAd", "%s", AD_V1_MISS_NAME); emit_param("MyString", "%s", ""); emit_output_actual_header(); emit_param("Error Message", "%s", actual.Value()); if(actual.IsEmpty()) { FAIL; } PASS; } static bool test_mf_ad_error_v1r_invalid_delim() { emit_test("Test that MergeFrom() generates an error message for an " "invalid ClassAd that uses V1Raw due to a missing delimiter."); emit_comment("This test just checks if the error message is not empty."); Env env; MyString actual; ClassAd classad; initAdFromString(AD_V1_MISS_DELIM, classad); env.MergeFrom(&classad, &actual); emit_input_header(); emit_param("ClassAd", "%s", AD_V1_MISS_DELIM); emit_param("MyString", "%s", ""); emit_output_actual_header(); emit_param("Error Message", "%s", actual.Value()); if(actual.IsEmpty()) { FAIL; } PASS; } static bool test_mf_ad_error_v2r_invalid_name() { emit_test("Test that MergeFrom() generates an error message for an " "invalid ClassAd that uses V2Raw due to a missing variable name."); emit_comment("This test just checks if the error message is not empty."); Env env; MyString actual; ClassAd classad; initAdFromString(AD_V2_MISS_NAME, classad); env.MergeFrom(&classad, &actual); emit_input_header(); emit_param("ClassAd", "%s", AD_V2_MISS_NAME); emit_param("MyString", "%s", ""); emit_output_actual_header(); emit_param("Error Message", "%s", actual.Value()); if(actual.IsEmpty()) { FAIL; } PASS; } static bool test_mf_ad_error_v2r_invalid_delim() { emit_test("Test that MergeFrom() generates an error message for an " "invalid ClassAd that uses V2Raw due to a missing delimiter."); emit_comment("This test just checks if the error message is not empty."); Env env; MyString actual; ClassAd classad; initAdFromString(AD_V2_MISS_NAME, classad); env.MergeFrom(&classad, &actual); emit_input_header(); emit_param("ClassAd", "%s", AD_V2_MISS_NAME); emit_param("MyString", "%s", ""); emit_output_actual_header(); emit_param("Error Message", "%s", actual.Value()); if(actual.IsEmpty()) { FAIL; } PASS; } static bool test_mf_ad_add_null() { emit_test("Test that MergeFrom() doesn't add the environment variables " "when passed a NULL ClassAd pointer."); Env env; MyString actual; env.MergeFrom(NULL, NULL); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("ClassAd", "%s", "NULL"); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("Env", "%s", EMPTY); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(actual != EMPTY) { FAIL; } PASS; } static bool test_mf_ad_add_define() { emit_test("Test that MergeFrom() doesn't any environment variables " "when passed a ClassAd that doesn't define an environment variable."); Env env; ClassAd classad; initAdFromString(AD, classad); MyString actual; env.MergeFrom(&classad, NULL); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("ClassAd", "%s", AD); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("Env", "%s", EMPTY); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(actual != EMPTY) { FAIL; } PASS; } static bool test_mf_ad_add_v1r_one() { emit_test("Test that MergeFrom() adds the environment variables when " "passed a valid ClassAd that uses V1Raw with one variable."); Env env; const char* classad_string = "\tEnv = \"one=1\""; ClassAd classad; initAdFromString(classad_string, classad); MyString actual; env.MergeFrom(&classad, NULL); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("ClassAd", "%s", classad_string); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("Env", "%s", ONE); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(actual != ONE) { FAIL; } PASS; } static bool test_mf_ad_add_v1r_many() { emit_test("Test that MergeFrom() adds the environment variables when " "passed a valid ClassAd that uses V1Raw with many variables."); Env env; ClassAd classad; initAdFromString(AD_V1, classad); MyString actual; env.MergeFrom(&classad, NULL); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("ClassAd", "%s", AD_V1); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("Env", "%s", V2R); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(!strings_similar(actual.Value(), V2R)) { FAIL; } PASS; } static bool test_mf_ad_add_v2r_one() { emit_test("Test that MergeFrom() adds the environment variables when " "passed a valid ClassAd that uses V2Raw with one variable."); Env env; const char* classad_string = "\tEnvironment = \"one=1\""; ClassAd classad; initAdFromString(classad_string, classad); MyString actual; env.MergeFrom(&classad, NULL); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("ClassAd", "%s", classad_string); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("Env", "%s", ONE); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(actual != ONE) { FAIL; } PASS; } static bool test_mf_ad_add_v2r_many() { emit_test("Test that MergeFrom() adds the environment variables when " "passed a valid ClassAd that uses V2Raw with many variables."); Env env; ClassAd classad; initAdFromString(AD_V2, classad); MyString actual; env.MergeFrom(&classad, NULL); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("ClassAd", "%s", AD_V2); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("Env", "%s", V2R); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(!strings_similar(actual.Value(), V2R)) { FAIL; } PASS; } static bool test_mf_ad_v1r_replace() { emit_test("Test that MergeFrom() replaces the environment variables when " "passed a valid ClassAd that uses V1Raw with many variables."); Env env; ClassAd classad; initAdFromString(AD_V1_REP, classad); MyString actual; env.MergeFromV2Raw(V2R, NULL); env.MergeFrom(&classad, NULL); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("Env", "%s", V2R); emit_param("ClassAd", "%s", AD_V1_REP); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("Env", "%s", V2R_REP); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(!strings_similar(actual.Value(), V2R_REP)) { FAIL; } PASS; } static bool test_mf_ad_v2r_replace() { emit_test("Test that MergeFrom() replaces the environment variables when " "passed a valid ClassAd that uses V2Raw with many variables."); Env env; ClassAd classad; initAdFromString(AD_V2_REP, classad); MyString actual; env.MergeFromV2Raw(V2R, NULL); env.MergeFrom(&classad, NULL); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("Env", "%s", V2R); emit_param("ClassAd", "%s", AD_V2_REP); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("Env", "%s", V2R_REP); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(!strings_similar(actual.Value(), V2R_REP)) { FAIL; } PASS; } static bool test_mf_ad_v1r_replace_add() { emit_test("Test that MergeFrom() replaces some of the environment " "variables and adds new ones when passed a valid ClassAd that uses" " V1Raw with many variables."); Env env; ClassAd classad; initAdFromString(AD_V1_REP_ADD, classad); MyString actual; env.MergeFromV2Raw(V2R, NULL); env.MergeFrom(&classad, NULL); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("Env", "%s", V2R); emit_param("ClassAd", "%s", AD_V1_REP_ADD); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("Env", "%s", V2R_REP_ADD); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(!strings_similar(actual.Value(), V2R_REP_ADD)) { FAIL; } PASS; } static bool test_mf_ad_v2r_replace_add() { emit_test("Test that MergeFrom() replaces some of the environment " "variables when and adds new ones when passed a valid ClassAd that uses" " V2Raw with many variables."); Env env; ClassAd classad; initAdFromString(AD_V2_REP_ADD, classad); MyString actual; env.MergeFromV2Raw(V2R, NULL); env.MergeFrom(&classad, NULL); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("Env", "%s", V2R); emit_param("ClassAd", "%s", AD_V2_REP_ADD); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("Env", "%s", V2R_REP_ADD); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(!strings_similar(actual.Value(), V2R_REP_ADD)) { FAIL; } PASS; } static bool test_set_env_with_error_message_ret_null() { emit_test("Test that SetEnvWithErrorMessage() returns false when passed a" " NULL string."); Env env; bool expect = false; bool actual = env.SetEnvWithErrorMessage(NULL, NULL); emit_input_header(); emit_param("STRING", "%s", "NULL"); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_set_env_with_error_message_ret_valid() { emit_test("Test that SetEnvWithErrorMessage() returns true when passed a" " valid string."); Env env; bool expect = true; bool actual = env.SetEnvWithErrorMessage(ONE, NULL); emit_input_header(); emit_param("STRING", "%s", ONE); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_set_env_with_error_message_ret_invalid_name() { emit_test("Test that SetEnvWithErrorMessage() returns false when passed " "an invalid string due to a missing variable name."); Env env; bool expect = false; bool actual = env.SetEnvWithErrorMessage(ONE_MISS_NAME, NULL); emit_input_header(); emit_param("STRING", "%s", ONE_MISS_NAME); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_set_env_with_error_message_ret_invalid_delim() { emit_test("Test that SetEnvWithErrorMessage() returns false when passed " "an invalid string due to a missing delimiter."); Env env; bool expect = false; bool actual = env.SetEnvWithErrorMessage(ONE_MISS_DELIM, NULL); emit_input_header(); emit_param("STRING", "%s", ONE_MISS_DELIM); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_set_env_with_error_message_err_invalid_name() { emit_test("Test that SetEnvWithErrorMessage() generates an error message " "for an invalid string due to a missing variable name."); emit_comment("This test just checks if the error message is not empty."); Env env; MyString actual; bool retval; retval = env.SetEnvWithErrorMessage(ONE_MISS_NAME, &actual); emit_input_header(); emit_param("STRING", "%s", ONE_MISS_NAME); emit_param("MyString", "%s", ""); emit_output_actual_header(); emit_param("Error Message", "%s", actual.Value()); emit_param("Return Value", "%s", retval ? "true" : "false"); if(actual.IsEmpty() || retval) { FAIL; } PASS; } static bool test_set_env_with_error_message_err_invalid_delim() { emit_test("Test that SetEnvWithErrorMessage() generates an error message " "for an invalid string due to a missing delimiter."); emit_comment("This test just checks if the error message is not empty."); Env env; MyString actual; bool retval; retval = env.SetEnvWithErrorMessage(ONE_MISS_DELIM, &actual); emit_input_header(); emit_param("STRING", "%s", ONE_MISS_DELIM); emit_param("MyString", "%s", ""); emit_output_actual_header(); emit_param("Error Message", "%s", actual.Value()); emit_param("Return Value", "%s", retval ? "true" : "false"); if(actual.IsEmpty() || retval) { FAIL; } PASS; } static bool test_set_env_with_error_message_add_null() { emit_test("Test that SetEnvWithErrorMessage() doesn't add the environment" " variable when passed a NULL string."); Env env; MyString actual; env.SetEnvWithErrorMessage(NULL, NULL); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("Env", "%s", ""); emit_param("STRING", "%s", "NULL"); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("Env", "%s", EMPTY); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(actual != EMPTY) { FAIL; } PASS; } static bool test_set_env_with_error_message_add_invalid_delim() { emit_test("Test that SetEnvWithErrorMessage() doesn't adds any " "environment variables when passed a invalid string due to a missing " "delimiter."); Env env; MyString actual; env.SetEnvWithErrorMessage(ONE_MISS_DELIM, NULL); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("Env", "%s", ""); emit_param("STRING", "%s", ONE_MISS_DELIM); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("Env", "%s", EMPTY); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(actual != EMPTY) { FAIL; } PASS; } static bool test_set_env_with_error_message_add_invalid_var() { emit_test("Test that SetEnvWithErrorMessage() doesn't adds any " "environment variables when passed an invalid string due to a missing " "variable name."); Env env; MyString actual, expect; env.SetEnvWithErrorMessage(ONE_MISS_NAME, NULL); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("Env", "%s", ""); emit_param("STRING", "%s", ONE_MISS_NAME); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("Env", "%s", EMPTY); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(actual != expect) { FAIL; } PASS; } static bool test_set_env_with_error_message_add() { emit_test("Test that SetEnvWithErrorMessage() adds the environment " "variable when passed a valid string."); Env env; MyString actual; env.SetEnvWithErrorMessage(ONE, NULL); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("Env", "%s", ""); emit_param("STRING", "%s", ONE); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("Env", "%s", ONE); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(actual != ONE) { FAIL; } PASS; } static bool test_set_env_with_error_message_replace() { emit_test("Test that SetEnvWithErrorMessage() replaces the environment " "variable when passed a valid string."); Env env; MyString actual; env.SetEnvWithErrorMessage(ONE, NULL); env.SetEnvWithErrorMessage(ONE_REP, NULL); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("Env", "%s", ONE); emit_param("STRING", "%s", ONE_REP); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("Env", "%s", ONE_REP); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(actual != ONE_REP) { FAIL; } PASS; } static bool test_set_env_str_ret_null() { emit_test("Test that SetEnv() returns false when passed a NULL string."); Env env; bool expect = false; bool actual = env.SetEnv(NULL); emit_input_header(); emit_param("STRING", "%s", "NULL"); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_set_env_str_ret_valid() { emit_test("Test that SetEnv() returns true when passed a valid string."); Env env; bool expect = true; bool actual = env.SetEnv(ONE); emit_input_header(); emit_param("STRING", "%s", ONE); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_set_env_str_ret_invalid_name() { emit_test("Test that SetEnv() returns false when passed an invalid string" " due to a missing variable name."); Env env; bool expect = false; bool actual = env.SetEnv(ONE_MISS_NAME); emit_input_header(); emit_param("STRING", "%s", ONE_MISS_NAME); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_set_env_str_ret_invalid_delim() { emit_test("Test that SetEnv() returns false when passed an invalid string" " due to a missing delimiter."); Env env; bool expect = false; bool actual = env.SetEnv(ONE_MISS_DELIM); emit_input_header(); emit_param("STRING", "%s", ONE_MISS_DELIM); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_set_env_str_add_null() { emit_test("Test that SetEnv() doesn't add any environment variables when " "passed a NULL string."); Env env; MyString actual, expect; env.SetEnv(NULL); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("Env", "%s", ""); emit_param("STRING", "%s", "NULL"); emit_output_expected_header(); emit_param("Env", "%s", EMPTY); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(actual != expect) { FAIL; } PASS; } static bool test_set_env_str_add_invalid() { emit_test("Test that SetEnv() doesn't add the environment variables when " "passed invalid strings."); Env env; MyString actual; env.SetEnv(ONE_MISS_NAME); env.SetEnv(ONE_MISS_DELIM); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("Env", "%s", ""); emit_param("String 1", "%s", ONE_MISS_NAME); emit_param("String 2", "%s", ONE_MISS_DELIM); emit_output_expected_header(); emit_param("Env", "%s", EMPTY); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(actual != EMPTY) { FAIL; } PASS; } static bool test_set_env_str_add() { emit_test("Test that SetEnv() adds the environment variables when passed " "a valid string."); Env env; MyString actual; env.SetEnv(ONE); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("Env", "%s", ""); emit_param("STRING", "%s", ONE); emit_output_expected_header(); emit_param("Env", "%s", ONE); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(actual != ONE) { FAIL; } PASS; } static bool test_set_env_str_replace() { emit_test("Test that SetEnv() replaces the environment variables when " "passed a valid string."); Env env; MyString actual; env.SetEnv(ONE); env.SetEnv(ONE_REP); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("Env", "%s", ONE); emit_param("STRING", "%s", ONE_REP); emit_output_expected_header(); emit_param("Env", "%s", ONE_REP); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(actual != ONE_REP) { FAIL; } PASS; } static bool test_set_env_str_str_ret_null_var() { emit_test("Test that SetEnv() returns false when passed a NULL string for" " the variable name."); Env env; bool expect = false; bool actual = env.SetEnv(NULL, "1"); emit_input_header(); emit_param("STRING", "%s", "NULL"); emit_param("STRING", "%s", "1"); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_set_env_str_str_ret_null_val() { emit_test("Test that SetEnv() returns true when passed a NULL string for" " the variable value."); Env env; bool expect = true; bool actual = env.SetEnv("one", NULL); emit_input_header(); emit_param("STRING", "%s", "one"); emit_param("STRING", "%s", "NULL"); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_set_env_str_str_ret_valid() { emit_test("Test that SetEnv() returns true when passed a valid string for" " both the variable name and value."); Env env; bool expect = true; bool actual = env.SetEnv("one", "1"); emit_input_header(); emit_param("STRING", "%s", "one"); emit_param("STRING", "%s", "1"); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_set_env_str_str_add_null_var() { emit_test("Test that SetEnv() doesn't add any environment variables when " "passed a NULL string for the variable name."); Env env; MyString actual; env.SetEnv(NULL, "1"); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("Env", "%s", ""); emit_param("STRING", "%s", "NULL"); emit_param("STRING", "%s", "1"); emit_output_expected_header(); emit_param("Env", "%s", EMPTY); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(actual != EMPTY) { FAIL; } PASS; } static bool test_set_env_str_str_add_null_val() { emit_test("Test that SetEnv() adds the environment variables when passed " "a NULL string for the variable value."); Env env; MyString actual; env.SetEnv("one", NULL); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("Env", "%s", ""); emit_param("STRING", "%s", "one"); emit_param("STRING", "%s", "NULL"); emit_output_expected_header(); emit_param("Env", "%s", ONE_MISS_VAL); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(actual != ONE_MISS_VAL) { FAIL; } PASS; } static bool test_set_env_str_str_add() { emit_test("Test that SetEnv() adds the environment variables when passed " "a valid string for both the variable name and value."); Env env; MyString actual; env.SetEnv("one", "1"); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("Env", "%s", ""); emit_param("STRING", "%s", "one"); emit_param("STRING", "%s", "1"); emit_output_expected_header(); emit_param("Env", "%s", ONE); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(actual != ONE) { FAIL; } PASS; } static bool test_set_env_str_str_replace() { emit_test("Test that SetEnv() replaces the environment variables when " "passed a valid string for both the variable name and value."); Env env; MyString actual; env.SetEnv("one", "1"); env.SetEnv("one", "10"); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("Env", "%s", ONE); emit_param("STRING", "%s", "one"); emit_param("STRING", "%s", "10"); emit_output_expected_header(); emit_param("Env", "%s", ONE_REP); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(actual != ONE_REP) { FAIL; } PASS; } static bool test_set_env_mystr_ret_empty_var() { emit_test("Test that SetEnv() returns false when passed an empty MyString" " for the variable name."); Env env; MyString str2("1"); bool expect = false; bool actual = env.SetEnv(EMPTY, str2); emit_input_header(); emit_param("STRING", "%s", EMPTY); emit_param("STRING", "%s", str2.Value()); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_set_env_mystr_ret_empty_val() { emit_test("Test that SetEnv() returns false when passed an empty MyString" " for the variable value."); Env env; MyString str1("one"); bool expect = true; bool actual = env.SetEnv(str1, EMPTY); emit_input_header(); emit_param("MyString", "%s", str1.Value()); emit_param("MyString", "%s", EMPTY); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_set_env_mystr_ret_valid() { emit_test("Test that SetEnv() returns true when passed a valid MyString" " for both the variable name and value."); Env env; MyString str1("one"), str2("1"); bool expect = true; bool actual = env.SetEnv(str1, str2); emit_input_header(); emit_param("MyString", "%s", str1.Value()); emit_param("MyString", "%s", str2.Value()); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_set_env_mystr_add_empty_var() { emit_test("Test that SetEnv() doesn't add any environment variables when " "passed an empty MyString for the variable name."); Env env; MyString str2("1"), actual; env.SetEnv(EMPTY, str2); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("Env", "%s", ""); emit_param("MyString", "%s", EMPTY); emit_param("MyString", "%s", str2.Value()); emit_output_expected_header(); emit_param("Env", "%s", EMPTY); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(actual != EMPTY) { FAIL; } PASS; } static bool test_set_env_mystr_add_empty_val() { emit_test("Test that SetEnv() adds the environment variables when passed " "an empty MyString for the variable name."); Env env; MyString str1("one"), actual; env.SetEnv(str1, EMPTY); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("Env", "%s", ""); emit_param("MyString", "%s", str1.Value()); emit_param("MyString", "%s", EMPTY); emit_output_expected_header(); emit_param("Env", "%s", ONE_MISS_VAL); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(actual != ONE_MISS_VAL) { FAIL; } PASS; } static bool test_set_env_mystr_add() { emit_test("Test that SetEnv() adds the environment variables when passed " "a valid MyString for both the variable name and value."); Env env; MyString str1("one"), str2("1"), actual; env.SetEnv(str1, str2); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("Env", "%s", ""); emit_param("MyString", "%s", str1.Value()); emit_param("MyString", "%s", str2.Value()); emit_output_expected_header(); emit_param("Env", "%s", ONE); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(actual != ONE) { FAIL; } PASS; } static bool test_set_env_mystr_replace() { emit_test("Test that SetEnv() replaces the environment variables when " "passed a valid MyString for both the variable name and value."); Env env; MyString str1("one"), str2("10"), actual; env.SetEnv("one", "1"); env.SetEnv(str1, str2); env.getDelimitedStringForDisplay(&actual); emit_input_header(); emit_param("Env", "%s", ONE); emit_param("MyString", "%s", str1.Value()); emit_param("MyString", "%s", str2.Value()); emit_output_expected_header(); emit_param("Env", "%s", ONE_REP); emit_output_actual_header(); emit_param("Env", "%s", actual.Value()); if(actual != ONE_REP) { FAIL; } PASS; } static bool test_insert_env_into_classad_v1_empty() { emit_test("Test that InsertEnvIntoClassAd() inserts the environment " "variables from an Env object in V1 format into the empty classad."); Env env; env.MergeFromV1Raw(V1R, NULL); ClassAd classad; env.InsertEnvIntoClassAd(&classad, NULL); char* actual; classad.LookupString("Environment", &actual); emit_input_header(); emit_param("Env", "%s", V1R); emit_param("ClassAd", "%s", ""); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("ClassAd Environment", "%s", V2R); emit_output_actual_header(); emit_param("ClassAd Environment", "%s", actual); if(!strings_similar(actual, V2R)) { free(actual); FAIL; } free(actual); PASS; } static bool test_insert_env_into_classad_v2_empty() { emit_test("Test that InsertEnvIntoClassAd() inserts the environment " "variables from an Env object in V2 format into the empty classad."); Env env; env.MergeFromV2Raw(V2R, NULL); ClassAd classad; env.InsertEnvIntoClassAd(&classad, NULL); char* actual; classad.LookupString("Environment", &actual); emit_input_header(); emit_param("Env", "%s", V2R); emit_param("ClassAd", "%s", ""); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("ClassAd Environment", "%s", V2R); emit_output_actual_header(); emit_param("ClassAd Environment", "%s", actual); if(!strings_similar(actual, V2R)) { free(actual); FAIL; } free(actual); PASS; } static bool test_insert_env_into_classad_v1_v1_replace() { emit_test("Test that InsertEnvIntoClassAd() replaces the environment " "variables from an Env object in V1 format into the ClassAd with a V1 " "Environment."); Env env; char* actual; env.MergeFromV1Raw(V1R_REP, NULL); ClassAd classad; initAdFromString(AD_V1, classad); env.InsertEnvIntoClassAd(&classad, NULL); classad.LookupString("Env", &actual); emit_input_header(); emit_param("Env", "%s", V1R_REP); emit_param("ClassAd", "%s", AD_V1); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("ClassAd Env", "%s", V1R_REP); emit_output_actual_header(); emit_param("ClassAd Env", "%s", actual); if(!strings_similar(actual, V1R_REP, V1_ENV_DELIM)) { free(actual); FAIL; } free(actual); PASS; } static bool test_insert_env_into_classad_v1_v2_replace() { emit_test("Test that InsertEnvIntoClassAd() replaces the environment " "variables from an Env object in V1 format into the ClassAd with a V2 " "Environment."); Env env; char* actual; env.MergeFromV1Raw(V1R_REP, NULL); ClassAd classad; initAdFromString(AD_V2, classad); env.InsertEnvIntoClassAd(&classad, NULL); classad.LookupString("Environment", &actual); emit_input_header(); emit_param("Env", "%s", V1R_REP); emit_param("ClassAd", "%s", AD_V2); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("ClassAd Environment", "%s", V2R_REP); emit_output_actual_header(); emit_param("ClassAd Environment", "%s", actual); if(!strings_similar(actual, V2R_REP)) { free(actual); FAIL; } free(actual); PASS; } static bool test_insert_env_into_classad_v2_v1_replace() { emit_test("Test that InsertEnvIntoClassAd() replaces the environment " "variables from an Env object in V2 format into the ClassAd with a V1 " "Environment."); Env env; char* actual; env.MergeFromV2Raw(V2R_REP, NULL); ClassAd classad; initAdFromString(AD_V1, classad); env.InsertEnvIntoClassAd(&classad, NULL); classad.LookupString("Env", &actual); emit_input_header(); emit_param("Env", "%s", V2R_REP); emit_param("ClassAd", "%s", AD_V1); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("ClassAd Env", "%s", V1R_REP); emit_output_actual_header(); emit_param("ClassAd Env", "%s", actual); if(!strings_similar(actual, V1R_REP, V1_ENV_DELIM)) { free(actual); FAIL; } free(actual); PASS; } static bool test_insert_env_into_classad_v2_v2_replace() { emit_test("Test that InsertEnvIntoClassAd() replaces the environment " "variables from an Env object in V2 format into the ClassAd with a V2 " "Environment."); Env env; char* actual; env.MergeFromV2Raw(V2R_REP, NULL); ClassAd classad; initAdFromString(AD_V2, classad); env.InsertEnvIntoClassAd(&classad, NULL); classad.LookupString("Environment", &actual); emit_input_header(); emit_param("Env", "%s", V2R_REP); emit_param("ClassAd", "%s", AD_V2); emit_param("MyString", "%s", "NULL"); emit_output_expected_header(); emit_param("ClassAd Environment", "%s", V2R_REP); emit_output_actual_header(); emit_param("ClassAd Environment", "%s", actual); if(!strings_similar(actual, V2R_REP)) { free(actual); FAIL; } free(actual); PASS; } static bool test_insert_env_into_classad_version_v1() { emit_test("Test that InsertEnvIntoClassAd() adds the environment " "variables from an Env object in V2 format into the ClassAd when the " "CondorVersionInfo requires V1 format."); Env env; CondorVersionInfo info("$CondorVersion: 6.0.0 " __DATE__ " PRE-RELEASE $"); char *actual, *version = info.get_version_string(); env.MergeFromV2Raw(V2R, NULL); ClassAd classad; env.InsertEnvIntoClassAd(&classad, NULL, NULL, &info); classad.LookupString("Env", &actual); emit_input_header(); emit_param("Env", "%s", V2R); emit_param("ClassAd", "%s", EMPTY); emit_param("MyString", "%s", "NULL"); emit_param("STRING", "%s", "NULL"); emit_param("CondorVersionInfo", "%s", version); emit_output_expected_header(); emit_param("ClassAd Env", "%s", V1R); emit_output_actual_header(); emit_param("ClassAd Env", "%s", actual); if(!strings_similar(actual, V1R, V1_ENV_DELIM)) { free(actual); free(version); FAIL; } free(actual); free(version); PASS; } static bool test_insert_env_into_classad_version_v1_os_winnt() { emit_test("Test that InsertEnvIntoClassAd() adds the environment " "variables from an Env object in V2 format into the ClassAd when the " "CondorVersionInfo requires V1 format and the target OS is WINNT."); Env env; CondorVersionInfo info("$CondorVersion: 6.0.0 " __DATE__ " PRE-RELEASE $"); char *actual, *version = info.get_version_string(); env.MergeFromV2Raw(V2R, NULL); ClassAd classad; env.InsertEnvIntoClassAd(&classad, NULL, "WINNT", &info); classad.LookupString("Env", &actual); emit_input_header(); emit_param("Env", "%s", V2R); emit_param("ClassAd", "%s", EMPTY); emit_param("MyString", "%s", "NULL"); emit_param("STRING", "%s", "WINNT"); emit_param("CondorVersionInfo", "%s", version); emit_output_expected_header(); emit_param("ClassAd Env", "%s", V1R_WIN); emit_output_actual_header(); emit_param("ClassAd Env", "%s", actual); if(!strings_similar(actual, V1R_WIN, "|")) { free(actual); free(version); FAIL; } free(actual); free(version); PASS; } static bool test_insert_env_into_classad_version_v1_os_win32() { emit_test("Test that InsertEnvIntoClassAd() adds the environment " "variables from an Env object in V2 format into the ClassAd when the " "CondorVersionInfo requires V1 format and the target OS is WIN32."); Env env; CondorVersionInfo info("$CondorVersion: 6.0.0 " __DATE__ " PRE-RELEASE $"); char *actual, *version = info.get_version_string(); env.MergeFromV2Raw(V2R, NULL); ClassAd classad; env.InsertEnvIntoClassAd(&classad, NULL, "WIN32", &info); classad.LookupString("Env", &actual); emit_input_header(); emit_param("Env", "%s", V2R); emit_param("ClassAd", "%s", EMPTY); emit_param("MyString", "%s", "NULL"); emit_param("STRING", "%s", "WIN32"); emit_param("CondorVersionInfo", "%s", version); emit_output_expected_header(); emit_param("ClassAd Env", "%s", V1R_WIN); emit_output_actual_header(); emit_param("ClassAd Env", "%s", actual); if(!strings_similar(actual, V1R_WIN, "|")) { free(actual); free(version); FAIL; } free(actual); free(version); PASS; } static bool test_insert_env_into_classad_version_v1_os_unix() { emit_test("Test that InsertEnvIntoClassAd() adds the environment " "variables from an Env object in V2 format into the ClassAd when the " "CondorVersionInfo requires V1 format and the target OS is UNIX."); Env env; CondorVersionInfo info("$CondorVersion: 6.0.0 " __DATE__ " PRE-RELEASE $"); char *actual, *version = info.get_version_string(); env.MergeFromV2Raw(V2R, NULL); ClassAd classad; env.InsertEnvIntoClassAd(&classad, NULL, "UNIX", &info); classad.LookupString("Env", &actual); emit_input_header(); emit_param("Env", "%s", V2R); emit_param("ClassAd", "%s", EMPTY); emit_param("MyString", "%s", "NULL"); emit_param("STRING", "%s", "UNIX"); emit_param("CondorVersionInfo", "%s", version); emit_output_expected_header(); emit_param("ClassAd Env", "%s", V1R_NIX); emit_output_actual_header(); emit_param("ClassAd Env", "%s", actual); if(!strings_similar(actual, V1R_NIX, V1_ENV_DELIM_NIX)) { free(actual); free(version); FAIL; } free(actual); free(version); PASS; } static bool test_insert_env_into_classad_version_v1_semi() { emit_test("Test that InsertEnvIntoClassAd() adds the environment " "variables from an Env object in V2 format into the ClassAd when the " "CondorVersionInfo requires V1 format and the ClassAd previously used " "a semicolon as a delimiter."); Env env; CondorVersionInfo info("$CondorVersion: 6.0.0 " __DATE__ " PRE-RELEASE $"); char *actual, *version = info.get_version_string(); env.MergeFromV2Raw(V2R, NULL); ClassAd classad; initAdFromString(AD_V1, classad); env.InsertEnvIntoClassAd(&classad, NULL, NULL, &info); classad.LookupString("Env", &actual); emit_input_header(); emit_param("Env", "%s", V2R); emit_param("ClassAd", "%s", AD_V1); emit_param("MyString", "%s", "NULL"); emit_param("STRING", "%s", "NULL"); emit_param("CondorVersionInfo", "%s", version); emit_output_expected_header(); emit_param("ClassAd Env", "%s", V1R); emit_output_actual_header(); emit_param("ClassAd Env", "%s", actual); if(!strings_similar(actual, V1R, V1_ENV_DELIM)) { free(actual); free(version); FAIL; } free(actual); free(version); PASS; } static bool test_insert_env_into_classad_version_v1_line() { emit_test("Test that InsertEnvIntoClassAd() adds the environment " "variables from an Env object in V2 format into the ClassAd when the " "CondorVersionInfo requires V1 format and the ClassAd previously used " "a '|' as a delimiter."); Env env; CondorVersionInfo info("$CondorVersion: 6.0.0 " __DATE__ " PRE-RELEASE $"); char *actual, *version = info.get_version_string(); env.MergeFromV2Raw(V2R_REP, NULL); ClassAd classad; initAdFromString(AD_V1_WIN, classad); env.InsertEnvIntoClassAd(&classad, NULL, NULL, &info); classad.LookupString("Env", &actual); emit_input_header(); emit_param("Env", "%s", V2R); emit_param("ClassAd", "%s", AD_V1_WIN); emit_param("MyString", "%s", "NULL"); emit_param("STRING", "%s", "NULL"); emit_param("CondorVersionInfo", "%s", version); emit_output_expected_header(); emit_param("ClassAd Env", "%s", V1R_WIN); emit_output_actual_header(); emit_param("ClassAd Env", "%s", actual); if(!strings_similar(actual, V1R_REP_WIN, "|")) { free(actual); free(version); FAIL; } free(actual); free(version); PASS; } static bool test_insert_env_into_classad_version_v1_current() { emit_test("Test that InsertEnvIntoClassAd() adds the environment " "variables from an Env object in V2 format into the ClassAd when the " "CondorVersionInfo requires V1 format and we use the delimiter for the " "current OS."); Env env; CondorVersionInfo info("$CondorVersion: 6.0.0 " __DATE__ " PRE-RELEASE $"); char *actual, *version = info.get_version_string(); env.MergeFromV2Raw(V2R, NULL); ClassAd classad; env.InsertEnvIntoClassAd(&classad, NULL, NULL, &info); classad.LookupString("Env", &actual); emit_input_header(); emit_param("Env", "%s", V2R); emit_param("ClassAd", "%s", EMPTY); emit_param("MyString", "%s", "NULL"); emit_param("STRING", "%s", "NULL"); emit_param("CondorVersionInfo", "%s", version); emit_output_expected_header(); emit_param("ClassAd Env", "%s", V1R); emit_output_actual_header(); emit_param("ClassAd Env", "%s", actual); if(!strings_similar(actual, V1R, V1_ENV_DELIM)) { free(actual); free(version); FAIL; } free(actual); free(version); PASS; } static bool test_insert_env_into_classad_version_v1_error_v2() { emit_test("Test that InsertEnvIntoClassAd() sets the error MyString for " "an Env object in V2 format that cannot be converted into V1 format " "when the CondorVersionInfo requires V1 format, but the ClassAd started" " with V2."); emit_comment("This test just checks if the error message is not empty."); Env env; CondorVersionInfo info("$CondorVersion: 6.0.0 " __DATE__ " PRE-RELEASE $"); char *actual, *version = info.get_version_string(); MyString error; env.MergeFromV2Raw(V2R_SEMI, NULL); ClassAd classad; initAdFromString(AD_V2, classad); env.InsertEnvIntoClassAd(&classad, &error, NULL, &info); classad.LookupString("Env", &actual); emit_input_header(); emit_param("Env", "%s", V2R_SEMI); emit_param("ClassAd", "%s", EMPTY); emit_param("MyString", "%s", ""); emit_param("STRING", "%s", "NULL"); emit_param("CondorVersionInfo", "%s", version); emit_output_actual_header(); emit_param("Error MyString", "%s", error.Value()); if(error.IsEmpty()) { free(actual); free(version); FAIL; } free(actual); free(version); PASS; } static bool test_insert_env_into_classad_version_v1_error() { emit_test("Test that InsertEnvIntoClassAd() sets the error MyString for " "an Env object in V2 format that cannot be converted into V1 format " "when the CondorVersionInfo requires V1 format."); emit_comment("This test just checks if the error message is not empty."); Env env; CondorVersionInfo info("$CondorVersion: 6.0.0 " __DATE__ " PRE-RELEASE $"); char *actual, *version = info.get_version_string(); MyString error; env.MergeFromV2Raw(V2R_SEMI, NULL); ClassAd classad; env.InsertEnvIntoClassAd(&classad, &error, NULL, &info); classad.LookupString("Env", &actual); emit_input_header(); emit_param("Env", "%s", V2R_SEMI); emit_param("ClassAd", "%s", EMPTY); emit_param("MyString", "%s", ""); emit_param("STRING", "%s", "NULL"); emit_param("CondorVersionInfo", "%s", version); emit_output_actual_header(); emit_param("Error MyString", "%s", error.Value()); if(error.IsEmpty()) { free(version); //don't need to free 'actual' FAIL; } free(version); //don't need to free 'actual' PASS; } static bool test_insert_env_into_classad_version_v2() { emit_test("Test that InsertEnvIntoClassAd() adds the environment " "variables from an Env object in V1 format into the ClassAd when the " "CondorVersionInfo doesn't require V1 format."); Env env; CondorVersionInfo info("$CondorVersion: 7.0.0 " __DATE__ " PRE-RELEASE $"); char *actual, *version = info.get_version_string(); env.MergeFromV1Raw(V1R, NULL); ClassAd classad; env.InsertEnvIntoClassAd(&classad, NULL, NULL, &info); classad.LookupString("Environment", &actual); emit_input_header(); emit_param("Env", "%s", V1R); emit_param("ClassAd", "%s", EMPTY); emit_param("MyString", "%s", "NULL"); emit_param("STRING", "%s", "NULL"); emit_param("CondorVersionInfo", "%s", version); emit_output_expected_header(); emit_param("ClassAd Environment", "%s", V2R); emit_output_actual_header(); emit_param("ClassAd Environment", "%s", actual); if(!strings_similar(actual, V2R)) { free(actual); free(version); FAIL; } free(actual); free(version); PASS; } static bool test_condor_version_requires_v1_false() { emit_test("Test that CondorVersionRequiresV1() returns false for condor " "version 7.0.0."); CondorVersionInfo info("$CondorVersion: 7.0.0 " __DATE__ " PRE-RELEASE $"); bool expect = false; bool actual = Env::CondorVersionRequiresV1(info); char* version = info.get_version_string(); emit_input_header(); emit_param("Condor Version", "%s", version); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { free(version); FAIL; } free(version); PASS; } static bool test_condor_version_requires_v1_true() { emit_test("Test that CondorVersionRequiresV1() returns true for condor " "version 6.0.0."); CondorVersionInfo info("$CondorVersion: 6.0.0 " __DATE__ " PRE-RELEASE $"); bool expect = true; bool actual = Env::CondorVersionRequiresV1(info); char* version = info.get_version_string(); emit_input_header(); emit_param("Condor Version", "%s", version); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { free(version); FAIL; } free(version); PASS; } static bool test_condor_version_requires_v1_this() { emit_test("Test that CondorVersionRequiresV1() returns false for this " "version of condor."); CondorVersionInfo info; bool expect = false; bool actual = Env::CondorVersionRequiresV1(info); char* version = info.get_version_string(); emit_input_header(); emit_param("Condor Version", "%s", version); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { free(version); FAIL; } free(version); PASS; } static bool test_get_delim_str_v2_raw_return_empty() { emit_test("Test that getDelimitedStringV2Raw() returns true for an empty " "Env object."); Env env; MyString result, error; bool expect = true; bool actual = env.getDelimitedStringV2Raw(&result, &error); emit_input_header(); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_get_delim_str_v2_raw_return_v1() { emit_test("Test that getDelimitedStringV2Raw() returns true for an Env " "object using V1 format."); Env env; MyString result, error; env.MergeFromV1Raw(V1R, NULL); bool expect = true; bool actual = env.getDelimitedStringV2Raw(&result, &error); emit_input_header(); emit_param("Env", "%s", V1R); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_get_delim_str_v2_raw_return_v2() { emit_test("Test that getDelimitedStringV2Raw() returns true for an Env " "object using V2 format."); Env env; MyString result, error; env.MergeFromV2Raw(V2R, NULL); bool expect = true; bool actual = env.getDelimitedStringV2Raw(&result, &error); emit_input_header(); emit_param("Env", "%s", V2R); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_get_delim_str_v2_raw_result_empty() { emit_test("Test that getDelimitedStringV2Raw() sets the result MyString " "to the expected value for an empty Env object."); Env env; MyString actual, error; env.getDelimitedStringV2Raw(&actual, &error); emit_input_header(); emit_param("Env", "%s", ""); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_param("Result MyString", "%s", EMPTY); emit_output_actual_header(); emit_param("Result MyString", "%s", actual.Value()); if(actual != EMPTY) { FAIL; } PASS; } static bool test_get_delim_str_v2_raw_result_v1() { emit_test("Test that getDelimitedStringV2Raw() sets the result MyString " "to the expected value for an Env object using V1 format."); Env env; MyString actual, error; env.MergeFromV1Raw(V1R, NULL); env.getDelimitedStringV2Raw(&actual, &error); emit_input_header(); emit_param("Env", "%s", V1R); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_param("Result MyString", "%s", V2R); emit_output_actual_header(); emit_param("Result MyString", "%s", actual.Value()); if(!strings_similar(actual.Value(), V2R)) { FAIL; } PASS; } static bool test_get_delim_str_v2_raw_result_v2() { emit_test("Test that getDelimitedStringV2Raw() sets the result MyString " "to the expected value for an Env object using V2 format."); Env env; MyString actual, error; env.MergeFromV2Raw(V2R, NULL); env.getDelimitedStringV2Raw(&actual, &error); emit_input_header(); emit_param("Env", "%s", V2R); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_param("Result MyString", "%s", V2R); emit_output_actual_header(); emit_param("Result MyString", "%s", actual.Value()); if(!strings_similar(actual.Value(), V2R)) { FAIL; } PASS; } static bool test_get_delim_str_v2_raw_result_add() { emit_test("Test that getDelimitedStringV2Raw() sets the result MyString " "to the expected value after adding environment variables with " "MergeFromV2Raw()."); Env env; MyString actual1, actual2, error; env.MergeFromV2Raw(V2R_REP, NULL); env.getDelimitedStringV2Raw(&actual1, &error); env.MergeFromV2Raw(V2R_ADD, NULL); env.getDelimitedStringV2Raw(&actual2, &error); emit_input_header(); emit_param("Env", "%s", V2R_REP); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_param("Result MyString Before", "%s", V2R_REP); emit_param("Result MyString After", "%s", V2R_REP_ADD); emit_output_actual_header(); emit_param("Result MyString Before", "%s", actual1.Value()); emit_param("Result MyString After", "%s", actual2.Value()); if(!strings_similar(actual1.Value(), V2R_REP) || !strings_similar(actual2.Value(), V2R_REP_ADD)) { FAIL; } PASS; } static bool test_get_delim_str_v2_raw_result_replace() { emit_test("Test that getDelimitedStringV2Raw() sets the result MyString " "to the expected value after replacing environment variables with" "MergeFromV2Raw()."); Env env; MyString actual1, actual2, error; env.MergeFromV2Raw(V2R, NULL); env.getDelimitedStringV2Raw(&actual1, &error); env.MergeFromV2Raw(V2R_REP, NULL); env.getDelimitedStringV2Raw(&actual2, &error); emit_input_header(); emit_param("Env", "%s", V2R); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_param("Result MyString Before", "%s", V2R); emit_param("Result MyString After", "%s", V2R_REP); emit_output_actual_header(); emit_param("Result MyString Before", "%s", actual1.Value()); emit_param("Result MyString After", "%s", actual2.Value()); if(!strings_similar(actual1.Value(), V2R) || !strings_similar(actual2.Value(), V2R_REP)) { FAIL; } PASS; } static bool test_get_delim_str_v2_raw_result_add_replace() { emit_test("Test that getDelimitedStringV2Raw() sets the result MyString " "to the expected value after adding and replacing environment variables" " with MergeFromV2Raw()."); Env env; MyString actual1, actual2, error; env.MergeFromV2Raw(V2R, NULL); env.getDelimitedStringV2Raw(&actual1, &error); env.MergeFromV2Raw(V2R_REP_ADD, NULL); env.getDelimitedStringV2Raw(&actual2, &error); emit_input_header(); emit_param("Env", "%s", V2R); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_param("Result MyString Before", "%s", V2R); emit_param("Result MyString After", "%s", V2R_REP_ADD); emit_output_actual_header(); emit_param("Result MyString Before", "%s", actual1.Value()); emit_param("Result MyString After", "%s", actual2.Value()); if(!strings_similar(actual1.Value(), V2R) || !strings_similar(actual2.Value(), V2R_REP_ADD)) { FAIL; } PASS; } static bool test_get_delim_str_v2_raw_mark_empty() { emit_test("Test that getDelimitedStringV2Raw() adds the RAW_ENV_V2_MARKER" " to the result MyString for an empty Env object."); Env env; MyString actual, error; env.getDelimitedStringV2Raw(&actual, &error, true); emit_input_header(); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_param("BOOLEAN", "%s", "TRUE"); emit_output_expected_header(); emit_param("Result MyString", "'%s'", " "); emit_output_actual_header(); emit_param("Result MyString", "'%s'", actual.Value()); if(actual != " ") { FAIL; } PASS; } static bool test_get_delim_str_v2_raw_mark_v1() { emit_test("Test that getDelimitedStringV2Raw() adds the RAW_ENV_V2_MARKER" " to the result MyString for an Env object using V1 format."); Env env; MyString actual, error; env.MergeFromV1Raw(V1R, NULL); env.getDelimitedStringV2Raw(&actual, &error, true); emit_input_header(); emit_param("Env", "%s", V1R); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_param("BOOLEAN", "%s", "TRUE"); emit_output_expected_header(); emit_param("Result MyString", "%s", V2R); emit_output_actual_header(); emit_param("Result MyString", "%s", actual.Value()); if(!strings_similar(actual.Value(), V2R) || actual[0] != ' ') { FAIL; } PASS; } static bool test_get_delim_str_v2_raw_mark_v2() { emit_test("Test that getDelimitedStringV2Raw() adds the RAW_ENV_V2_MARKER" " to the result MyString for an Env object using V2 format."); Env env; MyString actual, error; env.MergeFromV2Raw(V2R_SEMI, NULL); env.getDelimitedStringV2Raw(&actual, &error, true); emit_input_header(); emit_param("Env", "%s", V2R); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_param("BOOLEAN", "%s", "FALSE"); emit_output_expected_header(); emit_param("Result MyString", "%s", V2R_MARK); emit_output_actual_header(); emit_param("Result MyString", "%s", actual.Value()); if(!strings_similar(actual.Value(), V2R_MARK) || actual[0] != ' ') { FAIL; } PASS; } static bool test_get_delim_str_v1_raw_return_empty() { emit_test("Test that getDelimitedStringV1Raw() returns true for an empty " "Env object."); Env env; MyString result, error; bool expect = true; bool actual = env.getDelimitedStringV1Raw(&result, &error); emit_input_header(); emit_param("Env", "%s", ""); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_get_delim_str_v1_raw_return_v1() { emit_test("Test that getDelimitedStringV1Raw() returns true for an Env " "object using V1 format."); Env env; MyString result, error; env.MergeFromV1Raw(V1R, NULL); bool expect = true; bool actual = env.getDelimitedStringV1Raw(&result, &error); emit_input_header(); emit_param("Env", "%s", V1R); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_get_delim_str_v1_raw_return_v2() { emit_test("Test that getDelimitedStringV1Raw() returns true for an Env " "object using V2 format."); Env env; MyString result, error; env.MergeFromV2Raw(V2R, NULL); bool expect = true; bool actual = env.getDelimitedStringV1Raw(&result, &error); emit_input_header(); emit_param("Env", "%s", V2R); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_get_delim_str_v1_raw_return_delim() { emit_test("Test that getDelimitedStringV1Raw() returns false for an Env " "object using V2 format with a ';'."); Env env; MyString result, error; env.MergeFromV2Raw(V2R_SEMI, NULL); bool expect = false; bool actual = env.getDelimitedStringV1Raw(&result, &error); emit_input_header(); emit_param("Env", "%s", V2R_SEMI); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_get_delim_str_v1_raw_error_delim() { emit_test("Test that getDelimitedStringV1Raw() sets the error MyString " "for an Env object using V2 format with a ';'."); emit_comment("This test just checks if the error message is not empty."); Env env; MyString result, error; env.MergeFromV2Raw(V2R_SEMI, NULL); env.getDelimitedStringV1Raw(&result, &error); emit_input_header(); emit_param("Env", "%s", V2R_SEMI); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_param("Error MyString is Empty", "%s", "FALSE"); emit_output_actual_header(); emit_param("Error MyString is Empty", "%s", tfstr(error.IsEmpty())); if(error.IsEmpty()) { FAIL; } PASS; } static bool test_get_delim_str_v1_raw_result_empty() { emit_test("Test that getDelimitedStringV1Raw() sets the result MyString " "to the expected value for an empty Env object."); Env env; MyString actual, error; env.getDelimitedStringV1Raw(&actual, &error); emit_input_header(); emit_param("Env", "%s", ""); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_param("Result MyString", "%s", EMPTY); emit_output_actual_header(); emit_param("Result MyString", "%s", actual.Value()); if(actual != EMPTY) { FAIL; } PASS; } static bool test_get_delim_str_v1_raw_result_v1() { emit_test("Test that getDelimitedStringV1Raw() sets the result MyString " "to the expected value for an Env object in V1 format."); Env env; MyString actual, error; env.MergeFromV1Raw(V1R, NULL); env.getDelimitedStringV1Raw(&actual, &error); emit_input_header(); emit_param("Env", "%s", V1R); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_param("Result MyString", "%s", V1R); emit_output_actual_header(); emit_param("Result MyString", "%s", actual.Value()); if(!strings_similar(actual.Value(), V1R, V1_ENV_DELIM)) { FAIL; } PASS; } static bool test_get_delim_str_v1_raw_result_v2() { emit_test("Test that getDelimitedStringV1Raw() sets the result MyString " "to the expected value for an Env object in V2 format."); Env env; MyString actual, error; env.MergeFromV2Raw(V2R, NULL); env.getDelimitedStringV1Raw(&actual, &error); emit_input_header(); emit_param("Env", "%s", V2R); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_param("Result MyString", "%s", V1R); emit_output_actual_header(); emit_param("Result MyString", "%s", actual.Value()); if(!strings_similar(actual.Value(), V1R, V1_ENV_DELIM)) { FAIL; } PASS; } static bool test_get_delim_str_v1_raw_result_add() { emit_test("Test that getDelimitedStringV1Raw() sets the result MyString " "to the expected value after adding environment variables with " "MergeFromV1Raw()."); Env env; MyString actual1, actual2, error; env.MergeFromV1Raw(V1R_REP, NULL); env.getDelimitedStringV1Raw(&actual1, &error); env.MergeFromV1Raw(V1R_ADD, NULL); env.getDelimitedStringV1Raw(&actual2, &error); emit_input_header(); emit_param("Env", "%s", V1R_REP); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_param("Result MyString Before", "%s", V1R_REP); emit_param("Result MyString After", "%s", V1R_REP_ADD); emit_output_actual_header(); emit_param("Result MyString Before", "%s", actual1.Value()); emit_param("Result MyString After", "%s", actual2.Value()); if(!strings_similar(actual1.Value(), V1R_REP, V1_ENV_DELIM) || !strings_similar(actual2.Value(), V1R_REP_ADD, V1_ENV_DELIM)) { FAIL; } PASS; } static bool test_get_delim_str_v1_raw_result_replace() { emit_test("Test that getDelimitedStringV1Raw() sets the result MyString " "to the expected value after replacing environment variables with " "MergeFromV1Raw()."); Env env; MyString actual1, actual2, error; env.MergeFromV1Raw(V1R, NULL); env.getDelimitedStringV1Raw(&actual1, &error); env.MergeFromV1Raw(V1R_REP, NULL); env.getDelimitedStringV1Raw(&actual2, &error); emit_input_header(); emit_param("Env", "%s", V1R); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_param("Result MyString Before", "%s", V1R); emit_param("Result MyString After", "%s", V1R_REP); emit_output_actual_header(); emit_param("Result MyString Before", "%s", actual1.Value()); emit_param("Result MyString After", "%s", actual2.Value()); if(!strings_similar(actual1.Value(), V1R, V1_ENV_DELIM) || !strings_similar(actual2.Value(), V1R_REP, V1_ENV_DELIM)) { FAIL; } PASS; } static bool test_get_delim_str_v1_raw_result_add_replace() { emit_test("Test that getDelimitedStringV1Raw() sets the result MyString " "to the expected value after adding and replacing environment variables" " with MergeFromV1Raw()."); Env env; MyString actual1, actual2, error; env.MergeFromV1Raw(V1R, NULL); env.getDelimitedStringV1Raw(&actual1, &error); env.MergeFromV1Raw(V1R_REP_ADD, NULL); env.getDelimitedStringV1Raw(&actual2, &error); emit_input_header(); emit_param("Env", "%s", V1R); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_param("Result MyString Before", "%s", V1R); emit_param("Result MyString After", "%s", V1R_REP); emit_output_actual_header(); emit_param("Result MyString Before", "%s", actual1.Value()); emit_param("Result MyString After", "%s", actual2.Value()); if(!strings_similar(actual1.Value(), V1R, V1_ENV_DELIM) || !strings_similar(actual2.Value(), V1R_REP_ADD, V1_ENV_DELIM)) { FAIL; } PASS; } static bool test_get_delim_str_v1or2_raw_ad_return_empty() { emit_test("Test that getDelimitedStringV1or2Raw() returns true for an " "empty ClassAd."); Env env; ClassAd classad; MyString result, error; bool expect = true; bool actual = env.getDelimitedStringV1or2Raw(&classad, &result, &error); emit_input_header(); emit_param("Env", "%s", ""); emit_param("ClassAd", "%s", ""); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_get_delim_str_v1or2_raw_ad_return_v1() { emit_test("Test that getDelimitedStringV1or2Raw() returns true for a " "ClassAd using V1 format."); Env env; ClassAd classad; initAdFromString(AD_V1, classad); MyString result, error; bool expect = true; bool actual = env.getDelimitedStringV1or2Raw(&classad, &result, &error); emit_input_header(); emit_param("Env", "%s", ""); emit_param("ClassAd", "%s", AD_V1); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_get_delim_str_v1or2_raw_ad_return_v2() { emit_test("Test that getDelimitedStringV1or2Raw() returns true for a " "ClassAd using V2 format."); Env env; ClassAd classad; initAdFromString(AD_V2, classad); MyString result, error; bool expect = true; bool actual = env.getDelimitedStringV1or2Raw(&classad, &result, &error); emit_input_header(); emit_param("Env", "%s", ""); emit_param("ClassAd", "%s", AD_V2); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_get_delim_str_v1or2_raw_ad_return_invalid_v1() { emit_test("Test that getDelimitedStringV1or2Raw() returns false when " "passed an invalid ClassAd using V1 format."); Env env; ClassAd classad; initAdFromString(AD_V1_MISS_BOTH, classad); MyString result, error; bool expect = false; bool actual = env.getDelimitedStringV1or2Raw(&classad, &result, &error); emit_input_header(); emit_param("Env", "%s", ""); emit_param("ClassAd", "%s", AD_V1_MISS_BOTH); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_get_delim_str_v1or2_raw_ad_return_invalid_v2() { emit_test("Test that getDelimitedStringV1or2Raw() returns false when " "passed an invalid ClassAd using V2 format."); Env env; ClassAd classad; initAdFromString(AD_V2_MISS_BOTH, classad); MyString result, error; bool expect = false; bool actual = env.getDelimitedStringV1or2Raw(&classad, &result, &error); emit_input_header(); emit_param("Env", "%s", ""); emit_param("ClassAd", "%s", AD_V2_MISS_BOTH); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_get_delim_str_v1or2_raw_ad_error_v1() { emit_test("Test that getDelimitedStringV1or2Raw() sets the error MyString" " when passed an invalid ClassAd using V1 format."); emit_comment("This test just checks if the error message is not empty."); Env env; ClassAd classad; initAdFromString(AD_V1_MISS_BOTH, classad); MyString result, error; env.getDelimitedStringV1or2Raw(&classad, &result, &error); emit_input_header(); emit_param("Env", "%s", ""); emit_param("ClassAd", "%s", AD_V1_MISS_BOTH); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_actual_header(); emit_param("Error Message", "%s", error.Value()); if(error.IsEmpty()) { FAIL; } PASS; } static bool test_get_delim_str_v1or2_raw_ad_error_v2() { emit_test("Test that getDelimitedStringV1or2Raw() sets the error MyString" " when passed an invalid ClassAd using V2 format."); emit_comment("This test just checks if the error message is not empty."); Env env; ClassAd classad; initAdFromString(AD_V2_MISS_BOTH, classad); MyString result, error; env.getDelimitedStringV1or2Raw(&classad, &result, &error); emit_input_header(); emit_param("Env", "%s", ""); emit_param("ClassAd", "%s", AD_V2_MISS_BOTH); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_actual_header(); emit_param("Error Message", "%s", error.Value()); if(error.IsEmpty()) { FAIL; } PASS; } static bool test_get_delim_str_v1or2_raw_ad_result_empty() { emit_test("Test that getDelimitedStringV1or2Raw() sets the result " "MyString to the expected value for an empty Env object."); Env env; ClassAd classad; MyString actual, error; env.getDelimitedStringV1or2Raw(&classad, &actual, &error); emit_input_header(); emit_param("Env", "%s", ""); emit_param("ClassAd", "%s", ""); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_param("Result MyString", "%s", EMPTY); emit_output_actual_header(); emit_param("Result MyString", "%s", actual.Value()); if(actual != EMPTY) { FAIL; } PASS; } static bool test_get_delim_str_v1or2_raw_ad_result_v1() { emit_test("Test that getDelimitedStringV1or2Raw() sets the result " "MyString to the expected value for an Env object in V1 format."); Env env; ClassAd classad; initAdFromString(AD_V1, classad); MyString actual, error; env.getDelimitedStringV1or2Raw(&classad, &actual, &error); emit_input_header(); emit_param("Env", "%s", ""); emit_param("ClassAd", "%s", AD_V1); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_param("Result MyString", "%s", V1R); emit_output_actual_header(); emit_param("Result MyString", "%s", actual.Value()); if(!strings_similar(actual.Value(), V1R, V1_ENV_DELIM)) { FAIL; } PASS; } static bool test_get_delim_str_v1or2_raw_ad_result_v2() { emit_test("Test that getDelimitedStringV1or2Raw() sets the result " "MyString to the expected value for an Env object in V2 format."); Env env; ClassAd classad; initAdFromString(AD_V2_SEMI, classad); MyString actual, error; env.getDelimitedStringV1or2Raw(&classad, &actual, &error); emit_input_header(); emit_param("Env", "%s", ""); emit_param("ClassAd", "%s", AD_V2_SEMI); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_param("Result MyString", "%s", V2R_SEMI); emit_output_actual_header(); emit_param("Result MyString", "%s", actual.Value()); if(!strings_similar(actual.Value(), V2R_SEMI)) { FAIL; } PASS; } static bool test_get_delim_str_v1or2_raw_ad_result_replace() { emit_test("Test that getDelimitedStringV1or2Raw() sets the result " "MyString to the expected value after replacing environment variables " "from the ClassAd."); Env env; ClassAd classad; initAdFromString(AD_V1_REP, classad); MyString actual1, actual2, error; env.MergeFromV1Raw(V1R, NULL); env.getDelimitedStringV1Raw(&actual1, &error); env.getDelimitedStringV1or2Raw(&classad, &actual2, &error); emit_input_header(); emit_param("Env", "%s", V1R); emit_param("ClassAd", "%s", AD_V1_REP); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_param("Result MyString Before", "%s", V1R); emit_param("Result MyString After", "%s", V1R_REP); emit_output_actual_header(); emit_param("Result MyString Before", "%s", actual1.Value()); emit_param("Result MyString After", "%s", actual2.Value()); if(!strings_similar(actual1.Value(), V1R, V1_ENV_DELIM) || !strings_similar(actual2.Value(), V1R_REP, V1_ENV_DELIM)) { FAIL; } PASS; } static bool test_get_delim_str_v1or2_raw_return_empty() { emit_test("Test that getDelimitedStringV1or2Raw() returns true for an " "empty Env object."); Env env; MyString result, error; bool expect = true; bool actual = env.getDelimitedStringV1or2Raw(&result, &error); emit_input_header(); emit_param("Env", "%s", ""); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_get_delim_str_v1or2_raw_return_v1() { emit_test("Test that getDelimitedStringV1or2Raw() returns true for an " "Env object using V1 format."); Env env; MyString result, error; env.MergeFromV1Raw(V1R, NULL); bool expect = true; bool actual = env.getDelimitedStringV1or2Raw(&result, &error); emit_input_header(); emit_param("Env", "%s", V1R); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_get_delim_str_v1or2_raw_return_v2() { emit_test("Test that getDelimitedStringV1or2Raw() returns true for an " "Env object using V2 format."); Env env; MyString result, error; env.MergeFromV2Raw(V2R_SEMI, NULL); bool expect = true; bool actual = env.getDelimitedStringV1or2Raw(&result, &error); emit_input_header(); emit_param("Env", "%s", V2R_SEMI); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_get_delim_str_v1or2_raw_result_empty() { emit_test("Test that getDelimitedStringV1or2Raw() sets the result " "MyString to the expected value for an empty Env object."); Env env; MyString actual, error; env.getDelimitedStringV1or2Raw(&actual, &error); emit_input_header(); emit_param("Env", "%s", ""); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_param("Result MyString", "%s", EMPTY); emit_output_actual_header(); emit_param("Result MyString", "%s", actual.Value()); if(actual != EMPTY) { FAIL; } PASS; } static bool test_get_delim_str_v1or2_raw_result_v1() { emit_test("Test that getDelimitedStringV1or2Raw() sets the result " "MyString to the expected value for an Env object using V1 format."); Env env; MyString actual, error; env.MergeFromV1Raw(V1R, NULL); env.getDelimitedStringV1or2Raw(&actual, &error); emit_input_header(); emit_param("Env", "%s", V1R); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_param("Result MyString", "%s", V1R); emit_output_actual_header(); emit_param("Result MyString", "%s", actual.Value()); if(!strings_similar(actual.Value(), V1R, V1_ENV_DELIM)) { FAIL; } PASS; } static bool test_get_delim_str_v1or2_raw_result_v2() { emit_test("Test that getDelimitedStringV1or2Raw() sets the result " "MyString to the expected value for an Env object using V2 format."); Env env; MyString actual, error; env.MergeFromV2Raw(V2R_SEMI, NULL); env.getDelimitedStringV1or2Raw(&actual, &error); emit_input_header(); emit_param("Env", "%s", V2R_SEMI); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_param("Result MyString", "%s", V2R_SEMI); emit_output_actual_header(); emit_param("Result MyString", "%s", actual.Value()); if(!strings_similar(actual.Value(), V2R_SEMI)) { FAIL; } PASS; } static bool test_get_delim_str_v1or2_raw_result_add() { emit_test("Test that getDelimitedStringV1or2Raw() sets the result " "MyString to the expected value after adding environment variables with" " MergeFromV1Raw()."); Env env; MyString actual1, actual2, error; env.MergeFromV1Raw(V1R_REP, NULL); env.getDelimitedStringV1or2Raw(&actual1, &error); env.MergeFromV1Raw(V1R_ADD, NULL); env.getDelimitedStringV1or2Raw(&actual2, &error); emit_input_header(); emit_param("Env", "%s", V1R_REP); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_param("Result MyString Before", "%s", V1R_REP); emit_param("Result MyString After", "%s", V1R_REP_ADD); emit_output_actual_header(); emit_param("Result MyString Before", "%s", actual1.Value()); emit_param("Result MyString After", "%s", actual2.Value()); if(!strings_similar(actual1.Value(), V1R_REP, V1_ENV_DELIM) || !strings_similar(actual2.Value(), V1R_REP_ADD, V1_ENV_DELIM)) { FAIL; } PASS; } static bool test_get_delim_str_v1or2_raw_result_replace() { emit_test("Test that getDelimitedStringV1or2Raw() sets the result " "MyString to the expected value after replacing environment variables " "with MergeFromV1Raw()."); Env env; MyString actual1, actual2, error; env.MergeFromV1Raw(V1R, NULL); env.getDelimitedStringV1or2Raw(&actual1, &error); env.MergeFromV1Raw(V1R_REP, NULL); env.getDelimitedStringV1or2Raw(&actual2, &error); emit_input_header(); emit_param("Env", "%s", V1R); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_param("Result MyString Before", "%s", V1R); emit_param("Result MyString After", "%s", V1R_REP); emit_output_actual_header(); emit_param("Result MyString Before", "%s", actual1.Value()); emit_param("Result MyString After", "%s", actual2.Value()); if(!strings_similar(actual1.Value(), V1R, V1_ENV_DELIM) || !strings_similar(actual2.Value(), V1R_REP, V1_ENV_DELIM)) { FAIL; } PASS; } static bool test_get_delim_str_v1or2_raw_result_add_replace() { emit_test("Test that getDelimitedStringV1or2Raw() sets the result " "MyString to the expected value after adding and replacing environment " "variables with MergeFromV1Raw()."); Env env; MyString actual1, actual2, error; env.MergeFromV1Raw(V1R, NULL); env.getDelimitedStringV1or2Raw(&actual1, &error); env.MergeFromV1Raw(V1R_REP_ADD, NULL); env.getDelimitedStringV1or2Raw(&actual2, &error); emit_input_header(); emit_param("Env", "%s", V1R); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_param("Result MyString Before", "%s", V1R); emit_param("Result MyString After", "%s", V1R_REP_ADD); emit_output_actual_header(); emit_param("Result MyString Before", "%s", actual1.Value()); emit_param("Result MyString After", "%s", actual2.Value()); if(!strings_similar(actual1.Value(), V1R, V1_ENV_DELIM) || !strings_similar(actual2.Value(), V1R_REP_ADD, V1_ENV_DELIM)) { FAIL; } PASS; } static bool test_get_delim_str_v2_quoted_return_empty() { emit_test("Test that getDelimitedStringV2Quoted() returns true for an " "empty Env object."); Env env; MyString result, error; bool expect = true; bool actual = env.getDelimitedStringV2Quoted(&result, &error); emit_input_header(); emit_param("Env", "%s", ""); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_get_delim_str_v2_quoted_return_v1() { emit_test("Test that getDelimitedStringV2Quoted() returns true for an " "Env object using V1 format."); Env env; MyString result, error; env.MergeFromV1Raw(V1R, NULL); bool expect = true; bool actual = env.getDelimitedStringV2Quoted(&result, &error); emit_input_header(); emit_param("Env", "%s", V1R); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_get_delim_str_v2_quoted_return_v2() { emit_test("Test that getDelimitedStringV2Quoted() returns true for an " "Env object using V2 format."); Env env; MyString result, error; env.MergeFromV2Raw(V2R, NULL); bool expect = true; bool actual = env.getDelimitedStringV2Quoted(&result, &error); emit_input_header(); emit_param("Env", "%s", V2R); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_get_delim_str_v2_quoted_result_empty() { emit_test("Test that getDelimitedStringV2Quoted() sets the result " "MyString to the expected value for an empty Env object."); Env env; MyString actual, error; env.getDelimitedStringV2Quoted(&actual, &error); emit_input_header(); emit_param("Env", "%s", ""); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_param("Result MyString", "%s", "\"\""); emit_output_actual_header(); emit_param("Result MyString", "%s", actual.Value()); if(actual != "\"\"") { FAIL; } PASS; } static bool test_get_delim_str_v2_quoted_result_v1() { emit_test("Test that getDelimitedStringV2Quoted() sets the result " "MyString to the expected value for an Env object using V1 format."); Env env; MyString actual, error; env.MergeFromV1Raw(V1R, NULL); env.getDelimitedStringV2Quoted(&actual, &error); emit_input_header(); emit_param("Env", "%s", V1R); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_param("Result MyString", "%s", V2Q); emit_output_actual_header(); emit_param("Result MyString", "%s", actual.Value()); if(!strings_similar(actual.Value(), V2Q, " \"")) { FAIL; } PASS; } static bool test_get_delim_str_v2_quoted_result_v2() { emit_test("Test that getDelimitedStringV2Quoted() sets the result " "MyString to the expected value for an Env object using V2 format."); Env env; MyString actual, error; env.MergeFromV2Raw(V2R, NULL); env.getDelimitedStringV2Quoted(&actual, &error); emit_input_header(); emit_param("Env", "%s", V2R); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_param("Result MyString", "%s", V2Q); emit_output_actual_header(); emit_param("Result MyString", "%s", actual.Value()); if(!strings_similar(actual.Value(), V2Q, " \"")) { FAIL; } PASS; } static bool test_get_delim_str_v2_quoted_result_add() { emit_test("Test that getDelimitedStringV2Quoted() sets the result " "MyString to the expected value after adding environment variables with" " MergeFromV2Raw()."); Env env; MyString actual1, actual2, error; env.MergeFromV2Raw(V2R_REP, NULL); env.getDelimitedStringV2Quoted(&actual1, &error); env.MergeFromV2Raw(V2R_ADD, NULL); env.getDelimitedStringV2Quoted(&actual2, &error); emit_input_header(); emit_param("Env", "%s", V2R_REP); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_param("Result MyString Before", "%s", V2Q_REP); emit_param("Result MyString After", "%s", V2Q_REP_ADD); emit_output_actual_header(); emit_param("Result MyString Before", "%s", actual1.Value()); emit_param("Result MyString After", "%s", actual2.Value()); if(!strings_similar(actual1.Value(), V2Q_REP, " \"") || !strings_similar(actual2.Value(), V2Q_REP_ADD, " \"")) { FAIL; } PASS; } static bool test_get_delim_str_v2_quoted_result_replace() { emit_test("Test that getDelimitedStringV2Quoted() sets the result " "MyString to the expected value after replacing environment variables " "with MergeFromV2Raw()."); Env env; MyString actual1, actual2, error; env.MergeFromV2Raw(V2R, NULL); env.getDelimitedStringV2Quoted(&actual1, &error); env.MergeFromV2Raw(V2R_REP, NULL); env.getDelimitedStringV2Quoted(&actual2, &error); emit_input_header(); emit_param("Env", "%s", V2R); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_param("Result MyString Before", "%s", V2Q); emit_param("Result MyString After", "%s", V2Q_REP); emit_output_actual_header(); emit_param("Result MyString Before", "%s", actual1.Value()); emit_param("Result MyString After", "%s", actual2.Value()); if(!strings_similar(actual1.Value(), V2Q, " \"") || !strings_similar(actual2.Value(), V2Q_REP, " \"")) { FAIL; } PASS; } static bool test_get_delim_str_v2_quoted_result_add_replace() { emit_test("Test that getDelimitedStringV2Quoted() sets the result " "MyString to the expected value after adding and replacing environment " "variables with MergeFromV2Raw()."); Env env; MyString actual1, actual2, error; env.MergeFromV2Raw(V2R, NULL); env.getDelimitedStringV2Quoted(&actual1, &error); env.MergeFromV2Raw(V2R_REP_ADD, NULL); env.getDelimitedStringV2Quoted(&actual2, &error); emit_input_header(); emit_param("Env", "%s", V2R); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_param("Result MyString Before", "%s", V2Q); emit_param("Result MyString After", "%s", V2Q_REP_ADD); emit_output_actual_header(); emit_param("Result MyString Before", "%s", actual1.Value()); emit_param("Result MyString After", "%s", actual2.Value()); if(!strings_similar(actual1.Value(), V2Q, " \"") || !strings_similar(actual2.Value(), V2Q_REP_ADD, " \"")) { FAIL; } PASS; } static bool test_get_delim_str_v1r_or_v2q_return_empty() { emit_test("Test that getDelimitedStringV1RawOrV2Quoted() returns true for" " an empty Env object."); Env env; MyString result, error; bool expect = true; bool actual = env.getDelimitedStringV1RawOrV2Quoted(&result, &error); emit_input_header(); emit_param("Env", "%s", ""); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_get_delim_str_v1r_or_v2q_return_v1() { emit_test("Test that getDelimitedStringV1RawOrV2Quoted() returns true for" " an Env object using V1 format."); Env env; MyString result, error; env.MergeFromV1Raw(V1R, NULL); bool expect = true; bool actual = env.getDelimitedStringV1RawOrV2Quoted(&result, &error); emit_input_header(); emit_param("Env", "%s", V1R); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_get_delim_str_v1r_or_v2q_return_v2() { emit_test("Test that getDelimitedStringV1RawOrV2Quoted() returns true for" " an Env object using V2 format."); Env env; MyString result, error; env.MergeFromV2Raw(V2R, NULL); bool expect = true; bool actual = env.getDelimitedStringV1RawOrV2Quoted(&result, &error); emit_input_header(); emit_param("Env", "%s", V2R); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_get_delim_str_v1r_or_v2q_result_empty() { emit_test("Test that getDelimitedStringV1RawOrV2Quoted() sets the result " "MyString to the expected value for an empty Env object."); Env env; MyString actual, error; env.getDelimitedStringV1RawOrV2Quoted(&actual, &error); emit_input_header(); emit_param("Env", "%s", ""); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_param("Result MyString", "%s", EMPTY); emit_output_actual_header(); emit_param("Result MyString", "%s", actual.Value()); if(actual != EMPTY) { FAIL; } PASS; } static bool test_get_delim_str_v1r_or_v2q_result_v1() { emit_test("Test that getDelimitedStringV1RawOrV2Quoted() sets the result " "MyString to the expected value for an Env object using V1 format."); Env env; MyString actual, error; env.MergeFromV1Raw(V1R, NULL); env.getDelimitedStringV1RawOrV2Quoted(&actual, &error); emit_input_header(); emit_param("Env", "%s", V1R); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_param("Result MyString", "%s", V1R); emit_output_actual_header(); emit_param("Result MyString", "%s", actual.Value()); if(!strings_similar(actual.Value(), V1R, V1_ENV_DELIM)) { FAIL; } PASS; } static bool test_get_delim_str_v1r_or_v2q_result_v2() { emit_test("Test that getDelimitedStringV1RawOrV2Quoted() sets the result " "MyString to the expected value for an Env object using V2Raw format."); Env env; MyString actual, actual2, error; env.MergeFromV2Raw(V2R_SEMI, NULL); env.getDelimitedStringForDisplay(&actual2); env.getDelimitedStringV1RawOrV2Quoted(&actual, &error); emit_input_header(); emit_param("Env", "%s", V2R_SEMI); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_param("Result MyString", "%s", V2Q_SEMI); emit_output_actual_header(); emit_param("Display MyString", "%s", actual2.Value()); emit_param("Result MyString", "%s", actual.Value()); if(!strings_similar(actual.Value(), V2Q_SEMI, "\" ")) { FAIL; } PASS; } static bool test_get_delim_str_v1r_or_v2q_result_add() { emit_test("Test that getDelimitedStringV1RawOrV2Quoted() sets the result " "MyString to the expected value after adding environment variables with" " MergeFromV1Raw()."); Env env; MyString actual1, actual2, error; env.MergeFromV1Raw(V1R_REP, NULL); env.getDelimitedStringV1RawOrV2Quoted(&actual1, &error); env.MergeFromV1Raw(V1R_ADD, NULL); env.getDelimitedStringV1RawOrV2Quoted(&actual2, &error); emit_input_header(); emit_param("Env", "%s", V1R_REP); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_param("Result MyString Before", "%s", V1R_REP); emit_param("Result MyString After", "%s", V1R_REP_ADD); emit_output_actual_header(); emit_param("Result MyString Before", "%s", actual1.Value()); emit_param("Result MyString After", "%s", actual2.Value()); if(!strings_similar(actual1.Value(), V1R_REP, V1_ENV_DELIM) || !strings_similar(actual2.Value(), V1R_REP_ADD, V1_ENV_DELIM)) { FAIL; } PASS; } static bool test_get_delim_str_v1r_or_v2q_result_replace() { emit_test("Test that getDelimitedStringV1RawOrV2Quoted() sets the result " "MyString to the expected value after replacing environment variables " "with MergeFromV1Raw()."); Env env; MyString actual1, actual2, error; env.MergeFromV1Raw(V1R, NULL); env.getDelimitedStringV1RawOrV2Quoted(&actual1, &error); env.MergeFromV1Raw(V1R_REP, NULL); env.getDelimitedStringV1RawOrV2Quoted(&actual2, &error); emit_input_header(); emit_param("Env", "%s", V1R); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_param("Result MyString Before", "%s", V1R); emit_param("Result MyString After", "%s", V1R_REP); emit_output_actual_header(); emit_param("Result MyString Before", "%s", actual1.Value()); emit_param("Result MyString After", "%s", actual2.Value()); if(!strings_similar(actual1.Value(), V1R, V1_ENV_DELIM) || !strings_similar(actual2.Value(), V1R_REP, V1_ENV_DELIM)) { FAIL; } PASS; } static bool test_get_delim_str_v1r_or_v2q_result_add_replace() { emit_test("Test that getDelimitedStringV1RawOrV2Quoted() sets the result " "MyString to the expected value after adding and replacing environment " "variables with MergeFromV1Raw()."); Env env; MyString actual1, actual2, error; env.MergeFromV1Raw(V1R, NULL); env.getDelimitedStringV1RawOrV2Quoted(&actual1, &error); env.MergeFromV1Raw(V1R_REP_ADD, NULL); env.getDelimitedStringV1RawOrV2Quoted(&actual2, &error); emit_input_header(); emit_param("Env", "%s", V1R); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_param("Result MyString Before", "%s", V1R); emit_param("Result MyString After", "%s", V1R_REP_ADD); emit_output_actual_header(); emit_param("Result MyString Before", "%s", actual1.Value()); emit_param("Result MyString After", "%s", actual2.Value()); if(!strings_similar(actual1.Value(), V1R, V1_ENV_DELIM) || !strings_similar(actual2.Value(), V1R_REP_ADD, V1_ENV_DELIM)) { FAIL; } PASS; } static bool test_get_string_array_empty() { emit_test("Test that getStringArray() returns the expected string array " "for an empty Env object."); Env env; char** result = env.getStringArray(); emit_input_header(); emit_param("Env", "%s", ""); emit_output_expected_header(); emit_param("array[0] == NULL", "%s", "TRUE"); emit_output_actual_header(); emit_param("array[0] == NULL", "%s", tfstr(result != NULL && *result == NULL)); if(result == NULL || *result != NULL) { deleteStringArray(result); FAIL; } deleteStringArray(result); PASS; } static bool test_get_string_array_v1() { emit_test("Test that getStringArray() returns the expected string array " "for an Env object using V1 format."); Env env; env.MergeFromV1Raw(V1R, NULL); char** result = env.getStringArray(); MyString* actual = convert_string_array(result, 3); emit_input_header(); emit_param("Env", "%s", V1R); emit_output_expected_header(); emit_retval("%s", V2R); emit_output_actual_header(); emit_retval("%s", actual->Value()); if(!strings_similar(actual->Value(), V2R)) { deleteStringArray(result); delete actual; FAIL; } deleteStringArray(result); delete actual; PASS; } static bool test_get_string_array_v2() { emit_test("Test that getStringArray() returns the expected string array " "for an Env object using V2 format."); Env env; env.MergeFromV2Raw(V2R, NULL); char** result = env.getStringArray(); MyString* actual = convert_string_array(result, 3); emit_input_header(); emit_param("Env", "%s", V2R); emit_output_expected_header(); emit_retval("%s", V2R); emit_output_actual_header(); emit_retval("%s", actual->Value()); if(!strings_similar(actual->Value(), V2R)) { deleteStringArray(result); delete actual; FAIL; } deleteStringArray(result); delete actual; PASS; } static bool test_get_string_array_add() { emit_test("Test that getStringArray() returns the expected string array " "after adding environment variables with MergeFromV2Raw()."); Env env; env.MergeFromV2Raw(V2R_REP, NULL); char** result1 = env.getStringArray(); env.MergeFromV2Raw(V2R_ADD, NULL); char** result2 = env.getStringArray(); MyString* actual1 = convert_string_array(result1, 3); MyString* actual2 = convert_string_array(result2, 5); emit_input_header(); emit_param("Env", "%s", V2R_REP); emit_output_expected_header(); emit_param("String Array Before", "%s", V2R_REP); emit_param("String Array After", "%s", V2R_REP_ADD); emit_output_actual_header(); emit_param("String Array Before", "%s", actual1->Value()); emit_param("String Array After", "%s", actual2->Value()); if(!strings_similar(actual1->Value(), V2R_REP) || !(strings_similar(actual2->Value(), V2R_REP_ADD))) { deleteStringArray(result1); deleteStringArray(result2); delete actual1; delete actual2; FAIL; } deleteStringArray(result1); deleteStringArray(result2); delete actual1; delete actual2; PASS; } static bool test_get_string_array_replace() { emit_test("Test that getStringArray() returns the expected string array " "after replacing environment variables with MergeFromV2Raw()."); Env env; env.MergeFromV2Raw(V2R, NULL); char** result1 = env.getStringArray(); env.MergeFromV2Raw(V2R_REP, NULL); char** result2 = env.getStringArray(); MyString* actual1 = convert_string_array(result1, 3); MyString* actual2 = convert_string_array(result2, 3); emit_input_header(); emit_param("Env", "%s", V2R); emit_output_expected_header(); emit_param("String Array Before", "%s", V2R); emit_param("String Array After", "%s", V2R_REP); emit_output_actual_header(); emit_param("String Array Before", "%s", actual1->Value()); emit_param("String Array After", "%s", actual2->Value()); if(!strings_similar(actual1->Value(), V2R) || !(strings_similar(actual2->Value(), V2R_REP))) { deleteStringArray(result1); deleteStringArray(result2); delete actual1; delete actual2; FAIL; } deleteStringArray(result1); deleteStringArray(result2); delete actual1; delete actual2; PASS; } static bool test_get_string_array_add_replace() { emit_test("Test that getStringArray() returns the expected string array " "after adding and replacing environment variables with " "MergeFromV2Raw()."); Env env; env.MergeFromV2Raw(V2R, NULL); char** result1 = env.getStringArray(); env.MergeFromV2Raw(V2R_REP_ADD, NULL); char** result2 = env.getStringArray(); MyString* actual1 = convert_string_array(result1, 3); MyString* actual2 = convert_string_array(result2, 5); emit_input_header(); emit_param("Env", "%s", V2R); emit_output_expected_header(); emit_param("String Array Before", "%s", V2R); emit_param("String Array After", "%s", V2R_REP_ADD); emit_output_actual_header(); emit_param("String Array Before", "%s", actual1->Value()); emit_param("String Array After", "%s", actual2->Value()); if(!strings_similar(actual1->Value(), V2R) || !(strings_similar(actual2->Value(), V2R_REP_ADD))) { deleteStringArray(result1); deleteStringArray(result2); delete actual1; delete actual2; FAIL; } deleteStringArray(result1); deleteStringArray(result2); delete actual1; delete actual2; PASS; } static bool test_get_env_bool_return_empty_empty() { emit_test("Test that getEnv() returns false for an empty Env object when " "passed an empty variable and value."); Env env; bool expect = false; MyString val; const bool actual = env.GetEnv(EMPTY, val); emit_input_header(); emit_param("Env", "%s", ""); emit_param("Variable", "%s", EMPTY); emit_param("Value", "%s", val.Value()); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_get_env_bool_return_empty_not() { emit_test("Test that getEnv() returns false for an empty Env object when " "passed a non-existent variable."); Env env; MyString var("one"), val; bool expect = false; bool actual = env.GetEnv(var, val); emit_input_header(); emit_param("Env", "%s", ""); emit_param("Variable", "%s", var.Value()); emit_param("Value", "%s", val.Value()); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_get_env_bool_return_hit_one() { emit_test("Test that getEnv() returns true for an Env object when " "passed a correct variable."); Env env; env.MergeFromV2Raw(V2R, NULL); MyString var("one"), val("1"); bool expect = true; bool actual = env.GetEnv(var, val); emit_input_header(); emit_param("Env", "%s", V2R); emit_param("Variable", "%s", var.Value()); emit_param("Value", "%s", ""); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_get_env_bool_return_hit_all() { emit_test("Test that getEnv() returns true for an Env object when " "passed a correct variable name for each variable within the " "Env."); Env env; env.MergeFromV2Raw(V2R, NULL); MyString var1("one"), var2("two"), var3("three"), val1("1"), val2("2"), val3("3"); bool expect = true; bool actual = env.GetEnv(var1, val1) && env.GetEnv(var2, val2) && env.GetEnv(var3, val3); emit_input_header(); emit_param("Env", "%s", V2R); emit_param("Variable", "%s", var1.Value()); emit_param("Value", "%s", ""); emit_param("Variable", "%s", var2.Value()); emit_param("Value", "%s", ""); emit_param("Variable", "%s", var3.Value()); emit_param("Value", "%s", ""); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_get_env_bool_value_miss() { emit_test("Test that getEnv() doesn't change the value MyString when the " "variable does not exist."); Env env; env.MergeFromV2Raw(V2R, NULL); MyString var("miss"), val("1"); env.GetEnv(var, val); emit_input_header(); emit_param("Env", "%s", V2R); emit_param("Variable", "%s", var.Value()); emit_param("Value", "%s", "1"); emit_output_expected_header(); emit_param("Value", "%s", "1"); emit_output_actual_header(); emit_param("Value", "%s", val.Value()); if(val != "1") { FAIL; } PASS; } static bool test_get_env_bool_value_hit_one() { emit_test("Test that getEnv() sets the value MyString to the expected " "value for a variable that exists."); Env env; env.MergeFromV2Raw(V2R, NULL); MyString var("one"), val; env.GetEnv(var, val); emit_input_header(); emit_param("Env", "%s", V2R); emit_param("Variable", "%s", var.Value()); emit_param("Value", "%s", ""); emit_output_expected_header(); emit_param("Value", "%s", "1"); emit_output_actual_header(); emit_param("Value", "%s", val.Value()); if(val != "1") { FAIL; } PASS; } static bool test_get_env_bool_value_hit_all() { emit_test("Test that getEnv() sets the value MyString to the expected " "value for each variable within the Env."); Env env; env.MergeFromV2Raw(V2R, NULL); MyString var1("one"), var2("two"), var3("three"), val1, val2, val3, expect1("1"), expect2("2"), expect3("3"); env.GetEnv(var1, val1); env.GetEnv(var2, val2); env.GetEnv(var3, val3); emit_input_header(); emit_param("Env", "%s", V2R); emit_param("Variable", "%s", var1.Value()); emit_param("Value", "%s", ""); emit_param("Variable", "%s", var2.Value()); emit_param("Value", "%s", ""); emit_param("Variable", "%s", var3.Value()); emit_param("Value", "%s", ""); emit_output_expected_header(); emit_param("Value", "%s", expect1.Value()); emit_param("Value", "%s", expect2.Value()); emit_param("Value", "%s", expect3.Value()); emit_output_actual_header(); emit_param("Value", "%s", val1.Value()); emit_param("Value", "%s", val2.Value()); emit_param("Value", "%s", val3.Value()); if(val1 != expect1 || val2 != expect2 || val3 != expect3) { FAIL; } PASS; } static bool test_is_safe_env_v1_value_false_null() { emit_test("Test that IsSafeEnvV1Value() returns false for a NULL " "string."); Env env; bool expect = false; bool actual = env.IsSafeEnvV1Value(NULL); emit_input_header(); emit_param("STRING", "%s", "NULL"); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_is_safe_env_v1_value_false_semi() { emit_test("Test that IsSafeEnvV1Value() returns false for a string " "with a semicolon."); Env env; bool expect = false; bool actual = env.IsSafeEnvV1Value("semi=" V1_ENV_DELIM); emit_input_header(); emit_param("STRING", "%s", "semi=" V1_ENV_DELIM); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_is_safe_env_v1_value_false_newline() { emit_test("Test that IsSafeEnvV1Value() returns false for a string " "with a newline character."); Env env; bool expect = false; bool actual = env.IsSafeEnvV1Value("newline=\n"); emit_input_header(); emit_param("STRING", "%s", "newline=\n"); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_is_safe_env_v1_value_false_param() { emit_test("Test that IsSafeEnvV1Value() returns false for a string " "with the passed delimiter."); Env env; bool expect = false; bool actual = env.IsSafeEnvV1Value("star=*", '*'); emit_input_header(); emit_param("STRING", "%s", "star=*"); emit_param("CHAR", "%c", '*'); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_is_safe_env_v1_value_true_one() { emit_test("Test that IsSafeEnvV1Value() returns true for a valid V1 " "format string."); Env env; bool expect = true; bool actual = env.IsSafeEnvV1Value(ONE); emit_input_header(); emit_param("STRING", "%s", ONE); emit_param("CHAR", "%c", '*'); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_is_safe_env_v1_value_true_quotes() { emit_test("Test that IsSafeEnvV1Value() returns true for a string " "surrounded in quotes."); Env env; bool expect = true; bool actual = env.IsSafeEnvV1Value("\"one=1\""); emit_input_header(); emit_param("STRING", "%s", "\"one=1\""); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_is_safe_env_v2_value_false_null() { emit_test("Test that IsSafeEnvV2Value() returns false for a NULL " "string."); Env env; bool expect = false; bool actual = env.IsSafeEnvV2Value(NULL); emit_input_header(); emit_param("STRING", "%s", "NULL"); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_is_safe_env_v2_value_false_newline() { emit_test("Test that IsSafeEnvV2Value() returns false for a string with " "a newline character."); Env env; bool expect = false; bool actual = env.IsSafeEnvV2Value("newline=\n"); emit_input_header(); emit_param("STRING", "%s", "newline=\""); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_is_safe_env_v2_value_true_one() { emit_test("Test that IsSafeEnvV2Value() returns true for a valid V2 " "format string with only one environment variable."); Env env; bool expect = true; bool actual = env.IsSafeEnvV2Value(ONE); emit_input_header(); emit_param("STRING", "%s", ONE); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_is_safe_env_v2_value_true_many() { emit_test("Test that IsSafeEnvV2Value() returns true for a valid V2 " "format string with many environment variables."); Env env; bool expect = true; bool actual = env.IsSafeEnvV2Value(V2R_SEMI); emit_input_header(); emit_param("STRING", "%s", V2R_SEMI); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_get_env_v1_delim_param_winnt() { emit_test("Test that GetEnvV1Delimiter() returns a '|' for an Env " "when passed a string beginning with \"WINNT\"."); Env env; char expect = '|'; char actual = env.GetEnvV1Delimiter("WINNT"); emit_input_header(); emit_param("Env", "%s", ""); emit_param("STRING", "%s", "WINNT"); emit_output_expected_header(); emit_retval("%c", expect); emit_output_actual_header(); emit_retval("%c", actual); if(actual != expect) { FAIL; } PASS; } static bool test_get_env_v1_delim_param_win32() { emit_test("Test that GetEnvV1Delimiter() returns a '|' for an Env " "when passed a string beginning with \"WIN32\"."); Env env; char expect = '|'; char actual = env.GetEnvV1Delimiter("WIN32"); emit_input_header(); emit_param("Env", "%s", ""); emit_param("STRING", "%s", "WIN32"); emit_output_expected_header(); emit_retval("%c", expect); emit_output_actual_header(); emit_retval("%c", actual); if(actual != expect) { FAIL; } PASS; } static bool test_get_env_v1_delim_param_unix() { emit_test("Test that GetEnvV1Delimiter() returns a semicolon for an Env " "when passed a string beginning with \"UNIX\"."); Env env; char expect = ';'; char actual = env.GetEnvV1Delimiter("UNIX"); emit_input_header(); emit_param("Env", "%s", ""); emit_param("STRING", "%s", "UNIX"); emit_output_expected_header(); emit_retval("%c", expect); emit_output_actual_header(); emit_retval("%c", actual); if(actual != expect) { FAIL; } PASS; } static bool test_is_v2_quoted_string_false_v1() { emit_test("Test that IsV2QuotedString() returns false for a V1 format " "string that doesn't begin or end with quotes."); bool expect = false; bool actual = Env::IsV2QuotedString(V1R); emit_input_header(); emit_param("STRING", "%s", V1R); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_is_v2_quoted_string_false_v2() { emit_test("Test that IsV2QuotedString() returns false for a V2 format " "string that doesn't begin or end with quotes."); bool expect = false; bool actual = Env::IsV2QuotedString(V2R); emit_input_header(); emit_param("STRING", "%s", V2R); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_is_v2_quoted_string_true() { emit_test("Test that IsV2QuotedString() returns true for a V2 format " "string that begins and ends with quotes."); bool expect = true; bool actual = Env::IsV2QuotedString(V2Q); emit_input_header(); emit_param("STRING", "%s", V2Q); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_v2_quoted_to_v2_raw_return_false_miss_end() { emit_test("Test that V2QuotedToV2Raw() returns false for an invalid V2 " "quoted string due to missing quotes at the end."); MyString result, error; bool expect = false; bool actual = Env::V2QuotedToV2Raw(V2Q_MISS_END, &result, &error); emit_input_header(); emit_param("STRING", "%s", V2Q_MISS_END); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_v2_quoted_to_v2_raw_return_false_trail() { emit_test("Test that V2QuotedToV2Raw() returns false for an invalid V2 " "quoted string due to trailing characters after the quotes."); MyString result, error; bool expect = false; bool actual = Env::V2QuotedToV2Raw(V2Q_TRAIL, &result, &error); emit_input_header(); emit_param("STRING", "%s", V2Q_TRAIL); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_v2_quoted_to_v2_raw_return_true() { emit_test("Test that V2QuotedToV2Raw() returns true for a valid V2 " "quoted string."); MyString result, error; bool expect = true; bool actual = Env::V2QuotedToV2Raw(V2Q, &result, &error); emit_input_header(); emit_param("STRING", "%s", V2Q); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_v2_quoted_to_v2_raw_return_true_semi() { emit_test("Test that V2QuotedToV2Raw() returns true for a V2 " "quoted string that uses a semicolon as a delimiter."); MyString result, error; bool expect = true; bool actual = Env::V2QuotedToV2Raw(V2Q_DELIM_SEMI, &result, &error); emit_input_header(); emit_param("STRING", "%s", V2Q_DELIM_SEMI); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_v2_quoted_to_v2_raw_error_miss_end() { emit_test("Test that V2QuotedToV2Raw() sets an error message for an " "invalid V2 quoted string due to missing quotes at the end."); emit_comment("This test just checks if the error message is not empty."); MyString result, error; Env::V2QuotedToV2Raw(V2Q_MISS_END, &result, &error); emit_input_header(); emit_param("STRING", "%s", V2Q_MISS_END); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_actual_header(); emit_param("Error MyString", "%s", error.Value()); if(error.IsEmpty()) { FAIL; } PASS; } static bool test_v2_quoted_to_v2_raw_error_trail() { emit_test("Test that V2QuotedToV2Raw() sets an error message for an " "invalid V2 quoted string due to trailing characters after the " "quotes."); emit_comment("This test just checks if the error message is not empty."); MyString result, error; Env::V2QuotedToV2Raw(V2Q_TRAIL, &result, &error); emit_input_header(); emit_param("STRING", "%s", V2Q_TRAIL); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_actual_header(); emit_param("Error MyString", "%s", error.Value()); if(error.IsEmpty()) { FAIL; } PASS; } static bool test_v2_quoted_to_v2_raw_result() { emit_test("Test that V2QuotedToV2Raw() sets the result MyString to the " "expected value for a valid V2 quoted string."); MyString result, error; Env::V2QuotedToV2Raw(V2Q, &result, &error); emit_input_header(); emit_param("STRING", "%s", V2Q); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_param("Result MyString", "%s", V2R); emit_output_actual_header(); emit_param("Result MyString", "%s", result.Value()); if(!strings_similar(result.Value(), V2R)) { FAIL; } PASS; } static bool test_v2_quoted_to_v2_raw_result_semi() { emit_test("Test that V2QuotedToV2Raw() sets the result MyString to the " "expected value for a V2 quoted string that uses a semicolon as a " "delimiter."); MyString result, error; Env::V2QuotedToV2Raw(V2Q_DELIM_SEMI, &result, &error); emit_input_header(); emit_param("STRING", "%s", V2Q_DELIM_SEMI); emit_param("MyString", "%s", ""); emit_param("MyString", "%s", ""); emit_output_expected_header(); emit_param("Result MyString", "%s", V1R); emit_output_actual_header(); emit_param("Result MyString", "%s", result.Value()); if(!strings_similar(result.Value(), V1R, V1_ENV_DELIM)) { FAIL; } PASS; } static bool test_input_was_v1_false_empty() { emit_test("Test that InputWasV1() returns false for an empty Env " "object."); Env env; bool expect = false; bool actual = env.InputWasV1(); emit_input_header(); emit_param("Env", "%s", ""); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_input_was_v1_false_v2q_or() { emit_test("Test that InputWasV1() returns false for an Env object " "created from a V2Quoted string with MergeFromV1RawOrV2Quoted()."); Env env; env.MergeFromV1RawOrV2Quoted(V2Q, NULL); bool expect = false; bool actual = env.InputWasV1(); emit_input_header(); emit_param("Env", "%s", V2Q); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_input_was_v1_false_v2q() { emit_test("Test that InputWasV1() returns false for an Env object " "created from a V2Quoted string with MergeFromV2Quoted()."); Env env; env.MergeFromV2Quoted(V2Q, NULL); bool expect = false; bool actual = env.InputWasV1(); emit_input_header(); emit_param("Env", "%s", V2Q); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_input_was_v1_false_v2r_or() { emit_test("Test that InputWasV1() returns false for an Env object " "created from a V2Raw string with MergeFromV1or2Raw()."); Env env; env.MergeFromV1or2Raw(V2R_MARK, NULL); bool expect = false; bool actual = env.InputWasV1(); emit_input_header(); emit_param("Env", "%s", V2R_MARK); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_input_was_v1_false_v2r() { emit_test("Test that InputWasV1() returns false for an Env object " "created from a V2Raw string with MergeFromV2Raw()."); Env env; env.MergeFromV2Raw(V2R, NULL); bool expect = false; bool actual = env.InputWasV1(); emit_input_header(); emit_param("Env", "%s", V2R); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_input_was_v1_false_array() { emit_test("Test that InputWasV1() returns false for an Env object " "created from a string array with MergeFrom()."); Env env; env.MergeFrom(ARRAY); bool expect = false; bool actual = env.InputWasV1(); emit_input_header(); emit_param("Env", "%s", V2R); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_input_was_v1_false_str() { emit_test("Test that InputWasV1() returns false for an Env object " "created from a string with MergeFrom()."); Env env; env.MergeFrom(V2R); bool expect = false; bool actual = env.InputWasV1(); emit_input_header(); emit_param("Env", "%s", V2R); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_input_was_v1_false_env() { emit_test("Test that InputWasV1() returns false for an Env object " "created from another Env object with MergeFrom()."); Env env1, env2; env2.MergeFromV2Raw(V2R, NULL); env1.MergeFrom(env2); bool expect = false; bool actual = env2.InputWasV1(); emit_input_header(); emit_param("Env", "%s", V2R); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_input_was_v1_false_ad() { emit_test("Test that InputWasV1() returns false for an Env object " "created from a ClassAd that uses a V2 environment with MergeFrom()."); ClassAd classad; initAdFromString(AD_V2, classad); Env env; env.MergeFrom(&classad, NULL); bool expect = false; bool actual = env.InputWasV1(); emit_input_header(); emit_param("ClassAd", "%s", AD_V2); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_input_was_v1_true_v1r_or() { emit_test("Test that InputWasV1() returns true for an Env object " "created from V1Raw string that with MergeFromV1RawOrV2Quoted()."); Env env; env.MergeFromV1RawOrV2Quoted(V1R, NULL); bool expect = true; bool actual = env.InputWasV1(); emit_input_header(); emit_param("ClassAd", "%s", V1R); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_input_was_v1_true_v1r() { emit_test("Test that InputWasV1() returns true for an Env object " "created from V1Raw string that with MergeFromV1Raw()."); Env env; env.MergeFromV1Raw(V1R, NULL); bool expect = true; bool actual = env.InputWasV1(); emit_input_header(); emit_param("ClassAd", "%s", V1R); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; } static bool test_input_was_v1_true_ad() { emit_test("Test that InputWasV1() returns true for an Env object " "created from a ClassAd that uses a V1 environment with MergeFrom()."); ClassAd classad; initAdFromString(AD_V1, classad); Env env; env.MergeFrom(&classad, NULL); bool expect = true; bool actual = env.InputWasV1(); emit_input_header(); emit_param("ClassAd", "%s", AD_V1); emit_output_expected_header(); emit_retval("%s", tfstr(expect)); emit_output_actual_header(); emit_retval("%s", tfstr(actual)); if(actual != expect) { FAIL; } PASS; }
32.326485
136
0.738204
[ "object" ]
298120e23e41e32b12f20af321eae9d4f091806c
9,782
cpp
C++
Source/Raymarcher/Private/Rendering/LightingShaderUtils.cpp
combatdave/TBRaymarcherPlugin
3b7334fd58274b5f62372a90ee5a5067db230a79
[ "MIT" ]
29
2021-03-15T04:05:11.000Z
2022-03-22T22:23:06.000Z
Source/Raymarcher/Private/Rendering/LightingShaderUtils.cpp
combatdave/TBRaymarcherPlugin
3b7334fd58274b5f62372a90ee5a5067db230a79
[ "MIT" ]
null
null
null
Source/Raymarcher/Private/Rendering/LightingShaderUtils.cpp
combatdave/TBRaymarcherPlugin
3b7334fd58274b5f62372a90ee5a5067db230a79
[ "MIT" ]
10
2021-09-02T20:18:41.000Z
2022-03-17T13:27:55.000Z
#include "Rendering/LightingShaderUtils.h" FString GetDirectionName(FCubeFace Face) { switch (Face) { case FCubeFace::XPositive: return FString("+X"); case FCubeFace::XNegative: return FString("-X"); case FCubeFace::YPositive: return FString("+Y"); case FCubeFace::YNegative: return FString("-Y"); case FCubeFace::ZPositive: return FString("+Z"); case FCubeFace::ZNegative: return FString("-Z"); default: return FString("Something went wrong here!"); } } bool SortDescendingWeights(const std::pair<FCubeFace, float>& a, const std::pair<FCubeFace, float>& b) { return (a.second > b.second); } FMajorAxes FMajorAxes::GetMajorAxes(FVector LightPos) { FMajorAxes RetVal; std::vector<std::pair<FCubeFace, float>> faceVector; for (int i = 0; i < 6; i++) { // Dot of position and face normal yields cos(angle) float weight = FVector::DotProduct(FCubeFaceNormals[i], LightPos); // Need to make sure we go along the axis with a positive weight, not negative. weight = (weight > 0 ? weight * weight : 0); RetVal.FaceWeight.push_back(std::make_pair(FCubeFace(i), weight)); } // Sort so that the 3 major axes are the first. std::sort(RetVal.FaceWeight.begin(), RetVal.FaceWeight.end(), SortDescendingWeights); return RetVal; } FIntVector GetTransposedDimensions(const FMajorAxes& Axes, const FRHITexture3D* VolumeRef, const unsigned index) { FCubeFace face = Axes.FaceWeight[index].first; unsigned axis = (uint8) face / 2; switch (axis) { case 0: // going along X -> Volume Y = x, volume Z = y return FIntVector(VolumeRef->GetSizeY(), VolumeRef->GetSizeZ(), VolumeRef->GetSizeX()); case 1: // going along Y -> Volume X = x, volume Z = y return FIntVector(VolumeRef->GetSizeX(), VolumeRef->GetSizeZ(), VolumeRef->GetSizeY()); case 2: // going along Z -> Volume X = x, volume Y = y return FIntVector(VolumeRef->GetSizeX(), VolumeRef->GetSizeY(), VolumeRef->GetSizeZ()); default: check(false); return FIntVector(0, 0, 0); } } int GetAxisDirection(const FMajorAxes& Axes, unsigned index) { // All even axis number are going down on their respective axes. return (((uint8) Axes.FaceWeight[index].first) % 2 ? 1 : -1); } OneAxisReadWriteBufferResources& GetBuffers( const FMajorAxes& Axes, const unsigned index, FBasicRaymarchRenderingResources& InParams) { FCubeFace Face = Axes.FaceWeight[index].first; unsigned FaceAxis = (uint8) Face / 2; return InParams.XYZReadWriteBuffers[FaceAxis]; } /// Returns the UV offset to the previous layer. This is the position in the previous layer that is in the direction of the light. FVector2D GetUVOffset(FCubeFace Axis, FVector LightPosition, FIntVector TransposedDimensions) { FVector normLightPosition = LightPosition; // Normalize the light position to get the major axis to be one. The other 2 components are then // an offset to apply to current pos to read from our read buffer texture. FVector2D RetVal; switch (Axis) { case FCubeFace::XPositive: // +X normLightPosition /= normLightPosition.X; RetVal = FVector2D(normLightPosition.Y, normLightPosition.Z); break; case FCubeFace::XNegative: // -X normLightPosition /= -normLightPosition.X; RetVal = FVector2D(normLightPosition.Y, normLightPosition.Z); break; case FCubeFace::YPositive: // +Y normLightPosition /= normLightPosition.Y; RetVal = FVector2D(normLightPosition.X, normLightPosition.Z); break; case FCubeFace::YNegative: // -Y normLightPosition /= -normLightPosition.Y; RetVal = FVector2D(normLightPosition.X, normLightPosition.Z); break; case FCubeFace::ZPositive: // +Z normLightPosition /= normLightPosition.Z; RetVal = FVector2D(normLightPosition.X, normLightPosition.Y); break; case FCubeFace::ZNegative: // -Z normLightPosition /= -normLightPosition.Z; RetVal = FVector2D(normLightPosition.X, normLightPosition.Y); break; default: { check(false); return FVector2D(0, 0); }; } // Now normalize for different voxel sizes. Because we have Transposed Dimensions as input, we // know that we're propagating along TD.Z, The X-size of the buffer is in TD.X and Y-size of the // buffer is in TD.Y //// Divide by length of step RetVal /= TransposedDimensions.Z; return RetVal; } void GetStepSizeAndUVWOffset(FCubeFace Axis, FVector LightPosition, FIntVector TransposedDimensions, const FRaymarchWorldParameters WorldParameters, float& OutStepSize, FVector& OutUVWOffset) { OutUVWOffset = LightPosition; // Since we don't care about the direction, just the size, ignore signs. switch (Axis) { case FCubeFace::XPositive: // +-X case FCubeFace::XNegative: OutUVWOffset /= abs(LightPosition.X) * TransposedDimensions.Z; break; case FCubeFace::YPositive: // +-Y case FCubeFace::YNegative: OutUVWOffset /= abs(LightPosition.Y) * TransposedDimensions.Z; break; case FCubeFace::ZPositive: // +-Z case FCubeFace::ZNegative: OutUVWOffset /= abs(LightPosition.Z) * TransposedDimensions.Z; break; default: check(false); ; } // Multiply StepSize by fixed volume density. OutStepSize = OutUVWOffset.Size(); } void GetLocalLightParamsAndAxes(const FDirLightParameters& LightParameters, const FTransform& VolumeTransform, FDirLightParameters& OutLocalLightParameters, FMajorAxes& OutLocalMajorAxes) { // #TODO Why the fuck does light direction need NoScale and no multiplication by scale and clipping // plane needs to be multiplied? // Transform light directions into local space. OutLocalLightParameters.LightDirection = VolumeTransform.InverseTransformVector(LightParameters.LightDirection); // Normalize Light Direction to get unit length. OutLocalLightParameters.LightDirection.Normalize(); // Intensity is the same in local space -> copy. OutLocalLightParameters.LightIntensity = LightParameters.LightIntensity; // Get Major Axes (notice inverting of light Direction - for a directional light, the position of // the light is the opposite of the direction) e.g. Directional light with direction (1, 0, 0) is // assumed to be shining from (-1, 0, 0) OutLocalMajorAxes = FMajorAxes::GetMajorAxes(-OutLocalLightParameters.LightDirection); // Prevent near-zero bugs in the shader (if first axis is very, very dominant, the secondary axis offsets are giant // and they just read out of bounds all the time. if (OutLocalMajorAxes.FaceWeight[0].second > 0.99f) { OutLocalMajorAxes.FaceWeight[0].second = 1.0f; } // Set second axis weight to (1 - (first axis weight)) OutLocalMajorAxes.FaceWeight[1].second = 1 - OutLocalMajorAxes.FaceWeight[0].second; } FSamplerStateRHIRef GetBufferSamplerRef(uint32 BorderColorInt) { // Return a sampler for RW buffers - bordered by specified color. return RHICreateSamplerState( FSamplerStateInitializerRHI(SF_Bilinear, AM_Border, AM_Border, AM_Border, 0, 0, 0, 1, BorderColorInt)); } uint32 GetBorderColorIntSingle(FDirLightParameters LightParams, FMajorAxes MajorAxes, unsigned index) { // Set alpha channel to the texture's red channel (when reading single-channel, only red component // is read) FLinearColor LightColor = FLinearColor(LightParams.LightIntensity * MajorAxes.FaceWeight[index].second, 0.0, 0.0, 0.0); return LightColor.ToFColor(true).ToPackedARGB(); } FClippingPlaneParameters GetLocalClippingParameters(const FRaymarchWorldParameters WorldParameters) { FClippingPlaneParameters RetVal; // Get clipping center to (0-1) texture local space. (Invert transform, add 0.5 to get to (0-1) // space of a unit cube centered on 0,0,0) RetVal.Center = WorldParameters.VolumeTransform.InverseTransformPosition(WorldParameters.ClippingPlaneParameters.Center) + 0.5; // Get clipping direction in local space // TODO Why the hell does light direction work with regular InverseTransformVector // but clipping direction only works with NoScale and multiplying by scale afterwards? RetVal.Direction = WorldParameters.VolumeTransform.InverseTransformVectorNoScale(WorldParameters.ClippingPlaneParameters.Direction); RetVal.Direction *= WorldParameters.VolumeTransform.GetScale3D(); RetVal.Direction.Normalize(); return RetVal; } float GetLightAlpha(FDirLightParameters LightParams, FMajorAxes MajorAxes, unsigned index) { return LightParams.LightIntensity * MajorAxes.FaceWeight[index].second; } FMatrix GetPermutationMatrix(FMajorAxes MajorAxes, unsigned index) { uint8 Axis = (uint8) MajorAxes.FaceWeight[index].first / 2; FMatrix retVal; retVal.SetIdentity(); FVector xVec(1, 0, 0); FVector yVec(0, 1, 0); FVector zVec(0, 0, 1); switch (Axis) { case 0: // X Axis retVal.SetAxes(&yVec, &zVec, &xVec); break; case 1: // Y Axis retVal.SetAxes(&xVec, &zVec, &yVec); break; case 2: // We keep identity set... default: break; } return retVal; } void GetLoopStartStopIndexes( int& OutStart, int& OutStop, int& OutAxisDirection, const FMajorAxes& MajorAxes, const unsigned& index, const int zDimension) { OutAxisDirection = GetAxisDirection(MajorAxes, index); if (OutAxisDirection == -1) { OutStart = zDimension - 1; OutStop = -1; // We want to go all the way to zero, so stop at -1 } else { OutStart = 0; OutStop = zDimension; // want to go to Z - 1, so stop at Z } } void TransitionBufferResources( FRHICommandListImmediate& RHICmdList, FRHITexture* NewlyReadableTexture, FRHIUnorderedAccessView* NewlyWriteableUAV) { // RHICmdList.Transition(FRHITransitionInfo(NewlyReadableTexture, ERHIAccess::UAVGraphics, ERHIAccess::UAVCompute)); // // RHICmdList.TransitionResource(EResourceTransitionAccess::EReadable, NewlyReadableTexture); // RHICmdList.TransitionResource( // EResourceTransitionAccess::EWritable, EResourceTransitionPipeline::EComputeToCompute, NewlyWriteableUAV); }
35.442029
131
0.746575
[ "vector", "transform" ]
2984802964b2618e769ffa46e4202c7c86a68121
1,416
cpp
C++
src/prod/src/ServiceModel/management/FileStoreService/uploadsession.cpp
gridgentoo/ServiceFabricAzure
c3e7a07617e852322d73e6cc9819d266146866a4
[ "MIT" ]
2,542
2018-03-14T21:56:12.000Z
2019-05-06T01:18:20.000Z
src/prod/src/ServiceModel/management/FileStoreService/uploadsession.cpp
gridgentoo/ServiceFabricAzure
c3e7a07617e852322d73e6cc9819d266146866a4
[ "MIT" ]
994
2019-05-07T02:39:30.000Z
2022-03-31T13:23:04.000Z
src/prod/src/ServiceModel/management/FileStoreService/uploadsession.cpp
gridgentoo/ServiceFabricAzure
c3e7a07617e852322d73e6cc9819d266146866a4
[ "MIT" ]
300
2018-03-14T21:57:17.000Z
2019-05-06T20:07:00.000Z
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" using namespace std; using namespace Common; using namespace Management::FileStoreService; UploadSession::UploadSession() : uploadSessions_() { } UploadSession::UploadSession( std::vector<UploadSessionInfo> const & uploadSessions) : uploadSessions_(uploadSessions) { } UploadSession& UploadSession::operator = (UploadSession const & other) { if (this != &other) { this->uploadSessions_ = other.uploadSessions_; } return *this; } UploadSession& UploadSession::operator = (std::vector<UploadSessionInfo> const & session) { this->uploadSessions_ = session; return *this; } UploadSession& UploadSession::operator = (UploadSession && other) { if (this != &other) { this->uploadSessions_ = move(other.uploadSessions_); } return *this; } UploadSession& UploadSession::operator = (std::vector<UploadSessionInfo> && session) { this->uploadSessions_ = std::move(session); return *this; } void UploadSession::WriteTo(TextWriter & w, FormatOptions const &) const { w.Write("UploadSessionCount={0}", this->uploadSessions_.size()); }
24
98
0.644068
[ "vector" ]
29851d342fcb2c4f2ecf64d53309221d9060b21c
9,704
cpp
C++
sparse/control/magma_zmgenerator.cpp
klast/magma
cfb849621be6f697288e995831ec3c9e84530d9d
[ "BSD-3-Clause" ]
4
2020-12-04T13:31:18.000Z
2021-12-10T11:41:23.000Z
sparse/control/magma_zmgenerator.cpp
klast/magma
cfb849621be6f697288e995831ec3c9e84530d9d
[ "BSD-3-Clause" ]
1
2021-03-27T20:00:25.000Z
2021-03-28T06:19:59.000Z
sparse/control/magma_zmgenerator.cpp
klast/magma
cfb849621be6f697288e995831ec3c9e84530d9d
[ "BSD-3-Clause" ]
2
2020-12-04T13:23:36.000Z
2021-03-27T00:50:27.000Z
/* -- MAGMA (version 2.5.4) -- Univ. of Tennessee, Knoxville Univ. of California, Berkeley Univ. of Colorado, Denver @date October 2020 @precisions normal z -> s d c @author Hartwig Anzt */ #include "magmasparse_internal.h" /** Purpose ------- Generate a symmetric n x n CSR matrix for a stencil. Arguments --------- @param[in] n magma_int_t number of rows @param[in] offdiags magma_int_t number of offdiagonals @param[in] diag_offset magma_int_t* array containing the offsets (length offsets+1) @param[in] diag_vals magmaDoubleComplex* array containing the values (length offsets+1) @param[out] A magma_z_matrix* matrix to generate @param[in] queue magma_queue_t Queue to execute in. @ingroup magmasparse_zaux ********************************************************************/ extern "C" magma_int_t magma_zmgenerator( magma_int_t n, magma_int_t offdiags, magma_index_t *diag_offset, magmaDoubleComplex *diag_vals, magma_z_matrix *A, magma_queue_t queue ) { magma_int_t info = 0; magma_z_matrix B={Magma_CSR}; B.val = NULL; B.col = NULL; B.row = NULL; B.rowidx = NULL; B.blockinfo = NULL; B.diag = NULL; B.dval = NULL; B.dcol = NULL; B.drow = NULL; B.drowidx = NULL; B.ddiag = NULL; B.list = NULL; B.dlist = NULL; B.num_rows = n; B.num_cols = n; B.fill_mode = MagmaFull; B.memory_location = Magma_CPU; B.storage_type = Magma_ELLPACKT; B.max_nnz_row = (2*offdiags+1); CHECK( magma_zmalloc_cpu( &B.val, B.max_nnz_row*n )); CHECK( magma_index_malloc_cpu( &B.col, B.max_nnz_row*n )); for( int i=0; i<n; i++ ) { // stride over rows // stride over the number of nonzeros in each row // left of diagonal for( int j=0; j<offdiags; j++ ) { B.val[ i*B.max_nnz_row + j ] = diag_vals[ offdiags - j ]; B.col[ i*B.max_nnz_row + j ] = -1 * diag_offset[ offdiags-j ] + i; } // elements on the diagonal B.val[ i*B.max_nnz_row + offdiags ] = diag_vals[ 0 ]; B.col[ i*B.max_nnz_row + offdiags ] = i; // right of diagonal for( int j=0; j<offdiags; j++ ) { B.val[ i*B.max_nnz_row + j + offdiags +1 ] = diag_vals[ j+1 ]; B.col[ i*B.max_nnz_row + j + offdiags +1 ] = diag_offset[ j+1 ] + i; } } // set invalid entries to zero for( int i=0; i<n; i++ ) { // stride over rows for( int j=0; j<B.max_nnz_row; j++ ) { // nonzeros in every row if ( (B.col[i*B.max_nnz_row + j] < 0) || (B.col[i*B.max_nnz_row + j] >= n) ) { B.val[ i*B.max_nnz_row + j ] = MAGMA_Z_MAKE( 0.0, 0.0 ); } } } B.nnz = 0; for( int i=0; i<n; i++ ) { // stride over rows for( int j=0; j<B.max_nnz_row; j++ ) { // nonzeros in every row if ( MAGMA_Z_REAL( B.val[i*B.max_nnz_row + j]) != 0.0 ) B.nnz++; } } B.true_nnz = B.nnz; // converting it to CSR will remove the invalit entries completely CHECK( magma_zmconvert( B, A, Magma_ELLPACKT, Magma_CSR, queue )); cleanup: if( info != 0 ){ magma_zmfree( &B, queue ); } return info; } /** Purpose ------- Generate a 27-point stencil for a 3D FD discretization. Arguments --------- @param[in] n magma_int_t number of rows @param[out] A magma_z_matrix* matrix to generate @param[in] queue magma_queue_t Queue to execute in. @ingroup magmasparse_zaux ********************************************************************/ extern "C" magma_int_t magma_zm_27stencil( magma_int_t n, magma_z_matrix *A, magma_queue_t queue ) { magma_int_t info = 0; magma_int_t i,j,k; magma_z_matrix hA={Magma_CSR}; // generate matrix of desired structure and size (3d 27-point stencil) magma_int_t nn = n*n*n; magma_int_t offdiags = 13; magma_index_t *diag_offset=NULL; magmaDoubleComplex *diag_vals=NULL; CHECK( magma_zmalloc_cpu( &diag_vals, offdiags+1 )); CHECK( magma_index_malloc_cpu( &diag_offset, offdiags+1 )); diag_offset[0] = 0; diag_offset[1] = 1; diag_offset[2] = n-1; diag_offset[3] = n; diag_offset[4] = n+1; diag_offset[5] = n*n-n-1; diag_offset[6] = n*n-n; diag_offset[7] = n*n-n+1; diag_offset[8] = n*n-1; diag_offset[9] = n*n; diag_offset[10] = n*n+1; diag_offset[11] = n*n+n-1; diag_offset[12] = n*n+n; diag_offset[13] = n*n+n+1; diag_vals[0] = MAGMA_Z_MAKE( 26.0, 0.0 ); diag_vals[1] = MAGMA_Z_MAKE( -1.0, 0.0 ); diag_vals[2] = MAGMA_Z_MAKE( -1.0, 0.0 ); diag_vals[3] = MAGMA_Z_MAKE( -1.0, 0.0 ); diag_vals[4] = MAGMA_Z_MAKE( -1.0, 0.0 ); diag_vals[5] = MAGMA_Z_MAKE( -1.0, 0.0 ); diag_vals[6] = MAGMA_Z_MAKE( -1.0, 0.0 ); diag_vals[7] = MAGMA_Z_MAKE( -1.0, 0.0 ); diag_vals[8] = MAGMA_Z_MAKE( -1.0, 0.0 ); diag_vals[9] = MAGMA_Z_MAKE( -1.0, 0.0 ); diag_vals[10] = MAGMA_Z_MAKE( -1.0, 0.0 ); diag_vals[11] = MAGMA_Z_MAKE( -1.0, 0.0 ); diag_vals[12] = MAGMA_Z_MAKE( -1.0, 0.0 ); diag_vals[13] = MAGMA_Z_MAKE( -1.0, 0.0 ); CHECK( magma_zmgenerator( nn, offdiags, diag_offset, diag_vals, &hA, queue )); // now set some entries to zero (boundary...) for( i=0; i < n*n; i++ ) { for( j=0; j < n; j++ ) { magma_index_t row = i*n+j; for( k=hA.row[row]; k<hA.row[row+1]; k++) { if ((hA.col[k] == row-1 || hA.col[k] == row-n-1 || hA.col[k] == row+n-1 || hA.col[k] == row-n*n+n-1 || hA.col[k] == row+n*n-n-1 || hA.col[k] == row-n*n-1 || hA.col[k] == row+n*n-1 || hA.col[k] == row-n*n-n-1 || hA.col[k] == row+n*n+n-1 ) && (row+1)%n == 1 ) hA.val[k] = MAGMA_Z_MAKE( 0.0, 0.0 ); if ((hA.col[k] == row+1 || hA.col[k] == row-n+1 || hA.col[k] == row+n+1 || hA.col[k] == row-n*n+n+1 || hA.col[k] == row+n*n-n+1 || hA.col[k] == row-n*n+1 || hA.col[k] == row+n*n+1 || hA.col[k] == row-n*n-n+1 || hA.col[k] == row+n*n+n+1 ) && (row)%n ==n-1 ) hA.val[k] = MAGMA_Z_MAKE( 0.0, 0.0 ); } } } hA.true_nnz = hA.nnz; if (A->ownership) { magma_zmfree( A, queue ); } A->ownership = MagmaTrue; CHECK( magma_zmconvert( hA, A, Magma_CSR, Magma_CSR, queue )); cleanup: magma_free_cpu( diag_vals ); magma_free_cpu( diag_offset ); magma_zmfree( &hA, queue ); return info; } /** Purpose ------- Generate a 5-point stencil for a 2D FD discretization. Arguments --------- @param[in] n magma_int_t number of rows @param[out] A magma_z_matrix* matrix to generate @param[in] queue magma_queue_t Queue to execute in. @ingroup magmasparse_zaux ********************************************************************/ extern "C" magma_int_t magma_zm_5stencil( magma_int_t n, magma_z_matrix *A, magma_queue_t queue ) { magma_int_t info = 0; magma_int_t i,j,k; magma_z_matrix hA={Magma_CSR}; // generate matrix of desired structure and size (2d 5-point stencil) magma_int_t nn = n*n; magma_int_t offdiags = 2; magma_index_t *diag_offset=NULL; magmaDoubleComplex *diag_vals=NULL; CHECK( magma_zmalloc_cpu( &diag_vals, offdiags+1 )); CHECK( magma_index_malloc_cpu( &diag_offset, offdiags+1 )); magma_zmfree( A, queue ); A->ownership = MagmaTrue; diag_offset[0] = 0; diag_offset[1] = 1; diag_offset[2] = n; #define COMPLEX #ifdef COMPLEX // complex case diag_vals[0] = MAGMA_Z_MAKE( 4.0, 4.0 ); diag_vals[1] = MAGMA_Z_MAKE( -1.0, -1.0 ); diag_vals[2] = MAGMA_Z_MAKE( -1.0, -1.0 ); #else // real case diag_vals[0] = MAGMA_Z_MAKE( 4.0, 0.0 ); diag_vals[1] = MAGMA_Z_MAKE( -1.0, 0.0 ); diag_vals[2] = MAGMA_Z_MAKE( -1.0, 0.0 ); #endif CHECK( magma_zmgenerator( nn, offdiags, diag_offset, diag_vals, &hA, queue )); // now set some entries to zero (boundary...) for( i=0; i<n; i++ ) { for( j=0; j<n; j++ ) { magma_index_t row = i*n+j; for( k=hA.row[row]; k<hA.row[row+1]; k++) { if ((hA.col[k] == row-1 ) && (row+1)%n == 1 ) hA.val[k] = MAGMA_Z_MAKE( 0.0, 0.0 ); if ((hA.col[k] == row+1 ) && (row)%n ==n-1 ) hA.val[k] = MAGMA_Z_MAKE( 0.0, 0.0 ); } } } CHECK( magma_zmconvert( hA, A, Magma_CSR, Magma_CSR, queue )); magma_zmcsrcompressor( A, queue ); A->true_nnz = A->nnz; cleanup: magma_free_cpu( diag_vals ); magma_free_cpu( diag_offset ); magma_zmfree( &hA, queue ); return info; }
27.805158
82
0.500721
[ "3d" ]
298b2e3163ce1131ddd353babdee56a67753a326
2,906
cpp
C++
Main/lib/Memory/Remote/Hook/VirtualMethodsTable/RemoteVirtualMethodsTableHook.cpp
Y3t1y3t/CSGO-Extern
854b11e749924124e1bba9020569e18e5812d4a9
[ "MIT" ]
17
2017-01-29T16:56:46.000Z
2021-07-28T01:59:45.000Z
Main/lib/Memory/Remote/Hook/VirtualMethodsTable/RemoteVirtualMethodsTableHook.cpp
Y3t1y3t/CSGO-Extern
854b11e749924124e1bba9020569e18e5812d4a9
[ "MIT" ]
3
2017-02-06T15:31:39.000Z
2017-02-09T08:34:17.000Z
Main/lib/Memory/Remote/Hook/VirtualMethodsTable/RemoteVirtualMethodsTableHook.cpp
Y3t1y3t/CSGO-Extern
854b11e749924124e1bba9020569e18e5812d4a9
[ "MIT" ]
4
2017-02-04T06:37:08.000Z
2018-04-21T08:44:38.000Z
#include "RemoteVirtualMethodsTableHook.h" namespace Memory { RemoteVirtualMethodsTableHook::RemoteVirtualMethodsTableHook( SharedRemoteProcessService remoteProcessService, const uintptr_t& virtualMethodsTablePtr, std::vector<uintptr_t>& virtualMethods, const uintptr_t& sharedDataPtr, const size_t& sharedDataSize ) : _remoteProcessService( remoteProcessService ) { _sharedData.Ptr = sharedDataPtr; _sharedData.Size = sharedDataSize; _virtualMethodsTable.Ptr = virtualMethodsTablePtr; _virtualMethodsTable.VirtualMethods = virtualMethods; _remoteProcessService->Read<uintptr_t>( _virtualMethodsTable.Ptr, &_virtualMethodsTable.PtrValue ); } RemoteVirtualMethodsTableHook::~RemoteVirtualMethodsTableHook() { RemoveTableHook(); if( !IsValidSharedDataPtr() ) return; _remoteProcessService->FreeAllocatedRemoteData( reinterpret_cast< LPVOID >( GetSharedDataPtr() ) ); } void RemoteVirtualMethodsTableHook::SetTableHook() const { _remoteProcessService->Suspend(); _remoteProcessService->Write<uintptr_t>( _virtualMethodsTable.Ptr, GetVirtualMethodsPtr() ); _remoteProcessService->Resume(); } void RemoteVirtualMethodsTableHook::RemoveTableHook() const { _remoteProcessService->Suspend(); _remoteProcessService->Write<uintptr_t>( _virtualMethodsTable.Ptr, _virtualMethodsTable.PtrValue ); _remoteProcessService->Resume(); } bool RemoteVirtualMethodsTableHook::IsValidSharedDataPtr() const { return _sharedData.Ptr != 0x0; } uintptr_t RemoteVirtualMethodsTableHook::GetVirtualMethodsPtr() const { return GetSharedDataPtr() + GetSharedDataSize(); } uintptr_t RemoteVirtualMethodsTableHook::GetVirtualMethodPtr( const size_t& index ) const { if( index < 0 || index >= _virtualMethodsTable.VirtualMethods.size() ) return 0; return _virtualMethodsTable.VirtualMethods.at( index ); } void RemoteVirtualMethodsTableHook::SetVirtualMethodPtr( const size_t& index, const uintptr_t& virtualMethodPtr ) const { if( index < 0 || index >= _virtualMethodsTable.VirtualMethods.size() ) return; _remoteProcessService->Suspend(); _remoteProcessService->Write<uintptr_t>( GetVirtualMethodsPtr() + index * sizeof( uintptr_t ), virtualMethodPtr ); _remoteProcessService->Resume(); } uintptr_t RemoteVirtualMethodsTableHook::GetSharedDataPtr() const { return _sharedData.Ptr; } void RemoteVirtualMethodsTableHook::SetSharedDataPtr( const uintptr_t& sharedDataPtr ) { _sharedData.Ptr = sharedDataPtr; } size_t RemoteVirtualMethodsTableHook::GetSharedDataSize() const { return _sharedData.Size; } }
33.790698
123
0.703028
[ "vector" ]
298e48c48ebcc7ed2e10707d61942452054dcd8c
6,306
cpp
C++
FP_UniformsCivilians/config.cpp
FarflungWanderer/fp_uniforms
384ae9d8d1d28166a02ec806d91ca1d47e8c02a9
[ "MIT" ]
null
null
null
FP_UniformsCivilians/config.cpp
FarflungWanderer/fp_uniforms
384ae9d8d1d28166a02ec806d91ca1d47e8c02a9
[ "MIT" ]
null
null
null
FP_UniformsCivilians/config.cpp
FarflungWanderer/fp_uniforms
384ae9d8d1d28166a02ec806d91ca1d47e8c02a9
[ "MIT" ]
null
null
null
class CfgPatches { class FP_UniformsCivilians { units[]={}; weapons[]={}; requiredVersion=0.1; requiredAddons[]={ "A3_Characters_F", "A3_Characters_F_BLUFOR", "A3_Characters_F_Common" }; }; }; class CfgVehicles { class I_Officer_F; class Civilian_F; class I_Soldier_F; class FP_AFR_CIV_01 : Civilian_F { _generalMacro = "FP_AFR_CIV_01"; scope = 1; side = 2; model = "\A3\characters_F\civil\c_poor"; hiddenSelections[] = {"camo", "insignia"}; hiddenSelectionsTextures[] = {"\A3\characters_f\civil\data\c_cloth1_v2_co.paa"}; uniformClass = "FP_U_Civ_01"; class Wounds { tex[] = {}; mat[] = { "A3\Characters_F\Civil\Data\c_cloth1.rvmat", "A3\Characters_F\Civil\Data\c_cloth1_injury.rvmat", "A3\Characters_F\Civil\Data\c_cloth1_injury.rvmat", "A3\Characters_F\Civil\Data\c_cloth2.rvmat", "A3\Characters_F\Civil\Data\c_cloth2_injury.rvmat", "A3\Characters_F\Civil\Data\c_cloth2_injury.rvmat", "A3\Characters_F\Civil\Data\c_cloth3.rvmat", "A3\Characters_F\Civil\Data\c_cloth3_injury.rvmat", "A3\Characters_F\Civil\Data\c_cloth3_injury.rvmat", "A3\Characters_F\Civil\Data\c_cloth4.rvmat", "A3\Characters_F\Civil\Data\c_cloth4_injury.rvmat", "A3\Characters_F\Civil\Data\c_cloth4_injury.rvmat", "A3\characters_f\civil\data\c_poloshirt.rvmat", "A3\Characters_F\Civil\Data\c_poloshirt_injury.rvmat", "A3\Characters_F\Civil\Data\c_poloshirt_injury.rvmat", "A3\characters_f\common\data\coveralls.rvmat", "A3\Characters_F\Common\Data\coveralls_injury.rvmat", "A3\Characters_F\Common\Data\coveralls_injury.rvmat", "A3\Characters_F\Civil\Data\hunter.rvmat", "A3\Characters_F\Civil\Data\hunter_injury.rvmat", "A3\Characters_F\Civil\Data\hunter_injury.rvmat", "A3\Characters_F\Civil\Data\c_poloshirtpants.rvmat", "A3\Characters_F\Civil\Data\c_poloshirtpants_injury.rvmat", "A3\Characters_F\Civil\Data\c_poloshirtpants_injury.rvmat", "A3\Characters_F\Civil\Data\priest.rvmat", "A3\Characters_F\Civil\Data\priest_injury.rvmat", "A3\Characters_F\Civil\Data\priest_injury.rvmat", "A3\Characters_F\Heads\Data\hl_white_bald_muscular.rvmat", "A3\Characters_F\Heads\Data\hl_white_bald_muscular_injury.rvmat", "A3\Characters_F\Heads\Data\hl_white_bald_muscular_injury.rvmat", "A3\Characters_F\Heads\Data\hl_black_bald_muscular.rvmat", "A3\Characters_F\Heads\Data\hl_black_bald_muscular_injury.rvmat", "A3\Characters_F\Heads\Data\hl_black_bald_muscular_injury.rvmat", "A3\Characters_F\Heads\Data\hl_white_hairy_muscular.rvmat", "A3\Characters_F\Heads\Data\hl_white_hairy_muscular_injury.rvmat", "A3\Characters_F\Heads\Data\hl_white_hairy_muscular_injury.rvmat", "A3\Characters_F\Heads\Data\hl_white_old.rvmat", "A3\Characters_F\Heads\Data\hl_white_old_injury.rvmat", "A3\Characters_F\Heads\Data\hl_white_old_injury.rvmat", "A3\Characters_F\Heads\Data\hl_asian_bald_muscular.rvmat", "A3\Characters_F\Heads\Data\hl_asian_bald_muscular_injury.rvmat", "A3\Characters_F\Heads\Data\hl_asian_bald_muscular_injury.rvmat" }; }; }; class FP_AFR_CIV_02 : FP_AFR_CIV_01 { _generalMacro = "FP_AFR_CIV_02"; hiddenSelectionsTextures[] = {"\A3\characters_f\civil\data\c_cloth1_v3_co.paa"}; uniformClass = "FP_U_Civ_02"; }; class FP_AFR_CIV_03 : FP_AFR_CIV_01 { _generalMacro = "FP_AFR_CIV_03"; hiddenSelectionsTextures[] = {"\A3\characters_f\civil\data\c_cloth1_kabeiroi_co.paa"}; uniformClass = "FP_U_Civ_03"; }; class FP_AFR_CIV_04 : FP_AFR_CIV_01 { _generalMacro = "FP_AFR_CIV_04"; hiddenSelectionsTextures[] = {"\A3\characters_f\civil\data\c_cloth1_bandit_co.paa"}; uniformClass = "FP_U_Civ_04"; }; class FP_AFR_CIV_05 : FP_AFR_CIV_01 { _generalMacro = "FP_AFR_CIV_05"; hiddenSelectionsTextures[] = {"\A3\characters_f\civil\data\c_cloth1_co.paa"}; uniformClass = "FP_U_Civ_05"; }; class FP_AFR_CIV_06 : FP_AFR_CIV_01 { _generalMacro = "FP_AFR_CIV_06"; hiddenSelectionsTextures[] = {"\a3\characters_f_bootcamp\Guerrilla\data\c_cloth1_kabeiroi_co.paa"}; uniformClass = "FP_U_Civ_06"; }; }; class cfgWeapons { class ItemCore; class UniformItem; class Uniform_Base: ItemCore { class ItemInfo; }; class FP_U_Civ_01: Uniform_Base { author="FP"; scope=2; side=2; displayName="African civ. fatigues 01"; picture="\A3\characters_f\data\ui\icon_U_Citizen_ca.paa"; model="\A3\Characters_F\Common\Suitpacks\suitpack_universal_F.p3d"; hiddenSelections[]= { "camo" }; hiddenSelectionsTextures[]= { "\A3\Characters_F\Common\Suitpacks\data\suitpack_soldier_blufor_co.paa" }; class ItemInfo: UniformItem { uniformModel="-"; uniformClass="FP_AFR_CIV_01"; containerClass="Supply20"; mass=20; }; }; class FP_U_Civ_02: FP_U_Civ_01 { displayName="African civ. fatigues 02"; hiddenSelectionsTextures[]={"\A3\Characters_F\Common\Suitpacks\data\suitpack_soldier_blufor_co.paa"}; class ItemInfo: UniformItem { uniformModel="-"; uniformClass="FP_AFR_CIV_02"; containerClass="Supply20"; mass=20; }; }; class FP_U_Civ_03: FP_U_Civ_01 { displayName="African civ. fatigues 03"; hiddenSelectionsTextures[]={"\A3\Characters_F\Common\Suitpacks\data\suitpack_soldier_blufor_co.paa"}; class ItemInfo: UniformItem { uniformModel="-"; uniformClass="FP_AFR_CIV_03"; containerClass="Supply20"; mass=20; }; }; class FP_U_Civ_04: FP_U_Civ_01 { displayName="African civ. fatigues 04"; hiddenSelectionsTextures[]={"\A3\Characters_F\Common\Suitpacks\data\suitpack_soldier_blufor_co.paa"}; class ItemInfo: UniformItem { uniformModel="-"; uniformClass="FP_AFR_CIV_04"; containerClass="Supply20"; mass=20; }; }; class FP_U_Civ_05: FP_U_Civ_01 { displayName="African civ. fatigues 05"; hiddenSelectionsTextures[]={"\A3\Characters_F\Common\Suitpacks\data\suitpack_soldier_blufor_co.paa"}; class ItemInfo: UniformItem { uniformModel="-"; uniformClass="FP_AFR_CIV_05"; containerClass="Supply20"; mass=20; }; }; class FP_U_Civ_06: FP_U_Civ_01 { displayName="African civ. fatigues 06"; hiddenSelectionsTextures[]={"\A3\Characters_F\Common\Suitpacks\data\suitpack_soldier_blufor_co.paa"}; class ItemInfo: UniformItem { uniformModel="-"; uniformClass="FP_AFR_CIV_06"; containerClass="Supply20"; mass=20; }; }; };
36.034286
138
0.748493
[ "model" ]
298eaa2707d7a9ec6a00f43b7039941573d3adf3
17,705
cc
C++
v8_4_8/src/ic/ic-state.cc
wenfeifei/miniblink49
2ed562ff70130485148d94b0e5f4c343da0c2ba4
[ "Apache-2.0" ]
5,964
2016-09-27T03:46:29.000Z
2022-03-31T16:25:27.000Z
v8_4_8/src/ic/ic-state.cc
w4454962/miniblink49
b294b6eacb3333659bf7b94d670d96edeeba14c0
[ "Apache-2.0" ]
459
2016-09-29T00:51:38.000Z
2022-03-07T14:37:46.000Z
v8_4_8/src/ic/ic-state.cc
w4454962/miniblink49
b294b6eacb3333659bf7b94d670d96edeeba14c0
[ "Apache-2.0" ]
1,006
2016-09-27T05:17:27.000Z
2022-03-30T02:46:51.000Z
// Copyright 2014 the V8 project 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 "src/ic/ic-state.h" #include "src/ic/ic.h" namespace v8 { namespace internal { // static void ICUtility::Clear(Isolate* isolate, Address address, Address constant_pool) { IC::Clear(isolate, address, constant_pool); } std::ostream& operator<<(std::ostream& os, const CallICState& s) { return os << "(args(" << s.argc() << "), " << s.convert_mode() << ", "; } // static STATIC_CONST_MEMBER_DEFINITION const int BinaryOpICState::FIRST_TOKEN; // static STATIC_CONST_MEMBER_DEFINITION const int BinaryOpICState::LAST_TOKEN; BinaryOpICState::BinaryOpICState(Isolate* isolate, ExtraICState extra_ic_state) : fixed_right_arg_( HasFixedRightArgField::decode(extra_ic_state) ? Just(1 << FixedRightArgValueField::decode(extra_ic_state)) : Nothing<int>()), isolate_(isolate) { op_ = static_cast<Token::Value>(FIRST_TOKEN + OpField::decode(extra_ic_state)); strong_ = StrengthField::decode(extra_ic_state); left_kind_ = LeftKindField::decode(extra_ic_state); right_kind_ = fixed_right_arg_.IsJust() ? (Smi::IsValid(fixed_right_arg_.FromJust()) ? SMI : INT32) : RightKindField::decode(extra_ic_state); result_kind_ = ResultKindField::decode(extra_ic_state); DCHECK_LE(FIRST_TOKEN, op_); DCHECK_LE(op_, LAST_TOKEN); } ExtraICState BinaryOpICState::GetExtraICState() const { ExtraICState extra_ic_state = OpField::encode(op_ - FIRST_TOKEN) | LeftKindField::encode(left_kind_) | ResultKindField::encode(result_kind_) | StrengthField::encode(strong_) | HasFixedRightArgField::encode(fixed_right_arg_.IsJust()); if (fixed_right_arg_.IsJust()) { extra_ic_state = FixedRightArgValueField::update( extra_ic_state, WhichPowerOf2(fixed_right_arg_.FromJust())); } else { extra_ic_state = RightKindField::update(extra_ic_state, right_kind_); } return extra_ic_state; } // static void BinaryOpICState::GenerateAheadOfTime( Isolate* isolate, void (*Generate)(Isolate*, const BinaryOpICState&)) { // TODO(olivf) We should investigate why adding stubs to the snapshot is so // expensive at runtime. When solved we should be able to add most binops to // the snapshot instead of hand-picking them. // Generated list of commonly used stubs #define GENERATE(op, left_kind, right_kind, result_kind) \ do { \ BinaryOpICState state(isolate, op, Strength::WEAK); \ state.left_kind_ = left_kind; \ state.fixed_right_arg_ = Nothing<int>(); \ state.right_kind_ = right_kind; \ state.result_kind_ = result_kind; \ Generate(isolate, state); \ } while (false) GENERATE(Token::ADD, INT32, INT32, INT32); GENERATE(Token::ADD, INT32, INT32, NUMBER); GENERATE(Token::ADD, INT32, NUMBER, NUMBER); GENERATE(Token::ADD, INT32, SMI, INT32); GENERATE(Token::ADD, NUMBER, INT32, NUMBER); GENERATE(Token::ADD, NUMBER, NUMBER, NUMBER); GENERATE(Token::ADD, NUMBER, SMI, NUMBER); GENERATE(Token::ADD, SMI, INT32, INT32); GENERATE(Token::ADD, SMI, INT32, NUMBER); GENERATE(Token::ADD, SMI, NUMBER, NUMBER); GENERATE(Token::ADD, SMI, SMI, INT32); GENERATE(Token::ADD, SMI, SMI, SMI); GENERATE(Token::BIT_AND, INT32, INT32, INT32); GENERATE(Token::BIT_AND, INT32, INT32, SMI); GENERATE(Token::BIT_AND, INT32, SMI, INT32); GENERATE(Token::BIT_AND, INT32, SMI, SMI); GENERATE(Token::BIT_AND, NUMBER, INT32, INT32); GENERATE(Token::BIT_AND, NUMBER, SMI, SMI); GENERATE(Token::BIT_AND, SMI, INT32, INT32); GENERATE(Token::BIT_AND, SMI, INT32, SMI); GENERATE(Token::BIT_AND, SMI, NUMBER, SMI); GENERATE(Token::BIT_AND, SMI, SMI, SMI); GENERATE(Token::BIT_OR, INT32, INT32, INT32); GENERATE(Token::BIT_OR, INT32, INT32, SMI); GENERATE(Token::BIT_OR, INT32, SMI, INT32); GENERATE(Token::BIT_OR, INT32, SMI, SMI); GENERATE(Token::BIT_OR, NUMBER, SMI, INT32); GENERATE(Token::BIT_OR, NUMBER, SMI, SMI); GENERATE(Token::BIT_OR, SMI, INT32, INT32); GENERATE(Token::BIT_OR, SMI, INT32, SMI); GENERATE(Token::BIT_OR, SMI, SMI, SMI); GENERATE(Token::BIT_XOR, INT32, INT32, INT32); GENERATE(Token::BIT_XOR, INT32, INT32, SMI); GENERATE(Token::BIT_XOR, INT32, NUMBER, SMI); GENERATE(Token::BIT_XOR, INT32, SMI, INT32); GENERATE(Token::BIT_XOR, NUMBER, INT32, INT32); GENERATE(Token::BIT_XOR, NUMBER, SMI, INT32); GENERATE(Token::BIT_XOR, NUMBER, SMI, SMI); GENERATE(Token::BIT_XOR, SMI, INT32, INT32); GENERATE(Token::BIT_XOR, SMI, INT32, SMI); GENERATE(Token::BIT_XOR, SMI, SMI, SMI); GENERATE(Token::DIV, INT32, INT32, INT32); GENERATE(Token::DIV, INT32, INT32, NUMBER); GENERATE(Token::DIV, INT32, NUMBER, NUMBER); GENERATE(Token::DIV, INT32, SMI, INT32); GENERATE(Token::DIV, INT32, SMI, NUMBER); GENERATE(Token::DIV, NUMBER, INT32, NUMBER); GENERATE(Token::DIV, NUMBER, NUMBER, NUMBER); GENERATE(Token::DIV, NUMBER, SMI, NUMBER); GENERATE(Token::DIV, SMI, INT32, INT32); GENERATE(Token::DIV, SMI, INT32, NUMBER); GENERATE(Token::DIV, SMI, NUMBER, NUMBER); GENERATE(Token::DIV, SMI, SMI, NUMBER); GENERATE(Token::DIV, SMI, SMI, SMI); GENERATE(Token::MOD, NUMBER, SMI, NUMBER); GENERATE(Token::MOD, SMI, SMI, SMI); GENERATE(Token::MUL, INT32, INT32, INT32); GENERATE(Token::MUL, INT32, INT32, NUMBER); GENERATE(Token::MUL, INT32, NUMBER, NUMBER); GENERATE(Token::MUL, INT32, SMI, INT32); GENERATE(Token::MUL, INT32, SMI, NUMBER); GENERATE(Token::MUL, NUMBER, INT32, NUMBER); GENERATE(Token::MUL, NUMBER, NUMBER, NUMBER); GENERATE(Token::MUL, NUMBER, SMI, NUMBER); GENERATE(Token::MUL, SMI, INT32, INT32); GENERATE(Token::MUL, SMI, INT32, NUMBER); GENERATE(Token::MUL, SMI, NUMBER, NUMBER); GENERATE(Token::MUL, SMI, SMI, INT32); GENERATE(Token::MUL, SMI, SMI, NUMBER); GENERATE(Token::MUL, SMI, SMI, SMI); GENERATE(Token::SAR, INT32, SMI, INT32); GENERATE(Token::SAR, INT32, SMI, SMI); GENERATE(Token::SAR, NUMBER, SMI, SMI); GENERATE(Token::SAR, SMI, SMI, SMI); GENERATE(Token::SHL, INT32, SMI, INT32); GENERATE(Token::SHL, INT32, SMI, SMI); GENERATE(Token::SHL, NUMBER, SMI, SMI); GENERATE(Token::SHL, SMI, SMI, INT32); GENERATE(Token::SHL, SMI, SMI, SMI); GENERATE(Token::SHR, INT32, SMI, SMI); GENERATE(Token::SHR, NUMBER, SMI, INT32); GENERATE(Token::SHR, NUMBER, SMI, SMI); GENERATE(Token::SHR, SMI, SMI, SMI); GENERATE(Token::SUB, INT32, INT32, INT32); GENERATE(Token::SUB, INT32, NUMBER, NUMBER); GENERATE(Token::SUB, INT32, SMI, INT32); GENERATE(Token::SUB, NUMBER, INT32, NUMBER); GENERATE(Token::SUB, NUMBER, NUMBER, NUMBER); GENERATE(Token::SUB, NUMBER, SMI, NUMBER); GENERATE(Token::SUB, SMI, INT32, INT32); GENERATE(Token::SUB, SMI, NUMBER, NUMBER); GENERATE(Token::SUB, SMI, SMI, SMI); #undef GENERATE #define GENERATE(op, left_kind, fixed_right_arg_value, result_kind) \ do { \ BinaryOpICState state(isolate, op, Strength::WEAK); \ state.left_kind_ = left_kind; \ state.fixed_right_arg_ = Just(fixed_right_arg_value); \ state.right_kind_ = SMI; \ state.result_kind_ = result_kind; \ Generate(isolate, state); \ } while (false) GENERATE(Token::MOD, SMI, 2, SMI); GENERATE(Token::MOD, SMI, 4, SMI); GENERATE(Token::MOD, SMI, 8, SMI); GENERATE(Token::MOD, SMI, 16, SMI); GENERATE(Token::MOD, SMI, 32, SMI); GENERATE(Token::MOD, SMI, 2048, SMI); #undef GENERATE } Type* BinaryOpICState::GetResultType(Zone* zone) const { Kind result_kind = result_kind_; if (HasSideEffects()) { result_kind = NONE; } else if (result_kind == GENERIC && op_ == Token::ADD) { return Type::Union(Type::Number(zone), Type::String(zone), zone); } else if (result_kind == NUMBER && op_ == Token::SHR) { return Type::Unsigned32(zone); } DCHECK_NE(GENERIC, result_kind); return KindToType(result_kind, zone); } std::ostream& operator<<(std::ostream& os, const BinaryOpICState& s) { os << "(" << Token::Name(s.op_); if (s.CouldCreateAllocationMementos()) os << "_CreateAllocationMementos"; if (is_strong(s.strength())) os << "_Strong"; os << ":" << BinaryOpICState::KindToString(s.left_kind_) << "*"; if (s.fixed_right_arg_.IsJust()) { os << s.fixed_right_arg_.FromJust(); } else { os << BinaryOpICState::KindToString(s.right_kind_); } return os << "->" << BinaryOpICState::KindToString(s.result_kind_) << ")"; } void BinaryOpICState::Update(Handle<Object> left, Handle<Object> right, Handle<Object> result) { ExtraICState old_extra_ic_state = GetExtraICState(); left_kind_ = UpdateKind(left, left_kind_); right_kind_ = UpdateKind(right, right_kind_); int32_t fixed_right_arg_value = 0; bool has_fixed_right_arg = op_ == Token::MOD && right->ToInt32(&fixed_right_arg_value) && fixed_right_arg_value > 0 && base::bits::IsPowerOfTwo32(fixed_right_arg_value) && FixedRightArgValueField::is_valid(WhichPowerOf2(fixed_right_arg_value)) && (left_kind_ == SMI || left_kind_ == INT32) && (result_kind_ == NONE || !fixed_right_arg_.IsJust()); fixed_right_arg_ = has_fixed_right_arg ? Just(fixed_right_arg_value) : Nothing<int32_t>(); result_kind_ = UpdateKind(result, result_kind_); if (!Token::IsTruncatingBinaryOp(op_)) { Kind input_kind = Max(left_kind_, right_kind_); if (result_kind_ < input_kind && input_kind <= NUMBER) { result_kind_ = input_kind; } } // We don't want to distinguish INT32 and NUMBER for string add (because // NumberToString can't make use of this anyway). if (left_kind_ == STRING && right_kind_ == INT32) { DCHECK_EQ(STRING, result_kind_); DCHECK_EQ(Token::ADD, op_); right_kind_ = NUMBER; } else if (right_kind_ == STRING && left_kind_ == INT32) { DCHECK_EQ(STRING, result_kind_); DCHECK_EQ(Token::ADD, op_); left_kind_ = NUMBER; } if (old_extra_ic_state == GetExtraICState()) { // Tagged operations can lead to non-truncating HChanges if (left->IsUndefined() || left->IsBoolean()) { left_kind_ = GENERIC; } else { DCHECK(right->IsUndefined() || right->IsBoolean()); right_kind_ = GENERIC; } } } BinaryOpICState::Kind BinaryOpICState::UpdateKind(Handle<Object> object, Kind kind) const { Kind new_kind = GENERIC; bool is_truncating = Token::IsTruncatingBinaryOp(op()); if (object->IsBoolean() && is_truncating) { // Booleans will be automatically truncated by HChange. new_kind = INT32; } else if (object->IsUndefined()) { // Undefined will be automatically truncated by HChange. new_kind = is_truncating ? INT32 : NUMBER; } else if (object->IsSmi()) { new_kind = SMI; } else if (object->IsHeapNumber()) { double value = Handle<HeapNumber>::cast(object)->value(); new_kind = IsInt32Double(value) ? INT32 : NUMBER; } else if (object->IsString() && op() == Token::ADD) { new_kind = STRING; } if (new_kind == INT32 && SmiValuesAre32Bits()) { new_kind = NUMBER; } if (kind != NONE && ((new_kind <= NUMBER && kind > NUMBER) || (new_kind > NUMBER && kind <= NUMBER))) { new_kind = GENERIC; } return Max(kind, new_kind); } // static const char* BinaryOpICState::KindToString(Kind kind) { switch (kind) { case NONE: return "None"; case SMI: return "Smi"; case INT32: return "Int32"; case NUMBER: return "Number"; case STRING: return "String"; case GENERIC: return "Generic"; } UNREACHABLE(); return NULL; } // static Type* BinaryOpICState::KindToType(Kind kind, Zone* zone) { switch (kind) { case NONE: return Type::None(zone); case SMI: return Type::SignedSmall(zone); case INT32: return Type::Signed32(zone); case NUMBER: return Type::Number(zone); case STRING: return Type::String(zone); case GENERIC: return Type::Any(zone); } UNREACHABLE(); return NULL; } const char* CompareICState::GetStateName(State state) { switch (state) { case UNINITIALIZED: return "UNINITIALIZED"; case BOOLEAN: return "BOOLEAN"; case SMI: return "SMI"; case NUMBER: return "NUMBER"; case INTERNALIZED_STRING: return "INTERNALIZED_STRING"; case STRING: return "STRING"; case UNIQUE_NAME: return "UNIQUE_NAME"; case OBJECT: return "OBJECT"; case KNOWN_OBJECT: return "KNOWN_OBJECT"; case GENERIC: return "GENERIC"; } UNREACHABLE(); return NULL; } Type* CompareICState::StateToType(Zone* zone, State state, Handle<Map> map) { switch (state) { case UNINITIALIZED: return Type::None(zone); case BOOLEAN: return Type::Boolean(zone); case SMI: return Type::SignedSmall(zone); case NUMBER: return Type::Number(zone); case STRING: return Type::String(zone); case INTERNALIZED_STRING: return Type::InternalizedString(zone); case UNIQUE_NAME: return Type::UniqueName(zone); case OBJECT: return Type::Receiver(zone); case KNOWN_OBJECT: return map.is_null() ? Type::Receiver(zone) : Type::Class(map, zone); case GENERIC: return Type::Any(zone); } UNREACHABLE(); return NULL; } CompareICState::State CompareICState::NewInputState(State old_state, Handle<Object> value) { switch (old_state) { case UNINITIALIZED: if (value->IsBoolean()) return BOOLEAN; if (value->IsSmi()) return SMI; if (value->IsHeapNumber()) return NUMBER; if (value->IsInternalizedString()) return INTERNALIZED_STRING; if (value->IsString()) return STRING; if (value->IsSymbol()) return UNIQUE_NAME; if (value->IsJSObject()) return OBJECT; break; case BOOLEAN: if (value->IsBoolean()) return BOOLEAN; break; case SMI: if (value->IsSmi()) return SMI; if (value->IsHeapNumber()) return NUMBER; break; case NUMBER: if (value->IsNumber()) return NUMBER; break; case INTERNALIZED_STRING: if (value->IsInternalizedString()) return INTERNALIZED_STRING; if (value->IsString()) return STRING; if (value->IsSymbol()) return UNIQUE_NAME; break; case STRING: if (value->IsString()) return STRING; break; case UNIQUE_NAME: if (value->IsUniqueName()) return UNIQUE_NAME; break; case OBJECT: if (value->IsJSObject()) return OBJECT; break; case GENERIC: break; case KNOWN_OBJECT: UNREACHABLE(); break; } return GENERIC; } // static CompareICState::State CompareICState::TargetState( State old_state, State old_left, State old_right, Token::Value op, bool has_inlined_smi_code, Handle<Object> x, Handle<Object> y) { switch (old_state) { case UNINITIALIZED: if (x->IsBoolean() && y->IsBoolean()) return BOOLEAN; if (x->IsSmi() && y->IsSmi()) return SMI; if (x->IsNumber() && y->IsNumber()) return NUMBER; if (Token::IsOrderedRelationalCompareOp(op)) { // Ordered comparisons treat undefined as NaN, so the // NUMBER stub will do the right thing. if ((x->IsNumber() && y->IsUndefined()) || (y->IsNumber() && x->IsUndefined())) { return NUMBER; } } if (x->IsInternalizedString() && y->IsInternalizedString()) { // We compare internalized strings as plain ones if we need to determine // the order in a non-equality compare. return Token::IsEqualityOp(op) ? INTERNALIZED_STRING : STRING; } if (x->IsString() && y->IsString()) return STRING; if (x->IsJSObject() && y->IsJSObject()) { if (Handle<JSObject>::cast(x)->map() == Handle<JSObject>::cast(y)->map()) { return KNOWN_OBJECT; } else { return Token::IsEqualityOp(op) ? OBJECT : GENERIC; } } if (!Token::IsEqualityOp(op)) return GENERIC; if (x->IsUniqueName() && y->IsUniqueName()) return UNIQUE_NAME; return GENERIC; case SMI: return x->IsNumber() && y->IsNumber() ? NUMBER : GENERIC; case INTERNALIZED_STRING: DCHECK(Token::IsEqualityOp(op)); if (x->IsString() && y->IsString()) return STRING; if (x->IsUniqueName() && y->IsUniqueName()) return UNIQUE_NAME; return GENERIC; case NUMBER: // If the failure was due to one side changing from smi to heap number, // then keep the state (if other changed at the same time, we will get // a second miss and then go to generic). if (old_left == SMI && x->IsHeapNumber()) return NUMBER; if (old_right == SMI && y->IsHeapNumber()) return NUMBER; return GENERIC; case KNOWN_OBJECT: if (x->IsJSObject() && y->IsJSObject()) { return Token::IsEqualityOp(op) ? OBJECT : GENERIC; } return GENERIC; case BOOLEAN: case STRING: case UNIQUE_NAME: case OBJECT: case GENERIC: return GENERIC; } UNREACHABLE(); return GENERIC; // Make the compiler happy. } } // namespace internal } // namespace v8
34.64775
80
0.641457
[ "object" ]