blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
9153725d9e48f9cfc269bc6c7d30a863262d7e14
496bfb693a5f9a25b3f368eaae3358fd06cd5429
/Framework/Framework/modules/FreeBird/include/AndGate.h
fef36d1925f6c08ec8c409353127d4db73510f13
[]
no_license
Aideng666/Project-Poultry-Game
a32cc911ab18673c33ec469a944cb666ea8cc78d
7e27c67939f789202d87ae720f2a6bc8b84c7593
refs/heads/Master
2023-04-04T06:49:32.352043
2021-04-09T16:41:11
2021-04-09T16:41:11
300,339,278
0
1
null
2021-01-17T20:05:11
2020-10-01T16:03:30
C++
UTF-8
C++
false
false
207
h
#pragma once #include "LogicGate.h" namespace freebird { class AndGate : public LogicGate { public: AndGate(Entity ent1, Entity ent2, Entity out); void Update(); private: }; }
[ "aiden.gimpel@ontariotechu.net" ]
aiden.gimpel@ontariotechu.net
f788cf77c7d4cd5cc276aaff0ddd69d3eb657494
e60bec80c00cd484a5acec538bb9b419bce734a5
/2023/tmb/scaa_mod_age_dir.cpp
23962d734240af8390e4cf27c0b11b030e41e813
[]
no_license
commfish/seak_sablefish
cd63c84c271765242abd3476880f80a9704576ee
8828847b3f352b9b9a260b58dbf68cccce39a5b1
refs/heads/master
2023-09-01T01:31:42.213887
2023-08-23T17:37:30
2023-08-23T17:37:30
104,012,945
8
6
null
2023-01-10T18:55:16
2017-09-19T01:57:03
R
UTF-8
C++
false
false
61,566
cpp
// Sex-structured statistical catch-at-age model for NSEI sablefish that // includes catch, fishery and survey CPUE, mark-recapture abundance estimates, // fishery and survey weight-at-age, survey data about maturity-at-age and // proportions-at-age, and fishery and survey age and length compositions. // Original Author: Jane Sullivan, ummjane@gmail.com // Current Driver: Phil Joy, philip.joy@alaska.gov // Last updated March 2023 #include <TMB.hpp> #include <numeric> template <class Type> Type square(Type x){return x*x;} // template <class Type> Type sumVec(vector<Type> vec){return std::accumulate(vec.begin(), vec.end(), 0.0);} // template <class Type> Type mean(vector<Type> vec){return std::accumulate(vec.begin(), vec.end(), 0.0) / vec.size();} template<class Type> Type objective_function<Type>::operator() () { // **DATA SECTION** // Model dimensions DATA_INTEGER(nyr) // number of years in the model (year indexed as i) DATA_INTEGER(nage) // number of ages in the model (age indexed as j) DATA_INTEGER(nsex) // controls whether model is sex-structured or not (sex indexed as k) DATA_INTEGER(nlenbin) // number of length bins (indexed as l) DATA_VECTOR(lenbin) // length bins // Switch for recruitment estimate: 0 = penalized likelihood (fixed sigma_r), 1 // = random effects DATA_INTEGER(random_rec) // Switch for selectivity type: 0 = a50, a95 logistic; 1 = a50, slope logistic DATA_INTEGER(slx_type) // Swtich for age composition type (hopefully one day length too): 0 = multinomial; 1 = Dirichlet-multinomial DATA_INTEGER(comp_type) // Switch for assumption on SPR equilibrium recruitment. 0 = arithmetic mean // (same as Federal assessment), 1 = geometric mean, 2 = median (2 not coded // yet) DATA_INTEGER(spr_rec_type) // Prior for natural mortality DATA_INTEGER(M_type) // switch to fix M (0) or estimate with prior (1) DATA_SCALAR(p_log_M) // mean M=0.1 DATA_SCALAR(p_sigma_M) // CV or sigma = 0.1 // Time varying parameter blocks (indexed as h) - each vector contains the terminal years of // each time block. Used for both selectivity and catchability DATA_IVECTOR(fsh_blks) // fishery DATA_IVECTOR(srv_blks) // survey // Fixed parameters DATA_ARRAY(dmr) // discard mortality in the fishery by year, age, and sex. assume constant dmr 0 or 0.16 DATA_ARRAY(retention) // probability of retaining a fish, sex- and age-based // Fxx levels that correspond with log_spr_Fxx in Parameter section (indexed as x) DATA_VECTOR(Fxx_levels) // e.g. F35=0.35, F40=0.40, and F50=0.50 // Priors ("p_" denotes prior) DATA_VECTOR(p_fsh_q) // prior fishery catchability coefficient (on natural scale) DATA_VECTOR(sigma_fsh_q) // sigma for fishery q DATA_SCALAR(p_srv_q) // prior on survey catchability coefficient (on natural scale) DATA_SCALAR(sigma_srv_q) // sigma for survey q DATA_SCALAR(p_mr_q) // prior on mark-recapture catchability coefficient (on natural scale) DATA_SCALAR(sigma_mr_q) // sigma for mark-recapture q // Weights on likelihood componets("wt_" denotes weight) DATA_SCALAR(wt_catch) // catch DATA_SCALAR(wt_fsh_cpue) // fishery cpue DATA_SCALAR(wt_srv_cpue) // soak survey DATA_SCALAR(wt_mr) // mark-recapture abundance DATA_SCALAR(wt_fsh_age) // fishery age comps DATA_SCALAR(wt_srv_age) // survey age comps DATA_SCALAR(wt_fsh_len) // fishery length comps DATA_SCALAR(wt_srv_len) // survey length comps DATA_SCALAR(wt_rec_like) // penalty on recruitment deviations DATA_SCALAR(wt_fpen) // penality on fishing mortality deviations DATA_SCALAR(wt_spr) // penalty on spawner per recruit calcs // INDICES OF ABUNDANCE // Catch DATA_VECTOR(data_catch) // vector of landed catch estimates DATA_VECTOR(sigma_catch) // assumed CV of 5% for catch // Mark-recapture estimates DATA_INTEGER(nyr_mr) // number of years DATA_IVECTOR(yrs_mr) // vector of years DATA_VECTOR(data_mr) // vector of estimates DATA_VECTOR(sigma_mr) // posterior SDs for mark-recapture estimates // Fishery cpue DATA_INTEGER(nyr_fsh_cpue) // number of years DATA_IVECTOR(yrs_fsh_cpue) // vector of years DATA_VECTOR(data_fsh_cpue) // vector of estimates DATA_VECTOR(sigma_fsh_cpue) // vector of fishery cpue SDs // Survey cpue DATA_INTEGER(nyr_srv_cpue) // number of years DATA_IVECTOR(yrs_srv_cpue) // vector of years DATA_VECTOR(data_srv_cpue) // vector of estimates DATA_VECTOR(sigma_srv_cpue) // vector of survey cpue SDs // BIOLOGICAL DATA // Timing in months (e.g. January = 1/12 = 0.083) DATA_SCALAR(spawn_month) // month when spawning occurs (February) DATA_SCALAR(srv_month) // month when survey begins (July) DATA_SCALAR(fsh_month) // month when fishery begins (August) // Proportion mature at age (rows = 1, cols = nage); the rows could one day // represent annual or time-varying maturity DATA_MATRIX(prop_mature) // Proportion female at age in the survey (all years combined) applied in // calculation of spawning biomass. When nsex=2, the N matrix is // already split by sex, so you don't need prop_fem in spawning biomass calculation // (it will be a vector of 1's). DATA_VECTOR(prop_fem) // Sex ratio in survey (all years combined) used to split N matrix by sex. // First row is males at age, second row is females at age. The underlying // data underpins prop_fem and sex_ratio; this redundancy serves to // accommodate single sex and sex-structured versions of this model. When // nsex=1, the sex_ratio is a matrix of 1's so the N matrix doesn't get split // by sex. DATA_MATRIX(sex_ratio) // Weight-at-age (rows = 1, all years combined; cols = nage; matrices = 0 for // males, 1 for females); the rows could one day represent annual or // time-varying weight-at-age DATA_ARRAY(data_fsh_waa) // Fishery (sex-specific) DATA_ARRAY(data_srv_waa) // Survey (sex-specific) //std::cout << data_srv_waa << "\n"; // Fishery age comps DATA_INTEGER(nyr_fsh_age) // number of years DATA_IVECTOR(yrs_fsh_age) // vector of years DATA_MATRIX(data_fsh_age) // matrix of observations (year, age) DATA_VECTOR(n_fsh_age) // raw sample size for age comps DATA_VECTOR(effn_fsh_age) // effective sample size // Survey age comps DATA_INTEGER(nyr_srv_age) // number of years DATA_IVECTOR(yrs_srv_age) // vector of years DATA_MATRIX(data_srv_age) // matrix of observations (year, age) DATA_VECTOR(n_srv_age) // raw sample size for age comps DATA_VECTOR(effn_srv_age) // effective sample size // Fishery length comps DATA_INTEGER(nyr_fsh_len) // number of years DATA_IVECTOR(yrs_fsh_len) // vector of years DATA_ARRAY(data_fsh_len) // observations (nyr, nlenbin, nsex) DATA_ARRAY(n_fsh_len) // raw sample size for length comps (nyr, 1, nsex) DATA_ARRAY(effn_fsh_len) // effective sample size (nyr, 1, nsex) // Survey length comps DATA_INTEGER(nyr_srv_len) // number of years DATA_IVECTOR(yrs_srv_len) // vector of years DATA_ARRAY(data_srv_len) // observations (nyr, nlenbin, nsex) DATA_ARRAY(n_srv_len) // raw sample size for length comps (nyr, 1, nsex) DATA_ARRAY(effn_srv_len) // effective sample size (nyr, 1, nsex) // Ageing error transition matrix (proportion at reader age given true age) DATA_MATRIX(ageing_error) // Age-length transition matrices DATA_ARRAY(agelen_key_fsh) // Fishery (nage, nlenbin, nsex) DATA_ARRAY(agelen_key_srv) // Survey (nage, nlenbin, nsex) // **PARAMETER SECTION** // Dummy variable for troubleshooting PARAMETER(dummy); // Natural mortality PARAMETER(log_M); // M_type = 0 is fixed, 1 is estimated Type M = exp(log_M); // Selectivity PARAMETER_ARRAY(log_fsh_slx_pars); // Fishery selectivity (slx_type controls parameterization) PARAMETER_ARRAY(log_srv_slx_pars); // Survey selectivity (slx_type controls parameterization) // Catchability PARAMETER_VECTOR(fsh_logq); // fishery PARAMETER(srv_logq); // survey PARAMETER(mr_logq); // mark-recapture // Recruitment (rec_devs include a parameter for all ages in the inital yr plus age-2 in all yrs) PARAMETER(log_rbar); // Mean recruitment PARAMETER_VECTOR(log_rec_devs); // Annual recruitment deviations (formerly nyr+nage-2, now nyr) PARAMETER(log_rinit); // Mean initial numbers-at-age in syr PARAMETER_VECTOR(log_rinit_devs); // Age-specific deviations from log_rinit (nage-2) PARAMETER(log_sigma_r); // Variability in rec_devs and rinits, only estimated when using random effects (random_rec=1) // Fishing mortality PARAMETER(log_Fbar); // Mean F on log scale PARAMETER_VECTOR(log_F_devs); // Annual deviations from log_Fbar (nyr) // SPR-based fishing mortality rates, i.e. the F at which the spawning biomass // per recruit is reduced to xx% of its value in an unfished stock PARAMETER_VECTOR(log_spr_Fxx); // e.g. F35, F40, F50 // Parameter related to effective sample size for Dirichlet-multinomial // likelihood used for composition data. Eqn 11 in Thorson et al. 2017. PARAMETER(log_fsh_theta); //ages... u PARAMETER(log_srv_theta); //ages // **DERIVED QUANTITIES** // Predicted indices of catch and abundance vector<Type> pred_catch(nyr); // Total catch biomass vector<Type> pred_landed(nyr); // Landed catch biomass vector<Type> pred_wastage(nyr); // Discarded biomass assumed dead vector<Type> pred_mr(nyr_mr); // Mark-recapture index of abundance (only years with an estimate) vector<Type> pred_mr_all(nyr); // Mark-recapture index of abundance (all years!) vector<Type> pred_fsh_cpue(nyr_fsh_cpue); // Fishery cpue vector<Type> pred_srv_cpue(nyr_srv_cpue); // Survey cpue pred_catch.setZero(); pred_landed.setZero(); pred_wastage.setZero(); pred_mr.setZero(); pred_mr_all.setZero(); pred_fsh_cpue.setZero(); pred_srv_cpue.setZero(); // Predicted age compositions matrix<Type> pred_fsh_age(nyr_fsh_age, nage); // Fishery (with ageing error) matrix<Type> pred_srv_age(nyr_srv_age, nage); // Survey (with ageing error) pred_fsh_age.setZero(); pred_srv_age.setZero(); // Predicted length compositions array<Type> pred_fsh_obsage(nyr_fsh_len, nage, nsex); // Fishery (before age-length transition) array<Type> pred_srv_obsage(nyr_srv_len, nage, nsex); // Survey (before age-length transition) array<Type> pred_fsh_len(nyr_fsh_len, nlenbin, nsex); // Fishery array<Type> pred_srv_len(nyr_srv_len, nlenbin, nsex); // Survey pred_fsh_len.setZero(); pred_srv_len.setZero(); pred_fsh_obsage.setZero(); pred_srv_obsage.setZero(); // Predicted selectivity array<Type> fsh_slx(nyr, nage, nsex); // Fishery selectivity-at-age by sex (on natural scale) array<Type> srv_slx(nyr, nage, nsex); // Survey selectivity-at-age by sex(on natural scale) fsh_slx.setZero(); srv_slx.setZero(); // Predicted annual fishing mortality vector<Type> Fmort(nyr); // On natural scale Fmort.setZero(); // Derived matrices by year, age, and sex array<Type> N(nyr+1, nage, nsex); // Abundance-at-age, projected 1 year forward array<Type> Z(nyr, nage, nsex); // Total mortality array<Type> F(nyr, nage, nsex); // Fishing mortality array<Type> S(nyr, nage, nsex); // Total survivorship (natural + fishing) array<Type> C(nyr, nage, nsex); // Total catch in numbers array<Type> L(nyr, nage, nsex); // Total landed catch in numbers array<Type> D(nyr, nage, nsex); // Total discards in numbers assumed to die post-release N.setZero(); Z.setZero(); F.setZero(); S.setZero(); C.setZero(); L.setZero(); D.setZero(); // Derived time series of recruitment, biomass, and abundance (+ projected values) vector<Type> pred_rec(nyr); // Predicted age-2 recruitment pred_rec.setZero(); array<Type> biom(nyr+1, nage, nsex); // Biomass by year, age, and sex, projected 1 year forward vector<Type> tot_biom(nyr+1); // Summed over age and sex biom.setZero(); tot_biom.setZero(); array<Type> expl_biom(nyr+1, nage, nsex); // Exploitable biomass to fishery at the beginning of the fishery, projected 1 year forward array<Type> expl_abd(nyr+1, nage, nsex); // Exploitable abundance to fishery at the beginning of the fishery, projected 1 year forward vector<Type> tot_expl_biom(nyr+1); // Summed over age and sex vector<Type> tot_expl_abd(nyr+1); // Summed over age and sex expl_biom.setZero(); tot_expl_biom.setZero(); expl_abd.setZero(); tot_expl_abd.setZero(); array<Type> vuln_abd(nyr+1, nage, nsex); // Vulnerable abundance to survey at the beginning of the survey, projected 1 year forward vector<Type> tot_vuln_abd(nyr+1); // Summed over age and sex vuln_abd.setZero(); tot_vuln_abd.setZero(); matrix<Type> spawn_biom(nyr+1, nage); // Spawning biomass, just females vector<Type> tot_spawn_biom(nyr+1); // Summed over age spawn_biom.setZero(); tot_spawn_biom.setZero(); // Other derived and projected values array<Type> survival_srv(nyr, nage, nsex); // Survival at time of survey array<Type> survival_fsh(nyr, nage, nsex); // Survival at time of fishery array<Type> survival_spawn(nyr, nage, nsex); // Survival at time of spawning Type pred_rbar; // Predicted mean recruitment Type sigma_r = exp(log_sigma_r); // Estimated recruitment on natural scale survival_srv.setZero(); survival_fsh.setZero(); survival_spawn.setZero(); // SPR-based equilibrium reference points int n_Fxx = Fxx_levels.size(); // Number of Fs estimated vector<Type> Fxx(n_Fxx + 1); // Separate Fxx vector that is scaled to fully selected values (+1 includes F=0) matrix<Type> Nspr(n_Fxx + 1, nage); // Matrix of spawning numbers-at-age *FLAG* number of rows = number of estimated F_xx% (e.g. 3 = F35,F40,F50) vector<Type> SBPR(n_Fxx + 1); // Spawning biomass per recruit at various fishing levels vector<Type> SB(n_Fxx + 1); // Equilibrium spawning biomass at various fishing levels Fxx.setZero(); Nspr.setZero(); SBPR.setZero(); SB.setZero(); // ABC calculation array<Type> sel_Fxx(n_Fxx, nage, nsex); // Age-specific fully-selected fishing mortality at each Fxx% array<Type> Z_Fxx(n_Fxx, nage, nsex); // Total mortality at each Fxx% array<Type> S_Fxx(n_Fxx, nage, nsex); // Total survivorship at each Fxx% matrix<Type> ABC(nyr+1, n_Fxx); // ABCs at each F_xx%, retrospectively estimated for past years matrix<Type> wastage(nyr+1, n_Fxx); // Discarded catch assumed to die under each F_xx%, retrospectively estimated for past years sel_Fxx.setZero(); Z_Fxx.setZero(); S_Fxx.setZero(); ABC.setZero(); wastage.setZero(); // Priors, likelihoods, offsets, and penalty functions vector<Type> priors(3); // Priors for catchability coefficients priors.setZero(); Type prior_M = 0; // Prior on natural mortality if estimated Type catch_like = 0; // Catch Type rec_like = 0; // Recruitment Type fpen = 0; // Penality for Fmort regularity Type spr_pen = 0; // Penality for SPR-based reference points vector<Type> index_like(3); // Fishery cpue, survey cpue, MR estimates index_like.setZero(); vector<Type> age_like(2); // Fishery and survey age comps vector<Type> fsh_len_like(nsex); // Fishery length comps vector<Type> srv_len_like(nsex); // Survey length comps age_like.setZero(); fsh_len_like.setZero(); srv_len_like.setZero(); // Offset for multinomial distribution that lets likelihood equal zero when obs = pred vector<Type> offset(2); // Age comps (both fsh and srv) vector<Type> offset_fsh_len(nsex); // Fishery length comps (sex-specific) vector<Type> offset_srv_len(nsex); // Survey length comp (sex-specific) offset.setZero(); offset_fsh_len.setZero(); offset_srv_len.setZero(); Type obj_fun = 0; // Objective function Type c = 0.00001; // Tiny constant to prevent likelihoods from going to 0 // **MODEL** // Indexing: i = year, j = age, l = length bin, k = sex, h = time block, x = Fxx level // Fishery selectivity // Number of parameters in the chosen selectivity type: int npar_slx = log_fsh_slx_pars.dim(1); // dim = array dimensions; 1 = # columns in array = # params in slx_type // std::cout << npar_slx << "\n number of params for slx type\n"; // Preliminary calcs to bring parameters out of log space array<Type> fsh_slx_pars(log_fsh_slx_pars.dim); fsh_slx_pars.setZero(); for (int k = 0; k < nsex; k++) { for (int h = 0; h < fsh_blks.size(); h++) { for (int n = 0; n < npar_slx; n++) { fsh_slx_pars(h,n,k) = exp(log_fsh_slx_pars(h,n,k)); } } } // std::cout << fsh_slx_pars << "\n slx out of log space\n"; // Notes on the following syntax: the do while allows you to estimate parameters within a time block. It // "does" the looping over year and age "while" within the time block, then // iterates to the next block. Year is not in a for loop because it is // iterated by the do statement. // The switch for slx_type allows you to change parameterization. This could // easily be expanded to accomodate any selectivity type (the fsh_slx_pars // allows for a flexible number of parameters and time blocks) int i = 0; for(int h = 0; h < fsh_blks.size(); h++){ do{ for (int k = 0; k < nsex; k++) { for (int j = 0; j < nage; j++) { // Selectivity switch (case 0 or 1 references the value of slx_type) switch (slx_type) { case 0: // Logistic with a50 and a95, where fsh_slx_pars(h,0,k) = a50 and fsh_slx_pars(h,1,k) = a95 fsh_slx(i,j,k) = Type(1.0) / ( Type(1.0) + exp(-log(Type(19)) * (j - fsh_slx_pars(h,0,k)) / (fsh_slx_pars(h,1,k) - fsh_slx_pars(h,0,k))) ); break; case 1: // Logistic with a50 and slope, where fsh_slx_pars(h,0,k) = a50 and fsh_slx_pars(h,1,k) = slope. // *This is the preferred logistic parameterization b/c it reduces parameter correlation* fsh_slx(i,j,k) = Type(1.0) / ( Type(1.0) + exp( Type(-1.0) * fsh_slx_pars(h,1,k) * (j - fsh_slx_pars(h,0,k)) ) ); break; } } } i++; } while (i <= fsh_blks(h)); } // std::cout << fsh_slx(1,1,1) << "\n Fishery selectivity \n"; // Survey selectivity - see notes on syntax in fishery selectivity section // Preliminary calcs to bring parameters out of log space array<Type> srv_slx_pars(log_srv_slx_pars.dim); srv_slx_pars.setZero(); for (int k = 0; k < nsex; k++) { for (int h = 0; h < srv_blks.size(); h++) { for (int n = 0; n < npar_slx; n++) { srv_slx_pars(h,n,k) = exp(log_srv_slx_pars(h,n,k)); } } } i = 0; // re-set i to 0 (do not redeclare) for(int h = 0; h < srv_blks.size(); h++){ do{ for (int k = 0; k < nsex; k++) { for (int j = 0; j < nage; j++) { // Selectivity switch (case 0 or 1 references the value of slx_type) switch (slx_type) { case 0: // Logistic with a50 and a95, where srv_slx_pars(h,0,k) = a50 and srv_slx_pars(h,1,k) = a95 srv_slx(i,j,k) = Type(1.0) / ( Type(1.0) + exp(-log(Type(19)) * (j - srv_slx_pars(h,0,k)) / (srv_slx_pars(h,1,k) - fsh_slx_pars(h,0,k))) ); break; case 1: // Logistic with a50 and slope, where srv_slx_pars(h,0,k) = a50 and srv_slx_pars(h,1,k) = slope. // *This is the preferred logistic parameterization b/c it reduces parameter correlation* srv_slx(i,j,k) = Type(1.0) / ( Type(1.0) + exp( Type(-1.0) * srv_slx_pars(h,1,k) * (j - srv_slx_pars(h,0,k)) ) ); break; } } } i++; } while (i <= srv_blks(h)); } // std::cout << srv_slx << "\n Survey selectivity \n"; // Mortality and survivorship for (int i = 0; i < nyr; i++) { Fmort(i) = exp(log_Fbar + log_F_devs(i)); // Total annual fishing mortality } for (int k = 0; k < nsex; k++) { for (int i = 0; i < nyr; i++) { for (int j = 0; j < nage; j++) { // Fishing mortality by year, age, and sex. If discard mortality (dmr) // and retention probability = 1, this eqn collapses to Fmort(i) * // fsh_slx(i,j,k) F(i,j,k) = Fmort(i) * fsh_slx(i,j,k) * (retention(0,j,k) + dmr(i,j,k) * (Type(1.0) - retention(0,j,k))); // Total mortality by year, age, and sex Z(i,j,k) = M + F(i,j,k); // Survivorship by year, age, and sex S(i,j,k) = exp(Type(-1.0) * Z(i,j,k)); } } } // std::cout << Fmort << "\n"; // std::cout << F << "\n"; // std::cout << Z << "\n"; // std::cout << S << "\n"; // Survival at time of survey, fishery, and spawning (fraction // surviving from beginning of year to the time of survey and fishery). These // quantities have the flexibility to vary by year, age, or sex, but currently // do not. Includes F because this model assumes continuous F. for (int k = 0; k < nsex; k++) { for (int i = 0; i < nyr; i++) { for (int j = 0; j < nage; j++) { survival_srv(i,j,k) = exp(Type(-1.0) * srv_month * (M + F(i,j,k))); survival_fsh(i,j,k) = exp(Type(-1.0) * fsh_month * (M + F(i,j,k))); survival_spawn(i,j,k) = exp(Type(-1.0) * spawn_month * (M + F(i,j,k))); } } } // std::cout << survival_srv << "\n"; // std::cout << survival_fsh << "\n"; // Abundance and recruitment // Start year: initial numbers-at-age (sage + 1 to plus group - 1). *FLAG* // Nijk here I've assumed the sex ratio from the survey. Could also use 0.5 // (assuming 50/50 sex ratio). Don't know what the standard practice is here. for (int k = 0; k < nsex; k++) { for (int j = 1; j < nage-1; j++) { N(0,j,k) = exp(log_rinit - M * Type(j) + log_rinit_devs(j-1)) * Type(0.5); //sex_ratio(k,j); } } // Start year: plus group *FLAG* sex ratio from survey or 50/50 or ? for (int k = 0; k < nsex; k++) { N(0,nage-1,k) = exp(log_rinit - M * Type(nage-1)) / (1 - exp(-M)) * Type(0.5); //sex_ratio(k,nage-1); } // Recruitment in all years (except the projected year) *FLAG* sex ratio from // survey or 50/50 or ? for (int k = 0; k < nsex; k++) { for (int i = 0; i < nyr; i++) { N(i,0,k) = exp(log_rbar + log_rec_devs(i)) * Type(0.5); //sex_ratio(k,0); } } // Project remaining N matrix for (int k = 0; k < nsex; k++) { for (int i = 0; i < nyr; i++) { for (int j=0; j < nage-1; j++) { N(i+1,j+1,k) = N(i,j,k) * S(i,j,k); // S is total survivorship } } } // Plus group for start year + 1 to final year + 1 (sum of cohort survivors and // surviving memebers of last year's plus group) for (int k = 0; k < nsex; k++) { for (int i = 0; i < nyr; i++) { N(i+1,nage-1,k) += N(i,nage-1,k) * S(i,nage-1,k); } } // Projected recruitment (average over recent 15 years, excluding most recent // 2 years), where the indexing of log_rec_devs(0,nyr+nage-3) *FLAG* sex ratio from // survey or 50/50 or ? for (int k = 0; k < nsex; k++) { for (int i = nyr-16; i <= nyr-2; i++) { N(nyr,0,k) += exp(log_rbar + log_rec_devs(i)) * Type(0.5); //sex_ratio(k,0); } N(nyr,0,k) /= Type(15.0); } // FLAG - Alternative way using mean(). Want to find a way to sum() over // vector // vector<Type> tmp = exp(log_rbar + log_rec_devs(nyr+nage-3-16, nyr+nage-3-2)); // N(nyr,0) = mean(tmp); // std::cout << N << "\n"; // In numbers-at-age: Total catch (C), landed catch (L), and discarded catch // assumed to die (D). Currently assuming continuous F, but may want to add // discrete F in the future. F is fully-selected, S is total survivorship. The // 0 in data_srv_waa(0,j,k) is a place holder if you ever wanted time-varying // weight-at-age. for (int k = 0; k < nsex; k++) { for (int i = 0; i < nyr; i++) { for (int j = 0; j < nage; j++) { // Total catch in numbers and summed to get a total catch biomass by year C(i,j,k) = N(i,j,k) * F(i,j,k) * (Type(1.0) - S(i,j,k)) / Z(i,j,k); // Landed catch in numbers and summed to get total landed catch in // biomass by year L(i,j,k) = retention(0,j,k) * N(i,j,k) * F(i,j,k) * (Type(1.0) - S(i,j,k)) / Z(i,j,k); pred_landed(i) += L(i,j,k) * data_fsh_waa(0,j,k) / Type(1e3) ; // in mt // Discarded catch in numbers and summed to get total biomass of dead // discards by year D(i,j,k) = dmr(i,j,k) * (Type(1.0) - retention(0,j,k)) * N(i,j,k) * F(i,j,k) * (Type(1.0) - S(i,j,k)) / Z(i,j,k); pred_wastage(i) += D(i,j,k) * data_srv_waa(0,j,k) / Type(1e3) ; // in mt } } } // Total catch summed to get a total catch biomass by year for (int i = 0; i < nyr; i++) { pred_catch(i) += pred_landed(i) + pred_wastage(i); } // std::cout << C << "\nTotal catch in numbers-at-age\n"; // std::cout << pred_catch << "\nPredicted total catch biomass\n" // std::cout << L << "\nLanded catch in numbers-at-age\n"; // std::cout << pred_landed << "\nPredicted landed catch biomass\n" // std::cout << D << "\nDead discards in numbers-at-age\n"; // std::cout << pred_wastage << "\nPredicted dead discarded biomass\n" // Predicted recruitment by year, summed over the sexes //for (int i = 0; i < nyr; i++) { // alternative approach... same answer. // pred_rec(i) = exp(log_rbar + log_rec_devs(i)); // } for (int k = 0; k < nsex; k++) { for (int i = 0; i < nyr; i++) { pred_rec(i) += N(i,0,k); } } // std::cout << "Predicted recruitment\n" << pred_rec << "\n"; // Mean recruitment Type len_rec = pred_rec.size(); Type sum_rec = 0; // temporary variable (sum over predicted recruitment values) for (int i = 0; i < nyr; i++) { sum_rec += pred_rec(i); } pred_rbar = sum_rec / len_rec; // std::cout << "sum_rec\n" << sum_rec << "\n"; // std::cout << "pred_rbar\n" << pred_rbar << "\n"; // Various flavors of projected biomass estimates [Note: the 0 in // data_srv_waa(0,j,k) and prop_mature(0,k) is a place holder if you ever // wanted time blocks or annual variation in weight-at-age or maturity] for (int k = 0; k < nsex; k++) { for (int i = 0; i < nyr; i++) { for (int j = 0; j < nage; j++) { // Total biomass at time of longline survey biom(i,j,k) = data_srv_waa(0,j,k) * N(i,j,k) * survival_srv(i,j,k); // Exploitable biomass to the fishery at the beginning of the fishery expl_biom(i,j,k) = data_srv_waa(0,j,k) * fsh_slx(i,j,k) * retention(0,j,k) * N(i,j,k) * survival_fsh(i,j,k); // Exploitable abundance to the fishery at the beginning of the fishery expl_abd(i,j,k) = fsh_slx(i,j,k) * retention(0,j,k) * N(i,j,k) * survival_fsh(i,j,k); // Vulnerable abundance to the survey at the beginning of the survey vuln_abd(i,j,k) = srv_slx(i,j,k) * N(i,j,k) * survival_srv(i,j,k); } } } // Project those values into the next year for (int k = 0; k < nsex; k++) { for (int j = 0; j < nage; j++) { biom(nyr,j,k) = data_srv_waa(0,j,k) * N(nyr,j,k) * survival_srv(nyr-1,j,k); expl_biom(nyr,j,k) = data_srv_waa(0,j,k) * fsh_slx(nyr-1,j,k) * retention(0,j,k) * N(nyr,j,k) * survival_fsh(nyr-1,j,k); expl_abd(nyr,j,k) = fsh_slx(nyr-1,j,k) * retention(0,j,k) * N(nyr,j,k) * survival_fsh(nyr-1,j,k); vuln_abd(nyr,j,k) = srv_slx(nyr-1,j,k) * N(nyr,j,k) * survival_srv(nyr-1,j,k); } } // std::cout << "Predicted biomass by age and sex \n" << biom << "\n"; // std::cout << "Predicted exploited biomass by age and sex \n" << expl_biom << "\n"; // std::cout << "Predicted vulnerable abundance by age and sex \n" << vuln_abd << "\n"; // Sum variables to get an annual total for (int k = 0; k < nsex; k++) { for (int i = 0; i <= nyr; i++) { // include projection year for (int j = 0; j < nage; j++) { // Total biomass at time of longline survey tot_biom(i) += biom(i,j,k); // Exploitable biomass to the fishery at the beginning of the fishery tot_expl_biom(i) += expl_biom(i,j,k); // Exploitable abundance to the fishery at the beginning of the fishery tot_expl_abd(i) += expl_abd(i,j,k); // Vulnerable abundance to the survey at the beginning of the survey tot_vuln_abd(i) += vuln_abd(i,j,k); } } } // std::cout << "Annual predicted biomass \n" << tot_biom << "\n"; // std::cout << "Annual predicted exploited biomass\n" << tot_expl_biom << "\n"; // std::cout << "Annual predicted vulnerable abundance\n" << tot_vuln_abd << "\n"; // Female spawning biomass: Calculated a little differently if model is // single-sex or sex-structured if (nsex == 1) { // By year and age for (int i = 0; i < nyr; i++) { for (int j = 0; j < nage; j++) { spawn_biom(i,j) = data_srv_waa(0,j,0) * N(i,j,0) * survival_spawn(i,j,0) * prop_fem(j) * prop_mature(0,j); } } // Projected for (int j = 0; j < nage; j++) { spawn_biom(nyr,j) = data_srv_waa(0,j,0) * N(nyr,j,0) * survival_spawn(nyr-1,j,0) * prop_fem(j) * prop_mature(0,j); } // Annual totals, summed over age for (int i = 0; i <= nyr; i++) { // include projection year for (int j = 0; j < nage; j++) { tot_spawn_biom(i) += spawn_biom(i,j); } } } if (nsex == 2) { // By year and age for (int i = 0; i < nyr; i++) { for (int j = 0; j < nage; j++) { spawn_biom(i,j) = data_srv_waa(0,j,1) * N(i,j,1) * survival_spawn(i,j,1) * prop_mature(0,j); } } // Projected for (int j = 0; j < nage; j++) { spawn_biom(nyr,j) = data_srv_waa(0,j,1) * N(nyr,j,1) * survival_spawn(nyr-1,j,1) * prop_mature(0,j); } // Annual totals, summed over age for (int i = 0; i <= nyr; i++) { // include projection year for (int j = 0; j < nage; j++) { tot_spawn_biom(i) += spawn_biom(i,j); } } } // std::cout << "Predicted spawning biomass by age\n" << spawn_biom << "\n"; // std::cout << "Annual predicted spawning biomass\n" << tot_spawn_biom << "\n"; // Predicted values // Mark-recapture catchability and predicted abundance (in millions) Type mr_q = exp(mr_logq); for (int i = 0; i < nyr_mr; i++) { pred_mr(i) = mr_q * (tot_expl_abd(yrs_mr(i)) / Type(1e6)); // Just in years with a MR estimate } // std::cout << "Predicted MR \n" << pred_mr << "\n"; for (int i = 0; i < nyr; i++) { pred_mr_all(i) = mr_q * (tot_expl_abd(i) / Type(1e6)); // All years } // std::cout << "Predicted MR for all years\n" << pred_mr_all << "\n"; // Fishery catchability and predicted cpue - blocks for fishery correspond to // pre- and post- Equal Quota Share vector<Type> fsh_q(fsh_blks.size()); for (int h = 0; h < fsh_blks.size(); h++){ fsh_q(h) = exp(fsh_logq(h)); } i = 0; for(int h = 0; h < fsh_blks.size(); h++){ while (i < yrs_fsh_cpue.size() && yrs_fsh_cpue(i) <= fsh_blks(h)) { pred_fsh_cpue(i) = fsh_q(h) * tot_expl_biom(yrs_fsh_cpue(i)); i++; } } // std::cout << "Predicted fishery cpue\n" << pred_fsh_cpue << "\n"; // Survey catchability and predicted survey cpue Type srv_q = exp(srv_logq); for (int i = 0; i < nyr_srv_cpue; i++) { pred_srv_cpue(i) = srv_q * tot_vuln_abd(yrs_srv_cpue(i)); } // std::cout << "Predicted srv cpue\n" << pred_srv_cpue << "\n"; // Predicted fishery age compositions - for landed portion of the catch // Temporary variables for age comp calcs Type sumL = 0; vector<Type> sumL_age(nage); vector<Type> sumN_age(nage); for (int i = 0; i < nyr_fsh_age; i++) { // sumL = temporary variable, landed catch in numbers summed over age and // sex in a given year sumL = 0; for (int k = 0; k < nsex; k++) { for (int j = 0; j < nage; j++) { sumL += L(yrs_fsh_age(i),j,k); } } // sumL_age = temporary vector of landed catch in numbers by age in a given // year (combine sexes since we currently do not have sex-structured age // comps) sumL_age.setZero(); for (int k = 0; k < nsex; k++) { for (int j = 0; j < nage; j++) { sumL_age(j) += L(yrs_fsh_age(i),j,k); } } // Get predicted age comps (proportions-at-age) for (int j = 0; j < nage; j++) { pred_fsh_age(i,j) = sumL_age(j) / sumL; } // Loop over each year i } pred_fsh_age = pred_fsh_age * ageing_error; // apply ageing error matrix // std::cout << "Predicted fishery age comps\n" << pred_fsh_age << "\n"; // Test do the predicted age comps sum to 1 // vector<Type> tst(nyr_fsh_age); // for (int i = 0; i < nyr_fsh_age; i++) { // for (int j = 0; j < nage; j++) { // tst(i) += pred_fsh_age(i,j); // } // } // std::cout << "Do the comps sum to 1?\n" << tst << "\n"; // // Type tst_n = tst.size(); // std::cout << "Length of tst vector\n" << tst_n << "\n"; // Predicted survey age compositions for (int i = 0; i < nyr_srv_age; i++) { // sumN_age = temporary vector of catch in numbers by age in a given year // (combine sexes since we currently do not have sex-structured age comps) sumN_age.setZero(); for (int k = 0; k < nsex; k++) { for (int j = 0; j < nage; j++) { sumN_age(j) += vuln_abd(yrs_srv_age(i),j,k); } } // Get predicted age comps (proportions-at-age) for (int j = 0; j < nage; j++) { pred_srv_age(i,j) = sumN_age(j) / tot_vuln_abd(yrs_srv_age(i)); } // Loop over each year i } pred_srv_age = pred_srv_age * ageing_error; // apply ageing error matrix // // Test do the predicted age comps sum to 1 // vector<Type> tst(nyr_srv_age); // for (int i = 0; i < nyr_srv_age; i++) { // for (int j = 0; j < nage; j++) { // tst(i) += pred_srv_age(i,j); // } // } // std::cout << "Do the age comps sum to 1?\n" << tst << "\n"; // Type tst_n = tst.size(); // std::cout << "Length of tst vector\n" << tst_n << "\n"; // FLAG - would like to know the TMB syntax to do the age comps in fewer // lines, for example: // for (int i = 0; i < nyr_srv_age; i++) { // for (int j = 0; j < nage; j++) { // pred_srv_age(i,j) = N(yrs_srv_age(i),j) * srv_slx(j) / sum(N(yrs_srv_age(i)) * srv_slx(j)); // } // } // Predicted fishery length compositions (for landed portion of catch)- *FLAG* // early in development, would like to streamline matrix<Type> sumL_jk(nage,nsex); vector<Type> sumL_k(nsex); for (int i = 0; i < nyr_fsh_len; i++) { sumL_k.setZero(); // tmp variable for each year sumL_jk.setZero(); for (int k = 0; k < nsex; k++) { for (int j = 0; j < nage; j++) { sumL_k(k) += L(yrs_fsh_len(i),j,k); // numbers by sex sumL_jk(j,k) += L(yrs_fsh_len(i),j,k); // numbers by sex and age } } for (int k = 0; k < nsex; k++) { for (int j = 0; j < nage; j++) { pred_fsh_obsage(i,j,k) = sumL_jk(j,k) / sumL_k(k); // Get predicted age comps (proportions-at-age) } } } matrix<Type> tmp_pred_fsh_obsage(nyr_fsh_len,nage); matrix<Type> tmp_fsh_agelen(nage,nlenbin); matrix<Type> tmp_pred_fsh_len(nyr_srv_len,nlenbin); for (int k = 0; k < nsex; k++) { tmp_pred_fsh_obsage.setZero(); for (int i = 0; i < nyr_fsh_len; i++) { for (int j = 0; j < nage; j++) { tmp_pred_fsh_obsage(i,j) = pred_fsh_obsage(i,j,k); // Extract nyr x nage matrix } } tmp_fsh_agelen.setZero(); for (int j = 0; j < nage; j++) { for (int l = 0; l < nlenbin; l++) { tmp_fsh_agelen(j,l) = agelen_key_fsh(j,l,k); // Extract age-length key } } tmp_pred_fsh_len.setZero(); tmp_pred_fsh_len = tmp_pred_fsh_obsage * tmp_fsh_agelen; // Apply age-length key for (int i = 0; i < nyr_fsh_len; i++) { for (int l = 0; l < nlenbin; l++) { pred_fsh_len(i,l,k) = tmp_pred_fsh_len(i,l); // Put everything back in the arry } } } // Test do the initial observed age comps sum to 1 // vector<Type> tst2(nyr_fsh_len); // for (int i = 0; i < nyr_fsh_len; i++) { // for (int l = 0; l < nlenbin; l++) { // tst2(i) += pred_fsh_len(i,l,0); // } // } // std::cout << "Do the length comps sum to 1?\n" << tst2 << "\n"; // Predicted survey length compositions - *FLAG* would like to streamline this matrix<Type> sumN_jk(nage,nsex); vector<Type> sumN_k(nsex); for (int i = 0; i < nyr_srv_len; i++) { sumN_k.setZero(); // tmp variable for each year sumN_jk.setZero(); for (int k = 0; k < nsex; k++) { for (int j = 0; j < nage; j++) { sumN_k(k) += vuln_abd(yrs_srv_len(i),j,k); // numbers by sex sumN_jk(j,k) += vuln_abd(yrs_srv_len(i),j,k); // numbers by sex and age } } for (int k = 0; k < nsex; k++) { for (int j = 0; j < nage; j++) { pred_srv_obsage(i,j,k) = sumN_jk(j,k) / sumN_k(k); // Get predicted age comps (proportions-at-age) } } } matrix<Type> tmp_pred_obsage(nyr_srv_len,nage); matrix<Type> tmp_agelen(nage,nlenbin); matrix<Type> tmp_pred_len(nyr_srv_len,nlenbin); for (int k = 0; k < nsex; k++) { tmp_pred_obsage.setZero(); for (int i = 0; i < nyr_srv_len; i++) { for (int j = 0; j < nage; j++) { tmp_pred_obsage(i,j) = pred_srv_obsage(i,j,k); // Extract nyr x nage matrix } } tmp_agelen.setZero(); for (int j = 0; j < nage; j++) { for (int l = 0; l < nlenbin; l++) { tmp_agelen(j,l) = agelen_key_srv(j,l,k); // Extract age-length key } } tmp_pred_len.setZero(); tmp_pred_len = tmp_pred_obsage * tmp_agelen; // Apply age-length key for (int i = 0; i < nyr_srv_len; i++) { for (int l = 0; l < nlenbin; l++) { pred_srv_len(i,l,k) = tmp_pred_len(i,l); // Put everything back in the array } } } // Test do the initial observed age comps sum to 1 // vector<Type> tst3(nyr_srv_len); // for (int i = 0; i < nyr_srv_len; i++) { // for (int l = 0; l < nlenbin; l++) { // tst3(i) += pred_srv_len(i,l,0); // } // } // std::cout << "Do the length comps sum to 1?\n" << tst3 << "\n"; // Compute SPR rates and spawning biomass under different Fxx levels. Note // that biological reference points are only for the female component of the // population. // Preliminary calcs, get Fs out of log space vector<Type> spr_Fxx(n_Fxx+1); spr_Fxx(0) = 0; // No fishing for(int x = 1; x <= n_Fxx; x++) { spr_Fxx(x) = exp(log_spr_Fxx(x-1)); } // For SPR calculations, use only female fishery selectivity in the most recent time block for all calculations. The 'nsex-1' should work // for both single sex and sex-structured versions vector<Type> spr_fsh_slx(nage); for (int j = 0; j < nage; j++) { spr_fsh_slx(j) = fsh_slx(nyr-1,j,nsex-1); } // std::cout << "spr fishery selectivity\n" << spr_fsh_slx << "\n"; Fxx(0) = 0; // No fishing // Scale Fxx to fully selected values (not necessary for logistic selectivity // b/c max is 1 but may be needed for other selectivity types in future // development). for(int x = 1; x <= n_Fxx; x++) { Fxx(x) = spr_Fxx(x) * max(spr_fsh_slx); } // std::cout << "Fxx\n" << Fxx << "\n"; // Populate numbers of potential spawners at age matrix - Note: for the Nspr // and SBPR calculations, the Federal assessment uses the equivalent of // spr_Fxx instead of the scales Fxx. Not sure why. for(int x = 0; x <= n_Fxx; x++) { Nspr(x,0) = Type(1.0); // Initialize SPR with 1 // Survival equation by age for(int j = 1; j < nage - 1; j++) { Nspr(x,j) = Nspr(x,j-1) * exp(Type(-1.0) * (Fxx(x) * spr_fsh_slx(j-1) + M)); } // Plus group Nspr(x,nage-1) = Nspr(x,nage-2) * exp(Type(-1.0) * (Fxx(x) * spr_fsh_slx(nage-2) + M)) / (Type(1.0) - exp(Type(-1.0) * (Fxx(x) * spr_fsh_slx(nage-1) + M))); } // std::cout << "Number of spawners\n" << Nspr << "\n"; // Unfished spawning biomass per recruit for(int j = 0; j < nage; j++) { SBPR(0) += Nspr(0,j) * prop_mature(j) * data_srv_waa(0,j,1) * survival_spawn(nyr-1,j,nsex-1); //Type(0.5) * } // Remaining spawning biomass per recruit matrix for(int x = 1; x <= n_Fxx; x++) { for(int j = 0; j < nage; j++) { if (nsex == 1) { // single sex model uses prop_fem vector SBPR(x) += Nspr(x,j) * prop_mature(j) * data_srv_waa(0,j,1) * exp(Type(-1.0) * spawn_month * (M + Fxx(x) * spr_fsh_slx(j))); //prop_fem(j) * } if (nsex == 2) { // sex-structured model uses sex_ratio matrix SBPR(x) += Nspr(x,j) * prop_mature(0,j) * data_srv_waa(0,j,1) * exp(Type(-1.0) * spawn_month * (M + Fxx(x) * spr_fsh_slx(j))); //sex_ratio(nsex-1,j) * } } } // std::cout << "Spawning biomass per recruit\n" << SBPR << "\n"; // Mean recruitment, where spr_rec_type is a switch for different assumptions // of what the "mean" should be Type mean_rec; switch (spr_rec_type) { case 0: // Arithmentic mean mean_rec = 0; for (int i = 0; i < nyr; i++) { mean_rec += pred_rec(i); } mean_rec /= nyr; break; case 1: // Geometric mean mean_rec = 1; for (int i = 0; i < nyr; i++) { mean_rec *= pred_rec(i); } mean_rec = pow(mean_rec, Type(1)/nyr); break; // case 2: // Median *FLAG* future development } // Virgin female spawning biomass (no fishing), assuming 50:50 sex ratio for // recruitment (equivalent to B_100) // SB(0) = SBPR(0) * mean_rec; // Spawning biomass as a fraction of virgin spawning biomass - FLAG check this // for(int x = 1; x <= n_Fxx; x++) { // SB(x) = Fxx_levels(x-1) * SB(0); // } for(int x = 0; x <= n_Fxx; x++) { SB(x) = Type(0.5) * SBPR(x) * mean_rec; // } // std::cout << "Spawning biomass\n" << SB << "\n"; // Get Allowable Biological Catch and wastage estimates for different Fxx levels: all of // these should be sex-structured, then final ABC will be summed across sexes for(int x = 0; x < n_Fxx; x++) { for(int k = 0; k < nsex; k++) { for(int j = 0; j < nage; j++) { // Fully selected fishing mortality by age and sex. If discard mortality // (dmr) and retention probability = 1, this eqn collapses to Fmort * // fsh_slx) sel_Fxx(x,j,k) = Fxx(x+1) * fsh_slx(nyr-1,j,k) * (retention(0,j,k) + dmr(nyr-1,j,k) * (Type(1.0) - retention(0,j,k))); Z_Fxx(x,j,k) = M + sel_Fxx(x,j,k); // Total instantaneous mortality at age S_Fxx(x,j,k) = exp(-Z_Fxx(x,j,k)); // Total survival at age } } } for(int i = 0; i <= nyr; i++) { // include forecast year for(int x = 0; x < n_Fxx; x++) { for(int k = 0; k < nsex; k++) { for(int j = 0; j < nage; j++) { // ABC calculation (landed catch under Fxx) using projected abundance ABC(i,x) += data_srv_waa(0,j,k) * retention(0,j,k) * N(i,j,k) * sel_Fxx(x,j,k) * (Type(1.0) - S_Fxx(x,j,k)) / Z_Fxx(x,j,k); // Discarded catch assumed to die under Fxx wastage(i,x) += data_srv_waa(0,j,k) * dmr(nyr-1,j,k) * (Type(1.0) - retention(0,j,k)) * N(i,j,k) * sel_Fxx(x,j,k) * (Type(1.0) - S_Fxx(x,j,k)) / Z_Fxx(x,j,k); } } } } // The final ABC is then the difference between the preliminary ABC and wastage estimates for(int i = 0; i <= nyr; i++) { for(int x = 0; x < n_Fxx; x++) { ABC(i,x) = ABC(i,x) - wastage(i,x); } } // std::cout << "ABC\n" << ABC << "\n"; // std::cout << "Wastage\n" << wastage << "\n"; // Get sex-specific numbers-at-length for Luke Rogers data request array<Type> Nlen(nyr+1,nlenbin,nsex); matrix<Type> tmp_N(nyr+1,nage); matrix<Type> tmp_Nlen(nyr+1,nage); // matrix<Type> tmp_agelen(nage,nlenbin); // already defined when predicting len comps for (int k = 0; k < nsex; k++) { tmp_N.setZero(); for (int i = 0; i < nyr+1; i++) { for (int j = 0; j < nage; j++) { tmp_N(i,j) = N(i,j,k); // Extract nyr+1 x nage matrix } } tmp_agelen.setZero(); for (int j = 0; j < nage; j++) { for (int l = 0; l < nlenbin; l++) { tmp_agelen(j,l) = agelen_key_srv(j,l,k); // Extract sex-specific age-length key } } tmp_Nlen.setZero(); tmp_Nlen = tmp_N * tmp_agelen; // Apply age-length key for (int i = 0; i < nyr+1; i++) { for (int l = 0; l < nlenbin; l++) { Nlen(i,l,k) = tmp_Nlen(i,l); // Put everything into array } } } // Priors // Fishery cpue catchability coefficient for (int h = 0; h < fsh_blks.size(); h++){ priors(0) += square( log(fsh_q(h) / p_fsh_q(h)) ) / ( Type(2.0) * square(sigma_fsh_q(h)) ); } // Survey catchability coefficient priors(1) = square( log(srv_q / p_srv_q) ) / ( Type(2.0) * square(sigma_srv_q) ); // Mark-recapture abundance estimate catchability coefficient priors(2) = square( log(mr_q / p_mr_q) ) / ( Type(2.0) * square(sigma_mr_q) ); // std::cout << "priors\n" << priors << "\n"; // Only calculate prior for M if estimated (M_type = 1), otherwise stays 0 and // adds nothing to objective function if(M_type == 1) { prior_M += square(log_M - p_log_M) / (Type(2.0) * square(p_sigma_M)); } // Catch: normal (check) // for (int i = 0; i < nyr; i++) { // catch_like += square( (data_catch(i) - pred_landed(i)) / pred_landed(i)) / // (Type(2.0) * square(sigma_catch(i))); // } // Catch: lognormal // for (int i = 0; i < nyr; i++) { // catch_like += square( log((data_catch(i) + c) / (pred_landed(i) + c)) )/ // Type(2.0) * square(sigma_catch(i)); // } // Catch: lognormal alternative (these should be equivalent) for (int i = 0; i < nyr; i++) { catch_like += square( log(data_catch(i) + c) - log(pred_landed(i) + c) )/ (Type(2.0) * square(sigma_catch(i))); } catch_like *= wt_catch; // Likelihood weight // std::cout << "Catch likelihood\n" << catch_like << "\n"; // Fishery CPUE: lognormal for (int i = 0; i < nyr_fsh_cpue; i++) { index_like(0) += square( log((data_fsh_cpue(i) + c) / (pred_fsh_cpue(i) + c)) ) / (Type(2.0) * square(sigma_fsh_cpue(i))); } index_like(0) *= wt_fsh_cpue; // Likelihood weight // Survey CPUE: lognormal for (int i = 0; i < nyr_srv_cpue; i++) { index_like(1) += square( log((data_srv_cpue(i) + c) / (pred_srv_cpue(i) + c)) ) / (Type(2.0) * square(sigma_srv_cpue(i))); } index_like(1) *= wt_srv_cpue; // Likelihood weight // Mark-recapture index: lognormal for (int i = 0; i < nyr_mr; i++) { index_like(2) += square( log((data_mr(i) + c) / (pred_mr(i) + c)) ) / (Type(2.0) * square(sigma_mr(i))); } index_like(2) *= wt_mr; // Likelihood weight // std::cout << "Index likelihoods\n" << index_like << "\n"; // Likelihood for fishery age compositions Type fsh_theta = exp(log_fsh_theta); // Dirichlet-multinomial parameter vector<Type> sum1_fsh(nyr_fsh_age); // First sum in D-M likelihood (log of Eqn 10, Thorson et al. 2017) vector<Type> sum2_fsh(nyr_fsh_age); // Second sum in D-M likelihood (log of Eqn 10, Thorson et al. 2017) //fsh_theta.setZero(); sum1_fsh.setZero(); sum2_fsh.setZero(); // Switch for composition likelihood (case 0 or 1 references the value of comp_type) switch (comp_type) { case 0: // Multinomial for (int i = 0; i < nyr_fsh_age; i++) { for (int j = 0; j < nage; j++) { // Offset offset(0) -= effn_fsh_age(i) * (data_fsh_age(i,j) + c) * log(data_fsh_age(i,j) + c); // Likelihood age_like(0) -= effn_fsh_age(i) * (data_fsh_age(i,j) + c) * log(pred_fsh_age(i,j) + c); } } age_like(0) -= offset(0); // subtract offset age_like(0) *= wt_fsh_age; // likelihood weight break; case 1: // Dirichlet-multinomial (D-M) for (int i = 0; i < nyr_fsh_age; i++) { // Preliminary calcs for (int j = 0; j < nage; j++) { // First sum in D-M likelihood (log of Eqn 10, Thorson et al. 2017) sum1_fsh(i) += lgamma( n_fsh_age(i) * data_fsh_age(i,j) + Type(1.0) ); // Second sum in D-M likelihood (log of Eqn 10, Thorson et al. 2017) //sum2_fsh(i) += lgamma( n_fsh_age(i) + data_fsh_age(i,j) + fsh_theta * n_fsh_age(i) * pred_fsh_age(i,j) ) - // lgamma( fsh_theta * n_fsh_age(i) - pred_fsh_age(i,j) ); sum2_fsh(i) += lgamma( n_fsh_age(i) * data_fsh_age(i,j) + fsh_theta * n_fsh_age(i) * pred_fsh_age(i,j) ) - lgamma( fsh_theta * n_fsh_age(i) * pred_fsh_age(i,j) ); // second n_fsh_age(i) should be big N in Thorso which is not specified an may be a typo? //sum2_fsh(i) += lgamma( n_fsh_age(i) * data_fsh_age(i,j) + fsh_theta * bigN * pred_fsh_age(i,j) ) - // lgamma( fsh_theta * n_fsh_age(i) * pred_fsh_age(i,j) ); } // Full nll for D-M, Eqn 10, Thorson et al. 2017 //age_like(0) -= lgamma(n_fsh_age(i) + Type(1.0)) - sum1_fsh(i) + lgamma(fsh_theta * n_fsh_age(i)) - // lgamma(n_fsh_age(i) + fsh_theta * n_fsh_age(i)) + sum2_fsh(i); age_like(0) -= lgamma(n_fsh_age(i) + Type(1.0)) - sum1_fsh(i) + lgamma(fsh_theta * n_fsh_age(i)) - lgamma(n_fsh_age(i) + fsh_theta * n_fsh_age(i)) + sum2_fsh(i); } break; // case 2: // Multivariate logistic (MVL) - future development } // Likelihood for survey age compositions Type srv_theta = exp(log_srv_theta); // Dirichlet-multinomial parameter vector<Type> sum1_srv(nyr_srv_age); // First sum in D-M likelihood (log of Eqn 10, Thorson et al. 2017) vector<Type> sum2_srv(nyr_srv_age); // Second sum in D-M likelihood (log of Eqn 10, Thorson et al. 2017) //srv_theta.setZero(); sum1_srv.setZero(); sum2_srv.setZero(); // Switch for composition likelihood (case 0 or 1 references the value of comp_type) switch (comp_type) { case 0: // Multinomial for (int i = 0; i < nyr_srv_age; i++) { for (int j = 0; j < nage; j++) { // Offset offset(1) -= effn_srv_age(i) * (data_srv_age(i,j) + c) * log(data_srv_age(i,j) + c); // Likelihood age_like(1) -= effn_srv_age(i) * (data_srv_age(i,j) + c) * log(pred_srv_age(i,j) + c); } } age_like(1) -= offset(1); // subtract offset age_like(1) *= wt_srv_age; // likelihood weight break; case 1: // Dirichlet-multinomial (D-M) for (int i = 0; i < nyr_srv_age; i++) { // Preliminary calcs for (int j = 0; j < nage; j++) { // First sum in D-M likelihood (log of Eqn 10, Thorson et al. 2017) sum1_srv(i) += lgamma( n_srv_age(i) * data_srv_age(i,j) + Type(1.0) ); // Second sum in D-M likelihood (log of Eqn 10, Thorson et al. 2017) //sum2_srv(i) += lgamma( n_srv_age(i) + data_srv_age(i,j) + srv_theta * n_srv_age(i) * pred_srv_age(i,j) ) - // lgamma( srv_theta * n_srv_age(i) - pred_srv_age(i,j) ); sum2_srv(i) += lgamma( n_srv_age(i) * data_srv_age(i,j) + srv_theta * n_srv_age(i) * pred_srv_age(i,j) ) - lgamma( srv_theta * n_srv_age(i) * pred_srv_age(i,j) ); //switch - to * ?? } // Full nll for D-M, Eqn 10, Thorson et al. 2017 //age_like(1) -= lgamma(n_srv_age(i) + Type(1.0)) - sum1_srv(i) + lgamma(srv_theta * n_srv_age(i)) - // lgamma(n_srv_age(i) + srv_theta * n_srv_age(i)) + sum2_srv(i); age_like(1) -= lgamma(n_srv_age(i) + Type(1.0)) - sum1_srv(i) + lgamma(srv_theta * n_srv_age(i)) - lgamma(n_srv_age(i) + srv_theta * n_srv_age(i)) + sum2_srv(i); } break; // case 2: // Multivariate logistic - future development } // std::cout << "Age comp offset\n" << offset << "\n"; // std::cout << "Age comp likelihoods\n" << age_like << "\n"; // Multinomial likelihood for fishery length comps. for (int k = 0; k < nsex; k++) { for (int i = 0; i < nyr_fsh_len; i++) { for (int l = 0; l < nlenbin; l++) { // Offset offset_fsh_len(k) -= effn_fsh_len(i,0,k) * (data_fsh_len(i,l,k) + c) * log(data_fsh_len(i,l,k) + c); // Likelihood fsh_len_like(k) -= effn_fsh_len(i,0,k) * (data_fsh_len(i,l,k) + c) * log(pred_fsh_len(i,l,k) + c); } } fsh_len_like(k) -= offset_fsh_len(k); // subtract offset fsh_len_like(k) *= wt_fsh_len; // likelihood weight } // Multinomial likelihood for survey length comps. for (int k = 0; k < nsex; k++) { for (int i = 0; i < nyr_srv_len; i++) { for (int l = 0; l < nlenbin; l++) { // Offset offset_srv_len(k) -= effn_srv_len(i,0,k) * (data_srv_len(i,l,k) + c) * log(data_srv_len(i,l,k) + c); // Likelihood srv_len_like(k) -= effn_srv_len(i,0,k) * (data_srv_len(i,l,k) + c) * log(pred_srv_len(i,l,k) + c); } } srv_len_like(k) -= offset_srv_len(k); // subtract offset srv_len_like(k) *= wt_srv_len; // likelihood weight } // Recruitment - random_rec switches between penalized likelihood and random // effects. Shared sigma_r between rinit_devs and rec_devs, rinit_devs are the // same as the rec_devs but have been reduced by mortality. They were kept // separate to help with accounting. // Penalized likelihood, sigma_r fixed, bias correction for lognormal // likelihood (-0.5*sigma^2) needed to get mean instead of median from // distribution if (random_rec == 0) { // Annual recruitment deviations for (int i = 0; i < nyr; i++) { rec_like += square(log_rec_devs(i) - Type(0.5) * square(sigma_r)); } // Initial numbers-at-age (sage + 1 to plus group - 1) for (int j = 0; j < nage - 2; j++) { rec_like += square(log_rinit_devs(j) - Type(0.5) * square(sigma_r)); } rec_like *= wt_rec_like; // weight } // Random effects: mean = 0, sigma_r estimated, same bias correction as // penalized likelihood for lognormal distribution if (random_rec == 1) { // Recruitment deviations for (int i = 0; i < nyr; i++) { rec_like += log(sigma_r) + Type(0.5) * square(log_rec_devs(i) - Type(0.5) * square(sigma_r)) / square(sigma_r); // Should be equivalent to: rec_like -= dnorm(log_rec_dev(i) - Type(0.5) * square(sigma_r) , Type(0.0), sigma_r, true); } // Initial numbers-at-age (sage + 1 to plus group - 1) for (int j = 0; j < nage - 2; j++) { rec_like += log(sigma_r) + Type(0.5) * square(log_rinit_devs(j) - Type(0.5) * square(sigma_r)) / square(sigma_r); } rec_like *= wt_rec_like; // weight } // std::cout << "Log recruitment deviations\n" << log_rec_devs << "\n"; // std::cout << "Log deviations for initial numbers-at-age\n" << log_rinit_devs << "\n"; // std::cout << "Recruitment likelihood\n" << rec_like << "\n"; // Regularity penalty on fishing mortality for (int i = 0; i < nyr; i++) { fpen += square(log_F_devs(i)); } fpen *= wt_fpen; // weight // Large penalty on SPR calculations for(int x = 1; x <= n_Fxx; x++) { spr_pen += wt_spr * square(SBPR(x) / SBPR(0) - Fxx_levels(x-1)); } // std::cout << "Log fishing mortality deviations\n" << log_F_devs << "\n"; // std::cout << "Penality for fishing mortality\n" << fpen << "\n"; // std::cout << "Penality for SPR calcs\n" << spr_pen << "\n"; // Sum likelihood components obj_fun += priors(0); // Fishery q obj_fun += priors(1); // Survey q obj_fun += priors(2); // Mark-recapture abndance index q obj_fun += prior_M; // prior for natural mortality (if fixed this is 0) obj_fun += catch_like; // Catch obj_fun += index_like(0); // Fishery cpue obj_fun += index_like(1); // Survey cpue obj_fun += index_like(2); // Mark-recapture abundance index obj_fun += age_like(0); // Fishery age compositions obj_fun += age_like(1); // Survey age compositions for (int k = 0; k < nsex; k++) { obj_fun += fsh_len_like(k); // Fishery length comps obj_fun += srv_len_like(k); // Survey length comps } obj_fun += rec_like; // Recruitment deviations obj_fun += fpen; // Fishing mortality deviations obj_fun += spr_pen; // SPR calculations // std::cout << "Objective function\n" << obj_fun << "\n"; // obj_fun = dummy*dummy; // Uncomment when debugging code // REPORT SECTION // Predicted indices of catch and abundance REPORT(pred_catch); // Total catch REPORT(pred_landed); // Landed catch REPORT(pred_wastage); // Discarded catch assumed to die REPORT(pred_mr); // Mark-recapture index of abundance (only years with an estimate) REPORT(pred_mr_all); // Mark-recapture index of abundance (all years) REPORT(pred_fsh_cpue); // Fishery cpue REPORT(pred_srv_cpue); // Survey cpue // Predicted compositions REPORT(pred_fsh_age); // Fishery REPORT(pred_srv_age); // Survey REPORT(pred_fsh_len); // Fishery REPORT(pred_srv_len); // Survey // Predicted selectivity-at-age REPORT(fsh_slx); // Fishery REPORT(srv_slx); // Survey // Predicted annual fishing mortality REPORT(Fmort); // Derived matrices by year and age REPORT(N); // Abundance-at-age, projected 1 year forward REPORT(Nlen); // Abundance-at-length, projected 1 year forward REPORT(Z); // Total mortality REPORT(F); // Fishing mortality REPORT(S); // Survivorship REPORT(C); // Catch in numbers at age // Derived vectors by year ADREPORT(pred_rec); // Predicted age-2 recruitment REPORT(pred_rec); // Predicted age-2 recruitment REPORT(tot_biom); // Total age-2+ biomass REPORT(tot_expl_biom); // Vulnerable biomass to fishery at the beginning of the fishery REPORT(tot_expl_abd); // Vulnerable abundance to fishery at the beginning of the fishery REPORT(tot_vuln_abd); // Vulnerable abundance to survey at the beginning of the survey REPORT(tot_spawn_biom); // Female spawning biomass // Derived arrays by year, age, sex REPORT(biom); // Total age-2+ biomass REPORT(expl_biom); // Vulnerable biomass to fishery at the beginning of the fishery REPORT(expl_abd); // Vulnerable abundance to fishery at the beginning of the fishery REPORT(vuln_abd); // Vulnerable abundance to survey at the beginning of the survey REPORT(spawn_biom); // Spawning biomass // // SPR-based biological reference points and ABC REPORT(Fxx); // Vector of Fs scaled to fully selected values REPORT(sel_Fxx); // Fishery selectivity used in ABC calcs REPORT(SBPR); // Vector of spawning biomass per recruit at various Fxx levels REPORT(mean_rec); // Mean recruitment assumed to be equilibrium recruitment REPORT(SB); // Vector of spawning biomass at various Fxx levels REPORT(ABC); // ABC at various Fxx levels REPORT(wastage); // Dead discarded catch at various Fxx levels // Other derived and projected values REPORT(survival_srv); // Survival at time of survey REPORT(survival_fsh); // Survival at time of fishery REPORT(survival_spawn); // Survival at time of spawning REPORT(pred_rbar); // Predicted mean recruitment // Priors, likelihoods, offsets, and penalty functions REPORT(priors); // q priors REPORT(prior_M); // M prior REPORT(catch_like); // Catch REPORT(index_like); // Abundance indices REPORT(age_like); // Age compositions REPORT(srv_len_like); // Survey length composition likelihoods REPORT(fsh_len_like); // Fishery length composition likelihoods REPORT(rec_like); // Recruitment deviations REPORT(fpen); // Fishing mortality deviations REPORT(spr_pen); // SPR penalty REPORT(obj_fun); // Total objective function REPORT(offset); // Offsets for age comp multinomial REPORT(offset_srv_len); // Offsets for survey length comp multinomial REPORT(offset_fsh_len); // Offsets for fishery length comp multinomial return(obj_fun); }
[ "philip.joy@alaska.gov" ]
philip.joy@alaska.gov
76a22172829ff41aba3eecf2ca8b2b1440114363
07306d96ba61d744cb54293d75ed2e9a09228916
/External/NaturalMotion/morpheme/SDK/euphoriaCoreBehaviours/AutoGenerated/SteppingBalancePackaging.h
fea38e4d5a40da784411a68c012d658deb64293a
[]
no_license
D34Dspy/warz-client
e57783a7c8adab1654f347f389c1dace35b81158
5262ea65e0baaf3f37ffaede5f41c9b7eafee7c1
refs/heads/master
2023-03-17T00:56:46.602407
2015-12-20T16:43:00
2015-12-20T16:43:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,871
h
#pragma once /* * Copyright (c) 2013 NaturalMotion Ltd. All rights reserved. * * Not to be copied, adapted, modified, used, distributed, sold, * licensed or commercially exploited in any manner without the * written consent of NaturalMotion. * * All non public elements of this software are the confidential * information of NaturalMotion and may not be disclosed to any * person nor used for any purpose not expressly approved by * NaturalMotion in writing. * */ //---------------------------------------------------------------------------------------------------------------------- // This file is auto-generated //---------------------------------------------------------------------------------------------------------------------- #ifndef NM_MDF_STEPPINGBALANCE_PKG_H #define NM_MDF_STEPPINGBALANCE_PKG_H // include definition file to create project dependency #include "./Definition/Modules/SteppingBalance.module" #include "SteppingBalanceData.h" #include "BalanceManagementPackaging.h" namespace MR { class InstanceDebugInterface; } namespace NM_BEHAVIOUR_LIB_NAMESPACE { //---------------------------------------------------------------------------------------------------------------------- // API Packaging struct SteppingBalanceAPIBase { SteppingBalanceAPIBase( const SteppingBalanceData* const _data, const SteppingBalanceInputs* const _in, const SteppingBalanceFeedbackInputs* const _feedIn, const BalanceManagementAPIBase* const _owner ) :data(_data) ,in(_in) ,feedIn(_feedIn) ,owner(_owner) {} const SteppingBalanceData* const data; const SteppingBalanceInputs* const in; const SteppingBalanceFeedbackInputs* const feedIn; const BalanceManagementAPIBase* const owner; SteppingBalanceAPIBase(const SteppingBalanceAPIBase& rhs); SteppingBalanceAPIBase& operator = (const SteppingBalanceAPIBase& rhs); }; //---------------------------------------------------------------------------------------------------------------------- // Update Packaging struct SteppingBalanceUpdatePackage : public SteppingBalanceAPIBase { SteppingBalanceUpdatePackage( SteppingBalanceData* const _data, const SteppingBalanceInputs* const _in, const SteppingBalanceFeedbackInputs* const _feedIn, SteppingBalanceOutputs* const _out, const BalanceManagementAPIBase* const _owner ) : SteppingBalanceAPIBase(_data ,_in ,_feedIn ,_owner ), data(_data), out(_out) { } SteppingBalanceData* const data; SteppingBalanceOutputs* const out; // module update entrypoint void update(float timeStep, MR::InstanceDebugInterface* pDebugDrawInst); SteppingBalanceUpdatePackage(const SteppingBalanceUpdatePackage& rhs); SteppingBalanceUpdatePackage& operator = (const SteppingBalanceUpdatePackage& rhs); }; //---------------------------------------------------------------------------------------------------------------------- // Feedback Packaging struct SteppingBalanceFeedbackPackage : public SteppingBalanceAPIBase { SteppingBalanceFeedbackPackage( SteppingBalanceData* const _data, const SteppingBalanceFeedbackInputs* const _feedIn, const SteppingBalanceInputs* const _in, SteppingBalanceFeedbackOutputs* const _feedOut, const BalanceManagementAPIBase* const _owner ) : SteppingBalanceAPIBase(_data ,_in ,_feedIn ,_owner ), data(_data), feedOut(_feedOut) { } SteppingBalanceData* const data; SteppingBalanceFeedbackOutputs* const feedOut; // module feedback entrypoint void feedback(float timeStep, MR::InstanceDebugInterface* pDebugDrawInst); SteppingBalanceFeedbackPackage(const SteppingBalanceFeedbackPackage& rhs); SteppingBalanceFeedbackPackage& operator = (const SteppingBalanceFeedbackPackage& rhs); }; } // namespace NM_BEHAVIOUR_LIB_NAMESPACE #endif // NM_MDF_STEPPINGBALANCE_PKG_H
[ "hasan@openkod.com" ]
hasan@openkod.com
8ff3a3dc29e81cceed58f4f04d1c2b1300c64cfa
af52fd80f18ca6b33e5abff650f23bd437087e10
/top4000/3163-pdftotext-2.1.6/pdftotext.cpp
9f9e3ad3b61c32259dcec1762ce9494e604f3f16
[ "MIT" ]
permissive
hpyproject/top4000-pypi-packages
8338ee316ab073bfba022c4c0d3f24256b01bfc6
0cd919943a007f95f4bf8510e667cfff5bd059fc
refs/heads/master
2023-05-11T22:26:04.188536
2021-06-03T09:56:00
2021-06-03T09:56:00
372,450,555
6
0
null
null
null
null
UTF-8
C++
false
false
9,379
cpp
#include <Python.h> #include <poppler/cpp/poppler-document.h> #include <poppler/cpp/poppler-global.h> #include <poppler/cpp/poppler-page.h> #include <algorithm> #include <climits> #include <string> #include <vector> static PyObject* PdftotextError; typedef struct { PyObject_HEAD int page_count; bool raw; PyObject* data; poppler::document* doc; } PDF; static void PDF_clear(PDF* self) { self->page_count = 0; self->raw = false; delete self->doc; self->doc = NULL; Py_CLEAR(self->data); } static int PDF_set_raw(PDF* self, int raw) { if (raw == 0) { self->raw = false; } else if (raw == 1) { self->raw = true; } else { PyErr_Format(PyExc_ValueError, "a boolean is required"); return -1; } return 0; } static int PDF_load_data(PDF* self, PyObject* file) { #if PY_MAJOR_VERSION >= 3 self->data = PyObject_CallMethod(file, "read", NULL); #else self->data = PyObject_CallMethod(file, (char*)"read", NULL); #endif if (self->data == NULL) { return -1; } return 0; } static int PDF_create_doc(PDF* self) { Py_ssize_t len; char* buf; if (PyBytes_AsStringAndSize(self->data, &buf, &len) < 0) { return -1; } if (len > INT_MAX) { PyErr_Format(PdftotextError, "invalid buffer length %zd", len); return -1; } self->doc = poppler::document::load_from_raw_data(buf, (int)len); if (self->doc == NULL) { PyErr_Format(PdftotextError, "poppler error creating document"); return -1; } return 0; } static int PDF_unlock(PDF* self, char* password) { if (self->doc->unlock(std::string(password), std::string(password))) { PyErr_Format(PdftotextError, "failed to unlock document"); return -1; } return 0; } static int PDF_init(PDF* self, PyObject* args, PyObject* kwds) { PyObject* pdf_file; char* password = (char*)""; int raw = 0; static char* kwlist[] = {(char*)"pdf_file", (char*)"password", (char*)"raw", NULL}; PDF_clear(self); if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si", kwlist, &pdf_file, &password, &raw)) { goto error; } if (PDF_set_raw(self, raw) < 0) { goto error; } if (PDF_load_data(self, pdf_file) < 0) { goto error; } if (PDF_create_doc(self) < 0) { goto error; } if (PDF_unlock(self, password) < 0) { goto error; } self->page_count = self->doc->pages(); return 0; error: PDF_clear(self); return -1; } static void PDF_dealloc(PDF* self) { PDF_clear(self); Py_TYPE(self)->tp_free((PyObject*)self); } static PyObject* PDF_read_page(PDF* self, int page_number) { const poppler::page* page; poppler::page::text_layout_enum layout_mode; std::vector<char> page_utf8; page = self->doc->create_page(page_number); if (page == NULL) { return PyErr_Format(PdftotextError, "poppler error creating page"); } layout_mode = poppler::page::physical_layout; if (self->raw) { layout_mode = poppler::page::raw_order_layout; } #if POPPLER_CPP_AT_LEAST_0_58_0 page_utf8 = page->text(poppler::rectf(0, 0, 0, 0), layout_mode).to_utf8(); #else // Workaround for poppler bug #94517, fixed in poppler 0.58.0, released 2017-09-01 const poppler::rectf rect = page->page_rect(); const int min = std::min(rect.left(), rect.top()); const int max = std::max(rect.right(), rect.bottom()); page_utf8 = page->text(poppler::rectf(min, min, max, max), layout_mode).to_utf8(); #endif delete page; return PyUnicode_DecodeUTF8(page_utf8.data(), page_utf8.size(), NULL); } static Py_ssize_t PDF_len(PyObject* obj) { PDF* self = (PDF*)obj; return self->page_count; } static PyObject* PDF_getitem(PyObject* obj, Py_ssize_t i) { PDF* self = (PDF*)obj; if (i < 0 || i >= self->page_count) { return PyErr_Format(PyExc_IndexError, "index out of range"); } return PDF_read_page(self, (int)i); } static PySequenceMethods PDF_sequence_methods = { PDF_len, // sq_length (__len__) 0, // sq_concat 0, // sq_repeat PDF_getitem, // sq_item (__getitem__) }; static PyTypeObject PDFType = { PyVarObject_HEAD_INIT(NULL, 0) "pdftotext.PDF", // tp_name sizeof(PDF), // tp_basicsize 0, // tp_itemsize (destructor)PDF_dealloc, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr 0, // tp_reserved 0, // tp_repr 0, // tp_as_number &PDF_sequence_methods, // tp_as_sequence 0, // tp_as_mapping 0, // tp_hash 0, // tp_call 0, // tp_str 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, // tp_flags "PDF(pdf_file, password=\"\", raw=False)\n" "\n" "Args:\n" " pdf_file: A file opened for reading in binary mode.\n" " password: Unlocks the document, if required. Either the owner\n" " password or the user password works.\n" " raw: If True, page text is output in the order it appears in the\n" " content stream, rather than in the order it appears on the\n" " page.\n" "\n" "Example:\n" " with open(\"doc.pdf\", \"rb\") as f:\n" " pdf = PDF(f)\n" " for page in pdf:\n" " print(page)", // tp_doc 0, // tp_traverse 0, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset 0, // tp_iter 0, // tp_iternext 0, // tp_methods 0, // tp_members 0, // tp_getset 0, // tp_base 0, // tp_dict 0, // tp_descr_get 0, // tp_descr_set 0, // tp_dictoffset (initproc)PDF_init, // tp_init }; #if POPPLER_CPP_AT_LEAST_0_30_0 static void do_nothing(const std::string&, void*) {} #endif #if PY_MAJOR_VERSION >= 3 static PyModuleDef pdftotextmodule = { PyModuleDef_HEAD_INIT, "pdftotext", "Simple PDF text extraction.", }; PyMODINIT_FUNC PyInit_pdftotext() { PyObject* module; PDFType.tp_new = PyType_GenericNew; if (PyType_Ready(&PDFType) < 0) { return NULL; } module = PyModule_Create(&pdftotextmodule); if (module == NULL) { return NULL; } Py_INCREF(&PDFType); PyModule_AddObject(module, "PDF", (PyObject*)&PDFType); PdftotextError = PyErr_NewExceptionWithDoc( "pdftotext.Error", "PDF error.", NULL, NULL); Py_INCREF(PdftotextError); PyModule_AddObject(module, "Error", PdftotextError); #if POPPLER_CPP_AT_LEAST_0_30_0 poppler::set_debug_error_function(do_nothing, NULL); #endif return module; } #else PyMODINIT_FUNC initpdftotext() { PyObject* module; PDFType.tp_new = PyType_GenericNew; if (PyType_Ready(&PDFType) < 0) { return; } module = Py_InitModule3("pdftotext", NULL, "Simple PDF text extraction."); if (module == NULL) { return; } Py_INCREF(&PDFType); PyModule_AddObject(module, "PDF", (PyObject*)&PDFType); PdftotextError = PyErr_NewExceptionWithDoc( (char*)"pdftotext.Error", (char*)"PDF error.", NULL, NULL); Py_INCREF(PdftotextError); PyModule_AddObject(module, "Error", PdftotextError); #if POPPLER_CPP_AT_LEAST_0_30_0 poppler::set_debug_error_function(do_nothing, NULL); #endif } #endif
[ "anto.cuni@gmail.com" ]
anto.cuni@gmail.com
8ab982013d723f7b09c0150999de9e288d170a3b
8c0e6d4343241603a1221e26cda4c30beed60a80
/Synth/SysExMessage.cpp
8439f63bf8693e6afd57d5977c0c1e8e699248ab
[]
no_license
Luiz-Monad/synth
f24ccb01da63e3e4ba2ed2db21eb3cf7d629290b
0baf844f5d4b53868ee4a9187ff6d443289f3213
refs/heads/master
2021-05-27T03:00:37.319603
2014-08-19T14:49:59
2014-08-19T14:49:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,219
cpp
//REGION(License) /* Copyright (c) 2005 Leslie Sanford * * 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. */ //ENDREGION() //REGION(Contact) /* * Leslie Sanford * Email: jabberdabber@hotmail.com */ //ENDREGION() #include "SysExMessage.h" #include "Exception.h" namespace Sanford { namespace Multimedia { namespace Midi { typedef SysExMessageClass cls; void cls::init() { this->Length = Functor::New(this, &cls::get_Length); this->SysExType = Functor::New(this, &cls::get_SysExType); this->Status = Functor::New(this, &cls::get_Status); this->MessageType = Functor::New(this, &cls::get_MessageType); this->data = bytebufferclass::null; } REGION(Construction) /// <summary> /// Initializes a new instance of the SysExMessageEventArgs class with the /// specified system exclusive data. /// </summary> /// <param name="data"> /// The system exclusive data. /// </param> /// <remarks> /// The system exclusive data's status byte, the first byte in the /// data, must have a value of 0xF0 or 0xF7. /// </remarks> SysExMessageClass::SysExMessageClass(bytebuffer data) : data(data) { init(); REGION(Require) if(data.Length < 1) { throw new ArgumentException( "System exclusive data is too short.", "data"); } else if(data[0] != (byte)SysExType::Start && data[0] != (byte)SysExType::Continuation) { throw new ArgumentException( "Unknown status value.", "data"); } ENDREGION() this->data = bytebufferclass(data.Length); data.CopyTo(this->data, 0); } ENDREGION() REGION(Methods) bytebuffer SysExMessageClass::GetBytes() { return data.Clone(); } void SysExMessageClass::CopyTo(bytebuffer buffer, int index) { data.CopyTo(buffer, index); } bool SysExMessageClass::Equals(IEquatable obj) { REGION(Guard) if(!(isinst<SysExMessage>(obj))) { return false; } ENDREGION() SysExMessage message = (SysExMessage)obj; bool equals = true; if(this->Length != message.Length) { equals = false; } for(int i = 0; i < this->Length && equals; i++) { if((*this)[i] != message[i]) { equals = false; } } return equals; } int SysExMessageClass::GetHashCode() { return data.GetHashCode(); } ENDREGION() REGION(Properties) /// <summary> /// Gets the element at the specified index. /// </summary> /// <exception cref="ArgumentOutOfRangeException"> /// If index is less than zero or greater than or equal to the length /// of the message. /// </exception> const byte& SysExMessageClass::operator [](int index) { REGION(Require) if(index < 0 || index >= Length) { throw new ArgumentOutOfRangeException("index", index, "Index into system exclusive message out of range."); } ENDREGION() return data[index]; } /// <summary> /// Gets the length of the system exclusive data. /// </summary> int SysExMessageClass::get_Length() { return data.Length; } /// <summary> /// Gets the system exclusive type. /// </summary> SysExType SysExMessageClass::get_SysExType() { return (Midi::SysExType)(data[0]); } ENDREGION() ENDREGION() /// <summary> /// Gets the status value. /// </summary> int SysExMessageClass::get_Status() { return (int)data[0]; } /// <summary> /// Gets the MessageType. /// </summary> MessageType SysExMessageClass::get_MessageType() { return MessageType::SystemExclusive; } REGION(IEnumerable Members) bytebufferclass::iterator SysExMessageClass::GetIterator() { return data.GetIterator(); } ENDREGION() }}}
[ "luizfelipestang@gmail.com" ]
luizfelipestang@gmail.com
80446ed73f8abe7b81030d8f01fc4727f1acaf80
4cc7c74b4bb7b818562bedffd026a86f9ec78f41
/chrome/browser/safe_browsing/test_safe_browsing_service.cc
f6949cf8f0707cb2e76c4a82f4e4a725e970294c
[ "BSD-3-Clause" ]
permissive
jennyb2911/chromium
1e03c9e5a63af1cf82832e0e99e0028e255872bd
62b48b4fdb3984762f4d2fd3690f02f167920f52
refs/heads/master
2023-01-10T01:08:34.961976
2018-09-28T03:36:36
2018-09-28T03:36:36
150,682,761
1
0
NOASSERTION
2018-09-28T03:49:28
2018-09-28T03:49:27
null
UTF-8
C++
false
false
5,906
cc
// Copyright (c) 2016 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/safe_browsing/test_safe_browsing_service.h" #include "base/strings/string_util.h" #include "chrome/browser/safe_browsing/download_protection/download_protection_service.h" #include "chrome/browser/safe_browsing/incident_reporting/incident_reporting_service.h" #include "chrome/browser/safe_browsing/ui_manager.h" #include "components/safe_browsing/db/database_manager.h" #include "components/safe_browsing/db/test_database_manager.h" #include "components/safe_browsing/db/v4_feature_list.h" namespace safe_browsing { // TestSafeBrowsingService functions: TestSafeBrowsingService::TestSafeBrowsingService() : SafeBrowsingService(), serialized_download_report_(base::EmptyString()), use_v4_local_db_manager_(false) { #if defined(FULL_SAFE_BROWSING) services_delegate_ = ServicesDelegate::CreateForTest(this, this); #endif // defined(FULL_SAFE_BROWSING) } TestSafeBrowsingService::~TestSafeBrowsingService() {} V4ProtocolConfig TestSafeBrowsingService::GetV4ProtocolConfig() const { if (v4_protocol_config_) return *v4_protocol_config_; return SafeBrowsingService::GetV4ProtocolConfig(); } void TestSafeBrowsingService::UseV4LocalDatabaseManager() { use_v4_local_db_manager_ = true; } std::string TestSafeBrowsingService::serilized_download_report() { return serialized_download_report_; } void TestSafeBrowsingService::ClearDownloadReport() { serialized_download_report_.clear(); } void TestSafeBrowsingService::SetDatabaseManager( TestSafeBrowsingDatabaseManager* database_manager) { SetDatabaseManagerForTest(database_manager); } void TestSafeBrowsingService::SetUIManager( TestSafeBrowsingUIManager* ui_manager) { ui_manager->SetSafeBrowsingService(this); ui_manager_ = ui_manager; } SafeBrowsingUIManager* TestSafeBrowsingService::CreateUIManager() { if (ui_manager_) return ui_manager_.get(); return SafeBrowsingService::CreateUIManager(); } void TestSafeBrowsingService::SendSerializedDownloadReport( const std::string& report) { serialized_download_report_ = report; } const scoped_refptr<SafeBrowsingDatabaseManager>& TestSafeBrowsingService::database_manager() const { if (test_database_manager_) return test_database_manager_; return SafeBrowsingService::database_manager(); } void TestSafeBrowsingService::SetV4ProtocolConfig( V4ProtocolConfig* v4_protocol_config) { v4_protocol_config_.reset(v4_protocol_config); } // ServicesDelegate::ServicesCreator: bool TestSafeBrowsingService::CanCreateDatabaseManager() { return !use_v4_local_db_manager_; } bool TestSafeBrowsingService::CanCreateDownloadProtectionService() { return false; } bool TestSafeBrowsingService::CanCreateIncidentReportingService() { return true; } bool TestSafeBrowsingService::CanCreateResourceRequestDetector() { return false; } SafeBrowsingDatabaseManager* TestSafeBrowsingService::CreateDatabaseManager() { DCHECK(!use_v4_local_db_manager_); #if defined(FULL_SAFE_BROWSING) return new TestSafeBrowsingDatabaseManager(); #else NOTIMPLEMENTED(); return nullptr; #endif // defined(FULL_SAFE_BROWSING) } DownloadProtectionService* TestSafeBrowsingService::CreateDownloadProtectionService() { NOTIMPLEMENTED(); return nullptr; } IncidentReportingService* TestSafeBrowsingService::CreateIncidentReportingService() { #if defined(FULL_SAFE_BROWSING) return new IncidentReportingService(nullptr); #else NOTIMPLEMENTED(); return nullptr; #endif // defined(FULL_SAFE_BROWSING) } ResourceRequestDetector* TestSafeBrowsingService::CreateResourceRequestDetector() { NOTIMPLEMENTED(); return nullptr; } // TestSafeBrowsingServiceFactory functions: TestSafeBrowsingServiceFactory::TestSafeBrowsingServiceFactory() : test_safe_browsing_service_(nullptr), use_v4_local_db_manager_(false) {} TestSafeBrowsingServiceFactory::~TestSafeBrowsingServiceFactory() {} SafeBrowsingService* TestSafeBrowsingServiceFactory::CreateSafeBrowsingService() { // Instantiate TestSafeBrowsingService. test_safe_browsing_service_ = new TestSafeBrowsingService(); // Plug-in test member clases accordingly. if (use_v4_local_db_manager_) test_safe_browsing_service_->UseV4LocalDatabaseManager(); if (test_ui_manager_) test_safe_browsing_service_->SetUIManager(test_ui_manager_.get()); if (test_database_manager_) { test_safe_browsing_service_->SetDatabaseManager( test_database_manager_.get()); } return test_safe_browsing_service_; } TestSafeBrowsingService* TestSafeBrowsingServiceFactory::test_safe_browsing_service() { return test_safe_browsing_service_; } void TestSafeBrowsingServiceFactory::SetTestUIManager( TestSafeBrowsingUIManager* ui_manager) { test_ui_manager_ = ui_manager; } void TestSafeBrowsingServiceFactory::SetTestDatabaseManager( TestSafeBrowsingDatabaseManager* database_manager) { test_database_manager_ = database_manager; } void TestSafeBrowsingServiceFactory::UseV4LocalDatabaseManager() { use_v4_local_db_manager_ = true; } // TestSafeBrowsingUIManager functions: TestSafeBrowsingUIManager::TestSafeBrowsingUIManager() : SafeBrowsingUIManager(nullptr) {} TestSafeBrowsingUIManager::TestSafeBrowsingUIManager( const scoped_refptr<SafeBrowsingService>& service) : SafeBrowsingUIManager(service) {} void TestSafeBrowsingUIManager::SetSafeBrowsingService( SafeBrowsingService* sb_service) { sb_service_ = sb_service; } void TestSafeBrowsingUIManager::SendSerializedThreatDetails( const std::string& serialized) { details_.push_back(serialized); } std::list<std::string>* TestSafeBrowsingUIManager::GetThreatDetails() { return &details_; } TestSafeBrowsingUIManager::~TestSafeBrowsingUIManager() {} } // namespace safe_browsing
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
21b9f4df87a2d67d7e659724c2870a35d576e07e
72b0b2328a1749d25c0ebb5c51a7a202fb35b382
/leetcode/8.cpp
2ae12aff7a1ebf4c5233e345643af678c16ccbbd
[]
no_license
bluarry/prepare
5140b57612fab19b8b24573012bf796d2c0def31
c9c94fa7970b40b6f828d2f2e31267acaecbc07c
refs/heads/master
2021-05-22T01:10:29.998403
2020-05-05T04:25:22
2020-05-05T04:25:22
252,900,366
0
0
null
null
null
null
UTF-8
C++
false
false
1,672
cpp
#include <iostream> #include <vector> #include <string> #include <cstring> #include <algorithm> using namespace std; class Solution { public: bool isEffect(char c){ if(c=='-'||c=='+'||(c>='0'&& c<='9')) return true; return false; } bool isnum(char c){ if(c>='0'&& c<='9') return true; return false; } string trim(string str){ int index=0; while(str[index++]==' '); return str.substr(index-1); } int myAtoi(string str) { str=trim(str); //cout << str<<endl; int flag=0,ans=0,len=str.length(),p=0,n=0; if(len==0) return 0; if(isEffect(str[0])) p=0; else return 0; if(str[0]=='-') flag=1,p++; else if(str[0]=='+') p++; //cout << "len= " <<len<<endl; for(int i=p;i<len;i++){ if(isnum(str[i])){ n=i; }else { break; } } //cout << p << " " << n <<endl; // 当正数处理 int flag2=0; int c=0; for(int i=p;i<=n;i++){ c=str[i]-'0'; if( ans > INT32_MAX/10 ||(ans==INT32_MAX/10 && c>7)){ flag2=1; ans=INT32_MAX; break; } ans=ans*10+c; } if(flag){ if(flag2) ans=INT32_MIN; else ans=-ans; } return ans; } }; int main(){ Solution ss; string s="-2147483648" ; cout << ss.myAtoi(s)<<endl; return 0; }
[ "root@winpc_bluarry.localdomain" ]
root@winpc_bluarry.localdomain
f19b63ace7a50acef5ec5e3fef9f5bc8cd7d51c6
ceeddddcf3e99e909c4af5ff2b9fad4a8ecaeb2a
/tags/release-1.5.2/source/Irrlicht/CQuake3ShaderSceneNode.h
7ffc7b6d024aa58da8238832c8f45aa19b8cd5fe
[ "LicenseRef-scancode-other-permissive", "Zlib", "LicenseRef-scancode-unknown-license-reference" ]
permissive
jivibounty/irrlicht
d9d6993bd0aee00dce2397a887b7f547ade74fbb
c5c80cde40b6d14fe5661440638d36a16b41d7ab
refs/heads/master
2021-01-18T02:56:08.844268
2015-07-21T08:02:25
2015-07-21T08:02:25
39,405,895
0
0
null
2015-07-20T20:07:06
2015-07-20T20:07:06
null
UTF-8
C++
false
false
2,223
h
// Copyright (C) 2002-2009 Nikolaus Gebhardt / Thomas Alten // This file is part of the "Irrlicht Engine". // For conditions of distribution and use, see copyright notice in irrlicht.h #ifndef __C_QUAKE3_SCENE_NODE_H_INCLUDED__ #define __C_QUAKE3_SCENE_NODE_H_INCLUDED__ #include "ISceneNode.h" #include "IQ3Shader.h" #include "IFileSystem.h" #include "SMeshBuffer.h" #include "SMeshBufferLightMap.h" namespace irr { namespace scene { //! Scene node which is a quake3 shader. class CQuake3ShaderSceneNode : public scene::ISceneNode { public: CQuake3ShaderSceneNode( ISceneNode* parent, ISceneManager* mgr,s32 id, io::IFileSystem *fileSystem,IMeshBuffer *buffer, const quake3::SShader * shader); virtual ~CQuake3ShaderSceneNode(); virtual void OnRegisterSceneNode(); virtual void render(); virtual void OnAnimate(u32 timeMs); virtual const core::aabbox3d<f32>& getBoundingBox() const; virtual u32 getMaterialCount() const; virtual video::SMaterial& getMaterial(u32 i); private: SMeshBuffer* MeshBuffer; SMeshBufferLightMap* Original; const quake3::SShader* Shader; struct SQ3Texture { SQ3Texture () : TextureIndex ( 0 ), TextureFrequency(0.f), TextureAddressMode( video::ETC_REPEAT ) {} quake3::tTexArray Texture; u32 TextureIndex; f32 TextureFrequency; video::E_TEXTURE_CLAMP TextureAddressMode; // Wrapping/Clamping }; core::array< SQ3Texture > Q3Texture; void loadTextures ( io::IFileSystem * fileSystem ); void cloneBuffer ( scene::SMeshBufferLightMap * buffer ); void vertextransform_wave ( f32 dt, quake3::SModifierFunction &function ); void vertextransform_bulge( f32 dt, quake3::SModifierFunction &function ); void vertextransform_autosprite( f32 dt, quake3::SModifierFunction &function ); void vertextransform_tcgen ( f32 dt, quake3::SModifierFunction &function ); void vertextransform_rgbgen ( f32 dt, quake3::SModifierFunction &function ); void transformtex ( const core::matrix4 &m, const u32 clamp ); f32 TimeAbs; void animate( u32 stage, core::matrix4 &texture ); bool isTransparent() const; }; } // end namespace scene } // end namespace irr #endif
[ "hybrid@dfc29bdd-3216-0410-991c-e03cc46cb475" ]
hybrid@dfc29bdd-3216-0410-991c-e03cc46cb475
4ad1472a84ba67cdd52887a530ed36762ab5874c
cfbe32d3c679487610e0a8e924c33ab6aa64f3d1
/topcoder/programs/PilingRectsDiv2.cpp
2de48e3d098db1405a65cbda63508e62f1aee8ac
[]
no_license
hophacker/algorithm_coding
6062fafd00e276baeb5ef92198c6c1dab66b6184
bfc9a124ed21eabf241590b90105427f0a2b6573
refs/heads/master
2020-06-04T00:41:25.378594
2014-07-07T00:50:35
2014-07-07T00:50:35
18,478,412
5
1
null
null
null
null
UTF-8
C++
false
false
5,450
cpp
#include <sstream> /* */ #define debuging #ifdef debuging #define FIN {freopen("new.in" , "r" , stdin) ;} #define FOUT {freopen("new.out" , "w" , stdout) ;} #define OUT(x) {cout<< #x << " : " << x <<endl ;} #define ERR(x) {cout<<"#error: "<< x ; while(1) ;} #endif // END CUT HERE #ifndef debuging #define FIN ; #define FOUT ; #define OUT(x) ; #define ERR(x) ; #endif #include <cstdio> #include <iostream> #include <cstring> #include <algorithm> #include <cmath> #include <vector> #include <list> using namespace std ; #define For(i , n) for(int i = 0 ; i < (n) ; ++i) #define SZ(x) (int)((x).size()) typedef long long lint ; const int maxint = -1u>>2 ; const double eps = 1e-6 ; class PilingRectsDiv2 { list<int> link[50]; bool unSearched[50]; public: int search(int x){ int ret = 0; for (list<int>::iterator it=link[x].begin(); it != link[x].end(); ++it){ int y = *it; if (unSearched[y]){ unSearched[y] = 0; cout << "->" << y; ret = max(ret, 1+search(y)); unSearched[y] = 1; } } cout << endl; return ret; } int getmax(vector <int> X, vector <int> Y, int limit){ unsigned n = X.size(); for (unsigned i = 0; i < n; i++) link[i].clear(); for (unsigned i = 0; i < n; i++) { for (unsigned j = i+1; j < n; j++){ if (min(X[i],X[j])*min(Y[i],Y[j]) >= limit || min(X[i],Y[j]) * min(X[j],Y[i]) >= limit){ link[i].push_back(j); link[j].push_back(i); cout << i << ' ' << j << endl; } } } int maxN = -1; memset(unSearched, true, sizeof(unSearched)); for (unsigned i = 0; i < X.size(); i++) cout << i << ':' << link[i].size() << endl; for (unsigned i = 0; i < X.size(); i++) if (X[i]*Y[i] >= limit){ unSearched[i] = 0; cout << i; maxN = max(maxN, 1+search(i)); cout << maxN << endl; unSearched[i] = 1; } return maxN; return int() ; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); if ((Case == -1) || (Case == 5)) test_case_5(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { int Arr0[] = {1,2,3,1}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {3,2,4,4}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 3; int Arg3 = 3; verify_case(0, Arg3, getmax(Arg0, Arg1, Arg2)); } void test_case_1() { int Arr0[] = {4,7}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {7,4}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 25; int Arg3 = 2; verify_case(1, Arg3, getmax(Arg0, Arg1, Arg2)); } void test_case_2() { int Arr0[] = {10}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {10}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 9999; int Arg3 = -1; verify_case(2, Arg3, getmax(Arg0, Arg1, Arg2)); } void test_case_3() { int Arr0[] = {10}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {3}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 30; int Arg3 = 1; verify_case(3, Arg3, getmax(Arg0, Arg1, Arg2)); } void test_case_4() { int Arr0[] = {3,6,5,8,2,9,14}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {14,6,13,8,15,6,3}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 27; int Arg3 = 4; verify_case(4, Arg3, getmax(Arg0, Arg1, Arg2)); } void test_case_5() { int Arr0[] = {121,168,86,106,36,10,125,97,53,26,148,129,41,18,173,55,13,73,91,174,177,190,28,164,122,92,5,26,58,188,14,67,48,196,41,94,24,89,54,117,12,6,155,103,200,128,184,29,92,149}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {199,182,43,191,2,145,15,53,38,37,61,45,157,129,119,123,177,178,183,188,132,108,112,137,92,59,75,196,102,152,114,121,181,93,32,3,24,116,4,163,96,159,196,43,59,150,79,113,20,146}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 5345; int Arg3 = 24; verify_case(5, Arg3, getmax(Arg0, Arg1, Arg2)); } // END CUT HERE };// BEGIN CUT HERE int main(){ PilingRectsDiv2 ___test; ___test.run_test(0); return 0; } // END CUT HERE
[ "jokerfeng2010@gmail.com" ]
jokerfeng2010@gmail.com
ff8514b5868b691e4742448f660fb7b94adeee60
b8487f927d9fb3fa5529ad3686535714c687dd50
/lib/AST/SemanticValidator.h
ad193bbbcde5cbe101857272b313e782f3636419
[ "MIT" ]
permissive
hoangtuanhedspi/hermes
4a1399f05924f0592c36a9d4b3fd1f804f383c14
02dbf3c796da4d09ec096ae1d5808dcb1b6062bf
refs/heads/master
2020-07-12T21:21:53.781167
2019-08-27T22:58:17
2019-08-27T22:59:55
204,908,743
1
0
MIT
2019-08-28T17:44:49
2019-08-28T10:44:49
null
UTF-8
C++
false
false
8,841
h
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the LICENSE * file in the root directory of this source tree. */ #ifndef HERMES_AST_SEMANTICVALIDATOR_H #define HERMES_AST_SEMANTICVALIDATOR_H #include "hermes/AST/SemValidate.h" #include "RecursiveVisitor.h" namespace hermes { namespace sem { using namespace hermes::ESTree; // Forward declarations class FunctionContext; class SemanticValidator; //===----------------------------------------------------------------------===// // Keywords class Keywords { public: /// Identifier for "arguments". const UniqueString *const identArguments; /// Identifier for "eval". const UniqueString *const identEval; /// Identifier for "delete". const UniqueString *const identDelete; /// Identifier for "use strict". const UniqueString *const identUseStrict; /// Identifier for "var". const UniqueString *const identVar; /// Identifier for "let". const UniqueString *const identLet; /// Identifier for "const". const UniqueString *const identConst; Keywords(Context &astContext); }; //===----------------------------------------------------------------------===// // SemanticValidator /// Class the performs all semantic validation class SemanticValidator { friend class FunctionContext; Context &astContext_; /// A copy of Context::getSM() for easier access. SourceErrorManager &sm_; /// All semantic tables are persisted here. SemContext &semCtx_; /// Save the initial error count so we know whether we generated any errors. const unsigned initialErrorCount_; /// Keywords we will be checking for. Keywords kw_; /// The current function context. FunctionContext *funcCtx_{}; #ifndef NDEBUG /// Our parser detects strictness and initializes the flag in every node, /// but if we are reading an external AST, we must look for "use strict" and /// initialize the flag ourselves here. /// For consistency we always perform the detection, but in debug mode we also /// want to ensure that our results match what the parser generated. This /// flag indicates whether strictness is preset or not. bool strictnessIsPreset_{false}; #endif public: explicit SemanticValidator(Context &astContext, sem::SemContext &semCtx); // Perform the validation on whole AST. bool doIt(Node *rootNode); /// Perform the validation on an individual function. bool doFunction(Node *function, bool strict); /// Handle the default case for all nodes which we ignore, but we still want /// to visit their children. void visit(Node *node) { visitESTreeChildren(*this, node); } void visit(ProgramNode *node); void visit(FunctionDeclarationNode *funcDecl); void visit(FunctionExpressionNode *funcExpr); void visit(ArrowFunctionExpressionNode *arrowFunc); void visit(VariableDeclaratorNode *varDecl, Node *parent); void visit(MetaPropertyNode *metaProp); void visit(IdentifierNode *identifier); void visit(ForInStatementNode *forIn); void visit(ForOfStatementNode *forOf); void visitForInOf(LoopStatementNode *loopNode, Node *left); void visit(AssignmentExpressionNode *assignment); void visit(UpdateExpressionNode *update); void visit(LabeledStatementNode *labelStmt); void visit(RegExpLiteralNode *regexp); void visit(TryStatementNode *tryStatement); void visit(DoWhileStatementNode *loop); void visit(ForStatementNode *loop); void visit(WhileStatementNode *loop); void visit(SwitchStatementNode *switchStmt); void visit(BreakStatementNode *breakStmt); void visit(ContinueStatementNode *continueStmt); void visit(ReturnStatementNode *returnStmt); void visit(YieldExpressionNode *yieldExpr); void visit(UnaryExpressionNode *unaryExpr); void visit(ArrayPatternNode *arrayPat); void visit(SpreadElementNode *S, Node *parent); void visit(ClassExpressionNode *node); void visit(ClassDeclarationNode *node); void visit(ImportDeclarationNode *importDecl); void visit(ImportDefaultSpecifierNode *importDecl); void visit(ImportNamespaceSpecifierNode *importDecl); void visit(ImportSpecifierNode *importDecl); void visit(ExportNamedDeclarationNode *exportDecl); void visit(ExportDefaultDeclarationNode *exportDecl); void visit(ExportAllDeclarationNode *exportDecl); void visit(CoverEmptyArgsNode *CEA); void visit(CoverTrailingCommaNode *CTC); void visit(CoverInitializerNode *CI); void visit(CoverRestElementNode *R); private: inline bool haveActiveContext() const { return funcCtx_ != nullptr; } inline FunctionContext *curFunction() { assert(funcCtx_ && "No active function context"); return funcCtx_; } inline const FunctionContext *curFunction() const { assert(funcCtx_ && "No active function context"); return funcCtx_; } /// Process a function declaration by creating a new FunctionContext. Update /// the context with the strictness of the function. /// \param node the current node /// \param id if not null, the associated name (for validation) /// \param params the parameter list /// \param body the body. It may be a BlockStatementNode, an EmptyNode (for /// lazy functions), or an expression (for simple arrow functions). void visitFunction(FunctionLikeNode *node, Node *id, NodeList &params, Node *body); /// Scan a list of directives in the beginning of a program of function /// (see ES5.1 4.1 - a directive is a statement consisting of a single /// string literal). /// Update the flags in the function context to reflect the directives. (We /// currently only recognize "use strict".) /// \return the node containing "use strict" or nullptr. Node *scanDirectivePrologue(NodeList &body); /// Determine if the argument is something that can be assigned to: a /// variable or a property. 'arguments' cannot be assigned to in strict mode, /// but we don't support code generation for assigning to it in any mode. bool isLValue(const Node *node) const; /// In strict mode 'arguments' and 'eval' cannot be used in declarations. bool isValidDeclarationName(const IdentifierNode *idNode) const; /// Ensure that the declared identifier(s) is valid to be used in a /// declaration and append them to the specified list. /// \param node is one of nullptr, EmptyNode, IdentifierNode, PatternNode. /// \param idents if not-null, all identifiers are appended there. void validateDeclarationNames( FunctionInfo::VarDecl::Kind declKind, Node *node, llvm::SmallVectorImpl<FunctionInfo::VarDecl> *idents); /// Ensure that the specified node is a valid target for an assignment, in /// other words it is an l-value, a Pattern (checked recursively) or an Empty /// (used by elision). void validateAssignmentTarget(const Node *node); /// A debugging method to set the strictness of a function-like node to /// the curent strictness, asserting that it doesn't change if it had been /// preset. void updateNodeStrictness(FunctionLikeNode *node); /// Get the LabelDecorationBase depending on the node type. static LabelDecorationBase *getLabelDecorationBase(StatementNode *node); /// Collapse array pattern rest elements into their parent: /// [a, ...[b, c]] => [a, b, c]. static void collapseNestedAP(NodeList &elements); }; //===----------------------------------------------------------------------===// // FunctionContext /// Holds all per-function state, specifically label tables. Should always be /// constructed on the stack. class FunctionContext { SemanticValidator *validator_; FunctionContext *oldContextValue_; public: struct Label { /// Where it was declared. IdentifierNode *declarationNode; /// Statement targeted by the label. It is either a LoopStatement or a /// LabeledStatement. StatementNode *targetStatement; }; /// The associated seminfo object sem::FunctionInfo *const semInfo; /// The most nested active loop statement. LoopStatementNode *activeLoop = nullptr; /// The most nested active loop or switch statement. StatementNode *activeSwitchOrLoop = nullptr; /// Is this function in strict mode. bool strictMode = false; /// The currently active labels in the function. llvm::DenseMap<NodeLabel, Label> labelMap; explicit FunctionContext( SemanticValidator *validator, bool strictMode, FunctionLikeNode *node); ~FunctionContext(); /// \return true if this is the "global scope" function context, in other /// words not a real function. bool isGlobalScope() const { return !oldContextValue_; } /// Allocate a new label in the current context. unsigned allocateLabel() { return semInfo->allocateLabel(); } }; } // namespace sem } // namespace hermes #endif // HERMES_AST_SEMANTICVALIDATOR_H
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
37db6cba98ee35dbd915bd98ad6b25de160e1c59
43fd0cc577bea4c611657b728e3c3036796d3aa6
/profilclassic.cpp
410bfe4163a8b68c2424e1963eb07cba20680ac8
[]
no_license
SnowKiss/TTVQTB
358be31da650dfdf64996168047f2e4ab75d9045
372540e0a48e7a75e805ecd9804894553da8eeff
refs/heads/master
2021-05-02T16:29:32.627933
2018-02-10T10:44:41
2018-02-10T10:44:41
120,677,474
0
0
null
null
null
null
UTF-8
C++
false
false
64
cpp
#include "profilclassic.h" ProfilClassic::ProfilClassic() { }
[ "john.schmitt9@gmail.com" ]
john.schmitt9@gmail.com
e45cb321bce6a88a4e167a27b69c5ae4d21cbb54
74a99fb7d20dc4e9312268c1e2936e97607cc62e
/Sea_Chain/helpers/astar.cpp
a2b1c58b83d7c4c11965d04a46ee51813f8d9676
[ "LicenseRef-scancode-unknown-license-reference", "CC-BY-4.0", "MIT" ]
permissive
Vvaridus/SeaChain
fa6c674e6decbd5fe7d7da5058b053f8849b8d04
5e48925161e6244245f3af21bd8a1cb7a7acfbd4
refs/heads/main
2023-04-25T04:13:57.507698
2021-05-03T21:11:48
2021-05-03T21:11:48
350,384,241
0
0
null
null
null
null
UTF-8
C++
false
false
3,389
cpp
#include "astar.h" #include <LevelSystem.h> #include <array> #include <queue> class Node { private: sf::Vector2i _pos; int _level; int _priority; public: Node() = default; Node(const sf::Vector2i& pos, int level, int priority) : _pos(pos), _level(level), _priority(priority) { } const sf::Vector2i& getPos() const { return _pos; } int getLevel() const { return _level; } int getPriority() const { return _priority; } unsigned int estimate(const sf::Vector2i& dest) const { sf::Vector2i delta = dest - _pos; return static_cast<unsigned int>(length(delta)); } void updatePriority(const sf::Vector2i& dest) { _priority = _level + estimate(dest) * 100; } void nextLevel() { _level += 10; } bool operator<(const Node& other) const { return _priority > other._priority; } }; std::vector<sf::Vector2i> pathFind(sf::Vector2i start, sf::Vector2i finish) { static std::array<sf::Vector2i, 4> directions = { sf::Vector2i(1, 0), sf::Vector2i(0, 1), sf::Vector2i(-1, 0), sf::Vector2i(0, -1) }; std::vector<std::vector<bool>> closed_nodes_map(ls::getWidth()); std::vector<std::vector<int>> open_nodes_map(ls::getWidth()); std::vector<std::vector<sf::Vector2i>> direction_map(ls::getWidth()); std::priority_queue<Node> queue[2]; size_t queue_index = 0; for (size_t y = 0; y < ls::getHeight(); ++y) { for (size_t x = 0; x < ls::getWidth(); ++x) { closed_nodes_map[x].push_back(false); open_nodes_map[x].push_back(0); direction_map[x].emplace_back(sf::Vector2i(0, 0)); } } Node n0(start, 0, 0); n0.updatePriority(finish); queue[queue_index].push(n0); open_nodes_map[start.x][start.y] = n0.getPriority(); while (!queue[queue_index].empty()) { auto tmp = queue[queue_index].top(); n0 = Node(tmp.getPos(), tmp.getLevel(), tmp.getPriority()); auto pos = n0.getPos(); queue[queue_index].pop(); open_nodes_map[pos.x][pos.y] = 0; closed_nodes_map[pos.x][pos.y] = true; if (pos == finish) { std::vector<sf::Vector2i> path; while (!(pos == start)) { auto dir = direction_map[pos.x][pos.y]; path.push_back(pos); pos += dir; } reverse(begin(path), end(path)); return path; } for (auto& dir : directions) { auto next = pos + dir; if (!(next.x < 0 || next.x > ls::getWidth() || next.y < 0 || next.y > ls::getWidth() || ls::getTile(sf::Vector2ul(next.x, next.y)) == ls::WALL || closed_nodes_map[next.x][next.y])) { Node m0(next, n0.getLevel(), n0.getPriority()); m0.nextLevel(); m0.updatePriority(finish); if (open_nodes_map[next.x][next.y] == 0) { open_nodes_map[next.x][next.y] = m0.getPriority(); queue[queue_index].push(m0); direction_map[next.x][next.y] = dir * -1; } else if (open_nodes_map[next.x][next.y] > m0.getPriority()) { direction_map[next.x][next.y] = dir * -1; while (queue[queue_index].top().getPos() != next) { queue[1 - queue_index].push(queue[queue_index].top()); queue[queue_index].pop(); } queue[queue_index].pop(); if (queue[queue_index].size() > queue[1 - queue_index].size()) queue_index = 1 - queue_index; while (!queue[queue_index].empty()) { queue[1 - queue_index].push(queue[queue_index].top()); queue[queue_index].pop(); } queue_index = 1 - queue_index; queue[queue_index].push(m0); } } } } return std::vector<sf::Vector2i>(); }
[ "40429124@live.napier.ac.uk" ]
40429124@live.napier.ac.uk
6114ee868a181c5ef7ac64ba4a57b32ccf501238
639aa908a9cfc8cd7b969e328e092d3e847187ee
/devel/include/ros_arduino_msgs/Digital.h
c306000313ae1f5870a670827a98b8913c471abc
[]
no_license
pengboyemo/Ros
4f34eea65d8154bd2eb248bf62712deb1b059864
a2ca990fff76414d83ca5c3a622f53493e2deb9b
refs/heads/master
2022-05-01T10:53:34.194307
2022-04-01T07:44:03
2022-04-01T07:44:03
228,379,978
0
0
null
2019-12-16T12:14:14
2019-12-16T12:14:13
null
UTF-8
C++
false
false
5,993
h
// Generated by gencpp from file ros_arduino_msgs/Digital.msg // DO NOT EDIT! #ifndef ROS_ARDUINO_MSGS_MESSAGE_DIGITAL_H #define ROS_ARDUINO_MSGS_MESSAGE_DIGITAL_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> #include <std_msgs/Header.h> namespace ros_arduino_msgs { template <class ContainerAllocator> struct Digital_ { typedef Digital_<ContainerAllocator> Type; Digital_() : header() , value(0) { } Digital_(const ContainerAllocator& _alloc) : header(_alloc) , value(0) { (void)_alloc; } typedef ::std_msgs::Header_<ContainerAllocator> _header_type; _header_type header; typedef uint8_t _value_type; _value_type value; typedef boost::shared_ptr< ::ros_arduino_msgs::Digital_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::ros_arduino_msgs::Digital_<ContainerAllocator> const> ConstPtr; }; // struct Digital_ typedef ::ros_arduino_msgs::Digital_<std::allocator<void> > Digital; typedef boost::shared_ptr< ::ros_arduino_msgs::Digital > DigitalPtr; typedef boost::shared_ptr< ::ros_arduino_msgs::Digital const> DigitalConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::ros_arduino_msgs::Digital_<ContainerAllocator> & v) { ros::message_operations::Printer< ::ros_arduino_msgs::Digital_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace ros_arduino_msgs namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': True} // {'std_msgs': ['/opt/ros/indigo/share/std_msgs/cmake/../msg'], 'ros_arduino_msgs': ['/home/ewenwan/ewenwan/catkin_ws/src/ros_arduino_bridge/ros_arduino_msgs/msg']} // !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types'] template <class ContainerAllocator> struct IsFixedSize< ::ros_arduino_msgs::Digital_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct IsFixedSize< ::ros_arduino_msgs::Digital_<ContainerAllocator> const> : FalseType { }; template <class ContainerAllocator> struct IsMessage< ::ros_arduino_msgs::Digital_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::ros_arduino_msgs::Digital_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::ros_arduino_msgs::Digital_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::ros_arduino_msgs::Digital_<ContainerAllocator> const> : TrueType { }; template<class ContainerAllocator> struct MD5Sum< ::ros_arduino_msgs::Digital_<ContainerAllocator> > { static const char* value() { return "90539346f3c3c8fc47f159ab9a6ff208"; } static const char* value(const ::ros_arduino_msgs::Digital_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0x90539346f3c3c8fcULL; static const uint64_t static_value2 = 0x47f159ab9a6ff208ULL; }; template<class ContainerAllocator> struct DataType< ::ros_arduino_msgs::Digital_<ContainerAllocator> > { static const char* value() { return "ros_arduino_msgs/Digital"; } static const char* value(const ::ros_arduino_msgs::Digital_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::ros_arduino_msgs::Digital_<ContainerAllocator> > { static const char* value() { return "# Reading on a digital pin\n\ Header header\n\ uint8 value\n\ \n\ \n\ ================================================================================\n\ MSG: std_msgs/Header\n\ # Standard metadata for higher-level stamped data types.\n\ # This is generally used to communicate timestamped data \n\ # in a particular coordinate frame.\n\ # \n\ # sequence ID: consecutively increasing ID \n\ uint32 seq\n\ #Two-integer timestamp that is expressed as:\n\ # * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')\n\ # * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')\n\ # time-handling sugar is provided by the client library\n\ time stamp\n\ #Frame this data is associated with\n\ # 0: no frame\n\ # 1: global frame\n\ string frame_id\n\ "; } static const char* value(const ::ros_arduino_msgs::Digital_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::ros_arduino_msgs::Digital_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.header); stream.next(m.value); } ROS_DECLARE_ALLINONE_SERIALIZER }; // struct Digital_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::ros_arduino_msgs::Digital_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::ros_arduino_msgs::Digital_<ContainerAllocator>& v) { s << indent << "header: "; s << std::endl; Printer< ::std_msgs::Header_<ContainerAllocator> >::stream(s, indent + " ", v.header); s << indent << "value: "; Printer<uint8_t>::stream(s, indent + " ", v.value); } }; } // namespace message_operations } // namespace ros #endif // ROS_ARDUINO_MSGS_MESSAGE_DIGITAL_H
[ "18817776414@yeah.net" ]
18817776414@yeah.net
46b29b845775d2221650855a97a523ccc84c4a95
da6a4172a23472d1eb54722203452555745c4354
/lib/tinyxml2/xmltest.cpp
663f6aa5ea4b208808ec9e7cb9003d9c4e9ff9e4
[ "Zlib" ]
permissive
HenrikSte/esp32msi
ec380dc5cd1b245f10ab1594e3c8eb7d9615bf4c
a12295eb7e97f0dd4fb5a484f7654b0cfe2b0883
refs/heads/master
2021-11-08T03:04:25.374338
2019-11-13T08:22:47
2019-11-13T08:22:47
150,953,418
1
0
null
null
null
null
UTF-8
C++
false
false
76,693
cpp
#if defined( _MSC_VER ) #if !defined( _CRT_SECURE_NO_WARNINGS ) #define _CRT_SECURE_NO_WARNINGS // This test file is not intended to be secure. #endif #endif #include "tinyxml2.h" #include <cerrno> #include <cstdlib> #include <cstring> #include <ctime> #if defined( _MSC_VER ) || defined (WIN32) #include <crtdbg.h> #define WIN32_LEAN_AND_MEAN #include <windows.h> _CrtMemState startMemState; _CrtMemState endMemState; #else #include <sys/stat.h> #include <sys/types.h> #endif using namespace tinyxml2; using namespace std; int gPass = 0; int gFail = 0; bool XMLTest (const char* testString, const char* expected, const char* found, bool echo=true, bool extraNL=false ) { bool pass; if ( !expected && !found ) pass = true; else if ( !expected || !found ) pass = false; else pass = !strcmp( expected, found ); if ( pass ) printf ("[pass]"); else printf ("[fail]"); if ( !echo ) { printf (" %s\n", testString); } else { if ( extraNL ) { printf( " %s\n", testString ); printf( "%s\n", expected ); printf( "%s\n", found ); } else { printf (" %s [%s][%s]\n", testString, expected, found); } } if ( pass ) ++gPass; else ++gFail; return pass; } bool XMLTest(const char* testString, XMLError expected, XMLError found, bool echo = true, bool extraNL = false) { return XMLTest(testString, XMLDocument::ErrorIDToName(expected), XMLDocument::ErrorIDToName(found), echo, extraNL); } bool XMLTest(const char* testString, bool expected, bool found, bool echo = true, bool extraNL = false) { return XMLTest(testString, expected ? "true" : "false", found ? "true" : "false", echo, extraNL); } template< class T > bool XMLTest( const char* testString, T expected, T found, bool echo=true ) { bool pass = ( expected == found ); if ( pass ) printf ("[pass]"); else printf ("[fail]"); if ( !echo ) printf (" %s\n", testString); else printf (" %s [%d][%d]\n", testString, static_cast<int>(expected), static_cast<int>(found) ); if ( pass ) ++gPass; else ++gFail; return pass; } void NullLineEndings( char* p ) { while( p && *p ) { if ( *p == '\n' || *p == '\r' ) { *p = 0; return; } ++p; } } int example_1() { XMLDocument doc; doc.LoadFile( "resources/dream.xml" ); return doc.ErrorID(); } /** @page Example_1 Load an XML File * @dontinclude ./xmltest.cpp * Basic XML file loading. * The basic syntax to load an XML file from * disk and check for an error. (ErrorID() * will return 0 for no error.) * @skip example_1() * @until } */ int example_2() { static const char* xml = "<element/>"; XMLDocument doc; doc.Parse( xml ); return doc.ErrorID(); } /** @page Example_2 Parse an XML from char buffer * @dontinclude ./xmltest.cpp * Basic XML string parsing. * The basic syntax to parse an XML for * a char* and check for an error. (ErrorID() * will return 0 for no error.) * @skip example_2() * @until } */ int example_3() { static const char* xml = "<?xml version=\"1.0\"?>" "<!DOCTYPE PLAY SYSTEM \"play.dtd\">" "<PLAY>" "<TITLE>A Midsummer Night's Dream</TITLE>" "</PLAY>"; XMLDocument doc; doc.Parse( xml ); XMLElement* titleElement = doc.FirstChildElement( "PLAY" )->FirstChildElement( "TITLE" ); const char* title = titleElement->GetText(); printf( "Name of play (1): %s\n", title ); XMLText* textNode = titleElement->FirstChild()->ToText(); title = textNode->Value(); printf( "Name of play (2): %s\n", title ); return doc.ErrorID(); } /** @page Example_3 Get information out of XML @dontinclude ./xmltest.cpp In this example, we navigate a simple XML file, and read some interesting text. Note that this example doesn't use error checking; working code should check for null pointers when walking an XML tree, or use XMLHandle. (The XML is an excerpt from "dream.xml"). @skip example_3() @until </PLAY>"; The structure of the XML file is: <ul> <li>(declaration)</li> <li>(dtd stuff)</li> <li>Element "PLAY"</li> <ul> <li>Element "TITLE"</li> <ul> <li>Text "A Midsummer Night's Dream"</li> </ul> </ul> </ul> For this example, we want to print out the title of the play. The text of the title (what we want) is child of the "TITLE" element which is a child of the "PLAY" element. We want to skip the declaration and dtd, so the method FirstChildElement() is a good choice. The FirstChildElement() of the Document is the "PLAY" Element, the FirstChildElement() of the "PLAY" Element is the "TITLE" Element. @until ( "TITLE" ); We can then use the convenience function GetText() to get the title of the play. @until title ); Text is just another Node in the XML DOM. And in fact you should be a little cautious with it, as text nodes can contain elements. @verbatim Consider: A Midsummer Night's <b>Dream</b> @endverbatim It is more correct to actually query the Text Node if in doubt: @until title ); Noting that here we use FirstChild() since we are looking for XMLText, not an element, and ToText() is a cast from a Node to a XMLText. */ bool example_4() { static const char* xml = "<information>" " <attributeApproach v='2' />" " <textApproach>" " <v>2</v>" " </textApproach>" "</information>"; XMLDocument doc; doc.Parse( xml ); int v0 = 0; int v1 = 0; XMLElement* attributeApproachElement = doc.FirstChildElement()->FirstChildElement( "attributeApproach" ); attributeApproachElement->QueryIntAttribute( "v", &v0 ); XMLElement* textApproachElement = doc.FirstChildElement()->FirstChildElement( "textApproach" ); textApproachElement->FirstChildElement( "v" )->QueryIntText( &v1 ); printf( "Both values are the same: %d and %d\n", v0, v1 ); return !doc.Error() && ( v0 == v1 ); } /** @page Example_4 Read attributes and text information. @dontinclude ./xmltest.cpp There are fundamentally 2 ways of writing a key-value pair into an XML file. (Something that's always annoyed me about XML.) Either by using attributes, or by writing the key name into an element and the value into the text node wrapped by the element. Both approaches are illustrated in this example, which shows two ways to encode the value "2" into the key "v": @skip example_4() @until "</information>"; TinyXML-2 has accessors for both approaches. When using an attribute, you navigate to the XMLElement with that attribute and use the QueryIntAttribute() group of methods. (Also QueryFloatAttribute(), etc.) @skip XMLElement* attributeApproachElement @until &v0 ); When using the text approach, you need to navigate down one more step to the XMLElement that contains the text. Note the extra FirstChildElement( "v" ) in the code below. The value of the text can then be safely queried with the QueryIntText() group of methods. (Also QueryFloatText(), etc.) @skip XMLElement* textApproachElement @until &v1 ); */ int main( int argc, const char ** argv ) { #if defined( _MSC_VER ) && defined( TINYXML2_DEBUG ) _CrtMemCheckpoint( &startMemState ); // Enable MS Visual C++ debug heap memory leaks dump on exit _CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF); { int leaksOnStart = _CrtDumpMemoryLeaks(); XMLTest( "No leaks on start?", FALSE, leaksOnStart ); } #endif { TIXMLASSERT( true ); } if ( argc > 1 ) { XMLDocument* doc = new XMLDocument(); clock_t startTime = clock(); doc->LoadFile( argv[1] ); clock_t loadTime = clock(); int errorID = doc->ErrorID(); delete doc; doc = 0; clock_t deleteTime = clock(); printf( "Test file '%s' loaded. ErrorID=%d\n", argv[1], errorID ); if ( !errorID ) { printf( "Load time=%u\n", (unsigned)(loadTime - startTime) ); printf( "Delete time=%u\n", (unsigned)(deleteTime - loadTime) ); printf( "Total time=%u\n", (unsigned)(deleteTime - startTime) ); } exit(0); } FILE* fp = fopen( "resources/dream.xml", "r" ); if ( !fp ) { printf( "Error opening test file 'dream.xml'.\n" "Is your working directory the same as where \n" "the xmltest.cpp and dream.xml file are?\n\n" #if defined( _MSC_VER ) "In windows Visual Studio you may need to set\n" "Properties->Debugging->Working Directory to '..'\n" #endif ); exit( 1 ); } fclose( fp ); XMLTest( "Example_1", 0, example_1() ); XMLTest( "Example_2", 0, example_2() ); XMLTest( "Example_3", 0, example_3() ); XMLTest( "Example_4", true, example_4() ); /* ------ Example 2: Lookup information. ---- */ { static const char* test[] = { "<element />", "<element></element>", "<element><subelement/></element>", "<element><subelement></subelement></element>", "<element><subelement><subsub/></subelement></element>", "<!--comment beside elements--><element><subelement></subelement></element>", "<!--comment beside elements, this time with spaces--> \n <element> <subelement> \n </subelement> </element>", "<element attrib1='foo' attrib2=\"bar\" ></element>", "<element attrib1='foo' attrib2=\"bar\" ><subelement attrib3='yeehaa' /></element>", "<element>Text inside element.</element>", "<element><b></b></element>", "<element>Text inside and <b>bolded</b> in the element.</element>", "<outer><element>Text inside and <b>bolded</b> in the element.</element></outer>", "<element>This &amp; That.</element>", "<element attrib='This&lt;That' />", 0 }; for( int i=0; test[i]; ++i ) { XMLDocument doc; doc.Parse( test[i] ); XMLTest( "Element test", false, doc.Error() ); doc.Print(); printf( "----------------------------------------------\n" ); } } #if 1 { static const char* test = "<!--hello world\n" " line 2\r" " line 3\r\n" " line 4\n\r" " line 5\r-->"; XMLDocument doc; doc.Parse( test ); XMLTest( "Hello world declaration", false, doc.Error() ); doc.Print(); } { // This test is pre-test for the next one // (where Element1 is inserted "after itself". // This code didn't use to crash. XMLDocument doc; XMLElement* element1 = doc.NewElement("Element1"); XMLElement* element2 = doc.NewElement("Element2"); doc.InsertEndChild(element1); doc.InsertEndChild(element2); doc.InsertAfterChild(element2, element2); doc.InsertAfterChild(element2, element2); } { XMLDocument doc; XMLElement* element1 = doc.NewElement("Element1"); XMLElement* element2 = doc.NewElement("Element2"); doc.InsertEndChild(element1); doc.InsertEndChild(element2); // This insertion "after itself" // used to cause invalid memory access and crash doc.InsertAfterChild(element1, element1); doc.InsertAfterChild(element1, element1); doc.InsertAfterChild(element2, element2); doc.InsertAfterChild(element2, element2); } { static const char* test = "<element>Text before.</element>"; XMLDocument doc; doc.Parse( test ); XMLTest( "Element text before", false, doc.Error() ); XMLElement* root = doc.FirstChildElement(); XMLElement* newElement = doc.NewElement( "Subelement" ); root->InsertEndChild( newElement ); doc.Print(); } { XMLDocument* doc = new XMLDocument(); static const char* test = "<element><sub/></element>"; doc->Parse( test ); XMLTest( "Element with sub element", false, doc->Error() ); delete doc; } { // Test: Programmatic DOM nodes insertion return values XMLDocument doc; XMLNode* first = doc.NewElement( "firstElement" ); XMLTest( "New element", true, first != 0 ); XMLNode* firstAfterInsertion = doc.InsertFirstChild( first ); XMLTest( "New element inserted first", true, firstAfterInsertion == first ); XMLNode* last = doc.NewElement( "lastElement" ); XMLTest( "New element", true, last != 0 ); XMLNode* lastAfterInsertion = doc.InsertEndChild( last ); XMLTest( "New element inserted last", true, lastAfterInsertion == last ); XMLNode* middle = doc.NewElement( "middleElement" ); XMLTest( "New element", true, middle != 0 ); XMLNode* middleAfterInsertion = doc.InsertAfterChild( first, middle ); XMLTest( "New element inserted middle", true, middleAfterInsertion == middle ); } { // Test: Programmatic DOM // Build: // <element> // <!--comment--> // <sub attrib="1" /> // <sub attrib="2" /> // <sub attrib="3" >& Text!</sub> // <element> XMLDocument* doc = new XMLDocument(); XMLNode* element = doc->InsertEndChild( doc->NewElement( "element" ) ); XMLElement* sub[3] = { doc->NewElement( "sub" ), doc->NewElement( "sub" ), doc->NewElement( "sub" ) }; for( int i=0; i<3; ++i ) { sub[i]->SetAttribute( "attrib", i ); } element->InsertEndChild( sub[2] ); const int dummyInitialValue = 1000; int dummyValue = dummyInitialValue; XMLNode* comment = element->InsertFirstChild( doc->NewComment( "comment" ) ); comment->SetUserData(&dummyValue); element->InsertAfterChild( comment, sub[0] ); element->InsertAfterChild( sub[0], sub[1] ); sub[2]->InsertFirstChild( doc->NewText( "& Text!" )); doc->Print(); XMLTest( "Programmatic DOM", "comment", doc->FirstChildElement( "element" )->FirstChild()->Value() ); XMLTest( "Programmatic DOM", "0", doc->FirstChildElement( "element" )->FirstChildElement()->Attribute( "attrib" ) ); XMLTest( "Programmatic DOM", 2, doc->FirstChildElement()->LastChildElement( "sub" )->IntAttribute( "attrib" ) ); XMLTest( "Programmatic DOM", "& Text!", doc->FirstChildElement()->LastChildElement( "sub" )->FirstChild()->ToText()->Value() ); XMLTest("User data - pointer", true, &dummyValue == comment->GetUserData(), false); XMLTest("User data - value behind pointer", dummyInitialValue, dummyValue, false); // And now deletion: element->DeleteChild( sub[2] ); doc->DeleteNode( comment ); element->FirstChildElement()->SetAttribute( "attrib", true ); element->LastChildElement()->DeleteAttribute( "attrib" ); XMLTest( "Programmatic DOM", true, doc->FirstChildElement()->FirstChildElement()->BoolAttribute( "attrib" ) ); const int defaultIntValue = 10; const int replacementIntValue = 20; int value1 = defaultIntValue; int value2 = doc->FirstChildElement()->LastChildElement()->IntAttribute( "attrib", replacementIntValue ); XMLError result = doc->FirstChildElement()->LastChildElement()->QueryIntAttribute( "attrib", &value1 ); XMLTest( "Programmatic DOM", XML_NO_ATTRIBUTE, result ); XMLTest( "Programmatic DOM", defaultIntValue, value1 ); XMLTest( "Programmatic DOM", replacementIntValue, value2 ); doc->Print(); { XMLPrinter streamer; doc->Print( &streamer ); printf( "%s", streamer.CStr() ); } { XMLPrinter streamer( 0, true ); doc->Print( &streamer ); XMLTest( "Compact mode", "<element><sub attrib=\"true\"/><sub/></element>", streamer.CStr(), false ); } doc->SaveFile( "./resources/out/pretty.xml" ); XMLTest( "Save pretty.xml", false, doc->Error() ); doc->SaveFile( "./resources/out/compact.xml", true ); XMLTest( "Save compact.xml", false, doc->Error() ); delete doc; } { // Test: Dream // XML1 : 1,187,569 bytes in 31,209 allocations // XML2 : 469,073 bytes in 323 allocations //int newStart = gNew; XMLDocument doc; doc.LoadFile( "resources/dream.xml" ); XMLTest( "Load dream.xml", false, doc.Error() ); doc.SaveFile( "resources/out/dreamout.xml" ); XMLTest( "Save dreamout.xml", false, doc.Error() ); doc.PrintError(); XMLTest( "Dream", "xml version=\"1.0\"", doc.FirstChild()->ToDeclaration()->Value() ); XMLTest( "Dream", true, doc.FirstChild()->NextSibling()->ToUnknown() != 0 ); XMLTest( "Dream", "DOCTYPE PLAY SYSTEM \"play.dtd\"", doc.FirstChild()->NextSibling()->ToUnknown()->Value() ); XMLTest( "Dream", "And Robin shall restore amends.", doc.LastChild()->LastChild()->LastChild()->LastChild()->LastChildElement()->GetText() ); XMLTest( "Dream", "And Robin shall restore amends.", doc.LastChild()->LastChild()->LastChild()->LastChild()->LastChildElement()->GetText() ); XMLDocument doc2; doc2.LoadFile( "resources/out/dreamout.xml" ); XMLTest( "Load dreamout.xml", false, doc2.Error() ); XMLTest( "Dream-out", "xml version=\"1.0\"", doc2.FirstChild()->ToDeclaration()->Value() ); XMLTest( "Dream-out", true, doc2.FirstChild()->NextSibling()->ToUnknown() != 0 ); XMLTest( "Dream-out", "DOCTYPE PLAY SYSTEM \"play.dtd\"", doc2.FirstChild()->NextSibling()->ToUnknown()->Value() ); XMLTest( "Dream-out", "And Robin shall restore amends.", doc2.LastChild()->LastChild()->LastChild()->LastChild()->LastChildElement()->GetText() ); //gNewTotal = gNew - newStart; } { const char* error = "<?xml version=\"1.0\" standalone=\"no\" ?>\n" "<passages count=\"006\" formatversion=\"20020620\">\n" " <wrong error>\n" "</passages>"; XMLDocument doc; doc.Parse( error ); XMLTest( "Bad XML", XML_ERROR_PARSING_ATTRIBUTE, doc.ErrorID() ); const char* errorStr = doc.ErrorStr(); XMLTest("Formatted error string", "Error=XML_ERROR_PARSING_ATTRIBUTE ErrorID=7 (0x7) Line number=3: XMLElement name=wrong", errorStr); } { const char* str = "<doc attr0='1' attr1='2.0' attr2='foo' />"; XMLDocument doc; doc.Parse( str ); XMLTest( "Top level attributes", false, doc.Error() ); XMLElement* ele = doc.FirstChildElement(); int iVal; XMLError result; double dVal; result = ele->QueryDoubleAttribute( "attr0", &dVal ); XMLTest( "Query attribute: int as double", XML_SUCCESS, result); XMLTest( "Query attribute: int as double", 1, (int)dVal ); XMLTest( "Query attribute: int as double", 1, (int)ele->DoubleAttribute("attr0")); result = ele->QueryDoubleAttribute( "attr1", &dVal ); XMLTest( "Query attribute: double as double", XML_SUCCESS, result); XMLTest( "Query attribute: double as double", 2.0, dVal ); XMLTest( "Query attribute: double as double", 2.0, ele->DoubleAttribute("attr1") ); result = ele->QueryIntAttribute( "attr1", &iVal ); XMLTest( "Query attribute: double as int", XML_SUCCESS, result); XMLTest( "Query attribute: double as int", 2, iVal ); result = ele->QueryIntAttribute( "attr2", &iVal ); XMLTest( "Query attribute: not a number", XML_WRONG_ATTRIBUTE_TYPE, result ); XMLTest( "Query attribute: not a number", 4.0, ele->DoubleAttribute("attr2", 4.0) ); result = ele->QueryIntAttribute( "bar", &iVal ); XMLTest( "Query attribute: does not exist", XML_NO_ATTRIBUTE, result ); XMLTest( "Query attribute: does not exist", true, ele->BoolAttribute("bar", true) ); } { const char* str = "<doc/>"; XMLDocument doc; doc.Parse( str ); XMLTest( "Empty top element", false, doc.Error() ); XMLElement* ele = doc.FirstChildElement(); int iVal, iVal2; double dVal, dVal2; ele->SetAttribute( "str", "strValue" ); ele->SetAttribute( "int", 1 ); ele->SetAttribute( "double", -1.0 ); const char* cStr = ele->Attribute( "str" ); { XMLError queryResult = ele->QueryIntAttribute( "int", &iVal ); XMLTest( "Query int attribute", XML_SUCCESS, queryResult); } { XMLError queryResult = ele->QueryDoubleAttribute( "double", &dVal ); XMLTest( "Query double attribute", XML_SUCCESS, queryResult); } { int queryResult = ele->QueryAttribute( "int", &iVal2 ); XMLTest( "Query int attribute generic", (int)XML_SUCCESS, queryResult); } { int queryResult = ele->QueryAttribute( "double", &dVal2 ); XMLTest( "Query double attribute generic", (int)XML_SUCCESS, queryResult); } XMLTest( "Attribute match test", "strValue", ele->Attribute( "str", "strValue" ) ); XMLTest( "Attribute round trip. c-string.", "strValue", cStr ); XMLTest( "Attribute round trip. int.", 1, iVal ); XMLTest( "Attribute round trip. double.", -1, (int)dVal ); XMLTest( "Alternate query", true, iVal == iVal2 ); XMLTest( "Alternate query", true, dVal == dVal2 ); XMLTest( "Alternate query", true, iVal == ele->IntAttribute("int") ); XMLTest( "Alternate query", true, dVal == ele->DoubleAttribute("double") ); } { XMLDocument doc; doc.LoadFile( "resources/utf8test.xml" ); XMLTest( "Load utf8test.xml", false, doc.Error() ); // Get the attribute "value" from the "Russian" element and check it. XMLElement* element = doc.FirstChildElement( "document" )->FirstChildElement( "Russian" ); const unsigned char correctValue[] = { 0xd1U, 0x86U, 0xd0U, 0xb5U, 0xd0U, 0xbdU, 0xd0U, 0xbdU, 0xd0U, 0xbeU, 0xd1U, 0x81U, 0xd1U, 0x82U, 0xd1U, 0x8cU, 0 }; XMLTest( "UTF-8: Russian value.", (const char*)correctValue, element->Attribute( "value" ) ); const unsigned char russianElementName[] = { 0xd0U, 0xa0U, 0xd1U, 0x83U, 0xd1U, 0x81U, 0xd1U, 0x81U, 0xd0U, 0xbaU, 0xd0U, 0xb8U, 0xd0U, 0xb9U, 0 }; const char russianText[] = "<\xD0\xB8\xD0\xBC\xD0\xB5\xD0\xB5\xD1\x82>"; XMLText* text = doc.FirstChildElement( "document" )->FirstChildElement( (const char*) russianElementName )->FirstChild()->ToText(); XMLTest( "UTF-8: Browsing russian element name.", russianText, text->Value() ); // Now try for a round trip. doc.SaveFile( "resources/out/utf8testout.xml" ); XMLTest( "UTF-8: Save testout.xml", false, doc.Error() ); // Check the round trip. bool roundTripOkay = false; FILE* saved = fopen( "resources/out/utf8testout.xml", "r" ); XMLTest( "UTF-8: Open utf8testout.xml", true, saved != 0 ); FILE* verify = fopen( "resources/utf8testverify.xml", "r" ); XMLTest( "UTF-8: Open utf8testverify.xml", true, verify != 0 ); if ( saved && verify ) { roundTripOkay = true; char verifyBuf[256]; while ( fgets( verifyBuf, 256, verify ) ) { char savedBuf[256]; fgets( savedBuf, 256, saved ); NullLineEndings( verifyBuf ); NullLineEndings( savedBuf ); if ( strcmp( verifyBuf, savedBuf ) ) { printf( "verify:%s<\n", verifyBuf ); printf( "saved :%s<\n", savedBuf ); roundTripOkay = false; break; } } } if ( saved ) fclose( saved ); if ( verify ) fclose( verify ); XMLTest( "UTF-8: Verified multi-language round trip.", true, roundTripOkay ); } // --------GetText()----------- { const char* str = "<foo>This is text</foo>"; XMLDocument doc; doc.Parse( str ); XMLTest( "Double whitespace", false, doc.Error() ); const XMLElement* element = doc.RootElement(); XMLTest( "GetText() normal use.", "This is text", element->GetText() ); str = "<foo><b>This is text</b></foo>"; doc.Parse( str ); XMLTest( "Bold text simulation", false, doc.Error() ); element = doc.RootElement(); XMLTest( "GetText() contained element.", element->GetText() == 0, true ); } // --------SetText()----------- { const char* str = "<foo></foo>"; XMLDocument doc; doc.Parse( str ); XMLTest( "Empty closed element", false, doc.Error() ); XMLElement* element = doc.RootElement(); element->SetText("darkness."); XMLTest( "SetText() normal use (open/close).", "darkness.", element->GetText() ); element->SetText("blue flame."); XMLTest( "SetText() replace.", "blue flame.", element->GetText() ); str = "<foo/>"; doc.Parse( str ); XMLTest( "Empty self-closed element", false, doc.Error() ); element = doc.RootElement(); element->SetText("The driver"); XMLTest( "SetText() normal use. (self-closing)", "The driver", element->GetText() ); element->SetText("<b>horses</b>"); XMLTest( "SetText() replace with tag-like text.", "<b>horses</b>", element->GetText() ); //doc.Print(); str = "<foo><bar>Text in nested element</bar></foo>"; doc.Parse( str ); XMLTest( "Text in nested element", false, doc.Error() ); element = doc.RootElement(); element->SetText("wolves"); XMLTest( "SetText() prefix to nested non-text children.", "wolves", element->GetText() ); str = "<foo/>"; doc.Parse( str ); XMLTest( "Empty self-closed element round 2", false, doc.Error() ); element = doc.RootElement(); element->SetText( "str" ); XMLTest( "SetText types", "str", element->GetText() ); element->SetText( 1 ); XMLTest( "SetText types", "1", element->GetText() ); element->SetText( 1U ); XMLTest( "SetText types", "1", element->GetText() ); element->SetText( true ); XMLTest( "SetText types", "true", element->GetText() ); element->SetText( 1.5f ); XMLTest( "SetText types", "1.5", element->GetText() ); element->SetText( 1.5 ); XMLTest( "SetText types", "1.5", element->GetText() ); } // ---------- Attributes --------- { static const int64_t BIG = -123456789012345678; XMLDocument doc; XMLElement* element = doc.NewElement("element"); doc.InsertFirstChild(element); { element->SetAttribute("attrib", int(-100)); { int v = 0; XMLError queryResult = element->QueryIntAttribute("attrib", &v); XMLTest("Attribute: int", XML_SUCCESS, queryResult, true); XMLTest("Attribute: int", -100, v, true); } { int v = 0; int queryResult = element->QueryAttribute("attrib", &v); XMLTest("Attribute: int", (int)XML_SUCCESS, queryResult, true); XMLTest("Attribute: int", -100, v, true); } XMLTest("Attribute: int", -100, element->IntAttribute("attrib"), true); } { element->SetAttribute("attrib", unsigned(100)); { unsigned v = 0; XMLError queryResult = element->QueryUnsignedAttribute("attrib", &v); XMLTest("Attribute: unsigned", XML_SUCCESS, queryResult, true); XMLTest("Attribute: unsigned", unsigned(100), v, true); } { unsigned v = 0; int queryResult = element->QueryAttribute("attrib", &v); XMLTest("Attribute: unsigned", (int)XML_SUCCESS, queryResult, true); XMLTest("Attribute: unsigned", unsigned(100), v, true); } { const char* v = "failed"; XMLError queryResult = element->QueryStringAttribute("not-attrib", &v); XMLTest("Attribute: string default", false, queryResult == XML_SUCCESS); queryResult = element->QueryStringAttribute("attrib", &v); XMLTest("Attribute: string", XML_SUCCESS, queryResult, true); XMLTest("Attribute: string", "100", v); } XMLTest("Attribute: unsigned", unsigned(100), element->UnsignedAttribute("attrib"), true); } { element->SetAttribute("attrib", BIG); { int64_t v = 0; XMLError queryResult = element->QueryInt64Attribute("attrib", &v); XMLTest("Attribute: int64_t", XML_SUCCESS, queryResult, true); XMLTest("Attribute: int64_t", BIG, v, true); } { int64_t v = 0; int queryResult = element->QueryAttribute("attrib", &v); XMLTest("Attribute: int64_t", (int)XML_SUCCESS, queryResult, true); XMLTest("Attribute: int64_t", BIG, v, true); } XMLTest("Attribute: int64_t", BIG, element->Int64Attribute("attrib"), true); } { element->SetAttribute("attrib", true); { bool v = false; XMLError queryResult = element->QueryBoolAttribute("attrib", &v); XMLTest("Attribute: bool", XML_SUCCESS, queryResult, true); XMLTest("Attribute: bool", true, v, true); } { bool v = false; int queryResult = element->QueryAttribute("attrib", &v); XMLTest("Attribute: bool", (int)XML_SUCCESS, queryResult, true); XMLTest("Attribute: bool", true, v, true); } XMLTest("Attribute: bool", true, element->BoolAttribute("attrib"), true); } { element->SetAttribute("attrib", true); const char* result = element->Attribute("attrib"); XMLTest("Bool true is 'true'", "true", result); XMLUtil::SetBoolSerialization("1", "0"); element->SetAttribute("attrib", true); result = element->Attribute("attrib"); XMLTest("Bool true is '1'", "1", result); XMLUtil::SetBoolSerialization(0, 0); } { element->SetAttribute("attrib", 100.0); { double v = 0; XMLError queryResult = element->QueryDoubleAttribute("attrib", &v); XMLTest("Attribute: double", XML_SUCCESS, queryResult, true); XMLTest("Attribute: double", 100.0, v, true); } { double v = 0; int queryResult = element->QueryAttribute("attrib", &v); XMLTest("Attribute: bool", (int)XML_SUCCESS, queryResult, true); XMLTest("Attribute: double", 100.0, v, true); } XMLTest("Attribute: double", 100.0, element->DoubleAttribute("attrib"), true); } { element->SetAttribute("attrib", 100.0f); { float v = 0; XMLError queryResult = element->QueryFloatAttribute("attrib", &v); XMLTest("Attribute: float", XML_SUCCESS, queryResult, true); XMLTest("Attribute: float", 100.0f, v, true); } { float v = 0; int queryResult = element->QueryAttribute("attrib", &v); XMLTest("Attribute: float", (int)XML_SUCCESS, queryResult, true); XMLTest("Attribute: float", 100.0f, v, true); } XMLTest("Attribute: float", 100.0f, element->FloatAttribute("attrib"), true); } { element->SetText(BIG); int64_t v = 0; XMLError queryResult = element->QueryInt64Text(&v); XMLTest("Element: int64_t", XML_SUCCESS, queryResult, true); XMLTest("Element: int64_t", BIG, v, true); } } // ---------- XMLPrinter stream mode ------ { { FILE* printerfp = fopen("resources/out/printer.xml", "w"); XMLTest("Open printer.xml", true, printerfp != 0); XMLPrinter printer(printerfp); printer.OpenElement("foo"); printer.PushAttribute("attrib-text", "text"); printer.PushAttribute("attrib-int", int(1)); printer.PushAttribute("attrib-unsigned", unsigned(2)); printer.PushAttribute("attrib-int64", int64_t(3)); printer.PushAttribute("attrib-bool", true); printer.PushAttribute("attrib-double", 4.0); printer.CloseElement(); fclose(printerfp); } { XMLDocument doc; doc.LoadFile("resources/out/printer.xml"); XMLTest("XMLPrinter Stream mode: load", XML_SUCCESS, doc.ErrorID(), true); const XMLDocument& cdoc = doc; const XMLAttribute* attrib = cdoc.FirstChildElement("foo")->FindAttribute("attrib-text"); XMLTest("attrib-text", "text", attrib->Value(), true); attrib = cdoc.FirstChildElement("foo")->FindAttribute("attrib-int"); XMLTest("attrib-int", int(1), attrib->IntValue(), true); attrib = cdoc.FirstChildElement("foo")->FindAttribute("attrib-unsigned"); XMLTest("attrib-unsigned", unsigned(2), attrib->UnsignedValue(), true); attrib = cdoc.FirstChildElement("foo")->FindAttribute("attrib-int64"); XMLTest("attrib-int64", int64_t(3), attrib->Int64Value(), true); attrib = cdoc.FirstChildElement("foo")->FindAttribute("attrib-bool"); XMLTest("attrib-bool", true, attrib->BoolValue(), true); attrib = cdoc.FirstChildElement("foo")->FindAttribute("attrib-double"); XMLTest("attrib-double", 4.0, attrib->DoubleValue(), true); } } // ---------- CDATA --------------- { const char* str = "<xmlElement>" "<![CDATA[" "I am > the rules!\n" "...since I make symbolic puns" "]]>" "</xmlElement>"; XMLDocument doc; doc.Parse( str ); XMLTest( "CDATA symbolic puns round 1", false, doc.Error() ); doc.Print(); XMLTest( "CDATA parse.", "I am > the rules!\n...since I make symbolic puns", doc.FirstChildElement()->FirstChild()->Value(), false ); } // ----------- CDATA ------------- { const char* str = "<xmlElement>" "<![CDATA[" "<b>I am > the rules!</b>\n" "...since I make symbolic puns" "]]>" "</xmlElement>"; XMLDocument doc; doc.Parse( str ); XMLTest( "CDATA symbolic puns round 2", false, doc.Error() ); doc.Print(); XMLTest( "CDATA parse. [ tixml1:1480107 ]", "<b>I am > the rules!</b>\n...since I make symbolic puns", doc.FirstChildElement()->FirstChild()->Value(), false ); } // InsertAfterChild causes crash. { // InsertBeforeChild and InsertAfterChild causes crash. XMLDocument doc; XMLElement* parent = doc.NewElement( "Parent" ); doc.InsertFirstChild( parent ); XMLElement* childText0 = doc.NewElement( "childText0" ); XMLElement* childText1 = doc.NewElement( "childText1" ); XMLNode* childNode0 = parent->InsertEndChild( childText0 ); XMLTest( "InsertEndChild() return", true, childNode0 == childText0 ); XMLNode* childNode1 = parent->InsertAfterChild( childNode0, childText1 ); XMLTest( "InsertAfterChild() return", true, childNode1 == childText1 ); XMLTest( "Test InsertAfterChild on empty node. ", true, ( childNode1 == parent->LastChild() ) ); } { // Entities not being written correctly. // From Lynn Allen const char* passages = "<?xml version=\"1.0\" standalone=\"no\" ?>" "<passages count=\"006\" formatversion=\"20020620\">" "<psg context=\"Line 5 has &quot;quotation marks&quot; and &apos;apostrophe marks&apos;." " It also has &lt;, &gt;, and &amp;, as well as a fake copyright &#xA9;.\"> </psg>" "</passages>"; XMLDocument doc; doc.Parse( passages ); XMLTest( "Entity transformation parse round 1", false, doc.Error() ); XMLElement* psg = doc.RootElement()->FirstChildElement(); const char* context = psg->Attribute( "context" ); const char* expected = "Line 5 has \"quotation marks\" and 'apostrophe marks'. It also has <, >, and &, as well as a fake copyright \xC2\xA9."; XMLTest( "Entity transformation: read. ", expected, context, true ); const char* textFilePath = "resources/out/textfile.txt"; FILE* textfile = fopen( textFilePath, "w" ); XMLTest( "Entity transformation: open text file for writing", true, textfile != 0, true ); if ( textfile ) { XMLPrinter streamer( textfile ); bool acceptResult = psg->Accept( &streamer ); fclose( textfile ); XMLTest( "Entity transformation: Accept", true, acceptResult ); } textfile = fopen( textFilePath, "r" ); XMLTest( "Entity transformation: open text file for reading", true, textfile != 0, true ); if ( textfile ) { char buf[ 1024 ]; fgets( buf, 1024, textfile ); XMLTest( "Entity transformation: write. ", "<psg context=\"Line 5 has &quot;quotation marks&quot; and &apos;apostrophe marks&apos;." " It also has &lt;, &gt;, and &amp;, as well as a fake copyright \xC2\xA9.\"/>\n", buf, false ); fclose( textfile ); } } { // Suppress entities. const char* passages = "<?xml version=\"1.0\" standalone=\"no\" ?>" "<passages count=\"006\" formatversion=\"20020620\">" "<psg context=\"Line 5 has &quot;quotation marks&quot; and &apos;apostrophe marks&apos;.\">Crazy &ttk;</psg>" "</passages>"; XMLDocument doc( false ); doc.Parse( passages ); XMLTest( "Entity transformation parse round 2", false, doc.Error() ); XMLTest( "No entity parsing.", "Line 5 has &quot;quotation marks&quot; and &apos;apostrophe marks&apos;.", doc.FirstChildElement()->FirstChildElement()->Attribute( "context" ) ); XMLTest( "No entity parsing.", "Crazy &ttk;", doc.FirstChildElement()->FirstChildElement()->FirstChild()->Value() ); doc.Print(); } { const char* test = "<?xml version='1.0'?><a.elem xmi.version='2.0'/>"; XMLDocument doc; doc.Parse( test ); XMLTest( "dot in names", false, doc.Error() ); XMLTest( "dot in names", "a.elem", doc.FirstChildElement()->Name() ); XMLTest( "dot in names", "2.0", doc.FirstChildElement()->Attribute( "xmi.version" ) ); } { const char* test = "<element><Name>1.1 Start easy ignore fin thickness&#xA;</Name></element>"; XMLDocument doc; doc.Parse( test ); XMLTest( "fin thickness", false, doc.Error() ); XMLText* text = doc.FirstChildElement()->FirstChildElement()->FirstChild()->ToText(); XMLTest( "Entity with one digit.", "1.1 Start easy ignore fin thickness\n", text->Value(), false ); } { // DOCTYPE not preserved (950171) // const char* doctype = "<?xml version=\"1.0\" ?>" "<!DOCTYPE PLAY SYSTEM 'play.dtd'>" "<!ELEMENT title (#PCDATA)>" "<!ELEMENT books (title,authors)>" "<element />"; XMLDocument doc; doc.Parse( doctype ); XMLTest( "PLAY SYSTEM parse", false, doc.Error() ); doc.SaveFile( "resources/out/test7.xml" ); XMLTest( "PLAY SYSTEM save", false, doc.Error() ); doc.DeleteChild( doc.RootElement() ); doc.LoadFile( "resources/out/test7.xml" ); XMLTest( "PLAY SYSTEM load", false, doc.Error() ); doc.Print(); const XMLUnknown* decl = doc.FirstChild()->NextSibling()->ToUnknown(); XMLTest( "Correct value of unknown.", "DOCTYPE PLAY SYSTEM 'play.dtd'", decl->Value() ); } { // Comments do not stream out correctly. const char* doctype = "<!-- Somewhat<evil> -->"; XMLDocument doc; doc.Parse( doctype ); XMLTest( "Comment somewhat evil", false, doc.Error() ); XMLComment* comment = doc.FirstChild()->ToComment(); XMLTest( "Comment formatting.", " Somewhat<evil> ", comment->Value() ); } { // Double attributes const char* doctype = "<element attr='red' attr='blue' />"; XMLDocument doc; doc.Parse( doctype ); XMLTest( "Parsing repeated attributes.", XML_ERROR_PARSING_ATTRIBUTE, doc.ErrorID() ); // is an error to tinyxml (didn't use to be, but caused issues) doc.PrintError(); } { // Embedded null in stream. const char* doctype = "<element att\0r='red' attr='blue' />"; XMLDocument doc; doc.Parse( doctype ); XMLTest( "Embedded null throws error.", true, doc.Error() ); } { // Empty documents should return TIXML_XML_ERROR_PARSING_EMPTY, bug 1070717 const char* str = ""; XMLDocument doc; doc.Parse( str ); XMLTest( "Empty document error", XML_ERROR_EMPTY_DOCUMENT, doc.ErrorID() ); // But be sure there is an error string! const char* errorStr = doc.ErrorStr(); XMLTest("Error string should be set", "Error=XML_ERROR_EMPTY_DOCUMENT ErrorID=13 (0xd) Line number=0", errorStr); } { // Documents with all whitespaces should return TIXML_XML_ERROR_PARSING_EMPTY, bug 1070717 const char* str = " "; XMLDocument doc; doc.Parse( str ); XMLTest( "All whitespaces document error", XML_ERROR_EMPTY_DOCUMENT, doc.ErrorID() ); } { // Low entities XMLDocument doc; doc.Parse( "<test>&#x0e;</test>" ); XMLTest( "Hex values", false, doc.Error() ); const char result[] = { 0x0e, 0 }; XMLTest( "Low entities.", result, doc.FirstChildElement()->GetText() ); doc.Print(); } { // Attribute values with trailing quotes not handled correctly XMLDocument doc; doc.Parse( "<foo attribute=bar\" />" ); XMLTest( "Throw error with bad end quotes.", true, doc.Error() ); } { // [ 1663758 ] Failure to report error on bad XML XMLDocument xml; xml.Parse("<x>"); XMLTest("Missing end tag at end of input", true, xml.Error()); xml.Parse("<x> "); XMLTest("Missing end tag with trailing whitespace", true, xml.Error()); xml.Parse("<x></y>"); XMLTest("Mismatched tags", XML_ERROR_MISMATCHED_ELEMENT, xml.ErrorID() ); } { // [ 1475201 ] TinyXML parses entities in comments XMLDocument xml; xml.Parse("<!-- declarations for <head> & <body> -->" "<!-- far &amp; away -->" ); XMLTest( "Declarations for head and body", false, xml.Error() ); XMLNode* e0 = xml.FirstChild(); XMLNode* e1 = e0->NextSibling(); XMLComment* c0 = e0->ToComment(); XMLComment* c1 = e1->ToComment(); XMLTest( "Comments ignore entities.", " declarations for <head> & <body> ", c0->Value(), true ); XMLTest( "Comments ignore entities.", " far &amp; away ", c1->Value(), true ); } { XMLDocument xml; xml.Parse( "<Parent>" "<child1 att=''/>" "<!-- With this comment, child2 will not be parsed! -->" "<child2 att=''/>" "</Parent>" ); XMLTest( "Comments iteration", false, xml.Error() ); xml.Print(); int count = 0; for( XMLNode* ele = xml.FirstChildElement( "Parent" )->FirstChild(); ele; ele = ele->NextSibling() ) { ++count; } XMLTest( "Comments iterate correctly.", 3, count ); } { // trying to repro ]1874301]. If it doesn't go into an infinite loop, all is well. unsigned char buf[] = "<?xml version=\"1.0\" encoding=\"utf-8\"?><feed><![CDATA[Test XMLblablablalblbl"; buf[60] = 239; buf[61] = 0; XMLDocument doc; doc.Parse( (const char*)buf); XMLTest( "Broken CDATA", true, doc.Error() ); } { // bug 1827248 Error while parsing a little bit malformed file // Actually not malformed - should work. XMLDocument xml; xml.Parse( "<attributelist> </attributelist >" ); XMLTest( "Handle end tag whitespace", false, xml.Error() ); } { // This one must not result in an infinite loop XMLDocument xml; xml.Parse( "<infinite>loop" ); XMLTest( "No closing element", true, xml.Error() ); XMLTest( "Infinite loop test.", true, true ); } #endif { const char* pub = "<?xml version='1.0'?> <element><sub/></element> <!--comment--> <!DOCTYPE>"; XMLDocument doc; doc.Parse( pub ); XMLTest( "Trailing DOCTYPE", false, doc.Error() ); XMLDocument clone; for( const XMLNode* node=doc.FirstChild(); node; node=node->NextSibling() ) { XMLNode* copy = node->ShallowClone( &clone ); clone.InsertEndChild( copy ); } clone.Print(); int count=0; const XMLNode* a=clone.FirstChild(); const XMLNode* b=doc.FirstChild(); for( ; a && b; a=a->NextSibling(), b=b->NextSibling() ) { ++count; XMLTest( "Clone and Equal", true, a->ShallowEqual( b )); } XMLTest( "Clone and Equal", 4, count ); } { // Deep Cloning of root element. XMLDocument doc2; XMLPrinter printer1; { // Make sure doc1 is deleted before we test doc2 const char* xml = "<root>" " <child1 foo='bar'/>" " <!-- comment thing -->" " <child2 val='1'>Text</child2>" "</root>"; XMLDocument doc; doc.Parse(xml); XMLTest( "Parse before deep cloning root element", false, doc.Error() ); doc.Print(&printer1); XMLNode* root = doc.RootElement()->DeepClone(&doc2); doc2.InsertFirstChild(root); } XMLPrinter printer2; doc2.Print(&printer2); XMLTest("Deep clone of element.", printer1.CStr(), printer2.CStr(), true); } { // Deep Cloning of sub element. XMLDocument doc2; XMLPrinter printer1; { // Make sure doc1 is deleted before we test doc2 const char* xml = "<?xml version ='1.0'?>" "<root>" " <child1 foo='bar'/>" " <!-- comment thing -->" " <child2 val='1'>Text</child2>" "</root>"; XMLDocument doc; doc.Parse(xml); XMLTest( "Parse before deep cloning sub element", false, doc.Error() ); const XMLElement* subElement = doc.FirstChildElement("root")->FirstChildElement("child2"); bool acceptResult = subElement->Accept(&printer1); XMLTest( "Accept before deep cloning", true, acceptResult ); XMLNode* clonedSubElement = subElement->DeepClone(&doc2); doc2.InsertFirstChild(clonedSubElement); } XMLPrinter printer2; doc2.Print(&printer2); XMLTest("Deep clone of sub-element.", printer1.CStr(), printer2.CStr(), true); } { // Deep cloning of document. XMLDocument doc2; XMLPrinter printer1; { // Make sure doc1 is deleted before we test doc2 const char* xml = "<?xml version ='1.0'?>" "<!-- Top level comment. -->" "<root>" " <child1 foo='bar'/>" " <!-- comment thing -->" " <child2 val='1'>Text</child2>" "</root>"; XMLDocument doc; doc.Parse(xml); XMLTest( "Parse before deep cloning document", false, doc.Error() ); doc.Print(&printer1); doc.DeepCopy(&doc2); } XMLPrinter printer2; doc2.Print(&printer2); XMLTest("DeepCopy of document.", printer1.CStr(), printer2.CStr(), true); } { // This shouldn't crash. XMLDocument doc; if(XML_SUCCESS != doc.LoadFile( "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" )) { doc.PrintError(); } XMLTest( "Error in snprinf handling.", true, doc.Error() ); } { // Attribute ordering. static const char* xml = "<element attrib1=\"1\" attrib2=\"2\" attrib3=\"3\" />"; XMLDocument doc; doc.Parse( xml ); XMLTest( "Parse for attribute ordering", false, doc.Error() ); XMLElement* ele = doc.FirstChildElement(); const XMLAttribute* a = ele->FirstAttribute(); XMLTest( "Attribute order", "1", a->Value() ); a = a->Next(); XMLTest( "Attribute order", "2", a->Value() ); a = a->Next(); XMLTest( "Attribute order", "3", a->Value() ); XMLTest( "Attribute order", "attrib3", a->Name() ); ele->DeleteAttribute( "attrib2" ); a = ele->FirstAttribute(); XMLTest( "Attribute order", "1", a->Value() ); a = a->Next(); XMLTest( "Attribute order", "3", a->Value() ); ele->DeleteAttribute( "attrib1" ); ele->DeleteAttribute( "attrib3" ); XMLTest( "Attribute order (empty)", true, ele->FirstAttribute() == 0 ); } { // Make sure an attribute with a space in it succeeds. static const char* xml0 = "<element attribute1= \"Test Attribute\"/>"; static const char* xml1 = "<element attribute1 =\"Test Attribute\"/>"; static const char* xml2 = "<element attribute1 = \"Test Attribute\"/>"; XMLDocument doc0; doc0.Parse( xml0 ); XMLTest( "Parse attribute with space 1", false, doc0.Error() ); XMLDocument doc1; doc1.Parse( xml1 ); XMLTest( "Parse attribute with space 2", false, doc1.Error() ); XMLDocument doc2; doc2.Parse( xml2 ); XMLTest( "Parse attribute with space 3", false, doc2.Error() ); XMLElement* ele = 0; ele = doc0.FirstChildElement(); XMLTest( "Attribute with space #1", "Test Attribute", ele->Attribute( "attribute1" ) ); ele = doc1.FirstChildElement(); XMLTest( "Attribute with space #2", "Test Attribute", ele->Attribute( "attribute1" ) ); ele = doc2.FirstChildElement(); XMLTest( "Attribute with space #3", "Test Attribute", ele->Attribute( "attribute1" ) ); } { // Make sure we don't go into an infinite loop. static const char* xml = "<doc><element attribute='attribute'/><element attribute='attribute'/></doc>"; XMLDocument doc; doc.Parse( xml ); XMLTest( "Parse two elements with attribute", false, doc.Error() ); XMLElement* ele0 = doc.FirstChildElement()->FirstChildElement(); XMLElement* ele1 = ele0->NextSiblingElement(); bool equal = ele0->ShallowEqual( ele1 ); XMLTest( "Infinite loop in shallow equal.", true, equal ); } // -------- Handles ------------ { static const char* xml = "<element attrib='bar'><sub>Text</sub></element>"; XMLDocument doc; doc.Parse( xml ); XMLTest( "Handle, parse element with attribute and nested element", false, doc.Error() ); { XMLElement* ele = XMLHandle( doc ).FirstChildElement( "element" ).FirstChild().ToElement(); XMLTest( "Handle, non-const, element is found", true, ele != 0 ); XMLTest( "Handle, non-const, element name matches", "sub", ele->Value() ); } { XMLHandle docH( doc ); XMLElement* ele = docH.FirstChildElement( "noSuchElement" ).FirstChildElement( "element" ).ToElement(); XMLTest( "Handle, non-const, element not found", true, ele == 0 ); } { const XMLElement* ele = XMLConstHandle( doc ).FirstChildElement( "element" ).FirstChild().ToElement(); XMLTest( "Handle, const, element is found", true, ele != 0 ); XMLTest( "Handle, const, element name matches", "sub", ele->Value() ); } { XMLConstHandle docH( doc ); const XMLElement* ele = docH.FirstChildElement( "noSuchElement" ).FirstChildElement( "element" ).ToElement(); XMLTest( "Handle, const, element not found", true, ele == 0 ); } } { // Default Declaration & BOM XMLDocument doc; doc.InsertEndChild( doc.NewDeclaration() ); doc.SetBOM( true ); XMLPrinter printer; doc.Print( &printer ); static const char* result = "\xef\xbb\xbf<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; XMLTest( "BOM and default declaration", result, printer.CStr(), false ); XMLTest( "CStrSize", 42, printer.CStrSize(), false ); } { const char* xml = "<ipxml ws='1'><info bla=' /></ipxml>"; XMLDocument doc; doc.Parse( xml ); XMLTest( "Ill formed XML", true, doc.Error() ); } // QueryXYZText { const char* xml = "<point> <x>1.2</x> <y>1</y> <z>38</z> <valid>true</valid> </point>"; XMLDocument doc; doc.Parse( xml ); XMLTest( "Parse points", false, doc.Error() ); const XMLElement* pointElement = doc.RootElement(); { int intValue = 0; XMLError queryResult = pointElement->FirstChildElement( "y" )->QueryIntText( &intValue ); XMLTest( "QueryIntText result", XML_SUCCESS, queryResult, false ); XMLTest( "QueryIntText", 1, intValue, false ); } { unsigned unsignedValue = 0; XMLError queryResult = pointElement->FirstChildElement( "y" )->QueryUnsignedText( &unsignedValue ); XMLTest( "QueryUnsignedText result", XML_SUCCESS, queryResult, false ); XMLTest( "QueryUnsignedText", (unsigned)1, unsignedValue, false ); } { float floatValue = 0; XMLError queryResult = pointElement->FirstChildElement( "x" )->QueryFloatText( &floatValue ); XMLTest( "QueryFloatText result", XML_SUCCESS, queryResult, false ); XMLTest( "QueryFloatText", 1.2f, floatValue, false ); } { double doubleValue = 0; XMLError queryResult = pointElement->FirstChildElement( "x" )->QueryDoubleText( &doubleValue ); XMLTest( "QueryDoubleText result", XML_SUCCESS, queryResult, false ); XMLTest( "QueryDoubleText", 1.2, doubleValue, false ); } { bool boolValue = false; XMLError queryResult = pointElement->FirstChildElement( "valid" )->QueryBoolText( &boolValue ); XMLTest( "QueryBoolText result", XML_SUCCESS, queryResult, false ); XMLTest( "QueryBoolText", true, boolValue, false ); } } { const char* xml = "<element><_sub/><:sub/><sub:sub/><sub-sub/></element>"; XMLDocument doc; doc.Parse( xml ); XMLTest( "Non-alpha element lead letter parses.", false, doc.Error() ); } { const char* xml = "<element _attr1=\"foo\" :attr2=\"bar\"></element>"; XMLDocument doc; doc.Parse( xml ); XMLTest("Non-alpha attribute lead character parses.", false, doc.Error()); } { const char* xml = "<3lement></3lement>"; XMLDocument doc; doc.Parse( xml ); XMLTest("Element names with lead digit fail to parse.", true, doc.Error()); } { const char* xml = "<element/>WOA THIS ISN'T GOING TO PARSE"; XMLDocument doc; doc.Parse( xml, 10 ); XMLTest( "Set length of incoming data", false, doc.Error() ); } { XMLDocument doc; XMLTest( "Document is initially empty", true, doc.NoChildren() ); doc.Clear(); XMLTest( "Empty is empty after Clear()", true, doc.NoChildren() ); doc.LoadFile( "resources/dream.xml" ); XMLTest( "Load dream.xml", false, doc.Error() ); XMLTest( "Document has something to Clear()", false, doc.NoChildren() ); doc.Clear(); XMLTest( "Document Clear()'s", true, doc.NoChildren() ); } { XMLDocument doc; XMLTest( "No error initially", false, doc.Error() ); XMLError error = doc.Parse( "This is not XML" ); XMLTest( "Error after invalid XML", true, doc.Error() ); XMLTest( "Error after invalid XML", error, doc.ErrorID() ); doc.Clear(); XMLTest( "No error after Clear()", false, doc.Error() ); } // ----------- Whitespace ------------ { const char* xml = "<element>" "<a> This \nis &apos; text &apos; </a>" "<b> This is &apos; text &apos; \n</b>" "<c>This is &apos; \n\n text &apos;</c>" "</element>"; XMLDocument doc( true, COLLAPSE_WHITESPACE ); doc.Parse( xml ); XMLTest( "Parse with whitespace collapsing and &apos", false, doc.Error() ); const XMLElement* element = doc.FirstChildElement(); for( const XMLElement* parent = element->FirstChildElement(); parent; parent = parent->NextSiblingElement() ) { XMLTest( "Whitespace collapse", "This is ' text '", parent->GetText() ); } } #if 0 { // Passes if assert doesn't fire. XMLDocument xmlDoc; xmlDoc.NewDeclaration(); xmlDoc.NewComment("Configuration file"); XMLElement *root = xmlDoc.NewElement("settings"); root->SetAttribute("version", 2); } #endif { const char* xml = "<element> </element>"; XMLDocument doc( true, COLLAPSE_WHITESPACE ); doc.Parse( xml ); XMLTest( "Parse with all whitespaces", false, doc.Error() ); XMLTest( "Whitespace all space", true, 0 == doc.FirstChildElement()->FirstChild() ); } { // An assert should not fire. const char* xml = "<element/>"; XMLDocument doc; doc.Parse( xml ); XMLTest( "Parse with self-closed element", false, doc.Error() ); XMLElement* ele = doc.NewElement( "unused" ); // This will get cleaned up with the 'doc' going out of scope. XMLTest( "Tracking unused elements", true, ele != 0, false ); } { const char* xml = "<parent><child>abc</child></parent>"; XMLDocument doc; doc.Parse( xml ); XMLTest( "Parse for printing of sub-element", false, doc.Error() ); XMLElement* ele = doc.FirstChildElement( "parent")->FirstChildElement( "child"); XMLPrinter printer; bool acceptResult = ele->Accept( &printer ); XMLTest( "Accept of sub-element", true, acceptResult ); XMLTest( "Printing of sub-element", "<child>abc</child>\n", printer.CStr(), false ); } { XMLDocument doc; XMLError error = doc.LoadFile( "resources/empty.xml" ); XMLTest( "Loading an empty file", XML_ERROR_EMPTY_DOCUMENT, error ); XMLTest( "Loading an empty file and ErrorName as string", "XML_ERROR_EMPTY_DOCUMENT", doc.ErrorName() ); doc.PrintError(); } { // BOM preservation static const char* xml_bom_preservation = "\xef\xbb\xbf<element/>\n"; { XMLDocument doc; XMLTest( "BOM preservation (parse)", XML_SUCCESS, doc.Parse( xml_bom_preservation ), false ); XMLPrinter printer; doc.Print( &printer ); XMLTest( "BOM preservation (compare)", xml_bom_preservation, printer.CStr(), false, true ); doc.SaveFile( "resources/bomtest.xml" ); XMLTest( "Save bomtest.xml", false, doc.Error() ); } { XMLDocument doc; doc.LoadFile( "resources/bomtest.xml" ); XMLTest( "Load bomtest.xml", false, doc.Error() ); XMLTest( "BOM preservation (load)", true, doc.HasBOM(), false ); XMLPrinter printer; doc.Print( &printer ); XMLTest( "BOM preservation (compare)", xml_bom_preservation, printer.CStr(), false, true ); } } { // Insertion with Removal const char* xml = "<?xml version=\"1.0\" ?>" "<root>" "<one>" "<subtree>" "<elem>element 1</elem>text<!-- comment -->" "</subtree>" "</one>" "<two/>" "</root>"; const char* xmlInsideTwo = "<?xml version=\"1.0\" ?>" "<root>" "<one/>" "<two>" "<subtree>" "<elem>element 1</elem>text<!-- comment -->" "</subtree>" "</two>" "</root>"; const char* xmlAfterOne = "<?xml version=\"1.0\" ?>" "<root>" "<one/>" "<subtree>" "<elem>element 1</elem>text<!-- comment -->" "</subtree>" "<two/>" "</root>"; const char* xmlAfterTwo = "<?xml version=\"1.0\" ?>" "<root>" "<one/>" "<two/>" "<subtree>" "<elem>element 1</elem>text<!-- comment -->" "</subtree>" "</root>"; XMLDocument doc; doc.Parse(xml); XMLTest( "Insertion with removal parse round 1", false, doc.Error() ); XMLElement* subtree = doc.RootElement()->FirstChildElement("one")->FirstChildElement("subtree"); XMLElement* two = doc.RootElement()->FirstChildElement("two"); two->InsertFirstChild(subtree); XMLPrinter printer1(0, true); bool acceptResult = doc.Accept(&printer1); XMLTest("Move node from within <one> to <two> - Accept()", true, acceptResult); XMLTest("Move node from within <one> to <two>", xmlInsideTwo, printer1.CStr()); doc.Parse(xml); XMLTest( "Insertion with removal parse round 2", false, doc.Error() ); subtree = doc.RootElement()->FirstChildElement("one")->FirstChildElement("subtree"); two = doc.RootElement()->FirstChildElement("two"); doc.RootElement()->InsertAfterChild(two, subtree); XMLPrinter printer2(0, true); acceptResult = doc.Accept(&printer2); XMLTest("Move node from within <one> after <two> - Accept()", true, acceptResult); XMLTest("Move node from within <one> after <two>", xmlAfterTwo, printer2.CStr(), false); doc.Parse(xml); XMLTest( "Insertion with removal parse round 3", false, doc.Error() ); XMLNode* one = doc.RootElement()->FirstChildElement("one"); subtree = one->FirstChildElement("subtree"); doc.RootElement()->InsertAfterChild(one, subtree); XMLPrinter printer3(0, true); acceptResult = doc.Accept(&printer3); XMLTest("Move node from within <one> after <one> - Accept()", true, acceptResult); XMLTest("Move node from within <one> after <one>", xmlAfterOne, printer3.CStr(), false); doc.Parse(xml); XMLTest( "Insertion with removal parse round 4", false, doc.Error() ); subtree = doc.RootElement()->FirstChildElement("one")->FirstChildElement("subtree"); two = doc.RootElement()->FirstChildElement("two"); doc.RootElement()->InsertEndChild(subtree); XMLPrinter printer4(0, true); acceptResult = doc.Accept(&printer4); XMLTest("Move node from within <one> after <two> - Accept()", true, acceptResult); XMLTest("Move node from within <one> after <two>", xmlAfterTwo, printer4.CStr(), false); } { const char* xml = "<svg width = \"128\" height = \"128\">" " <text> </text>" "</svg>"; XMLDocument doc; doc.Parse(xml); XMLTest( "Parse svg with text", false, doc.Error() ); doc.Print(); } { // Test that it doesn't crash. const char* xml = "<?xml version=\"1.0\"?><root><sample><field0><1</field0><field1>2</field1></sample></root>"; XMLDocument doc; doc.Parse(xml); XMLTest( "Parse root-sample-field0", true, doc.Error() ); doc.PrintError(); } #if 1 // the question being explored is what kind of print to use: // https://github.com/leethomason/tinyxml2/issues/63 { //const char* xml = "<element attrA='123456789.123456789' attrB='1.001e9' attrC='1.0e-10' attrD='1001000000.000000' attrE='0.1234567890123456789'/>"; const char* xml = "<element/>"; XMLDocument doc; doc.Parse( xml ); XMLTest( "Parse self-closed empty element", false, doc.Error() ); doc.FirstChildElement()->SetAttribute( "attrA-f64", 123456789.123456789 ); doc.FirstChildElement()->SetAttribute( "attrB-f64", 1.001e9 ); doc.FirstChildElement()->SetAttribute( "attrC-f64", 1.0e9 ); doc.FirstChildElement()->SetAttribute( "attrC-f64", 1.0e20 ); doc.FirstChildElement()->SetAttribute( "attrD-f64", 1.0e-10 ); doc.FirstChildElement()->SetAttribute( "attrD-f64", 0.123456789 ); doc.FirstChildElement()->SetAttribute( "attrA-f32", 123456789.123456789f ); doc.FirstChildElement()->SetAttribute( "attrB-f32", 1.001e9f ); doc.FirstChildElement()->SetAttribute( "attrC-f32", 1.0e9f ); doc.FirstChildElement()->SetAttribute( "attrC-f32", 1.0e20f ); doc.FirstChildElement()->SetAttribute( "attrD-f32", 1.0e-10f ); doc.FirstChildElement()->SetAttribute( "attrD-f32", 0.123456789f ); doc.Print(); /* The result of this test is platform, compiler, and library version dependent. :(" XMLPrinter printer; doc.Print( &printer ); XMLTest( "Float and double formatting.", "<element attrA-f64=\"123456789.12345679\" attrB-f64=\"1001000000\" attrC-f64=\"1e+20\" attrD-f64=\"0.123456789\" attrA-f32=\"1.2345679e+08\" attrB-f32=\"1.001e+09\" attrC-f32=\"1e+20\" attrD-f32=\"0.12345679\"/>\n", printer.CStr(), true ); */ } #endif { // Issue #184 // If it doesn't assert, it passes. Caused by objects // getting created during parsing which are then // inaccessible in the memory pools. const char* xmlText = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><test>"; { XMLDocument doc; doc.Parse(xmlText); XMLTest( "Parse hex no closing tag round 1", true, doc.Error() ); } { XMLDocument doc; doc.Parse(xmlText); XMLTest( "Parse hex no closing tag round 2", true, doc.Error() ); doc.Clear(); } } { // If this doesn't assert in TINYXML2_DEBUG, all is well. tinyxml2::XMLDocument doc; tinyxml2::XMLElement *pRoot = doc.NewElement("Root"); doc.DeleteNode(pRoot); } { XMLDocument doc; XMLElement* root = doc.NewElement( "Root" ); XMLTest( "Node document before insertion", true, &doc == root->GetDocument() ); doc.InsertEndChild( root ); XMLTest( "Node document after insertion", true, &doc == root->GetDocument() ); } { // If this doesn't assert in TINYXML2_DEBUG, all is well. XMLDocument doc; XMLElement* unlinkedRoot = doc.NewElement( "Root" ); XMLElement* linkedRoot = doc.NewElement( "Root" ); doc.InsertFirstChild( linkedRoot ); unlinkedRoot->GetDocument()->DeleteNode( linkedRoot ); unlinkedRoot->GetDocument()->DeleteNode( unlinkedRoot ); } { // Should not assert in TINYXML2_DEBUG XMLPrinter printer; } { // Issue 291. Should not crash const char* xml = "&#0</a>"; XMLDocument doc; doc.Parse( xml ); XMLTest( "Parse hex with closing tag", false, doc.Error() ); XMLPrinter printer; doc.Print( &printer ); } { // Issue 299. Can print elements that are not linked in. // Will crash if issue not fixed. XMLDocument doc; XMLElement* newElement = doc.NewElement( "printme" ); XMLPrinter printer; bool acceptResult = newElement->Accept( &printer ); XMLTest( "printme - Accept()", true, acceptResult ); // Delete the node to avoid possible memory leak report in debug output doc.DeleteNode( newElement ); } { // Issue 302. Clear errors from LoadFile/SaveFile XMLDocument doc; XMLTest( "Issue 302. Should be no error initially", "XML_SUCCESS", doc.ErrorName() ); doc.SaveFile( "./no/such/path/pretty.xml" ); XMLTest( "Issue 302. Fail to save", "XML_ERROR_FILE_COULD_NOT_BE_OPENED", doc.ErrorName() ); doc.SaveFile( "./resources/out/compact.xml", true ); XMLTest( "Issue 302. Subsequent success in saving", "XML_SUCCESS", doc.ErrorName() ); } { // If a document fails to load then subsequent // successful loads should clear the error XMLDocument doc; XMLTest( "Should be no error initially", false, doc.Error() ); doc.LoadFile( "resources/no-such-file.xml" ); XMLTest( "No such file - should fail", true, doc.Error() ); doc.LoadFile( "resources/dream.xml" ); XMLTest( "Error should be cleared", false, doc.Error() ); } { // Check that declarations are allowed only at beginning of document const char* xml0 = "<?xml version=\"1.0\" ?>" " <!-- xml version=\"1.1\" -->" "<first />"; const char* xml1 = "<?xml version=\"1.0\" ?>" "<?xml-stylesheet type=\"text/xsl\" href=\"Anything.xsl\"?>" "<first />"; const char* xml2 = "<first />" "<?xml version=\"1.0\" ?>"; const char* xml3 = "<first></first>" "<?xml version=\"1.0\" ?>"; const char* xml4 = "<first><?xml version=\"1.0\" ?></first>"; XMLDocument doc; doc.Parse(xml0); XMLTest("Test that the code changes do not affect normal parsing", false, doc.Error() ); doc.Parse(xml1); XMLTest("Test that the second declaration is allowed", false, doc.Error() ); doc.Parse(xml2); XMLTest("Test that declaration after self-closed child is not allowed", XML_ERROR_PARSING_DECLARATION, doc.ErrorID() ); doc.Parse(xml3); XMLTest("Test that declaration after a child is not allowed", XML_ERROR_PARSING_DECLARATION, doc.ErrorID() ); doc.Parse(xml4); XMLTest("Test that declaration inside a child is not allowed", XML_ERROR_PARSING_DECLARATION, doc.ErrorID() ); } { // No matter - before or after successfully parsing a text - // calling XMLDocument::Value() used to cause an assert in debug. // Null must be returned. const char* validXml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" "<first />" "<second />"; XMLDocument* doc = new XMLDocument(); XMLTest( "XMLDocument::Value() returns null?", NULL, doc->Value() ); doc->Parse( validXml ); XMLTest( "Parse to test XMLDocument::Value()", false, doc->Error()); XMLTest( "XMLDocument::Value() returns null?", NULL, doc->Value() ); delete doc; } { XMLDocument doc; for( int i = 0; i < XML_ERROR_COUNT; i++ ) { const XMLError error = static_cast<XMLError>(i); const char* name = XMLDocument::ErrorIDToName(error); XMLTest( "ErrorName() not null after ClearError()", true, name != 0 ); if( name == 0 ) { // passing null pointer into strlen() is undefined behavior, so // compiler is allowed to optimise away the null test above if it's // as reachable as the strlen() call continue; } XMLTest( "ErrorName() not empty after ClearError()", true, strlen(name) > 0 ); } } { const char* html("<!DOCTYPE html><html><body><p>test</p><p><br/></p></body></html>"); XMLDocument doc(false); doc.Parse(html); XMLPrinter printer(0, true); doc.Print(&printer); XMLTest(html, html, printer.CStr()); } { // Evil memory leaks. // If an XMLElement (etc) is allocated via NewElement() (etc.) // and NOT added to the XMLDocument, what happens? // // Previously (buggy): // The memory would be free'd when the XMLDocument is // destructed. But the XMLElement destructor wasn't called, so // memory allocated for the XMLElement text would not be free'd. // In practice this meant strings allocated for the XMLElement // text would be leaked. An edge case, but annoying. // Now: // The XMLElement destructor is called. But the unlinked nodes // have to be tracked using a list. This has a minor performance // impact that can become significant if you have a lot of // unlinked nodes. (But why would you do that?) // The only way to see this bug was in a Visual C++ runtime debug heap // leak tracker. This is compiled in by default on Windows Debug and // enabled with _CRTDBG_LEAK_CHECK_DF parameter passed to _CrtSetDbgFlag(). { XMLDocument doc; doc.NewElement("LEAK 1"); } { XMLDocument doc; XMLElement* ele = doc.NewElement("LEAK 2"); doc.DeleteNode(ele); } } { // Bad bad crash. Parsing error results in stack overflow, if uncaught. const char* TESTS[] = { "./resources/xmltest-5330.xml", "./resources/xmltest-4636783552757760.xml", "./resources/xmltest-5720541257269248.xml", 0 }; for (int i=0; TESTS[i]; ++i) { XMLDocument doc; doc.LoadFile(TESTS[i]); XMLTest("Stack overflow prevented.", XML_ELEMENT_DEPTH_EXCEEDED, doc.ErrorID()); } } { // Crashing reported via email. const char* xml = "<playlist id='playlist1'>" "<property name='track_name'>voice</property>" "<property name='audio_track'>1</property>" "<entry out = '604' producer = '4_playlist1' in = '0' />" "<blank length = '1' />" "<entry out = '1625' producer = '3_playlist' in = '0' />" "<blank length = '2' />" "<entry out = '946' producer = '2_playlist1' in = '0' />" "<blank length = '1' />" "<entry out = '128' producer = '1_playlist1' in = '0' />" "</playlist>"; // It's not a good idea to delete elements as you walk the // list. I'm not sure this technically should work; but it's // an interesting test case. XMLDocument doc; XMLError err = doc.Parse(xml); XMLTest("Crash bug parsing", XML_SUCCESS, err ); XMLElement* playlist = doc.FirstChildElement("playlist"); XMLTest("Crash bug parsing", true, playlist != 0); { const char* elementName = "entry"; XMLElement* entry = playlist->FirstChildElement(elementName); XMLTest("Crash bug parsing", true, entry != 0); while (entry) { XMLElement* todelete = entry; entry = entry->NextSiblingElement(elementName); playlist->DeleteChild(todelete); } entry = playlist->FirstChildElement(elementName); XMLTest("Crash bug parsing", true, entry == 0); } { const char* elementName = "blank"; XMLElement* blank = playlist->FirstChildElement(elementName); XMLTest("Crash bug parsing", true, blank != 0); while (blank) { XMLElement* todelete = blank; blank = blank->NextSiblingElement(elementName); playlist->DeleteChild(todelete); } XMLTest("Crash bug parsing", true, blank == 0); } tinyxml2::XMLPrinter printer; const bool acceptResult = playlist->Accept(&printer); XMLTest("Crash bug parsing - Accept()", true, acceptResult); printf("%s\n", printer.CStr()); // No test; it only need to not crash. // Still, wrap it up with a sanity check int nProperty = 0; for (const XMLElement* p = playlist->FirstChildElement("property"); p; p = p->NextSiblingElement("property")) { nProperty++; } XMLTest("Crash bug parsing", 2, nProperty); } // ----------- Line Number Tracking -------------- { struct TestUtil: XMLVisitor { TestUtil() : str() {} void TestParseError(const char *testString, const char *docStr, XMLError expected_error, int expectedLine) { XMLDocument doc; const XMLError parseError = doc.Parse(docStr); XMLTest(testString, parseError, doc.ErrorID()); XMLTest(testString, true, doc.Error()); XMLTest(testString, expected_error, parseError); XMLTest(testString, expectedLine, doc.ErrorLineNum()); }; void TestStringLines(const char *testString, const char *docStr, const char *expectedLines) { XMLDocument doc; doc.Parse(docStr); XMLTest(testString, false, doc.Error()); TestDocLines(testString, doc, expectedLines); } void TestFileLines(const char *testString, const char *file_name, const char *expectedLines) { XMLDocument doc; doc.LoadFile(file_name); XMLTest(testString, false, doc.Error()); TestDocLines(testString, doc, expectedLines); } private: DynArray<char, 10> str; void Push(char type, int lineNum) { str.Push(type); str.Push(char('0' + (lineNum / 10))); str.Push(char('0' + (lineNum % 10))); } bool VisitEnter(const XMLDocument& doc) { Push('D', doc.GetLineNum()); return true; } bool VisitEnter(const XMLElement& element, const XMLAttribute* firstAttribute) { Push('E', element.GetLineNum()); for (const XMLAttribute *attr = firstAttribute; attr != 0; attr = attr->Next()) Push('A', attr->GetLineNum()); return true; } bool Visit(const XMLDeclaration& declaration) { Push('L', declaration.GetLineNum()); return true; } bool Visit(const XMLText& text) { Push('T', text.GetLineNum()); return true; } bool Visit(const XMLComment& comment) { Push('C', comment.GetLineNum()); return true; } bool Visit(const XMLUnknown& unknown) { Push('U', unknown.GetLineNum()); return true; } void TestDocLines(const char *testString, XMLDocument &doc, const char *expectedLines) { str.Clear(); const bool acceptResult = doc.Accept(this); XMLTest(testString, true, acceptResult); str.Push(0); XMLTest(testString, expectedLines, str.Mem()); } } tester; tester.TestParseError("ErrorLine-Parsing", "\n<root>\n foo \n<unclosed/>", XML_ERROR_PARSING, 2); tester.TestParseError("ErrorLine-Declaration", "<root>\n<?xml version=\"1.0\"?>", XML_ERROR_PARSING_DECLARATION, 2); tester.TestParseError("ErrorLine-Mismatch", "\n<root>\n</mismatch>", XML_ERROR_MISMATCHED_ELEMENT, 2); tester.TestParseError("ErrorLine-CData", "\n<root><![CDATA[ \n foo bar \n", XML_ERROR_PARSING_CDATA, 2); tester.TestParseError("ErrorLine-Text", "\n<root>\n foo bar \n", XML_ERROR_PARSING_TEXT, 3); tester.TestParseError("ErrorLine-Comment", "\n<root>\n<!-- >\n", XML_ERROR_PARSING_COMMENT, 3); tester.TestParseError("ErrorLine-Declaration", "\n<root>\n<? >\n", XML_ERROR_PARSING_DECLARATION, 3); tester.TestParseError("ErrorLine-Unknown", "\n<root>\n<! \n", XML_ERROR_PARSING_UNKNOWN, 3); tester.TestParseError("ErrorLine-Element", "\n<root>\n<unclosed \n", XML_ERROR_PARSING_ELEMENT, 3); tester.TestParseError("ErrorLine-Attribute", "\n<root>\n<unclosed \n att\n", XML_ERROR_PARSING_ATTRIBUTE, 4); tester.TestParseError("ErrorLine-ElementClose", "\n<root>\n<unclosed \n/unexpected", XML_ERROR_PARSING_ELEMENT, 3); tester.TestStringLines( "LineNumbers-String", "<?xml version=\"1.0\"?>\n" // 1 Doc, DecL "<root a='b' \n" // 2 Element Attribute "c='d'> d <blah/> \n" // 3 Attribute Text Element "newline in text \n" // 4 Text "and second <zxcv/><![CDATA[\n" // 5 Element Text " cdata test ]]><!-- comment -->\n" // 6 Comment "<! unknown></root>", // 7 Unknown "D01L01E02A02A03T03E03T04E05T05C06U07"); tester.TestStringLines( "LineNumbers-CRLF", "\r\n" // 1 Doc (arguably should be line 2) "<?xml version=\"1.0\"?>\n" // 2 DecL "<root>\r\n" // 3 Element "\n" // 4 "text contining new line \n" // 5 Text " and also containing crlf \r\n" // 6 "<sub><![CDATA[\n" // 7 Element Text "cdata containing new line \n" // 8 " and also containing cflr\r\n" // 9 "]]></sub><sub2/></root>", // 10 Element "D01L02E03T05E07T07E10"); tester.TestFileLines( "LineNumbers-File", "resources/utf8test.xml", "D01L01E02E03A03A03T03E04A04A04T04E05A05A05T05E06A06A06T06E07A07A07T07E08A08A08T08E09T09E10T10"); } { const char* xml = "<Hello>Text</Error>"; XMLDocument doc; doc.Parse(xml); XMLTest("Test mismatched elements.", true, doc.Error()); XMLTest("Test mismatched elements.", XML_ERROR_MISMATCHED_ELEMENT, doc.ErrorID()); // For now just make sure calls work & doesn't crash. // May solidify the error output in the future. printf("%s\n", doc.ErrorStr()); doc.PrintError(); } // ----------- Performance tracking -------------- { #if defined( _MSC_VER ) __int64 start, end, freq; QueryPerformanceFrequency((LARGE_INTEGER*)&freq); #endif FILE* perfFP = fopen("resources/dream.xml", "r"); XMLTest("Open dream.xml", true, perfFP != 0); fseek(perfFP, 0, SEEK_END); long size = ftell(perfFP); fseek(perfFP, 0, SEEK_SET); char* mem = new char[size + 1]; memset(mem, 0xfe, size); size_t bytesRead = fread(mem, 1, size, perfFP); XMLTest("Read dream.xml", true, uint32_t(size) >= uint32_t(bytesRead)); fclose(perfFP); mem[size] = 0; #if defined( _MSC_VER ) QueryPerformanceCounter((LARGE_INTEGER*)&start); #else clock_t cstart = clock(); #endif bool parseDreamXmlFailed = false; static const int COUNT = 10; for (int i = 0; i < COUNT; ++i) { XMLDocument doc; doc.Parse(mem); parseDreamXmlFailed = parseDreamXmlFailed || doc.Error(); } #if defined( _MSC_VER ) QueryPerformanceCounter((LARGE_INTEGER*)&end); #else clock_t cend = clock(); #endif XMLTest( "Parse dream.xml", false, parseDreamXmlFailed ); delete[] mem; static const char* note = #ifdef TINYXML2_DEBUG "DEBUG"; #else "Release"; #endif #if defined( _MSC_VER ) const double duration = 1000.0 * (double)(end - start) / ((double)freq * (double)COUNT); #else const double duration = (double)(cend - cstart) / (double)COUNT; #endif printf("\nParsing dream.xml (%s): %.3f milli-seconds\n", note, duration); } #if defined( _MSC_VER ) && defined( TINYXML2_DEBUG ) { _CrtMemCheckpoint( &endMemState ); _CrtMemState diffMemState; _CrtMemDifference( &diffMemState, &startMemState, &endMemState ); _CrtMemDumpStatistics( &diffMemState ); { int leaksBeforeExit = _CrtDumpMemoryLeaks(); XMLTest( "No leaks before exit?", FALSE, leaksBeforeExit ); } } #endif printf ("\nPass %d, Fail %d\n", gPass, gFail); return gFail; }
[ "42669863+HenrikSte@users.noreply.github.com" ]
42669863+HenrikSte@users.noreply.github.com
0a60922bd0bcfdfec8d29c63173d454de64bdec3
be55b78c5ec4d90b5c9f91122a64ab486d615814
/qt/KDSqlDatabaseTransaction/KDSqlDatabaseTransaction.h
2292770f644a2a67599c083032c47a1f020e06df
[ "MIT", "LicenseRef-scancode-generic-cla" ]
permissive
elProxy/KDToolBox
4f2724b44622e5ca090115409fe81f9fd2afb448
bd538894347d8630458dccce054ac7f698cd1c16
refs/heads/master
2023-08-12T15:12:29.230802
2021-09-21T12:09:11
2021-09-21T12:46:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,418
h
/**************************************************************************** ** MIT License ** ** Copyright (C) 2019-2021 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com ** ** This file is part of KDToolBox (https://github.com/KDAB/KDToolBox). ** ** 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 (including the next paragraph) ** 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. ****************************************************************************/ #ifndef KDTOOLBOX_KDSQLDATABASETRANSACTION_H #define KDTOOLBOX_KDSQLDATABASETRANSACTION_H #include <QSqlDatabase> #include <QSqlDriver> #include <QLoggingCategory> #include <QtDebug> namespace KDToolBox { namespace Private { // `inline` logging category; Qt doesn't support them. inline const QLoggingCategory &kdsqllc() { static const QLoggingCategory category("KDToolBox.KDSqlDatabaseTransaction", QtWarningMsg); return category; } } // namespace Private class Q_REQUIRED_RESULT KDSqlDatabaseTransaction { Q_DISABLE_COPY(KDSqlDatabaseTransaction) public: /*! * \brief Begins a new transaction. The transaction will be * committed when commit() is called (and returns true), otherwise * it will be automatically rolled back. * * \param database is the database connection to use. The connection * must be opened before use. */ explicit KDSqlDatabaseTransaction(const QSqlDatabase &database = QSqlDatabase::database()) : m_db(database) , m_shouldRollback(true) { if (!m_db.isOpen()) { qCWarning(Private::kdsqllc) << "The database" << m_db << "is not open"; m_shouldRollback = false; } else if (!m_db.driver()->hasFeature(QSqlDriver::Transactions)) { qCWarning(Private::kdsqllc) << "The database" << m_db << "does not support transactions"; m_shouldRollback = false; } else if (!m_db.transaction()) { qCWarning(Private::kdsqllc) << "Could not begin a new transaction"; m_shouldRollback = false; } } /*! * \brief Destroys the transaction object. If it has not been committed * by calling commit(), the transaction will be rolled back. */ ~KDSqlDatabaseTransaction() { if (m_shouldRollback) { m_db.rollback(); } } KDSqlDatabaseTransaction(KDSqlDatabaseTransaction &&other) noexcept : m_db(std::move(other.m_db)) , m_shouldRollback(std::exchange(other.m_shouldRollback, false)) {} KDSqlDatabaseTransaction &operator=(KDSqlDatabaseTransaction &&other) noexcept { KDSqlDatabaseTransaction moved(std::move(other)); swap(moved); return *this; } void swap(KDSqlDatabaseTransaction &other) noexcept { qSwap(m_db, other.m_db); qSwap(m_shouldRollback, other.m_shouldRollback); } /*! * \brief Commits the transaction. If the commit fails, the * KDSqlDatabaseTransaction object will roll back the transaction * when it gets destroyed. * * \return True if committing succeeded, false if it failed. */ bool commit() { if (!m_shouldRollback) { qCWarning(Private::kdsqllc) << "commit() / rollback() already called on this object"; return false; } const bool result = m_db.commit(); if (result) { m_shouldRollback = false; } return result; } /*! * \brief Rolls back the transaction. If the rollback fails, the * KDSqlDatabaseTransaction object will NOT roll back the transaction * again when it gets destroyed. * * \return True if rollback succeeded, false if it failed. */ bool rollback() { if (!m_shouldRollback) { qCWarning(Private::kdsqllc) << "commit() / rollback() already called on this object"; return false; } // in case rollback fails, what can we do? should we try again? m_shouldRollback = false; return m_db.rollback(); } /*! * \brief Returns the database connection used by this object. * \return The database connection. */ const QSqlDatabase &database() const { return m_db; } private: QSqlDatabase m_db; bool m_shouldRollback; }; } // namespace KDToolBox #endif // KDTOOLBOX_KDSQLDATABASETRANSACTION_H
[ "giuseppe.dangelo@kdab.com" ]
giuseppe.dangelo@kdab.com
6210f2879a4d4383f0f096def96cffbd2cdf9310
84ebd7388dba35d4b0f5819c3e2ffc1522f1ad8a
/093_tests_binsrch/function.h
ab0d5cf4fdfe7a864409b2e6cb0647b7a59ce7d2
[]
no_license
cankiki/ECE551
32eb75148b041c7d290b9bccdb64d55929ddd7aa
cee873e2c091d7ff32afb05565fc156c8f1c627e
refs/heads/master
2020-04-16T21:19:37.460085
2019-01-16T20:07:20
2019-01-16T20:07:20
165,921,227
0
1
null
null
null
null
UTF-8
C++
false
false
171
h
#ifndef __FUNCTION_H__ #define __FUNCTION_H__ template<typename R, typename A> class Function { public: virtual R invoke(A arg) = 0; virtual ~Function() {} }; #endif
[ "noreply@github.com" ]
cankiki.noreply@github.com
6dbeb85c6cbb815057d90f4762f5565a3c34d33d
357607a0cf01d44ecf97feaf047f7a9bad9a0be5
/13.前端project/0.4/src/mappoint.cpp
d6fb1358264c7da9cde9b818178ba23330ce6031
[ "DOC", "GPL-3.0-or-later", "MIT" ]
permissive
sunnieeee/VSLAM
7699602cd2a8b3086660352fa9158d81c19badc7
a0f58b7990f0706ff569481aadac81bb227f3332
refs/heads/master
2020-03-28T21:23:07.158817
2018-11-20T14:58:03
2018-11-20T14:58:03
149,150,830
0
0
MIT
2018-09-17T15:56:51
2018-09-17T15:56:51
null
UTF-8
C++
false
false
1,783
cpp
/*================================================================================= * Copyleft! 2018 William Yu * Some rights reserved:CC(creativecommons.org)BY-NC-SA * Copyleft! 2018 William Yu * 版权部分所有,遵循CC(creativecommons.org)BY-NC-SA协议授权方式使用 * * Filename : * Description : 视觉SLAM十四讲 学习记录 * Reference : * Programmer(s) : William Yu, windmillyucong@163.com * Company : HUST, DMET国家重点实验室FOCUS团队 * Modification History : ver1.0, 2018.04.26, William Yu * ver1.1, 2018.05.12, William Yu, add notes =================================================================================*/ #include "myslam/common_include.h" #include "myslam/mappoint.h" namespace myslam { MapPoint::MapPoint() : id_(-1), pos_(Vector3d(0,0,0)), norm_(Vector3d(0,0,0)), good_(true), visible_times_(0), matched_times_(0) { } MapPoint::MapPoint ( long unsigned int id, const Vector3d& position, const Vector3d& norm, Frame* frame, const Mat& descriptor ) : id_(id), pos_(position), norm_(norm), good_(true), visible_times_(1), matched_times_(1), descriptor_(descriptor) { observed_frames_.push_back(frame); } MapPoint::Ptr MapPoint::createMapPoint() { return MapPoint::Ptr( new MapPoint( factory_id_++, Vector3d(0,0,0), Vector3d(0,0,0) ) ); } MapPoint::Ptr MapPoint::createMapPoint ( const Vector3d& pos_world, const Vector3d& norm, const Mat& descriptor, Frame* frame ) { return MapPoint::Ptr( new MapPoint( factory_id_++, pos_world, norm, frame, descriptor ) ); } unsigned long MapPoint::factory_id_ = 0; }
[ "windmillyucong@163.com" ]
windmillyucong@163.com
fcc9c4f520dcc229424922457c47f4b903d32419
f95c500f5bd6e8d283e47a9a7ca383c6ed7566d7
/src/fingerprint_probe.h
842ba56e7db8478c06ef4ef81b9aea3965404f44
[]
no_license
smrt28/sonoff-s26-blynk-firmware
ebd201f37b73bd0b4c7ce5e8bea6f67b4dc3fb19
ef79bc1e92f79882c6c41fdf087cf7231c0130b8
refs/heads/master
2023-04-04T08:33:22.005740
2021-03-12T18:27:30
2021-03-12T18:27:30
347,151,941
0
0
null
null
null
null
UTF-8
C++
false
false
255
h
#ifndef fingerprint_probe_h #define fingerprint_probe_h namespace s28 { struct Fingerprint { uint8_t raw[20]; String to_string(); }; int probe(const String &host, int port, Fingerprint *fp); } // namespace s28 #endif /* fingerprint_probe_h */
[ "oholecek@purestorage.com" ]
oholecek@purestorage.com
e210164bee6230dfd20869bcf763adc0c4befc37
f158527ea88ebc7b2b8221d3d3dac4fd687e8a86
/AVS/avs.cpp
3dae24d42514784db8c19aca9c73848eee3a0613
[]
no_license
zlvb/dshowsample
7b2487f41bcce19e960546b8334ba39bec082e52
7ad79396b782dd10f5bf5c18dfecd537076b86a1
refs/heads/master
2021-01-20T23:23:57.105398
2015-07-25T00:44:09
2015-07-25T00:44:09
32,433,973
1
2
null
null
null
null
UTF-8
C++
false
false
10,290
cpp
#pragma warning(disable: 4819) #include "avs.h" namespace AVS{ Manager::Manager() :m_Graph(NULL) ,m_MediaControl(NULL) ,m_Event(NULL) ,m_BasicVideo(NULL) ,m_BasicAudio(NULL) ,m_VideoWindow(NULL) ,m_Seeking(NULL) ,m_ObjectTableEntry(0) { } Manager::~Manager() { Close(); } BOOL Manager::Create(void) { if (!m_Graph) { if (SUCCEEDED(CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER, IID_IGraphBuilder, (void **)&m_Graph))) { AddToObjectTable(); return QueryInterfaces(); } m_Graph = 0; } return FALSE; } BOOL Manager::QueryInterfaces(void) { if (m_Graph) { HRESULT hr = NOERROR; hr |= m_Graph->QueryInterface(IID_IMediaControl, (void **)&m_MediaControl); hr |= m_Graph->QueryInterface(IID_IMediaEventEx, (void **)&m_Event); hr |= m_Graph->QueryInterface(IID_IBasicVideo, (void **)&m_BasicVideo); hr |= m_Graph->QueryInterface(IID_IBasicAudio, (void **)&m_BasicAudio); hr |= m_Graph->QueryInterface(IID_IVideoWindow, (void **)&m_VideoWindow); hr |= m_Graph->QueryInterface(IID_IMediaSeeking, (void **)&m_Seeking); if (m_Seeking) { m_Seeking->SetTimeFormat(&TIME_FORMAT_MEDIA_TIME); } return SUCCEEDED(hr); } return FALSE; } void Manager::Close(void) { if (m_Seeking) { m_Seeking->Release(); m_Seeking = NULL; } if (m_MediaControl) { m_MediaControl->Release(); m_MediaControl = NULL; } if (m_Event) { m_Event->Release(); m_Event = NULL; } if (m_BasicVideo) { m_BasicVideo->Release(); m_BasicVideo = NULL; } if (m_BasicAudio) { m_BasicAudio->Release(); m_BasicAudio = NULL; } if (m_VideoWindow) { m_VideoWindow->put_Visible(OAFALSE); m_VideoWindow->put_MessageDrain((OAHWND)NULL); m_VideoWindow->put_Owner(OAHWND(0)); m_VideoWindow->Release(); m_VideoWindow = NULL; } RemoveFromObjectTable(); if (m_Graph) { m_Graph->Release(); m_Graph = NULL; } } BOOL Manager::Attach(IGraphBuilder * inGraphBuilder) { Close(); if (inGraphBuilder) { inGraphBuilder->AddRef(); m_Graph = inGraphBuilder; AddToObjectTable(); return QueryInterfaces(); } return TRUE; } IGraphBuilder * Manager::GetGraph(void) { return m_Graph; } IMediaEventEx * Manager::GetEventHandle(void) { return m_Event; } BOOL Manager::ConnectFilters(IPin * inOutputPin, IPin * inInputPin, const AM_MEDIA_TYPE * inMediaType) { if (m_Graph && inOutputPin && inInputPin) { HRESULT hr = m_Graph->ConnectDirect(inOutputPin, inInputPin, inMediaType); return SUCCEEDED(hr) ? TRUE : FALSE; } return FALSE; } void Manager::DisconnectFilters(IPin * inOutputPin) { if (m_Graph && inOutputPin) { HRESULT hr = m_Graph->Disconnect(inOutputPin); } } BOOL Manager::SetDisplayWindow() { if (m_VideoWindow) { m_VideoWindow->put_Visible(OAFALSE); m_VideoWindow->put_Owner((OAHWND)m_Window); RECT windowRect; ::GetClientRect(m_Window, &windowRect); m_VideoWindow->put_Left(0); m_VideoWindow->put_Top(0); m_VideoWindow->put_Width(windowRect.right - windowRect.left); m_VideoWindow->put_Height(windowRect.bottom - windowRect.top); m_VideoWindow->put_WindowStyle(WS_CHILD|WS_CLIPCHILDREN|WS_CLIPSIBLINGS); m_VideoWindow->put_MessageDrain((OAHWND) m_Window); if (m_Window != NULL) { m_VideoWindow->put_Visible(OATRUE); } else { m_VideoWindow->put_Visible(OAFALSE); } return TRUE; } return FALSE; } BOOL Manager::ResizeVideoWindow(long inLeft, long inTop, long inWidth, long inHeight) { if (m_VideoWindow) { long lVisible = OATRUE; m_VideoWindow->get_Visible(&lVisible); m_VideoWindow->put_Visible(OAFALSE); m_VideoWindow->put_Left(inLeft); m_VideoWindow->put_Top(inTop); m_VideoWindow->put_Width(inWidth); m_VideoWindow->put_Height(inHeight); m_VideoWindow->put_Visible(lVisible); return TRUE; } return FALSE; } BOOL Manager::SetNotifyWindow() { if (m_Event) { m_Event->SetNotifyWindow((OAHWND)m_Window, WM_GRAPHNOTIFY, 0); return TRUE; } return FALSE; } void Manager::HandleEvent(WPARAM inWParam, LPARAM inLParam) { if (m_Event) { LONG eventCode = 0, eventParam1 = 0, eventParam2 = 0; while (SUCCEEDED(m_Event->GetEvent(&eventCode, &eventParam1, &eventParam2, 0))) { m_Event->FreeEventParams(eventCode, eventParam1, eventParam2); switch (eventCode) { case EC_COMPLETE: break; case EC_USERABORT: case EC_ERRORABORT: break; default: break; } } } } BOOL Manager::Play(void) { if (m_Graph && m_MediaControl) { if (!IsPlaying()) { if (SUCCEEDED(m_MediaControl->Run())) { return TRUE; } } else { return TRUE; } } return FALSE; } BOOL Manager::Stop(void) { if (m_Graph && m_MediaControl) { if (!IsStopped()) { if (SUCCEEDED(m_MediaControl->Stop())) { return TRUE; } } else { return TRUE; } } return FALSE; } BOOL Manager::Pause(void) { if (m_Graph && m_MediaControl) { if (!IsPaused()) { if (SUCCEEDED(m_MediaControl->Pause())) { return TRUE; } } else { return TRUE; } } return FALSE; } BOOL Manager::IsPlaying(void) { if (m_Graph && m_MediaControl) { OAFilterState state = State_Stopped; if (SUCCEEDED(m_MediaControl->GetState(10, &state))) { return state == State_Running; } } return FALSE; } BOOL Manager::IsStopped(void) { if (m_Graph && m_MediaControl) { OAFilterState state = State_Stopped; if (SUCCEEDED(m_MediaControl->GetState(10, &state))) { return state == State_Stopped; } } return FALSE; } BOOL Manager::IsPaused(void) { if (m_Graph && m_MediaControl) { OAFilterState state = State_Stopped; if (SUCCEEDED(m_MediaControl->GetState(10, &state))) { return state == State_Paused; } } return FALSE; } BOOL Manager::SetFullScreen(BOOL inEnabled) { if (m_VideoWindow) { HRESULT hr = m_VideoWindow->put_FullScreenMode(inEnabled ? OATRUE : OAFALSE); return SUCCEEDED(hr); } return FALSE; } BOOL Manager::isFullScreen(void) { if (m_VideoWindow) { long fullScreenMode = OAFALSE; m_VideoWindow->get_FullScreenMode(&fullScreenMode); return (fullScreenMode == OATRUE); } return FALSE; } BOOL Manager::GetCurrentPosition(double * outPosition) { if (m_Seeking) { __int64 position = 0; if (SUCCEEDED(m_Seeking->GetCurrentPosition(&position))) { *outPosition = ((double)position) / 10000000.; return TRUE; } } return FALSE; } BOOL Manager::GetStopPosition(double * outPosition) { if (m_Seeking) { __int64 position = 0; if (SUCCEEDED(m_Seeking->GetStopPosition(&position))) { *outPosition = ((double)position) / 10000000.; return TRUE; } } return FALSE; } BOOL Manager::SetCurrentPosition(double inPosition) { if (m_Seeking) { __int64 one = 10000000; __int64 position = (__int64)(one * inPosition); HRESULT hr = m_Seeking->SetPositions(&position, AM_SEEKING_AbsolutePositioning | AM_SEEKING_SeekToKeyFrame, 0, AM_SEEKING_NoPositioning); return SUCCEEDED(hr); } return FALSE; } BOOL Manager::SetStartStopPosition(double inStart, double inStop) { if (m_Seeking) { __int64 one = 10000000; __int64 startPos = (__int64)(one * inStart); __int64 stopPos = (__int64)(one * inStop); HRESULT hr = m_Seeking->SetPositions(&startPos, AM_SEEKING_AbsolutePositioning | AM_SEEKING_SeekToKeyFrame, &stopPos, AM_SEEKING_AbsolutePositioning | AM_SEEKING_SeekToKeyFrame); return SUCCEEDED(hr); } return FALSE; } BOOL Manager::GetDuration(double * outDuration) { if (m_Seeking) { __int64 length = 0; if (SUCCEEDED(m_Seeking->GetDuration(&length))) { *outDuration = ((double)length) / 10000000.; return TRUE; } } return FALSE; } BOOL Manager::SetPlaybackRate(double inRate) { if (m_Seeking) { if (SUCCEEDED(m_Seeking->SetRate(inRate))) { return TRUE; } } return FALSE; } BOOL Manager::SetAudioVolume(long inVolume) { if (m_BasicAudio) { HRESULT hr = m_BasicAudio->put_Volume(inVolume); return SUCCEEDED(hr); } return FALSE; } long Manager::GetAudioVolume(void) { long volume = 0; if (m_BasicAudio) { m_BasicAudio->get_Volume(&volume); } return volume; } BOOL Manager::SetAudioBalance(long inBalance) { if (m_BasicAudio) { HRESULT hr = m_BasicAudio->put_Balance(inBalance); return SUCCEEDED(hr); } return FALSE; } long Manager::GetAudioBalance(void) { long balance = 0; if (m_BasicAudio) { m_BasicAudio->get_Balance(&balance); } return balance; } BOOL Manager::OpenMedia(const char * inFile) { strcpy(filename,inFile); Create (); if (m_Graph) { WCHAR szFilePath[MAX_PATH]; MultiByteToWideChar(CP_ACP, 0, inFile, -1, szFilePath, MAX_PATH); if (SUCCEEDED(m_Graph->RenderFile(szFilePath, NULL))) { SetDisplayWindow (); SetNotifyWindow (); return TRUE; } } return FALSE; } char* Manager::GetFileName(char* outFileName) { strcpy(outFileName,filename); return outFileName; } void Manager::ReOpen() { Stop(); Close(); Create(); OpenMedia (filename); } void Manager::AddToObjectTable(void) { IMoniker * pMoniker = 0; IRunningObjectTable * objectTable = 0; if (SUCCEEDED(GetRunningObjectTable(0, &objectTable))) { WCHAR wsz[256]; wsprintfW(wsz, L"FilterGraph %08p pid %08x", (DWORD_PTR)m_Graph, GetCurrentProcessId()); HRESULT hr = CreateItemMoniker(L"!", wsz, &pMoniker); if (SUCCEEDED(hr)) { hr = objectTable->Register(0, m_Graph, pMoniker, &m_ObjectTableEntry); pMoniker->Release(); } objectTable->Release(); } } void Manager::RemoveFromObjectTable(void) { IRunningObjectTable * objectTable = 0; if (SUCCEEDED(GetRunningObjectTable(0, &objectTable))) { objectTable->Revoke(m_ObjectTableEntry); objectTable->Release(); m_ObjectTableEntry = 0; } } void Manager::RePlay () { ReOpen (); Play (); } }
[ "zlvbvbzl@b1507354-4840-11de-ba0e-b5da6ac7b600" ]
zlvbvbzl@b1507354-4840-11de-ba0e-b5da6ac7b600
1a2455d8e4df4bbaf4f1af510257967471a5c424
1dbb60db92072801e3e7eaf6645ef776e2a26b29
/server/src/common/resource/r_formationindexdata.h
637902efac43243d2c1d58ea7bb92c905da1a163
[]
no_license
atom-chen/phone-code
5a05472fcf2852d1943ad869b37603a4901749d5
c0c0f112c9a2570cc0390703b1bff56d67508e89
refs/heads/master
2020-07-05T01:15:00.585018
2015-06-17T08:52:21
2015-06-17T08:52:21
202,480,234
0
1
null
2019-08-15T05:36:11
2019-08-15T05:36:09
null
UTF-8
C++
false
false
739
h
#ifndef IMMORTAL_COMMON_RESOURCE_R_FORMATIONINDEXDATA_H_ #define IMMORTAL_COMMON_RESOURCE_R_FORMATIONINDEXDATA_H_ #include "proto/common.h" #include "r_basedata.h" #include "resource.h" class CFormationIndexData : public CBaseData { public: struct SData { uint32 index; uint32 level; }; typedef std::map<uint32, SData*> UInt32FormationIndexMap; CFormationIndexData(); virtual ~CFormationIndexData(); virtual void LoadData(void); void ClearData(void); SData * Find( uint32 index ); protected: UInt32FormationIndexMap id_formationindex_map; void Add(SData* formationindex); }; #endif //IMMORTAL_COMMON_RESOURCE_R_FORMATIONINDEXMGR_H_
[ "757690733@qq.com" ]
757690733@qq.com
c869ca02eac219044f6b47c6d82bc3f3a8f7aaf8
c7ad1dd84604e275ebfc5a7e354b23ceb598fca5
/include/algo/structure/cd_utils/cuDmAlignedOptimalScore.hpp
7583c980a69d05e87f5065eb9ba2eb8674f513bd
[]
no_license
svn2github/ncbi_tk
fc8cfcb75dfd79840e420162a8ae867826a3d922
c9580988f9e5f7c770316163adbec8b7a40f89ca
refs/heads/master
2023-09-03T12:30:52.531638
2017-05-15T14:17:27
2017-05-15T14:17:27
60,197,012
1
1
null
null
null
null
UTF-8
C++
false
false
3,462
hpp
#ifndef CU_DM_ALIGNED_OPTIMAL_SCORE__HPP #define CU_DM_ALIGNED_OPTIMAL_SCORE__HPP /* $Id$ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Author: Chris Lanczycki * * File Description: cdt_dm_alignedscore.hpp * * Concrete distance matrix class. * Distance is computed based on a scoring matrix, where the * score is based on an existing alignment in a CD. A pair of parameters * to extend an alignment at the N-terminal and C-terminal end can be specified. * Different substitution matrices can be defined (see * cdt_scoring_matrices.hpp for the supported scoring matrices). * */ #include <algo/structure/cd_utils/cuDistmat.hpp> #include <algo/structure/cd_utils/cuAlignedDM.hpp> #include <algo/structure/cd_utils/cuBlockExtender.hpp> BEGIN_NCBI_SCOPE USING_SCOPE(objects); BEGIN_SCOPE(cd_utils) // The pairwise score between two rows in an alignment is the sum over the // scores of each pair of aligned residues: // // d[i][j] = max_Score_for_CD - sum(k)( scoring_matrix(i_k, j_k)) // // where x_k is the kth aligned residue of row x. The offset is to make // high scores map to short distances. Although note that each row will // in general have a different score for an exact match, making d=0 ambiguous. class NCBI_CDUTILS_EXPORT DMAlignedOptimalScore : public AlignedDM { static const EDistMethod DIST_METHOD; public: DMAlignedOptimalScore(EScoreMatrixType type = GLOBAL_DEFAULT_SCORE_MATRIX); void setBlockExtender(BlockExtender* be); virtual bool ComputeMatrix(pProgressFunction pFunc); virtual ~DMAlignedOptimalScore(); private: //the pair of block and sequence index /* moved to algBlockExtender.hpp typedef pair<Block, int> ScoringTerm; double scoreBlockPair(const ScoringTerm& term1, const ScoringTerm& term, int** ppScores); bool getScoringTerm(int row, int blockNum, int nExt, int cExt, ScoringTerm& st); double optimizeBlockScore(int row1, int row2, int block, int** ppScores); double scoreOneRowPair(int row1, int row2, int** ppScores); */ void convertScoreToDistance(); void initDMAlignedScore(EScoreMatrixType type, int nTermExt, int cTermExt); BlockExtender* m_blockExtender; }; END_SCOPE(cd_utils) END_NCBI_SCOPE #endif /* CU_DM_ALIGNED_OPTIMAL_SCORE__HPP */
[ "lanczyck@112efe8e-fc92-43c6-89b6-d25c299ce97b" ]
lanczyck@112efe8e-fc92-43c6-89b6-d25c299ce97b
4664d785530742c4226e58f7449a49cdd6c9bf61
7ad169f5931978189f640f3881f89d70e94363d6
/Fecha.h
73a9853d0dc330a06426254d558a3e965cde5071
[]
no_license
martnreh/Cplusplus-SellShoesStock
b6052c029401572d8c3d50030e630b1667f939ef
2837f66afbdfb956ee4731261372bb5bcde4caa1
refs/heads/main
2023-06-04T19:04:58.161946
2021-06-19T04:53:07
2021-06-19T04:53:07
378,324,693
0
0
null
null
null
null
UTF-8
C++
false
false
1,374
h
#ifndef Fecha_h #define Fecha_h #include <sstream> #include <iostream> //Programado por Adrián Martin class Fecha { // publico public: // constructor default Fecha(); // constructor con parámetros Fecha(int dd, int mm, int aa); // métodos de acceso para todos los atributos int getDia(); int getMes(); int getAno(); // métodos de modificación para todos los atributos void setDia(int dd); void setMes(int mm); void setAno(int aa); //método para obtener en formato fecha string getFecha(); // privado private: // atributos dia mes y año int dia; int mes; int ano; }; // implementa los métodos //constructor default Fecha::Fecha() { dia = 0; mes = 0; ano = 0; } //constructor con parámetros Fecha::Fecha(int dd, int mm, int aa) { dia = dd; mes = mm; ano = aa; } //métodos de acceso int Fecha::getDia() { return dia; } int Fecha::getMes() { return mes; } int Fecha::getAno() { return ano; } string Fecha::getFecha() { stringstream fechaI; fechaI << dia << "/" << mes << "/" << ano; string fechaF = fechaI.str(); return fechaF; } //métodos de modificación void Fecha::setDia(int dd) { dia = dd; } void Fecha::setMes(int mm) { mes = mm; } void Fecha::setAno(int aa) { ano = aa; } #endif /* Fraccion_h_h */
[ "noreply@github.com" ]
martnreh.noreply@github.com
d7be4930565f94d62d0256f8a356d961075ad3f9
68b763fe498c4572e39155926a7fdd97e4b06389
/cpp/data_structure/self_implemented/hashtable/hashtable.cpp
365ae9dce50a1e815c74d46ec27031a2ea758a4b
[]
no_license
alfchung/coding_practice
64eff671fc6a4c73e4bf47916526791413dd1357
24c0e270b780145f42199ddf324085d3b55e3970
refs/heads/master
2021-01-18T17:28:00.550167
2013-01-19T03:28:49
2013-01-19T03:28:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,162
cpp
/* * keys are unique */ #include<stdlib.h> #include<stdint.h> #include<math.h> #include<iostream> #include<string> #include<map> #include<vector> #include<typeinfo> using namespace std; const int default_table_size = 277; const int error_exit_wrong_key_type = -1; const int put_status_insert_new = 0; const int put_status_insert_overwritten = 1; const int put_status_insert_fail = -1; const int get_not_found = -1; const int get_found = 0; template <class Key, class Value> class record { public: Key key; Value value; record* next; bool empty; }; template <class Key, class Value> class primary_record { public: primary_record() { empty = true; record_root = NULL; } bool empty; record<Key, Value> *record_root; }; template <class Key, class Value> class hashtable { public: hashtable() { table_size = default_table_size; table.resize(default_table_size); //default table size for (int i=0; i<table_size; i++) { primary_record<Key, Value> pr; table.push_back(pr); } } hashtable(int size) { table_size = size; table.resize(size); //default table size for (int i=0; i<table_size; i++) { primary_record<Key, Value> pr; table.push_bash(pr); } } int put(Key key, Value value) { int hashkey; int position; hashkey = static_cast<int>(key); //hashkey = key; position = hash(hashkey); if (table[position].empty == true) { table[position].record_root = new record<Key, Value>; table[position].record_root->key = key; table[position].record_root->value = value; table[position].record_root->next = NULL; table[position].empty = false; return put_status_insert_new; } record<Key,Value> *pRecord = table[position].record_root; record<Key,Value> *last; while (pRecord != NULL) { if (key == pRecord->key) { pRecord->value = value; return put_status_insert_overwritten; } last = pRecord; pRecord = pRecord->next; } //go through the chain, no dupliated keys found last->next = new record<Key, Value>; last->next->key = key; last->next->value = value; return put_status_insert_new; } int get( Key key, Value *value ) { int hashkey; int position; hashkey = static_cast<int>(key); //hashkey = key; position = hash(hashkey); if (table[position].empty == true) { return get_not_found; } record<Key,Value> *pRecord = table[position].record_root; while (pRecord != NULL) { if (key == pRecord->key) { *value = pRecord->value; return get_found; } } //go through the chain, no dupliated keys found return get_not_found; } int hash(int key) { return key%table_size; } private: int table_size; vector< primary_record <Key, Value> > table; }; class hashable_string:public string { public: hashable_string() { } hashable_string(string s) { str = s; } operator int() const { int ret = 0; int size = str.size(); for (int i=0; i<size; i++) { ret += static_cast<int>(str[i]) * (i%10); } return ret; } operator string() { return str; } string to_string() { return str; } string str; private: }; int main() { hashtable<int, int> ht; ht.put(2,20); ht.put(7,7); ht.put(3,3); ht.put(1,1); ht.put(8,8); ht.put(9,9); hashtable<hashable_string, string> ht2; hashable_string s1("Alfred"); ht2.put(s1, "731 Lexington Ave"); hashable_string s3("Wang"); ht2.put(s3,"100 ABC drive"); int ret1; if ( ht.get(3, &ret1) == get_found ) cout<<"in ht,key 3 returns value "<<ret1<<endl; else cout<<"in ht,key 3 not found."<<endl; if ( ht.get(8, &ret1) == get_found ) cout<<"in ht,key 8 returns value "<<ret1<<endl; else cout<<"in ht,key 8 not found."<<endl; if ( ht.get(99, &ret1) == get_found ) cout<<"in ht,key 99 returns value "<<ret1<<endl; else cout<<"in ht,key 99 not found."<<endl; string ret2; if ( ht2.get(s1, &ret2) == get_found ) cout<<"in ht,key "<<(string)(s1)<<" returns value "<<ret2<<endl; else cout<<"in ht,key"<<s1.to_string()<<" not found."<<endl; return 0; }
[ "az@cs.brown.edu" ]
az@cs.brown.edu
68481af64cbe538e311f0dae57711fc4c4c18a8d
af2b9daade951d0239c56468e31ac924aad2d7db
/StandardRound/r231div2-394/394-B-a.cpp
3a0f902666bf3c83d989b5b77d7dcbd5ca1872b4
[]
no_license
zentorwie/codeforces-solutions
75446e153a95cb48fe8ce1ad7a214a9b16017c68
6ed365fff441f4b53294d7f4deb89e09fa8ea52e
refs/heads/master
2020-05-18T07:10:42.245670
2014-08-01T12:51:11
2014-08-01T12:51:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
872
cpp
#include <stdio.h> #include <string> int main() { int p, x; char n[1000010] = {0}; int b = 0; int t = 0; // to store int next = 0; int ptr = 0; // place int ok = 0; scanf("%d%d", &p, &x); if (x == 1) { for (int i = 0; i < p; i++) { printf("1"); } printf("\n"); return 0; } for (b = 1; b <= 9; b++) { //from 1 to 9 if (ok) break; n[0] = b; next = 0; t = 0; for (ptr = 0; ptr < p; ptr++) { next = n[ptr] * x + t; t = next / 10; // printf("next = %d\n", next); if (ptr == p-1) { if (t == 0 && (next % 10 == n[0]) && n[p-1] != 0) { ok = 1; } } else { n[ptr+1] = next % 10; } } } if (ok) { for (int i = p - 1; i >= 0; i--) { printf("%d", n[i]); } printf("\n"); } else printf("Impossible\n"); return 0; }
[ "zentorwie@gmail.com" ]
zentorwie@gmail.com
b7aa80cb3fcff2c107bc9fc650b642bfe9ae500f
a421d742de106725206384622dcf774913357d11
/include/inviwo/qt/widgets/inviwodockwidget.h
97ed938ecbc2792fef643533b55fa7844dc80177
[ "BSD-2-Clause" ]
permissive
sarbi127/inviwo
b91d0d57704a40faf720b4d9e2d29200f150a1cc
ae61d33d61128f584c08a704696bb4b3d0cc5eec
refs/heads/master
2021-01-17T05:35:59.982468
2015-09-18T10:42:55
2015-09-18T10:43:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,435
h
/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2012-2015 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #ifndef IVW_INVIWODOCKWIDGET_H #define IVW_INVIWODOCKWIDGET_H #include <inviwo/qt/widgets/inviwoqtwidgetsdefine.h> #include <QDockWidget> class QKeyEvent; class QLayout; namespace inviwo { class InviwoDockWidgetTitleBar; class IVW_QTWIDGETS_API InviwoDockWidget : public QDockWidget { Q_OBJECT public: InviwoDockWidget(QString title, QWidget* parent); virtual ~InviwoDockWidget(); virtual void showEvent(QShowEvent* showEvent) override; virtual void keyPressEvent(QKeyEvent* keyEvent) override; void setSticky(bool sticky); bool isSticky() const; void setContents(QWidget *widget); void setContents(QLayout *layout); protected slots: void updateWindowTitle(const QString &string); private: InviwoDockWidgetTitleBar* dockWidgetTitleBar_; }; } // namespace #endif // IVW_INVIWODOCKWIDGET_H
[ "eriksunden85@gmail.com" ]
eriksunden85@gmail.com
4d4eae743c3bfe9be4774bcb3377e2f1309f818e
9eff4a0c6890bc8571bb1115d14159ce93c2f5a7
/include/kspp/utils/concurrent_queue.h
28deb3aae43e8c05a759e8e97ca567a0b0edb1b4
[ "BSL-1.0" ]
permissive
bitbouncer/kspp
d06865e46a1e3820e65d24edb951a48a996dffbf
8539f359e32bd3dd1360ac4616eab88e79aab607
refs/heads/master
2022-10-20T22:45:11.118381
2022-09-28T14:50:00
2022-09-28T14:50:00
73,604,579
136
27
BSL-1.0
2022-05-16T19:20:41
2016-11-13T08:42:34
C++
UTF-8
C++
false
false
1,521
h
#include <chrono> #include <thread> #include <mutex> #include <condition_variable> #include <queue> #pragma once template<typename T> class concurrent_queue { public: concurrent_queue() = default; concurrent_queue(const concurrent_queue &) = delete; concurrent_queue &operator=(const concurrent_queue &) = delete; void push(const T &item) { std::unique_lock<std::mutex> lk(cv_m_); queue_.push(item); lk.unlock(); cv_.notify_one(); } inline bool empty() const { std::unique_lock<std::mutex> lk(cv_m_); return queue_.empty(); } T pop() { std::unique_lock<std::mutex> lk(cv_m_); while (queue_.empty()) cv_.wait(lk); auto val = queue_.front(); queue_.pop(); return val; } void pop(T &item) { std::unique_lock<std::mutex> lk(cv_m_); while (queue_.empty()) cv_.wait(lk); item = queue_.front(); queue_.pop(); } bool try_pop(T &item) { std::unique_lock<std::mutex> lk(cv_m_); if (queue_.empty()) return false; item = queue_.front(); queue_.pop(); return true; } template<class Rep, class Period> bool try_pop(T &item, const std::chrono::duration<Rep, Period> &rel_time) { std::unique_lock<std::mutex> lk(cv_m_); while (queue_.empty()) { if (cv_.wait_for(lk, rel_time) == std::cv_status::timeout) return false; } item = queue_.front(); queue_.pop(); return true; } private: std::queue<T> queue_; std::mutex cv_m_; std::condition_variable cv_; };
[ "svante.karlsson@csi.se" ]
svante.karlsson@csi.se
7a71739778bfe25d00a2b26a4ec3343e2c57914c
fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd
/net/base/network_interfaces_unittest.cc
1469b49fbb537b05784fbe48f8853f5dd76b3a68
[ "BSD-3-Clause" ]
permissive
wzyy2/chromium-browser
2644b0daf58f8b3caee8a6c09a2b448b2dfe059c
eb905f00a0f7e141e8d6c89be8fb26192a88c4b7
refs/heads/master
2022-11-23T20:25:08.120045
2018-01-16T06:41:26
2018-01-16T06:41:26
117,618,467
3
2
BSD-3-Clause
2022-11-20T22:03:57
2018-01-16T02:09:10
null
UTF-8
C++
false
false
2,737
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/base/network_interfaces.h" #include <ostream> #include <string> #include <unordered_set> #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" #include "net/base/ip_endpoint.h" #include "testing/gtest/include/gtest/gtest.h" #if defined(OS_POSIX) && !defined(OS_ANDROID) #include <net/if.h> #elif defined(OS_WIN) #include <iphlpapi.h> #include <objbase.h> #endif namespace net { namespace { // Verify GetNetworkList(). TEST(NetworkInterfacesTest, GetNetworkList) { NetworkInterfaceList list; ASSERT_TRUE(GetNetworkList(&list, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES)); for (NetworkInterfaceList::iterator it = list.begin(); it != list.end(); ++it) { // Verify that the names are not empty. EXPECT_FALSE(it->name.empty()); EXPECT_FALSE(it->friendly_name.empty()); // Verify that the address is correct. EXPECT_TRUE(it->address.IsValid()) << "Invalid address of size " << it->address.size(); EXPECT_FALSE(it->address.IsZero()); EXPECT_GT(it->prefix_length, 1u); EXPECT_LE(it->prefix_length, it->address.size() * 8); #if defined(OS_WIN) // On Windows |name| is NET_LUID. NET_LUID luid; EXPECT_EQ(static_cast<DWORD>(NO_ERROR), ConvertInterfaceIndexToLuid(it->interface_index, &luid)); GUID guid; EXPECT_EQ(static_cast<DWORD>(NO_ERROR), ConvertInterfaceLuidToGuid(&luid, &guid)); LPOLESTR name; StringFromCLSID(guid, &name); EXPECT_STREQ(base::UTF8ToWide(it->name).c_str(), name); CoTaskMemFree(name); if (it->type == NetworkChangeNotifier::CONNECTION_WIFI) { EXPECT_NE(WIFI_PHY_LAYER_PROTOCOL_NONE, GetWifiPHYLayerProtocol()); } #elif defined(OS_POSIX) && !defined(OS_ANDROID) char name[IF_NAMESIZE]; EXPECT_TRUE(if_indextoname(it->interface_index, name)); EXPECT_STREQ(it->name.c_str(), name); #endif } } TEST(NetworkInterfacesTest, GetWifiSSID) { // We can't check the result of GetWifiSSID() directly, since the result // will differ across machines. Simply exercise the code path and hope that it // doesn't crash. EXPECT_NE((const char*)NULL, GetWifiSSID().c_str()); } TEST(NetworkInterfacesTest, GetHostName) { // We can't check the result of GetHostName() directly, since the result // will differ across machines. Our goal here is to simply exercise the // code path, and check that things "look about right". std::string hostname = GetHostName(); EXPECT_FALSE(hostname.empty()); } } // namespace } // namespace net
[ "jacob-chen@iotwrt.com" ]
jacob-chen@iotwrt.com
8b54daf45bd29928ca307311ff1ab1bcd6960e86
c39ae78fd4450b9972ef2b49ab9a94306656bb32
/Examples/src/WarpingDemo.cc
a0c9bc10517bb8ffed04e73c25baed08b1a4b0dc
[ "BSD-3-Clause" ]
permissive
mingliangfu/MTF
a206cf78008585e229a74dbeb03a591736ee37a5
d9f60de242b92d4a6db76563f3d940b8b34d4302
refs/heads/master
2021-01-25T09:20:27.111448
2017-06-03T02:33:39
2017-06-03T02:33:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,762
cc
//#include <mtf/SM/ESM.h> //#include<mtf/AM/NCC.h> //#include <mtf/SSM/Homography.h> #include <mtf/mtf.h> #include <mtf/Tools/pipeline.h> #include <mtf/Tools/cvUtils.h> #include <mtf/Utilities/miscUtils.h> // typedef mtf::RKLT<mtf::NCC, mtf::Homography> TrackerType; typedef mtf::CompositeSM<mtf::NCC, mtf::Homography> TrackerType; int main(int argc, char * argv[]){ if(!readParams(argc, argv)){ return EXIT_FAILURE; } enable_nt = 0; //ESM<NCC, Homography> tracker; // TrackerType *tracker = static_cast<TrackerType*>(mtf::getTracker("rklt", "ncc", "8", "0")); TrackerType *tracker = dynamic_cast<TrackerType*>(mtf::getTracker("nnic", "ncc", "8", "0")); // TrackerType *tracker = static_cast<TrackerType*>(mtf::getTracker("pffc", "ncc", "8", "0")); if(!tracker){ printf("Dynamic casting failed.\n"); return EXIT_FAILURE; } // mtf::Homography &ssm = tracker->templ_tracker->getSSM(); mtf::Homography &ssm = tracker->getSSM(); InputCV input('u'); GaussianSmoothing pre_proc(tracker->inputType()); input.initialize(); pre_proc.initialize(input.getFrame()); tracker->setImage(pre_proc.getFrame()); CVUtils cv_utils; cv_utils.selectObjects(&input, 1); tracker->initialize(cv_utils.getObj().corners); while(input.update()){ pre_proc.update(input.getFrame()); tracker->update(pre_proc.getFrame()); mtf::utils::printMatrix(ssm.getState(), "Homography Params"); Matrix3d warp_mat; ssm.getWarpFromState(warp_mat, ssm.getState()); mtf::utils::printMatrix(warp_mat, "Homography Matrix"); utils::drawRegion(input.getFrame(MUTABLE), tracker->getRegion()); cv::imshow("Tracker Location", input.getFrame()); if(cv::waitKey(1) == 27){ break; } } cv::destroyAllWindows(); return 0; }
[ "asingh1@ualberta.ca" ]
asingh1@ualberta.ca
6e9eea5703e03c881e8a5f4fb67c1732c4a9fc77
8dbf8e350b809ac68435ad0e49ce17b98d20895f
/cpp_src/HelperFuncs.cpp
da5c8c7798441fde958cdb0faaca8254cdb14362
[]
no_license
oralmer/algo_proj
c621967886fb95801e264e55d008b29c8d6394e8
7b6925c7a498e8457abc2713b756191b7048f9cc
refs/heads/master
2020-04-06T07:38:47.436648
2019-08-10T19:15:49
2019-08-10T19:15:49
157,280,040
0
0
null
null
null
null
UTF-8
C++
false
false
211
cpp
#include "HelperFuncs.h" std::ostream &operator<<(std::ostream &s, std::vector<char> t) { for (const char i : t) { if (i == '\0') { break; } s << i; } return s; }
[ "almer1or@gmail.com" ]
almer1or@gmail.com
01f31a4ede39bae7a6c50833f96b717af7ed29f9
ab431740965416a1f0de857cd54771a4558e6b64
/lunchTime.cpp
64a840ec1b750ceef781d35d780a4814e03b56c3
[]
no_license
dycha0430/Algorithm_Problem_Solving_Strategies
eb0c84b9560b5439d2cc8e3f9db6cdc302ffef04
a2a5e2cb1d1414ece4b8800a1aad63cc516c4e92
refs/heads/master
2023-03-10T08:52:37.520188
2021-02-24T15:45:08
2021-02-24T15:45:08
333,058,649
1
0
null
null
null
null
UTF-8
C++
false
false
1,229
cpp
#include <iostream> #include <vector> #include <algorithm> using namespace std; int N; int M[10000]; vector<pair<int, int>> lunchTime; bool compare(pair<int, int> a, pair<int, int> b) { return a.first > b.first; } int minimized_lunch(); int main() { int T, E; cin >> T; for (int test_case = 0; test_case < T; ++test_case) { cin >> N; lunchTime.clear(); for (int i = 0; i < N; ++i) cin >> M[i]; for (int i = 0; i < N; ++i) { cin >> E; lunchTime.push_back(make_pair(E, M[i])); } // Sort by Eating time in descending order. sort(lunchTime.begin(), lunchTime.end(), compare); cout << minimized_lunch() << endl; } } /* Return minimized lunch time */ int minimized_lunch() { int i, partSum = 0; vector<pair<int, int>>::reverse_iterator iter; int Answer = 0; /* Find the maximum amount of time to eat a food * that exceeds the microwave usage time required * after that food has been heated. */ for (i = 0, iter = lunchTime.rbegin(); i < N; ++i, ++iter) { Answer = max(Answer, (*iter).first - partSum); partSum = partSum + (*iter).second; } /* Minimized lunch time is the sum of the total usage time * of the microwave and the value obtained above. */ return partSum + Answer; }
[ "2019056799@hanyang.ac.kr" ]
2019056799@hanyang.ac.kr
8d379faa2793030d5a6cb551ee0acd9c73bfe0db
ac51dce98cb821df7334619d2fd25c26757d17d4
/eg2512554/Future_Value_Function/main.cpp
30b0bfb30b42e01dd3a5a73316ccf5a5cc9ee404
[]
no_license
Riverside-City-College-Computer-Science/CSC5_Winter_2014_40375
a85aa5ef80ca44a0968fdbae52a5cd0c0a3ed621
853b40e40086ab97ef3075df4287b34a536c6573
refs/heads/master
2021-01-01T06:27:43.574978
2014-02-13T04:21:23
2014-02-13T04:21:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,537
cpp
/* * File: main.cpp * Author: Edwin Gibbs * Created on January 21, 2014, 8:49 AM * Future Value Function */ //System Libraries #include <iostream> #include<cmath> using namespace std; //Global Constants //Functional pro float fv1(float, float, int); float fv2(float, float, int); float fv3(float, float, int); float fv4(float, float, int); float fv5(float, float, int); int main(int argc, char** argv) { //Execution begins here //declare variables float prin, interest; int periods; //Read in variables cout<<"Principal = $'s"<<endl; cin>>prin; cout<<"Interest in %/year"<<endl; cin>>interest; cout<<"Number of compounding periods(yrs)"<<endl; cin>>periods; //run the function cout<<"Future value =$"<<fv1(prin,interest,periods)<<endl; cout<<"Future value =$"<<fv2(prin,interest,periods)<<endl; cout<<"Future value =$"<<fv3(prin,interest,periods)<<endl; cout<<"Future value =$"<<fv4(prin,interest,periods)<<endl; cout<<"Future value =$"<<fv5(prin,interest,periods)<<endl; return 0; } //Future value function //input //pv->Present value $'s //iRate->Interest rate % //n->Number of compounding periods (years) //output //future value in $'s float fv5(float pv, float iRate, int n){ float save=pv; for(int years=n;years>=1;years--){ save*=(1+iRate/100); } return save; } //Future value function //input //pv->Present value $'s //iRate->Interest rate % //n->Number of compounding periods (years) //output //future value in $'s float fv4(float pv, float iRate, int n){ if(n==0)return pv; else return fv4(pv,iRate,n-1)*(1+iRate/100); } //Future value function //input //pv->Present value $'s //iRate->Interest rate % //n->Number of compounding periods (years) //output //future value in $'s float fv3(float pv, float iRate, int n){ return static_cast<float>(pv*exp(n*log(1.0+iRate/100.0))); } //Future value function //input //pv->Present value $'s //iRate->Interest rate % //n->Number of compounding periods (years) //output //future value in $'s float fv2(float pv, float iRate, int n){ return static_cast<float>(pv*exp(n*log(1.0+iRate/100.0))); } //Future value function //input //pv->Present value $'s //iRate->Interest rate % //n->Number of compounding periods (years) //output //future value in $'s float fv1(float pv, float iRate, int n){ float save=pv; for(int years=1;years<=n;years++){ save*=(1+iRate/100); } return save; }
[ "eddygibbs007@yahoo.com" ]
eddygibbs007@yahoo.com
0ab3208da33345c8baf1bc53ef4984af3fe268ff
f9b81e12421955fbfcf5d7dd987f1b5dcfb236f6
/demos/设计模式之命令模式/CommandPattern/CommandPattern.h
88d5dd7de4762492f0506194024385981ff4af3d
[]
no_license
lichangke/DesignPattern
f3aec170f6f3f54a84060143fba8f3c51514ceb8
a47738505177aeea05a977a8ffb12fff070d80c9
refs/heads/main
2023-02-17T07:05:30.906338
2021-01-12T13:51:53
2021-01-12T13:51:53
324,113,049
9
6
null
null
null
null
UTF-8
C++
false
false
4,357
h
// // Created by leacock on 2021/1/5. // #ifndef COMMANDPATTERN_COMMANDPATTERN_H #define COMMANDPATTERN_COMMANDPATTERN_H #include <iostream> #include <vector> /// Command(抽象命令类): Command class Command { public: virtual ~Command() = default; // 声明抽象接口:执行命令 virtual void execute() = 0; protected: Command() = default; }; /// Receiver(接收者): Lamp 、 Fan class Lamp { public: Lamp() { lampState = false; std::cout << "Lamp Hello" << std::endl; } ~Lamp() { std::cout << "Lamp Bye" << std::endl; } void lampOn() { lampState = true; std::cout << "Lamp On" << std::endl; } void lampOff() { lampState = false; std::cout << "Lamp Off" << std::endl; } bool getLampState(){ return lampState; } private: bool lampState; }; class Fan { public: Fan() { fanState = false; std::cout << "Fan Hello" << std::endl; } ~Fan() { std::cout << "Fan Bye" << std::endl; } void fanOn() { fanState = true; std::cout << "Fan On" << std::endl; } void fanOff() { fanState = false; std::cout << "Fan Off" << std::endl; } bool getFanState(){ return fanState; } private: bool fanState; }; /// ConcreteCommand(具体命令类): LampCommand 、 FanCommand class LampCommand : public Command { public: LampCommand() { std::cout << "LampCommand Hello" << std::endl; lamp = new Lamp(); } ~LampCommand() override { std::cout << "LampCommand Bye" << std::endl; delete lamp; } void execute() override{ if(lamp->getLampState()) { // true lamp->lampOff(); // false } else { lamp->lampOn(); } } private: Lamp *lamp; }; class FanCommand : public Command { public: FanCommand() { std::cout << "FanCommand Hello" << std::endl; fan = new Fan(); } ~FanCommand() override { std::cout << "FanCommand Bye" << std::endl; delete fan; } void execute() override{ if(fan->getFanState()) { // true fan->fanOff(); // false } else { fan->fanOn(); } } private: Fan *fan; }; /// Invoker(调用者):Switch class Switch { public: Switch() { std::cout << "Switch Hello" << std::endl; command = nullptr; } ~Switch() { std::cout << "Switch Bye" << std::endl; delete command; } // 设值注入具体命令类对象 void setCommand(Command *cmd){ delete command;// 删除之前命令 command = cmd; } // 发送命令:切换开关 void touch(){ std::cout << "切换开关:" << std::endl; command->execute(); } private: Command *command; }; /// CommandVector 命令集合 示例 class CommandVector { public: CommandVector() { std::cout << "CommandVector Hello" << std::endl; } ~CommandVector() { std::cout << "CommandVector Bye" << std::endl; for(auto command : commandVector) { delete command; } } void addCommand(Command *cmd) { commandVector.push_back(cmd); } void execute() { // 直接调用 commandVector 中元素 的 execute for(auto command : commandVector) { command->execute(); } } private: std::vector<Command *> commandVector; }; /// Invoker(调用者):SwitchVector 处理 CommandVector 命令集合 class SwitchVector { public: SwitchVector() { std::cout << "SwitchVector Hello" << std::endl; commandVector = nullptr; } ~SwitchVector() { std::cout << "SwitchVector Bye" << std::endl; delete commandVector; } // 设值注入具体命令类对象 void setCommandVector(CommandVector *vector){ commandVector = vector; } // 发送命令:切换开关 void touch(){ if(nullptr!=commandVector) { std::cout << "切换开关:" << std::endl; commandVector->execute(); } else { std::cout << "commandVector 为空" << std::endl; } } private: CommandVector *commandVector; }; #endif //COMMANDPATTERN_COMMANDPATTERN_H
[ "986740304@qq.com" ]
986740304@qq.com
e507e5310f74cc6495783be9f0cea79a6997afe4
bc62956b6b32eaeff1527dbc1e22127e6afe95e4
/assign6&7/src/main.cpp
e93dbba7b5971088acbbd8b9107209dda3463714
[]
no_license
Prakhar0409/Basic_Programming
93af5f4553fb0b0913d5ba9ab5c3074daa52204c
a1ff560c4c6f1298c98f1b2fab367c794b3ad1e1
refs/heads/master
2016-08-12T14:47:40.053715
2015-10-29T11:33:04
2015-10-29T11:33:04
45,177,283
0
0
null
null
null
null
UTF-8
C++
false
false
5,773
cpp
#include <iostream> // Allows input output operations #include <iomanip> #include<math.h> //user defined headers #include "matrix_functions.h" #include "map_functions.h" #include "print_functions.h" #include "compare_functions.h" using namespace std; #define N 200 #define ARRAY_SIZE (N*N) #define M 100 // Mapping is defined for [a-z] , [A-Z] , [0-9] // {'A','6'} maps A to 6 // // Define functionality for the following functions // And call them in main() /*For calculating Determinant of the Matrix */ // Donot modify the functions below(upto main) void keygen(float key[N][N], int marker) { int i,j; for(i=0;i<marker;i++){ for(j=0;j<marker;j++){ if(i != j) key[i][j] = marker; else key[i][j] = marker + 1; } } } int main() { /*********** DO NOT CHANGE VARIABLE NAMES ************/ char plain_text[ARRAY_SIZE]; char plain_text_zero_padded[ARRAY_SIZE]; char mapped_array[ARRAY_SIZE]; float mapped_array_in_2D[N][N]; int marker; char inv_mapped_array[ARRAY_SIZE]; char decrypt_plain_text_zero_padded[ARRAY_SIZE]; float key[N][N]; float cipher_text[N][N]; float invkey[N][N]; char decrypt_plain_text[ARRAY_SIZE]; /***************Get User Input***************/ cout << "Enter the plain text" << endl; cin >> plain_text; cout << "Enter the marker" << endl; cin >> marker; // Creating a key matrix of size (marker x marker) keygen(key,marker); /***************End User Input***************/ /*---------------------------------------------*/ // Please add your code here //getting string or plain text length. int length=0; //length of the plain text. for(int i=0;plain_text[i]!='\0';i++) { plain_text_zero_padded[i]=plain_text[i]; length++; } // cout<<length<<endl; //output length of input string // Step 1---Padding with zeros-0's int tmp=(length%marker); if(tmp!=0)tmp=marker-tmp; for(int i=0;i<tmp;i++) plain_text_zero_padded[length+i]='0'; length=length+tmp; plain_text_zero_padded[length]='\0'; /* //OUTPUT length and plain text zero padded cout<<length<<endl; for(int i=0;i<length;i++) cout<<plain_text_zero_padded[i]; cout<<endl; */ //Step 2---mapping 0 padded plain text (stored in plain text) into mapped_array array_map(mapped_array, plain_text_zero_padded); /* //OUTPUT mapped array for(int i=0;i<length;i++) { cout<<mapped_array[i]; } cout<<endl; */ //step 3--generating cipher text //3.1)---writing mapped_array in 2 D form mapped_array[length]='\0'; int j1=0; for(int i=0;mapped_array[i*marker+j1]!='\0';i++) { for(j1=0;j1<marker;j1++) { mapped_array_in_2D[i][j1]=mapped_array[i*marker+j1]; } j1=0; } /* //OUTPUT 2D array for(int i=0;mapped_array[i]!='\0';i++) { for(int j=0;j<marker;j++) { cout<<mapped_array_in_2D[i][j]; } cout<<endl; } */ //create cipher text for(int i=0;i<(length/marker);i++) { for(int j=0;j<marker;j++) { cipher_text[i][j]=0; for(int k=0;k<marker;k++) { cipher_text[i][j]+=mapped_array_in_2D[i][k]*key[k][j]; } } } inverse(invkey,key,marker); //transpose for(int i=0;i<marker;i++) { for(int j=0;j<i;j++) { invkey[i][j]+=invkey[j][i]; invkey[j][i]=invkey[i][j]-invkey[j][i]; invkey[i][j]=invkey[i][j]-invkey[j][i]; } } for(int i=0;i<(length/marker);i++) { for(int j=0;j<marker;j++) { mapped_array_in_2D[i][j]='\0'; for(int k=0;k<marker;k++) { mapped_array_in_2D[i][j]+=cipher_text[i][k]*invkey[k][j]; } mapped_array_in_2D[i][j]=round(mapped_array_in_2D[i][j]); } } /* //OUTPUT array mapped in 2D cout<<"array mapped in 2d"<<endl; for(int i=0;i<length/marker;i++) { for(int j=0;j<marker;j++) { cout<<mapped_array_in_2D[i][j]; } cout<<endl; } */ //from 2d array to a single 1D array with inverse mappings. for(int i=0;i<(length/marker);i++) { for(int j=0;j<marker;j++) { inv_mapped_array[(i*marker)+j]=mapped_array_in_2D[i][j]; } } inv_mapped_array[length]='\0'; /* // OUTPUT inverse mapped array cout<<"inverse mapped array"<<endl; for(int i=0;i<length;i++) { cout<<inv_mapped_array[i]; } */ inv_array_map(inv_mapped_array, decrypt_plain_text_zero_padded); /* //OUTPUT decrypted plain text zero padded cout<<"decrypt plain text zero padded"<<endl; for(int i=0;i<length;i++) { cout<<decrypt_plain_text_zero_padded[i]; } */ int x=length-1; while(decrypt_plain_text_zero_padded[x]=='0') { x--; } for(int i=0;i<=x;i++){ decrypt_plain_text[i]=decrypt_plain_text_zero_padded[i]; } /* // OUTPUT decrypted plain text cout<<"decrypted plain text"<<endl; for(int i=0;i<=x;i++){ cout<<decrypt_plain_text[i]; } cout<<endl; */ /*---------------------------------------------*/ // Donot modify // int length_of_input; for (length_of_input = 0;plain_text[length_of_input];length_of_input++); cout << "Plain Text entered" << endl; cout << plain_text<< "\n"; cout << "Key Used" << endl; print(key,marker,marker); cout << "Cipher Text " << endl; print(cipher_text,(int)ceil((float)length_of_input/marker),marker); cout << "Key Inverse" << endl; print(invkey,marker,marker); cout << "Decrypted Text" << endl; cout << decrypt_plain_text << "\n"; compare(plain_text,decrypt_plain_text,length_of_input); return 0; }
[ "prakhar0409@gmail.com" ]
prakhar0409@gmail.com
b1c6881c383bc3ffc601c10eb52d87c59256cb11
9c942fe75218d6018f8390c926f0b693e36ceaad
/cpp/0088_MergeSortedArray.cpp
8fee056ae04334afbe1808772090b3256e504f3f
[]
no_license
joy-yjl/leetcode_yjl
5878113ae6cb81d1f735fa812b13e7f7b31883f6
1def24ac4ef723ecfd1e4dc50ced677809bc942c
refs/heads/master
2022-07-31T04:42:45.845904
2022-07-20T03:35:20
2022-07-20T03:35:20
206,940,495
0
0
null
null
null
null
UTF-8
C++
false
false
421
cpp
class Solution { public: void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) { int right=m+n-1; int r1=m-1; for(int i=n-1;i>=0;i--) { while(r1>=0 && nums1[r1]>nums2[i]) { nums1[right]=nums1[r1]; r1--; right--; } nums1[right]=nums2[i]; right--; } } };
[ "yangjiali94@126.com" ]
yangjiali94@126.com
4352e74546bf129f8ec6f376bfccbdfb927ec41c
09b172fda28355214e237da62d4635b61617b4d6
/heater-with-display/heater-with-display.ino
da57604ebbdc5c4bffd4b5bf93ad0fd439e27863
[ "Apache-2.0" ]
permissive
lgv2018/filament-joiner
1c787b9d0d930e1d1eed099158abc2b4d83ae525
abd1bd5fdf2063e904306e7a222540911ba23f4f
refs/heads/master
2021-03-26T02:37:16.087382
2020-03-16T00:40:27
2020-03-16T00:40:27
247,667,197
0
1
Apache-2.0
2020-03-16T09:58:01
2020-03-16T09:58:00
null
UTF-8
C++
false
false
4,256
ino
/* * heater-with-display.ino * * Copyright 2020 Victor Chew * * 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. */ // Libraries required: // - NTC_Thermister (Yurii Salimov) [Source: Arduino Library Manager] // - PID (Brett Beuuregard) [Source: Arduino Library Manager] // - ss_oled (Larry Bank) [Source: Arduino Library Manager] // - TimerOne (Paul Stoffregen et al.) [Source: Arduino Library Manager] // - ClickEncoder (0xPIT) [Source: https://github.com/0xPIT/encoder/tree/arduino] #include <ss_oled.h> #include <TimerOne.h> #include <ClickEncoder.h> #include <NTC_Thermistor.h> #include <SmoothThermistor.h> #include <PID_v1.h> #define KP 17.07 #define KI 0.75 #define KD 96.57 #define SMOOTHING_WINDOW 5 #define MOSFET_GATE_PIN 3 #define THERMISTOR_PIN A6 #define KY040_CLK 9 #define KY040_DT 8 #define KY040_SW 2 #define KY040_STEPS_PER_NOTCH 2 bool heaterOn = false, pOnM = false; double pwmOut, curTemp, setTemp = 0; NTC_Thermistor* thermistor = new NTC_Thermistor(THERMISTOR_PIN, 10000, 100000, 25, 3950); SmoothThermistor* sthermistor = new SmoothThermistor(thermistor, SMOOTHING_WINDOW); PID pid(&curTemp, &pwmOut, &setTemp, KP, KI, KD, P_ON_E, DIRECT); ClickEncoder encoder(KY040_CLK, KY040_DT, KY040_SW, KY040_STEPS_PER_NOTCH); void refreshDisplay() { oledFill(0, 1); char msg[64]; sprintf(msg, "Hotend: %dc", (int)curTemp); oledWriteString(0, 0, 1, msg, FONT_NORMAL, 0, 1); sprintf(msg, "Target: %dc", (int)setTemp); oledWriteString(0, 0, 3, msg, FONT_NORMAL, 0, 1); oledWriteString(0, 0, 6, heaterOn ? "Heating..." : "- Heater off -", FONT_NORMAL, heaterOn ? 1 : 0, 1); } void encoderISR() { encoder.service(); } void setup() { Serial.begin(115200); pinMode(MOSFET_GATE_PIN, OUTPUT); pid.SetMode(AUTOMATIC); pinMode(LED_BUILTIN, OUTPUT); digitalWrite(LED_BUILTIN, LOW); encoder.setAccelerationEnabled(true); Timer1.initialize(10000); Timer1.attachInterrupt(encoderISR); oledInit(OLED_128x64, 0, 0, -1, -1, -1, 400000L); refreshDisplay(); } void loop() { // Get rotary encoder values and update display int _curTemp = sthermistor->readCelsius(); int _setTemp = setTemp - encoder.getValue()*5; // minus because signal from this rotary switch works in the opposite direction _setTemp = min(300, max(0, _setTemp)); bool _heaterOn = heaterOn; if (encoder.getButton() == ClickEncoder::Clicked) { _heaterOn = !_heaterOn; if (!_heaterOn) _setTemp = 0; } // Update display only if something changes if (_curTemp != curTemp || _setTemp != setTemp || _heaterOn != heaterOn) { curTemp = _curTemp; setTemp = _setTemp; heaterOn = _heaterOn; refreshDisplay(); } // Turn on LED if we are within 1% of target temperature digitalWrite(LED_BUILTIN, heaterOn ? abs(_curTemp-setTemp)/setTemp <= 0.01 : LOW); // To speed things up, only switch to proportional-on-measurement when we are near target temperature // See: http://brettbeauregard.com/blog/2017/06/introducing-proportional-on-measurement/ if (!pOnM && abs(curTemp-setTemp) <= max(curTemp, setTemp)*0.2) { pOnM = true; pid.SetTunings(KP, KI, KD, P_ON_M); Serial.println("P_ON_M activated."); } // Prevent thermal overrun in case of PID malfunction pid.Compute(); if (curTemp < 300) { analogWrite(MOSFET_GATE_PIN, heaterOn ? pwmOut : 0); } else { analogWrite(MOSFET_GATE_PIN, 0); Serial.println("Thermal overrun detected!"); } // Display stats //Serial.print("pwmOut = "); Serial.print(pwmOut); Serial.print(", "); //Serial.print("diff = "); Serial.print(setTemp - curTemp); Serial.print(", "); //Serial.print("curTemp = "); Serial.print(round(curTemp)); //Serial.print(" / "); Serial.println(round(setTemp)); delay(200); }
[ "victor.chew@gmail.com" ]
victor.chew@gmail.com
17e5bf532d7ba25a66a3154607b3873063ec29b5
b13b51704390ee6af926a85ab8e7890b6aa8976e
/Flatten_Binary_Tree_to_Linked_List.cpp
98fd3dfe224067050e8d74020ce4f62e62954971
[]
no_license
kxingit/LeetCode
7308eb306fe899e3f68a7cf90b43a37da46416cc
a0ef8e5454bd29076b50ffedc5b1720dd7273a9d
refs/heads/master
2021-01-14T08:03:20.811221
2017-03-20T19:25:56
2017-03-20T19:25:56
35,183,062
0
1
null
null
null
null
UTF-8
C++
false
false
1,536
cpp
/** * Given a binary tree, flatten it to a linked list in-place. */ class Solution { public: void flatten(TreeNode* root) { if(root == NULL) return; if(root->left) flatten(root->left); if(root->right) flatten(root->right); TreeNode* p = root->left; if(p == NULL) return; while(p->right) p = p->right; // while(p): X p->right = root->right; root->right = root->left; root->left = NULL; } }; // v2 class Solution { public: void flatten(TreeNode* root) { if(!root) return; TreeNode* left = root->left; TreeNode* right = root->right; flatten(left); flatten(right); if(!left) return; while(left->right) left = left->right; left->right = root->right; root->right = root->left; root->left = NULL; } }; // v3 class Solution { public: void flatten(TreeNode* root) { if(!root) return; auto left = root->left; auto right = root->right; flatten(left); flatten(right); auto p = left; if(!p) return; // important while(p->right) p = p->right; p->right = root->right; root->right = left; root->left = NULL; } }; // v4 class Solution { public: void flatten(TreeNode* root) { if(!root) return; flatten(root->left); flatten(root->right); auto p = root->left; if(!p) return; while(p->right) p = p->right; p->right = root->right; root->right = root->left; root->left = NULL; } };
[ "kxin@me.com" ]
kxin@me.com
2c0db062aaab4309d82eba159317baf49a8620fe
7de947c4ebb33105d349d54b903e936e56ad1e90
/clients/gtest/laswp_gtest.cpp
cf75ca766591d71b727e91d2759de45f13ce7cc7
[ "BSD-2-Clause" ]
permissive
amdkila/rocSOLVER
b466ee8b89b073d453c53c1766f3bbdd131e4f3b
3134f3fd1cf562b221188b0aa2ff97267e405bf3
refs/heads/master
2021-07-25T11:44:34.635650
2020-01-22T23:44:13
2020-01-22T23:44:13
206,652,297
0
0
BSD-2-Clause
2019-09-05T20:31:32
2019-09-05T20:31:32
null
UTF-8
C++
false
false
2,189
cpp
/* ************************************************************************ * Copyright 2018 Advanced Micro Devices, Inc. * * ************************************************************************ */ #include "testing_laswp.hpp" #include "utility.h" #include <gtest/gtest.h> #include <math.h> #include <stdexcept> #include <vector> using ::testing::Combine; using ::testing::TestWithParam; using ::testing::Values; using ::testing::ValuesIn; using namespace std; //TO BE IMPLEMENTED.... typedef std::tuple<vector<int>, vector<int>> wpTuple; const vector<vector<int>> range1 = { {1,1} }; const vector<vector<int>> range2 = { {-10,0} }; const vector<vector<int>> large_range1 = { {192,192} }; const vector<vector<int>> large_range2 = { {-10,0} }; Arguments laswp_setup_arguments(wpTuple tup) { Arguments arg; arg.timing = 0; return arg; } class permut : public ::TestWithParam<wpTuple> { protected: permut() {} virtual ~permut() {} virtual void SetUp() {} virtual void TearDown() {} }; TEST_P(permut, laswp_float) { Arguments arg = laswp_setup_arguments(GetParam()); rocblas_status status = testing_laswp<float>(arg); // if not success, then the input argument is problematic, so detect the error // message if (status != rocblas_status_success) { // if (arg.N < 0 || arg.K < 1 || arg.ldv < arg.N || arg.ldt < arg.K) { // EXPECT_EQ(rocblas_status_invalid_size, status); // } } } TEST_P(permut, laswp_double) { Arguments arg = laswp_setup_arguments(GetParam()); rocblas_status status = testing_laswp<double>(arg); // if not success, then the input argument is problematic, so detect the error // message if (status != rocblas_status_success) { // if (arg.N < 0 || arg.K < 1 || arg.ldv < arg.N || arg.ldt < arg.K) { // EXPECT_EQ(rocblas_status_invalid_size, status); // } } } INSTANTIATE_TEST_CASE_P(daily_lapack, permut, Combine(ValuesIn(large_range1), ValuesIn(large_range2))); INSTANTIATE_TEST_CASE_P(checkin_lapack, permut, Combine(ValuesIn(range1), ValuesIn(range2)));
[ "noreply@github.com" ]
amdkila.noreply@github.com
52e68ec90aa33155477dad0e14bf94301112f9f5
24b2ad530cbeba558a799c005f34df0d3337300a
/pvVision_DL0120/process_face/UltraLightFastGenericGaceDetector1MB.cpp
58d6bd4ab82dff2324d44165fd3b1b46381dde82
[]
no_license
lishang06/code_test
e27bd3ab158214fb32b636b445d1bc9507d9a0ca
a4f431c6c436924a2fda2f9bf7d0e94f11e55277
refs/heads/main
2023-06-10T01:33:13.453353
2021-01-20T06:38:38
2021-01-20T06:38:38
331,214,565
0
0
null
null
null
null
UTF-8
C++
false
false
2,187
cpp
#include <algorithm> #include <map> #include "UltraLightFastGenericGaceDetector1MB.h" #include "faceLUT.h" #include <iostream> #include "unistd.h" #include "stdio.h" #include "stdlib.h" #include <sys/stat.h> UltraLightFastGenericGaceDetector1MB::UltraLightFastGenericGaceDetector1MB() { } UltraLightFastGenericGaceDetector1MB::~UltraLightFastGenericGaceDetector1MB() { } void UltraLightFastGenericGaceDetector1MB::load(const std::string &model_path, int num_thread) { // std::vector<std::string> tmpp = { model_path + "/faceDetector_V2.mnn" }; //RFB_v1_dev255_BGR std::vector<std::string> tmpp = { model_path + "/RFB_v1_dev255_BGR.mnn" }; //RFB_v1_dev255_BGR //std::vector<std::string> tmpp = { model_path + "/faceDetector.mnn" }; net.load_param(tmpp, num_thread); } void UltraLightFastGenericGaceDetector1MB::detectInternal(cv::Mat& img_, std::vector<cv::Rect> &faces, std::vector<landmarkFace> &landmarkBoxResult, int detectState) { faces.clear(); img = img_; if( detectState==1 ) { net.Ultra_infer_img(img,conf_threshold, nms_threshold,OUTPUT_NUM, center_variance, size_variance, anchors,faces, landmarkBoxResult); }else if( detectState==2 ) { net.Ultra_infer_img_160(img,conf_threshold, nms_threshold,OUTPUT_NUM_160, center_variance, size_variance, anchors_160,faces, landmarkBoxResult); }else { net.Ultra_infer_img_80(img,conf_threshold, nms_threshold,OUTPUT_NUM_80, center_variance, size_variance, anchors_80,faces, landmarkBoxResult); } return; } void UltraLightFastGenericGaceDetector1MB::detect(const cv::Mat& img_, std::vector<cv::Rect> &faces, std::vector<landmarkFace> &landmarkBoxResult, int detectState) { if (img_.empty()) return; cv::Mat testImg; // resize and normal if( detectState==1 ) { cv::resize(img_, testImg, cv::Size(320,240)); //320 240 }else if( detectState==2 ) { cv::resize(img_, testImg, cv::Size(160,120)); //320 240 }else{ cv::resize(img_, testImg, cv::Size(80,60)); //320 240 } // detect face detectInternal(testImg, faces, landmarkBoxResult, detectState); return; }
[ "1540002025@qq.com" ]
1540002025@qq.com
6378f0d6b81332c02e684c639b77e1a22f2b0b6e
14735baf7e2f38131afb351c2d5905ccf829cfd3
/arregloG.cpp
5a521ce4330dfcf3ac0b2768ff055f112230c563
[]
no_license
sebasluna/taller3
df3a259214d80a7f20b2f471409657ed685ffa76
974ea18fed859321218b2db679345756647bb5bb
refs/heads/master
2021-01-22T23:26:41.194334
2017-03-21T00:05:28
2017-03-21T00:05:28
85,639,479
0
0
null
null
null
null
UTF-8
C++
false
false
580
cpp
/* *NOMBRE:UNION DE CADENAS *AUTOR:Luis Sebastian Urbano Luna *FECHA: *RESIMEN:Se ingresan dos cadenas al final se devuelve una */ #include <iostream> #include <stdio.h> int main(){ char cadena1[]={'s','e','b','a','s','t','i','a','n'}; char cadena2[]={'l','u','n','a'}; char resultado[13]; int i=0; for(int i=0; i<9; i++){ resultado[i]=cadena1[i]; } for (i=0; i<13; i++){ resultado[i]=cadena2[i+cadena1]; } for (i=0; i<13; i++){ printf("cadena nueva=%s",resultado[i]); } return 0; }
[ "noreply@github.com" ]
sebasluna.noreply@github.com
cd62640a737a9d87623885c8f8c510a9af7028e0
33fb56658c522ba250049b8f49e403daec843184
/src/log/tLog_Category_A.h
02bde87bfcffd698ad631d3f75c6d77cfa757ce5
[]
no_license
rleofield/previewbox
2551ee60a38fec29c2e6a366bf6b88a1d2345f1b
43f6439701568164c0b65f9e18a9a23f6633cd02
refs/heads/master
2021-05-16T02:29:00.998654
2019-09-18T21:39:50
2019-09-18T21:39:50
18,600,083
0
1
null
null
null
null
UTF-8
C++
false
false
2,094
h
/* -------------------------------------------------------------------------- Copyright 2012 by Richard Albrecht richard.albrecht@rleofield.de www.rleofield.de This program 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, 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 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, see <http://www.gnu.org/licenses/>. ------------------------------------------------------------------------------ */ #ifndef TLOG_DEFINE_A_H #define TLOG_DEFINE_A_H #include <iostream> #include "tLog.h" #include "tLogCategories.h" // wird bei Auslieferung in 'tLog.h' eingestellt #ifdef L_A_DEBUG // bei Auslieferung auskommentiert //#undef L_A_DEBUG #endif #ifndef L_A_DEBUG // bei Auslieferung auskommentiert //#define L_A_DEBUG #endif using namespace rlf_tlog; // logline in Code #ifdef L_A_DEBUG #define LOGT_A_DEBUG(exp) (logger().log( LfmCL(__LINE__,__FILE__,__FUNCTION__, eCategory::Cat_A, eLevel::LDEBUG, (exp) ) ) ) #define LOGT_A_INFO(exp) (logger().log( LfmCL(__LINE__,__FILE__,__FUNCTION__, eCategory::Cat_A, eLevel::INFO, (exp) ) ) ) #define LOGT_A_WARN(exp) (logger().log( LfmCL(__LINE__,__FILE__,__FUNCTION__, eCategory::Cat_A, eLevel::WARN, (exp) ))) #define LOGT_A_ERROR(exp) (logger().log( LfmCL(__LINE__,__FILE__,__FUNCTION__, eCategory::Cat_A, eLevel::LERROR, (exp) ))) #define LOGT_A_FATAL(exp) (logger().log( LfmCL(__LINE__,__FILE__,__FUNCTION__, eCategory::Cat_A, eLevel::FATAL, (exp) ))) #else #define LOGT_A_DEBUG(exp) {} #define LOGT_INFO(exp) {} #define LOGT_A_WARN(exp) {} #define LOGT_A_ERROR(exp) {} #define LOGT_A_FATAL(exp) {} #endif #endif // TLOG_DEFINE_A_H //EOF
[ "richard@rleofield.de" ]
richard@rleofield.de
5c9caf942e2fa22e1d718864fb41f032e90e9be6
bb8f8accc040f7e0880ac194fc823f96933345fd
/RPLB.cpp
c6bb363f8c53b768aac8789a0b370506ab23de25
[]
no_license
draconware/spoj
16f5501d9a721d93729db524896963bd2606746c
c8df41eceb00b87a6015465d30e21003bb681731
refs/heads/master
2021-01-01T06:00:56.568003
2018-02-28T16:57:15
2018-02-28T16:57:15
97,326,359
0
0
null
null
null
null
UTF-8
C++
false
false
607
cpp
#include<bits/stdc++.h> using namespace std; int main(){ #ifndef ONLINE_JUDGE freopen("input.in","r",stdin); freopen("output.out","w",stdout); #endif int t,c=0; cin>>t; while(t--){ c++; int n,k; cin>>n>>k; int arr[n+2]; for(int i=2;i<=n+1;i++){cin>>arr[i];} int dp[k+1][n+2]; memset(dp,0,sizeof(dp)); for(int i=1;i<=k;i++){ for(int j=2;j<=n+1;j++){ if(arr[j] <= i){dp[i][j] = max(dp[i][j-1],dp[i-arr[j]][j-2]+arr[j]);} else{dp[i][j] = dp[i][j-1];} //cout<<i<<" "<<j-1<<" "<<dp[i][j]<<endl; } } cout<<"Scenario #"<<c<<": "<<dp[k][n+1]<<endl; } return 0; }
[ "mayankaggarwal426@gmail.com" ]
mayankaggarwal426@gmail.com
58e0b067f42e056858067a72f5e23bcf400912c9
89e001f757cd6257bf24c3daf362fb9d2d49a320
/include/futex_semaphore.hpp
67480f7c8cad015403f5b6da1ce4145a2535442c
[]
no_license
4ertovwig/dummy_futex
503e82ff67bf802314416919be3122f6ea8f0a4a
760083b3876081aa48c7b724930910939a8e556f
refs/heads/main
2023-08-31T20:59:59.698306
2021-09-22T23:50:11
2021-09-22T23:50:11
409,363,881
0
0
null
null
null
null
UTF-8
C++
false
false
1,712
hpp
#ifndef FUTEX_SEMAPHORE_HPP_ #define FUTEX_SEMAPHORE_HPP_ #include "futex_mutex.hpp" #include "futex_condition_variable.hpp" //! Simple and naive semaphore realization with own mutex and condition variable //! Semantics are similar to <semaphore.h> template< shared_policy policy > class futex_semaphore : boost::noncopyable { //! Internal types using mutex_t = futex_mutex< policy >; using condition_t = futex_condition_variable< policy >; public: explicit futex_semaphore(std::int32_t maximum_simultaneous_workers) : m_limit(maximum_simultaneous_workers), m_waiters(0u) { if (m_limit <= 0u) THROW_EXCEPTION(std::runtime_error, "Maximum waiters must be greater than zero"); } void wait() { futex_mutex_unique_lock< mutex_t > lk(m_mutex); ++m_waiters; m_cond.wait(lk, [&](){ return m_waiters.load() <= m_limit; }); } template< typename Rep, typename Period > bool wait_for(const std::chrono::duration< Rep, Period >& waited_time) { futex_mutex_unique_lock< mutex_t > lk(m_mutex); ++m_waiters; if (!m_cond.wait_for(lk, waited_time, [&](){ return m_waiters.load() <= m_limit; })) { --m_waiters; return false; } return true; } void post() { futex_mutex_lock_guard< decltype(m_mutex) > lk(m_mutex); if (m_waiters.load() == 0u) return; --m_waiters; m_cond.notify_one(); } private: const std::uint32_t m_limit; std::atomic< std::int32_t > m_waiters; //! Synchronized mutex mutex_t m_mutex; //! Condition variable condition_t m_cond; }; //! Mutex 'analog' with 1 maximum worker template< shared_policy policy > class binary_semaphore : public futex_semaphore< policy > { public: binary_semaphore() : futex_semaphore< policy >(1u) {} }; #endif
[ "i.korotkov@iva-tech.ru" ]
i.korotkov@iva-tech.ru
893737be26cdbf3faf2bd73d3336ccd5be2379da
64e4fabf9b43b6b02b14b9df7e1751732b30ad38
/src/chromium/mojo_TODO/public/cpp/bindings/lib/string_serialization.h
ef6d57fa183223dc2c4206d2053409d0fe4e7b9a
[ "BSD-3-Clause" ]
permissive
ivan-kits/skia-opengl-emscripten
8a5ee0eab0214c84df3cd7eef37c8ba54acb045e
79573e1ee794061bdcfd88cacdb75243eff5f6f0
refs/heads/master
2023-02-03T16:39:20.556706
2020-12-25T14:00:49
2020-12-25T14:00:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,722
h
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef MOJO_PUBLIC_CPP_BINDINGS_LIB_STRING_SERIALIZATION_H_ #define MOJO_PUBLIC_CPP_BINDINGS_LIB_STRING_SERIALIZATION_H_ #include <stddef.h> #include <string.h> #include "mojo/public/cpp/bindings/lib/array_internal.h" #include "mojo/public/cpp/bindings/lib/serialization_forward.h" #include "mojo/public/cpp/bindings/lib/serialization_util.h" #include "mojo/public/cpp/bindings/string_data_view.h" #include "mojo/public/cpp/bindings/string_traits.h" namespace mojo { namespace internal { //#if defined(ENABLE_GIPC) template <typename MaybeConstUserType> struct Serializer<StringDataView, MaybeConstUserType> { using UserType = typename std::remove_const<MaybeConstUserType>::type; using Traits = StringTraits<UserType>; static void Serialize(MaybeConstUserType& input, Buffer* buffer, String_Data::BufferWriter* writer, SerializationContext* context) { if (CallIsNullIfExists<Traits>(input)) return; auto r = Traits::GetUTF8(input); writer->Allocate(r.size(), buffer); memcpy((*writer)->storage(), r.data(), r.size()); } static bool Deserialize(String_Data* input, UserType* output, SerializationContext* context) { if (!input) return CallSetToNullIfExists<Traits>(output); return Traits::Read(StringDataView(input, context), output); } }; //#endif // ENABLE_GIPC } // namespace internal } // namespace mojo #endif // MOJO_PUBLIC_CPP_BINDINGS_LIB_STRING_SERIALIZATION_H_
[ "trofimov_d_a@magnit.ru" ]
trofimov_d_a@magnit.ru
46c531bd1e2af48cfb7daa9429599d102107552b
19e048e210e8201eb0de48db0d61af96da243a95
/WBGT01.ino
3ea0efab68d918238ee803df2b8f01defe11123c
[]
no_license
pado3/ArduinoWBGT
3b6959f4901e4a56c37d392284fea71fe5c3aefb
25d0dff087821591103bef5745011bc1f03584c4
refs/heads/main
2022-12-28T11:31:37.652311
2020-10-08T03:49:03
2020-10-08T03:49:03
301,588,532
0
0
null
null
null
null
UTF-8
C++
false
false
12,258
ino
// BME280で測定した屋内の温湿度を元に暑さ指数WBGTを求め、秋月電子8x2LCDに表示する // 2020/08/27 by パドラッパ (twitter: @pado3) // 2020/08/30 LCDとBME280のVddをVcc固定から電圧可変にした(3.3V品はPWM=168) // 2020/09/22 カラーLEDを点けるのに失敗。赤色LEDを13から移動して上半分で完結させた // 参考: // 屋内での暑さ指数(指針の図2) http://seikishou.jp/heatstroke.html // 使用した旧Arduino nano https://www.switch-science.com/catalog/750/ // LCDの商品ページ・使い方 https://www.switch-science.com/catalog/1405/ // BME280の商品ページ・使い方 https://www.switch-science.com/catalog/2236/ #include <Wire.h> // pin assign #define LED 2 // LED @ D13 (2.2k) #define VDD 3 // センサ・液晶用のVdd @ D3 #define Vin 14 // LCD VolumeのADC @ D14=A0 #define VOLH 15 // LCD VolumeのH側 @ D15=A1 (10k), LはGND直結 #define sdaPin 18 // Arduino A4 #define sclPin 19 // Arduino A5 // I2C addresses #define LCDadr 0x3e // LCD address, fixed #define BMEadr 0x76 // BME280 address, SDO:L float Vdd_V = 3.3; // センサ・液晶のVdd電圧 3.3V or 5.0V in typical byte contrast = 10; // LCDコントラスト(0~63)、初期値10 boolean splash = false; // Indoor use message unsigned long int hum_raw,temp_raw,pres_raw; signed long int t_fine; uint16_t dig_T1; int16_t dig_T2; int16_t dig_T3; uint16_t dig_P1; int16_t dig_P2; int16_t dig_P3; int16_t dig_P4; int16_t dig_P5; int16_t dig_P6; int16_t dig_P7; int16_t dig_P8; int16_t dig_P9; int8_t dig_H1; int16_t dig_H2; int8_t dig_H3; int16_t dig_H4; int16_t dig_H5; int8_t dig_H6; void setup() { // Contrast reader setup pinMode(VDD, OUTPUT); pinMode(VOLH, OUTPUT); pinMode(Vin, INPUT); analogWrite(VDD, int(255*Vdd_V/5)); // LCDとBME280の電源電圧(value/255)*5V digitalWrite(VOLH, HIGH); // 5V contrast = analogRead(Vin) >> 4; // ADC1024step ->4bit-> contrast64step // BME280 setup uint8_t osrs_t = 1; // Temperature oversampling x 1 uint8_t osrs_p = 1; // Pressure oversampling x 1 uint8_t osrs_h = 1; // Humidity oversampling x 1 uint8_t mode = 3; // Normal mode uint8_t t_sb = 5; // Tstandby 1000ms uint8_t filter = 0; // Filter off uint8_t spi3w_en = 0; // 3-wire SPI Disable uint8_t ctrl_meas_reg = (osrs_t << 5) | (osrs_p << 2) | mode; uint8_t config_reg = (t_sb << 5) | (filter << 2) | spi3w_en; uint8_t ctrl_hum_reg = osrs_h; Serial.begin(115200); delay(200); Serial.println(); Serial.println(F("START " __FILE__ " from " __DATE__ " " __TIME__)); Wire.begin(); writeReg(0xF2,ctrl_hum_reg); writeReg(0xF4,ctrl_meas_reg); writeReg(0xF5,config_reg); readTrim(); // LED setup pinMode(LED, OUTPUT); // LCD setup delay(500); lcd_cmd(0b00111000); // function set lcd_cmd(0b00111001); // function set lcd_cmd(0b00000100); // EntryModeSet lcd_cmd(0b00010100); // interval osc lcd_cmd(0b01110000 | (contrast & 0xF)); // contrast Low lcd_cmd(0b01011100 | ((contrast >> 4) & 0x3)); // contast High/icon/power lcd_cmd(0b01101100); // follower control delay(200); lcd_cmd(0b00111000); // function set lcd_cmd(0b00001100); // Display On lcd_cmd(0b00000001); // Clear Display delay(2); } void loop() { double temp_act = 0.0, press_act = 0.0, hum_act=0.0; signed long int temp_cal; unsigned long int press_cal, hum_cal; // 屋内専用であることのスプラッシュ表示 兼 BME280の初期化待ち if (!splash) { lcd_clear(); lcd_setCursor(0, 0); lcd_printStr("WBGT use"); lcd_setCursor(0, 1); lcd_printStr(" indoor"); delay(2000); splash = true; } // BME280データの読み込み readData(); // rawデータはreadData() の中で設定される temp_cal = calibration_T(temp_raw); hum_cal = calibration_H(hum_raw); press_cal = calibration_P(pres_raw); temp_act = (double)temp_cal / 100.0; hum_act = (double)hum_cal / 1024.0; press_act = (double)press_cal / 100.0; // WBGT計算のデバッグ用 // temp_act = 40.0; // hum_act = 99.0; // calc WBGT int W = calcWBGT(temp_act, hum_act); // シリアルモニタで確認できるようにしておく Serial.print("TEMP: "); Serial.print(temp_act); Serial.print("degC, HUM: "); Serial.print(hum_act); Serial.print("%RH, PRESS: "); Serial.print(press_act); Serial.print("hPa, WBGT: "); Serial.print(W); Serial.print("degC, index["); Serial.print(round(temp_act - 21)); Serial.print(", "); Serial.print(round((hum_act - 20)/5)); Serial.print("], contrast: "); Serial.println(contrast); // ここから表示 lcd_clear(); // WBGT lcd_setCursor(0, 0); lcd_printStr("WBGT "); if (W < 15) { lcd_printStr("--"); } else { lcd_printInt(W); } lcd_printStr("C"); // 温湿度 char tmp[16]; char hum[16]; dtostrf(temp_act, 4, 1, tmp); dtostrf(hum_act, 2, 0, hum); lcd_setCursor(0, 1); lcd_printStr(tmp); lcd_printStr("C"); lcd_printStr(hum); lcd_printStr("%"); // LEDを同期点滅。危険のW>31で激しく点滅 // ざっくり1秒ループにする。センサ読み込みが20msecぐらい。 digitalWrite(LED, HIGH); // ON if (W >= 31) { for (int i=0; i<3; i++) { delay(125); digitalWrite(LED, LOW); // OFF delay(125); digitalWrite(LED, HIGH); // ON } delay(125); digitalWrite(LED, LOW); // OFF delay(105); } else { delay(10); digitalWrite(LED, LOW); // OFF delay(970); } // コントラスト設定値をシリアルコンソールで確認する用。設定はリセット時のみ。 contrast = analogRead(Vin) >> 4; } int calcWBGT(double temp, double hum) { // 上から下:21-40°C, 左から右:5ステップで20-100%RH int wbgt[20][17] = { {15,15,16,16,17,17,18,19,19,20,20,21,21,22,23,23,24}, {15,16,17,17,18,18,19,19,20,21,21,22,22,23,24,24,25}, {16,17,17,18,19,19,20,20,21,22,22,23,23,24,25,25,26}, {17,18,18,19,19,20,21,21,22,22,23,24,24,25,26,26,27}, {18,18,19,20,20,21,22,22,23,23,24,25,25,26,27,27,28}, {18,19,20,20,21,22,22,23,24,24,25,26,26,27,28,28,29}, {19,20,21,21,22,23,23,24,25,25,26,27,27,28,29,29,30}, {20,21,21,22,23,23,24,25,25,26,27,28,28,29,30,30,31}, {21,21,22,23,24,24,25,26,26,27,28,29,29,30,31,31,32}, {21,22,23,24,24,25,26,27,27,28,29,29,30,31,32,32,33}, {22,23,24,24,25,26,27,27,28,29,30,30,31,32,33,33,34}, {23,24,25,25,26,27,28,28,29,30,31,31,32,33,34,34,35}, {24,25,25,26,27,28,28,29,30,31,32,32,33,34,35,35,36}, {25,25,26,27,28,29,29,30,31,32,33,33,34,35,36,37,37}, {25,26,27,28,29,29,30,31,32,33,33,34,35,36,37,38,38}, {26,27,28,29,29,30,31,32,33,34,34,35,36,37,38,39,39}, {27,28,29,29,30,31,32,33,34,35,35,36,37,38,39,40,41}, {28,28,29,30,31,32,33,34,35,35,36,37,38,39,40,41,42}, {28,29,30,31,32,33,34,35,35,36,37,38,39,40,41,42,43}, {29,30,31,32,33,34,35,35,36,37,38,39,40,41,42,43,44} }; // 温湿度の値からインデックス値を得る int t = round(temp - 21); int h = round((hum - 20)/5); // WBGT初期値 int W = 0; // インデックス圏外のときは初期値のまま戻す if (t<0) return W; if (t>=20) return W; if (h<0) return W; if (h>=17) return W; // ここまできたらWBGTを求めて返す W = wbgt[t][h]; return W; } // ここからBME280関係の関数 void readTrim() { uint8_t data[32],i=0; Wire.beginTransmission(BMEadr); Wire.write(0x88); Wire.endTransmission(); Wire.requestFrom(BMEadr,24); while(Wire.available()){ data[i] = Wire.read(); i++; } Wire.beginTransmission(BMEadr); Wire.write(0xA1); Wire.endTransmission(); Wire.requestFrom(BMEadr,1); data[i] = Wire.read(); i++; Wire.beginTransmission(BMEadr); Wire.write(0xE1); Wire.endTransmission(); Wire.requestFrom(BMEadr,7); while(Wire.available()){ data[i] = Wire.read(); i++; } dig_T1 = (data[1] << 8) | data[0]; dig_T2 = (data[3] << 8) | data[2]; dig_T3 = (data[5] << 8) | data[4]; dig_P1 = (data[7] << 8) | data[6]; dig_P2 = (data[9] << 8) | data[8]; dig_P3 = (data[11]<< 8) | data[10]; dig_P4 = (data[13]<< 8) | data[12]; dig_P5 = (data[15]<< 8) | data[14]; dig_P6 = (data[17]<< 8) | data[16]; dig_P7 = (data[19]<< 8) | data[18]; dig_P8 = (data[21]<< 8) | data[20]; dig_P9 = (data[23]<< 8) | data[22]; dig_H1 = data[24]; dig_H2 = (data[26]<< 8) | data[25]; dig_H3 = data[27]; dig_H4 = (data[28]<< 4) | (0x0F & data[29]); dig_H5 = (data[30] << 4) | ((data[29] >> 4) & 0x0F); dig_H6 = data[31]; } void writeReg(uint8_t reg_address, uint8_t data) { Wire.beginTransmission(BMEadr); Wire.write(reg_address); Wire.write(data); Wire.endTransmission(); } void readData() { int i = 0; uint32_t data[8]; Wire.beginTransmission(BMEadr); Wire.write(0xF7); Wire.endTransmission(); Wire.requestFrom(BMEadr,8); while(Wire.available()){ data[i] = Wire.read(); i++; } pres_raw = (data[0] << 12) | (data[1] << 4) | (data[2] >> 4); temp_raw = (data[3] << 12) | (data[4] << 4) | (data[5] >> 4); hum_raw = (data[6] << 8) | data[7]; } signed long int calibration_T(signed long int adc_T) { signed long int var1, var2, T; var1 = ((((adc_T >> 3) - ((signed long int)dig_T1<<1))) * ((signed long int)dig_T2)) >> 11; var2 = (((((adc_T >> 4) - ((signed long int)dig_T1)) * ((adc_T>>4) - ((signed long int)dig_T1))) >> 12) * ((signed long int)dig_T3)) >> 14; t_fine = var1 + var2; T = (t_fine * 5 + 128) >> 8; return T; } unsigned long int calibration_P(signed long int adc_P) { signed long int var1, var2; unsigned long int P; var1 = (((signed long int)t_fine)>>1) - (signed long int)64000; var2 = (((var1>>2) * (var1>>2)) >> 11) * ((signed long int)dig_P6); var2 = var2 + ((var1*((signed long int)dig_P5))<<1); var2 = (var2>>2)+(((signed long int)dig_P4)<<16); var1 = (((dig_P3 * (((var1>>2)*(var1>>2)) >> 13)) >>3) + ((((signed long int)dig_P2) * var1)>>1))>>18; var1 = ((((32768+var1))*((signed long int)dig_P1))>>15); if (var1 == 0) { return 0; } P = (((unsigned long int)(((signed long int)1048576)-adc_P)-(var2>>12)))*3125; if(P<0x80000000) { P = (P << 1) / ((unsigned long int) var1); } else { P = (P / (unsigned long int)var1) * 2; } var1 = (((signed long int)dig_P9) * ((signed long int)(((P>>3) * (P>>3))>>13)))>>12; var2 = (((signed long int)(P>>2)) * ((signed long int)dig_P8))>>13; P = (unsigned long int)((signed long int)P + ((var1 + var2 + dig_P7) >> 4)); return P; } unsigned long int calibration_H(signed long int adc_H) { signed long int v_x1; v_x1 = (t_fine - ((signed long int)76800)); v_x1 = (((((adc_H << 14) -(((signed long int)dig_H4) << 20) - (((signed long int)dig_H5) * v_x1)) + ((signed long int)16384)) >> 15) * (((((((v_x1 * ((signed long int)dig_H6)) >> 10) * (((v_x1 * ((signed long int)dig_H3)) >> 11) + ((signed long int) 32768))) >> 10) + (( signed long int)2097152)) * ((signed long int) dig_H2) + 8192) >> 14)); v_x1 = (v_x1 - (((((v_x1 >> 15) * (v_x1 >> 15)) >> 7) * ((signed long int)dig_H1)) >> 4)); v_x1 = (v_x1 < 0 ? 0 : v_x1); v_x1 = (v_x1 > 419430400 ? 419430400 : v_x1); return (unsigned long int)(v_x1 >> 12); } // ここからLCD関係の関数 void lcd_cmd(byte x) { Wire.beginTransmission(LCDadr); Wire.write(0b00000000); // CO = 0,RS = 0 Wire.write(x); Wire.endTransmission(); } void lcd_clear() { lcd_cmd(0b00000001); } void lcd_contdata(byte x) { Wire.write(0b11000000); // CO = 1, RS = 1 Wire.write(x); } void lcd_lastdata(byte x) { Wire.write(0b01000000); // CO = 0, RS = 1 Wire.write(x); } // 文字の表示 void lcd_printStr(const char *s) { Wire.beginTransmission(LCDadr); while (*s) { if (*(s + 1)) { lcd_contdata(*s); } else { lcd_lastdata(*s); } s++; } Wire.endTransmission(); } // 整数の表示 void lcd_printInt(int num) { char int2str[10]; sprintf(int2str,"%d",num); lcd_printStr(int2str); } // 表示位置の指定 void lcd_setCursor(byte x, byte y) { lcd_cmd(0x80 | (y * 0x40 + x)); }
[ "noreply@github.com" ]
pado3.noreply@github.com
3890dfb249519cf9efda9b41540005a1e996a21c
b65131ff8007c7da85cd5384e94993bf91869c57
/libSemphella/hal.cpp
e20e7bf58f3f5002209488655c5ec6a40f17e41c
[]
no_license
moyilong/libSemphella
748ba9cea93d5a3ae2a4d026578611d92c896813
6f420f45e386dcc9d6ad477b04f7407a83e2d2c4
refs/heads/master
2020-04-06T10:41:00.314803
2018-04-29T11:23:18
2018-04-29T11:23:18
157,388,161
0
0
null
null
null
null
GB18030
C++
false
false
3,899
cpp
#include "hal.h" #ifdef __linux__ int UART0_Open(int fd, char* port); void UART0_Close(int fd); int UART0_Set(int fd, int speed, int flow_ctrl, int databits, int stopbits, int parity); int UART0_Init(int fd, int speed, int flow_ctrl, int databits, int stopbits, int parity); int UART0_Recv(int fd, char *rcv_buf, int data_len); int UART0_Send(int fd, char *send_buf, int data_len); #endif void Serial::SetPath(const string xpath) { path = xpath; } void Serial::close() { if (!status) return; #ifdef _WINDOWS if (CloseHandle(handle)) status = false; #elif defined(__linux__) #endif } void Serial::open() { if (is_opened()) return; #ifdef _WINDOWS handle = CreateFile(path.data(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); if (handle == (HANDLE)-1) return; status = true; DCB dcfg; if (!GetCommState(handle, &dcfg)) { debug << "Import Configure Faild!" << endl; close(); return; } dcfg.BaudRate = cfg.speed; dcfg.fBinary = true; dcfg.fParity = (cfg.parity != NONE); switch (cfg.parity) { case ODD: dcfg.Parity = ODDPARITY; break; case NONE: dcfg.Parity = NOPARITY; break; case MARK: dcfg.Parity = MARKPARITY; break; case EVEN: dcfg.Parity = EVENPARITY; break; } dcfg.fOutxCtsFlow = FALSE; // No CTS output flow control dcfg.fOutxDsrFlow = FALSE; // No DSR output flow control dcfg.fDtrControl = DTR_CONTROL_DISABLE; // No DTR flow control dcfg.fDsrSensitivity = FALSE; // DSR sensitivity dcfg.fTXContinueOnXoff = TRUE; // XOFF continues Tx dcfg.fOutX = FALSE; // No XON/XOFF out flow control dcfg.fInX = FALSE; // No XON/XOFF in flow control dcfg.fErrorChar = FALSE; // Disable error replacement dcfg.fNull = FALSE; // Disable null stripping dcfg.fRtsControl = RTS_CONTROL_DISABLE; //No RTS flow control dcfg.fAbortOnError = FALSE; // 当串口发生错误,并不终止串口读写 dcfg.ByteSize = cfg.data_bit; //dcfg.StopBits = cfg.stop_bit; if (cfg.stop_bit == 2) dcfg.StopBits = TWOSTOPBITS; else dcfg.StopBits = ONESTOPBIT; if (!SetCommState(handle, &dcfg)) { debug << "Setting Faild!" << endl; close(); return; } #elif defined(__linux__) /*if (!UART0_Open(&handle, path.data())) { debug << "Enable Handle Faild!" << endl; return; }*/ handle=UART0_Open(handle, path.data()); if (handle == 0) { debug << "Handle is Zero!" << endl; return; } debug << "Handle ID=" << handle << endl; int parity_mode = 'N'; switch (cfg.parity) { case ODD: parity_mode = 'O'; break; case MARK: parity_mode = 'S'; break; case EVEN: parity_mode = 'E'; break; case NONE: parity_mode = 'N'; break; } int value = UART0_Set(handle, cfg.speed, 0, cfg.data_bit, cfg.stop_bit, parity_mode); debug << "Return Value:" << value << endl; if (!value) { debug << "Linux Init Faild! Handle Return Empty" << endl;; return; } #endif status = true; debug << "Port Open Success!" << endl; return; } void Serial::open(const string xpath) { SetPath(xpath); open(); } void Serial::open(const SerialConfig xcfg) { SetConfig(xcfg); open(); } void Serial::open(const string xpath, const SerialConfig xcfg) { SetConfig(xcfg); SetPath(xpath); open(); } void Serial::SetConfig(const SerialConfig xcfg) { cfg = xcfg; } SerialConfig Serial::GetConfig() { return cfg; } bool Serial::is_opened() { return status; } bool Serial::read(char * buff, int len) { #ifdef _WINDOWS LPDWORD get=NULL; return ReadFile(handle, buff, len, get, NULL); #elif defined(__linux__) return UART0_Recv(handle, buff, len); #endif } bool Serial::write(const char * buff, const int len) { #ifdef _WINDOWS /*LPDWORD get = NULL; debug << "Writting ...." << endl; bool tget=WriteFile(handle, buff, len, get, NULL); debug << "Success!" << endl; return tget;*/ return true; #elif defined(__linux__) return UART0_Send(handle, buff, len); #endif }
[ "羿龙吟风" ]
羿龙吟风
8fa3b567956535463c5c7257dea72e4054ee6398
3544b08313d9b3e10d717d865c44ee381d4c64e1
/Eurotherm/Eurotherm.cpp
380e7fc9e4b0960d93abb0047ca5f78e9bb943de
[]
no_license
turbotom777/DLTS
b01625a93e3798dbfa1c8e9d78305c012a64dd9c
18d045560760311ae04d33261ed1f57f0be47d0f
refs/heads/master
2021-04-28T02:35:32.155353
2018-02-19T21:02:14
2018-02-19T21:02:14
122,118,643
0
0
null
null
null
null
UTF-8
C++
false
false
1,563
cpp
// Eurotherm.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "Eurotherm.h" #include "ComHandler.h" #include "FileWriter.h" #include ".\tempcontroller.h" #include "conio.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // The one and only application object CWinApp theApp; CWriter console; using namespace std; int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]) { int nRetCode = 0; // initialize MFC and print and error on failure if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0)) { // TODO: change error code to suit your needs cerr << _T("Fatal Error: MFC initialization failed") << endl; nRetCode = 1; } else { console.writeln("DLTS Messsoftware / Temperatursteuerung Version 0.1"); console.writeln("Copyright 2005 T. Schwaiger"); console.writeln(""); console.writeln("Please press 'c' to terminate program while execution!"); console.writeln("Please do NOT stop execution with key 'CRTL + c'!"); console.writeln("Please press ENTER to start the program"); int ch = _getch(); if (ch != 13){ console.writeln("Will terminate program"); return nRetCode; } TempController tempController; int TStart = 25; int TEnd = 35; int TStep = 10; int THold = 20; // sec tempController.start(TStart, TEnd, TStep, THold); console.writeln("Please press any key to close window"); _getch(); } return nRetCode; }
[ "31222466+turbotom777@users.noreply.github.com" ]
31222466+turbotom777@users.noreply.github.com
83d0a92dd932fd2bb4571a7890c2cfa607f68085
47f9c8c46cb7a43bc2d390c7f1039ad8ffbc339f
/src_mod/public/IGameUIFuncs.h
31eb269d6acc0860e57e7a1d9a0d1098c9ee8353
[]
no_license
SourceEnginePlayground/source-sdk-2004
4135e00b06d8491baf174d19897950c40ef6112c
962ba835716d3e6d778054ab3fb4534bf3b35e1a
refs/heads/master
2023-03-27T15:04:00.381752
2021-03-24T06:42:27
2021-03-24T06:42:27
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
948
h
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #ifndef IGAMEUIFUNCS_H #define IGAMEUIFUNCS_H #ifdef _WIN32 #pragma once #endif #include "vgui/keycode.h" class IGameUIFuncs { public: virtual bool IsKeyDown( char const *keyname, bool& isdown ) = 0; virtual const char *Key_NameForKey( int keynum ) = 0; virtual const char *Key_BindingForKey( int keynum ) = 0; virtual vgui::KeyCode GetVGUI2KeyCodeForBind( const char *bind ) = 0; virtual void GetVideoModes( struct vmode_s **liststart, int *count ) = 0; virtual void SetFriendsID( uint friendsID, const char *friendsName ) = 0; virtual void GetDesktopResolution( int &width, int &height ) = 0; }; #define VENGINE_GAMEUIFUNCS_VERSION "VENGINE_GAMEUIFUNCS_VERSION004" #endif // IGAMEUIFUNCS_H
[ "jeremy.lorelli.1337@gmail.com" ]
jeremy.lorelli.1337@gmail.com
1b30b614abbf4dc4990d6bd57a32654b310e0eca
d444f1a6c7db7b6e4766fe47a2c2419123375a60
/SpriteSystemView.h
f2ae9b9c7d11ff89ecfb7647b5bd5382d8fec583
[]
no_license
MCPGNZ/engine
789adfc44aae2a5ebc070f03855a7392ed0c4dfb
4e8770f88a4bcd453672e08cdd124b85f924a181
refs/heads/master
2021-01-21T18:53:28.052352
2017-05-28T20:31:56
2017-05-28T20:31:56
92,091,986
0
0
null
null
null
null
UTF-8
C++
false
false
182
h
#pragma once #include "WindowView.h" #include "SpriteView.h" namespace pk { class SpriteSystemView { public: static void render(SpriteSystem& source); }; }
[ "daniel.w.poke@hotmail.com" ]
daniel.w.poke@hotmail.com
1d67182a78d97cb21560d630bdfd9dca3fbddac4
8206f93cbae3ffbf66de94a87fcb70ce5ba4e197
/src/hard_config.hxx
2b94aa027cdd9b7d6095be74f9d4a0d98bbd8992
[]
no_license
ivokabel/PG3Render
0409ae831c6f0d691cb08056d7f61961c4ef6ded
573a7abf611151be566eef69e79bab649c00724f
refs/heads/master
2020-03-10T13:58:33.171583
2018-07-04T11:14:22
2018-07-04T11:14:22
129,413,788
6
0
null
null
null
null
UTF-8
C++
false
false
788
hxx
#pragma once /////////////////////////////////////////////////////////////////////////////////////////////////// // Hard-wired settings /////////////////////////////////////////////////////////////////////////////////////////////////// //#define PG3_RUN_UNIT_TESTS_INSTEAD_OF_RENDERER //#define PG3_COMPUTE_AND_PRINT_RENDERER_INTROSPECTION #define PG3_COMPUTE_AND_PRINT_EM_STEERABLE_STATISTICS #define PG3_USE_DOUBLE_FRAMEBUFFER //#define PG3_USE_ART_FRESNEL #define PG3_USE_MITSUBA_FRESNEL #define PG3_USE_ENVMAP_SIMPLE_SPHERICAL_SAMPLER //#define PG3_USE_ENVMAP_STEERABLE_SAMPLER #define PG3_USE_HIERARCHICAL_1D_DISTRIBUTION //#define PG3_USE_EM_MORTON_MAPPING //#define PG3_USE_BALANCE_MIS_HEURISTIC #define PG3_USE_POWER_MIS_HEURISTIC //#define PG3_WWL_USE_AUX_DEBUG_PARAMS
[ "ivo.pavlik@gmail.com" ]
ivo.pavlik@gmail.com
4ebc5670071fe01465ffb90dd059b5dc989bdd9d
8dc1626b90a4a2047868e7131e1d783445f84d8e
/6-GeometryShaders/src/Managers/DisplaceShaderManager.cpp
b16df5e0f1095ace34b4f8420c572373ea1585ff
[]
no_license
icq4ever/ShadersLibrary
b8131dc08059e966ad753bcd41f159dba23acb2b
2e7a206a7d199f20f373f2f4fddc528eeafda39c
refs/heads/master
2021-06-26T18:14:12.646552
2021-04-09T13:18:28
2021-04-09T13:18:28
223,934,129
0
0
null
2019-11-25T11:37:13
2019-11-25T11:37:13
null
UTF-8
C++
false
false
808
cpp
// // ShaderManager.cpp // multilight // // Created by Leo on 10/12/16. // // #include "DisplaceShaderManager.h" //-------------------------------------------------------------- void DisplaceShaderManager::begin(){ shader.begin(); shader.setUniform1f("maxHeight", maxHeight); if (tex != NULL){ shader.setUniformTexture("texColor", (*tex), 1); tex->bind(); } if (bumpTex != NULL){ shader.setUniformTexture("texBumpMap", (*bumpTex), 2); bumpTex->bind(); } setupLights(); setupMaterial(); } //-------------------------------------------------------------- void DisplaceShaderManager::end(){ shader.end(); if (tex != NULL) tex->unbind(); if (bumpTex != NULL) bumpTex->unbind(); }
[ "icq4ever@gmail.com" ]
icq4ever@gmail.com
e0bafb496802c3601183ff96ac77c84b88fd2940
f33b46dde55500f8e3cb42ff856dc0b24287179e
/ComputerVis/Project_3/Scale.cpp
c15000b14645d6a4eecfdb992dcb3ee78c1b5966
[]
no_license
BrianGoga/School
63acc490757c9f46a20f1429072d30c805f8c069
81c2f4ad0ab52685f55dcf73e2ca20bdd9b12dd5
refs/heads/master
2021-01-21T08:06:06.658223
2015-11-23T23:55:55
2015-11-23T23:55:55
37,559,753
0
0
null
null
null
null
UTF-8
C++
false
false
96
cpp
#include "Image.cpp" struct Scale { float SigmaInit; float SigmaDer; ImageP5 Scaleimage; };
[ "goabrian@gmail.com" ]
goabrian@gmail.com
fa3f6d672a41472c67e8b59eaabb8449ab5cc2d0
9241d6ca884b63e0abae80f13d6bbf7eeb818c1e
/FastCat/Dependencies/maya/tbb/internal/_tbb_windef.h
35651f5d9a7018144f56265cc7c3c20b506aa6a4
[]
no_license
AlexMiller12/FastCatVS2013
100022c6ed5206903bc10c65e05cebf3a79c4f45
b93df56cc10e109e9f9b62ccd0cad5fc8be983ae
refs/heads/master
2021-01-13T00:48:59.076862
2016-05-06T20:17:48
2016-05-06T20:17:48
52,799,609
3
2
null
null
null
null
UTF-8
C++
false
false
2,744
h
/* Copyright 2005-2014 Intel Corporation. All Rights Reserved. The source code contained or described herein and all documents related to the source code ("Material") are owned by Intel Corporation or its suppliers or licensors. Title to the Material remains with Intel Corporation or its suppliers and licensors. The Material is protected by worldwide copyright laws and treaty provisions. No part of the Material may be used, copied, reproduced, modified, published, uploaded, posted, transmitted, distributed, or disclosed in any way without Intel's prior express written permission. No license under any patent, copyright, trade secret or other intellectual property right is granted to or conferred upon you by disclosure or delivery of the Materials, either expressly, by implication, inducement, estoppel or otherwise. Any license under such intellectual property rights must be express and approved by Intel in writing. */ #ifndef __TBB_tbb_windef_H #error Do not #include this internal file directly; use public TBB headers instead. #endif /* __TBB_tbb_windef_H */ // Check that the target Windows version has all API calls requried for TBB. // Do not increase the version in condition beyond 0x0500 without prior discussion! #if defined(_WIN32_WINNT) && _WIN32_WINNT<0x0501 #error TBB is unable to run on old Windows versions; _WIN32_WINNT must be 0x0501 or greater. #endif #if !defined(_MT) #error TBB requires linkage with multithreaded C/C++ runtime library. \ Choose multithreaded DLL runtime in project settings, or use /MD[d] compiler switch. #endif // Workaround for the problem with MVSC headers failing to define namespace std namespace std { using ::size_t; using ::ptrdiff_t; } #define __TBB_STRING_AUX(x) #x #define __TBB_STRING(x) __TBB_STRING_AUX(x) // Default setting of TBB_USE_DEBUG #ifdef TBB_USE_DEBUG # if TBB_USE_DEBUG # if !defined(_DEBUG) # pragma message(__FILE__ "(" __TBB_STRING(__LINE__) ") : Warning: Recommend using /MDd if compiling with TBB_USE_DEBUG!=0") # endif # else # if defined(_DEBUG) # pragma message(__FILE__ "(" __TBB_STRING(__LINE__) ") : Warning: Recommend using /MD if compiling with TBB_USE_DEBUG==0") # endif # endif #endif #if (__TBB_BUILD || __TBBMALLOC_BUILD) && !defined(__TBB_NO_IMPLICIT_LINKAGE) #define __TBB_NO_IMPLICIT_LINKAGE 1 #endif #if _MSC_VER #if !__TBB_NO_IMPLICIT_LINKAGE #ifdef __TBB_LIB_NAME #pragma comment(lib, __TBB_STRING(__TBB_LIB_NAME)) #else #ifdef _DEBUG #pragma comment(lib, "tbb_debug.lib") #else #pragma comment(lib, "tbb.lib") #endif #endif #endif #endif
[ "alexmiller12@yahoo.com" ]
alexmiller12@yahoo.com
24ce8029258c4ec67ac31a4842b82ab954207cf0
bcf138c82fcba9acc7d7ce4d3a92618b06ebe7c7
/rdr2/0xF232C2C546AC16D0.cpp
dd1296ade1006984c67fbc4490c8c71903bb3501
[]
no_license
DeepWolf413/additional-native-data
aded47e042f0feb30057e753910e0884c44121a0
e015b2500b52065252ffbe3c53865fe3cdd3e06c
refs/heads/main
2023-07-10T00:19:54.416083
2021-08-12T16:00:12
2021-08-12T16:00:12
395,340,507
1
0
null
null
null
null
UTF-8
C++
false
false
1,078
cpp
// saint_denis1.ysc @ L97420 bool func_2621(char[4] cParam0) { if (func_195(iLocal_1759, 268435456)) { return true; } if (!ANIMSCENE::_0x0DF57F86FE71DBE5(uLocal_1769[10], "Pl_Dutch_Callover") && !ANIMSCENE::_0x23E33CB9F4A3F547(uLocal_1769[10], "Pl_Dutch_Callover")) { ANIMSCENE::_0xDF7B5144E25CD3FE(uLocal_1769[10], "Pl_Dutch_Callover"); if (!ANIMSCENE::_IS_ANIM_SCENE_LOADED(uLocal_1769[10], true, false)) { if (!ANIMSCENE::_IS_ANIM_SCENE_LOADING(uLocal_1769[10], true)) { ANIMSCENE::LOAD_ANIM_SCENE(uLocal_1769[10]); } } } else if (ANIMSCENE::_0x23E33CB9F4A3F547(uLocal_1769[10], "Pl_Dutch_Callover")) { ANIMSCENE::_SET_ANIM_SCENE_PLAYBACK_LIST_BOOL(uLocal_1769[10], "Pl_Dutch_Callover", true); if (!ANIMSCENE::_IS_ANIM_SCENE_STARTED(uLocal_1769[10], false)) { ANIMSCENE::START_ANIM_SCENE(uLocal_1769[10]); } AUDIO::_0xF232C2C546AC16D0("NBD1_IG8_CALL"); if (!func_195(iLocal_1759, 268435456)) { func_408(&iLocal_1759, 268435456); } return true; } return false; }
[ "jesper15fuji@live.dk" ]
jesper15fuji@live.dk
f2a965af98b26adfde6de980151d0f48355af7e0
d15fb7b8d121bed1f43237b718e14ee7286f7a40
/Lists/lab4.cpp
02e60ef14da2ebf71af28034ea926d3783dfa6c6
[]
no_license
anamariaradu0/Data-Structures-Cpp
414754a18a857852cbbf90ffda58622fe33ba740
f8c63dc485c4812dbddebb290d1d8662805c2383
refs/heads/master
2020-05-20T04:38:02.085301
2019-10-08T18:04:10
2019-10-08T18:04:10
185,386,572
0
0
null
null
null
null
UTF-8
C++
false
false
648
cpp
#include <iostream> #include "DoublyLinkedList.h" #include "Stack.h" #include "Queue.h" #include "Quetack.h" int main() { /* Stack<int, 100> stiva; std::cout << stiva.isEmpty() << '\n'; stiva.push(10); std::cout << stiva.peek() << '\n' << stiva.isEmpty() << " " << stiva.size() << '\n'; stiva.pop(); std::cout << stiva.peek(); */ Quetack<int, 100> coada; std::cout << coada.isEmpty() << '\n'; coada.enqueue(10); coada.enqueue(5); std::cout << coada.front() << '\n' << coada.isEmpty() << '\n' ; coada.dequeue(); std::cout << coada.front(); return 0; }
[ "noreply@github.com" ]
anamariaradu0.noreply@github.com
1bf3e74bafb6aa411e11b7d108e0d656ac40ea71
52a4095bc25c9da44597eef788c77711d8ad17cb
/minimgio/src/minimgio_ancient.cpp
c0fdc67f3cfec899f702bae9ce78e6e02ee1a1d2
[ "BSD-3-Clause" ]
permissive
SmartEngines/minimg_interfaces
ab998ea2e7cb1a98f9195b536879744fc5355f42
b9276f4d800a7d4563c7e1aaa08ef927bbccb918
refs/heads/main
2023-06-15T19:17:51.715790
2021-07-14T08:08:32
2021-07-14T08:08:32
385,863,316
5
1
null
null
null
null
UTF-8
C++
false
false
7,883
cpp
/* Copyright 2021 Smart Engines Service LLC 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. */ #ifdef _MSC_VER #pragma warning(disable : 4996) #endif #include <minimgio/minimgio.h> #include <minimgio/minimgio.hpp> #include <cstdio> #include <cmath> #include <cstring> #include <algorithm> // std::min #include <ctype.h> #include <minbase/minresult.h> #include <minutils/smartptr.h> #include "minimgiodevice.h" #include "utils.h" #include "pack.h" #ifdef _WIN32 #define stricmp _stricmp #else #include <strings.h> // POSIX #define stricmp strcasecmp #endif typedef enum _FileLocation { inFileSystem, inMemory, inDevice } FileLocation; static FileLocation DeduceFileLocation( const char *fileName) { const char kMemoryLocationPrefix[] = "mem://"; const char kDeviceLocationPrefix[] = "dev://"; if (!strncmp(fileName, kMemoryLocationPrefix, strlen(kMemoryLocationPrefix))) return inMemory; else if (!strncmp(fileName, kDeviceLocationPrefix, strlen(kDeviceLocationPrefix))) return inDevice; else return inFileSystem; } struct UniversalBinaryStream { UniversalBinaryStream() : stream(NULL) {} MinResult initialize(const char *pFileName, const FileLocation fileLocation ) { if (fileLocation == inFileSystem) this->stream = new minimgio::BinaryFileStream(pFileName); else if (fileLocation == inMemory) { uint8_t *ptr = 0; size_t size = 0; MR_PROPAGATE_ERROR(ExtractMemoryLocation(pFileName, &ptr, &size)); this->stream = new minimgio::BinaryMemoryReadonlyStream(ptr, size); } else { return MR_INTERNAL_ERROR; } return MR_SUCCESS; } operator minimgio::BinaryStream &() const { return *this->stream; } ~UniversalBinaryStream() { delete stream; } private: minimgio::BinaryStream *stream; }; namespace minimgio { namespace internal { #define MIN_DECLARE_INTERNAL(MODULE_NAME) \ MinResult GetNumPages ## MODULE_NAME( \ int &pages, \ BinaryStream &stream); \ MinResult GetProps ## MODULE_NAME( \ MinImg &img, \ ExtImgProps *p_props, \ BinaryStream &stream, \ int page); \ MinResult Load ## MODULE_NAME( \ MinImg const &img, \ BinaryStream &stream, \ int page); \ MinResult Save ## MODULE_NAME( \ BinaryStream &stream, \ const MinImg &img, \ const ExtImgProps *p_props, \ int page); #ifdef WITH_TIFF MIN_DECLARE_INTERNAL(Tiff) #endif #ifdef WITH_JPEG MIN_DECLARE_INTERNAL(Jpeg) #endif #ifdef WITH_PNG MIN_DECLARE_INTERNAL(Png) #endif #ifdef WITH_WEBP MIN_DECLARE_INTERNAL(WebP) #endif MIN_DECLARE_INTERNAL(Lst) #undef MIN_DECLARE_INTERNAL }} MINIMGIO_API int GetMinImageFilePages( const char *pFileName) { if (!pFileName) return MR_CONTRACT_VIOLATION; const FileLocation fileLocation = DeduceFileLocation(pFileName); int pages = -1; if (fileLocation == inDevice) { MR_PROPAGATE_ERROR(GetDevicePages(&pages, pFileName)); } else { UniversalBinaryStream stream; MR_PROPAGATE_ERROR(stream.initialize(pFileName, fileLocation)); MR_PROPAGATE_ERROR(static_cast<minimgio::BinaryStream&>(stream). initialize(MIS_READONLY)); MR_PROPAGATE_ERROR(minimgio::GetNumPages(pages, stream)); } return pages; } MINIMGIO_API int GetMinImagePageName( char *pPageName, int pageNameSize, const char *pFileName, int page) { const FileLocation fileLocation = DeduceFileLocation(pFileName); if (fileLocation == inDevice) return GetDevicePageName(pPageName, pageNameSize, pFileName, page); minimgio::BinaryFileStream stream(pFileName); return minimgio::GetPageName(pPageName, pageNameSize, stream, page); } MINIMGIO_API int GetMinImageFileProps( MinImg *pImg, const char *pFileName, int page) { return GetMinImageFilePropsEx(pImg, NULL, pFileName, page); } MINIMGIO_API int GetMinImageFilePropsEx( MinImg *pImg, ExtImgProps *pProps, const char *pFileName, int page) { if (!pFileName || (!pProps && !pImg)) return MR_CONTRACT_VIOLATION; const FileLocation fileLocation = DeduceFileLocation(pFileName); if (fileLocation == inDevice) return GetDevicePropsEx(pImg, pProps, pFileName); UniversalBinaryStream uni_strem; MR_PROPAGATE_ERROR(uni_strem.initialize(pFileName, fileLocation)); return minimgio::GetFileProps(*pImg, uni_strem, pProps, page); } MINIMGIO_API int LoadMinImage( const MinImg *pImg, const char *pFileName, int page) { if (!pFileName || !pImg) return MR_CONTRACT_VIOLATION; const FileLocation fileLocation = DeduceFileLocation(pFileName); if (fileLocation == inDevice) return LoadDevice(pImg, pFileName); UniversalBinaryStream uni_strem; MR_PROPAGATE_ERROR(uni_strem.initialize(pFileName, fileLocation)); return minimgio::Load(*pImg, uni_strem, page); } #ifndef STRICT_DATA_CONTAINMENT MINIMGIO_API int SaveMinImage( const char *pFileName, const MinImg *pImg, int page) { return SaveMinImageEx(pFileName, pImg, NULL, page); } MINIMGIO_API int SaveMinImageEx( const char *pFileName, const MinImg *pImg, const ExtImgProps *pProps, int page) { const FileLocation fileLocation = DeduceFileLocation(pFileName); if (fileLocation == inDevice) return SaveDeviceEx(pFileName, pImg, pProps); ImgFileFormat iff = pProps ? pProps->iff : IFF_UNKNOWN; if (iff == IFF_UNKNOWN) iff = GuessImageFileFormatByExtension(pFileName); if (iff == IFF_UNKNOWN) return MR_CONTRACT_VIOLATION; minimgio::BinaryFileStream stream(pFileName); return minimgio::Save(stream, *pImg, iff, pProps, page); } #endif // #ifndef STRICT_DATA_CONTAINMENT MINIMGIO_API int PackMinImage( const MinImg *p_dst_image, const MinImg *p_src_image, uint8_t level) { if (p_src_image == NULL || p_dst_image == NULL) return MR_CONTRACT_VIOLATION; return minimgio::Pack(*p_dst_image, *p_src_image, level); } MINIMGIO_API int UnpackMinImage( const MinImg *p_dst_image, const MinImg *p_src_image) { if (p_src_image == NULL || p_dst_image == NULL) return MR_CONTRACT_VIOLATION; return minimgio::Unpack(*p_dst_image, *p_src_image); }
[ "kbulatov@smartengines.com" ]
kbulatov@smartengines.com
fc4db948b83294d2fed1bd73344ba581ae0fa4bc
f6bf4099ba7fb4e6037f3116e3f52b6e1f002032
/imageFeatures/basic/featuresFile.cpp
d1fc805a69f73aee6719a7db860cb11a568d44d1
[]
no_license
laura-burdick/imagesPersonality
abcc249c2545d3215ae2e78e3175d7c19dfd9e70
8db50f25d3217d8bae48d2232daabdb933f8793b
refs/heads/master
2020-03-08T11:26:13.147322
2018-04-09T18:02:40
2018-04-09T18:02:40
128,097,441
1
0
null
null
null
null
UTF-8
C++
false
false
5,275
cpp
/** @author Wendlandt Laura <wenlaura@umich.edu> */ #include "featuresFile.h" #include <boost/filesystem.hpp> #include <iostream> #include <sstream> using std::stringstream; using std::cout; using std::to_string; using std::endl; using namespace boost::filesystem; FeaturesFile::FeaturesFile(string fileName) : brightness(true), saturation(true), rgb(true), lines(true), circles(true), pleasureArousalDominance(true), initialized(false), threshold(DEFAULT_LINES_THRESHOLD), minLineLength(DEFAULT_LINES_MINLINELENGTH), maxLineGap(DEFAULT_LINES_MAXLINEGAP), deviation(DEFAULT_LINES_DEVIATION), minDist(DEFAULT_CIRCLES_MINDIST), param1(DEFAULT_CIRCLES_PARAM1), param2(DEFAULT_CIRCLES_PARAM2), visualizeLines(false), visualizeCircles(false) { fout.open(fileName); if(fout.fail()) { throw string("Failed to create new file: " + fileName + "\n"); } } FeaturesFile::~FeaturesFile() { fout.close(); } void FeaturesFile::init() { if(initialized) { return; } else { initialized = true; } vector<string> features; features.push_back("file"); if(brightness) { features.push_back("brightness_mean"); features.push_back("brightness_stddev"); } if(saturation) { features.push_back("saturation_mean"); features.push_back("saturation_stddev"); } if(pleasureArousalDominance) { features.push_back("pleasure"); features.push_back("arousal"); features.push_back("dominance"); } if(rgb) { features.push_back("red_%"); features.push_back("blue_%"); features.push_back("green_%"); } if(lines) { features.push_back("static_lines_%"); features.push_back("dynamic_lines_%"); } if(circles) { features.push_back("num_circles"); } for(int i=0; i<features.size(); ++i) { fout << features[i]; if(i != features.size()-1) { fout << ", "; } } fout << endl; } void FeaturesFile::outputImage(Image& img) { init(); vector<string> features; features.push_back(img.getName()); if(brightness || saturation) { vector<double> results = img.brightnessAndSaturation(); if(brightness) { features.push_back(to_string(static_cast<long double>(results[0]))); //throws compiler errors on Flux unless result is converted to long double features.push_back(to_string(static_cast<long double>(results[1]))); } if(saturation) { features.push_back(to_string(static_cast<long double>(results[2]))); features.push_back(to_string(static_cast<long double>(results[3]))); } } if(pleasureArousalDominance) { vector<double> results = img.pleasureArousalDominance(); for(int i=0; i<results.size(); ++i) { features.push_back(to_string(static_cast<long double>(results[i]))); } } if(rgb) { vector<double> results = img.rgbPercentages(); for(int i=0; i<results.size(); ++i) { features.push_back(to_string(static_cast<long double>(results[i]))); } } if(lines) { vector<double> results; if(visualizeLines) { string outputFile = img.getImagePath().substr(0,img.getImagePath().find_last_of('/')+1) + img.getName() + "_lines" + img.getImagePath().substr(img.getImagePath().find_last_of('.')); results = img.drawLines(outputFile,threshold,minLineLength,maxLineGap,deviation); } else { results = img.lines(threshold,minLineLength,maxLineGap,deviation); } for(int i=0; i<results.size(); ++i) { features.push_back(to_string(static_cast<long double>(results[i]))); } } if(circles) { int result; if(visualizeCircles) { string outputFile = img.getImagePath().substr(0,img.getImagePath().find_last_of('/')+1) + img.getName() + "_circles" + img.getImagePath().substr(img.getImagePath().find_last_of('.')); result = img.drawCircles(outputFile,minDist,param1,param2); } else { result = img.circles(minDist,param1,param2); } features.push_back(to_string(static_cast<long long int>(result))); } for(int i=0; i<features.size(); ++i) { fout << features[i]; if(i != features.size()-1) { fout << ", "; } } fout << endl; } void FeaturesFile::outputImagesInDirectory(string& root) { this->root = root; if(!is_directory(root)) { try { string name = root.substr(root.find_last_of('/')+1,root.substr(root.find_last_of('/')).find('.')-1); Image img(root,name); outputImage(img); } catch(string s) { cout << "Problem with image " << root << endl; cout << s << endl; cout << "Skipping image and moving on" << endl; } return; } //Root is a directory int completed = 0; for(directory_iterator it = directory_iterator(root); it != directory_iterator(); ++it) { try { string name = it->path().filename().string().substr(0,it->path().filename().string().find('.')); Image img(it->path().string(),name); outputImage(img); } catch(string s) { cout << "Problem with image " << it->path().string() << endl; cout << s << endl; cout << "Skipping image and moving on" << endl; } completed += 1; cout << "progress: " << completed << "\n"; } }
[ "wenlaura@umich.edu" ]
wenlaura@umich.edu
67a84d071a92c7298c012472cb8729371f59a6b1
7c900bb997edc44cc9f24b98b35452109b3365d6
/fridguino.ino
9efd249533f898926b549d286e17197da2db9e4c
[]
no_license
idanbenzvi/Fridguino
84f7a623373a9da21642565d7276e35304c0ac8f
cb8725a5894fce21d5dba7f0d9313f81ef8144cd
refs/heads/master
2020-04-08T17:26:14.969949
2018-12-03T09:58:52
2018-12-03T09:58:52
159,566,820
0
0
null
null
null
null
UTF-8
C++
false
false
3,529
ino
#include <ESP8266WiFi.h> #include "AlertMe.h" // This includes all of the references to WiFiManager and ArduinoJSON that we need #include <TroykaDHT.h> AlertMe alert; DHT dht(4, DHT21); const uint8_t config_pin = 12; const double CRITCAL_TEMP = 10; const double CRITCAL_DELTA = 3; const int DHT_ERROR = 999; String to_email = "etay1283@gmail.com"; // The email address to send the message to String to_sms = "5551234567@carriersmsportal.com"; // Look up your carrier's Email-to-SMS gateway here: https://martinfitzpatrick.name/list-of-email-to-sms-gateways/ String subject_line = "Fridge Temprature Alert"; String message; double previousTemp; /** * Fridguino by Idan Ben Zvi and Itay Ceder (c) 12/2018 * The sketch sets up a wifi access point initially to get mail and wifi credentials. * After setup the device will constantly poll for the temprature once every 15 minutes. * If the temprature rises above a specified threshold a message will be sent. * TODO: * add derivative calculations and set a bar for alerts * add auto reconnect ability * add SIM Gprs capability */ void setup() { dht.begin(); Serial.begin(115200); // the speed in which the serial USB connection is set delay(200); // We start by connecting to a WiFi network pinMode(config_pin,INPUT_PULLUP); if(config_pin == LOW){ // Short pin to GND for config AP alert.config(); } alert.debug(true); // uncomment for debug/SMTP data Serial.print("\nConnecting to WIFI/SMTP..."); alert.connect(); // Connect to WiFi, then test connect to SMTP server. // If we fail with either, or they aren't configured, // host an AP portal for configuration. // alert.connect(true) prints WiFi debug info Serial.println("Connected!"); } double measureTemprature() { dht.read(); switch(dht.getState()) { case DHT_OK: Serial.print("Temperature = "); Serial.print(dht.getTemperatureC()); Serial.println(" C \t"); Serial.print("Humidity = "); Serial.print(dht.getHumidity()); Serial.println(" %"); return dht.getTemperatureC(); case DHT_ERROR_CHECKSUM: return DHT_ERROR; case DHT_ERROR_TIMEOUT: return DHT_ERROR; case DHT_ERROR_NO_REPLY: return DHT_ERROR; } } void sendNotificaiton(String message) { Serial.print("Sending Email: " + message); alert.send(subject_line,message,to_email); } void loop() { while(true) { delay(60 * 15 * 1000); int retryAttemps = 3; double currTemprature; do { currTemprature = measureTemprature(); retryAttemps--; } while (currTemprature != DHT_ERROR && retryAttemps > 0); double currentDeltaTemp = currTemprature - previousTemp; if (currTemprature == DHT_ERROR) { message = "Device " + String(ESP.getChipId()) + " Error: no temprature response return, sensor is broken"; sendNotificaiton(message); } else if (currentDeltaTemp > CRITCAL_DELTA){ message = "Device " + String(ESP.getChipId()) + " : Delta Temprature is above trashold! the current temprature is " + currTemprature; sendNotificaiton(message); } else if(currTemprature > CRITCAL_TEMP) { message = "Device " + String(ESP.getChipId()) + " : Temprature is above trashold! the current temprature is " + currTemprature; sendNotificaiton(message); } if (currTemprature != DHT_ERROR) { previousTemp = currTemprature; } } }
[ "noreply@github.com" ]
idanbenzvi.noreply@github.com
6abc4099175c97bd1ae42184cb46c16bc0e905ab
4ca615c72ee4e28199ff1431b24dd6b68b97b14c
/shader.cpp
b3ce1e9a801a9b56bc0c1a02c122dee12546fa4c
[]
no_license
abhikjain360/opengl-tutorial
9585762371e08eaf5e843725e5b33f95ed59e313
4ddccff75625b918163dd87b30e2d5d1bae4457f
refs/heads/master
2022-11-10T16:47:12.550080
2020-06-21T12:44:22
2020-06-21T12:44:22
273,512,430
0
0
null
null
null
null
UTF-8
C++
false
false
3,053
cpp
#include "shader.h" #include "renderer.h" #include <iostream> #include <sstream> #include <fstream> shader::shader(const std::string& filepath) : m_filepath(filepath), m_rendererID(0) { shader_source source = parse_shader(); m_rendererID = create_shader(source.vertex_shader, source.fragment_shader); } shader::~shader() { GLCALL( glDeleteProgram(m_rendererID) ); } shader_source shader::parse_shader() { std::ifstream file(m_filepath); enum class shader_type { NONE = -1, VERTEX = 0, FRAGMENT = 1 }; std::stringstream ss[2]; std::string line; shader_type type = shader_type::NONE; while(getline(file, line)) { if (line.find("// shader") != std::string::npos) { if (line.find("vertex") != std::string::npos) type = shader_type::VERTEX; else if (line.find("fragment") != std::string::npos) type = shader_type::FRAGMENT; } else { ss[(int)type] << line << "\n"; } } return { ss[0].str(), ss[1].str() }; } unsigned int shader::compile_shader(unsigned int type, const std::string& source) { GLCALL( unsigned int id = glCreateShader(type) ); // use getString if source actually doesn't exist as just a pointer // memory may not exist even if pointer points const char* src = source.c_str(); GLCALL( glShaderSource(id, 1, &src, nullptr) ); GLCALL( (glCompileShader(id)); ) int result; GLCALL( glGetShaderiv(id, GL_COMPILE_STATUS, &result) ); if (result == GL_FALSE) { int lenght; GLCALL( glGetShaderiv(id, GL_INFO_LOG_LENGTH, &lenght) ); char* message = (char*)alloca(lenght * sizeof(char)); GLCALL( glGetShaderInfoLog(id, lenght, &lenght, message) ); std::cout << "Failed to compile " << (type == GL_VERTEX_SHADER ? "vertex" : "fragment") << std::endl; std::cout << message << std::endl; GLCALL( glDeleteShader(id) ); return 0; } return id; } unsigned int shader::create_shader(const std::string& vertex_shader, std::string& fragment_shader) { GLCALL( unsigned int program = glCreateProgram() ); unsigned int vs = compile_shader(GL_VERTEX_SHADER, vertex_shader); unsigned int fs = compile_shader(GL_FRAGMENT_SHADER, fragment_shader); GLCALL( glAttachShader(program, vs) ); GLCALL( glAttachShader(program, fs) ); GLCALL( glLinkProgram(program) ); GLCALL( glValidateProgram(program) ); GLCALL( glDeleteShader(vs) ); GLCALL( glDeleteShader(fs) ); return program; } void shader::bind() const { GLCALL( glUseProgram(m_rendererID) ); } void shader::unbind() const { GLCALL( glUseProgram(0) ); } int shader::get_uniform_location(const std::string& name) { if (m_uniform_location_cache.find(name) != m_uniform_location_cache.end()) return m_uniform_location_cache[name]; int location = glGetUniformLocation(m_rendererID, name.c_str()); if (location == -1) std::cout << "Warning: uniform " << name << "doesn't exist" << std::endl; m_uniform_location_cache[name] = location; return location; } void shader::set_uniform4f(const std::string& name, float v0, float v1, float v2, float v3) { GLCALL( glUniform4f(get_uniform_location(name), v0, v1, v2, v3) ); }
[ "abhikjain360@gmail.com" ]
abhikjain360@gmail.com
381f78f99c1c752634bda9df9085ce39177123b3
02907c91bb8703ca8b307a087b351f8573f90bad
/src/qt/guiutil.h
ec6da043d32053cacce58d3faaf6c08a24a4bb01
[ "MIT" ]
permissive
1UP-Coin/1UP
636efee7b55570f3cfb1769f3a6399f63e7d2828
eb41397f977b7bcc4f59dbbb939fa04bbb891bca
refs/heads/master
2021-09-11T21:07:30.002481
2018-04-12T12:48:42
2018-04-12T12:48:42
115,657,451
6
14
MIT
2018-01-05T15:16:57
2017-12-28T20:32:32
C++
UTF-8
C++
false
false
8,222
h
// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_QT_GUIUTIL_H #define BITCOIN_QT_GUIUTIL_H #include "amount.h" #include <QEvent> #include <QHeaderView> #include <QMessageBox> #include <QObject> #include <QProgressBar> #include <QString> #include <QTableView> #include <QTableWidget> #include <boost/filesystem.hpp> class QValidatedLineEdit; class SendCoinsRecipient; QT_BEGIN_NAMESPACE class QAbstractItemView; class QDateTime; class QFont; class QLineEdit; class QUrl; class QWidget; QT_END_NAMESPACE /** Utility functions used by the 1UP Qt UI. */ namespace GUIUtil { // Create human-readable string from date QString dateTimeStr(const QDateTime& datetime); QString dateTimeStr(qint64 nTime); // Render 1UP addresses in monospace font QFont bitcoinAddressFont(); // Set up widgets for address and amounts void setupAddressWidget(QValidatedLineEdit* widget, QWidget* parent); void setupAmountWidget(QLineEdit* widget, QWidget* parent); // Parse "1up:" URI into recipient object, return true on successful parsing bool parseBitcoinURI(const QUrl& uri, SendCoinsRecipient* out); bool parseBitcoinURI(QString uri, SendCoinsRecipient* out); QString formatBitcoinURI(const SendCoinsRecipient& info); // Returns true if given address+amount meets "dust" definition bool isDust(const QString& address, const CAmount& amount); // HTML escaping for rich text controls QString HtmlEscape(const QString& str, bool fMultiLine = false); QString HtmlEscape(const std::string& str, bool fMultiLine = false); /** Copy a field of the currently selected entry of a view to the clipboard. Does nothing if nothing is selected. @param[in] column Data column to extract from the model @param[in] role Data role to extract from the model @see TransactionView::copyLabel, TransactionView::copyAmount, TransactionView::copyAddress */ void copyEntryData(QAbstractItemView* view, int column, int role = Qt::EditRole); void setClipboard(const QString& str); /** Get save filename, mimics QFileDialog::getSaveFileName, except that it appends a default suffix when no suffix is provided by the user. @param[in] parent Parent window (or 0) @param[in] caption Window caption (or empty, for default) @param[in] dir Starting directory (or empty, to default to documents directory) @param[in] filter Filter specification such as "Comma Separated Files (*.csv)" @param[out] selectedSuffixOut Pointer to return the suffix (file type) that was selected (or 0). Can be useful when choosing the save file format based on suffix. */ QString getSaveFileName(QWidget* parent, const QString& caption, const QString& dir, const QString& filter, QString* selectedSuffixOut); /** Get open filename, convenience wrapper for QFileDialog::getOpenFileName. @param[in] parent Parent window (or 0) @param[in] caption Window caption (or empty, for default) @param[in] dir Starting directory (or empty, to default to documents directory) @param[in] filter Filter specification such as "Comma Separated Files (*.csv)" @param[out] selectedSuffixOut Pointer to return the suffix (file type) that was selected (or 0). Can be useful when choosing the save file format based on suffix. */ QString getOpenFileName(QWidget* parent, const QString& caption, const QString& dir, const QString& filter, QString* selectedSuffixOut); /** Get connection type to call object slot in GUI thread with invokeMethod. The call will be blocking. @returns If called from the GUI thread, return a Qt::DirectConnection. If called from another thread, return a Qt::BlockingQueuedConnection. */ Qt::ConnectionType blockingGUIThreadConnection(); // Determine whether a widget is hidden behind other windows bool isObscured(QWidget* w); // Open debug.log void openDebugLogfile(); // Open 1up.conf void openConfigfile(); // Open masternode.conf void openMNConfigfile(); // Browse backup folder void showBackups(); // Replace invalid default fonts with known good ones void SubstituteFonts(const QString& language); /** Qt event filter that intercepts ToolTipChange events, and replaces the tooltip with a rich text representation if needed. This assures that Qt can word-wrap long tooltip messages. Tooltips longer than the provided size threshold (in characters) are wrapped. */ class ToolTipToRichTextFilter : public QObject { Q_OBJECT public: explicit ToolTipToRichTextFilter(int size_threshold, QObject* parent = 0); protected: bool eventFilter(QObject* obj, QEvent* evt); private: int size_threshold; }; /** * Makes a QTableView last column feel as if it was being resized from its left border. * Also makes sure the column widths are never larger than the table's viewport. * In Qt, all columns are resizable from the right, but it's not intuitive resizing the last column from the right. * Usually our second to last columns behave as if stretched, and when on strech mode, columns aren't resizable * interactively or programatically. * * This helper object takes care of this issue. * */ class TableViewLastColumnResizingFixer : public QObject { Q_OBJECT public: TableViewLastColumnResizingFixer(QTableView* table, int lastColMinimumWidth, int allColsMinimumWidth); void stretchColumnWidth(int column); private: QTableView* tableView; int lastColumnMinimumWidth; int allColumnsMinimumWidth; int lastColumnIndex; int columnCount; int secondToLastColumnIndex; void adjustTableColumnsWidth(); int getAvailableWidthForColumn(int column); int getColumnsWidth(); void connectViewHeadersSignals(); void disconnectViewHeadersSignals(); void setViewHeaderResizeMode(int logicalIndex, QHeaderView::ResizeMode resizeMode); void resizeColumn(int nColumnIndex, int width); private slots: void on_sectionResized(int logicalIndex, int oldSize, int newSize); void on_geometriesChanged(); }; /** * Extension to QTableWidgetItem that facilitates proper ordering for "DHMS" * strings (primarily used in the masternode's "active" listing). */ class DHMSTableWidgetItem : public QTableWidgetItem { public: DHMSTableWidgetItem(const int64_t seconds); virtual bool operator<(QTableWidgetItem const& item) const; private: // Private backing value for DHMS string, used for sorting. int64_t value; }; bool GetStartOnSystemStartup(); bool SetStartOnSystemStartup(bool fAutoStart); /** Save window size and position */ void saveWindowGeometry(const QString& strSetting, QWidget* parent); /** Restore window size and position */ void restoreWindowGeometry(const QString& strSetting, const QSize& defaultSizeIn, QWidget* parent); /** Load global CSS theme */ QString loadStyleSheet(); /** Check whether a theme is not build-in */ bool isExternal(QString theme); /* Convert QString to OS specific boost path through UTF-8 */ boost::filesystem::path qstringToBoostPath(const QString& path); /* Convert OS specific boost path to QString through UTF-8 */ QString boostPathToQString(const boost::filesystem::path& path); /* Convert seconds into a QString with days, hours, mins, secs */ QString formatDurationStr(int secs); /* Format CNodeStats.nServices bitmask into a user-readable string */ QString formatServicesStr(quint64 mask); /* Format a CNodeCombinedStats.dPingTime into a user-readable string or display N/A, if 0*/ QString formatPingTime(double dPingTime); #if defined(Q_OS_MAC) && QT_VERSION >= 0x050000 // workaround for Qt OSX Bug: // https://bugreports.qt-project.org/browse/QTBUG-15631 // QProgressBar uses around 10% CPU even when app is in background class ProgressBar : public QProgressBar { bool event(QEvent* e) { return (e->type() != QEvent::StyleAnimationUpdate) ? QProgressBar::event(e) : false; } }; #else typedef QProgressBar ProgressBar; #endif } // namespace GUIUtil #endif // BITCOIN_QT_GUIUTIL_H
[ "ratstang@piex.io" ]
ratstang@piex.io
d47005523ad153cb035dbcdd9c995e3d167b75a8
33d9fb53e5e5ec22dd8f7336399a4d60c6987f7b
/zImprovedArmor/ZenGin/Gothic_II_Classic/API/oHelp.h
34836995ddba2a93bcd65994da0ae57c1c236a4f
[]
no_license
Gratt-5r2/zImprovedArmor
bae5dde5c0c1ae1b3614141d7592b8a73eee2a41
061915791032acfed45703284d2ccd5d394e4a88
refs/heads/master
2023-04-30T23:20:52.486636
2023-03-12T12:42:08
2023-03-12T12:42:08
332,370,109
1
2
null
2023-04-18T23:44:42
2021-01-24T04:54:39
C++
UTF-8
C++
false
false
1,131
h
// Supported with union (c) 2018-2021 Union team #ifndef __OHELP_H__VER2__ #define __OHELP_H__VER2__ namespace Gothic_II_Classic { // sizeof 5Ch class oCHelp { public: zCView* win; // sizeof 04h offset 00h int dx; // sizeof 04h offset 04h int dy; // sizeof 04h offset 08h int sx; // sizeof 04h offset 0Ch int sy; // sizeof 04h offset 10h int x[4]; // sizeof 10h offset 14h int y[4]; // sizeof 10h offset 24h int index[4]; // sizeof 10h offset 34h int led[2]; // sizeof 08h offset 44h int ledx[2]; // sizeof 08h offset 4Ch int ledy[2]; // sizeof 08h offset 54h void oCHelp_OnInit() zCall( 0x006A3B40 ); oCHelp() zInit( oCHelp_OnInit() ); ~oCHelp() zCall( 0x006A42E0 ); void CalcPos() zCall( 0x006A4310 ); void Toggle() zCall( 0x006A43C0 ); void Update() zCall( 0x006A4570 ); void Redraw( zCVob* ) zCall( 0x006A4580 ); // user API #include "oCHelp.inl" }; } // namespace Gothic_II_Classic #endif // __OHELP_H__VER2__
[ "amax96@yandex.ru" ]
amax96@yandex.ru
2c3258e233ef156d5472ee3674ed5581da61053d
90047daeb462598a924d76ddf4288e832e86417c
/ash/focus_cycler.cc
4927bfecfdf99e61640454505c4d3c64751365d4
[ "BSD-3-Clause" ]
permissive
massbrowser/android
99b8c21fa4552a13c06bbedd0f9c88dd4a4ad080
a9c4371682c9443d6e1d66005d4db61a24a9617c
refs/heads/master
2022-11-04T21:15:50.656802
2017-06-08T12:31:39
2017-06-08T12:31:39
93,747,579
2
2
BSD-3-Clause
2022-10-31T10:34:25
2017-06-08T12:36:07
null
UTF-8
C++
false
false
3,439
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/focus_cycler.h" #include "ash/shell.h" #include "ash/wm/mru_window_tracker.h" #include "ash/wm/widget_finder.h" #include "ash/wm/window_state.h" #include "ash/wm/window_util.h" #include "ash/wm_window.h" #include "ui/views/accessible_pane_view.h" #include "ui/views/focus/focus_search.h" #include "ui/views/widget/widget.h" #include "ui/wm/public/activation_client.h" namespace ash { namespace { bool HasFocusableWindow() { return !Shell::Get()->mru_window_tracker()->BuildMruWindowList().empty(); } } // namespace FocusCycler::FocusCycler() : widget_activating_(nullptr) {} FocusCycler::~FocusCycler() {} void FocusCycler::AddWidget(views::Widget* widget) { widgets_.push_back(widget); } void FocusCycler::RemoveWidget(views::Widget* widget) { auto iter = std::find(widgets_.begin(), widgets_.end(), widget); if (iter != widgets_.end()) widgets_.erase(iter); } void FocusCycler::RotateFocus(Direction direction) { WmWindow* window = WmWindow::Get(wm::GetActiveWindow()); if (window) { views::Widget* widget = GetInternalWidgetForWindow(window->aura_window()); // First try to rotate focus within the active widget. If that succeeds, // we're done. if (widget && widget->GetFocusManager()->RotatePaneFocus( direction == BACKWARD ? views::FocusManager::kBackward : views::FocusManager::kForward, views::FocusManager::kNoWrap)) { return; } } const bool has_window = HasFocusableWindow(); int index = 0; int count = static_cast<int>(widgets_.size()); int browser_index = has_window ? count : -1; for (; index < count; ++index) { if (widgets_[index]->IsActive()) break; } int start_index = index; if (has_window) ++count; for (;;) { if (direction == FORWARD) index = (index + 1) % count; else index = ((index - 1) + count) % count; // Ensure that we don't loop more than once. if (index == start_index) break; if (index == browser_index) { // Activate the most recently active browser window. MruWindowTracker::WindowList mru_windows( Shell::Get()->mru_window_tracker()->BuildMruWindowList()); if (mru_windows.empty()) break; WmWindow* window = mru_windows.front(); window->GetWindowState()->Activate(); views::Widget* widget = GetInternalWidgetForWindow(window->aura_window()); if (!widget) break; views::FocusManager* focus_manager = widget->GetFocusManager(); focus_manager->ClearFocus(); focus_manager->RotatePaneFocus(direction == BACKWARD ? views::FocusManager::kBackward : views::FocusManager::kForward, views::FocusManager::kWrap); break; } else { if (FocusWidget(widgets_[index])) break; } } } bool FocusCycler::FocusWidget(views::Widget* widget) { // Note: It is not necessary to set the focus directly to the pane since that // will be taken care of by the widget activation. widget_activating_ = widget; widget->Activate(); widget_activating_ = NULL; return widget->IsActive(); } } // namespace ash
[ "xElvis89x@gmail.com" ]
xElvis89x@gmail.com
8834464115a828ff43ecd0cda1af70589f3c8c4b
1942a0d16bd48962e72aa21fad8d034fa9521a6c
/aws-cpp-sdk-iam/include/aws/iam/model/ListAttachedUserPoliciesResult.h
71b5ca376de619d2a94d87947acd6ca8e786e817
[ "Apache-2.0", "JSON", "MIT" ]
permissive
yecol/aws-sdk-cpp
1aff09a21cfe618e272c2c06d358cfa0fb07cecf
0b1ea31e593d23b5db49ee39d0a11e5b98ab991e
refs/heads/master
2021-01-20T02:53:53.557861
2018-02-11T11:14:58
2018-02-11T11:14:58
83,822,910
0
1
null
2017-03-03T17:17:00
2017-03-03T17:17:00
null
UTF-8
C++
false
false
7,784
h
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #pragma once #include <aws/iam/IAM_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/iam/model/ResponseMetadata.h> #include <aws/iam/model/AttachedPolicy.h> namespace Aws { template<typename RESULT_TYPE> class AmazonWebServiceResult; namespace Utils { namespace Xml { class XmlDocument; } // namespace Xml } // namespace Utils namespace IAM { namespace Model { /** * <p>Contains the response to a successful <a>ListAttachedUserPolicies</a> * request. </p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListAttachedUserPoliciesResponse">AWS * API Reference</a></p> */ class AWS_IAM_API ListAttachedUserPoliciesResult { public: ListAttachedUserPoliciesResult(); ListAttachedUserPoliciesResult(const AmazonWebServiceResult<Aws::Utils::Xml::XmlDocument>& result); ListAttachedUserPoliciesResult& operator=(const AmazonWebServiceResult<Aws::Utils::Xml::XmlDocument>& result); /** * <p>A list of the attached policies.</p> */ inline const Aws::Vector<AttachedPolicy>& GetAttachedPolicies() const{ return m_attachedPolicies; } /** * <p>A list of the attached policies.</p> */ inline void SetAttachedPolicies(const Aws::Vector<AttachedPolicy>& value) { m_attachedPolicies = value; } /** * <p>A list of the attached policies.</p> */ inline void SetAttachedPolicies(Aws::Vector<AttachedPolicy>&& value) { m_attachedPolicies = value; } /** * <p>A list of the attached policies.</p> */ inline ListAttachedUserPoliciesResult& WithAttachedPolicies(const Aws::Vector<AttachedPolicy>& value) { SetAttachedPolicies(value); return *this;} /** * <p>A list of the attached policies.</p> */ inline ListAttachedUserPoliciesResult& WithAttachedPolicies(Aws::Vector<AttachedPolicy>&& value) { SetAttachedPolicies(value); return *this;} /** * <p>A list of the attached policies.</p> */ inline ListAttachedUserPoliciesResult& AddAttachedPolicies(const AttachedPolicy& value) { m_attachedPolicies.push_back(value); return *this; } /** * <p>A list of the attached policies.</p> */ inline ListAttachedUserPoliciesResult& AddAttachedPolicies(AttachedPolicy&& value) { m_attachedPolicies.push_back(value); return *this; } /** * <p>A flag that indicates whether there are more items to return. If your results * were truncated, you can make a subsequent pagination request using the * <code>Marker</code> request parameter to retrieve more items. Note that IAM * might return fewer than the <code>MaxItems</code> number of results even when * there are more results available. We recommend that you check * <code>IsTruncated</code> after every call to ensure that you receive all of your * results.</p> */ inline bool GetIsTruncated() const{ return m_isTruncated; } /** * <p>A flag that indicates whether there are more items to return. If your results * were truncated, you can make a subsequent pagination request using the * <code>Marker</code> request parameter to retrieve more items. Note that IAM * might return fewer than the <code>MaxItems</code> number of results even when * there are more results available. We recommend that you check * <code>IsTruncated</code> after every call to ensure that you receive all of your * results.</p> */ inline void SetIsTruncated(bool value) { m_isTruncated = value; } /** * <p>A flag that indicates whether there are more items to return. If your results * were truncated, you can make a subsequent pagination request using the * <code>Marker</code> request parameter to retrieve more items. Note that IAM * might return fewer than the <code>MaxItems</code> number of results even when * there are more results available. We recommend that you check * <code>IsTruncated</code> after every call to ensure that you receive all of your * results.</p> */ inline ListAttachedUserPoliciesResult& WithIsTruncated(bool value) { SetIsTruncated(value); return *this;} /** * <p>When <code>IsTruncated</code> is <code>true</code>, this element is present * and contains the value to use for the <code>Marker</code> parameter in a * subsequent pagination request.</p> */ inline const Aws::String& GetMarker() const{ return m_marker; } /** * <p>When <code>IsTruncated</code> is <code>true</code>, this element is present * and contains the value to use for the <code>Marker</code> parameter in a * subsequent pagination request.</p> */ inline void SetMarker(const Aws::String& value) { m_marker = value; } /** * <p>When <code>IsTruncated</code> is <code>true</code>, this element is present * and contains the value to use for the <code>Marker</code> parameter in a * subsequent pagination request.</p> */ inline void SetMarker(Aws::String&& value) { m_marker = value; } /** * <p>When <code>IsTruncated</code> is <code>true</code>, this element is present * and contains the value to use for the <code>Marker</code> parameter in a * subsequent pagination request.</p> */ inline void SetMarker(const char* value) { m_marker.assign(value); } /** * <p>When <code>IsTruncated</code> is <code>true</code>, this element is present * and contains the value to use for the <code>Marker</code> parameter in a * subsequent pagination request.</p> */ inline ListAttachedUserPoliciesResult& WithMarker(const Aws::String& value) { SetMarker(value); return *this;} /** * <p>When <code>IsTruncated</code> is <code>true</code>, this element is present * and contains the value to use for the <code>Marker</code> parameter in a * subsequent pagination request.</p> */ inline ListAttachedUserPoliciesResult& WithMarker(Aws::String&& value) { SetMarker(value); return *this;} /** * <p>When <code>IsTruncated</code> is <code>true</code>, this element is present * and contains the value to use for the <code>Marker</code> parameter in a * subsequent pagination request.</p> */ inline ListAttachedUserPoliciesResult& WithMarker(const char* value) { SetMarker(value); return *this;} inline const ResponseMetadata& GetResponseMetadata() const{ return m_responseMetadata; } inline void SetResponseMetadata(const ResponseMetadata& value) { m_responseMetadata = value; } inline void SetResponseMetadata(ResponseMetadata&& value) { m_responseMetadata = value; } inline ListAttachedUserPoliciesResult& WithResponseMetadata(const ResponseMetadata& value) { SetResponseMetadata(value); return *this;} inline ListAttachedUserPoliciesResult& WithResponseMetadata(ResponseMetadata&& value) { SetResponseMetadata(value); return *this;} private: Aws::Vector<AttachedPolicy> m_attachedPolicies; bool m_isTruncated; Aws::String m_marker; ResponseMetadata m_responseMetadata; }; } // namespace Model } // namespace IAM } // namespace Aws
[ "henso@amazon.com" ]
henso@amazon.com
810290ce68fb9f73e9613d0ccc74bdea5f9b4513
091afb7001e86146209397ea362da70ffd63a916
/inst/include/nt2/include/functions/fnsm.hpp
592addcfb2777e61b626b1778cff18f42936be77
[]
no_license
RcppCore/RcppNT2
f156b58c08863243f259d1e609c9a7a8cf669990
cd7e548daa2d679b6ccebe19744b9a36f1e9139c
refs/heads/master
2021-01-10T16:15:16.861239
2016-02-02T22:18:25
2016-02-02T22:18:25
50,460,545
15
1
null
2019-11-15T22:08:50
2016-01-26T21:29:34
C++
UTF-8
C++
false
false
158
hpp
#ifndef NT2_INCLUDE_FUNCTIONS_FNSM_HPP_INCLUDED #define NT2_INCLUDE_FUNCTIONS_FNSM_HPP_INCLUDED #include <nt2/arithmetic/include/functions/fnsm.hpp> #endif
[ "kevinushey@gmail.com" ]
kevinushey@gmail.com
958395e0f0939331f96d45546d45b94795fa5633
5456502f97627278cbd6e16d002d50f1de3da7bb
/components/proximity_auth/remote_device.cc
447a1484ec8ace48f5c228f758430a3de8fe3cd0
[ "BSD-3-Clause" ]
permissive
TrellixVulnTeam/Chromium_7C66
72d108a413909eb3bd36c73a6c2f98de1573b6e5
c8649ab2a0f5a747369ed50351209a42f59672ee
refs/heads/master
2023-03-16T12:51:40.231959
2017-12-20T10:38:26
2017-12-20T10:38:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,139
cc
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/proximity_auth/remote_device.h" namespace proximity_auth { RemoteDevice::RemoteDevice() : bluetooth_type(BLUETOOTH_CLASSIC) {} RemoteDevice::RemoteDevice(const std::string& user_id, const std::string& name, const std::string& public_key, BluetoothType bluetooth_type, const std::string& bluetooth_address, const std::string& persistent_symmetric_key, std::string sign_in_challenge) : user_id(user_id), name(name), public_key(public_key), bluetooth_type(bluetooth_type), bluetooth_address(bluetooth_address), persistent_symmetric_key(persistent_symmetric_key), sign_in_challenge(sign_in_challenge) {} RemoteDevice::RemoteDevice(const RemoteDevice& other) = default; RemoteDevice::~RemoteDevice() {} } // namespace
[ "lixiaodonglove7@aliyun.com" ]
lixiaodonglove7@aliyun.com
c97da01368937fbb3b085f360703d28db234bd3b
fb782a8c56059035c57e6e0639c027720f1a27cd
/Subrat_Su16/matlab_node/matKinect/matkinect/matkinectAdaptor.cpp
c996f13ec10b6f8626d407705169fc9bef745193
[]
no_license
NickelsLab/ChemoTaxis
d0d8cb81922f6ed557a0fd1b2ee2d15d418f2790
7d907b4541ed3ed353692cccf9c83dd14284b140
refs/heads/master
2021-01-15T15:44:09.878351
2016-09-01T13:44:09
2016-09-01T13:44:09
34,916,347
0
0
null
null
null
null
UTF-8
C++
false
false
6,806
cpp
/* Implementation of the matkinect interface for acquisition from a given camera This is the Image Acquisition Adaptor Class that is created when you execute "vi = videoinput('matkinect');"b Author: Gus K Lott III, PhD November 23, 2010 Neurobiological Instrumentation Engineer Howard Hughes Medical Institute - Janelia Farm Research Campus Senior Engineer, YarCom Inc. guslott@yarcom.com */ #include "matkinectimaq.h" #include "matkinectAdaptor.h" #include "matkinectPropListener.h" #include "matkinectSourceListener.h" #include "matkinectDeviceFormat.h" #include "myKinListener.h" #include <stdio.h> //Class Constructor matkinectAdaptor::matkinectAdaptor(imaqkit::IEngine* engine, imaqkit::IDeviceInfo* deviceInfo, const char* formatName):imaqkit::IAdaptor(engine){ //Connect the camera object to the indicated camera with the indicated format devId = deviceInfo->getDeviceID(); kin = 0; motorPos = 1; //setup listeners _enginePropContainer = getEngine()->getAdaptorPropContainer(); _enginePropContainer->addListener("SelectedSourceName", new matkinectSourceListener(this)); imaqkit::IPropContainer* adaptorPropContainer = getEngine()->getAdaptorPropContainer(); int numDeviceProps = adaptorPropContainer->getNumberProps(); const char **devicePropNames = new const char*[numDeviceProps]; adaptorPropContainer->getPropNames(devicePropNames); for (int i = 0; i < numDeviceProps; i++){ // Get the property information object. imaqkit::IPropInfo* propInfo = adaptorPropContainer->getIPropInfo(devicePropNames[i]); // Check to see whether the property is device-specific. Do not create // create property listeners for non device-specific properties such // as 'Parent' and 'Tag'. if (propInfo->isPropertyDeviceSpecific()) { adaptorPropContainer->addListener(devicePropNames[i], new matkinectPropListener(this)); } } delete [] devicePropNames; _grabSection = imaqkit::createCriticalSection(); //imaqkit::adaptorWarn("matkinectAdaptor:debug","In Constructor"); } //Class Destructor matkinectAdaptor::~matkinectAdaptor(){ //When the C1394Camera Object is destroyed, it cleans itself up (Stops acquisition and frees resources) } //Device Driver information functions const char* matkinectAdaptor::getDriverDescription() const{ return "matkinect_skeleton"; } const char* matkinectAdaptor::getDriverVersion() const{ return "0.1"; } //Image data information functions int matkinectAdaptor::getMaxWidth() const { unsigned long pWidth, pHeight; pWidth = 640; pHeight = 480; return (int)pWidth; } int matkinectAdaptor::getMaxHeight() const { unsigned long pWidth, pHeight; pWidth = 640; pHeight = 480; return pHeight; } int matkinectAdaptor::getNumberOfBands() const { //Image Acquisition toolbox software only supports image data with 1 or 3 bands return 1; //this is an unfortunate limitation } imaqkit::frametypes::FRAMETYPE matkinectAdaptor::getFrameType() const { //return imaqkit::frametypes::MONO16; return imaqkit::frametypes::MONO12; //its really only 11 bits... still stored in a short regardless } //Image acquisition functions bool matkinectAdaptor::openDevice() { //If device is already open, return true. if (isOpen()) return true; //imaqkit::adaptorWarn("matkinectAdaptor:debug","Constructing Acquisition Thread"); //Create acquisition thread acquireFlag = true; _acquireThread = CreateThread(NULL,0,acquireThread,this,0,&_acquireThreadID); if ( _acquireThread == NULL ){closeDevice();return false;} //Wait for thread to create message queue. while(PostThreadMessage(_acquireThreadID, WM_USER+1,0,0) == 0) Sleep(1); return true; } bool matkinectAdaptor::closeDevice() { //If the device is not open, return. if(!isOpen()) return true; //Terminate and close the acquisition thread. acquireFlag = false; if(_acquireThread){ // Send WM_QUIT message to thread PostThreadMessage(_acquireThreadID, WM_QUIT, 0,0); //Give the thread a chance to finish WaitForSingleObject(_acquireThread, 1000); //Close thread handle CloseHandle(_acquireThread); _acquireThread = NULL; } return true; } bool matkinectAdaptor::startCapture() { //Check if device is already acquiring frames if (isAcquiring()) return false; //imaqkit::adaptorWarn("matkinectAdaptor:debug","Start Acquisition"); //kin->AddListener(listener); //Send start message to acquisition thread PostThreadMessage(_acquireThreadID, WM_USER,0,0); return true; } bool matkinectAdaptor::stopCapture() { //If the device is not acquiring data, return if (!isOpen()) return true; acquireFlag = false; //TODO: Must wait until acquisition is done to exit this function (assume this is to fire stopfcn of object) //kin->RemoveListener(listener); return true; } DWORD WINAPI matkinectAdaptor::acquireThread(void* param){ matkinectAdaptor* adaptor = reinterpret_cast<matkinectAdaptor*>(param); MSG msg; //Connect to the kinect Kinect::KinectFinder finder; adaptor->kin = finder.GetKinect(adaptor->devId); double tempMotorPos = adaptor->motorPos; //Create the listener adaptor->listener = new MyKinListener(); adaptor->listener->adaptor = adaptor; unsigned int imWidth = adaptor->getMaxWidth(); unsigned int imHeight = adaptor->getMaxHeight(); // Set the thread priority. //SetThreadPriority(GetCurrentThread(),THREAD_PRIORITY_TIME_CRITICAL); //imaqkit::adaptorWarn("matkinectAdaptor:debug","Entry to Acquisition Thread - width %i height %i",imWidth,imHeight); while(GetMessage(&msg,NULL,0,0) > 0){ switch(msg.message){ case WM_USER: //The Frame Acquisition Loop code goes here. //imaqkit::adaptorWarn("matkinectAdaptor:debug","In Acquisition Case for WM_USER"); //When the user requests, attach to the depth buffer adaptor->kin->AddListener(adaptor->listener); //Check if a frame needs to be acquired while(adaptor->isAcquisitionNotComplete() & adaptor->acquireFlag){ if (adaptor->motorPos != tempMotorPos){ adaptor->kin->SetMotorPosition(adaptor->motorPos); tempMotorPos = adaptor->motorPos; } Sleep(10); //At this point, the listener is being called in the API thread and // pumping the kinect's frames back to matlab }//While Frame Acq Loop adaptor->kin->RemoveListener(adaptor->listener); break; }//While message is not WM_QUIT = 0 } delete adaptor->listener; adaptor->kin = 0; //imaqkit::adaptorWarn("matkinectAdaptor:debug","Leaving Acquisition Thread"); return 0; }
[ "smahapat@trinity.edu" ]
smahapat@trinity.edu
4e738d0569179f528bf85417520bae1ca92b39d9
7bb563ccfae8a9d4cbb78ffcba0b66002beb4181
/BITMAP.cpp
f868ef79f437b08191fdab79c49621a663b1c6c1
[]
no_license
lafolle/Agastya
7096d209ef30e60cc5cc38df7851ec3108bcf52d
3953dd03f4dde04b55d6f79707c4c5d2d70bd0e3
refs/heads/master
2021-01-01T18:33:04.257200
2018-01-15T20:32:37
2018-01-15T20:32:37
5,926,317
1
2
null
null
null
null
UTF-8
C++
false
false
1,832
cpp
#include <vector> #include <list> #include <map> #include <set> #include <deque> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime> #include <iterator> #include <queue> using namespace std; #define pl cout<<endl; #define all(v) v.begin(),v.end() #define sz(v) v.size() typedef vector<int> vi; typedef vector<vector<int> > vvi; typedef vector<string> vs; int n,m; bool valid(int i,int j){ return i>-1&&i<n&&j>-1&&j<m; } int main() { int t,i,j,k; scanf("%d",&t); while(t--){ scanf("%d %d",&n,&m); char bm[n][m]; vvi closest(n,vi(m)); for(i=0;i<n;i++) scanf("%s",bm[i]); for(i=0;i<n;i++){ for(j=0;j<m;j++){ if(bm[i][j]=='1'){ closest[i][j]==0; continue; } queue<pair<int,int> > Q; if(valid(i+1,j)) Q.push(make_pair(i+1,j)); if(valid(i-1,j)) Q.push(make_pair(i-1,j)); if(valid(i,j+1)) Q.push(make_pair(i,j+1)); if(valid(i,j-1)) Q.push(make_pair(i,j-1)); pair<int,int> cell; // bool visited[n][m]; vector<vector<bool> > visited(n,vector<bool>(m,false)); int p,q; while(!Q.empty()){ cell=Q.front();Q.pop(); p=cell.first;q=cell.second; if(visited[p][q]) continue; if(bm[p][q]=='1') break; // ans found visited[p][q]=true; if(valid(p+1,q)&&!visited[p+1][q]) Q.push(make_pair(p+1,q)); if(valid(p-1,q)&&!visited[p-1][q]) Q.push(make_pair(p-1,q)); if(valid(p,q+1)&&!visited[p][q+1]) Q.push(make_pair(p,q+1)); if(valid(p,q-1)&&!visited[p][q-1]) Q.push(make_pair(p,q-1)); } closest[i][j]=abs(p-i)+abs(q-j); } } for(i=0;i<n;i++){ for(j=0;j<m;j++) printf("%d ",closest[i][j]); pl; } } return 0; } /* TLE...was expecting */
[ "fghjklp@gmail.com" ]
fghjklp@gmail.com
08df35e5cd794034cc80bfa978cf3b9c39c4b28b
bf6e386ba9de52fe221b8655c632374438b10890
/VoyaUtilTest.h
9adb1dc0c8c381a7872a4f6f504a15d55a811885
[]
no_license
Crinson/VoyaUtil
c7cd0c26e59b6a6b39f3d8bff3ba3f8923f75d11
14e507585a476584532c9ebd0df95e248285fc0f
refs/heads/master
2021-03-27T13:44:03.337760
2018-01-07T07:33:07
2018-01-07T07:33:07
116,544,781
0
0
null
null
null
null
UTF-8
C++
false
false
417
h
#pragma once namespace voya { ////////////////////////////////////////////////////////////////////////// //测试类 class CUtilTest { public: static void enter(); static void exit(); static bool testAll(); static bool testSharePtr(); static bool testAllocator(); static bool testObjectPool(); static void testPerformance(); }; }
[ "luck21zks@msn.com" ]
luck21zks@msn.com
0d829099ed76cfb129a2a6fb31dd9422eec20b7b
928a397c849830865980deab082309c3295c762c
/adt7410_defs.hpp
9ea1aa0272c78805b63c0729e576329faeb1ba78
[]
no_license
JSRagman/ADT7410
e4d8e66b368de1e341e4a661aabd460db7b6659b
a7910778fa3037d716d8e8ca590aba0c113624f5
refs/heads/master
2020-03-30T21:34:09.935462
2019-03-06T10:54:12
2019-03-06T10:54:12
151,632,984
0
0
null
null
null
null
UTF-8
C++
false
false
3,890
hpp
/* * adt7410_defs.hpp * * Created on: Sep 19, 2018 * Author: JSRagman * * Description: * Definitions for use with the ADT7410 16-bit digital * I2C temperature sensor. * * These definitions are derived from the Analog Devices * ADT7410 Data Sheet, Rev C. */ #ifndef ADT7410_DEFS_HPP_ #define ADT7410_DEFS_HPP_ // Operating Constants // ------------------------- #define ADT7410_CONV_TIME 240 // 240 ms conversion time (auto) #define ADT7410_RANGE_HIGH 150 // Device temperature limits (in deg C) #define ADT7410_RANGE_LOW -55 #define ADT7410_RESET 0x2F // Reset to POD #define ADT7410_RESET_DELAY 220 // Reset time, in microseconds // Device I2C Address Values // ------------------------- // The device I2C address is determined by the A0 and A1 pins, which // may be connected to GND (0) or VDD (1). #define ADT7410_I2C0 0x48 // A1 = 0, A0 = 0 #define ADT7410_I2C1 0x49 // A1 = 0, A0 = 1 #define ADT7410_I2C2 0x4A // A1 = 1, A0 = 0 #define ADT7410_I2C3 0x4B // A1 = 1, A0 = 1 // ADT7410 Register Power-On Default Values // ---------------------------------------- #define ADT7410_STATUS_POD 0x80 // 0b_1000_0000 #define ADT7410_CONFIG_POD 0x00 // 0b_0000_0000 // ADT7410 Register Addresses // -------------------------- #define ADT7410_R_TEMP 0x00 #define ADT7410_R_STATUS 0x02 #define ADT7410_R_CONFIG 0x03 #define ADT7410_R_THIGH 0x04 #define ADT7410_R_TLOW 0x06 #define ADT7410_R_TCRIT 0x08 #define ADT7410_R_THYST 0x0A #define ADT7410_R_ID 0x0B // Status (Register 0x02) // --------------------------------------------------- // Status Register bits 4, 5, 6, ans 7 are used as flags. #define ADT7410_STAT_TLOW 4 // T Low flag #define ADT7410_STAT_THIGH 5 // T High flag #define ADT7410_STAT_TCRIT 6 // T Crit flag #define ADT7410_STAT_RDY 7 // Ready flag (active low) // Configuration (Register 0x03) // --------------------------------------------------- // Use one configuration option from each of the six categories. // 1. Resolution. // 2. Operation mode. // 3. Mode for the INT and CT pins. // 4. Active polarity of the CT pin. // 5. Active polarity of the INT pin. // 6. Number of consecutive faults required to activate the // INT and CT pins. // 1. Temperature Resolution #define ADT7410_RESOLUTION_POD 0x00 // power-on default #define ADT7410_RESOLUTION_13 0x00 // 13-bit resolution #define ADT7410_RESOLUTION_16 0x80 // 16-bit resolution // 2. Operation Mode #define ADT7410_OPMODE_POD 0x00 // power-on default #define ADT7410_OPMODE_NORM 0x00 // continuous conversion #define ADT7410_OPMODE_1SHOT 0x20 // one-shot #define ADT7410_OPMODE_1SPS 0x40 // 1 SPS #define ADT7410_OPMODE_SD 0x60 // shutdown // 3. Comparator or Interrupt Mode for the INT and CT Pins #define ADT7410_FAULTMODE_POD 0x00 // power-on default #define ADT7410_FAULTMODE_INTERRUPT 0x00 #define ADT7410_FAULTMODE_COMPARATOR 0x10 // 4. Active Polarity for the CT Pin #define ADT7410_CT_ACTIVE_POD 0x00 // power-on default #define ADT7410_CT_ACTIVE_LOW 0x00 // CT pin active low #define ADT7410_CT_ACTIVE_HIGH 0x04 // CT pin active high // 5. Active Polarity for the INT Pin #define ADT7410_INT_ACTIVE_POD 0x00 // power-on default #define ADT7410_INT_ACTIVE_LOW 0x00 // INT pin active low #define ADT7410_INT_ACTIVE_HIGH 0x08 // INT pin active high // 6. Fault Count - Determines the number of consecutive // under/over temperature readings allowed before // activating the INT and CT pins. #define ADT7410_FAULTQUEUE_POD 0x00 // power-on default #define ADT7410_FAULTQUEUE_1 0x00 #define ADT7410_FAULTQUEUE_2 0x01 #define ADT7410_FAULTQUEUE_3 0x02 #define ADT7410_FAULTQUEUE_4 0x03 #endif /* ADT7410_DEFS_HPP_ */
[ "noreply@github.com" ]
JSRagman.noreply@github.com
b5b3a89f27e03241306f45f2eea3268168b2a024
4fc5bb49e94c76642fa1c1946460b805c9797cc1
/Lista Exercicios 1/struct3.cpp
fd40931c49c703a884dda3c854c60c08b594df90
[]
no_license
bruunofernandz/estruturaDados
10fdaf56693cab258da8ed61a09cb763e2c7ff9c
cdad48980af95d4317421384752b7e5d36c11ab6
refs/heads/master
2020-03-21T16:55:32.380994
2018-06-22T00:59:39
2018-06-22T00:59:39
138,802,657
1
0
null
2018-06-26T23:00:22
2018-06-26T23:00:21
null
ISO-8859-1
C++
false
false
2,325
cpp
// Exercicio Structs 3 - Lista 1 - Estrutura de dados // Danilo de Nadai Sicari - Turma 1 - Fatec Araras // 24/03/18 /***************************************************** Escrever um programa que cadastre vários produtos. Em seguida, imprima uma lista com o código e nome da cada produto. Por último, consulte o preço de um produto através de seu código. *****************************************************/ #include <iostream> #include <stdio.h> #include <stdlib.h> #include <string> #define MAX_PRODUTOS 3 using namespace std; typedef struct TProduto{ int cdg; string nome; }; TProduto Produto[MAX_PRODUTOS]; int idxProduto = 0; void CadastroProduto() { char opt; if(idxProduto < MAX_PRODUTOS) { do { cout << "\n\nCadastro Produto" << endl; cout << "\nNome: "; cin >> Produto[idxProduto].nome; Produto[idxProduto].cdg = idxProduto + 1; cout << "\nCodigo associado: " << Produto[idxProduto].cdg << endl; cout << "Deseja cadastrar novamente? (S)im/(N)ao : "; cin >> opt; idxProduto++; }while(opt == 'S' && idxProduto < MAX_PRODUTOS); if(opt == 'S' && idxProduto >= MAX_PRODUTOS) cout << "\nAviso: Numero maximo de produtos cadastrados!!"; } else cout << "\nAviso: Numero maximo de produtos cadastrados!!"; } void ImprimeProduto() { cout << "\n\nRelatorio Produtos" << endl; for(int i = 0; i < idxProduto; i++) cout << "Produto CODIGO["<<Produto[i].cdg<<"]: "<<Produto[i].nome<<endl; } void PesquisaProduto() { int cdg; bool r = false; cout << "\n\nPesquisar produto"<< endl; cout << "\nCODIGO: "; cin >> cdg; cout << "\nResultado: " << endl; for(int i = 0; i < idxProduto && r == false; i++) { if(cdg == Produto[i].cdg) { cout << "Produto CODIGO["<<Produto[i].cdg<<"]: "<<Produto[i].nome<<endl; //Se encontrar, sair do loop r = true; } } if(r == false) cout << "\nCODIGO nao encontrado!"; } int main(){ int opt = 0; do { cout << "\n\nMenu cadastro produto" << endl; cout << "1 - Cadastrar Produto" << endl; cout << "2 - Imprimir Produtos" << endl; cout << "3 - Pesquisar Produto" << endl; cout << "4 - Sair" << endl; cout << "Escolha a opcao desejada: "; cin >> opt; if(opt == 1) CadastroProduto(); if(opt == 2) ImprimeProduto(); if(opt == 3) PesquisaProduto(); }while(opt != 4); return 0; }
[ "37124989+dsicari@users.noreply.github.com" ]
37124989+dsicari@users.noreply.github.com
9be0b331ff6eae62ee23fe55cee2ca703f344a53
84856e480edf36f60f8d780da59c53a5ac0b7499
/glean/rts/binary.h
821178e865c60f455e910796a9b10aba3c0ab485
[ "BSD-3-Clause", "LicenseRef-scancode-generic-cla" ]
permissive
netproteus/Glean
ef3c16879cc6893116e1c25324a1f9bd3bde980d
4eda8d616709fe45f55d24e355e8cd79268d3e53
refs/heads/main
2023-07-28T21:28:07.174925
2021-09-02T11:40:05
2021-09-02T12:28:27
402,573,617
0
0
NOASSERTION
2021-09-02T22:00:55
2021-09-02T22:00:55
null
UTF-8
C++
false
false
10,323
h
// Copyright (c) Facebook, Inc. and its affiliates. #pragma once #include <folly/FBString.h> #include <folly/Range.h> #include <folly/Varint.h> #include "glean/ffi/memory.h" #include "glean/rts/id.h" #include "glean/rts/error.h" #include "glean/rts/nat.h" #include "glean/rts/string.h" namespace facebook { namespace glean { namespace binary { inline folly::ByteRange byteRange(const std::vector<unsigned char>& s) { return folly::ByteRange(s.data(), s.size()); } inline folly::ByteRange byteRange(const std::string& s) { return folly::ByteRange( reinterpret_cast<const unsigned char*>(s.data()), s.size()); } inline folly::ByteRange byteRange(const folly::fbstring& s) { return folly::ByteRange( reinterpret_cast<const unsigned char*>(s.data()), s.size()); } inline folly::ByteRange stringRange(const char* s) { return folly::ByteRange(reinterpret_cast<const unsigned char*>(s), strlen(s)); } inline std::string mkString(folly::ByteRange r) { return std::string(reinterpret_cast<const char*>(r.data()), r.size()); } inline folly::fbstring mkFbstring(folly::ByteRange r) { return folly::fbstring(reinterpret_cast<const char*>(r.data()), r.size()); } /// Return the smallest sequence of bytes that is lexicographically larger than /// and sequence with the prefix 'range' or the empty sequence if no such /// sequence exists. Example: /// /// lexicographicallyNext({0x25, 0x42, 0xFF, 0xFF}) == {0x25, 0x43} /// lexicographicallyNext({0xFF}) = {} std::vector<unsigned char> lexicographicallyNext(folly::ByteRange range); namespace detail { template<typename T, typename = void> struct word_traits; template<typename T> struct word_traits<T, typename std::enable_if_t< std::is_integral<std::remove_const_t<T>>::value || std::is_enum<std::remove_const_t<T>>::value>> { using word_type = T; static T fromWord(word_type x) { return x; } static word_type toWord(T x) { return x; } }; template<typename T> struct word_traits<rts::WordId<T>> { using word_type = typename rts::WordId<T>::word_type; static rts::WordId<T> fromWord(word_type x) { return rts::WordId<T>::fromWord(x); } static word_type toWord(rts::WordId<T> x) { return x.toWord(); } }; } struct Output; /** * A binary buffer which can be read from. * * NOTE: It does not own the memory! * */ struct Input { folly::ByteRange buf; Input() {} explicit Input(const folly::ByteRange& b) : buf(b) {} explicit Input(const std::string* s) : buf(reinterpret_cast<const unsigned char*>(s->data()), s->size()) {} explicit Input(const folly::fbstring* s) : buf(reinterpret_cast<const unsigned char*>(s->data()), s->size()) {} Input(const void* p, size_t n) : buf(static_cast<const unsigned char*>(p), n) {} Input(const void* start, const void* finish) : buf(static_cast<const unsigned char*>(start), static_cast<const unsigned char*>(finish)) {} void wantError(size_t n) const { rts::error("truncated input: expected {} bytes, got {}", n, buf.size()); } /// Ensure that there are at least n bytes left inline void want(size_t n) const { if (buf.size() < n) { wantError(n); } } bool empty() const { return buf.empty(); } /// Read a fixed width number. template <typename T> T fixed() { using word_type = typename detail::word_traits<T>::word_type; const auto n = sizeof(word_type); want(n); const void* p = buf.data(); buf.uncheckedAdvance(n); return detail::word_traits<T>::fromWord(folly::loadUnaligned<word_type>(p)); } /// Read a packed unsigned number template <typename T> inline T packed() { auto temp = buf; if (auto r = folly::tryDecodeVarint(temp)) { buf = temp; return detail::word_traits<T>::fromWord( static_cast<typename detail::word_traits<T>::word_type>(r.value())); } else { rts::error("invalid packed value"); } } /// Validate and read an encoded nat inline uint64_t untrustedNat() { auto r = rts::loadUntrustedNat(buf.begin(), buf.end()); if (r.second != nullptr) { buf = {r.second, buf.end()}; return r.first; } else { rts::error("invalid nat"); } } /// Read an encoded nat without any checks inline uint64_t trustedNat() { auto r = rts::loadTrustedNat(buf.begin()); assert(r.second <= buf.end()); buf = {r.second, buf.end()}; return r.first; } /// Validate and skip over an encoded nat inline void skipUntrustedNat() { auto p = rts::skipUntrustedNat(buf.begin(), buf.end()); if (p != nullptr) { buf = {p, buf.end()}; } else { rts::error("invalid nat"); } } /// Skip over an encoded nat without any checks inline void skipTrustedNat() { auto p = rts::skipTrustedNat(buf.begin()); buf = {p, buf.end()}; } uint8_t byte() { want(1); auto c = *buf.data(); buf.uncheckedAdvance(1); return c; } /// Read n bytes folly::ByteRange bytes(size_t n) { want(n); auto p = buf.data(); buf.uncheckedAdvance(n); return folly::ByteRange(p, n); } /// Read the rest of the input folly::ByteRange bytes() { return bytes(buf.size()); } const unsigned char* data() const { return buf.data(); } const unsigned char* end() const { return buf.end(); } size_t size() const { return buf.size(); } /// Validate and skip over a mangled UTF-8 string. void skipUntrustedString() { buf.uncheckedAdvance(rts::validateUntrustedString(buf)); } /// Validate and skip over a mangled string, writing its demangled /// representation into the Output void demangleUntrustedString(Output& output) { buf.uncheckedAdvance(rts::demangleUntrustedString(buf, output)); } /// Skip over a trusted mangled string and return its *demangled* size. size_t skipTrustedString() { auto r = rts::skipTrustedString(buf); buf.uncheckedAdvance(r.first); return r.second; } template <typename T> T generic_string(size_t n) { folly::ByteRange r = bytes(n); return T(reinterpret_cast<const char*>(r.data()), r.size()); } folly::fbstring fbstring(size_t n) { return generic_string<folly::fbstring>(n); } folly::fbstring fbstring() { return fbstring(buf.size()); } std::string string(size_t n) { return generic_string<std::string>(n); } std::string string() { return string(buf.size()); } bool shift(folly::ByteRange pat) { auto n = pat.size(); if (buf.size() >= n && !std::memcmp(buf.data(), pat.data(), n)) { buf.uncheckedAdvance(n); return true; } else { return false; } } }; // namespace binary /** * * A binary buffer which can be written to. * */ struct Output { Output() {} Output(Output&&) = default; Output& operator=(Output&&) = default; Output(const Output&) = delete; void operator=(const Output&) = delete; size_t size() const { return buf.size(); } const unsigned char* data() const { return buf.data(); } // Write a packed unsigned number template <typename T> void packed(T x) { auto p = buf.buffer(folly::kMaxVarintLength64); auto n = folly::encodeVarint( static_cast<uint64_t>(detail::word_traits<T>::toWord(x)), p); buf.use(n); } /// Write an encoded nat inline void nat(uint64_t x) { auto p = buf.buffer(rts::MAX_NAT_SIZE); auto n = rts::storeNat(p, x); buf.use(n); } // Write a fixed width number template <typename T> void fixed(T x) { const auto w = detail::word_traits<T>::toWord(x); bytes(&w, sizeof(w)); } void put(folly::ByteRange bytes) { this->bytes(bytes.begin(), bytes.size()); } void bytes(const void* data, size_t size) { if (size > 0) { auto b = buf.grab(size); std::memcpy(b, data, size); } } void expect(size_t n) { (void)buf.buffer(n); } /// Store the mangled representation of a UTF-8 string. The validity of the /// string isn't checked. void mangleString(folly::ByteRange r) { rts::mangleString(r, *this); } folly::ByteRange bytes() & { return buf.to<folly::ByteRange>(); } folly::fbstring fbstring() const { return buf.to<folly::fbstring>(); } std::string string() const { return buf.to<std::string>(); } ffi::malloced_array<uint8_t> moveBytes() { return buf.moveBytes(); } folly::fbstring moveToFbString() { return buf.moveToFbString(); } private: /// Simple implementation of a growable buffer. We need to be able to get /// ownership of the underlying memory which only folly::fbstring and /// folly::IOBuf seem to provide but both seem to be significantly slower /// (the latter more so than the former). class Buf { public: Buf() { len = 0; } Buf(Buf&&) = default; Buf& operator=(Buf&&) = default; Buf(const Buf&) = delete; Buf& operator=(const Buf&) = delete; size_t size() const { return len; } size_t capacity() const { return buf.size(); } const unsigned char* data() const { return buf.get(); } /// Return a point to enough space for n bytes. This reserves memory but /// doesn't increase the size - this can be done via 'use' afterwards. unsigned char* buffer(size_t n) { if (n > capacity() - size()) { realloc(n); } return buf.get() + size(); } /// Increase the size of the buffer. This doesn't reserve memory so the /// new size must be <= capacity. void use(size_t n) { assert(capacity() - size() >= n); len += n; } /// Increase the buffer size by n and return a pointer to the new memory. unsigned char* grab(size_t n) { auto p = buffer(n); use(n); return p; } ffi::malloced_array<uint8_t> moveBytes() { buf.prune(len); return std::move(buf); } /// Transfer ownership of the underlying memory to a folly::fbstring. folly::fbstring moveToFbString(); /// Create a container template<typename C> C to() const { return C(buf.get(), buf.get() + size()); } private: void realloc(size_t n); ffi::malloced_array<uint8_t> buf; size_t len; }; Buf buf; }; } // namespace binary } // namespace glean } // namespace facebook
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
d7d89a854b14476086a543c888a3270779d3522c
ba8bbdb740f2462f8123191d1f4c3a831a7c9f8c
/src/apps/deepwalk.hpp
ba60e85be5f175c1e538796f275dec11f6dba872
[ "MIT", "Apache-2.0" ]
permissive
ykwd/KnightKing
88d51c132c56fa56c96d848011fc5b0516d25208
2dd3fd3c820b85d5bd73a47a3f948d4b513dacd1
refs/heads/master
2022-02-13T16:57:51.112521
2022-01-22T08:02:04
2022-01-22T08:02:04
218,097,898
0
0
MIT
2019-10-28T16:43:04
2019-10-28T16:43:04
null
UTF-8
C++
false
false
1,807
hpp
/* * The MIT License (MIT) * * Copyright (c) 2019 Ke Yang, Tsinghua University * * 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. */ #pragma once #include "walk.hpp" #include "static_comp.hpp" template <typename edge_data_t> void deepwalk(WalkEngine<edge_data_t, EmptyData> *graph, walker_id_t walker_num, step_t walk_length) { MPI_Barrier(MPI_COMM_WORLD); Timer timer; graph->set_walkers(walker_num); auto extension_comp = [&] (Walker<EmptyData>& walker, vertex_id_t current_v) { return walker.step >= walk_length ? 0.0 : 1.0; }; auto static_comp = get_trivial_static_comp(graph); graph->random_walk( extension_comp, static_comp ); #ifndef UNIT_TEST printf("total time %lfs\n", timer.duration()); #endif }
[ "oneday117@qq.com" ]
oneday117@qq.com
8bf641500637b83daf2e1504596a765515f6cd4a
f90693e84ac05894341b4c08df6a2bf1febb06ee
/include/common/ThreadLocal.hpp
033bccb5581bc40660fdd099cf4bc8f3d05ae50a
[]
no_license
riclas/rstm
1ce57d423b813ee9916a09fb70d9041a72984e39
a72c861c1b68f5fd516b2293ebdc58c2b62849b4
refs/heads/master
2020-12-31T04:28:34.289771
2016-02-19T19:23:08
2016-02-19T19:23:08
51,465,568
0
0
null
null
null
null
UTF-8
C++
false
false
9,338
hpp
/** * Copyright (C) 2011 * University of Rochester Department of Computer Science * and * Lehigh University Department of Computer Science and Engineering * * License: Modified BSD * Please see the file LICENSE.RSTM for licensing information */ /** * Since Apple doesn't support __thread in its toolchain, we need a clean * interface that lets us use either __thread or pthread_getspecific. This * file hides all interaction with thread-local storage behind a simple * macro, so that the complexities of non-__thread are hidden from the * programmer * * Note, too, that we allow a non-Apple user to configure the library in * order to explicitly use pthread_getspecific. */ // NB: This file could use significant hardening, using template // metaprogramming to support all the necessary types, i.e., arrays, // unions, etc. #ifndef STM_COMMON_THREAD_LOCAL_H #define STM_COMMON_THREAD_LOCAL_H #include <stm/config.h> /** * We define the following interface for interacting with thread local data. * * THREAD_LOCAL_DECL_TYPE(X) * * The macro will expand in a platform specific manner into the correct * thread local type for X. * * Examples: * * static THREAD_LOCAL_DECL_TYPE(unsigned) a; * Linux: static __thread unsigned a; * Windows: static __declspec(thread) unsigned a; * pthreads: static ThreadLocal<unsigned, sizeof(unsigned)> a; * * extern THREAD_LOCAL_DECL_TYPE(Foo*) foo; * Linux: extern __thread Foo* foo; * Windows: extern __declspec(thread) Foo* foo; * pthreads: extern ThreadLocal<Foo*, sizeof(Foo*)> a; */ #if defined(STM_TLS_PTHREAD) # define THREAD_LOCAL_DECL_TYPE(X) stm::tls::ThreadLocal<X, sizeof(X)> #elif defined(STM_OS_WINDOWS) # define THREAD_LOCAL_DECL_TYPE(X) __declspec(thread) X #elif defined(STM_CC_GCC) || defined(STM_CC_SUN) || defined(STM_CC_ICC) # define THREAD_LOCAL_DECL_TYPE(X) __thread X #else # warning "No thread local implementation defined." #endif /** * In the above macro definitions, only STM_TLS_PTHREAD needs more work. * The remainder of this file implements the ThreadLocal<> templates that * make pthread_getspecific and pthread_setspecific look like __thread to * client code */ #if defined(STM_TLS_PTHREAD) #include <pthread.h> #include <cstdlib> namespace stm { namespace tls { /** * The basic thread local wrapper. The pthread interface stores the * value as a void*, and this class manages that void* along with the * pthread key. */ class PThreadLocalImplementation { protected: PThreadLocalImplementation(void* const v) { pthread_key_create(&key, NULL); pthread_setspecific(key, v); } virtual ~PThreadLocalImplementation() { pthread_key_delete(key); } void* getValue() const { return pthread_getspecific(key); } void setValue(void* const v) { pthread_setspecific(key, v); } private: pthread_key_t key; private: // Do not implement PThreadLocalImplementation(); PThreadLocalImplementation(const PThreadLocalImplementation&); PThreadLocalImplementation& operator=(const PThreadLocalImplementation&); }; /** * Templates allow us to mimic an __thread interface to PThread data. We * have two basic categories of data. * * 1) Value data. * 2) Pointer data. * * Value data is builtin types and user defined structs that are * compatible with direct __thread allocation. We can split this type of * data into two cases. * * 1) Data that can fit in the size of a void*. * 2) Data that is too large. * * This distinction is important when we consider levels of * indirection. The pthread interface gives us access to void* sized * slots of data. If we can fit what we need there, then we have just * the one level of indirection to access it. If we can't, then we need * to allocate space elsewhere for it, and store a pointer to that space * in the slot. * * Pointer data is easy to manage, since the client expects the location * to look like a pointer, and pthreads is giving us a pointer. The * client is going to have to manage the memory if it's dynamically * allocated, so we can just return it as needed. * * The main problem to this interface is that each interaction requires * a pthread library call. If the client knew there was a pthreads * interface (or just an interface more expensive than __thread) * underneath then it could optimize for that situation. */ /** * The ThreadLocal template for objects that are larger than the size * allotted by a pthread_getspecific. It uses either malloc and free or * a trivial new constructor to allocate and deallocate space for the * data, and memcpy to write to the data as needed. It owns the * allocated space, which is fine because the client is thinking of this * as automatically managed anyway. * * Currently, we trigger an error if the type has a constructor, but * doesn't have a default constructor. This is the same approach that * C++ takes with arrays of user-defined classes. */ template <typename T, unsigned S> class ThreadLocal : public PThreadLocalImplementation { public: ThreadLocal() : PThreadLocalImplementation(new T()) { } ThreadLocal(T t) : PThreadLocalImplementation(new T()) { __builtin_memcpy(getValue(), &t, S); } virtual ~ThreadLocal() { delete static_cast<T*>(getValue()); } T* operator&() const { return static_cast<T*>(getValue()); } private: // Do not implement these. We assume that anyone trying to copy the // ThreadLocal object probably wants to copy the underlying object // instead. ThreadLocal(const ThreadLocal<T, S>&); ThreadLocal<T, S>& operator=(const ThreadLocal<T, S>&); }; /** * The ThreadLocal template for objects that are the size of a void*, * but not a pointer. This differs from the basic template in that we * don't need to allocate any extra space for the stored item. */ template <typename T> class ThreadLocal<T, sizeof(void*)> : public PThreadLocalImplementation { public: ThreadLocal() : PThreadLocalImplementation(NULL) { } ThreadLocal(T t) : PThreadLocalImplementation(NULL) { __builtin_memcpy(getValue(), &t, sizeof(T)); } T* operator&() const { return static_cast<T*>(getValue()); } private: // Do not implement these. We assume that anyone trying to copy the // ThreadLocal object probably wants to copy the underlying object // instead. ThreadLocal(const ThreadLocal<T, sizeof(void*)>&); ThreadLocal<T,sizeof(void*)>& operator=(const ThreadLocal<T,sizeof(void*)>&); }; /** * We use partial template specialization to implement a thread local * type just for pointers. This extends the interface to allow * interaction with the stored variable in "smart pointer" fashion. * * This differs from the basic thread local implementation in that we * don't provide an address-of operator, in the expectation that no one * is going to want it, but we do provide an implicit cast to the * underlying pointer type that returns the pointer value stored at the * key. * * This allows clients to pass and return the value as expected. A * normal smart pointer would be hesitant to do this because of * ownership issues, but this class is really just trying to emulate * __thread. The ThreadLocal does *not* take ownership of managing the * underlying pointer. */ template <typename T> class ThreadLocal<T*, sizeof(void*)> : public PThreadLocalImplementation { public: ThreadLocal(T* t = NULL) : PThreadLocalImplementation(t) { } virtual ~ThreadLocal() { } // The smart pointer interface to the variable. const T& operator*() const { return *static_cast<T*>(getValue()); } const T* operator->() const { return static_cast<T*>(getValue()); } T& operator*() { return *static_cast<T*>(getValue()); } T* operator->() { return static_cast<T*>(getValue()); } operator T*() { return static_cast<T*>(getValue()); } // allow assignments ThreadLocal<T*, sizeof(void*)>& operator=(T* rhs) { setValue(rhs); return *this; } bool operator==(T* rhs) { return (getValue() == rhs); } private: // Restrict access to potentially dangerous things. Start by // preventing the thread local to be copied around (presumably people // trying to copy a ThreadLocal /actually/ want to copy the // underlying object). ThreadLocal(const ThreadLocal<T*, sizeof(T*)>&); ThreadLocal<T*, sizeof(T*)>& operator=(const ThreadLocal<T*, sizeof(T*)>&); }; } // namespace stm::tls } // namespace stm #endif #endif // STM_COMMON_THREAD_LOCAL_H
[ "ricardojdfilipe@gmail.com" ]
ricardojdfilipe@gmail.com
308b47f45b9ffe64732e68df0b8bb5627497ecf6
691abc0e58e9f6ed0e1dd4704276a3356215f63b
/other/source/goipachi_source_backup/koyakemain_itr_try.cpp
f354446b75b0453a85bae86746406b7cb5b40fe6
[]
no_license
kykyk47/goipachi
3512405daa97bac434961d1a39e28944b24f8adf
d0ea782d298e9480bbc1e89598fe2721868daac6
refs/heads/master
2020-08-30T03:55:28.365671
2020-07-23T02:30:55
2020-07-23T02:30:55
218,251,259
0
0
null
null
null
null
UTF-8
C++
false
false
158,426
cpp
// goipachi.cpp ////小宅用 //#include "pch.h" #include <Windows.h> #include <iostream> #include <gl/glut.h> #include <math.h> #include <objbase.h> #include <stdio.h> #include <stdlib.h> #include <gdiplus.h> #include <vector> #include <random> #include <SDL.h> #include <SDL_mixer.h> //松本用 /* #include <objbase.h> #include <stdio.h> #include <stdlib.h> #include <gdiplus.h> #include <gl/glut.h> #include <iostream> #include <math.h> #include <Windows.h> #include <vector> */ using namespace Gdiplus; #define WIDTH 1280 //デフォルトの画面のサイズ #define HEIGHT 720 #define TIME_LIMIT 180 //タイマー.ほぼ1秒に1すすむ #define dic_3_LIMIT 44000 //3文字辞書の単語数の余地(今後追加できるよう少し多めに設定) #define dic_4_LIMIT 44000 //4文字辞書の単語数の余地(今後追加できるよう少し多めに設定) #define dic_5_LIMIT 44000 //5文字辞書の単語数の余地(今後追加できるよう少し多めに設定) #define OBJECT_LIMIT 10000 //ブロックの制限 #define PATTERN_LIMIT 45 //横に並べるブロック配置パターンの上限 #define MADE_LIMIT 100 //ステージモードにおいて,作れる単語の限界数(すてーじもーどで単語重複不可のステージの時に使う) #define STAGE_LIMIT 518 //ステージモードの上限 GdiplusStartupInput gdiPSI; ULONG_PTR gdiPT; GLuint tex_num[7][11] = { {} }; //[0][]:数字フォント(赤) //[1][]:数字フォント(頭上のスコアの数字・黄緑) [10]は「+」 void check_goi(int* moji); void LoadImagePNG(const wchar_t* filename, GLuint &texture); void SetNumImage(double x, double y, int size_x, int size_y, int num, int font, int d); int choose_hiragana(void); int choose_pattern(void); int choose_odai(void); void set_block_info(int type, int x_grid, int y_grid, int leftside, int blocknum); void block_standby(void); void standby_stage(int stage_num); void game_reset(void); void game_shutdown(void); int ranking; //ランキング表示のため bool onMoveKeyPress_L = false; bool onMoveKeyPress_R = false; bool player_jump = false; bool player_walk = false; int jump_timer = 0; //キャラクターがジャンプしてからの時間を計測 #define JUMP_HIGHEST 11 //キャラクターがジャンプしてから最高点に達した瞬間のjump_timer bool move_lock = false; //ポーズ時trueになる なんのオブジェクトの移動も許さないマン int walk_timer = 0; //キャラクターのアニメーション int lamp_timer_01 = 0; //Kキー(決定ボタン)を押した後の赤ライトの点灯 int lamp_timer_02 = 0; //プレイヤーのリアクションのエフェクト int lamp_timer_block = 0; //ルーレットブロックのエフェクトのアニメーション int lamp_timer_clear = 0; //クリアランプ全点灯でゴージャスになる int hiragana_roulette_timer = 0; //ルーレットブロックの中身のタイマー int hiragana_roulette[74] = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75 }; //ルーレットの中身 int gun_timer = 0; //銃を構えているイラストの表示 int bullet_timer = 0; //弾丸が発射されてからの秒数 一定時間たつと消える(無限に飛び続けるのいやでしょ) int scene = 0; //◇シーンの追加.0:タイトル 1:スタンバイ画面 2:ポーズ画面 3:リザルト画面A 4リザルト画面B 5:プレイ画面(メイン) 6:GAME OVER画面 7:ステージ・モード選択( 8:文字数選択メニュー 9:ステージ選択画面 10:ほんとうによろしいですか int next_scene = 0; //ゲームをやめる→ほんとうによろしいですか?→の分岐などに使う int mode = 0; //0:スコアアタック 1:ステージモード スコアの計算にも影響する int mode_mojisu = 4; //3or4or5 3文字,5文字はおいおい辞書を用意して実装したい.とりあえず4文字モードだけ int stage_medal[3] = {}; //全ステージ中の獲得したメダルの総数を記録 int made_tango[MADE_LIMIT+1][5] = { {} }; //ステージクリアモードのとき,重複した単語は作れない int stage_select = 1; //ステージクリアモードで選んでいるステージの番号 int stage_clear[STAGE_LIMIT + 1][5] = { {} }; //ステージクリアモードの進捗状況 0~2 メダル 3:クリア時間ハイスコア 4:ミス回数ハイスコア int stage_info[STAGE_LIMIT + 1] = {}; //0:未定義(カミングスーン) 1:何単語作るかミッション それ以外:面白そうなのがあったら追加 int stage_nolma[STAGE_LIMIT + 1] = {}; //例:ステージ1で10単語作れミッション→ [1]=10 int stage_time_limit[STAGE_LIMIT + 1] = {}; //例:ステージ1は200秒以内 [1]=200 int stage_time_limit_gold[STAGE_LIMIT + 1] = {}; //例:ステージ1のメダル獲得タイム50秒以内→[1]=50 int stage_slot_constraint[STAGE_LIMIT + 1][5] = { {} }; //語彙スロット固定(例:ステージ1で[][][い][ろ]のときは [1][0]~[1][3]:__いろになる int stage_block_info[OBJECT_LIMIT][3] = { {} }; //ステージモードの時に配置されるブロックの情報 int score_miss = 0; //スコア(ミス数)(ステージモードのみ std::vector<std::vector<int>>dic_3moji; //辞書の情報を動的に格納(ジャグ配列 std::vector<std::vector<int>>dic_4moji;//辞書の情報を格納 std::vector<std::vector<int>>dic_5moji;//辞書の情報を格納 std::vector<std::vector<int>>dic_sample;//辞書の情報を格納 int score_get_hiragana = 0; //入手したひらがなの数 int score_leave_hiragana = 0; //捨てたひらがなの数 int score_most_hiragana = 0; //最も単語に使ったひらがなの数 int max_most_hiragana = 0; //↑を求めるのに使う int score_tango = 0; //作った単語の数 int score = 0; //ゲーム中でのスコア int list_most_hiragana[80] = {}; //最も入手したひらがなを決めるのに必要 int hiragana_weight_3[80][5] = { {} }; //各何文字目かの登場回数(単語を構成するひらがなのほかにランダムなひらがなを配置するため,それの生成率を決める重み int hiragana_weight_4[80][5] = { {} }; //各何文字目かの登場回数(単語を構成するひらがなのほかにランダムなひらがなを配置するため,それの生成率を決める重み int hiragana_weight_5[80][5] = { {} }; //各何文字目かの登場回数(単語を構成するひらがなのほかにランダムなひらがなを配置するため,それの生成率を決める重み float hiragana_score_3[80][3] = { {} }; //Kキーを押下した際スロットの各文字の点数を合計するための要素 float hiragana_score_4[80][4] = { {} }; //Kキーを押下した際スロットの各文字の点数を合計するための要素 float hiragana_score_5[80][5] = { {} }; //Kキーを押下した際スロットの各文字の点数を合計するための要素 int odai; //お題の番号を決める int odai_hiragana_3[75][5] = { {0,46,0} }; //お題のひらがなの配置 int odai_hiragana_4[75][5] = { {0,6,2,0},{0,0,2,43},{11,0,0,8},{0,46,0,46},{0,2,0,2},{0,3,0,3},{0,2,15,0},{14,2,0,0},{0,0,6,39}, {66,46,0,0},{0,47,0,3},{0,0,0,48},{6,0,6,0},{16,0,0,46},{0,47,0,2},{0,50,0,50},{0,50,41,0},{26,0,0,8}, {39,0,0,50},{0,0,50,65} }; //お題のひらがなの配置 int odai_hiragana_5[75][5] = { {0,0,0,46,7} }; //お題のひらがなの配置 int choose_hiragana_weight[80] = { 0, //ひらがなブロックがステージに配置されるときの平仮名の種類の重み 12,20,18,10,16, //ア行 20,18,10,10,12, 12,15,10,10,9, 15,8,10,15,15, 15,9,5,10,13, 12,9,12,7,12, 16,13,11,11,12, 15,10,10, 8,12,10,12,12, 12,4,13,15,4,0,17, //わをんっヴ箱ー 10,10,10,9,14, 8,14,10,10,8, 15,6,6,14,14, 10,8,13,13,10, 9,9,9,9,7, 0,0,0,0 }; int choose_hiragana_weight_add[80] = {}; //最終的に乱数よりひらがなを決定するために 1~79だったら「あ」 80~144だったら「い」みたいにできるように int high_score_3[5] = { 0,0,0,0,0 }; //レコードされているハイスコア int high_score_4[5] = { 0,0,0,0,0 }; //レコードされているハイスコア int high_score_5[5] = { 0,0,0,0,0 }; //レコードされているハイスコア int slot[5] = { 0,0,0,0,0 }; //スロット(のちのち5文字でもできるように) int slot_select = 0; //どの文字をさしているか int slot_start[OBJECT_LIMIT] = {}; //オブジェクトがルーレットだった場合ルーレットはどっから始まるか int object_on_stage = 0; //そのセッションで配置されたブロックの総数 int score_word = 0; //1つ1つのワードのスコア int time = TIME_LIMIT * 60; int stage_structure[PATTERN_LIMIT] = {}; int set_leftside = 0; int object_block[OBJECT_LIMIT][3] = { {} }; //衝突判定に使う,プレイヤーとの距離の条件を満たすためにこの配列にオブジェクトの情報を記載(ブロックの種類,中心座標(xとy)) int height_c = 0; //衝突判定に使う,ジャンプした後着地できる位置(高さ)最も高い座標 FILE *fp_score_3; //スコアファイル FILE *fp_score_4; //スコアファイル FILE *fp_score_5; //スコアファイル FILE *fp_dic_3; //3文字辞書ファイル(未完成) FILE *fp_dic_4; //4文字辞書ファイル FILE *fp_dic_5; //5文字辞書ファイル(未完成) FILE *fp_stageclear; //ステージクリア進捗 FILE *fp_stage_structure_info; //ステージの情報 FILE *fp_stage_nolma_info; FILE *fp_dic_sample_i; //辞書ファイル(ひらがな格納)を数値化できるように工夫するテスト FILE *fp_dic_sample_o; int dic_3_all = 0; //実際に辞書に登録されていた単語数 int dic_4_all = 0; int dic_5_all = 0; int dic_sample_all = 0; bool word_hit = false; //Kキー押下後,辞書に存在していたかどうか(trueなら得点+エフェクト,falseなら時間減少+エフェクト) int i, j, k, l; double camera_x = 0; //カメラの位置 double camera_y = 0; double temp_camera_x = 0; //◇シーン移動によりカメラの位置をリセットするため,ゲーム中のカメラ位置をストックしておく double temp_camera_y = 0; //void LoadImagePNG(const wchar_t* filename, GLuint &texture); int speed = 0; //プレイヤーが進むスピード bool flag_move_x = true; //次のタイマー関数が呼び出されるまでx方向の移動を与えないための制御 bool flag_move_y = true; //次のタイマー関数が呼び出されるまでy方向の移動を与えないための制御 bool flag_collision_L = false; //衝突判定(プレイヤーの左方向) bool flag_collision_R = false; //衝突判定(右方向) bool flag_collision_U = false; //衝突判定(上方向) bool flag_collision_D = false; //衝突判定(下方向) bool flag_move_bullet = true; //次のタイマー関数が呼び出されるまで弾丸の移動を与えないための制御 bool flag_jump_slow = false; //ジャンプ→落下時ゆっくり降りるかんじにするトリガー bool flag_bullet_exist = false; //弾丸が存在して動いている状態(当たり判定起動) int time_1flame; //デバッグ用,1フレームでどれだけ進んだか,どれだけ時間がたっているか(ms)(下3つも同じ) double speed_1flame; int time_temp; double speed_temp; std::random_device rnd; std::mt19937 mt(rnd()); //なんか乱数のタネを決定するやつ std::uniform_int_distribution<> rand_hiragana(1, 75); std::uniform_int_distribution<> rand_pattern(1, 15); std::uniform_int_distribution<> rand_odai(1, 75); std::uniform_int_distribution<> rand_dic_4(1, dic_4_LIMIT); //4文字辞書のステージで,ブロックを配置するときに使う class GameObject { public: double center_x = 0; double center_y = 0; double size_x = 0; double size_y = 0; const wchar_t *file; GLuint tex; GameObject(double x, double y, double size_x, double size_y, const wchar_t *filename) :center_x(x), center_y(y), size_x(size_x), size_y(size_y) { file = filename; tex = *filename; GdiplusStartup(&gdiPT, &gdiPSI, NULL); glEnable(GL_TEXTURE_2D); Bitmap bmp(filename); BitmapData data; bmp.LockBits(0, ImageLockModeRead, PixelFormat32bppARGB, &data); glGenTextures(1, &tex); glBindTexture(GL_TEXTURE_2D, tex); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, 4, data.Width, data.Height, 0, GL_BGRA_EXT, GL_UNSIGNED_BYTE, data.Scan0); glBindTexture(GL_TEXTURE_2D, 0); bmp.UnlockBits(&data); Update(); } void Update() { if (center_x <= camera_x + 500 && center_x >= camera_x - 1500) { glBindTexture(GL_TEXTURE_2D, tex); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_TEXTURE_2D); glEnable(GL_ALPHA_TEST); glBegin(GL_POLYGON); glTexCoord2f(0.0f, 1.0f); glVertex2d(center_x + 64.0 / 2, center_y + 64.0 / 2);//左下 glTexCoord2f(0.0f, 0.0f); glVertex2d(center_x + 64.0 / 2, center_y - 64.0 / 2);//左上 glTexCoord2f(1.0f, 0.0f); glVertex2d(center_x - 64.0 / 2, center_y - 64.0 / 2);//右上 glTexCoord2f(1.0f, 1.0f); glVertex2d(center_x - 64.0 / 2, center_y + 64.0 / 2);//右下 glEnd(); glDisable(GL_ALPHA_TEST); glDisable(GL_TEXTURE_2D); glDisable(GL_BLEND); } } void Set(double x, double y) { center_x = x; center_y = y; Update(); } double Get_x() { return center_x; } double Get_y() { return center_y; } void LoadImagePNG2(const wchar_t* filename, GLuint &texture) //追加 { GdiplusStartup(&gdiPT, &gdiPSI, NULL); glEnable(GL_TEXTURE_2D); Bitmap bmp(filename); BitmapData data; bmp.LockBits(0, ImageLockModeRead, PixelFormat32bppARGB, &data); glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, 4, data.Width, data.Height, 0, GL_BGRA_EXT, GL_UNSIGNED_BYTE, data.Scan0); glBindTexture(GL_TEXTURE_2D, 0); bmp.UnlockBits(&data); } void SetImage(double center_x, double center_y) { if (center_x <= camera_x + 1800 && center_x >= camera_x - 1800) { glBindTexture(GL_TEXTURE_2D, tex); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_TEXTURE_2D); glEnable(GL_ALPHA_TEST); glBegin(GL_POLYGON); glTexCoord2f(0.0f, 1.0f); glVertex2d(center_x + size_x / 2, center_y + size_y / 2);//右下 glTexCoord2f(0.0f, 0.0f); glVertex2d(center_x + size_x / 2, center_y - size_y / 2);//右上 glTexCoord2f(1.0f, 0.0f); glVertex2d(center_x - size_x / 2, center_y - size_y / 2);//←上 glTexCoord2f(1.0f, 1.0f); glVertex2d(center_x - size_x / 2, center_y + size_y / 2);//←下 glEnd(); glDisable(GL_ALPHA_TEST); glDisable(GL_TEXTURE_2D); glDisable(GL_BLEND); } }; }; class MoveObject :public GameObject { public: MoveObject(double x, double y, double size_x, double size_y, const wchar_t *filename) :GameObject(x, y, size_x, size_y, filename) { } void Move(double x, double y) { center_x += x; center_y += y; Update(); } }; class AnimationChara :public MoveObject { public: std::vector<GLuint> texes; int direction; AnimationChara(double x, double y, double size_x, double size_y, const wchar_t *filename) :MoveObject(x, y, size_x, size_y, filename) { texes.push_back(tex); direction = 1; } void LoadPNGImage(const wchar_t *filename) { GLuint texture = 0; GdiplusStartup(&gdiPT, &gdiPSI, NULL); glEnable(GL_TEXTURE_2D); Bitmap bmp(filename); BitmapData data; bmp.LockBits(0, ImageLockModeRead, PixelFormat32bppARGB, &data); glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, 4, data.Width, data.Height, 0, GL_BGRA_EXT, GL_UNSIGNED_BYTE, data.Scan0); glBindTexture(GL_TEXTURE_2D, 0); bmp.UnlockBits(&data); Update(); texes.push_back(texture); //std::cout << texes.size() << std::endl; } void ChangeImage(const int num) { tex = texes.at(num); Update(); } void UpdateDirR() { if (center_x <= camera_x + 500 && center_x >= camera_x - 1500) { glBindTexture(GL_TEXTURE_2D, tex); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_TEXTURE_2D); glEnable(GL_ALPHA_TEST); glBegin(GL_POLYGON); glTexCoord2f(0.0f, 1.0f); glVertex2d(center_x + 64.0 / 2, center_y + 64.0 / 2);//左下 glTexCoord2f(0.0f, 0.0f); glVertex2d(center_x + 64.0 / 2, center_y - 64.0 / 2);//左上 glTexCoord2f(1.0f, 0.0f); glVertex2d(center_x - 64.0 / 2, center_y - 64.0 / 2);//右上 glTexCoord2f(1.0f, 1.0f); glVertex2d(center_x - 64.0 / 2, center_y + 64.0 / 2);//右下 glEnd(); glDisable(GL_ALPHA_TEST); glDisable(GL_TEXTURE_2D); glDisable(GL_BLEND); } } void UpdateDirL() { if (center_x <= camera_x + 500 && center_x >= camera_x - 1500) { glBindTexture(GL_TEXTURE_2D, tex); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_TEXTURE_2D); glEnable(GL_ALPHA_TEST); glBegin(GL_POLYGON); glTexCoord2f(1.0f, 1.0f); glVertex2d(center_x + 64.0 / 2, center_y + 64.0 / 2);//左下 glTexCoord2f(1.0f, 0.0f); glVertex2d(center_x + 64.0 / 2, center_y - 64.0 / 2);//左上 glTexCoord2f(0.0f, 0.0f); glVertex2d(center_x - 64.0 / 2, center_y - 64.0 / 2);//右上 glTexCoord2f(0.0f, 1.0f); glVertex2d(center_x - 64.0 / 2, center_y + 64.0 / 2);//右下 glEnd(); glDisable(GL_ALPHA_TEST); glDisable(GL_TEXTURE_2D); glDisable(GL_BLEND); } } }; GameObject floor1 = GameObject(0, 0, 64, 64, L"./pic/ground.png"); GameObject player1 = GameObject(0, 0, 64, 64, L"./pic/player_walk1.png"); GameObject player2 = GameObject(0, 0, 64, 64, L"./pic/player_walk2.png"); GameObject player3 = GameObject(0, 0, 64, 64, L"./pic/player_walk3.png"); GameObject UI_title = GameObject(0, 0, 768, 256, L"./pic/title_a.png"); GameObject UI_quit = GameObject(0, 0, 256, 32, L"./pic/title_quit.png"); GameObject UI_gamestart = GameObject(0, 0, 512, 64, L"./pic/game_start.png"); GameObject UI_pressstart = GameObject(0, 0, 128, 64, L"./pic/press.png"); GameObject block_alphabet_p = GameObject(0, 0, 128, 128, L"./pic/block_alphabet_p.png"); GameObject block_alphabet_a = GameObject(0, 0, 128, 128, L"./pic/block_alphabet_a.png"); GameObject block_alphabet_u = GameObject(0, 0, 128, 128, L"./pic/block_alphabet_u.png"); GameObject block_alphabet_s = GameObject(0, 0, 128, 128, L"./pic/block_alphabet_s.png"); GameObject block_alphabet_e = GameObject(0, 0, 128, 128, L"./pic/block_alphabet_e.png"); GameObject UI_return = GameObject(0, 0, 768, 96, L"./pic/pause_menu.png"); GameObject UI_highscore = GameObject(0, 0, 256, 32, L"./pic/highscore.png"); GameObject UI_gameover = GameObject(0, 0, 1024, 128, L"./pic/gameover.png"); GameObject UI_tonext = GameObject(0, 0, 1024, 128, L"./pic/menu_tonext01.png"); GameObject UI_difficulty01 = GameObject(0, 0, 256, 64, L"./pic/difficulty_menu01.png"); GameObject UI_difficulty02 = GameObject(0, 0, 256, 64, L"./pic/difficulty_menu02.png"); GameObject UI_difficulty03 = GameObject(0, 0, 256, 64, L"./pic/difficulty_menu03.png"); GameObject UI_07 = GameObject(0, 0, 384, 192, L"./pic/menu_UI_07.png"); GameObject UI_08 = GameObject(0, 0, 512, 256, L"./pic/menu_UI_08.png"); GameObject UI_09 = GameObject(0, 0, 1024, 64, L"./pic/menu_UI_09.png"); GameObject UI_13 = GameObject(0, 0, 1024, 128, L"./pic/menu_tonext02.png"); GameObject UI_14 = GameObject(0, 0, 1024, 128, L"./pic/are_you_ready.png"); GameObject UI_result01 = GameObject(0, 0, 384, 48, L"./pic/result_01.png"); GameObject UI_result02 = GameObject(0, 0, 384, 48, L"./pic/result_02.png"); GameObject UI_result03 = GameObject(0, 0, 384, 48, L"./pic/result_03.png"); GameObject UI_result04 = GameObject(0, 0, 384, 48, L"./pic/result_04.png"); GameObject UI_score = GameObject(0, 0, 128, 32, L"./pic/score.png"); GameObject UI_newrecord = GameObject(0, 0, 512, 256, L"./pic/result_newrecord.png"); GameObject UI_ranking = GameObject(0, 0, 384, 192, L"./pic/result_ranking.png"); GameObject UI_rank01 = GameObject(0, 0, 80, 40, L"./pic/ranking_01.png"); GameObject UI_rank02 = GameObject(0, 0, 80, 40, L"./pic/ranking_02.png"); GameObject UI_rank03 = GameObject(0, 0, 80, 40, L"./pic/ranking_03.png"); GameObject UI_rank04 = GameObject(0, 0, 80, 40, L"./pic/ranking_04.png"); GameObject UI_rank05 = GameObject(0, 0, 80, 40, L"./pic/ranking_05.png"); GameObject BG_01 = GameObject(0, 0, 1024, 512, L"./pic/bg01.png"); GameObject BG_02 = GameObject(0, 0, 1024, 512, L"./pic/bg02.png"); GameObject BG_03 = GameObject(0, 0, 1024, 512, L"./pic/bg03.png"); GameObject BG_04 = GameObject(0, 0, 1024, 512, L"./pic/bg04.png"); GameObject BG_05 = GameObject(0, 0, 1024, 512, L"./pic/bg05.png"); GameObject UI_10 = GameObject(0, 0, 384, 192, L"./pic/menu_UI_10.png"); GameObject UI_11 = GameObject(0, 0, 256, 64, L"./pic/menu_UI_11.png"); GameObject UI_12 = GameObject(0, 0, 384, 192, L"./pic/menu_UI_12.png"); GameObject UI_15 = GameObject(0, 0, 1024, 64, L"./pic/menu_UI_15.png"); GameObject UI_16 = GameObject(0, 0, 768, 96, L"./pic/menu_UI_16.png"); GameObject UI_17 = GameObject(0, 0, 768, 96, L"./pic/menu_UI_17.png"); GameObject UI_slot_base_3 = GameObject(0, 0, 768, 192, L"./pic/slot_base_3.png"); GameObject UI_slot_base_4 = GameObject(0, 0, 768, 192, L"./pic/slot_base_4.png"); GameObject UI_slot_base_5 = GameObject(0, 0, 768, 192, L"./pic/slot_base_5.png"); GameObject UI_slot_highlight = GameObject(0, 0, 192, 192, L"./pic/slot_highlight.png"); GameObject UI_slot_decision = GameObject(0, 0, 192, 192, L"./pic/slot_decision.png"); GameObject UI_slot_decision_green = GameObject(0, 0, 192, 192, L"./pic/slot_decision_green.png"); GameObject arrow = GameObject(0, 0, 128, 128, L"./pic/arrow.png"); GameObject select_highlight = GameObject(0, 0, 136, 136, L"./pic/Y.png"); GameObject player_penalty = GameObject(0, 0, 96, 24, L"./pic/player_penalty.png"); GameObject player_maru = GameObject(0, 0, 64, 64, L"./pic/maru.png"); GameObject player_batsu = GameObject(0, 0, 64, 64, L"./pic/batsu.png"); GameObject player_fukidashi01 = GameObject(0, 0, 64, 64, L"./pic/fukidashi1.png"); GameObject player_fukidashi02 = GameObject(0, 0, 64, 64, L"./pic/fukidashi2.png"); GameObject UI_confirm = GameObject(0, 0, 1024, 128, L"./pic/confirm.png"); GameObject UI_confirm_2 = GameObject(0, 0, 1024, 128, L"./pic/confirm_2.png"); GameObject UI_mode_score_attack = GameObject(0, 0, 512, 256, L"./pic/mode_score_attack.png"); GameObject UI_mode_stage_clear = GameObject(0, 0, 512, 256, L"./pic/mode_stage_clear.png"); GameObject UI_mode_highlight = GameObject(0, 0, 512, 256, L"./pic/mode_highlight.png"); GameObject UI_mode_description_1 = GameObject(0, 0, 512, 512, L"./pic/mode_description_1.png"); GameObject UI_mode_description_2 = GameObject(0, 0, 512, 512, L"./pic/mode_description_2.png"); GameObject UI_mode_select_UI = GameObject(0, 0, 768, 96, L"./pic/mode_select_UI.png"); GameObject UI_mode_mojisu = GameObject(0, 0, 1024, 128, L"./pic/select_mojisu.png"); GameObject UI_mode_stage = GameObject(0, 0, 1024, 128, L"./pic/select_stage.png"); GameObject UI_mode_3 = GameObject(0, 0, 192, 192, L"./pic/3.png"); GameObject UI_mode_4 = GameObject(0, 0, 192, 192, L"./pic/4.png"); GameObject UI_mode_5 = GameObject(0, 0, 192, 192, L"./pic/5.png"); GameObject UI_mode_mojisu_highlight = GameObject(0, 0, 192, 192, L"./pic/mojisu_highlight.png"); GameObject UI_mode_select_mojisu_UI = GameObject(0, 0, 1024, 128, L"./pic/mode_select_mojisu_UI.png"); //GameObject UI_mode_highscore = GameObject(0, 0, 320, 40, L"./pic/highscore.png"); GameObject UI_mode_waku = GameObject(0, 0, 512, 512, L"./pic/waku_1.png"); GameObject UI_mode_highscore_1 = GameObject(0, 0, 512, 512, L"./pic/mode_highscore_1.png"); GameObject UI_mode_highscore_2 = GameObject(0, 0, 512, 512, L"./pic/mode_highscore_2.png"); GameObject UI_slot_locked = GameObject(0, 0, 192, 192, L"./pic/slot_locked.png"); GameObject UI_block_stage_num = GameObject(0, 0, 96, 96, L"./pic/block_stage_num.png"); GameObject UI_block_stage_num_select = GameObject(0, 0, 192, 192, L"./pic/block_stage_num_selected.png"); GameObject UI_clear_lamp_on_1 = GameObject(0, 0, 160, 40, L"./pic/clear_lamp_on_1.png"); GameObject UI_clear_lamp_on_2 = GameObject(0, 0, 160, 40, L"./pic/clear_lamp_on_2.png"); GameObject UI_clear_lamp_on_3 = GameObject(0, 0, 160, 40, L"./pic/clear_lamp_on_3.png"); GameObject UI_clear_lamp_on_1_lux = GameObject(0, 0, 160, 40, L"./pic/clear_lamp_on_1_lux.png"); GameObject UI_clear_lamp_on_2_lux = GameObject(0, 0, 160, 40, L"./pic/clear_lamp_on_2_lux.png"); GameObject UI_clear_lamp_on_3_lux = GameObject(0, 0, 160, 40, L"./pic/clear_lamp_on_3_lux.png"); GameObject UI_clear_lamp_off = GameObject(0, 0, 160, 40, L"./pic/clear_lamp_off.png"); GameObject UI_time_limit_description= GameObject(0, 0, 1024, 64, L"./pic/time_limit_description.png"); GameObject UI_coming_soon64 = GameObject(0, 0, 64, 64, L"./pic/coming_soon.png"); GameObject UI_coming_soon192 = GameObject(0, 0, 192, 192, L"./pic/coming_soon.png"); GameObject UI_slot_constraint_description = GameObject(0, 0, 1024, 64, L"./pic/slot_constraint_description.png"); GameObject UI_mission_description_0 = GameObject(0, 0, 1024, 64, L"./pic/mission_description_0.png"); GameObject UI_mission_description_1 = GameObject(0, 0, 1024, 64, L"./pic/mission_description_1.png"); GameObject UI_mission_description_2 = GameObject(0, 0, 1024, 64, L"./pic/mission_description_2.png"); GameObject UI_num_aslash = GameObject(0, 0, 20, 20, L"./pic/num_aslash.png"); GameObject UI_num_aslash_big = GameObject(0, 0, 40, 40, L"./pic/num_aslash.png"); GameObject UI_result_stage = GameObject(0, 0, 768, 384, L"./pic/result_stage.png"); GameObject UI_result_stage_title = GameObject(0, 0, 384, 96, L"./pic/result_stage_title.png"); GameObject UI_result_stage_medal_1 = GameObject(0, 0, 768, 384, L"./pic/result_stage_medal_1.png"); GameObject UI_result_stage_medal_2 = GameObject(0, 0, 768, 384, L"./pic/result_stage_medal_2.png"); GameObject UI_result_stage_medal_3 = GameObject(0, 0, 768, 384, L"./pic/result_stage_medal_3.png"); GameObject UI_result_stage_medal_1_lux = GameObject(0, 0, 768, 384, L"./pic/result_stage_medal_1_lux.png"); GameObject UI_result_stage_medal_2_lux = GameObject(0, 0, 768, 384, L"./pic/result_stage_medal_2_lux.png"); GameObject UI_result_stage_medal_3_lux = GameObject(0, 0, 768, 384, L"./pic/result_stage_medal_3_lux.png"); GameObject UI_arrow_2L = GameObject(0, 0, 64, 64, L"./pic/arrow_2L.png"); GameObject UI_arrow_2R = GameObject(0, 0, 64, 64, L"./pic/arrow_2R.png"); GameObject UI_arrow_2D = GameObject(0, 0, 64, 64, L"./pic/arrow_2D.png"); GameObject block_hiragana_UI[80] = { GameObject(0, 0, 96, 96, L"./pic/block_blank.png"), //空白 ID:0 GameObject(0, 0, 96, 96, L"./pic/block_hiragana_01.png"), //あ GameObject(0, 0, 96, 96, L"./pic/block_hiragana_02.png"), //い GameObject(0, 0, 96, 96, L"./pic/block_hiragana_03.png"), //う GameObject(0, 0, 96, 96, L"./pic/block_hiragana_04.png"), //え GameObject(0, 0, 96, 96, L"./pic/block_hiragana_05.png"), //お GameObject(0, 0, 96, 96, L"./pic/block_hiragana_06.png"), //か GameObject(0, 0, 96, 96, L"./pic/block_hiragana_07.png"), //き GameObject(0, 0, 96, 96, L"./pic/block_hiragana_08.png"), //く GameObject(0, 0, 96, 96, L"./pic/block_hiragana_09.png"), //け GameObject(0, 0, 96, 96, L"./pic/block_hiragana_10.png"), //こ GameObject(0, 0, 96, 96, L"./pic/block_hiragana_11.png"), //さ GameObject(0, 0, 96, 96, L"./pic/block_hiragana_12.png"), //し GameObject(0, 0, 96, 96, L"./pic/block_hiragana_13.png"), //す GameObject(0, 0, 96, 96, L"./pic/block_hiragana_14.png"), //せ GameObject(0, 0, 96, 96, L"./pic/block_hiragana_15.png"), //そ GameObject(0, 0, 96, 96, L"./pic/block_hiragana_16.png"), //た GameObject(0, 0, 96, 96, L"./pic/block_hiragana_17.png"), //ち GameObject(0, 0, 96, 96, L"./pic/block_hiragana_18.png"), //つ GameObject(0, 0, 96, 96, L"./pic/block_hiragana_19.png"), //て GameObject(0, 0, 96, 96, L"./pic/block_hiragana_20.png"), //と GameObject(0, 0, 96, 96, L"./pic/block_hiragana_21.png"), //な GameObject(0, 0, 96, 96, L"./pic/block_hiragana_22.png"), //に GameObject(0, 0, 96, 96, L"./pic/block_hiragana_23.png"), //ぬ GameObject(0, 0, 96, 96, L"./pic/block_hiragana_24.png"), //ね GameObject(0, 0, 96, 96, L"./pic/block_hiragana_25.png"), //の GameObject(0, 0, 96, 96, L"./pic/block_hiragana_26.png"), //は GameObject(0, 0, 96, 96, L"./pic/block_hiragana_27.png"), //ひ GameObject(0, 0, 96, 96, L"./pic/block_hiragana_28.png"), //ふ GameObject(0, 0, 96, 96, L"./pic/block_hiragana_29.png"), //へ GameObject(0, 0, 96, 96, L"./pic/block_hiragana_30.png"), //ほ GameObject(0, 0, 96, 96, L"./pic/block_hiragana_31.png"), //ま GameObject(0, 0, 96, 96, L"./pic/block_hiragana_32.png"), //み GameObject(0, 0, 96, 96, L"./pic/block_hiragana_33.png"), //む GameObject(0, 0, 96, 96, L"./pic/block_hiragana_34.png"), //め GameObject(0, 0, 96, 96, L"./pic/block_hiragana_35.png"), //も GameObject(0, 0, 96, 96, L"./pic/block_hiragana_36.png"), //や GameObject(0, 0, 96, 96, L"./pic/block_hiragana_37.png"), //ゆ GameObject(0, 0, 96, 96, L"./pic/block_hiragana_38.png"), //よ GameObject(0, 0, 96, 96, L"./pic/block_hiragana_39.png"), //ら GameObject(0, 0, 96, 96, L"./pic/block_hiragana_40.png"), //り GameObject(0, 0, 96, 96, L"./pic/block_hiragana_41.png"), //る GameObject(0, 0, 96, 96, L"./pic/block_hiragana_42.png"), //れ GameObject(0, 0, 96, 96, L"./pic/block_hiragana_43.png"), //ろ GameObject(0, 0, 96, 96, L"./pic/block_hiragana_44.png"), //わ GameObject(0, 0, 96, 96, L"./pic/block_hiragana_45.png"), //を ID:45 GameObject(0, 0, 96, 96, L"./pic/block_hiragana_46.png"), //ん ID:46 GameObject(0, 0, 96, 96, L"./pic/block_hiragana_73.png"), //っ ID:47 GameObject(0, 0, 96, 96, L"./pic/block_hiragana_74.png"), //ヴ GameObject(0, 0, 96, 96, L"./pic/block_wood.png"), //木材(足場ブロック)ID:49 GameObject(0, 0, 96, 96, L"./pic/block_hiragana_47.png"), //ー ID:50 GameObject(0, 0, 96, 96, L"./pic/block_hiragana_48.png"), //が GameObject(0, 0, 96, 96, L"./pic/block_hiragana_49.png"), //ぎ GameObject(0, 0, 96, 96, L"./pic/block_hiragana_50.png"), //ぐ GameObject(0, 0, 96, 96, L"./pic/block_hiragana_51.png"), //げ GameObject(0, 0, 96, 96, L"./pic/block_hiragana_52.png"), //ご GameObject(0, 0, 96, 96, L"./pic/block_hiragana_53.png"), //ざ GameObject(0, 0, 96, 96, L"./pic/block_hiragana_54.png"), //じ GameObject(0, 0, 96, 96, L"./pic/block_hiragana_55.png"), //ず GameObject(0, 0, 96, 96, L"./pic/block_hiragana_56.png"), //zw GameObject(0, 0, 96, 96, L"./pic/block_hiragana_57.png"), //ぞ GameObject(0, 0, 96, 96, L"./pic/block_hiragana_58.png"), //だ GameObject(0, 0, 96, 96, L"./pic/block_hiragana_59.png"), //ぢ GameObject(0, 0, 96, 96, L"./pic/block_hiragana_60.png"), //づ GameObject(0, 0, 96, 96, L"./pic/block_hiragana_61.png"), //で GameObject(0, 0, 96, 96, L"./pic/block_hiragana_62.png"), //ど GameObject(0, 0, 96, 96, L"./pic/block_hiragana_63.png"), //ば GameObject(0, 0, 96, 96, L"./pic/block_hiragana_64.png"), //び GameObject(0, 0, 96, 96, L"./pic/block_hiragana_65.png"), //ぶ GameObject(0, 0, 96, 96, L"./pic/block_hiragana_66.png"), //べ GameObject(0, 0, 96, 96, L"./pic/block_hiragana_67.png"), //ぼ GameObject(0, 0, 96, 96, L"./pic/block_hiragana_68.png"), //ぱ GameObject(0, 0, 96, 96, L"./pic/block_hiragana_69.png"), //ぴ GameObject(0, 0, 96, 96, L"./pic/block_hiragana_70.png"), //ぷ GameObject(0, 0, 96, 96, L"./pic/block_hiragana_71.png"), //ぺ GameObject(0, 0, 96, 96, L"./pic/block_hiragana_72.png"),//ぽ GameObject(0, 0, 96, 96, L"./pic/ground.png"), //地面 ID:76 GameObject(0, 0, 96, 96, L"./pic/block_undifined.png"), //未使用(お題箱とかに使う? GameObject(0, 0, 96, 96, L"./pic/block_undifined.png"), //未使用(お題箱とかに使う? GameObject(0, 0, 96, 96, L"./pic/block_undifined.png") //未使用(お題箱とかに使う? }; GameObject block_hiragana[80] = { GameObject(0, 0, 64, 64, L"./pic/block_blank.png"), //空白 ID:0 GameObject(0, 0, 64, 64, L"./pic/block_hiragana_01.png"), //あ GameObject(0, 0, 64, 64, L"./pic/block_hiragana_02.png"), //い GameObject(0, 0, 64, 64, L"./pic/block_hiragana_03.png"), //う GameObject(0, 0, 64, 64, L"./pic/block_hiragana_04.png"), //え GameObject(0, 0, 64, 64, L"./pic/block_hiragana_05.png"), //お GameObject(0, 0, 64, 64, L"./pic/block_hiragana_06.png"), //か GameObject(0, 0, 64, 64, L"./pic/block_hiragana_07.png"), //き GameObject(0, 0, 64, 64, L"./pic/block_hiragana_08.png"), //く GameObject(0, 0, 64, 64, L"./pic/block_hiragana_09.png"), //け GameObject(0, 0, 64, 64, L"./pic/block_hiragana_10.png"), //こ GameObject(0, 0, 64, 64, L"./pic/block_hiragana_11.png"), //さ GameObject(0, 0, 64, 64, L"./pic/block_hiragana_12.png"), //し GameObject(0, 0, 64, 64, L"./pic/block_hiragana_13.png"), //す GameObject(0, 0, 64, 64, L"./pic/block_hiragana_14.png"), //せ GameObject(0, 0, 64, 64, L"./pic/block_hiragana_15.png"), //そ GameObject(0, 0, 64, 64, L"./pic/block_hiragana_16.png"), //た GameObject(0, 0, 64, 64, L"./pic/block_hiragana_17.png"), //ち GameObject(0, 0, 64, 64, L"./pic/block_hiragana_18.png"), //つ GameObject(0, 0, 64, 64, L"./pic/block_hiragana_19.png"), //て GameObject(0, 0, 64, 64, L"./pic/block_hiragana_20.png"), //と GameObject(0, 0, 64, 64, L"./pic/block_hiragana_21.png"), //な GameObject(0, 0, 64, 64, L"./pic/block_hiragana_22.png"), //に GameObject(0, 0, 64, 64, L"./pic/block_hiragana_23.png"), //ぬ GameObject(0, 0, 64, 64, L"./pic/block_hiragana_24.png"), //ね GameObject(0, 0, 64, 64, L"./pic/block_hiragana_25.png"), //の GameObject(0, 0, 64, 64, L"./pic/block_hiragana_26.png"), //は GameObject(0, 0, 64, 64, L"./pic/block_hiragana_27.png"), //ひ GameObject(0, 0, 64, 64, L"./pic/block_hiragana_28.png"), //ふ GameObject(0, 0, 64, 64, L"./pic/block_hiragana_29.png"), //へ GameObject(0, 0, 64, 64, L"./pic/block_hiragana_30.png"), //ほ GameObject(0, 0, 64, 64, L"./pic/block_hiragana_31.png"), //ま GameObject(0, 0, 64, 64, L"./pic/block_hiragana_32.png"), //み GameObject(0, 0, 64, 64, L"./pic/block_hiragana_33.png"), //む GameObject(0, 0, 64, 64, L"./pic/block_hiragana_34.png"), //め GameObject(0, 0, 64, 64, L"./pic/block_hiragana_35.png"), //も GameObject(0, 0, 64, 64, L"./pic/block_hiragana_36.png"), //や GameObject(0, 0, 64, 64, L"./pic/block_hiragana_37.png"), //ゆ GameObject(0, 0, 64, 64, L"./pic/block_hiragana_38.png"), //よ GameObject(0, 0, 64, 64, L"./pic/block_hiragana_39.png"), //ら GameObject(0, 0, 64, 64, L"./pic/block_hiragana_40.png"), //り GameObject(0, 0, 64, 64, L"./pic/block_hiragana_41.png"), //る GameObject(0, 0, 64, 64, L"./pic/block_hiragana_42.png"), //れ GameObject(0, 0, 64, 64, L"./pic/block_hiragana_43.png"), //ろ GameObject(0, 0, 64, 64, L"./pic/block_hiragana_44.png"), //わ GameObject(0, 0, 64, 64, L"./pic/block_hiragana_45.png"), //を ID:45 GameObject(0, 0, 64, 64, L"./pic/block_hiragana_46.png"), //ん ID:46 GameObject(0, 0, 64, 64, L"./pic/block_hiragana_73.png"), //っ ID:47 GameObject(0, 0, 64, 64, L"./pic/block_hiragana_74.png"), //ヴ GameObject(0, 0, 64, 64, L"./pic/block_wood.png"), //木材(足場ブロック)ID:49 GameObject(0, 0, 64, 64, L"./pic/block_hiragana_47.png"), //ー ID:50 GameObject(0, 0, 64, 64, L"./pic/block_hiragana_48.png"), //が GameObject(0, 0, 64, 64, L"./pic/block_hiragana_49.png"), //ぎ GameObject(0, 0, 64, 64, L"./pic/block_hiragana_50.png"), //ぐ GameObject(0, 0, 64, 64, L"./pic/block_hiragana_51.png"), //げ GameObject(0, 0, 64, 64, L"./pic/block_hiragana_52.png"), //ご GameObject(0, 0, 64, 64, L"./pic/block_hiragana_53.png"), //ざ GameObject(0, 0, 64, 64, L"./pic/block_hiragana_54.png"), //じ GameObject(0, 0, 64, 64, L"./pic/block_hiragana_55.png"), //ず GameObject(0, 0, 64, 64, L"./pic/block_hiragana_56.png"), //zw GameObject(0, 0, 64, 64, L"./pic/block_hiragana_57.png"), //ぞ GameObject(0, 0, 64, 64, L"./pic/block_hiragana_58.png"), //だ GameObject(0, 0, 64, 64, L"./pic/block_hiragana_59.png"), //ぢ GameObject(0, 0, 64, 64, L"./pic/block_hiragana_60.png"), //づ GameObject(0, 0, 64, 64, L"./pic/block_hiragana_61.png"), //で GameObject(0, 0, 64, 64, L"./pic/block_hiragana_62.png"), //ど GameObject(0, 0, 64, 64, L"./pic/block_hiragana_63.png"), //ば GameObject(0, 0, 64, 64, L"./pic/block_hiragana_64.png"), //び GameObject(0, 0, 64, 64, L"./pic/block_hiragana_65.png"), //ぶ GameObject(0, 0, 64, 64, L"./pic/block_hiragana_66.png"), //べ GameObject(0, 0, 64, 64, L"./pic/block_hiragana_67.png"), //ぼ GameObject(0, 0, 64, 64, L"./pic/block_hiragana_68.png"), //ぱ GameObject(0, 0, 64, 64, L"./pic/block_hiragana_69.png"), //ぴ GameObject(0, 0, 64, 64, L"./pic/block_hiragana_70.png"), //ぷ GameObject(0, 0, 64, 64, L"./pic/block_hiragana_71.png"), //ぺ GameObject(0, 0, 64, 64, L"./pic/block_hiragana_72.png"),//ぽ GameObject(0, 0, 64, 64, L"./pic/ground.png"), //地面 ID:76 GameObject(0, 0, 64, 64, L"./pic/block_odai.png"), //おだいばこ GameObject(0, 0, 64, 64, L"./pic/block_odai_off.png"), //お題箱オフ GameObject(0, 0, 64, 64, L"./pic/block_undifined.png") //未使用(お題箱とかに使う? }; GameObject block_hiragana_mini[80] = { GameObject(0, 0, 32, 32, L"./pic/block_blank.png"), //空白 ID:0 GameObject(0, 0, 32, 32, L"./pic/block_hiragana_01.png"), //あ GameObject(0, 0, 32, 32, L"./pic/block_hiragana_02.png"), //い GameObject(0, 0, 32, 32, L"./pic/block_hiragana_03.png"), //う GameObject(0, 0, 32, 32, L"./pic/block_hiragana_04.png"), //え GameObject(0, 0, 32, 32, L"./pic/block_hiragana_05.png"), //お GameObject(0, 0, 32, 32, L"./pic/block_hiragana_06.png"), //か GameObject(0, 0, 32, 32, L"./pic/block_hiragana_07.png"), //き GameObject(0, 0, 32, 32, L"./pic/block_hiragana_08.png"), //く GameObject(0, 0, 32, 32, L"./pic/block_hiragana_09.png"), //け GameObject(0, 0, 32, 32, L"./pic/block_hiragana_10.png"), //こ GameObject(0, 0, 32, 32, L"./pic/block_hiragana_11.png"), //さ GameObject(0, 0, 32, 32, L"./pic/block_hiragana_12.png"), //し GameObject(0, 0, 32, 32, L"./pic/block_hiragana_13.png"), //す GameObject(0, 0, 32, 32, L"./pic/block_hiragana_14.png"), //せ GameObject(0, 0, 32, 32, L"./pic/block_hiragana_15.png"), //そ GameObject(0, 0, 32, 32, L"./pic/block_hiragana_16.png"), //た GameObject(0, 0, 32, 32, L"./pic/block_hiragana_17.png"), //ち GameObject(0, 0, 32, 32, L"./pic/block_hiragana_18.png"), //つ GameObject(0, 0, 32, 32, L"./pic/block_hiragana_19.png"), //て GameObject(0, 0, 32, 32, L"./pic/block_hiragana_20.png"), //と GameObject(0, 0, 32, 32, L"./pic/block_hiragana_21.png"), //な GameObject(0, 0, 32, 32, L"./pic/block_hiragana_22.png"), //に GameObject(0, 0, 32, 32, L"./pic/block_hiragana_23.png"), //ぬ GameObject(0, 0, 32, 32, L"./pic/block_hiragana_24.png"), //ね GameObject(0, 0, 32, 32, L"./pic/block_hiragana_25.png"), //の GameObject(0, 0, 32, 32, L"./pic/block_hiragana_26.png"), //は GameObject(0, 0, 32, 32, L"./pic/block_hiragana_27.png"), //ひ GameObject(0, 0, 32, 32, L"./pic/block_hiragana_28.png"), //ふ GameObject(0, 0, 32, 32, L"./pic/block_hiragana_29.png"), //へ GameObject(0, 0, 32, 32, L"./pic/block_hiragana_30.png"), //ほ GameObject(0, 0, 32, 32, L"./pic/block_hiragana_31.png"), //ま GameObject(0, 0, 32, 32, L"./pic/block_hiragana_32.png"), //み GameObject(0, 0, 32, 32, L"./pic/block_hiragana_33.png"), //む GameObject(0, 0, 32, 32, L"./pic/block_hiragana_34.png"), //め GameObject(0, 0, 32, 32, L"./pic/block_hiragana_35.png"), //も GameObject(0, 0, 32, 32, L"./pic/block_hiragana_36.png"), //や GameObject(0, 0, 32, 32, L"./pic/block_hiragana_37.png"), //ゆ GameObject(0, 0, 32, 32, L"./pic/block_hiragana_38.png"), //よ GameObject(0, 0, 32, 32, L"./pic/block_hiragana_39.png"), //ら GameObject(0, 0, 32, 32, L"./pic/block_hiragana_40.png"), //り GameObject(0, 0, 32, 32, L"./pic/block_hiragana_41.png"), //る GameObject(0, 0, 32, 32, L"./pic/block_hiragana_42.png"), //れ GameObject(0, 0, 32, 32, L"./pic/block_hiragana_43.png"), //ろ GameObject(0, 0, 32, 32, L"./pic/block_hiragana_44.png"), //わ GameObject(0, 0, 32, 32, L"./pic/block_hiragana_45.png"), //を ID:45 GameObject(0, 0, 32, 32, L"./pic/block_hiragana_46.png"), //ん ID:46 GameObject(0, 0, 32, 32, L"./pic/block_hiragana_73.png"), //っ ID:47 GameObject(0, 0, 32, 32, L"./pic/block_hiragana_74.png"), //ヴ GameObject(0, 0, 32, 32, L"./pic/block_wood.png"), //木材(足場ブロック)ID:49 GameObject(0, 0, 32, 32, L"./pic/block_hiragana_47.png"), //ー ID:50 GameObject(0, 0, 32, 32, L"./pic/block_hiragana_48.png"), //が GameObject(0, 0, 32, 32, L"./pic/block_hiragana_49.png"), //ぎ GameObject(0, 0, 32, 32, L"./pic/block_hiragana_50.png"), //ぐ GameObject(0, 0, 32, 32, L"./pic/block_hiragana_51.png"), //げ GameObject(0, 0, 32, 32, L"./pic/block_hiragana_52.png"), //ご GameObject(0, 0, 32, 32, L"./pic/block_hiragana_53.png"), //ざ GameObject(0, 0, 32, 32, L"./pic/block_hiragana_54.png"), //じ GameObject(0, 0, 32, 32, L"./pic/block_hiragana_55.png"), //ず GameObject(0, 0, 32, 32, L"./pic/block_hiragana_56.png"), //zw GameObject(0, 0, 32, 32, L"./pic/block_hiragana_57.png"), //ぞ GameObject(0, 0, 32, 32, L"./pic/block_hiragana_58.png"), //だ GameObject(0, 0, 32, 32, L"./pic/block_hiragana_59.png"), //ぢ GameObject(0, 0, 32, 32, L"./pic/block_hiragana_60.png"), //づ GameObject(0, 0, 32, 32, L"./pic/block_hiragana_61.png"), //で GameObject(0, 0, 32, 32, L"./pic/block_hiragana_62.png"), //ど GameObject(0, 0, 32, 32, L"./pic/block_hiragana_63.png"), //ば GameObject(0, 0, 32, 32, L"./pic/block_hiragana_64.png"), //び GameObject(0, 0, 32, 32, L"./pic/block_hiragana_65.png"), //ぶ GameObject(0, 0, 32, 32, L"./pic/block_hiragana_66.png"), //べ GameObject(0, 0, 32, 32, L"./pic/block_hiragana_67.png"), //ぼ GameObject(0, 0, 32, 32, L"./pic/block_hiragana_68.png"), //ぱ GameObject(0, 0, 32, 32, L"./pic/block_hiragana_69.png"), //ぴ GameObject(0, 0, 32, 32, L"./pic/block_hiragana_70.png"), //ぷ GameObject(0, 0, 32, 32, L"./pic/block_hiragana_71.png"), //ぺ GameObject(0, 0, 32, 32, L"./pic/block_hiragana_72.png"),//ぽ GameObject(0, 0, 32, 32, L"./pic/ground.png"), //地面 ID:76 GameObject(0, 0, 32, 32, L"./pic/block_odai.png"), //おだいばこ GameObject(0, 0, 32, 32, L"./pic/block_odai_off.png"), //お題箱オフ GameObject(0, 0, 32, 32, L"./pic/block_undifined.png") //未使用(お題箱とかに使う? }; GameObject block_light_1 = GameObject(0, 0, 64, 64, L"./pic/block_highlight_1.png"); //ルーレットブロックのライトエフェクト(明 GameObject block_light_2 = GameObject(0, 0, 64, 64, L"./pic/block_highlight_2.png"); //ルーレットブロックのライトエフェクト(暗 AnimationChara *player; //プレイヤーのあらゆる情報を扱う AnimationChara *bullet; //弾丸のあらゆる情報を扱う Mix_Chunk *SE_select = NULL; //効果音たち Mix_Chunk *SE_back = NULL; Mix_Chunk *SE_batsu = NULL; Mix_Chunk *SE_enter = NULL; Mix_Chunk *SE_hit = NULL; Mix_Chunk *SE_jump = NULL; Mix_Chunk *SE_maru = NULL; Mix_Chunk *SE_shoot = NULL; Mix_Chunk *SE_throw = NULL; void end() { GdiplusShutdown(gdiPT); } void check_goi(int* moji) { float *hs3 = &hiragana_score_3[0][0]; float *hs4 = &hiragana_score_4[0][0]; float *hs5 = &hiragana_score_5[0][0]; int *dic3 = &dic_3moji[0][0]; int *dic4 = &dic_4moji[0][0]; int *dic5 = &dic_5moji[0][0]; int *lmhr = &list_most_hiragana[0]; if (mode == 0)//スコアモード { switch (mode_mojisu) { case 3: { for (i = 0; i < dic_3_all; i++) { if (moji[0] == *(dic3 + i * 3) && moji[1] == *(dic3 + i * 3 + 1) && moji[2] == *(dic3 + i * 3 + 2)) { word_hit = true; Mix_PlayChannel(-1, SE_maru, 0); score_word = (int)(*(hs3 + 3 * moji[0]) + *(hs3 + 3 * moji[1] + 1) + *(hs3 + 3 * moji[2] + 2) ); score += score_word; score_tango++; (*(lmhr + moji[0]))++; (*(lmhr + moji[1]))++; (*(lmhr + moji[2]))++; break; } } if (word_hit == false) //ペナルティ { Mix_PlayChannel(-1, SE_batsu, 0); time -= 30 * 60; } }break; case 4: { for (i = 0; i < dic_4_all; i++) { if (moji[0] == *(dic4 + i * 4) && moji[1] == *(dic4 + i * 4 + 1) && moji[2] == *(dic4 + i * 4 + 2) && moji[3] == *(dic4 + i * 4 + 3)) { word_hit = true; Mix_PlayChannel(-1, SE_maru, 0); score_word = (int)(*(hs4 + 4 * moji[0]) + *(hs4 + 4 * moji[1] + 1) + *(hs4 + 4 * moji[2] + 2) + *(hs4 + 4 * moji[3] + 3)); score += score_word; score_tango++; (*(lmhr + moji[0]))++; (*(lmhr + moji[1]))++; (*(lmhr + moji[2]))++; (*(lmhr + moji[3]))++; break; } } if (word_hit == false) //ペナルティ { Mix_PlayChannel(-1, SE_batsu, 0); time -= 30 * 60; } }break; case 5: { for (i = 0; i < dic_5_all; i++) { if (moji[0] == *(dic5 + i * 5) && moji[1] == *(dic5 + i * 5 + 1) && moji[2] == *(dic5 + i * 5 + 2) && moji[3] == *(dic5+ i * 5 + 3) && moji[4] == *(dic5 + i * 5 + 4)) { word_hit = true; Mix_PlayChannel(-1, SE_maru, 0); score_word = (int)(*(hs5 + 5 * moji[0]) + *(hs5 + 5 * moji[1] + 1) + *(hs5 + 45* moji[2] + 2) + *(hs5 + 5 * moji[3] + 3) + *(hs5 + 5 * moji[4] + 4)); score += score_word; score_tango++; (*(lmhr + moji[0]))++; (*(lmhr + moji[1]))++; (*(lmhr + moji[2]))++; (*(lmhr + moji[3]))++; (*(lmhr + moji[4]))++; break; } } if (word_hit == false) //ペナルティ { Mix_PlayChannel(-1, SE_batsu, 0); time -= 30 * 60; } }break; } } if (mode == 1)//ステージモード { switch (stage_info[stage_select] %10) { case 3: { for (i = 0; i < dic_3_all; i++) { if (moji[0] == *(dic3 + i * 3) && moji[1] == *(dic3 + i * 3 + 1) && moji[2] == *(dic3 + i * 3 + 2)) { for (k = 0; k <= score; k++) { if (made_tango[k][0] == moji[0] && made_tango[k][1] == moji[1] && made_tango[k][2] == moji[2]) { word_hit = false; break; } word_hit = true; Mix_PlayChannel(-1, SE_maru, 0); break; } } } if (word_hit == true) { made_tango[score][0] = moji[0]; made_tango[score][1] = moji[1]; made_tango[score][2] = moji[2]; score_word = 1; score += score_word; } if (word_hit == false) //ペナルティ { Mix_PlayChannel(-1, SE_batsu, 0); time -= 30 * 60; score_miss++; } }break; case 4: { for (i = 0; i < dic_4_all; i++) { if (moji[0] == *(dic4 + i * 4) && moji[1] == *(dic4 + i * 4 + 1) && moji[2] == *(dic4 + i * 4 + 2) && moji[3] == *(dic4 + i * 4 + 3)) { for (k = 0; k <= score; k++) { if (made_tango[k][0] == moji[0] && made_tango[k][1] == moji[1] && made_tango[k][2] == moji[2] && made_tango[k][3] == moji[3]) { word_hit = false; break; } word_hit = true; Mix_PlayChannel(-1, SE_maru, 0); break; } } } if (word_hit == true) { made_tango[score][0] = moji[0]; made_tango[score][1] = moji[1]; made_tango[score][2] = moji[2]; made_tango[score][3] = moji[3]; score_word = 1; score += score_word; } if (word_hit == false) //ペナルティ { Mix_PlayChannel(-1, SE_batsu, 0); time -= 30 * 60; score_miss++; } }break; case 5: { for (i = 0; i < dic_5_all; i++) { if (moji[0] == *(dic5 + i * 5) && moji[1] == *(dic5 + i *5 + 1) && moji[2] == *(dic5 + i * 5 + 2) && moji[3] == *(dic5 + i * 5 + 3) && moji[4] == *(dic5 + i * 5 + 4)) { for (k = 0; k <= score; k++) { if (made_tango[k][0] == moji[0] && made_tango[k][1] == moji[1] && made_tango[k][2] == moji[2] && made_tango[k][3] == moji[3] && made_tango[k][4] == moji[4]) { word_hit = false; break; } word_hit = true; Mix_PlayChannel(-1, SE_maru, 0); break; } } } if (word_hit == true) { made_tango[score][0] = moji[0]; made_tango[score][1] = moji[1]; made_tango[score][2] = moji[2]; made_tango[score][3] = moji[3]; made_tango[score][4] = moji[4]; score_word = 1; score += score_word; } if (word_hit == false) //ペナルティ { Mix_PlayChannel(-1, SE_batsu, 0); time -= 30 * 60; score_miss++; } }break; } } } void LoadImagePNG(const wchar_t* filename, GLuint &texture) { glEnable(GL_TEXTURE_2D); Bitmap bmp(filename); BitmapData data; bmp.LockBits(0, ImageLockModeRead, PixelFormat32bppARGB, &data); glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, 4, data.Width, data.Height, 0, GL_BGRA_EXT, GL_UNSIGNED_BYTE, data.Scan0); glBindTexture(GL_TEXTURE_2D, 0); bmp.UnlockBits(&data); } void SetNumImage(double x, double y, int size_x, int size_y, int num, int font, int d) { //プレイヤーエフェクトとしての数字 //dは文字同士の間隔 if (num >= 100000) //10万の位 { glBindTexture(GL_TEXTURE_2D, tex_num[font][num / 100000]); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_TEXTURE_2D); glEnable(GL_ALPHA_TEST); glBegin(GL_POLYGON); glTexCoord2f(0.0f, 1.0f); glVertex2d(size_x / 8 * 6 + x + d*5, size_y + y);//左下 glTexCoord2f(0.0f, 0.0f); glVertex2d(size_x / 8 * 6 + x + d * 5, y);//左上 glTexCoord2f(1.0f, 0.0f); glVertex2d(size_x / 8 * 5 + x + d * 5, y);//右上 glTexCoord2f(1.0f, 1.0f); glVertex2d(size_x / 8 * 5 + x + d * 5, size_y + y);//右下 glEnd(); glDisable(GL_ALPHA_TEST); glDisable(GL_TEXTURE_2D); glDisable(GL_BLEND); } if (num >= 10000) //1万の位 { glBindTexture(GL_TEXTURE_2D, tex_num[font][(num / 10000) % 10]); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_TEXTURE_2D); glEnable(GL_ALPHA_TEST); glBegin(GL_POLYGON); glTexCoord2f(0.0f, 1.0f); glVertex2d(size_x / 8 * 5 + x + d * 4, size_y + y);//左下 glTexCoord2f(0.0f, 0.0f); glVertex2d(size_x / 8 * 5 + x + d * 4, y);//左上 glTexCoord2f(1.0f, 0.0f); glVertex2d(size_x / 8 * 4 + x + d * 4, y);//右上 glTexCoord2f(1.0f, 1.0f); glVertex2d(size_x / 8 * 4 + x + d * 4, size_y + y);//右下 glEnd(); glDisable(GL_ALPHA_TEST); glDisable(GL_TEXTURE_2D); glDisable(GL_BLEND); } if (num >= 1000) //1000の位 { glBindTexture(GL_TEXTURE_2D, tex_num[font][(num / 1000) % 10]); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_TEXTURE_2D); glEnable(GL_ALPHA_TEST); glBegin(GL_POLYGON); glTexCoord2f(0.0f, 1.0f); glVertex2d(size_x / 8 * 4 + x + d * 3, size_y + y);//左下 glTexCoord2f(0.0f, 0.0f); glVertex2d(size_x / 8 * 4 + x + d * 3, y);//左上 glTexCoord2f(1.0f, 0.0f); glVertex2d(size_x / 8 * 3 + x + d * 3, y);//右上 glTexCoord2f(1.0f, 1.0f); glVertex2d(size_x / 8 * 3 + x + d * 3, size_y + y);//右下 glEnd(); glDisable(GL_ALPHA_TEST); glDisable(GL_TEXTURE_2D); glDisable(GL_BLEND); } if (num >= 100) //100の位 { glBindTexture(GL_TEXTURE_2D, tex_num[font][(num / 100) % 10]); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_TEXTURE_2D); glEnable(GL_ALPHA_TEST); glBegin(GL_POLYGON); glTexCoord2f(0.0f, 1.0f); glVertex2d(size_x / 8 * 3 + x + d * 2, size_y + y);//左下 glTexCoord2f(0.0f, 0.0f); glVertex2d(size_x / 8 * 3 + x + d * 2, y);//左上 glTexCoord2f(1.0f, 0.0f); glVertex2d(size_x / 8 * 2 + x + d * 2, y);//右上 glTexCoord2f(1.0f, 1.0f); glVertex2d(size_x / 8 * 2 + x + d * 2, size_y + y);//右下 glEnd(); glDisable(GL_ALPHA_TEST); glDisable(GL_TEXTURE_2D); glDisable(GL_BLEND); } if (num >= 10) //10の位 { glBindTexture(GL_TEXTURE_2D, tex_num[font][(num / 10) % 10]); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_TEXTURE_2D); glEnable(GL_ALPHA_TEST); glBegin(GL_POLYGON); glTexCoord2f(0.0f, 1.0f); glVertex2d(size_x / 8 * 2 + x + d * 1, size_y + y);//左下 glTexCoord2f(0.0f, 0.0f); glVertex2d(size_x / 8 * 2 + x + d * 1, y);//左上 glTexCoord2f(1.0f, 0.0f); glVertex2d(size_x / 8 * 1 + x + d * 1, y);//右上 glTexCoord2f(1.0f, 1.0f); glVertex2d(size_x / 8 * 1 + x + d * 1, size_y + y);//右下 glEnd(); glDisable(GL_ALPHA_TEST); glDisable(GL_TEXTURE_2D); glDisable(GL_BLEND); } glBindTexture(GL_TEXTURE_2D, tex_num[font][num % 10]); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_TEXTURE_2D); glEnable(GL_ALPHA_TEST); glBegin(GL_POLYGON); glTexCoord2f(0.0f, 1.0f); glVertex2d(size_x / 8 * 1 + x, size_y + y);//左下 glTexCoord2f(0.0f, 0.0f); glVertex2d(size_x / 8 * 1 + x, y);//左上 glTexCoord2f(1.0f, 0.0f); glVertex2d(size_x / 8 * 0 + x, y);//右上 glTexCoord2f(1.0f, 1.0f); glVertex2d(size_x / 8 * 0 + x, size_y + y);//右下 glEnd(); glDisable(GL_ALPHA_TEST); glDisable(GL_TEXTURE_2D); glDisable(GL_BLEND); //ここからプラス記号の描画 if (num >= 100000) { glBindTexture(GL_TEXTURE_2D, tex_num[font][10]); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_TEXTURE_2D); glEnable(GL_ALPHA_TEST); glBegin(GL_POLYGON); glTexCoord2f(0.0f, 1.0f); glVertex2d(size_x / 8 * 7 + x + 20, size_y + y);//左下 glTexCoord2f(0.0f, 0.0f); glVertex2d(size_x / 8 * 7 + x + 20, y);//左上 glTexCoord2f(1.0f, 0.0f); glVertex2d(size_x / 8 * 6 + x + 20, y);//右上 glTexCoord2f(1.0f, 1.0f); glVertex2d(size_x / 8 * 6 + x + 20, size_y + y);//右下 glEnd(); glDisable(GL_ALPHA_TEST); glDisable(GL_TEXTURE_2D); glDisable(GL_BLEND); } else if (num >= 10000 && num <= 99999) { glBindTexture(GL_TEXTURE_2D, tex_num[font][10]); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_TEXTURE_2D); glEnable(GL_ALPHA_TEST); glBegin(GL_POLYGON); glTexCoord2f(0.0f, 1.0f); glVertex2d(size_x / 8 * 6 + x + 20, size_y + y);//左下 glTexCoord2f(0.0f, 0.0f); glVertex2d(size_x / 8 * 6 + x + 20, y);//左上 glTexCoord2f(1.0f, 0.0f); glVertex2d(size_x / 8 * 5 + x + 20, y);//右上 glTexCoord2f(1.0f, 1.0f); glVertex2d(size_x / 8 * 5 + x + 20, size_y + y);//右下 glEnd(); glDisable(GL_ALPHA_TEST); glDisable(GL_TEXTURE_2D); glDisable(GL_BLEND); } else if (num >= 1000 && num <= 9999) { glBindTexture(GL_TEXTURE_2D, tex_num[font][10]); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_TEXTURE_2D); glEnable(GL_ALPHA_TEST); glBegin(GL_POLYGON); glTexCoord2f(0.0f, 1.0f); glVertex2d(size_x / 8 * 5 + x + 20, size_y + y);//左下 glTexCoord2f(0.0f, 0.0f); glVertex2d(size_x / 8 * 5 + x + 20, y);//左上 glTexCoord2f(1.0f, 0.0f); glVertex2d(size_x / 8 * 4 + x + 20, y);//右上 glTexCoord2f(1.0f, 1.0f); glVertex2d(size_x / 8 * 4 + x + 20, size_y + y);//右下 glEnd(); glDisable(GL_ALPHA_TEST); glDisable(GL_TEXTURE_2D); glDisable(GL_BLEND); } else if (num >= 100 && num <= 999) { glBindTexture(GL_TEXTURE_2D, tex_num[font][10]); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_TEXTURE_2D); glEnable(GL_ALPHA_TEST); glBegin(GL_POLYGON); glTexCoord2f(0.0f, 1.0f); glVertex2d(size_x / 8 * 4 + x + 20, size_y + y);//左下 glTexCoord2f(0.0f, 0.0f); glVertex2d(size_x / 8 * 4 + x + 20, y);//左上 glTexCoord2f(1.0f, 0.0f); glVertex2d(size_x / 8 * 3 + x + 20, y);//右上 glTexCoord2f(1.0f, 1.0f); glVertex2d(size_x / 8 * 3 + x + 20, size_y + y);//右下 glEnd(); glDisable(GL_ALPHA_TEST); glDisable(GL_TEXTURE_2D); glDisable(GL_BLEND); } else if (num >= 10 && num <= 99) { glBindTexture(GL_TEXTURE_2D, tex_num[font][10]); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_TEXTURE_2D); glEnable(GL_ALPHA_TEST); glBegin(GL_POLYGON); glTexCoord2f(0.0f, 1.0f); glVertex2d(size_x / 8 * 3 + x + 20, size_y + y);//左下 glTexCoord2f(0.0f, 0.0f); glVertex2d(size_x / 8 * 3 + x + 20, y);//左上 glTexCoord2f(1.0f, 0.0f); glVertex2d(size_x / 8 * 2 + x + 20, y);//右上 glTexCoord2f(1.0f, 1.0f); glVertex2d(size_x / 8 * 2 + x + 20, size_y + y);//右下 glEnd(); glDisable(GL_ALPHA_TEST); glDisable(GL_TEXTURE_2D); glDisable(GL_BLEND); } else if (num >= 1 && num <= 9) { glBindTexture(GL_TEXTURE_2D, tex_num[font][10]); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_TEXTURE_2D); glEnable(GL_ALPHA_TEST); glBegin(GL_POLYGON); glTexCoord2f(0.0f, 1.0f); glVertex2d(size_x / 8 * 2 + x + 20, size_y + y);//左下 glTexCoord2f(0.0f, 0.0f); glVertex2d(size_x / 8 * 2 + x + 20, y);//左上 glTexCoord2f(1.0f, 0.0f); glVertex2d(size_x / 8 * 1 + x + 20, y);//右上 glTexCoord2f(1.0f, 1.0f); glVertex2d(size_x / 8 * 1 + x + 20, size_y + y);//右下 glEnd(); glDisable(GL_ALPHA_TEST); glDisable(GL_TEXTURE_2D); glDisable(GL_BLEND); } } int choose_hiragana(void) //ひらがなブロックをランダムに選ぶ関数 { int a; do { a = rand_hiragana(mt); } while (a == 49); return a; } int choose_pattern(void) //ステージのブロック配置パターンをランダムに選ぶ関数 { int a; do { a = rand_pattern(mt); } while (a >= 15); return a; } int choose_odai(void) //ヒントブロックの中身をランダムに選ぶ関数 { int a; do { a = rand_odai(mt); } while (a >= 15); return a; } void set_block_info(int type, int x_grid, int y_grid, int leftside, int blocknum) //leftsideはそのまま使う { int *obbl = &object_block[blocknum][0]; *(obbl) = type; *(obbl+1) = (-64)*(leftside + x_grid); *(obbl+2) = (-64)*(y_grid); } void block_standby(void) //スコアアタックモード { j = 0; //オブジェクトブロックを配置するための添え字,1個設置したら1増える. object_on_stage = 0; int Q[12] = {}; //地形パターンを生成する際,同じ辞書の単語に含まれるひらがなを所定の位置に配置するため,その単語の番号を乱数で取得する //ここから100行程度,導入部分のブロックを配置 set_block_info(76, 0, -1, 0,j); j++; set_block_info(76, -1, -1, 0, j); j++; set_block_info(76, -2, -1, 0, j); j++; set_block_info(76, -3, -1, 0, j); j++; set_block_info(76, -4, -1, 0, j); j++; set_block_info(76, -5, -1, 0, j); j++; set_block_info(76, -6, -1, 0, j); j++; set_block_info(76, -7, -1, 0, j); j++; set_block_info(76, -8, -1, 0, j); j++; set_block_info(76, -9, -1, 0, j); j++; set_block_info(76, -10, -1, 0, j); j++; set_block_info(76, -11, -1, 0, j); j++; set_block_info(76, -12, -1, 0, j); j++; set_block_info(49, -1, 0, 0, j); j++; set_block_info(49, -1, 1, 0, j); j++; set_block_info(49, -1, 2, 0, j); j++; set_block_info(49, -1, 3, 0, j); j++; set_block_info(49, -1, 4, 0, j); j++; set_block_info(49, -1, 5, 0, j); j++; set_block_info(49, -1, 6, 0, j); j++; set_block_info(49, -1, 7, 0, j); j++; set_block_info(49, -1, 8, 0, j); j++; for (k = 0; k <= 39; k++) //床の配置 { set_block_info(76, k, -1, 0, j); j++; } set_block_info(11, 5, 0, 0, j); j++; set_block_info(2, 6, 0, 0, j); j++; set_block_info(14, 7, 0, 0, j); j++; set_block_info(2, 8, 0, 0, j); j++; set_block_info(49, 11, 0, 0, j); j++; set_block_info(49, 12, 0, 0, j); j++; set_block_info(49, 13, 0, 0, j); j++; set_block_info(49, 14, 0, 0, j); j++; set_block_info(49, 15, 0, 0, j); j++; set_block_info(49, 16, 0, 0, j); j++; set_block_info(49, 17, 0, 0, j); j++; set_block_info(49, 18, 0, 0, j); j++; set_block_info(5, 13, 1, 0, j); j++; set_block_info(10, 14, 1, 0, j); j++; set_block_info(21, 15, 1, 0, j); j++; set_block_info(2, 16, 1, 0, j); j++; set_block_info(14, 23, 0, 0, j); j++; set_block_info(7, 24, 0, 0, j); j++; set_block_info(44, 25, 0, 0, j); j++; set_block_info(9, 26, 0, 0, j); j++; set_block_info(5, 23, 3, 0, j); j++; set_block_info(5, 24, 3, 0, j); j++; set_block_info(59, 25, 3, 0, j); j++; set_block_info(7, 26, 3, 0, j); j++; set_block_info(38, 23, 6, 0, j); j++; set_block_info(10, 24, 6, 0, j); j++; set_block_info(63, 25, 6, 0, j); j++; set_block_info(21, 26, 6, 0, j); j++; set_block_info(49, 20, 2, 0, j); j++; set_block_info(49, 21, 2, 0, j); j++; set_block_info(49, 22, 2, 0, j); j++; set_block_info(49, 23, 2, 0, j); j++; set_block_info(49, 24, 2, 0, j); j++; set_block_info(49, 25, 2, 0, j); j++; set_block_info(49, 26, 2, 0, j); j++; set_block_info(49, 27, 2, 0, j); j++; set_block_info(49, 22, 5, 0, j); j++; set_block_info(49, 23, 5, 0, j); j++; set_block_info(49, 24, 5, 0, j); j++; set_block_info(49, 25, 5, 0, j); j++; set_block_info(49, 26, 5, 0, j); j++; set_block_info(49, 27, 5, 0, j); j++; set_block_info(49, 28, 5, 0, j); j++; set_block_info(49, 29, 5, 0, j); j++; set_block_info(49, 20, 3, 0, j); j++; set_block_info(49, 20, 4, 0, j); j++; set_block_info(49, 20, 5, 0, j); j++; set_block_info(49, 20, 6, 0, j); j++; set_block_info(49, 29, 0, 0, j); j++; set_block_info(49, 29, 1, 0, j); j++; set_block_info(49, 29, 2, 0, j); j++; set_block_info(49, 29, 3, 0, j); j++; set_block_info(49, 29, 4, 0, j); j++; set_block_info(49, 29, 5, 0, j); j++; set_block_info(12, 32, 0, 0, j); j++; set_block_info(12, 32, 1, 0, j); j++; set_block_info(25, 32, 2, 0, j); j++; set_block_info(2, 32, 3, 0, j); j++; set_block_info(12, 34, 0, 0, j); j++; set_block_info(12, 34, 1, 0, j); j++; set_block_info(31, 34, 2, 0, j); j++; set_block_info(2, 34, 3, 0, j); j++; set_block_info(49, 37, 0, 0, j); j++; set_block_info(49, 38, 0, 0, j); j++; set_block_info(49, 38, 1, 0, j); j++; set_block_info(49, 38, 2, 0, j); j++; set_block_info(49, 39, 0, 0, j); j++; set_block_info(49, 39, 1, 0, j); j++; set_block_info(49, 39, 2, 0, j); j++; set_block_info(49, 39, 3, 0, j); j++; set_block_info(49, 39, 4, 0, j); j++; set_leftside = 40; for (i = 0; i <= PATTERN_LIMIT; i++) //structureの配列をもとに左から配置していく { switch (stage_structure[i]) { case 1: //サンプル { for (k = 0; k <= 16; k++) //床の配置 { set_block_info(76, k, -1, set_leftside, j); j++; } set_block_info(10, 3, 0, set_leftside, j); j++; set_block_info(20, 3, 2, set_leftside, j); j++; set_block_info(68, 3, 4, set_leftside, j); j++; set_block_info(7, 4, 0, set_leftside, j); j++; set_block_info(54, 4, 2, set_leftside, j); j++; set_block_info(46, 4, 4, set_leftside, j); j++; set_block_info(6, 6, 0, set_leftside, j); j++; set_block_info(50, 5, 2, set_leftside, j); j++; set_block_info(46, 6, 4, set_leftside, j); j++; set_block_info(13, 7, 0, set_leftside, j); j++; set_block_info(75, 7, 2, set_leftside, j); j++; set_block_info(22, 7, 4, set_leftside, j); j++; set_block_info(18, 8, 0, set_leftside, j); j++; set_block_info(2, 8, 2, set_leftside, j); j++; set_block_info(19, 8, 4, set_leftside, j); j++; set_block_info(17, 10, 0, set_leftside, j); j++; set_block_info(40, 9, 2, set_leftside, j); j++; set_block_info(47, 10, 4, set_leftside, j); j++; set_block_info(45, 11, 0, set_leftside, j); j++; set_block_info(18, 11, 2, set_leftside, j); j++; set_block_info(3, 11, 4, set_leftside, j); j++; set_block_info(19, 12, 0, set_leftside, j); j++; set_block_info(3, 12, 2, set_leftside, j); j++; set_block_info(33, 12, 4, set_leftside, j); j++; set_block_info(49, 0, 1, set_leftside, j); j++; set_block_info(49, 1, 3, set_leftside, j); j++; set_block_info(49, 15, 1, set_leftside, j); j++; set_block_info(49, 14, 3, set_leftside, j); j++; set_leftside += 17; }break; case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 11: case 12: case 13: { for (k = 0; k <= 16; k++) //床の配置 { set_block_info(76, k, -1, set_leftside, j); j++; } for (k = 0; k <= 5; k++) //配置するブロックがどの単語のひらがなか,の単語の番号を決める { do { Q[k] = rand_dic_4(mt); } while (Q[k]>=dic_4_all); } set_block_info(dic_4moji[Q[0]][0], 3, 0, set_leftside, j); j++; set_block_info(dic_4moji[Q[0]][2], 3, 2, set_leftside, j); j++; set_block_info(dic_4moji[Q[0]][3], 3, 4, set_leftside, j); j++; set_block_info(dic_4moji[Q[0]][1], 4, 0, set_leftside, j); j++; set_block_info(dic_4moji[Q[1]][2], 4, 2, set_leftside, j); j++; set_block_info(dic_4moji[Q[1]][0], 4, 4, set_leftside, j); j++; set_block_info(dic_4moji[Q[1]][3], 6, 0, set_leftside, j); j++; set_block_info(dic_4moji[Q[2]][1], 5, 2, set_leftside, j); j++; set_block_info(dic_4moji[Q[1]][1], 6, 4, set_leftside, j); j++; set_block_info(dic_4moji[Q[2]][0], 7, 0, set_leftside, j); j++; set_block_info(dic_4moji[Q[2]][2], 7, 2, set_leftside, j); j++; set_block_info(choose_hiragana() , 7, 4, set_leftside, j); j++; set_block_info(dic_4moji[Q[2]][3], 8, 0, set_leftside, j); j++; set_block_info(choose_hiragana(), 8, 2, set_leftside, j); j++; set_block_info(choose_hiragana(), 8, 4, set_leftside, j); j++; set_block_info(dic_4moji[Q[4]][1], 10, 0, set_leftside, j); j++; set_block_info(dic_4moji[Q[4]][0], 9, 2, set_leftside, j); j++; set_block_info(choose_hiragana(), 10, 4, set_leftside, j); j++; set_block_info(dic_4moji[Q[5]][1], 11, 0, set_leftside, j); j++; set_block_info(dic_4moji[Q[5]][3], 11, 2, set_leftside, j); j++; set_block_info(dic_4moji[Q[4]][2], 11, 4, set_leftside, j); j++; set_block_info(dic_4moji[Q[5]][0], 12, 0, set_leftside, j); j++; set_block_info(dic_4moji[Q[5]][2], 12, 2, set_leftside, j); j++; set_block_info(dic_4moji[Q[4]][3], 12, 4, set_leftside, j); j++; set_block_info(49, 0, 1, set_leftside, j); j++; set_block_info(49, 1, 3, set_leftside, j); j++; set_block_info(49, 15, 1, set_leftside, j); j++; set_block_info(49, 14, 3, set_leftside, j); j++; set_leftside += 17; }break; case 254: //ボーナスエリア { for (k = 0; k <= 16; k++) //床の配置 { set_block_info(76, k, -1, set_leftside, j); j++; } set_block_info(79, 4, 0, set_leftside, j); j++; set_block_info(79, 5, 0, set_leftside, j); j++; set_block_info(79, 4, 2, set_leftside, j); j++; set_block_info(79, 5, 2, set_leftside, j); j++; set_block_info(79, 4, 4, set_leftside, j); j++; set_block_info(79, 5, 4, set_leftside, j); j++; set_block_info(79, 11, 0, set_leftside, j); j++; set_block_info(79, 12, 0, set_leftside, j); j++; set_block_info(79, 11, 2, set_leftside, j); j++; set_block_info(79, 12, 2, set_leftside, j); j++; set_block_info(79, 11, 4, set_leftside, j); j++; set_block_info(79, 12, 4, set_leftside, j); j++; set_block_info(77, 5, 6, set_leftside, j); j++; set_block_info(77, 11, 6, set_leftside, j); j++; set_block_info(49, 1, 3, set_leftside, j); j++; set_block_info(49, 2, 1, set_leftside, j); j++; set_block_info(49, 7, 1, set_leftside, j); j++; set_block_info(49, 8, 3, set_leftside, j); j++; set_block_info(49, 9, 1, set_leftside, j); j++; set_block_info(49, 14, 1, set_leftside, j); j++; set_block_info(49, 15, 3, set_leftside, j); j++; set_leftside += 17; }break; case 255: //終端 { for (k = 0; k <= 10; k++) //床の配置 { set_block_info(76, k, -1, set_leftside, j); j++; } for (k = 0; k <= 10; k++) //床の配置 { for (l = 0; l <= 10; l++) //床の配置 { set_block_info(49, l, k, set_leftside, j); j++; } } set_leftside += 11; }break; default: { set_block_info(76, 0, -1, set_leftside, j); j++; set_leftside += 1; }break; } } object_on_stage = j; std::cout << "<info 024: " << object_on_stage <<"個のオブジェクトがステージに配置されました" << std::endl; } void standby_stage(int stage_num) //ステージモード { time = stage_time_limit[stage_num]*60; player->center_x = 0; player->center_y = -8; score = 0; score_miss = 0; lamp_timer_01 = 0; lamp_timer_02 = 0; slot_select = 0; char file_path[32]; //ステージファイルを読み込むときのステージ名 for (i = 0; i <= 100; i++) //作った単語のやつをリセットする { made_tango[i][0] = 0; made_tango[i][1] = 0; made_tango[i][2] = 0; made_tango[i][3] = 0; made_tango[i][4] = 0; } for (i = 0; i <= OBJECT_LIMIT; i++) //ゲーム内ブロックをリセットする { object_block[i][0] = 0; object_block[i][1] = 0; object_block[i][2] = 0; } object_on_stage = 0; sprintf_s(file_path, "./dat/stage_%03d.dat", stage_num); //ステージファイルを読み込む if ((fopen_s(&fp_stage_structure_info, file_path, "r")) != 0) { printf("%s\n", file_path); std::cout << "<info 034: ステージファイルを開けませんでした" << std::endl; exit(34); } i = 0; while (fscanf_s(fp_stage_structure_info, "%d,%d,%d", &stage_block_info[i][0], &stage_block_info[i][1], &stage_block_info[i][2]) != EOF) { i++; } object_on_stage = i; std::cout << "<info 035: ステージファイルを読み込みました>" << std::endl; for (i = 0; i <= object_on_stage; i++) //ファイルの情報をobject_blockに書き出していく { object_block[i][0] = stage_block_info[i][0]; object_block[i][1] = stage_block_info[i][1]*(-64); object_block[i][2] = stage_block_info[i][2]*(-64); } int *slst = &slot_start[0]; for (i = 0; i < object_on_stage; i++) { *(slst + i) = choose_hiragana(); //ヒントブロックの表示ひらがなをばらけさせるためにそれぞれのオブジェクトに割り振る(ルーレットブロックが登場するステージもあるので) } slot[0] = stage_slot_constraint[stage_num][0]; slot[1] = stage_slot_constraint[stage_num][1]; slot[2] = stage_slot_constraint[stage_num][2]; slot[3] = stage_slot_constraint[stage_num][3]; slot[4] = stage_slot_constraint[stage_num][4]; fclose(fp_stage_structure_info); std::cout << "<info 036: ステージファイルを閉じました>" << std::endl; } void game_reset(void) //ステージ構造などゲームを開始する直前にゲームを準備する { player->center_x = 0; player->center_y = -8; lamp_timer_01 = 0; lamp_timer_02 = 0; score = 0; score_get_hiragana = 0; score_leave_hiragana = 0; max_most_hiragana = 0; score_most_hiragana = 0; score_tango = 0; time = TIME_LIMIT * 60; slot[0] = 0; slot[1] = 0; slot[2] = 0; slot[3] = 0; slot[4] = 0; slot_select = 0; int *obbl = &object_block[0][0]; int *stst = &stage_structure[0]; int *slst = &slot_start[0]; //ステージの構造を再構成 for (i = 0; i < object_on_stage; i++) //ブロックの情報をリセット { *(obbl + i*3) = 0; *(obbl + i * 3+1) = 0; *(obbl + i * 3+2) = 0; } for (i = 0; i < PATTERN_LIMIT; i++) { *(stst + i) = choose_pattern(); if (i % 6 == 5) //6パターンおきにボーナスステージ配置 { *(stst+i) = 254; } } *(stst + 1) = 1; //サンプル *(stst+18) = 255; //最後の壁(暫定)なんか無限だとクソヌルゲーになるらしいので block_standby(); //ブロックの配置(再構成) for (i = 0; i < object_on_stage; i++) { *(slst + i) = choose_hiragana(); //ヒントブロックの表示ひらがなをばらけさせるためにそれぞれのオブジェクトに割り振る } } void game_shutdown(void) //Escキーを押下されたとき諸々を終了させる { fclose(fp_score_3); fclose(fp_score_4); fclose(fp_score_5); std::cout << "<info 017: スコアファイルを閉じました>" << std::endl; fclose(fp_dic_4); std::cout << "<info 018: 4文字辞書ファイルを閉じました>" << std::endl; fclose(fp_stageclear); std::cout << "<info 031: ステージクリア進捗状況ファイルを閉じました>" << std::endl; fclose(fp_stage_nolma_info); std::cout << "<info 052: ステージノルマファイルを閉じました>" << std::endl; Mix_FreeChunk(SE_select); Mix_CloseAudio(); exit(1); } void display(void) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); int *obbl = &object_block[0][0]; GameObject *blhr = &block_hiragana[0]; GameObject *blUI = &block_hiragana_UI[0]; GameObject *blmn = &block_hiragana_mini[0]; int *hrrl = &hiragana_roulette[0]; int *slst = &slot_start[0]; int *sl = &slot[0]; switch (scene) { case 0: { glOrtho(0.0, WIDTH, HEIGHT, 0.0, -1.0, 1.0); gluLookAt(camera_x, camera_y, 0, camera_x, camera_y, 1, 0, 1, 0); UI_title.SetImage(0, -352); UI_quit.SetImage(0, 100); UI_gamestart.SetImage(-80, 48); UI_pressstart.SetImage(140, -32); }break; case 1: { glOrtho(0.0, WIDTH, HEIGHT, 0.0, -1.0, 1.0); gluLookAt(camera_x, camera_y, 0, camera_x, camera_y, 1, 0, 1, 0); UI_08.SetImage(0, -172); UI_13.SetImage(0, 64); //次へ進む UI_14.SetImage(0, -444); //are you ready? }break; case 2: { glOrtho(0.0, WIDTH, HEIGHT, 0.0, -1.0, 1.0); gluLookAt(camera_x, camera_y, 0, camera_x, camera_y, 1, 0, 1, 0); block_alphabet_p.SetImage(256, -416); block_alphabet_a.SetImage(128, -416); block_alphabet_u.SetImage(0, -416); block_alphabet_s.SetImage(-128, -416); block_alphabet_e.SetImage(-256, -416); UI_return.SetImage(0, 72); UI_08.SetImage(0, -172); }break; case 3: { glOrtho(0.0, WIDTH, HEIGHT, 0.0, -1.0, 1.0); gluLookAt(camera_x, camera_y, 0, camera_x, camera_y, 1, 0, 1, 0); UI_score.SetImage(164, -396); if (ranking == 0) { UI_newrecord.SetImage(0, -426); } UI_ranking.SetImage(0, -344); SetNumImage(-224, -420, 320, 40, score,0, 4); UI_09.SetImage(0, 96); UI_rank01.SetImage(204, -228); UI_rank02.SetImage(204, -180); UI_rank03.SetImage(204, -132); UI_rank04.SetImage(204, -84); UI_rank05.SetImage(204, -36); SetNumImage(-244, -244, 320, 40, high_score_4[0], 0,4); SetNumImage(-244, -200, 320, 40, high_score_4[1], 0, 4); SetNumImage(-244, -152, 320, 40, high_score_4[2], 0, 4); SetNumImage(-244, -104, 320, 40, high_score_4[3], 0, 4); SetNumImage(-244, -56, 320, 40, high_score_4[4], 0, 4); arrow.SetImage(334, -224 + 48 * ranking); }break; case 4: { glOrtho(0.0, WIDTH, HEIGHT, 0.0, -1.0, 1.0); gluLookAt(camera_x, camera_y, 0, camera_x, camera_y, 1, 0, 1, 0); UI_score.SetImage(164, -396); if (ranking == 0) { UI_newrecord.SetImage(0, -426); } SetNumImage(-224, -420, 320, 40, score, 0, 4); UI_09.SetImage(0, 96); UI_result01.SetImage(128, -232); UI_result02.SetImage(128, -184); UI_result03.SetImage(128, -136); UI_result04.SetImage(128, -88); block_hiragana[score_most_hiragana].SetImage(-224, -132); SetNumImage(-244, -244, 320, 40, score_get_hiragana, 0, 4); SetNumImage(-244, -200, 320, 40, score_leave_hiragana, 0, 4); SetNumImage(-244, -104, 320, 40, score_tango, 0, 4); }break; case 5: { glOrtho(0.0, WIDTH, HEIGHT, 0.0, -1.0, 1.0); gluLookAt(camera_x, camera_y + 128, 0, camera_x, camera_y + 128, 1, 0, 1, 0); UI_10.SetImage(440 + player->center_x, 200); UI_11.SetImage(0 + player->center_x, 272); UI_12.SetImage(-440 + player->center_x, 200); if (mode == 0 && mode_mojisu == 3 || mode == 1 && stage_info[stage_select] % 10 == 3) //3文字モードの時のスロットの背景 { UI_slot_base_3.SetImage(0 + player->center_x, 200); } else if (mode == 0 && mode_mojisu == 4 || mode == 1 && stage_info[stage_select] % 10 == 4) //4文字モードの時のスロットの背景 { UI_slot_base_4.SetImage(0 + player->center_x, 200); } else if (mode == 0 && mode_mojisu == 5 || mode == 1 && stage_info[stage_select] % 10 == 5) //5文字モードの時のスロットの背景 { UI_slot_base_5.SetImage(0 + player->center_x, 200); } SetNumImage(360 + player->center_x, 132, 160, 20, time / 60, 0, 4); //タイマー SetNumImage(360 + player->center_x, 268, 160, 20, high_score_4[0], 0, 4); //ハイスコア if (mode == 0) { SetNumImage(360 + player->center_x, 200, 160, 20, score, 0, 4); //スコア } else if (mode == 1) { SetNumImage(444 + player->center_x, 200, 160, 20, score, 0, 4); //スコア(何分の何 UI_num_aslash.SetImage(430 + player->center_x,210); SetNumImage(360 + player->center_x, 200, 160, 20, stage_nolma[stage_select], 0, 4); } if (mode == 0 && mode_mojisu == 3 || mode == 1 && stage_info[stage_select] % 10 == 3) //3文字モードの時のひらがなスロット { (*(blUI + *(sl + 0))).SetImage(174 + player->center_x, 176); //ひらがなスロット (*(blUI + *(sl + 1))).SetImage(0 + player->center_x, 176); (*(blUI + *(sl + 2))).SetImage(-174 + player->center_x, 176); } else if (mode == 0 && mode_mojisu == 4 || mode == 1 && stage_info[stage_select] % 10 == 4) //4文字モードの時ひらがなスロット { (*(blUI + *(sl + 0))).SetImage(216 + player->center_x, 176); //ひらがなスロット (*(blUI + *(sl + 1))).SetImage(72 + player->center_x, 176); (*(blUI + *(sl + 2))).SetImage(-72 + player->center_x, 176); (*(blUI + *(sl + 3))).SetImage(-216 + player->center_x, 176); } else if (mode == 0 && mode_mojisu == 5 || mode == 1 && stage_info[stage_select] % 10 == 5) //5文字モードの時のひらがなスロット { (*(blUI + *(sl + 0))).SetImage(264 + player->center_x, 176); //ひらがなスロット (*(blUI + *(sl + 1))).SetImage(132 + player->center_x, 176); (*(blUI + *(sl + 2))).SetImage(0 + player->center_x, 176); (*(blUI + *(sl + 3))).SetImage(-132 + player->center_x, 176); (*(blUI + *(sl + 4))).SetImage(-264 + player->center_x, 176); } if (mode == 0 && mode_mojisu == 3 || mode == 1 && stage_info[stage_select] % 10 == 3) //3文字モードの時の語彙スロット固定がある場合 { for (i = 0; i <= 2; i++) { if (stage_slot_constraint[stage_select][i] != 0) { UI_slot_locked.SetImage(174 - 174 * i + player->center_x, 176); //ステージモードでスロットの文字固定の場合 } } } else if (mode == 0 && mode_mojisu == 4 || mode == 1 && stage_info[stage_select] % 10 == 4) //4文字モードの時の語彙スロット固定がある場合 { for (i = 0; i <= 3; i++) { if (stage_slot_constraint[stage_select][i] != 0) { UI_slot_locked.SetImage(216 - 144 * i + player->center_x, 176); //ステージモードでスロットの文字固定の場合 } } } else if (mode == 0 && mode_mojisu == 5 || mode == 1 && stage_info[stage_select] % 10 == 5) //5文字モードの時の語彙スロット固定がある場合 { for (i = 0; i <= 4; i++) { if (stage_slot_constraint[stage_select][i] != 0) { UI_slot_locked.SetImage(264 - 132 * i + player->center_x, 176); //ステージモードでスロットの文字固定の場合 } } } if (lamp_timer_01 == 0) { if (mode == 0 && mode_mojisu == 3 || mode == 1 && stage_info[stage_select] % 10 == 3) //3文字モードの時選択箇所 { UI_slot_highlight.SetImage(174 - slot_select * 174 + player->center_x, 176); //スロットの選択箇所 } if (mode == 0 && mode_mojisu == 4 || mode == 1 && stage_info[stage_select] % 10 == 4) //4文字モードの時の選択箇所 { UI_slot_highlight.SetImage(216 - slot_select * 144 + player->center_x, 176); //スロットの選択箇所 } if (mode == 0 && mode_mojisu == 5 || mode == 1 && stage_info[stage_select] % 10 == 5) //5文字モードの時の選択箇所 { UI_slot_highlight.SetImage(264 - slot_select * 132 + player->center_x, 176); //スロットの選択箇所 } } if (lamp_timer_01 % 10 >= 6 && lamp_timer_01 > 0) //Kキーを押した後スロットを点滅させる { switch (word_hit) { case false: { if (mode == 0 && mode_mojisu == 3 || mode == 1 && stage_info[stage_select] % 10 == 3) //3文字モードの時の語彙スロット点滅 { UI_slot_decision.SetImage(174+ player->center_x, 176); UI_slot_decision.SetImage(0 + player->center_x, 176); UI_slot_decision.SetImage(-174 + player->center_x, 176); } else if (mode == 0 && mode_mojisu == 4 || mode == 1 && stage_info[stage_select] % 10 == 4) //4文字モードの時のの語彙スロット点滅 { UI_slot_decision.SetImage(216 + player->center_x, 176); UI_slot_decision.SetImage(72 + player->center_x, 176); UI_slot_decision.SetImage(-72 + player->center_x, 176); UI_slot_decision.SetImage(-216 + player->center_x, 176); } else if (mode == 0 && mode_mojisu == 5 || mode == 1 && stage_info[stage_select] % 10 == 5) //5文字モードの時のの語彙スロット点滅 { UI_slot_decision.SetImage(264 + player->center_x, 176); UI_slot_decision.SetImage(132 + player->center_x, 176); UI_slot_decision.SetImage(0 + player->center_x, 176); UI_slot_decision.SetImage(-132 + player->center_x, 176); UI_slot_decision.SetImage(-264 + player->center_x, 176); } }break; case true: { if (mode == 0 && mode_mojisu == 3 || mode == 1 && stage_info[stage_select] % 10 == 3) //3文字モードの時の語彙スロット点滅 { UI_slot_decision_green.SetImage(174 + player->center_x, 176); UI_slot_decision_green.SetImage(0 + player->center_x, 176); UI_slot_decision_green.SetImage(-174 + player->center_x, 176); } else if (mode == 0 && mode_mojisu == 4 || mode == 1 && stage_info[stage_select] % 10 == 4) //4文字モードの時のの語彙スロット点滅 { UI_slot_decision_green.SetImage(216 + player->center_x, 176); UI_slot_decision_green.SetImage(72 + player->center_x, 176); UI_slot_decision_green.SetImage(-72 + player->center_x, 176); UI_slot_decision_green.SetImage(-216 + player->center_x, 176); } else if (mode == 0 && mode_mojisu == 5 || mode == 1 && stage_info[stage_select] % 10 == 5) //4文字モードの時のの語彙スロット点滅 { UI_slot_decision_green.SetImage(264 + player->center_x, 176); UI_slot_decision_green.SetImage(132 + player->center_x, 176); UI_slot_decision_green.SetImage(0 + player->center_x, 176); UI_slot_decision_green.SetImage(-132 + player->center_x, 176); UI_slot_decision_green.SetImage(-264 + player->center_x, 176); } }break; } } for (int i = -6400; i < 300; i++) { //ここから5つ背景を描画 BG_05.SetImage(i * 1024 + (player->center_x *1.0), -224); } for (int i = -6400; i < 300; i++) { BG_04.SetImage(i * 1024 + (player->center_x *0.75), -224); } for (int i = -6400; i < 300; i++) { BG_03.SetImage(i * 1024 + (player->center_x *0.5), -224); } for (int i = -6400; i < 300; i++) { BG_02.SetImage(i * 1024 + (player->center_x *0.25), -224); } for (int i = -6400; i < 300; i++) { BG_01.SetImage(i * 1024 + (player->center_x *0.0), -224); } if (gun_timer > 0) //銃を発射しているときのプレイヤーの描画 { if (player->direction == 1) { player->ChangeImage(4); } else { player->ChangeImage(9); } } else if (player_jump == true) { if (player->direction == 1) { player->ChangeImage(3); } else { player->ChangeImage(8); } } else if (walk_timer == 0) { if (player->direction == 1) { player->ChangeImage(1); } else { player->ChangeImage(6); } } else { if (walk_timer % 12 >= 0 && walk_timer % 12 <= 2) { if (player->direction == 1) { player->ChangeImage(1); } else { player->ChangeImage(6); } } else if (walk_timer % 12 >= 3 && walk_timer % 12 <= 5) { if (player->direction == 1) { player->ChangeImage(2); } else { player->ChangeImage(7); } } else if (walk_timer % 12 >= 6 && walk_timer % 12 <= 8) { if (player->direction == 1) { player->ChangeImage(1); } else { player->ChangeImage(6); } } else if (walk_timer % 12 >= 9 && walk_timer % 12 <= 11) { if (player->direction == 1) { player->ChangeImage(0); } else { player->ChangeImage(5); } } } glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_TEXTURE_2D); glEnable(GL_ALPHA_TEST); glBegin(GL_POLYGON); switch (player->direction) { case 0: { player->UpdateDirR(); } break; case 1: { player->UpdateDirR(); } break; } glEnd(); glDisable(GL_ALPHA_TEST); glDisable(GL_TEXTURE_2D); glDisable(GL_BLEND); for (i = 0; i < object_on_stage; i++) //オブジェクトとなるブロックここで全部描画 { if (*(obbl + i * 3) != 0 && *(obbl + i * 3) != 77 && *(obbl + i * 3) != 79) { (*(blhr+ *(obbl + i * 3))).SetImage(double(*(obbl + i * 3 + 1)), double(*(obbl + i * 3 + 2))); } else if (*(obbl + i * 3) == 77) //お題箱描画 { if (*(sl + 0) == 0 && *(sl + 1) == 0 && *(sl + 2) == 0 && *(sl + 3) == 0) { (*(blhr + 77)).SetImage(double(*(obbl + i * 3+1)), double(*(obbl + i * 3+2))); } else //スロットが空っぽじゃなかったらお題箱は起動しない { (*(blhr + 78)).SetImage(double(*(obbl + i * 3+1)), double(*(obbl + i * 3+2))); } } else if (*(obbl + i * 3) == 79) //お題箱描画 { //block_hiragana[hiragana_roulette[((hiragana_roulette_timer + (slot_start[i])*60))%(74*60) / 60]].SetImage(double(*(obbl + i * 3 + 1)), double(*(obbl + i * 3 + 2))); //下式が複雑なので一応変形前も載せる (*(blhr+ *(hrrl + ((hiragana_roulette_timer + *(slst + i) * 60)) % (74 * 60) / 60))).SetImage(double(*(obbl + i * 3 + 1)), double(*(obbl + i * 3 + 2))); if (lamp_timer_block % 20 >= 0 && lamp_timer_block % 20 <= 4) { block_light_2.SetImage(double(*(obbl + i * 3 + 1)), double(*(obbl + i * 3 + 2))); } if (lamp_timer_block % 20 >= 5 && lamp_timer_block % 20 <= 9) { block_light_1.SetImage(double(*(obbl + i * 3 + 1)), double(*(obbl + i * 3 + 2))); } if (lamp_timer_block % 20 >= 10 && lamp_timer_block % 20 <= 14) { block_light_2.SetImage(double(*(obbl + i * 3 + 1)), double(*(obbl + i * 3 + 2))); } } } if (lamp_timer_02 > 0) //Kキーを押した後ふきだしとエフェクト点灯 { switch (word_hit) { case true: //プレイヤーの吹き出しと加点スコアを描画 { player_fukidashi01.SetImage(player->center_x, player->center_y - 80); if (score >= 100000) { SetNumImage(player->center_x - 12 * 9, player->center_y - 128, 192, 24, score_word,1, 4); } else if (score >= 10000 && score <= 99999) { SetNumImage(player->center_x - 12 * 8, player->center_y - 128, 192, 24, score_word,1, 4); } else if (score >= 1000 && score <= 9999) { SetNumImage(player->center_x - 12 * 7, player->center_y - 128, 192, 24, score_word, 1, 4); } else if (score >= 100 && score <= 999) { SetNumImage(player->center_x - 12 * 6, player->center_y - 128, 192, 24, score_word, 1, 4); } else if (score >= 10 && score <= 99) { SetNumImage(player->center_x - 12 * 5, player->center_y - 128, 192, 24, score_word, 1, 4); } else if (score >= 0 && score <= 9) { SetNumImage(player->center_x - 12 * 4, player->center_y - 128, 192, 24, score_word, 1, 4); } }break; case false: //プレイヤーの吹き出しとペナルティを描画 { player_fukidashi02.SetImage(player->center_x, player->center_y - 80); player_penalty.SetImage(player->center_x, player->center_y - 120); }break; } } if (lamp_timer_02 % 7 >= 3 && lamp_timer_02 > 0) //Kキーを押した後プレイヤーエフェクト点滅 { switch (word_hit) { case true: { player_maru.SetImage(player->center_x, player->center_y); }break; case false: { player_batsu.SetImage(player->center_x, player->center_y); }break; } } if (flag_bullet_exist == true) { bullet->ChangeImage(0); //弾丸の描画 } if (stage_info[stage_select] % 10 == 3) //ステージモードかつ3文字モードのとき,今まで作った単語を左上に表示 { for (i = 0; i <= 100; i++) { if (made_tango[i][0] != 0) { (*(blmn + made_tango[i][0])).SetImage(600+player->center_x, -400 + i*35); } if (made_tango[i][1] != 0) { (*(blmn + made_tango[i][1])).SetImage(568 + player->center_x, -400+i*35); } if (made_tango[i][2] != 0) {(*(blmn + made_tango[i][2])).SetImage(536 + player->center_x, -400 + i * 35);} } } else if (stage_info[stage_select] % 10 == 4) //ステージモードかつ4文字モードのとき,今まで作った単語を左上に表示 { for (i = 0; i <= 100; i++) { if (made_tango[i][0] != 0) { (*(blmn + made_tango[i][0])).SetImage(600 + player->center_x, -400 + i * 35); } if (made_tango[i][1] != 0) { (*(blmn + made_tango[i][1])).SetImage(568 + player->center_x, -400 + i * 35); } if (made_tango[i][2] != 0) { (*(blmn + made_tango[i][2])).SetImage(536 + player->center_x, -400 + i * 35); } if (made_tango[i][3] != 0) { (*(blmn + made_tango[i][3])).SetImage(504 + player->center_x, -400 + i * 35); } } } else if (stage_info[stage_select] % 10 == 5) //ステージモードかつ5文字モードのとき,今まで作った単語を左上に表示 { for (i = 0; i <= 100; i++) { if (made_tango[i][0] != 0) { (*(blmn + made_tango[i][0])).SetImage(600 + player->center_x, -400 + i * 35); } if (made_tango[i][1] != 0) { (*(blmn + made_tango[i][1])).SetImage(568 + player->center_x, -400 + i * 35); } if (made_tango[i][2] != 0) { (*(blmn + made_tango[i][2])).SetImage(536 + player->center_x, -400 + i * 35); } if (made_tango[i][3] != 0) { (*(blmn + made_tango[i][3])).SetImage(504 + player->center_x, -400 + i * 35); } if (made_tango[i][4] != 0) { (*(blmn + made_tango[i][4])).SetImage(472 + player->center_x, -400 + i * 35); } } } }break; case 6: //ゲームオーバー画面 { glOrtho(0.0, WIDTH, HEIGHT, 0.0, -1.0, 1.0); gluLookAt(camera_x, camera_y, 0, camera_x, camera_y, 1, 0, 1, 0); UI_gameover.SetImage(0, -416); UI_tonext.SetImage(0, 64); }break; case 7: //モード選択画面 { glOrtho(0.0, WIDTH, HEIGHT, 0.0, -1.0, 1.0); gluLookAt(camera_x, camera_y, 0, camera_x, camera_y, 1, 0, 1, 0); if(mode==0) { UI_mode_description_1.SetImage(-315, -256); UI_mode_highscore_1.SetImage(-315,-20); UI_mode_waku.SetImage(-315, -20); SetNumImage(-520, 80, 400, 50, 0, 0, 4); SetNumImage(-520, 0, 400, 50, high_score_4[0], 0, 4); SetNumImage(-520, -80, 400, 50, 0, 0, 4); } else if (mode == 1) { UI_mode_description_2.SetImage(-315, -256); UI_mode_highscore_2.SetImage(-315, -20); UI_mode_waku.SetImage(-315, -20); SetNumImage(-350, -80, 300, 50, stage_medal[0], 0, 4); SetNumImage(-350, 0, 300, 50, stage_medal[1], 0, 4); SetNumImage(-350, 80, 300, 50, stage_medal[2], 0, 4); UI_num_aslash_big.SetImage(-375, 25); UI_num_aslash_big.SetImage(-375, 105); UI_num_aslash_big.SetImage(-375, -55); SetNumImage(-520, 80, 300, 50, STAGE_LIMIT, 0, 4); SetNumImage(-520, 0, 300, 50, STAGE_LIMIT, 0, 4); SetNumImage(-520, -80, 300, 50, STAGE_LIMIT, 0, 4); } UI_mode_score_attack.SetImage(224, -364); UI_mode_stage_clear.SetImage(224, -76); UI_mode_highlight.SetImage(224, -364+mode*288); UI_mode_select_UI.SetImage(224, 112); }break; case 8: //文字数選択画面 { glOrtho(0.0, WIDTH, HEIGHT, 0.0, -1.0, 1.0); gluLookAt(camera_x, camera_y, 0, camera_x, camera_y, 1, 0, 1, 0); UI_mode_3.SetImage(224, -76); UI_mode_4.SetImage(0, -76); UI_mode_5.SetImage(-224, -76); UI_mode_mojisu.SetImage(0, -416); UI_mode_mojisu_highlight.SetImage(224-(mode_mojisu-3)*224, -76); UI_mode_select_mojisu_UI.SetImage(0, 112); UI_coming_soon192.SetImage(224, -216); UI_coming_soon192.SetImage(-224, -216); }break; case 9: //ステージ選択画面 { glOrtho(0.0, WIDTH, HEIGHT, 0.0, -1.0, 1.0); gluLookAt(camera_x, camera_y, 0, camera_x, camera_y, 1, 0, 1, 0); UI_mode_stage.SetImage(0, -460); UI_block_stage_num_select.SetImage(0, -348); if (stage_select >= 2) //ステージ選択の左の矢印 { UI_arrow_2L.SetImage(488, -348); } if (stage_select <= STAGE_LIMIT - 1) //ステージ選択の右の矢印 { UI_arrow_2R.SetImage(-488, -348); } for (i = -3; i <= 3; i++) { if (stage_select + i >= 1 && stage_select + i <= STAGE_LIMIT) //ステージ選択のブロックの描画 { UI_clear_lamp_off.SetImage(-i * 128, -280); UI_block_stage_num.SetImage(-i * 128, -348); if (stage_info[stage_select + i] == 0) { UI_coming_soon64.SetImage(-i * 128, -236); } if (stage_clear[stage_select + i][0] == 1) { UI_clear_lamp_on_1.SetImage(-i*128,-280); } //クリアランプの点灯 if (stage_clear[stage_select + i][1] == 1) { UI_clear_lamp_on_2.SetImage(-i * 128, -280); } if (stage_clear[stage_select + i][2] == 1) { UI_clear_lamp_on_3.SetImage(-i * 128, -280); } if (stage_clear[stage_select + i][0] == 1 && stage_clear[stage_select + i][1] == 1 && stage_clear[stage_select + i][2] == 1) //全点灯アニメーション { if(lamp_timer_clear%12 <=5){ UI_clear_lamp_on_1_lux.SetImage(-i * 128, -280); UI_clear_lamp_on_2_lux.SetImage(-i * 128, -280); UI_clear_lamp_on_3_lux.SetImage(-i * 128, -280); } } } } for (i = -3; i <= 3; i++) { if (stage_select + i >= 1 && stage_select + i <= STAGE_LIMIT) //ステージ選択の番号の描画 { if (stage_select + i >= 100) //桁数によってブロックへの数字の画像の納め方が変わるので分けた&ステージが定義されている場合は明るいフォントで描画 { if (stage_info[stage_select + i] == 0) { SetNumImage(-38 - i * 128, -372, 288, 48, stage_select + i, 3, -16); } else { SetNumImage(-38 - i * 128, -372, 288, 48, stage_select + i, 2, -16); } } else if (stage_select + i >= 10 && stage_select + i <= 99) { if (stage_info[stage_select + i] == 0) { SetNumImage(-40 - i * 128, -372, 384, 48, stage_select + i, 3, -16); } else { SetNumImage(-40 - i * 128, -372, 384, 48, stage_select + i, 2, -16); } } else if (stage_select + i <= 9) { if (stage_info[stage_select + i] == 0) { SetNumImage(-24 - i * 128, -372, 384, 48, stage_select + i, 3, -16); } else { SetNumImage(-24 - i * 128, -372, 384, 48, stage_select + i, 2, -16); } } } } if (stage_info[stage_select] != 0) //ステージが定義されている場合ステージの概要情報と決定ボタンを描画 { UI_time_limit_description.SetImage(0, 0); UI_16.SetImage(0, 64); //決定ボタン SetNumImage(112, -16, 320, 40, stage_time_limit[stage_select], 0, 4); SetNumImage(-324, -16, 320, 40, stage_time_limit_gold[stage_select], 0, 4); switch (stage_info[stage_select])//stage_infno情報は1の位でなんもじもーどか決まる { case 3: { if (stage_slot_constraint[stage_select][0] == 0 && stage_slot_constraint[stage_select][1] == 0 && stage_slot_constraint[stage_select][2] == 0 && stage_slot_constraint[stage_select][3] == 0) { UI_mission_description_0.SetImage(0, -96); //スロット固定がない場合「ただのn単語作成ミッション」になる SetNumImage(80, -166, 320, 40, stage_nolma[stage_select], 0, 4); } else { UI_slot_constraint_description.SetImage(0, -160); UI_mission_description_1.SetImage(0, -96); //スロット固定がある場合のn単語作成ミッション SetNumImage(-48, -115, 320, 40, stage_nolma[stage_select], 0, 4); block_hiragana[stage_slot_constraint[stage_select][0]].SetImage(-64, -160); //固定スロットの情報を描画 block_hiragana[stage_slot_constraint[stage_select][1]].SetImage(-128, -160); block_hiragana[stage_slot_constraint[stage_select][2]].SetImage(-192, -160); } }break; case 4: { if (stage_slot_constraint[stage_select][0] == 0 && stage_slot_constraint[stage_select][1] == 0 && stage_slot_constraint[stage_select][2] == 0 && stage_slot_constraint[stage_select][3] == 0) { UI_mission_description_0.SetImage(0, -145);//スロット固定がない場合「ただのn単語作成ミッション」になる SetNumImage(80, -166, 320, 40, stage_nolma[stage_select], 0, 4); } else { UI_slot_constraint_description.SetImage(0, -160); UI_mission_description_1.SetImage(0, -96);//スロット固定がある場合のn単語作成ミッション SetNumImage(-48, -115, 320, 40, stage_nolma[stage_select], 0, 4); block_hiragana[stage_slot_constraint[stage_select][0]].SetImage(-64, -160); //固定スロットの情報を描画 block_hiragana[stage_slot_constraint[stage_select][1]].SetImage(-128, -160); block_hiragana[stage_slot_constraint[stage_select][2]].SetImage(-192, -160); block_hiragana[stage_slot_constraint[stage_select][3]].SetImage(-256, -160); } }break; case 5: { if (stage_slot_constraint[stage_select][0] == 0 && stage_slot_constraint[stage_select][1] == 0 && stage_slot_constraint[stage_select][2] == 0 && stage_slot_constraint[stage_select][3] == 0 && stage_slot_constraint[stage_select][4] == 0) { UI_mission_description_0.SetImage(0, -96);//スロット固定がない場合「ただのn単語作成ミッション」になる SetNumImage(80, -166, 320, 40, stage_nolma[stage_select], 0, 4); } else { UI_slot_constraint_description.SetImage(0, -160); UI_mission_description_1.SetImage(0, -96);//スロット固定がある場合のn単語作成ミッショ SetNumImage(-48, -115, 320, 40, stage_nolma[stage_select], 0, 4); block_hiragana[stage_slot_constraint[stage_select][0]].SetImage(-64, -160); //固定スロットの情報を描画 block_hiragana[stage_slot_constraint[stage_select][1]].SetImage(-128, -160); block_hiragana[stage_slot_constraint[stage_select][2]].SetImage(-192, -160); block_hiragana[stage_slot_constraint[stage_select][3]].SetImage(-256, -160); block_hiragana[stage_slot_constraint[stage_select][4]].SetImage(-320, -160); } }break; case 13: case 14: case 15: //しりとりミッション { UI_mission_description_2.SetImage(0, -145); SetNumImage(10, -166, 320, 40, stage_nolma[stage_select], 0, 4); }break; } } UI_17.SetImage(0, 64); }break; case 10: //ほんとうによろしいですか? { glOrtho(0.0, WIDTH, HEIGHT, 0.0, -1.0, 1.0); gluLookAt(camera_x, camera_y, 0, camera_x, camera_y, 1, 0, 1, 0); UI_confirm.SetImage(0, -416); UI_confirm_2.SetImage(0, 64); }break; case 11: //ステージクリアモードのリザルト { glOrtho(0.0, WIDTH, HEIGHT, 0.0, -1.0, 1.0); gluLookAt(camera_x, camera_y, 0, camera_x, camera_y, 1, 0, 1, 0); UI_result_stage.SetImage(0,-160); UI_result_stage_title.SetImage(80,-416); SetNumImage(-300,-464,768,96,stage_select,2,-16); SetNumImage(-260, -100, 512, 64, stage_time_limit[stage_select] - time/60 - score_miss * 30, 0, 4); SetNumImage(-260, -192, 512, 64, score_miss, 0, 4); UI_15.SetImage(0,64); if (lamp_timer_clear % 12 >= 6) //リザルト画面でのメダルのきらびやかアニメーション { UI_result_stage_medal_1.SetImage(0,-160); if (score_miss == 0) { UI_result_stage_medal_2.SetImage(0, -160); } if (stage_time_limit[stage_select] - time / 60 - score_miss * 30 <= stage_time_limit_gold[stage_select]) { UI_result_stage_medal_3.SetImage(0, -160); } } else { UI_result_stage_medal_1_lux.SetImage(0,-160); if (score_miss == 0) { UI_result_stage_medal_2_lux.SetImage(0, -160); } if (stage_time_limit[stage_select] - time / 60 - score_miss * 30 <= stage_time_limit_gold[stage_select]) { UI_result_stage_medal_3_lux.SetImage(0, -160); } } }break; } glutSwapBuffers(); } void idle(void) { double player_y_before = 0; int *obbl = &object_block[0][0]; int *slst = &slot_start[0]; int *hrrl = &hiragana_roulette[0]; int *odhr3 = &odai_hiragana_3[0][0]; int *odhr4 = &odai_hiragana_4[0][0]; int *odhr5 = &odai_hiragana_5[0][0]; int *sl = &slot[0]; // std::cout <<--------------------フレーム開始--------------------->" << std::endl; /* std::cout << "<info 007: プレイヤーの座標:[ "<< player->center.x << "],[" << player->center.y <<"]" << std::endl; //コピー用 随所で使う std::cout << "<info 007: 見てるブロックの座標:[" << *(obbl + i * 3+1) << "],[" << *(obbl + i * 3+2) <<"]" << std::endl; //コピー用 随所で使う */ if (player_jump == true && flag_move_y == true && move_lock == false) //ジャンプ { player_y_before = player->center_y; switch (flag_jump_slow) { case true://ふわふわ落下モード { player->Move(0, -(15.8 * jump_timer - 9.8* jump_timer * sqrt(jump_timer) *0.5)*0.0015 * 36); }break; case false: { player->Move(0, -(15.8 * jump_timer - 9.8* jump_timer * sqrt(jump_timer) *0.5)*0.01 * 128); }break; } if (player->center_y - player_y_before > 0) //前のフレームのy座標よりも落ちていたらふわふわ落下モードに { flag_jump_slow = true; } flag_collision_U = false; flag_collision_D = false; for (i = 0; i < object_on_stage; i++) { if (player->center_y < *(obbl + i * 3 + 2) && *(obbl + i * 3) != 0) //プレイやーがブロックより下側にいる時,かつ比較するオブジェクトブロックが空白でないとき { if (abs(player->center_x - double(*(obbl + i * 3+1))) < 48 && abs(player->center_y - double(*(obbl + i * 3+2))) <= 64) //ブロックとの距離がx<48 y<64であるとき { // std::cout << "<info 002: 下に行こうとしてブロック[ << i <<] に衝突しています>" << std::endl; flag_collision_D = true; if (height_c > *(obbl + i * 3+2)) { height_c = *(obbl + i * 3 + 2); //着地点の座標を記録 } } } } for (i = 0; i < object_on_stage; i++) { if (player->center_y > *(obbl + i * 3 + 2) && *(obbl + i * 3) != 0) //プレイやーがブロックより上側にいる時,かつ比較するオブジェクトブロックが空白でないとき { if (abs(player->center_x - double(*(obbl + i * 3+1))) < 48 && abs(player->center_y - double(*(obbl + i * 3+2))) <= 64) //ブロックとの距離がx<48 y<64であるとき { // std::cout << "<info 003: 上に行こうとしてブロック[ << i <<] に衝突しています>" << std::endl; flag_collision_U = true; } } } if (flag_collision_U == true) //天井との衝突を感知したフレームでの処理 { jump_timer = JUMP_HIGHEST; player->Move(0,(-((int)(player->center_y))) % 64); //衝突したらそのブロックの下にブロックまで戻す } if (flag_collision_D == true) //地面との衝突を感知したフレームでの処理 { player->center_y = height_c - 64; player_jump = false; jump_timer = 0; flag_jump_slow = false; } else if (flag_collision_D == false) //地面との衝突を感知したフレームでの処理 { height_c = 8000; //自分の位置よりも十分に低い場所に衝突判定を戻す } flag_move_y = false; } else if (player_jump == false && flag_move_y == true && move_lock == false) //自由落下の制御 { flag_collision_D = false; for (i = 0; i < object_on_stage; i++) { if (player->center_y < *(obbl + i * 3 + 2) && *(obbl + i * 3) != 0) //プレイやーがブロックより下側にいる時,かつ比較するオブジェクトブロックが空白でないとき { if (abs(player->center_x - double(*(obbl + i * 3 + 1))) < 48 && abs(player->center_y - double(*(obbl + i * 3 + 2))) <= 64) //ブロックとの距離がx<48 y<64であるとき { // std::cout << "<info 004: 下に行こうとしてブロック[ << i <<] に衝突しています>" << std::endl; flag_collision_D = true; if (height_c > *(obbl + i * 3+2)) { height_c = *(obbl + i * 3 + 2); //着地点を取得 } } } } if (flag_collision_D == false) //地面との衝突を感知したフレームでの処理 { height_c = 8000; //自分の位置よりも風聞に低い場所に衝突判定に使う数値を戻す } if (flag_collision_D == false) { jump_timer = JUMP_HIGHEST; player_jump = true; } //足場がなくなると自由落下(タイマー = JUMP_HIGHEST で鉛直投げ上げ最高点) flag_move_y = false; } if (onMoveKeyPress_L == true && flag_move_x == true && move_lock == false) { //左に移動 camera_x += speed; player->Move(speed, 0); for (i = 0; i < object_on_stage; i++) { if (player->center_x < *(obbl + i * 3+1) && *(obbl + i * 3) != 0) //プレイやーがブロックより←側にいる時,かつ比較するオブジェクトブロックが空白でないとき { if (abs(player->center_x - double(*(obbl + i * 3+1))) < 48 && abs(player->center_y - double(*(obbl + i * 3+2))) < 60 ) //ブロックとの距離がx<48 y<64であるとき { // std::cout << "<info 005: 左に行こうとしてブロック[ << i <<] に衝突しています>" << std::endl; flag_collision_L = true; } } } if (flag_collision_L == true) { camera_x -= speed; player->Move(-speed, 0); } gluLookAt(camera_x, camera_y, 0, camera_x, camera_y, 1, 0, 1, 0); flag_move_x = false; flag_collision_L = false; } if (onMoveKeyPress_R == true && flag_move_x == true && move_lock == false) { //右に移動 camera_x -= speed; player->Move(-speed, 0); for (i = 0; i < object_on_stage; i++) { if (player->center_x > *(obbl + i * 3+1) && *(obbl + i * 3) != 0) //プレイやーがブロックより→側にいる時,かつ比較するオブジェクトブロックが空白でないとき { if (abs(player->center_x - double(*(obbl + i * 3+1))) < 48 && abs(player->center_y - double(*(obbl + i * 3+2))) < 60) //ブロックとの距離がx<48 y<64であるとき { // std::cout << "<info 006: 右に行こうとしてブロック[ << i <<] に衝突しています>" << std::endl; flag_collision_R = true; } } } if (flag_collision_R == true) { camera_x += speed; player->Move(speed, 0); } gluLookAt(camera_x, camera_y, 0, camera_x, camera_y, 1, 0, 1, 0); flag_move_x = false; flag_collision_R = false; } if (flag_bullet_exist == true && flag_move_bullet == true && move_lock == false) //弾丸と語彙ブロックの衝突判定 { switch (bullet->direction) //弾をそのときプレイヤーが向いていた方向に動かす { case 0: { bullet->Move(32, 0); }break; case 1: { bullet->Move(-32, 0); }break; } for (i = 0; i < object_on_stage; i++) { if (flag_bullet_exist == true && *(obbl + i * 3) != 0 && abs(bullet->center_x - double(*(obbl + i * 3+1))) < 32 && abs(bullet->center_y - double(*(obbl + i * 3+2))) < 32) //ブロックとの距離がx<32 y<64で32あるとき(ブロックID=0すなわち空気の時はスルー) { flag_bullet_exist = false; if (*(sl+slot_select) == 0 && *(obbl + i * 3) != 49 && *(obbl + i * 3) != 76 && *(obbl + i * 3) != 77 && *(obbl + i * 3) != 78 && *(obbl + i * 3) != 79)//すでにスロットにひらがなが入っている場合は衝突してもブロック消えないしひらがなも保持されない,あと木はスロットには入れられない(当然 { *(sl + slot_select) = *(obbl + i * 3); //弾丸が衝突したブロックをスロットに格納 *(obbl + i * 3) = 0; //弾丸とブロックが衝突したらそのブロックの情報を0にする Mix_PlayChannel(-1, SE_hit, 0); score_get_hiragana++; } else if (*(obbl + i * 3) == 77) //お題箱にヒットしたとき(ごいスロットに何かあるときはOFF状態になる) { if (mode_mojisu == 3 && slot[0] == 0 && slot[1] == 0 && slot[2] == 0)//3文字モードの時 { odai = choose_odai(); //おだい *(sl + 0) = *(odhr3 + odai * 5 + 0); *(sl + 1) = *(odhr3 + odai * 5 + 1); *(sl + 2) = *(odhr3 + odai * 5 + 2); Mix_PlayChannel(-1, SE_hit, 0); *(obbl + i * 3) = 0; //弾丸とブロックが衝突したらお互いの情報を0にする } else if (mode_mojisu == 4 && slot[0] == 0 && slot[1] == 0 && slot[2] == 0 && slot[3] == 0)//4文字モードの時 { odai = choose_odai(); //おだい *(sl + 0) = *(odhr4 + odai * 5 + 0); *(sl + 1) = *(odhr4 + odai * 5 + 1); *(sl + 2) = *(odhr4 + odai * 5 + 2); *(sl + 3) = *(odhr4 + odai * 5 + 3); Mix_PlayChannel(-1, SE_hit, 0); *(obbl + i * 3) = 0; //弾丸とブロックが衝突したらお互いの情報を0にする } else if (mode_mojisu == 5 && slot[0] == 0 && slot[1] == 0 && slot[2] == 0 && slot[3] == 0 && slot[4] == 0)//5文字モードの時 { odai = choose_odai(); //おだい *(sl + 0) = *(odhr5 + odai * 5 + 0); *(sl + 1) = *(odhr5 + odai * 5 + 1); *(sl + 2) = *(odhr5 + odai * 5 + 2); *(sl + 3) = *(odhr5 + odai * 5 + 3); *(sl + 4) = *(odhr5 + odai * 5 + 4); Mix_PlayChannel(-1, SE_hit, 0); *(obbl + i * 3) = 0; //弾丸とブロックが衝突したらお互いの情報を0にする } } else if (*(obbl + i * 3) == 79 && slot[slot_select] == 0) //ひらがなルーレットにヒットした場合 { *(sl + slot_select) = *(hrrl + ((hiragana_roulette_timer + *(slst + i) * 60)) % (74 * 60) / 60); //弾丸が衝突したブロックをスロットに格納(ランダムで選ばれたスロットの開始位置+ひらがなの総数の結果ひらがなの総数を超えてしまう場合,ひらがなの総数で割ったあまりを求めることでルーレットの中身がひらがなの総数分から外れることを防いでいる) *(obbl + i * 3) = 0; //弾丸とブロックが衝突したらお互いの情報を0にする Mix_PlayChannel(-1, SE_hit, 0); score_get_hiragana++; //ひらがなを入手した数+1 } } } flag_move_bullet = false; } if (scene == 5 && mode == 1 && stage_nolma[stage_select] == score) //ステージクリアモードでノルマを達成した { scene = 11; camera_x = 640; camera_y = -544; player->center_x = 0; player->center_y = 0; fclose(fp_stageclear); std::cout << "<info 041: ステージクリア進捗状況ファイルを「読み取り用として」閉じました>" << std::endl; if ((fopen_s(&fp_stageclear, "./dat/stage_clear.dat", "w")) != 0) //スコアファイルを読み込む { std::cout << "<info 042:ステージクリア進捗状況ファイルを「書き取り用として」開けませんでした>" << std::endl; exit(42); } std::cout << "<info 043:スステージクリア進捗状況ファイルを「書き取り用として」開きました>\n" << std::endl; if (stage_clear[stage_select][4] > score_miss) //ミス回数のハイスコア更新 { stage_clear[stage_select][4] = score_miss; } if (stage_clear[stage_select][3] > stage_time_limit[stage_select] - time/60) //タイム更新 { stage_clear[stage_select][3] = stage_time_limit[stage_select] - time / 60; } stage_clear[stage_select][0] = 1; //ノルマクリアで無条件でメダル一枚目獲得 if (score_miss == 0) { stage_clear[stage_select][1] = 1; //ミス0回でメダル二枚目獲得 } if (stage_time_limit[stage_select] - time / 60 - score_miss * 30 <= stage_time_limit_gold[stage_select]) { stage_clear[stage_select][2] = 1; //ゴールドタイマーでメダル3枚目獲得 } stage_medal[0] = 0; stage_medal[1] = 0; stage_medal[2] = 0; for (i = 0; i <= STAGE_LIMIT; i++) { fprintf(fp_stageclear, "%d,%d,%d,%d,%d\n", stage_clear[i][0], stage_clear[i][1], stage_clear[i][2], stage_clear[i][3], stage_clear[i][4]); //ステージクリア進捗状況ファイルを更新 if (stage_clear[i][0] == 1) { stage_medal[0]++; } if (stage_clear[i][1] == 1) { stage_medal[1]++; } if (stage_clear[i][2] == 1) { stage_medal[2]++; } //メダルを取った数を記録 } fclose(fp_stageclear); //書き取り用として閉じて,もっかい読み取り用として開く std::cout << "<info 047: ステージクリア進捗状況ファイルを「書き取り用として」閉じました>" << std::endl; if ((fopen_s(&fp_stageclear, "./dat/stage_clear.dat", "r")) != 0) //スコアファイルを読み込む { std::cout << "<info 048:ステージクリア進捗状況ファイルを「読み取り用として」開けませんでした>" << std::endl; exit(48); } std::cout << "<info 049:ステージクリア進捗状況ファイルを「読み取り用として」開きました>\n" << std::endl; } if (time < 0 && scene == 5) //タイムアップ時 { time = 0; camera_x = 640; camera_y = -544; player->center_x = 0; player->center_y = 0; if (mode == 0) //スコアアタックモードのとき,ランキングを更新する { scene = 6; switch (mode_mojisu) //文字数ごとにスコアをランキング化する(なんかもうちょっときれいにできそう) { case 3: { fclose(fp_score_3); std::cout << "<info 019: スコアファイルを「読み取り用として」閉じました>" << std::endl; if ((fopen_s(&fp_score_3, "./dat/score_3.dat", "w")) != 0) //スコアファイルを読み込む { std::cout << "<info 020:スコアファイルを「書き取り用として」開けませんでした>" << std::endl; exit(20); } std::cout << "<info 021:スコアファイルを「書き取り用として」開きました>\n" << std::endl; if (high_score_3[0] < score) { ranking = 0; high_score_3[4] = high_score_3[3]; high_score_3[3] = high_score_3[2]; high_score_3[2] = high_score_3[1]; high_score_3[1] = high_score_3[0]; high_score_3[0] = score; } else if (high_score_3[1] < score) { ranking = 1; high_score_3[4] = high_score_3[3]; high_score_3[3] = high_score_3[2]; high_score_3[2] = high_score_3[1]; high_score_3[1] = score; } else if (high_score_3[2] < score) { ranking = 2; high_score_3[4] = high_score_3[3]; high_score_3[3] = high_score_3[2]; high_score_3[2] = score; } else if (high_score_3[3] < score) { ranking = 3; high_score_3[4] = high_score_3[3]; high_score_3[3] = score; } else if (high_score_3[4] < score) { ranking = 4; high_score_3[4] = score; } else { ranking = 5; //ランク外 } for (i = 0; i <= 4; i++) { fprintf(fp_score_3, "%d\n", high_score_3[i]); //スコアファイルを更新 } for (i = 0; i <= 79; i++) { if (list_most_hiragana[i] > max_most_hiragana) { max_most_hiragana = list_most_hiragana[i]; score_most_hiragana = i; } } fclose(fp_score_3); //書き取り用として閉じて,もっかい読み取り用として開く std::cout << "<info 044: スコアファイルを「書き取り用として」閉じました>" << std::endl; if ((fopen_s(&fp_score_3, "./dat/score_4.dat", "r")) != 0) //スコアファイルを読み込む { std::cout << "<info 045:スコアファイルを「読み取り用として」開けませんでした>" << std::endl; exit(45); } std::cout << "<info 046:スコアファイルを「読み取り用として」開きました>\n" << std::endl; }break; case 4: { fclose(fp_score_4); std::cout << "<info 019: スコアファイルを「読み取り用として」閉じました>" << std::endl; if ((fopen_s(&fp_score_4, "./dat/score_4.dat", "w")) != 0) //スコアファイルを読み込む { std::cout << "<info 020:スコアファイルを「書き取り用として」開けませんでした>" << std::endl; exit(20); } std::cout << "<info 021:スコアファイルを「書き取り用として」開きました>\n" << std::endl; if (high_score_4[0] < score) { ranking = 0; high_score_4[4] = high_score_4[3]; high_score_4[3] = high_score_4[2]; high_score_4[2] = high_score_4[1]; high_score_4[1] = high_score_4[0]; high_score_4[0] = score; } else if (high_score_4[1] < score) { ranking = 1; high_score_4[4] = high_score_4[3]; high_score_4[3] = high_score_4[2]; high_score_4[2] = high_score_4[1]; high_score_4[1] = score; } else if (high_score_4[2] < score) { ranking = 2; high_score_4[4] = high_score_4[3]; high_score_4[3] = high_score_4[2]; high_score_4[2] = score; } else if (high_score_4[3] < score) { ranking = 3; high_score_4[4] = high_score_4[3]; high_score_4[3] = score; } else if (high_score_4[4] < score) { ranking = 4; high_score_4[4] = score; } else { ranking = 5; //ランク外 } for (i = 0; i <= 4; i++) { fprintf(fp_score_4, "%d\n", high_score_4[i]); //スコアファイルを更新 } for (i = 0; i <= 79; i++) { if (list_most_hiragana[i] > max_most_hiragana) { max_most_hiragana = list_most_hiragana[i]; score_most_hiragana = i; } } fclose(fp_score_4); //書き取り用として閉じて,もっかい読み取り用として開く std::cout << "<info 044: スコアファイルを「書き取り用として」閉じました>" << std::endl; if ((fopen_s(&fp_score_4, "./dat/score_4.dat", "r")) != 0) //スコアファイルを読み込む { std::cout << "<info 045:スコアファイルを「読み取り用として」開けませんでした>" << std::endl; exit(45); } std::cout << "<info 046:スコアファイルを「読み取り用として」開きました>\n" << std::endl; }break; case 5: { fclose(fp_score_5); std::cout << "<info 019: スコアファイルを「読み取り用として」閉じました>" << std::endl; if ((fopen_s(&fp_score_5, "./dat/score_4.dat", "w")) != 0) //スコアファイルを読み込む { std::cout << "<info 020:スコアファイルを「書き取り用として」開けませんでした>" << std::endl; exit(20); } std::cout << "<info 021:スコアファイルを「書き取り用として」開きました>\n" << std::endl; if (high_score_5[0] < score) { ranking = 0; high_score_5[4] = high_score_5[3]; high_score_5[3] = high_score_5[2]; high_score_5[2] = high_score_5[1]; high_score_5[1] = high_score_5[0]; high_score_5[0] = score; } else if (high_score_5[1] < score) { ranking = 1; high_score_5[4] = high_score_5[3]; high_score_5[3] = high_score_5[2]; high_score_5[2] = high_score_5[1]; high_score_5[1] = score; } else if (high_score_5[2] < score) { ranking = 2; high_score_5[4] = high_score_5[3]; high_score_5[3] = high_score_5[2]; high_score_5[2] = score; } else if (high_score_5[3] < score) { ranking = 3; high_score_5[4] = high_score_5[3]; high_score_5[3] = score; } else if (high_score_5[4] < score) { ranking = 4; high_score_5[4] = score; } else { ranking = 5; //ランク外 } for (i = 0; i <= 4; i++) { fprintf(fp_score_5, "%d\n", high_score_5[i]); //スコアファイルを更新 } for (i = 0; i <= 79; i++) { if (list_most_hiragana[i] > max_most_hiragana) { max_most_hiragana = list_most_hiragana[i]; score_most_hiragana = i; } } fclose(fp_score_5); //書き取り用として閉じて,もっかい読み取り用として開く std::cout << "<info 044: スコアファイルを「書き取り用として」閉じました>" << std::endl; if ((fopen_s(&fp_score_5, "./dat/score_4.dat", "r")) != 0) //スコアファイルを読み込む { std::cout << "<info 045:スコアファイルを「読み取り用として」開けませんでした>" << std::endl; exit(45); } std::cout << "<info 046:スコアファイルを「読み取り用として」開きました>\n" << std::endl; }break; } } else if (mode == 1) //ステージモードのとき(タイムオーバー) { scene = 6; } } if (lamp_timer_02 <= 0) { word_hit = false; //正解or間違いの演出のエフェクト終了後,語彙スロット未完成状態に } } void keyboard(unsigned char key, int x, int y) { switch (scene) { case 0: { switch (key) { case 'q': case '\033': game_shutdown(); break; case 'g': Mix_PlayChannel(-1, SE_enter, 0); scene = 7; break; //PRESS GAME START 次の画面へ default: break; } }break; case 1: { switch (key) { case '\033': game_shutdown(); break; case 'l': { Mix_PlayChannel(-1, SE_enter, 0); if (mode == 0) { game_reset(); scene = 5;} //スコアアタックモード else if (mode == 1) { standby_stage(stage_select); scene = 5; } //ステージクリアモード } break; default: break; } }break; case 2: { switch (key) { case 'p': {move_lock = false; camera_x = temp_camera_x; camera_y = temp_camera_y; scene = 5; } break;//再開 カメラの位置をゲーム中のに戻す case 'r': {Mix_PlayChannel(-1, SE_select, 0); next_scene = 1; scene = 10; } break;//やりなおす→ほんとうによろしいですか? case 't': {Mix_PlayChannel(-1, SE_select, 0); next_scene = 0; scene = 10; } break;//タイトルに戻る→ほんとうによろしいですか? case '\033': game_shutdown(); break; } }break; case 3: { switch (key) { case 'l': {scene = 4; } break; //リザルト画面切り替え case 'o': {Mix_PlayChannel(-1, SE_enter, 0); camera_x = 640; camera_y = -544; player->center_x = 0; player->center_y = 0; scene = 5; game_reset(); } break;//リトライ case 'p': {Mix_PlayChannel(-1, SE_enter, 0); camera_x = 640; camera_y = -544; player->center_x = 0; player->center_y = 0; scene = 1; game_reset(); }break;//メニューに戻る case '\033':game_shutdown(); break; } }break; case 4: { switch (key) { case 'l': {scene = 3; } break; //リザルト画面切り替え case 'o': {Mix_PlayChannel(-1, SE_enter, 0); camera_x = 640; camera_y = -544; player->center_x = 0; player->center_y = 0; scene = 5; game_reset();} break;//リトライ case 'p': {Mix_PlayChannel(-1, SE_enter, 0); camera_x = 640; camera_y = -544; player->center_x = 0; player->center_y = 0; scene = 1; game_reset();} break;//メニューに戻る case '\033': game_shutdown(); break; } }break; case 5: //ゲーム画面 { switch (key) { case '\033': game_shutdown(); break; case 'a': {onMoveKeyPress_L = true; gun_timer = 0;/*MoveLock_R = true;*/ player->direction = 0; } break; case 'd': {onMoveKeyPress_R = true; gun_timer = 0; /*MoveLock_L = true;*/ player->direction = 1; } break; case 'j': { if (slot_select > 0 && lamp_timer_02 == 0) { Mix_PlayChannel(-1, SE_select, 0); slot_select--; } } break; //スロット移動 case 'l': { if (lamp_timer_02 == 0) { if (mode == 0 && slot_select < mode_mojisu - 1 || mode == 1 && slot_select < stage_info[stage_select] % 10 - 1) { Mix_PlayChannel(-1, SE_select, 0); slot_select++; } } } break; case 'i': { if (lamp_timer_02 == 0) { if (slot[slot_select] != 0 && stage_slot_constraint[stage_select][slot_select]==0) { Mix_PlayChannel(-1, SE_throw, 0); score_leave_hiragana++; slot[slot_select] = 0; } } } break; //選択中のスロットの場所をからっぽにする case 'k': { if (lamp_timer_02 == 0) { if ((mode==0 && mode_mojisu == 3 || mode==1&& stage_info[stage_select] %10==3 ) && slot[0] != 0 && slot[1] != 0 && slot[2] != 0) //3文字モードの時のチェック語彙 { check_goi(slot); lamp_timer_02 = 100; lamp_timer_01 = 50; if (stage_info[stage_select] == 13) //しりとりモード { stage_slot_constraint[stage_select][0] = slot[2]; slot[0] = slot[2]; slot[1] = 0; slot[2] = 0; } else { if (stage_slot_constraint[stage_select][0] == 0) { slot[0] = 0; } if (stage_slot_constraint[stage_select][1] == 0) { slot[1] = 0; } if (stage_slot_constraint[stage_select][2] == 0) { slot[2] = 0; } } } if ((mode == 0 && mode_mojisu == 4 || mode == 1 && stage_info[stage_select] % 10 == 4) && slot[0] != 0 && slot[1] != 0 && slot[2] != 0 && slot[3] != 0) //4文字モードの時のチェック語彙 { check_goi(slot); lamp_timer_02 = 100; lamp_timer_01 = 50; if (stage_info[stage_select] == 14) //しりとりモード { stage_slot_constraint[stage_select][0] = slot[3]; slot[0] = slot[3]; slot[1] = 0; slot[2] = 0; slot[3] = 0; } else { if (stage_slot_constraint[stage_select][0] == 0) { slot[0] = 0; } if (stage_slot_constraint[stage_select][1] == 0) { slot[1] = 0; } if (stage_slot_constraint[stage_select][2] == 0) { slot[2] = 0; } if (stage_slot_constraint[stage_select][3] == 0) { slot[3] = 0; } } } if ((mode == 0 && mode_mojisu == 5 || mode == 1 && stage_info[stage_select] % 10 == 5) && slot[0] != 0 && slot[1] != 0 && slot[2] != 0 && slot[3] != 0 && slot[4] != 0) //5文字モードの時のチェック語彙 { check_goi(slot); lamp_timer_02 = 100; lamp_timer_01 = 50; if (stage_info[stage_select] == 15) //しりとりモード { stage_slot_constraint[stage_select][0] = slot[4]; slot[0] = slot[4]; slot[1] = 0; slot[2] = 0; slot[3] = 0; slot[4] = 0; } else { if (stage_slot_constraint[stage_select][0] == 0) { slot[0] = 0; } if (stage_slot_constraint[stage_select][1] == 0) { slot[1] = 0; } if (stage_slot_constraint[stage_select][2] == 0) { slot[2] = 0; } if (stage_slot_constraint[stage_select][3] == 0) { slot[3] = 0; } if (stage_slot_constraint[stage_select][4] == 0) { slot[4] = 0; } } } slot_select = 0; //スロットの選択位置を左↑ } } break;//単語チェック case 'v': {if (flag_bullet_exist == false) //射撃 { Mix_PlayChannel(-1, SE_shoot, 0); bullet->direction = player->direction; bullet_timer = 0; gun_timer = 60; flag_bullet_exist = true; if (player->direction == 0) { bullet->center_x = player->center_x + 40; bullet->center_y = player->center_y; } else if (player->direction == 1) { bullet->center_x = player->center_x - 40; bullet->center_y = player->center_y; } }} break; case 'p': {move_lock = true; scene = 2; temp_camera_x = camera_x; temp_camera_y = camera_y; camera_x = 640; camera_y = -544; } break; //ポーズ カメラの位置をGUI用の位置にリセット //case 't': scene = 6; temp_camera_x = camera_x; temp_camera_y = camera_y; camera_x = 640; camera_y = -544; break; //デバッグ用トリガー1 強制ゲームオーバー //case 'b': slot[3] = 19; break; //デバッグ用トリガー2 //case 'n': slot[0] = 5; slot[1] = 12; slot[2] = 47; slot[3] = 10; break; //デバッグ用トリガー3(成功時シミュレーション) //case 'm': slot[0] = 5; slot[1] = 12; slot[2] = 47; slot[3] = 6; break; //デバッグ用トリガー4(失敗時シミュレーション) case '\040': if (player_jump == false) { Mix_PlayChannel(-1, SE_jump, 0); player_jump = true; flag_collision_D = false; } break; default: break; } }break; case 6: //ゲームオーバー画面 { switch (key) { case 'k': { Mix_PlayChannel(-1, SE_enter, 0); if (mode == 0) { scene = 3; lamp_timer_01 = 0; lamp_timer_02 = 0; } else { scene = 9; } //ステージクリアモードのときはステージ選択画面に戻る } break; //リザルト画面へ case '\033': game_shutdown(); break; } }break; case 7: //モード選択画面 { switch (key) { case 'i': { Mix_PlayChannel(-1, SE_back, 0); scene = 0; } break; //タイトル画面に戻る case 'k': { if (mode == 0) { Mix_PlayChannel(-1, SE_enter, 0); stage_select = 0; scene = 8; } if (mode == 1) { Mix_PlayChannel(-1, SE_enter, 0); stage_select = 1; scene = 9; }} break; //スコアアタックモードはステージ0として扱う case 'w': { Mix_PlayChannel(-1, SE_select, 0); mode = 0; } break; case 's': { Mix_PlayChannel(-1, SE_select, 0); mode =1; } break; case '\033': game_shutdown(); break; } }break; case 8: //スコアアタックモード選択時の次の画面(文字数選択) { switch (key) { case 'i': { Mix_PlayChannel(-1, SE_back, 0); scene = 7; } break; //モード選択画面に戻る case 'k': { Mix_PlayChannel(-1, SE_enter, 0); scene = 1; } break; // 'a': { if (mode_mojisu >=4) { mode_mojisu--; }} break; //ステージ生成アルゴリズムが考え付いたら開放します. //case 'd': { if (mode_mojisu <= 4) { mode_mojisu++; }} break; case '\033': game_shutdown(); break; } }break; case 9: //ステージモード選択時の次の画面 (ステージ選択画面 { switch (key) { case 'i': { Mix_PlayChannel(-1, SE_back, 0); scene = 7; } break; //モード選択画面に戻る case 'k': {if (stage_info[stage_select] !=0) { Mix_PlayChannel(-1, SE_enter, 0); scene = 1; } } break; //ステージが定義されていれば次のシーンへ case 'a': { if (stage_select >= 2) { Mix_PlayChannel(-1, SE_select, 0); stage_select--; }} break; case 'd': { if (stage_select <= STAGE_LIMIT-1) { Mix_PlayChannel(-1, SE_select, 0); stage_select++; }} break; case 'j': { if (stage_select >= 12) { Mix_PlayChannel(-1, SE_select, 0); stage_select -= 10; } else { stage_select = 1; }} break; case 'l': { if (stage_select <= STAGE_LIMIT - 11) { Mix_PlayChannel(-1, SE_select, 0); stage_select += 10; } else { stage_select = STAGE_LIMIT; }} break; case '\033': game_shutdown(); break; } }break; case 10: //ほんとうによろしいですか? { switch (key) { case 'y': { //はい Mix_PlayChannel(-1, SE_enter, 0); move_lock = false; camera_x = 640; camera_y = -544; player->center_x = 0; player->center_y = 0; if (next_scene == 1) //ゲームをはじめからやりなおすとき,モードに応じてステージを再構築する { if (mode == 0) { scene = 5; game_reset(); stage_select = 0; } else if (mode == 1) { scene = 5; standby_stage(stage_select); } } scene = next_scene; }break; case 'n': { //いいえ Mix_PlayChannel(-1, SE_back, 0); scene = 2; }break; case '\033': game_shutdown(); break; } }break; case 11: { switch (key) { case 'o': {Mix_PlayChannel(-1, SE_enter, 0); camera_x = 640; camera_y = -544; player->center_x = 0; player->center_y = 0; scene = 1; } break;//リトライ case 'p': {Mix_PlayChannel(-1, SE_enter, 0); camera_x = 640; camera_y = -544; player->center_x = 0; player->center_y = 0; scene = 9; }break;//ステージ選択画面に戻る case '\033':game_shutdown(); break; } }break; } } void keyboardUp(unsigned char key, int x, int y) { switch (key) { case 'a': onMoveKeyPress_L = false; break; case 'd': onMoveKeyPress_R = false; break; default: break; } } void resize(int w, int h) { camera_x = 640; camera_y = -544; if ((double)h/(double)w <= (double)HEIGHT / (double)WIDTH) //規定のアスペクト比より横長の場合 { glViewport((w-(double)h/0.5625)/2, 0, (double)h / 0.5625, h); } else //規定のアスペクト比より縦長の場合 { glViewport(0, (h-(double)w * 0.5625)/2 , w, (double)w * 0.5625); } glLoadIdentity(); glOrtho(0.0, WIDTH, HEIGHT, 0.0, -1.0, 1.0); gluLookAt(camera_x, camera_y, 0, camera_x, camera_y, 1, 0, 1, 0); std::cout << "<info 028: 画面のリサイズ>" << std::endl; } void Init() { int temp[9] = {}; //ファイルから配列に渡すための受け皿.使い捨て int *sc = &stage_clear[0][0]; // 効果音のロード SE_select = Mix_LoadWAV("./sound/select.wav"); if (SE_select == NULL) { std::cout << "<info 056: 音声ファイルを開けませんでした>" << std::endl; exit(56); } SE_back = Mix_LoadWAV("./sound/back.wav"); if (SE_back == NULL) { std::cout << "<info 056: 音声ファイルを開けませんでした>" << std::endl; exit(56); } SE_batsu = Mix_LoadWAV("./sound/batsu.wav"); if (SE_batsu == NULL) { std::cout << "<info 056: 音声ファイルを開けませんでした>" << std::endl; exit(56); } SE_maru = Mix_LoadWAV("./sound/maru.wav"); if (SE_maru == NULL) { std::cout << "<info 056: 音声ファイルを開けませんでした>" << std::endl; exit(56); } SE_enter = Mix_LoadWAV("./sound/enter.wav"); if (SE_enter == NULL) { std::cout << "<info 056: 音声ファイルを開けませんでした>" << std::endl; exit(56); } SE_hit = Mix_LoadWAV("./sound/hit.wav"); if (SE_hit == NULL) { std::cout << "<info 056: 音声ファイルを開けませんでした>" << std::endl; exit(56); } SE_shoot = Mix_LoadWAV("./sound/shoot.wav"); if (SE_shoot == NULL) { std::cout << "<info 056: 音声ファイルを開けませんでした>" << std::endl; exit(56); } SE_jump = Mix_LoadWAV("./sound/jump.wav"); if (SE_jump== NULL) { std::cout << "<info 056: 音声ファイルを開けませんでした>" << std::endl; exit(56); } SE_throw = Mix_LoadWAV("./sound/throw.wav"); if (SE_throw == NULL) { std::cout << "<info 056: 音声ファイルを開けませんでした>" << std::endl; exit(56); } std::cout << "<info 057: 音声ファイルを読み込みました>" << std::endl; std::cout << "<info 016: スコアファイルを読み込みました>" << std::endl; if ((fopen_s(&fp_score_3, "./dat/score_3.dat", "r")) != 0) //スコアファイルを読み込む { std::cout << "<info 015: スコアファイルを開けませんでした>" << std::endl; exit(15); } i = 0; while (fscanf_s(fp_score_3, "%d", &high_score_4[i]) != EOF) { i++; } std::cout << "<info 016: スコアファイルを読み込みました>" << std::endl; if ((fopen_s(&fp_score_4, "./dat/score_4.dat", "r")) != 0) //スコアファイルを読み込む { std::cout << "<info 015: スコアファイルを開けませんでした>" << std::endl; exit(15); } i = 0; while (fscanf_s(fp_score_4, "%d", &high_score_4[i]) != EOF) { i++; } std::cout << "<info 016: スコアファイルを読み込みました>" << std::endl; if ((fopen_s(&fp_score_5, "./dat/score_5.dat", "r")) != 0) //スコアファイルを読み込む { std::cout << "<info 015: スコアファイルを開けませんでした>" << std::endl; exit(15); } i = 0; while (fscanf_s(fp_score_5, "%d", &high_score_4[i]) != EOF) { i++; } std::cout << "<info 016: スコアファイルを読み込みました>" << std::endl; if ((fopen_s(&fp_dic_3, "./dat/3moji_dic.dat", "r")) != 0) //辞書ファイルを読み込む { std::cout << "<info 012: 辞書ファイルを開けませんでした" << std::endl; exit(12); } i = 0; while (fscanf_s(fp_dic_3, "%d,%d,%d,", &temp[0],&temp[1],&temp[2]) != EOF) { dic_3moji.push_back({ temp[0],temp[1],temp[2] }); printf("dic_3moji[%d][0]=%d %d %x\n", i, dic_3moji[i][0],&dic_3moji[i][0]); printf("dic_3moji[%d][1]=%d %d %x\n", i, dic_3moji[i][1], &dic_3moji[i][1]); printf("dic_3moji[%d][2]=%d %d %x\n", i,dic_3moji[i][2], &dic_3moji[i][2]); i++; } dic_3_all = i; std::cout << "<info 013: 3文字辞書 " << dic_3_all << "単語を読み込みました>" << std::endl; if ((fopen_s(&fp_dic_4, "./dat/4moji_dic.dat", "r")) != 0) //辞書ファイルを読み込む { std::cout << "<info 012: 辞書ファイルを開けませんでした" << std::endl; exit(12); } i = 0; while (fscanf_s(fp_dic_4, "%d,%d,%d,%d,",&temp[0],&temp[1],&temp[2],&temp[3]) != EOF) { dic_4moji.push_back({ temp[0],temp[1],temp[2],temp[3] }); i++; } dic_4_all = i; std::cout << "<info 013: 4文字辞書 " << dic_4_all << "単語を読み込みました>" << std::endl; if ((fopen_s(&fp_dic_5, "./dat/5moji_dic.dat", "r")) != 0) //辞書ファイルを読み込む { std::cout << "<info 012: 辞書ファイルを開けませんでした" << std::endl; exit(12); } i = 0; while (fscanf_s(fp_dic_5, "%d,%d,%d,%d,%d,", &temp[0], &temp[1], &temp[2], &temp[3],&temp[4]) != EOF) { dic_5moji.push_back({ temp[0],temp[1],temp[2],temp[3],temp[4] }); i++; } dic_5_all = i; std::cout << "<info 013: 5文字辞書 " << dic_5_all << "単語を読み込みました>" << std::endl; if ((fopen_s(&fp_stageclear, "./dat/stage_clear.dat", "r")) != 0) //ステージクリア進捗状況ファイルを読み込んで,ステージ選択モードで「何ステージをどのくらいクリアしているか」の情報を取得する { std::cout << "<info 032: ステージクリア進捗状況ファイルを開けませんでした>" << std::endl; exit(32); } i = 0; while (fscanf_s(fp_stageclear, "%d,%d,%d,%d,%d", sc + i * 5, sc + i * 5 + 1, sc + i * 5 + 2, sc + i * 5 + 3, sc + i * 5 + 4) != EOF) { i++; } std::cout << "<info 033: ステージクリア進捗状況(" << i << ")をステージ分を読み込みました>" << std::endl; for (i = 0; i <= STAGE_LIMIT; i++) { //fprintf(fp_stageclear, "%d,%d,%d,%d,%d\n", stage_clear[i][0], stage_clear[i][1], stage_clear[i][2], stage_clear[i][3], stage_clear[i][4]); //ステージクリア進捗状況ファイルを更新 if (stage_clear[i][0] == 1) { stage_medal[0]++; } if (stage_clear[i][1] == 1) { stage_medal[1]++; } if (stage_clear[i][2] == 1) { stage_medal[2]++; } //メダルを取った数を記録し,「何ステージをどのくらいクリアしているか」の情報を取得する } if ((fopen_s(&fp_stage_nolma_info, "./dat/stage_nolma_info.dat", "r")) != 0) //ステージのノルマや制限時間などの基本情報を取得する { std::cout << "<info 050: ステージノルマ情報ファイルを開けませんでした>" << std::endl; exit(50); } i = 0; while (fscanf_s(fp_stage_nolma_info, "%d,%d,%d,%d,%d,%d,%d,%d,%d", &stage_info[i], &stage_nolma[i], &stage_time_limit[i], &stage_time_limit_gold[i], &stage_slot_constraint[i][0], &stage_slot_constraint[i][1], &stage_slot_constraint[i][2], &stage_slot_constraint[i][3], &stage_slot_constraint[i][4]) != EOF) { i++; } std::cout << "<info 051: ステージノルマ情報ファイルをステージ分を読み込みました>" << std::endl; glClearColor(0.0, 0.0, 0.0, 1.0); glOrtho(0, WIDTH, HEIGHT, 0, -1, 1); GdiplusStartup(&gdiPT, &gdiPSI, NULL); LoadImagePNG(L"./pic/num_a0.png", tex_num[0][0]); LoadImagePNG(L"./pic/num_a1.png", tex_num[0][1]); LoadImagePNG(L"./pic/num_a2.png", tex_num[0][2]); LoadImagePNG(L"./pic/num_a3.png", tex_num[0][3]); LoadImagePNG(L"./pic/num_a4.png", tex_num[0][4]); LoadImagePNG(L"./pic/num_a5.png", tex_num[0][5]); LoadImagePNG(L"./pic/num_a6.png", tex_num[0][6]); LoadImagePNG(L"./pic/num_a7.png", tex_num[0][7]); LoadImagePNG(L"./pic/num_a8.png", tex_num[0][8]); LoadImagePNG(L"./pic/num_a9.png", tex_num[0][9]); LoadImagePNG(L"./pic/block_null.png", tex_num[0][10]); LoadImagePNG(L"./pic/num_b0.png", tex_num[1][0]); LoadImagePNG(L"./pic/num_b1.png", tex_num[1][1]); LoadImagePNG(L"./pic/num_b2.png", tex_num[1][2]); LoadImagePNG(L"./pic/num_b3.png", tex_num[1][3]); LoadImagePNG(L"./pic/num_b4.png", tex_num[1][4]); LoadImagePNG(L"./pic/num_b5.png", tex_num[1][5]); LoadImagePNG(L"./pic/num_b6.png", tex_num[1][6]); LoadImagePNG(L"./pic/num_b7.png", tex_num[1][7]); LoadImagePNG(L"./pic/num_b8.png", tex_num[1][8]); LoadImagePNG(L"./pic/num_b9.png", tex_num[1][9]); LoadImagePNG(L"./pic/num_plus.png", tex_num[1][10]); LoadImagePNG(L"./pic/num_c0.png", tex_num[2][0]); LoadImagePNG(L"./pic/num_c1.png", tex_num[2][1]); LoadImagePNG(L"./pic/num_c2.png", tex_num[2][2]); LoadImagePNG(L"./pic/num_c3.png", tex_num[2][3]); LoadImagePNG(L"./pic/num_c4.png", tex_num[2][4]); LoadImagePNG(L"./pic/num_c5.png", tex_num[2][5]); LoadImagePNG(L"./pic/num_c6.png", tex_num[2][6]); LoadImagePNG(L"./pic/num_c7.png", tex_num[2][7]); LoadImagePNG(L"./pic/num_c8.png", tex_num[2][8]); LoadImagePNG(L"./pic/num_c9.png", tex_num[2][9]); LoadImagePNG(L"./pic/block_null.png", tex_num[2][10]); LoadImagePNG(L"./pic/num_d0.png", tex_num[3][0]); LoadImagePNG(L"./pic/num_d1.png", tex_num[3][1]); LoadImagePNG(L"./pic/num_d2.png", tex_num[3][2]); LoadImagePNG(L"./pic/num_d3.png", tex_num[3][3]); LoadImagePNG(L"./pic/num_d4.png", tex_num[3][4]); LoadImagePNG(L"./pic/num_d5.png", tex_num[3][5]); LoadImagePNG(L"./pic/num_d6.png", tex_num[3][6]); LoadImagePNG(L"./pic/num_d7.png", tex_num[3][7]); LoadImagePNG(L"./pic/num_d8.png", tex_num[3][8]); LoadImagePNG(L"./pic/num_d9.png", tex_num[3][9]); LoadImagePNG(L"./pic/block_null.png", tex_num[3][10]); player1.LoadImagePNG2(player1.file, player1.tex); player2.LoadImagePNG2(player2.file, player2.tex); player3.LoadImagePNG2(player3.file, player3.tex); floor1.LoadImagePNG2(floor1.file, floor1.tex); UI_title.LoadImagePNG2(UI_title.file, UI_title.tex); UI_quit.LoadImagePNG2(UI_quit.file, UI_quit.tex); UI_gamestart.LoadImagePNG2(UI_gamestart.file, UI_gamestart.tex); UI_pressstart.LoadImagePNG2(UI_pressstart.file, UI_pressstart.tex); select_highlight.LoadImagePNG2(select_highlight.file, select_highlight.tex); block_alphabet_p.LoadImagePNG2(block_alphabet_p.file, block_alphabet_p.tex); block_alphabet_a.LoadImagePNG2(block_alphabet_a.file, block_alphabet_a.tex); block_alphabet_u.LoadImagePNG2(block_alphabet_u.file, block_alphabet_u.tex); block_alphabet_s.LoadImagePNG2(block_alphabet_s.file, block_alphabet_s.tex); block_alphabet_e.LoadImagePNG2(block_alphabet_e.file, block_alphabet_e.tex); UI_return.LoadImagePNG2(UI_return.file, UI_return.tex); UI_highscore.LoadImagePNG2(UI_highscore.file, UI_highscore.tex); UI_gameover.LoadImagePNG2(UI_gameover.file, UI_gameover.tex); UI_tonext.LoadImagePNG2(UI_tonext.file, UI_tonext.tex); UI_07.LoadImagePNG2(UI_07.file, UI_07.tex); UI_08.LoadImagePNG2(UI_08.file, UI_08.tex); UI_09.LoadImagePNG2(UI_09.file, UI_09.tex); UI_result01.LoadImagePNG2(UI_result01.file, UI_result01.tex); UI_result02.LoadImagePNG2(UI_result02.file, UI_result02.tex); UI_result03.LoadImagePNG2(UI_result03.file, UI_result03.tex); UI_result04.LoadImagePNG2(UI_result04.file, UI_result04.tex); UI_score.LoadImagePNG2(UI_score.file, UI_score.tex); UI_newrecord.LoadImagePNG2(UI_newrecord.file, UI_newrecord.tex); UI_ranking.LoadImagePNG2(UI_ranking.file, UI_ranking.tex); UI_rank01.LoadImagePNG2(UI_rank01.file, UI_rank01.tex); UI_rank02.LoadImagePNG2(UI_rank02.file, UI_rank02.tex); UI_rank03.LoadImagePNG2(UI_rank03.file, UI_rank03.tex); UI_rank04.LoadImagePNG2(UI_rank04.file, UI_rank04.tex); UI_rank05.LoadImagePNG2(UI_rank05.file, UI_rank05.tex); UI_difficulty01.LoadImagePNG2(UI_difficulty01.file, UI_difficulty01.tex); UI_difficulty02.LoadImagePNG2(UI_difficulty02.file, UI_difficulty02.tex); UI_difficulty03.LoadImagePNG2(UI_difficulty03.file, UI_difficulty03.tex); arrow.LoadImagePNG2(arrow.file, arrow.tex); BG_01.LoadImagePNG2(BG_01.file, BG_01.tex); BG_02.LoadImagePNG2(BG_02.file, BG_02.tex); BG_03.LoadImagePNG2(BG_03.file, BG_03.tex); BG_04.LoadImagePNG2(BG_04.file, BG_04.tex); BG_05.LoadImagePNG2(BG_05.file, BG_05.tex); UI_10.LoadImagePNG2(UI_10.file, UI_10.tex); UI_11.LoadImagePNG2(UI_11.file, UI_11.tex); UI_12.LoadImagePNG2(UI_12.file, UI_12.tex); UI_13.LoadImagePNG2(UI_13.file, UI_13.tex); UI_14.LoadImagePNG2(UI_14.file, UI_14.tex); UI_15.LoadImagePNG2(UI_15.file, UI_15.tex); UI_16.LoadImagePNG2(UI_16.file, UI_16.tex); UI_17.LoadImagePNG2(UI_17.file, UI_17.tex); UI_slot_base_3.LoadImagePNG2(UI_slot_base_3.file, UI_slot_base_3.tex); UI_slot_base_4.LoadImagePNG2(UI_slot_base_4.file, UI_slot_base_4.tex); UI_slot_base_5.LoadImagePNG2(UI_slot_base_5.file, UI_slot_base_5.tex); UI_slot_highlight.LoadImagePNG2(UI_slot_highlight.file, UI_slot_highlight.tex); UI_slot_decision.LoadImagePNG2(UI_slot_decision.file, UI_slot_decision.tex); UI_slot_decision_green.LoadImagePNG2(UI_slot_decision_green.file, UI_slot_decision_green.tex); player_penalty.LoadImagePNG2(player_penalty.file, player_penalty.tex); player_maru.LoadImagePNG2(player_maru.file, player_maru.tex); player_batsu.LoadImagePNG2(player_batsu.file, player_batsu.tex); player_fukidashi01.LoadImagePNG2(player_fukidashi01.file, player_fukidashi01.tex); player_fukidashi02.LoadImagePNG2(player_fukidashi02.file, player_fukidashi02.tex); //bullet.LoadImagePNG2(bullet.file, bullet.tex); block_light_1.LoadImagePNG2(block_light_1.file, block_light_1.tex); block_light_2.LoadImagePNG2(block_light_2.file, block_light_2.tex); UI_confirm.LoadImagePNG2(UI_confirm.file, UI_confirm.tex); UI_confirm_2.LoadImagePNG2(UI_confirm_2.file, UI_confirm_2.tex); UI_mode_score_attack.LoadImagePNG2(UI_mode_score_attack.file, UI_mode_score_attack.tex); UI_mode_stage_clear.LoadImagePNG2(UI_mode_stage_clear.file, UI_mode_stage_clear.tex); UI_mode_highlight.LoadImagePNG2(UI_mode_highlight.file, UI_mode_highlight.tex); UI_mode_description_1.LoadImagePNG2(UI_mode_description_1.file, UI_mode_description_1.tex); UI_mode_description_2.LoadImagePNG2(UI_mode_description_2.file, UI_mode_description_2.tex); UI_mode_select_UI.LoadImagePNG2(UI_mode_select_UI.file, UI_mode_select_UI.tex); UI_mode_mojisu.LoadImagePNG2(UI_mode_mojisu.file, UI_mode_mojisu.tex); UI_mode_stage.LoadImagePNG2(UI_mode_stage.file, UI_mode_stage.tex); UI_mode_3.LoadImagePNG2(UI_mode_3.file, UI_mode_3.tex); UI_mode_4.LoadImagePNG2(UI_mode_4.file, UI_mode_4.tex); UI_mode_5.LoadImagePNG2(UI_mode_5.file, UI_mode_5.tex); UI_mode_highlight.LoadImagePNG2(UI_mode_mojisu_highlight.file, UI_mode_mojisu_highlight.tex); UI_mode_select_mojisu_UI.LoadImagePNG2(UI_mode_select_mojisu_UI.file, UI_mode_select_mojisu_UI.tex); UI_mode_waku.LoadImagePNG2(UI_mode_waku.file, UI_mode_waku.tex); UI_mode_highscore_1.LoadImagePNG2(UI_mode_highscore_1.file, UI_mode_highscore_1.tex); UI_mode_highscore_2.LoadImagePNG2(UI_mode_highscore_2.file, UI_mode_highscore_2.tex); UI_slot_locked.LoadImagePNG2(UI_slot_locked.file, UI_slot_locked.tex); UI_block_stage_num.LoadImagePNG2(UI_block_stage_num.file, UI_block_stage_num.tex); UI_block_stage_num_select.LoadImagePNG2(UI_block_stage_num_select.file, UI_block_stage_num_select.tex); UI_clear_lamp_on_1.LoadImagePNG2(UI_clear_lamp_on_1.file, UI_clear_lamp_on_1.tex); UI_clear_lamp_on_2.LoadImagePNG2(UI_clear_lamp_on_2.file, UI_clear_lamp_on_2.tex); UI_clear_lamp_on_3.LoadImagePNG2(UI_clear_lamp_on_3.file, UI_clear_lamp_on_3.tex); UI_clear_lamp_on_1_lux.LoadImagePNG2(UI_clear_lamp_on_1_lux.file, UI_clear_lamp_on_1_lux.tex); UI_clear_lamp_on_2_lux.LoadImagePNG2(UI_clear_lamp_on_2_lux.file, UI_clear_lamp_on_2_lux.tex); UI_clear_lamp_on_3_lux.LoadImagePNG2(UI_clear_lamp_on_3_lux.file, UI_clear_lamp_on_3_lux.tex); UI_clear_lamp_off.LoadImagePNG2(UI_clear_lamp_off.file, UI_clear_lamp_off.tex); UI_time_limit_description.LoadImagePNG2(UI_time_limit_description.file, UI_time_limit_description.tex); UI_coming_soon192.LoadImagePNG2(UI_coming_soon192.file, UI_coming_soon192.tex); UI_coming_soon64.LoadImagePNG2(UI_coming_soon64.file, UI_coming_soon64.tex); UI_slot_constraint_description.LoadImagePNG2(UI_slot_constraint_description.file, UI_slot_constraint_description.tex); UI_mission_description_0.LoadImagePNG2(UI_mission_description_0.file, UI_mission_description_0.tex); UI_mission_description_1.LoadImagePNG2(UI_mission_description_1.file, UI_mission_description_1.tex); UI_mission_description_2.LoadImagePNG2(UI_mission_description_2.file, UI_mission_description_2.tex); UI_num_aslash.LoadImagePNG2(UI_num_aslash.file, UI_num_aslash.tex); UI_num_aslash_big.LoadImagePNG2(UI_num_aslash_big.file, UI_num_aslash_big.tex); UI_result_stage.LoadImagePNG2(UI_result_stage.file, UI_result_stage.tex); UI_result_stage_title.LoadImagePNG2(UI_result_stage_title.file, UI_result_stage_title.tex); UI_result_stage_title.LoadImagePNG2(UI_result_stage_title.file, UI_result_stage_title.tex); UI_result_stage_medal_1.LoadImagePNG2(UI_result_stage_medal_1.file, UI_result_stage_medal_1.tex); UI_result_stage_medal_2.LoadImagePNG2(UI_result_stage_medal_2.file, UI_result_stage_medal_2.tex); UI_result_stage_medal_3.LoadImagePNG2(UI_result_stage_medal_3.file, UI_result_stage_medal_3.tex); UI_result_stage_medal_1_lux.LoadImagePNG2(UI_result_stage_medal_1_lux.file, UI_result_stage_medal_1_lux.tex); UI_result_stage_medal_2_lux.LoadImagePNG2(UI_result_stage_medal_2_lux.file, UI_result_stage_medal_2_lux.tex); UI_result_stage_medal_3_lux.LoadImagePNG2(UI_result_stage_medal_3_lux.file, UI_result_stage_medal_3_lux.tex); UI_arrow_2L.LoadImagePNG2(UI_arrow_2L.file, UI_arrow_2L.tex); UI_arrow_2R.LoadImagePNG2(UI_arrow_2R.file, UI_arrow_2R.tex); UI_arrow_2D.LoadImagePNG2(UI_arrow_2D.file, UI_arrow_2D.tex); for (i = 0; i <= 79; i++) { block_hiragana_UI[i].LoadImagePNG2(block_hiragana_UI[i].file, block_hiragana_UI[i].tex); block_hiragana[i].LoadImagePNG2(block_hiragana[i].file, block_hiragana[i].tex); block_hiragana_mini[i].LoadImagePNG2(block_hiragana_mini[i].file, block_hiragana_mini[i].tex); } for (i = 1; i <= 79; i++) { choose_hiragana_weight_add[i] = choose_hiragana_weight_add[i - 1] + choose_hiragana_weight[i]; } //コピー用 //.LoadImagePNG2(.file, .tex); player = new AnimationChara(0.0, 0.0, 64.0, 64.0, L"./pic/player_walk1.png"); player->LoadPNGImage(L"./pic/player_walk2.png"); player->LoadPNGImage(L"./pic/player_walk3.png"); player->LoadPNGImage(L"./pic/player_jump.png"); player->LoadPNGImage(L"./pic/player_kamae.png"); player->LoadPNGImage(L"./pic/player_walk1_r.png"); player->LoadPNGImage(L"./pic/player_walk2_r.png"); player->LoadPNGImage(L"./pic/player_walk3_r.png"); player->LoadPNGImage(L"./pic/player_jump_r.png"); player->LoadPNGImage(L"./pic/player_kamae_r.png"); bullet = new AnimationChara(0.0, 0.0, 64.0, 64.0, L"./pic/bullet.png"); std::cout << "<info 022: 画像を読み込みました>" << std::endl; scene = 0; std::vector<std::vector<int>>::iterator dic3 = dic_3moji.begin(); //vectorのポインタ的なやつ 辞書のデータ std::vector<std::vector<int>>::iterator dic4 = dic_4moji.begin(); std::vector<std::vector<int>>::iterator dic5 = dic_5moji.begin(); int *hw3 = &hiragana_weight_3[0][0]; int *hw4 = &hiragana_weight_4[0][0]; int *hw5 = &hiragana_weight_5[0][0]; float *hs3 = &hiragana_score_3[0][0]; float *hs4 = &hiragana_score_4[0][0]; float *hs5 = &hiragana_score_5[0][0]; const char dics2[40000][25] = {}; const char *dics2_ = &dics2[0][0]; i = 0; for (k = 0; k < dic_3_all; k++) { //if (k >= 35000 && k< 38000) //{ // printf("%d:%d %d %d %d\n", k, dic_4moji[k][0], dic_4moji[k][1], dic_4moji[k][2], dic_4moji[k][3]); //} for (j = 0; j <= 2; j++) { (*(hw3 + dic_3moji[k][j]))++; //ひらがなの登場回数を計算して格納する //printf("%d %d %d\n",(dic3 +k*3+j),k,j); } } for (dic3 = dic_3moji.begin(); dic3 != dic_3moji.end(); dic3++) { std::cout << *dic3 << std::endl; } for (k = 0; k < dic_4_all; k++) { //if (k >= 35000 && k< 38000) //{ // printf("%d:%d %d %d %d\n", k, dic_4moji[k][0], dic_4moji[k][1], dic_4moji[k][2], dic_4moji[k][3]); //} for (j = 0; j <= 3; j++) { //(*(hw4 + (*(dic4 + k * 4 + j)) * 4 + j))++; //ひらがなの登場回数を計算して格納する } } for (k = 0; k < dic_5_all; k++) { //if (k >= 35000 && k< 38000) //{ // printf("%d:%d %d %d %d\n", k, dic_4moji[k][0], dic_4moji[k][1], dic_4moji[k][2], dic_4moji[k][3]); //} for (j = 0; j <= 4; j++) { //(*(hw5 + (*(dic5 + k * 5 + j)) * 5 + j))++; //ひらがなの登場回数を計算して格納する } } for (k = 0; k < 80; k++) //何文字目の何のひらがなであれば何点,という点数を付与する { for (j = 0; j <= 2; j++) { if (*(hw3+3*k+j) >= 2000) { *(hs3+3*k+j) = 2.5; } else if (*(hw3+3*k+j) >= 1600) { *(hs3+3*k+j) = 3; } else if (*(hw3+3*k+j) >= 1300) { *(hs3+3*k+j) = 4.5; } else if (*(hw3+3*k+j) >= 1000) { *(hs3+3*k+j) = 5; } else if (*(hw3+3*k+j) >= 750) { *(hs3+3*k+j) = 7.5; } else if (*(hw3+3*k+j) >= 500) { *(hs3+3*k+j) = 10; } else if (*(hw3+3*k+j) >= 300) { *(hs3+3*k+j) = 12; } else if (*(hw3+3*k+j) >= 150) { *(hs3+3*k+j) = 18; } else if (*(hw3+3*k+j) >= 75) { *(hs3+3*k+j) = 30; } else if (*(hw3+3*k+j) >= 0) { *(hs3+3*k+j) = 45; } } for (j = 0; j <= 3; j++) { if (*(hw4 + 4 * k + j) >= 2000) { *(hs4 + 4 * k + j) = 2.5; } else if (*(hw4 + 4 * k + j) >= 1600) { *(hs4 + 4 * k + j) = 3; } else if (*(hw4 + 4 * k + j) >= 1300) { *(hs4 + 4 * k + j) = 5; } else if (*(hw4 + 4 * k + j) >= 1000) { *(hs4 + 4 * k + j) = 7.5; } else if (*(hw4 + 4 * k + j) >= 750) { *(hs4 + 4 * k + j) = 10; } else if (*(hw4 + 4 * k + j) >= 500) { *(hs4 + 4 * k + j) = 15; } else if (*(hw4 + 4 * k + j) >= 300) { *(hs4 + 4 * k + j) = 20; } else if (*(hw4 + 4 * k + j) >= 150) { *(hs4 + 4 * k + j) = 30; } else if (*(hw4 + 4 * k + j) >= 75) { *(hs4 + 4 * k + j) = 50; } else if (*(hw4 + 4 * k + j) >= 0) { *(hs4 + 4 * k + j) = 75; } } for (j = 0; j <= 4; j++) { if (*(hw5 + 5 * k + j) >= 2000) { *(hs5 + 5 * k + j) = 2.5; } else if (*(hw5 + 5 * k + j) >= 1600) { *(hs5 + 5 * k + j) = 4; } else if (*(hw5 + 5 * k + j) >= 1300) { *(hs5 + 5 * k + j) = 6; } else if (*(hw5 + 5 * k + j) >= 1000) { *(hs5 + 5 * k + j) = 10; } else if (*(hw5 + 5 * k + j) >= 750) { *(hs5 + 5 * k + j) = 12.5; } else if (*(hw5 + 5 * k + j) >= 500) { *(hs5 + 5 * k + j) = 20; } else if (*(hw5 + 5 * k + j) >= 300) { *(hs5 + 5 * k + j) = 30; } else if (*(hw5 + 5 * k + j) >= 150) { *(hs5 + 5 * k + j) = 50; } else if (*(hw5 + 5 * k + j) >= 75) { *(hs5 + 5 * k + j) = 75; } else if (*(hw5 + 5 * k + j) >= 0) { *(hs5 + 5 * k + j) = 100; } } } std::cout << "<info 023: ひらがなの配点計算が完了しました>" << std::endl; } void timer(int value) { glutPostRedisplay(); glutTimerFunc(16, timer, 0); //だいたい60fpsを目指す flag_move_x = true; //タイマー関数が呼び出されたのでプレイヤーや弾丸の移動を許可する flag_move_y = true; flag_move_bullet = true; if (scene == 5) //ゲーム中,タイマー起動 { time--; //ゲーム時間の残りタイムをへらす if (lamp_timer_01 > 0) //スロットの点滅時間 { lamp_timer_01--; } if (lamp_timer_02 > 0) //キャラクターのリアクションの時間 { lamp_timer_02--; } if (gun_timer > 0) //キャラクターのリアクションの時間 { gun_timer--; } if (flag_bullet_exist == true) //キャラクターのリアクションの時間 { bullet_timer++; } if (bullet_timer > 30) //弾が飛んでいる間,弾が発射できなかったりする { flag_bullet_exist = false; } lamp_timer_block++; if (lamp_timer_block > 400) //ルーレットブロックのランプの点灯エフェクト { lamp_timer_block=0; } hiragana_roulette_timer++; if (hiragana_roulette_timer > 74*60) //ルーレットブロックの中身の遷移のタイマー { hiragana_roulette_timer = 0; } if (player_jump == true) { jump_timer++; } } if (scene == 6) { temp_camera_x = camera_x; temp_camera_y = camera_y; camera_x = 640; camera_y = -544; } if (scene == 9 || scene == 11) //クリアメダル全点灯のゴージャスな演出 { lamp_timer_clear++; if (lamp_timer_clear > 200) //ルーレットブロックのランプの点灯エフェクト { lamp_timer_clear = 0; } } if (onMoveKeyPress_L == true || onMoveKeyPress_R == true) //歩きアニメーションのため (画像1→2→3→2というふうに歩き中には4枚の画像を連続で表示する) { walk_timer++; if (speed <= 8) //キャラクターのスピードを加速する { speed += 1; } } else { speed = 0; walk_timer = 0; } //歩行が止まるとスピードとアニメーションをリセットする } int main(int argc, char *argv[]) { if (SDL_Init(SDL_INIT_AUDIO) < 0) //SDLのセットアップ { std::cout << "<info 054: SDLのセットアップに失敗しました>" << std::endl; exit(54); } if (Mix_OpenAudio(22050, MIX_DEFAULT_FORMAT, 2, 512) == -1) //SDL_mixerのセットアップ { std::cout << "<info 055: SDL_mixerのセットアップに失敗しました.スピーカーの設定が施されていない場合があります.>" << std::endl; exit(55); } atexit(end); glutInitWindowPosition(0, 0); glutInitWindowSize(WIDTH, HEIGHT); glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE); glutCreateWindow("goipachi ver.1.4.0"); glutDisplayFunc(display); glutReshapeFunc(resize); glutTimerFunc(16, timer, 0); glutKeyboardFunc(keyboard); glutKeyboardUpFunc(keyboardUp); glutIdleFunc(idle); Init(); glutMainLoop(); return 0; }
[ "sakoshin8mk2@outlook.jp" ]
sakoshin8mk2@outlook.jp
f74f9bd7baaa3b89ac99a96648ef9b2968263fa1
38c25f40ec9f1cce40e6e274daa9c0fa8d731244
/pcx/Utils.cpp
f3a052829b74c03ea6c607dec4c39c2d16542580
[]
no_license
seshbot/new-cpp-project
7f5601b422ad1d4dc2eef719703a425bedd51fdc
096bb664e0487890b822b547723b8dc8b4e4c4ed
refs/heads/master
2020-05-17T12:07:26.378614
2014-02-02T10:47:55
2014-02-02T10:47:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
950
cpp
#include <pcx/Utils.h> #include <boost/assert.hpp> #ifdef __GNUC__ #include <cxxabi.h> #endif namespace pcx { std::string demangle_name(std::string name) { #if defined(_MSC_VER) return name; #else std::string ret; int status = 0; char* demang = abi::__cxa_demangle(name.c_str(), NULL, 0, &status); if (status) return name; // TODO: why does this fail sometimes? BOOST_ASSERT_MSG(!status, name.c_str()); try { ret = demang; } catch (...) { free(demang); throw; } free(demang); return ret; #endif } } // namespace pcx namespace std { std::ostream & operator<<(std::ostream & stream, std::type_index const & t) { stream << pcx::demangle_name(t.name()); return stream; } }
[ "git@cechner.com" ]
git@cechner.com
e48ddb3af913d343045ee11568caa6262a1ab60e
6e46e7c538055e86285c65153cd6d4a863348229
/EvaluatorMother.h
c6874e914b67f9d575f78b65db6f358cb28f8fc6
[]
no_license
Cosimzhou/othello
91ff8c8dffe7e78e7fa278c7c2e25d9151094c61
03c61ba3d3049084dbfa6ebe56ef7adbc5de83f2
refs/heads/master
2021-01-09T20:38:32.360407
2016-07-14T14:59:47
2016-07-14T14:59:47
63,345,757
0
0
null
null
null
null
UTF-8
C++
false
false
733
h
// EvaluatorMother.h: interface for the CEvaluatorMother class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_EVALUATORMOTHER_H__ACF43AEF_2A93_4D73_896C_CA1CFD7883C3__INCLUDED_) #define AFX_EVALUATORMOTHER_H__ACF43AEF_2A93_4D73_896C_CA1CFD7883C3__INCLUDED_ #include "GameScript.h" #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CEvaluatorMother { public: CEvaluatorMother(); virtual ~CEvaluatorMother(); virtual int Evaluate(ChessType* curboard, ChessType col, int empties=-1, bool end=false)=0; protected: int FinalScore(ChessType* board, ChessType color) const; }; #endif // !defined(AFX_EVALUATORMOTHER_H__ACF43AEF_2A93_4D73_896C_CA1CFD7883C3__INCLUDED_)
[ "cosimzhou@hotmail.com" ]
cosimzhou@hotmail.com
8b7bcf120c1d73c84f8902655aa1b905f43adf23
976004c9f4426106d7ca59db25755d4d574b8025
/containers/vector/vector_operator_binary.h
ec660af5f5897350b8437562ffb25f4bcfdcb9b0
[]
no_license
peterzxli/cvpp
18a90c23baaaa07a32b2aafdb25d6ae78a1768c0
3b73cfce99dc4b5908cd6cb7898ce5ef1e336dce
refs/heads/master
2022-12-05T07:23:20.488638
2020-08-11T20:08:10
2020-08-11T20:08:10
286,062,971
1
0
null
null
null
null
UTF-8
C++
false
false
1,886
h
#include "../vector.h" namespace cvpp { // Vector + Element TPL_DTM inline Vector<D,T,M> operator+( const Vector<D,T,M> vec , const D& elm ) { return vec.clone() += elm; } // Vector - Element TPL_DTM inline Vector<D,T,M> operator-( const Vector<D,T,M> vec , const D& elm ) { return vec.clone() -= elm; } // Element + Vector TPL_DTM inline Vector<D,T,M> operator+( const D& elm , const Vector<D,T,M> vec ) { return vec.clone() += elm; } // Element - Vector TPL_DTM inline Vector<D,T,M> operator-( const D& elm , const Vector<D,T,M> vec ) { return vec.clone().mlt( -1.0 ) += elm; } // Vector * Value TPL_DTM inline Vector<D,T,M> operator*( const Vector<D,T,M> vec , const T& val ) { return vec.clone() *= val; } // Vector / Value TPL_DTM inline Vector<D,T,M> operator/( const Vector<D,T,M> vec , const T& val ) { return vec.clone() /= val; } // Value * Vector TPL_DTM inline Vector<D,T,M> operator*( const T& val , const Vector<D,T,M> vec ) { return vec.clone() *= val; } // Value / Vector TPL_DTM inline Vector<D,T,M> operator/( const T& val , const Vector<D,T,M> vec ) { Vector<D,T,M> tmp = vec.clone(); tmp.mat().Denominator(); return tmp *= val; } // Vector + Vector TPL_DTM inline Vector<D,T,M> operator+( const Vector<D,T,M>& vec1 , const Vector<D,T,M> vec2 ) { Vector<D,T,M> tmp = vec1.clone(); return tmp += vec2; } // Vector - Vector TPL_DTM inline Vector<D,T,M> operator-( const Vector<D,T,M>& vec1 , const Vector<D,T,M> vec2 ) { Vector<D,T,M> tmp = vec1.clone(); return tmp -= vec2; } // Vector % Vector TPL_DTM inline Vector<D,T,M> operator%( const Vector<D,T,M>& vec1 , const Vector<D,T,M> vec2 ) { Vector<D,T,M> tmp = vec1.clone(); return tmp %= vec2; } // Vector * Matrix TPL_DTM inline Vector<D,T,M> operator*( const Vector<D,T,M>& vec , const Matrix<T>& mat ) { return vec.clone() *= mat; } }
[ "peterli@MacBook-Pro.local" ]
peterli@MacBook-Pro.local
5bc10de8c8986ddf0efcd30aaeeb7a4540a70f0b
01372165bc486046fd1211a39ee57bdc7ccc3279
/dev/lsf/asio/curl_multi.hpp
f5eba26fc95f70d1e3882255300d441355d9477d
[]
no_license
leoxk/lsf
8f92c63604a3449a1bd95d1c9e1b264f7f32a0a2
864cbcac292247e2e602364e1b6134616b0859a6
refs/heads/master
2021-01-18T01:49:25.157791
2016-09-21T10:30:08
2016-09-21T10:30:08
24,362,480
1
1
null
null
null
null
UTF-8
C++
false
false
6,735
hpp
// File: curl_multi.hpp // Description: --- // Notes: --- // Author: leoxiang <leoxiang727@qq.com> // Revision: 2016-03-31 by leoxiang #pragma once #include "lsf/asio/curl.hpp" #include "lsf/asio/async.hpp" namespace lsf { namespace asio { //////////////////////////////////////////////////////////// // CurlMulti class CurlMulti : public lsf::basic::Singleton<CurlMulti>, public lsf::basic::Error { public: using finish_callback_type = std::function<void(SharedCurl)>; // add timer callback static void AddTimerCallback(CURLM* multi_handle, long timeout_milli, void* puser) { // just invoke timeout immediately if (timeout_milli <= 0) timeout_milli = 1; // add new timer int timer_fd = IOService::Instance()->AsyncAddTimerOnce(timeout_milli, [](int timer_fd) { // remove timer fd CurlMulti::Instance()->_timer_set.erase(timer_fd); // notify action int running_handles = 0; auto ret = curl_multi_socket_action(CurlMulti::Instance()->_handle, CURL_SOCKET_TIMEOUT, 0, &running_handles); if (ret != CURLM_OK) { LSF_LOG_ERR("socket action failed, fd=%u, %s", timer_fd, curl_multi_strerror(ret)); } // if all done, kill all timer if (running_handles <= 0) { for (auto timer_fd : CurlMulti::Instance()->_timer_set) { IOService::Instance()->AsyncCloseTimer(timer_fd); } CurlMulti::Instance()->_timer_set.clear(); } // check handle CheckMultiInfo(); }); // add to set if (timer_fd != -1) CurlMulti::Instance()->_timer_set.insert(timer_fd); } // handle socket callback static int HandleSocketCallback(CURL* easy_handle, curl_socket_t sock, int action, void* puser, void* psock) { // handle action switch (action) { case CURL_POLL_IN: case CURL_POLL_OUT: case CURL_POLL_INOUT: { // here use epoll ET mode for CPU optimise int flag = (action == CURL_POLL_IN ? IOService::FLAG_READ : IOService::FLAG_WRITE); IOService::Instance()->AsyncRawCallback(sock, flag, [](int sockfd, int flags) { // init curl flags int curl_flags = 0; if (flags & IOService::FLAG_READ) curl_flags |= CURL_CSELECT_IN; if (flags & IOService::FLAG_WRITE) curl_flags |= CURL_CSELECT_OUT; if (flags & IOService::FLAG_ERR) curl_flags |= CURL_CSELECT_ERR; // notify action int running_handles = 0; auto ret = curl_multi_socket_action(CurlMulti::Instance()->_handle, sockfd, curl_flags, &running_handles); if (ret != CURLM_OK) { LSF_LOG_ERR("socket action failed, fd=%u, %s", sockfd, curl_multi_strerror(ret)); } // if all done, kill all timer if (running_handles <= 0) { for (auto timer_fd : CurlMulti::Instance()->_timer_set) { IOService::Instance()->AsyncCloseTimer(timer_fd); } CurlMulti::Instance()->_timer_set.clear(); } // check handle CheckMultiInfo(); }); break; } case CURL_POLL_REMOVE: { IOService::Instance()->AsyncCancel(sock); break; } } return 0; } static void CheckMultiInfo() { // traverse all curl int pending; CURLMsg* pmsg = nullptr; while ((pmsg = curl_multi_info_read(CurlMulti::Instance()->_handle, &pending))) { switch (pmsg->msg){ case CURLMSG_DONE: { // release from multi curl_multi_remove_handle(CurlMulti::Instance()->_handle, pmsg->easy_handle); // get curl instance auto& curl_map = CurlMulti::Instance()->_curl_map; auto iter = curl_map.find(pmsg->easy_handle); if (iter == curl_map.end()) { LSF_LOG_ERR("cant get curl when process done, handle=%x", pmsg->easy_handle); continue; } // set result iter->second.first->_error = pmsg->data.result; // callback if (iter->second.second) iter->second.second(iter->second.first); // release obj curl_map.erase(iter); } break; default: break; } } } public: CurlMulti() {} ~CurlMulti() {if (*this) curl_multi_cleanup(_handle); } explicit operator bool() const { return _handle != nullptr; } bool Init() { // check already init if (_handle) return true; // init global handle if (curl_global_init(CURL_GLOBAL_ALL) != 0) { SetErrString(LSF_DEBUG_INFO); return false; } // init multi handle if ((_handle = curl_multi_init()) == nullptr) { SetErrString(LSF_DEBUG_INFO); return false; } // set callback curl_multi_setopt(_handle, CURLMOPT_SOCKETFUNCTION, HandleSocketCallback); curl_multi_setopt(_handle, CURLMOPT_TIMERFUNCTION, AddTimerCallback); return true; } template<typename HandlerType = std::nullptr_t> bool AddCurl(SharedCurl shared_curl, HandlerType&& handler = nullptr) { // check input if (!shared_curl) return false; // set string output shared_curl->SetOutputToString(); // add to map _curl_map[shared_curl->NativeHandle()] = std::make_pair(shared_curl, std::forward<HandlerType>(handler)); // add to handle curl_multi_add_handle(_handle, shared_curl->NativeHandle()); return true; } void RemoveCurl(SharedCurl shared_curl) { _curl_map.erase(shared_curl->NativeHandle()); } std::set<int> const& TimerSet() const { return _timer_set; } std::map<CURL*,std::pair<SharedCurl,finish_callback_type>> const& CurlMap() const { return _curl_map; } private: CURLM* _handle = nullptr; std::set<int> _timer_set; std::map<CURL*,std::pair<SharedCurl,finish_callback_type>> _curl_map; }; } // end namespace asio } // end namespace lsf // vim:ts=4:sw=4:et:ft=cpp:
[ "leoxiang727@qq.com" ]
leoxiang727@qq.com
913c655cb1ec1b0f1f71e3e8affc330d172d4ab5
a5b43123d91d23581ae1f1cc725d7b004a4caa25
/cpp/File/polymorphism.cpp
a5b86ef95b317c6582c4e547590f0e35f751b9f5
[]
no_license
ivan570/code
376001416a01f0a870a0d73796f1a61dd3bfe958
e5a8e9bf7c9ea27b070ca3f351bb54cb16ce0317
refs/heads/main
2023-05-23T04:48:30.477060
2021-06-11T15:50:30
2021-06-11T15:50:30
330,686,610
0
1
null
null
null
null
UTF-8
C++
false
false
714
cpp
#include <iostream> using namespace std; class Base { public: void show() { cout << "Base class show" << endl; } }; class Derive : public Base { public: // it's also polymorphism // it's function overriding int show() { cout << "Derive class show" << endl; return 23; } }; void function(int first, int second) { cout << "x is " << first << " y is " << second << endl; } void function(int first, int second, int third) { cout << "first is " << first << " second " << second << " third " << third << endl; } int main() { Derive derive; derive.show(); // function overloading function(90, 99); function(89, 90); return 0; }
[ "ivankshu@gmail.com" ]
ivankshu@gmail.com
eb4610f4b76fa0acd49d10099d78ab1e68c5f989
6ec33f877c3e1d84da44ea1b347209284f6c6d5c
/src/minhash.hpp
9b2db3ec64f134c29f6ed18ef9d82987148ed254
[]
no_license
zhaobomath/minhash-lsh
dccf476624e03d9eaff53c19bf0d102f3c44044b
f5a82ea333ec43a43754bd4048822bf2d4d8b14e
refs/heads/master
2023-04-27T17:20:30.322034
2019-01-08T03:25:00
2019-01-08T03:25:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
552
hpp
#ifndef MINHASH_HPP #define MINHASH_HPP #include <vector> #include <map> #include <fstream> #include <iostream> #include "clhash.h" using namespace std; class minhasher{ private: int hash_num = 256; // bxr = 16x16 int shingle_num = 9; vector<void*> randoms; public: minhasher(); ~minhasher(); vector<uint64_t> signature(ifstream *inFile); float compute_similarity(ifstream *f1, ifstream *f2); // bool load(const char *path); // bool save(const char *path); }; #endif
[ "zhanzy5@mail2.sysu.edu.cn" ]
zhanzy5@mail2.sysu.edu.cn
06d2d5f1652d8bba350d97fb061b3e791cfa168d
77a05803f0527c22fa4b7effeafb05711111e264
/yash.hpp
5e0b49d7704491154c0f066658346d6217f4a686
[]
no_license
afett/yash
9843f7b32a57404eaa284010d8164629882436eb
50380296a8628377e8b5482f097c12bd9f553577
refs/heads/master
2021-01-10T19:47:49.695424
2019-04-15T20:36:54
2019-04-15T20:36:54
19,382,329
1
0
null
null
null
null
UTF-8
C++
false
false
5,881
hpp
/* * Copyright (c) 2014, 2015, 2017 Andreas Fett. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR * 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 YASH_HPP #define YASH_HPP #include <cassert> #include <functional> #include <algorithm> #include <memory> #include <vector> // yet another signal library^W header namespace yash { class callback_base { public: using weak_ptr = std::weak_ptr<callback_base>; virtual void disconnect() = 0; virtual ~callback_base() = default; }; // handle for single slot connected to a signal class connection { public: connection() = default; ~connection() { cb_.reset(); } connection(callback_base::weak_ptr const& cb) : cb_(cb) { } // The connections share the actual callback closure if disconnect // is called on one of them, all are disconnected. connection(connection const& o) : cb_(o.cb_) { } connection(connection && o) : cb_(o.cb_) { o.cb_.reset(); } // Assignment to a connected connection will not disconnect it but // leave the callback connected to the signal. There is just no // external reference to it anymore. connection & operator=(connection const& o) { if (&o != this) { cb_ = o.cb_; } return *this; } connection & operator=(connection && o) { if (&o != this) { cb_ = o.cb_; o.cb_.reset(); } return *this; } bool connected() const { return !cb_.expired(); } void disconnect() { auto cb(cb_.lock()); if (cb) { cb->disconnect(); cb_.reset(); } } private: callback_base::weak_ptr cb_; }; // RAII wrapper for connection class auto_connection { public: auto_connection() = delete; auto_connection(auto_connection const&) = delete; auto_connection & operator=(auto_connection const&) = delete; auto_connection(connection const& conn) : conn_(conn) { } auto_connection(auto_connection && o) : conn_(std::move(o.conn_)) { } auto_connection & operator=(auto_connection && o) { conn_ = std::move(o.conn_); return *this; } void disconnect() { conn_.disconnect(); } bool connected() const { return conn_.connected(); } ~auto_connection() { conn_.disconnect(); } private: connection conn_; }; // Interface to expose a signal for a user without allowing to invoke it template <typename T> class signal_proxy { public: using slot_type = std::function<T>; virtual connection connect(slot_type const&) = 0; virtual ~signal_proxy() = default; }; template <typename T> class signal : public signal_proxy<T> { public: using proxy_type = signal_proxy<T>; using slot_type = typename signal_proxy<T>::slot_type; signal() = default; signal(signal && o) : cb_(std::move(o.cb_)) { } signal & operator=(signal && o) { cb_ = std::move(o.cb_); return *this; } // Rationale // The semantics of copying and assigning a signal are somewhat undefined. signal(signal const&) = delete; signal & operator=(signal const&) = delete; size_t slots() const { return cb_.size(); } // The callback will not be called for any already active invokation // of this signal at the time connect() is called. connection connect(slot_type const& slot) final { return connection(add_callback(slot)); } template <typename... Args> void operator()(Args&&... args) { if (cb_.empty()) { return; } call_each({cb_.begin(), cb_.end()}, std::forward<Args>(args)...); } template <typename... Args> void operator()(Args&&... args) const { if (cb_.empty()) { return; } call_each({cb_.begin(), cb_.end()}, std::forward<Args>(args)...); } private: struct callback : public callback_base { callback(signal<T> *owner_, slot_type const& fn_) : owner(owner_), fn(fn_) { assert(owner && "no callback owner"); assert(fn && "no callback function"); } void disconnect() final { if (owner) { owner->del_callback(this); owner = nullptr; fn = nullptr; } } signal<T> *owner; slot_type fn; }; using callback_ptr = std::shared_ptr<callback>; using callback_weak_ptr = std::weak_ptr<callback>; callback_ptr add_callback(slot_type const& slot) { cb_.push_back(std::make_shared<callback>(this, slot)); return cb_.back(); } void del_callback(callback * cb) { assert(cb && "trying to remove null callback"); auto it(std::find_if(cb_.begin(), cb_.end(), [cb](callback_ptr const& ptr){ return ptr.get() == cb; })); assert(it != cb_.end() && "trying to remove invalid callback"); it->reset(); cb_.erase(it); } template <typename... Args> static void call_each(std::vector<callback_weak_ptr> cbs, Args&&... args) { for (auto ptr: cbs) { auto cb(ptr.lock()); if (cb) { cb->fn(std::forward<Args>(args)...); } } } std::vector<callback_ptr> cb_; }; } #endif
[ "a.fett@gmx.de" ]
a.fett@gmx.de
49769c68765fbbda598400bfbe36c17a5ec6f364
603ad7bb3df5a02d222acefec08ce4f94d75409b
/atcoder/abc202c.cpp
6357f4fbcaa50e988cae2c5b7fc1ca494b2dd4d1
[]
no_license
MijaelTola/icpc
6fc43aa49f97cf951a2b2fcbd0becd8c895abf36
ee2629ba087fbe7303743c84b509959f8d3fc9a0
refs/heads/master
2023-07-09T00:47:42.812242
2021-08-08T00:44:10
2021-08-08T00:44:10
291,160,127
0
0
null
null
null
null
UTF-8
C++
false
false
661
cpp
#include <bits/stdc++.h> using namespace std; vector<int> c[100010]; int main() { int n; cin >> n; map<int, vector<int> > mp; vector<int> a,b; for (int i = 0; i < n; ++i) { int x; cin >> x; x--; a.push_back(x); } for (int i = 0; i < n; ++i) { int x; cin >> x; x--; b.push_back(x); } for (int i = 0; i < n; ++i) { int x; cin >> x; x--; c[b[x]].push_back(i); } long long ans = 0; for (int i = 0; i < n; ++i) { int x = a[i]; ans += c[x].size(); } cout << ans << "\n"; return 0; }
[ "mija.tola.ap@gmail.com" ]
mija.tola.ap@gmail.com
40093d41bac5f0028e45f0fbc38823208f465bb5
8b6cdb025cd575136abe911debd4414d10f4d59d
/AGame/MainMenu.cpp
d07e129ef3d782c3236edab23943a249d8bbe6ca
[]
no_license
Julianobsg/AGameEngine
38fedd81184e005ca5d47ec2c6d6391bce5e86d6
6d9469ffb0cfa98f8f1122c2f7bae3dbb4141b58
refs/heads/master
2020-12-24T15:22:38.631591
2016-02-18T22:33:20
2016-02-18T22:33:20
19,335,581
3
0
null
null
null
null
UTF-8
C++
false
false
822
cpp
#include "stdafx.h" #include "MainMenu.h" #include "ButtonBehaviour.h" #include "Application.h" #include <functional> MainMenu::MainMenu() { header = new Text("CaviarDreams.ttf"); header->SetContent("Tomato attack"); header->transform->position = Vector2D<float>(4, 2); playButton = new UIButton("Play", Vector2D<float>(5, 7)); playButton->SetConclick(std::bind(&MainMenu::LoadLevel, this)); quitButton = new UIButton("Quit", Vector2D<float>(5, 7.5));; quitButton->SetConclick(std::bind(&MainMenu::QuitGame, this)); } MainMenu::~MainMenu() { } void MainMenu::LoadLevel() { Application::LoadScene(1); } void MainMenu::QuitGame() { Application::CloseGame(); } void MainMenu::Init() { this->AddGameObject(header); this->AddGameObject(playButton->Button()); this->AddGameObject(quitButton->Button()); }
[ "julianobsg@gmail.com" ]
julianobsg@gmail.com
b74e295e2baebea41e1450497bb1357da25571a4
d3d1af801b7822a456eda4d2586a47207dcadd40
/test/my_string.h
ba6b8b68ed40546ed78f12c80d84edb83f7aa4ca
[]
no_license
HumbleHunger/Cpp
df7a38dd33734c86e3d2c956e033e88c74390244
7d7527f5b34f626eac342910f1ea23ed4bf75639
refs/heads/master
2023-03-23T08:42:11.166175
2021-03-17T12:43:00
2021-03-17T12:43:00
293,516,688
1
0
null
null
null
null
UTF-8
C++
false
false
896
h
/************************************************************************* > File Name: my_string.h > Author: > Mail: > Created Time: 2020年11月04日 星期三 15时46分49秒 ************************************************************************/ #ifndef _MY_STRING_H #define _MY_STRING_H #include<memory> #include<cstring> #include<new> using namespace std; class String { public: String():elements(nullptr),end(nullptr){} String(const char *s){ auto newdata=alloc.allocate(strlen(s)); auto iter=newdata; for(int i=0;i<strlen(s);++i){ alloc.construct(iter++,s[i]); } elements=newdata; end=iter; } String(const String &s){ } size_t size() const {return end-elements;} String& operator=(const String& s); private: allocator<char> alloc; char *elements; char *end; }; #endif
[ "2495970924@qq.com" ]
2495970924@qq.com
2856ae02e36329c90793f709cb86e798c23a8808
78300621bc7b7858d1890cbd8c4186ac490cdf47
/src/modules/thread/wrap_ThreadModule.h
1c0cffaf132045d3d3f71f21017dfe0fce351eb7
[ "Zlib", "BSL-1.0", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
LavenderTheGreat/six
e859f5bdc2d3dbc7a6be0c1a7524fc72340edf29
0922ce212e129a5404bf116b64bc2f6f076c53cb
refs/heads/master
2021-01-03T07:24:02.542275
2017-02-28T23:27:07
2017-02-28T23:27:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,235
h
/** * Copyright (c) 2006-2017 LOVE Development Team * * 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 LOVE_THREAD_WRAP_THREADMODULE_H #define LOVE_THREAD_WRAP_THREADMODULE_H // LOVE #include "common/config.h" #include "common/runtime.h" namespace love { namespace thread { extern "C" LOVE_EXPORT int luaopen_love_thread(lua_State * L); } // thread } // love #endif // LOVE_THREAD_WRAP_THREADMODULE_H
[ "shakesoda@gmail.com" ]
shakesoda@gmail.com
d32b41dd5460c7081b1ef6461a1de231a19ba653
22bd625b1a2ffc102761914469c9673f62cf8e78
/benchmarks/src/cuda/dragon_li/dragon_li/util/userConfig.h
acd6434e7c1becaf56eaf93e45e71bcf5a9d7a33
[ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
purdue-aalp/gpgpu-sim_simulations
f1c32ac5a88c4120d326d1053c82e598ca2d05fe
84113a92a4aacfdd1ddbc1beb2f01746060dfb05
refs/heads/master
2021-08-05T21:56:58.378115
2021-01-28T23:31:26
2021-01-28T23:31:26
154,350,995
6
15
BSD-2-Clause
2021-05-18T15:28:08
2018-10-23T15:18:42
HTML
UTF-8
C++
false
false
233
h
#pragma once namespace dragon_li { namespace util { class UserConfig { public: bool verbose; bool veryVerbose; UserConfig( bool _verbose, bool _veryVerbose) : verbose(_verbose), veryVerbose(_veryVerbose) {} }; } }
[ "k.mkhairy@yahoo.com" ]
k.mkhairy@yahoo.com
6c1f69bf188f15a473d21330a0bf0d9daeed1958
6de7f1f0d9be7d0659902dc60c77dcaf332e927e
/src/libtsduck/dtv/descriptors/tsTargetMACAddressDescriptor.h
83e6cf6403b83cc3665ff05427da2a23994e8916
[ "BSD-2-Clause" ]
permissive
ConnectionMaster/tsduck
ed41cd625c894dca96f9b64f7e18cc265ef7f394
32732db5fed5f663dfe68ffb6213a469addc9342
refs/heads/master
2023-08-31T20:01:00.538543
2022-09-30T05:25:02
2022-09-30T08:14:43
183,097,216
1
0
BSD-2-Clause
2023-04-03T23:24:45
2019-04-23T21:15:45
C++
UTF-8
C++
false
false
3,407
h
//---------------------------------------------------------------------------- // // TSDuck - The MPEG Transport Stream Toolkit // Copyright (c) 2005-2022, Thierry Lelegard // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // //---------------------------------------------------------------------------- //! //! @file //! Representation of a target_MAC_address_descriptor (INT/UNT specific). //! //---------------------------------------------------------------------------- #pragma once #include "tsAbstractDescriptor.h" #include "tsMACAddress.h" namespace ts { //! //! Representation of a target_MAC_address_descriptor (INT/UNT specific). //! //! This descriptor cannot be present in other tables than an INT or UNT //! because its tag reuses an MPEG-defined one. //! //! @see ETSI EN 301 192, 8.4.5.6 //! @see ETSI TS 102 006, 6.5.2.2 //! @ingroup descriptor //! class TSDUCKDLL TargetMACAddressDescriptor : public AbstractDescriptor { public: // TargetMACAddressDescriptor public members: MACAddress MAC_addr_mask; //!< MAC address mask MACAddressVector MAC_addr; //!< MAC addresses //! //! Maximum number of entries to fit in 255 bytes. //! static const size_t MAX_ENTRIES = 41; //! //! Default constructor. //! TargetMACAddressDescriptor(); //! //! Constructor from a binary descriptor. //! @param [in,out] duck TSDuck execution context. //! @param [in] bin A binary descriptor to deserialize. //! TargetMACAddressDescriptor(DuckContext& duck, const Descriptor& bin); // Inherited methods DeclareDisplayDescriptor(); protected: // Inherited methods virtual void clearContent() override; virtual void serializePayload(PSIBuffer&) const override; virtual void deserializePayload(PSIBuffer&) override; virtual void buildXML(DuckContext&, xml::Element*) const override; virtual bool analyzeXML(DuckContext&, const xml::Element*) override; }; }
[ "thierry@lelegard.fr" ]
thierry@lelegard.fr
291e0a17f2e80450b180ce77202110900b8e3a7d
052de931412cf8f7bd86bc79d34522ef113b6267
/tracker.h
726aec945d6bf46cf22f1101da65c091f5e6ee40
[ "MIT" ]
permissive
my-official/QtBT
46022288da90b26ea30124a03da95fcf44e0d716
0c78119b373bfc549a3262cb66794764a1416205
refs/heads/master
2021-05-03T05:37:50.074184
2018-04-06T15:57:18
2018-04-06T15:57:18
120,641,398
2
0
null
null
null
null
UTF-8
C++
false
false
1,664
h
#ifndef TRACKER_H #define TRACKER_H #include <QObject> #include <QUrl> #include <QHostAddress> #include <QSharedPointer> #include <QNetworkAccessManager> #include <QNetworkRequest> #include <QNetworkReply> #include <QTimer> //#include <QAuthenticator> namespace torrent { class Server; class Torrent; class PeerInfo; class Tracker : public QObject { Q_OBJECT public: enum class State { TS_NULL, TS_WAITING, TS_SENT, TS_RECVED }; State GetState(); QString GetTrackerId() const; QString GetTrackerMessage() const; //bool operator == (const Tracker& rhs) const; void Start(); void Stop(); Tracker(Server* server, Torrent* torrent, const QUrl& url); signals: void NewPeerInfo(const QSharedPointer<PeerInfo>& peerInfo); protected: friend class Torrent; QList< QSharedPointer<PeerInfo> > m_PeerList; enum class RequestEventType { Regular = 0, Start = 1, Stop = 2, Complete = 3, }; void Request(RequestEventType eventType = RequestEventType::Regular); void Response(); private: State m_State; Torrent* m_Torrent; Server* m_Server; QUrl m_Url; QNetworkRequest m_Request; QNetworkReply* m_Reply; QSharedPointer<QNetworkAccessManager> m_NetworkAccessManager; int m_Interval; QTimer m_RemainingTime; QString m_TrackerId; QString m_TrackerMessage; bool m_LastResult; QString MakeRequestUrl(RequestEventType eventType); bool AddPeerInfoUnique(const QHostAddress& address, quint16 port, const QString& peerId = ""); private slots: void OnTimeout(); void OnFinished(); }; } #endif
[ "my_official@outlook.com" ]
my_official@outlook.com
81c8b8c990d0f7250ce06c4a9301016efec1a765
9a79e230bf9a411aa14989d01c7d3b16ec06dbe0
/src/crypto/sha1.h
b5c9576a10604860cb8591ab426c792bfba79fd2
[ "MIT" ]
permissive
fcecin/infinitum
02ff75e86ed1e80922970a33c5167c64ede49b74
ebead4bc77a95bf7d19cda5e88013a72f2fd5a9c
refs/heads/master
2021-01-22T17:28:47.795413
2016-10-15T15:56:12
2016-10-15T15:56:12
69,108,854
1
0
null
null
null
null
UTF-8
C++
false
false
649
h
// Copyright (c) 2014 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef INFINITUM_CRYPTO_SHA1_H #define INFINITUM_CRYPTO_SHA1_H #include <stdint.h> #include <stdlib.h> /** A hasher class for SHA1. */ class CSHA1 { private: uint32_t s[5]; unsigned char buf[64]; uint64_t bytes; public: static const size_t OUTPUT_SIZE = 20; CSHA1(); CSHA1& Write(const unsigned char* data, size_t len); void Finalize(unsigned char hash[OUTPUT_SIZE]); CSHA1& Reset(); }; #endif // INFINITUM_CRYPTO_SHA1_H
[ "fcecin@gmail.com" ]
fcecin@gmail.com
3d132c4b3b912fd817fd657e109453aa1129175e
1fdbb7e551cf8b52b43359cf406bedd969b5f59f
/source/common/redundancy/rmservice/rmserviceut/ShareMemHelperTester.h
f4e1b59d96bd75dd1f7e10dd10e981a26993c351
[]
no_license
trigrass2/eview-server
1292958416ebe772ff4ce0b1f1639c65ca13ce92
a5e452016a730af79a1d402a3d918403eb6073aa
refs/heads/master
2023-06-17T09:38:25.004889
2021-07-15T09:45:56
2021-07-15T09:45:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
632
h
#include <cppunit/extensions/HelperMacros.h> #include "../ShareMemHelper.h" class ShareMemHelperTester : public CPPUNIT_NS::TestFixture { CPPUNIT_TEST_SUITE( ShareMemHelperTester ); CPPUNIT_TEST(testGetAndSetObjRMStatus); CPPUNIT_TEST(testGetAndSetObjRMStatusCtrl); CPPUNIT_TEST(testSetAndGetObjStatus); CPPUNIT_TEST(testNeedSync); CPPUNIT_TEST(testNeedDoSvc); CPPUNIT_TEST_SUITE_END(); public: void testGetAndSetObjRMStatus(); void testGetAndSetObjRMStatusCtrl(); void testSetAndGetObjStatus(); void testNeedSync(); void testNeedDoSvc(); void setUp(); void tearDown(); private: CShareMemHelper *pMemHelper; };
[ "746257224@qq.com" ]
746257224@qq.com
9995c29d646f9a1e753d0b7b66f9267fbd608383
90a9cba29f9f0bf67bd6650c3c5db7630ee8167e
/test-core/-perf/deform_profile/main_test_deform_profile.cpp
57958be2e99f0e7d67e45f91881773ff2a9a4951
[]
no_license
lkolt/corecvs
ffd7ead75e924ab207e376526839edafd384917e
cabae053e5c72d4af132ddac8180fdf4ce565391
refs/heads/master
2021-05-14T10:35:55.605237
2018-01-05T10:35:33
2018-01-05T10:35:33
116,359,316
0
0
null
2018-01-05T08:05:54
2018-01-05T08:05:54
null
UTF-8
C++
false
false
1,116
cpp
/** * \file main_test_deform.cpp * \brief This is the main file for the test deform * * \date Mar 01, 2012 * \author alexander * * \ingroup autotest */ #include <iostream> #include "gtest/gtest.h" #include "core/utils/global.h" #include "core/buffers/fixeddisp/fixedPointDisplace.h" #include "core/math/matrix/matrix33.h" #include "core/math/projectiveTransform.h" #include "core/buffers/g12Buffer.h" #include "core/buffers/bufferFactory.h" #include "core/fileformats/bmpLoader.h" #include "core/buffers/rgb24/rgb24Buffer.h" #include "core/alignment/radialCorrection.h" #include "core/buffers/displacementBuffer.h" using corecvs::Matrix33; using corecvs::ProjectiveTransform; using corecvs::G12Buffer; using corecvs::BufferFactory; using corecvs::FixedPointDisplace; using corecvs::BMPLoader; using corecvs::RGB24Buffer; void testRadialApplication(int scale); void testRadialInversion(int scale); TEST(Deform, profileRadialApplication) // TODO: move to perf-tests! { testRadialApplication(10); } TEST(Deform, profileRadialInversion) // TODO: move to perf-tests! { testRadialInversion(10); }
[ "Aleksandr.Pimenov@lanit-tercom.com" ]
Aleksandr.Pimenov@lanit-tercom.com
22095b213216db945a5b96b28655070b12fbe2e1
01e056cb6af213a68252d60dd75e5c137e2845d4
/factory/libpainter/CRegularPolygon.h
2033d8e485a4125c28b0ac1d6e9dec9f5ede2dae
[]
no_license
fedjakova-anastasija/OOD
fa8b4ceca889f6b734062cffcb7eae4d948715e5
3324bae1b3be526f9ee30dd7b24fb12585a0b435
refs/heads/master
2020-04-21T06:14:10.815516
2019-06-03T07:57:57
2019-06-03T07:57:57
169,360,723
0
1
null
null
null
null
UTF-8
C++
false
false
490
h
#pragma once #include "CShape.h" #include "ICanvas.h" #include "CPoint.h" class CRegularPolygon : public CShape { public: CRegularPolygon(const CPoint& center, double radius, unsigned vertexCount, const Color& color); ~CRegularPolygon() = default; void Draw(ICanvas& canvas) const override; unsigned GetVertexCount() const; CPoint GetCenter() const; double GetRadius() const; private: unsigned m_vertexCount; CPoint m_center; double m_radius; std::vector<CPoint> m_vertices; };
[ "fedyakova.anastasia@gmail.com" ]
fedyakova.anastasia@gmail.com
ffacfc45e002f8f6c83cce4a8337dab0f612efd1
8f8b5e1273db8f8af790a14cfb6c0a35dfbd7c01
/codeforces/1520/F1.cpp
c69d32e49e5b2216b71734087f661f68925b23e4
[]
no_license
nathan-drake17/competitive_programming
ae2b343567f0e4fdff8b8263e869634fc2520775
09f89ff0dec0c8da135f2afbbf10d34f3f9f9a15
refs/heads/main
2023-05-31T04:59:53.091189
2021-06-14T12:53:41
2021-06-14T12:53:41
376,816,133
0
0
null
2021-06-14T12:31:45
2021-06-14T12:31:44
null
UTF-8
C++
false
false
2,178
cpp
#include <algorithm> #include <cmath> #include <cstring> #include <iostream> #include <limits> #include <queue> #include <set> #include <sstream> #include <stack> #include <unordered_map> #include <utility> #include <vector> using namespace std; typedef long long ll; typedef vector<int> vi; typedef vector<int>::iterator vit; typedef vector<vector<int>> vii; typedef pair<int, int> pii; #define REP(i, a, b) for (int i = a; i < b; i++) #define VECITR(itr, v) for (vit itr = v.begin(); itr != v.end(); itr++) #define PB push_back #define MP make_pair #define F first #define S second #define sq(a) ((a) * (a)) int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } string next_valid_bracket_sequence(const string &x) { string s = x; int n = s.size(); int d = 0; for (int i = n - 1; i >= 1; i--) { if (s[i] == ')') d++; else { d--; if (d > 0) { s[i] = ')'; s = s.substr(0, i + 1); REP(j, 0, (n - i - d) / 2) { s += "("; } REP(j, 0, (n - i + d - 2) / 2) { s += ")"; } if (s.size() < n) return s + ")"; return s; } } } return ""; } ll modulo(ll x, ll m) { int r = x % m; return r < 0 ? r + m : r; } int dfs(vector<vector<bool>> &change, vector<string> &arr, int i, int j, int k) { return 0; } void run() { int n, t, k; cin >> n >> t >> k; int lo = 1, hi = n; while (lo < hi) { // cout << "lo: " << lo << " hi: " << hi << endl; cout << "? " << lo << " " << (hi + lo) / 2 << endl; cout.flush(); int x; cin >> x; x = ((hi + lo) / 2) - lo + 1 - x; if (x < k) { lo = ((hi + lo) / 2) + 1; k -= x; } else { hi = ((hi + lo) / 2); } } // cout << "lo: " << lo << " hi: " << hi << endl; cout << "! " << lo << endl; cout.flush(); } int main() { cin.tie(NULL); ios_base::sync_with_stdio(false); int t = 1; // cin >> t; REP(i, 0, t) { run(); } }
[ "ojus.singhal17@gmail.com" ]
ojus.singhal17@gmail.com
67123ed8fbe79fd6c06c899a432fa73280e2a4f4
7afb9762709a74dae506fc4ef3d1d4ef86ff3d7e
/ch1_firstCase/ch1_switch/main.cpp
0d0930fa1ab0a8e3a752289bc217e105bff4af1b
[]
no_license
chentuo14/BookRebuild
2dee033f58f2c7be7d1f76aa1a61a19827e773be
0286a4c57890ae55b47b0b7876a656329a29d588
refs/heads/master
2020-04-26T17:19:51.851196
2019-03-08T02:11:46
2019-03-08T02:11:46
173,709,235
0
0
null
null
null
null
UTF-8
C++
false
false
2,008
cpp
#include <iostream> #include <string> #include <vector> #include "movie.h" #include "rental.h" #include "customer.h" using namespace std; int main() { /* create 10 movies */ std::vector<Movie> movies; for(int i=0;i<10;i++) { Movie tempMovie("Movie"+std::to_string(i+1), (i+1)%3); movies.push_back(tempMovie); } /* create 5 customers */ std::vector<Customer> customers; for(int i=0;i<5;i++) { Customer tempCustomers("customer" + std::to_string(i+1)); for(int j=2*i;j<2*i+2;++j) { Movie tempMovie = movies[j]; Rental tempRent(tempMovie, i+1); tempCustomers.addRental(tempRent); } customers.push_back(tempCustomers); } //print out all movies information; const std::vector<Movie>::size_type numMovies = movies.size(); for(unsigned int i=0;i<numMovies;++i) { Movie tempMovie = movies[i]; std::cout << " the Tile of the "<<i+1 << "(" << tempMovie.getTitle() << "," << tempMovie.getPriceCode() << ")" << std::endl; } std::cout << std::endl; //print out all customers information const std::vector<Customer>::size_type numCustomers = customers.size(); for(unsigned int i=0;i<numCustomers;++i) { Customer tempCust = customers[i]; std::cout << "the " << std::to_string(i+1) << " the customer " << tempCust.getName() << " has rented these movies:" << std::endl; const std::vector<Rental>::size_type numRentals = tempCust.getRentals().size(); for(unsigned int j=0;j<numRentals;++j) { std::cout << " (" << tempCust.getRentals()[j].getMovie().getTitle() << ", " << tempCust.getRentals()[j].getDaysRented() << ")" << std::endl; } } std::cout << std::endl; auto iter = customers.begin(); for(;iter != customers.end(); ++ iter) { std::cout << iter->statement() << std::endl;; } return 0; }
[ "ch122633@126.com" ]
ch122633@126.com
96a4e740311e7e9503f199d98c03e59965f6913c
123cf35ddf76c3c25d953a2c512f63a55bb04757
/src/data/UniversalString.cpp
cf3b96f6ac80b1428063acd46a565b640f136e79
[ "MIT" ]
permissive
JiaoMX-keeping/rsp3-armv8-baremetal
c0457dd6fc06dc668b0fe8f5e722be0f55639e39
f7e2ac04abd3be20daa94ad9c7ad2c1bad5159b0
refs/heads/master
2022-01-19T20:25:25.367222
2018-05-20T03:22:19
2018-05-20T03:22:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
491
cpp
/* * UniversalStrings.cpp * * Created on: Apr 11, 2018 * Author: 13774 */ #include <data/UniversalString.h> #include <data/StringRef.h> #undef _ARG_DO_GENERATE #define _ARG_DO_GENERATE #undef _ARG_GEN_DEFINITIONS #define _ARG_GEN_DEFINITIONS #undef _ARG_GEN_DECL //#define _ARG_GEN_DECL #undef _ARG_NAME #define _ARG_NAME UniversalString #undef _ARG_GLOBAL //#define _ARG_GLOBAL #undef _ARG_BASE_TYPE #define _ARG_BASE_TYPE UniversalVector #include <data/GenerateString.h>
[ "xhd2015@gmail.com" ]
xhd2015@gmail.com
692aaee9059641dc5970da6a8fc8f5a17b3418b5
ea0e85ad9a3e149397516ee405d81ed8573a63cc
/ServerManager/jni/servermanager/command/defaults/TeleportCommand.h
dc44a44c76ff3b58886b414cf410c576ccf0017b
[]
no_license
TrinityDevelopers/MCPE-addons
c1b37f96355d4ebf629555453be0a2fdc74fbfa0
0b4739640a245bb2e7c0a5a8a3779b2db5c58288
refs/heads/master
2020-12-03T09:21:10.732089
2016-01-04T00:11:17
2016-01-04T00:11:17
48,916,775
0
1
null
2016-01-04T00:11:17
2016-01-02T16:55:10
C++
UTF-8
C++
false
false
247
h
#pragma once #include "../Command.h" class TeleportCommand : public Command { public: TeleportCommand(std::string const &name); virtual bool execute(SMPlayer *sender, std::string const &commandLabel, std::vector<std::string> const &args); };
[ "ksy4362@naver.com" ]
ksy4362@naver.com
ad2b6971be0d143e10799814b0a43fb99c467a75
b475fb4a090928ffb3b6ae9eec73f3cc90483053
/DLL_G3/TestForMyFunctions/unittest1.cpp
06ec53f8d3bb41a4f7ab008483feee8e09b1e981
[]
no_license
ivonneleonor/Calculator-C-
55a330bfced43599ef361d76ff45866913abd4f7
27094f56aae5a32a486dfbeba7ba51391832ad92
refs/heads/master
2021-07-05T12:28:54.077618
2017-09-29T22:32:35
2017-09-29T22:32:35
105,230,344
0
0
null
null
null
null
UTF-8
C++
false
false
1,797
cpp
#include "stdafx.h" #include "CppUnitTest.h" #include "..\DLL_G3\DLL_G3.h" using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace TestForMyFunctions { TEST_CLASS(UnitTest1) { MyFunctions functions; public: TEST_METHOD(Sum_7plu8_15) { Assert::AreEqual(15.0, functions.sum(7, 8), 0.0001); } TEST_METHOD(Substraction_15minus8_7) { Assert::AreEqual(5, functions.subtraction(15, 10), 0.0001); } TEST_METHOD(Multiplication_7times3_21) { Assert::AreEqual(21, functions.multiplication(7, 3), 0.0001); } TEST_METHOD(division_100dividedby10_10) { Assert::AreEqual(10, functions.division(100, 10), 0.0001); } TEST_METHOD(division_by_0_Exception) { bool exceptionCaught = false; try { functions.division(10, 0); } catch (std::invalid_argument& exception) { exceptionCaught = true; } Assert::IsTrue(exceptionCaught); } TEST_METHOD(sqrt_of_100_10) { Assert::AreEqual(3.5, functions.squareroot(12.25), 0.00001); } TEST_METHOD(sqrt_of_a_negative) { Assert::AreEqual(-1, functions.squareroot(-1), 0.00001); } TEST_METHOD(binary_of_49_is_100011) { //Assert::AreEqual("100011", functions.binarynumber(49), 0); } TEST_METHOD(factorial_of_5_is_120) { Assert::AreEqual(120, functions.calcFactorial(5), 0.000001); } TEST_METHOD(factorial1_of_0_is_1) { Assert::AreEqual(1, functions.calcFactorial(0), 0.000001); } TEST_METHOD(factorial2_of_1_is_1) { Assert::AreEqual(1, functions.calcFactorial(1), 0.000001); } TEST_METHOD(factorial3_of_negnum_is_error) { Assert::AreEqual(0, functions.calcFactorial(-5), 0.000001); } TEST_METHOD(factorial4_of_floatnum_is_error) { Assert::AreEqual(0, functions.calcFactorial(5.5), 0.000001); } }; }
[ "ivonneleonor@yahoo.com.mx" ]
ivonneleonor@yahoo.com.mx
88cc260c11f8dd3846312a7b31fd5d3bc5c81de3
bad9540214867925ca99fcfe51a8b7bfae17f2c1
/test/SceneChanger.cpp
9844a48d6798b6c5611afc01bf2ddc94bf89cc12
[]
no_license
8bit-TD/DxLib_Action
522d448e7477c261beb0a9007ad3e9f649a87b2c
6b8ff835b4fa9a4f0f8a8330d00f66747ccece0c
refs/heads/master
2020-03-26T15:43:38.276321
2018-08-17T02:25:12
2018-08-17T02:25:12
145,060,991
0
0
null
null
null
null
UTF-8
C++
false
false
59
cpp
#include "SceneChanger.h" SceneChanger::~SceneChanger(){}
[ "8bittd@gmail.com" ]
8bittd@gmail.com
1b8771425653d5688bf4ebace21d2eb419da9d64
24e8398aac1aeb5b825a675670faea9bb186c855
/CreditScene.h
08c2cfb12a5ae30f774b5f05c894201e5e9402ac
[]
no_license
arkaik/terraria_vj
7522f405e1d7fc8c78a09627e013cc10b0924d05
a99f7b5f365f3137bf410fd3965d8ef44208e4b3
refs/heads/master
2020-05-30T07:12:53.347285
2016-11-05T02:00:02
2016-11-05T02:00:02
69,266,552
0
0
null
null
null
null
UTF-8
C++
false
false
411
h
#pragma once #include "BasicScene.h" #include "Sprite.h" #include <iostream> class CreditScene : public BasicScene { public: CreditScene(); ~CreditScene(); void init(); void update(int deltatime); void render(); BasicScene* changeState(); private: void initShaders(); ShaderProgram texProgram; glm::mat4 projection; Sprite* n1; Sprite* n2; Sprite* background; Sprite* anywhere; bool bmenu; };
[ "falc@null.net" ]
falc@null.net
c6b2d49e7d72b16d6fceddff44674020b1863370
73cfd700522885a3fec41127e1f87e1b78acd4d3
/_Include/boost/spirit/include/classic_parser_id.hpp
a533b730c589763507902c543245ad4d189ca2d6
[]
no_license
pu2oqa/muServerDeps
88e8e92fa2053960671f9f57f4c85e062c188319
92fcbe082556e11587887ab9d2abc93ec40c41e4
refs/heads/master
2023-03-15T12:37:13.995934
2019-02-04T10:07:14
2019-02-04T10:07:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
907
hpp
//////////////////////////////////////////////////////////////////////////////// // classic_parser_id.hpp /*============================================================================= Copyright (c) 2001-2008 Joel de Guzman Copyright (c) 2001-2008 Hartmut Kaiser http://spirit.sourceforge.net/ 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 BOOST_SPIRIT_INCLUDE_CLASSIC_PARSER_ID #define BOOST_SPIRIT_INCLUDE_CLASSIC_PARSER_ID #include <boost/spirit/home/classic/core/non_terminal/parser_id.hpp> #endif ///////////////////////////////////////////////// // vnDev.Games - Trong.LIVE - DAO VAN TRONG // ////////////////////////////////////////////////////////////////////////////////
[ "langley.joshua@gmail.com" ]
langley.joshua@gmail.com
c00a773227a3f6b26aaf4c05166a442b4aca6330
6ed471f36e5188f77dc61cca24daa41496a6d4a0
/SDK/Wall_Wood_Small_SM_New_functions.cpp
dbdaf2278b5d244ca8a0efeae8d5981f830197b2
[]
no_license
zH4x-SDK/zARKSotF-SDK
77bfaf9b4b9b6a41951ee18db88f826dd720c367
714730f4bb79c07d065181caf360d168761223f6
refs/heads/main
2023-07-16T22:33:15.140456
2021-08-27T13:40:06
2021-08-27T13:40:06
400,521,086
0
0
null
null
null
null
UTF-8
C++
false
false
1,489
cpp
#include "../SDK.h" // Name: ARKSotF, Version: 178.8.0 #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- // Functions //--------------------------------------------------------------------------- // Function Wall_Wood_Small_SM_New.Wall_Wood_Small_SM_New_C.UserConstructionScript // (Final) void AWall_Wood_Small_SM_New_C::UserConstructionScript() { static auto fn = UObject::FindObject<UFunction>("Function Wall_Wood_Small_SM_New.Wall_Wood_Small_SM_New_C.UserConstructionScript"); AWall_Wood_Small_SM_New_C_UserConstructionScript_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Wall_Wood_Small_SM_New.Wall_Wood_Small_SM_New_C.ExecuteUbergraph_Wall_Wood_Small_SM_New // (Final) // Parameters: // int EntryPoint (Parm, ZeroConstructor, IsPlainOldData) void AWall_Wood_Small_SM_New_C::ExecuteUbergraph_Wall_Wood_Small_SM_New(int EntryPoint) { static auto fn = UObject::FindObject<UFunction>("Function Wall_Wood_Small_SM_New.Wall_Wood_Small_SM_New_C.ExecuteUbergraph_Wall_Wood_Small_SM_New"); AWall_Wood_Small_SM_New_C_ExecuteUbergraph_Wall_Wood_Small_SM_New_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "zp2kshield@gmail.com" ]
zp2kshield@gmail.com