hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
dc099f9300c0294a933f125597250addf2186707
5,273
cpp
C++
src/Objects/Spiral.cpp
heyjoeway/CuckySonic
122ccc7319d117b977b5c019cedc6de6951bfc49
[ "MIT" ]
1
2019-12-16T16:32:46.000Z
2019-12-16T16:32:46.000Z
src/Objects/Spiral.cpp
heyjoeway/CuckySonic
122ccc7319d117b977b5c019cedc6de6951bfc49
[ "MIT" ]
null
null
null
src/Objects/Spiral.cpp
heyjoeway/CuckySonic
122ccc7319d117b977b5c019cedc6de6951bfc49
[ "MIT" ]
1
2019-12-13T22:04:02.000Z
2019-12-13T22:04:02.000Z
#include <stdint.h> #include "../Level.h" #include "../Game.h" #include "../Log.h" #include "../MathUtil.h" //#define SPIRAL_OFFSET_FIX //Fixes the radius offset to scale properly static const uint8_t FlipAngleTable[] = { 0x00,0x00, 0x01,0x01,0x16,0x16,0x16,0x16,0x2C,0x2C, 0x2C,0x2C,0x42,0x42,0x42,0x42,0x58,0x58, 0x58,0x58,0x6E,0x6E,0x6E,0x6E,0x84,0x84, 0x84,0x84,0x9A,0x9A,0x9A,0x9A,0xB0,0xB0, 0xB0,0xB0,0xC6,0xC6,0xC6,0xC6,0xDC,0xDC, 0xDC,0xDC,0xF2,0xF2,0xF2,0xF2,0x01,0x01, 0x00,0x00, }; static const int8_t CosineTable[] = { 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 30, 30, 30, 30, 29, 29, 29, 29, 29, 28, 28, 28, 28, 27, 27, 27, 27, 26, 26, 26, 25, 25, 25, 24, 24, 24, 23, 23, 22, 22, 21, 21, 20, 20, 19, 18, 18, 17, 16, 16, 15, 14, 14, 13, 12, 12, 11, 10, 10, 9, 8, 8, 7, 6, 6, 5, 4, 4, 3, 2, 2, 1, 0, -1, -2, -2, -3, -4, -4, -5, -6, -7, -7, -8, -9, -9,-10,-10, -11,-11,-12,-12,-13,-14,-14,-15, -15,-16,-16,-17,-17,-18,-18,-19, -19,-19,-20,-21,-21,-22,-22,-23, -23,-24,-24,-25,-25,-26,-26,-27, -27,-28,-28,-28,-29,-29,-30,-30, -30,-31,-31,-31,-32,-32,-32,-33, -33,-33,-33,-34,-34,-34,-35,-35, -35,-35,-35,-35,-35,-35,-36,-36, -36,-36,-36,-36,-36,-36,-36,-37, -37,-37,-37,-37,-37,-37,-37,-37, -37,-37,-37,-37,-37,-37,-37,-37, -37,-37,-37,-37,-37,-37,-37,-37, -37,-37,-37,-37,-36,-36,-36,-36, -36,-36,-36,-35,-35,-35,-35,-35, -35,-35,-35,-34,-34,-34,-33,-33, -33,-33,-32,-32,-32,-31,-31,-31, -30,-30,-30,-29,-29,-28,-28,-28, -27,-27,-26,-26,-25,-25,-24,-24, -23,-23,-22,-22,-21,-21,-20,-19, -19,-18,-18,-17,-16,-16,-15,-14, -14,-13,-12,-11,-11,-10, -9, -8, -7, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 10, 10, 11, 12, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 24, 24, 25, 25, 25, 25, 26, 26, 26, 26, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 30, 30, 30, 30, 30, 30, 30, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, }; void ObjSpiral(OBJECT *object) //Also MTZ cylinder { //Set our routine based off of our subtype if (object->routine == 0) { object->routine = (object->subtype < 0x80) ? 1 : 2; object->widthPixels = 208; } switch (object->routine) { case 1: //EHZ Spiral { for (size_t i = 0; i < gLevel->playerList.size(); i++) { //Get the player PLAYER *player = gLevel->playerList[i]; if (object->playerContact[i].standing == false) //Not already on the spiral { if (player->status.inAir) //Don't run on corkscrew if in mid-air continue; //Check if we're at the sides of the spiral if (!player->status.shouldNotFall) //If not standing on an object (already on a spiral) { //Check if we're at the sides of the spiral int16_t xOff = player->x.pos - object->x.pos; if (player->xVel >= 0) //Moving in from the left { if (xOff < -0xD0 || xOff > -0xC0) continue; } else //Moving in from the right { if (xOff < 0xC0 || xOff > 0xD0) continue; } } else { //Check if we're at the sides of the spiral int16_t xOff = player->x.pos - object->x.pos; if (player->xVel >= 0) //Moving in from the left { if (xOff < -0xC0 || xOff > -0xB0) continue; } else //Moving in from the right { if (xOff < 0xB0 || xOff > 0xC0) continue; } } //Check if we're near the bottom and not already on an object controlling us int16_t yOff = player->y.pos - object->y.pos - 0x10; if (yOff < 0 || yOff >= 0x30 || player->objectControl.disableOurMovement) continue; //Set the player to run on the spiral player->AttachToObject(object, i); } else { //Running on the corkscrew if (!(abs(player->inertia) < 0x600 || player->status.inAir)) //If not slowed down or jumped off { int16_t xOff = player->x.pos - object->x.pos + 0xD0; if (xOff >= 0 && xOff < 0x1A0) //If still on the spiral { //Move across the spiral if (player->status.shouldNotFall) //If still running on the spiral { //Set our Y-position int8_t cosine = CosineTable[xOff]; #ifndef SPIRAL_OFFSET_FIX int16_t yOff = player->yRadius - 19; #else int16_t yOff = ((player->yRadius - 19) * cosine) / (cosine < 0 ? 37 : 32); #endif player->y.pos = (object->y.pos + cosine) - yOff; //Set our flip angle player->flipAngle = FlipAngleTable[(xOff / 8) & 0x3F]; } continue; } } //Fall off player->status.shouldNotFall = false; object->playerContact[i].standing = false; player->flipsRemaining = false; player->flipSpeed = 4; } } break; } case 2: //MTZ Cylinder { //None break; } } object->UnloadOffscreen(object->x.pos); }
26.497487
100
0.535938
heyjoeway
dc0a628b5b8c4cefbfa6addb955d5241025331d7
1,731
cc
C++
Codeforces/252 Division 2/Problem D/D.cc
VastoLorde95/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
170
2017-07-25T14:47:29.000Z
2022-01-26T19:16:31.000Z
Codeforces/252 Division 2/Problem D/D.cc
navodit15/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
null
null
null
Codeforces/252 Division 2/Problem D/D.cc
navodit15/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
55
2017-07-28T06:17:33.000Z
2021-10-31T03:06:22.000Z
#include<cstdio> #include<iostream> #include<cmath> #include<algorithm> #include<cstring> #include<map> #include<set> #include<vector> #include<utility> #include<queue> #include<stack> #define sd(x) scanf("%d",&x) #define sd2(x,y) scanf("%d%d",&x,&y) #define sd3(x,y,z) scanf("%d%d%d",&x,&y,&z) #define fi first #define se second #define pb(x) push_back(x) #define mp(x,y) make_pair(x,y) #define LET(x, a) __typeof(a) x(a) #define foreach(it, v) for(LET(it, v.begin()); it != v.end(); it++) #define _ ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); #define __ freopen("input.txt", "r", stdin);freopen("output.txt", "w", stdout); #define tr(x) cout<<x<<endl; #define tr2(x,y) cout<<x<<" "<<y<<endl; #define tr3(x,y,z) cout<<x<<" "<<y<<" "<<z<<endl; #define tr4(w,x,y,z) cout<<w<<" "<<x<<" "<<y<<" "<<z<<endl; using namespace std; int n, p[3001], v[3001], m, cnt; void visit(int cur){ if(v[cur]) return; v[cur] = 1; visit(p[cur]); return; } int main(){ sd(n); for(int i = 1; i <= n; i++){ sd(p[i]); } sd(m); for(int i = 1; i <= n; i++){ if(!v[i]){ visit(i); cnt++; } } memset(v, 0, sizeof v); m = n - m; // tr(cnt); printf("%d\n", abs(m-cnt)); if(m < cnt){ visit(1); for(int i = 2; i <= n and cnt > m; i++){ if(!v[i]){ visit(i); printf("%d %d ", 1, i); cnt--; } } } else if(m > cnt){ for(int i = 1; i <= n and m > cnt; i++){ vector<int> pos(n+1, -1); int cur = 0; for(int j = p[i]; j != i; j = p[j]) pos[j] = cur++; pos[i] = cur; cur = 0; for(int j = i+1; j <= n and m > cnt; j++){ if(pos[j] >= cur){ printf("%d %d ", i, j); m--; cur = pos[j]+1; swap(p[i], p[j]); } } } } return 0; }
18.612903
79
0.514731
VastoLorde95
dc0dcb6630b98b9d5853238ec6aa4c17ab3ab11f
786
cpp
C++
infer/tests/codetoanalyze/cpp/errors/vector/iterator_access.cpp
shakenetwork/infer
faf04af1f4bd7a590948f3760cc9a11540420361
[ "BSD-3-Clause" ]
1
2017-09-14T09:03:44.000Z
2017-09-14T09:03:44.000Z
infer/tests/codetoanalyze/cpp/errors/vector/iterator_access.cpp
shakenetwork/infer
faf04af1f4bd7a590948f3760cc9a11540420361
[ "BSD-3-Clause" ]
2
2020-11-13T19:42:27.000Z
2020-11-13T19:49:19.000Z
infer/tests/codetoanalyze/cpp/errors/vector/iterator_access.cpp
shakenetwork/infer
faf04af1f4bd7a590948f3760cc9a11540420361
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2016 - present Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #include <vector> namespace iterator_access { struct X { int id; }; int possible_npe(std::vector<X> in) { int* x = nullptr; for (auto iter = in.begin(); iter != in.end(); ++iter) { if (iter->id >= 0 && iter->id <= 0) { return *x; } } return 1; } int impossible_npe(std::vector<X> in) { int* x = nullptr; for (auto iter = in.begin(); iter != in.end(); ++iter) { if (iter->id > 0 && iter->id <= 0) { return *x; } } return 1; } }
21.243243
78
0.604326
shakenetwork
dc0ddd3dc12fe6d5070d300b9baf89cb9ff7d362
1,436
cpp
C++
Cpp_Projects/HP_Calculator/hp_rechner.cpp
EderLukas/Portfolio
1c9adef3435129d26d3c6275a79ed363bf062e8f
[ "MIT" ]
null
null
null
Cpp_Projects/HP_Calculator/hp_rechner.cpp
EderLukas/Portfolio
1c9adef3435129d26d3c6275a79ed363bf062e8f
[ "MIT" ]
null
null
null
Cpp_Projects/HP_Calculator/hp_rechner.cpp
EderLukas/Portfolio
1c9adef3435129d26d3c6275a79ed363bf062e8f
[ "MIT" ]
null
null
null
/* * source code: hp_rechner.cpp * author: Lukas Eder * date: 28.12.2017 * * Descr.: * Grundlegende Rechnungen von Addition, Subtraktion, Multiplikation und Division nach dem HP-Rechner-Model. */ #include "hpFunktionen.h" #include <iostream> using namespace std; // Hauptprogramm int main() { // Variablen double resultat = 0.0, input1 = 0.0, input2 = 0.0; char menu = ' ', rep = ' '; // Titel cout << "***** HP-RECHNER *****\n" << endl; do { menu = menue(menu); // Input durch user if (rep == 'c') { input1 = resultat; } else { cout << "\nVariable 1:" << endl; cin >> input1; } cout << "Variable 2:" << endl; cin >> input2; // Berechnungen switch (menu) { case '+': resultat = addition(input1, input2); break; case '-': resultat = subtraktion(input1, input2); break; case '*': resultat = multiplikation(input1, input2); break; case '/': resultat = division(input1, input2); break; default: cout << "ERROR!" << endl; break; } // Output cout << "\n" << input1 << " " << menu << " " << input2 << " = " << resultat << endl; //Programmrepetition cout << "\n" << "y\tNeue Rechnung\n" << "c\tmit altem Resultat fortfahren\n" << "q\tBeenden\n\n" <<"Ihre Wahl:" << endl; cin >> rep; } while (rep != 'q'); cout << "\nWiedersehen!" << endl; }
18.894737
109
0.533426
EderLukas
dc0e1ca53b71dc9a172a14e2e61a5a2335496bfa
11,486
cxx
C++
test/unit/grid_heating/gridHeatingTestElec.cxx
tnakaicode/vpic
44c5c1f89de0ba57d54e4109176ba0a1714ce7e5
[ "BSD-3-Clause" ]
110
2017-02-14T20:02:57.000Z
2022-03-02T17:27:23.000Z
test/unit/grid_heating/gridHeatingTestElec.cxx
tnakaicode/vpic
44c5c1f89de0ba57d54e4109176ba0a1714ce7e5
[ "BSD-3-Clause" ]
124
2017-02-03T17:00:05.000Z
2022-02-28T20:47:36.000Z
test/unit/grid_heating/gridHeatingTestElec.cxx
tnakaicode/vpic
44c5c1f89de0ba57d54e4109176ba0a1714ce7e5
[ "BSD-3-Clause" ]
70
2017-01-19T19:15:12.000Z
2022-03-09T12:56:14.000Z
//============================================================================== /* Grid heating test case for electros in 2D This deck is made for quickly testing code changes by testing the grid heating rate. It initializes a 2D box of electrons with periodic boundary conditions and lets it evolve for for 0.5 picoseconds. The electrons are started very hot in an approximately linear heating regime. Ions are excluded for speed. This is not a test of the correctness of the physics in the code, i.e., it does not compare to an analytic physical result and asess if the code gives an answer close to that. Instead, it tests (more specifically, gridHeatingTestElec.py tests) if the code output has changed appreciably from a reference. This deck is very heavily modified from a short pulse deck origionally written by Brian J. Albright, 2005. Written by Scott V. Luedtke, XCP-6, August 15, 2019 */ //============================================================================== //#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() #define CATCH_CONFIG_RUNNER // We will provide a custom main #include "catch.hpp" // TODO: this import may ultimately be a bad idea, but it lets you paste an input deck in... #include "deck/wrapper.h" begin_globals { int energies_interval; // how frequently to dump energies }; begin_diagnostics { //if ( step()%1==0 ) sim_log("Time step: "<<step()); # define should_dump(x) \ (global->x##_interval>0 && remainder(step(),global->x##_interval)==0) if ( step()==0 ) { if ( rank()==0 ) { dump_mkdir("heating_rundata"); } // if } // energy in various fields/particles if( should_dump(energies) ) { dump_energies( "heating_rundata/energies", step() ==0 ? 0 : 1 ); } //if } begin_initialization { // do not change parameters in this block: double elementary_charge = 4.8032e-10; // stat coulomb double elementary_charge2 = elementary_charge * elementary_charge; double speed_of_light = 2.99792458e10; // cm/sec double m_e = 9.1094e-28; // g double k_boltz = 1.6022e-12; // ergs/eV double mec2 = m_e*speed_of_light*speed_of_light/k_boltz; double eps0 = 1; double cfl_req = 0.98; // How close to Courant should we try to run double damp = 0.0; // Level of radiation damping double n_e_over_n_crit = 1e2; // n_e/n_crit in solid slab double vacuum_wavelength = 1e3 *1e-7; // used for normalization double delta = (vacuum_wavelength/(2.0*M_PI))/sqrt(n_e_over_n_crit); // c/wpe double nx = 10; double ny = 10; double nz = 1; double box_size_x = nx*0.5*delta;// microns double box_size_y = ny*0.5*delta;// microns double box_size_z = nz*0.5*delta;// microns int load_particles = 1; // Flag to turn off particle load for testing wave launch. William Daughton. //???????????????????????????????????????????????????????????????????? double nppc = 64 ; // Average number of macro particles/cell of each species double t_e = 20e4; // electron temp, eV double uthe = sqrt(t_e/mec2); // vthe/c double n_e = speed_of_light*speed_of_light*m_e/(4.0*M_PI*elementary_charge2*delta*delta); // n_e is used for emax only double debye = uthe*delta; //?????????????????????????????????????????????????????????????????????????? int topology_x = nproc(); int topology_y = 1; int topology_z = 1; double cell_size_t = box_size_y/(debye*ny); // in debye double cell_size_tz= box_size_z/(debye*nz); double cell_size_l = box_size_x/(debye*nx); double hy = debye*cell_size_t/delta; double hz = debye*cell_size_tz/delta; double hx = debye*cell_size_l/delta; double Lx = nx*hx; // in c/wpe double Ly = ny*hy; double Lz = nz*hz; double particles_alloc = nppc*ny*nz*nx; double dt = cfl_req*courant_length(Lx, Ly, Lz, nx, ny, nz); double dt_courant = dt; double t_stop = 500. * 1e-15*speed_of_light/delta;// runtime in 1/omega_pe // Diagnostics intervals. int energies_interval = 100; global->energies_interval = energies_interval; double omega_0 = sqrt(1.0/n_e_over_n_crit); // w0/wpe double delta_0 = delta*sqrt(n_e_over_n_crit); // c/w0 double Ne = nppc*nx*ny*nz; // Number of macro electrons in box Ne = trunc_granular(Ne, nproc()); // Make Ne divisible by number of processors double Npe = Lx*Ly*Lz; // Number of physical electrons in box, wpe = 1 double qe = -Npe/Ne; // Charge per macro electron // Print stuff that I need for plotters and such, and with enough sig figs! // Be very careful modifying this. Plotters depend on explicit locations of // some of these numbers. Generally speaking, add lines at the end only. if(rank() == 0){ FILE * out; out = fopen("heating_params.txt", "w"); fprintf(out, "# Parameter file used for plotters.\n"); fprintf(out, "%.14e Time step (dt), code units\n", dt); fprintf(out, "%.14e Laser wavelength, SI\n", vacuum_wavelength*1e-2); fprintf(out, "%.14e Ratio of electron to critical density\n", n_e_over_n_crit); fprintf(out, "%d Number of cells in x\n", int(nx)); fprintf(out, "%d Number of cells in y\n", int(ny)); fprintf(out, "%d Number of cells in z\n", int(nz)); fprintf(out, "%.14e Box size x, microns\n", box_size_x*1e4); fprintf(out, "%.14e Box size y, microns\n", box_size_y*1e4); fprintf(out, "%.14e Box size z, microns\n", box_size_z*1e4); fclose(out); } // PRINT SIMULATION PARAMETERS sim_log("***** Simulation parameters *****"); sim_log("* Processors: "<<nproc()); sim_log("* dt_courant"<<dt_courant); sim_log("* delta/dx,delta/dz = "<<1.0/hx<<" "<<1.0/hz); sim_log("* Time step, max time, nsteps = "<<dt<<" "<<t_stop<<" "<<int(t_stop/(dt))); sim_log("* Debye length,cell size_l,cell size_t,delta,delta_0 = "<<debye<<" "<<cell_size_l<<" "<<cell_size_t<<" "<<delta<<" "<<delta_0); sim_log("* Lx, Ly, Lz = "<<Lx<<" "<<Ly<<" "<<Lz); sim_log("* nx, ny, nz = "<<nx<<" "<<ny<<" "<<nz); sim_log("* Charge/macro electron = "<<qe); sim_log("* particles_alloc = "<<particles_alloc); sim_log("* Average particles/processor: "<<Ne/nproc()); sim_log("* Average particles/cell: "<<nppc); sim_log("* Omega_0, Omega_pe: "<<(omega_0)<<" "<<1); sim_log("* Plasma density, ne/nc: "<<n_e<<" "<<n_e_over_n_crit); sim_log("* T_e,m_e: "<<t_e<<" "<<1); sim_log("* Radiation damping: "<<damp); sim_log("* Fraction of courant limit: "<<cfl_req); sim_log("* vthe/c: "<<uthe); sim_log("* energies_interval: "<<energies_interval); sim_log("*********************************"); // SETUP HIGH-LEVEL SIMULATION PARMETERS // FIXME : proper normalization in these units for: xfocus, ycenter, zcenter, waist sim_log("Setting up high-level simulation parameters. "); num_step = int(t_stop/(dt)); status_interval = 20000; //???????????????????????????????????????????????????????????????????????????????? sync_shared_interval = status_interval/10; clean_div_e_interval = status_interval/10; clean_div_b_interval = status_interval/10; verbose = 0; // SETUP THE GRID sim_log("Setting up computational grid."); grid->dx = hx; grid->dy = hy; grid->dz = hz; grid->dt = dt; grid->cvac = 1; grid->eps0 = eps0; // Partition a periodic box among the processors sliced uniformly in z: define_periodic_grid( 0, -0.5*Ly, -0.5*Lz, // Low corner Lx, 0.5*Ly, 0.5*Lz, // High corner nx, ny, nz, // Resolution topology_x, topology_y, topology_z); // Topology sim_log("Setting up electrons. "); //??????????????????????????????????????????????????????????????????????? // How oversized should the particle buffers be in case of non-uniform plasma? // The left and right ranks are half filled, and the middle will get to 1.5x // filled. An over_alloc_fac between .5 and 1.5 should drop if not // dynamically resizing. double over_alloc_fac = 1.3; double max_local_np_e = over_alloc_fac*particles_alloc/nproc(); double max_local_nm_e = max_local_np_e / 1.; species_t * electron = define_species("electron", -1, 1, max_local_np_e, max_local_nm_e, 0, 1); // SETUP THE MATERIALS sim_log("Setting up materials. "); define_material( "vacuum", 1 ); define_field_array( NULL, damp ); // LOAD PARTICLES // Load particles using rejection method (p. 290 Num. Recipes in C 2ed, Press et al.) if ( load_particles!=0 ) { sim_log( "Loading particles" ); seed_entropy( 2995471 ); // Kevin said it should be this way // Fast load of particles double xmin = grid->x0; double xmax = (grid->x0+grid->nx*grid->dx); double ymin = grid->y0; double ymax = (grid->y0+grid->ny*grid->dy); double zmin = grid->z0; double zmax = (grid->z0+grid->nz*grid->dz); repeat( (Ne)/(topology_x*topology_y*topology_z) ) { double x = uniform( rng(0), xmin, xmax ); double y = uniform( rng(0), ymin, ymax ); double z = uniform( rng(0), zmin, zmax ); // Rejection method, based on user-defined density function // Simplified for the uniform plasma used in this test if ( uniform( rng(0), 0, 1 ) < 1. ) { inject_particle( electron, x, y, z, normal( rng(0), 0, uthe ), normal( rng(0), 0, uthe ), normal( rng(0), 0, uthe ), fabs(qe), 0, 0 ); } } } // if load_particles } TEST_CASE( "Check if Weibel gives correct energy (within tol)", "[energy]" ) { // Init and run sim vpic_simulation simulation = vpic_simulation(); // TODO: We should do this in a safer manner simulation.initialize( 0, NULL ); while( simulation.advance() ); simulation.finalize(); } begin_particle_injection { // No particle injection for this simulation } begin_current_injection { // No current injection for this simulation } begin_field_injection { // No field injection for this simulation } begin_particle_collisions{ // No collisions for this simulation } // Manually implement catch main int main( int argc, char* argv[] ) { // Setup boot_services( &argc, &argv ); int result = Catch::Session().run( argc, argv ); // clean-up... halt_services(); return result; }
38.286667
141
0.559986
tnakaicode
dc0eb820d91d3e84942c7cb38a5ec15534bc08c4
2,204
cc
C++
cloudwf/src/model/SetUpgradeImgByModelRequest.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
cloudwf/src/model/SetUpgradeImgByModelRequest.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
cloudwf/src/model/SetUpgradeImgByModelRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/cloudwf/model/SetUpgradeImgByModelRequest.h> using AlibabaCloud::Cloudwf::Model::SetUpgradeImgByModelRequest; SetUpgradeImgByModelRequest::SetUpgradeImgByModelRequest() : RpcServiceRequest("cloudwf", "2017-03-28", "SetUpgradeImgByModel") { setMethod(HttpRequest::Method::Post); } SetUpgradeImgByModelRequest::~SetUpgradeImgByModelRequest() {} std::string SetUpgradeImgByModelRequest::getImgVersion()const { return imgVersion_; } void SetUpgradeImgByModelRequest::setImgVersion(const std::string& imgVersion) { imgVersion_ = imgVersion; setParameter("ImgVersion", imgVersion); } long SetUpgradeImgByModelRequest::getApModelId()const { return apModelId_; } void SetUpgradeImgByModelRequest::setApModelId(long apModelId) { apModelId_ = apModelId; setParameter("ApModelId", std::to_string(apModelId)); } std::string SetUpgradeImgByModelRequest::getAccessKeyId()const { return accessKeyId_; } void SetUpgradeImgByModelRequest::setAccessKeyId(const std::string& accessKeyId) { accessKeyId_ = accessKeyId; setParameter("AccessKeyId", accessKeyId); } std::string SetUpgradeImgByModelRequest::getImgAddr()const { return imgAddr_; } void SetUpgradeImgByModelRequest::setImgAddr(const std::string& imgAddr) { imgAddr_ = imgAddr; setParameter("ImgAddr", imgAddr); } std::string SetUpgradeImgByModelRequest::getComment()const { return comment_; } void SetUpgradeImgByModelRequest::setComment(const std::string& comment) { comment_ = comment; setParameter("Comment", comment); }
25.929412
81
0.760436
iamzken
dc0ee3e12e145c6957d7534a82041d2733c608e8
38,320
hpp
C++
include/armadillo_bits/wrapper_lapack.hpp
embarktrucks/armadillo-code
edfce747962f8ad508db660caa3892ed1a4069f8
[ "Apache-2.0" ]
16
2021-03-14T16:30:32.000Z
2022-03-18T13:41:53.000Z
include/armadillo_bits/wrapper_lapack.hpp
sinmx/armadillo
1314e433b09a77455647e84375292a2b0a16ac94
[ "Apache-2.0" ]
1
2018-01-08T09:16:37.000Z
2018-02-28T15:43:40.000Z
include/armadillo_bits/wrapper_lapack.hpp
sinmx/armadillo
1314e433b09a77455647e84375292a2b0a16ac94
[ "Apache-2.0" ]
4
2020-03-08T14:04:50.000Z
2020-12-03T08:51:04.000Z
// Copyright 2008-2016 Conrad Sanderson (http://conradsanderson.id.au) // Copyright 2008-2016 National ICT Australia (NICTA) // // 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. // ------------------------------------------------------------------------ #ifdef ARMA_USE_LAPACK //! \namespace lapack namespace for LAPACK functions namespace lapack { template<typename eT> inline void getrf(blas_int* m, blas_int* n, eT* a, blas_int* lda, blas_int* ipiv, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sgetrf)(m, n, (T*)a, lda, ipiv, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dgetrf)(m, n, (T*)a, lda, ipiv, info); } else if(is_supported_complex_float<eT>::value) { typedef std::complex<float> T; arma_fortran(arma_cgetrf)(m, n, (T*)a, lda, ipiv, info); } else if(is_supported_complex_double<eT>::value) { typedef std::complex<double> T; arma_fortran(arma_zgetrf)(m, n, (T*)a, lda, ipiv, info); } } template<typename eT> inline void getri(blas_int* n, eT* a, blas_int* lda, blas_int* ipiv, eT* work, blas_int* lwork, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sgetri)(n, (T*)a, lda, ipiv, (T*)work, lwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dgetri)(n, (T*)a, lda, ipiv, (T*)work, lwork, info); } else if(is_supported_complex_float<eT>::value) { typedef std::complex<float> T; arma_fortran(arma_cgetri)(n, (T*)a, lda, ipiv, (T*)work, lwork, info); } else if(is_supported_complex_double<eT>::value) { typedef std::complex<double> T; arma_fortran(arma_zgetri)(n, (T*)a, lda, ipiv, (T*)work, lwork, info); } } template<typename eT> inline void trtri(char* uplo, char* diag, blas_int* n, eT* a, blas_int* lda, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_strtri)(uplo, diag, n, (T*)a, lda, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dtrtri)(uplo, diag, n, (T*)a, lda, info); } else if(is_supported_complex_float<eT>::value) { typedef std::complex<float> T; arma_fortran(arma_ctrtri)(uplo, diag, n, (T*)a, lda, info); } else if(is_supported_complex_double<eT>::value) { typedef std::complex<double> T; arma_fortran(arma_ztrtri)(uplo, diag, n, (T*)a, lda, info); } } template<typename eT> inline void geev(char* jobvl, char* jobvr, blas_int* N, eT* a, blas_int* lda, eT* wr, eT* wi, eT* vl, blas_int* ldvl, eT* vr, blas_int* ldvr, eT* work, blas_int* lwork, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sgeev)(jobvl, jobvr, N, (T*)a, lda, (T*)wr, (T*)wi, (T*)vl, ldvl, (T*)vr, ldvr, (T*)work, lwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dgeev)(jobvl, jobvr, N, (T*)a, lda, (T*)wr, (T*)wi, (T*)vl, ldvl, (T*)vr, ldvr, (T*)work, lwork, info); } } template<typename eT> inline void cx_geev(char* jobvl, char* jobvr, blas_int* N, eT* a, blas_int* lda, eT* w, eT* vl, blas_int* ldvl, eT* vr, blas_int* ldvr, eT* work, blas_int* lwork, typename eT::value_type* rwork, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_supported_complex_float<eT>::value) { typedef float T; typedef typename std::complex<T> cx_T; arma_fortran(arma_cgeev)(jobvl, jobvr, N, (cx_T*)a, lda, (cx_T*)w, (cx_T*)vl, ldvl, (cx_T*)vr, ldvr, (cx_T*)work, lwork, (T*)rwork, info); } else if(is_supported_complex_double<eT>::value) { typedef double T; typedef typename std::complex<T> cx_T; arma_fortran(arma_zgeev)(jobvl, jobvr, N, (cx_T*)a, lda, (cx_T*)w, (cx_T*)vl, ldvl, (cx_T*)vr, ldvr, (cx_T*)work, lwork, (T*)rwork, info); } } template<typename eT> inline void syev(char* jobz, char* uplo, blas_int* n, eT* a, blas_int* lda, eT* w, eT* work, blas_int* lwork, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_ssyev)(jobz, uplo, n, (T*)a, lda, (T*)w, (T*)work, lwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dsyev)(jobz, uplo, n, (T*)a, lda, (T*)w, (T*)work, lwork, info); } } template<typename eT> inline void syevd(char* jobz, char* uplo, blas_int* n, eT* a, blas_int* lda, eT* w, eT* work, blas_int* lwork, blas_int* iwork, blas_int* liwork, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_ssyevd)(jobz, uplo, n, (T*)a, lda, (T*)w, (T*)work, lwork, iwork, liwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dsyevd)(jobz, uplo, n, (T*)a, lda, (T*)w, (T*)work, lwork, iwork, liwork, info); } } template<typename eT> inline void heev ( char* jobz, char* uplo, blas_int* n, eT* a, blas_int* lda, typename eT::value_type* w, eT* work, blas_int* lwork, typename eT::value_type* rwork, blas_int* info ) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_supported_complex_float<eT>::value) { typedef float T; typedef typename std::complex<T> cx_T; arma_fortran(arma_cheev)(jobz, uplo, n, (cx_T*)a, lda, (T*)w, (cx_T*)work, lwork, (T*)rwork, info); } else if(is_supported_complex_double<eT>::value) { typedef double T; typedef typename std::complex<T> cx_T; arma_fortran(arma_zheev)(jobz, uplo, n, (cx_T*)a, lda, (T*)w, (cx_T*)work, lwork, (T*)rwork, info); } } template<typename eT> inline void heevd ( char* jobz, char* uplo, blas_int* n, eT* a, blas_int* lda, typename eT::value_type* w, eT* work, blas_int* lwork, typename eT::value_type* rwork, blas_int* lrwork, blas_int* iwork, blas_int* liwork, blas_int* info ) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_supported_complex_float<eT>::value) { typedef float T; typedef typename std::complex<T> cx_T; arma_fortran(arma_cheevd)(jobz, uplo, n, (cx_T*)a, lda, (T*)w, (cx_T*)work, lwork, (T*)rwork, lrwork, iwork, liwork, info); } else if(is_supported_complex_double<eT>::value) { typedef double T; typedef typename std::complex<T> cx_T; arma_fortran(arma_zheevd)(jobz, uplo, n, (cx_T*)a, lda, (T*)w, (cx_T*)work, lwork, (T*)rwork, lrwork, iwork, liwork, info); } } template<typename eT> inline void ggev ( char* jobvl, char* jobvr, blas_int* n, eT* a, blas_int* lda, eT* b, blas_int* ldb, eT* alphar, eT* alphai, eT* beta, eT* vl, blas_int* ldvl, eT* vr, blas_int* ldvr, eT* work, blas_int* lwork, blas_int* info ) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sggev)(jobvl, jobvr, n, (T*)a, lda, (T*)b, ldb, (T*)alphar, (T*)alphai, (T*)beta, (T*)vl, ldvl, (T*)vr, ldvr, (T*)work, lwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dggev)(jobvl, jobvr, n, (T*)a, lda, (T*)b, ldb, (T*)alphar, (T*)alphai, (T*)beta, (T*)vl, ldvl, (T*)vr, ldvr, (T*)work, lwork, info); } } template<typename eT> inline void cx_ggev ( char* jobvl, char* jobvr, blas_int* n, eT* a, blas_int* lda, eT* b, blas_int* ldb, eT* alpha, eT* beta, eT* vl, blas_int* ldvl, eT* vr, blas_int* ldvr, eT* work, blas_int* lwork, typename eT::value_type* rwork, blas_int* info ) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_supported_complex_float<eT>::value) { typedef float T; typedef typename std::complex<T> cx_T; arma_fortran(arma_cggev)(jobvl, jobvr, n, (cx_T*)a, lda, (cx_T*)b, ldb, (cx_T*)alpha, (cx_T*)beta, (cx_T*)vl, ldvl, (cx_T*)vr, ldvr, (cx_T*)work, lwork, (T*)rwork, info); } else if(is_supported_complex_double<eT>::value) { typedef double T; typedef typename std::complex<T> cx_T; arma_fortran(arma_zggev)(jobvl, jobvr, n, (cx_T*)a, lda, (cx_T*)b, ldb, (cx_T*)alpha, (cx_T*)beta, (cx_T*)vl, ldvl, (cx_T*)vr, ldvr, (cx_T*)work, lwork, (T*)rwork, info); } } template<typename eT> inline void potrf(char* uplo, blas_int* n, eT* a, blas_int* lda, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_spotrf)(uplo, n, (T*)a, lda, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dpotrf)(uplo, n, (T*)a, lda, info); } else if(is_supported_complex_float<eT>::value) { typedef std::complex<float> T; arma_fortran(arma_cpotrf)(uplo, n, (T*)a, lda, info); } else if(is_supported_complex_double<eT>::value) { typedef std::complex<double> T; arma_fortran(arma_zpotrf)(uplo, n, (T*)a, lda, info); } } template<typename eT> inline void potri(char* uplo, blas_int* n, eT* a, blas_int* lda, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_spotri)(uplo, n, (T*)a, lda, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dpotri)(uplo, n, (T*)a, lda, info); } else if(is_supported_complex_float<eT>::value) { typedef std::complex<float> T; arma_fortran(arma_cpotri)(uplo, n, (T*)a, lda, info); } else if(is_supported_complex_double<eT>::value) { typedef std::complex<double> T; arma_fortran(arma_zpotri)(uplo, n, (T*)a, lda, info); } } template<typename eT> inline void geqrf(blas_int* m, blas_int* n, eT* a, blas_int* lda, eT* tau, eT* work, blas_int* lwork, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sgeqrf)(m, n, (T*)a, lda, (T*)tau, (T*)work, lwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dgeqrf)(m, n, (T*)a, lda, (T*)tau, (T*)work, lwork, info); } else if(is_supported_complex_float<eT>::value) { typedef std::complex<float> T; arma_fortran(arma_cgeqrf)(m, n, (T*)a, lda, (T*)tau, (T*)work, lwork, info); } else if(is_supported_complex_double<eT>::value) { typedef std::complex<double> T; arma_fortran(arma_zgeqrf)(m, n, (T*)a, lda, (T*)tau, (T*)work, lwork, info); } } template<typename eT> inline void orgqr(blas_int* m, blas_int* n, blas_int* k, eT* a, blas_int* lda, eT* tau, eT* work, blas_int* lwork, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sorgqr)(m, n, k, (T*)a, lda, (T*)tau, (T*)work, lwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dorgqr)(m, n, k, (T*)a, lda, (T*)tau, (T*)work, lwork, info); } } template<typename eT> inline void ungqr(blas_int* m, blas_int* n, blas_int* k, eT* a, blas_int* lda, eT* tau, eT* work, blas_int* lwork, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_supported_complex_float<eT>::value) { typedef float T; arma_fortran(arma_cungqr)(m, n, k, (T*)a, lda, (T*)tau, (T*)work, lwork, info); } else if(is_supported_complex_double<eT>::value) { typedef double T; arma_fortran(arma_zungqr)(m, n, k, (T*)a, lda, (T*)tau, (T*)work, lwork, info); } } template<typename eT> inline void gesvd ( char* jobu, char* jobvt, blas_int* m, blas_int* n, eT* a, blas_int* lda, eT* s, eT* u, blas_int* ldu, eT* vt, blas_int* ldvt, eT* work, blas_int* lwork, blas_int* info ) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sgesvd)(jobu, jobvt, m, n, (T*)a, lda, (T*)s, (T*)u, ldu, (T*)vt, ldvt, (T*)work, lwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dgesvd)(jobu, jobvt, m, n, (T*)a, lda, (T*)s, (T*)u, ldu, (T*)vt, ldvt, (T*)work, lwork, info); } } template<typename T> inline void cx_gesvd ( char* jobu, char* jobvt, blas_int* m, blas_int* n, std::complex<T>* a, blas_int* lda, T* s, std::complex<T>* u, blas_int* ldu, std::complex<T>* vt, blas_int* ldvt, std::complex<T>* work, blas_int* lwork, T* rwork, blas_int* info ) { arma_type_check(( is_supported_blas_type<T>::value == false )); arma_type_check(( is_supported_blas_type< std::complex<T> >::value == false )); if(is_float<T>::value) { typedef float bT; arma_fortran(arma_cgesvd) ( jobu, jobvt, m, n, (std::complex<bT>*)a, lda, (bT*)s, (std::complex<bT>*)u, ldu, (std::complex<bT>*)vt, ldvt, (std::complex<bT>*)work, lwork, (bT*)rwork, info ); } else if(is_double<T>::value) { typedef double bT; arma_fortran(arma_zgesvd) ( jobu, jobvt, m, n, (std::complex<bT>*)a, lda, (bT*)s, (std::complex<bT>*)u, ldu, (std::complex<bT>*)vt, ldvt, (std::complex<bT>*)work, lwork, (bT*)rwork, info ); } } template<typename eT> inline void gesdd ( char* jobz, blas_int* m, blas_int* n, eT* a, blas_int* lda, eT* s, eT* u, blas_int* ldu, eT* vt, blas_int* ldvt, eT* work, blas_int* lwork, blas_int* iwork, blas_int* info ) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sgesdd)(jobz, m, n, (T*)a, lda, (T*)s, (T*)u, ldu, (T*)vt, ldvt, (T*)work, lwork, iwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dgesdd)(jobz, m, n, (T*)a, lda, (T*)s, (T*)u, ldu, (T*)vt, ldvt, (T*)work, lwork, iwork, info); } } template<typename T> inline void cx_gesdd ( char* jobz, blas_int* m, blas_int* n, std::complex<T>* a, blas_int* lda, T* s, std::complex<T>* u, blas_int* ldu, std::complex<T>* vt, blas_int* ldvt, std::complex<T>* work, blas_int* lwork, T* rwork, blas_int* iwork, blas_int* info ) { arma_type_check(( is_supported_blas_type<T>::value == false )); arma_type_check(( is_supported_blas_type< std::complex<T> >::value == false )); if(is_float<T>::value) { typedef float bT; arma_fortran(arma_cgesdd) ( jobz, m, n, (std::complex<bT>*)a, lda, (bT*)s, (std::complex<bT>*)u, ldu, (std::complex<bT>*)vt, ldvt, (std::complex<bT>*)work, lwork, (bT*)rwork, iwork, info ); } else if(is_double<T>::value) { typedef double bT; arma_fortran(arma_zgesdd) ( jobz, m, n, (std::complex<bT>*)a, lda, (bT*)s, (std::complex<bT>*)u, ldu, (std::complex<bT>*)vt, ldvt, (std::complex<bT>*)work, lwork, (bT*)rwork, iwork, info ); } } template<typename eT> inline void gesv(blas_int* n, blas_int* nrhs, eT* a, blas_int* lda, blas_int* ipiv, eT* b, blas_int* ldb, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sgesv)(n, nrhs, (T*)a, lda, ipiv, (T*)b, ldb, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dgesv)(n, nrhs, (T*)a, lda, ipiv, (T*)b, ldb, info); } else if(is_supported_complex_float<eT>::value) { typedef std::complex<float> T; arma_fortran(arma_cgesv)(n, nrhs, (T*)a, lda, ipiv, (T*)b, ldb, info); } else if(is_supported_complex_double<eT>::value) { typedef std::complex<double> T; arma_fortran(arma_zgesv)(n, nrhs, (T*)a, lda, ipiv, (T*)b, ldb, info); } } template<typename eT> inline void gesvx(char* fact, char* trans, blas_int* n, blas_int* nrhs, eT* a, blas_int* lda, eT* af, blas_int* ldaf, blas_int* ipiv, char* equed, eT* r, eT* c, eT* b, blas_int* ldb, eT* x, blas_int* ldx, eT* rcond, eT* ferr, eT* berr, eT* work, blas_int* iwork, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sgesvx)(fact, trans, n, nrhs, (T*)a, lda, (T*)af, ldaf, ipiv, equed, (T*)r, (T*)c, (T*)b, ldb, (T*)x, ldx, (T*)rcond, (T*)ferr, (T*)berr, (T*)work, iwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dgesvx)(fact, trans, n, nrhs, (T*)a, lda, (T*)af, ldaf, ipiv, equed, (T*)r, (T*)c, (T*)b, ldb, (T*)x, ldx, (T*)rcond, (T*)ferr, (T*)berr, (T*)work, iwork, info); } } template<typename T, typename eT> inline void cx_gesvx(char* fact, char* trans, blas_int* n, blas_int* nrhs, eT* a, blas_int* lda, eT* af, blas_int* ldaf, blas_int* ipiv, char* equed, T* r, T* c, eT* b, blas_int* ldb, eT* x, blas_int* ldx, T* rcond, T* ferr, T* berr, eT* work, T* rwork, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_supported_complex_float<eT>::value) { typedef float pod_T; typedef std::complex<float> cx_T; arma_fortran(arma_cgesvx)(fact, trans, n, nrhs, (cx_T*)a, lda, (cx_T*)af, ldaf, ipiv, equed, (pod_T*)r, (pod_T*)c, (cx_T*)b, ldb, (cx_T*)x, ldx, (pod_T*)rcond, (pod_T*)ferr, (pod_T*)berr, (cx_T*)work, (pod_T*)rwork, info); } else if(is_supported_complex_double<eT>::value) { typedef double pod_T; typedef std::complex<double> cx_T; arma_fortran(arma_zgesvx)(fact, trans, n, nrhs, (cx_T*)a, lda, (cx_T*)af, ldaf, ipiv, equed, (pod_T*)r, (pod_T*)c, (cx_T*)b, ldb, (cx_T*)x, ldx, (pod_T*)rcond, (pod_T*)ferr, (pod_T*)berr, (cx_T*)work, (pod_T*)rwork, info); } } template<typename eT> inline void gels(char* trans, blas_int* m, blas_int* n, blas_int* nrhs, eT* a, blas_int* lda, eT* b, blas_int* ldb, eT* work, blas_int* lwork, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sgels)(trans, m, n, nrhs, (T*)a, lda, (T*)b, ldb, (T*)work, lwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dgels)(trans, m, n, nrhs, (T*)a, lda, (T*)b, ldb, (T*)work, lwork, info); } else if(is_supported_complex_float<eT>::value) { typedef std::complex<float> T; arma_fortran(arma_cgels)(trans, m, n, nrhs, (T*)a, lda, (T*)b, ldb, (T*)work, lwork, info); } else if(is_supported_complex_double<eT>::value) { typedef std::complex<double> T; arma_fortran(arma_zgels)(trans, m, n, nrhs, (T*)a, lda, (T*)b, ldb, (T*)work, lwork, info); } } template<typename eT> inline void gelsd(blas_int* m, blas_int* n, blas_int* nrhs, eT* a, blas_int* lda, eT* b, blas_int* ldb, eT* S, eT* rcond, blas_int* rank, eT* work, blas_int* lwork, blas_int* iwork, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sgelsd)(m, n, nrhs, (T*)a, lda, (T*)b, ldb, (T*)S, (T*)rcond, rank, (T*)work, lwork, iwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dgelsd)(m, n, nrhs, (T*)a, lda, (T*)b, ldb, (T*)S, (T*)rcond, rank, (T*)work, lwork, iwork, info); } } template<typename T> inline void cx_gelsd(blas_int* m, blas_int* n, blas_int* nrhs, std::complex<T>* a, blas_int* lda, std::complex<T>* b, blas_int* ldb, T* S, T* rcond, blas_int* rank, std::complex<T>* work, blas_int* lwork, T* rwork, blas_int* iwork, blas_int* info) { typedef typename std::complex<T> eT; arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_supported_complex_float<eT>::value) { typedef float pod_T; typedef std::complex<float> cx_T; arma_fortran(arma_cgelsd)(m, n, nrhs, (cx_T*)a, lda, (cx_T*)b, ldb, (pod_T*)S, (pod_T*)rcond, rank, (cx_T*)work, lwork, (pod_T*)rwork, iwork, info); } else if(is_supported_complex_double<eT>::value) { typedef double pod_T; typedef std::complex<double> cx_T; arma_fortran(arma_zgelsd)(m, n, nrhs, (cx_T*)a, lda, (cx_T*)b, ldb, (pod_T*)S, (pod_T*)rcond, rank, (cx_T*)work, lwork, (pod_T*)rwork, iwork, info); } } template<typename eT> inline void trtrs(char* uplo, char* trans, char* diag, blas_int* n, blas_int* nrhs, const eT* a, blas_int* lda, eT* b, blas_int* ldb, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_strtrs)(uplo, trans, diag, n, nrhs, (T*)a, lda, (T*)b, ldb, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dtrtrs)(uplo, trans, diag, n, nrhs, (T*)a, lda, (T*)b, ldb, info); } else if(is_supported_complex_float<eT>::value) { typedef std::complex<float> T; arma_fortran(arma_ctrtrs)(uplo, trans, diag, n, nrhs, (T*)a, lda, (T*)b, ldb, info); } else if(is_supported_complex_double<eT>::value) { typedef std::complex<double> T; arma_fortran(arma_ztrtrs)(uplo, trans, diag, n, nrhs, (T*)a, lda, (T*)b, ldb, info); } } template<typename eT> inline void gees(char* jobvs, char* sort, void* select, blas_int* n, eT* a, blas_int* lda, blas_int* sdim, eT* wr, eT* wi, eT* vs, blas_int* ldvs, eT* work, blas_int* lwork, blas_int* bwork, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sgees)(jobvs, sort, select, n, (T*)a, lda, sdim, (T*)wr, (T*)wi, (T*)vs, ldvs, (T*)work, lwork, bwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dgees)(jobvs, sort, select, n, (T*)a, lda, sdim, (T*)wr, (T*)wi, (T*)vs, ldvs, (T*)work, lwork, bwork, info); } } template<typename T> inline void cx_gees(char* jobvs, char* sort, void* select, blas_int* n, std::complex<T>* a, blas_int* lda, blas_int* sdim, std::complex<T>* w, std::complex<T>* vs, blas_int* ldvs, std::complex<T>* work, blas_int* lwork, T* rwork, blas_int* bwork, blas_int* info) { arma_type_check(( is_supported_blas_type<T>::value == false )); arma_type_check(( is_supported_blas_type< std::complex<T> >::value == false )); if(is_float<T>::value) { typedef float bT; typedef std::complex<bT> cT; arma_fortran(arma_cgees)(jobvs, sort, select, n, (cT*)a, lda, sdim, (cT*)w, (cT*)vs, ldvs, (cT*)work, lwork, (bT*)rwork, bwork, info); } else if(is_double<T>::value) { typedef double bT; typedef std::complex<bT> cT; arma_fortran(arma_zgees)(jobvs, sort, select, n, (cT*)a, lda, sdim, (cT*)w, (cT*)vs, ldvs, (cT*)work, lwork, (bT*)rwork, bwork, info); } } template<typename eT> inline void trsyl(char* transa, char* transb, blas_int* isgn, blas_int* m, blas_int* n, const eT* a, blas_int* lda, const eT* b, blas_int* ldb, eT* c, blas_int* ldc, eT* scale, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_strsyl)(transa, transb, isgn, m, n, (T*)a, lda, (T*)b, ldb, (T*)c, ldc, (T*)scale, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dtrsyl)(transa, transb, isgn, m, n, (T*)a, lda, (T*)b, ldb, (T*)c, ldc, (T*)scale, info); } else if(is_supported_complex_float<eT>::value) { typedef std::complex<float> T; arma_fortran(arma_ctrsyl)(transa, transb, isgn, m, n, (T*)a, lda, (T*)b, ldb, (T*)c, ldc, (float*)scale, info); } else if(is_supported_complex_double<eT>::value) { typedef std::complex<double> T; arma_fortran(arma_ztrsyl)(transa, transb, isgn, m, n, (T*)a, lda, (T*)b, ldb, (T*)c, ldc, (double*)scale, info); } } template<typename eT> inline void sytrf(char* uplo, blas_int* n, eT* a, blas_int* lda, blas_int* ipiv, eT* work, blas_int* lwork, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_ssytrf)(uplo, n, (T*)a, lda, ipiv, (T*)work, lwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dsytrf)(uplo, n, (T*)a, lda, ipiv, (T*)work, lwork, info); } else if(is_supported_complex_float<eT>::value) { typedef std::complex<float> T; arma_fortran(arma_csytrf)(uplo, n, (T*)a, lda, ipiv, (T*)work, lwork, info); } else if(is_supported_complex_double<eT>::value) { typedef std::complex<double> T; arma_fortran(arma_zsytrf)(uplo, n, (T*)a, lda, ipiv, (T*)work, lwork, info); } } template<typename eT> inline void sytri(char* uplo, blas_int* n, eT* a, blas_int* lda, blas_int* ipiv, eT* work, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_ssytri)(uplo, n, (T*)a, lda, ipiv, (T*)work, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dsytri)(uplo, n, (T*)a, lda, ipiv, (T*)work, info); } else if(is_supported_complex_float<eT>::value) { typedef std::complex<float> T; arma_fortran(arma_csytri)(uplo, n, (T*)a, lda, ipiv, (T*)work, info); } else if(is_supported_complex_double<eT>::value) { typedef std::complex<double> T; arma_fortran(arma_zsytri)(uplo, n, (T*)a, lda, ipiv, (T*)work, info); } } template<typename eT> inline void gges ( char* jobvsl, char* jobvsr, char* sort, void* selctg, blas_int* n, eT* a, blas_int* lda, eT* b, blas_int* ldb, blas_int* sdim, eT* alphar, eT* alphai, eT* beta, eT* vsl, blas_int* ldvsl, eT* vsr, blas_int* ldvsr, eT* work, blas_int* lwork, eT* bwork, blas_int* info ) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sgges)(jobvsl, jobvsr, sort, selctg, n, (T*)a, lda, (T*)b, ldb, sdim, (T*)alphar, (T*)alphai, (T*)beta, (T*)vsl, ldvsl, (T*)vsr, ldvsr, (T*)work, lwork, (T*)bwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dgges)(jobvsl, jobvsr, sort, selctg, n, (T*)a, lda, (T*)b, ldb, sdim, (T*)alphar, (T*)alphai, (T*)beta, (T*)vsl, ldvsl, (T*)vsr, ldvsr, (T*)work, lwork, (T*)bwork, info); } } template<typename eT> inline void cx_gges ( char* jobvsl, char* jobvsr, char* sort, void* selctg, blas_int* n, eT* a, blas_int* lda, eT* b, blas_int* ldb, blas_int* sdim, eT* alpha, eT* beta, eT* vsl, blas_int* ldvsl, eT* vsr, blas_int* ldvsr, eT* work, blas_int* lwork, typename eT::value_type* rwork, typename eT::value_type* bwork, blas_int* info ) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_supported_complex_float<eT>::value) { typedef float T; typedef typename std::complex<T> cx_T; arma_fortran(arma_cgges)(jobvsl, jobvsr, sort, selctg, n, (cx_T*)a, lda, (cx_T*)b, ldb, sdim, (cx_T*)alpha, (cx_T*)beta, (cx_T*)vsl, ldvsl, (cx_T*)vsr, ldvsr, (cx_T*)work, lwork, (T*)rwork, (T*)bwork, info); } else if(is_supported_complex_double<eT>::value) { typedef double T; typedef typename std::complex<T> cx_T; arma_fortran(arma_zgges)(jobvsl, jobvsr, sort, selctg, n, (cx_T*)a, lda, (cx_T*)b, ldb, sdim, (cx_T*)alpha, (cx_T*)beta, (cx_T*)vsl, ldvsl, (cx_T*)vsr, ldvsr, (cx_T*)work, lwork, (T*)rwork, (T*)bwork, info); } } template<typename eT> inline typename get_pod_type<eT>::result lange(char* norm, blas_int* m, blas_int* n, eT* a, blas_int* lda, typename get_pod_type<eT>::result* work) { arma_type_check(( is_supported_blas_type<eT>::value == false )); typedef typename get_pod_type<eT>::result out_T; if(is_float<eT>::value) { typedef float pod_T; typedef float T; return out_T( arma_fortran(arma_slange)(norm, m, n, (T*)a, lda, (pod_T*)work) ); } else if(is_double<eT>::value) { typedef double pod_T; typedef double T; return out_T( arma_fortran(arma_dlange)(norm, m, n, (T*)a, lda, (pod_T*)work) ); } else if(is_supported_complex_float<eT>::value) { typedef float pod_T; typedef std::complex<float> T; return out_T( arma_fortran(arma_clange)(norm, m, n, (T*)a, lda, (pod_T*)work) ); } else if(is_supported_complex_double<eT>::value) { typedef double pod_T; typedef std::complex<double> T; return out_T( arma_fortran(arma_zlange)(norm, m, n, (T*)a, lda, (pod_T*)work) ); } } template<typename eT> inline void gecon(char* norm, blas_int* n, eT* a, blas_int* lda, eT* anorm, eT* rcond, eT* work, blas_int* iwork, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sgecon)(norm, n, (T*)a, lda, (T*)anorm, (T*)rcond, (T*)work, iwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dgecon)(norm, n, (T*)a, lda, (T*)anorm, (T*)rcond, (T*)work, iwork, info); } } template<typename T> inline void cx_gecon(char* norm, blas_int* n, std::complex<T>* a, blas_int* lda, T* anorm, T* rcond, std::complex<T>* work, T* rwork, blas_int* info) { typedef typename std::complex<T> eT; arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_supported_complex_float<eT>::value) { typedef float pod_T; typedef typename std::complex<T> cx_T; arma_fortran(arma_cgecon)(norm, n, (cx_T*)a, lda, (pod_T*)anorm, (pod_T*)rcond, (cx_T*)work, (pod_T*)rwork, info); } else if(is_supported_complex_double<eT>::value) { typedef double pod_T; typedef typename std::complex<T> cx_T; arma_fortran(arma_zgecon)(norm, n, (cx_T*)a, lda, (pod_T*)anorm, (pod_T*)rcond, (cx_T*)work, (pod_T*)rwork, info); } } inline blas_int laenv(blas_int* ispec, char* name, char* opts, blas_int* n1, blas_int* n2, blas_int* n3, blas_int* n4) { return arma_fortran(arma_ilaenv)(ispec, name, opts, n1, n2, n3, n4); } template<typename eT> inline void sytrs(char* uplo, blas_int* n, blas_int* nrhs, eT* a, blas_int* lda, blas_int* ipiv, eT* b, blas_int* ldb, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_ssytrs)(uplo, n, nrhs, (T*)a, lda, ipiv, (T*)b, ldb, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dsytrs)(uplo, n, nrhs, (T*)a, lda, ipiv, (T*)b, ldb, info); } else if(is_supported_complex_float<eT>::value) { typedef std::complex<float> T; arma_fortran(arma_csytrs)(uplo, n, nrhs, (T*)a, lda, ipiv, (T*)b, ldb, info); } else if(is_supported_complex_double<eT>::value) { typedef std::complex<double> T; arma_fortran(arma_zsytrs)(uplo, n, nrhs, (T*)a, lda, ipiv, (T*)b, ldb, info); } } template<typename eT> inline void getrs(char* trans, blas_int* n, blas_int* nrhs, eT* a, blas_int* lda, blas_int* ipiv, eT* b, blas_int* ldb, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sgetrs)(trans, n, nrhs, (T*)a, lda, ipiv, (T*)b, ldb, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dgetrs)(trans, n, nrhs, (T*)a, lda, ipiv, (T*)b, ldb, info); } else if(is_supported_complex_float<eT>::value) { typedef std::complex<float> T; arma_fortran(arma_cgetrs)(trans, n, nrhs, (T*)a, lda, ipiv, (T*)b, ldb, info); } else if(is_supported_complex_double<eT>::value) { typedef std::complex<double> T; arma_fortran(arma_zgetrs)(trans, n, nrhs, (T*)a, lda, ipiv, (T*)b, ldb, info); } } template<typename eT> inline void lahqr(blas_int* wantt, blas_int* wantz, blas_int* n, blas_int* ilo, blas_int* ihi, eT* h, blas_int* ldh, eT* wr, eT* wi, blas_int* iloz, blas_int* ihiz, eT* z, blas_int* ldz, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_slahqr)(wantt, wantz, n, ilo, ihi, (T*)h, ldh, (T*)wr, (T*)wi, iloz, ihiz, (T*)z, ldz, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dlahqr)(wantt, wantz, n, ilo, ihi, (T*)h, ldh, (T*)wr, (T*)wi, iloz, ihiz, (T*)z, ldz, info); } } template<typename eT> inline void stedc(char* compz, blas_int* n, eT* d, eT* e, eT* z, blas_int* ldz, eT* work, blas_int* lwork, blas_int* iwork, blas_int* liwork, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sstedc)(compz, n, (T*)d, (T*)e, (T*)z, ldz, (T*)work, lwork, iwork, liwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dstedc)(compz, n, (T*)d, (T*)e, (T*)z, ldz, (T*)work, lwork, iwork, liwork, info); } } template<typename eT> inline void trevc(char* side, char* howmny, blas_int* select, blas_int* n, eT* t, blas_int* ldt, eT* vl, blas_int* ldvl, eT* vr, blas_int* ldvr, blas_int* mm, blas_int* m, eT* work, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_strevc)(side, howmny, select, n, (T*)t, ldt, (T*)vl, ldvl, (T*)vr, ldvr, mm, m, (T*)work, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dtrevc)(side, howmny, select, n, (T*)t, ldt, (T*)vl, ldvl, (T*)vr, ldvr, mm, m, (T*)work, info); } } template<typename eT> inline void larnv(blas_int* idist, blas_int* iseed, blas_int* n, eT* x) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_slarnv)(idist, iseed, n, (T*)x); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dlarnv)(idist, iseed, n, (T*)x); } } } #endif
29.91413
268
0.582777
embarktrucks
dc133148e87e81cf79dcc080817d4377684ab185
12,250
hh
C++
third_party/OpenMesh-8.1/src/OpenMesh/Tools/Subdivider/Adaptive/Composite/RuleInterfaceT.hh
hporro/grafica_cpp
1427bb6e8926b44be474b906e9f52cca77b3df9d
[ "MIT" ]
62
2020-11-06T17:29:24.000Z
2022-03-21T19:21:16.000Z
third_party/OpenMesh-8.1/src/OpenMesh/Tools/Subdivider/Adaptive/Composite/RuleInterfaceT.hh
hporro/grafica_cpp
1427bb6e8926b44be474b906e9f52cca77b3df9d
[ "MIT" ]
134
2017-02-25T20:47:43.000Z
2022-03-14T06:54:58.000Z
third_party/OpenMesh-8.1/src/OpenMesh/Tools/Subdivider/Adaptive/Composite/RuleInterfaceT.hh
hporro/grafica_cpp
1427bb6e8926b44be474b906e9f52cca77b3df9d
[ "MIT" ]
6
2021-02-19T07:20:19.000Z
2021-12-27T09:07:27.000Z
/* ========================================================================= * * * * OpenMesh * * Copyright (c) 2001-2015, RWTH-Aachen University * * Department of Computer Graphics and Multimedia * * All rights reserved. * * www.openmesh.org * * * *---------------------------------------------------------------------------* * This file is part of OpenMesh. * *---------------------------------------------------------------------------* * * * 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. * * * * ========================================================================= */ //============================================================================= // // CLASS RuleInterfaceT // //============================================================================= #ifndef OPENMESH_SUBDIVIDER_ADAPTIVE_RULEINTERFACET_HH #define OPENMESH_SUBDIVIDER_ADAPTIVE_RULEINTERFACET_HH //== INCLUDES ================================================================= #include <string> #include <OpenMesh/Tools/Subdivider/Adaptive/Composite/CompositeTraits.hh> //== NAMESPACE ================================================================ namespace OpenMesh { // BEGIN_NS_OPENMESH namespace Subdivider { // BEGIN_NS_SUBDIVIDER namespace Adaptive { // BEGIN_NS_ADAPTIVE //== FORWARDS ================================================================= template <typename M> class CompositeT; template <typename M> class RuleInterfaceT; //== CLASS DEFINITION ========================================================= // ---------------------------------------------------------------------------- /** Handle template for adaptive composite subdividion rules * \internal * * Use typed handle of a rule, e.g. Tvv3<MyMesh>::Handle. */ template < typename R > struct RuleHandleT : public BaseHandle { explicit RuleHandleT(int _idx=-1) : BaseHandle(_idx) {} typedef R Rule; operator bool() const { return is_valid(); } }; /** Defines the method type() (RuleInterfaceT::type()) and the * typedefs Self and Handle. */ #define COMPOSITE_RULE( classname, mesh_type ) \ protected:\ friend class CompositeT<mesh_type>; \ public: \ const char *type() const override { return #classname; } \ typedef classname<mesh_type> Self; \ typedef RuleHandleT< Self > Handle // ---------------------------------------------------------------------------- /** Base class for adaptive composite subdivision rules * \see class CompositeT */ template <typename M> class RuleInterfaceT { public: typedef M Mesh; typedef RuleInterfaceT<M> Self; typedef RuleHandleT< Self > Rule; typedef typename M::Scalar scalar_t; protected: /// Default constructor RuleInterfaceT(Mesh& _mesh) : mesh_(_mesh),prev_rule_(nullptr),subdiv_rule_(nullptr),subdiv_type_(0),number_(0),n_rules_(0) {}; public: /// Destructor virtual ~RuleInterfaceT() {}; /// Returns the name of the rule. /// Use define COMPOSITE_RULE to overload this function in a derived class. virtual const char *type() const = 0; public: /// \name Raise item //@{ /// Raise item to target state \c _target_state. virtual void raise(typename M::FaceHandle& _fh, state_t _target_state) { if (mesh_.data(_fh).state() < _target_state) { update(_fh, _target_state); mesh_.data(_fh).inc_state(); } } virtual void raise(typename M::EdgeHandle& _eh, state_t _target_state) { if (mesh_.data(_eh).state() < _target_state) { update(_eh, _target_state); mesh_.data(_eh).inc_state(); } } virtual void raise(typename M::VertexHandle& _vh, state_t _target_state) { if (mesh_.data(_vh).state() < _target_state) { update(_vh, _target_state); mesh_.data(_vh).inc_state(); } } //@} void update(typename M::FaceHandle& _fh, state_t _target_state) { typename M::FaceHandle opp_fh; while (mesh_.data(_fh).state() < _target_state - 1) { prev_rule()->raise(_fh, _target_state - 1); } // Don't use unflipped / unfinal faces!!! if (subdiv_type() == 3) { if (mesh_.face_handle(mesh_.opposite_halfedge_handle(mesh_.halfedge_handle(_fh))).is_valid()) { while (!mesh_.data(_fh).final()) { opp_fh = mesh_.face_handle(mesh_.opposite_halfedge_handle(mesh_.halfedge_handle(_fh))); assert (mesh_.data(_fh).state() >= mesh_.data(opp_fh).state()); // different states: raise other face if (mesh_.data(_fh).state() > mesh_.data(opp_fh).state()){ // raise opposite face prev_rule()->raise(opp_fh, _target_state - 1); } else { // equal states // flip edge // typename M::EdgeHandle eh(mesh_.edge_handle(mesh_.halfedge_handle(_fh))); // if (mesh_.is_flip_ok(eh)) { // std::cout << "Flipping Edge...\n"; // mesh_.flip(eh); // mesh_.data(_fh).set_final(); // mesh_.data(opp_fh).set_final(); // } // else { // std::cout << "Flip not okay.\n"; // } } } } else { // mesh_.data(_fh).set_final(); } // std::cout << "Raising Face to Level " // << _target_state // << " with " // << type() // << ".\n"; } assert( subdiv_type() != 4 || mesh_.data(_fh).final() || _target_state%n_rules() == (subdiv_rule()->number() + 1)%n_rules() ); typename M::FaceEdgeIter fe_it; typename M::FaceVertexIter fv_it; typename M::EdgeHandle eh; typename M::VertexHandle vh; std::vector<typename M::FaceHandle> face_vector; face_vector.clear(); if (_target_state > 1) { for (fe_it = mesh_.fe_iter(_fh); fe_it.is_valid(); ++fe_it) { eh = *fe_it; prev_rule()->raise(eh, _target_state - 1); } for (fv_it = mesh_.fv_iter(_fh); fv_it.is_valid(); ++fv_it) { vh = *fv_it; prev_rule()->raise(vh, _target_state - 1); } } } void update(typename M::EdgeHandle& _eh, state_t _target_state) { state_t state(mesh_.data(_eh).state()); // raise edge to correct state if (state + 1 < _target_state && _target_state > 0) { prev_rule()->raise(_eh, _target_state - 1); } typename M::VertexHandle vh; typename M::FaceHandle fh; if (_target_state > 1) { vh = mesh_.to_vertex_handle(mesh_.halfedge_handle(_eh, 0)); prev_rule()->raise(vh, _target_state - 1); vh = mesh_.to_vertex_handle(mesh_.halfedge_handle(_eh, 1)); prev_rule()->raise(vh, _target_state - 1); fh = mesh_.face_handle(mesh_.halfedge_handle(_eh, 0)); if (fh.is_valid()) prev_rule()->raise(fh, _target_state - 1); fh = mesh_.face_handle(mesh_.halfedge_handle(_eh, 1)); if (fh.is_valid()) prev_rule()->raise(fh, _target_state - 1); } } void update(typename M::VertexHandle& _vh, state_t _target_state) { state_t state(mesh_.data(_vh).state()); // raise vertex to correct state if (state + 1 < _target_state) { prev_rule()->raise(_vh, _target_state - 1); } std::vector<typename M::HalfedgeHandle> halfedge_vector; halfedge_vector.clear(); typename M::VertexOHalfedgeIter voh_it; typename M::EdgeHandle eh; typename M::FaceHandle fh; if (_target_state > 1) { for (voh_it = mesh_.voh_iter(_vh); voh_it.is_valid(); ++voh_it) { halfedge_vector.push_back(*voh_it); } while ( !halfedge_vector.empty() ) { eh = mesh_.edge_handle(halfedge_vector.back()); halfedge_vector.pop_back(); prev_rule()->raise(eh, _target_state - 1); } for (voh_it = mesh_.voh_iter(_vh); voh_it.is_valid(); ++voh_it) { halfedge_vector.push_back(*voh_it); } while ( !halfedge_vector.empty() ) { fh = mesh_.face_handle(halfedge_vector.back()); halfedge_vector.pop_back(); if (fh.is_valid()) prev_rule()->raise(fh, _target_state - 1); } } } public: /// Type of split operation, if it is a topological operator int subdiv_type() const { return subdiv_type_; } /// Position in rule sequence int number() const { return number_; } /// \name Parameterization of rule //@{ /// Set coefficient - ignored by non-parameterized rules. virtual void set_coeff( scalar_t _coeff ) { coeff_ = _coeff; } /// Get coefficient - ignored by non-parameterized rules. scalar_t coeff() const { return coeff_; } //@} protected: void set_prev_rule(Self*& _p) { prev_rule_ = _p; } Self* prev_rule() { return prev_rule_; } void set_subdiv_rule(Self*& _n) { subdiv_rule_ = _n; } Self* subdiv_rule() const { return subdiv_rule_; } void set_number(int _n) { number_ = _n; } void set_n_rules(int _n) { n_rules_ = _n; } int n_rules() const { return n_rules_; } void set_subdiv_type(int _n) { assert(_n == 3 || _n == 4); subdiv_type_ = _n; } friend class CompositeT<M>; protected: Mesh& mesh_; private: Self* prev_rule_; Self* subdiv_rule_; int subdiv_type_; int number_; int n_rules_; scalar_t coeff_; private: // Noncopyable RuleInterfaceT(const RuleInterfaceT&); RuleInterfaceT& operator=(const RuleInterfaceT&); }; //============================================================================= } // END_NS_ADAPTIVE } // END_NS_SUBDIVIDER } // END_NS_OPENMESH //============================================================================= #endif // OPENMESH_SUBDIVIDER_ADAPTIVE_RULEINTERFACET_HH defined //=============================================================================
30.397022
129
0.533224
hporro
dc17e129762729e809cefe6f33c1e5dcee550e89
217
hh
C++
Include/Zion/Log.hh
zionmultiplayer/Client
291c027c4011cb1ab207c9b394fb5f4b1da8652c
[ "MIT" ]
4
2022-02-08T07:04:49.000Z
2022-02-09T23:43:49.000Z
Include/Zion/Log.hh
zionmultiplayer/Client
291c027c4011cb1ab207c9b394fb5f4b1da8652c
[ "MIT" ]
null
null
null
Include/Zion/Log.hh
zionmultiplayer/Client
291c027c4011cb1ab207c9b394fb5f4b1da8652c
[ "MIT" ]
null
null
null
#pragma once namespace Zion { class Log { public: static void Open(const char *filename); static void Close(); static void Write(const char *format, ...); }; };
18.083333
55
0.520737
zionmultiplayer
dc19b4bf11e668d5cf6fc8dd48356bd945c17f06
34,710
cpp
C++
src/AC3DPlugins/obj8_import.cpp
den-rain/xptools
4c39da8d44a4a92e9efb2538844d433496b38f07
[ "X11", "MIT" ]
null
null
null
src/AC3DPlugins/obj8_import.cpp
den-rain/xptools
4c39da8d44a4a92e9efb2538844d433496b38f07
[ "X11", "MIT" ]
null
null
null
src/AC3DPlugins/obj8_import.cpp
den-rain/xptools
4c39da8d44a4a92e9efb2538844d433496b38f07
[ "X11", "MIT" ]
null
null
null
/* * Copyright (c) 2007, Laminar Research. * * 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. * */ /** OBJ7 exporter for AC3D **/ /* ANDY SEZ ABOUT MATERIALS: There's: Prototype int ac_palette_get_new_material_index(ACMaterialTemplate *m) if this material exists then return it's index otherwise, allocate a new one, copy the contents from m and return it's index This calls: Prototype Boolean material_compare(ACMaterial *m, ACMaterialTemplate *m2) That checks each part of the material. So- you'll get a whole new material if there's the slightest difference. If you only need RGB, use: Prototype long rgb_to_index(long rgbcol) This only checks the rgb of existing materials - not all the other attributes. */ #include "TclStubs.h" #include "ac_plugin.h" #include "Undoable.h" #ifdef Boolean #undef Boolean #endif #include "obj8_import.h" #include "ac_utils.h" #include "XObjDefs.h" #include "XObjReadWrite.h" #include "ObjConvert.h" #include "obj_model.h" #include "obj_anim.h" #include "obj_panel.h" #include <list> using std::list; // Set this to 1 and each change in culling or flat/smooth shading pops another object. #define OBJ_FOR_ALL_ATTRS 0 /*************************************************************************************************** * OBJ8 IMPORT AND EXPORT ***************************************************************************************************/ ACObject * do_obj8_load(char *filename) { ACObject * group_obj = NULL; ACObject * lod_obj = NULL; ACObject * stuff_obj = NULL; list<ACObject *> anim_obj; char * tex_full_name = NULL; int tex_id = -1; char * panel_full_name = NULL; int panel_id = -1; // char anim_cmd[1024]; string anim_dat; // char * anim_old_cmd; // Point3 key1, key2; int i; material_template_t current_material; current_material.rgb.r = 1.0; current_material.rgb.g = 1.0; current_material.rgb.b = 1.0; current_material.ambient.r = 0.2; current_material.ambient.g = 0.2; current_material.ambient.b = 0.2; current_material.specular.r = 0.0; current_material.specular.g = 0.0; current_material.specular.b = 0.0; current_material.emissive.r = 0.0; current_material.emissive.g = 0.0; current_material.emissive.b = 0.0; current_material.shininess = 128; current_material.transparency = 0.0; int default_material = ac_palette_get_new_material_index(&current_material); Point3 p3; char strbuf[256]; // obj8.lods.clear(); XObj8 obj8; if (!XObj8Read(filename, obj8)) { XObj obj7; if (!XObjRead(filename, obj7)) return NULL; Obj7ToObj8(obj7, obj8); } set_std_panel(); for (int n = 0; n < obj8.regions.size(); ++n) { add_sub_panel(obj8.regions[n].left,obj8.regions[n].bottom,obj8.regions[n].right,obj8.regions[n].top); } group_obj = new_object(OBJECT_GROUP); string fname(filename); string::size_type p = fname.find_last_of("\\/"); string justName = (p == fname.npos) ? fname : fname.substr(p+1); string justPath = fname.substr(0,p+1); string::size_type p2 = obj8.texture.find_last_of("\\/:"); string texName = (p2 == obj8.texture.npos) ? obj8.texture : obj8.texture.substr(p2+1); if (texName.size() > 4) texName.erase(texName.size()-4); string texPath; if(p2 != obj8.texture.npos) texPath = obj8.texture.substr(0,p2+1); string texNameBmp = texName + ".bmp"; string texNamePng = texName + ".png"; string texNameDds = texName + ".dds"; string texNamePvr = texName + ".pvr"; string texPathBmp = texPath + texNameBmp; string texPathPng = texPath + texNamePng; string texPathDds = texPath + texNameDds; string texPathPvr = texPath + texNamePvr; const char * panel_names[] = { "cockpit_3d/-PANELS-/Panel_Preview.png", "cockpit_3d/-PANELS-/Panel.png", "cockpit_3d/-PANELS-/Panel_Airliner.png", "cockpit_3d/-PANELS-/Panel_Fighter.png", "cockpit_3d/-PANELS-/Panel_Glider.png", "cockpit_3d/-PANELS-/Panel_Helo.png", "cockpit_3d/-PANELS-/Panel_Autogyro.png", "cockpit_3d/-PANELS-/Panel_General_IFR.png", "cockpit_3d/-PANELS-/Panel_Autogyro_Twin.png", "cockpit_3d/-PANELS-/Panel_Fighter_IFR.png", "cockpit/-PANELS-/Panel_Preview.png", "cockpit/-PANELS-/Panel.png", "cockpit/-PANELS-/Panel_Airliner.png", "cockpit/-PANELS-/Panel_Fighter.png", "cockpit/-PANELS-/Panel_Glider.png", "cockpit/-PANELS-/Panel_Helo.png", "cockpit/-PANELS-/Panel_Autogyro.png", "cockpit/-PANELS-/Panel_General_IFR.png", "cockpit/-PANELS-/Panel_Autogyro_Twin.png", "cockpit/-PANELS-/Panel_Fighter_IFR.png", 0 }; bool has_cockpit_cmd = false; bool has_cockpit_reg = false; for(vector<XObjLOD8>::iterator lod = obj8.lods.begin(); lod != obj8.lods.end(); ++lod) for(vector<XObjCmd8>::iterator cmd = lod->cmds.begin(); cmd != lod->cmds.end(); ++cmd) { if (cmd->cmd == attr_Tex_Cockpit) has_cockpit_cmd = true; if (cmd->cmd == attr_Tex_Cockpit_Subregion) has_cockpit_reg = true; } object_set_name(group_obj,(char *) justName.c_str()); if (!texName.empty()) { if (tex_id == -1) tex_full_name = search_texture(filename, (char *) texNamePvr.c_str()); if (tex_full_name != NULL) tex_id = add_new_texture_opt(tex_full_name,tex_full_name); if (tex_id == -1) tex_full_name = search_texture(filename, (char *) texNamePng.c_str()); if (tex_full_name != NULL) tex_id = add_new_texture_opt(tex_full_name,tex_full_name); if (tex_id == -1) tex_full_name = search_texture(filename, (char *) texNameBmp.c_str()); if (tex_full_name != NULL) tex_id = add_new_texture_opt(tex_full_name,tex_full_name); if (tex_id == -1) tex_full_name = search_texture(filename, (char *) texNameDds.c_str()); if (tex_full_name != NULL) tex_id = add_new_texture_opt(tex_full_name,tex_full_name); if (tex_id == -1) tex_full_name = search_texture(filename, (char *) texPathPvr.c_str()); if (tex_full_name != NULL) tex_id = add_new_texture_opt(tex_full_name,tex_full_name); if (tex_id == -1) tex_full_name = search_texture(filename, (char *) texPathPng.c_str()); if (tex_full_name != NULL) tex_id = add_new_texture_opt(tex_full_name,tex_full_name); if (tex_id == -1) tex_full_name = search_texture(filename, (char *) texPathBmp.c_str()); if (tex_full_name != NULL) tex_id = add_new_texture_opt(tex_full_name,tex_full_name); if (tex_id == -1) tex_full_name = search_texture(filename, (char *) texPathDds.c_str()); if (tex_full_name != NULL) tex_id = add_new_texture_opt(tex_full_name,tex_full_name); } if (has_cockpit_cmd || has_cockpit_reg) { printf("Trying cockpit textures.\n"); int n = 0; while(panel_id == -1 && panel_names[n]) { panel_full_name = search_texture(filename, (char*)panel_names[n]); if(panel_full_name) panel_id = add_new_texture_opt(panel_full_name, (char*)panel_names[n]); ++n; } if(panel_id == -1 && has_cockpit_reg) { message_dialog((char*)"Warning: I was unable to find a panel texture to load, but you are using panel regions. Your texure coordinates may be incorrect after import."); } } for(vector<XObjLOD8>::iterator lod = obj8.lods.begin(); lod != obj8.lods.end(); ++lod) { lod_obj = new_object(OBJECT_GROUP); if (lod->lod_far != 0.0) sprintf(strbuf, "LOD %f/%f",lod->lod_near, lod->lod_far); else strcpy(strbuf, "Default LOD"); object_set_name(lod_obj, strbuf); if (lod->lod_far != 0.0) { OBJ_set_LOD_near(lod_obj, lod->lod_near); OBJ_set_LOD_far (lod_obj, lod->lod_far ); } object_add_child(group_obj, lod_obj); bool shade_flat = false; bool two_side = false; int panel_tex = tex_id; int last_reg = -1; float s_mul=1.0,t_mul=1.0,s_add=0.0,t_add=0.0; float no_blend = -1.0; string hard_poly; int deck = 0; float offset = 0; string light_level; float light_v1 = 0.0f, light_v2 = 1.0f; int draw_disable = 0; int wall = 0; int manip_type = manip_none; string manip_dref1, manip_dref2, manip_cursor, manip_tooltip; float manip_wheel = 0.0; float manip_drag_axis[3]; float manip_v1_min; float manip_v1_max; float manip_v2_min; float manip_v2_max; map<int, Vertex *> vmap; for(vector<XObjCmd8>::iterator cmd = lod->cmds.begin(); cmd != lod->cmds.end(); ++cmd) { switch(cmd->cmd) { case obj8_Tris: case obj8_Lines: if (stuff_obj == NULL) { stuff_obj = new_object(OBJECT_NORMAL); vmap.clear(); if (panel_tex != -1)object_texture_set(stuff_obj, panel_tex); object_add_child(anim_obj.empty() ? lod_obj : anim_obj.back(), stuff_obj); OBJ_set_poly_os(stuff_obj, offset); OBJ_set_blend(stuff_obj, no_blend); OBJ_set_hard(stuff_obj, hard_poly.c_str()); OBJ_set_deck(stuff_obj,deck); if(light_level.empty()) OBJ_set_mod_lit(stuff_obj,0); else { OBJ_set_mod_lit(stuff_obj,1); OBJ_set_lit_dataref(stuff_obj,light_level.c_str()); OBJ_set_lit_v1(stuff_obj, light_v1); OBJ_set_lit_v2(stuff_obj, light_v2); } OBJ_set_wall(stuff_obj,wall); OBJ_set_draw_disable(stuff_obj,draw_disable); OBJ_set_manip_type(stuff_obj,manip_type); switch(manip_type) { case manip_axis: case manip_axis_pix: OBJ_set_manip_v1_min(stuff_obj,manip_v1_min); OBJ_set_manip_v1_max(stuff_obj,manip_v1_max); OBJ_set_manip_dx(stuff_obj,manip_drag_axis[0]); OBJ_set_manip_dy(stuff_obj,manip_drag_axis[1]); OBJ_set_manip_dz(stuff_obj,manip_drag_axis[2]); OBJ_set_manip_dref1(stuff_obj,manip_dref1.c_str()); OBJ_set_manip_cursor(stuff_obj,manip_cursor.c_str()); OBJ_set_manip_tooltip(stuff_obj,manip_tooltip.c_str()); OBJ_set_manip_wheel(stuff_obj, manip_wheel); break; case manip_axis_2d: OBJ_set_manip_v1_min(stuff_obj,manip_v1_min); OBJ_set_manip_v1_max(stuff_obj,manip_v1_max); OBJ_set_manip_v2_min(stuff_obj,manip_v2_min); OBJ_set_manip_v2_max(stuff_obj,manip_v2_max); OBJ_set_manip_dx(stuff_obj,manip_drag_axis[0]); OBJ_set_manip_dy(stuff_obj,manip_drag_axis[1]); OBJ_set_manip_dref1(stuff_obj,manip_dref1.c_str()); OBJ_set_manip_dref2(stuff_obj,manip_dref2.c_str()); OBJ_set_manip_cursor(stuff_obj,manip_cursor.c_str()); OBJ_set_manip_tooltip(stuff_obj,manip_tooltip.c_str()); break; case manip_command: OBJ_set_manip_dref1(stuff_obj,manip_dref1.c_str()); OBJ_set_manip_cursor(stuff_obj,manip_cursor.c_str()); OBJ_set_manip_tooltip(stuff_obj,manip_tooltip.c_str()); break; case manip_command_axis: OBJ_set_manip_dx(stuff_obj,manip_drag_axis[0]); OBJ_set_manip_dy(stuff_obj,manip_drag_axis[1]); OBJ_set_manip_dz(stuff_obj,manip_drag_axis[2]); OBJ_set_manip_dref1(stuff_obj,manip_dref1.c_str()); OBJ_set_manip_dref2(stuff_obj,manip_dref2.c_str()); OBJ_set_manip_cursor(stuff_obj,manip_cursor.c_str()); OBJ_set_manip_tooltip(stuff_obj,manip_tooltip.c_str()); break; case manip_noop: OBJ_set_manip_dref1(stuff_obj,manip_dref1.c_str()); OBJ_set_manip_tooltip(stuff_obj,manip_tooltip.c_str()); break; case manip_dref_push: case manip_dref_toggle: OBJ_set_manip_v1_min(stuff_obj,manip_v1_min); OBJ_set_manip_v1_max(stuff_obj,manip_v1_max); OBJ_set_manip_dref1(stuff_obj,manip_dref1.c_str()); OBJ_set_manip_cursor(stuff_obj,manip_cursor.c_str()); OBJ_set_manip_tooltip(stuff_obj,manip_tooltip.c_str()); OBJ_set_manip_wheel(stuff_obj, manip_wheel); break; case manip_dref_radio: OBJ_set_manip_v1_max(stuff_obj,manip_v1_max); OBJ_set_manip_dref1(stuff_obj,manip_dref1.c_str()); OBJ_set_manip_cursor(stuff_obj,manip_cursor.c_str()); OBJ_set_manip_tooltip(stuff_obj,manip_tooltip.c_str()); OBJ_set_manip_wheel(stuff_obj, manip_wheel); break; case manip_dref_delta: case manip_dref_wrap: OBJ_set_manip_v1_min(stuff_obj,manip_v1_min); OBJ_set_manip_v1_max(stuff_obj,manip_v1_max); OBJ_set_manip_v2_min(stuff_obj,manip_v2_min); OBJ_set_manip_v2_max(stuff_obj,manip_v2_max); OBJ_set_manip_dref1(stuff_obj,manip_dref1.c_str()); OBJ_set_manip_cursor(stuff_obj,manip_cursor.c_str()); OBJ_set_manip_tooltip(stuff_obj,manip_tooltip.c_str()); OBJ_set_manip_wheel(stuff_obj, manip_wheel); break; case manip_command_knob: case manip_command_switch_ud: case manip_command_switch_lr: OBJ_set_manip_dref1(stuff_obj,manip_dref1.c_str()); OBJ_set_manip_dref2(stuff_obj,manip_dref2.c_str()); OBJ_set_manip_cursor(stuff_obj,manip_cursor.c_str()); OBJ_set_manip_tooltip(stuff_obj,manip_tooltip.c_str()); break; case manip_dref_knob: case manip_dref_switch_ud: case manip_dref_switch_lr: OBJ_set_manip_dref1(stuff_obj,manip_dref1.c_str()); OBJ_set_manip_cursor(stuff_obj,manip_cursor.c_str()); OBJ_set_manip_tooltip(stuff_obj,manip_tooltip.c_str()); OBJ_set_manip_v1_min(stuff_obj,manip_v1_min); OBJ_set_manip_v1_max(stuff_obj,manip_v1_max); OBJ_set_manip_dx(stuff_obj,manip_drag_axis[0]); OBJ_set_manip_dy(stuff_obj,manip_drag_axis[1]); break; } sprintf(strbuf, "POLY_OS=%d HARD=%s BLEND=%s", (int) offset, hard_poly.c_str(), no_blend >= 0.0 ? "no":"yes"); object_set_name(stuff_obj, strbuf); } if (cmd->cmd == obj8_Tris) { int total_verts = 0; vector<Vertex *> verts; for (i = 0; i < cmd->idx_count; ++i) { map<int,Vertex *>::iterator idx_iter = vmap.find(obj8.indices[cmd->idx_offset + i]); if(idx_iter != vmap.end()) { verts.push_back(idx_iter->second); } else { ++total_verts; float * dat = obj8.geo_tri.get(obj8.indices[cmd->idx_offset + i]); p3.x = dat[0]; p3.y = dat[1]; p3.z = dat[2]; verts.push_back(object_add_new_vertex_head(stuff_obj, &p3)); vmap.insert(map<int,Vertex*>::value_type(obj8.indices[cmd->idx_offset + i],verts.back())); } } Surface * s = NULL; for (i = 0; i < cmd->idx_count; ++i) { if ((i % 3) == 0) { s = new_surface(); surface_set_type(s, SURFACE_POLYGON); surface_set_twosided(s, two_side); surface_set_shading(s, !shade_flat); object_add_surface_head(stuff_obj, s); int our_material = ac_palette_get_new_material_index(&current_material); surface_set_col(s, our_material); if (our_material != default_material) OBJ_set_use_materials(stuff_obj, 1); } float * dat = obj8.geo_tri.get(obj8.indices[cmd->idx_offset + i]); surface_add_vertex_head(s, verts[i], dat[6] * s_mul + s_add, dat[7] * t_mul + t_add); } } else { vector<Vertex *> verts; int i; for (i = 0; i < cmd->idx_count; ++i) { float * dat = obj8.geo_lines.get(obj8.indices[cmd->idx_offset + i]); p3.x = dat[0]; p3.y = dat[1]; p3.z = dat[2]; verts.push_back(object_add_new_vertex_head(stuff_obj, &p3)); } Surface * s = NULL; for (i = 0; i < cmd->idx_count; ++i) { float * dat = obj8.geo_lines.get(obj8.indices[cmd->idx_offset + i]); if ((i % 2) == 0) { s = new_surface(); surface_set_rgb_long(s, rgb_floats_to_long(dat[3], dat[4], dat[5])); surface_set_type(s, SURFACE_LINE); surface_set_twosided(s, two_side); surface_set_shading(s, !shade_flat); object_add_surface_head(stuff_obj, s); } surface_add_vertex_head(s, verts[i], 0.0, 0.0); } } break; case attr_Tex_Normal: if (panel_tex != tex_id) stuff_obj = NULL; panel_tex = tex_id; last_reg = -1; s_mul=1.0,t_mul=1.0,s_add=0.0,t_add=0.0; manip_type = manip_none; break; case attr_Tex_Cockpit: if (panel_tex != panel_id) stuff_obj = NULL; panel_tex = panel_id; last_reg = -1; s_mul=1.0,t_mul=1.0,s_add=0.0,t_add=0.0; manip_type = manip_panel; break; case attr_Tex_Cockpit_Subregion: if (panel_tex != panel_id) stuff_obj = NULL; if(last_reg != (int) cmd->params[0]) stuff_obj = NULL; panel_tex = panel_id; last_reg = (int) cmd->params[0]; manip_type = manip_panel; panel_get_import_scaling(panel_id,last_reg,&s_mul,&t_mul,&s_add,&t_add); break; case attr_No_Blend: if (!no_blend != cmd->params[0]) stuff_obj = NULL; no_blend = cmd->params[0]; break; case attr_Blend: if (no_blend != -1.0) stuff_obj = NULL; no_blend = -1.0; break; case attr_Hard: if (hard_poly != cmd->name) stuff_obj = NULL; if(deck == 1) stuff_obj = NULL; hard_poly = cmd->name; deck = 0; break; case attr_Hard_Deck: if (hard_poly != cmd->name) stuff_obj = NULL; if(deck == 0) stuff_obj = NULL; hard_poly = cmd->name; deck = 1; break; case attr_No_Hard: if (!hard_poly.empty()) stuff_obj = NULL; hard_poly.clear(); deck = 0; break; case attr_Offset: if (offset != cmd->params[0]) stuff_obj = NULL; offset = cmd->params[0]; break; case attr_Shade_Flat: #if OBJ_FOR_ALL_ATTRS if (!shade_flat) stuff_obj = NULL; #endif shade_flat = true; break; case attr_Shade_Smooth: #if OBJ_FOR_ALL_ATTRS if (shade_flat) stuff_obj = NULL; #endif shade_flat = false; break; case attr_Cull: #if OBJ_FOR_ALL_ATTRS if (two_side) stuff_obj = NULL; #endif two_side = false; break; case attr_NoCull: #if OBJ_FOR_ALL_ATTRS if (!two_side) stuff_obj = NULL; #endif two_side = true; break; case attr_Solid_Wall: if(!wall) stuff_obj = NULL; wall = 1; break; case attr_No_Solid_Wall: if(wall) stuff_obj = NULL; wall = 0; break; case attr_Draw_Disable: if(!draw_disable) stuff_obj = NULL; draw_disable = 1; break; case attr_Draw_Enable: if(draw_disable) stuff_obj = NULL; draw_disable = 0; break; case attr_Light_Level: if(light_level != cmd->name) stuff_obj = NULL; if(light_v1 != cmd->params[0]) stuff_obj = NULL; if(light_v2 != cmd->params[1]) stuff_obj = NULL; light_v1 = cmd->params[0]; light_v2 = cmd->params[1]; light_level = cmd->name; break; case attr_Light_Level_Reset: if(!light_level.empty()) stuff_obj = NULL; light_v1 = 0.0f; light_v2 = 1.0f; light_level.clear(); break; case attr_Layer_Group: OBJ_set_layer_group(group_obj, cmd->name.c_str()); OBJ_set_layer_group_offset(group_obj, cmd->params[0]); break; case attr_Manip_Drag_Axis: stuff_obj = NULL; manip_type = manip_axis; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_cursor = obj8.manips[cmd->idx_offset].cursor; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; manip_v1_min = obj8.manips[cmd->idx_offset].v1_min; manip_v1_max = obj8.manips[cmd->idx_offset].v1_max; manip_drag_axis[0] = obj8.manips[cmd->idx_offset].axis[0]; manip_drag_axis[1] = obj8.manips[cmd->idx_offset].axis[1]; manip_drag_axis[2] = obj8.manips[cmd->idx_offset].axis[2]; manip_wheel = obj8.manips[cmd->idx_offset].mouse_wheel_delta; break; case attr_Manip_Drag_2d: stuff_obj = NULL; manip_type = manip_axis_2d; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_dref2 = obj8.manips[cmd->idx_offset].dataref2; manip_cursor = obj8.manips[cmd->idx_offset].cursor; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; manip_v1_min = obj8.manips[cmd->idx_offset].v1_min; manip_v1_max = obj8.manips[cmd->idx_offset].v1_max; manip_v2_min = obj8.manips[cmd->idx_offset].v2_min; manip_v2_max = obj8.manips[cmd->idx_offset].v2_max; manip_drag_axis[0] = obj8.manips[cmd->idx_offset].axis[0]; manip_drag_axis[1] = obj8.manips[cmd->idx_offset].axis[1]; break; case attr_Manip_Command: stuff_obj = NULL; manip_type = manip_command; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_cursor = obj8.manips[cmd->idx_offset].cursor; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; break; case attr_Manip_Command_Axis: stuff_obj = NULL; manip_type = manip_command_axis; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_dref2 = obj8.manips[cmd->idx_offset].dataref2; manip_cursor = obj8.manips[cmd->idx_offset].cursor; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; manip_drag_axis[0] = obj8.manips[cmd->idx_offset].axis[0]; manip_drag_axis[1] = obj8.manips[cmd->idx_offset].axis[1]; manip_drag_axis[2] = obj8.manips[cmd->idx_offset].axis[2]; break; case attr_Manip_Noop: stuff_obj = NULL; manip_type = manip_noop; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; break; case attr_Manip_Push: stuff_obj = NULL; manip_type = manip_dref_push; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_cursor = obj8.manips[cmd->idx_offset].cursor; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; manip_v1_min = obj8.manips[cmd->idx_offset].v1_min; manip_v1_max = obj8.manips[cmd->idx_offset].v1_max; manip_wheel = obj8.manips[cmd->idx_offset].mouse_wheel_delta; break; case attr_Manip_Radio: stuff_obj = NULL; manip_type = manip_dref_radio; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_cursor = obj8.manips[cmd->idx_offset].cursor; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; manip_v1_max = obj8.manips[cmd->idx_offset].v1_max; manip_wheel = obj8.manips[cmd->idx_offset].mouse_wheel_delta; break; case attr_Manip_Toggle: stuff_obj = NULL; manip_type = manip_dref_toggle; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_cursor = obj8.manips[cmd->idx_offset].cursor; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; manip_v1_min = obj8.manips[cmd->idx_offset].v1_min; manip_v1_max = obj8.manips[cmd->idx_offset].v1_max; manip_wheel = obj8.manips[cmd->idx_offset].mouse_wheel_delta; break; case attr_Manip_Delta: stuff_obj = NULL; manip_type = manip_dref_delta; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_cursor = obj8.manips[cmd->idx_offset].cursor; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; manip_v1_min = obj8.manips[cmd->idx_offset].v1_min; manip_v1_max = obj8.manips[cmd->idx_offset].v1_max; manip_v2_min = obj8.manips[cmd->idx_offset].v2_min; manip_v2_max = obj8.manips[cmd->idx_offset].v2_max; manip_wheel = obj8.manips[cmd->idx_offset].mouse_wheel_delta; break; case attr_Manip_Wrap: stuff_obj = NULL; manip_type = manip_dref_wrap; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_cursor = obj8.manips[cmd->idx_offset].cursor; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; manip_v1_min = obj8.manips[cmd->idx_offset].v1_min; manip_v1_max = obj8.manips[cmd->idx_offset].v1_max; manip_v2_min = obj8.manips[cmd->idx_offset].v2_min; manip_v2_max = obj8.manips[cmd->idx_offset].v2_max; manip_wheel = obj8.manips[cmd->idx_offset].mouse_wheel_delta; break; case attr_Manip_Drag_Axis_Pix: stuff_obj = NULL; manip_type = manip_axis_pix; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_cursor = obj8.manips[cmd->idx_offset].cursor; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; manip_v1_min = obj8.manips[cmd->idx_offset].v1_min; manip_v1_max = obj8.manips[cmd->idx_offset].v1_max; manip_drag_axis[0] = obj8.manips[cmd->idx_offset].axis[0]; manip_drag_axis[1] = obj8.manips[cmd->idx_offset].axis[1]; manip_drag_axis[2] = obj8.manips[cmd->idx_offset].axis[2]; manip_wheel = obj8.manips[cmd->idx_offset].mouse_wheel_delta; break; case attr_Manip_Command_Knob: stuff_obj = NULL; manip_type = manip_command_knob; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_dref2 = obj8.manips[cmd->idx_offset].dataref2; manip_cursor = obj8.manips[cmd->idx_offset].cursor; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; break; case attr_Manip_Command_Switch_Up_Down: stuff_obj = NULL; manip_type = manip_command_switch_ud; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_dref2 = obj8.manips[cmd->idx_offset].dataref2; manip_cursor = obj8.manips[cmd->idx_offset].cursor; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; break; case attr_Manip_Command_Switch_Left_Right: stuff_obj = NULL; manip_type = manip_command_switch_lr; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_dref2 = obj8.manips[cmd->idx_offset].dataref2; manip_cursor = obj8.manips[cmd->idx_offset].cursor; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; break; case attr_Manip_Axis_Knob: stuff_obj = NULL; manip_type = manip_dref_knob; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_cursor = obj8.manips[cmd->idx_offset].cursor; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; manip_v1_min = obj8.manips[cmd->idx_offset].v1_min; manip_v1_max = obj8.manips[cmd->idx_offset].v1_max; manip_drag_axis[0] = obj8.manips[cmd->idx_offset].axis[0]; manip_drag_axis[1] = obj8.manips[cmd->idx_offset].axis[1]; break; case attr_Manip_Axis_Switch_Up_Down: stuff_obj = NULL; manip_type = manip_dref_switch_ud; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_cursor = obj8.manips[cmd->idx_offset].cursor; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; manip_v1_min = obj8.manips[cmd->idx_offset].v1_min; manip_v1_max = obj8.manips[cmd->idx_offset].v1_max; manip_drag_axis[0] = obj8.manips[cmd->idx_offset].axis[0]; manip_drag_axis[1] = obj8.manips[cmd->idx_offset].axis[1]; break; case attr_Manip_Axis_Switch_Left_Right: stuff_obj = NULL; manip_type = manip_dref_switch_lr; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_cursor = obj8.manips[cmd->idx_offset].cursor; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; manip_v1_min = obj8.manips[cmd->idx_offset].v1_min; manip_v1_max = obj8.manips[cmd->idx_offset].v1_max; manip_drag_axis[0] = obj8.manips[cmd->idx_offset].axis[0]; manip_drag_axis[1] = obj8.manips[cmd->idx_offset].axis[1]; break; case anim_Begin: { stuff_obj = NULL; ACObject * parent = anim_obj.empty() ? lod_obj : anim_obj.back(); anim_obj.push_back(new_object(OBJECT_GROUP)); object_add_child(parent, anim_obj.back()); object_set_name(anim_obj.back(), (char*)"ANIMATION"); OBJ_set_animation_group(anim_obj.back(),1); } break; case anim_End: stuff_obj = NULL; anim_obj.pop_back(); break; case anim_Translate: { stuff_obj = NULL; int root = 0; if (obj8.animation[cmd->idx_offset].keyframes[root].v[0] != 0.0 || obj8.animation[cmd->idx_offset].keyframes[root].v[1] != 0.0 || obj8.animation[cmd->idx_offset].keyframes[root].v[2] != 0.0) anim_add_static(anim_obj.back(), 0, obj8.animation[cmd->idx_offset].keyframes[root].v, obj8.animation[cmd->idx_offset].dataref.c_str(), "static translate"); if (obj8.animation[cmd->idx_offset].keyframes.size() > 2 || (obj8.animation[cmd->idx_offset].keyframes.size() == 2 && ( obj8.animation[cmd->idx_offset].keyframes[0].v[0] != obj8.animation[cmd->idx_offset].keyframes[1].v[0] || obj8.animation[cmd->idx_offset].keyframes[0].v[1] != obj8.animation[cmd->idx_offset].keyframes[1].v[1] || obj8.animation[cmd->idx_offset].keyframes[0].v[2] != obj8.animation[cmd->idx_offset].keyframes[1].v[2]))) anim_add_translate(anim_obj.back(), 0, obj8.animation[cmd->idx_offset].keyframes, obj8.animation[cmd->idx_offset].dataref.c_str(), "translate", obj8.animation[cmd->idx_offset].loop); } break; case anim_Rotate: { stuff_obj = NULL; float center[3] = { 0.0, 0.0, 0.0 }; anim_add_rotate(anim_obj.back(), 0, center, obj8.animation[cmd->idx_offset].axis, obj8.animation[cmd->idx_offset].keyframes, obj8.animation[cmd->idx_offset].dataref.c_str(), "rotate", obj8.animation[cmd->idx_offset].loop); } break; case anim_Show: stuff_obj = NULL; anim_add_show(anim_obj.back(), 0, obj8.animation[cmd->idx_offset].keyframes, obj8.animation[cmd->idx_offset].dataref.c_str(), "show"); break; case anim_Hide: stuff_obj = NULL; anim_add_hide(anim_obj.back(), 0, obj8.animation[cmd->idx_offset].keyframes, obj8.animation[cmd->idx_offset].dataref.c_str(), "show"); break; case obj8_Lights: for (i = 0; i < cmd->idx_count; ++i) { stuff_obj = NULL; ACObject * light = new_object(OBJECT_LIGHT); Point3 pt_ac3, col_ac3 = { 0.0, 0.0, 0.0 }; float * dat = obj8.geo_lights.get(cmd->idx_offset + i); pt_ac3.x = dat[0]; pt_ac3.y = dat[1]; pt_ac3.z = dat[2]; ac_entity_set_point_value(light, (char*)"loc", &pt_ac3); sprintf(strbuf, "RGB (%f,%f,%f)", dat[3], dat[4], dat[5]); ac_entity_set_point_value(light, (char*)"diffuse", &col_ac3); object_set_name(light, strbuf); object_add_child(anim_obj.empty() ? lod_obj : anim_obj.back(), light); OBJ_set_light_red(light, dat[3]); OBJ_set_light_green(light, dat[4]); OBJ_set_light_blue(light, dat[5]); OBJ_set_light_named(light, "rgb"); } break; case obj8_LightNamed: { stuff_obj = NULL; ACObject * light = new_object(OBJECT_LIGHT); Point3 pt_ac3, col_ac3 = { 0.0, 0.0, 0.0 }; pt_ac3.x = cmd->params[0]; pt_ac3.y = cmd->params[1]; pt_ac3.z = cmd->params[2]; ac_entity_set_point_value(light, (char*)"loc", &pt_ac3); ac_entity_set_point_value(light, (char*)"diffuse", &col_ac3); object_set_name(light, (char*) cmd->name.c_str()); object_add_child(anim_obj.empty() ? lod_obj : anim_obj.back(), light); OBJ_set_light_named(light, cmd->name.c_str()); } break; case obj8_LightCustom: { stuff_obj = NULL; ACObject * light = new_object(OBJECT_LIGHT); Point3 pt_ac3, col_ac3 = { 0.0, 0.0, 0.0 }; pt_ac3.x = cmd->params[0]; pt_ac3.y = cmd->params[1]; pt_ac3.z = cmd->params[2]; ac_entity_set_point_value(light, (char*)"loc", &pt_ac3); ac_entity_set_point_value(light, (char*)"diffuse", &col_ac3); object_add_child(anim_obj.empty() ? lod_obj : anim_obj.back(), light); OBJ_set_light_named(light, "custom"); OBJ_set_light_dataref(light, cmd->name.c_str()); OBJ_set_light_red (light,cmd->params[3]); OBJ_set_light_green (light,cmd->params[4]); OBJ_set_light_blue (light,cmd->params[5]); OBJ_set_light_alpha (light,cmd->params[6]); OBJ_set_light_size (light,cmd->params[7]); OBJ_set_light_s1 (light,cmd->params[8]); OBJ_set_light_t1 (light,cmd->params[9]); OBJ_set_light_s2 (light,cmd->params[10]); OBJ_set_light_t2 (light,cmd->params[11]); } break; case obj_Smoke_Black: { stuff_obj = NULL; ACObject * light = new_object(OBJECT_LIGHT); Point3 pt_ac3, col_ac3 = { 0.0, 0.0, 0.0 }; pt_ac3.x = cmd->params[0]; pt_ac3.y = cmd->params[1]; pt_ac3.z = cmd->params[2]; ac_entity_set_point_value(light, (char*)"loc", &pt_ac3); ac_entity_set_point_value(light, (char*)"diffuse", &col_ac3); object_set_name(light, (char*)"Black Smoke"); object_add_child(anim_obj.empty() ? lod_obj : anim_obj.back(), light); OBJ_set_light_smoke_size(light, cmd->params[3]); OBJ_set_light_named(light, "black smoke"); } break; case obj_Smoke_White: { stuff_obj = NULL; ACObject * light = new_object(OBJECT_LIGHT); Point3 pt_ac3, col_ac3 = { 0.0, 0.0, 0.0 }; pt_ac3.x = cmd->params[0]; pt_ac3.y = cmd->params[1]; pt_ac3.z = cmd->params[2]; ac_entity_set_point_value(light, (char*)"loc", &pt_ac3); ac_entity_set_point_value(light, (char*)"diffuse", &col_ac3); object_set_name(light, (char*)"White Smoke"); object_add_child(anim_obj.empty() ? lod_obj : anim_obj.back(), light); OBJ_set_light_smoke_size(light, cmd->params[3]); OBJ_set_light_named(light, "white smoke"); } break; case attr_Ambient_RGB: break; case attr_Diffuse_RGB: current_material.rgb.r = cmd->params[0]; current_material.rgb.g = cmd->params[1]; current_material.rgb.b = cmd->params[2]; break; case attr_Emission_RGB: current_material.emissive.r = cmd->params[0]; current_material.emissive.g = cmd->params[1]; current_material.emissive.b = cmd->params[2]; break; case attr_Specular_RGB: break; case attr_Shiny_Rat: current_material.specular.r = cmd->params[0]; current_material.specular.g = cmd->params[0]; current_material.specular.b = cmd->params[0]; break; case attr_Reset: current_material.rgb.r = 1.0; current_material.rgb.g = 1.0; current_material.rgb.b = 1.0; current_material.specular.r = 0.0; current_material.specular.g = 0.0; current_material.specular.b = 0.0; current_material.emissive.r = 0.0; current_material.emissive.g = 0.0; current_material.emissive.b = 0.0; break; } } } object_calc_normals_force(group_obj); bake_static_transitions(group_obj); purge_datarefs(); gather_datarefs(group_obj); sync_datarefs(); return group_obj; }
36.006224
172
0.681648
den-rain
dc1abdf77ef4738900b3dcc654db8e753608f195
28,436
cpp
C++
test/cxx/Core/SpawningKit/HandshakePerformTest.cpp
m5o/passenger
9640816af708867d0994bd2eddb80ac24399f855
[ "MIT" ]
2,728
2015-01-01T10:06:45.000Z
2022-03-30T18:12:58.000Z
test/cxx/Core/SpawningKit/HandshakePerformTest.cpp
m5o/passenger
9640816af708867d0994bd2eddb80ac24399f855
[ "MIT" ]
1,192
2015-01-01T06:03:19.000Z
2022-03-31T09:14:36.000Z
test/cxx/Core/SpawningKit/HandshakePerformTest.cpp
m5o/passenger
9640816af708867d0994bd2eddb80ac24399f855
[ "MIT" ]
334
2015-01-08T20:47:03.000Z
2022-02-18T07:07:01.000Z
#include <TestSupport.h> #include <Core/SpawningKit/Handshake/Prepare.h> #include <Core/SpawningKit/Handshake/Perform.h> #include <LoggingKit/Context.h> #include <SystemTools/UserDatabase.h> #include <boost/bind/bind.hpp> #include <cstdio> #include <IOTools/IOUtils.h> using namespace std; using namespace Passenger; using namespace Passenger::SpawningKit; namespace tut { struct Core_SpawningKit_HandshakePerformTest: public TestBase { WrapperRegistry::Registry wrapperRegistry; SpawningKit::Context::Schema schema; SpawningKit::Context context; SpawningKit::Config config; boost::shared_ptr<HandshakeSession> session; pid_t pid; Pipe stdoutAndErr; HandshakePerform::DebugSupport *debugSupport; AtomicInt counter; FileDescriptor server; Core_SpawningKit_HandshakePerformTest() : context(schema), pid(getpid()), debugSupport(NULL) { wrapperRegistry.finalize(); context.resourceLocator = resourceLocator; context.wrapperRegistry = &wrapperRegistry; context.integrationMode = "standalone"; context.spawnDir = getSystemTempDir(); config.appGroupName = "appgroup"; config.appRoot = "/tmp/myapp"; config.startCommand = "echo hi"; config.startupFile = "/tmp/myapp/app.py"; config.appType = "wsgi"; config.spawnMethod = "direct"; config.bindAddress = "127.0.0.1"; config.user = lookupSystemUsernameByUid(getuid()); config.group = lookupSystemGroupnameByGid(getgid()); config.internStrings(); } ~Core_SpawningKit_HandshakePerformTest() { Json::Value config; vector<ConfigKit::Error> errors; LoggingKit::ConfigChangeRequest req; config["level"] = DEFAULT_LOG_LEVEL_NAME; config["app_output_log_level"] = DEFAULT_APP_OUTPUT_LOG_LEVEL_NAME; if (LoggingKit::context->prepareConfigChange(config, errors, req)) { LoggingKit::context->commitConfigChange(req); } else { P_BUG("Error configuring LoggingKit: " << ConfigKit::toString(errors)); } } void init(JourneyType type) { vector<StaticString> errors; ensure("Config is valid", config.validate(errors)); context.finalize(); session = boost::make_shared<HandshakeSession>(context, config, type); session->journey.setStepInProgress(SPAWNING_KIT_PREPARATION); HandshakePrepare(*session).execute().finalize(); session->journey.setStepInProgress(SPAWNING_KIT_HANDSHAKE_PERFORM); session->journey.setStepInProgress(SUBPROCESS_BEFORE_FIRST_EXEC); } void execute() { HandshakePerform performer(*session, pid, FileDescriptor(), stdoutAndErr.first); performer.debugSupport = debugSupport; performer.execute(); counter++; } static Json::Value createGoodPropertiesJson() { Json::Value socket, doc; socket["address"] = "tcp://127.0.0.1:3000"; socket["protocol"] = "http"; socket["concurrency"] = 1; socket["accept_http_requests"] = true; doc["sockets"].append(socket); return doc; } void signalFinish() { writeFile(session->responseDir + "/finish", "1"); } void signalFinishWithError() { writeFile(session->responseDir + "/finish", "0"); } }; struct FreePortDebugSupport: public HandshakePerform::DebugSupport { Core_SpawningKit_HandshakePerformTest *test; HandshakeSession *session; AtomicInt expectedStartPort; virtual void beginWaitUntilSpawningFinished() { expectedStartPort = session->expectedStartPort; test->counter++; } }; struct CrashingDebugSupport: public HandshakePerform::DebugSupport { virtual void beginWaitUntilSpawningFinished() { throw RuntimeException("oh no!"); } }; DEFINE_TEST_GROUP_WITH_LIMIT(Core_SpawningKit_HandshakePerformTest, 80); /***** General logic *****/ TEST_METHOD(1) { set_test_name("If the app is generic, it finishes when the app is pingable"); FreePortDebugSupport debugSupport; this->debugSupport = &debugSupport; config.genericApp = true; init(SPAWN_DIRECTLY); debugSupport.test = this; debugSupport.session = session.get(); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::execute, this)); EVENTUALLY(1, result = counter == 1; ); server.assign(createTcpServer("127.0.0.1", debugSupport.expectedStartPort.get()), NULL, 0); EVENTUALLY(1, result = counter == 2; ); } TEST_METHOD(2) { set_test_name("If findFreePort is true, it finishes when the app is pingable"); FreePortDebugSupport debugSupport; this->debugSupport = &debugSupport; config.findFreePort = true; init(SPAWN_DIRECTLY); debugSupport.test = this; debugSupport.session = session.get(); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::execute, this)); EVENTUALLY(1, result = counter == 1; ); server.assign(createTcpServer("127.0.0.1", debugSupport.expectedStartPort.get()), NULL, 0); EVENTUALLY(1, result = counter == 2; ); } TEST_METHOD(3) { set_test_name("It finishes when the app has sent the finish signal"); init(SPAWN_DIRECTLY); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::execute, this)); SHOULD_NEVER_HAPPEN(100, result = counter > 0; ); createFile(session->responseDir + "/properties.json", createGoodPropertiesJson().toStyledString()); signalFinish(); EVENTUALLY(1, result = counter == 1; ); } TEST_METHOD(10) { set_test_name("It raises an error if the process exits prematurely"); init(SPAWN_DIRECTLY); pid = fork(); if (pid == 0) { // Exit child _exit(1); } try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure_equals(StaticString(e.what()), "The application process exited prematurely."); } } TEST_METHOD(11) { set_test_name("It raises an error if the procedure took too long"); config.startTimeoutMsec = 50; init(SPAWN_DIRECTLY); pid = fork(); if (pid == 0) { // Exit child usleep(1000000); _exit(1); } try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure_equals(StaticString(e.what()), "A timeout occurred while spawning an application process."); } } TEST_METHOD(15) { set_test_name("In the event of an error, it sets the SPAWNING_KIT_HANDSHAKE_PERFORM step to the errored state"); CrashingDebugSupport debugSupport; this->debugSupport = &debugSupport; init(SPAWN_DIRECTLY); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &) { ensure_equals(session->journey.getFirstFailedStep(), SPAWNING_KIT_HANDSHAKE_PERFORM); } } TEST_METHOD(16) { set_test_name("In the event of an error, the exception contains journey state information from the response directory"); CrashingDebugSupport debugSupport; this->debugSupport = &debugSupport; init(SPAWN_DIRECTLY); createFile(session->responseDir + "/steps/subprocess_listen/state", "STEP_ERRORED"); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &) { ensure_equals(session->journey.getStepInfo(SUBPROCESS_LISTEN).state, STEP_ERRORED); } } TEST_METHOD(17) { set_test_name("In the event of an error, the exception contains subprocess stdout and stderr data"); Pipe p = createPipe(__FILE__, __LINE__); CrashingDebugSupport debugSupport; init(SPAWN_DIRECTLY); HandshakePerform performer(*session, pid, FileDescriptor(), p.first); performer.debugSupport = &debugSupport; Json::Value config; vector<ConfigKit::Error> errors; LoggingKit::ConfigChangeRequest req; config["app_output_log_level"] = "debug"; if (LoggingKit::context->prepareConfigChange(config, errors, req)) { LoggingKit::context->commitConfigChange(req); } else { P_BUG("Error configuring LoggingKit: " << ConfigKit::toString(errors)); } writeExact(p.second, "hi\n"); try { performer.execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure_equals(e.getStdoutAndErrData(), "hi\n"); } } TEST_METHOD(18) { set_test_name("In the event of an error caused by the subprocess, the exception contains messages from" " the subprocess as dumped in the response directory"); init(SPAWN_DIRECTLY); pid = fork(); if (pid == 0) { // Exit child _exit(1); } createFile(session->responseDir + "/error/summary", "the summary"); createFile(session->responseDir + "/error/problem_description.txt", "the <problem>"); createFile(session->responseDir + "/error/advanced_problem_details", "the advanced problem details"); createFile(session->responseDir + "/error/solution_description.html", "the <b>solution</b>"); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure_equals(e.getSummary(), "the summary"); ensure_equals(e.getProblemDescriptionHTML(), "the &lt;problem&gt;"); ensure_equals(e.getAdvancedProblemDetails(), "the advanced problem details"); ensure_equals(e.getSolutionDescriptionHTML(), "the <b>solution</b>"); } } TEST_METHOD(19) { set_test_name("In the event of success, it loads the journey state information from the response directory"); init(SPAWN_DIRECTLY); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::execute, this)); createFile(session->responseDir + "/properties.json", createGoodPropertiesJson().toStyledString()); createFile(session->responseDir + "/steps/subprocess_listen/state", "STEP_PERFORMED"); signalFinish(); EVENTUALLY(5, result = counter == 1; ); ensure_equals(session->journey.getStepInfo(SUBPROCESS_LISTEN).state, STEP_PERFORMED); } TEST_METHOD(20) { // Limited test of whether the code mitigates symlink attacks. set_test_name("It does not read from symlinks"); init(SPAWN_DIRECTLY); createFile(session->responseDir + "/properties-real.json", createGoodPropertiesJson().toStyledString()); symlink("properties-real.json", (session->responseDir + "/properties.json").c_str()); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::signalFinish, this)); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure(containsSubstring(e.getSummary(), "Cannot open 'properties.json'")); } } /***** Success response handling *****/ TEST_METHOD(30) { set_test_name("The result object contains basic information such as FDs and time"); init(SPAWN_DIRECTLY); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::execute, this)); createFile(session->responseDir + "/properties.json", createGoodPropertiesJson().toStyledString()); createFile(session->responseDir + "/steps/subprocess_listen/state", "STEP_PERFORMED"); signalFinish(); EVENTUALLY(5, result = counter == 1; ); ensure_equals(session->result.pid, pid); ensure(session->result.spawnStartTime != 0); ensure(session->result.spawnEndTime >= session->result.spawnStartTime); ensure(session->result.spawnStartTimeMonotonic != 0); ensure(session->result.spawnEndTimeMonotonic >= session->result.spawnStartTimeMonotonic); } TEST_METHOD(31) { set_test_name("The result object contains sockets specified in properties.json"); init(SPAWN_DIRECTLY); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::execute, this)); createFile(session->responseDir + "/properties.json", createGoodPropertiesJson().toStyledString()); createFile(session->responseDir + "/steps/subprocess_listen/state", "STEP_PERFORMED"); signalFinish(); EVENTUALLY(5, result = counter == 1; ); ensure_equals(session->result.sockets.size(), 1u); ensure_equals(session->result.sockets[0].address, "tcp://127.0.0.1:3000"); ensure_equals(session->result.sockets[0].protocol, "http"); ensure_equals(session->result.sockets[0].concurrency, 1); ensure(session->result.sockets[0].acceptHttpRequests); } TEST_METHOD(32) { set_test_name("If the app is generic, it automatically registers the free port as a request-handling socket"); FreePortDebugSupport debugSupport; this->debugSupport = &debugSupport; config.genericApp = true; init(SPAWN_DIRECTLY); debugSupport.test = this; debugSupport.session = session.get(); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::execute, this)); EVENTUALLY(1, result = counter == 1; ); server.assign(createTcpServer("127.0.0.1", debugSupport.expectedStartPort.get()), NULL, 0); EVENTUALLY(1, result = counter == 2; ); ensure_equals(session->result.sockets.size(), 1u); ensure_equals(session->result.sockets[0].address, "tcp://127.0.0.1:" + toString(session->expectedStartPort)); ensure_equals(session->result.sockets[0].protocol, "http"); ensure_equals(session->result.sockets[0].concurrency, -1); ensure(session->result.sockets[0].acceptHttpRequests); } TEST_METHOD(33) { set_test_name("If findFreePort is true, it automatically registers the free port as a request-handling socket"); FreePortDebugSupport debugSupport; this->debugSupport = &debugSupport; config.findFreePort = true; init(SPAWN_DIRECTLY); debugSupport.test = this; debugSupport.session = session.get(); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::execute, this)); EVENTUALLY(1, result = counter == 1; ); server.assign(createTcpServer("127.0.0.1", debugSupport.expectedStartPort.get()), NULL, 0); EVENTUALLY(1, result = counter == 2; ); ensure_equals(session->result.sockets.size(), 1u); ensure_equals(session->result.sockets[0].address, "tcp://127.0.0.1:" + toString(session->expectedStartPort)); ensure_equals(session->result.sockets[0].protocol, "http"); ensure_equals(session->result.sockets[0].concurrency, -1); ensure(session->result.sockets[0].acceptHttpRequests); } TEST_METHOD(34) { set_test_name("It raises an error if we expected the subprocess to create a properties.json," " but the file does not conform to the required format"); init(SPAWN_DIRECTLY); createFile(session->responseDir + "/properties.json", "{ \"sockets\": {} }"); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::signalFinish, this)); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure(containsSubstring(e.getSummary(), "'sockets' must be an array")); } } TEST_METHOD(35) { set_test_name("It raises an error if we expected the subprocess to specify at" " least one request-handling socket in properties.json, yet the file does" " not specify any"); Json::Value socket, doc; socket["address"] = "tcp://127.0.0.1:3000"; socket["protocol"] = "http"; socket["concurrency"] = 1; doc["sockets"].append(socket); init(SPAWN_DIRECTLY); createFile(session->responseDir + "/properties.json", doc.toStyledString()); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::signalFinish, this)); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure(containsSubstring(e.getSummary(), "the application did not report any sockets to receive requests on")); } } TEST_METHOD(36) { set_test_name("It raises an error if we expected the subprocess to specify at" " least one request-handling socket in properties.json, yet properties.json" " does not exist"); init(SPAWN_DIRECTLY); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::signalFinish, this)); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure(containsSubstring(e.getSummary(), "sockets are not supplied")); } } TEST_METHOD(37) { set_test_name("It raises an error if we expected the subprocess to specify at" " least one preloader command socket in properties.json, yet the file does" " not specify any"); Json::Value socket, doc; socket["address"] = "tcp://127.0.0.1:3000"; socket["protocol"] = "http"; socket["concurrency"] = 1; doc["sockets"].append(socket); init(START_PRELOADER); createFile(session->responseDir + "/properties.json", doc.toStyledString()); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::signalFinish, this)); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure(containsSubstring(e.getSummary(), "the application did not report any sockets to receive preloader commands on")); } } TEST_METHOD(38) { set_test_name("It raises an error if we expected the subprocess to specify at" " least one preloader command socket in properties.json, yet properties.json" " does not exist"); init(START_PRELOADER); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::signalFinish, this)); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure(containsSubstring(e.getSummary(), "sockets are not supplied")); } } TEST_METHOD(39) { set_test_name("It raises an error if properties.json specifies a Unix domain socket" " that is not located in the apps.s subdir of the instance directory"); TempDir tmpDir("tmp.instance"); context.instanceDir = absolutizePath("tmp.instance"); init(SPAWN_DIRECTLY); Json::Value doc = createGoodPropertiesJson(); doc["sockets"][0]["address"] = "unix:/foo"; createFile(session->responseDir + "/properties.json", doc.toStyledString()); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::signalFinish, this)); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure(containsSubstring(e.getSummary(), "must be an absolute path to a file in")); } } TEST_METHOD(40) { set_test_name("It raises an error if properties.json specifies a Unix domain socket" " that is not owned by the app"); if (geteuid() != 0) { return; } TempDir tmpDir("tmp.instance"); mkdir("tmp.instance/apps.s", 0700); string socketPath = absolutizePath("tmp.instance/apps.s/foo.sock"); init(SPAWN_DIRECTLY); Json::Value doc = createGoodPropertiesJson(); doc["sockets"][0]["address"] = "unix:" + socketPath; createFile(session->responseDir + "/properties.json", doc.toStyledString()); safelyClose(createUnixServer(socketPath)); chown(socketPath.c_str(), 1, 1); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::signalFinish, this)); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure("(1)", containsSubstring(e.getSummary(), "must be owned by user")); } } /***** Error response handling *****/ TEST_METHOD(50) { set_test_name("It raises an error if the application responded with an error"); init(SPAWN_DIRECTLY); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::signalFinishWithError, this)); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure_equals(e.getSummary(), "The web application aborted with an error during startup."); } } TEST_METHOD(51) { set_test_name("The exception contains error messages provided by the application"); init(SPAWN_DIRECTLY); writeFile(session->workDir->getPath() + "/response/error/summary", "the summary"); writeFile(session->workDir->getPath() + "/response/error/problem_description.html", "the problem description"); writeFile(session->workDir->getPath() + "/response/error/solution_description.html", "the solution description"); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::signalFinishWithError, this)); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure_equals(e.getSummary(), "the summary"); ensure_equals(e.getProblemDescriptionHTML(), "the problem description"); ensure_equals(e.getSolutionDescriptionHTML(), "the solution description"); } } TEST_METHOD(52) { set_test_name("The exception describes which steps in the journey had failed"); init(SPAWN_DIRECTLY); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::signalFinishWithError, this)); try { execute(); } catch (const SpawnException &e) { ensure_equals(e.getJourney().getFirstFailedStep(), SUBPROCESS_BEFORE_FIRST_EXEC); } } TEST_METHOD(53) { set_test_name("The exception contains the subprocess' output"); Json::Value config; vector<ConfigKit::Error> errors; LoggingKit::ConfigChangeRequest req; config["app_output_log_level"] = "debug"; if (LoggingKit::context->prepareConfigChange(config, errors, req)) { LoggingKit::context->commitConfigChange(req); } else { P_BUG("Error configuring LoggingKit: " << ConfigKit::toString(errors)); } init(SPAWN_DIRECTLY); stdoutAndErr = createPipe(__FILE__, __LINE__); writeExact(stdoutAndErr.second, "oh no"); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::signalFinishWithError, this)); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure_equals(e.getStdoutAndErrData(), "oh no"); } } TEST_METHOD(54) { set_test_name("The exception contains the subprocess' environment variables dump"); init(SPAWN_DIRECTLY); writeFile(session->workDir->getPath() + "/envdump/envvars", "the env dump"); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::signalFinishWithError, this)); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure_equals(e.getSubprocessEnvvars(), "the env dump"); } } TEST_METHOD(55) { set_test_name("If the subprocess fails without setting a specific" " journey step to the ERRORED state," " and there is a subprocess journey step in the IN_PROGRESS state," " then we set that latter step to the ERRORED state"); init(SPAWN_DIRECTLY); pid = fork(); if (pid == 0) { // Exit child _exit(1); } createFile(session->responseDir + "/steps/subprocess_before_first_exec/state", "STEP_PERFORMED"); createFile(session->responseDir + "/steps/subprocess_before_first_exec/duration", "1"); createFile(session->responseDir + "/steps/subprocess_spawn_env_setupper_before_shell/state", "STEP_IN_PROGRESS"); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure_equals("SPAWNING_KIT_HANDSHAKE_PERFORM is in the IN_PROGRESS state", e.getJourney().getStepInfo(SPAWNING_KIT_HANDSHAKE_PERFORM).state, STEP_IN_PROGRESS); ensure_equals("SUBPROCESS_BEFORE_FIRST_EXEC is in the PERFORMED state", e.getJourney().getStepInfo(SUBPROCESS_BEFORE_FIRST_EXEC).state, STEP_PERFORMED); ensure_equals("SUBPROCESS_SPAWN_ENV_SETUPPER_BEFORE_SHELL is in the ERRORED state", e.getJourney().getStepInfo(SUBPROCESS_SPAWN_ENV_SETUPPER_BEFORE_SHELL).state, STEP_ERRORED); ensure_equals("SUBPROCESS_OS_SHELL is in the NOT_STARTED state", e.getJourney().getStepInfo(SUBPROCESS_OS_SHELL).state, STEP_NOT_STARTED); ensure_equals("SUBPROCESS_SPAWN_ENV_SETUPPER_AFTER_SHELL is in the NOT_STARTED state", e.getJourney().getStepInfo(SUBPROCESS_SPAWN_ENV_SETUPPER_AFTER_SHELL).state, STEP_NOT_STARTED); } } TEST_METHOD(56) { set_test_name("If the subprocess fails without setting a specific" " journey step to the ERRORED state," " and there is no subprocess journey step in the IN_PROGRESS state," " and no subprocess journey steps are in the PERFORMED state," " then we set the first subprocess journey step to the ERRORED state"); init(SPAWN_DIRECTLY); pid = fork(); if (pid == 0) { // Exit child _exit(1); } try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure_equals("SPAWNING_KIT_HANDSHAKE_PERFORM is in the IN_PROGRESS state", e.getJourney().getStepInfo(SPAWNING_KIT_HANDSHAKE_PERFORM).state, STEP_IN_PROGRESS); ensure_equals("SUBPROCESS_BEFORE_FIRST_EXEC is in the ERRORED state", e.getJourney().getStepInfo(SUBPROCESS_BEFORE_FIRST_EXEC).state, STEP_ERRORED); ensure_equals("SUBPROCESS_SPAWN_ENV_SETUPPER_BEFORE_SHELL is in the NOT_STARTED state", e.getJourney().getStepInfo(SUBPROCESS_SPAWN_ENV_SETUPPER_BEFORE_SHELL).state, STEP_NOT_STARTED); } } TEST_METHOD(57) { set_test_name("If the subprocess fails without setting a specific" " journey step to the ERRORED state," " and there is no subprocess journey step in the IN_PROGRESS state," " and some but not all subprocess journey steps are in the PERFORMED state," " then we set the step that comes right after the last PERFORMED step," " to the ERRORED state"); init(SPAWN_DIRECTLY); pid = fork(); if (pid == 0) { // Exit child _exit(1); } createFile(session->responseDir + "/steps/subprocess_before_first_exec/state", "STEP_PERFORMED"); createFile(session->responseDir + "/steps/subprocess_before_first_exec/duration", "1"); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure_equals("SPAWNING_KIT_HANDSHAKE_PERFORM is in the IN_PROGRESS state", e.getJourney().getStepInfo(SPAWNING_KIT_HANDSHAKE_PERFORM).state, STEP_IN_PROGRESS); ensure_equals("SUBPROCESS_BEFORE_FIRST_EXEC is in the PERFORMED state", e.getJourney().getStepInfo(SUBPROCESS_BEFORE_FIRST_EXEC).state, STEP_PERFORMED); ensure_equals("SUBPROCESS_SPAWN_ENV_SETUPPER_BEFORE_SHELL is in the ERRORED state", e.getJourney().getStepInfo(SUBPROCESS_SPAWN_ENV_SETUPPER_BEFORE_SHELL).state, STEP_ERRORED); ensure_equals("SUBPROCESS_OS_SHELL is in the NOT_STARTED state", e.getJourney().getStepInfo(SUBPROCESS_OS_SHELL).state, STEP_NOT_STARTED); ensure_equals("SUBPROCESS_SPAWN_ENV_SETUPPER_AFTER_SHELL is in the NOT_STARTED state", e.getJourney().getStepInfo(SUBPROCESS_SPAWN_ENV_SETUPPER_AFTER_SHELL).state, STEP_NOT_STARTED); } } TEST_METHOD(58) { set_test_name("If the subprocess fails without setting a specific" " journey step to the ERRORED state," " and there is no subprocess journey step in the IN_PROGRESS state," " and all subprocess journey steps are in the PERFORMED state," " then we set the last subprocess step to the ERRORED state"); init(SPAWN_DIRECTLY); pid = fork(); if (pid == 0) { // Exit child _exit(1); } JourneyStep firstStep = getFirstSubprocessJourneyStep(); JourneyStep lastStep = getLastSubprocessJourneyStep(); JourneyStep step; for (step = firstStep; step < lastStep; step = JourneyStep((int) step + 1)) { if (!session->journey.hasStep(step)) { continue; } createFile(session->responseDir + "/steps/" + journeyStepToStringLowerCase(step) + "/state", "STEP_PERFORMED"); createFile(session->responseDir + "/steps/" + journeyStepToStringLowerCase(step) + "/duration", "1"); } try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure_equals("SPAWNING_KIT_HANDSHAKE_PERFORM is in the IN_PROGRESS state", e.getJourney().getStepInfo(SPAWNING_KIT_HANDSHAKE_PERFORM).state, STEP_IN_PROGRESS); ensure_equals("SUBPROCESS_BEFORE_FIRST_EXEC is in the PERFORMED state", e.getJourney().getStepInfo(SUBPROCESS_BEFORE_FIRST_EXEC).state, STEP_PERFORMED); ensure_equals("SUBPROCESS_SPAWN_ENV_SETUPPER_BEFORE_SHELL is in the PERFORMED state", e.getJourney().getStepInfo(SUBPROCESS_SPAWN_ENV_SETUPPER_BEFORE_SHELL).state, STEP_PERFORMED); ensure_equals("SUBPROCESS_OS_SHELL is in the PERFORMED state", e.getJourney().getStepInfo(SUBPROCESS_OS_SHELL).state, STEP_PERFORMED); ensure_equals("SUBPROCESS_SPAWN_ENV_SETUPPER_AFTER_SHELL is in the PERFORMED state", e.getJourney().getStepInfo(SUBPROCESS_SPAWN_ENV_SETUPPER_AFTER_SHELL).state, STEP_PERFORMED); ensure_equals("SUBPROCESS_APP_LOAD_OR_EXEC is in the PERFORMED state", e.getJourney().getStepInfo(SUBPROCESS_APP_LOAD_OR_EXEC).state, STEP_PERFORMED); ensure_equals("SUBPROCESS_APP_LOAD_OR_EXEC is in the PERFORMED state", e.getJourney().getStepInfo(SUBPROCESS_APP_LOAD_OR_EXEC).state, STEP_PERFORMED); ensure_equals("SUBPROCESS_LISTEN is in the PERFORMED state", e.getJourney().getStepInfo(SUBPROCESS_LISTEN).state, STEP_PERFORMED); ensure_equals("SUBPROCESS_FINISH is in the ERRORED state", e.getJourney().getStepInfo(SUBPROCESS_FINISH).state, STEP_ERRORED); } } }
31.630701
122
0.727247
m5o
dc1b7cd50823d8f78d0abed3fa4ea84afd42ef00
7,019
cxx
C++
applications/js_cdi_server/targets/js.emscripten/main.cxx
balazsracz/openmrn
338f5dcbafeff6d171b2787b291d1904f2c45965
[ "BSD-2-Clause" ]
34
2015-05-23T03:57:56.000Z
2022-03-27T03:48:48.000Z
applications/js_cdi_server/targets/js.emscripten/main.cxx
balazsracz/openmrn
338f5dcbafeff6d171b2787b291d1904f2c45965
[ "BSD-2-Clause" ]
214
2015-07-05T05:06:55.000Z
2022-02-06T14:53:14.000Z
applications/js_cdi_server/targets/js.emscripten/main.cxx
balazsracz/openmrn
338f5dcbafeff6d171b2787b291d1904f2c45965
[ "BSD-2-Clause" ]
38
2015-08-28T05:32:07.000Z
2021-07-06T16:47:23.000Z
/** \copyright * Copyright (c) 2013, Balazs Racz * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * \file main.cxx * * An application which acts as an openlcb hub with the GC protocol. * * @author Balazs Racz * @date 3 Aug 2013 */ #include <emscripten.h> #include <emscripten/bind.h> #include <emscripten/val.h> #include <memory> #include "os/os.h" #include "utils/constants.hxx" #include "utils/Hub.hxx" #include "utils/GridConnectHub.hxx" #include "utils/GcTcpHub.hxx" #include "utils/JSTcpHub.hxx" #include "utils/JSTcpClient.hxx" #include "utils/FileUtils.hxx" #include "executor/Executor.hxx" #include "executor/Service.hxx" #include "openlcb/SimpleStack.hxx" #include "openlcb/SimpleNodeInfoMockUserFile.hxx" namespace openlcb { extern const SimpleNodeStaticValues SNIP_STATIC_DATA = { 4, "OpenMRN", "CDI test server", "node.js", "1.00"}; } openlcb::MockSNIPUserFile snip_user_file( "Default user name", "Default user description"); const char *const openlcb::SNIP_DYNAMIC_FILENAME = openlcb::MockSNIPUserFile::snip_user_file_path; const uint64_t node_id_base = 0x050101011800ULL; uint64_t node_id = node_id_base | 0xF3; OVERRIDE_CONST(gc_generate_newlines, 1); int port = -1; int upstream_port = 12021; const char *upstream_host = nullptr; const char *cdi_file = nullptr; namespace openlcb { /// This symbol contains the embedded text of the CDI xml file. const char CDI_DATA[128*1024] = {0,}; } void usage(const char *e) { fprintf(stderr, "Usage: %s [-p port] [-u hub_host [-q hub_port]] [-n id] -x cdi_file\n\n", e); fprintf(stderr, "\n\nArguments:\n"); fprintf(stderr, "\t-c filename is the filename for the CDI (xml text).\n"); fprintf(stderr, "\t-p port Opens a TCP server on this port and listens for clients connecting with a GridConnect protocol (like a hub).\n"); /* fprintf(stderr, "\t-d device is a path to a physical device doing " "serial-CAN or USB-CAN. If specified, opens device and " "adds it to the hub.\n");*/ fprintf(stderr, "\t-u upstream_host is the host name for a TCP GridConnect " "hub. If specified, this program will connect to that hub for the CAN-bus.\n"); fprintf(stderr, "\t-q upstream_port is the port number for the upstream hub.\n"); fprintf(stderr, "\t-n id sets the lowest 8 bits of the node id. Valid values: 0..255. Default: 243.\n"); exit(1); } void parse_args(int argc, char *argv[]) { int opt; while ((opt = getopt(argc, argv, "hp:u:q:x:n:")) >= 0) { switch (opt) { case 'h': usage(argv[0]); break; /* case 'd': device_path = optarg; break;*/ case 'p': port = atoi(optarg); break; case 'u': upstream_host = optarg; break; case 'q': upstream_port = atoi(optarg); break; case 'n': node_id = node_id_base + atoi(optarg); break; case 'x': cdi_file = optarg; break; default: fprintf(stderr, "Unknown option %c\n", opt); usage(argv[0]); } } if (!cdi_file) { fprintf(stderr, "cdi_file is not specified\n"); usage(argv[0]); } string contents = read_file_to_string(cdi_file); if (contents.size() + 1 <= sizeof(openlcb::CDI_DATA)) { memcpy((char*)openlcb::CDI_DATA, contents.c_str(), contents.size() + 1); } else { DIE("CDI file too large."); } } /** Entry point to application. * @param argc number of command line arguments * @param argv array of command line arguments * @return 0, should never return */ int appl_main(int argc, char *argv[]) { parse_args(argc, argv); openlcb::SimpleCanStack stack(node_id); const size_t configlen = 16*1024; uint8_t* cdispace = new uint8_t[configlen]; memset(cdispace, 0, configlen); openlcb::ReadWriteMemoryBlock ramblock(cdispace, configlen); stack.memory_config_handler()->registry()->insert(nullptr, openlcb::MemoryConfigDefs::SPACE_CONFIG, &ramblock); GcPacketPrinter packet_printer(stack.can_hub(), false); std::unique_ptr<JSTcpHub> hub; if (port > 0) { hub.reset(new JSTcpHub(stack.can_hub(), port)); } std::unique_ptr<JSTcpClient> client; if (upstream_host) { client.reset(new JSTcpClient(stack.can_hub(), upstream_host, upstream_port)); } /* int dev_fd = 0; while (1) { if (device_path && !dev_fd) { dev_fd = ::open(device_path, O_RDWR); if (dev_fd > 0) { // Sets up the terminal in raw mode. Otherwise linux might echo // characters coming in from the device and that will make // packets go back to where they came from. HASSERT(!tcflush(dev_fd, TCIOFLUSH)); struct termios settings; HASSERT(!tcgetattr(dev_fd, &settings)); cfmakeraw(&settings); HASSERT(!tcsetattr(dev_fd, TCSANOW, &settings)); LOG(INFO, "Opened device %s.\n", device_path); create_gc_port_for_can_hub(&can_hub0, dev_fd); } else { LOG(ERROR, "Failed to open device %s: %s\n", device_path, strerror(errno)); } } sleep(1); }*/ stack.loop_executor(); return 0; }
35.271357
148
0.618464
balazsracz
dc2090a8c236cb7ff67543336f86908555f5fc1b
335
cpp
C++
books/tech/cpp/std-11/b_sutherland-cpp_recipes/ch_10-memory/recipe_10.2-using_stack_memory/02-class_varibles_on_the_stack/main.cpp
ordinary-developer/education
1b1f40dacab873b28ee01dfa33a9bd3ec4cfed58
[ "MIT" ]
1
2017-05-04T08:23:46.000Z
2017-05-04T08:23:46.000Z
books/techno/cpp/__intermediate/cpp_recipes_a_problem_solution_approach_b_shutherland/code/ch_10-MEMORY/recipe_10.2-using_stack_memory/02-class_varibles_on_the_stack/main.cpp
ordinary-developer/lin_education
13d65b20cdbc3e5467b2383e5c09c73bbcdcb227
[ "MIT" ]
null
null
null
books/techno/cpp/__intermediate/cpp_recipes_a_problem_solution_approach_b_shutherland/code/ch_10-MEMORY/recipe_10.2-using_stack_memory/02-class_varibles_on_the_stack/main.cpp
ordinary-developer/lin_education
13d65b20cdbc3e5467b2383e5c09c73bbcdcb227
[ "MIT" ]
null
null
null
#include <iostream> class MyClass { public: MyClass() { std::cout << "Constructor called!" << std::endl; } ~MyClass() { std::cout << "Destructor called!" << std::endl; } }; int main() { MyClass myClass; std::cout << "Function body!" << std::endl; return 0; }
16.75
60
0.483582
ordinary-developer
dc2128e0d36510297a49c0ea322fba2baa90d13e
6,713
cc
C++
chrome/browser/extensions/api/identity/identity_mint_queue_unittest.cc
nagineni/chromium-crosswalk
5725642f1c67d0f97e8613ec1c3e8107ab53fdf8
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
9
2018-09-21T05:36:12.000Z
2021-11-15T15:14:36.000Z
chrome/browser/extensions/api/identity/identity_mint_queue_unittest.cc
nagineni/chromium-crosswalk
5725642f1c67d0f97e8613ec1c3e8107ab53fdf8
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-12-13T19:44:12.000Z
2021-12-13T19:44:12.000Z
chrome/browser/extensions/api/identity/identity_mint_queue_unittest.cc
nagineni/chromium-crosswalk
5725642f1c67d0f97e8613ec1c3e8107ab53fdf8
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
4
2017-04-05T01:52:03.000Z
2022-02-13T17:58:45.000Z
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/api/identity/identity_mint_queue.h" #include <vector> #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using extensions::IdentityMintRequestQueue; namespace { class MockRequest : public extensions::IdentityMintRequestQueue::Request { public: MOCK_METHOD1(StartMintToken, void(IdentityMintRequestQueue::MintType)); }; } // namespace TEST(IdentityMintQueueTest, SerialRequests) { IdentityMintRequestQueue::MintType type = IdentityMintRequestQueue::MINT_TYPE_NONINTERACTIVE; IdentityMintRequestQueue queue; std::string extension_id("ext_id"); MockRequest request1; MockRequest request2; EXPECT_CALL(request1, StartMintToken(type)).Times(1); queue.RequestStart(type, extension_id, std::set<std::string>(), &request1); queue.RequestComplete(type, extension_id, std::set<std::string>(), &request1); EXPECT_CALL(request2, StartMintToken(type)).Times(1); queue.RequestStart(type, extension_id, std::set<std::string>(), &request2); queue.RequestComplete(type, extension_id, std::set<std::string>(), &request2); } TEST(IdentityMintQueueTest, InteractiveType) { IdentityMintRequestQueue::MintType type = IdentityMintRequestQueue::MINT_TYPE_INTERACTIVE; IdentityMintRequestQueue queue; std::string extension_id("ext_id"); MockRequest request1; EXPECT_CALL(request1, StartMintToken(type)).Times(1); queue.RequestStart(type, extension_id, std::set<std::string>(), &request1); queue.RequestComplete(type, extension_id, std::set<std::string>(), &request1); } TEST(IdentityMintQueueTest, ParallelRequests) { IdentityMintRequestQueue::MintType type = IdentityMintRequestQueue::MINT_TYPE_NONINTERACTIVE; IdentityMintRequestQueue queue; std::string extension_id("ext_id"); MockRequest request1; MockRequest request2; MockRequest request3; EXPECT_CALL(request1, StartMintToken(type)).Times(1); queue.RequestStart(type, extension_id, std::set<std::string>(), &request1); queue.RequestStart(type, extension_id, std::set<std::string>(), &request2); queue.RequestStart(type, extension_id, std::set<std::string>(), &request3); EXPECT_CALL(request2, StartMintToken(type)).Times(1); queue.RequestComplete(type, extension_id, std::set<std::string>(), &request1); EXPECT_CALL(request3, StartMintToken(type)).Times(1); queue.RequestComplete(type, extension_id, std::set<std::string>(), &request2); queue.RequestComplete(type, extension_id, std::set<std::string>(), &request3); } TEST(IdentityMintQueueTest, ParallelRequestsFromTwoExtensions) { IdentityMintRequestQueue::MintType type = IdentityMintRequestQueue::MINT_TYPE_NONINTERACTIVE; IdentityMintRequestQueue queue; std::string extension_id1("ext_id_1"); std::string extension_id2("ext_id_2"); MockRequest request1; MockRequest request2; EXPECT_CALL(request1, StartMintToken(type)).Times(1); EXPECT_CALL(request2, StartMintToken(type)).Times(1); queue.RequestStart(type, extension_id1, std::set<std::string>(), &request1); queue.RequestStart(type, extension_id2, std::set<std::string>(), &request2); queue.RequestComplete(type, extension_id1, std::set<std::string>(), &request1); queue.RequestComplete(type, extension_id2, std::set<std::string>(), &request2); } TEST(IdentityMintQueueTest, ParallelRequestsForDifferentScopes) { IdentityMintRequestQueue::MintType type = IdentityMintRequestQueue::MINT_TYPE_NONINTERACTIVE; IdentityMintRequestQueue queue; std::string extension_id("ext_id"); MockRequest request1; MockRequest request2; std::set<std::string> scopes1; std::set<std::string> scopes2; scopes1.insert("a"); scopes1.insert("b"); scopes2.insert("a"); EXPECT_CALL(request1, StartMintToken(type)).Times(1); EXPECT_CALL(request2, StartMintToken(type)).Times(1); queue.RequestStart(type, extension_id, scopes1, &request1); queue.RequestStart(type, extension_id, scopes2, &request2); queue.RequestComplete(type, extension_id, scopes1, &request1); queue.RequestComplete(type, extension_id, scopes2, &request2); } TEST(IdentityMintQueueTest, KeyComparisons) { std::string extension_id1("ext_id_1"); std::string extension_id2("ext_id_2"); std::set<std::string> scopes1; std::set<std::string> scopes2; std::set<std::string> scopes3; scopes1.insert("a"); scopes1.insert("b"); scopes2.insert("a"); std::vector<std::string> ids; ids.push_back(extension_id1); ids.push_back(extension_id2); std::vector<std::set<std::string> > scopesets; scopesets.push_back(scopes1); scopesets.push_back(scopes2); scopesets.push_back(scopes3); std::vector<IdentityMintRequestQueue::RequestKey> keys; typedef std::vector< IdentityMintRequestQueue::RequestKey>::const_iterator RequestKeyIterator; std::vector<std::string>::const_iterator id_it; std::vector<std::set<std::string> >::const_iterator scope_it; for (id_it = ids.begin(); id_it != ids.end(); ++id_it) { for (scope_it = scopesets.begin(); scope_it != scopesets.end(); ++scope_it) { keys.push_back(IdentityMintRequestQueue::RequestKey( IdentityMintRequestQueue::MINT_TYPE_NONINTERACTIVE, *id_it, *scope_it)); keys.push_back(IdentityMintRequestQueue::RequestKey( IdentityMintRequestQueue::MINT_TYPE_INTERACTIVE, *id_it, *scope_it)); } } // keys should not be less than themselves for (RequestKeyIterator it = keys.begin(); it != keys.end(); ++it) { EXPECT_FALSE(*it < *it); } // keys should not equal different keys for (RequestKeyIterator it1 = keys.begin(); it1 != keys.end(); ++it1) { RequestKeyIterator it2 = it1; for (++it2; it2 != keys.end(); ++it2) { EXPECT_TRUE(*it1 < *it2 || *it2 < *it1); EXPECT_FALSE(*it1 < *it2 && *it2 < *it1); } } } TEST(IdentityMintQueueTest, Empty) { IdentityMintRequestQueue::MintType type = IdentityMintRequestQueue::MINT_TYPE_INTERACTIVE; IdentityMintRequestQueue queue; std::string extension_id("ext_id"); MockRequest request1; EXPECT_TRUE(queue.empty(type, extension_id, std::set<std::string>())); EXPECT_CALL(request1, StartMintToken(type)).Times(1); queue.RequestStart(type, extension_id, std::set<std::string>(), &request1); EXPECT_FALSE(queue.empty(type, extension_id, std::set<std::string>())); queue.RequestComplete(type, extension_id, std::set<std::string>(), &request1); EXPECT_TRUE(queue.empty(type, extension_id, std::set<std::string>())); }
36.091398
80
0.731864
nagineni
dc218df738ec770a57a06c101e884a29706610e6
1,106
cpp
C++
homework/Propazhin/04/matrix.cpp
nkotelevskii/msu_cpp_spring_2018
b5d84447f9b8c7f3615b421c51cf4192f1b90342
[ "MIT" ]
12
2018-02-20T15:25:12.000Z
2022-02-15T03:31:55.000Z
homework/Propazhin/04/matrix.cpp
nkotelevskii/msu_cpp_spring_2018
b5d84447f9b8c7f3615b421c51cf4192f1b90342
[ "MIT" ]
1
2018-02-26T12:40:47.000Z
2018-02-26T12:40:47.000Z
homework/Propazhin/04/matrix.cpp
nkotelevskii/msu_cpp_spring_2018
b5d84447f9b8c7f3615b421c51cf4192f1b90342
[ "MIT" ]
33
2018-02-20T15:25:11.000Z
2019-02-13T22:33:36.000Z
#include "matrix.h" #include <iostream> Matrix::~Matrix() { for (size_t i = 0; i < cols; i++) delete[] arr[i]; delete[] arr; } Matrix& Matrix::operator *= (int k) { for (size_t i = 0; i < cols; i++) for (size_t j = 0; j < rows; j++) arr[i][j] *= k; return *this; } bool Matrix::operator == (const Matrix &m) { if (rows != m.rows || cols != m.cols) return false; for (size_t i = 0; i < cols; i++) for (size_t j = 0; j < rows; j++) if (arr[i][j] != m.arr[i][j]) return false; return true; } bool Matrix::operator != (const Matrix &m) { return !(*this == m); } Row Matrix::operator[](size_t j) { if (j >= cols) throw std::out_of_range(""); return Row(arr[j], rows); } const Row Matrix::operator[](size_t j) const { if (j >= cols) throw std::out_of_range(""); return Row(arr[j], rows); } int& Row::operator [](size_t i) { if (i >= rows) throw std::out_of_range(""); return row[i]; } const int& Row::operator [](size_t i) const { if (i >= rows) throw std::out_of_range(""); return row[i]; }
19.75
55
0.536166
nkotelevskii
dc22a5090698cd215315a989cc3f41eb0f086031
2,086
cpp
C++
Engine/Source/Runtime/AnimGraphRuntime/Private/BoneControllers/AnimNode_ObserveBone.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
Engine/Source/Runtime/AnimGraphRuntime/Private/BoneControllers/AnimNode_ObserveBone.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
2
2015-06-21T17:38:11.000Z
2015-06-22T20:54:42.000Z
Engine/Source/Runtime/AnimGraphRuntime/Private/BoneControllers/AnimNode_ObserveBone.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. #include "AnimGraphRuntimePrivatePCH.h" #include "BoneControllers/AnimNode_ObserveBone.h" #include "AnimationRuntime.h" ///////////////////////////////////////////////////// // FAnimNode_ObserveBone FAnimNode_ObserveBone::FAnimNode_ObserveBone() : DisplaySpace(BCS_ComponentSpace) , bRelativeToRefPose(false) , Translation(FVector::ZeroVector) , Rotation(FRotator::ZeroRotator) , Scale(FVector(1.0f)) { } void FAnimNode_ObserveBone::GatherDebugData(FNodeDebugData& DebugData) { const FString DebugLine = FString::Printf(TEXT("(Bone: %s has T(%s), R(%s), S(%s))"), *BoneToObserve.BoneName.ToString(), *Translation.ToString(), *Rotation.Euler().ToString(), *Scale.ToString()); DebugData.AddDebugItem(DebugLine); ComponentPose.GatherDebugData(DebugData); } void FAnimNode_ObserveBone::EvaluateBoneTransforms(USkeletalMeshComponent* SkelComp, FCSPose<FCompactPose>& MeshBases, TArray<FBoneTransform>& OutBoneTransforms) { const FBoneContainer BoneContainer = MeshBases.GetPose().GetBoneContainer(); const FCompactPoseBoneIndex BoneIndex = BoneToObserve.GetCompactPoseIndex(BoneContainer); FTransform BoneTM = MeshBases.GetComponentSpaceTransform(BoneIndex); // Convert to the specific display space if necessary FAnimationRuntime::ConvertCSTransformToBoneSpace(SkelComp, MeshBases, BoneTM, BoneIndex, DisplaySpace); // Convert to be relative to the ref pose if necessary if (bRelativeToRefPose) { const FTransform& SourceOrigRef = BoneContainer.GetRefPoseArray()[BoneToObserve.BoneIndex]; BoneTM = BoneTM.GetRelativeTransform(SourceOrigRef); } // Cache off the values for display Translation = BoneTM.GetTranslation(); Rotation = BoneTM.GetRotation().Rotator(); Scale = BoneTM.GetScale3D(); } bool FAnimNode_ObserveBone::IsValidToEvaluate(const USkeleton* Skeleton, const FBoneContainer& RequiredBones) { return (BoneToObserve.IsValid(RequiredBones)); } void FAnimNode_ObserveBone::InitializeBoneReferences(const FBoneContainer& RequiredBones) { BoneToObserve.Initialize(RequiredBones); }
35.355932
197
0.778523
PopCap
dc2412763be970d0ac53c0a3664feb704b6905b7
1,317
hpp
C++
kernel/src/modelingTools/RelationTypes.hpp
bremond/siconos
8deea56ff6779379f4f69e0376d24a81562a42d4
[ "Apache-2.0" ]
null
null
null
kernel/src/modelingTools/RelationTypes.hpp
bremond/siconos
8deea56ff6779379f4f69e0376d24a81562a42d4
[ "Apache-2.0" ]
null
null
null
kernel/src/modelingTools/RelationTypes.hpp
bremond/siconos
8deea56ff6779379f4f69e0376d24a81562a42d4
[ "Apache-2.0" ]
null
null
null
/* Siconos is a program dedicated to modeling, simulation and control * of non smooth dynamical systems. * * Copyright 2016 INRIA. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*! \file RelationTypes.hpp \brief enum of the available types and subtypes for relations, plugin names ... */ /*! \file RelationTypes.hpp Include files related to the different types of relations */ #ifndef RelationTypes_hpp #define RelationTypes_hpp #include "FirstOrderNonLinearR.hpp" #include "FirstOrderType1R.hpp" #include "FirstOrderType2R.hpp" #include "FirstOrderLinearR.hpp" #include "FirstOrderLinearTIR.hpp" #include "LagrangianLinearTIR.hpp" #include "LagrangianScleronomousR.hpp" #include "LagrangianRheonomousR.hpp" #include "LagrangianCompliantR.hpp" #include "LagrangianCompliantLinearTIR.hpp" #endif
31.357143
75
0.772969
bremond
dc25abbea41d1af3961493eec08d89258cc87558
19,392
cc
C++
rocksdb-6.14.5-unmodified/table/block_based/partitioned_filter_block.cc
cssl-unist/tweezer
3a6c2c65ff61a525150aa2b1ae30b561ac79d241
[ "MIT" ]
null
null
null
rocksdb-6.14.5-unmodified/table/block_based/partitioned_filter_block.cc
cssl-unist/tweezer
3a6c2c65ff61a525150aa2b1ae30b561ac79d241
[ "MIT" ]
null
null
null
rocksdb-6.14.5-unmodified/table/block_based/partitioned_filter_block.cc
cssl-unist/tweezer
3a6c2c65ff61a525150aa2b1ae30b561ac79d241
[ "MIT" ]
null
null
null
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved. // This source code is licensed under both the GPLv2 (found in the // COPYING file in the root directory) and Apache 2.0 License // (found in the LICENSE.Apache file in the root directory). #include "table/block_based/partitioned_filter_block.h" #include <utility> #include "file/file_util.h" #include "monitoring/perf_context_imp.h" #include "port/malloc.h" #include "port/port.h" #include "rocksdb/filter_policy.h" #include "table/block_based/block.h" #include "table/block_based/block_based_table_reader.h" #include "util/coding.h" namespace ROCKSDB_NAMESPACE { PartitionedFilterBlockBuilder::PartitionedFilterBlockBuilder( const SliceTransform* _prefix_extractor, bool whole_key_filtering, FilterBitsBuilder* filter_bits_builder, int index_block_restart_interval, const bool use_value_delta_encoding, PartitionedIndexBuilder* const p_index_builder, const uint32_t partition_size) : FullFilterBlockBuilder(_prefix_extractor, whole_key_filtering, filter_bits_builder), index_on_filter_block_builder_(index_block_restart_interval, true /*use_delta_encoding*/, use_value_delta_encoding), index_on_filter_block_builder_without_seq_(index_block_restart_interval, true /*use_delta_encoding*/, use_value_delta_encoding), p_index_builder_(p_index_builder), keys_added_to_partition_(0) { keys_per_partition_ = filter_bits_builder_->CalculateNumEntry(partition_size); if (keys_per_partition_ < 1) { // partition_size (minus buffer, ~10%) might be smaller than minimum // filter size, sometimes based on cache line size. Try to find that // minimum size without CalculateSpace (not necessarily available). uint32_t larger = std::max(partition_size + 4, uint32_t{16}); for (;;) { keys_per_partition_ = filter_bits_builder_->CalculateNumEntry(larger); if (keys_per_partition_ >= 1) { break; } larger += larger / 4; if (larger > 100000) { // might be a broken implementation. substitute something reasonable: // 1 key / byte. keys_per_partition_ = partition_size; break; } } } } PartitionedFilterBlockBuilder::~PartitionedFilterBlockBuilder() {} void PartitionedFilterBlockBuilder::MaybeCutAFilterBlock( const Slice* next_key) { // Use == to send the request only once if (keys_added_to_partition_ == keys_per_partition_) { // Currently only index builder is in charge of cutting a partition. We keep // requesting until it is granted. p_index_builder_->RequestPartitionCut(); } if (!p_index_builder_->ShouldCutFilterBlock()) { return; } filter_gc.push_back(std::unique_ptr<const char[]>(nullptr)); // Add the prefix of the next key before finishing the partition. This hack, // fixes a bug with format_verison=3 where seeking for the prefix would lead // us to the previous partition. const bool add_prefix = next_key && prefix_extractor() && prefix_extractor()->InDomain(*next_key); if (add_prefix) { FullFilterBlockBuilder::AddPrefix(*next_key); } Slice filter = filter_bits_builder_->Finish(&filter_gc.back()); std::string& index_key = p_index_builder_->GetPartitionKey(); filters.push_back({index_key, filter}); keys_added_to_partition_ = 0; Reset(); } void PartitionedFilterBlockBuilder::Add(const Slice& key) { MaybeCutAFilterBlock(&key); FullFilterBlockBuilder::Add(key); } void PartitionedFilterBlockBuilder::AddKey(const Slice& key) { FullFilterBlockBuilder::AddKey(key); keys_added_to_partition_++; } Slice PartitionedFilterBlockBuilder::Finish( const BlockHandle& last_partition_block_handle, Status* status) { if (finishing_filters == true) { // Record the handle of the last written filter block in the index FilterEntry& last_entry = filters.front(); std::string handle_encoding; last_partition_block_handle.EncodeTo(&handle_encoding); std::string handle_delta_encoding; PutVarsignedint64( &handle_delta_encoding, last_partition_block_handle.size() - last_encoded_handle_.size()); last_encoded_handle_ = last_partition_block_handle; const Slice handle_delta_encoding_slice(handle_delta_encoding); index_on_filter_block_builder_.Add(last_entry.key, handle_encoding, &handle_delta_encoding_slice); if (!p_index_builder_->seperator_is_key_plus_seq()) { index_on_filter_block_builder_without_seq_.Add( ExtractUserKey(last_entry.key), handle_encoding, &handle_delta_encoding_slice); } filters.pop_front(); } else { MaybeCutAFilterBlock(nullptr); } // If there is no filter partition left, then return the index on filter // partitions if (UNLIKELY(filters.empty())) { *status = Status::OK(); if (finishing_filters) { if (p_index_builder_->seperator_is_key_plus_seq()) { return index_on_filter_block_builder_.Finish(); } else { return index_on_filter_block_builder_without_seq_.Finish(); } } else { // This is the rare case where no key was added to the filter return Slice(); } } else { // Return the next filter partition in line and set Incomplete() status to // indicate we expect more calls to Finish *status = Status::Incomplete(); finishing_filters = true; return filters.front().filter; } } PartitionedFilterBlockReader::PartitionedFilterBlockReader( const BlockBasedTable* t, CachableEntry<Block>&& filter_block) : FilterBlockReaderCommon(t, std::move(filter_block)) {} std::unique_ptr<FilterBlockReader> PartitionedFilterBlockReader::Create( const BlockBasedTable* table, const ReadOptions& ro, FilePrefetchBuffer* prefetch_buffer, bool use_cache, bool prefetch, bool pin, BlockCacheLookupContext* lookup_context) { assert(table); assert(table->get_rep()); assert(!pin || prefetch); CachableEntry<Block> filter_block; if (prefetch || !use_cache) { const Status s = ReadFilterBlock(table, prefetch_buffer, ro, use_cache, nullptr /* get_context */, lookup_context, &filter_block); if (!s.ok()) { IGNORE_STATUS_IF_ERROR(s); return std::unique_ptr<FilterBlockReader>(); } if (use_cache && !pin) { filter_block.Reset(); } } return std::unique_ptr<FilterBlockReader>( new PartitionedFilterBlockReader(table, std::move(filter_block))); } bool PartitionedFilterBlockReader::KeyMayMatch( const Slice& key, const SliceTransform* prefix_extractor, uint64_t block_offset, const bool no_io, const Slice* const const_ikey_ptr, GetContext* get_context, BlockCacheLookupContext* lookup_context) { assert(const_ikey_ptr != nullptr); assert(block_offset == kNotValid); if (!whole_key_filtering()) { return true; } return MayMatch(key, prefix_extractor, block_offset, no_io, const_ikey_ptr, get_context, lookup_context, &FullFilterBlockReader::KeyMayMatch); } void PartitionedFilterBlockReader::KeysMayMatch( MultiGetRange* range, const SliceTransform* prefix_extractor, uint64_t block_offset, const bool no_io, BlockCacheLookupContext* lookup_context) { assert(block_offset == kNotValid); if (!whole_key_filtering()) { return; // Any/all may match } MayMatch(range, prefix_extractor, block_offset, no_io, lookup_context, &FullFilterBlockReader::KeysMayMatch); } bool PartitionedFilterBlockReader::PrefixMayMatch( const Slice& prefix, const SliceTransform* prefix_extractor, uint64_t block_offset, const bool no_io, const Slice* const const_ikey_ptr, GetContext* get_context, BlockCacheLookupContext* lookup_context) { assert(const_ikey_ptr != nullptr); assert(block_offset == kNotValid); if (!table_prefix_extractor() && !prefix_extractor) { return true; } return MayMatch(prefix, prefix_extractor, block_offset, no_io, const_ikey_ptr, get_context, lookup_context, &FullFilterBlockReader::PrefixMayMatch); } void PartitionedFilterBlockReader::PrefixesMayMatch( MultiGetRange* range, const SliceTransform* prefix_extractor, uint64_t block_offset, const bool no_io, BlockCacheLookupContext* lookup_context) { assert(block_offset == kNotValid); if (!table_prefix_extractor() && !prefix_extractor) { return; // Any/all may match } MayMatch(range, prefix_extractor, block_offset, no_io, lookup_context, &FullFilterBlockReader::PrefixesMayMatch); } BlockHandle PartitionedFilterBlockReader::GetFilterPartitionHandle( const CachableEntry<Block>& filter_block, const Slice& entry) const { IndexBlockIter iter; const InternalKeyComparator* const comparator = internal_comparator(); Statistics* kNullStats = nullptr; filter_block.GetValue()->NewIndexIterator( comparator->user_comparator(), table()->get_rep()->get_global_seqno(BlockType::kFilter), &iter, kNullStats, true /* total_order_seek */, false /* have_first_key */, index_key_includes_seq(), index_value_is_full()); iter.Seek(entry); if (UNLIKELY(!iter.Valid())) { // entry is larger than all the keys. However its prefix might still be // present in the last partition. If this is called by PrefixMayMatch this // is necessary for correct behavior. Otherwise it is unnecessary but safe. // Assuming this is an unlikely case for full key search, the performance // overhead should be negligible. iter.SeekToLast(); } assert(iter.Valid()); BlockHandle fltr_blk_handle = iter.value().handle; return fltr_blk_handle; } Status PartitionedFilterBlockReader::GetFilterPartitionBlock( FilePrefetchBuffer* prefetch_buffer, const BlockHandle& fltr_blk_handle, bool no_io, GetContext* get_context, BlockCacheLookupContext* lookup_context, CachableEntry<ParsedFullFilterBlock>* filter_block) const { assert(table()); assert(filter_block); assert(filter_block->IsEmpty()); if (!filter_map_.empty()) { auto iter = filter_map_.find(fltr_blk_handle.offset()); // This is a possible scenario since block cache might not have had space // for the partition if (iter != filter_map_.end()) { filter_block->SetUnownedValue(iter->second.GetValue()); return Status::OK(); } } ReadOptions read_options; if (no_io) { read_options.read_tier = kBlockCacheTier; } const Status s = table()->RetrieveBlock(prefetch_buffer, read_options, fltr_blk_handle, UncompressionDict::GetEmptyDict(), filter_block, BlockType::kFilter, get_context, lookup_context, /* for_compaction */ false, /* use_cache */ true); return s; } bool PartitionedFilterBlockReader::MayMatch( const Slice& slice, const SliceTransform* prefix_extractor, uint64_t block_offset, bool no_io, const Slice* const_ikey_ptr, GetContext* get_context, BlockCacheLookupContext* lookup_context, FilterFunction filter_function) const { CachableEntry<Block> filter_block; Status s = GetOrReadFilterBlock(no_io, get_context, lookup_context, &filter_block); if (UNLIKELY(!s.ok())) { IGNORE_STATUS_IF_ERROR(s); return true; } if (UNLIKELY(filter_block.GetValue()->size() == 0)) { return true; } auto filter_handle = GetFilterPartitionHandle(filter_block, *const_ikey_ptr); if (UNLIKELY(filter_handle.size() == 0)) { // key is out of range return false; } CachableEntry<ParsedFullFilterBlock> filter_partition_block; s = GetFilterPartitionBlock(nullptr /* prefetch_buffer */, filter_handle, no_io, get_context, lookup_context, &filter_partition_block); if (UNLIKELY(!s.ok())) { IGNORE_STATUS_IF_ERROR(s); return true; } FullFilterBlockReader filter_partition(table(), std::move(filter_partition_block)); return (filter_partition.*filter_function)( slice, prefix_extractor, block_offset, no_io, const_ikey_ptr, get_context, lookup_context); } void PartitionedFilterBlockReader::MayMatch( MultiGetRange* range, const SliceTransform* prefix_extractor, uint64_t block_offset, bool no_io, BlockCacheLookupContext* lookup_context, FilterManyFunction filter_function) const { CachableEntry<Block> filter_block; Status s = GetOrReadFilterBlock(no_io, range->begin()->get_context, lookup_context, &filter_block); if (UNLIKELY(!s.ok())) { IGNORE_STATUS_IF_ERROR(s); return; // Any/all may match } if (UNLIKELY(filter_block.GetValue()->size() == 0)) { return; // Any/all may match } auto start_iter_same_handle = range->begin(); BlockHandle prev_filter_handle = BlockHandle::NullBlockHandle(); // For all keys mapping to same partition (must be adjacent in sorted order) // share block cache lookup and use full filter multiget on the partition // filter. for (auto iter = start_iter_same_handle; iter != range->end(); ++iter) { // TODO: re-use one top-level index iterator BlockHandle this_filter_handle = GetFilterPartitionHandle(filter_block, iter->ikey); if (!prev_filter_handle.IsNull() && this_filter_handle != prev_filter_handle) { MultiGetRange subrange(*range, start_iter_same_handle, iter); MayMatchPartition(&subrange, prefix_extractor, block_offset, prev_filter_handle, no_io, lookup_context, filter_function); range->AddSkipsFrom(subrange); start_iter_same_handle = iter; } if (UNLIKELY(this_filter_handle.size() == 0)) { // key is out of range // Not reachable with current behavior of GetFilterPartitionHandle assert(false); range->SkipKey(iter); prev_filter_handle = BlockHandle::NullBlockHandle(); } else { prev_filter_handle = this_filter_handle; } } if (!prev_filter_handle.IsNull()) { MultiGetRange subrange(*range, start_iter_same_handle, range->end()); MayMatchPartition(&subrange, prefix_extractor, block_offset, prev_filter_handle, no_io, lookup_context, filter_function); range->AddSkipsFrom(subrange); } } void PartitionedFilterBlockReader::MayMatchPartition( MultiGetRange* range, const SliceTransform* prefix_extractor, uint64_t block_offset, BlockHandle filter_handle, bool no_io, BlockCacheLookupContext* lookup_context, FilterManyFunction filter_function) const { CachableEntry<ParsedFullFilterBlock> filter_partition_block; Status s = GetFilterPartitionBlock( nullptr /* prefetch_buffer */, filter_handle, no_io, range->begin()->get_context, lookup_context, &filter_partition_block); if (UNLIKELY(!s.ok())) { IGNORE_STATUS_IF_ERROR(s); return; // Any/all may match } FullFilterBlockReader filter_partition(table(), std::move(filter_partition_block)); (filter_partition.*filter_function)(range, prefix_extractor, block_offset, no_io, lookup_context); } size_t PartitionedFilterBlockReader::ApproximateMemoryUsage() const { size_t usage = ApproximateFilterBlockMemoryUsage(); #ifdef ROCKSDB_MALLOC_USABLE_SIZE usage += malloc_usable_size(const_cast<PartitionedFilterBlockReader*>(this)); #else usage += sizeof(*this); #endif // ROCKSDB_MALLOC_USABLE_SIZE return usage; // TODO(myabandeh): better estimation for filter_map_ size } // TODO(myabandeh): merge this with the same function in IndexReader void PartitionedFilterBlockReader::CacheDependencies(const ReadOptions& ro, bool pin) { assert(table()); const BlockBasedTable::Rep* const rep = table()->get_rep(); assert(rep); BlockCacheLookupContext lookup_context{TableReaderCaller::kPrefetch}; CachableEntry<Block> filter_block; Status s = GetOrReadFilterBlock(false /* no_io */, nullptr /* get_context */, &lookup_context, &filter_block); if (!s.ok()) { ROCKS_LOG_WARN(rep->ioptions.info_log, "Error retrieving top-level filter block while trying to " "cache filter partitions: %s", s.ToString().c_str()); IGNORE_STATUS_IF_ERROR(s); return; } // Before read partitions, prefetch them to avoid lots of IOs assert(filter_block.GetValue()); IndexBlockIter biter; const InternalKeyComparator* const comparator = internal_comparator(); Statistics* kNullStats = nullptr; filter_block.GetValue()->NewIndexIterator( comparator->user_comparator(), rep->get_global_seqno(BlockType::kFilter), &biter, kNullStats, true /* total_order_seek */, false /* have_first_key */, index_key_includes_seq(), index_value_is_full()); // Index partitions are assumed to be consecuitive. Prefetch them all. // Read the first block offset biter.SeekToFirst(); BlockHandle handle = biter.value().handle; uint64_t prefetch_off = handle.offset(); // Read the last block's offset biter.SeekToLast(); handle = biter.value().handle; uint64_t last_off = handle.offset() + handle.size() + kBlockTrailerSize; uint64_t prefetch_len = last_off - prefetch_off; std::unique_ptr<FilePrefetchBuffer> prefetch_buffer; prefetch_buffer.reset(new FilePrefetchBuffer()); IOOptions opts; s = PrepareIOFromReadOptions(ro, rep->file->env(), opts); if (s.ok()) { s = prefetch_buffer->Prefetch(opts, rep->file.get(), prefetch_off, static_cast<size_t>(prefetch_len)); } // After prefetch, read the partitions one by one for (biter.SeekToFirst(); biter.Valid(); biter.Next()) { handle = biter.value().handle; CachableEntry<ParsedFullFilterBlock> block; // TODO: Support counter batch update for partitioned index and // filter blocks s = table()->MaybeReadBlockAndLoadToCache( prefetch_buffer.get(), ro, handle, UncompressionDict::GetEmptyDict(), &block, BlockType::kFilter, nullptr /* get_context */, &lookup_context, nullptr /* contents */); assert(s.ok() || block.GetValue() == nullptr); if (s.ok() && block.GetValue() != nullptr) { if (block.IsCached()) { if (pin) { filter_map_[handle.offset()] = std::move(block); } } } IGNORE_STATUS_IF_ERROR(s); } } const InternalKeyComparator* PartitionedFilterBlockReader::internal_comparator() const { assert(table()); assert(table()->get_rep()); return &table()->get_rep()->internal_comparator; } bool PartitionedFilterBlockReader::index_key_includes_seq() const { assert(table()); assert(table()->get_rep()); return table()->get_rep()->index_key_includes_seq; } bool PartitionedFilterBlockReader::index_value_is_full() const { assert(table()); assert(table()->get_rep()); return table()->get_rep()->index_value_is_full; } } // namespace ROCKSDB_NAMESPACE
37.581395
80
0.698381
cssl-unist
dc25ac98836587fdbea428d73ec9a32938708afe
626
cpp
C++
Codeforces/contests/Codeforces Round #740 (Div. 2, based on VK Cup 2021 - Final (Engine))/D.cpp
LeKSuS-04/Competitive-Programming
fbc86a8c6febeef72587a8f94135e92197e1f99e
[ "WTFPL" ]
null
null
null
Codeforces/contests/Codeforces Round #740 (Div. 2, based on VK Cup 2021 - Final (Engine))/D.cpp
LeKSuS-04/Competitive-Programming
fbc86a8c6febeef72587a8f94135e92197e1f99e
[ "WTFPL" ]
null
null
null
Codeforces/contests/Codeforces Round #740 (Div. 2, based on VK Cup 2021 - Final (Engine))/D.cpp
LeKSuS-04/Competitive-Programming
fbc86a8c6febeef72587a8f94135e92197e1f99e
[ "WTFPL" ]
null
null
null
/* D. Up the Strip */ // https://codeforces.com/contest/1561/problem/D1 // Date: Aug/24/2021 18:29 (00:54:05) // Runtime: 6000 ms // Memory: 29160 KB // Verdict: TLE #include <iostream> #include <string.h> using namespace std; int n, m; int memo[4000010]; int count(int x) { if (memo[x] != -1) return memo[x]; if (x == 1) return 1; long long ans = 0; for (int y = 1; y <= x - 1; y++) ans = (ans + count(x - y)) % m; for (int z = 2; z <= x; z++) ans = (ans + count(x / z)) % m; return memo[x] = ans; } int main() { cin >> n >> m; memset(memo, -1, sizeof memo); cout << count(n); }
21.586207
68
0.535144
LeKSuS-04
dc25d7aff1fd976c19d99335e047bf0468cbcf07
4,090
hpp
C++
openstudiocore/src/project/ConcreteObjectRecords.hpp
ORNL-BTRIC/OpenStudio
878f94bebf6f025445d1373e8b2304ececac16d8
[ "blessing" ]
null
null
null
openstudiocore/src/project/ConcreteObjectRecords.hpp
ORNL-BTRIC/OpenStudio
878f94bebf6f025445d1373e8b2304ececac16d8
[ "blessing" ]
null
null
null
openstudiocore/src/project/ConcreteObjectRecords.hpp
ORNL-BTRIC/OpenStudio
878f94bebf6f025445d1373e8b2304ececac16d8
[ "blessing" ]
null
null
null
/********************************************************************** * Copyright (c) 2008-2014, Alliance for Sustainable Energy. * All rights reserved. * * This library 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 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********************************************************************/ #ifndef PROJECT_CONCRETEOBJECTRECORDS_HPP #define PROJECT_CONCRETEOBJECTRECORDS_HPP // utilities #include <project/AttributeRecord.hpp> #include <project/CloudSessionRecord.hpp> #include <project/CloudSettingsRecord.hpp> #include <project/FileReferenceRecord.hpp> #include <project/TagRecord.hpp> #include <project/UrlRecord.hpp> #include <project/URLSearchPathRecord.hpp> #include <project/VagrantSessionRecord.hpp> #include <project/VagrantSettingsRecord.hpp> // runmanager #include <project/WorkflowRecord.hpp> // ruleset #include <project/OSArgumentRecord.hpp> // analysis #include <project/AnalysisRecord.hpp> #include <project/DataPointRecord.hpp> #include <project/DataPointValueRecord.hpp> #include <project/DDACEAlgorithmRecord.hpp> #include <project/DesignOfExperimentsRecord.hpp> #include <project/FSUDaceAlgorithmRecord.hpp> #include <project/LinearFunctionRecord.hpp> #include <project/MeasureGroupRecord.hpp> #include <project/NullMeasureRecord.hpp> #include <project/OptimizationDataPointRecord.hpp> #include <project/OptimizationProblemRecord.hpp> #include <project/OutputAttributeVariableRecord.hpp> #include <project/ParameterStudyAlgorithmRecord.hpp> #include <project/ProblemRecord.hpp> #include <project/PSUADEDaceAlgorithmRecord.hpp> #include <project/RubyContinuousVariableRecord.hpp> #include <project/RubyMeasureRecord.hpp> #include <project/SamplingAlgorithmRecord.hpp> #include <project/SequentialSearchRecord.hpp> // utilities #include <project/AttributeRecord_Impl.hpp> #include <project/CloudSessionRecord_Impl.hpp> #include <project/CloudSettingsRecord_Impl.hpp> #include <project/FileReferenceRecord_Impl.hpp> #include <project/TagRecord_Impl.hpp> #include <project/UrlRecord_Impl.hpp> #include <project/URLSearchPathRecord_Impl.hpp> #include <project/VagrantSessionRecord_Impl.hpp> #include <project/VagrantSettingsRecord_Impl.hpp> // runmanager #include <project/WorkflowRecord_Impl.hpp> // ruleset #include <project/OSArgumentRecord_Impl.hpp> // analysis #include <project/AnalysisRecord_Impl.hpp> #include <project/DataPointRecord_Impl.hpp> #include <project/DataPointValueRecord_Impl.hpp> #include <project/DDACEAlgorithmRecord_Impl.hpp> #include <project/DesignOfExperimentsRecord_Impl.hpp> #include <project/FSUDaceAlgorithmRecord_Impl.hpp> #include <project/LinearFunctionRecord_Impl.hpp> #include <project/MeasureGroupRecord_Impl.hpp> #include <project/NullMeasureRecord_Impl.hpp> #include <project/OptimizationDataPointRecord_Impl.hpp> #include <project/OptimizationProblemRecord_Impl.hpp> #include <project/OutputAttributeVariableRecord_Impl.hpp> #include <project/ParameterStudyAlgorithmRecord_Impl.hpp> #include <project/ProblemRecord_Impl.hpp> #include <project/PSUADEDaceAlgorithmRecord_Impl.hpp> #include <project/RubyContinuousVariableRecord_Impl.hpp> #include <project/RubyMeasureRecord_Impl.hpp> #include <project/SamplingAlgorithmRecord_Impl.hpp> #include <project/SequentialSearchRecord_Impl.hpp> #endif // PROJECT_CONCRETEOBJECTRECORDS_HPP
40.9
83
0.771394
ORNL-BTRIC
dc27846a28ec616352a0fc676d036a4916953736
357
hpp
C++
function.hpp
Kayasama/Mine-Sweeper-master
f7f6cb54cba1ee86ba6b84302be88bb949f99740
[ "MIT" ]
null
null
null
function.hpp
Kayasama/Mine-Sweeper-master
f7f6cb54cba1ee86ba6b84302be88bb949f99740
[ "MIT" ]
null
null
null
function.hpp
Kayasama/Mine-Sweeper-master
f7f6cb54cba1ee86ba6b84302be88bb949f99740
[ "MIT" ]
null
null
null
#ifndef _FUNCTION_HPP #define _FUNCTION_HPP #include <SDL2/SDL.h> #include <string> #include "block.hpp" void gameover(const std::string &message); block *XYtoArr(int x, int y); void dfs(block *it); block *mouseToArr(int _x, int _y); void setball(); void init(); inline void clock(const unsigned int frames_per_second); void my_time_update(bool); #endif
19.833333
56
0.747899
Kayasama
dc28d53b00a958fb711ad49fcc2ab21a0a8a650d
612
cpp
C++
Searching/1. Linear Search/Linear Search.cpp
kanitmann/DSA_mastery
9b006892f24c697aae98ede0be203b87ad67c16a
[ "MIT" ]
1
2021-03-03T19:07:41.000Z
2021-03-03T19:07:41.000Z
Searching/1. Linear Search/Linear Search.cpp
kanitmann/DSA_mastery
9b006892f24c697aae98ede0be203b87ad67c16a
[ "MIT" ]
null
null
null
Searching/1. Linear Search/Linear Search.cpp
kanitmann/DSA_mastery
9b006892f24c697aae98ede0be203b87ad67c16a
[ "MIT" ]
null
null
null
#include<iostream> #define MAX_SIZE 5 int sort(int arr[MAX_SIZE], int key) { int pos = 0; for(int i=0;i<MAX_SIZE;i++) { if(arr[i]==key) return(i); } return (-1); } int main() { int list[MAX_SIZE]; int ele; std::cout<<"Enter Array: "; for(int i = 0; i<MAX_SIZE;i++){ std::cin>>list[i]; } std::cout<<"\n\nEnter element to search: "; std::cin>>ele; int pos = sort(list,ele); if (pos==-1) std::cout<<"\nElement not found."; else std::cout<<"\nElement found at position "<<pos+1; return 0; }
20.4
54
0.503268
kanitmann
dc29d1609d1f94e419039cbd1e6cbb4b3b0b4668
2,480
cpp
C++
RusOI-reg/16-numbers.cpp
SpeedOfMagic/CompetitiveProgramming
03f9d2925dbf9af29e93f67753397b5fbff7ab27
[ "MIT" ]
1
2021-05-07T07:38:26.000Z
2021-05-07T07:38:26.000Z
RusOI-reg/16-numbers.cpp
SpeedOfMagic/CompetitiveProgramming
03f9d2925dbf9af29e93f67753397b5fbff7ab27
[ "MIT" ]
null
null
null
RusOI-reg/16-numbers.cpp
SpeedOfMagic/CompetitiveProgramming
03f9d2925dbf9af29e93f67753397b5fbff7ab27
[ "MIT" ]
null
null
null
/** MIT License Copyright (c) 2018 Vasilyev Daniil **/ #include <bits/stdc++.h> using namespace std; #pragma GCC optimize("Ofast") template<typename T> using v = vector<T>; #define int long long typedef string str; typedef vector<int> vint; #define rep(a, l, r) for(int a = (l); a < (r); a++) #define pb push_back #define sz(a) ((int) a.size()) const long long inf = 4611686018427387903; //2^62 - 1 #if 0 //FileIO const string fileName = ""; ifstream fin ((fileName == "" ? "input.txt" : fileName + ".in" )); ofstream fout((fileName == "" ? "output.txt" : fileName + ".out")); #define get fin>> #define put fout<< #else #define get cin>> #define put cout<< #endif #define eol put endl void read() {} template<typename Arg,typename... Args> void read (Arg& arg,Args&... args){get (arg) ;read(args...) ;} void print(){} template<typename Arg,typename... Args> void print(Arg arg,Args... args){put (arg)<<" ";print(args...);} void debug(){eol;} template<typename Arg,typename... Args> void debug(Arg arg,Args... args){put (arg)<<" ";debug(args...);} int getInt(){int a; get a; return a;} //code goes here const int mod = 1e9 + 7; int solve(str r) { if (sz(r) == 1) return r[0] - '0' + 1; int ans = 0; str dd = "9"; while (sz(dd) + 1 < sz(r)) dd += "9"; ans += solve(dd); int n = sz(r); int dp[n][10]; rep(i, 0, n) { int prob1 = (i ? r[i - 1] - '0' : -1); if (prob1 > r[i] - '0') break; rep(j, 0, 10) { dp[i][j] = 0; if (r[i] - '0' < j || (i + 1 < n && r[i] - '0' == j) || (i == 0 && j == 0)) continue; if (prob1 <= j) dp[i][j] = 1; } rep(p, i + 1, n) rep(j, 0, 10) { dp[p][j] = 0; rep(k, 0, j + 1) dp[p][j] = (dp[p][j] + dp[p - 1][k]) % mod; } rep(j, 0, 10) ans = (ans + dp[n - 1][j]) % mod; } return ans; } int good(str a) { char pr = '0'; for (char i : a) if (i >= pr) pr = i; else return 0; return 1; } void run() { str a, b; read(a, b); put (solve(b) - solve(a) + good(a) + mod) % mod; } int32_t main() {srand(time(0)); ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); put fixed; put setprecision(15); run(); return 0;}
27.252747
133
0.468952
SpeedOfMagic
dc2ad5ebed96a92dd7965248f93618f5780174b5
4,424
hh
C++
src/shared/Alphabet.hh
AlgoLab/BEETL
b5953f841b3c8928e8e6e96a105d2b1efe1aea28
[ "BSD-Source-Code" ]
null
null
null
src/shared/Alphabet.hh
AlgoLab/BEETL
b5953f841b3c8928e8e6e96a105d2b1efe1aea28
[ "BSD-Source-Code" ]
null
null
null
src/shared/Alphabet.hh
AlgoLab/BEETL
b5953f841b3c8928e8e6e96a105d2b1efe1aea28
[ "BSD-Source-Code" ]
null
null
null
/** ** Copyright (c) 2011 Illumina, Inc. ** ** ** This software is covered by the "Illumina Non-Commercial Use Software ** and Source Code License Agreement" and any user of this software or ** source file is bound by the terms therein (see accompanying file ** Illumina_Non-Commercial_Use_Software_and_Source_Code_License_Agreement.pdf) ** ** This file is part of the BEETL software package. ** ** Citation: Markus J. Bauer, Anthony J. Cox and Giovanna Rosone ** Lightweight BWT Construction for Very Large String Collections. ** Proceedings of CPM 2011, pp.219-231 ** **/ #ifndef DEFINED_ALPHABET_HH #define DEFINED_ALPHABET_HH #include "Config.hh" #include "Types.hh" // Convention is that first char is the string terminator char and // is lexicographically less than the rest #ifdef USE_STANDARD_LEXICOGRAPHIC_ORDER static const char alphabet[] = "$ACGNTZ"; static const int whichPileInverse[] = { '$', 'A', 'C', 'G', 'N', 'T', 'Z' }; #else static const char alphabet[] = "$ACGTN"; static const int whichPileInverse[] = { '$', 'A', 'C', 'G', 'T', 'N', 'Z' }; #endif // Type able to contain symbols of the alphabet (in biologic case 6 ($,A,C,G,N,T)) typedef uchar AlphabetSymbol; //static const int alphabetSize(strlen(alphabet)); enum { alphabetSize = 7 }; // Next is a character that should not be in the alphabet // because it gets used as a marker in a couple of places in the code static const char notInAlphabet( 'Z' ); // One of the characters has special status: marks end of a string static const char terminatorChar( '$' ); // One of the characters has special status: 'don't know' character static const char dontKnowChar( 'N' ); const int nv( -1 ); #ifdef USE_STANDARD_LEXICOGRAPHIC_ORDER // encoding is ($,A,C,G,N,T)=(0,1,2,3,4,5) //static const char baseNames [] = "ACGNT"; static const int whichPile[] = { nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, 0, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, /* next is 'A' */ 1, nv, 2, nv, nv, nv, 3, nv, nv, nv, nv, nv, nv, 4, nv, /* next is 'P' */ nv, nv, nv, nv, 5, nv, nv, nv, nv, nv, 6, nv, nv, nv, nv, nv, // added Z for Huffman nv, /* next is 'a' */ 1, nv, 2, nv, nv, nv, 3, nv, nv, nv, nv, nv, nv, 4, nv, /* next is 'p' */ nv, nv, nv, nv, 5, nv, nv, nv, nv, nv, 6, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv }; #else // encoding is ($,A,C,G,T,N)=(0,1,2,3,4,5) //static const char baseNames [] = "ACGTN"; static const int whichPile[] = { nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, 0, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, /* next is 'A' */ 1, nv, 2, nv, nv, nv, 3, nv, nv, nv, nv, nv, nv, 5, nv, /* next is 'P' */ nv, nv, nv, nv, 4, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, /* next is 'a' */ 1, nv, 2, nv, nv, nv, 3, nv, nv, nv, nv, nv, nv, 5, nv, /* next is 'p' */ nv, nv, nv, nv, 4, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv, nv }; #endif // Used by BackTracker classes typedef bool AlphabetFlag[alphabetSize]; #endif
35.677419
88
0.573463
AlgoLab
dc2ae9cd37386c66d6357345fa01b89e2cc54e02
4,899
hpp
C++
code/linear/tropical.hpp
Brunovsky/competitive
41cf49378e430ca20d844f97c67aa5059ab1e973
[ "MIT" ]
1
2020-02-10T09:15:59.000Z
2020-02-10T09:15:59.000Z
code/linear/tropical.hpp
Brunovsky/kickstart
41cf49378e430ca20d844f97c67aa5059ab1e973
[ "MIT" ]
null
null
null
code/linear/tropical.hpp
Brunovsky/kickstart
41cf49378e430ca20d844f97c67aa5059ab1e973
[ "MIT" ]
null
null
null
#pragma once #include <bits/stdc++.h> using namespace std; // Tropical matrix operations (max plus or min plus) template <typename T> struct tmat { using vec = vector<T>; using unit_type = T; static constexpr T inf = numeric_limits<T>::lowest() / 2; static const T add(const T& a, const T& b) { return max(a, b); } static const T mul(const T& a, const T& b) { return a + b; } int n, m; T* data = nullptr; tmat() : n(0), m(0) {} tmat(int n, int m, const T& v = inf) { assign(n, m, v); } tmat(const tmat& o) : n(o.n), m(o.m), data(new T[n * m]) { copy(o.data, o.data + n * m, data); } tmat(tmat&& o) : tmat() { *this = move(o); } tmat& operator=(const tmat& o) { return *this = tmat(o); } tmat& operator=(tmat&& o) noexcept { using std::swap; swap(n, o.n), swap(m, o.m), swap(data, o.data); return *this; } ~tmat() { delete[] data; } bool operator==(const tmat& o) const { return n == o.n && m == o.m && equal(data, data + n * m, o.data); } bool operator!=(const tmat& o) const { return !(*this == o); } void assign(int n, int m, const T& v) { this->n = n, this->m = m, delete[] data, data = new T[n * m]; std::fill(data, data + n * m, v); } array<int, 2> size() const { return {n, m}; } T* operator[](int x) const { return data + x * m; } T& operator[](array<int, 2> xy) const { return data + (xy[0] * m + xy[1]); } template <typename U> static tmat from(const vector<vector<U>>& vals) { int n = vals.size(), m = n ? vals[0].size() : 0; tmat a(n, m); for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) a[i][j] = vals[i][j]; return a; } template <typename O = T> friend auto tovec(const tmat& a) { vector<vector<O>> m(a.n, vector<T>(a.m)); for (int i = 0; i < a.n; i++) for (int j = 0; j < a.m; j++) m[i][j] = a[i][j]; return m; } static tmat identity(int n) { tmat a(n, n, inf); for (int i = 0; i < n; i++) a[i][i] = 0; return a; } friend tmat transpose(const tmat& a) { tmat b(a.m, a.n); for (int i = 0; i < a.m; i++) for (int j = 0; j < a.n; j++) b[i][j] = a[j][i]; return b; } friend tmat& operator+=(tmat& a, const tmat& b) { assert(a.size() == b.size() && "Different matrix dimensions"); for (int i = 0, s = a.n * a.m; i < s; i++) a[i] = add(a[i], b[i]); return a; } friend tmat operator*(const tmat& a, const tmat& b) { assert(a.m == b.n && "Invalid proper matrix multiplication"); tmat c(a.n, b.m, inf); for (int i = 0; i < a.n; i++) for (int k = 0; k < a.m; k++) for (int j = 0; j < b.m; j++) c[i][j] = add(c[i][j], mul(a[i][k], b[k][j])); return c; } friend vec operator*(const tmat& a, const vec& b) { assert(a.m == int(b.size()) && "Invalid matrix/vector multiplication"); vec c(a.n, inf); for (int i = 0; i < a.n; i++) for (int j = 0; j < a.m; j++) c[i] = add(c[i], mul(a[i][j], b[j])); return c; } friend tmat operator^(tmat a, int64_t e) { assert(a.n == a.m && "Matrix exp operand is not square"); tmat c = tmat::identity(a.n); while (e > 0) { if (e & 1) c = c * a; if (e >>= 1) a = a * a; } return c; } friend tmat operator+(tmat a, const tmat& b) { return a += b; } tmat operator*=(const tmat& b) { return *this = *this * b; } tmat operator^=(int64_t e) { return *this = *this ^ e; } friend string to_string(const tmat& a) { vector<vector<string>> cell(a.n, vector<string>(a.m)); vector<size_t> w(a.m); for (int i = 0; i < a.n; i++) { for (int j = 0; j < a.m; j++) { using std::to_string; if constexpr (std::is_same<T, string>::value) { cell[i][j] = a[i][j]; } else { cell[i][j] = to_string(a[i][j]); } w[j] = max(w[j], cell[i][j].size()); } } string s; for (int i = 0; i < a.n; i++) { for (int j = 0; j < a.m; j++) { s += string(w[j] + 1 - cell[i][j].size(), ' '); s += cell[i][j]; } s += '\n'; } return s; } friend ostream& operator<<(ostream& out, const tmat& a) { return out << to_string(a); } friend istream& operator>>(istream& in, tmat& a) { for (int i = 0; i < a.n * a.m; i++) in >> a.data[i]; return in; } };
31.606452
80
0.441519
Brunovsky
dc2bedf536d5a1d5870e4417529522bcc453dcb7
1,234
cpp
C++
src/gfx/device.cpp
Necrys/engine
c4a69bcfa39d6410b7c24f142f692de1df145ffc
[ "Unlicense" ]
null
null
null
src/gfx/device.cpp
Necrys/engine
c4a69bcfa39d6410b7c24f142f692de1df145ffc
[ "Unlicense" ]
null
null
null
src/gfx/device.cpp
Necrys/engine
c4a69bcfa39d6410b7c24f142f692de1df145ffc
[ "Unlicense" ]
null
null
null
#include <glapi.h> #include <device.h> #include <config.h> #include <window.h> #include <GLFW/glfw3.h> #include <GL/gl.h> namespace engine { namespace gfx { Device::Device(Window& wnd): m_log("GFX_DEVICE"), m_window(wnd) { } bool Device::init() { m_log.debug("init"); if (!glapi::init()) { OGL_CHECK_ERRORS(); return false; } glClearColor(0.1f, 0.1f, 0.25f, 1.0f); glClearDepth(1.0f); glDisable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glFrontFace(GL_CW); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); return OGL_CHECK_ERRORS(); } void Device::swapBuffers() { glFinish(); glfwSwapBuffers(m_window.handle()); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); OGL_CHECK_ERRORS(); } void Device::onResize(const int width, const int height) { glViewport(0, 0, width, height); OGL_CHECK_ERRORS(); for (auto cb: m_resizeCallbacks) { cb(width, height); } } void Device::registerOnResizeCallback(ResizeCb cb) { m_resizeCallbacks.push_back(cb); } void Device::getFramebufferSize(int* width, int* height) { glfwGetFramebufferSize(m_window.handle(), width, height); } } //gfx } //engine
18.984615
61
0.664506
Necrys
dc2bfdb1739d5efedc36fe06e8285f353b4bc353
5,496
cpp
C++
src/pal/tests/palsuite/threading/QueueUserAPC/test2/test2.cpp
elinor-fung/coreclr
c1801e85024add717f518feb6a9caed60d54500f
[ "MIT" ]
159
2020-06-17T01:01:55.000Z
2022-03-28T10:33:37.000Z
src/pal/tests/palsuite/threading/QueueUserAPC/test2/test2.cpp
elinor-fung/coreclr
c1801e85024add717f518feb6a9caed60d54500f
[ "MIT" ]
19
2020-06-27T01:16:35.000Z
2022-02-06T20:33:24.000Z
src/pal/tests/palsuite/threading/QueueUserAPC/test2/test2.cpp
elinor-fung/coreclr
c1801e85024add717f518feb6a9caed60d54500f
[ "MIT" ]
19
2020-05-21T08:18:20.000Z
2021-06-29T01:13:13.000Z
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*===================================================================== ** ** Source: test2.c ** ** Purpose: Tests that APCs are not executed if a thread never enters an ** alertable state after they are queued. ** ** **===================================================================*/ #include <palsuite.h> const int ChildThreadSleepTime = 2000; const int InterruptTime = 1000; DWORD ChildThread; BOOL InAPC; /* synchronization events */ static HANDLE hSyncEvent1 = NULL; static HANDLE hSyncEvent2 = NULL; /* thread result because we have no GetExitCodeThread() API */ static BOOL bThreadResult = FAIL; VOID PALAPI APCFunc(ULONG_PTR dwParam) { InAPC = TRUE; } DWORD PALAPI SleeperProc(LPVOID lpParameter) { DWORD ret; /* signal the main thread that we're ready to proceed */ if( ! SetEvent( hSyncEvent1 ) ) { Trace( "ERROR:%lu:SetEvent() call failed\n", GetLastError() ); bThreadResult = FAIL; goto done; } /* wait for notification from the main thread */ ret = WaitForSingleObject( hSyncEvent2, 20000 ); if( ret != WAIT_OBJECT_0 ) { Trace( "ERROR:WaitForSingleObject() returned %lu, " "expected WAIT_OBJECT_0\n", ret ); bThreadResult = FAIL; goto done; } /* call our sleep function */ Sleep( ChildThreadSleepTime ); /* success if we reach here */ bThreadResult = PASS; done: /* signal the main thread that we're finished */ if( ! SetEvent( hSyncEvent1 ) ) { Trace( "ERROR:%lu:SetEvent() call failed\n", GetLastError() ); bThreadResult = FAIL; } /* return success or failure */ return bThreadResult; } int __cdecl main (int argc, char **argv) { /* local variables */ HANDLE hThread = 0; int ret; BOOL bResult = FAIL; /* initialize the PAL */ if (0 != (PAL_Initialize(argc, argv))) { return FAIL; } InAPC = FALSE; /* create a pair of synchronization events to coordinate our threads */ hSyncEvent1 = CreateEvent( NULL, FALSE, FALSE, NULL ); if( hSyncEvent1 == NULL ) { Trace( "ERROR:%lu:CreateEvent() call failed\n", GetLastError() ); goto cleanup; } hSyncEvent2 = CreateEvent( NULL, FALSE, FALSE, NULL ); if( hSyncEvent2 == NULL ) { Trace( "ERROR:%lu:CreateEvent() call failed\n", GetLastError() ); goto cleanup; } /* create a child thread */ hThread = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)SleeperProc, 0, 0, &ChildThread); if (hThread == NULL) { Trace( "ERROR:%lu:CreateThread() call failed\n", GetLastError()); goto cleanup; } /* wait on our synchronization event to ensure the thread is running */ ret = WaitForSingleObject( hSyncEvent1, 20000 ); if( ret != WAIT_OBJECT_0 ) { Trace( "ERROR:WaitForSingleObject() returned %lu, " "expected WAIT_OBJECT_0\n", ret ); goto cleanup; } /* queue a user APC on the child thread */ ret = QueueUserAPC(APCFunc, hThread, 0); if (ret == 0) { Trace( "ERROR:%lu:QueueUserAPC() call failed\n", GetLastError()); goto cleanup; } /* signal the child thread to continue */ if( ! SetEvent( hSyncEvent2 ) ) { Trace( "ERROR:%lu:SetEvent() call failed\n", GetLastError() ); goto cleanup; } /* wait on our synchronization event to ensure the other thread is done */ ret = WaitForSingleObject( hSyncEvent1, 20000 ); if( ret != WAIT_OBJECT_0 ) { Trace( "ERROR:WaitForSingleObject() returned %lu, " "expected WAIT_OBJECT_0\n", ret ); goto cleanup; } /* check that the thread executed successfully */ if( bThreadResult == FAIL ) { goto cleanup; } /* check whether the APC function was executed */ if( InAPC ) { Trace( "FAIL:APC function was executed but shouldn't have been\n" ); goto cleanup; } /* success if we reach here */ bResult = PASS; cleanup: /* wait for the other thread to finish */ if( hThread != NULL ) { ret = WaitForSingleObject( hThread, INFINITE ); if (ret == WAIT_FAILED) { Trace( "ERROR:%lu:WaitForSingleObject() returned %lu, " "expected WAIT_OBJECT_0\n", ret ); bResult = FAIL; } } /* close our synchronization handles */ if( hSyncEvent1 != NULL ) { if( ! CloseHandle( hSyncEvent1 ) ) { Trace( "ERROR:%lu:CloseHandle() call failed\n", GetLastError() ); bResult = FAIL; } } if( hSyncEvent2 != NULL ) { if( ! CloseHandle( hSyncEvent2 ) ) { Trace( "ERROR:%lu:CloseHandle() call failed\n", GetLastError() ); bResult = FAIL; } } if( bResult == FAIL ) { Fail( "test failed\n" ); } /* terminate the PAL */ PAL_Terminate(); /* return success */ return PASS; }
24.426667
78
0.549309
elinor-fung
dc2cfa9f16ec95c64a39b816566477272c8d13be
2,057
cc
C++
src/fe-write.cc
tdaede/fluxengine
056055bf0bf8b4091ab9d23b1542d1549aa99e6a
[ "MIT" ]
247
2019-01-07T05:12:52.000Z
2022-03-30T02:30:21.000Z
src/fe-write.cc
tdaede/fluxengine
056055bf0bf8b4091ab9d23b1542d1549aa99e6a
[ "MIT" ]
337
2019-02-19T17:56:56.000Z
2022-03-31T22:04:25.000Z
src/fe-write.cc
tdaede/fluxengine
056055bf0bf8b4091ab9d23b1542d1549aa99e6a
[ "MIT" ]
57
2019-01-07T05:18:17.000Z
2022-03-05T09:12:28.000Z
#include "globals.h" #include "flags.h" #include "writer.h" #include "fluxmap.h" #include "decoders/decoders.h" #include "encoders/encoders.h" #include "sector.h" #include "proto.h" #include "fluxsink/fluxsink.h" #include "fluxsource/fluxsource.h" #include "arch/brother/brother.h" #include "arch/ibm/ibm.h" #include "imagereader/imagereader.h" #include "fluxengine.h" #include "fmt/format.h" #include <google/protobuf/text_format.h> #include <fstream> static FlagGroup flags; static StringFlag sourceImage( { "--input", "-i" }, "source image to read from", "", [](const auto& value) { ImageReader::updateConfigForFilename(config.mutable_image_reader(), value); }); static StringFlag destFlux( { "--dest", "-d" }, "flux destination to write to", "", [](const auto& value) { FluxSink::updateConfigForFilename(config.mutable_flux_sink(), value); FluxSource::updateConfigForFilename(config.mutable_flux_source(), value); }); static StringFlag destCylinders( { "--cylinders", "-c" }, "cylinders to write to", "", [](const auto& value) { setRange(config.mutable_cylinders(), value); }); static StringFlag destHeads( { "--heads", "-h" }, "heads to write to", "", [](const auto& value) { setRange(config.mutable_heads(), value); }); int mainWrite(int argc, const char* argv[]) { if (argc == 1) showProfiles("write", formats); flags.parseFlagsWithConfigFiles(argc, argv, formats); std::unique_ptr<ImageReader> reader(ImageReader::create(config.image_reader())); std::unique_ptr<AbstractEncoder> encoder(AbstractEncoder::create(config.encoder())); std::unique_ptr<FluxSink> fluxSink(FluxSink::create(config.flux_sink())); std::unique_ptr<AbstractDecoder> decoder; if (config.has_decoder()) decoder = AbstractDecoder::create(config.decoder()); std::unique_ptr<FluxSource> fluxSource; if (config.has_flux_source() && config.flux_source().has_drive()) fluxSource = FluxSource::create(config.flux_source()); writeDiskCommand(*reader, *encoder, *fluxSink, decoder.get(), fluxSource.get()); return 0; }
25.395062
85
0.713175
tdaede
dc2d411d6cd6c8bacc6ceb50980515692cd7ffdf
2,594
cpp
C++
src/gui/win/layout/items/li_wire.cpp
lbz007/rectanglequery
59d6eb007bf65480fa3e9245542d0b6071f81831
[ "BSD-3-Clause" ]
null
null
null
src/gui/win/layout/items/li_wire.cpp
lbz007/rectanglequery
59d6eb007bf65480fa3e9245542d0b6071f81831
[ "BSD-3-Clause" ]
null
null
null
src/gui/win/layout/items/li_wire.cpp
lbz007/rectanglequery
59d6eb007bf65480fa3e9245542d0b6071f81831
[ "BSD-3-Clause" ]
null
null
null
#include "li_wire.h" #include <QDebug> #include "../layout_def.h" #include "li_layer.h" namespace open_edi { namespace gui { LI_Wire::LI_Wire(ScaleFactor* scale_factor) : LI_Base(scale_factor) { item_ = new LGI_Wire; item_->setLiBase(this); pen_.setColor(QColor(0xff, 0, 0, 0xff)); brush_ = QBrush(QColor(0xff, 0, 0, 0xff), Qt::Dense5Pattern); type_ = ObjType::kWire; name_ = kLiWireName; visible_ = true; setZ(0); } LI_Wire::~LI_Wire() { } LGI_Wire* LI_Wire::getGraphicItem() { return item_; } void LI_Wire::draw(QPainter* painter) { painter->setPen(pen_); painter->setBrush(brush_); LI_Base::draw(painter); } void LI_Wire::drawWires(open_edi::db::Wire& wire) { auto layer = dynamic_cast<LI_Layer*>(li_mgr_->getLayerByName(wire.getLayer()->getName())); if (!layer->isVisible()) { return; } QPainter painter(layer->getGraphicItem()->getMap()); pen_.setColor(layer->getColor()); brush_.setColor(layer->getColor()); auto box = __translateDbBoxToQtBox(wire.getBBox()); painter.setBrush(brush_); painter.setPen(pen_); __fillBox(&painter, brush_, box); __drawBox(&painter, box); } void LI_Wire::drawWires(open_edi::db::Wire* wire) { // auto layer = dynamic_cast<LI_Layer*>(li_mgr_->getLayerByName(wire->getLayer()->getName())); // if (!layer->isVisible()) { // return; // } // layer->obj_vectors_.push_back(wire); } bool LI_Wire::isMainLI() { return false; } void LI_Wire::setZ(int z) { z_ = z + (int)(LayerZ::kBase); item_->setZValue(z_); } // namespace gui void LI_Wire::preDraw() { auto net_v = li_mgr_->getLiByName(kLiNetName)->isVisible(); // if (!net_v) { // return; // } // if (!visible_) { // return; // } refreshBoundSize(); refreshItemMap(); std::vector<open_edi::db::Object*> result; open_edi::db::fetchDB(selected_area_, &result); auto factor = *scale_factor_; // printf("COMPONENTS %d ;\n", num_components); setOffset(-selected_area_.getLLX(), -selected_area_.getLLY()); open_edi::db::Wire* wire; QPainter painter; for (auto obj : result) { auto obj_type = obj->getObjectType(); if (open_edi::db::ObjectType::kObjectTypeWire == obj_type) { wire = static_cast<open_edi::db::Wire*>(obj); // drawWires(*wire); drawWires(wire); } if (open_edi::db::ObjectType::kObjectTypeVia == obj_type) { qDebug() << "via"; } } } } // namespace gui } // namespace open_edi
24.471698
98
0.615266
lbz007
dc2f19297e0c528f98ef5d47fc7902bac8ede3ca
2,151
hpp
C++
include/coco/combix/combinators/choice.hpp
agatan/coco
e19e74cf97d788b435351379296ea3ead901c576
[ "BSL-1.0" ]
1
2016-08-31T04:44:17.000Z
2016-08-31T04:44:17.000Z
include/coco/combix/combinators/choice.hpp
agatan/coco
e19e74cf97d788b435351379296ea3ead901c576
[ "BSL-1.0" ]
null
null
null
include/coco/combix/combinators/choice.hpp
agatan/coco
e19e74cf97d788b435351379296ea3ead901c576
[ "BSL-1.0" ]
null
null
null
#ifndef COCO_COMBIX_COMBINATORS_CHOICE_HPP_ #define COCO_COMBIX_COMBINATORS_CHOICE_HPP_ #include <type_traits> #include <utility> #include <coco/combix/error.hpp> #include <coco/combix/parser_traits.hpp> namespace coco { namespace combix { template <typename... P> struct choice_parser; template <typename P> struct choice_parser<P> { choice_parser(P const& p) : p(p) {} template <typename Stream> parse_result<parse_result_of_t<P, Stream>, Stream> parse(Stream& s) const { return coco::combix::parse(p, s); } template <typename Stream> void add_error(parse_error<Stream>& err) const { p.add_error(err); } private: P p; }; template <typename Head, typename... Tail> struct choice_parser<Head, Tail...> : choice_parser<Tail...> { using base_type = choice_parser<Tail...>; choice_parser(Head const& h, Tail const&... tail) : choice_parser<Tail...>(tail...), p(h) {} template <typename Stream> typename std::enable_if< std::is_same<parse_result_of_t<Head, Stream>, parse_result_of_t<base_type, Stream>>::value, parse_result<parse_result_of_t<Head, Stream>, Stream>>::type parse(Stream& s) const { auto res = coco::combix::parse(p, s); if (res) { return res; } else if (res.unwrap_error().consumed()) { return res.unwrap_error(); } auto tail_res = base_type::parse(s); if (tail_res) { return tail_res; } res.unwrap_error().merge(std::move(tail_res.unwrap_error())); return res.unwrap_error(); } template <typename Stream> void add_error(parse_error<Stream>& err) const { p.add_error(err); base_type::add_error(err); } private: Head p; }; template <typename... Args> choice_parser<std::decay_t<Args>...> choice(Args&&... args) { return choice_parser<std::decay_t<Args>...>(std::forward<Args>(args)...); } } // namespace combix } // namespace coco #endif
26.231707
79
0.598326
agatan
dc310cc44ed33e191a9bcd380ff199740ab2f7f8
8,593
hpp
C++
cmdstan/stan/lib/stan_math/stan/math/torsten/events_record.hpp
csetraynor/Torsten
55b59b8068e2a539346f566ec698c755a9e3536c
[ "BSD-3-Clause" ]
null
null
null
cmdstan/stan/lib/stan_math/stan/math/torsten/events_record.hpp
csetraynor/Torsten
55b59b8068e2a539346f566ec698c755a9e3536c
[ "BSD-3-Clause" ]
null
null
null
cmdstan/stan/lib/stan_math/stan/math/torsten/events_record.hpp
csetraynor/Torsten
55b59b8068e2a539346f566ec698c755a9e3536c
[ "BSD-3-Clause" ]
null
null
null
#ifndef STAN_MATH_TORSTEN_NONMEN_EVENTS_RECORD_HPP #define STAN_MATH_TORSTEN_NONMEN_EVENTS_RECORD_HPP #include <stan/math/torsten/dsolve/pk_vars.hpp> #include <stan/math/torsten/return_type.hpp> #include <boost/math/tools/promotion.hpp> #include <Eigen/Dense> #include <numeric> #include <string> #include <vector> namespace torsten { /* * Raw events record in the form of NONMEN, except that * for the population input @c len consisting of data record * length for each individual. * @tparam T0 type of scalar for time of events. * @tparam T1 type of scalar for amount at each event. * @tparam T2 type of scalar for rate at each event. * @tparam T3 type of scalar for inter-dose inteveral at each event. * @tparam T4 type of scalars for the model parameters. * @tparam T5 type of scalars for the bio-variability parameters. * @tparam T6 type of scalars for the model tlag parameters. */ template <typename T0, typename T1, typename T2, typename T3, typename T4_container, typename T5, typename T6> struct NONMENEventsRecord { using T4 = typename stan::math::value_type<T4_container>::type; using T_scalar = typename torsten::return_t<T0, T1, T2, T3, T4, T5, T6>::type; using T_time = typename torsten::return_t<T0, T1, T3, T6, T2>::type; using T_rate = typename torsten::return_t<T2, T5>::type; using T_amt = typename torsten::return_t<T1, T5>::type; using T_par = T4; using T_par_rate = T2; using T_par_ii = T3; private: const std::vector<int> len_1_; public: const int nev; const int ncmt; std::vector<int> begin_; const std::vector<int>& len_; const int total_num_event_times; const std::vector<T0>& time_; const std::vector<T1>& amt_; const std::vector<T2>& rate_; const std::vector<T3>& ii_; const std::vector<int>& evid_; const std::vector<int>& cmt_; const std::vector<int>& addl_; const std::vector<int>& ss_; const std::vector<T4_container>& pMatrix_; const std::vector<std::vector<T5> >& biovar_; const std::vector<std::vector<T6> >& tlag_; /* * Constructor using population data with parameter give as * matrix, such as in linear ODE models * @param[in] n number of compartments in model * @param[in] len record length for each individual. * @param[in] time times of events * @param[in] amt amount at each event * @param[in] rate rate at each event * @param[in] ii inter-dose interval at each event * @param[in] evid event identity: * (0) observation * (1) dosing * (2) other * (3) reset * (4) reset AND dosing * @param[in] cmt compartment number at each event * @param[in] addl additional dosing at each event * @param[in] ss steady state approximation at each event (0: no, 1: yes) * @param[in] pMatrix parameters at each event * @param[in] biovar bioavailability * @param[in] tlag lag time */ template <typename T0_, typename T1_, typename T2_, typename T3_, typename T4_container_, typename T5_, typename T6_> NONMENEventsRecord(int n, const std::vector<int>& len, const std::vector<T0_>& time, const std::vector<T1_>& amt, const std::vector<T2_>& rate, const std::vector<T3_>& ii, const std::vector<int>& evid, const std::vector<int>& cmt, const std::vector<int>& addl, const std::vector<int>& ss, const std::vector<T4_container_>& pMatrix, const std::vector<std::vector<T5_> >& biovar, const std::vector<std::vector<T6_> >& tlag) : len_1_(), nev(time.size()), ncmt(n), begin_(len.size()), len_(len), total_num_event_times(std::accumulate(len_.begin(), len_.end(), 0)), time_ (time ), amt_ (amt ), rate_ (rate ), ii_ (ii ), evid_ (evid ), cmt_ (cmt ), addl_ (addl ), ss_ (ss ), pMatrix_(pMatrix), biovar_ (biovar ), tlag_ (tlag ) { begin_[0] = 0; std::partial_sum(len.begin(), len.end() - 1, begin_.begin() + 1); } /* * Constructor using individual data with parameter give as * matrix, such as in linear ODE models * @param[in] n number of compartments in model * @param[in] len record length for each individual. * @param[in] time times of events * @param[in] amt amount at each event * @param[in] rate rate at each event * @param[in] ii inter-dose interval at each event * @param[in] evid event identity: * (0) observation * (1) dosing * (2) other * (3) reset * (4) reset AND dosing * @param[in] cmt compartment number at each event * @param[in] addl additional dosing at each event * @param[in] ss steady state approximation at each event (0: no, 1: yes) * @param[in] pMatrix parameters at each event * @param[in] biovar bioavailability * @param[in] tlag lag time */ template <typename T0_, typename T1_, typename T2_, typename T3_, typename T4_container_, typename T5_, typename T6_> NONMENEventsRecord(int n, const std::vector<T0_>& time, const std::vector<T1_>& amt, const std::vector<T2_>& rate, const std::vector<T3_>& ii, const std::vector<int>& evid, const std::vector<int>& cmt, const std::vector<int>& addl, const std::vector<int>& ss, const std::vector<T4_container_>& pMatrix, const std::vector<std::vector<T5_> >& biovar, const std::vector<std::vector<T6_> >& tlag) : len_1_(1, time.size()), nev(time.size()), ncmt(n), begin_{0}, len_(len_1_), total_num_event_times(std::accumulate(len_.begin(), len_.end(), 0)), time_ (time ), amt_ (amt ), rate_ (rate ), ii_ (ii ), evid_ (evid ), cmt_ (cmt ), addl_ (addl ), ss_ (ss ), pMatrix_(pMatrix), biovar_ (biovar ), tlag_ (tlag ) {} /* * begin of the parameters for individual @c id * in @c pMatrix. It is assumed that all the paramter are * either constant or time dependent. */ int begin_param(int id) const { return pMatrix_.size() == len_.size() ? id : begin_[id]; } /* * length of the parameters for individual @c id * in @c pMatrix. It is assumed that all the paramter are * either constant or time dependent. */ int len_param(int id) const { return pMatrix_.size() == len_.size() ? 1 : len_[id]; } int begin_biovar(int id) const { return biovar_.size() == len_.size() ? id : begin_[id]; } int len_biovar(int id) const { return biovar_.size() == len_.size() ? 1 : len_[id]; } int begin_tlag(int id) const { return tlag_.size() == len_.size() ? id : begin_[id]; } int len_tlag(int id) const { return tlag_.size() == len_.size() ? 1 : len_[id]; } inline bool has_ss_dosing() const { return has_ss_dosing(0); } /* * check the exisitence of steady state dosing events */ inline bool has_ss_dosing(int id) const { bool res = false; int begin = begin_[id]; int end = size_t(id + 1) == len_.size() ? time_.size() : begin_[id + 1]; for (int i = begin; i < end; ++i) { if ((evid_[i] == 1 || evid_[i] == 4) && ss_[i] != 0) { res = true; break; } } return res; } /* * check for the exisitence of lag time */ bool has_lag(int id) const { using stan::math::value_of; return std::any_of(tlag_.begin() + begin_tlag(id), tlag_.begin() + begin_tlag(id) + len_tlag(id), [](const std::vector<T6>& v) { return std::any_of(v.begin(), v.end(), [](const T6& x) { return std::abs(value_of(x)) > 1.E-10; }); }); } /* * check for the exisitence of lag time */ bool has_lag() const { return has_lag(0); } inline int parameter_size() const { return pMatrix_[0].size(); } inline int num_event_times(int id) const { return len_.at(id); } inline int num_event_times() const { return len_.at(0); } inline int num_subjects() const { return len_.size(); } }; } #endif
32.673004
124
0.584895
csetraynor
dc3280a3a76518bc325fbc6be30ddd3f46936cd0
2,793
hpp
C++
include/framework/Parser.hpp
Vitaliy-Grigoriev/Protocol-Analyzer
853aef9cfe355db481f558a2cdee298cc57d0ee4
[ "MIT" ]
14
2018-02-06T20:45:00.000Z
2020-06-23T06:53:51.000Z
include/framework/Parser.hpp
Vitaliy-Grigoriev/http2-analyzer
853aef9cfe355db481f558a2cdee298cc57d0ee4
[ "MIT" ]
null
null
null
include/framework/Parser.hpp
Vitaliy-Grigoriev/http2-analyzer
853aef9cfe355db481f558a2cdee298cc57d0ee4
[ "MIT" ]
6
2018-02-03T11:53:52.000Z
2020-05-07T03:10:29.000Z
// ============================================================================ // Copyright (c) 2017-2019, by Vitaly Grigoriev, <Vit.link420@gmail.com>. // This file is part of ProtocolAnalyzer open source project under MIT License. // ============================================================================ #ifndef PROTOCOL_ANALYZER_PARSER_HPP #define PROTOCOL_ANALYZER_PARSER_HPP #include <vector> #include <string_view> namespace analyzer::framework::parser { /** * @class PortsParser Parser.hpp "include/framework/Parser.hpp" * @brief Class that parses the range of ports. */ class PortsParser { private: /** * @brief Variable that contains the current value of range. */ uint16_t rangeState = 0; /** * @brief Variable that contains the last value of range. */ uint16_t rangeEnd = 0; /** * @brief Vector of strings that contains the split values on input. */ std::vector<std::string_view> inputStates = { }; public: /** * @brief Default constructor of PortsParser class. */ PortsParser(void) = default; /** * @brief Default destructor of PortsParser class. */ ~PortsParser(void) = default; PortsParser (PortsParser &&) = delete; PortsParser (const PortsParser &) = delete; PortsParser & operator= (PortsParser &&) = delete; PortsParser & operator= (const PortsParser &) = delete; /** * @brief Static variable that indicates the end of parsing or error. */ static const uint16_t end = 0; /** * @brief Constructor of PortParser class. * @param [in] ports - The sequence of ports listed through a separator. * @param [in] delimiter - The separator. Default: ','. * * @note For example: 80,1-5,433,25-36,90. */ explicit PortsParser (std::string_view /*ports*/, char /*delimiter*/ = ',') noexcept; /** * @brief Method that sets internal state of port parser. * @param [in] ports - The sequence of ports listed through a separator. * @param [in] delimiter - The separator. Default: ','. */ void SetPorts (std::string_view /*ports*/, char /*delimiter*/ = ',') noexcept; /** * @brief Method that gets next port value in input range. * @return Port number or PortsParser::end value if port enumeration is complete or an error occurred. * * @note The program MUST check the return value for PortsParser::end value. */ uint16_t GetNextPort(void) noexcept; }; } // namespace parser. #endif // PROTOCOL_ANALYZER_PARSER_HPP
33.25
110
0.56212
Vitaliy-Grigoriev
dc333129b23470245651fa871f40e2980aedba3c
772
cpp
C++
tools/train/source/parameters/Distributions.cpp
xhuan28/MNN
81df3a48d79cbc0b75251d12934345948866f7be
[ "Apache-2.0" ]
6,958
2019-05-06T02:38:02.000Z
2022-03-31T18:08:48.000Z
tools/train/source/parameters/Distributions.cpp
xhuan28/MNN
81df3a48d79cbc0b75251d12934345948866f7be
[ "Apache-2.0" ]
1,775
2019-05-06T04:40:19.000Z
2022-03-30T15:39:24.000Z
tools/train/source/parameters/Distributions.cpp
xhuan28/MNN
81df3a48d79cbc0b75251d12934345948866f7be
[ "Apache-2.0" ]
1,511
2019-05-06T02:38:05.000Z
2022-03-31T16:59:39.000Z
// // Distributions.cpp // MNN // // Created by MNN on 2019/11/28. // Copyright © 2018, Alibaba Group Holding Limited // #include "Distributions.hpp" #include <cmath> namespace MNN { namespace Train { void Distributions::uniform(const int count, const float min, const float max, float *r, std::mt19937 gen) { std::uniform_real_distribution<float> dis(min, std::nextafter(max, std::numeric_limits<float>::max())); for (int i = 0; i < count; i++) { r[i] = dis(gen); } } void Distributions::gaussian(const int count, const float mu, const float sigma, float *r, std::mt19937 gen) { std::normal_distribution<float> dis(mu, sigma); for (int i = 0; i < count; i++) { r[i] = dis(gen); } } } // namespace Train } // namespace MNN
24.903226
110
0.641192
xhuan28
dc344799ac401d7747b1ddd615442c7520b21c43
7,422
cc
C++
F/src/vbobuild.cc
vaginessa/Ctrl-Alt-Test
b981ebdbc6b0678f004c4052d70ebb56af2d89a0
[ "Apache-2.0" ]
114
2015-04-14T10:30:05.000Z
2021-06-11T02:57:59.000Z
F/src/vbobuild.cc
vaginessa/Ctrl-Alt-Test
b981ebdbc6b0678f004c4052d70ebb56af2d89a0
[ "Apache-2.0" ]
null
null
null
F/src/vbobuild.cc
vaginessa/Ctrl-Alt-Test
b981ebdbc6b0678f004c4052d70ebb56af2d89a0
[ "Apache-2.0" ]
11
2015-07-26T02:11:32.000Z
2020-04-02T21:06:15.000Z
// // Construction de VBO // #include "vbobuild.hh" #include "sys/msys.h" #include "sys/msys_debug.h" #include "cube.hh" namespace VBO { // ========================================================================= // Versions pour les hommes, où il faut gérer les indices // Version de base, avec position et taille unsigned int addCubeToChunk(vertex * dest, const vector3f &p, float size, bool x1face, bool x2face, bool y1face, bool y2face, bool z1face, bool z2face) { assert(x1face || x2face || y1face || y2face || z1face || z2face); unsigned int count = 0; for (unsigned int i = 0; i < Cube::numberOfVertices; ++i) if ((x1face && i < 4) || (x2face && (i >= 4 && i < 8)) || (y1face && (i >= 8 && i < 12)) || (y2face && (i >= 12 && i < 16)) || (z1face && (i >= 16 && i < 20)) || (z2face && i >= 20)) { dest[count] = Cube::vertices[i]; vertex & dst = dest[count]; dst.p = dst.p * size + p; ++count; } return count; } // Version de base, avec position et couleur unsigned int addCubeToChunk(vertex * dest, const vector3f &p, const vector3f &color, bool x1face, bool x2face, bool y1face, bool y2face, bool z1face, bool z2face) { assert(x1face || x2face || y1face || y2face || z1face || z2face); unsigned int count = 0; for (unsigned int i = 0; i < Cube::numberOfVertices; ++i) if ((x1face && i < 4) || (x2face && (i >= 4 && i < 8)) || (y1face && (i >= 8 && i < 12)) || (y2face && (i >= 12 && i < 16)) || (z1face && (i >= 16 && i < 20)) || (z2face && i >= 20)) { dest[count] = Cube::vertices[i]; vertex & dst = dest[count]; dst.p += p; dst.r = color.x; dst.g = color.y; dst.b = color.z; ++count; } return count; } // Version de base, avec position et couleur par face unsigned int addCubeToChunk(vertex * dest, const vector3f &p, const vector3f & x1Color, const vector3f & x2Color, const vector3f & y1Color, const vector3f & y2Color, const vector3f & z1Color, const vector3f & z2Color, bool x1face, bool x2face, bool y1face, bool y2face, bool z1face, bool z2face) { assert(x1face || x2face || y1face || y2face || z1face || z2face); unsigned int count = 0; for (unsigned int i = 0; i < Cube::numberOfVertices; ++i) if ((x1face && i < 4) || (x2face && (i >= 4 && i < 8)) || (y1face && (i >= 8 && i < 12)) || (y2face && (i >= 12 && i < 16)) || (z1face && (i >= 16 && i < 20)) || (z2face && i >= 20)) { dest[count] = Cube::vertices[i]; vertex & dst = dest[count]; dst.p += p; if (i < 4) { dst.r = x1Color.x; dst.g = x1Color.y; dst.b = x1Color.z; } else if (i < 8) { dst.r = x2Color.x; dst.g = x2Color.y; dst.b = x2Color.z; } else if (i < 12) { dst.r = y1Color.x; dst.g = y1Color.y; dst.b = y1Color.z; } else if (i < 16) { dst.r = y2Color.x; dst.g = y2Color.y; dst.b = y2Color.z; } else if (i < 20) { dst.r = z1Color.x; dst.g = z1Color.y; dst.b = z1Color.z; } else { dst.r = z2Color.x; dst.g = z2Color.y; dst.b = z2Color.z; } ++count; } return count; } // Version avec matrice unsigned int addCubeToChunk(vertex * dest, const matrix4 & transform, const vector3f &color, bool x1face, bool x2face, bool y1face, bool y2face, bool z1face, bool z2face) { assert(x1face || x2face || y1face || y2face || z1face || z2face); unsigned int count = 0; for (unsigned int i = 0; i < Cube::numberOfVertices; ++i) if ((x1face && i < 4) || (x2face && (i >= 4 && i < 8)) || (y1face && (i >= 8 && i < 12)) || (y2face && (i >= 12 && i < 16)) || (z1face && (i >= 16 && i < 20)) || (z2face && i >= 20)) { dest[count] = Cube::vertices[i]; vertex & dst = transformedVertex(transform, dest[count]); dst.r = color.x; dst.g = color.y; dst.b = color.z; ++count; } return count; } // ========================================================================= // Versions équivalentes, à base de tableau void addCube(Array<vertex> &vbo, const vector3f & pos, float size, bool x1face, bool x2face, bool y1face, bool y2face, bool z1face, bool z2face) { // FIXME : l'assert n'est plus bonne depuis qu'on peut retirer des faces IFDBG(assert(vbo.max_size >= vbo.size + (int)Cube::numberOfVertices)); vertex *ptr = vbo.elt + vbo.size; vbo.size += VBO::addCubeToChunk(ptr, pos, size, x1face, x2face, y1face, y2face, z1face, z2face); } void addCube(Array<vertex> &vbo, const vector3f & pos, const vector3f & color, bool x1face, bool x2face, bool y1face, bool y2face, bool z1face, bool z2face) { // FIXME : l'assert n'est plus bonne depuis qu'on peut retirer des faces IFDBG(assert(vbo.max_size >= vbo.size + (int)Cube::numberOfVertices)); vertex *ptr = vbo.elt + vbo.size; vbo.size += VBO::addCubeToChunk(ptr, pos, color, x1face, x2face, y1face, y2face, z1face, z2face); } void addCube(Array<vertex> &vbo, const vector3f & pos, const vector3f & x1Color, const vector3f & x2Color, const vector3f & y1Color, const vector3f & y2Color, const vector3f & z1Color, const vector3f & z2Color, bool x1face, bool x2face, bool y1face, bool y2face, bool z1face, bool z2face) { // FIXME : l'assert n'est plus bonne depuis qu'on peut retirer des faces IFDBG(assert(vbo.max_size >= vbo.size + (int)Cube::numberOfVertices)); vertex *ptr = vbo.elt + vbo.size; vbo.size += VBO::addCubeToChunk(ptr, pos, x1Color, x2Color, y1Color, y2Color, z1Color, z2Color, x1face, x2face, y1face, y2face, z1face, z2face); } void addCube(Array<vertex> & vbo, const matrix4 & transform, const vector3f & color, bool x1face, bool x2face, bool y1face, bool y2face, bool z1face, bool z2face) { IFDBG(assert(vbo.max_size >= vbo.size + (int)Cube::numberOfVertices)); vertex *ptr = vbo.elt + vbo.size; vbo.size += VBO::addCubeToChunk(ptr, transform, color, x1face, x2face, y1face, y2face, z1face, z2face); } // ========================================================================= // Version last minute VBO service // Si on veut reutiliser le code, attention a la couleur aleatoire. :) void addElements(Array<vertex> & vbo, const Node * tree, bool x1face, bool x2face, bool y1face, bool y2face, bool z1face, bool z2face) { const Renderable * renderables = tree->visiblePart(); for (int i = 0; i < tree->numberOfRenderables(); ++i) { const Renderable & renderable = renderables[i]; const vector3f color(msys_frand(), 1., 1.); // // FIXME : c'est un mesh qu'on veut ajouter !! // addCube(vbo, tree->localTransform(), color, x1face, x2face, y1face, y2face, z1face, z2face); } const Node * const * children = tree->children(); for (int i = 0; i < tree->numberOfChildren(); ++i) { addElements(vbo, children[i], x1face, x2face, y1face, y2face, z1face, z2face); } } }
27.286765
78
0.545001
vaginessa
dc34f47fa4d9615c28b7a730d60cb4f2947b0ccf
21,402
cpp
C++
src/Preprocessor.cpp
adcirc/gahm
bf31b2478bc8db1b41c3d8fac65acf034b6a743c
[ "MIT" ]
1
2021-07-21T00:59:59.000Z
2021-07-21T00:59:59.000Z
src/Preprocessor.cpp
adcirc/gahm
bf31b2478bc8db1b41c3d8fac65acf034b6a743c
[ "MIT" ]
null
null
null
src/Preprocessor.cpp
adcirc/gahm
bf31b2478bc8db1b41c3d8fac65acf034b6a743c
[ "MIT" ]
null
null
null
// MIT License // // Copyright (c) 2020 ADCIRC Development Group // // 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. // // Author: Zach Cobell // Contact: zcobell@thewaterinstitute.org // #include "Preprocessor.h" #include <numeric> #include <utility> #include "Constants.h" #include "Logging.h" #include "Vortex.h" using namespace Gahm; Preprocessor::Preprocessor(Atcf *atcf) : m_data(atcf) {} int Preprocessor::run() { if (m_data->format() == Atcf::ASWIP) { Logging::warning( "You have elected to recompute parameters previously input into the " "code. Input will be overwritten."); } int ierr = 0; ierr = this->calculateOverlandTranslationVelocity(); ierr += this->generateMissingPressureData(); ierr += this->calculateRadii(); ierr += this->computeParameters(); return ierr; } /** * Compute the U/V translational velocities on sphere * @param d1 Previous AtcfLine object * @param d2 Current AtcfLine object * @param[out] uv u-speed * @param[out] vv v-speed * @param[out] uuvv uv-speed * @return error code */ int Preprocessor::uvTrans(const AtcfLine &d1, const AtcfLine &d2, double &uv, double &vv, double &uuvv) { const auto dxdy = Constants::sphericalDx(d1.lon(), d1.lat(), d2.lon(), d2.lat()); const double dt = static_cast<double>(d2.datetime().toSeconds() - d1.datetime().toSeconds()); uv = std::abs(std::get<0>(dxdy) / dt); if (d2.lon() - d1.lon() <= 0.0) uv *= -1.0; vv = std::abs(std::get<1>(dxdy) / dt); if (d2.lat() - d1.lat() <= 0.0) vv *= -1.0; uuvv = std::get<2>(dxdy) / dt; return 0; } /** * Compute the translation velocities for all records in the storm * @return error code */ int Preprocessor::calculateOverlandTranslationVelocity() { for (auto it = m_data->data()->begin() + 1; it != m_data->data()->end(); ++it) { auto r1 = *(it - 1); auto r2 = *(it); double u, v, uv; int ierr = Preprocessor::uvTrans(r1, r2, u, v, uv); if (ierr != 0) { gahm_throw_exception("Error calculating UVTrans"); } if (uv * Units::convert(Units::MetersPerSecond, Units::Knot) < 1.0) { uv = 1.0 * Units::convert(Units::Knot, Units::MetersPerSecond); it->setStormDirection((it - 1)->stormDirection()); } else { double dir = std::atan2(u, v); if (dir < 0.0) dir += Constants::twopi(); it->setStormDirection(dir * Units::convert(Units::Radian, Units::Degree)); } it->setStormTranslationVelocities(u, v, uv); it->setStormSpeed(uv); } m_data->data()->begin()->setStormDirection( (m_data->data()->begin() + 1)->stormDirection()); m_data->data()->begin()->setStormSpeed( (m_data->data()->begin() + 1)->stormSpeed()); auto v = (m_data->data()->begin() + 1)->stormTranslationVelocities(); m_data->data()->begin()->setStormTranslationVelocities( std::get<0>(v), std::get<1>(v), std::get<2>(v)); return 0; } /** * Sets the isotach to have all radii at rmax * @param[inout] radii array of radii in each quadrant * @param[inout] quadFlag flag specifying if the quadrant has data * @param[in] rmax radius to isotach * @param[in] record record number * @param[in] isotach isotach number */ void Preprocessor::setAllRadiiToRmax(CircularArray<double, 4> &radii, CircularArray<bool, 4> &quadFlag, const double rmax, const size_t record, const size_t isotach) { std::fill(quadFlag.begin(), quadFlag.end(), 1); std::fill(radii.begin(), radii.end(), rmax); m_data->assumptions()->add(generate_assumption( Assumption::MAJOR, "No isotachs reported. Assuming a constant " "radius (RMAX). Record " + std::to_string(record) + ", isotach: " + std::to_string(isotach))); } /** * Sets the radii to half of the sum of the nonzero radii * @param[inout] radii array of radii in each quadrant * @param[in] radiisum sum of available radii * @param[in] record record number * @param[in] isotach isotach number */ void Preprocessor::setMissingRadiiToHalfNonzeroRadii( CircularArray<double, 4> &radii, const double radiisum, const size_t record, const size_t isotach) { Logging::debug("RADII:HALF:: " + std::to_string(radiisum) + " " + std::to_string(radiisum * 0.5)); for (auto i = 0; i < radii.size(); ++i) { if (radii.at(i) == 0.0) radii.set(i, radiisum * 0.5); } m_data->assumptions()->add(generate_assumption( Assumption::MAJOR, "One isotach reported. Missing radii are half " "the nonzero radius. Record " + std::to_string(record) + ", isotach: " + std::to_string(isotach))); } /** * Sets the missing radii to half of the average of the two specified radii * @param radii array of radii in each quadrant * @param radiisum sum of available radii * @param record record number * @param isotach isotach number */ void Preprocessor::setMissingRadiiToHalfOfAverageSpecifiedRadii( CircularArray<double, 4> &radii, const double radiisum, size_t record, size_t isotach) { Logging::debug( "RADII:HALFAVERAGE:: " + std::to_string(radiisum * Units::convert(Units::Kilometer, Units::NauticalMile)) + " " + std::to_string(radiisum * 0.25 * Units::convert(Units::Kilometer, Units::NauticalMile))); for (auto i = 0; i < radii.size(); ++i) { if (radii.at(i) == 0.0) radii.set(i, radiisum * 0.25); } m_data->assumptions()->add(generate_assumption( Assumption::MAJOR, "Two isotachs reported. Missing radii are half " "the average of the nonzero radii, Record " + std::to_string(record) + ", isotach: " + std::to_string(isotach))); } /** * Sets the radii to the average of the specified adjacent radii * @param radii array of radii for this isotach * @param lookup_radii radii specified in extended space * @param record record number * @param isotach isotach number */ void Preprocessor::setMissingRadiiToAverageOfAdjacentRadii( CircularArray<double, 4> &radii, size_t record, size_t isotach) { for (long j = 0; j < static_cast<long>(radii.size()); ++j) { if (radii.at(j) == 0.0) { Logging::debug("RADII:AVGADJACENT: " + std::to_string(radii.at(j - 1)) + ", " + std::to_string(radii.at(j + 1)) + ", " + std::to_string((radii.at(j - 1) + radii.at(j + 1)) * 0.5)); radii.set(j, (radii.at(j - 1) + radii.at(j + 1)) * 0.5); } } m_data->assumptions()->add(generate_assumption( Assumption::MAJOR, "Three isotachs reported. Missing radius is half " "the nonzero radius on either side. Record " + std::to_string(record) + ", isotach: " + std::to_string(isotach))); } /** * Computes the isotach radii values when they are not fully specified by the * Atcf file * @return */ int Preprocessor::calculateRadii() { Logging::debug("Beginning to compute missing radii"); for (auto ait = m_data->data()->begin(); ait != m_data->data()->end(); ++ait) { for (size_t i = 0; i < ait->nIsotach(); ++i) { const double radiisum = std::accumulate(ait->isotach(i).isotachRadius().begin(), ait->isotach(i).isotachRadius().end(), 0.0); ait->isotach(i).generateQuadFlag(); const unsigned int numNonzero = Preprocessor::countNonzeroIsotachs(ait, i); Logging::debug("NumNonzero Isotachs: " + std::to_string(numNonzero) + " " + std::to_string(ait->isotach(i).quadFlag().at(0)) + " " + std::to_string(ait->isotach(i).quadFlag().at(1)) + " " + std::to_string(ait->isotach(i).quadFlag().at(2)) + " " + std::to_string(ait->isotach(i).quadFlag().at(3))); const size_t record = ait - m_data->data()->begin(); switch (numNonzero) { case 0: this->setAllRadiiToRmax(ait->isotach(i).isotachRadius(), ait->isotach(i).quadFlag(), ait->radiusMaxWinds(), record, i); break; case 1: this->setMissingRadiiToHalfNonzeroRadii( ait->isotach(i).isotachRadius(), radiisum, record, i); break; case 2: this->setMissingRadiiToHalfOfAverageSpecifiedRadii( ait->isotach(i).isotachRadius(), radiisum, record, i); break; case 3: this->setMissingRadiiToAverageOfAdjacentRadii( ait->isotach(i).isotachRadius(), record, i); break; case 4: //...No missing radii break; default: gahm_throw_exception("Number of radii specified is not applicable"); break; } } } return 0; } unsigned Preprocessor::countNonzeroIsotachs( const std::vector<AtcfLine>::iterator &ait, size_t i) { unsigned numNonzero = 0; for (auto j = 0; j < 4; ++j) { if (ait->isotach(i).quadFlag().at(j)) { numNonzero++; } } return numNonzero; } /** * Computes any missing pressure values in the specified Atcf data using the * specified method * @param[in] method method to use for hurricane pressure * @return error code */ int Preprocessor::generateMissingPressureData( const HurricanePressure::PressureMethod &method) { HurricanePressure hp(method); double vmax_global = 0.0; for (auto it = m_data->data()->begin(); it != m_data->data()->end(); ++it) { vmax_global = std::max(vmax_global, it->vmax()); if (it->centralPressure() <= 0.0) { if (it == m_data->data()->begin()) { it->setCentralPressure( HurricanePressure::computeInitialPressureEstimate(it->vmax())); m_data->assumptions()->add(generate_assumption( Assumption::MINOR, "Pressure data was assumed using initial " "pressure estimate method. Record " + std::to_string(it - m_data->data()->begin()))); } else { it->setCentralPressure(hp.computePressure( it->vmax(), vmax_global, (it - 1)->vmax(), (it - 1)->centralPressure(), it->lat(), it->uvTrans())); m_data->assumptions()->add(generate_assumption( Assumption::MINOR, "Pressure was computed as " + std::to_string(it->centralPressure()) + "mb using vmax=" + std::to_string(it->vmax()) + "m/s, vmax_global=" + std::to_string(vmax_global) + "m/s, previous_pressure=" + std::to_string((it - 1)->centralPressure()) + "mb, lat=" + std::to_string(it->lat()) + ", speed=" + std::to_string(it->uvTrans()) + "m/s, with method=" + HurricanePressure::pressureMethodString(hp.pressureMethod()) + " for record " + std::to_string(it - m_data->data()->begin()))); } } } return 0; } int Preprocessor::computeParameters() { size_t rec_counter = 0; for (auto &a : *(m_data->data())) { //...Compute the global parameters for this period in the storm const auto stormMotion = Preprocessor::computeStormMotion(a.stormSpeed(), a.stormDirection()); a.setVmaxBl(Preprocessor::computeVMaxBL(a.vmax(), stormMotion.uv)); a.setHollandB(Constants::calcHollandB(a.vmaxBl(), a.centralPressure(), Constants::backgroundPressure())); for (size_t i = 0; i < a.nIsotach(); ++i) { rec_counter++; //...Check if the isotach is zero const double vr = a.isotach(i).windSpeed() == 0.0 ? a.vmax() : a.isotach(i).windSpeed(); //...Compute the inward rotation angles const std::array<double, 4> quadRotateAngle = Preprocessor::computeQuadRotateAngle(a, i); //...Initialize the flag that checks for violations in vmax vs vmaxbl std::array<bool, 4> vmwBLflag = {false, false, false, false}; //...Fill the holland b and phi in all quadrants for this isotach a.isotach(i).hollandB().fill(a.hollandB()); a.isotach(i).phi().fill(1.0); //...Converge inward rotation angle Preprocessor::convergeInwardRotationAngle(rec_counter, i, a, stormMotion, vr, quadRotateAngle, vmwBLflag); } } return 0; } void Preprocessor::convergeInwardRotationAngle( size_t rec_counter, size_t i, AtcfLine &a, const Preprocessor::StormMotion &stormMotion, const double vr, const std::array<double, 4> &quadRotateAngle, std::array<bool, 4> &vmwBLflag) const { const size_t nquadrotat = i == 0 ? 300 : 1; // const size_t nquadrotat = 1; for (auto j = 0; j < nquadrotat; ++j) { Preprocessor::computeQuadrantVrLoop(j, quadRotateAngle, vmwBLflag, a.vmaxBl(), vr, stormMotion, a.isotach(i)); Preprocessor::recomputeQuadrantVrLoop(j, quadRotateAngle, vmwBLflag, a.vmaxBl(), vr, a.stormDirection(), stormMotion, a.isotach(i)); //...Create a new vortex object and compute the radius to max wind // in each quadrant of the storm Vortex v(&a, rec_counter, i, m_data->assumptions_sharedptr()); v.computeRadiusToWind(); } } std::array<double, 4> Preprocessor::computeQuadRotateAngle(const AtcfLine &a, size_t i) { constexpr double initial_quadRotateAngle = 25.0 * Units::convert(Units::Degree, Units::Radian); std::array<double, 4> quadRotateAngle{ initial_quadRotateAngle, initial_quadRotateAngle, initial_quadRotateAngle, initial_quadRotateAngle}; if (i > 0) { for (auto j = 0; j < 4; ++j) { quadRotateAngle[j] = Constants::frictionAngle( a.isotach(i).isotachRadius().at(j), a.isotach(i).rmax().at(j)); } } return quadRotateAngle; } void Preprocessor::computeQuadrantVrLoop( const size_t quadrotindex, const std::array<double, 4> &quadRotateAngle, const std::array<bool, 4> &vmwBLflag, const double vmaxBL, const double vr, const StormMotion &stormMotion, Isotach &isotach) { for (auto k = 0; k < 4; ++k) { const double quadrantVectorAngle = Preprocessor::computeQuadrantVectorAngle(k, quadRotateAngle); if (quadrotindex == 0 || !vmwBLflag[k]) { const double qvr = Preprocessor::computeQuadrantVrValue( vmaxBL, quadrantVectorAngle, stormMotion, vr); isotach.quadrantVr().set(k, qvr); } } } double Preprocessor::computeQuadrantVrValue(const double vmaxBL, const double quadrantVectorAngles, const StormMotion &stormMotion, const double vr) { const double epsilonAngle = Preprocessor::computeEpsilonAngle( vmaxBL, quadrantVectorAngles, stormMotion); const double uvr = vr * std::cos(epsilonAngle); const double vvr = vr * std::sin(epsilonAngle); const double gamma = Preprocessor::computeGamma(uvr, vvr, vr, stormMotion, vmaxBL); constexpr double mps2kt = Units::convert(Units::MetersPerSecond, Units::Knot); const double qvr = std::sqrt(std::pow(uvr * mps2kt - gamma * stormMotion.u * mps2kt, 2.0) + std::pow(vvr * mps2kt - gamma * stormMotion.v * mps2kt, 2.0)) / Constants::windReduction(); return qvr * Units::convert(Units::Knot, Units::MetersPerSecond); } void Preprocessor::recomputeQuadrantVrLoop( const size_t quadrotindex, const std::array<double, 4> &quadRotateAngle, std::array<bool, 4> &vmwBLflag, const double vmaxBL, const double vr, const double stormDirection, const StormMotion &stormMotion, Isotach &isotach) { constexpr double deg2rad = Units::convert(Units::Degree, Units::Radian); for (auto k = 0; k < 4; ++k) { if (isotach.quadrantVr().at(k) > vmaxBL || vmwBLflag[k]) { if (quadrotindex == 1) vmwBLflag[k] = true; if (!isotach.isotachRadiusNullInInput().at(k)) { const double quadrantVectorAngle = Preprocessor::computeQuadrantVectorAngle(k, quadRotateAngle); double qvr = Preprocessor::computeQuadrantVrValue(quadrantVectorAngle, stormMotion, vr); qvr /= Constants::windReduction(); isotach.quadrantVr().set(k, qvr); isotach.vmaxBl().set(k, qvr); } else { isotach.vmaxBl().set(k, vmaxBL); const double uvr = vr * std::cos(stormDirection * deg2rad); const double vvr = vr * std::sin(stormDirection * deg2rad); const double gamma = Preprocessor::computeGamma(uvr, vvr, vr, stormMotion, vmaxBL); const double qvr2 = (vr - gamma * stormMotion.uv) / Constants::windReduction(); isotach.quadrantVr().set(k, qvr2); } } else { isotach.vmaxBl().set(k, vmaxBL); } } } double Preprocessor::computeQuadrantVrValue(const double quadrantVectorAngle, const StormMotion &stormMotion, const double vr) { constexpr double mps2kt = Units::convert(Units::MetersPerSecond, Units::Knot); const double qvr_1 = (stormMotion.u * mps2kt * std::cos(quadrantVectorAngle) + stormMotion.v * mps2kt * std::sin(quadrantVectorAngle)); const double qvr = (-2.0 * qvr_1 + std::sqrt(4.0 * std::pow(qvr_1, 2.0) - 4.0 * (std::pow(stormMotion.uv * mps2kt, 2.0) - std::pow(vr * mps2kt, 2.0)))) / 2.0; return qvr * Units::convert(Units::Knot, Units::MetersPerSecond); } double Preprocessor::computeGamma(const double uvr, const double vvr, const double vr, const StormMotion &stormMotion, const double vmaxBL) { constexpr double ms2kt = Units::convert(Units::MetersPerSecond, Units::Knot); const double g0 = (2.0 * uvr * ms2kt * stormMotion.u * ms2kt + 2.0 * vvr * ms2kt * stormMotion.v * ms2kt); const double g1 = std::pow(g0, 2.0); const double g2 = 4.0 * (std::pow(stormMotion.uv * ms2kt, 2.0) - std::pow(vmaxBL * ms2kt, 2.0) * Constants::windReduction() * Constants::windReduction()); const double g3 = std::pow(vr * ms2kt, 2.0); const double g4 = 2.0 * (std::pow(stormMotion.uv * ms2kt, 2.0) - std::pow(vmaxBL * ms2kt, 2.0) * Constants::windReduction() * Constants::windReduction()); double g = (g0 - std::sqrt(g1 - g2 * g3)) / g4; g = std::max(std::min(g, 1.0), 0.0); return g; } double Preprocessor::computeEpsilonAngle(const double velocity, const double quadrantVectorAngle, const StormMotion &stormMotion) { double e = Constants::twopi() + std::atan2(velocity * std::sin(quadrantVectorAngle) + stormMotion.v, velocity * std::cos(quadrantVectorAngle) + stormMotion.u); if (e > Constants::twopi()) e -= Constants::twopi(); return e; } Preprocessor::StormMotion Preprocessor::computeStormMotion( const double speed, const double direction) { double stormMotion = 1.5 * std::pow(speed * Units::convert(Units::MetersPerSecond, Units::Knot), 0.63) * Units::convert(Units::Knot, Units::MetersPerSecond); double stormMotionU = std::sin(direction * Units::convert(Units::Degree, Units::Radian)) * stormMotion; double stormMotionV = std::cos(direction * Units::convert(Units::Degree, Units::Radian)) * stormMotion; return {stormMotionU, stormMotionV, stormMotion}; } double Preprocessor::computeVMaxBL(const double vmax, const double stormMotion) { return (vmax - stormMotion) / Constants::windReduction(); } double Preprocessor::computeQuadrantVectorAngle( const size_t index, const std::array<double, 4> quadRotateAngle) { assert(index < 4); return Constants::quadrantAngle(index) + (Constants::halfpi() + quadRotateAngle[index]); }
39.126143
80
0.60985
adcirc
dc3622a3bce0a9d3a996629a687830e67f4b9399
3,636
cpp
C++
tests/src/TerminalOutputTests.cpp
codesmithyide/ishiko-cpp-terminal
643b551fd01471323e2ffd118670ed529014822b
[ "MIT" ]
null
null
null
tests/src/TerminalOutputTests.cpp
codesmithyide/ishiko-cpp-terminal
643b551fd01471323e2ffd118670ed529014822b
[ "MIT" ]
null
null
null
tests/src/TerminalOutputTests.cpp
codesmithyide/ishiko-cpp-terminal
643b551fd01471323e2ffd118670ed529014822b
[ "MIT" ]
null
null
null
/* Copyright (c) 2020 Xavier Leclercq Released under the MIT License See https://github.com/Ishiko-cpp/Terminal/blob/master/LICENSE.txt */ #include "TerminalOutputTests.h" #include "Ishiko/Terminal/TerminalOutput.h" #include <Ishiko/Process/CurrentProcess.h> #include <boost/filesystem/operations.hpp> using namespace Ishiko::Terminal; using namespace Ishiko::Tests; TerminalOutputTests::TerminalOutputTests(const TestNumber& number, const TestEnvironment& environment) : TestSequence(number, "TerminalOutput tests", environment) { append<HeapAllocationErrorsTest>("Construction test 1", ConstructionTest1); append<FileComparisonTest>("write test 1", WriteTest1); append<FileComparisonTest>("write test 2", WriteTest2); append<FileComparisonTest>("write test 3", WriteTest3); append<FileComparisonTest>("write test 4", WriteTest4); } void TerminalOutputTests::ConstructionTest1(Test& test) { TerminalOutput output(stdout); ISHTF_PASS(); } void TerminalOutputTests::WriteTest1(FileComparisonTest& test) { boost::filesystem::path outputPath(test.environment().getTestOutputDirectory() / "TerminalOutputTests_WriteTest1.txt"); boost::filesystem::remove(outputPath); test.setOutputFilePath(outputPath); test.setReferenceFilePath(test.environment().getReferenceDataDirectory() / "TerminalOutputTests_WriteTest1.txt"); Ishiko::Process::CurrentProcess::RedirectStandardOutputToFile(outputPath.string()); TerminalOutput output(stdout); output.write("text"); Ishiko::Process::CurrentProcess::RedirectStandardOutputToTerminal(); ISHTF_PASS(); } void TerminalOutputTests::WriteTest2(FileComparisonTest& test) { boost::filesystem::path outputPath(test.environment().getTestOutputDirectory() / "TerminalOutputTests_WriteTest2.txt"); boost::filesystem::remove(outputPath); test.setOutputFilePath(outputPath); test.setReferenceFilePath(test.environment().getReferenceDataDirectory() / "TerminalOutputTests_WriteTest2.txt"); Ishiko::Process::CurrentProcess::RedirectStandardOutputToFile(outputPath.string()); TerminalOutput output(stdout); std::string text = "text"; output.write(text); Ishiko::Process::CurrentProcess::RedirectStandardOutputToTerminal(); ISHTF_PASS(); } void TerminalOutputTests::WriteTest3(FileComparisonTest& test) { boost::filesystem::path outputPath(test.environment().getTestOutputDirectory() / "TerminalOutputTests_WriteTest3.txt"); boost::filesystem::remove(outputPath); test.setOutputFilePath(outputPath); test.setReferenceFilePath(test.environment().getReferenceDataDirectory() / "TerminalOutputTests_WriteTest3.txt"); Ishiko::Process::CurrentProcess::RedirectStandardOutputToFile(outputPath.string()); TerminalOutput output(stdout); output.write("text", Ishiko::Color::eRed); Ishiko::Process::CurrentProcess::RedirectStandardOutputToTerminal(); ISHTF_PASS(); } void TerminalOutputTests::WriteTest4(FileComparisonTest& test) { boost::filesystem::path outputPath(test.environment().getTestOutputDirectory() / "TerminalOutputTests_WriteTest4.txt"); boost::filesystem::remove(outputPath); test.setOutputFilePath(outputPath); test.setReferenceFilePath(test.environment().getReferenceDataDirectory() / "TerminalOutputTests_WriteTest4.txt"); Ishiko::Process::CurrentProcess::RedirectStandardOutputToFile(outputPath.string()); TerminalOutput output(stdout); std::string text = "text"; output.write(text, Ishiko::Color::eRed); Ishiko::Process::CurrentProcess::RedirectStandardOutputToTerminal(); ISHTF_PASS(); }
36
123
0.768977
codesmithyide
dc37ebc2fe2e18f2e37f8402565df01993e2b02f
1,290
inl
C++
include/msstl/converted/xcharconv.h.inl
iboB/mscharconv
7c4bd58ebabda50140ee833c8b869d6ca1d11243
[ "Apache-2.0" ]
34
2021-04-17T14:25:24.000Z
2021-08-21T19:22:58.000Z
include/msstl/converted/xcharconv.h.inl
iboB/mscharconv
7c4bd58ebabda50140ee833c8b869d6ca1d11243
[ "Apache-2.0" ]
1
2021-11-19T00:30:13.000Z
2021-11-26T04:13:38.000Z
include/msstl/converted/xcharconv.h.inl
iboB/mscharconv
7c4bd58ebabda50140ee833c8b869d6ca1d11243
[ "Apache-2.0" ]
3
2021-04-17T14:25:27.000Z
2021-08-06T08:28:09.000Z
// xcharconv.h internal header // Copyright (c) Microsoft Corporation. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception //~ #pragma once #ifndef _XCHARCONV_H #define _XCHARCONV_H //~ #include <yvals_core.h> //~ #if _STL_COMPILER_PREPROCESSOR //~ #include <cstdint> //~ #include <type_traits> //~ #include <xerrc.h> #if 0 //~#if !_HAS_CXX17 #error The contents of <charconv> are only available with C++17. (Also, you should not include this internal header.) #endif // !_HAS_CXX17 //~ #pragma pack(push, _CRT_PACKING) //~ #pragma warning(push, _STL_WARNING_LEVEL) //~ #pragma warning(disable : _STL_DISABLED_WARNINGS) //~ _STL_DISABLE_CLANG_WARNINGS //~ #pragma push_macro("new") //~ #undef new //~ _STD_BEGIN enum class chars_format { scientific = 0b001, fixed = 0b010, hex = 0b100, general = fixed | scientific, }; //~ _BITMASK_OPS(chars_format) struct to_chars_result { char* ptr; std::errc ec; #if 0 //~#if _HAS_CXX20 [[nodiscard]] friend bool operator==(const to_chars_result&, const to_chars_result&) = default; #endif // _HAS_CXX20 }; //~ _STD_END //~ #pragma pop_macro("new") //~ _STL_RESTORE_CLANG_WARNINGS //~ #pragma warning(pop) //~ #pragma pack(pop) //~ #endif // _STL_COMPILER_PREPROCESSOR #endif // _XCHARCONV_H
23.888889
117
0.693798
iboB
dc3a411dcdb33e8e5a1608ec599746c217ea97e4
734
hpp
C++
include/nall/string/char/utility.hpp
wareya/kotareci
14c87d1364d442456f93cebe73a288f85b79ba74
[ "Libpng" ]
null
null
null
include/nall/string/char/utility.hpp
wareya/kotareci
14c87d1364d442456f93cebe73a288f85b79ba74
[ "Libpng" ]
null
null
null
include/nall/string/char/utility.hpp
wareya/kotareci
14c87d1364d442456f93cebe73a288f85b79ba74
[ "Libpng" ]
null
null
null
#ifdef NALL_STRING_INTERNAL_HPP namespace nall { template<bool Insensitive> bool chrequal(char x, char y) { if(Insensitive) return chrlower(x) == chrlower(y); return x == y; } template<bool Quoted, typename T> bool quoteskip(T*& p) { if(Quoted == false) return false; if(*p != '\'' && *p != '\"') return false; while(*p == '\'' || *p == '\"') { char x = *p++; while(*p && *p++ != x); } return true; } template<bool Quoted, typename T> bool quotecopy(char*& t, T*& p) { if(Quoted == false) return false; if(*p != '\'' && *p != '\"') return false; while(*p == '\'' || *p == '\"') { char x = *p++; *t++ = x; while(*p && *p != x) *t++ = *p++; *t++ = *p++; } return true; } } #endif
18.35
52
0.506812
wareya
dc3ce990dd73312c8a8ac7a634e63da91dac404f
6,781
cpp
C++
source/microbit/microbiti2c.cpp
kopp/minipython
c26f50028e98e20c760cf63588ff46786c7304e1
[ "MIT" ]
null
null
null
source/microbit/microbiti2c.cpp
kopp/minipython
c26f50028e98e20c760cf63588ff46786c7304e1
[ "MIT" ]
null
null
null
source/microbit/microbiti2c.cpp
kopp/minipython
c26f50028e98e20c760cf63588ff46786c7304e1
[ "MIT" ]
null
null
null
/* * This file is part of the MiniPython project, http://minipython.org/ * * The MIT License (MIT) * * Copyright (c) 2015-2017 Kevin Thomas * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "microbit/microbitdal.h" extern "C" { #include "py/runtime.h" #include "microbit/modmicrobit.h" typedef struct _microbit_i2c_obj_t { mp_obj_base_t base; MiniPythonI2C *i2c; } microbit_i2c_obj_t; STATIC mp_obj_t microbit_i2c_init(mp_uint_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { static const mp_arg_t allowed_args[] = { { MP_QSTR_freq, MP_ARG_INT, {.u_int = 100000} }, { MP_QSTR_sda, MP_ARG_OBJ, {.u_obj = mp_const_none } }, { MP_QSTR_scl, MP_ARG_OBJ, {.u_obj = mp_const_none } }, }; // parse args microbit_i2c_obj_t *self = (microbit_i2c_obj_t*)pos_args[0]; mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); PinName p_sda = I2C_SDA0; PinName p_scl = I2C_SCL0; if (args[1].u_obj != mp_const_none) { p_sda = (PinName)microbit_obj_get_pin_name(args[1].u_obj); } if (args[2].u_obj != mp_const_none) { p_scl = (PinName)microbit_obj_get_pin_name(args[2].u_obj); } self->i2c->set_pins(p_sda, p_scl); self->i2c->frequency(args[0].u_int); // Call underlying mbed i2c_reset to reconfigure the pins and reset the peripheral i2c_reset(self->i2c->get_i2c_obj()); return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_KW(microbit_i2c_init_obj, 1, microbit_i2c_init); // Probe the given I2C address with an empty write to see if a device responds with an ACK STATIC bool i2c_probe(i2c_t *obj, uint8_t address) { obj->i2c->ADDRESS = address; obj->i2c->SHORTS = 0; obj->i2c->TASKS_STARTTX = 1; obj->i2c->EVENTS_STOPPED = 0; obj->i2c->TASKS_STOP = 1; uint32_t timeout = 10000; while (!obj->i2c->EVENTS_STOPPED && timeout > 0) { --timeout; } bool ack = timeout > 0 && obj->i2c->ERRORSRC == 0; i2c_reset(obj); return ack; } STATIC mp_obj_t microbit_i2c_scan(mp_obj_t self_in) { microbit_i2c_obj_t *self = (microbit_i2c_obj_t*)MP_OBJ_TO_PTR(self_in); i2c_t *obj = self->i2c->get_i2c_obj(); mp_obj_t list = mp_obj_new_list(0, NULL); // 7-bit addresses 0b0000xxx and 0b1111xxx are reserved for (int addr = 0x08; addr < 0x78; ++addr) { if (i2c_probe(obj, addr)) { mp_obj_list_append(list, MP_OBJ_NEW_SMALL_INT(addr)); } } return list; } MP_DEFINE_CONST_FUN_OBJ_1(microbit_i2c_scan_obj, microbit_i2c_scan); STATIC mp_obj_t microbit_i2c_read(mp_uint_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { static const mp_arg_t allowed_args[] = { { MP_QSTR_addr, MP_ARG_REQUIRED | MP_ARG_INT, {.u_int = 0} }, { MP_QSTR_n, MP_ARG_REQUIRED | MP_ARG_INT, {.u_int = 0} }, { MP_QSTR_repeat, MP_ARG_BOOL, {.u_bool = false} }, }; // parse args microbit_i2c_obj_t *self = (microbit_i2c_obj_t*)pos_args[0]; mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); // do the I2C read vstr_t vstr; vstr_init_len(&vstr, args[1].u_int); int err = self->i2c->read(args[0].u_int << 1, vstr.buf, vstr.len, args[2].u_bool); if (err != MICROBIT_OK) { nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OSError, "I2C read error %d", err)); } // return bytes object with read data return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); } MP_DEFINE_CONST_FUN_OBJ_KW(microbit_i2c_read_obj, 1, microbit_i2c_read); STATIC mp_obj_t microbit_i2c_write(mp_uint_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { static const mp_arg_t allowed_args[] = { { MP_QSTR_addr, MP_ARG_REQUIRED | MP_ARG_INT, {.u_int = 0} }, { MP_QSTR_buf, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, { MP_QSTR_repeat, MP_ARG_BOOL, {.u_bool = false} }, }; // parse args microbit_i2c_obj_t *self = (microbit_i2c_obj_t*)pos_args[0]; mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); // do the I2C write mp_buffer_info_t bufinfo; mp_get_buffer_raise(args[1].u_obj, &bufinfo, MP_BUFFER_READ); int err = self->i2c->write(args[0].u_int << 1, (char*)bufinfo.buf, bufinfo.len, args[2].u_bool); if (err != MICROBIT_OK) { nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OSError, "I2C write error %d", err)); } return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_KW(microbit_i2c_write_obj, 1, microbit_i2c_write); STATIC const mp_map_elem_t microbit_i2c_locals_dict_table[] = { { MP_OBJ_NEW_QSTR(MP_QSTR_init), (mp_obj_t)&microbit_i2c_init_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_scan), (mp_obj_t)&microbit_i2c_scan_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_read), (mp_obj_t)&microbit_i2c_read_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_write), (mp_obj_t)&microbit_i2c_write_obj }, }; STATIC MP_DEFINE_CONST_DICT(microbit_i2c_locals_dict, microbit_i2c_locals_dict_table); const mp_obj_type_t microbit_i2c_type = { { &mp_type_type }, .name = MP_QSTR_MicroBitI2C, .print = NULL, .make_new = NULL, .call = NULL, .unary_op = NULL, .binary_op = NULL, .attr = NULL, .subscr = NULL, .getiter = NULL, .iternext = NULL, .buffer_p = {NULL}, .protocol = NULL, .parent = NULL, .locals_dict = (mp_obj_dict_t*)&microbit_i2c_locals_dict, }; const microbit_i2c_obj_t microbit_i2c_obj = { {&microbit_i2c_type}, .i2c = &ubit_i2c, }; }
37.054645
105
0.699897
kopp
dc40a7c67eb1603a55fdb5c56b0fe89b3c260e25
8,226
cpp
C++
openstudiocore/src/model/test/GroundHeatExchangerVertical_GTest.cpp
hongyuanjia/OpenStudio
6cc52f1b66c069cf13f2b6ca2a0cc3c137c37cf0
[ "MIT" ]
1
2019-04-21T15:38:54.000Z
2019-04-21T15:38:54.000Z
openstudiocore/src/model/test/GroundHeatExchangerVertical_GTest.cpp
hongyuanjia/OpenStudio
6cc52f1b66c069cf13f2b6ca2a0cc3c137c37cf0
[ "MIT" ]
null
null
null
openstudiocore/src/model/test/GroundHeatExchangerVertical_GTest.cpp
hongyuanjia/OpenStudio
6cc52f1b66c069cf13f2b6ca2a0cc3c137c37cf0
[ "MIT" ]
1
2019-07-18T06:52:29.000Z
2019-07-18T06:52:29.000Z
/*********************************************************************************************************************** * OpenStudio(R), Copyright (c) 2008-2018, Alliance for Sustainable Energy, LLC. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following * disclaimer. * * (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other materials provided with the distribution. * * (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote * products derived from this software without specific prior written permission from the respective party. * * (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative * works may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without * specific prior written permission from Alliance for Sustainable Energy, LLC. * * 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, THE UNITED STATES GOVERNMENT, OR ANY CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **********************************************************************************************************************/ #include <gtest/gtest.h> #include "ModelFixture.hpp" #include "../GroundHeatExchangerVertical.hpp" #include "../GroundHeatExchangerVertical_Impl.hpp" #include "../AirLoopHVAC.hpp" #include "../PlantLoop.hpp" #include "../Node.hpp" #include "../Node_Impl.hpp" #include "../AirLoopHVACZoneSplitter.hpp" using namespace openstudio; using namespace openstudio::model; TEST_F(ModelFixture, GroundHeatExchangerVertical_DefaultConstructor) { ::testing::FLAGS_gtest_death_test_style = "threadsafe"; ASSERT_EXIT ( { Model model; GroundHeatExchangerVertical testObject = GroundHeatExchangerVertical(model); exit(0); } , ::testing::ExitedWithCode(0), "" ); } TEST_F(ModelFixture, GroundHeatExchangerVertical_Connections) { Model m; GroundHeatExchangerVertical testObject(m); Node inletNode(m); Node outletNode(m); m.connect(inletNode,inletNode.outletPort(),testObject,testObject.inletPort()); m.connect(testObject,testObject.outletPort(),outletNode,outletNode.inletPort()); ASSERT_TRUE( testObject.inletModelObject() ); ASSERT_TRUE( testObject.outletModelObject() ); EXPECT_EQ( inletNode.handle(), testObject.inletModelObject()->handle() ); EXPECT_EQ( outletNode.handle(), testObject.outletModelObject()->handle() ); } TEST_F(ModelFixture, GroundHeatExchangerVertical_addToNode) { Model m; GroundHeatExchangerVertical testObject(m); AirLoopHVAC airLoop(m); Node supplyOutletNode = airLoop.supplyOutletNode(); EXPECT_FALSE(testObject.addToNode(supplyOutletNode)); EXPECT_EQ( (unsigned)2, airLoop.supplyComponents().size() ); Node inletNode = airLoop.zoneSplitter().lastOutletModelObject()->cast<Node>(); EXPECT_FALSE(testObject.addToNode(inletNode)); EXPECT_EQ((unsigned)5, airLoop.demandComponents().size()); PlantLoop plantLoop(m); supplyOutletNode = plantLoop.supplyOutletNode(); EXPECT_TRUE(testObject.addToNode(supplyOutletNode)); EXPECT_EQ( (unsigned)7, plantLoop.supplyComponents().size() ); Node demandOutletNode = plantLoop.demandOutletNode(); EXPECT_FALSE(testObject.addToNode(demandOutletNode)); EXPECT_EQ( (unsigned)5, plantLoop.demandComponents().size() ); GroundHeatExchangerVertical testObjectClone = testObject.clone(m).cast<GroundHeatExchangerVertical>(); supplyOutletNode = plantLoop.supplyOutletNode(); EXPECT_TRUE(testObjectClone.addToNode(supplyOutletNode)); EXPECT_EQ( (unsigned)9, plantLoop.supplyComponents().size() ); } TEST_F(ModelFixture, GroundHeatExchangerVertical_AddRemoveSupplyBranchForComponent) { Model model; GroundHeatExchangerVertical testObject(model); PlantLoop plantLoop(model); EXPECT_TRUE(plantLoop.addSupplyBranchForComponent(testObject)); EXPECT_EQ((unsigned)7, plantLoop.supplyComponents().size()); EXPECT_NE((unsigned)9, plantLoop.supplyComponents().size()); EXPECT_TRUE(testObject.inletPort()); EXPECT_TRUE(testObject.outletPort()); EXPECT_TRUE(plantLoop.removeSupplyBranchWithComponent(testObject)); EXPECT_EQ((unsigned)5, plantLoop.supplyComponents().size()); EXPECT_NE((unsigned)7, plantLoop.supplyComponents().size()); } TEST_F(ModelFixture, GroundHeatExchangerVertical_AddDemandBranchForComponent) { Model model; GroundHeatExchangerVertical testObject(model); PlantLoop plantLoop(model); EXPECT_FALSE(plantLoop.addDemandBranchForComponent(testObject)); EXPECT_EQ((unsigned)5, plantLoop.demandComponents().size()); EXPECT_NE((unsigned)7, plantLoop.demandComponents().size()); } TEST_F(ModelFixture, GroundHeatExchangerVertical_AddToNodeTwoSameObjects) { Model model; GroundHeatExchangerVertical testObject(model); PlantLoop plantLoop(model); Node supplyOutletNode = plantLoop.supplyOutletNode(); testObject.addToNode(supplyOutletNode); supplyOutletNode = plantLoop.supplyOutletNode(); EXPECT_FALSE(testObject.addToNode(supplyOutletNode)); } TEST_F(ModelFixture, GroundHeatExchangerVertical_Remove) { Model model; GroundHeatExchangerVertical testObject(model); PlantLoop plantLoop(model); Node supplyOutletNode = plantLoop.supplyOutletNode(); testObject.addToNode(supplyOutletNode); EXPECT_EQ((unsigned)7, plantLoop.supplyComponents().size()); testObject.remove(); EXPECT_EQ((unsigned)5, plantLoop.supplyComponents().size()); } //test cloning the object TEST_F(ModelFixture, GroundHeatExchangerVertical_Clone){ Model m; //make an object to clone, and edit some property to make sure the clone worked GroundHeatExchangerVertical testObject(m); testObject.setMaximumFlowRate(3.14); //clone into the same model GroundHeatExchangerVertical testObjectClone = testObject.clone(m).cast<GroundHeatExchangerVertical>(); EXPECT_EQ(3.14,testObjectClone.maximumFlowRate()); //clone into another model Model m2; GroundHeatExchangerVertical testObjectClone2 = testObject.clone(m2).cast<GroundHeatExchangerVertical>(); EXPECT_EQ(3.14,testObjectClone2.maximumFlowRate()); EXPECT_NE(testObjectClone2, testObjectClone); EXPECT_NE(testObjectClone2.handle(), testObjectClone.handle()); } TEST_F(ModelFixture, GroundHeatExchangerVertical_GFunctions) { Model model; GroundHeatExchangerVertical testObject(model); std::vector< GFunction > gFunctions = testObject.gFunctions(); EXPECT_EQ(35, gFunctions.size()); testObject.removeAllGFunctions(); gFunctions = testObject.gFunctions(); EXPECT_EQ(0, gFunctions.size()); EXPECT_TRUE(testObject.addGFunction(1.0, 1.5)); gFunctions = testObject.gFunctions(); EXPECT_EQ(1, gFunctions.size()); testObject.addGFunction(2.0, 2.5); testObject.removeGFunction(0); gFunctions = testObject.gFunctions(); EXPECT_EQ(1, gFunctions.size()); EXPECT_DOUBLE_EQ(2.0, gFunctions[0].lnValue()); EXPECT_DOUBLE_EQ(2.5, gFunctions[0].gValue()); testObject.removeAllGFunctions(); for (int i=0; i<100; i++) { testObject.addGFunction(i, i + 0.5); } gFunctions = testObject.gFunctions(); EXPECT_EQ(100, gFunctions.size()); EXPECT_THROW(testObject.addGFunction(1.0, 1.5), openstudio::Exception); }
37.221719
120
0.752127
hongyuanjia
dc4172443571ea59ac06aa0e3f45d066c5e10c74
3,568
cpp
C++
regression/reference/example/pyUserLibrarymodule.cpp
ExternalRepositories/shroud
86c39d2324d947d28055f9024f52cc493eb0c813
[ "BSD-3-Clause" ]
73
2017-10-11T17:01:50.000Z
2022-01-01T21:42:12.000Z
regression/reference/example/pyUserLibrarymodule.cpp
ExternalRepositories/shroud
86c39d2324d947d28055f9024f52cc493eb0c813
[ "BSD-3-Clause" ]
29
2018-03-21T19:34:29.000Z
2022-02-04T18:13:14.000Z
regression/reference/example/pyUserLibrarymodule.cpp
ExternalRepositories/shroud
86c39d2324d947d28055f9024f52cc493eb0c813
[ "BSD-3-Clause" ]
8
2017-11-22T14:27:01.000Z
2022-03-30T08:49:03.000Z
// pyUserLibrarymodule.cpp // This file is generated by Shroud nowrite-version. Do not edit. // Copyright (c) 2017-2021, Lawrence Livermore National Security, LLC and // other Shroud Project Developers. // See the top-level COPYRIGHT file for details. // // SPDX-License-Identifier: (BSD-3-Clause) // #include "pyUserLibrarymodule.hpp" #define PY_ARRAY_UNIQUE_SYMBOL SHROUD_USERLIBRARY_ARRAY_API #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include "numpy/arrayobject.h" // splicer begin include // splicer end include #ifdef __cplusplus #define SHROUD_UNUSED(param) #else #define SHROUD_UNUSED(param) param #endif #if PY_MAJOR_VERSION >= 3 #define PyInt_AsLong PyLong_AsLong #define PyInt_FromLong PyLong_FromLong #define PyInt_FromSize_t PyLong_FromSize_t #define PyString_FromString PyUnicode_FromString #define PyString_FromStringAndSize PyUnicode_FromStringAndSize #endif // splicer begin C_definition // splicer end C_definition PyObject *PP_error_obj; PyObject *PP_init_userlibrary_example_nested(void); PyObject *PP_init_userlibrary_example(void); // splicer begin additional_functions // splicer end additional_functions static PyMethodDef PP_methods[] = { {nullptr, (PyCFunction)nullptr, 0, nullptr} /* sentinel */ }; /* * inituserlibrary - Initialization function for the module * *must* be called inituserlibrary */ static char PP__doc__[] = "library documentation" ; struct module_state { PyObject *error; }; #if PY_MAJOR_VERSION >= 3 #define GETSTATE(m) ((struct module_state*)PyModule_GetState(m)) #else #define GETSTATE(m) (&_state) static struct module_state _state; #endif #if PY_MAJOR_VERSION >= 3 static int userlibrary_traverse(PyObject *m, visitproc visit, void *arg) { Py_VISIT(GETSTATE(m)->error); return 0; } static int userlibrary_clear(PyObject *m) { Py_CLEAR(GETSTATE(m)->error); return 0; } static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "userlibrary", /* m_name */ PP__doc__, /* m_doc */ sizeof(struct module_state), /* m_size */ PP_methods, /* m_methods */ nullptr, /* m_reload */ userlibrary_traverse, /* m_traverse */ userlibrary_clear, /* m_clear */ NULL /* m_free */ }; #define RETVAL m #define INITERROR return nullptr #else #define RETVAL #define INITERROR return #endif extern "C" PyMODINIT_FUNC #if PY_MAJOR_VERSION >= 3 PyInit_userlibrary(void) #else inituserlibrary(void) #endif { PyObject *m = nullptr; const char * error_name = "userlibrary.Error"; // splicer begin C_init_locals // splicer end C_init_locals /* Create the module and add the functions */ #if PY_MAJOR_VERSION >= 3 m = PyModule_Create(&moduledef); #else m = Py_InitModule4("userlibrary", PP_methods, PP__doc__, (PyObject*)nullptr,PYTHON_API_VERSION); #endif if (m == nullptr) return RETVAL; struct module_state *st = GETSTATE(m); import_array(); { PyObject *submodule = PP_init_userlibrary_example(); if (submodule == nullptr) INITERROR; Py_INCREF(submodule); PyModule_AddObject(m, (char *) "example", submodule); } PP_error_obj = PyErr_NewException((char *) error_name, nullptr, nullptr); if (PP_error_obj == nullptr) return RETVAL; st->error = PP_error_obj; PyModule_AddObject(m, "Error", st->error); // splicer begin C_init_body // splicer end C_init_body /* Check for errors */ if (PyErr_Occurred()) Py_FatalError("can't initialize module userlibrary"); return RETVAL; }
25.126761
77
0.71889
ExternalRepositories
dc42d4f656d36b3228e4cc905fd4ae855bd88645
1,529
cpp
C++
test/function/leak/target.cpp
Jk-bit/stumpless
e7374b7b9f5618b335c5e657c759a5c47fb8499f
[ "Apache-2.0" ]
28
2019-03-20T22:33:11.000Z
2022-03-19T16:59:21.000Z
test/function/leak/target.cpp
Jk-bit/stumpless
e7374b7b9f5618b335c5e657c759a5c47fb8499f
[ "Apache-2.0" ]
204
2017-10-08T22:26:31.000Z
2022-03-26T16:16:51.000Z
test/function/leak/target.cpp
Jk-bit/stumpless
e7374b7b9f5618b335c5e657c759a5c47fb8499f
[ "Apache-2.0" ]
30
2020-01-17T17:48:49.000Z
2022-03-13T06:18:20.000Z
// SPDX-License-Identifier: Apache-2.0 /* * Copyright 2019-2020 Joel E. Anderson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stddef.h> #include <stumpless.h> #include <gtest/gtest.h> #include "test/helper/memory_counter.hpp" #define TEST_BUFFER_LENGTH 2048 NEW_MEMORY_COUNTER( add_message_leak ) namespace { TEST( AddMessageLeakTest, TypicalUse ) { struct stumpless_target *target; char buffer[TEST_BUFFER_LENGTH]; int i; int add_result; INIT_MEMORY_COUNTER( add_message_leak ); target = stumpless_open_buffer_target( "add-message-leak-testing", buffer, sizeof( buffer ) ); ASSERT_TRUE( target != NULL ); for( i = 0; i < 1000; i++ ) { add_result = stumpless_add_message( target, "temp message %d", i ); ASSERT_GE( add_result, 0 ); } stumpless_close_buffer_target( target ); stumpless_free_all( ); ASSERT_NO_LEAK( add_message_leak ); } }
27.8
75
0.671681
Jk-bit
dc43ac26e14ecadfa5e82081eaa80a7b45c1a934
5,295
cpp
C++
Source/ObjectProxy.cpp
nolancs/OrangeMUD
3db3ddf73855bb76110d7a6a8e67271c36652b04
[ "MIT" ]
4
2020-01-25T04:20:07.000Z
2022-01-14T02:59:28.000Z
Source/ObjectProxy.cpp
nolancs/OrangeMUD
3db3ddf73855bb76110d7a6a8e67271c36652b04
[ "MIT" ]
null
null
null
Source/ObjectProxy.cpp
nolancs/OrangeMUD
3db3ddf73855bb76110d7a6a8e67271c36652b04
[ "MIT" ]
1
2020-04-01T04:36:48.000Z
2020-04-01T04:36:48.000Z
/****************************************************************************** Author: Matthew Nolan OrangeMUD Codebase Date: January 2001 [Crossplatform] License: MIT License 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. Copyright 2000-2019 Matthew Nolan, All Rights Reserved ******************************************************************************/ #include "CommonTypes.h" #include "ObjectIndex.h" #include "ObjectProxy.h" ObjectProxy::ObjectProxy() : mObject(NULL) { } ObjectProxy::~ObjectProxy() { } bool ObjectProxy::IsCustom() { return mCustomObject.IsNull() ? false : true; } void ObjectProxy::Customize() { if(mCustomObject.Ptr()) return; APtr<ObjectData> nCustom(new ObjectData(GetIndex())); mCustomObject = nCustom.Detach(); mObject = mCustomObject; } void ObjectProxy::Revert() { mCustomObject.Dispose(); mObject = GetIndex()->GetFlyweight(); ASSERT(mObject); } #if 0 //***************************************************************************// /////////////////////////////////////////////////////////////////////////////// //***************************************************************************// #pragma mark - #endif const STRINGCW& ObjectProxy::Name() const { return mObject->mName; } const STRINGCW& ObjectProxy::PName() const { return mObject->mPName; } const STRINGCW& ObjectProxy::Keywords() const { return mObject->mKeywords; } const STRINGCW& ObjectProxy::ShortDesc() const { return mObject->mShortDesc; } const STRINGCW& ObjectProxy::PShortDesc() const { return mObject->mPShortDesc; } const STRINGCW& ObjectProxy::Description() const { return mObject->mDescription; } LONG ObjectProxy::Value(SHORT hIndex) const { return mObject->mValue[hIndex]; } LONG ObjectProxy::WearFlags() const { return GetIndex()->mWearFlags; } SHORT ObjectProxy::ItemType() const { return GetIndex()->mItemType; } float ObjectProxy::Weight() const { return mObject->mWeight; } #if 0 //***************************************************************************// /////////////////////////////////////////////////////////////////////////////// //***************************************************************************// #pragma mark - #endif STRINGCW& ObjectProxy::xName() { Customize(); return mObject->mName; } STRINGCW& ObjectProxy::xPName() { Customize(); return mObject->mPName; } STRINGCW& ObjectProxy::xKeywords() { Customize(); return mObject->mKeywords; } STRINGCW& ObjectProxy::xShortDesc() { Customize(); return mObject->mShortDesc; } STRINGCW& ObjectProxy::xPShortDesc() { Customize(); return mObject->mPShortDesc; } STRINGCW& ObjectProxy::xDescription() { Customize(); return mObject->mDescription; } LONG& ObjectProxy::xValue(SHORT hIndex) { Customize(); return mObject->mValue[hIndex]; } #if 0 //***************************************************************************// /////////////////////////////////////////////////////////////////////////////// //***************************************************************************// #pragma mark - #endif ObjectData::ObjectData(ObjectIndex* hLikeObj) { ASSERT(hLikeObj); mName = hLikeObj->mName; mPName = hLikeObj->mPName; mKeywords = hLikeObj->mKeywords; mShortDesc = hLikeObj->mShortDesc; mPShortDesc = hLikeObj->mPShortDesc; mDescription = hLikeObj->mDescription; mItemType = hLikeObj->mItemType; mLevel = hLikeObj->mLevel; mWeight = hLikeObj->mWeight; mMaterials = hLikeObj->mMaterials; mAntiFlags = hLikeObj->mAntiFlags; mObjectFlags = hLikeObj->mObjectFlags; mValue[0] = hLikeObj->mValue[0]; mValue[1] = hLikeObj->mValue[1]; mValue[2] = hLikeObj->mValue[2]; mValue[3] = hLikeObj->mValue[3]; mValue[4] = hLikeObj->mValue[4]; //Only exist in Customized Objects: mAge = 0; mOwner = ""; mTimer = 0; mEnchantment = 0; } ObjectData::~ObjectData() { }
19.046763
79
0.552786
nolancs
dc465eb06aee5b46116e2c94acc01f27161d8217
5,761
cpp
C++
src/DialogManager/DialogManager/src/CExpressionPicker.cpp
xylsxyls/xueyelingshuan
61eb1c7c4f76c3eaf4cf26e4b2b37b6ed2abc5b9
[ "MIT" ]
3
2019-11-26T05:33:47.000Z
2020-05-18T06:49:41.000Z
src/DialogManager/DialogManager/src/CExpressionPicker.cpp
xylsxyls/xueyelingshuan
61eb1c7c4f76c3eaf4cf26e4b2b37b6ed2abc5b9
[ "MIT" ]
null
null
null
src/DialogManager/DialogManager/src/CExpressionPicker.cpp
xylsxyls/xueyelingshuan
61eb1c7c4f76c3eaf4cf26e4b2b37b6ed2abc5b9
[ "MIT" ]
null
null
null
#include "CExpressionPicker.h" #include <QHeaderView> #include <QMouseEvent> #include "CExpressionPickerDelegate.h" #include <QDebug> CExpressionPicker::CExpressionPicker(QWidget *parent) :QTableView(parent) ,mModel(new QStandardItemModel(this)) ,mPreView(new QLabel(this)) ,mShowPreView(false) ,mShowIconRect(true) ,mMaxColumnCount(12) ,mMaxRowCount(4) ,mMovie(new QMovie(this)) { this->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); this->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); this->horizontalHeader()->setVisible(false); this->verticalHeader()->setVisible(false); this->horizontalHeader()->setDefaultSectionSize(33); this->verticalHeader()->setDefaultSectionSize(33); this->setEditTriggers(QTableView::NoEditTriggers); this->setSelectionMode(QTableView::SingleSelection); this->setShowGrid(false); this->setMouseTracking(true); this->setStyleSheet("QTableView{background-color:rgba(0,0,0,0);border:none;}"); this->setModel(mModel); connect(this, &CExpressionPicker::clicked, this, &CExpressionPicker::onClicked); //delegate CExpressionPickerDelegate* tdelegate = new CExpressionPickerDelegate; tdelegate->setParent(this); this->setItemDelegate(tdelegate); //pre viewer mPreView->setMouseTracking(true); mPreView->hide(); mPreView->resize(33*2,33*2); mPreView->setStyleSheet("background-color:white;"); mPreView->installEventFilter(this); mMovie->setScaledSize(mPreView->size()); mMovie->setCacheMode(QMovie::CacheAll); mPreView->setMovie(mMovie); } CExpressionPicker::~CExpressionPicker() { } void CExpressionPicker::setShowPreView(bool s) { mShowPreView = s; } bool CExpressionPicker::isShowPreView() { return mShowPreView; } void CExpressionPicker::setShowIconRect(bool s) { mShowIconRect = s; } bool CExpressionPicker::isShowIconRect() { return mShowIconRect; } void CExpressionPicker::setExpressionList(const CExpressionPicker::ExpressionList &li) { mExpressionList = li; mModel->clear(); int capacity = this->maxRowCount()*this->maxColumnCount(); int tSize = capacity <= li.count() ? capacity : li.count(); for(int i = 0; i < tSize; i++) { Expression exp = li[i]; QStandardItem* item = new QStandardItem("expression"); item->setData(exp.desc , ExpressionRole_Desc); item->setData(exp.fileName , ExpressionRole_FileName); item->setData(exp.groupid , ExpressionRole_GroupId); item->setData(exp.id , ExpressionRole_Id); item->setData(exp.shortcut , ExpressionRole_Shortcut); item->setData(exp.tooltip , ExpressionRole_Tooltip); item->setToolTip(exp.tooltip); int currentColumn = i % this->maxColumnCount(); int currentRow = i / this->maxColumnCount(); mModel->setItem(currentRow, currentColumn, item); } } CExpressionPicker::ExpressionList CExpressionPicker::expressionList() { return mExpressionList; } void CExpressionPicker::setMaxColumnCount(int n) { mMaxColumnCount = n; } void CExpressionPicker::setMaxRowCount(int n) { mMaxRowCount = n; } int CExpressionPicker::maxColumnCount() { return mMaxColumnCount; } int CExpressionPicker::maxRowCount() { return mMaxRowCount; } void CExpressionPicker::leaveEvent(QEvent *e) { QTableView::leaveEvent(e); mPreView->hide(); } void CExpressionPicker::mouseMoveEvent(QMouseEvent *e) { QTableView::mouseMoveEvent(e); if(!this->isShowPreView()) { mPreView->hide(); return; } //movie QModelIndex tindex = this->indexAt(e->pos()); if(!tindex.isValid() || !tindex.data(ExpressionRole_Id).isValid()) { mPreView->hide(); return; } if(e->x() <= mPreView->width()) { mPreView->move(this->width() - mPreView->width() - 1, 0 + 1); } else { mPreView->move(1,1); } mPreView->show(); QString filename = tindex.data(ExpressionRole_FileName).toString(); if(filename != mMovie->fileName()) { mMovie->stop(); mMovie->setFileName(filename); mMovie->start(); } } bool CExpressionPicker::eventFilter(QObject *obj, QEvent *e) { bool res = QTableView::eventFilter(obj,e); if (obj == nullptr || e == nullptr) { return res; } if(obj == mPreView) { if(e->type() == QEvent::MouseMove) { if(mPreView->pos() != QPoint(0,0)) { mPreView->move(0,0); } else { mPreView->move(this->width() - mPreView->width(), 0); } } if(e->type() == QEvent::Hide) { mMovie->stop(); } if(e->type() == QEvent::Show) { mMovie->start(); } } return res; } void CExpressionPicker::onClicked(const QModelIndex &index) { if(!index.isValid()) return; if(!index.data(ExpressionRole_Id).isValid()) return; Expression exp; exp.desc = index.data(ExpressionRole_Desc ).toString(); exp.fileName = index.data(ExpressionRole_FileName ).toString(); exp.groupid = index.data(ExpressionRole_GroupId ).toString(); exp.id = index.data(ExpressionRole_Id ).toString(); exp.shortcut = index.data(ExpressionRole_Shortcut ).toString(); exp.tooltip = index.data(ExpressionRole_Tooltip ).toString(); emit expressionClicked(exp); }
25.267544
87
0.619511
xylsxyls
dc469b8ca9fec546a251c4f9eb45ca3db0986ab9
2,777
cpp
C++
Source/Services/Misc/contextual_search_game_clip_uri_info.cpp
claytonv/xbox-live-api
d8db86cf930085c7547ae95999c9b301506de343
[ "MIT" ]
3
2020-07-15T17:50:24.000Z
2021-11-17T11:15:11.000Z
Source/Services/Misc/contextual_search_game_clip_uri_info.cpp
CameronGoodwin/xbox-live-api
ee0c3ee2413f2fed6a373df4b26035792e922fe2
[ "MIT" ]
null
null
null
Source/Services/Misc/contextual_search_game_clip_uri_info.cpp
CameronGoodwin/xbox-live-api
ee0c3ee2413f2fed6a373df4b26035792e922fe2
[ "MIT" ]
1
2021-02-01T01:56:08.000Z
2021-02-01T01:56:08.000Z
// Copyright (c) Microsoft Corporation // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include "pch.h" #include "xsapi/contextual_search_service.h" NAMESPACE_MICROSOFT_XBOX_SERVICES_CONTEXTUAL_SEARCH_CPP_BEGIN contextual_search_game_clip_uri_info::contextual_search_game_clip_uri_info() : m_fileSize(0), m_uriType(contextual_search_game_clip_uri_type::none) { } contextual_search_game_clip_uri_info::contextual_search_game_clip_uri_info( _In_ web::uri url, _In_ uint64_t fileSize, _In_ contextual_search_game_clip_uri_type uriType, _In_ utility::datetime expiration ) : m_url(std::move(url)), m_fileSize(fileSize), m_uriType(uriType), m_expiration(std::move(expiration)) { } contextual_search_game_clip_uri_type contextual_search_game_clip_uri_info::convert_string_to_clip_uri_type(_In_ const string_t& value) { if (utils::str_icmp(value, _T("Original")) == 0) { return contextual_search_game_clip_uri_type::original; } else if (utils::str_icmp(value, _T("Download")) == 0) { return contextual_search_game_clip_uri_type::download; } else if (utils::str_icmp(value, _T("Ahls")) == 0) { return contextual_search_game_clip_uri_type::http_live_streaming; } else if (utils::str_icmp(value, _T("SmoothStreaming")) == 0) { return contextual_search_game_clip_uri_type::smooth_streaming; } return contextual_search_game_clip_uri_type::none; } xbox_live_result<contextual_search_game_clip_uri_info> contextual_search_game_clip_uri_info::_Deserialize(_In_ const web::json::value& inputJson) { if (inputJson.is_null()) return xbox_live_result<contextual_search_game_clip_uri_info>(); std::error_code errc = xbox_live_error_code::no_error; contextual_search_game_clip_uri_info result( utils::extract_json_string(inputJson, _T("Uri"), errc, false), utils::extract_json_uint52(inputJson, _T("FileSize"), errc, false), convert_string_to_clip_uri_type(utils::extract_json_string(inputJson, _T("UriType"), errc, false)), utils::extract_json_time(inputJson, _T("Expiration"), errc, false) ); return xbox_live_result<contextual_search_game_clip_uri_info>(result, errc); } const web::uri& contextual_search_game_clip_uri_info::url() const { return m_url; } uint64_t contextual_search_game_clip_uri_info::file_size() const { return m_fileSize; } contextual_search_game_clip_uri_type contextual_search_game_clip_uri_info::uri_type() const { return m_uriType; } const utility::datetime& contextual_search_game_clip_uri_info::expiration() const { return m_expiration; } NAMESPACE_MICROSOFT_XBOX_SERVICES_CONTEXTUAL_SEARCH_CPP_END
30.855556
107
0.764494
claytonv
dc4e683a355e65a3d1e39c1feca306c11c8830cb
8,329
cpp
C++
Source/FSD/Private/FSDWidgetBlueprintLibrary.cpp
Dr-Turtle/DRG_ModPresetManager
abd7ff98a820969504491a1fe68cf2f9302410dc
[ "MIT" ]
8
2021-07-10T20:06:05.000Z
2022-03-04T19:03:50.000Z
Source/FSD/Private/FSDWidgetBlueprintLibrary.cpp
Dr-Turtle/DRG_ModPresetManager
abd7ff98a820969504491a1fe68cf2f9302410dc
[ "MIT" ]
9
2022-01-13T20:49:44.000Z
2022-03-27T22:56:48.000Z
Source/FSD/Private/FSDWidgetBlueprintLibrary.cpp
Dr-Turtle/DRG_ModPresetManager
abd7ff98a820969504491a1fe68cf2f9302410dc
[ "MIT" ]
2
2021-07-10T20:05:42.000Z
2022-03-14T17:05:35.000Z
#include "FSDWidgetBlueprintLibrary.h" #include "Templates/SubclassOf.h" class UObject; class UWidget; class UHorizontalBox; class UUserWidget; class UWidgetAnimation; class USizeBox; class UPanelWidget; class UTextBlock; class UImage; class UWindowWidget; class AFSDPlayerState; class UFSDCheatManager; class APlayerController; class UVerticalBox; class USpacer; class UTexture2D; class UHorizontalBoxSlot; class UVerticalBoxSlot; class UUniformGridPanel; class UUniformGridSlot; void UFSDWidgetBlueprintLibrary::ToggleAnimationLooping(UObject* WorldContext, UWidgetAnimation* InAnimation, FWidgetAnimationSettings InSettings, bool InLoop, bool& OutPlayingChanged, bool& OutIsPlaying) { } bool UFSDWidgetBlueprintLibrary::TextSmallerThan(const FText& Text1, const FText& Text2) { return false; } bool UFSDWidgetBlueprintLibrary::TextGreaterThan(const FText& Text1, const FText& Text2) { return false; } TArray<UWidget*> UFSDWidgetBlueprintLibrary::SortWidgetArray(const TArray<UWidget*>& InWidgets, const FFSDWidgetBlueprintLibraryInCompareFunction& InCompareFunction) { return TArray<UWidget*>(); } void UFSDWidgetBlueprintLibrary::SimpleBox(FPaintContext& Context, FVector2D Position, FVector2D Size, FLinearColor Tint) { } FTimerHandle UFSDWidgetBlueprintLibrary::SetTimerForNextTick(UObject* WorldContext, const FFSDWidgetBlueprintLibraryTimerDelegate& TimerDelegate) { return FTimerHandle{}; } void UFSDWidgetBlueprintLibrary::SetSizeBoxSettings(USizeBox*& InSizeBox, const FSizeBoxSettings& InSettings) { } void UFSDWidgetBlueprintLibrary::SetMousePosition(UObject* WorldContextObject, int32 X, int32 Y) { } void UFSDWidgetBlueprintLibrary::SetChildrenVisibility(UPanelWidget* Panel, ESlateVisibility Visibility, int32 StartIndex, TSubclassOf<UUserWidget> OptionalClassFilter) { } void UFSDWidgetBlueprintLibrary::ScrubAnimation(UObject* WorldContext, UWidgetAnimation* InAnimation, float Progress01) { } void UFSDWidgetBlueprintLibrary::ScaleTextBlockToHeight(UTextBlock* TextBlock, float TargetHeight, bool SetMinimimumWidth) { } void UFSDWidgetBlueprintLibrary::ScaleImageToHeight(UImage* Image, float TargetHeight) { } void UFSDWidgetBlueprintLibrary::PrintStrings(UObject* WorldContextObject, const TArray<FString>& InStrings, bool bPrintToScreen, bool bPrintToLog, FLinearColor TextColor, float Duration) { } FString UFSDWidgetBlueprintLibrary::MidIgnoringWhiteSpace(const FString& Source, int32 Index, int32 count) { return TEXT(""); } FVector2D UFSDWidgetBlueprintLibrary::MeasureTextSize(const FText& Text, const FSlateFontInfo& Font) { return FVector2D{}; } FVector2D UFSDWidgetBlueprintLibrary::MeasureTextBlockSize(const UTextBlock* TextBlock) { return FVector2D{}; } void UFSDWidgetBlueprintLibrary::Line(FPaintContext& Context, FVector2D Pos1, FVector2D Pos2, FLinearColor Tint) { } FLinearColor UFSDWidgetBlueprintLibrary::LerpColors(const TArray<FLinearColor>& Colors, bool Interpolate, float Progress01) { return FLinearColor{}; } int32 UFSDWidgetBlueprintLibrary::LengthIgnoringWhitespace(const FString& Source) { return 0; } bool UFSDWidgetBlueprintLibrary::IsWindowsPlatform(UObject* WorldContextObject) { return false; } bool UFSDWidgetBlueprintLibrary::IsWhiteSpaceAt(const FString& Source, int32 Index) { return false; } bool UFSDWidgetBlueprintLibrary::IsWhiteSpace(const FString& Source) { return false; } bool UFSDWidgetBlueprintLibrary::IsHUDVisible(UObject* WorldContextObject) { return false; } FString UFSDWidgetBlueprintLibrary::IntToRomanNumeral(int32 Value) { return TEXT(""); } bool UFSDWidgetBlueprintLibrary::HasAnyVisibleChildren(UPanelWidget* Panel, int32 StartIndex, TSubclassOf<UUserWidget> OptionalClassFilter) { return false; } FString UFSDWidgetBlueprintLibrary::GetShortTimeString(int32 TotalSeconds, bool BlinkDelimiter) { return TEXT(""); } UWindowWidget* UFSDWidgetBlueprintLibrary::GetParentWindowWidget(UUserWidget* InWidget) { return NULL; } UUserWidget* UFSDWidgetBlueprintLibrary::GetParentUserWidget(UUserWidget* InWidget) { return NULL; } AFSDPlayerState* UFSDWidgetBlueprintLibrary::GetOwningFSDPlayerState(UWidget* Target) { return NULL; } FText UFSDWidgetBlueprintLibrary::GetKeyName(const FKey& Key) { return FText::GetEmpty(); } float UFSDWidgetBlueprintLibrary::GetFontMaxHeight(const FSlateFontInfo& Font) { return 0.0f; } float UFSDWidgetBlueprintLibrary::GetFontBaseline(const FSlateFontInfo& Font) { return 0.0f; } UWidget* UFSDWidgetBlueprintLibrary::GetFocusedWidget(UObject* WorldContextObject, APlayerController* Controller) { return NULL; } UUserWidget* UFSDWidgetBlueprintLibrary::GetFocusableParentUserWidget(UUserWidget* InWidget) { return NULL; } FVector2D UFSDWidgetBlueprintLibrary::GetDrawSize(FPaintContext& InContext) { return FVector2D{}; } UFSDCheatManager* UFSDWidgetBlueprintLibrary::GetCheatManager(UObject* WorldContextObject) { return NULL; } UWidget* UFSDWidgetBlueprintLibrary::FindChildWidget(UPanelWidget*& ParentWidget, TSubclassOf<UUserWidget> WidgetClass, bool SearchChildren) { return NULL; } UVerticalBox* UFSDWidgetBlueprintLibrary::CreateVerticalBox(UObject* WorldContext) { return NULL; } UTextBlock* UFSDWidgetBlueprintLibrary::CreateTextBlock(UObject* WorldContext, FText Text, FSlateFontInfo Font, TEnumAsByte<ETextJustify::Type> Justification, FLinearColor Color, bool WrapText) { return NULL; } USpacer* UFSDWidgetBlueprintLibrary::CreateSpacer(UObject* WorldContext, FVector2D Size) { return NULL; } TArray<UUserWidget*> UFSDWidgetBlueprintLibrary::CreateOrReuseChildrenWithCallbackEx(UPanelWidget* Panel, int32 count, TSubclassOf<UUserWidget> WidgetClass, const FFSDWidgetBlueprintLibraryOnCreatedOrReused& OnCreatedOrReused, const FFSDWidgetBlueprintLibraryOnCollapsed& OnCollapsed) { return TArray<UUserWidget*>(); } TArray<UUserWidget*> UFSDWidgetBlueprintLibrary::CreateOrReuseChildrenWithCallback(UPanelWidget* Panel, int32 count, TSubclassOf<UUserWidget> WidgetClass, const FFSDWidgetBlueprintLibraryOnCreatedOrReused& OnCreatedOrReused) { return TArray<UUserWidget*>(); } TArray<UUserWidget*> UFSDWidgetBlueprintLibrary::CreateOrReuseChildren(UPanelWidget* Panel, int32 count, TSubclassOf<UUserWidget> WidgetClass) { return TArray<UUserWidget*>(); } UImage* UFSDWidgetBlueprintLibrary::CreateImageSized(UObject* WorldContext, UTexture2D* Texture, FLinearColor Tint, FVector2D Size) { return NULL; } UImage* UFSDWidgetBlueprintLibrary::CreateImage(UObject* WorldContext, UTexture2D* Texture, FLinearColor Tint, bool AutoSize) { return NULL; } UHorizontalBox* UFSDWidgetBlueprintLibrary::CreateHorizontalBox(UObject* WorldContext) { return NULL; } FText UFSDWidgetBlueprintLibrary::ClampTextLength(const FText& Text, int32 MaxLength, const FText& CutOffIndicator) { return FText::GetEmpty(); } void UFSDWidgetBlueprintLibrary::Box(FPaintContext& Context, FVector2D Position, FVector2D Size, const FSlateBrush& Brush, FLinearColor Tint) { } UWidget* UFSDWidgetBlueprintLibrary::AddWidgetToRow(UVerticalBox* VerticalBox, UWidget* Widget, int32 MaxWidgetsPerRow, float WidgetSpacing, float RowSpacing, UHorizontalBoxSlot*& OutSlot, UHorizontalBox*& OutRow) { return NULL; } UWidget* UFSDWidgetBlueprintLibrary::AddChildToVerticalBoxEx(UVerticalBox* VerticalBox, UWidget* Widget, TEnumAsByte<EHorizontalAlignment> HorizontalAlignment, TEnumAsByte<EVerticalAlignment> VerticalAlignment, float Size, FMargin Padding, UVerticalBoxSlot*& OutSlot, UVerticalBox*& OutVerticalBox) { return NULL; } UWidget* UFSDWidgetBlueprintLibrary::AddChildToUniformGridEx(UUniformGridPanel* GridPanel, UWidget* Widget, TEnumAsByte<EHorizontalAlignment> HorizontalAlignment, TEnumAsByte<EVerticalAlignment> VerticalAlignment, int32 Column, int32 Row, UUniformGridSlot*& OutSlot, UUniformGridPanel*& OutGridPanel) { return NULL; } UWidget* UFSDWidgetBlueprintLibrary::AddChildToHorizontalBoxEx(UHorizontalBox* HorizontalBox, UWidget* Widget, TEnumAsByte<EHorizontalAlignment> HorizontalAlignment, TEnumAsByte<EVerticalAlignment> VerticalAlignment, float Size, FMargin Padding, UHorizontalBoxSlot*& OutSlot, UHorizontalBox*& OutHorizontalBox) { return NULL; } UFSDWidgetBlueprintLibrary::UFSDWidgetBlueprintLibrary() { }
37.017778
312
0.817505
Dr-Turtle
dc4e79d12722135d83cc445feee48bd77d308cff
4,491
cpp
C++
App.BeanOfLight/src/AnimalThirdPersonControler.cpp
BeanOfLight/BeanOfLight
ec8ae0d81fd548c2128d6e8ae8860e6e34c36e52
[ "MIT" ]
null
null
null
App.BeanOfLight/src/AnimalThirdPersonControler.cpp
BeanOfLight/BeanOfLight
ec8ae0d81fd548c2128d6e8ae8860e6e34c36e52
[ "MIT" ]
null
null
null
App.BeanOfLight/src/AnimalThirdPersonControler.cpp
BeanOfLight/BeanOfLight
ec8ae0d81fd548c2128d6e8ae8860e6e34c36e52
[ "MIT" ]
null
null
null
#include "AnimalThirdPersonControler.h" #include <OgreMath.h> #include "TerrainUtils.h" const float camDist = 900.f; AnimalThirdPersonControler::AnimalThirdPersonControler() : m_lookAround(false), m_camDistance(camDist), m_camAngularSpeed(0.0015f), m_camHeightOffset(0.f), m_pCamera(nullptr), m_pAnimal(nullptr), m_pTerrainGroup(nullptr) { } AnimalThirdPersonControler::~AnimalThirdPersonControler() { } void AnimalThirdPersonControler::attach(Animal* i_pAnimal, Ogre::Camera* i_pCamera, Ogre::TerrainGroup* i_pTerrainGroup) { m_pAnimal = i_pAnimal; m_pCamera = i_pCamera; m_pTerrainGroup = i_pTerrainGroup; m_camHeightOffset = i_pAnimal->m_heightOffset; if (!(m_pAnimal != nullptr && m_pCamera != nullptr)) return; m_pAnimal->dropOnTerrain(*i_pTerrainGroup); // Position camera m_pCamera->setPosition(m_pAnimal->m_pNode->getPosition() - m_camDistance * m_pAnimal->m_pNode->getOrientation().xAxis()); m_pCamera->lookAt(m_pAnimal->m_pNode->getPosition() + m_pAnimal->m_cameraLookAtOffset); } void AnimalThirdPersonControler::detach() { m_pAnimal = nullptr; m_pCamera = nullptr; } void AnimalThirdPersonControler::alignAnimalToCamera(double i_timeSinceLastFrame) { if (!(m_pAnimal != nullptr && m_pCamera != nullptr)) return; // Find new orientation of avatar Ogre::Vector3 camY = m_pCamera->getDirection(); Ogre::Vector3 aniX = m_pAnimal->m_pNode->getOrientation().xAxis(); Ogre::Vector3 aniY = m_pAnimal->m_pNode->getOrientation().yAxis(); Ogre::Vector3 newAniX = camY.dotProduct(aniX) * aniX + camY.dotProduct(aniY) * aniY; if (newAniX.isZeroLength()) return; newAniX.normalise(); m_pAnimal->turn(newAniX, i_timeSinceLastFrame); } void AnimalThirdPersonControler::move(int i_frontDir, int i_sideDir, bool i_run, double i_timeSinceLastFrame) { if (!(m_pAnimal != nullptr && m_pCamera != nullptr)) return; if (!(i_frontDir == 0 && i_sideDir == 0)) { Ogre::Vector3 oldAniPos = m_pAnimal->m_pNode->getPosition(); m_pAnimal->moveOnTerrain(i_frontDir, i_sideDir, i_run, i_timeSinceLastFrame, *m_pTerrainGroup); Ogre::Vector3 newAniPos = m_pAnimal->m_pNode->getPosition(); // Update cammera Ogre::Vector3 newCamPos = m_pCamera->getPosition() + newAniPos - oldAniPos; Ogre::Vector3 newAvatarToCamera = newCamPos - m_pAnimal->m_pNode->getPosition(); if (newAvatarToCamera.length() != m_camDistance) newAvatarToCamera = newAvatarToCamera.normalisedCopy() * m_camDistance; // Collide with terrain m_collideCamWithTerrain(newAvatarToCamera); } if (!m_lookAround) alignAnimalToCamera(i_timeSinceLastFrame); } void AnimalThirdPersonControler::orient(int i_xRel, int i_yRel, double i_timeSinceLastFrame) { if (!(m_pAnimal != nullptr && m_pCamera != nullptr)) return; Ogre::Vector3 camPos = m_pCamera->getPosition(); Ogre::Radian angleX(i_xRel * -m_camAngularSpeed); Ogre::Radian angleY(i_yRel * -m_camAngularSpeed); Ogre::Vector3 avatarToCamera = m_pCamera->getPosition() - m_pAnimal->m_pNode->getPosition(); // restore lenght if (avatarToCamera.length() != m_camDistance) avatarToCamera = avatarToCamera.normalisedCopy() * m_camDistance; // Do not go to the poles Ogre::Radian latitude = m_pAnimal->m_pNode->getOrientation().zAxis().angleBetween(avatarToCamera); if (latitude < Ogre::Radian(Ogre::Math::DegreesToRadians(10.f)) && angleY < Ogre::Radian(0.f)) angleY = Ogre::Radian(0.f); else if (latitude > Ogre::Radian(Ogre::Math::DegreesToRadians(170.f)) && angleY > Ogre::Radian(0.f)) angleY = Ogre::Radian(0.f); Ogre::Quaternion orient = Ogre::Quaternion(angleY, m_pCamera->getOrientation().xAxis()) * Ogre::Quaternion(angleX, m_pCamera->getOrientation().yAxis()); Ogre::Vector3 newAvatarToCamera = orient * avatarToCamera; // Move camera closer if collides with terrain m_collideCamWithTerrain(newAvatarToCamera); } void AnimalThirdPersonControler::m_collideCamWithTerrain(const Ogre::Vector3& i_avatarToCamera) { // Move camera closer if collides with terrain Ogre::Vector3 colPos, newCamPos; if (rayToTerrain(m_pAnimal->m_pNode->getPosition(), i_avatarToCamera, *m_pTerrainGroup, colPos) && ((m_pAnimal->m_pNode->getPosition() - colPos).length() < m_camDistance + m_camHeightOffset)) { newCamPos = colPos - i_avatarToCamera.normalisedCopy() * m_camHeightOffset; } else { newCamPos = m_pAnimal->m_pNode->getPosition() + i_avatarToCamera; } m_pCamera->setPosition(newCamPos); m_pCamera->lookAt(m_pAnimal->m_pNode->getPosition() + m_pAnimal->m_cameraLookAtOffset); }
32.543478
153
0.754843
BeanOfLight
dc51223a2a6ac53b1f377668309060dc08f17033
1,537
cpp
C++
src/kernels/cpu/roi_align.cpp
ViewFaceCore/TenniS
c1d21a71c1cd025ddbbe29924c8b3296b3520fc0
[ "BSD-2-Clause" ]
null
null
null
src/kernels/cpu/roi_align.cpp
ViewFaceCore/TenniS
c1d21a71c1cd025ddbbe29924c8b3296b3520fc0
[ "BSD-2-Clause" ]
null
null
null
src/kernels/cpu/roi_align.cpp
ViewFaceCore/TenniS
c1d21a71c1cd025ddbbe29924c8b3296b3520fc0
[ "BSD-2-Clause" ]
null
null
null
// // Created by kier on 2019-09-03. // #include "runtime/operator.h" #include "global/operator_factory.h" #include "backend/name.h" #include "core/tensor_builder.h" #include "runtime/stack.h" #include "kernels/cpu/operator_on_cpu.h" #include "backend/base/base_roi_align.h" #include "dragon/roi_align_op.h" /** * THis cpu implement was fork from Dragon, SeetaTech */ namespace ts { namespace cpu { class ROIAlign : public OperatorOnCPU<base::ROIAlign> { public: std::shared_ptr<dragon::ROIAlignOp<dragon::CPUContext>> m_dragon; void init() override { dragon::Workspace ws; m_dragon = std::make_shared<dragon::ROIAlignOp<dragon::CPUContext>>(this, &ws); } int run(Stack &stack) override { m_dragon->bind_outputs(1); m_dragon->bind_inputs(std::vector<Tensor>(stack.begin(), stack.end())); m_dragon->RunOnDevice(); stack.push(Tensor::Pack(m_dragon->outputs())); m_dragon->clean(); return 1; } std::vector<Tensor> roi_align( const std::vector<Tensor> &inputs, int pool_h, int pool_w, float spatial_scale, int sampling_ratio) override { TS_LOG_ERROR << "What a Terrible Failure!" << eject; return {}; } }; } } using namespace ts; using namespace cpu; TS_REGISTER_OPERATOR(ROIAlign, CPU, name::layer::roi_align())
28.462963
95
0.585556
ViewFaceCore
dc51ab493c502205b7f761e6168f2ae218120cc9
59,189
cpp
C++
tests/juliet/testcases/CWE675_Duplicate_Operations_on_Resource/main.cpp
RanerL/analyzer
a401da4680f163201326881802ee535d6cf97f5a
[ "MIT" ]
28
2017-01-20T15:25:54.000Z
2020-03-17T00:28:31.000Z
tests/juliet/testcases/CWE675_Duplicate_Operations_on_Resource/main.cpp
RanerL/analyzer
a401da4680f163201326881802ee535d6cf97f5a
[ "MIT" ]
1
2021-07-12T02:57:17.000Z
2021-07-16T02:07:29.000Z
tests/juliet/testcases/CWE675_Duplicate_Operations_on_Resource/main.cpp
RanerL/analyzer
a401da4680f163201326881802ee535d6cf97f5a
[ "MIT" ]
2
2019-07-15T19:07:04.000Z
2019-09-07T14:21:04.000Z
/* NOTE - eventually this file will be automatically updated using a Perl script that understand * the naming of test case files, functions, and namespaces. */ #include <time.h> /* for time() */ #include <stdlib.h> /* for srand() */ #include "std_testcase.h" #include "testcases.h" int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); globalArgc = argc; globalArgv = argv; #ifndef OMITGOOD /* Calling C good functions */ /* BEGIN-AUTOGENERATED-C-GOOD-FUNCTION-CALLS */ printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_05_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_05_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_66_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_66_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_13_good();"); CWE675_Duplicate_Operations_on_Resource__open_13_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_21_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_21_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_44_good();"); CWE675_Duplicate_Operations_on_Resource__open_44_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_51_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_51_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_14_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_14_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_17_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_17_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_04_good();"); CWE675_Duplicate_Operations_on_Resource__open_04_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_10_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_10_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_17_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_17_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_64_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_64_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_16_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_16_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_64_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_64_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_11_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_11_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_34_good();"); CWE675_Duplicate_Operations_on_Resource__open_34_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_18_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_18_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_02_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_02_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_13_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_13_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_12_good();"); CWE675_Duplicate_Operations_on_Resource__open_12_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_53_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_53_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_44_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_44_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_65_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_65_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_21_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_21_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_31_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_31_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_04_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_04_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_68_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_68_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_22_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_22_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_12_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_12_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_03_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_03_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_54_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_54_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_31_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_31_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_45_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_45_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_45_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_45_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_14_good();"); CWE675_Duplicate_Operations_on_Resource__open_14_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_63_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_63_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_53_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_53_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_15_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_15_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_18_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_18_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_22_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_22_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_05_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_05_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_65_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_65_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_18_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_18_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_14_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_14_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_61_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_61_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_22_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_22_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_17_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_17_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_44_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_44_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_32_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_32_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_10_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_10_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_52_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_52_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_63_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_63_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_32_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_32_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_41_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_41_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_54_good();"); CWE675_Duplicate_Operations_on_Resource__open_54_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_21_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_21_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_08_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_08_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_05_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_05_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_41_good();"); CWE675_Duplicate_Operations_on_Resource__open_41_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_03_good();"); CWE675_Duplicate_Operations_on_Resource__open_03_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_53_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_53_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_05_good();"); CWE675_Duplicate_Operations_on_Resource__open_05_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_02_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_02_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_04_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_04_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_04_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_04_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_42_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_42_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_09_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_09_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_64_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_64_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_11_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_11_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_12_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_12_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_53_good();"); CWE675_Duplicate_Operations_on_Resource__open_53_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_01_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_01_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_10_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_10_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_54_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_54_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_09_good();"); CWE675_Duplicate_Operations_on_Resource__open_09_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_17_good();"); CWE675_Duplicate_Operations_on_Resource__open_17_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_63_good();"); CWE675_Duplicate_Operations_on_Resource__open_63_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_21_good();"); CWE675_Duplicate_Operations_on_Resource__open_21_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_09_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_09_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_61_good();"); CWE675_Duplicate_Operations_on_Resource__open_61_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_66_good();"); CWE675_Duplicate_Operations_on_Resource__open_66_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_07_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_07_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_41_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_41_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_11_good();"); CWE675_Duplicate_Operations_on_Resource__open_11_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_42_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_42_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_34_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_34_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_61_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_61_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_16_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_16_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_34_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_34_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_67_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_67_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_41_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_41_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_15_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_15_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_68_good();"); CWE675_Duplicate_Operations_on_Resource__open_68_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_02_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_02_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_06_good();"); CWE675_Duplicate_Operations_on_Resource__open_06_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_67_good();"); CWE675_Duplicate_Operations_on_Resource__open_67_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_32_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_32_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_54_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_54_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_06_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_06_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_67_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_67_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_03_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_03_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_61_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_61_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_42_good();"); CWE675_Duplicate_Operations_on_Resource__open_42_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_13_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_13_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_13_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_13_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_65_good();"); CWE675_Duplicate_Operations_on_Resource__open_65_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_16_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_16_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_01_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_01_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_01_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_01_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_34_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_34_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_65_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_65_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_11_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_11_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_52_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_52_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_51_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_51_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_16_good();"); CWE675_Duplicate_Operations_on_Resource__open_16_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_08_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_08_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_66_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_66_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_08_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_08_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_22_good();"); CWE675_Duplicate_Operations_on_Resource__open_22_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_12_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_12_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_44_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_44_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_52_good();"); CWE675_Duplicate_Operations_on_Resource__open_52_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_31_good();"); CWE675_Duplicate_Operations_on_Resource__open_31_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_14_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_14_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_07_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_07_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_64_good();"); CWE675_Duplicate_Operations_on_Resource__open_64_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_06_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_06_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_63_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_63_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_45_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_45_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_32_good();"); CWE675_Duplicate_Operations_on_Resource__open_32_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_06_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_06_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_07_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_07_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_52_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_52_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_67_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_67_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_07_good();"); CWE675_Duplicate_Operations_on_Resource__open_07_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_45_good();"); CWE675_Duplicate_Operations_on_Resource__open_45_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_03_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_03_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_02_good();"); CWE675_Duplicate_Operations_on_Resource__open_02_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_09_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_09_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_66_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_66_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_10_good();"); CWE675_Duplicate_Operations_on_Resource__open_10_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_08_good();"); CWE675_Duplicate_Operations_on_Resource__open_08_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_42_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_42_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_68_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_68_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_68_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_68_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_31_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_31_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_01_good();"); CWE675_Duplicate_Operations_on_Resource__open_01_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_18_good();"); CWE675_Duplicate_Operations_on_Resource__open_18_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_15_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_15_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_15_good();"); CWE675_Duplicate_Operations_on_Resource__open_15_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_51_good();"); CWE675_Duplicate_Operations_on_Resource__open_51_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_51_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_51_good(); /* END-AUTOGENERATED-C-GOOD-FUNCTION-CALLS */ #ifdef __cplusplus /* Calling C++ good functions */ /* BEGIN-AUTOGENERATED-CPP-GOOD-FUNCTION-CALLS */ printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_74::good();"); CWE675_Duplicate_Operations_on_Resource__open_74::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_84::good();"); CWE675_Duplicate_Operations_on_Resource__freopen_84::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_62::good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_62::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_73::good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_73::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_62::good();"); CWE675_Duplicate_Operations_on_Resource__open_62::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_73::good();"); CWE675_Duplicate_Operations_on_Resource__fopen_73::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_74::good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_74::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_83::good();"); CWE675_Duplicate_Operations_on_Resource__open_83::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_84::good();"); CWE675_Duplicate_Operations_on_Resource__open_84::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_82::good();"); CWE675_Duplicate_Operations_on_Resource__open_82::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_83::good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_83::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_73::good();"); CWE675_Duplicate_Operations_on_Resource__open_73::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_33::good();"); CWE675_Duplicate_Operations_on_Resource__fopen_33::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_43::good();"); CWE675_Duplicate_Operations_on_Resource__open_43::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_74::good();"); CWE675_Duplicate_Operations_on_Resource__fopen_74::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_81::good();"); CWE675_Duplicate_Operations_on_Resource__freopen_81::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_83::good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_83::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_84::good();"); CWE675_Duplicate_Operations_on_Resource__open_84::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_74::good();"); CWE675_Duplicate_Operations_on_Resource__freopen_74::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_84::good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_84::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_72::good();"); CWE675_Duplicate_Operations_on_Resource__open_72::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_62::good();"); CWE675_Duplicate_Operations_on_Resource__fopen_62::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_72::good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_72::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_84::good();"); CWE675_Duplicate_Operations_on_Resource__fopen_84::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_33::good();"); CWE675_Duplicate_Operations_on_Resource__open_33::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_81::good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_81::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_43::good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_43::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_81::good();"); CWE675_Duplicate_Operations_on_Resource__open_81::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_84::good();"); CWE675_Duplicate_Operations_on_Resource__freopen_84::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_62::good();"); CWE675_Duplicate_Operations_on_Resource__freopen_62::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_84::good();"); CWE675_Duplicate_Operations_on_Resource__fopen_84::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_83::good();"); CWE675_Duplicate_Operations_on_Resource__fopen_83::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_83::good();"); CWE675_Duplicate_Operations_on_Resource__open_83::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_33::good();"); CWE675_Duplicate_Operations_on_Resource__freopen_33::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_33::good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_33::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_82::good();"); CWE675_Duplicate_Operations_on_Resource__fopen_82::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_82::good();"); CWE675_Duplicate_Operations_on_Resource__freopen_82::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_81::good();"); CWE675_Duplicate_Operations_on_Resource__fopen_81::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_43::good();"); CWE675_Duplicate_Operations_on_Resource__freopen_43::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_83::good();"); CWE675_Duplicate_Operations_on_Resource__freopen_83::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_72::good();"); CWE675_Duplicate_Operations_on_Resource__fopen_72::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_82::good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_82::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_43::good();"); CWE675_Duplicate_Operations_on_Resource__fopen_43::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_73::good();"); CWE675_Duplicate_Operations_on_Resource__freopen_73::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_83::good();"); CWE675_Duplicate_Operations_on_Resource__fopen_83::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_84::good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_84::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_72::good();"); CWE675_Duplicate_Operations_on_Resource__freopen_72::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_83::good();"); CWE675_Duplicate_Operations_on_Resource__freopen_83::good(); /* END-AUTOGENERATED-CPP-GOOD-FUNCTION-CALLS */ #endif /* __cplusplus */ #endif /* OMITGOOD */ #ifndef OMITBAD /* Calling C bad functions */ /* BEGIN-AUTOGENERATED-C-BAD-FUNCTION-CALLS */ printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_05_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_05_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_66_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_66_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_13_bad();"); CWE675_Duplicate_Operations_on_Resource__open_13_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_21_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_21_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_44_bad();"); CWE675_Duplicate_Operations_on_Resource__open_44_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_51_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_51_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_14_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_14_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_17_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_17_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_04_bad();"); CWE675_Duplicate_Operations_on_Resource__open_04_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_10_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_10_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_17_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_17_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_64_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_64_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_16_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_16_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_64_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_64_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_11_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_11_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_34_bad();"); CWE675_Duplicate_Operations_on_Resource__open_34_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_18_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_18_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_02_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_02_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_13_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_13_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_12_bad();"); CWE675_Duplicate_Operations_on_Resource__open_12_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_53_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_53_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_44_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_44_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_65_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_65_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_21_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_21_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_31_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_31_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_04_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_04_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_68_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_68_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_22_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_22_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_12_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_12_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_03_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_03_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_54_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_54_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_31_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_31_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_45_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_45_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_45_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_45_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_14_bad();"); CWE675_Duplicate_Operations_on_Resource__open_14_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_63_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_63_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_53_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_53_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_15_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_15_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_18_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_18_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_22_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_22_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_05_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_05_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_65_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_65_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_18_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_18_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_14_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_14_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_61_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_61_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_22_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_22_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_17_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_17_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_44_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_44_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_32_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_32_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_10_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_10_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_52_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_52_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_63_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_63_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_32_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_32_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_41_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_41_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_54_bad();"); CWE675_Duplicate_Operations_on_Resource__open_54_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_21_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_21_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_08_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_08_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_05_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_05_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_41_bad();"); CWE675_Duplicate_Operations_on_Resource__open_41_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_03_bad();"); CWE675_Duplicate_Operations_on_Resource__open_03_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_53_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_53_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_05_bad();"); CWE675_Duplicate_Operations_on_Resource__open_05_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_02_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_02_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_04_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_04_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_04_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_04_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_42_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_42_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_09_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_09_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_64_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_64_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_11_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_11_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_12_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_12_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_53_bad();"); CWE675_Duplicate_Operations_on_Resource__open_53_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_01_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_01_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_10_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_10_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_54_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_54_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_09_bad();"); CWE675_Duplicate_Operations_on_Resource__open_09_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_17_bad();"); CWE675_Duplicate_Operations_on_Resource__open_17_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_63_bad();"); CWE675_Duplicate_Operations_on_Resource__open_63_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_21_bad();"); CWE675_Duplicate_Operations_on_Resource__open_21_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_09_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_09_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_61_bad();"); CWE675_Duplicate_Operations_on_Resource__open_61_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_66_bad();"); CWE675_Duplicate_Operations_on_Resource__open_66_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_07_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_07_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_41_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_41_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_11_bad();"); CWE675_Duplicate_Operations_on_Resource__open_11_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_42_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_42_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_34_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_34_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_61_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_61_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_16_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_16_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_34_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_34_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_67_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_67_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_41_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_41_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_15_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_15_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_68_bad();"); CWE675_Duplicate_Operations_on_Resource__open_68_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_02_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_02_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_06_bad();"); CWE675_Duplicate_Operations_on_Resource__open_06_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_67_bad();"); CWE675_Duplicate_Operations_on_Resource__open_67_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_32_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_32_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_54_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_54_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_06_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_06_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_67_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_67_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_03_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_03_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_61_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_61_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_42_bad();"); CWE675_Duplicate_Operations_on_Resource__open_42_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_13_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_13_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_13_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_13_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_65_bad();"); CWE675_Duplicate_Operations_on_Resource__open_65_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_16_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_16_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_01_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_01_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_01_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_01_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_34_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_34_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_65_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_65_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_11_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_11_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_52_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_52_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_51_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_51_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_16_bad();"); CWE675_Duplicate_Operations_on_Resource__open_16_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_08_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_08_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_66_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_66_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_08_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_08_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_22_bad();"); CWE675_Duplicate_Operations_on_Resource__open_22_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_12_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_12_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_44_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_44_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_52_bad();"); CWE675_Duplicate_Operations_on_Resource__open_52_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_31_bad();"); CWE675_Duplicate_Operations_on_Resource__open_31_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_14_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_14_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_07_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_07_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_64_bad();"); CWE675_Duplicate_Operations_on_Resource__open_64_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_06_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_06_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_63_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_63_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_45_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_45_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_32_bad();"); CWE675_Duplicate_Operations_on_Resource__open_32_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_06_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_06_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_07_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_07_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_52_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_52_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_67_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_67_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_07_bad();"); CWE675_Duplicate_Operations_on_Resource__open_07_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_45_bad();"); CWE675_Duplicate_Operations_on_Resource__open_45_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_03_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_03_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_02_bad();"); CWE675_Duplicate_Operations_on_Resource__open_02_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_09_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_09_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_66_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_66_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_10_bad();"); CWE675_Duplicate_Operations_on_Resource__open_10_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_08_bad();"); CWE675_Duplicate_Operations_on_Resource__open_08_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_42_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_42_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_68_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_68_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_68_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_68_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_31_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_31_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_01_bad();"); CWE675_Duplicate_Operations_on_Resource__open_01_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_18_bad();"); CWE675_Duplicate_Operations_on_Resource__open_18_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_15_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_15_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_15_bad();"); CWE675_Duplicate_Operations_on_Resource__open_15_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_51_bad();"); CWE675_Duplicate_Operations_on_Resource__open_51_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_51_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_51_bad(); /* END-AUTOGENERATED-C-BAD-FUNCTION-CALLS */ #ifdef __cplusplus /* Calling C++ bad functions */ /* BEGIN-AUTOGENERATED-CPP-BAD-FUNCTION-CALLS */ printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_74::bad();"); CWE675_Duplicate_Operations_on_Resource__open_74::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_84::bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_84::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_62::bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_62::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_73::bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_73::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_62::bad();"); CWE675_Duplicate_Operations_on_Resource__open_62::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_73::bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_73::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_74::bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_74::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_83::bad();"); CWE675_Duplicate_Operations_on_Resource__open_83::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_84::bad();"); CWE675_Duplicate_Operations_on_Resource__open_84::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_82::bad();"); CWE675_Duplicate_Operations_on_Resource__open_82::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_83::bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_83::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_73::bad();"); CWE675_Duplicate_Operations_on_Resource__open_73::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_33::bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_33::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_43::bad();"); CWE675_Duplicate_Operations_on_Resource__open_43::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_74::bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_74::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_81::bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_81::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_83::bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_83::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_84::bad();"); CWE675_Duplicate_Operations_on_Resource__open_84::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_74::bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_74::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_84::bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_84::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_72::bad();"); CWE675_Duplicate_Operations_on_Resource__open_72::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_62::bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_62::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_72::bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_72::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_84::bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_84::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_33::bad();"); CWE675_Duplicate_Operations_on_Resource__open_33::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_81::bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_81::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_43::bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_43::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_81::bad();"); CWE675_Duplicate_Operations_on_Resource__open_81::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_84::bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_84::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_62::bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_62::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_84::bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_84::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_83::bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_83::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_83::bad();"); CWE675_Duplicate_Operations_on_Resource__open_83::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_33::bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_33::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_33::bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_33::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_82::bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_82::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_82::bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_82::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_81::bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_81::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_43::bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_43::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_83::bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_83::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_72::bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_72::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_82::bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_82::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_43::bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_43::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_73::bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_73::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_83::bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_83::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_84::bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_84::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_72::bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_72::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_83::bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_83::bad(); /* END-AUTOGENERATED-CPP-BAD-FUNCTION-CALLS */ #endif /* __cplusplus */ #endif /* OMITBAD */ return 0; }
46.938144
97
0.871513
RanerL
dc54953678bd002e7bf38c74658598e37771f97d
2,783
cpp
C++
samples/cpp/create_mask.cpp
thisisgopalmandal/opencv
4e2ef8c8f57644ccb8e762a37f70a61007c6be1c
[ "BSD-3-Clause" ]
56
2020-03-24T15:17:56.000Z
2022-03-21T13:44:08.000Z
samples/cpp/create_mask.cpp
thisisgopalmandal/opencv
4e2ef8c8f57644ccb8e762a37f70a61007c6be1c
[ "BSD-3-Clause" ]
9
2019-10-19T06:55:30.000Z
2019-10-21T15:08:33.000Z
samples/cpp/create_mask.cpp
thisisgopalmandal/opencv
4e2ef8c8f57644ccb8e762a37f70a61007c6be1c
[ "BSD-3-Clause" ]
15
2020-05-06T13:41:20.000Z
2022-03-31T19:15:47.000Z
/* * create_mask.cpp * * Author: * Siddharth Kherada <siddharthkherada27[at]gmail[dot]com> * * This tutorial demonstrates how to make mask image (black and white). * The program takes as input a source image and outputs its corresponding * mask image. */ #include "opencv2/imgproc.hpp" #include "opencv2/imgcodecs.hpp" #include "opencv2/highgui.hpp" #include <iostream> using namespace std; using namespace cv; Mat src, img1, mask, final; Point point; vector<Point> pts; int drag = 0; int var = 0; int flag = 0; void mouseHandler(int, int, int, int, void*); void mouseHandler(int event, int x, int y, int, void*) { if (event == EVENT_LBUTTONDOWN && !drag) { if (flag == 0) { if (var == 0) img1 = src.clone(); point = Point(x, y); circle(img1, point, 2, Scalar(0, 0, 255), -1, 8, 0); pts.push_back(point); var++; drag = 1; if (var > 1) line(img1,pts[var-2], point, Scalar(0, 0, 255), 2, 8, 0); imshow("Source", img1); } } if (event == EVENT_LBUTTONUP && drag) { imshow("Source", img1); drag = 0; } if (event == EVENT_RBUTTONDOWN) { flag = 1; img1 = src.clone(); if (var != 0) { polylines( img1, pts, 1, Scalar(0,0,0), 2, 8, 0); } imshow("Source", img1); } if (event == EVENT_RBUTTONUP) { flag = var; final = Mat::zeros(src.size(), CV_8UC3); mask = Mat::zeros(src.size(), CV_8UC1); vector<vector<Point> > vpts; vpts.push_back(pts); fillPoly(mask, vpts, Scalar(255, 255, 255), 8, 0); bitwise_and(src, src, final, mask); imshow("Mask", mask); imshow("Result", final); imshow("Source", img1); } if (event == EVENT_MBUTTONDOWN) { pts.clear(); var = 0; drag = 0; flag = 0; imshow("Source", src); } } int main(int argc, char **argv) { CommandLineParser parser(argc, argv, "{@input | lena.jpg | input image}"); parser.about("This program demonstrates using mouse events\n"); parser.printMessage(); cout << "\n\tleft mouse button - set a point to create mask shape\n" "\tright mouse button - create mask from points\n" "\tmiddle mouse button - reset\n"; String input_image = parser.get<String>("@input"); src = imread(samples::findFile(input_image)); if (src.empty()) { printf("Error opening image: %s\n", input_image.c_str()); return 0; } namedWindow("Source", WINDOW_AUTOSIZE); setMouseCallback("Source", mouseHandler, NULL); imshow("Source", src); waitKey(0); return 0; }
23
78
0.551563
thisisgopalmandal
dc57539f88602e33d29c83670d425b7994305558
4,469
hpp
C++
include/desola/profiling/EqualityCheckingVisitor.hpp
FrancisRussell/desola
a469428466e4849c7c0e2009a0c50b89184cae01
[ "Apache-2.0" ]
2
2021-12-17T10:46:20.000Z
2021-12-18T11:53:50.000Z
include/desola/profiling/EqualityCheckingVisitor.hpp
FrancisRussell/desola
a469428466e4849c7c0e2009a0c50b89184cae01
[ "Apache-2.0" ]
null
null
null
include/desola/profiling/EqualityCheckingVisitor.hpp
FrancisRussell/desola
a469428466e4849c7c0e2009a0c50b89184cae01
[ "Apache-2.0" ]
null
null
null
/****************************************************************************/ /* Copyright 2005-2006, Francis Russell */ /* */ /* Licensed under the Apache License, Version 2.0 (the License); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an AS IS BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ /* See the License for the specific language governing permissions and */ /* limitations under the License. */ /* */ /****************************************************************************/ #ifndef DESOLA_PROFILING_EQUALITY_CHECKING_VISITOR_HPP #define DESOLA_PROFILING_EQUALITY_CHECKING_VISITOR_HPP #include "Desola_profiling_fwd.hpp" #include <map> #include <cassert> #include <typeinfo> namespace desola { namespace detail { template<typename T_element> class PEqualityCheckingVisitor : public PExpressionNodeVisitor<T_element> { private: const std::map<const PExpressionNode<T_element>*, const PExpressionNode<T_element>*> mappings; bool equal; template<typename T_node> void checkMatch(const T_node& left) { assert(mappings.find(&left) != mappings.end()); const PExpressionNode<T_element>& right = *(mappings.find(&left)->second); if (typeid(left) == typeid(right)) { const T_node& castedRight = static_cast<const T_node&>(right); equal = equal && left.isEqual(castedRight, mappings); } else { equal = false; } } public: PEqualityCheckingVisitor(const std::map<const PExpressionNode<T_element>*, const PExpressionNode<T_element>*>& m) : mappings(m), equal(true) { } bool isEqual() const { return equal; } virtual void visit(PElementGet<vector, T_element>& e) { checkMatch(e); } virtual void visit(PElementGet<matrix, T_element>& e) { checkMatch(e); } virtual void visit(PElementSet<vector, T_element>& e) { checkMatch(e); } virtual void visit(PElementSet<matrix, T_element>& e) { checkMatch(e); } virtual void visit(PLiteral<scalar, T_element>& e) { checkMatch(e); } virtual void visit(PLiteral<vector, T_element>& e) { checkMatch(e); } virtual void visit(PLiteral<matrix, T_element>& e) { checkMatch(e); } virtual void visit(PMatrixMult<T_element>& e) { checkMatch(e); } virtual void visit(PMatrixVectorMult<T_element>& e) { checkMatch(e); } virtual void visit(PTransposeMatrixVectorMult<T_element>& e) { checkMatch(e); } virtual void visit(PVectorDot<T_element>& e) { checkMatch(e); } virtual void visit(PVectorCross<T_element>& e) { checkMatch(e); } virtual void visit(PVectorTwoNorm<T_element>& e) { checkMatch(e); } virtual void visit(PMatrixTranspose<T_element>& e) { checkMatch(e); } virtual void visit(PPairwise<scalar, T_element>& e) { checkMatch(e); } virtual void visit(PPairwise<vector, T_element>& e) { checkMatch(e); } virtual void visit(PPairwise<matrix, T_element>& e) { checkMatch(e); } virtual void visit(PScalarPiecewise<scalar, T_element>& e) { checkMatch(e); } virtual void visit(PScalarPiecewise<vector, T_element>& e) { checkMatch(e); } virtual void visit(PScalarPiecewise<matrix, T_element>& e) { checkMatch(e); } virtual void visit(PNegate<scalar, T_element>& e) { checkMatch(e); } virtual void visit(PNegate<vector, T_element>& e) { checkMatch(e); } virtual void visit(PNegate<matrix, T_element>& e) { checkMatch(e); } virtual void visit(PAbsolute<T_element>& e) { checkMatch(e); } virtual void visit(PSquareRoot<T_element>& e) { checkMatch(e); } }; } } #endif
22.685279
142
0.573059
FrancisRussell
dc58390656a009f243fd7e7855f84365afe22107
10,279
cpp
C++
src/raytracing/nvpro_core/nvvk/buffersuballocator_vk.cpp
zorofee/bgfx
56e69c858d56f452e8abe9902a760e5b4ba59747
[ "BSD-2-Clause" ]
null
null
null
src/raytracing/nvpro_core/nvvk/buffersuballocator_vk.cpp
zorofee/bgfx
56e69c858d56f452e8abe9902a760e5b4ba59747
[ "BSD-2-Clause" ]
null
null
null
src/raytracing/nvpro_core/nvvk/buffersuballocator_vk.cpp
zorofee/bgfx
56e69c858d56f452e8abe9902a760e5b4ba59747
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (c) 2014-2021, NVIDIA CORPORATION. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SPDX-FileCopyrightText: Copyright (c) 2014-2021 NVIDIA CORPORATION * SPDX-License-Identifier: Apache-2.0 */ #include <assert.h> #include "buffersuballocator_vk.h" #include "debug_util_vk.h" #include "error_vk.h" namespace bgfx { ////////////////////////////////////////////////////////////////////////// void BufferSubAllocator::init(MemAllocator* memAllocator, VkDeviceSize blockSize, VkBufferUsageFlags bufferUsageFlags, VkMemoryPropertyFlags memPropFlags, bool mapped, const std::vector<uint32_t>& sharingQueueFamilyIndices) { assert(!m_device); m_memAllocator = memAllocator; m_device = memAllocator->getDevice(); m_blockSize = std::min(blockSize, ((uint64_t(1) << Handle::BLOCKBITS) - 1) * uint64_t(BASE_ALIGNMENT)); m_bufferUsageFlags = bufferUsageFlags; m_memoryPropFlags = memPropFlags; m_memoryTypeIndex = ~0; m_keepLastBlock = true; m_mapped = mapped; m_sharingQueueFamilyIndices = sharingQueueFamilyIndices; m_freeBlockIndex = INVALID_ID_INDEX; m_usedSize = 0; m_allocatedSize = 0; } void BufferSubAllocator::deinit() { if(!m_memAllocator) return; free(false); m_blocks.clear(); m_memAllocator = nullptr; } BufferSubAllocator::Handle BufferSubAllocator::subAllocate(VkDeviceSize size, uint32_t align) { uint32_t usedOffset; uint32_t usedSize; uint32_t usedAligned; uint32_t blockIndex = INVALID_ID_INDEX; // if size either doesn't fit in the bits within the handle // or we are bigger than the default block size, we use a full dedicated block // for this allocation bool isDedicated = Handle::needsDedicated(size, align) || size > m_blockSize; if(!isDedicated) { // Find the first non-dedicated block that can fit the allocation for(uint32_t i = 0; i < (uint32_t)m_blocks.size(); i++) { Block& block = m_blocks[i]; if(!block.isDedicated && block.buffer && block.range.subAllocate((uint32_t)size, align, usedOffset, usedAligned, usedSize)) { blockIndex = block.index; break; } } } if(blockIndex == INVALID_ID_INDEX) { if(m_freeBlockIndex != INVALID_ID_INDEX) { Block& block = m_blocks[m_freeBlockIndex]; m_freeBlockIndex = setIndexValue(block.index, m_freeBlockIndex); blockIndex = block.index; } else { uint32_t newIndex = (uint32_t)m_blocks.size(); m_blocks.resize(m_blocks.size() + 1); Block& block = m_blocks[newIndex]; block.index = newIndex; blockIndex = newIndex; } Block& block = m_blocks[blockIndex]; block.size = std::max(m_blockSize, size); if(!isDedicated) { // only adjust size if not dedicated. // warning this lowers from 64 bit to 32 bit size, which should be fine given // such big allocations will trigger the dedicated path block.size = block.range.alignedSize((uint32_t)block.size); } VkResult result = allocBlock(block, blockIndex, block.size); NVVK_CHECK(result); if(result != VK_SUCCESS) { return Handle(); } block.isDedicated = isDedicated; if(!isDedicated) { // Dedicated blocks don't allow for subranges, so don't initialize the range allocator block.range.init((uint32_t)block.size); block.range.subAllocate((uint32_t)size, align, usedOffset, usedAligned, usedSize); m_regularBlocks++; } } Handle sub; if(!sub.setup(blockIndex, isDedicated ? 0 : usedOffset, isDedicated ? size : uint64_t(usedSize), isDedicated)) { return Handle(); } // append used space for stats m_usedSize += sub.getSize(); return sub; } void BufferSubAllocator::subFree(Handle sub) { if(!sub) return; Block& block = getBlock(sub.blockIndex); bool isDedicated = sub.isDedicated(); if(!isDedicated) { block.range.subFree(uint32_t(sub.getOffset()), uint32_t(sub.getSize())); } m_usedSize -= sub.getSize(); if(isDedicated || (block.range.isEmpty() && (!m_keepLastBlock || m_regularBlocks > 1))) { if(!isDedicated) { m_regularBlocks--; } freeBlock(block); } } float BufferSubAllocator::getUtilization(VkDeviceSize& allocatedSize, VkDeviceSize& usedSize) const { allocatedSize = m_allocatedSize; usedSize = m_usedSize; return float(double(usedSize) / double(allocatedSize)); } bool BufferSubAllocator::fitsInAllocated(VkDeviceSize size, uint32_t alignment) const { if(Handle::needsDedicated(size, alignment)) { return false; } for(const auto& block : m_blocks) { if(block.buffer && !block.isDedicated) { if(block.range.isAvailable((uint32_t)size, (uint32_t)alignment)) { return true; } } } return false; } void BufferSubAllocator::free(bool onlyEmpty) { for(uint32_t i = 0; i < (uint32_t)m_blocks.size(); i++) { Block& block = m_blocks[i]; if(block.buffer && (!onlyEmpty || (!block.isDedicated && block.range.isEmpty()))) { freeBlock(block); } } if(!onlyEmpty) { m_blocks.clear(); m_freeBlockIndex = INVALID_ID_INDEX; } } void BufferSubAllocator::freeBlock(Block& block) { m_allocatedSize -= block.size; BGFX_VKAPI(vkDestroyBuffer)(m_device, block.buffer, nullptr); if(block.mapping) { m_memAllocator->unmap(block.memory); } m_memAllocator->freeMemory(block.memory); if(!block.isDedicated) { block.range.deinit(); } block.memory = NullMemHandle; block.buffer = VK_NULL_HANDLE; block.mapping = nullptr; block.isDedicated = false; // update the block.index with the current head of the free list // pop its old value m_freeBlockIndex = setIndexValue(block.index, m_freeBlockIndex); } VkResult BufferSubAllocator::allocBlock(Block& block, uint32_t index, VkDeviceSize size) { std::string debugName = m_debugName + ":block:" + std::to_string(index); VkResult result; VkBufferCreateInfo createInfo = {VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; createInfo.size = size; createInfo.usage = m_bufferUsageFlags; createInfo.sharingMode = m_sharingQueueFamilyIndices.size() > 1 ? VK_SHARING_MODE_CONCURRENT : VK_SHARING_MODE_EXCLUSIVE; createInfo.pQueueFamilyIndices = m_sharingQueueFamilyIndices.data(); createInfo.queueFamilyIndexCount = static_cast<uint32_t>(m_sharingQueueFamilyIndices.size()); VkBuffer buffer = VK_NULL_HANDLE; result = BGFX_VKAPI(vkCreateBuffer)(m_device, &createInfo, nullptr, &buffer); if(result != VK_SUCCESS) { NVVK_CHECK(result); return result; } bgfx::DebugUtil(m_device).setObjectName(buffer, debugName); VkMemoryRequirements2 memReqs = {VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2}; VkBufferMemoryRequirementsInfo2 bufferReqs = {VK_STRUCTURE_TYPE_BUFFER_MEMORY_REQUIREMENTS_INFO_2}; bufferReqs.buffer = buffer; BGFX_VKAPI(vkGetBufferMemoryRequirements2)(m_device, &bufferReqs, &memReqs); if(m_memoryTypeIndex == ~0) { VkPhysicalDeviceMemoryProperties memoryProperties; BGFX_VKAPI(vkGetPhysicalDeviceMemoryProperties)(m_memAllocator->getPhysicalDevice(), &memoryProperties); VkMemoryPropertyFlags memProps = m_memoryPropFlags; // Find an available memory type that satisfies the requested properties. for(uint32_t memoryTypeIndex = 0; memoryTypeIndex < memoryProperties.memoryTypeCount; ++memoryTypeIndex) { if((memReqs.memoryRequirements.memoryTypeBits & (1 << memoryTypeIndex)) && (memoryProperties.memoryTypes[memoryTypeIndex].propertyFlags & memProps) == memProps) { m_memoryTypeIndex = memoryTypeIndex; break; } } } if(m_memoryTypeIndex == ~0) { assert(0 && "could not find memoryTypeIndex\n"); BGFX_VKAPI(vkDestroyBuffer)(m_device, buffer, nullptr); return VK_ERROR_INCOMPATIBLE_DRIVER; } MemAllocateInfo memAllocateInfo(memReqs.memoryRequirements, m_memoryPropFlags, false); memAllocateInfo.setDebugName(debugName); MemHandle memory = m_memAllocator->allocMemory(memAllocateInfo); if(!memory) { assert(0 && "could not allocate buffer\n"); BGFX_VKAPI(vkDestroyBuffer)(m_device, buffer, nullptr); return VK_ERROR_OUT_OF_DEVICE_MEMORY; } MemAllocator::MemInfo memInfo = m_memAllocator->getMemoryInfo(memory); VkBindBufferMemoryInfo bindInfos = {VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO}; bindInfos.buffer = buffer; bindInfos.memory = memInfo.memory; bindInfos.memoryOffset = memInfo.offset; result = BGFX_VKAPI(vkBindBufferMemory2)(m_device, 1, &bindInfos); if(result == VK_SUCCESS) { if(m_mapped) { block.mapping = m_memAllocator->mapT<uint8_t>(memory); } else { block.mapping = nullptr; } if(!m_mapped || block.mapping) { if(m_bufferUsageFlags & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT) { VkBufferDeviceAddressInfo info = {VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; info.buffer = buffer; block.address = BGFX_VKAPI(vkGetBufferDeviceAddress)(m_device, &info); } block.memory = memory; block.buffer = buffer; m_allocatedSize += block.size; return result; } } // error case NVVK_CHECK(result); BGFX_VKAPI(vkDestroyBuffer)(m_device, buffer, nullptr); m_memAllocator->freeMemory(memory); return result; } } // namespace bgfx
28.792717
129
0.67633
zorofee
dc5dd1a91bef80ba080bbcc5820c6b3ea8ac9b14
2,771
cpp
C++
src/listener.cpp
lydiazoghbi/beginner_tutorials
cbf5d5a7a44e8c6005b511ed0fc9a8a1dc937056
[ "Unlicense", "BSD-3-Clause" ]
null
null
null
src/listener.cpp
lydiazoghbi/beginner_tutorials
cbf5d5a7a44e8c6005b511ed0fc9a8a1dc937056
[ "Unlicense", "BSD-3-Clause" ]
null
null
null
src/listener.cpp
lydiazoghbi/beginner_tutorials
cbf5d5a7a44e8c6005b511ed0fc9a8a1dc937056
[ "Unlicense", "BSD-3-Clause" ]
null
null
null
/* * BSD License * * Copyright (c) Lydia Zoghbi 2019 * * Permission is hereby granted, free of charge, to any person or organization * obtaining a copy of the software and accompanying documentation covered by * this license (the "Software") to use, reproduce, display, distribute, * execute, and transmit the Software, and to prepare derivative works of the * Software, and to permit third-parties to whom the Software is furnished to * do so, all subject to the following: * * The copyright notices in the Software and this entire statement * must be included in all copies of the Software, in whole or in part, and * all derivative works of the Software, unless such copies or derivative * works are solely in the form of machine-executable object code generated by * a source language processor. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @file listener.cpp * @author Lydia Zoghbi * @copyright Copyright BSD License * @date 11/02/2019 * @version 1.0 * * @brief Listener file for the ENPM808X ROS Assignment * */ #include "ros/ros.h" #include "std_msgs/String.h" #include "beginner_tutorials/string_modifier.h" /** * @brief Callback function for the function outputting the string * * @param A constant string * * @return Nothing */ void chatterCallback(const std_msgs::String::ConstPtr& msg) { ROS_INFO("I am receiving: [%s]", msg->data.c_str()); } /** * @brief Main loop for the listener * * @param ROS argument count * @param ROS argument vector * * @return 0 exit status */ int main(int argc, char **argv) { // Initiates the listener node ros::init(argc, argv, "listener"); // Creates the nodehandle object, initiates the node, and closes it off at the end ros::NodeHandle n; // Creates the subscriber object auto sub = n.subscribe("chatter", 1000, chatterCallback); // Will enter a loop, exits only when Ctrl-C is pressed or node shutdown by Master ros::spin(); return 0; }
33.792683
82
0.716348
lydiazoghbi
dc5e42057a892a1fbbb263c7034c46d30d45da19
5,163
cpp
C++
dev/Code/CryEngine/CryAction/FlowSystem/Nodes/FlowTrackEventNode.cpp
crazyskateface/lumberyard
164512f8d415d6bdf37e195af319ffe5f96a8f0b
[ "AML" ]
1
2020-03-24T04:54:22.000Z
2020-03-24T04:54:22.000Z
dev/Code/CryEngine/CryAction/FlowSystem/Nodes/FlowTrackEventNode.cpp
santosh90n/lumberyard-1
9608bcf905bb60e9f326bd3fe8297381c22d83a6
[ "AML" ]
null
null
null
dev/Code/CryEngine/CryAction/FlowSystem/Nodes/FlowTrackEventNode.cpp
santosh90n/lumberyard-1
9608bcf905bb60e9f326bd3fe8297381c22d83a6
[ "AML" ]
2
2019-07-09T00:03:08.000Z
2020-03-24T04:54:27.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ // Original file Copyright Crytek GMBH or its affiliates, used under license. // Description : Dynamic node for Track Event logic #include "StdAfx.h" #include "FlowTrackEventNode.h" CFlowTrackEventNode::CFlowTrackEventNode(SActivationInfo* pActInfo) : m_refs(0) , m_pSequence(NULL) , m_nOutputs(1) { m_outputs = new SOutputPortConfig[1]; m_outputs[0] = SOutputPortConfig(); } CFlowTrackEventNode::~CFlowTrackEventNode() { SAFE_DELETE_ARRAY(m_outputs); if (NULL != m_pSequence && false == gEnv->IsEditor()) { m_pSequence->RemoveTrackEventListener(this); m_pSequence = NULL; } } CFlowTrackEventNode::CFlowTrackEventNode(CFlowTrackEventNode const& obj) : m_refs(0) , m_pSequence(NULL) , m_outputs(NULL) { *this = obj; } CFlowTrackEventNode& CFlowTrackEventNode::operator =(CFlowTrackEventNode const& obj) { if (this != &obj) { m_refs = 0; // New reference count m_pSequence = obj.m_pSequence; // Copy outputs m_nOutputs = obj.m_nOutputs; SAFE_DELETE_ARRAY(m_outputs); m_outputs = new SOutputPortConfig[m_nOutputs]; for (int i = 0; i < m_nOutputs; ++i) { m_outputs[i] = obj.m_outputs[i]; } m_outputStrings = obj.m_outputStrings; } return *this; } void CFlowTrackEventNode::AddRef() { ++m_refs; } void CFlowTrackEventNode::Release() { if (0 == --m_refs) { delete this; } } IFlowNodePtr CFlowTrackEventNode::Clone(SActivationInfo* pActInfo) { CFlowTrackEventNode* pClone = new CFlowTrackEventNode(*this); return pClone; } void CFlowTrackEventNode::GetConfiguration(SFlowNodeConfig& config) { static const SInputPortConfig inputs[] = { // Note: Must be first! InputPortConfig<string>("seq_Sequence", "", _HELP("Working animation sequence"), _HELP("Sequence"), 0), InputPortConfig<int>("seqid_SequenceId", 0, _HELP("Working animation sequence"), _HELP("SequenceId"), 0), {0} }; config.pInputPorts = inputs; config.pOutputPorts = m_outputs; config.SetCategory(EFLN_APPROVED); config.nFlags |= EFLN_DYNAMIC_OUTPUT; config.nFlags |= EFLN_HIDE_UI; } void CFlowTrackEventNode::ProcessEvent(EFlowEvent event, SActivationInfo* pActInfo) { if (event == eFE_Initialize && false == gEnv->IsEditor()) { AddListener(pActInfo); } } bool CFlowTrackEventNode::SerializeXML(SActivationInfo* pActInfo, const XmlNodeRef& root, bool reading) { if (true == reading) { int count = root->getChildCount(); // Resize if (m_outputs) { SAFE_DELETE_ARRAY(m_outputs); } m_outputs = new SOutputPortConfig[count + 1]; m_nOutputs = count + 1; for (int i = 0; i < count; ++i) { XmlNodeRef child = root->getChild(i); m_outputStrings.push_back(child->getAttr("Name")); m_outputs[i] = OutputPortConfig<string>(m_outputStrings[i]); } m_outputs[count] = SOutputPortConfig(); } return true; } void CFlowTrackEventNode::Serialize(SActivationInfo* pActInfo, TSerialize ser) { if (ser.IsReading() && false == gEnv->IsEditor()) { AddListener(pActInfo); } } void CFlowTrackEventNode::AddListener(SActivationInfo* pActInfo) { CRY_ASSERT(pActInfo); m_actInfo = *pActInfo; // Remove from old if (NULL != m_pSequence) { m_pSequence->RemoveTrackEventListener(this); m_pSequence = NULL; } // Look up sequence const int kSequenceName = 0; const int kSequenceId = 1; m_pSequence = gEnv->pMovieSystem->FindSequenceById((uint32)GetPortInt(pActInfo, kSequenceId)); if (NULL == m_pSequence) { string name = GetPortString(pActInfo, kSequenceName); m_pSequence = gEnv->pMovieSystem->FindLegacySequenceByName(name.c_str()); } if (NULL != m_pSequence) { m_pSequence->AddTrackEventListener(this); } } void CFlowTrackEventNode::OnTrackEvent(IAnimSequence* pSequence, int reason, const char* event, void* pUserData) { if (reason != ITrackEventListener::eTrackEventReason_Triggered) { return; } // Find output port and call it for (int i = 0; i < m_nOutputs; ++i) { if (m_outputs[i].name && strcmp(m_outputs[i].name, event) == 0) { // Call it TFlowInputData value; const char* param = (const char*)pUserData; value.Set(string(param)); ActivateOutput(&m_actInfo, i, value); return; } } }
27.031414
113
0.647879
crazyskateface
dc5eba32b42ce287379b17be3d5bdf1d80ce1415
826
cc
C++
geometry/plane.cc
IJDykeman/experiments-1
22badf166b2ea441e953939463f751020b8c251b
[ "MIT" ]
1
2022-02-28T04:19:34.000Z
2022-02-28T04:19:34.000Z
geometry/plane.cc
IJDykeman/experiments-1
22badf166b2ea441e953939463f751020b8c251b
[ "MIT" ]
null
null
null
geometry/plane.cc
IJDykeman/experiments-1
22badf166b2ea441e953939463f751020b8c251b
[ "MIT" ]
null
null
null
#include "plane.hh" namespace geometry { bool Plane::intersect(const Line& line, Out<Vec3> point) const { constexpr double EPS = 1e-7; if (line.direction.cross(normal).norm() < EPS) { // Parallel return false; } const double d = (origin - line.point).dot(normal) / (line.direction.dot(normal)); *point = line.point + (d * line.direction); return true; } bool Plane::intersect(const Ray& ray, Out<Vec3> point) const { constexpr double EPS = 1e-7; if (ray.direction.cross(normal).norm() < EPS) { // Parallel return false; } const double d = (origin - ray.origin).dot(normal) / (ray.direction.dot(normal)); *point = ray.origin + (d * ray.direction); if (d < 0.0) { // Pointing in the wrong direction return false; } else { return true; } } } // namespace geometry
22.324324
84
0.634383
IJDykeman
dc60dddf0d676504c596858d35dfb257261b7d45
259
hpp
C++
src/modules/osgViewer/generated_code/RecordCameraPathHandler.pypp.hpp
JaneliaSciComp/osgpyplusplus
a5ae3f69c7e9101a32d8cc95fe680dab292f75ac
[ "BSD-3-Clause" ]
17
2015-06-01T12:19:46.000Z
2022-02-12T02:37:48.000Z
src/modules/osgViewer/generated_code/RecordCameraPathHandler.pypp.hpp
cmbruns/osgpyplusplus
f8bfca2cf841e15f6ddb41c958f3ad0d0b9e4b75
[ "BSD-3-Clause" ]
7
2015-07-04T14:36:49.000Z
2015-07-23T18:09:49.000Z
src/modules/osgViewer/generated_code/RecordCameraPathHandler.pypp.hpp
cmbruns/osgpyplusplus
f8bfca2cf841e15f6ddb41c958f3ad0d0b9e4b75
[ "BSD-3-Clause" ]
7
2015-11-28T17:00:31.000Z
2020-01-08T07:00:59.000Z
// This file has been generated by Py++. #ifndef RecordCameraPathHandler_hpp__pyplusplus_wrapper #define RecordCameraPathHandler_hpp__pyplusplus_wrapper void register_RecordCameraPathHandler_class(); #endif//RecordCameraPathHandler_hpp__pyplusplus_wrapper
28.777778
55
0.880309
JaneliaSciComp
dc6110aa5a8ab5613b01d86632d47725e2432275
2,918
cpp
C++
soccer/src/soccer/radio/radio.cpp
xiaoqingyu0113/robocup-software
6127d25fc455051ef47610d0e421b2ca7330b4fa
[ "Apache-2.0" ]
200
2015-01-26T01:45:34.000Z
2022-03-19T13:05:31.000Z
soccer/src/soccer/radio/radio.cpp
xiaoqingyu0113/robocup-software
6127d25fc455051ef47610d0e421b2ca7330b4fa
[ "Apache-2.0" ]
1,254
2015-01-03T01:57:35.000Z
2022-03-16T06:32:21.000Z
soccer/src/soccer/radio/radio.cpp
xiaoqingyu0113/robocup-software
6127d25fc455051ef47610d0e421b2ca7330b4fa
[ "Apache-2.0" ]
206
2015-01-21T02:03:18.000Z
2022-02-01T17:57:46.000Z
#include "radio.hpp" namespace radio { DEFINE_FLOAT64(kRadioParamModule, timeout, 0.25, "Timeout after which radio will assume a robot is disconnected. Seconds."); Radio::Radio() : Node{"radio", rclcpp::NodeOptions{} .automatically_declare_parameters_from_overrides(true) .allow_undeclared_parameters(true)}, param_provider_(this, kRadioParamModule) { team_color_sub_ = create_subscription<rj_msgs::msg::TeamColor>( referee::topics::kTeamColorPub, rclcpp::QoS(1).transient_local(), [this](rj_msgs::msg::TeamColor::SharedPtr color) { // NOLINT switch_team(color->is_blue); }); for (int i = 0; i < kNumShells; i++) { robot_status_pubs_.at(i) = create_publisher<rj_msgs::msg::RobotStatus>( topics::robot_status_pub(i), rclcpp::QoS(1)); manipulator_subs_.at(i) = create_subscription<rj_msgs::msg::ManipulatorSetpoint>( control::topics::manipulator_setpoint_pub(i), rclcpp::QoS(1), [this, i](rj_msgs::msg::ManipulatorSetpoint::SharedPtr manipulator) { // NOLINT manipulators_cached_.at(i) = *manipulator; }); motion_subs_.at(i) = create_subscription<rj_msgs::msg::MotionSetpoint>( control::topics::motion_setpoint_pub(i), rclcpp::QoS(1), [this, i](rj_msgs::msg::MotionSetpoint::SharedPtr motion) { // NOLINT last_updates_.at(i) = RJ::now(); send(i, *motion, manipulators_cached_.at(i)); }); } tick_timer_ = create_wall_timer(std::chrono::milliseconds(16), [this]() { tick(); }); } void Radio::publish(int robot_id, const rj_msgs::msg::RobotStatus& robot_status) { robot_status_pubs_.at(robot_id)->publish(robot_status); } void Radio::tick() { receive(); RJ::Time update_time = RJ::now(); for (int i = 0; i < kNumShells; i++) { if (last_updates_.at(i) + RJ::Seconds(PARAM_timeout) < update_time) { using rj_msgs::msg::ManipulatorSetpoint; using rj_msgs::msg::MotionSetpoint; // Send a NOP packet if we haven't got any updates. const auto motion = rj_msgs::build<MotionSetpoint>() .velocity_x_mps(0) .velocity_y_mps(0) .velocity_z_radps(0); const auto manipulator = rj_msgs::build<ManipulatorSetpoint>() .shoot_mode(ManipulatorSetpoint::SHOOT_MODE_KICK) .trigger_mode(ManipulatorSetpoint::TRIGGER_MODE_STAND_DOWN) .kick_speed(0) .dribbler_speed(0); last_updates_.at(i) = RJ::now(); send(i, motion, manipulator); } } } } // namespace radio
43.552239
100
0.577108
xiaoqingyu0113
dc62bad401397865017b61073ec57761399965c8
14,278
cpp
C++
openstudiocore/src/model/YearDescription.cpp
ORNL-BTRIC/OpenStudio
878f94bebf6f025445d1373e8b2304ececac16d8
[ "blessing" ]
null
null
null
openstudiocore/src/model/YearDescription.cpp
ORNL-BTRIC/OpenStudio
878f94bebf6f025445d1373e8b2304ececac16d8
[ "blessing" ]
null
null
null
openstudiocore/src/model/YearDescription.cpp
ORNL-BTRIC/OpenStudio
878f94bebf6f025445d1373e8b2304ececac16d8
[ "blessing" ]
null
null
null
/********************************************************************** * Copyright (c) 2008-2014, Alliance for Sustainable Energy. * All rights reserved. * * This library 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 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********************************************************************/ #include <model/YearDescription.hpp> #include <model/YearDescription_Impl.hpp> #include <model/RunPeriod.hpp> #include <model/RunPeriod_Impl.hpp> #include <model/RunPeriodControlDaylightSavingTime.hpp> #include <model/RunPeriodControlDaylightSavingTime_Impl.hpp> #include <model/RunPeriodControlSpecialDays.hpp> #include <model/RunPeriodControlSpecialDays_Impl.hpp> #include <model/SizingPeriod.hpp> #include <model/SizingPeriod_Impl.hpp> #include <model/ScheduleBase.hpp> #include <model/ScheduleBase_Impl.hpp> #include <model/ScheduleRule.hpp> #include <model/ScheduleRule_Impl.hpp> #include <model/LightingDesignDay.hpp> #include <model/LightingDesignDay_Impl.hpp> #include <model/Model.hpp> #include <model/Model_Impl.hpp> #include <utilities/idd/IddFactory.hxx> #include <utilities/idd/OS_YearDescription_FieldEnums.hxx> #include <utilities/time/Date.hpp> #include <utilities/core/Assert.hpp> namespace openstudio { namespace model { namespace detail { YearDescription_Impl::YearDescription_Impl(const IdfObject& idfObject, Model_Impl* model, bool keepHandle) : ParentObject_Impl(idfObject,model,keepHandle) { OS_ASSERT(idfObject.iddObject().type() == YearDescription::iddObjectType()); } YearDescription_Impl::YearDescription_Impl(const openstudio::detail::WorkspaceObject_Impl& other, Model_Impl* model, bool keepHandle) : ParentObject_Impl(other,model,keepHandle) { OS_ASSERT(other.iddObject().type() == YearDescription::iddObjectType()); } YearDescription_Impl::YearDescription_Impl(const YearDescription_Impl& other, Model_Impl* model, bool keepHandle) : ParentObject_Impl(other,model,keepHandle) {} const std::vector<std::string>& YearDescription_Impl::outputVariableNames() const { static std::vector<std::string> result; if (result.empty()){ } return result; } IddObjectType YearDescription_Impl::iddObjectType() const { return YearDescription::iddObjectType(); } std::vector<ModelObject> YearDescription_Impl::children() const { std::vector<ModelObject> result; Model model = this->model(); boost::optional<RunPeriodControlDaylightSavingTime> dst = model.getOptionalUniqueModelObject<RunPeriodControlDaylightSavingTime>(); if (dst){ result.push_back(*dst); } BOOST_FOREACH(RunPeriodControlSpecialDays day, model.getConcreteModelObjects<RunPeriodControlSpecialDays>()){ result.push_back(day); } return result; } std::vector<IddObjectType> YearDescription_Impl::allowableChildTypes() const { IddObjectTypeVector result; result.push_back(RunPeriodControlDaylightSavingTime::iddObjectType()); result.push_back(RunPeriodControlSpecialDays::iddObjectType()); return result; } boost::optional<int> YearDescription_Impl::calendarYear() const { return getInt(OS_YearDescriptionFields::CalendarYear,true); } std::string YearDescription_Impl::dayofWeekforStartDay() const { boost::optional<int> calendarYear = this->calendarYear(); if (calendarYear){ openstudio::Date jan1(MonthOfYear::Jan, 1, *calendarYear); std::string result = jan1.dayOfWeek().valueName(); return result; } boost::optional<std::string> value = getString(OS_YearDescriptionFields::DayofWeekforStartDay,true); OS_ASSERT(value); return value.get(); } bool YearDescription_Impl::isDayofWeekforStartDayDefaulted() const { return isEmpty(OS_YearDescriptionFields::DayofWeekforStartDay); } bool YearDescription_Impl::isLeapYear() const { boost::optional<int> calendarYear = this->calendarYear(); if (calendarYear){ openstudio::Date jan1(MonthOfYear::Jan, 1, *calendarYear); bool result = jan1.isLeapYear(); return result; } boost::optional<std::string> value = getString(OS_YearDescriptionFields::IsLeapYear,true); OS_ASSERT(value); return openstudio::istringEqual(value.get(), "Yes"); } bool YearDescription_Impl::isIsLeapYearDefaulted() const { return isEmpty(OS_YearDescriptionFields::IsLeapYear); } void YearDescription_Impl::setCalendarYear(boost::optional<int> calendarYear) { bool wasLeapYear = this->isLeapYear(); bool result = false; if (calendarYear) { result = setInt(OS_YearDescriptionFields::CalendarYear, calendarYear.get()); this->resetDayofWeekforStartDay(); this->resetIsLeapYear(); } else { result = setString(OS_YearDescriptionFields::CalendarYear, ""); } OS_ASSERT(result); bool isLeapYear = this->isLeapYear(); updateModelLeapYear(wasLeapYear, isLeapYear); } void YearDescription_Impl::resetCalendarYear() { bool wasLeapYear = this->isLeapYear(); bool result = setString(OS_YearDescriptionFields::CalendarYear, ""); OS_ASSERT(result); bool isLeapYear = this->isLeapYear(); updateModelLeapYear(wasLeapYear, isLeapYear); } bool YearDescription_Impl::setDayofWeekforStartDay(std::string dayofWeekforStartDay) { bool result = false; if (!this->calendarYear()){ result = setString(OS_YearDescriptionFields::DayofWeekforStartDay, dayofWeekforStartDay); } return result; } void YearDescription_Impl::resetDayofWeekforStartDay() { bool result = setString(OS_YearDescriptionFields::DayofWeekforStartDay, ""); OS_ASSERT(result); } bool YearDescription_Impl::setIsLeapYear(bool isLeapYear) { bool result = false; bool wasLeapYear = this->isLeapYear(); if (!this->calendarYear()){ if (isLeapYear) { result = setString(OS_YearDescriptionFields::IsLeapYear, "Yes"); } else { result = setString(OS_YearDescriptionFields::IsLeapYear, "No"); } } if (result){ updateModelLeapYear(wasLeapYear, isLeapYear); } return result; } void YearDescription_Impl::resetIsLeapYear() { bool wasLeapYear = this->isLeapYear(); bool result = setString(OS_YearDescriptionFields::IsLeapYear, ""); OS_ASSERT(result); bool isLeapYear = this->isLeapYear(); updateModelLeapYear(wasLeapYear, isLeapYear); } int YearDescription_Impl::assumedYear() const { boost::optional<int> calendarYear = this->calendarYear(); if (calendarYear){ return *calendarYear; } openstudio::YearDescription yd; yd.isLeapYear = this->isLeapYear(); std::string dayofWeekforStartDay = this->dayofWeekforStartDay(); if (!dayofWeekforStartDay.empty()){ try{ openstudio::DayOfWeek dow(dayofWeekforStartDay); yd.yearStartsOnDayOfWeek = dow; }catch(const std::exception& ){ LOG(Error, "'" << dayofWeekforStartDay << "' is not yet a supported option for YearDescription"); } } return yd.assumedYear(); } openstudio::Date YearDescription_Impl::makeDate(openstudio::MonthOfYear monthOfYear, unsigned dayOfMonth) { boost::optional<int> calendarYear = this->calendarYear(); if (calendarYear){ return openstudio::Date(monthOfYear, dayOfMonth, *calendarYear); } openstudio::YearDescription yd; yd.isLeapYear = this->isLeapYear(); std::string dayofWeekforStartDay = this->dayofWeekforStartDay(); if (!dayofWeekforStartDay.empty()){ if (istringEqual(dayofWeekforStartDay, "UseWeatherFile")){ LOG(Info, "'UseWeatherFile' is not yet a supported option for YearDescription"); }else{ openstudio::DayOfWeek dow(dayofWeekforStartDay); yd.yearStartsOnDayOfWeek = dow; } } return openstudio::Date(monthOfYear, dayOfMonth, yd); } openstudio::Date YearDescription_Impl::makeDate(unsigned monthOfYear, unsigned dayOfMonth) { return makeDate(openstudio::MonthOfYear(monthOfYear), dayOfMonth); } openstudio::Date YearDescription_Impl::makeDate(openstudio::NthDayOfWeekInMonth n, openstudio::DayOfWeek dayOfWeek, openstudio::MonthOfYear monthOfYear) { boost::optional<int> year = this->calendarYear(); if (!year){ year = this->assumedYear(); } return openstudio::Date::fromNthDayOfMonth(n, dayOfWeek, monthOfYear, *year); } openstudio::Date YearDescription_Impl::makeDate(unsigned dayOfYear) { boost::optional<int> year = this->calendarYear(); if (!year){ year = this->assumedYear(); } return openstudio::Date::fromDayOfYear(dayOfYear, *year); } void YearDescription_Impl::updateModelLeapYear(bool wasLeapYear, bool isLeapYear) { if (wasLeapYear == isLeapYear){ return; } if (!wasLeapYear && isLeapYear){ return; } model::Model model = this->model(); if (wasLeapYear && !isLeapYear){ BOOST_FOREACH(RunPeriod runPeriod, model.getModelObjects<RunPeriod>()){ runPeriod.ensureNoLeapDays(); } BOOST_FOREACH(RunPeriodControlDaylightSavingTime runPeriodControlDaylightSavingTime, model.getModelObjects<RunPeriodControlDaylightSavingTime>()){ runPeriodControlDaylightSavingTime.ensureNoLeapDays(); } BOOST_FOREACH(RunPeriodControlSpecialDays runPeriodControlSpecialDays, model.getModelObjects<RunPeriodControlSpecialDays>()){ runPeriodControlSpecialDays.ensureNoLeapDays(); } BOOST_FOREACH(SizingPeriod sizingPeriod, model.getModelObjects<SizingPeriod>()){ sizingPeriod.ensureNoLeapDays(); } BOOST_FOREACH(ScheduleBase scheduleBase, model.getModelObjects<ScheduleBase>()){ scheduleBase.ensureNoLeapDays(); } BOOST_FOREACH(ScheduleRule scheduleRule, model.getModelObjects<ScheduleRule>()){ scheduleRule.ensureNoLeapDays(); } BOOST_FOREACH(LightingDesignDay lightingDesignDay, model.getModelObjects<LightingDesignDay>()){ lightingDesignDay.ensureNoLeapDays(); } } } } // detail IddObjectType YearDescription::iddObjectType() { IddObjectType result(IddObjectType::OS_YearDescription); return result; } std::vector<std::string> YearDescription::validDayofWeekforStartDayValues() { return getIddKeyNames(IddFactory::instance().getObject(iddObjectType()).get(), OS_YearDescriptionFields::DayofWeekforStartDay); } boost::optional<int> YearDescription::calendarYear() const { return getImpl<detail::YearDescription_Impl>()->calendarYear(); } std::string YearDescription::dayofWeekforStartDay() const { return getImpl<detail::YearDescription_Impl>()->dayofWeekforStartDay(); } bool YearDescription::isDayofWeekforStartDayDefaulted() const { return getImpl<detail::YearDescription_Impl>()->isDayofWeekforStartDayDefaulted(); } bool YearDescription::isLeapYear() const { return getImpl<detail::YearDescription_Impl>()->isLeapYear(); } bool YearDescription::isIsLeapYearDefaulted() const { return getImpl<detail::YearDescription_Impl>()->isIsLeapYearDefaulted(); } void YearDescription::setCalendarYear(int calendarYear) { getImpl<detail::YearDescription_Impl>()->setCalendarYear(calendarYear); } void YearDescription::resetCalendarYear() { getImpl<detail::YearDescription_Impl>()->resetCalendarYear(); } bool YearDescription::setDayofWeekforStartDay(std::string dayofWeekforStartDay) { return getImpl<detail::YearDescription_Impl>()->setDayofWeekforStartDay(dayofWeekforStartDay); } void YearDescription::resetDayofWeekforStartDay() { getImpl<detail::YearDescription_Impl>()->resetDayofWeekforStartDay(); } bool YearDescription::setIsLeapYear(bool isLeapYear) { return getImpl<detail::YearDescription_Impl>()->setIsLeapYear(isLeapYear); } void YearDescription::resetIsLeapYear() { getImpl<detail::YearDescription_Impl>()->resetIsLeapYear(); } int YearDescription::assumedYear() const { return getImpl<detail::YearDescription_Impl>()->assumedYear(); } openstudio::Date YearDescription::makeDate(openstudio::MonthOfYear monthOfYear, unsigned dayOfMonth) { return getImpl<detail::YearDescription_Impl>()->makeDate(monthOfYear, dayOfMonth); } openstudio::Date YearDescription::makeDate(unsigned monthOfYear, unsigned dayOfMonth) { return getImpl<detail::YearDescription_Impl>()->makeDate(monthOfYear, dayOfMonth); } openstudio::Date YearDescription::makeDate(openstudio::NthDayOfWeekInMonth n, openstudio::DayOfWeek dayOfWeek, openstudio::MonthOfYear monthOfYear) { return getImpl<detail::YearDescription_Impl>()->makeDate(n, dayOfWeek, monthOfYear); } openstudio::Date YearDescription::makeDate(unsigned dayOfYear) { return getImpl<detail::YearDescription_Impl>()->makeDate(dayOfYear); } /// @cond YearDescription::YearDescription(boost::shared_ptr<detail::YearDescription_Impl> impl) : ParentObject(impl) {} YearDescription::YearDescription(Model& model) : ParentObject(YearDescription::iddObjectType(),model) {} /// @endcond } // model } // openstudio
33.516432
155
0.698697
ORNL-BTRIC
dc64e0ed895adde1606bd1f077143af6656b5d9c
19,068
cpp
C++
CodeGenere/photogram/cEqAppui_NoDist__PProjInc_M2CFour11x2.cpp
kikislater/micmac
3009dbdad62b3ad906ec882b74b85a3db86ca755
[ "CECILL-B" ]
451
2016-11-25T09:40:28.000Z
2022-03-30T04:20:42.000Z
CodeGenere/photogram/cEqAppui_NoDist__PProjInc_M2CFour11x2.cpp
kikislater/micmac
3009dbdad62b3ad906ec882b74b85a3db86ca755
[ "CECILL-B" ]
143
2016-11-25T20:35:57.000Z
2022-03-01T11:58:02.000Z
CodeGenere/photogram/cEqAppui_NoDist__PProjInc_M2CFour11x2.cpp
kikislater/micmac
3009dbdad62b3ad906ec882b74b85a3db86ca755
[ "CECILL-B" ]
139
2016-12-02T10:26:21.000Z
2022-03-10T19:40:29.000Z
// File Automatically generated by eLiSe #include "StdAfx.h" #include "cEqAppui_NoDist__PProjInc_M2CFour11x2.h" cEqAppui_NoDist__PProjInc_M2CFour11x2::cEqAppui_NoDist__PProjInc_M2CFour11x2(): cElCompiledFonc(2) { AddIntRef (cIncIntervale("Intr",0,16)); AddIntRef (cIncIntervale("Orient",16,22)); AddIntRef (cIncIntervale("Tmp_PTer",22,25)); Close(false); } void cEqAppui_NoDist__PProjInc_M2CFour11x2::ComputeVal() { double tmp0_ = mCompCoord[16]; double tmp1_ = mCompCoord[17]; double tmp2_ = cos(tmp1_); double tmp3_ = mCompCoord[22]; double tmp4_ = mCompCoord[23]; double tmp5_ = mCompCoord[24]; double tmp6_ = sin(tmp0_); double tmp7_ = cos(tmp0_); double tmp8_ = sin(tmp1_); double tmp9_ = mCompCoord[18]; double tmp10_ = mLocProjI_x*tmp3_; double tmp11_ = mLocProjP0_x+tmp10_; double tmp12_ = mLocProjJ_x*tmp4_; double tmp13_ = tmp11_+tmp12_; double tmp14_ = mLocProjK_x*tmp5_; double tmp15_ = tmp13_+tmp14_; double tmp16_ = mCompCoord[19]; double tmp17_ = (tmp15_)-tmp16_; double tmp18_ = sin(tmp9_); double tmp19_ = -(tmp18_); double tmp20_ = -(tmp8_); double tmp21_ = cos(tmp9_); double tmp22_ = mLocProjI_y*tmp3_; double tmp23_ = mLocProjP0_y+tmp22_; double tmp24_ = mLocProjJ_y*tmp4_; double tmp25_ = tmp23_+tmp24_; double tmp26_ = mLocProjK_y*tmp5_; double tmp27_ = tmp25_+tmp26_; double tmp28_ = mCompCoord[20]; double tmp29_ = (tmp27_)-tmp28_; double tmp30_ = mLocProjI_z*tmp3_; double tmp31_ = mLocProjP0_z+tmp30_; double tmp32_ = mLocProjJ_z*tmp4_; double tmp33_ = tmp31_+tmp32_; double tmp34_ = mLocProjK_z*tmp5_; double tmp35_ = tmp33_+tmp34_; double tmp36_ = mCompCoord[21]; double tmp37_ = (tmp35_)-tmp36_; double tmp38_ = -(tmp6_); double tmp39_ = tmp7_*tmp20_; double tmp40_ = tmp6_*tmp20_; double tmp41_ = tmp38_*tmp19_; double tmp42_ = tmp39_*tmp21_; double tmp43_ = tmp41_+tmp42_; double tmp44_ = (tmp43_)*(tmp17_); double tmp45_ = tmp7_*tmp19_; double tmp46_ = tmp40_*tmp21_; double tmp47_ = tmp45_+tmp46_; double tmp48_ = (tmp47_)*(tmp29_); double tmp49_ = tmp44_+tmp48_; double tmp50_ = tmp2_*tmp21_; double tmp51_ = tmp50_*(tmp37_); double tmp52_ = tmp49_+tmp51_; double tmp53_ = tmp7_*tmp2_; double tmp54_ = tmp53_*(tmp17_); double tmp55_ = tmp6_*tmp2_; double tmp56_ = tmp55_*(tmp29_); double tmp57_ = tmp54_+tmp56_; double tmp58_ = tmp8_*(tmp37_); double tmp59_ = tmp57_+tmp58_; double tmp60_ = (tmp59_)/(tmp52_); double tmp61_ = tmp38_*tmp21_; double tmp62_ = tmp39_*tmp18_; double tmp63_ = tmp61_+tmp62_; double tmp64_ = (tmp63_)*(tmp17_); double tmp65_ = tmp7_*tmp21_; double tmp66_ = tmp40_*tmp18_; double tmp67_ = tmp65_+tmp66_; double tmp68_ = (tmp67_)*(tmp29_); double tmp69_ = tmp64_+tmp68_; double tmp70_ = tmp2_*tmp18_; double tmp71_ = tmp70_*(tmp37_); double tmp72_ = tmp69_+tmp71_; double tmp73_ = (tmp72_)/(tmp52_); mVal[0] = ((mLocNDP0_x+mLocNDdx_x*(tmp60_)+mLocNDdy_x*(tmp73_))-mLocXIm)*mLocScNorm; mVal[1] = ((mLocNDP0_y+mLocNDdx_y*(tmp60_)+mLocNDdy_y*(tmp73_))-mLocYIm)*mLocScNorm; } void cEqAppui_NoDist__PProjInc_M2CFour11x2::ComputeValDeriv() { double tmp0_ = mCompCoord[16]; double tmp1_ = mCompCoord[17]; double tmp2_ = cos(tmp1_); double tmp3_ = mCompCoord[22]; double tmp4_ = mCompCoord[23]; double tmp5_ = mCompCoord[24]; double tmp6_ = sin(tmp0_); double tmp7_ = cos(tmp0_); double tmp8_ = sin(tmp1_); double tmp9_ = mCompCoord[18]; double tmp10_ = mLocProjI_x*tmp3_; double tmp11_ = mLocProjP0_x+tmp10_; double tmp12_ = mLocProjJ_x*tmp4_; double tmp13_ = tmp11_+tmp12_; double tmp14_ = mLocProjK_x*tmp5_; double tmp15_ = tmp13_+tmp14_; double tmp16_ = mCompCoord[19]; double tmp17_ = (tmp15_)-tmp16_; double tmp18_ = sin(tmp9_); double tmp19_ = -(tmp18_); double tmp20_ = -(tmp8_); double tmp21_ = cos(tmp9_); double tmp22_ = mLocProjI_y*tmp3_; double tmp23_ = mLocProjP0_y+tmp22_; double tmp24_ = mLocProjJ_y*tmp4_; double tmp25_ = tmp23_+tmp24_; double tmp26_ = mLocProjK_y*tmp5_; double tmp27_ = tmp25_+tmp26_; double tmp28_ = mCompCoord[20]; double tmp29_ = (tmp27_)-tmp28_; double tmp30_ = mLocProjI_z*tmp3_; double tmp31_ = mLocProjP0_z+tmp30_; double tmp32_ = mLocProjJ_z*tmp4_; double tmp33_ = tmp31_+tmp32_; double tmp34_ = mLocProjK_z*tmp5_; double tmp35_ = tmp33_+tmp34_; double tmp36_ = mCompCoord[21]; double tmp37_ = (tmp35_)-tmp36_; double tmp38_ = -(tmp6_); double tmp39_ = tmp7_*tmp20_; double tmp40_ = tmp6_*tmp20_; double tmp41_ = tmp38_*tmp19_; double tmp42_ = tmp39_*tmp21_; double tmp43_ = tmp41_+tmp42_; double tmp44_ = (tmp43_)*(tmp17_); double tmp45_ = tmp7_*tmp19_; double tmp46_ = tmp40_*tmp21_; double tmp47_ = tmp45_+tmp46_; double tmp48_ = (tmp47_)*(tmp29_); double tmp49_ = tmp44_+tmp48_; double tmp50_ = tmp2_*tmp21_; double tmp51_ = tmp50_*(tmp37_); double tmp52_ = tmp49_+tmp51_; double tmp53_ = tmp7_*tmp2_; double tmp54_ = tmp53_*(tmp17_); double tmp55_ = tmp6_*tmp2_; double tmp56_ = tmp55_*(tmp29_); double tmp57_ = tmp54_+tmp56_; double tmp58_ = tmp8_*(tmp37_); double tmp59_ = tmp57_+tmp58_; double tmp60_ = -(1); double tmp61_ = tmp60_*tmp6_; double tmp62_ = -(tmp7_); double tmp63_ = tmp61_*tmp20_; double tmp64_ = tmp39_*tmp18_; double tmp65_ = tmp38_*tmp21_; double tmp66_ = tmp65_+tmp64_; double tmp67_ = (tmp66_)*(tmp17_); double tmp68_ = tmp7_*tmp21_; double tmp69_ = tmp40_*tmp18_; double tmp70_ = tmp68_+tmp69_; double tmp71_ = (tmp70_)*(tmp29_); double tmp72_ = tmp67_+tmp71_; double tmp73_ = tmp2_*tmp18_; double tmp74_ = tmp73_*(tmp37_); double tmp75_ = tmp72_+tmp74_; double tmp76_ = tmp62_*tmp19_; double tmp77_ = tmp63_*tmp21_; double tmp78_ = tmp76_+tmp77_; double tmp79_ = (tmp78_)*(tmp17_); double tmp80_ = tmp61_*tmp19_; double tmp81_ = tmp80_+tmp42_; double tmp82_ = (tmp81_)*(tmp29_); double tmp83_ = tmp79_+tmp82_; double tmp84_ = ElSquare(tmp52_); double tmp85_ = tmp60_*tmp8_; double tmp86_ = -(tmp2_); double tmp87_ = tmp86_*tmp7_; double tmp88_ = tmp86_*tmp6_; double tmp89_ = tmp87_*tmp21_; double tmp90_ = tmp89_*(tmp17_); double tmp91_ = tmp88_*tmp21_; double tmp92_ = tmp91_*(tmp29_); double tmp93_ = tmp90_+tmp92_; double tmp94_ = tmp85_*tmp21_; double tmp95_ = tmp94_*(tmp37_); double tmp96_ = tmp93_+tmp95_; double tmp97_ = -(tmp21_); double tmp98_ = tmp60_*tmp18_; double tmp99_ = tmp97_*tmp38_; double tmp100_ = tmp98_*tmp39_; double tmp101_ = tmp99_+tmp100_; double tmp102_ = (tmp101_)*(tmp17_); double tmp103_ = tmp97_*tmp7_; double tmp104_ = tmp98_*tmp40_; double tmp105_ = tmp103_+tmp104_; double tmp106_ = (tmp105_)*(tmp29_); double tmp107_ = tmp102_+tmp106_; double tmp108_ = tmp98_*tmp2_; double tmp109_ = tmp108_*(tmp37_); double tmp110_ = tmp107_+tmp109_; double tmp111_ = tmp60_*(tmp43_); double tmp112_ = tmp60_*(tmp47_); double tmp113_ = tmp60_*tmp50_; double tmp114_ = mLocProjI_x*(tmp43_); double tmp115_ = mLocProjI_y*(tmp47_); double tmp116_ = tmp114_+tmp115_; double tmp117_ = mLocProjI_z*tmp50_; double tmp118_ = tmp116_+tmp117_; double tmp119_ = mLocProjJ_x*(tmp43_); double tmp120_ = mLocProjJ_y*(tmp47_); double tmp121_ = tmp119_+tmp120_; double tmp122_ = mLocProjJ_z*tmp50_; double tmp123_ = tmp121_+tmp122_; double tmp124_ = mLocProjK_x*(tmp43_); double tmp125_ = mLocProjK_y*(tmp47_); double tmp126_ = tmp124_+tmp125_; double tmp127_ = mLocProjK_z*tmp50_; double tmp128_ = tmp126_+tmp127_; double tmp129_ = (tmp59_)/(tmp52_); double tmp130_ = (tmp75_)/(tmp52_); double tmp131_ = tmp61_*tmp2_; double tmp132_ = tmp131_*(tmp17_); double tmp133_ = tmp53_*(tmp29_); double tmp134_ = tmp132_+tmp133_; double tmp135_ = (tmp134_)*(tmp52_); double tmp136_ = (tmp59_)*(tmp83_); double tmp137_ = tmp135_-tmp136_; double tmp138_ = (tmp137_)/tmp84_; double tmp139_ = tmp62_*tmp21_; double tmp140_ = tmp63_*tmp18_; double tmp141_ = tmp139_+tmp140_; double tmp142_ = (tmp141_)*(tmp17_); double tmp143_ = tmp61_*tmp21_; double tmp144_ = tmp143_+tmp64_; double tmp145_ = (tmp144_)*(tmp29_); double tmp146_ = tmp142_+tmp145_; double tmp147_ = (tmp146_)*(tmp52_); double tmp148_ = (tmp75_)*(tmp83_); double tmp149_ = tmp147_-tmp148_; double tmp150_ = (tmp149_)/tmp84_; double tmp151_ = tmp85_*tmp7_; double tmp152_ = tmp151_*(tmp17_); double tmp153_ = tmp85_*tmp6_; double tmp154_ = tmp153_*(tmp29_); double tmp155_ = tmp152_+tmp154_; double tmp156_ = tmp2_*(tmp37_); double tmp157_ = tmp155_+tmp156_; double tmp158_ = (tmp157_)*(tmp52_); double tmp159_ = (tmp59_)*(tmp96_); double tmp160_ = tmp158_-tmp159_; double tmp161_ = (tmp160_)/tmp84_; double tmp162_ = tmp87_*tmp18_; double tmp163_ = tmp162_*(tmp17_); double tmp164_ = tmp88_*tmp18_; double tmp165_ = tmp164_*(tmp29_); double tmp166_ = tmp163_+tmp165_; double tmp167_ = tmp85_*tmp18_; double tmp168_ = tmp167_*(tmp37_); double tmp169_ = tmp166_+tmp168_; double tmp170_ = (tmp169_)*(tmp52_); double tmp171_ = (tmp75_)*(tmp96_); double tmp172_ = tmp170_-tmp171_; double tmp173_ = (tmp172_)/tmp84_; double tmp174_ = (tmp59_)*(tmp110_); double tmp175_ = -(tmp174_); double tmp176_ = tmp175_/tmp84_; double tmp177_ = tmp98_*tmp38_; double tmp178_ = tmp21_*tmp39_; double tmp179_ = tmp177_+tmp178_; double tmp180_ = (tmp179_)*(tmp17_); double tmp181_ = tmp98_*tmp7_; double tmp182_ = tmp21_*tmp40_; double tmp183_ = tmp181_+tmp182_; double tmp184_ = (tmp183_)*(tmp29_); double tmp185_ = tmp180_+tmp184_; double tmp186_ = tmp21_*tmp2_; double tmp187_ = tmp186_*(tmp37_); double tmp188_ = tmp185_+tmp187_; double tmp189_ = (tmp188_)*(tmp52_); double tmp190_ = (tmp75_)*(tmp110_); double tmp191_ = tmp189_-tmp190_; double tmp192_ = (tmp191_)/tmp84_; double tmp193_ = tmp60_*tmp53_; double tmp194_ = tmp193_*(tmp52_); double tmp195_ = (tmp59_)*tmp111_; double tmp196_ = tmp194_-tmp195_; double tmp197_ = (tmp196_)/tmp84_; double tmp198_ = tmp60_*(tmp66_); double tmp199_ = tmp198_*(tmp52_); double tmp200_ = (tmp75_)*tmp111_; double tmp201_ = tmp199_-tmp200_; double tmp202_ = (tmp201_)/tmp84_; double tmp203_ = tmp60_*tmp55_; double tmp204_ = tmp203_*(tmp52_); double tmp205_ = (tmp59_)*tmp112_; double tmp206_ = tmp204_-tmp205_; double tmp207_ = (tmp206_)/tmp84_; double tmp208_ = tmp60_*(tmp70_); double tmp209_ = tmp208_*(tmp52_); double tmp210_ = (tmp75_)*tmp112_; double tmp211_ = tmp209_-tmp210_; double tmp212_ = (tmp211_)/tmp84_; double tmp213_ = tmp85_*(tmp52_); double tmp214_ = (tmp59_)*tmp113_; double tmp215_ = tmp213_-tmp214_; double tmp216_ = (tmp215_)/tmp84_; double tmp217_ = tmp60_*tmp73_; double tmp218_ = tmp217_*(tmp52_); double tmp219_ = (tmp75_)*tmp113_; double tmp220_ = tmp218_-tmp219_; double tmp221_ = (tmp220_)/tmp84_; double tmp222_ = mLocProjI_x*tmp53_; double tmp223_ = mLocProjI_y*tmp55_; double tmp224_ = tmp222_+tmp223_; double tmp225_ = mLocProjI_z*tmp8_; double tmp226_ = tmp224_+tmp225_; double tmp227_ = (tmp226_)*(tmp52_); double tmp228_ = (tmp59_)*(tmp118_); double tmp229_ = tmp227_-tmp228_; double tmp230_ = (tmp229_)/tmp84_; double tmp231_ = mLocProjI_x*(tmp66_); double tmp232_ = mLocProjI_y*(tmp70_); double tmp233_ = tmp231_+tmp232_; double tmp234_ = mLocProjI_z*tmp73_; double tmp235_ = tmp233_+tmp234_; double tmp236_ = (tmp235_)*(tmp52_); double tmp237_ = (tmp75_)*(tmp118_); double tmp238_ = tmp236_-tmp237_; double tmp239_ = (tmp238_)/tmp84_; double tmp240_ = mLocProjJ_x*tmp53_; double tmp241_ = mLocProjJ_y*tmp55_; double tmp242_ = tmp240_+tmp241_; double tmp243_ = mLocProjJ_z*tmp8_; double tmp244_ = tmp242_+tmp243_; double tmp245_ = (tmp244_)*(tmp52_); double tmp246_ = (tmp59_)*(tmp123_); double tmp247_ = tmp245_-tmp246_; double tmp248_ = (tmp247_)/tmp84_; double tmp249_ = mLocProjJ_x*(tmp66_); double tmp250_ = mLocProjJ_y*(tmp70_); double tmp251_ = tmp249_+tmp250_; double tmp252_ = mLocProjJ_z*tmp73_; double tmp253_ = tmp251_+tmp252_; double tmp254_ = (tmp253_)*(tmp52_); double tmp255_ = (tmp75_)*(tmp123_); double tmp256_ = tmp254_-tmp255_; double tmp257_ = (tmp256_)/tmp84_; double tmp258_ = mLocProjK_x*tmp53_; double tmp259_ = mLocProjK_y*tmp55_; double tmp260_ = tmp258_+tmp259_; double tmp261_ = mLocProjK_z*tmp8_; double tmp262_ = tmp260_+tmp261_; double tmp263_ = (tmp262_)*(tmp52_); double tmp264_ = (tmp59_)*(tmp128_); double tmp265_ = tmp263_-tmp264_; double tmp266_ = (tmp265_)/tmp84_; double tmp267_ = mLocProjK_x*(tmp66_); double tmp268_ = mLocProjK_y*(tmp70_); double tmp269_ = tmp267_+tmp268_; double tmp270_ = mLocProjK_z*tmp73_; double tmp271_ = tmp269_+tmp270_; double tmp272_ = (tmp271_)*(tmp52_); double tmp273_ = (tmp75_)*(tmp128_); double tmp274_ = tmp272_-tmp273_; double tmp275_ = (tmp274_)/tmp84_; mVal[0] = ((mLocNDP0_x+mLocNDdx_x*(tmp129_)+mLocNDdy_x*(tmp130_))-mLocXIm)*mLocScNorm; mCompDer[0][0] = 0; mCompDer[0][1] = 0; mCompDer[0][2] = 0; mCompDer[0][3] = 0; mCompDer[0][4] = 0; mCompDer[0][5] = 0; mCompDer[0][6] = 0; mCompDer[0][7] = 0; mCompDer[0][8] = 0; mCompDer[0][9] = 0; mCompDer[0][10] = 0; mCompDer[0][11] = 0; mCompDer[0][12] = 0; mCompDer[0][13] = 0; mCompDer[0][14] = 0; mCompDer[0][15] = 0; mCompDer[0][16] = ((tmp138_)*mLocNDdx_x+(tmp150_)*mLocNDdy_x)*mLocScNorm; mCompDer[0][17] = ((tmp161_)*mLocNDdx_x+(tmp173_)*mLocNDdy_x)*mLocScNorm; mCompDer[0][18] = ((tmp176_)*mLocNDdx_x+(tmp192_)*mLocNDdy_x)*mLocScNorm; mCompDer[0][19] = ((tmp197_)*mLocNDdx_x+(tmp202_)*mLocNDdy_x)*mLocScNorm; mCompDer[0][20] = ((tmp207_)*mLocNDdx_x+(tmp212_)*mLocNDdy_x)*mLocScNorm; mCompDer[0][21] = ((tmp216_)*mLocNDdx_x+(tmp221_)*mLocNDdy_x)*mLocScNorm; mCompDer[0][22] = ((tmp230_)*mLocNDdx_x+(tmp239_)*mLocNDdy_x)*mLocScNorm; mCompDer[0][23] = ((tmp248_)*mLocNDdx_x+(tmp257_)*mLocNDdy_x)*mLocScNorm; mCompDer[0][24] = ((tmp266_)*mLocNDdx_x+(tmp275_)*mLocNDdy_x)*mLocScNorm; mVal[1] = ((mLocNDP0_y+mLocNDdx_y*(tmp129_)+mLocNDdy_y*(tmp130_))-mLocYIm)*mLocScNorm; mCompDer[1][0] = 0; mCompDer[1][1] = 0; mCompDer[1][2] = 0; mCompDer[1][3] = 0; mCompDer[1][4] = 0; mCompDer[1][5] = 0; mCompDer[1][6] = 0; mCompDer[1][7] = 0; mCompDer[1][8] = 0; mCompDer[1][9] = 0; mCompDer[1][10] = 0; mCompDer[1][11] = 0; mCompDer[1][12] = 0; mCompDer[1][13] = 0; mCompDer[1][14] = 0; mCompDer[1][15] = 0; mCompDer[1][16] = ((tmp138_)*mLocNDdx_y+(tmp150_)*mLocNDdy_y)*mLocScNorm; mCompDer[1][17] = ((tmp161_)*mLocNDdx_y+(tmp173_)*mLocNDdy_y)*mLocScNorm; mCompDer[1][18] = ((tmp176_)*mLocNDdx_y+(tmp192_)*mLocNDdy_y)*mLocScNorm; mCompDer[1][19] = ((tmp197_)*mLocNDdx_y+(tmp202_)*mLocNDdy_y)*mLocScNorm; mCompDer[1][20] = ((tmp207_)*mLocNDdx_y+(tmp212_)*mLocNDdy_y)*mLocScNorm; mCompDer[1][21] = ((tmp216_)*mLocNDdx_y+(tmp221_)*mLocNDdy_y)*mLocScNorm; mCompDer[1][22] = ((tmp230_)*mLocNDdx_y+(tmp239_)*mLocNDdy_y)*mLocScNorm; mCompDer[1][23] = ((tmp248_)*mLocNDdx_y+(tmp257_)*mLocNDdy_y)*mLocScNorm; mCompDer[1][24] = ((tmp266_)*mLocNDdx_y+(tmp275_)*mLocNDdy_y)*mLocScNorm; } void cEqAppui_NoDist__PProjInc_M2CFour11x2::ComputeValDerivHessian() { ELISE_ASSERT(false,"Foncteur cEqAppui_NoDist__PProjInc_M2CFour11x2 Has no Der Sec"); } void cEqAppui_NoDist__PProjInc_M2CFour11x2::SetNDP0_x(double aVal){ mLocNDP0_x = aVal;} void cEqAppui_NoDist__PProjInc_M2CFour11x2::SetNDP0_y(double aVal){ mLocNDP0_y = aVal;} void cEqAppui_NoDist__PProjInc_M2CFour11x2::SetNDdx_x(double aVal){ mLocNDdx_x = aVal;} void cEqAppui_NoDist__PProjInc_M2CFour11x2::SetNDdx_y(double aVal){ mLocNDdx_y = aVal;} void cEqAppui_NoDist__PProjInc_M2CFour11x2::SetNDdy_x(double aVal){ mLocNDdy_x = aVal;} void cEqAppui_NoDist__PProjInc_M2CFour11x2::SetNDdy_y(double aVal){ mLocNDdy_y = aVal;} void cEqAppui_NoDist__PProjInc_M2CFour11x2::SetProjI_x(double aVal){ mLocProjI_x = aVal;} void cEqAppui_NoDist__PProjInc_M2CFour11x2::SetProjI_y(double aVal){ mLocProjI_y = aVal;} void cEqAppui_NoDist__PProjInc_M2CFour11x2::SetProjI_z(double aVal){ mLocProjI_z = aVal;} void cEqAppui_NoDist__PProjInc_M2CFour11x2::SetProjJ_x(double aVal){ mLocProjJ_x = aVal;} void cEqAppui_NoDist__PProjInc_M2CFour11x2::SetProjJ_y(double aVal){ mLocProjJ_y = aVal;} void cEqAppui_NoDist__PProjInc_M2CFour11x2::SetProjJ_z(double aVal){ mLocProjJ_z = aVal;} void cEqAppui_NoDist__PProjInc_M2CFour11x2::SetProjK_x(double aVal){ mLocProjK_x = aVal;} void cEqAppui_NoDist__PProjInc_M2CFour11x2::SetProjK_y(double aVal){ mLocProjK_y = aVal;} void cEqAppui_NoDist__PProjInc_M2CFour11x2::SetProjK_z(double aVal){ mLocProjK_z = aVal;} void cEqAppui_NoDist__PProjInc_M2CFour11x2::SetProjP0_x(double aVal){ mLocProjP0_x = aVal;} void cEqAppui_NoDist__PProjInc_M2CFour11x2::SetProjP0_y(double aVal){ mLocProjP0_y = aVal;} void cEqAppui_NoDist__PProjInc_M2CFour11x2::SetProjP0_z(double aVal){ mLocProjP0_z = aVal;} void cEqAppui_NoDist__PProjInc_M2CFour11x2::SetScNorm(double aVal){ mLocScNorm = aVal;} void cEqAppui_NoDist__PProjInc_M2CFour11x2::SetXIm(double aVal){ mLocXIm = aVal;} void cEqAppui_NoDist__PProjInc_M2CFour11x2::SetYIm(double aVal){ mLocYIm = aVal;} double * cEqAppui_NoDist__PProjInc_M2CFour11x2::AdrVarLocFromString(const std::string & aName) { if (aName == "NDP0_x") return & mLocNDP0_x; if (aName == "NDP0_y") return & mLocNDP0_y; if (aName == "NDdx_x") return & mLocNDdx_x; if (aName == "NDdx_y") return & mLocNDdx_y; if (aName == "NDdy_x") return & mLocNDdy_x; if (aName == "NDdy_y") return & mLocNDdy_y; if (aName == "ProjI_x") return & mLocProjI_x; if (aName == "ProjI_y") return & mLocProjI_y; if (aName == "ProjI_z") return & mLocProjI_z; if (aName == "ProjJ_x") return & mLocProjJ_x; if (aName == "ProjJ_y") return & mLocProjJ_y; if (aName == "ProjJ_z") return & mLocProjJ_z; if (aName == "ProjK_x") return & mLocProjK_x; if (aName == "ProjK_y") return & mLocProjK_y; if (aName == "ProjK_z") return & mLocProjK_z; if (aName == "ProjP0_x") return & mLocProjP0_x; if (aName == "ProjP0_y") return & mLocProjP0_y; if (aName == "ProjP0_z") return & mLocProjP0_z; if (aName == "ScNorm") return & mLocScNorm; if (aName == "XIm") return & mLocXIm; if (aName == "YIm") return & mLocYIm; return 0; } cElCompiledFonc::cAutoAddEntry cEqAppui_NoDist__PProjInc_M2CFour11x2::mTheAuto("cEqAppui_NoDist__PProjInc_M2CFour11x2",cEqAppui_NoDist__PProjInc_M2CFour11x2::Alloc); cElCompiledFonc * cEqAppui_NoDist__PProjInc_M2CFour11x2::Alloc() { return new cEqAppui_NoDist__PProjInc_M2CFour11x2(); }
38.05988
165
0.707363
kikislater
dc64ff403dd7d036b83871e06a9e3282ee996373
5,488
cpp
C++
src/trace/DXInterceptor/dxcodegen/Generator/StructHelperGenerator.cpp
attila-sim/attila-sim
a64b57240b4e10dc4df7f21eff0232b28df09532
[ "BSD-3-Clause" ]
23
2016-01-14T04:47:13.000Z
2022-01-13T14:02:08.000Z
src/trace/DXInterceptor/dxcodegen/Generator/StructHelperGenerator.cpp
attila-sim/attila-sim
a64b57240b4e10dc4df7f21eff0232b28df09532
[ "BSD-3-Clause" ]
2
2018-03-25T14:39:20.000Z
2022-03-18T05:11:21.000Z
src/trace/DXInterceptor/dxcodegen/Generator/StructHelperGenerator.cpp
attila-sim/attila-sim
a64b57240b4e10dc4df7f21eff0232b28df09532
[ "BSD-3-Clause" ]
17
2016-02-13T05:35:35.000Z
2022-03-24T16:05:40.000Z
//////////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "Config/GeneratorConfiguration.h" #include "Items/StructSpecificCode.h" #include "Items/StructDescription.h" #include "Generator/StructHelperGenerator.h" using namespace std; using namespace dxcodegen::Config; using namespace dxcodegen::Items; using namespace dxcodegen::Generator; //////////////////////////////////////////////////////////////////////////////// StructHelperGenerator::StructHelperGenerator(GeneratorConfiguration& config, const std::vector<StructDescriptionPtr>& structures, const string& outputPath) : m_config(config), m_outputPath(outputPath), m_className("DXStructHelper"), IGenerator("class DXStructHelper") { m_structures = structures; } //////////////////////////////////////////////////////////////////////////////// StructHelperGenerator::~StructHelperGenerator() { } //////////////////////////////////////////////////////////////////////////////// void StructHelperGenerator::GenerateCode() { GenerateHpp(); GenerateCpp(); } //////////////////////////////////////////////////////////////////////////////// void StructHelperGenerator::GenerateHpp() { string filename = m_className + ".h"; ofstream* sortida = CreateFilename(m_outputPath + filename); if (sortida && sortida->is_open()) { cout << "Creating '" << filename << "'" << endl; GenerateDefinition(*sortida); } CloseFilename(sortida); } //////////////////////////////////////////////////////////////////////////////// void StructHelperGenerator::GenerateCpp() { string filename = m_className + ".cpp"; ofstream* sortida = CreateFilename(m_outputPath + filename); if (sortida && sortida->is_open()) { cout << "Creating '" << filename << "'" << endl; GenerateImplementation(*sortida); } CloseFilename(sortida); } //////////////////////////////////////////////////////////////////////////////// void StructHelperGenerator::GenerateDefinition(ofstream& sortida) { sortida << "#pragma once" << endl; sortida << endl; sortida << "namespace dxtraceman" << endl; sortida << "{" << endl; sortida << " class " << m_className << endl; sortida << " {" << endl; GenerateDefinitionMethods(sortida); sortida << " };" << endl; sortida << "}" << endl; } //////////////////////////////////////////////////////////////////////////////// void StructHelperGenerator::GenerateDefinitionMethods(ofstream& sortida) { sortida << " public:" << endl; sortida << endl; for (vector<StructDescriptionPtr>::iterator it = m_structures.begin(); it != m_structures.end(); it++) { sortida << " static int " << (*it)->GetName() << "_ToString(char* buffer, unsigned int size, " << (*it)->GetName() << "* value);" << endl; } sortida << endl; } //////////////////////////////////////////////////////////////////////////////// void StructHelperGenerator::GenerateImplementation(ofstream& sortida) { sortida << "#include \"stdafx.h\"" << endl; sortida << "#include \"arraystream.h\"" << endl; sortida << "#include \"DXTypeHelper.h\"" << endl; sortida << "#include \"" << m_className << ".h\"" << endl; sortida << endl; sortida << "using namespace dxtraceman;" << endl; sortida << endl; for (vector<StructDescriptionPtr>::iterator it = m_structures.begin(); it != m_structures.end(); it++) { GenerateImplementationMethod(sortida, *it); } } //////////////////////////////////////////////////////////////////////////////// void StructHelperGenerator::GenerateImplementationMethod(ofstream& sortida, StructDescriptionPtr structure) { StructSpecificCodePtr structSC = m_config.GetStructSpecificCode(structure->GetName()); // Begin generate method body sortida << "int " << m_className << "::" << structure->GetName() << "_ToString(char* buffer, unsigned int size, " << structure->GetName() << "* value)" << endl; sortida << "{" << endl; sortida << " char local_buffer[256];" << endl; sortida << " arraystream buf(buffer, size);" << endl; sortida << " std::ostream out(&buf);" << endl; sortida << endl; sortida << " out << \"# struct " << structure->GetName() << "\" << std::endl;" << endl; sortida << " out << \"# {\" << std::endl;" << endl; for (unsigned int i=0; i < structure->GetFieldCount(); i++) { string fieldType = structure->GetField(i)->GetType(); string fieldName = structure->GetField(i)->GetName(); if (structSC) { StructFieldSpecificCodePtr fieldSC = structSC->GetField(fieldName); if ((bool) fieldSC && (bool) fieldSC->GetPolicy(StructFieldSpecificCode::ChangeSaveType)) { StructFieldSpecificCode::StructFieldChangeSaveTypePolicy* fieldPolicy = (StructFieldSpecificCode::StructFieldChangeSaveTypePolicy*) (void*) fieldSC->GetPolicy(StructFieldSpecificCode::ChangeSaveType); fieldType = fieldPolicy->GetSaveType(); } } sortida << " DXTypeHelper::ToString(local_buffer, sizeof(local_buffer), (void*) &(value->" << fieldName << "), DXTypeHelper::TT_" << fieldType << ");" << endl; sortida << " out << \"# " << fieldName << " = \" << local_buffer << std::endl;" << endl; } sortida << " out << \"# }\";" << endl; sortida << endl; sortida << " buf.finalize();" << endl; sortida << " return buf.tellp();" << endl; // End generate method body sortida << "}" << endl; sortida << endl; } ////////////////////////////////////////////////////////////////////////////////
33.876543
208
0.552843
attila-sim
dc659f25833a9c5bc406113db9e33bfe67a989a1
1,165
cpp
C++
C-Plus-Plus/math/armstrong_number.cpp
zhcet19/NeoAlgo-1
c534a23307109280bda0e4867d6e8e490002a4ee
[ "MIT" ]
897
2020-06-25T00:12:52.000Z
2022-03-24T00:49:31.000Z
C-Plus-Plus/math/armstrong_number.cpp
zhcet19/NeoAlgo-1
c534a23307109280bda0e4867d6e8e490002a4ee
[ "MIT" ]
5,707
2020-06-24T17:53:28.000Z
2022-01-22T05:03:15.000Z
C-Plus-Plus/math/armstrong_number.cpp
zhcet19/NeoAlgo-1
c534a23307109280bda0e4867d6e8e490002a4ee
[ "MIT" ]
1,817
2020-06-25T03:51:05.000Z
2022-03-29T05:14:07.000Z
/* In recreational number theory, a narcissistic number is also known as a pluperfect digital invariant (PPDI), an Armstrong number or a plus perfect number is a number that is the sum of its digits each raised to the power of the number of digits. */ #include <bits/stdc++.h> using namespace std; // Function to check whether the Number is Armstrong Number or Not. bool is_armstrong(int n) { if (n < 0) { return false; } int sum = 0; int var = n; int number_of_digits = floor(log10(n) + 1); while (var > 0) { int rem = var % 10; sum = sum + pow(rem, number_of_digits); var = var / 10; } return n == sum; } int main() { cout << "Enter the Number to check whether it is Armstrong Number or Not:" << endl; int n; cin >> n; if (is_armstrong(n)) cout << n << " is Armstrong Number." << endl; else cout << n << " is Not Armstrong Number." << endl; return 0; } /* Input: Enter the Number to check whether it is Armstrong Number or Not: 153 Output: 153 is Armstrong Number. Input: Enter the Number to check whether it is Armstrong Number or Not: 12 Output: 12 is Not Armstrong Number. Time Complexity: O(log(n)) Space Complexity: O(1) */
20.086207
84
0.681545
zhcet19
dc6678ef9afe543c5d5deced9af83b002c54688a
347
cpp
C++
src/package.cpp
michaelbrockus/ram-package-cpp
a7cfb37239c6cf49e15e9291c504175d7fac3c47
[ "Apache-2.0" ]
null
null
null
src/package.cpp
michaelbrockus/ram-package-cpp
a7cfb37239c6cf49e15e9291c504175d7fac3c47
[ "Apache-2.0" ]
1
2021-11-29T23:15:50.000Z
2021-11-29T23:15:50.000Z
src/package.cpp
michaelbrockus/ram-package-cpp
a7cfb37239c6cf49e15e9291c504175d7fac3c47
[ "Apache-2.0" ]
null
null
null
// // file: package.cpp // author: Michael Brockus // gmail: <michaelbrockus@gmail.com> // #include "hackazon/package.hpp" // // Should return a greeting message as it’s initial value // // Param list: // -> There is none to speak of at this time. // const char *hak::greet(void) { return "Hello, C++ Developer."; } // end of functions greet
19.277778
57
0.665706
michaelbrockus
dc68b8da5e55997fa812e97a16c0ff0cdf99d031
1,680
hpp
C++
src/BinaryBuffer.hpp
HU-ACTS/sensor-module
6277cba8eb41cf3ecb0aafd58ed25d58abff2d81
[ "Apache-2.0" ]
null
null
null
src/BinaryBuffer.hpp
HU-ACTS/sensor-module
6277cba8eb41cf3ecb0aafd58ed25d58abff2d81
[ "Apache-2.0" ]
null
null
null
src/BinaryBuffer.hpp
HU-ACTS/sensor-module
6277cba8eb41cf3ecb0aafd58ed25d58abff2d81
[ "Apache-2.0" ]
null
null
null
/** * @file binaryBuffer.hpp * @data 21 september, 2017 * * \class BinaryBuffer * * \brief Buffer between sensor and SPI SD write * * This class holds a finite amount of data and acts * as a FiFo. */ #pragma once #include <vector> #include "SystemVariables.hpp" #include "esp_log.h" class BinaryBuffer{ public: /*! * \brief BinaryBuffer constructor * * Clear the buffer and set state to write only. */ BinaryBuffer(); /*! * \brief readOnly method * * This method sets the buffer to read only mode. */ void readOnly(); /*! * \brief writeOnly method * * This method set the buffer to write only mode. */ void writeOnly(); /*! * \brief clear method * * This method clears the BinaryBuffer. */ void clear(); /*! * \brief add method * \param in SampleData structure * \return bool returns flase if state is read only * * This method adds a SampleData strcture * to the buffer. */ bool add( SampleData in ); /*! * \brief get method * \return SampleData buffer pointer * * This method returns a pointer to the * first sample of the buffer. */ const std::vector<SampleData>& get(); // should perhaps be a pointer, copy could be too slow on large scale operations? /*! * \brief isFull method * \return bool (true) if the buffer is full * * Returns true if the buffer is full */ bool isFull(); /*! * \brief BinaryBuffer deconstructor * * Empty, not implemented. */ ~BinaryBuffer(); private: bool readState(); bool state; std::vector<SampleData> buffer; const int BufferSize = BINARY_BUFFER_SIZE; };
19.310345
121
0.630357
HU-ACTS
dc6a20cd581d10f2831db74ceee608e7064af81d
6,589
cpp
C++
tp4/test/tests.cpp
ctrlMarcio/feup-cal
ba9004e2c5d0612c1d4eda93f00ce126cce091d2
[ "MIT" ]
null
null
null
tp4/test/tests.cpp
ctrlMarcio/feup-cal
ba9004e2c5d0612c1d4eda93f00ce126cce091d2
[ "MIT" ]
null
null
null
tp4/test/tests.cpp
ctrlMarcio/feup-cal
ba9004e2c5d0612c1d4eda93f00ce126cce091d2
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include <gmock/gmock.h> #include "../src/Graph.h" #include "../src/Person.h" using namespace std; using testing::Eq; void createNetwork(Graph<Person> & net1) { Person p1("Ana",19); Person p2("Carlos",33); Person p3("Filipe", 20); Person p4("Ines", 18); Person p5("Maria", 24); Person p6("Rui",21); Person p7("Vasco",28); net1.addVertex(p1); net1.addVertex(p2); net1.addVertex(p3); net1.addVertex(p4); net1.addVertex(p5); net1.addVertex(p6); net1.addVertex(p7); net1.addEdge(p1,p2,0); net1.addEdge(p1,p3,0); net1.addEdge(p1,p4,0); net1.addEdge(p2,p5,0); net1.addEdge(p5,p6,0); net1.addEdge(p5,p1,0); net1.addEdge(p3,p6,0); net1.addEdge(p3,p7,0); net1.addEdge(p6,p2,0); } TEST(CAL_FP04, test_addVertex) { Graph<Person> net1; Person p1("Ana",19); Person p2("Carlos",33); Person p3("Filipe", 20); Person p4("Ines", 18); net1.addVertex(p1); net1.addVertex(p2); net1.addVertex(p3); net1.addVertex(p4); EXPECT_EQ(false, net1.addVertex(p2)); EXPECT_EQ(4, net1.getNumVertex()); } TEST(CAL_FP04, test_removeVertex) { Graph<Person> net1; Person p1("Ana",19); Person p2("Carlos",33); Person p3("Filipe", 20); Person p4("Ines", 18); net1.addVertex(p1); net1.addVertex(p2); net1.addVertex(p3); net1.addVertex(p4); EXPECT_EQ(true, net1.removeVertex(p2)); EXPECT_EQ(false, net1.removeVertex(p2)); EXPECT_EQ(3, net1.getNumVertex()); } TEST(CAL_FP04, test_addEdge) { Graph<Person> net1; Person p1("Ana",19); Person p2("Carlos",33); Person p3("Filipe", 20); Person p4("Ines", 18); Person p5("Maria", 24); net1.addVertex(p1); net1.addVertex(p2); net1.addVertex(p3); net1.addVertex(p4); EXPECT_EQ(true, net1.addEdge(p1,p2,0)); EXPECT_EQ(true, net1.addEdge(p1,p3,0)); EXPECT_EQ(true, net1.addEdge(p1,p4,0)); EXPECT_EQ(false, net1.addEdge(p2,p5,0)); } TEST(CAL_FP04, test_removeEdge) { Graph<Person> net1; Person p1("Ana",19); Person p2("Carlos",33); Person p3("Filipe", 20); Person p4("Ines", 18); Person p5("Maria", 24); net1.addVertex(p1); net1.addVertex(p2); net1.addVertex(p3); net1.addVertex(p4); EXPECT_EQ(true, net1.addEdge(p1,p2,0)); EXPECT_EQ(true, net1.addEdge(p1,p3,0)); EXPECT_EQ(true, net1.addEdge(p1,p4,0)); EXPECT_EQ(true, net1.addEdge(p2,p4,0)); EXPECT_EQ(true, net1.removeEdge(p1,p3)); EXPECT_EQ(false, net1.removeEdge(p1,p5)); EXPECT_EQ(false, net1.removeEdge(p2,p3)); } TEST(CAL_FP04, test_dfs) { Graph<Person> net1; createNetwork(net1); vector<Person> v1 = net1.dfs(); string names[] = {"Ana", "Carlos", "Maria", "Rui", "Filipe", "Vasco", "Ines"}; for (unsigned i = 0; i < 7; i++) if (i < v1.size()) EXPECT_EQ(names[i], v1[i].getName()); else EXPECT_EQ(names[i], "(null)"); } TEST(CAL_FP04, test_bfs) { Graph<Person> net1; createNetwork(net1); vector<Person> v1 = net1.bfs(Person("Ana",19)); string names[] = {"Ana", "Carlos", "Filipe", "Ines", "Maria", "Rui", "Vasco"}; for (unsigned i = 0; i < 7; i++) if (i < v1.size()) EXPECT_EQ(names[i], v1[i].getName()); else EXPECT_EQ(names[i], "(null)"); } TEST(CAL_FP04, test_removeVertex_Again) { Graph<Person> net1; createNetwork(net1); Person p2("Carlos",33); EXPECT_EQ(true, net1.removeVertex(p2)); vector<Person> v1=net1.dfs(); string names[] = {"Ana", "Filipe", "Rui", "Vasco", "Ines", "Maria"}; for (unsigned i = 0; i < 6; i++) EXPECT_EQ(names[i], v1[i].getName()); } TEST(CAL_FP04, test_removeEdge_Again) { /* //uncomment test body below! Graph<Person> net1; createNetwork(net1); Person p5("Maria", 24); Person p6("Rui",21); EXPECT_EQ(true, net1.removeEdge(p5,p6)); vector<Person> v1=net1.dfs(); string names[] = {"Ana", "Carlos", "Maria", "Filipe", "Rui", "Vasco", "Ines"}; for (unsigned i = 0; i < 7; i++) EXPECT_EQ(names[i], v1[i].getName()); */ } TEST(CAL_FP04, test_maxNewChildren) { Graph<Person> net1; Person p1("Ana",19); Person p2("Carlos",33); Person p3("Filipe", 20); Person p4("Ines", 18); Person p5("Maria", 24); Person p6("Rui",21); Person p7("Vasco",28); net1.addVertex(p1); net1.addVertex(p2); net1.addVertex(p3); net1.addVertex(p4); net1.addVertex(p5); net1.addVertex(p6); net1.addVertex(p7); net1.addEdge(p1,p2,0); net1.addEdge(p1,p3,0); net1.addEdge(p2,p5,0); net1.addEdge(p3,p4,0); net1.addEdge(p5,p6,0); net1.addEdge(p5,p1,0); net1.addEdge(p3,p6,0); net1.addEdge(p3,p7,0); net1.addEdge(p3,p2,0); Person pt; EXPECT_EQ(3, net1.maxNewChildren(Person("Ana",19), pt)); EXPECT_EQ("Filipe", pt.getName()); } TEST(CAL_FP04, test_isDAG) { Graph<int> myGraph; myGraph.addVertex(0);myGraph.addVertex(1); myGraph.addVertex(2); myGraph.addVertex(3); myGraph.addVertex(4); myGraph.addVertex(5); myGraph.addEdge(1, 2, 0); myGraph.addEdge(2, 5, 0); myGraph.addEdge(5, 4, 0); myGraph.addEdge(4, 1, 0); myGraph.addEdge(5, 1, 0); myGraph.addEdge(2, 3, 0); myGraph.addEdge(3, 1, 0); myGraph.addEdge(0, 4, 0); EXPECT_EQ(false, myGraph.isDAG()); myGraph.removeEdge(4, 1); myGraph.removeEdge(5, 1); myGraph.removeEdge(2, 3); EXPECT_EQ(true, myGraph.isDAG()); myGraph.addEdge(1, 4, 0); EXPECT_EQ(true, myGraph.isDAG()); } TEST(CAL_FP04, test_topsort) { Graph<int> myGraph; myGraph.addVertex(1); myGraph.addVertex(2); myGraph.addVertex(3); myGraph.addVertex(4); myGraph.addVertex(5); myGraph.addVertex(6); myGraph.addVertex(7); myGraph.addEdge(1, 2, 0); myGraph.addEdge(1, 4, 0); myGraph.addEdge(1, 3, 0); myGraph.addEdge(2, 5, 0); myGraph.addEdge(2, 4, 0); myGraph.addEdge(3, 6, 0); myGraph.addEdge(4, 3, 0); myGraph.addEdge(4, 6, 0); myGraph.addEdge(4, 7, 0); myGraph.addEdge(5, 4, 0); myGraph.addEdge(5, 7, 0); myGraph.addEdge(7, 6, 0); vector<int> topOrder; topOrder = myGraph.topsort(); stringstream ss; for( unsigned int i = 0; i < topOrder.size(); i++) ss << topOrder[i] << " "; EXPECT_EQ("1 2 5 4 3 7 6 ", ss.str()); //para testar a inclusao de um ciclo no grafo! myGraph.addEdge(3, 1, 0); topOrder = myGraph.topsort(); ss.str(""); for( unsigned int i = 0; i < topOrder.size(); i++) ss << topOrder[i] << " "; EXPECT_EQ("", ss.str()); }
28.899123
91
0.604948
ctrlMarcio
dc6b1ac6b929f04af408a582bff1b04a643f3be5
496
cpp
C++
src/qt/ionspaymentprocessor.cpp
IOCoin/Chameleon-
6d4ad8e1dc7127fd992d65ce0c7039d0248f8b5a
[ "MIT" ]
3
2019-04-28T14:45:33.000Z
2021-04-15T09:04:32.000Z
src/qt/ionspaymentprocessor.cpp
IOCoin/Chameleon-
6d4ad8e1dc7127fd992d65ce0c7039d0248f8b5a
[ "MIT" ]
null
null
null
src/qt/ionspaymentprocessor.cpp
IOCoin/Chameleon-
6d4ad8e1dc7127fd992d65ce0c7039d0248f8b5a
[ "MIT" ]
1
2019-07-07T03:19:05.000Z
2019-07-07T03:19:05.000Z
#include "ionspaymentprocessor.h" #include <QString> #include <iostream> IONSPaymentProcessor::IONSPaymentProcessor(BitcoinGUI * gui, QObject * parent) : QObject(parent), gui(gui) { } void IONSPaymentProcessor::pay(QString address, QString fee) { QString uri("chameleon:" + address + "?amount=" + fee); gui->handleURI(uri); } void IONSPaymentProcessor::myUsernames() { gui->ionsMyUsernamesClicked(); } void IONSPaymentProcessor::Register() { gui->ionsRegisterClicked(); }
19.84
78
0.719758
IOCoin
dc6bd473fb4f511baf9097d7d38c69e7d537650f
4,209
cxx
C++
Source/Applications/AppCommon/pqCMBColorMapWidget.cxx
developkits/cmb
caaf9cd7ffe0b7c1ac3be9edbce0f9430068d2cb
[ "BSD-3-Clause" ]
null
null
null
Source/Applications/AppCommon/pqCMBColorMapWidget.cxx
developkits/cmb
caaf9cd7ffe0b7c1ac3be9edbce0f9430068d2cb
[ "BSD-3-Clause" ]
null
null
null
Source/Applications/AppCommon/pqCMBColorMapWidget.cxx
developkits/cmb
caaf9cd7ffe0b7c1ac3be9edbce0f9430068d2cb
[ "BSD-3-Clause" ]
null
null
null
//========================================================================= // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt for details. // // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notice for more information. //========================================================================= #include "pqCMBColorMapWidget.h" #include "pqApplicationCore.h" #include "pqDataRepresentation.h" #include "pqProxyWidget.h" #include "vtkCommand.h" #include "vtkSMPVRepresentationProxy.h" #include "vtkSMProperty.h" #include "vtkSMPropertyHelper.h" #include "vtkSMTransferFunctionProxy.h" #include "vtkWeakPointer.h" #include <QPointer> #include <QVBoxLayout> class pqCMBColorMapWidget::pqInternals { public: QPointer<pqProxyWidget> ProxyWidget; QPointer<pqDataRepresentation> ActiveRepresentation; unsigned long ObserverId; pqInternals(pqCMBColorMapWidget* vtkNotUsed(self)) : ObserverId(0) { } ~pqInternals() {} }; pqCMBColorMapWidget::pqCMBColorMapWidget(QWidget* parentObject) : Superclass(parentObject) , Internals(new pqCMBColorMapWidget::pqInternals(this)) { // pqActiveObjects *activeObjects = &pqActiveObjects::instance(); // this->connect(activeObjects, SIGNAL(representationChanged(pqDataRepresentation*)), // this, SLOT(updateActive())); new QVBoxLayout(this); this->layout()->setMargin(0); this->updateRepresentation(); } pqCMBColorMapWidget::~pqCMBColorMapWidget() { delete this->Internals; this->Internals = NULL; } void pqCMBColorMapWidget::updatePanel() { if (this->Internals->ProxyWidget) { this->Internals->ProxyWidget->filterWidgets(true); } } void pqCMBColorMapWidget::updateRepresentation() { // pqDataRepresentation* repr = // pqActiveObjects::instance().activeRepresentation(); pqDataRepresentation* repr = this->Internals->ActiveRepresentation; // Set the current LUT proxy to edit. if (repr && vtkSMPVRepresentationProxy::GetUsingScalarColoring(repr->getProxy())) { this->setColorTransferFunction( vtkSMPropertyHelper(repr->getProxy(), "LookupTable", true).GetAsProxy()); } else { this->setColorTransferFunction(NULL); } } void pqCMBColorMapWidget::setDataRepresentation(pqDataRepresentation* repr) { // this method sets up hooks to ensure that when the repr's properties are // modified, the editor shows the correct LUT. if (this->Internals->ActiveRepresentation == repr) { return; } if (this->Internals->ActiveRepresentation) { // disconnect signals. if (this->Internals->ObserverId) { this->Internals->ActiveRepresentation->getProxy()->RemoveObserver( this->Internals->ObserverId); } } this->Internals->ObserverId = 0; this->Internals->ActiveRepresentation = repr; if (repr && repr->getProxy()) { this->Internals->ObserverId = repr->getProxy()->AddObserver( vtkCommand::PropertyModifiedEvent, this, &pqCMBColorMapWidget::updateRepresentation); } this->updateRepresentation(); } void pqCMBColorMapWidget::setColorTransferFunction(vtkSMProxy* ctf) { if (this->Internals->ProxyWidget == NULL && ctf == NULL) { return; } if (this->Internals->ProxyWidget && ctf && this->Internals->ProxyWidget->proxy() == ctf) { return; } if ((ctf == NULL && this->Internals->ProxyWidget) || (this->Internals->ProxyWidget && ctf && this->Internals->ProxyWidget->proxy() != ctf)) { this->layout()->removeWidget(this->Internals->ProxyWidget); delete this->Internals->ProxyWidget; } if (!ctf) { return; } pqProxyWidget* widget = new pqProxyWidget(ctf, this); widget->setObjectName("Properties"); widget->setApplyChangesImmediately(true); widget->filterWidgets(); this->layout()->addWidget(widget); this->Internals->ProxyWidget = widget; this->updatePanel(); QObject::connect(widget, SIGNAL(changeFinished()), this, SLOT(renderViews())); } void pqCMBColorMapWidget::renderViews() { if (this->Internals->ActiveRepresentation) { this->Internals->ActiveRepresentation->renderViewEventually(); } }
26.980769
91
0.692801
developkits
dc6c5b6abbdafa433eaf0cba7d63ccaf1937fec2
1,567
cpp
C++
test/main.cpp
zzh8829/LOLMapView
a042cc6c32fac170b5050a19bf5f72b36bc2189e
[ "MIT" ]
5
2015-08-16T02:23:18.000Z
2021-07-23T19:00:16.000Z
test/main.cpp
zzh8829/LOLMapView
a042cc6c32fac170b5050a19bf5f72b36bc2189e
[ "MIT" ]
1
2021-01-16T14:50:17.000Z
2021-01-16T14:50:17.000Z
test/main.cpp
zzh8829/LOLMapView
a042cc6c32fac170b5050a19bf5f72b36bc2189e
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <cmath> #include <algorithm> #include <cstring> #include <set> using namespace std; class Class { public: virtual int func1() { return 0; } virtual int func2() { return 1; } int var1; float var2; }; class Der : public Class { public: int func1() { return 2; } }; int main() { Class* obj = new Der; cout << Class << endl; return 0; } #if 0 typedef long double ld; ld poly[101]; ld newPoly[101]; ld newton(ld x) { int cnt = 0; while (true) { ld fx = poly[0]; ld dfx = 0.0; for(int i=1;i<=100;i++) { dfx += i*poly[i]*pow(x,i-1); fx += poly[i]*pow(x,i); } x = x - fx/dfx; cnt ++ ; if(cnt > 100000) return 0xdeadbeef; ld res = poly[0]; for(int i=1;i<=100;i++) if(poly[i]) res += poly[i]*pow(x,i); if(res < 1e-5) break; } cout << x << endl; return x; } void divide(ld divisor) { memset(newPoly,0,sizeof(newPoly)); ld next = poly[100]; for (int i=99;i>=0;i--) { newPoly[i] = next; next = next*divisor + poly[i]; } memcpy(poly,newPoly,sizeof(poly)); } int main() { int n; cin >> n; int co,po; int tm = 0; for(int i=0;i!=n;i++) { cin >> co >> po; poly[po] = co; if(!tm) tm = po; } set<ld> ans; for(int i=0;i!=tm;i++) { ld root = newton(1227); if(root==0xdeadbeef) break; ans.insert((ld)((((long long)(root))*100000)/100000)); divide(root); } if(ans.size()==0) { cout << "NO REAL ROOTS" << endl; } else { for(set<ld>::iterator it = ans.begin();it!=ans.end();it++) cout << *it << endl; } return 0; } #endif
13.168067
60
0.557754
zzh8829
dc6c883d239f80c74a1828fe076332e42a412f95
5,215
hpp
C++
shared/ebm_native/TreeSweep.hpp
StanislavParovoy/interpret
e2cdb2690988c953ebed81343d6b99e831d3bdf1
[ "MIT" ]
2,674
2019-10-03T14:14:35.000Z
2022-03-31T13:40:49.000Z
shared/ebm_native/TreeSweep.hpp
StanislavParovoy/interpret
e2cdb2690988c953ebed81343d6b99e831d3bdf1
[ "MIT" ]
257
2019-11-08T19:22:56.000Z
2022-03-29T20:09:07.000Z
shared/ebm_native/TreeSweep.hpp
StanislavParovoy/interpret
e2cdb2690988c953ebed81343d6b99e831d3bdf1
[ "MIT" ]
367
2019-10-31T15:33:21.000Z
2022-03-31T13:40:50.000Z
// Copyright (c) 2018 Microsoft Corporation // Licensed under the MIT license. // Author: Paul Koch <code@koch.ninja> #ifndef TREE_SWEEP_HPP #define TREE_SWEEP_HPP #include <type_traits> // std::is_standard_layout #include <stddef.h> // size_t, ptrdiff_t #include "ebm_native.h" #include "logging.h" #include "zones.h" #include "ebm_internal.hpp" #include "HistogramTargetEntry.hpp" namespace DEFINED_ZONE_NAME { #ifndef DEFINED_ZONE_NAME #error DEFINED_ZONE_NAME must be defined #endif // DEFINED_ZONE_NAME template<bool bClassification> struct HistogramBucket; template<bool bClassification> struct TreeSweep final { private: size_t m_cBestSamplesLeft; FloatEbmType m_bestWeightLeft; const HistogramBucket<bClassification> * m_pBestHistogramBucketEntry; // use the "struct hack" since Flexible array member method is not available in C++ // m_aBestHistogramTargetEntry must be the last item in this struct // AND this class must be "is_standard_layout" since otherwise we can't guarantee that this item is placed at the bottom // standard layout classes have some additional odd restrictions like all the member data must be in a single class // (either the parent or child) if the class is derrived HistogramTargetEntry<bClassification> m_aBestHistogramTargetEntry[1]; public: TreeSweep() = default; // preserve our POD status ~TreeSweep() = default; // preserve our POD status void * operator new(std::size_t) = delete; // we only use malloc/free in this library void operator delete (void *) = delete; // we only use malloc/free in this library INLINE_ALWAYS size_t GetCountBestSamplesLeft() const { return m_cBestSamplesLeft; } INLINE_ALWAYS void SetCountBestSamplesLeft(const size_t cBestSamplesLeft) { m_cBestSamplesLeft = cBestSamplesLeft; } INLINE_ALWAYS FloatEbmType GetBestWeightLeft() const { return m_bestWeightLeft; } INLINE_ALWAYS void SetBestWeightLeft(const FloatEbmType bestWeightLeft) { m_bestWeightLeft = bestWeightLeft; } INLINE_ALWAYS const HistogramBucket<bClassification> * GetBestHistogramBucketEntry() const { return m_pBestHistogramBucketEntry; } INLINE_ALWAYS void SetBestHistogramBucketEntry(const HistogramBucket<bClassification> * pBestHistogramBucketEntry) { m_pBestHistogramBucketEntry = pBestHistogramBucketEntry; } INLINE_ALWAYS HistogramTargetEntry<bClassification> * GetBestHistogramTargetEntry() { return ArrayToPointer(m_aBestHistogramTargetEntry); } }; static_assert(std::is_standard_layout<TreeSweep<true>>::value && std::is_standard_layout<TreeSweep<false>>::value, "We use the struct hack in several places, so disallow non-standard_layout types in general"); static_assert(std::is_trivial<TreeSweep<true>>::value && std::is_trivial<TreeSweep<false>>::value, "We use memcpy in several places, so disallow non-trivial types in general"); static_assert(std::is_pod<TreeSweep<true>>::value && std::is_pod<TreeSweep<false>>::value, "We use a lot of C constructs, so disallow non-POD types in general"); INLINE_ALWAYS bool GetTreeSweepSizeOverflow(const bool bClassification, const size_t cVectorLength) { const size_t cBytesHistogramTargetEntry = bClassification ? sizeof(HistogramTargetEntry<true>) : sizeof(HistogramTargetEntry<false>); if(UNLIKELY(IsMultiplyError(cBytesHistogramTargetEntry, cVectorLength))) { return true; } const size_t cBytesTreeSweepComponent = bClassification ? (sizeof(TreeSweep<true>) - sizeof(HistogramTargetEntry<true>)) : (sizeof(TreeSweep<false>) - sizeof(HistogramTargetEntry<false>)); if(UNLIKELY(IsAddError(cBytesTreeSweepComponent, cBytesHistogramTargetEntry * cVectorLength))) { return true; } return false; } INLINE_ALWAYS size_t GetTreeSweepSize(bool bClassification, const size_t cVectorLength) { const size_t cBytesTreeSweepComponent = bClassification ? sizeof(TreeSweep<true>) - sizeof(HistogramTargetEntry<true>) : sizeof(TreeSweep<false>) - sizeof(HistogramTargetEntry<false>); const size_t cBytesHistogramTargetEntry = bClassification ? sizeof(HistogramTargetEntry<true>) : sizeof(HistogramTargetEntry<false>); return cBytesTreeSweepComponent + cBytesHistogramTargetEntry * cVectorLength; } template<bool bClassification> INLINE_ALWAYS TreeSweep<bClassification> * AddBytesTreeSweep(TreeSweep<bClassification> * const pTreeSweep, const size_t cBytesAdd) { return reinterpret_cast<TreeSweep<bClassification> *>(reinterpret_cast<char *>(pTreeSweep) + cBytesAdd); } template<bool bClassification> INLINE_ALWAYS size_t CountTreeSweep( const TreeSweep<bClassification> * const pTreeSweepStart, const TreeSweep<bClassification> * const pTreeSweepCur, const size_t cBytesPerTreeSweep ) { EBM_ASSERT(reinterpret_cast<const char *>(pTreeSweepStart) <= reinterpret_cast<const char *>(pTreeSweepCur)); const size_t cBytesDiff = reinterpret_cast<const char *>(pTreeSweepCur) - reinterpret_cast<const char *>(pTreeSweepStart); EBM_ASSERT(0 == cBytesDiff % cBytesPerTreeSweep); return cBytesDiff / cBytesPerTreeSweep; } } // DEFINED_ZONE_NAME #endif // TREE_SWEEP_HPP
38.62963
133
0.771812
StanislavParovoy
dc6cefc0ede1e6ca1c2b0d630ac5a56aaefd6665
863
cpp
C++
proxygen/lib/http/codec/compress/HPACKEncoderBase.cpp
Mu-L/proxygen
10c368c3fbb7fd357a7c73f8e15dd4cf1d15f399
[ "BSD-3-Clause" ]
null
null
null
proxygen/lib/http/codec/compress/HPACKEncoderBase.cpp
Mu-L/proxygen
10c368c3fbb7fd357a7c73f8e15dd4cf1d15f399
[ "BSD-3-Clause" ]
null
null
null
proxygen/lib/http/codec/compress/HPACKEncoderBase.cpp
Mu-L/proxygen
10c368c3fbb7fd357a7c73f8e15dd4cf1d15f399
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #include <proxygen/lib/http/codec/compress/HPACKEncoderBase.h> namespace proxygen { uint32_t HPACKEncoderBase::handlePendingContextUpdate(HPACKEncodeBuffer& buf, uint32_t tableCapacity) { CHECK_EQ(HPACK::TABLE_SIZE_UPDATE.code, HPACK::Q_TABLE_SIZE_UPDATE.code) << "Code assumes these are equal"; uint32_t encoded = 0; if (pendingContextUpdate_) { VLOG(5) << "Encoding table size update size=" << tableCapacity; encoded = buf.encodeInteger(tableCapacity, HPACK::TABLE_SIZE_UPDATE); pendingContextUpdate_ = false; } return encoded; } } // namespace proxygen
30.821429
79
0.697567
Mu-L
dc7096bc57120b88d88b63f377fb508eaa3183aa
5,104
cpp
C++
src/modules/twinkle.cpp
Cameloah/fairy-in-a-jar
a1ddc913664aff0bc7e9e71a1cd0a8cdecf44074
[ "MIT" ]
null
null
null
src/modules/twinkle.cpp
Cameloah/fairy-in-a-jar
a1ddc913664aff0bc7e9e71a1cd0a8cdecf44074
[ "MIT" ]
null
null
null
src/modules/twinkle.cpp
Cameloah/fairy-in-a-jar
a1ddc913664aff0bc7e9e71a1cd0a8cdecf44074
[ "MIT" ]
null
null
null
#include "modules/twinkle.h" // Background color for 'unlit' pixels // Can be set to CRGB::Black if desired. CRGB gBackgroundColor = CRGB::Black; // Example of dim incandescent fairy light background color // CRGB gBackgroundColor = CRGB(CRGB::FairyLight).nscale8_video(16); // Add or remove palette names from this list to control which color // palettes are used, and in what order. const TProgmemRGBPalette16* ActivePaletteList[] = { //&RetroC9_p, //&BlueWhite_p, //&RainbowColors_p, &HeatColors_p, //&LavaColors_p, &FairyLight_p, &RedGreenWhite_p, &ForestColors_p, &PartyColors_p, &RedWhite_p, &OceanColors_p, //&Snow_p, //&Holly_p, //&Ice_p }; CRGBPalette16 gCurrentPalette; CRGBPalette16 gTargetPalette; void twinkle_init() { delay( 1000 ); //safety startup delay chooseNextColorPalette(gTargetPalette); } void twinkle_update(CRGBSet& user_leds) { EVERY_N_SECONDS( SECONDS_PER_PALETTE ) { chooseNextColorPalette( gTargetPalette ); } EVERY_N_MILLISECONDS( 10 ) { nblendPaletteTowardPalette( gCurrentPalette, gTargetPalette, 12); } drawTwinkles( user_leds); } void drawTwinkles( CRGBSet& L) { // "PRNG16" is the pseudorandom number generator // It MUST be reset to the same starting value each time // this function is called, so that the sequence of 'random' // numbers that it generates is (paradoxically) stable. uint16_t PRNG16 = 11337; uint32_t clock32 = millis(); // Set up the background color, "bg". // if AUTO_SELECT_BACKGROUND_COLOR == 1, and the first two colors of // the current palette are identical, then a deeply faded version of // that color is used for the background color CRGB bg; if( (AUTO_SELECT_BACKGROUND_COLOR == 1) && (gCurrentPalette[0] == gCurrentPalette[1] )) { bg = gCurrentPalette[0]; uint8_t bglight = bg.getAverageLight(); if( bglight > 64) { bg.nscale8_video( 16); // very bright, so scale to 1/16th } else if( bglight > 16) { bg.nscale8_video( 64); // not that bright, so scale to 1/4th } else { bg.nscale8_video( 86); // dim, scale to 1/3rd. } } else { bg = gBackgroundColor; // just use the explicitly defined background color } uint8_t backgroundBrightness = bg.getAverageLight(); for( CRGB& pixel: L) { PRNG16 = (uint16_t)(PRNG16 * 2053) + 1384; // next 'random' number uint16_t myclockoffset16= PRNG16; // use that number as clock offset PRNG16 = (uint16_t)(PRNG16 * 2053) + 1384; // next 'random' number // use that number as clock speed adjustment factor (in 8ths, from 8/8ths to 23/8ths) uint8_t myspeedmultiplierQ5_3 = ((((PRNG16 & 0xFF)>>4) + (PRNG16 & 0x0F)) & 0x0F) + 0x08; uint32_t myclock30 = (uint32_t)((clock32 * myspeedmultiplierQ5_3) >> 3) + myclockoffset16; uint8_t myunique8 = PRNG16 >> 8; // get 'salt' value for this pixel // We now have the adjusted 'clock' for this pixel, now we call // the function that computes what color the pixel should be based // on the "brightness = f( time )" idea. CRGB c = computeOneTwinkle( myclock30, myunique8); uint8_t cbright = c.getAverageLight(); int16_t deltabright = cbright - backgroundBrightness; if( deltabright >= 32 || (!bg)) { // If the new pixel is significantly brighter than the background color, // use the new color. pixel = c; } else if( deltabright > 0 ) { // If the new pixel is just slightly brighter than the background color, // mix a blend of the new color and the background color pixel = blend( bg, c, deltabright * 8); } else { // if the new pixel is not at all brighter than the background color, // just use the background color. pixel = bg; } } } CRGB computeOneTwinkle( uint32_t ms, uint8_t salt) { uint16_t ticks = ms >> (8-TWINKLE_SPEED); uint8_t fastcycle8 = ticks; uint16_t slowcycle16 = (ticks >> 8) + salt; slowcycle16 += sin8( slowcycle16); slowcycle16 = (slowcycle16 * 2053) + 1384; uint8_t slowcycle8 = (slowcycle16 & 0xFF) + (slowcycle16 >> 8); uint8_t bright = 0; if( ((slowcycle8 & 0x0E)/2) < TWINKLE_DENSITY) { bright = attackDecayWave8( fastcycle8); } uint8_t hue = slowcycle8 - salt; CRGB c; if( bright > 0) { c = ColorFromPalette( gCurrentPalette, hue, bright, NOBLEND); if( COOL_LIKE_INCANDESCENT == 1 ) { coolLikeIncandescent( c, fastcycle8); } } else { c = CRGB::Black; } return c; } uint8_t attackDecayWave8( uint8_t i) { if( i < 86) { return i * 3; } else { i -= 86; return 255 - (i + (i/2)); } } void coolLikeIncandescent( CRGB& c, uint8_t phase) { if( phase < 128) return; uint8_t cooling = (phase - 128) >> 4; c.g = qsub8( c.g, cooling); c.b = qsub8( c.b, cooling * 2); } void chooseNextColorPalette( CRGBPalette16& pal) { const uint8_t numberOfPalettes = sizeof(ActivePaletteList) / sizeof(ActivePaletteList[0]); static uint8_t whichPalette = -1; whichPalette = addmod8( whichPalette, 1, numberOfPalettes); pal = *(ActivePaletteList[whichPalette]); }
28.513966
94
0.669867
Cameloah
dc70f7550217cfede7f560d4066f7d67f637bf1e
1,574
cpp
C++
src/elona/browser.cpp
XrosFade/ElonaFoobar
c33880080e0b475103ae3ea7d546335f9d4abd02
[ "MIT" ]
null
null
null
src/elona/browser.cpp
XrosFade/ElonaFoobar
c33880080e0b475103ae3ea7d546335f9d4abd02
[ "MIT" ]
null
null
null
src/elona/browser.cpp
XrosFade/ElonaFoobar
c33880080e0b475103ae3ea7d546335f9d4abd02
[ "MIT" ]
null
null
null
#include "browser.hpp" #include <cstdlib> #include <string> #include "../util/range.hpp" #include "config/config.hpp" #ifdef ELONA_OS_WINDOWS #include <windows.h> #endif using namespace std::literals::string_literals; namespace { bool _is_trusted_url(const char* url) { const char* trusted_urls[] = { "http://ylvania.org/jp", "http://ylvania.org/en", "https://elonafoobar.com", }; return range::find(trusted_urls, url) != std::end(trusted_urls); } } // namespace namespace elona { void open_browser(const char* url) { if (Config::instance().is_test) { return; } if (!_is_trusted_url(url)) { throw std::runtime_error{"Try to open unknown URL!"}; } #if defined(ELONA_OS_WINDOWS) HWND parent = NULL; LPCWSTR operation = NULL; // `url` must be ascii only. const auto len = std::strlen(url); std::basic_string<WCHAR> url_(len, L'\0'); for (size_t i = 0; i < len; ++i) { url_[i] = url[i]; } LPCWSTR extra_parameter = NULL; LPCWSTR default_dir = NULL; INT show_command = SW_SHOWNORMAL; ::ShellExecute( parent, operation, url_.c_str(), extra_parameter, default_dir, show_command); #elif defined(ELONA_OS_MACOS) std::system(("open "s + url).c_str()); #elif defined(ELONA_OS_LINUX) std::system(("xdg-open "s + url).c_str()); #elif defined(ELONA_OS_ANDROID) // TODO: implement for android. (void)url; return; #else #error "Unsupported OS" #endif } } // namespace elona
18.963855
68
0.617535
XrosFade
dc718e28571039e76a6f51489477a1781cb5d665
3,856
cpp
C++
server/api/src/rsDataObjLseek.cpp
aghsmith/irods
31d48a47a4942df688da94b30aa8a5b5210261bb
[ "BSD-3-Clause" ]
1
2022-03-08T13:00:56.000Z
2022-03-08T13:00:56.000Z
server/api/src/rsDataObjLseek.cpp
selroc/irods
d232c7f3e0154cacc3a115aa50e366a98617b126
[ "BSD-3-Clause" ]
null
null
null
server/api/src/rsDataObjLseek.cpp
selroc/irods
d232c7f3e0154cacc3a115aa50e366a98617b126
[ "BSD-3-Clause" ]
null
null
null
#include "irods/rsDataObjLseek.hpp" #include "irods/dataObjLseek.h" #include "irods/rodsLog.h" #include "irods/rsGlobalExtern.hpp" #include "irods/rcGlobalExtern.h" #include "irods/subStructFileLseek.h" #include "irods/objMetaOpr.hpp" #include "irods/subStructFileUnlink.h" #include "irods/rsSubStructFileLseek.hpp" #include "irods/rsFileLseek.hpp" #include "irods/irods_resource_backport.hpp" #include <cstring> int rsDataObjLseek(rsComm_t* rsComm, openedDataObjInp_t* dataObjLseekInp, fileLseekOut_t** dataObjLseekOut) { const int l1descInx = dataObjLseekInp->l1descInx; if (l1descInx <= 2 || l1descInx >= NUM_L1_DESC) { rodsLog(LOG_ERROR, "%s: l1descInx %d out of range", __func__, l1descInx); return SYS_FILE_DESC_OUT_OF_RANGE; } auto& l1desc = L1desc[l1descInx]; if (l1desc.inuseFlag != FD_INUSE) { return BAD_INPUT_DESC_INDEX; } if (l1desc.remoteZoneHost) { // Cross zone operation. dataObjLseekInp->l1descInx = l1desc.remoteL1descInx; const auto ec = rcDataObjLseek(l1desc.remoteZoneHost->conn, dataObjLseekInp, dataObjLseekOut); dataObjLseekInp->l1descInx = l1descInx; return ec; } const int l3descInx = l1desc.l3descInx; if (l3descInx <= 2) { rodsLog(LOG_ERROR, "%s: l3descInx %d out of range", __func__, l3descInx); return SYS_FILE_DESC_OUT_OF_RANGE; } auto* dataObjInfo = l1desc.dataObjInfo; // Extract the host location from the resource hierarchy. std::string location; if (const auto ret = irods::get_loc_for_hier_string(dataObjInfo->rescHier, location); !ret.ok()) { irods::log(PASSMSG("rsDataObjLseek: failed in get_loc_for_hier_string", ret)); return ret.code(); } if (getStructFileType(dataObjInfo->specColl) >= 0) { subStructFileLseekInp_t subStructFileLseekInp{}; subStructFileLseekInp.type = dataObjInfo->specColl->type; subStructFileLseekInp.fd = l1desc.l3descInx; subStructFileLseekInp.offset = dataObjLseekInp->offset; subStructFileLseekInp.whence = dataObjLseekInp->whence; rstrcpy(subStructFileLseekInp.addr.hostAddr, location.c_str(), NAME_LEN); rstrcpy(subStructFileLseekInp.resc_hier, dataObjInfo->rescHier, NAME_LEN); return rsSubStructFileLseek(rsComm, &subStructFileLseekInp, dataObjLseekOut); } // If the replica was opened in read-only mode, then don't allow the client // to seek past the data size in the catalog. This is necessary because the // size of the replica in storage could be larger than the data size in the // catalog. // // For all other modes, let the seek operation do what it normally does. // // This code does not apply to objects that are related to special collections. const auto offset = (O_RDONLY == (l1desc.dataObjInp->openFlags & O_ACCMODE)) ? std::min(dataObjLseekInp->offset, dataObjInfo->dataSize) : dataObjLseekInp->offset; *dataObjLseekOut = static_cast<fileLseekOut_t*>(malloc(sizeof(fileLseekOut_t))); std::memset(*dataObjLseekOut, 0, sizeof(fileLseekOut_t)); (*dataObjLseekOut)->offset = _l3Lseek(rsComm, l3descInx, offset, dataObjLseekInp->whence); if ((*dataObjLseekOut)->offset >= 0) { return 0; } return (*dataObjLseekOut)->offset; } rodsLong_t _l3Lseek(rsComm_t* rsComm, int l3descInx, rodsLong_t offset, int whence) { fileLseekInp_t fileLseekInp{}; fileLseekInp.fileInx = l3descInx; fileLseekInp.offset = offset; fileLseekInp.whence = whence; fileLseekOut_t* fileLseekOut = nullptr; if (const auto ec = rsFileLseek(rsComm, &fileLseekInp, &fileLseekOut); ec < 0) { return ec; } const auto off = fileLseekOut->offset; std::free(fileLseekOut); return off; }
34.738739
102
0.696577
aghsmith
dc7207b35da8dff0d9bbfe3d8c601d9a94f5cafd
11,439
hxx
C++
com/rpc/runtime/mtrt/secclnt.hxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
com/rpc/runtime/mtrt/secclnt.hxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
com/rpc/runtime/mtrt/secclnt.hxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Copyright (C) Microsoft Corporation, 1991 - 1999 Module Name: secclnt.hxx Abstract: This file contains an abstraction to the security support for clients and that which is common to both servers and clients. Author: Michael Montague (mikemon) 10-Apr-1992 Revision History: --*/ #ifndef __SECCLNT_HXX__ #define __SECCLNT_HXX__ typedef SecBufferDesc SECURITY_BUFFER_DESCRIPTOR; typedef SecBuffer SECURITY_BUFFER; #define MAXIMUM_SECURITY_BLOCK_SIZE 16 enum PACKAGE_LEG_COUNT { LegsUnknown, ThreeLegs, EvenNumberOfLegs }; typedef struct { #ifdef UNICODE SecPkgInfoW PackageInfo; #else SecPkgInfoA PackageInfo; #endif SECURITY_CREDENTIALS *ServerSecurityCredentials; PACKAGE_LEG_COUNT LegCount; } SECURITY_PACKAGE_INFO; typedef struct { unsigned long Count; SECURITY_PACKAGE_INFO * SecurityPackages; PSecurityFunctionTable RpcSecurityInterface; void * ProviderDll; RPC_CHAR *ProviderDllName; } SECURITY_PROVIDER_INFO; extern SECURITY_PROVIDER_INFO PAPI * ProviderList; extern unsigned long NumberOfProviders; extern unsigned long LoadedProviders; extern unsigned long AvailableProviders; extern int SecuritySupportLoaded; extern int FailedToLoad; extern PSecurityFunctionTable RpcSecurityInterface; extern SecPkgInfo PAPI * SecurityPackages; extern unsigned long NumberOfSecurityPackages; extern MUTEX * SecurityCritSect; extern RPC_STATUS InsureSecuritySupportLoaded ( ); extern RPC_STATUS IsAuthenticationServiceSupported ( IN unsigned long AuthenticationService ); extern RPC_STATUS FindServerCredentials ( IN RPC_AUTH_KEY_RETRIEVAL_FN GetKeyFn, IN void __RPC_FAR * Arg, IN unsigned long AuthenticationService, IN unsigned long AuthenticationLevel, IN RPC_CHAR __RPC_FAR * Principal, IN OUT SECURITY_CREDENTIALS ** SecurityCredentials ); extern RPC_STATUS RemoveCredentialsFromCache ( IN unsigned long AuthenticationService ); extern PACKAGE_LEG_COUNT GetPackageLegCount( DWORD id ); extern BOOL ReadPackageLegInfo(); extern DWORD * FourLeggedPackages; class SECURITY_CREDENTIALS /*++ Class Description: This class is an abstraction of the credential handle provided by the Security APIs. Fields: PackageIndex - Contains the index for this package in the array of packages pointed to by SecurityPackages. Credentials - Contains the credential handle used by the security package. --*/ { friend RPC_STATUS FindServerCredentials ( IN RPC_AUTH_KEY_RETRIEVAL_FN GetKeyFn, IN void __RPC_FAR * Arg, IN unsigned long AuthenticationService, IN unsigned long AuthenticationLevel, IN RPC_CHAR __RPC_FAR * Principal, IN OUT SECURITY_CREDENTIALS ** SecurityCredentials ); public: unsigned AuthenticationService; private: BOOL Valid; unsigned int ProviderIndex; unsigned int PackageIndex; CredHandle CredentialsHandle; unsigned int ReferenceCount; MUTEX CredentialsMutex; SEC_CHAR __SEC_FAR * DefaultPrincName; public: SECURITY_CREDENTIALS ( IN OUT RPC_STATUS PAPI * Status ); ~SECURITY_CREDENTIALS (); RPC_STATUS AcquireCredentialsForServer ( IN RPC_AUTH_KEY_RETRIEVAL_FN GetKeyFn, IN void __RPC_FAR * Arg, IN unsigned long AuthenticationService, IN unsigned long AuthenticationLevel, IN RPC_CHAR __RPC_FAR * Principal ); RPC_STATUS AcquireCredentialsForClient ( IN RPC_AUTH_IDENTITY_HANDLE AuthIdentity, IN unsigned long AuthenticationService, IN unsigned long AuthenticationLevel ); RPC_STATUS InquireDefaultPrincName ( OUT SEC_CHAR __SEC_FAR **MyDefaultPrincName ); void FreeCredentials ( ); unsigned int MaximumTokenLength ( ); PCredHandle InquireCredHandle ( ); void ReferenceCredentials( void ); void DereferenceCredentials( void ); PSecurityFunctionTable InquireProviderFunctionTable ( ); int CompareCredentials( SECURITY_CREDENTIALS PAPI * Creds ); }; inline int SECURITY_CREDENTIALS::CompareCredentials( SECURITY_CREDENTIALS PAPI * Creds ) { CredHandle * Cookie = Creds->InquireCredHandle(); if ( (CredentialsHandle.dwLower == Cookie->dwLower) &&(CredentialsHandle.dwUpper == Cookie->dwUpper) ) { return 0; } return 1; } inline unsigned int SECURITY_CREDENTIALS::MaximumTokenLength ( ) /*++ Return Value: The maximum size, in bytes, of the tokens passed around at security context initialization time. --*/ { return(ProviderList[ProviderIndex].SecurityPackages[PackageIndex].PackageInfo.cbMaxToken); } inline PSecurityFunctionTable SECURITY_CREDENTIALS::InquireProviderFunctionTable( ) /*++ Return Value: --*/ { return(ProviderList[ProviderIndex].RpcSecurityInterface); } inline PCredHandle SECURITY_CREDENTIALS::InquireCredHandle ( ) /*++ Return Value: The credential handle for this object will be returned. --*/ { return(&CredentialsHandle); } class SECURITY_CONTEXT : public CLIENT_AUTH_INFO /*++ Class Description: This is an abstraction of a security context. It allows you to use it to generate signatures and then verify them, as well as, sealing and unsealing messages. Fields: DontForgetToDelete - Contains a flag indicating whether or not there is a valid security context which needs to be deleted. A value of non-zero indicates there is a valid security context. SecurityContext - Contains a handle to the security context maintained by the security package on our behalf. MaxHeaderLength - Contains the maximum size of a header for this security context. MaxSignatureLength - Contains the maximum size of a signature for this security context. --*/ { public: unsigned AuthContextId; unsigned Flags; unsigned long ContextAttributes; PACKAGE_LEG_COUNT Legs; SECURITY_CONTEXT ( CLIENT_AUTH_INFO *myAuthInfo, unsigned myAuthContextId, BOOL fUseDatagram, RPC_STATUS __RPC_FAR * pStatus ); inline ~SECURITY_CONTEXT ( void ) { DeleteSecurityContext(); } RPC_STATUS SetMaximumLengths ( ); unsigned int MaximumHeaderLength ( ); unsigned int MaximumSignatureLength ( ); unsigned int BlockSize ( ); RPC_STATUS CompleteSecurityToken ( IN OUT SECURITY_BUFFER_DESCRIPTOR PAPI * BufferDescriptor ); RPC_STATUS SignOrSeal ( IN unsigned long Sequence, IN unsigned int SignNotSealFlag, IN OUT SECURITY_BUFFER_DESCRIPTOR PAPI * BufferDescriptor ); RPC_STATUS VerifyOrUnseal ( IN unsigned long Sequence, IN unsigned int VerifyNotUnsealFlag, IN OUT SECURITY_BUFFER_DESCRIPTOR PAPI * BufferDescriptor ); BOOL FullyConstructed() { return fFullyConstructed; } // client-side calls RPC_STATUS InitializeFirstTime( IN SECURITY_CREDENTIALS * Credentials, IN RPC_CHAR * ServerPrincipal, IN unsigned long AuthenticationLevel, IN OUT SECURITY_BUFFER_DESCRIPTOR * BufferDescriptor, IN OUT unsigned char *NewAuthType = NULL ); RPC_STATUS InitializeThirdLeg( IN SECURITY_CREDENTIALS * Credentials, IN unsigned long DataRep, IN SECURITY_BUFFER_DESCRIPTOR * In, IN OUT SECURITY_BUFFER_DESCRIPTOR * Out ); RPC_STATUS GetWireIdForSnego( OUT unsigned char *WireId ); RPC_STATUS InqMarshalledTargetInfo ( OUT unsigned long *MarshalledTargetInfoLength, OUT unsigned char **MarshalledTargetInfo ); // server-side calls void DeletePac ( void PAPI * Pac ); RPC_STATUS AcceptFirstTime ( IN SECURITY_CREDENTIALS * Credentials, IN SECURITY_BUFFER_DESCRIPTOR PAPI * InputBufferDescriptor, IN OUT SECURITY_BUFFER_DESCRIPTOR PAPI * OutputBufferDescriptor, IN unsigned long AuthenticationLevel, IN unsigned long DataRepresentation, IN unsigned long NewContextNeededFlag ); RPC_STATUS AcceptThirdLeg ( IN unsigned long DataRepresentation, IN SECURITY_BUFFER_DESCRIPTOR PAPI * BufferDescriptor, OUT SECURITY_BUFFER_DESCRIPTOR PAPI * OutBufferDescriptor ); unsigned long InquireAuthorizationService ( ); RPC_AUTHZ_HANDLE InquirePrivileges ( ); RPC_STATUS ImpersonateClient ( ); void RevertToSelf ( ); RPC_STATUS GetAccessToken ( OUT HANDLE *ImpersonationToken, OUT BOOL *fNeedToCloseToken ); inline AUTHZ_CLIENT_CONTEXT_HANDLE GetAuthzContext ( void ) { return AuthzClientContext; } inline PAUTHZ_CLIENT_CONTEXT_HANDLE GetAuthzContextAddress ( void ) { return &AuthzClientContext; } RPC_STATUS GetDceInfo ( RPC_AUTHZ_HANDLE __RPC_FAR * PacHandle, unsigned long __RPC_FAR * AuthzSvc ); void DeleteSecurityContext ( void ); RPC_STATUS CheckForFailedThirdLeg ( void ); protected: unsigned char fFullyConstructed; unsigned char DontForgetToDelete; unsigned char fDatagram; CtxtHandle SecurityContext; unsigned int MaxHeaderLength; unsigned int MaxSignatureLength; unsigned int cbBlockSize; PSecurityFunctionTable RpcSecurityInterface; int FailedContext; ExtendedErrorInfo *FailedContextEEInfo; AUTHZ_CLIENT_CONTEXT_HANDLE AuthzClientContext; DWORD VerifyCertificate(); public: CtxtHandle * InqSecurityContext () { return &SecurityContext; } }; typedef SECURITY_CONTEXT * PSECURITY_CONTEXT; inline unsigned int SECURITY_CONTEXT::MaximumHeaderLength ( ) /*++ Return Value: The maximum size of the header used by SECURITY_CONTEXT::SealMessage will be returned. This is in bytes. --*/ { return(MaxHeaderLength); } inline unsigned int SECURITY_CONTEXT::BlockSize ( ) /*++ Return Value: For best effect, buffers to be signed or sealed should be a multiple of this length. --*/ { return(cbBlockSize); } inline unsigned int SECURITY_CONTEXT::MaximumSignatureLength ( ) /*++ Return Value: The maximum size, in bytes, of the signature used by SECURITY_CONTEXT::MakeSignature will be returned. --*/ { return(MaxSignatureLength); } #endif // __SECCLNT_HXX__
20.648014
93
0.655564
npocmaka
dc789022f623c1b1bcf6e21863d05f788dee77d7
6,192
cpp
C++
Source/WebCore/html/HTMLSlotElement.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
6
2021-07-05T16:09:39.000Z
2022-03-06T22:44:42.000Z
Source/WebCore/html/HTMLSlotElement.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
7
2022-03-15T13:25:39.000Z
2022-03-15T13:25:44.000Z
Source/WebCore/html/HTMLSlotElement.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (C) 2015 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "HTMLSlotElement.h" #include "Event.h" #include "EventNames.h" #include "HTMLNames.h" #include "MutationObserver.h" #include "ShadowRoot.h" #include "Text.h" #include <wtf/IsoMallocInlines.h> namespace WebCore { WTF_MAKE_ISO_ALLOCATED_IMPL(HTMLSlotElement); using namespace HTMLNames; Ref<HTMLSlotElement> HTMLSlotElement::create(const QualifiedName& tagName, Document& document) { return adoptRef(*new HTMLSlotElement(tagName, document)); } HTMLSlotElement::HTMLSlotElement(const QualifiedName& tagName, Document& document) : HTMLElement(tagName, document) { ASSERT(hasTagName(slotTag)); } HTMLSlotElement::InsertedIntoAncestorResult HTMLSlotElement::insertedIntoAncestor(InsertionType insertionType, ContainerNode& parentOfInsertedTree) { auto insertionResult = HTMLElement::insertedIntoAncestor(insertionType, parentOfInsertedTree); ASSERT_UNUSED(insertionResult, insertionResult == InsertedIntoAncestorResult::Done); if (insertionType.treeScopeChanged && isInShadowTree()) { if (auto* shadowRoot = containingShadowRoot()) shadowRoot->addSlotElementByName(attributeWithoutSynchronization(nameAttr), *this); } return InsertedIntoAncestorResult::Done; } void HTMLSlotElement::removedFromAncestor(RemovalType removalType, ContainerNode& oldParentOfRemovedTree) { if (removalType.treeScopeChanged && oldParentOfRemovedTree.isInShadowTree()) { auto* oldShadowRoot = oldParentOfRemovedTree.containingShadowRoot(); ASSERT(oldShadowRoot); oldShadowRoot->removeSlotElementByName(attributeWithoutSynchronization(nameAttr), *this, oldParentOfRemovedTree); } HTMLElement::removedFromAncestor(removalType, oldParentOfRemovedTree); } void HTMLSlotElement::childrenChanged(const ChildChange& childChange) { HTMLElement::childrenChanged(childChange); if (isInShadowTree()) { if (auto* shadowRoot = containingShadowRoot()) shadowRoot->slotFallbackDidChange(*this); } } void HTMLSlotElement::attributeChanged(const QualifiedName& name, const AtomString& oldValue, const AtomString& newValue, AttributeModificationReason reason) { HTMLElement::attributeChanged(name, oldValue, newValue, reason); if (isInShadowTree() && name == nameAttr) { if (auto shadowRoot = makeRefPtr(containingShadowRoot())) shadowRoot->renameSlotElement(*this, oldValue, newValue); } } const Vector<Node*>* HTMLSlotElement::assignedNodes() const { auto shadowRoot = makeRefPtr(containingShadowRoot()); if (!shadowRoot) return nullptr; return shadowRoot->assignedNodesForSlot(*this); } static void flattenAssignedNodes(Vector<Ref<Node>>& nodes, const HTMLSlotElement& slot) { if (!slot.containingShadowRoot()) return; auto* assignedNodes = slot.assignedNodes(); if (!assignedNodes) { for (RefPtr<Node> child = slot.firstChild(); child; child = child->nextSibling()) { if (is<HTMLSlotElement>(*child)) flattenAssignedNodes(nodes, downcast<HTMLSlotElement>(*child)); else if (is<Text>(*child) || is<Element>(*child)) nodes.append(*child); } return; } for (const RefPtr<Node>& node : *assignedNodes) { if (is<HTMLSlotElement>(*node) && downcast<HTMLSlotElement>(*node).containingShadowRoot()) flattenAssignedNodes(nodes, downcast<HTMLSlotElement>(*node)); else nodes.append(*node); } } Vector<Ref<Node>> HTMLSlotElement::assignedNodes(const AssignedNodesOptions& options) const { if (options.flatten) { if (!isInShadowTree()) return { }; Vector<Ref<Node>> nodes; flattenAssignedNodes(nodes, *this); return nodes; } auto* assignedNodes = this->assignedNodes(); if (!assignedNodes) return { }; return assignedNodes->map([] (Node* node) { return makeRef(*node); }); } Vector<Ref<Element>> HTMLSlotElement::assignedElements(const AssignedNodesOptions& options) const { auto nodes = assignedNodes(options); Vector<Ref<Element>> elements; elements.reserveCapacity(nodes.size()); for (auto& node : nodes) { if (is<Element>(node)) elements.uncheckedAppend(static_reference_cast<Element>(WTFMove(node))); } return elements; } void HTMLSlotElement::enqueueSlotChangeEvent() { // https://dom.spec.whatwg.org/#signal-a-slot-change if (m_inSignalSlotList) return; m_inSignalSlotList = true; MutationObserver::enqueueSlotChangeEvent(*this); } void HTMLSlotElement::dispatchSlotChangeEvent() { m_inSignalSlotList = false; Ref<Event> event = Event::create(eventNames().slotchangeEvent, Event::CanBubble::Yes, Event::IsCancelable::No); event->setTarget(this); dispatchEvent(event); } }
34.592179
157
0.721576
jacadcaps
dc78e1b955c29b261b2103479ea00bb836c0a31f
3,457
cc
C++
lite/kernels/arm/concat_compute.cc
xw-github/Paddle-Lite
3cbd1d375d89c4deb379d44cdbcdc32ee74634c5
[ "Apache-2.0" ]
null
null
null
lite/kernels/arm/concat_compute.cc
xw-github/Paddle-Lite
3cbd1d375d89c4deb379d44cdbcdc32ee74634c5
[ "Apache-2.0" ]
null
null
null
lite/kernels/arm/concat_compute.cc
xw-github/Paddle-Lite
3cbd1d375d89c4deb379d44cdbcdc32ee74634c5
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "lite/kernels/arm/concat_compute.h" #include <string> #include <vector> #include "lite/backends/arm/math/funcs.h" #include "lite/core/op_registry.h" #include "lite/core/tensor.h" #include "lite/core/type_system.h" namespace paddle { namespace lite { namespace kernels { namespace arm { std::vector<size_t> stride_numel(const DDim& ddim) { std::vector<size_t> strides(ddim.size()); strides[ddim.size() - 1] = ddim[ddim.size() - 1]; for (int i = ddim.size() - 2; i >= 0; --i) { strides[i] = strides[i + 1] * ddim[i]; } return strides; } template <typename T> void ConcatFunc(const std::vector<lite::Tensor*> inputs, int axis, lite::Tensor* out) { // Sometimes direct copies will be faster, this maybe need deeply analysis. if (axis == 0 && inputs.size() < 10) { size_t output_offset = 0; for (auto* in : inputs) { auto in_stride = stride_numel(in->dims()); auto out_stride = stride_numel(out->dims()); void* dst = out->mutable_data<T>() + output_offset; const void* src = in->data<T>(); // src and dst tensor should have the same dims size. CHECK(in_stride.size() == out_stride.size()); std::memcpy(dst, src, sizeof(T) * in_stride[0]); output_offset += in_stride[0]; } } else { std::vector<lite::Tensor*> inputs_concat(inputs.size()); for (int j = 0; j < inputs.size(); ++j) { inputs_concat[j] = inputs[j]; } lite::arm::math::concat_func<T>(inputs_concat, axis, out); } } void ConcatCompute::Run() { auto& param = Param<operators::ConcatParam>(); std::vector<lite::Tensor*> inputs = param.x; CHECK_GE(inputs.size(), 1); auto* out = param.output; int axis = param.axis; auto* axis_tensor = param.axis_tensor; if (axis_tensor != nullptr) { auto* axis_tensor_data = axis_tensor->data<int>(); axis = axis_tensor_data[0]; } switch (inputs.front()->precision()) { case PRECISION(kFloat): ConcatFunc<float>(inputs, axis, out); break; case PRECISION(kInt32): ConcatFunc<int32_t>(inputs, axis, out); break; case PRECISION(kInt64): ConcatFunc<int64_t>(inputs, axis, out); break; default: LOG(FATAL) << "Concat does not implement for the " << "input type:" << static_cast<int>(inputs.front()->precision()); } } } // namespace arm } // namespace kernels } // namespace lite } // namespace paddle REGISTER_LITE_KERNEL( concat, kARM, kAny, kNCHW, paddle::lite::kernels::arm::ConcatCompute, def) .BindInput("X", {LiteType::GetTensorTy(TARGET(kARM), PRECISION(kAny))}) .BindInput("AxisTensor", {LiteType::GetTensorTy(TARGET(kARM), PRECISION(kInt32))}) .BindOutput("Out", {LiteType::GetTensorTy(TARGET(kARM), PRECISION(kAny))}) .Finalize();
33.240385
78
0.649407
xw-github
dc7b9cfa26f956c189206b088a989af82ea64920
47,529
inl
C++
src/fonts/stb_font_consolas_bold_35_usascii.inl
stetre/moonfonts
5c8010c02ea62edcf42902e09478b0cd14af56ea
[ "MIT" ]
3
2018-03-13T12:51:57.000Z
2021-10-11T11:32:17.000Z
src/fonts/stb_font_consolas_bold_35_usascii.inl
stetre/moonfonts
5c8010c02ea62edcf42902e09478b0cd14af56ea
[ "MIT" ]
null
null
null
src/fonts/stb_font_consolas_bold_35_usascii.inl
stetre/moonfonts
5c8010c02ea62edcf42902e09478b0cd14af56ea
[ "MIT" ]
null
null
null
// Font generated by stb_font_inl_generator.c (4/1 bpp) // // Following instructions show how to use the only included font, whatever it is, in // a generic way so you can replace it with any other font by changing the include. // To use multiple fonts, replace STB_SOMEFONT_* below with STB_FONT_consolas_bold_35_usascii_*, // and separately install each font. Note that the CREATE function call has a // totally different name; it's just 'stb_font_consolas_bold_35_usascii'. // /* // Example usage: static stb_fontchar fontdata[STB_SOMEFONT_NUM_CHARS]; static void init(void) { // optionally replace both STB_SOMEFONT_BITMAP_HEIGHT with STB_SOMEFONT_BITMAP_HEIGHT_POW2 static unsigned char fontpixels[STB_SOMEFONT_BITMAP_HEIGHT][STB_SOMEFONT_BITMAP_WIDTH]; STB_SOMEFONT_CREATE(fontdata, fontpixels, STB_SOMEFONT_BITMAP_HEIGHT); ... create texture ... // for best results rendering 1:1 pixels texels, use nearest-neighbor sampling // if allowed to scale up, use bilerp } // This function positions characters on integer coordinates, and assumes 1:1 texels to pixels // Appropriate if nearest-neighbor sampling is used static void draw_string_integer(int x, int y, char *str) // draw with top-left point x,y { ... use texture ... ... turn on alpha blending and gamma-correct alpha blending ... glBegin(GL_QUADS); while (*str) { int char_codepoint = *str++; stb_fontchar *cd = &fontdata[char_codepoint - STB_SOMEFONT_FIRST_CHAR]; glTexCoord2f(cd->s0, cd->t0); glVertex2i(x + cd->x0, y + cd->y0); glTexCoord2f(cd->s1, cd->t0); glVertex2i(x + cd->x1, y + cd->y0); glTexCoord2f(cd->s1, cd->t1); glVertex2i(x + cd->x1, y + cd->y1); glTexCoord2f(cd->s0, cd->t1); glVertex2i(x + cd->x0, y + cd->y1); // if bilerping, in D3D9 you'll need a half-pixel offset here for 1:1 to behave correct x += cd->advance_int; } glEnd(); } // This function positions characters on float coordinates, and doesn't require 1:1 texels to pixels // Appropriate if bilinear filtering is used static void draw_string_float(float x, float y, char *str) // draw with top-left point x,y { ... use texture ... ... turn on alpha blending and gamma-correct alpha blending ... glBegin(GL_QUADS); while (*str) { int char_codepoint = *str++; stb_fontchar *cd = &fontdata[char_codepoint - STB_SOMEFONT_FIRST_CHAR]; glTexCoord2f(cd->s0f, cd->t0f); glVertex2f(x + cd->x0f, y + cd->y0f); glTexCoord2f(cd->s1f, cd->t0f); glVertex2f(x + cd->x1f, y + cd->y0f); glTexCoord2f(cd->s1f, cd->t1f); glVertex2f(x + cd->x1f, y + cd->y1f); glTexCoord2f(cd->s0f, cd->t1f); glVertex2f(x + cd->x0f, y + cd->y1f); // if bilerping, in D3D9 you'll need a half-pixel offset here for 1:1 to behave correct x += cd->advance; } glEnd(); } */ #ifndef STB_FONTCHAR__TYPEDEF #define STB_FONTCHAR__TYPEDEF typedef struct { // coordinates if using integer positioning float s0,t0,s1,t1; signed short x0,y0,x1,y1; int advance_int; // coordinates if using floating positioning float s0f,t0f,s1f,t1f; float x0f,y0f,x1f,y1f; float advance; } stb_fontchar; #endif #define STB_FONT_consolas_bold_35_usascii_BITMAP_WIDTH 256 #define STB_FONT_consolas_bold_35_usascii_BITMAP_HEIGHT 160 #define STB_FONT_consolas_bold_35_usascii_BITMAP_HEIGHT_POW2 256 #define STB_FONT_consolas_bold_35_usascii_FIRST_CHAR 32 #define STB_FONT_consolas_bold_35_usascii_NUM_CHARS 95 #define STB_FONT_consolas_bold_35_usascii_LINE_SPACING 23 static unsigned int stb__consolas_bold_35_usascii_pixels[]={ 0x0309fff3,0x00022000,0x300037ae,0x30000375,0x3ee7fdb9,0x3fffffff, 0xfffffffb,0x337be63f,0x3ba00002,0x99730005,0x10000035,0x0cccc333, 0x55553000,0x0aaaa600,0x884ccc00,0x88000999,0xfff99999,0x00017e44, 0xc8003ba2,0xb800ffff,0x05ffffff,0xfffff900,0x3ffffee7,0xfffb3fff, 0x263fffff,0x00dfffff,0x037fc400,0x3ffffee0,0x00001fff,0x7ecffff1, 0xf30002ff,0xfd005fff,0xf30009ff,0x3fff2dff,0xfffc8003,0x324fff9e, 0x10002fff,0x2001dffd,0x202fffff,0xffffffe8,0x7e4005ff,0xf73fffff, 0x7fffffff,0x3ffffff6,0xffff31ff,0xa8000dff,0xfb1005ff,0xffffffff, 0xf700007f,0x7ffcc7ff,0x3ffa0005,0x7ffcc05f,0xff98000f,0x07fff96f, 0x3dfff900,0x7fe49fff,0x744002ff,0x3a006fff,0xf102ffff,0xfd99dfff, 0x3e600dff,0x309adfff,0xfff95555,0x2abfff67,0x32a60aaa,0x0003ffff, 0x2009ff91,0xfffffffe,0x003fffff,0x207fffc0,0x0001fffe,0x401ffff7, 0x0005fffc,0x3f2dfff3,0xfb8003ff,0x4fff9dff,0x00ffffe4,0x01dfffb0, 0x037ffdc0,0xf707fffb,0xff9005ff,0x7fd4009f,0x00fffb3f,0x006fffa8, 0x3fffff6a,0xff504eff,0xf7315bff,0x4000ffff,0xfa84fffa,0xf10004ff, 0x7fc07fff,0xf30002ff,0x3fff2dff,0xfffb8003,0xd84fff9d,0xf7006fff, 0x30001dff,0x7ffdc079,0x017ff602,0x8003fff6,0xffb3fffa,0xfffd000f, 0xffffd300,0x0fffffff,0x5417fffa,0x0003ffff,0x3e03fffd,0x90000fff, 0x3ea0dfff,0x260007ff,0xfff96fff,0xfff50007,0x209fff39,0x4c04fffe, 0x0001ffff,0x09fff100,0x400fff98,0x54007ffe,0xfffb3fff,0x1fffb000, 0x7ffffc40,0x7fffffff,0x407fffb8,0x8006fffd,0x3206fff9,0x30003fff, 0xfb01ffff,0x4c0009ff,0xfff96fff,0xfff50007,0x209fff39,0x201ffffa, 0x5104fffe,0x55555555,0xfff70555,0x07fff001,0x4006fff8,0xffb3fffa, 0xfff9000f,0x7ffff401,0xdbafffbd,0x04fffd86,0x007fffd4,0x80bfff20, 0x0006fff8,0xf10ffffa,0x31003fff,0xfff99995,0x98ffff2d,0xf980abcb, 0x4fff9bff,0x417fff60,0x2a06fffa,0xffffffff,0x7fc0ffff,0x9110c43f, 0xfff809ff,0x7ffd4006,0x000fffb3,0x2201fff9,0xff33ffff,0x5fffd00b, 0x1ffff880,0x1fffe200,0x00bfff60,0x237ffdc0,0xa806fffa,0xffffffff, 0x7fff96ff,0xdfffffd1,0x9bfff981,0x3e204fff,0xffd80fff,0x3ffea02f, 0xffffffff,0x43ffea0f,0xcfefffe9,0x7fc05ffb,0x7fd4006f,0x00fffb3f, 0x201fff90,0xf50ffffa,0xffff009f,0x5ffff003,0x1fffdc00,0x02fffcc0, 0x1ffff880,0x880ffff6,0xfffffffd,0xff96ffff,0xfffffd9f,0x55443fff, 0x04fff98a,0x221fffec,0x75407fff,0xfeeeeeee,0x3ff20fff,0xffffff35, 0x80dff57f,0x54006fff,0xfffb3fff,0x3fff7000,0x4bfffe60,0x7c403ffb, 0xff800fff,0x3fa003ff,0xffd000ff,0x3f60001f,0xffff14ff,0x7fffec01, 0xffffdcdf,0xffffff96,0xbfffffdf,0x04fff980,0x2e37ffd4,0x40004fff, 0x3a0ffff8,0xffffd3ff,0xfff57fff,0x02fffc40,0x6cfffea0,0xfb8007ff, 0xfff104ff,0x05ffb9ff,0x00ffff98,0x004fffe8,0x400bfff5,0x0004fffb, 0x3eeffff3,0x3fea04ff,0xfff984ff,0xbfffff96,0x07fffec3,0x809fff30, 0x360ffff8,0x40002fff,0xf10ffff8,0x7fff53ff,0xff35fff1,0x1fffe40f, 0x4fffea00,0x98007ffd,0xfb00efff,0x3fffffff,0x0ffffa80,0x03fffe80, 0x003fffb0,0x000ffff8,0xfd5fffd0,0x7ffc03ff,0xdfff305f,0x41bffff2, 0x2603ffff,0xfd804fff,0x3fffa1ff,0x7fc40000,0x1fff50ff,0x3fe6dff9, 0x227ff99f,0x0ffffdba,0x9fffd400,0xb0007ffd,0x437bffff,0xffffffe8, 0xff301cff,0xfff003ff,0xfff3005f,0xfff9000d,0x3fee0007,0x206fffef, 0x301ffff9,0x3ff2dfff,0xfffb00ef,0x27ffcc0b,0xf17ffe40,0x10000fff, 0x3ee1ffff,0x2a9ffd6f,0x7ff98fff,0x3bffffea,0xfffa8001,0x000fffb3, 0x27ffff54,0x3fffff62,0x440dffff,0xf801ffff,0xfc801fff,0xf88002ff, 0xf10006ff,0x07ffffff,0x303fffd4,0x3ff2dfff,0x3ffee03f,0x13ffe606, 0x44ffff20,0x80006fff,0xf90ffff8,0x54fffebf,0x4dff57ff,0x00dffffa, 0x27fff500,0x20007ffd,0x04ffffda,0xffffffb5,0xfff81dff,0x7ffc403f, 0x7ffc400f,0x3ff60007,0xffb0001f,0x5c01ffff,0x3e606fff,0x7fff96ff, 0x03fffdc0,0x7009fff3,0x3fe69fff,0xf880005f,0x9ff90fff,0x3ee5fff1, 0x54dff57f,0x04fffffe,0xb3fffa80,0x2e000fff,0x03efffff,0x7fffffdc, 0x7fff46ff,0x3fffdc05,0x027ffdc0,0x0bfff500,0x3fffea00,0x7ffe404f, 0x5bffe605,0x2a03fffc,0x3e606fff,0xffb804ff,0x0dfff34f,0xffff1000, 0x3e33ff61,0x2dff92ff,0xeb885ffb,0x54002fff,0xfffb3fff,0xffff1000, 0x67fe4003,0x21fffffc,0x200ffffb,0xe803fffe,0x40000fff,0x0000fffe, 0x801ffffd,0x2605fffc,0xfff96fff,0x2fffdc07,0x009fff30,0x3e27fff7, 0x880007ff,0xffb0ffff,0x323fff17,0x09ff95ff,0x0027ffdc,0x7ecfffea, 0xffa8007f,0x7fec003f,0x47ffff51,0x80effff8,0x400ffffd,0x0005fffa, 0x004fffb8,0x00bffff0,0x540dfff7,0xfff96fff,0x27ffec07,0x009fff30, 0x7fc5fff9,0xf880007f,0x7ffb0fff,0x3fa5fff1,0x405ffd5f,0x4005fff8, 0xffb3fffa,0xfff7000f,0x0ffe8003,0xfb0ffffe,0xd97bdfff,0xb009ffff, 0x00003fff,0x000ffff1,0x003ffff7,0x101ffff5,0x3f2dfffd,0xfff103ff, 0x7ffcc05f,0x1fffd804,0x0007fffe,0x21ffff10,0x7fff4ffd,0xff3bfff7, 0x0dfff00f,0xb3fffa80,0xf9000fff,0xff8001ff,0x217fffc7,0xffffffe8, 0x805fffff,0x0006fff8,0x00bfff20,0x04ffffa8,0x07ffff10,0x32dffffd, 0xffb03fff,0x7fcc01ff,0x7ffc404f,0x0ffff60f,0xffff1000,0x7f57ff21, 0xffffffff,0xfff805ff,0x7ffd4006,0x000fffb3,0x2a01fff9,0x45bfe21b, 0x880ffffd,0xfffffffe,0xff9005ff,0x4c00007f,0x2aa06fff,0x06ffffda, 0x5ffffec0,0xffffffb9,0x41bfff96,0x03ffffd9,0x2027ffcc,0x7dc5fffa, 0x440006ff,0xff70ffff,0x3bfffeed,0x00effffd,0x4006fff8,0xffb3fffa, 0xfff9000f,0x3bffee01,0xfffdeffd,0x7f5404ff,0x002dffff,0x001ffff1, 0x1fffd800,0xfffffff0,0xff98001f,0xffffffff,0xfff96ffe,0xffffffff, 0xfff300bf,0x2fffd809,0x00ffffc4,0x1ffff100,0xffc9ffea,0x0dffe88e, 0x00dfff00,0xfb3fffa8,0xff9000ff,0x3ffee01f,0xffffffff,0x3ee005ff, 0x7dc004ff,0x800004ff,0xff05fffa,0x001bffff,0x3ffffee0,0x6ffd9fff, 0xfffffff9,0x0019ffff,0x4409fff3,0xffb06fff,0x7c40009f,0x3ffe67ff, 0x00020221,0x5001bffe,0x3ff67fff,0xfffc8007,0xfffff700,0x7fffffff, 0x6fff9800,0x3fffa010,0xfd000000,0xdfff01ff,0xd500005b,0x361bffff, 0xffb736ff,0x03bfffff,0x027ffcc0,0x2a07fffb,0x0001ffff,0xff8ffff5, 0xd000004f,0xfa800fff,0x0fffb3ff,0x01fffb00,0x3ffb2ea2,0x0002cdff, 0x13dffff1,0xfff30d93,0x5c00000b,0x09883fff,0x35100000,0x33310001, 0x3fe60001,0xdfff504f,0x37ffec01,0x5fffd800,0x0007ffe4,0x07ffec00, 0x27fff500,0xe8007ffd,0x7f4007ff,0xf900000f,0xffffffff,0x02fffd89, 0x3fe20000,0x0000007f,0x00000000,0x213ffe60,0x401ffff8,0x183ffff8, 0x13fffe20,0x300dfff3,0x5fffb800,0x4fffea00,0x5c007ffd,0x7c006fff, 0x7400007f,0xffffffff,0x0dfff10f,0xff900000,0x4ccccc5f,0x99999999, 0x10999999,0x11111111,0x00000011,0x444fff98,0x5004fffe,0xef85ffff, 0xffeb99ab,0xfffe80ff,0x0375c41d,0x3bfffe20,0x555531ac,0x3f67fff9, 0x0aaaaaff,0xffffb751,0x37fc4005,0x3ee20000,0x20dfffff,0x0002ccc9, 0x3ccc8800,0x3ffffffe,0xffffffff,0xff91ffff,0xdfffffff,0x98000000, 0x7ff44fff,0x7fe4006f,0x3fffe2ff,0x2fffffff,0xfffffd10,0x00dffffd, 0xffffff70,0x3ffffee7,0xfffb3fff,0x263fffff,0x06ffffff,0x002ffd40, 0x9aa98800,0x00000000,0xfffff800,0xffffffff,0x91ffffff,0xffffffff, 0x000000df,0x364fff98,0x8000efff,0xff1ffffd,0xffffffff,0xfffe8807, 0x05ffffff,0xfffff700,0x3ffffee7,0xfffb3fff,0x263fffff,0x00cfffff, 0x0004cc40,0x00000000,0x3e000000,0xffffffff,0xffffffff,0xffff91ff, 0x00dfffff,0xff980000,0x03bfea4f,0x24ffd800,0xefffffdb,0x3b2e000c, 0x001cefff,0x976e5440,0xeeeeeeea,0xddddd92e,0x37a61ddd,0x000001bc, 0x00000000,0x00000000,0x77500000,0x77777777,0x98000000,0x07544fff, 0x2026c000,0x11000008,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x013ffe60,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x7fcc0000,0x0000004f, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x20000000,0x00000009, 0x00d54400,0x54c01998,0xaaaabccc,0x0cccc42a,0x200eed40,0x80009998, 0x99999999,0x26600001,0x5cc01aaa,0x00999882,0x65d4c000,0x533a89ac, 0xabdca855,0x016e6000,0xaccb9880,0xefff9801,0x64c000bc,0x4003defe, 0x01effffb,0x6c41bff2,0xffffffff,0x3f60ffff,0x7fd407ff,0x3ff200ff, 0xfff8003f,0x01ffffff,0x7fff5400,0xff907fff,0x5fffb8df,0xfff50000, 0xdfffffff,0x7f4dfff2,0x400effff,0x0007fff9,0xfffffff7,0x7ffcc03f, 0x800bffff,0xfffffffc,0xfffb801e,0xf980ffff,0xfff880ff,0xffffffff, 0x3ff60fff,0x7ffec07f,0x3fff203f,0xffff8003,0x001fffff,0x3fffff60, 0xff987fff,0x3fee3fff,0x6c40005f,0xffffffff,0xfff96fff,0xfffffff5, 0x7fd403ff,0x7ec4007f,0xffffffff,0xffff303f,0x403fffff,0xfffffffc, 0x7fc00eff,0x83ffeabf,0xffd03ffe,0xfff935bf,0x7ec199bf,0x7fec07ff, 0x3ff203ff,0xfff8003f,0x01ffffff,0xfffff700,0xf50fffdf,0x7dc9ffff, 0x6c0005ff,0xdcdfffff,0xff96ffff,0xffdfffff,0x7d40bfff,0x7f4007ff, 0xffffffff,0xee883fff,0xefffffff,0xbffff980,0x04ffffb9,0xffa9bfe6, 0x9837fdc5,0xff986fff,0xffff906f,0x0ffff980,0x00ffff20,0x0ffffc00, 0x7fffc400,0x7cc0c40d,0x3ee3ffff,0x2a0005ff,0xf984ffff,0xffff96ff, 0x7ffec3bf,0xffff500f,0x7fffdc00,0xfffc98ad,0xffd7007f,0xfff70bff, 0x05fffa87,0xff993fea,0x407ffe66,0xfd02fffa,0xfff901ff,0x0177300d, 0x003fffc8,0x03ffff00,0x1ffff300,0x6fffd800,0x002fffdc,0x20bfffd0, 0xff96fff9,0x3ffe0dff,0xf955553f,0x55555fff,0x7fffc435,0x7ffff504, 0x3fffa200,0x07ffec0f,0xf5037ffc,0xd2ffd4bf,0x7fdc07ff,0x3fff902f, 0x00dfff90,0x3fffc800,0xffff0000,0xfff50003,0x0f2a000b,0x0017ffee, 0x80ffffcc,0xff96fff9,0x3ff601df,0xffffff5f,0xffffffff,0x3fffdcbf, 0x01bfff60,0x41ffffa8,0x7cc1fffd,0x3fe605ff,0x2e9ff90f,0x7fd406ff, 0x0fffd04f,0x551bfff2,0x15555555,0x51fffe40,0x7c0059b9,0xc8001fff, 0x00004fff,0x105fffb8,0x7d455555,0x3fe607ff,0x07fff96f,0xffb7ffdc, 0xffffffff,0x365fffff,0x7d404fff,0xf1000fff,0xffb87fff,0x1fffec4f, 0x3fbfffa0,0x1fff88ff,0x0ffffc40,0x5c1bffee,0x7ffc5fff,0x01ffffff, 0x3a6bfff2,0x00efffff,0x001ffff8,0x004fffc8,0x5fffb800,0x1ffffe88, 0x981bffee,0xfff96fff,0xbfffdc07,0xfffeeeed,0x4eeeeeef,0x100bfffa, 0x2003ffff,0x4c1ffff9,0xfd89ffff,0xff9806ff,0xffb3ffff,0x3fff2009, 0xffffecef,0x8bfff701,0xffffffff,0x3fff201f,0xfffffffc,0xffff806f, 0xfffc8001,0xfb800004,0xfffd85ff,0x2fffe42f,0x32dfff30,0x3ea03fff, 0xfff506ff,0x3fffe00f,0x2ffff801,0x1ffffb00,0xffdfffb0,0x22001dff, 0xff71deed,0x7ffd400d,0x3fffffff,0xb17ffee0,0xffffdddd,0x7fffe403, 0xffffffff,0x7fffc02f,0x77775c01,0xeeefffff,0x70002eee,0xffc8bfff, 0xfffc83ff,0x5bffe605,0x2e03fffc,0xff505fff,0xfff100ff,0xffff001f, 0xfd755307,0x3e209fff,0x0dffffff,0xfff88000,0xdfff1001,0x019fffff, 0x805fffa8,0x3201ffff,0x31dfffff,0xf809fffd,0x7e401fff,0xffffffff, 0x03ffffff,0x3fee02a2,0x3fffea5f,0x0dfff704,0xfcb7ffd4,0x3ff603ff, 0xffff504f,0x1ffff300,0x09fffd00,0xfffffffb,0x7ffec01d,0x200002ff, 0x32004ffd,0x000627ff,0xf009fff5,0x7e403fff,0xffc86fff,0x7fffc05f, 0x7fffe401,0xffffffff,0xff703fff,0x5fffb87f,0x409ffff3,0x880ffffa, 0xff96fffe,0x3ffe207f,0xffff502f,0x1ffff300,0x07fffd00,0xbffffffb, 0x3fffa201,0x66642fff,0x1bfea003,0x00fffd00,0x04fffa80,0x201ffff8, 0xa80efffc,0x7fc06fff,0x554c01ff,0xadfffdaa,0x880aaaaa,0x2e2fffff, 0xfff8dfff,0x7ffc405f,0xffffe83f,0x207fff96,0x500ffffd,0xf300ffff, 0xff003fff,0xfff905ff,0xffd8037d,0x10ffffff,0x2200bfff,0x6c001fff, 0x9aabefff,0xfffa8019,0x1ffff804,0x40ffff20,0x7c06fff9,0xc8001fff, 0x4c004fff,0x2e5fffff,0xfffedfff,0xffffb006,0xfffff737,0x37fff2df, 0x3ffff660,0x1fffea03,0x07fffe20,0x207fffe0,0xb801fffc,0xffe8efff, 0x4fff88ef,0x269ffb00,0xf703effe,0xffffffff,0x3e605dff,0xfff803ff, 0x3fff201f,0x0dfff303,0x001ffff8,0x004fffc8,0x3fffffc4,0xfffffff7, 0x3fe6001f,0xffffffff,0xfff96fff,0xffffffff,0xfffa80bf,0x7ffff007, 0x0ffff880,0x801fffb8,0xff11ffff,0x7fff5bff,0x51fff500,0x09ffffff, 0x3ffffff2,0x85ffffff,0xf803fff9,0x3f201fff,0xfff303ff,0x1ffff80d, 0x4fffc800,0xffffa800,0x3fbffee7,0x2e005fff,0xffffffff,0xff96fffa, 0xffffffff,0xffa8019f,0xfffd007f,0x7fffb80b,0x801fff70,0x7d46fff9, 0x2fffefff,0x457ffc40,0xfffddfff,0x77fff4c1,0xfffffeee,0x1fffcc3f, 0x00ffffc0,0x2607fff9,0x7fc06fff,0xfc8001ff,0xf90004ff,0x7ffdcdff, 0x03ffffad,0x3ffffaa0,0x96fff88d,0xffffffff,0x3e6003bf,0xfb800fff, 0x3fa00fff,0x500004ff,0xff70bfff,0xb00dffff,0x97feabff,0x3fa23ffd, 0xffd302ff,0xff0000df,0x7fe403ff,0xdfff303f,0x01ffff80,0x04fffc80, 0x49fff500,0xff95fffb,0xa88005ff,0x5bffe609,0x999bfffc,0xfff88000, 0xfff8802f,0xfffd80ef,0xf500000f,0x3ff60dff,0x7d403fff,0x47ff70ff, 0x3fee4ffb,0x7ffd405f,0xfff80007,0x3fff201f,0x0dfff303,0x001ffff8, 0x004fffc8,0x5c5fff90,0x3ffa5fff,0x980000ff,0xfff96fff,0x3fe00007, 0x0660aeff,0x79dffff9,0x07ffffd9,0x2006ff54,0xd01ffff8,0x4403ffff, 0x3ff22fff,0xfc93fea3,0x7fdc05ff,0x06f6445f,0x00ffffc0,0x2607fff9, 0x7fc06fff,0xfc8001ff,0x5c4004ff,0x7fdc4fff,0x3fffe65f,0x7cc0000e, 0x7fff96ff,0x3ff60000,0x5fffffff,0x7fffff44,0x0effffff,0x0dffff10, 0x15fffff0,0x3fffff26,0x717ff206,0x1ffe4bff,0x207ffff7,0x6c3ffffa, 0x26626fff,0xaffff999,0x3ff21999,0xdfff303f,0x3e666662,0x1999afff, 0x04fffc80,0xffffee88,0x2fffdc0e,0x017fffee,0x2dfff300,0x0003fffc, 0xffffff10,0xfb10bfff,0xffffffff,0xffffa809,0x7ffd400f,0xffffffff, 0xf984ffff,0x7ffcc0ff,0x220fffbc,0xeeffffff,0x84fffffe,0xf71fffff, 0xffffffff,0x323fffff,0xff303fff,0x3fffeedf,0xffffffff,0x7fe401ff, 0xfff8804f,0xfff703ff,0x7ffffb0b,0x7ffcc000,0x007fff96,0x7ffe4400, 0x2e04ffff,0x2efffffe,0x7ffff980,0xfffff900,0xffbfffff,0x2ffe87ff, 0xffffffb0,0xfffff309,0x9fffffff,0x43ffffa0,0xfffffffb,0x1fffffff, 0x2607fff9,0xfff76fff,0xffffffff,0xfc803fff,0xdf8804ff,0x3fee00bc, 0xfffe885f,0xff30002f,0x0ffff2df,0x54cc0000,0x0d4c001a,0x17ffe400, 0xffffb300,0x3ff219ff,0x0bff92ff,0x03ffffc8,0x3ffff6a2,0x2a00beff, 0x3fee3fff,0xffffffff,0xff91ffff,0x3ffe607f,0xffffff76,0xffffffff, 0x4fffc803,0xffb80000,0xffff305f,0xdd30003f,0x0bbbaebd,0x00000000, 0x054c0000,0x01553000,0x03300000,0x20006200,0x000000a8,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x10000000, 0x35999975,0x3732a601,0x55400abc,0xaaaaaaaa,0x310002aa,0x95300555, 0x00015799,0x2b332ea2,0x00d554c1,0xaa86aaa2,0xaaaaaaaa,0x953000aa, 0x4c003799,0x4c01accb,0x53002aaa,0x55554555,0x55551002,0x002aaa21, 0x5551aaa8,0x55555555,0xffc88155,0x5fffffff,0xfffffff8,0xff00cfff, 0xffffffff,0x32200fff,0x07ffffff,0x3fffff66,0x7000cfff,0xffffffff, 0x3ffee7ff,0x2fffdc05,0xfffffffd,0x4c07ffff,0xfffffffe,0x3fee00ff, 0x00efffff,0x003ffff5,0x7ec9fffd,0xff7007ff,0x0fffd4ff,0x3a9ffd00, 0xffffffff,0x3ea2ffff,0xffffffff,0xffff85ff,0x6fffffff,0xfffffff0, 0x80ffffff,0xffffffd8,0xfff307ff,0xffffffff,0xfffe880b,0xffffffff, 0x80bfff74,0x3fa5fffb,0xffffffff,0xfff703ff,0xffffffff,0x3ffff201, 0x02ffffff,0xa80bfffd,0x3ee0ffff,0xfd801fff,0x3ffea5ff,0x53ffe002, 0xfffffffe,0xf12fffff,0xffffffff,0xfff0bfff,0xfffffddf,0xfffff09f, 0xffffffff,0x7ffff440,0x887fffff,0xdcdfffff,0x503fffff,0xffffffff, 0x2e9fffff,0x7dc05fff,0x3fffa5ff,0xffffffff,0xfffffd83,0x0fffffff, 0xdfffffd8,0x81ffffff,0x200ffffa,0x7c44fffe,0xff804fff,0x3ffe62ff, 0x4fffe002,0xfffffffe,0xf92fffff,0x73019fff,0xa8815909,0xff87ffff, 0xccccccff,0xfff104cc,0x33357dff,0x0dfff703,0x741bfff2,0x89beffff, 0xf74fda98,0xffb80bff,0x2666625f,0x3fffe999,0x67ffffd4,0x0fdb988a, 0x21ffffcc,0xd05ffffa,0x3ea09fff,0xffe80fff,0x7ffd406f,0x0bffe60f, 0xfd3fff80,0x333337ff,0x3ffa1333,0x7000004f,0xff81ffff,0x3f20007f, 0x64002fff,0xff103fff,0xffff70ff,0x7fdc200b,0x7ffdc05f,0x3fffa005, 0x17ffff43,0x3fff6020,0x1ffff704,0x01ffff50,0x2e09fffd,0x3200ffff, 0x7fc45fff,0x3ffe003f,0x005fffd3,0x001ffffc,0xffff8800,0x003fffc0, 0x02ffff88,0x02fffd80,0xf88dfff1,0xb8005fff,0x7dc05fff,0x3fa005ff, 0x3ffee3ff,0xff98002f,0x3ff600ff,0x9fffd04f,0x00ffffa8,0x405ffff3, 0x7c43fffe,0xff1003ff,0x0bfffa5f,0x0effff80,0xff980000,0x07fff85f, 0x0bfff700,0x3bfff200,0x44fffb80,0x001ffffb,0x405fffb8,0x2005fffb, 0x3fa3fffe,0xf70006ff,0x7f4c0bff,0xfff506ff,0x27fff41f,0x413fffe0, 0xf80ffff8,0x066543ff,0x3fa5fff1,0x3f6002ff,0x0002efff,0x41fffec0, 0xb0007fff,0x20007fff,0x21effff9,0x640ffffa,0x70005fff,0xfb80bfff, 0x3fa005ff,0x3fffe3ff,0xfff90003,0x3fffee05,0x3fffa07f,0x01ffff53, 0x707fffc8,0x3fe0dfff,0x117ff43f,0x3ffa3fff,0x3fee002f,0x00bfffff, 0x3ae66660,0xff80dfff,0x1cceeeff,0x557fffc0,0x00bceeec,0x37fffff2, 0xe82ffffd,0x70004fff,0xfb80bfff,0x3fa005ff,0xffff33ff,0x3ff60003, 0x7ffec42f,0x3ea07fff,0x7fffb7ff,0x3ffff500,0x209fffb0,0x3fe64fff, 0x47ffe25f,0x4002fffe,0xfffffffd,0xfff801df,0x203fffff,0xffffffff, 0xff883eff,0xffffffff,0x3f203fff,0xffffffff,0x87ffff02,0xfffffff9, 0x80bfff74,0x2005fffb,0xff53fffe,0x3a0001ff,0x3fea1fff,0x0fffffff, 0x3f3fffa0,0xff000fff,0xffff07ff,0xb93ffa03,0x3fe67fff,0x9bfffd0f, 0x07999999,0xfffffff9,0x7fc01bff,0x2cffffff,0xfffffff0,0x987fffff, 0xffffffff,0x03ffffff,0x3fffffee,0xfff880df,0x7fffcc2f,0xfff74fff, 0x5fffb80b,0x4ffffa00,0x0007fffb,0x7e43fffe,0xffe8efff,0x3ffea01f, 0x2003ffff,0x7cc5fffd,0x3ffa07ff,0x47ffffa4,0xffd0fff9,0xffffffff, 0x3ff660df,0x0effffff,0xfffffff0,0x9990bfff,0xffffb999,0x7ffcc5ff, 0xfeccdfff,0xfa80ffff,0xffffffff,0x7fffc41f,0x7ffffcc2,0xbfff74ff, 0x05fffb80,0x5cffffa0,0x0000ffff,0xffd5ffff,0x7fffc9ff,0x7ffff401, 0x3ea000ff,0x3ff20fff,0x53ff604f,0x34fffff8,0x7fff4fff,0xffffffff, 0x7ff5c406,0x9804ffff,0x4ffffeb9,0x3ffee200,0x3fffe64f,0x7ffff703, 0xbdffffa8,0x41ffffff,0x6443ffff,0x74fffdcc,0xfb80bfff,0x3fa005ff, 0xffff53ff,0x3ffa0001,0x42ffffff,0x5c00ffff,0x003fffff,0xd17fffc4, 0x7ec05fff,0xffdff75f,0xfe9ffead,0xeeeeeeff,0x3aa005ee,0x000fffff, 0x007fffec,0x99bfff20,0x3600ffff,0x3fe65fff,0x3ff623ff,0x7fff46ff, 0xa7ffdc03,0x5c05fffb,0x3a005fff,0xfff33fff,0x3f60003f,0x40dfffff, 0xd007fff8,0x2000ffff,0xff14fffe,0x5ffd80ff,0x3fff5ffb,0x7ff4fff5, 0xd800002f,0x4001ffff,0x001ffff8,0x887fffd4,0x2e01ffff,0x3ff66fff, 0xffff904f,0x02fffec3,0x7dd3ffee,0x7fdc05ff,0x3ffa004f,0x7ffff13f, 0x3fff2000,0xfff303ff,0x3fff200d,0xfff70005,0x017ffead,0xdff1dff9, 0x3feafffa,0x00bfffa6,0x3ffea000,0xfff8002f,0x7fd4002f,0x17fffc7f, 0x7cdfff70,0x3fe00fff,0x3fff22ff,0x3ffee00f,0x80dfff54,0x2003fffc, 0x3fe2ffff,0xf90007ff,0x7e403fff,0xff9005ff,0x3e6000bf,0xfffd9fff, 0x577fe403,0x7dff94ff,0x7fff4dff,0xf9800002,0x4c000fff,0x4000ffff, 0x7f46fffc,0x3ff205ff,0x0ffff34f,0x262fffd8,0x2e04ffff,0xfff34fff, 0x2fffd80f,0x3ffff100,0x01ffffec,0x0ffffcc0,0x005ffff0,0x0017fff2, 0xffbfffe8,0x7fdc00ff,0xff31ffce,0x7f4bff9f,0x153002ff,0x0ffffb00, 0x7fffe880,0x7fffd400,0x0ffffdc4,0x897fffcc,0x3e03ffff,0x7fe41fff, 0xfff705ff,0x0ffffe29,0x707fffcc,0x07fffe40,0x09fffff1,0x3ff605c4, 0xdfff906f,0x2fffe400,0xdfff9000,0xf700dfff,0xff8fffff,0x3fa5ffef, 0xff5002ff,0xf955579d,0x5d49ffff,0xfca9999a,0x3263ffff,0xfda9999a, 0xff80efff,0xfb99bfff,0x3fa0efff,0x3661bfff,0xff887fff,0xbabdefff, 0x3f64fffe,0xb989cfff,0x7fc4ffff,0xfffd999c,0xffffc85f,0xfecbcdff, 0x7fffcc0f,0xfffc98ad,0x3ff2002f,0x3e60005f,0x03ffffff,0x4fffffa8, 0x2fffffe4,0x2005fffd,0xfffffffa,0x46ffffff,0xfffffffc,0x545fffff, 0xffffffff,0xf701ffff,0xffffffff,0xffa83fff,0xffffffff,0xff702fff, 0xffffffff,0x7fc49fff,0xffffffff,0x7ffc0eff,0xffffffff,0xffffe880, 0xffffffff,0xfffffd80,0x05ffffff,0x02fffe40,0x3ffffe00,0xffa801ff, 0x7fd42fff,0x3ffa4fff,0xfff5002f,0xffffffff,0xfffc81df,0xffffffff, 0xfffffa84,0x01dfffff,0x7fffffdc,0xf902ffff,0xffffffff,0xfe9807ff, 0xffffffff,0x7ffd44ff,0xefffffff,0xffffff81,0x5c02ffff,0xffffffff, 0xff900fff,0x7fffffff,0xbfff9000,0xfffd8000,0xff5007ff,0x3ffe0fff, 0x3fffa4ff,0xffdb3002,0x3bffffff,0x3fffff20,0x500befff,0xffffffff, 0x7ecc003b,0x00cfffff,0x7ffffecc,0x32000cff,0xfffffffe,0xffc880ad, 0x203fffff,0xffffffda,0xfd93000c,0x059fffff,0xfffffea8,0xff90002d, 0xfa8000bf,0x3004ffff,0x360bffff,0x3fa3ffff,0x988002ff,0x30009aa9, 0x00135533,0x001aa998,0x00135100,0x0026a660,0x066aa200,0x01353100, 0x00099980,0x00099880,0x00001530,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x88355300,0xaaa882aa,0x5554c01a,0x5555540a,0xaaaaaaaa, 0x555530aa,0x55555555,0x2aa25555,0x555402aa,0x80d55542,0x260aaaa9, 0x54001aaa,0x2aa01aaa,0x2aaaa2aa,0x00019aaa,0x01599751,0x20155544, 0x5531aaa9,0x00135555,0x55555555,0x26355555,0x09aaaaaa,0x4ffd8000, 0xff83ffd4,0x7ff406ff,0xffffe86f,0xffffffff,0xffff92ff,0xffffffff, 0x3feadfff,0x3fe00fff,0x3fffe25f,0x5ffffb06,0x0027ffe4,0x540ffff6, 0x3f64ffff,0xffffffff,0xffea802e,0x80cfffff,0x6406fffa,0xfffb4fff, 0x7dffffff,0x3fffffa0,0x4fffffff,0xfffffff7,0x00019dff,0xffb87ffd, 0x7ffff506,0x0bfffee0,0x3ffffffa,0xffffffff,0xffffff92,0xffffffff, 0x3fffeadf,0x97ffe04f,0x80fffff9,0x323fffff,0x6c004fff,0xff883fff, 0x7ffec6ff,0xffffffff,0xfffc880e,0xefffffff,0x037ffd40,0x7ed3fff2, 0xffffffff,0x7ff42fff,0xffffffff,0xffff74ff,0xffffffff,0x3ffe8007, 0xfd02ffe4,0x3ffa0fff,0xffffd06f,0xffffffff,0x3fff25ff,0xffffffff, 0xff56ffff,0x3e01ffff,0x3ffe65ff,0x7ffd43ff,0x3fff23ff,0x7ffec004, 0x1ffffd83,0x7fffffec,0x86ffffff,0xfffffffc,0x544fffff,0x7e406fff, 0xffffb4ff,0xffffffff,0x7ffff43f,0xffffffff,0xffffff74,0xdfffffff, 0x217ffc00,0x3ea04ffd,0x7fdc3fff,0x555501ff,0xff755555,0x26621fff, 0xefffc999,0xf5099999,0x207fffff,0x3fea5fff,0x7fe45fff,0x3ff23fff, 0x7fec004f,0x7fffd43f,0x9bfffd83,0xfffffdb9,0x567ff442,0xfffffa88, 0x01bffea0,0x3f69fff9,0xea999cff,0xfd0effff,0x333337ff,0x3fee1333, 0xfcba99df,0x8803ffff,0x7ff41fff,0x3fffec03,0x0017fffe,0x05ffffb0, 0x80bfff70,0x7ffffffa,0x7d4bfff0,0x3e0fffff,0x324fffff,0x6c004fff, 0x3fe23fff,0xfffb05ff,0x9ffff505,0x3ea03d30,0x3fea1fff,0x7ffe406f, 0x207fffb4,0xfd2ffffc,0x7dc005ff,0xfff504ff,0xfff501ff,0xffffffff, 0x307fffff,0x3ee7ffff,0x20001fff,0x005ffffa,0xa80bfff7,0x2fffffff, 0x3ea5fff8,0xf32ffeef,0x649ffbdf,0x6c004fff,0x3ff23fff,0xfffb00ff, 0x17fffa05,0x1ffffc00,0xc80dfff5,0xfffb4fff,0xa7fff407,0x2002fffe, 0x2a04fffb,0xfa84ffff,0xffffffff,0x3fffffff,0xf1ffff90,0x40009fff, 0x00fffff8,0x80bfff70,0xfffdfffa,0x2e5fff86,0x95ffcdff,0x4bffb7ff, 0x4004fffc,0xff53fffd,0x7fec05ff,0xbfff902f,0x3fffe000,0x01bffea3, 0x3f69fff9,0x3ff603ff,0x05fffd5f,0x027ffdc0,0x2a1bfffa,0xffffffff, 0xffffffff,0xdffff103,0x0001ffff,0x017fffe4,0x80bfff70,0xffebfffa, 0x72fffc2f,0x2fff3bff,0x5ffd9ffe,0x0013fff2,0xfd17fffb,0xffd80bff, 0x9fffd02f,0xffff1000,0x037ffd45,0x7ed3fff2,0x3ff603ff,0x05fffd5f, 0x027ffdc0,0x221fffee,0x99effc99,0x999fffa9,0x3ffff200,0x20004fff, 0x004ffffa,0x202fffdc,0xffabfffa,0x92fffc5f,0x2bffebff,0x4bff96ff, 0x4004fffc,0xffcbfffd,0x7fec00ef,0xffffc82f,0xfffb8001,0x3bffea0f, 0xdaaaaaaa,0xfffb4fff,0x9ffff407,0x999bfffe,0x3ee19999,0x7fd404ff, 0x2ffe407f,0x8801ffea,0x0fffffff,0xffff1000,0xffb8001d,0x7ffd405f, 0x7c3ffff3,0x57ff25ff,0x94ffeffd,0x7ffe4dff,0x7ffec004,0x801ffffd, 0xdccdfffd,0x003fffff,0x44fffe88,0xfffffffa,0xffffffff,0x207fffb4, 0xfd2ffffa,0xffffffff,0x3fee1fff,0x7ffcc04f,0x13ff601f,0xc800fff5, 0x004fffff,0x07ffff20,0x17ffee00,0x2e7fff50,0x3ffe5fff,0x7d57ff25, 0xff91ffff,0x027ffe4d,0x3fffff60,0xffb006ff,0xffffffff,0x3f60005d, 0x7fd40fff,0xffffffff,0xfb4fffff,0xfff507ff,0x7ffff4df,0xffffffff, 0x809fff70,0x201ffff9,0x7fdc3ffe,0x7fff4006,0xf50006ff,0x20009fff, 0x5405fffb,0xfff13fff,0xd97ffe1f,0xffff14ff,0xf93ffe4d,0xfd8009ff, 0x3ffffdff,0xfffffd80,0x0003ffff,0x20ffffee,0xfffffffa,0xffffffff, 0x99dfffb4,0x3fffffdb,0x7ffffff4,0x70ffffff,0xf9809fff,0x3fa01fff, 0x02ffe43f,0xffffff70,0xff88009f,0x2e0006ff,0x7d405fff,0x3fff23ff, 0x7ecbfff4,0x93fffa4f,0x3ff27ffb,0x7fec004f,0x0ffffdbf,0x777ffec0, 0x003fffff,0x04ffffb8,0x333dfff5,0xfff93333,0x3fffff69,0x3fffffff, 0x4cdffff4,0x2e199999,0x7d404fff,0x7ffcc7ff,0xffffffff,0x204fffff, 0xfffffff8,0x3f2000ff,0x20001fff,0x5405fffb,0x3fe23fff,0x25fff8ff, 0x3fee4ffe,0xc9ffee1f,0x6c004fff,0xfff8bfff,0x7ffec05f,0x3ffffb12, 0x7fffd400,0x1bffea05,0x369fff90,0xffffffff,0xffe80dff,0x3fee002f, 0x7ffdc04f,0x7ffffcc7,0xffffffff,0x3f204fff,0xffff9fff,0xffff5005, 0xffb80009,0x7ffd405f,0x7dfffec3,0x93ffa5ff,0x7fdc7ff9,0x09fff90f, 0x73fffd80,0x6c07ffff,0x3fa22fff,0xff5006ff,0xffa80bff,0x7ffe406f, 0xdddfffb4,0x7f40359b,0x3ee002ff,0x7fec04ff,0x7fffcc5f,0xffffffff, 0xf304ffff,0x3ff29fff,0x7f4401ff,0xb80006ff,0x7d405fff,0x7ffcc3ff, 0x3fa5fffe,0x2e0d543f,0xfff90fff,0xfffd8009,0x03ffffa3,0x2a17ffec, 0x5401ffff,0xa805ffff,0x7e406fff,0x7fffb4ff,0x5fffd000,0x27ffdc00, 0x07ffff30,0x33fff733,0x337fff33,0x3ffff601,0x0dffff10,0x01ffffc8, 0x5fffb800,0x41fffd40,0x5ffffffe,0x5400fffe,0xfff90fff,0xfffd8009, 0x1bfffe63,0x7417ffec,0x3ea05fff,0xf5004fff,0xffc80dff,0x07fffb4f, 0x05fffd00,0x027ffdc0,0x401ffffb,0x7fc46ffa,0x7ffd401f,0x7fffe43f, 0x7ffff503,0x3fee0000,0x7ffd405f,0xfffffa83,0x00fffe5f,0xfc8fffd4, 0x7ec004ff,0x7ffe43ff,0x2fffd83f,0x81ffffb8,0x004ffffa,0x901bffea, 0x3ff69fff,0xffe8003f,0x3fee002f,0xfffe884f,0x37fdc03f,0xd003ffe6, 0xf881ffff,0x7440ffff,0xeeeeffff,0x02eeeeee,0x202fffdc,0xff03fffa, 0x7fcbffff,0xfff5003f,0x33bfff23,0x4ccccccc,0xf10ffff6,0xfd83ffff, 0xfff882ff,0x7fffd45f,0xeeeeeeef,0xdfff51ee,0xb4fffc80,0xd0007fff, 0x9999bfff,0x3ee59999,0xfedcceff,0xc806ffff,0x3ffd45ff,0x0ffffee0, 0x227fffe4,0xfffffff9,0xffffffff,0x2fffdc03,0x40fffea0,0x15fffffb, 0x2a005fff,0xfff92fff,0xffffffff,0x1fffecff,0x237fffd4,0xf902fffd, 0x7fec3fff,0xffffffff,0xff52ffff,0xfffc80df,0x007fffb4,0xffffffd0, 0x29ffffff,0xfffffffb,0x00dfffff,0x7dc4ffd8,0x3ffe206f,0x3ffe207f, 0x3ffe61ff,0xffffffff,0x5c03ffff,0x7d405fff,0xfff103ff,0x3ffe2bff, 0x5fff5002,0x3ffffff2,0x27ffffff,0xfb03fffd,0x7fec9fff,0xffff302f, 0x7ffffec9,0xffffffff,0x0dfff52f,0xfb4fffc8,0xfd0007ff,0xffffffff, 0x3fee9fff,0xffffffff,0x3ffa002f,0x9037fdc3,0xb807ffff,0x3e65ffff, 0xffffffff,0x03ffffff,0x202fffdc,0x3203fffa,0xff35ffff,0x3fe6005f, 0xfffff92f,0xffffffff,0x881fffec,0xfb1fffff,0x7fec05ff,0xffffb0ff, 0xffffffff,0x3ffea5ff,0xa7ffe406,0x8003fffd,0xfffffffe,0xf74fffff, 0x79dfffff,0x00000015,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x55544000,0xaaaaaaaa,0xaa8801aa, 0x2aaaa01a,0x0009aaaa,0x35555510,0x2aa60000,0x555102aa,0x55555555, 0x4c015555,0x000accca,0x00000000,0x4de6dd44,0x32ea2000,0x800abccd, 0x801bccb9,0x5554c2b9,0x05555101,0xabccba88,0x7ffffdc0,0xffffffff, 0x3fff2204,0x3fff604f,0xdfffffff,0x3fff2001,0x880006ff,0x80ffffff, 0xfffffff8,0xffffffff,0xffffe982,0x80004fff,0x0009705a,0xffffff90, 0xfc8805ff,0xffffffff,0x3fffe602,0xf901efff,0x7ffe4dff,0x0dfff303, 0x3fffffa6,0x3fee2fff,0xffffffff,0xfc884fff,0x204fffff,0xfffffffd, 0x003fffff,0x1ffffffd,0xfffd8000,0xff880fff,0xffffffff,0x5c2fffff, 0xffffffff,0x70000eff,0x5ffb8bff,0xfffd3000,0xbfffffff,0x3ffffa20, 0x02ffffff,0xfffffff7,0xff987fff,0xfff93fff,0x1bffe607,0x3ffffff2, 0x3ee2ffff,0xffffffff,0x2e24ffff,0xffffffff,0x3ffff604,0xffffffff, 0x7ffc402f,0x0002ffff,0x3fffffea,0xffff880f,0xffffffff,0x3fe62fff, 0xfffeffff,0xfd8005ff,0xfff54fff,0xfe8001df,0xffffffff,0xffe82fff, 0xdcaabdff,0xffffa82f,0xffffebbe,0x3ffffea1,0x207fff94,0x7e46fff9, 0xffffffff,0x7fdc02ff,0x7fff405f,0x04ffffff,0x930bfff6,0xb80bffff, 0x4fffffff,0x3fffa000,0xc880ffff,0xcccccccc,0x11ffffec,0x443dffff, 0x001ffffd,0x1dffffb1,0x0f7fffe4,0xcffffb80,0x1bfffea0,0x807ffff1, 0x82fffe80,0x3e65fffd,0xff93ffff,0x3ffe607f,0x3ffffe66,0x00b6a60b, 0xb80bfff7,0xffdaefff,0x3fff604f,0x0ffff902,0xffcfffd8,0xff90007f, 0x01fffd9f,0x5fffe800,0x403fffea,0x9805fffe,0x705ffffe,0x805fffff, 0x304ffff8,0x7cc7ffff,0x5c001fff,0xff106fff,0x7ffec1ff,0x40ffff26, 0x3fa6fff9,0x40000fff,0x4405fffb,0x3fff63ff,0x0bfff604,0x203fffd4, 0xfff8ffff,0x7fcc001f,0x01fffd6f,0x7fffd400,0x817ffee1,0x4c07fffb, 0x403fffff,0x03fffffa,0x803fffea,0x3e24fffd,0x2002efff,0x3a02fffd, 0x1e541fff,0x4c0ffff2,0xfff36fff,0xf700007f,0x81500bff,0x3604fffd, 0xff702fff,0x7ffd40df,0x009fffb5,0xfd2fffd8,0x740001ff,0x7fec5fff, 0x3ffe204f,0xffff700f,0x3fa6005f,0xff704fff,0xfffb80bf,0x7fffff45, 0x7ff401ce,0xcccccccf,0x9002fffe,0x3e607fff,0xffff56ff,0x3fee0000, 0xffb0005f,0x7ffec09f,0x07fffd02,0xfb97ffe4,0x3ea006ff,0x3fffa5ff, 0xfff30000,0x6fffc85f,0x07fffe20,0x07bffff2,0xffffb100,0x4fffc81b, 0x237ffd40,0xfffffff9,0xfff80bef,0xffffffff,0x9003ffff,0x3e607fff, 0xdfff76ff,0x3fee0000,0xffb0005f,0x7ffec09f,0x3fffaa62,0x3fffa00e, 0x01ffff30,0x41ffff10,0x0000fffe,0xf70dfffb,0x7fc03fff,0x3ff622ff, 0x20000dff,0x20effffc,0x5404fffd,0xfe887fff,0xefffffff,0x3ffffe61, 0xffffffff,0xff9003ff,0x3ffe607f,0x00bfffb6,0x17ffee00,0x27ffec00, 0xffffffb0,0x01bfffff,0x3e37ffcc,0xfc803fff,0x7fff43ff,0xfff98000, 0xffff982f,0x3ff660ae,0x3fffa2ff,0xf900005f,0x3f23ffff,0x7fdc05ff, 0x3fae606f,0x10ffffff,0x5555ffff,0x15555555,0x0ffff200,0xfcb7ffcc, 0x700007ff,0x2000bfff,0x3604fffd,0xffffffff,0x2e01cfff,0x7fe44fff, 0x7ffcc05f,0x00fffe86,0x06fffd80,0x3ffffffa,0xfffffffe,0x3ffffea2, 0x7fcc0003,0x3fee3fff,0x7ffe406f,0xfff93004,0x7fffc7ff,0xfc800000, 0xfff503ff,0x03fffead,0x3ffee000,0xfffb0005,0x7fffec09,0xffffffff, 0x3fffb02f,0x407fffa8,0xfe81fffe,0x7cc000ff,0x3e202fff,0xffffffff, 0x4c1fffff,0x004ffffe,0x5fffff50,0x01ffffa8,0x000ffffe,0x749ffff3, 0x20002fff,0x3ff20cdb,0xffff884f,0x09ffff36,0xbfff7000,0x3fff6000, 0x2ffff604,0xfffc9999,0x7ffc40ff,0x2ffff887,0x209fff70,0x4000fffe, 0x8806fffd,0xfffffffc,0x880ffffd,0x00dffffe,0x3fffff20,0x5ffff881, 0x01ffff90,0x47ffff00,0x000ffffc,0x70ffffd8,0xfe88dfff,0x3ffe6fff, 0x002203ff,0x000bfff7,0xd813fff6,0xff502fff,0xfffa89ff,0x09fffd05, 0x333ffff1,0x3fffd333,0xff980133,0x2a2003ff,0xff98abcb,0x3ff600ff, 0xfd800eff,0x2e00efff,0xa9beffff,0x543ffffd,0xffc881be,0x3ffe21ff, 0x5d440bff,0x3ffffe62,0x3bffff53,0xdffffff7,0x77ffffd4,0x02fdbaac, 0x002fffdc,0x204fffd8,0x3a02fffd,0x7fe46fff,0xfeeeeeff,0xffa86fff, 0xffffffff,0x3fffffff,0x03fffec0,0xdfff7000,0xfffff700,0x3fffa205, 0xfffd005f,0xffffffff,0xfffff50d,0xdffffffd,0xffffff50,0x49ffffff, 0x24fffffa,0xffffffff,0x6c6ffeff,0xffffffff,0x7dc02fff,0xfb0005ff, 0x7fec09ff,0x3fff202f,0x7fffffc6,0xffffffff,0x7fffd41f,0xffffffff, 0x203fffff,0x003ffff8,0x0ffff600,0x7ffffd40,0x7ffffcc3,0x3ffa6004, 0xdfffffff,0xfffffa80,0x0effffff,0xffffff70,0x449fffff,0x2a2fffff, 0xffffffff,0x6446ffd9,0xffffffff,0x7fdc02ff,0xffb0005f,0x7ffec09f, 0x93fffa02,0xfffffff9,0xffffffff,0x7ffffd43,0xffffffff,0x3203ffff, 0x00007fff,0x003fffee,0x4fffff98,0x05fffff5,0x3fffae00,0x3a602eff, 0xffffffff,0x7ec400be,0xdfffffff,0x42fffdc2,0x0dfffffa,0x3660dffb, 0xcefffffe,0x2fffdc00,0x4fffd800,0x40bfff60,0x2e3ffffc,0xccccdfff, 0x5fffeccc,0x55555544,0xffffaaaa,0xff101aab,0x100007ff,0x009ffff9, 0x23fffd10,0x001fffe8,0x001a9880,0x09aaa998,0x35531000,0x401a8801, 0x800009a9,0x55100999,0x5dfffb55,0x77543555,0xeffffeee,0xffb2eeee, 0xfd97559f,0x7f41ffff,0x7fdc01ff,0xff0000ff,0xff9001ff,0x326001ff, 0xfffeeccc,0x6c0006ff,0x0077441f,0x00000000,0x00000000,0x00000000, 0xffffffb8,0x4fffffff,0x3fffffea,0xffffffff,0xffffffb3,0x3fffffff, 0x403fffc4,0x002ffff8,0x801ffff0,0x004ffff8,0x3fffffee,0x000effff, 0x00110080,0x00000000,0x00000000,0x00000000,0x7fffffdc,0x4fffffff, 0x3fffffea,0xffffffff,0xffffffb3,0x85dfffff,0xd004fffa,0x20009fff, 0x6400ffff,0x2000ffff,0xfffffffb,0x000003ff,0x00000000,0x00000000, 0x00000000,0xfffb8000,0xffffffff,0x3ffea4ff,0xffffffff,0xfffb3fff, 0x39bdffff,0x00bfff60,0x003fffe4,0x200ffff8,0x004ffff8,0x6f7fffdc, 0x0000009b,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x654c0000,0xa80abcdc,0x372e22aa,0x2e2aa82b,0x2f2e20bc,0x2a1554c0, 0xaa982cdc,0x5553002a,0x2ccc8805,0x55555440,0xaaaaaaaa,0x00aaaaa1, 0x2a155551,0x54c002aa,0x0999802a,0x00054c00,0xa9801555,0xaaaaaaaa, 0x2662aaaa,0x26666099,0x06666620,0xfffff900,0xf89fffff,0xffff76ff, 0x8fff89ff,0xe88ffffd,0x3f21ffff,0xffffd37f,0x7ffcc1df,0xfffe802f, 0x27ffcc04,0x3ffffe60,0xffffffff,0x13fffee4,0x365fffe8,0x36001fff, 0x7fc407ff,0x3ff2002f,0xfffc802f,0x7fffec04,0xffffffff,0x5ffff17f, 0x70bfffe2,0x400bffff,0xfffffffd,0x3fe4ffff,0xfffffbff,0x3ffe4fff, 0xdbfffffc,0x325fffff,0xffffafff,0x7f46ffff,0x7fcc05ff,0x7fcc00ff, 0x7ffcc04f,0xffffffff,0x7ffec4ff,0xffffb81f,0x00bfff20,0xf806ffe8, 0xff3001ff,0x7c401fff,0x3601ffff,0xffffffff,0x3e7fffff,0x3ffe1fff, 0xffff981f,0x9bffb005,0xfffff957,0x3fffffe3,0xfffffeff,0xddfffff0, 0xffbfffff,0x7fffe4ff,0xffffffff,0x3fffee2f,0x17fff200,0x013ffe60, 0xfffffff3,0x87ffffff,0x4c6ffff8,0x7dc2ffff,0x3fe003ff,0x3fe24c5f, 0x7dc0ea0f,0x3604ffff,0x206fffff,0xfffffffd,0x27ffffff,0x3fe0ffff, 0xffb101ff,0x403700bf,0xff4fffe8,0x2219ffff,0xfff3ffff,0x3fffe6bf, 0x321fff73,0x31dfffff,0x7c49fffd,0x3fe03fff,0xff9802ff,0x9999804f, 0xffffa999,0x9ffff506,0x542ffff4,0xf1004fff,0x1efd87ff,0xffb11ffd, 0xfffff301,0x27ffea0b,0x00003fff,0xe83fffa0,0x7e400fff,0xb80005ff, 0xffff5fff,0x9fff909f,0x7c47fffe,0x3ffea7ff,0x0dffff91,0xfc8bfff9, 0xfff506ff,0x3ffe600f,0x3fa20004,0x3f200fff,0xfffb9fff,0x5fff880f, 0xff30e664,0x7fffd45f,0xffe9ffdb,0xffff904f,0x5cbffa0d,0x00000fff, 0xfe8fffd0,0x5553007f,0xffa80003,0x0bffff6f,0x7fd3ffee,0x8fffe25f, 0xff91fffa,0xfff501df,0x0ffff98d,0x004fffd8,0x0009fff3,0x00ffffec, 0x7ffffff4,0x3ffe02ff,0x993ffe66,0x3f221fff,0xffffffff,0x3fa01dff, 0x6ffb84ff,0x00027ff4,0x6c7ffd80,0x000007ff,0x6e665544,0xffff6fff, 0x46aaa205,0x3fe24fff,0x47ffea2f,0xf303fffc,0xfffd0dff,0x1ffff887, 0x7fffffe4,0xffffffff,0x7ffdc07f,0xfff3003f,0xe809ffff,0x3fff27ff, 0x203ffea7,0xffffffb8,0xffc800cf,0x0fffc43f,0x9707ffea,0x99999999, 0x7ec99999,0x03ffec7f,0xffd98000,0xffffffff,0x005ffff6,0x3e24fff8, 0x3ffea2ff,0x207fff91,0xfb86fff9,0x7ffd46ff,0xfffffc86,0xffffffff, 0x3fe607ff,0x7dc005ff,0xd806ffff,0xfffd0fff,0x81ffee5f,0xdfffffb8, 0x1fffd000,0xfd05ffd8,0xffffd8df,0xffffffff,0x91bff27f,0x00000dff, 0xfffffff7,0x3edfffff,0x7c002fff,0x3ffe24ff,0x647ffea2,0xff303fff, 0xffff10df,0x41fffec3,0xfffffffc,0xffffffff,0xdffff107,0xfff88001, 0xffc804ff,0xfffff99f,0x910dff95,0xffffffff,0x3f2203bf,0x7ffcc3ff, 0x47fff301,0xfffffffd,0x27ffffff,0x554c2aa9,0x7d400002,0xaaabefff, 0xfff6fffc,0xfff8005f,0xa8bffe24,0xfff91fff,0x1bffe607,0xf8a7ffec, 0xaa980fff,0xdfffcaaa,0xd02aaaaa,0x0003ffff,0x5ffffffd,0xcafffb80, 0xd8ffffff,0x7ffd45ff,0xffdffeef,0xffdd54ff,0x9ffd0bff,0x70fffd80, 0x99999999,0x00999999,0xfb000000,0x3fea0bff,0x05ffff6f,0x224fff80, 0x3fea2fff,0x07fff91f,0x4c1bffe6,0xfff77fff,0xfff98009,0x3fff2004, 0xffc8003f,0x00ffffff,0x3fafffea,0xfeafffbf,0xa7ffc44f,0x5fff77fd, 0x0bbfffea,0x10033326,0x00005999,0x20000cc0,0x3ffe0098,0xdfff502f, 0x000bfffe,0x7fc49fff,0x47ffea2f,0xf303fffc,0x7ff40dff,0x01fffeaf, 0x027ffcc0,0x04ffffa8,0xbffffa80,0x2205ffff,0xd7ffdfff,0x07fffbff, 0x87ff45f7,0x337aa5e9,0x00000002,0x7ffe4000,0x8266604f,0xff04fffb, 0xfff507ff,0x0bfffedf,0x449fff00,0x3fea2fff,0x07fff91f,0xb81bffe6, 0x6fffefff,0x4fff9800,0x6ffff880,0xffff8800,0x07ffff74,0xaffffffc, 0x1ffffffb,0x41fff810,0x00000000,0xffd00000,0x881dffff,0xfff52fff, 0xfffd07ff,0x3ffee23d,0x5ffff6ff,0x24fff800,0x3ea2fff8,0x7fff91ff, 0x81bffe60,0xfffffff8,0xfff98003,0x7fff4404,0xccccccdf,0xefffd82c, 0x07ffffa0,0x97fffff4,0x0ffffff8,0x003fff00,0x00000000,0xffff5000, 0x541dffff,0xfff91fff,0xfff90bff,0xffffffff,0x3fffedff,0x27ffc002, 0x7d45fff1,0x7fff91ff,0x01bffe60,0x1ffffffb,0x9fff3000,0xfffffb80, 0xffffffff,0x17fffe45,0x41bfffe2,0x20fffffd,0x007ffffe,0x00007332, 0x00000000,0x2effffa0,0xd9afffff,0xfff90fff,0xfff10bff,0xd5ffffff, 0x3fffedff,0x27ffc002,0x7d45fff1,0x7fff91ff,0x01bffe60,0x0bfffff5, 0x13ffe600,0xffffff70,0xbfffffff,0x827fffcc,0xc84ffffb,0x7dc5ffff, 0x00006fff,0x00000000,0x3ffe0000,0x3ffffa24,0x3ea5ffff,0xb103ffff, 0x21bfffff,0xffff6ffd,0x4fff8005,0xfa8bffe2,0x7fff91ff,0x01bffe60, 0x007ffffa,0x7fdc0000,0xffffffff,0xfff15fff,0xfffd80df,0x7fffdc2f, 0x2ffffc42,0x00000000,0x80000000,0x7443fff8,0x1fffffff,0x402fffe4, 0x00009a98,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x80999800,0x1fffffc8,0x00001510,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00003751, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000, }; static signed short stb__consolas_bold_35_usascii_x[95]={ 0,6,3,0,1,0,0,7,4,3,2,1,3,4, 6,1,0,1,2,2,0,2,1,1,1,1,6,3,1,2,3,4,0,0,2,1,1,3,3,0,1,2,2,2, 3,0,1,0,2,0,2,1,1,1,0,0,0,0,1,5,2,4,1,0,0,1,2,2,1,1,0,1,2,2, 2,2,2,1,2,1,2,1,3,2,1,2,0,0,0,0,2,2,7,3,0, }; static signed short stb__consolas_bold_35_usascii_y[95]={ 25,0,0,2,-1,0,0,0,-1,-1,0,7,18,13, 18,0,2,2,2,2,2,2,2,2,2,2,7,7,5,10,5,0,0,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,0,0,2,28,0,7,0,7,0,7,0,7,0,0, 0,0,0,7,7,7,7,7,7,7,2,7,7,7,7,7,7,0,-3,0,11, }; static unsigned short stb__consolas_bold_35_usascii_w[95]={ 0,7,13,19,17,20,20,5,12,12,15,17,10,11, 7,17,19,17,16,16,19,16,17,17,17,17,7,11,15,15,15,13,20,20,16,17,18,14,14,18,17,15,14,17, 15,19,17,19,16,20,17,17,17,17,20,19,20,20,17,10,17,10,17,20,12,16,16,15,16,17,18,18,15,16, 14,17,16,18,15,18,16,16,15,15,16,15,19,20,19,19,15,14,5,14,19, }; static unsigned short stb__consolas_bold_35_usascii_h[95]={ 0,26,10,23,31,26,26,10,34,34,16,18,14,5, 8,29,24,23,23,24,23,24,24,23,24,23,19,25,21,11,21,26,33,23,23,24,23,23,23,24,23,23,24,23, 23,23,23,24,23,30,23,24,23,24,23,23,23,23,23,32,29,32,12,5,8,19,26,19,26,19,25,26,25,25, 33,25,25,18,18,19,25,25,18,19,24,19,18,18,18,26,18,32,36,32,9, }; static unsigned short stb__consolas_bold_35_usascii_s[95]={ 250,76,225,1,121,36,15,250,20,7,164, 89,180,217,245,160,159,17,168,19,73,36,53,93,71,111,214,153,129,209,145, 1,48,52,35,141,235,220,241,89,185,1,126,132,116,96,78,234,203,139,150, 1,60,108,200,221,21,179,42,95,178,84,191,196,239,1,233,238,216,196,134, 57,101,84,33,165,117,34,53,161,200,183,18,180,217,222,69,143,123,196,107, 69,1,106,225, }; static unsigned short stb__consolas_bold_35_usascii_t[95]={ 12,38,138,90,1,38,38,1,1,1,138, 138,138,28,149,1,65,114,90,65,114,65,65,114,65,114,114,38,114,138,114, 38,1,114,114,65,90,90,65,65,90,114,65,90,90,90,90,38,90,1,90, 65,90,65,65,65,90,65,90,1,1,1,138,28,138,138,1,114,1,114,38, 38,38,38,1,38,38,138,138,114,38,38,138,114,38,114,138,138,138,1,138, 1,1,1,149, }; static unsigned short stb__consolas_bold_35_usascii_a[95]={ 308,308,308,308,308,308,308,308, 308,308,308,308,308,308,308,308,308,308,308,308,308,308,308,308, 308,308,308,308,308,308,308,308,308,308,308,308,308,308,308,308, 308,308,308,308,308,308,308,308,308,308,308,308,308,308,308,308, 308,308,308,308,308,308,308,308,308,308,308,308,308,308,308,308, 308,308,308,308,308,308,308,308,308,308,308,308,308,308,308,308, 308,308,308,308,308,308,308, }; // Call this function with // font: NULL or array length // data: NULL or specified size // height: STB_FONT_consolas_bold_35_usascii_BITMAP_HEIGHT or STB_FONT_consolas_bold_35_usascii_BITMAP_HEIGHT_POW2 // return value: spacing between lines static void stb_font_consolas_bold_35_usascii(stb_fontchar font[STB_FONT_consolas_bold_35_usascii_NUM_CHARS], unsigned char data[STB_FONT_consolas_bold_35_usascii_BITMAP_HEIGHT][STB_FONT_consolas_bold_35_usascii_BITMAP_WIDTH], int height) { int i,j; if (data != 0) { unsigned int *bits = stb__consolas_bold_35_usascii_pixels; unsigned int bitpack = *bits++, numbits = 32; for (i=0; i < STB_FONT_consolas_bold_35_usascii_BITMAP_WIDTH*height; ++i) data[0][i] = 0; // zero entire bitmap for (j=1; j < STB_FONT_consolas_bold_35_usascii_BITMAP_HEIGHT-1; ++j) { for (i=1; i < STB_FONT_consolas_bold_35_usascii_BITMAP_WIDTH-1; ++i) { unsigned int value; if (numbits==0) bitpack = *bits++, numbits=32; value = bitpack & 1; bitpack >>= 1, --numbits; if (value) { if (numbits < 3) bitpack = *bits++, numbits = 32; data[j][i] = (bitpack & 7) * 0x20 + 0x1f; bitpack >>= 3, numbits -= 3; } else { data[j][i] = 0; } } } } // build font description if (font != 0) { float recip_width = 1.0f / STB_FONT_consolas_bold_35_usascii_BITMAP_WIDTH; float recip_height = 1.0f / height; for (i=0; i < STB_FONT_consolas_bold_35_usascii_NUM_CHARS; ++i) { // pad characters so they bilerp from empty space around each character font[i].s0 = (stb__consolas_bold_35_usascii_s[i]) * recip_width; font[i].t0 = (stb__consolas_bold_35_usascii_t[i]) * recip_height; font[i].s1 = (stb__consolas_bold_35_usascii_s[i] + stb__consolas_bold_35_usascii_w[i]) * recip_width; font[i].t1 = (stb__consolas_bold_35_usascii_t[i] + stb__consolas_bold_35_usascii_h[i]) * recip_height; font[i].x0 = stb__consolas_bold_35_usascii_x[i]; font[i].y0 = stb__consolas_bold_35_usascii_y[i]; font[i].x1 = stb__consolas_bold_35_usascii_x[i] + stb__consolas_bold_35_usascii_w[i]; font[i].y1 = stb__consolas_bold_35_usascii_y[i] + stb__consolas_bold_35_usascii_h[i]; font[i].advance_int = (stb__consolas_bold_35_usascii_a[i]+8)>>4; font[i].s0f = (stb__consolas_bold_35_usascii_s[i] - 0.5f) * recip_width; font[i].t0f = (stb__consolas_bold_35_usascii_t[i] - 0.5f) * recip_height; font[i].s1f = (stb__consolas_bold_35_usascii_s[i] + stb__consolas_bold_35_usascii_w[i] + 0.5f) * recip_width; font[i].t1f = (stb__consolas_bold_35_usascii_t[i] + stb__consolas_bold_35_usascii_h[i] + 0.5f) * recip_height; font[i].x0f = stb__consolas_bold_35_usascii_x[i] - 0.5f; font[i].y0f = stb__consolas_bold_35_usascii_y[i] - 0.5f; font[i].x1f = stb__consolas_bold_35_usascii_x[i] + stb__consolas_bold_35_usascii_w[i] + 0.5f; font[i].y1f = stb__consolas_bold_35_usascii_y[i] + stb__consolas_bold_35_usascii_h[i] + 0.5f; font[i].advance = stb__consolas_bold_35_usascii_a[i]/16.0f; } } } #ifndef STB_SOMEFONT_CREATE #define STB_SOMEFONT_CREATE stb_font_consolas_bold_35_usascii #define STB_SOMEFONT_BITMAP_WIDTH STB_FONT_consolas_bold_35_usascii_BITMAP_WIDTH #define STB_SOMEFONT_BITMAP_HEIGHT STB_FONT_consolas_bold_35_usascii_BITMAP_HEIGHT #define STB_SOMEFONT_BITMAP_HEIGHT_POW2 STB_FONT_consolas_bold_35_usascii_BITMAP_HEIGHT_POW2 #define STB_SOMEFONT_FIRST_CHAR STB_FONT_consolas_bold_35_usascii_FIRST_CHAR #define STB_SOMEFONT_NUM_CHARS STB_FONT_consolas_bold_35_usascii_NUM_CHARS #define STB_SOMEFONT_LINE_SPACING STB_FONT_consolas_bold_35_usascii_LINE_SPACING #endif
66.660589
133
0.797913
stetre
dc7c7aad5a84b37e159d8e5fcb8c8879c09905b7
13,988
hpp
C++
libs/ml/include/ml/dataloaders/tensor_dataloader.hpp
devjsc/ledger
5681480faf6e2aeee577f149c17745d6ab4d4ab3
[ "Apache-2.0" ]
null
null
null
libs/ml/include/ml/dataloaders/tensor_dataloader.hpp
devjsc/ledger
5681480faf6e2aeee577f149c17745d6ab4d4ab3
[ "Apache-2.0" ]
null
null
null
libs/ml/include/ml/dataloaders/tensor_dataloader.hpp
devjsc/ledger
5681480faf6e2aeee577f149c17745d6ab4d4ab3
[ "Apache-2.0" ]
null
null
null
#pragma once //------------------------------------------------------------------------------ // // Copyright 2018-2019 Fetch.AI Limited // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //------------------------------------------------------------------------------ #include "core/random.hpp" #include "core/serializers/group_definitions.hpp" #include "ml/dataloaders/dataloader.hpp" #include "ml/exceptions/exceptions.hpp" #include "ml/meta/ml_type_traits.hpp" #include <stdexcept> #include <utility> namespace fetch { namespace ml { namespace dataloaders { template <typename LabelType, typename InputType> class TensorDataLoader : public DataLoader<LabelType, InputType> { using TensorType = InputType; using DataType = typename TensorType::Type; using SizeType = fetch::math::SizeType; using SizeVector = fetch::math::SizeVector; using ReturnType = std::pair<LabelType, std::vector<TensorType>>; using IteratorType = typename TensorType::IteratorType; public: TensorDataLoader() = default; TensorDataLoader(SizeVector label_shape, std::vector<SizeVector> data_shapes); ~TensorDataLoader() override = default; ReturnType GetNext() override; bool AddData(std::vector<InputType> const &data, LabelType const &labels) override; SizeType Size() const override; bool IsDone() const override; void Reset() override; bool IsModeAvailable(DataLoaderMode mode) override; void SetTestRatio(float new_test_ratio) override; void SetValidationRatio(float new_validation_ratio) override; template <typename X, typename D> friend struct fetch::serializers::MapSerializer; LoaderType LoaderCode() override { return LoaderType::TENSOR; } protected: std::shared_ptr<SizeType> train_cursor_ = std::make_shared<SizeType>(0); std::shared_ptr<SizeType> test_cursor_ = std::make_shared<SizeType>(0); std::shared_ptr<SizeType> validation_cursor_ = std::make_shared<SizeType>(0); SizeType test_offset_ = 0; SizeType validation_offset_ = 0; SizeType n_samples_ = 0; // number of all samples SizeType n_test_samples_ = 0; // number of test samples SizeType n_validation_samples_ = 0; // number of validation samples SizeType n_train_samples_ = 0; // number of train samples std::vector<TensorType> data_; TensorType labels_; SizeVector label_shape_; SizeVector one_sample_label_shape_; std::vector<SizeVector> data_shapes_; std::vector<SizeVector> one_sample_data_shapes_; float test_to_train_ratio_ = 0.0; float validation_to_train_ratio_ = 0.0; SizeType batch_label_dim_ = fetch::math::numeric_max<SizeType>(); SizeType batch_data_dim_ = fetch::math::numeric_max<SizeType>(); random::Random rand; SizeType count_ = 0; void UpdateRanges(); void UpdateCursor() override; }; template <typename LabelType, typename InputType> TensorDataLoader<LabelType, InputType>::TensorDataLoader(SizeVector label_shape, std::vector<SizeVector> data_shapes) : DataLoader<LabelType, TensorType>() , label_shape_(std::move(label_shape)) , data_shapes_(std::move(data_shapes)) { UpdateCursor(); } template <typename LabelType, typename InputType> typename TensorDataLoader<LabelType, InputType>::ReturnType TensorDataLoader<LabelType, InputType>::GetNext() { std::vector<InputType> ret_data; LabelType ret_labels = labels_.View(*this->current_cursor_).Copy(one_sample_label_shape_); for (SizeType i{0}; i < data_.size(); i++) { ret_data.emplace_back( data_.at(i).View(*this->current_cursor_).Copy(one_sample_data_shapes_.at(i))); } if (this->random_mode_) { *this->current_cursor_ = this->current_min_ + (static_cast<SizeType>(decltype(rand)::generator()) % this->current_size_); ++count_; } else { (*this->current_cursor_)++; } return ReturnType(ret_labels, ret_data); } template <typename LabelType, typename InputType> bool TensorDataLoader<LabelType, InputType>::AddData(std::vector<InputType> const &data, LabelType const & labels) { one_sample_label_shape_ = labels.shape(); one_sample_label_shape_.at(one_sample_label_shape_.size() - 1) = 1; labels_ = labels.Copy(); // Resize data vector if (data_.size() < data.size()) { data_.resize(data.size()); one_sample_data_shapes_.resize(data.size()); } // Add data to data vector for (SizeType i{0}; i < data.size(); i++) { data_.at(i) = data.at(i).Copy(); one_sample_data_shapes_.at(i) = data.at(i).shape(); one_sample_data_shapes_.at(i).at(one_sample_data_shapes_.at(i).size() - 1) = 1; } n_samples_ = data_.at(0).shape().at(data_.at(0).shape().size() - 1); UpdateRanges(); return true; } template <typename LabelType, typename InputType> typename TensorDataLoader<LabelType, InputType>::SizeType TensorDataLoader<LabelType, InputType>::Size() const { return this->current_size_; } template <typename LabelType, typename InputType> bool TensorDataLoader<LabelType, InputType>::IsDone() const { if (this->random_mode_) { return (count_ > (this->current_max_ - this->current_min_)); } return *(this->current_cursor_) >= this->current_max_; } template <typename LabelType, typename InputType> void TensorDataLoader<LabelType, InputType>::Reset() { count_ = 0; *(this->current_cursor_) = this->current_min_; } template <typename LabelType, typename InputType> void TensorDataLoader<LabelType, InputType>::SetTestRatio(float new_test_ratio) { test_to_train_ratio_ = new_test_ratio; UpdateRanges(); } template <typename LabelType, typename InputType> void TensorDataLoader<LabelType, InputType>::SetValidationRatio(float new_validation_ratio) { validation_to_train_ratio_ = new_validation_ratio; UpdateRanges(); } template <typename LabelType, typename InputType> void TensorDataLoader<LabelType, InputType>::UpdateRanges() { float test_percentage = 1.0f - test_to_train_ratio_ - validation_to_train_ratio_; float validation_percentage = test_percentage + test_to_train_ratio_; // Define where test set starts test_offset_ = static_cast<uint32_t>(test_percentage * static_cast<float>(n_samples_)); if (test_offset_ == static_cast<SizeType>(0)) { test_offset_ = static_cast<SizeType>(1); } // Define where validation set starts validation_offset_ = static_cast<uint32_t>(validation_percentage * static_cast<float>(n_samples_)); if (validation_offset_ <= test_offset_) { validation_offset_ = test_offset_ + 1; } // boundary check and fix if (validation_offset_ > n_samples_) { validation_offset_ = n_samples_; } if (test_offset_ > n_samples_) { test_offset_ = n_samples_; } n_validation_samples_ = n_samples_ - validation_offset_; n_test_samples_ = validation_offset_ - test_offset_; n_train_samples_ = test_offset_; *train_cursor_ = 0; *test_cursor_ = test_offset_; *validation_cursor_ = validation_offset_; UpdateCursor(); } template <typename LabelType, typename InputType> void TensorDataLoader<LabelType, InputType>::UpdateCursor() { switch (this->mode_) { case DataLoaderMode::TRAIN: { this->current_cursor_ = train_cursor_; this->current_min_ = 0; this->current_max_ = test_offset_; this->current_size_ = n_train_samples_; break; } case DataLoaderMode::TEST: { if (test_to_train_ratio_ == 0) { throw exceptions::InvalidMode("Dataloader has no test set."); } this->current_cursor_ = test_cursor_; this->current_min_ = test_offset_; this->current_max_ = validation_offset_; this->current_size_ = n_test_samples_; break; } case DataLoaderMode::VALIDATE: { if (validation_to_train_ratio_ == 0) { throw exceptions::InvalidMode("Dataloader has no validation set."); } this->current_cursor_ = validation_cursor_; this->current_min_ = validation_offset_; this->current_max_ = n_samples_; this->current_size_ = n_validation_samples_; break; } default: { throw exceptions::InvalidMode("Unsupported dataloader mode."); } } } template <typename LabelType, typename InputType> bool TensorDataLoader<LabelType, InputType>::IsModeAvailable(DataLoaderMode mode) { switch (mode) { case DataLoaderMode::TRAIN: { return test_offset_ > 0; } case DataLoaderMode::TEST: { return test_offset_ < validation_offset_; } case DataLoaderMode::VALIDATE: { return validation_offset_ < n_samples_; } default: { throw exceptions::InvalidMode("Unsupported dataloader mode."); } } } } // namespace dataloaders } // namespace ml namespace serializers { /** * serializer for tensor dataloader * @tparam TensorType */ template <typename LabelType, typename InputType, typename D> struct MapSerializer<fetch::ml::dataloaders::TensorDataLoader<LabelType, InputType>, D> { using Type = fetch::ml::dataloaders::TensorDataLoader<LabelType, InputType>; using DriverType = D; static uint8_t const BASE_DATA_LOADER = 1; static uint8_t const TRAIN_CURSOR = 2; static uint8_t const TEST_CURSOR = 3; static uint8_t const VALIDATION_CURSOR = 4; static uint8_t const TEST_OFFSET = 5; static uint8_t const VALIDATION_OFFSET = 6; static uint8_t const TEST_TO_TRAIN_RATIO = 7; static uint8_t const VALIDATION_TO_TRAIN_RATIO = 8; static uint8_t const N_SAMPLES = 9; static uint8_t const N_TRAIN_SAMPLES = 10; static uint8_t const N_TEST_SAMPLES = 11; static uint8_t const N_VALIDATION_SAMPLES = 12; static uint8_t const DATA = 13; static uint8_t const LABELS = 14; static uint8_t const LABEL_SHAPE = 15; static uint8_t const ONE_SAMPLE_LABEL_SHAPE = 16; static uint8_t const DATA_SHAPES = 17; static uint8_t const ONE_SAMPLE_DATA_SHAPES = 18; static uint8_t const BATCH_LABEL_DIM = 19; static uint8_t const BATCH_DATA_DIM = 20; template <typename Constructor> static void Serialize(Constructor &map_constructor, Type const &sp) { auto map = map_constructor(20); // serialize parent class first auto dl_pointer = static_cast<ml::dataloaders::DataLoader<LabelType, InputType> const *>(&sp); map.Append(BASE_DATA_LOADER, *(dl_pointer)); map.Append(TRAIN_CURSOR, *sp.train_cursor_); map.Append(TEST_CURSOR, *sp.test_cursor_); map.Append(VALIDATION_CURSOR, *sp.validation_cursor_); map.Append(TEST_OFFSET, sp.test_offset_); map.Append(VALIDATION_OFFSET, sp.validation_offset_); map.Append(TEST_TO_TRAIN_RATIO, sp.test_to_train_ratio_); map.Append(VALIDATION_TO_TRAIN_RATIO, sp.validation_to_train_ratio_); map.Append(N_SAMPLES, sp.n_samples_); map.Append(N_TRAIN_SAMPLES, sp.n_train_samples_); map.Append(N_TEST_SAMPLES, sp.n_test_samples_); map.Append(N_VALIDATION_SAMPLES, sp.n_validation_samples_); map.Append(DATA, sp.data_); map.Append(LABELS, sp.labels_); map.Append(LABEL_SHAPE, sp.label_shape_); map.Append(ONE_SAMPLE_LABEL_SHAPE, sp.one_sample_label_shape_); map.Append(DATA_SHAPES, sp.data_shapes_); map.Append(ONE_SAMPLE_DATA_SHAPES, sp.one_sample_data_shapes_); map.Append(BATCH_LABEL_DIM, sp.batch_label_dim_); map.Append(BATCH_DATA_DIM, sp.batch_data_dim_); } template <typename MapDeserializer> static void Deserialize(MapDeserializer &map, Type &sp) { auto dl_pointer = static_cast<ml::dataloaders::DataLoader<LabelType, InputType> *>(&sp); map.ExpectKeyGetValue(BASE_DATA_LOADER, (*dl_pointer)); map.ExpectKeyGetValue(TRAIN_CURSOR, *sp.train_cursor_); map.ExpectKeyGetValue(TEST_CURSOR, *sp.test_cursor_); map.ExpectKeyGetValue(VALIDATION_CURSOR, *sp.validation_cursor_); map.ExpectKeyGetValue(TEST_OFFSET, sp.test_offset_); map.ExpectKeyGetValue(VALIDATION_OFFSET, sp.validation_offset_); map.ExpectKeyGetValue(TEST_TO_TRAIN_RATIO, sp.test_to_train_ratio_); map.ExpectKeyGetValue(VALIDATION_TO_TRAIN_RATIO, sp.validation_to_train_ratio_); map.ExpectKeyGetValue(N_SAMPLES, sp.n_samples_); map.ExpectKeyGetValue(N_TRAIN_SAMPLES, sp.n_train_samples_); map.ExpectKeyGetValue(N_TEST_SAMPLES, sp.n_test_samples_); map.ExpectKeyGetValue(N_VALIDATION_SAMPLES, sp.n_validation_samples_); map.ExpectKeyGetValue(DATA, sp.data_); map.ExpectKeyGetValue(LABELS, sp.labels_); map.ExpectKeyGetValue(LABEL_SHAPE, sp.label_shape_); map.ExpectKeyGetValue(ONE_SAMPLE_LABEL_SHAPE, sp.one_sample_label_shape_); map.ExpectKeyGetValue(DATA_SHAPES, sp.data_shapes_); map.ExpectKeyGetValue(ONE_SAMPLE_DATA_SHAPES, sp.one_sample_data_shapes_); map.ExpectKeyGetValue(BATCH_LABEL_DIM, sp.batch_label_dim_); map.ExpectKeyGetValue(BATCH_DATA_DIM, sp.batch_data_dim_); sp.UpdateRanges(); sp.UpdateCursor(); } }; } // namespace serializers } // namespace fetch
32.082569
100
0.696097
devjsc
dc7df497c6f0f6510db247d9385e1e9d2214fe87
7,100
cpp
C++
libraries/chain/gravity_evaluator.cpp
petrkotegov/gravity-core
52c9a96126739c33ee0681946e1d88c5be9a6190
[ "MIT" ]
8
2018-05-25T17:58:46.000Z
2018-06-23T21:13:26.000Z
libraries/chain/gravity_evaluator.cpp
petrkotegov/gravity-core
52c9a96126739c33ee0681946e1d88c5be9a6190
[ "MIT" ]
14
2018-05-25T19:44:30.000Z
2018-08-03T11:35:27.000Z
libraries/chain/gravity_evaluator.cpp
petrkotegov/gravity-core
52c9a96126739c33ee0681946e1d88c5be9a6190
[ "MIT" ]
6
2018-05-30T04:37:46.000Z
2019-03-05T14:47:34.000Z
/* * Copyright (c) 2015 Cryptonomex, Inc., and contributors. * * The MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <graphene/chain/gravity_evaluator.hpp> #include <graphene/chain/gravity_transfer_object.hpp> #include <graphene/chain/exceptions.hpp> #include <graphene/chain/hardfork.hpp> #include <graphene/chain/is_authorized_asset.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/uuid/string_generator.hpp> namespace graphene { namespace chain { //**********************************************************************************************************************************************// void_result gravity_transfer_evaluator::do_evaluate( const gravity_transfer_operation& op ) { try { const database& d = db(); const account_object& from_account = op.from(d); const account_object& to_account = op.to(d); const account_object& fee_payer = op.fee_payer_account(d); const asset_object& asset_type = op.amount.asset_id(d); try { GRAPHENE_ASSERT( is_authorized_asset( d, from_account, asset_type ), transfer_from_account_not_whitelisted, "'from' account ${from} is not whitelisted for asset ${asset}", ("from",op.from) ("asset",op.amount.asset_id) ); GRAPHENE_ASSERT( is_authorized_asset( d, to_account, asset_type ), transfer_to_account_not_whitelisted, "'to' account ${to} is not whitelisted for asset ${asset}", ("to",op.to) ("asset",op.amount.asset_id) ); if( asset_type.is_transfer_restricted() ) { GRAPHENE_ASSERT( from_account.id == asset_type.issuer || to_account.id == asset_type.issuer, transfer_restricted_transfer_asset, "Asset {asset} has transfer_restricted flag enabled", ("asset", op.amount.asset_id) ); } FC_ASSERT( ( from_account.id != fee_payer.id || to_account.id != fee_payer.id ), "wrong fee_payer account" ); bool insufficient_balance = d.get_balance( from_account, asset_type ).amount >= op.amount.amount; FC_ASSERT( insufficient_balance, "Insufficient Balance: ${balance}, unable to transfer '${total_transfer}' from account '${a}' to '${t}'", ("a",from_account.name)("t",to_account.name)("total_transfer",d.to_pretty_string(op.amount))("balance",d.to_pretty_string(d.get_balance(from_account, asset_type))) ); return void_result(); } FC_RETHROW_EXCEPTIONS( error, "Unable to transfer ${a} from ${f} to ${t}", ("a",d.to_pretty_string(op.amount))("f",op.from(d).name)("t",op.to(d).name) ); } FC_CAPTURE_AND_RETHROW( (op) ) } void_result gravity_transfer_evaluator::do_apply( const gravity_transfer_operation& o ) { try { const auto& gto = db( ).create<gravity_transfer_object>( [&]( gravity_transfer_object& obj ) { std::string time_str = boost::posix_time::to_iso_string( boost::posix_time::from_time_t( db( ).head_block_time( ).sec_since_epoch( ) ) ); std::string id = fc::to_string( obj.id.space( ) ) + "." + fc::to_string( obj.id.type( ) ) + "." + fc::to_string( obj.id.instance( ) ); boost::uuids::string_generator gen; boost::uuids::uuid u1 = gen( id + time_str + time_str ); obj.uuid = to_string( u1 ); obj.fee = o.fee; obj.from = o.from; obj.to = o.to; obj.amount = o.amount; obj.fee_payer = o.fee_payer_account; obj.memo = o.memo; }); return void_result(); } FC_CAPTURE_AND_RETHROW( (o) ) } //**********************************************************************************************************************************************// void_result gravity_transfer_approve_evaluator::do_evaluate( const gravity_transfer_approve_operation& op ) { return void_result(); } void_result gravity_transfer_approve_evaluator::do_apply( const gravity_transfer_approve_operation& o ) { try { bool gravity_transfer_founded = false; auto& e = db( ).get_index_type<gravity_transfer_index>( ).indices( ).get<by_transfer_by_uuid>( ); for( auto itr = e.begin( ); itr != e.end( ); itr++ ) { if( ( *itr ).uuid.compare( o.uuid ) == 0 ) { if( ( *itr ).to != o.approver ) FC_ASSERT( 0, "wrong receiver!" ); db().adjust_balance( ( *itr ).from, -( *itr ).amount ); db().adjust_balance( ( *itr ).to, ( *itr ).amount ); auto c = db().get_core_asset(); const auto& a = ( *itr ).amount.asset_id( (database&)db() ); db( ).remove( *itr ); gravity_transfer_founded = true; break; } } FC_ASSERT( gravity_transfer_founded, "gravity transfer not founed!" ); return void_result(); } FC_CAPTURE_AND_RETHROW( (o) ) } //**********************************************************************************************************************************************// void_result gravity_transfer_reject_evaluator::do_evaluate( const gravity_transfer_reject_operation& op ) { return void_result(); } void_result gravity_transfer_reject_evaluator::do_apply( const gravity_transfer_reject_operation& o ) { try { bool gravity_transfer_founded = false; auto& e = db( ).get_index_type<gravity_transfer_index>( ).indices( ).get<by_transfer_by_uuid>( ); for( auto itr = e.begin( ); itr != e.end( ); itr++ ) { if( ( *itr ).uuid.compare( o.uuid ) == 0 ) { if( ( *itr ).to != o.approver ) FC_ASSERT( 0, "wrong receiver!" ); db( ).remove( *itr ); gravity_transfer_founded = true; break; } } FC_ASSERT( gravity_transfer_founded, "gravity transfer not founed!" ); return void_result(); } FC_CAPTURE_AND_RETHROW( (o) ) } //**********************************************************************************************************************************************// } } // graphene::chain
43.030303
183
0.600282
petrkotegov
dc804902a46674089cae956272d34190e371d7f6
4,009
hpp
C++
modules/core/linalg/include/nt2/linalg/functions/gallery/kms.hpp
pbrunet/nt2
2aeca0f6a315725b335efd5d9dc95d72e10a7fb7
[ "BSL-1.0" ]
null
null
null
modules/core/linalg/include/nt2/linalg/functions/gallery/kms.hpp
pbrunet/nt2
2aeca0f6a315725b335efd5d9dc95d72e10a7fb7
[ "BSL-1.0" ]
null
null
null
modules/core/linalg/include/nt2/linalg/functions/gallery/kms.hpp
pbrunet/nt2
2aeca0f6a315725b335efd5d9dc95d72e10a7fb7
[ "BSL-1.0" ]
null
null
null
//============================================================================== // Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2012 LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #ifndef NT2_LINALG_FUNCTIONS_GALLERY_KMS_HPP_INCLUDED #define NT2_LINALG_FUNCTIONS_GALLERY_KMS_HPP_INCLUDED #include <nt2/linalg/functions/kms.hpp> #include <nt2/include/functions/pow.hpp> #include <nt2/include/functions/cif.hpp> #include <nt2/include/functions/rif.hpp> #include <nt2/include/functions/abs.hpp> #include <nt2/include/functions/whereij.hpp> #include <nt2/include/functions/is_less.hpp> #include <nt2/core/container/dsl.hpp> #include <nt2/core/utility/box.hpp> #include <nt2/sdk/complex/meta/is_complex.hpp> namespace nt2 { namespace ext { NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::kms_, tag::cpu_, (A0)(A1), (scalar_<integer_<A0> >) (scalar_<floating_<A1> >) ) { BOOST_DISPATCH_RETURNS(2, (A0 const& n, A1 const& rho), (boost::proto:: make_expr<nt2::tag::kms_, container::domain> ( rho , boxify(nt2::of_size(size_t(n), size_t(n))) ) ) ) }; NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::kms_, tag::cpu_, (A0)(A1)(T), (scalar_<integer_<A0> >) (scalar_<unspecified_<A1> >) (target_< scalar_< unspecified_<T> > >) ) { typedef typename T::type value_t; BOOST_DISPATCH_RETURNS(3, (A0 const& n, A1 const& rho, T const& t), (boost::proto:: make_expr<nt2::tag::kms_, container::domain> ( value_t(rho) , boxify(nt2::of_size(size_t(n), size_t(n))) ) ) ) }; NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::run_assign_, tag::cpu_ , (A0)(A1)(N) , ((ast_<A0, nt2::container::domain>)) ((node_<A1,nt2::tag::kms_,N,nt2::container::domain>)) ) { typedef A0& result_type; typedef typename boost::proto::result_of::child_c<A1&,0>::type tmp_type; typedef typename meta::strip<tmp_type>::type tmp1_type; typedef typename tmp1_type::value_type value_t; typedef typename meta::is_complex<value_t>::type iscplx_t; result_type operator()(A0& out, const A1& in) const { BOOST_AUTO_TPL(siz,boost::proto::value( boost::proto::child_c<1>(in))); value_t rho = boost::proto::child_c<0>(in); size_t n = siz[0]; out.resize(siz); finalize(out, n, rho, iscplx_t()); return out; } private : static BOOST_FORCEINLINE void finalize(A0& out, const size_t & n, const value_t & rho, const boost::mpl::false_ &) { out = nt2::pow(rho, nt2::abs(nt2::rif(n, meta::as_<value_t>())-cif(n, meta::as_<value_t>()))); } static BOOST_FORCEINLINE void finalize(A0& out, const size_t & n, const value_t & rho, const boost::mpl::true_ &) { out = pow(rho, nt2::abs(nt2::rif(n, meta::as_<value_t>())-nt2::cif(n, meta::as_<value_t>()))); out = whereij(nt2::functor<nt2::tag::is_less_>(), nt2::conj(out), out); //nt2::conj(nt2::tril(out,-1)) + nt2::triu(out); } }; } } #endif
42.2
126
0.499127
pbrunet
dc828fcddb0a659452f04bb7a96fd368e4a1d4d6
4,625
cpp
C++
Official Windows Driver Kit Sample/Windows Driver Kit (WDK) 8.1 Samples/[C++]-windows-driver-kit-81-cpp/WDK 8.1 C++ Samples/Async Notification Sample/C++/server/library/asyncnotify.cpp
zzgchina888/msdn-code-gallery-microsoft
21cb9b6bc0da3b234c5854ecac449cb3bd261f29
[ "MIT" ]
2
2022-01-21T01:40:58.000Z
2022-01-21T01:41:10.000Z
Official Windows Driver Kit Sample/Windows Driver Kit (WDK) 8.1 Samples/[C++]-windows-driver-kit-81-cpp/WDK 8.1 C++ Samples/Async Notification Sample/C++/server/library/asyncnotify.cpp
zzgchina888/msdn-code-gallery-microsoft
21cb9b6bc0da3b234c5854ecac449cb3bd261f29
[ "MIT" ]
1
2022-03-15T04:21:41.000Z
2022-03-15T04:21:41.000Z
Official Windows Driver Kit Sample/Windows Driver Kit (WDK) 8.1 Samples/[C++]-windows-driver-kit-81-cpp/WDK 8.1 C++ Samples/Async Notification Sample/C++/server/library/asyncnotify.cpp
zzgchina888/msdn-code-gallery-microsoft
21cb9b6bc0da3b234c5854ecac449cb3bd261f29
[ "MIT" ]
null
null
null
// // Windows Server (Printing) Driver Development Kit Samples. // // // Copyright (c) 1990 - 2005 Microsoft Corporation. // All Rights Reserved. // // // This source code is intended only as a supplement to Microsoft // Development Tools and/or on-line documentation. See these other // materials for detailed information regarding Microsoft code samples. // // THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY // KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // #include "precomp.h" #pragma hdrstop _Analysis_mode_(_Analysis_code_type_user_driver_) #include "acallback.hpp" #include "notifydata.hpp" // // MarshalSchema is used to marshal an EOEMDataSchema enum value into a byte array // in a platform-independent fashion (to avoid endianness and size issues on other platforms). // This allows the client and server to run on independent architectures without issue. // To marshal more complex data structures than a simple enum value, it is recommended that // the RPC Serialization Services be used. See the MSDN documentation at: // http://msdn2.microsoft.com/en-us/library/aa378670.aspx for details on their use. // void MarshalSchema( _In_ EOEMDataSchema const &in, _Out_ BYTE (&out)[4] ) { out[0] = (BYTE)(in); out[1] = (BYTE)(in >> 8); out[2] = (BYTE)(in >> 16); out[3] = (BYTE)(in >> 24); } VOID SendAsyncNotification( _In_ LPWSTR pPrinterName, EOEMDataSchema action ) { IPrintAsyncNotifyChannel *pIAsynchNotification = NULL; CPrintOEMAsyncNotifyCallback *pIAsynchCallback = new CPrintOEMAsyncNotifyCallback; if (pIAsynchCallback) { RouterCreatePrintAsyncNotificationChannel(pPrinterName, const_cast<GUID*>(&SAMPLE_NOTIFICATION_UI), kPerUser, kBiDirectional, pIAsynchCallback, &pIAsynchNotification); pIAsynchCallback->Release(); } if (pIAsynchNotification) { BYTE data[4] = { 0 }; MarshalSchema(action, data); CPrintOEMAsyncNotifyDataObject *pClientNotification = new CPrintOEMAsyncNotifyDataObject(data, sizeof(data), const_cast<GUID*>(&SAMPLE_NOTIFICATION_UI)); if (pClientNotification) { pIAsynchNotification->SendNotification(pClientNotification); pClientNotification->Release(); } pIAsynchNotification->Release(); } } VOID SendAsyncUINotification( _In_ LPWSTR pPrinterName ) { WCHAR pszMsg[] = L"<?xml version=\"1.0\" ?>" \ L"<asyncPrintUIRequest xmlns=\"http://schemas.microsoft.com/2003/print/asyncui/v1/request\">" \ L"<v1><requestOpen><balloonUI><title>AsyncUI sample</title><body>This text is a sample.</body>" \ L"</balloonUI></requestOpen></v1></asyncPrintUIRequest>"; IPrintAsyncNotifyChannel *pIAsynchNotification = NULL; CPrintOEMAsyncNotifyCallback *pIAsynchCallback = new CPrintOEMAsyncNotifyCallback; if (pIAsynchCallback) { RouterCreatePrintAsyncNotificationChannel(pPrinterName, const_cast<GUID*>(&MS_ASYNCNOTIFY_UI), kPerUser, kBiDirectional, pIAsynchCallback, &pIAsynchNotification); pIAsynchCallback->Release(); } if (pIAsynchNotification) { CPrintOEMAsyncNotifyDataObject *pClientNotification = new CPrintOEMAsyncNotifyDataObject(reinterpret_cast<BYTE*>(pszMsg), sizeof(pszMsg), const_cast<GUID*>(&MS_ASYNCNOTIFY_UI)); if (pClientNotification) { pIAsynchNotification->SendNotification(pClientNotification); pClientNotification->Release(); } pIAsynchNotification->Release(); } }
34.774436
141
0.568649
zzgchina888
dc86a02d5d9ddea2b60805bb68a57b445ec690dc
3,020
hpp
C++
upass/verifier/upass_verifier.hpp
masc-ucsc/lgraph
923a6f9b9fe7b3fe68d0ef028d9ad597317a0331
[ "BSD-3-Clause" ]
46
2018-05-31T23:07:02.000Z
2019-09-16T20:21:03.000Z
upass/verifier/upass_verifier.hpp
masc-ucsc/lgraph
923a6f9b9fe7b3fe68d0ef028d9ad597317a0331
[ "BSD-3-Clause" ]
120
2018-05-16T23:11:09.000Z
2019-09-25T18:52:49.000Z
upass/verifier/upass_verifier.hpp
masc-ucsc/lgraph
923a6f9b9fe7b3fe68d0ef028d9ad597317a0331
[ "BSD-3-Clause" ]
8
2018-11-08T18:53:52.000Z
2019-09-05T20:04:20.000Z
// This file is distributed under the BSD 3-Clause License. See LICENSE for details. #pragma once #include "fmt/format.h" #include "lnast_ntype.hpp" #include "upass_core.hpp" struct uPass_verifier : public upass::uPass { public: using uPass::uPass; // Assignment // void process_assign() override { check_binary(); } // Operators // - Bitwidth void process_bit_and() override { check_binary(); } void process_bit_or() override { check_binary(); } // void process_bit_not() override { check_binary(); } void process_bit_xor() override { check_binary(); } // - Bitwidth Insensitive Reduce // void process_reduce_or() override { check_binary(); } // - Logical void process_logical_and() override { check_binary(); } void process_logical_or() override { check_binary(); } // void process_logical_not() override { check_binary(); } // - Arithmetic void process_plus() override { check_binary(); } void process_minus() override { check_binary(); } void process_mult() override { check_binary(); } void process_div() override { check_binary(); } void process_mod() override { check_binary(); } // - Shift void process_shl() override { check_binary(); } void process_sra() override { check_binary(); } // - Bit Manipulation // void process_sext() override { check_binary(); } // void process_set_mask() override { check_binary(); } // void process_get_mask() override { check_binary(); } // void process_mask_and() override { check_binary(); } // void process_mask_popcount() override { check_binary(); } // void process_mask_xor() override { check_binary(); } // - Comparison void process_ne() override { check_binary(); } void process_eq() override { check_binary(); } void process_lt() override { check_binary(); } void process_le() override { check_binary(); } void process_gt() override { check_binary(); } void process_ge() override { check_binary(); } private: void check_binary() { move_to_child(); check_type(Lnast_ntype::Lnast_ntype_ref); move_to_sibling(); check_type(Lnast_ntype::Lnast_ntype_ref, Lnast_ntype::Lnast_ntype_const); move_to_sibling(); check_type(Lnast_ntype::Lnast_ntype_ref, Lnast_ntype::Lnast_ntype_const); end_of_siblings(); move_to_parent(); } void end_of_siblings() const { if (!is_last_child()) { upass::error(""); } } template <class... Lnast_ntype_int> void check_type(Lnast_ntype_int... ty) const { if (is_invalid()) { upass::error("invalid\n"); return; } // print_types(ty...); auto n = get_raw_ntype(); // print_types(n); if (((n == ty) || ...) || false) { return; } upass::error("failed\n"); } template <class T, class... Targs> void print_types(T ty, Targs... tys) const { std::cout << Lnast_ntype::debug_name(ty) << " "; print_types(tys...); } void print_types() const {} }; static upass::uPass_plugin verifier("verifier", upass::uPass_wrapper<uPass_verifier>::get_upass);
31.458333
97
0.671854
masc-ucsc
dc87d18e6b2106b111bb9e13745676a8752e419b
2,268
cpp
C++
SocketWatcher/RegisterServer.cpp
kiranjosek/HAM
26ef64aba7064f2279114213fbad37ab8cdafd7b
[ "Apache-2.0" ]
1
2020-06-14T01:16:20.000Z
2020-06-14T01:16:20.000Z
SocketWatcher/RegisterServer.cpp
kiranjosek/HAM
26ef64aba7064f2279114213fbad37ab8cdafd7b
[ "Apache-2.0" ]
null
null
null
SocketWatcher/RegisterServer.cpp
kiranjosek/HAM
26ef64aba7064f2279114213fbad37ab8cdafd7b
[ "Apache-2.0" ]
1
2020-06-14T01:16:21.000Z
2020-06-14T01:16:21.000Z
#include "RegisterServer.h" RegisterServer::RegisterServer(int port) { int sockFd= CreateServerSocket(port); CreateEpollSocket(sockFd); watchEvent = &SocketWatcher::StartServerWatcher; printf("Register Server\n"); } RegisterServer::RegisterServer(char* ipAddr,int port) { int sockFd = CreateClientSocket(ipAddr,port); // CreateEpollSocket(sockFd,1); CreateEpollSocket(sockFd,DEFAULT_SERVER_EVENTS|EPOLLET,new SocketInfo(sockFd,64)); watchEvent = &SocketWatcher::StartClientWatcher; //MUXER.AddSubscriberSocket(sockFd); printf("Register Client\n"); } void RegisterServer::EventErrorHandler(struct epoll_event &event) { printf("RegisterServer::EventErrorHandler();\n"); SocketInfo* dh = (SocketInfo*)event.data.ptr; //MUXER.RemoveSubscriberSocket(dh->m_socketDescriptor); close (dh->m_socketDescriptor); delete dh; } void RegisterServer::AcceptNewClientConnection(struct epoll_event &event) { printf("RegisterServer()::AcceptNewClientConnection()\n"); struct sockaddr in_addr; socklen_t in_len; int infd; in_len = sizeof in_addr; infd = accept(m_socketDescriptor,&in_addr,&in_len); if (infd == -1) //error or Exception return; if(SetSocketFlags(infd,O_NONBLOCK) < 0) { perror ("Flag Error:"); return;// exit() } event.data.ptr = new SocketInfo(infd,64); #ifdef EDGETRIGGERED event.events = EPOLLIN | EPOLLET | EPOLLERR | EPOLLRDHUP | EPOLLHUP; #else event.events = EPOLLIN | EPOLLERR | EPOLLRDHUP | EPOLLHUP; #endif if(epoll_ctl(m_epollDescriptor,EPOLL_CTL_ADD,infd,&event)) { perror ("epoll_ctl"); return; // exit() } //MUXER.AddSubscriberSocket(infd); } void RegisterServer::ProcessClientEvent(struct epoll_event &event) { printf("RegisterServer::ProcessClientEvent();\n"); int done = 0; SocketInfo* dh = (SocketInfo*)event.data.ptr; #ifdef EDGETRIGGERED while(1) { #endif dh->ReadFromSocket(dh->m_socketDescriptor,done); if(done == 1) // socket read Error { EventErrorHandler(event); return; } #ifdef EDGETRIGGERED else if(done == 2) //EAGAIN { return; } } #endif }
23.873684
86
0.666226
kiranjosek
dc8807302de6a2674509187012e123a28919d462
7,388
cpp
C++
src/LuminoEngine/src/Graphics/RenderPass.cpp
infinnie/Lumino
921caabdbcb91528a2aac290e31d650628bc3bed
[ "MIT" ]
null
null
null
src/LuminoEngine/src/Graphics/RenderPass.cpp
infinnie/Lumino
921caabdbcb91528a2aac290e31d650628bc3bed
[ "MIT" ]
null
null
null
src/LuminoEngine/src/Graphics/RenderPass.cpp
infinnie/Lumino
921caabdbcb91528a2aac290e31d650628bc3bed
[ "MIT" ]
null
null
null
/* 移行 Note: map を各 GraphicsResource から CommandBuffer へ移動する。 ※ ネイティブの map (transfar) は RenderPass の外側でなければ使えないので、順序制御するため CommandBuffer に統合したい CommandBuffer と RenderPass は全て pool からインスタンスを得る。インスタンスを外側で保持し続けてはならない。 */ #include "Internal.hpp" #include <LuminoEngine/Graphics/Texture.hpp> #include <LuminoEngine/Graphics/DepthBuffer.hpp> #include <LuminoEngine/Graphics/RenderPass.hpp> #include "GraphicsManager.hpp" #include "GraphicsProfiler.hpp" #include "RHIs/GraphicsDeviceContext.hpp" namespace ln { //============================================================================== // RenderPass RenderPass::RenderPass() : m_manager(nullptr) , m_rhiObject() , m_renderTargets{} , m_depthBuffer() , m_clearFlags(ClearFlags::None) , m_clearColor(0, 0, 0, 0) , m_clearDepth(1.0f) , m_clearStencil(0x00) , m_dirty(true) , m_active(false) { detail::GraphicsResourceInternal::initializeHelper_GraphicsResource(this, &m_manager); detail::GraphicsResourceInternal::manager(this)->profiler()->addRenderPass(this); } RenderPass::~RenderPass() { detail::GraphicsResourceInternal::manager(this)->profiler()->removeRenderPass(this); detail::GraphicsResourceInternal::finalizeHelper_GraphicsResource(this, &m_manager); } void RenderPass::init() { Object::init(); } void RenderPass::init(RenderTargetTexture* renderTarget, DepthBuffer* depthBuffer) { init(); setRenderTarget(0, renderTarget); setDepthBuffer(depthBuffer); } void RenderPass::onDispose(bool explicitDisposing) { releaseRHI(); Object::onDispose(explicitDisposing); } void RenderPass::setRenderTarget(int index, RenderTargetTexture* value) { if (LN_REQUIRE(!m_active)) return; if (LN_REQUIRE_RANGE(index, 0, GraphicsContext::MaxMultiRenderTargets)) return; if (m_renderTargets[index] != value) { m_renderTargets[index] = value; m_dirty = true; } } RenderTargetTexture* RenderPass::renderTarget(int index) const { if (LN_REQUIRE_RANGE(index, 0, GraphicsContext::MaxMultiRenderTargets)) return nullptr; return m_renderTargets[index]; } void RenderPass::setDepthBuffer(DepthBuffer* value) { if (LN_REQUIRE(!m_active)) return; if (m_depthBuffer != value) { m_depthBuffer = value; m_dirty = true; } } void RenderPass::setClearFlags(ClearFlags value) { if (LN_REQUIRE(!m_active)) return; if (m_clearFlags != value) { m_clearFlags = value; m_dirty = true; } } void RenderPass::setClearColor(const Color& value) { if (LN_REQUIRE(!m_active)) return; if (m_clearColor != value) { m_clearColor = value; m_dirty = true; } } void RenderPass::setClearDepth(float value) { if (LN_REQUIRE(!m_active)) return; if (m_clearDepth != value) { m_clearDepth = value; m_dirty = true; } } void RenderPass::setClearStencil(uint8_t value) { if (LN_REQUIRE(!m_active)) return; if (m_clearStencil != value) { m_clearStencil = value; m_dirty = true; } } void RenderPass::setClearValues(ClearFlags flags, const Color& color, float depth, uint8_t stencil) { if (LN_REQUIRE(!m_active)) return; setClearFlags(flags); setClearColor(color); setClearDepth(depth); setClearStencil(stencil); } DepthBuffer* RenderPass::depthBuffer() const { return m_depthBuffer; } void RenderPass::onChangeDevice(detail::IGraphicsDevice* device) { if (LN_REQUIRE(!m_active)) return; if (!device) { releaseRHI(); } else { m_dirty = true; // create with next resolveRHIObject } } detail::IRenderPass* RenderPass::resolveRHIObject(GraphicsContext* context, bool* outModified) { if (m_dirty) { releaseRHI(); m_dirty = false; const RenderTargetTexture* primaryTarget = m_renderTargets[0]; if (LN_REQUIRE(primaryTarget, "RenderPass: [0] Invalid render target.")) return nullptr; const Size primarySize(primaryTarget->width(), primaryTarget->height()); detail::NativeRenderPassCache::FindKey key; for (auto i = 0; i < m_renderTargets.size(); i++) { RenderTargetTexture* rt = m_renderTargets[i]; if (rt) { if (LN_REQUIRE(rt->width() == primarySize.width && rt->height() == primarySize.height, u"RenderPass: Invalid render target dimensions.")) return nullptr; } key.renderTargets[i] = detail::GraphicsResourceInternal::resolveRHIObject<detail::RHIResource>(context, rt, nullptr); } key.depthBuffer = detail::GraphicsResourceInternal::resolveRHIObject<detail::IDepthBuffer>(context, m_depthBuffer, nullptr); key.clearFlags = m_clearFlags; key.clearColor = m_clearColor; key.clearDepth = m_clearDepth; key.clearStencil = m_clearStencil; if (!m_renderTargets[0]->m_cleared && !testFlag(key.clearFlags, ClearFlags::Color)) { key.clearFlags = Flags<ClearFlags>(key.clearFlags) | ClearFlags::Color; m_dirty = true; } m_renderTargets[0]->m_cleared = true; if (m_depthBuffer) { if (LN_REQUIRE(m_depthBuffer->width() == primarySize.width && m_depthBuffer->height() == primarySize.height, u"RenderPass: Invalid depth buffer dimensions.")) return nullptr; if (!m_depthBuffer->m_cleared && !testFlag(key.clearFlags, Flags<ClearFlags>(ClearFlags::Depth | ClearFlags::Stencil).get())) { key.clearFlags = Flags<ClearFlags>(key.clearFlags) | ClearFlags::Depth | ClearFlags::Stencil; m_dirty = true; } m_depthBuffer->m_cleared = true; } auto device = detail::GraphicsResourceInternal::manager(this)->deviceContext(); m_rhiObject = device->renderPassCache()->findOrCreate(key); key.clearFlags = ClearFlags::None; key.clearColor = Color(0, 0, 0, 0); key.clearDepth = 1.0f; key.clearStencil = 0x00; m_rhiObjectNoClear = device->renderPassCache()->findOrCreate(key); } return m_rhiObject; } // [2019/10/5] // GraphicsContext はデータ転送を遅延実行するため、各種 resolve (vkCmdCopyBuffer()) が呼ばれるタイミングが RenderPass の内側に入ってしまう。 // // 多分グラフィックスAPIとして正しいであろう対策は、GraphicsContext に map, unmap, setData 等を実装して、resolve の遅延実行をやめること。 // ただ、dynamic なリソース更新するところすべてで GraphicsContext が必要になるので、描画に制限が多くなるし、GraphicsContext の取り回しを考えないとならない。 // 制限として厄介なのは DebugRendering. 各 onUpdate() の時点で何か描きたいときは GraphicsContext が確定していないのでいろいろ制約を考える必要がある。 // 特に、onUpdate 1度に対して複数 SwapChain から world を覗きたいときとか。 // // もうひとつ、泥臭いけど今のところあまり時間掛けないで回避できるのが、この方法。 detail::IRenderPass* RenderPass::resolveRHIObjectNoClear(GraphicsContext* context, bool* outModified) { resolveRHIObject(context, outModified); return m_rhiObjectNoClear; } void RenderPass::releaseRHI() { if (m_rhiObject) { //auto device = detail::GraphicsResourceInternal::manager(this)->deviceContext(); //device->renderPassCache()->release(m_rhiObject); m_rhiObject = nullptr; } } ////============================================================================== //// RenderPassPool //namespace detail { // //RenderPassPool::RenderPassPool(GraphicsManager* manager) //{ //} // //RenderPass* RenderPassPool::findOrCreate(const FindKey& key) //{ // uint64_t hash = computeHash(key); // auto itr = m_hashMap.find(hash); // if (itr != m_hashMap.end()) { // return itr->second; // } // else { // // TODO: Pool を使い切ったら、使っていないものを消す // // auto pipeline = m_device->createPipeline(key.renderPass, key.state); // if (!pipeline) { // return nullptr; // } // // m_hashMap.insert({ hash, pipeline }); // return pipeline; // } //} // //uint64_t RenderPassPool::computeHash(const FindKey& key) //{ //} // //} // namespace detail } // namespace ln
28.091255
177
0.70804
infinnie
dc8812275a6a339a60bb8ae06392c6c1fb9d39ae
1,108
cpp
C++
JTS/CF-B/CF6-D2-B/main.cpp
rahulsrma26/ol_codes
dc599f5b70c14229a001c5239c366ba1b990f68b
[ "MIT" ]
2
2019-03-18T16:06:10.000Z
2019-04-07T23:17:06.000Z
JTS/CF-B/CF6-D2-B/main.cpp
rahulsrma26/ol_codes
dc599f5b70c14229a001c5239c366ba1b990f68b
[ "MIT" ]
null
null
null
JTS/CF-B/CF6-D2-B/main.cpp
rahulsrma26/ol_codes
dc599f5b70c14229a001c5239c366ba1b990f68b
[ "MIT" ]
1
2019-03-18T16:06:52.000Z
2019-03-18T16:06:52.000Z
// Date : 2019-03-26 // Author : Rahul Sharma // Problem : http://codeforces.com/contest/6/problem/B #include <iostream> #include <string> int main() { using namespace std; ios_base::sync_with_stdio(false); cin.tie(0); int n, m; cin >> n >> m; char p; cin >> p; char d[128] = {}; auto check = [&](const string& s) { if (m > 1) { if (s[0] == p) d[s[1]] = 1; if (s[m - 1] == p) d[s[m - 2]] = 1; } for (int j = 1; j < m - 1; j++) if (s[j] == p) d[s[j - 1]] = d[s[j + 1]] = 1; }; string s[2]; cin >> s[0]; check(s[0]); for (int i = 1; i < n; i++) { auto& top = s[1 - (i & 1)]; auto& bot = s[i & 1]; cin >> bot; check(bot); for (int j = 0; j < m; j++) if (top[j] == p) d[bot[j]] = 1; else if (bot[j] == p) d[top[j]] = 1; } int c = 0; for (int i = 'A'; i <= 'Z'; i++) if (i != p && d[i]) c++; cout << c; }
20.518519
54
0.351083
rahulsrma26
dc88ab7715a71359d350dbea83a12ceea676505c
86,244
cpp
C++
plugin/al/mayautils/AL/maya/utils/NodeHelper.cpp
sopvop/maya-usd
c567a1661152ec2450359767fa2b0ca8cac4dc83
[ "Apache-2.0" ]
1
2020-01-09T06:42:22.000Z
2020-01-09T06:42:22.000Z
plugin/al/mayautils/AL/maya/utils/NodeHelper.cpp
ZhongLingXiao/maya-usd
c567a1661152ec2450359767fa2b0ca8cac4dc83
[ "Apache-2.0" ]
null
null
null
plugin/al/mayautils/AL/maya/utils/NodeHelper.cpp
ZhongLingXiao/maya-usd
c567a1661152ec2450359767fa2b0ca8cac4dc83
[ "Apache-2.0" ]
null
null
null
// // Copyright 2017 Animal Logic // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "AL/maya/utils/NodeHelper.h" #include "AL/maya/utils/MayaHelperMacros.h" #include "AL/maya/utils/DebugCodes.h" #include "maya/MDataBlock.h" #include "maya/MEulerRotation.h" #include "maya/MFnCompoundAttribute.h" #include "maya/MFnDependencyNode.h" #include "maya/MFnEnumAttribute.h" #include "maya/MFnMatrixAttribute.h" #include "maya/MFnMessageAttribute.h" #include "maya/MFnPluginData.h" #include "maya/MFnStringData.h" #include "maya/MFnTypedAttribute.h" #include "maya/MFnUnitAttribute.h" #include "maya/MGlobal.h" #include "maya/MMatrix.h" #include "maya/MPxNode.h" #include "maya/MTime.h" #include <cassert> #include <iostream> #include <sstream> #include <cctype> namespace AL { namespace maya { namespace utils { //---------------------------------------------------------------------------------------------------------------------- // takes an attribute name such as "thisIsAnAttribute" and turns it into "This Is An Attribute". Just used to make the // attributes a little bit more readable in the Attribute Editor GUI. //---------------------------------------------------------------------------------------------------------------------- std::string beautifyAttrName(std::string attrName) { if(std::islower(attrName[0])) { attrName[0] = std::toupper(attrName[0]); } for(size_t i = 1; i < attrName.size(); ++i) { if(std::isupper(attrName[i])) { attrName.insert(i++, 1, ' '); } } return attrName; } //---------------------------------------------------------------------------------------------------------------------- /// \brief A little code generator that outputs the custom AE gui needed to handle file path attributes. /// \param nodeName type name of the node /// \param attrName the name of the file path attribute /// \param fileFilter a filter string of the form: "USD Files (*.usd*) (*.usd*);;Alembic Files (*.abc)" //---------------------------------------------------------------------------------------------------------------------- void constructFilePathUi( std::ostringstream& oss, const std::string& nodeName, const std::string& attrName, const std::string& fileFilter, const NodeHelper::FileMode mode) { // generate code to create a file attribute GUI (with button to click to load the file) oss << "global proc AE" << nodeName << "Template_" << attrName << "New(string $anAttr) {\n"; oss << " setUITemplate -pushTemplate attributeEditorTemplate;\n"; oss << " rowLayout -numberOfColumns 3;\n"; oss << " text -label \"" << beautifyAttrName(attrName) << "\";\n"; oss << " textField " << attrName << "FilePathField;\n"; oss << " symbolButton -image \"navButtonBrowse.xpm\" " << attrName << "FileBrowserButton;\n"; oss << " setParent ..;\n"; oss << " AE" << nodeName << "Template_" << attrName << "Replace($anAttr);\n"; oss << " setUITemplate -popTemplate;\n"; oss << "}\n"; // generate the method that will replace the value in the control when another node of the same type is selected oss << "global proc AE" << nodeName << "Template_" << attrName << "Replace(string $anAttr) {\n"; oss << " evalDeferred (\"connectControl " << attrName << "FilePathField \" + $anAttr);\n"; oss << " button -edit -command (\"AE" << nodeName << "Template_" << attrName << "FileBrowser \" + $anAttr) " << attrName << "FileBrowserButton;\n"; oss << "}\n"; // generate the button callback that will actually create the file dialog for our attribute. // Depending on the fileMode used, we may end up having more than one filename, which will be munged // together with a semi-colon as the seperator. It's arguably a little wasteful to retain the code that // munges together multiple paths when using a single file select mode. Meh. :) oss << "global proc AE" << nodeName << "Template_" << attrName << "FileBrowser(string $anAttr) {\n"; oss << " string $fileNames[] = `fileDialog2 -caption \"Specify " << beautifyAttrName(attrName) << "\""; if(!fileFilter.empty()) { oss << " -fileFilter \"" << fileFilter << "\""; } oss << " -fileMode " << mode << "`;\n"; oss << " if (size($fileNames) > 0) {\n"; oss << " string $concatonated = $fileNames[0];\n"; oss << " for($ii=1; $ii < size($fileNames); ++$ii) $concatonated += (\";\" + $fileNames[$ii]);\n"; oss << " evalEcho (\"setAttr -type \\\"string\\\" \" + $anAttr + \" \\\"\" + $concatonated + \"\\\"\");\n"; oss << " }\n"; oss << "}\n"; } //---------------------------------------------------------------------------------------------------------------------- NodeHelper::InternalData* NodeHelper::m_internal = 0; //---------------------------------------------------------------------------------------------------------------------- void NodeHelper::setNodeType(const MString& typeName) { if(!m_internal) { m_internal = new InternalData; } m_internal->m_typeBeingRegistered = typeName.asChar(); } //---------------------------------------------------------------------------------------------------------------------- void NodeHelper::addFrame(const char* frameTitle) { if(!m_internal) m_internal = new InternalData; m_internal->m_frames.push_front(Frame(frameTitle)); } //---------------------------------------------------------------------------------------------------------------------- void NodeHelper::addInheritedAttr(const char* longName) { if(m_internal) { Frame& frame = *m_internal->m_frames.begin(); frame.m_attributes.push_back(longName); frame.m_attributeTypes.push_back(Frame::kNormal); } } //---------------------------------------------------------------------------------------------------------------------- MObject NodeHelper::addEnumAttr(const char* longName, const char* shortName, uint32_t flags, const char* const * strings, const int16_t* values) { if(m_internal) { Frame& frame = *m_internal->m_frames.begin(); if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode)) { frame.m_attributes.push_back(longName); frame.m_attributeTypes.push_back(Frame::kNormal); } } MFnEnumAttribute fn; MObject attribute = fn.create(longName, shortName, MFnData::kString); while(*strings) { fn.addField(*strings, *values); ++values; ++strings; } fn.setDefault(0); MStatus status = applyAttributeFlags(fn, flags); if(!status) throw status; return attribute; } //---------------------------------------------------------------------------------------------------------------------- MObject NodeHelper::addMeshAttr(const char* longName, const char* shortName, uint32_t flags) { MFnTypedAttribute fn; MStatus status; MObject attr = fn.create(longName, shortName, MFnData::kMesh, MObject::kNullObj, &status); if(!status) throw status; status = applyAttributeFlags(fn, flags); if(!status) throw status; return attr; } //---------------------------------------------------------------------------------------------------------------------- MObject NodeHelper::addStringAttr(const char* longName, const char* shortName, uint32_t flags, bool forceShow) { return addStringAttr(longName, shortName, "", flags, forceShow); } //---------------------------------------------------------------------------------------------------------------------- MObject NodeHelper::addStringAttr(const char* longName, const char* shortName, const char* defaultValue, uint32_t flags, bool forceShow) { if(m_internal) { Frame& frame = *m_internal->m_frames.begin(); if(forceShow || ((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode))) { frame.m_attributes.push_back(longName); frame.m_attributeTypes.push_back(Frame::kNormal); } } MFnTypedAttribute fn; MFnStringData stringData; MStatus stat; MObject attribute = fn.create(longName, shortName, MFnData::kString, stringData.create(MString(defaultValue), &stat)); MStatus status = applyAttributeFlags(fn, flags); if(!status) throw status; return attribute; } //---------------------------------------------------------------------------------------------------------------------- MObject NodeHelper::addFilePathAttr(const char* longName, const char* shortName, uint32_t flags, FileMode fileMode, const char* fileFilter) { if(m_internal) { Frame& frame = *m_internal->m_frames.begin(); if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode)) { frame.m_attributes.push_back(longName); frame.m_fileFilters.push_back(fileFilter); frame.m_attributeTypes.push_back((Frame::AttributeUiType)fileMode); } } MFnTypedAttribute fn; MObject attribute = fn.create(longName, shortName, MFnData::kString); MStatus status = applyAttributeFlags(fn, flags); if(!status) throw status; return attribute; } //---------------------------------------------------------------------------------------------------------------------- MObject NodeHelper::addInt8Attr(const char* longName, const char* shortName, int8_t defaultValue, uint32_t flags) { if(m_internal) { Frame& frame = *m_internal->m_frames.begin(); if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode)) { frame.m_attributes.push_back(longName); frame.m_attributeTypes.push_back(Frame::kNormal); } } MFnNumericAttribute fn; MObject attribute = fn.create(longName, shortName, MFnNumericData::kChar, defaultValue); MStatus status = applyAttributeFlags(fn, flags); if(!status) throw status; return attribute; } //---------------------------------------------------------------------------------------------------------------------- MObject NodeHelper::addInt16Attr(const char* longName, const char* shortName, int16_t defaultValue, uint32_t flags) { if(m_internal) { Frame& frame = *m_internal->m_frames.begin(); if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode)) { frame.m_attributes.push_back(longName); frame.m_attributeTypes.push_back(Frame::kNormal); } } MFnNumericAttribute fn; MObject attribute = fn.create(longName, shortName, MFnNumericData::kShort, defaultValue); MStatus status = applyAttributeFlags(fn, flags); if(!status) throw status; return attribute; } //---------------------------------------------------------------------------------------------------------------------- MObject NodeHelper::addInt32Attr(const char* longName, const char* shortName, int32_t defaultValue, uint32_t flags) { if(m_internal) { Frame& frame = *m_internal->m_frames.begin(); if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode)) { frame.m_attributes.push_back(longName); frame.m_attributeTypes.push_back(Frame::kNormal); } } MFnNumericAttribute fn; MObject attribute = fn.create(longName, shortName, MFnNumericData::kInt, defaultValue); MStatus status = applyAttributeFlags(fn, flags); if(!status) throw status; return attribute; } //---------------------------------------------------------------------------------------------------------------------- MObject NodeHelper::addInt64Attr(const char* longName, const char* shortName, int64_t defaultValue, uint32_t flags) { if(m_internal) { Frame& frame = *m_internal->m_frames.begin(); if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode)) { frame.m_attributes.push_back(longName); frame.m_attributeTypes.push_back(Frame::kNormal); } } MFnNumericAttribute fn; MObject attribute = fn.create(longName, shortName, MFnNumericData::kInt64, defaultValue); MStatus status = applyAttributeFlags(fn, flags); if(!status) throw status; return attribute; } //---------------------------------------------------------------------------------------------------------------------- MObject NodeHelper::addFloatAttr(const char* longName, const char* shortName, float defaultValue, uint32_t flags) { if(m_internal) { Frame& frame = *m_internal->m_frames.begin(); if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode)) { frame.m_attributes.push_back(longName); frame.m_attributeTypes.push_back(Frame::kNormal); } } MFnNumericAttribute fn; MObject attribute = fn.create(longName, shortName, MFnNumericData::kFloat, defaultValue); MStatus status = applyAttributeFlags(fn, flags); if(!status) throw status; return attribute; } //---------------------------------------------------------------------------------------------------------------------- MObject NodeHelper::addTimeAttr(const char* longName, const char* shortName, const MTime& defaultValue, uint32_t flags) { if(m_internal) { Frame& frame = *m_internal->m_frames.begin(); if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode)) { frame.m_attributes.push_back(longName); frame.m_attributeTypes.push_back(Frame::kNormal); } } MFnUnitAttribute fn; MObject attribute = fn.create(longName, shortName, defaultValue); MStatus status = applyAttributeFlags(fn, flags); if(!status) throw status; return attribute; } //---------------------------------------------------------------------------------------------------------------------- MObject NodeHelper::addDistanceAttr(const char* longName, const char* shortName, const MDistance& defaultValue, uint32_t flags) { if(m_internal) { Frame& frame = *m_internal->m_frames.begin(); if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode)) { frame.m_attributes.push_back(longName); frame.m_attributeTypes.push_back(Frame::kNormal); } } MFnUnitAttribute fn; MObject attribute = fn.create(longName, shortName, defaultValue); MStatus status = applyAttributeFlags(fn, flags); if(!status) throw status; return attribute; } //---------------------------------------------------------------------------------------------------------------------- MObject NodeHelper::addAngleAttr(const char* longName, const char* shortName, const MAngle& defaultValue, uint32_t flags) { if(m_internal) { Frame& frame = *m_internal->m_frames.begin(); if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode)) { frame.m_attributes.push_back(longName); frame.m_attributeTypes.push_back(Frame::kNormal); } } MFnUnitAttribute fn; MObject attribute = fn.create(longName, shortName, defaultValue); MStatus status = applyAttributeFlags(fn, flags); if(!status) throw status; return attribute; } //---------------------------------------------------------------------------------------------------------------------- MObject NodeHelper::addFloatArrayAttr(const MObject& node, const char* longName, const char* shortName, uint32_t flags) { if(m_internal) { Frame& frame = *m_internal->m_frames.begin(); if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode)) { frame.m_attributes.push_back(longName); frame.m_attributeTypes.push_back(Frame::kNormal); } } MStatus status; MFnTypedAttribute fnAttr; MString ln (longName); MString sn (shortName); MObject attribute = fnAttr.create(ln, sn, MFnData::kFloatArray, MObject::kNullObj, &status); if(status != MS::kSuccess) { MGlobal::displayWarning("addFloatArrayAttr:Failed to create attribute"); } applyAttributeFlags(fnAttr, flags); MFnDependencyNode fn(node, &status); if(!status) { throw status; } status = fn.addAttribute(attribute); if(status != MS::kSuccess) MGlobal::displayWarning(MString("addFloatArrayAttr::addAttribute: ") + MString(status.errorString())); return attribute; } //---------------------------------------------------------------------------------------------------------------------- MObject NodeHelper::addDoubleAttr(const char* longName, const char* shortName, double defaultValue, uint32_t flags) { if(m_internal) { Frame& frame = *m_internal->m_frames.begin(); if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode)) { frame.m_attributes.push_back(longName); frame.m_attributeTypes.push_back(Frame::kNormal); } } MFnNumericAttribute fn; MObject attribute = fn.create(longName, shortName, MFnNumericData::kDouble, defaultValue); MStatus status = applyAttributeFlags(fn, flags); if(!status) throw status; return attribute; } //---------------------------------------------------------------------------------------------------------------------- MObject NodeHelper::addBoolAttr(const char* longName, const char* shortName, bool defaultValue, uint32_t flags) { if(m_internal) { Frame& frame = *m_internal->m_frames.begin(); if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode)) { frame.m_attributes.push_back(longName); frame.m_attributeTypes.push_back(Frame::kNormal); } } MFnNumericAttribute fn; MObject attribute = fn.create(longName, shortName, MFnNumericData::kBoolean, defaultValue); MStatus status = applyAttributeFlags(fn, flags); if(!status) throw status; return attribute; } //---------------------------------------------------------------------------------------------------------------------- MObject NodeHelper::addFloat3Attr(const char* longName, const char* shortName, float defaultX, float defaultY, float defaultZ, uint32_t flags) { if(m_internal) { Frame& frame = *m_internal->m_frames.begin(); if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode)) { frame.m_attributes.push_back(longName); frame.m_attributeTypes.push_back(Frame::kNormal); } } MFnNumericAttribute fn; MObject attribute; if(flags & kColour) { attribute = fn.createColor(longName, shortName); fn.setDefault(defaultX, defaultY, defaultZ); } else { MString ln(longName); MString sn(shortName); MObject x = fn.create(ln + "X", sn + "x", MFnNumericData::kFloat, defaultX); MObject y = fn.create(ln + "Y", sn + "y", MFnNumericData::kFloat, defaultY); MObject z = fn.create(ln + "Z", sn + "z", MFnNumericData::kFloat, defaultZ); attribute = fn.create(ln, sn, x, y, z); } MStatus status = applyAttributeFlags(fn, flags); if(!status) throw status; return attribute; } //---------------------------------------------------------------------------------------------------------------------- MObject NodeHelper::addPointAttr(const char* longName, const char* shortName, const MPoint& defaultValue, uint32_t flags) { if(m_internal) { Frame& frame = *m_internal->m_frames.begin(); if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode)) { frame.m_attributes.push_back(longName); frame.m_attributeTypes.push_back(Frame::kNormal); } } MFnNumericAttribute fn; MObject attribute; attribute = fn.createPoint(longName, shortName); fn.setDefault(defaultValue.x, defaultValue.y, defaultValue.z); MStatus status = applyAttributeFlags(fn, flags); if(!status) throw status; return attribute; } //---------------------------------------------------------------------------------------------------------------------- MObject NodeHelper::addVectorAttr(const char* longName, const char* shortName, const MVector& defaultValue, uint32_t flags) { if(m_internal) { Frame& frame = *m_internal->m_frames.begin(); if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode)) { frame.m_attributes.push_back(longName); frame.m_attributeTypes.push_back(Frame::kNormal); } } MFnNumericAttribute fn; MObject attribute; MString ln(longName); MString sn(shortName); MObject x = fn.create(ln + "X", sn + "x", MFnNumericData::kDouble, defaultValue.x); MObject y = fn.create(ln + "Y", sn + "y", MFnNumericData::kDouble, defaultValue.y); MObject z = fn.create(ln + "Z", sn + "z", MFnNumericData::kDouble, defaultValue.z); attribute = fn.create(ln, sn, x, y, z); MStatus status = applyAttributeFlags(fn, flags); if(!status) throw status; return attribute; } //---------------------------------------------------------------------------------------------------------------------- MObject NodeHelper::addAngle3Attr(const char* longName, const char* shortName, float defaultX, float defaultY, float defaultZ, uint32_t flags) { if(m_internal) { Frame& frame = *m_internal->m_frames.begin(); if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode)) { frame.m_attributes.push_back(longName); frame.m_attributeTypes.push_back(Frame::kNormal); } } MFnUnitAttribute fnu; MFnNumericAttribute fn; MObject attribute; MString ln(longName); MString sn(shortName); MObject x = fnu.create(ln + "X", sn + "x", MFnUnitAttribute::kAngle, defaultX); MObject y = fnu.create(ln + "Y", sn + "y", MFnUnitAttribute::kAngle, defaultY); MObject z = fnu.create(ln + "Z", sn + "z", MFnUnitAttribute::kAngle, defaultZ); attribute = fn.create(ln, sn, x, y, z); MStatus status = applyAttributeFlags(fn, flags); if(!status) throw status; return attribute; } //---------------------------------------------------------------------------------------------------------------------- MObject NodeHelper::addDistance3Attr(const char* longName, const char* shortName, float defaultX, float defaultY, float defaultZ, uint32_t flags) { if(m_internal) { Frame& frame = *m_internal->m_frames.begin(); if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode)) { frame.m_attributes.push_back(longName); frame.m_attributeTypes.push_back(Frame::kNormal); } } MFnUnitAttribute fnu; MFnNumericAttribute fn; MObject attribute; MString ln(longName); MString sn(shortName); MObject x = fnu.create(ln + "X", sn + "x", MFnUnitAttribute::kDistance, defaultX); MObject y = fnu.create(ln + "Y", sn + "y", MFnUnitAttribute::kDistance, defaultY); MObject z = fnu.create(ln + "Z", sn + "z", MFnUnitAttribute::kDistance, defaultZ); attribute = fn.create(ln, sn, x, y, z); MStatus status = applyAttributeFlags(fn, flags); if(!status) throw status; return attribute; } //---------------------------------------------------------------------------------------------------------------------- MObject NodeHelper::addMatrixAttr(const char* longName, const char* shortName, const MMatrix& defaultValue, uint32_t flags) { if(m_internal) { Frame& frame = *m_internal->m_frames.begin(); if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode)) { frame.m_attributes.push_back(longName); frame.m_attributeTypes.push_back(Frame::kNormal); } } MFnMatrixAttribute fn; MObject attribute; attribute = fn.create(longName, shortName, MFnMatrixAttribute::kDouble); fn.setDefault(defaultValue); MStatus status = applyAttributeFlags(fn, flags); if(!status) throw status; return attribute; } //---------------------------------------------------------------------------------------------------------------------- MObject NodeHelper::addMatrix3x3Attr(const char* longName, const char* shortName, const float defaultValue[3][3], uint32_t flags) { if(m_internal) { Frame& frame = *m_internal->m_frames.begin(); if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode)) { frame.m_attributes.push_back(longName); frame.m_attributeTypes.push_back(Frame::kNormal); } } MFnNumericAttribute fn; MFnCompoundAttribute fnc; MString ln(longName); MString sn(shortName); MObject xx = fn.create(ln + "XX", sn + "xx", MFnNumericData::kFloat, defaultValue[0][0]); MObject xy = fn.create(ln + "XY", sn + "xy", MFnNumericData::kFloat, defaultValue[0][1]); MObject xz = fn.create(ln + "XZ", sn + "xz", MFnNumericData::kFloat, defaultValue[0][2]); MObject yx = fn.create(ln + "YX", sn + "yx", MFnNumericData::kFloat, defaultValue[1][0]); MObject yy = fn.create(ln + "YY", sn + "yy", MFnNumericData::kFloat, defaultValue[1][1]); MObject yz = fn.create(ln + "YZ", sn + "yz", MFnNumericData::kFloat, defaultValue[1][2]); MObject zx = fn.create(ln + "ZX", sn + "zx", MFnNumericData::kFloat, defaultValue[2][0]); MObject zy = fn.create(ln + "ZY", sn + "zy", MFnNumericData::kFloat, defaultValue[2][1]); MObject zz = fn.create(ln + "ZZ", sn + "zz", MFnNumericData::kFloat, defaultValue[2][2]); MObject x = fnc.create(ln + "X", sn + "x"); fnc.addChild(xx); fnc.addChild(xy); fnc.addChild(xz); MObject y = fnc.create(ln + "Y", sn + "y"); fnc.addChild(yx); fnc.addChild(yy); fnc.addChild(yz); MObject z = fnc.create(ln + "Z", sn + "z"); fnc.addChild(zx); fnc.addChild(zy); fnc.addChild(zz); MObject attribute = fnc.create(ln, sn); fnc.addChild(x); fnc.addChild(y); fnc.addChild(z); MStatus status = applyAttributeFlags(fnc, flags); if(!status) throw status; return attribute; } //---------------------------------------------------------------------------------------------------------------------- MObject NodeHelper::addMatrix2x2Attr(const char* longName, const char* shortName, const float defaultValue[2][2], uint32_t flags) { if(m_internal) { Frame& frame = *m_internal->m_frames.begin(); if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode)) { frame.m_attributes.push_back(longName); frame.m_attributeTypes.push_back(Frame::kNormal); } } MFnNumericAttribute fn; MFnCompoundAttribute fnc; MString ln(longName); MString sn(shortName); MObject xx = fn.create(ln + "XX", sn + "xx", MFnNumericData::kFloat, defaultValue[0][0]); MObject xy = fn.create(ln + "XY", sn + "xy", MFnNumericData::kFloat, defaultValue[0][1]); MObject yx = fn.create(ln + "YX", sn + "yx", MFnNumericData::kFloat, defaultValue[1][0]); MObject yy = fn.create(ln + "YY", sn + "yy", MFnNumericData::kFloat, defaultValue[1][1]); MObject x = fnc.create(ln + "X", sn + "x"); fnc.addChild(xx); fnc.addChild(xy); MObject y = fnc.create(ln + "Y", sn + "y"); fnc.addChild(yx); fnc.addChild(yy); MObject attribute = fnc.create(ln, sn); fnc.addChild(x); fnc.addChild(y); MStatus status = applyAttributeFlags(fnc, flags); if(!status) throw status; return attribute; } //---------------------------------------------------------------------------------------------------------------------- MObject NodeHelper::addDataAttr(const char* longName, const char* shortName, MFnData::Type type, uint32_t flags, MFnAttribute::DisconnectBehavior behaviour) { MFnTypedAttribute fn; MObject attribute = fn.create(longName, shortName, type); fn.setDisconnectBehavior(behaviour); MStatus status = applyAttributeFlags(fn, flags | kHidden); if(!status) throw status; return attribute; } //---------------------------------------------------------------------------------------------------------------------- MObject NodeHelper::addDataAttr(const char* longName, const char* shortName, const MTypeId& type, uint32_t flags, MFnAttribute::DisconnectBehavior behaviour) { MFnTypedAttribute fn; MObject attribute = fn.create(longName, shortName, type); fn.setDisconnectBehavior(behaviour); MStatus status = applyAttributeFlags(fn, flags | kHidden); if(!status) throw status; return attribute; } //---------------------------------------------------------------------------------------------------------------------- MObject NodeHelper::addMessageAttr(const char* longName, const char* shortName, uint32_t flags) { MFnMessageAttribute fn; MStatus status; MObject attribute = fn.create(longName, shortName, &status); status = applyAttributeFlags(fn, flags | kHidden); if(!status) throw status; return attribute; } //---------------------------------------------------------------------------------------------------------------------- MObject NodeHelper::addVec2fAttr(const char* longName, const char* shortName, uint32_t flags) { if(m_internal) { Frame& frame = *m_internal->m_frames.begin(); if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode)) { frame.m_attributes.push_back(longName); frame.m_attributeTypes.push_back(Frame::kNormal); } } MFnNumericAttribute fn; MObject attribute; MString ln(longName); MString sn(shortName); MObject x = fn.create(ln + "X", sn + "x", MFnNumericData::kFloat, 0); MObject y = fn.create(ln + "Y", sn + "y", MFnNumericData::kFloat, 0); attribute = fn.create(ln, sn, x, y); MStatus status = applyAttributeFlags(fn, flags); if(!status) throw status; return attribute; } //---------------------------------------------------------------------------------------------------------------------- MObject NodeHelper::addVec2iAttr(const char* longName, const char* shortName, uint32_t flags) { if(m_internal) { Frame& frame = *m_internal->m_frames.begin(); if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode)) { frame.m_attributes.push_back(longName); frame.m_attributeTypes.push_back(Frame::kNormal); } } MFnNumericAttribute fn; MObject attribute; MString ln(longName); MString sn(shortName); MObject x = fn.create(ln + "X", sn + "x", MFnNumericData::kLong, 0); MObject y = fn.create(ln + "Y", sn + "y", MFnNumericData::kLong, 0); attribute = fn.create(ln, sn, x, y); MStatus status = applyAttributeFlags(fn, flags); if(!status) throw status; return attribute; } //---------------------------------------------------------------------------------------------------------------------- MObject NodeHelper::addVec2dAttr(const char* longName, const char* shortName, uint32_t flags) { if(m_internal) { Frame& frame = *m_internal->m_frames.begin(); if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode)) { frame.m_attributes.push_back(longName); frame.m_attributeTypes.push_back(Frame::kNormal); } } MFnNumericAttribute fn; MObject attribute; MString ln(longName); MString sn(shortName); MObject x = fn.create(ln + "X", sn + "x", MFnNumericData::kDouble, 0); MObject y = fn.create(ln + "Y", sn + "y", MFnNumericData::kDouble, 0); attribute = fn.create(ln, sn, x, y); MStatus status = applyAttributeFlags(fn, flags); if(!status) throw status; return attribute; } //---------------------------------------------------------------------------------------------------------------------- MObject NodeHelper::addDoubleArrayAttr(const MObject& node, const char* longName, const char* shortName, uint32_t flags) { if(m_internal) { Frame& frame = *m_internal->m_frames.begin(); if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode)) { frame.m_attributes.push_back(longName); frame.m_attributeTypes.push_back(Frame::kNormal); } } MStatus status; MFnTypedAttribute fnAttr; MString ln (longName); MString sn (shortName); MObject attribute = fnAttr.create(ln, sn, MFnData::kDoubleArray, MObject::kNullObj, &status); if(status != MS::kSuccess) { MGlobal::displayWarning("addDoubleArrayAttr:Failed to create attribute"); } applyAttributeFlags(fnAttr, flags); MFnDependencyNode fn(node, &status); if(!status) { throw status; } status = fn.addAttribute(attribute); if(status != MS::kSuccess) MGlobal::displayWarning(MString("addDoubleArrayAttr::addAttribute: ") + MString(status.errorString())); return attribute; } //---------------------------------------------------------------------------------------------------------------------- MObject NodeHelper::addVec3fAttr(const char* longName, const char* shortName, uint32_t flags) { if(m_internal) { Frame& frame = *m_internal->m_frames.begin(); if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode)) { frame.m_attributes.push_back(longName); frame.m_attributeTypes.push_back(Frame::kNormal); } } MFnNumericAttribute fn; MObject attribute; MString ln(longName); MString sn(shortName); MObject x = fn.create(ln + "X", sn + "x", MFnNumericData::kFloat, 0); MObject y = fn.create(ln + "Y", sn + "y", MFnNumericData::kFloat, 0); MObject z = fn.create(ln + "Z", sn + "z", MFnNumericData::kFloat, 0); attribute = fn.create(ln, sn, x, y, z); MStatus status = applyAttributeFlags(fn, flags); if(!status) throw status; return attribute; } //---------------------------------------------------------------------------------------------------------------------- MObject NodeHelper::addVec3iAttr(const char* longName, const char* shortName, uint32_t flags) { if(m_internal) { Frame& frame = *m_internal->m_frames.begin(); if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode)) { frame.m_attributes.push_back(longName); frame.m_attributeTypes.push_back(Frame::kNormal); } } MFnNumericAttribute fn; MObject attribute; MString ln(longName); MString sn(shortName); MObject x = fn.create(ln + "X", sn + "x", MFnNumericData::kInt, 0); MObject y = fn.create(ln + "Y", sn + "y", MFnNumericData::kInt, 0); MObject z = fn.create(ln + "Z", sn + "z", MFnNumericData::kInt, 0); attribute = fn.create(ln, sn, x, y, z); MStatus status = applyAttributeFlags(fn, flags); if(!status) throw status; return attribute; } //---------------------------------------------------------------------------------------------------------------------- MObject NodeHelper::addVec3dAttr(const char* longName, const char* shortName, uint32_t flags) { if(m_internal) { Frame& frame = *m_internal->m_frames.begin(); if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode)) { frame.m_attributes.push_back(longName); frame.m_attributeTypes.push_back(Frame::kNormal); } } MFnNumericAttribute fn; MObject attribute; MString ln(longName); MString sn(shortName); MObject x = fn.create(ln + "X", sn + "x", MFnNumericData::kDouble, 0); MObject y = fn.create(ln + "Y", sn + "y", MFnNumericData::kDouble, 0); MObject z = fn.create(ln + "Z", sn + "z", MFnNumericData::kDouble, 0); attribute = fn.create(ln, sn, x, y, z); MStatus status = applyAttributeFlags(fn, flags); if(!status) throw status; return attribute; } //---------------------------------------------------------------------------------------------------------------------- MObject NodeHelper::addVec4fAttr(const char* longName, const char* shortName, uint32_t flags) { if(m_internal) { Frame& frame = *m_internal->m_frames.begin(); if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode)) { frame.m_attributes.push_back(longName); frame.m_attributeTypes.push_back(Frame::kNormal); } } MFnNumericAttribute fn; MFnCompoundAttribute fnc; MObject attribute; MString ln(longName); MString sn(shortName); MObject x = fn.create(ln + "X", sn + "x", MFnNumericData::kFloat, 0); MObject y = fn.create(ln + "Y", sn + "y", MFnNumericData::kFloat, 0); MObject z = fn.create(ln + "Z", sn + "z", MFnNumericData::kFloat, 0); MObject w = fn.create(ln + "W", sn + "w", MFnNumericData::kFloat, 0); attribute = fnc.create(ln, sn); AL_MAYA_CHECK_ERROR2(fnc.addChild(x), "could not add x"); AL_MAYA_CHECK_ERROR2(fnc.addChild(y), "could not add y"); AL_MAYA_CHECK_ERROR2(fnc.addChild(z), "could not add z"); AL_MAYA_CHECK_ERROR2(fnc.addChild(w), "could not add w"); MStatus status = applyAttributeFlags(fnc, flags); if(!status) throw status; return attribute; } //---------------------------------------------------------------------------------------------------------------------- MObject NodeHelper::addVec4iAttr(const char* longName, const char* shortName, uint32_t flags) { if(m_internal) { Frame& frame = *m_internal->m_frames.begin(); if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode)) { frame.m_attributes.push_back(longName); frame.m_attributeTypes.push_back(Frame::kNormal); } } MFnNumericAttribute fn; MFnCompoundAttribute fnc; MObject attribute; MString ln(longName); MString sn(shortName); MObject x = fn.create(ln + "X", sn + "x", MFnNumericData::kLong, 0); MObject y = fn.create(ln + "Y", sn + "y", MFnNumericData::kLong, 0); MObject z = fn.create(ln + "Z", sn + "z", MFnNumericData::kLong, 0); MObject w = fn.create(ln + "W", sn + "w", MFnNumericData::kLong, 0); attribute = fnc.create(ln, sn); AL_MAYA_CHECK_ERROR2(fnc.addChild(x), "could not add x"); AL_MAYA_CHECK_ERROR2(fnc.addChild(y), "could not add y"); AL_MAYA_CHECK_ERROR2(fnc.addChild(z), "could not add z"); AL_MAYA_CHECK_ERROR2(fnc.addChild(w), "could not add w"); MStatus status = applyAttributeFlags(fnc, flags); if(!status) throw status; return attribute; } //---------------------------------------------------------------------------------------------------------------------- MObject NodeHelper::addVec4dAttr(const char* longName, const char* shortName, uint32_t flags) { if(m_internal) { Frame& frame = *m_internal->m_frames.begin(); if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode)) { frame.m_attributes.push_back(longName); frame.m_attributeTypes.push_back(Frame::kNormal); } } MFnNumericAttribute fn; MFnCompoundAttribute fnc; MObject attribute; MString ln(longName); MString sn(shortName); MObject x = fn.create(ln + "X", sn + "x", MFnNumericData::kDouble, 0); MObject y = fn.create(ln + "Y", sn + "y", MFnNumericData::kDouble, 0); MObject z = fn.create(ln + "Z", sn + "z", MFnNumericData::kDouble, 0); MObject w = fn.create(ln + "W", sn + "w", MFnNumericData::kDouble, 0); attribute = fnc.create(ln, sn); AL_MAYA_CHECK_ERROR2(fnc.addChild(x), "could not add x"); AL_MAYA_CHECK_ERROR2(fnc.addChild(y), "could not add y"); AL_MAYA_CHECK_ERROR2(fnc.addChild(z), "could not add z"); AL_MAYA_CHECK_ERROR2(fnc.addChild(w), "could not add w"); MStatus status = applyAttributeFlags(fnc, flags); if(!status) throw status; return attribute; } //---------------------------------------------------------------------------------------------------------------------- MObject NodeHelper::addCompoundAttr(const char* longName, const char* shortName, uint32_t flags, std::initializer_list<MObject> objs) { if(m_internal) { Frame& frame = *m_internal->m_frames.begin(); if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode)) { frame.m_attributes.push_back(longName); frame.m_attributeTypes.push_back(Frame::kNormal); } } MFnCompoundAttribute fn; MObject obj = fn.create(longName, shortName); for(auto it : objs) { MStatus status = fn.addChild(it); if(!status) throw status; } MStatus status = applyAttributeFlags(fn, flags); if(!status) throw status; return obj; } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelper::applyAttributeFlags(MFnAttribute& fn, uint32_t flags) { const char* const errorString = "NodeHelper::applyAttributeFlags"; AL_MAYA_CHECK_ERROR(fn.setCached((flags & kCached) != 0), errorString); AL_MAYA_CHECK_ERROR(fn.setReadable((flags & kReadable) != 0), errorString); AL_MAYA_CHECK_ERROR(fn.setStorable((flags & kStorable) != 0), errorString); AL_MAYA_CHECK_ERROR(fn.setWritable((flags & kWritable) != 0), errorString); AL_MAYA_CHECK_ERROR(fn.setAffectsAppearance((flags & kAffectsAppearance) != 0), errorString); AL_MAYA_CHECK_ERROR(fn.setKeyable((flags & kKeyable) != 0), errorString); AL_MAYA_CHECK_ERROR(fn.setConnectable((flags & kConnectable) != 0), errorString); AL_MAYA_CHECK_ERROR(fn.setArray((flags & kArray) != 0), errorString); AL_MAYA_CHECK_ERROR(fn.setUsedAsColor((flags & kColour) != 0), errorString); AL_MAYA_CHECK_ERROR(fn.setHidden((flags & kHidden) != 0), errorString); AL_MAYA_CHECK_ERROR(fn.setInternal((flags & kInternal) != 0), errorString); AL_MAYA_CHECK_ERROR(fn.setAffectsWorldSpace((flags & kAffectsWorldSpace) != 0), errorString); AL_MAYA_CHECK_ERROR(fn.setUsesArrayDataBuilder((flags & kUsesArrayDataBuilder) != 0), errorString); if(!(flags & (kDynamic | kDontAddToNode))) { MStatus status = MPxNode::addAttribute(fn.object()); if(!status) throw status; } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- void NodeHelper::generateAETemplate() { assert(m_internal); // first hunt down all of the call custom attributes and generate the custom AE templates. This needs to be done before // we generate the main template procedure (these are all global methods). std::ostringstream oss; auto it = m_internal->m_frames.rbegin(); auto end = m_internal->m_frames.rend(); for(; it != end; ++it) { size_t fileIndex = 0; for(size_t i = 0; i < it->m_attributes.size(); ++i) { switch(it->m_attributeTypes[i]) { case Frame::kLoadFilePath: case Frame::kSaveFilePath: case Frame::kDirPathWithFiles: case Frame::kDirPath: case Frame::kMultiLoadFilePath: constructFilePathUi(oss, m_internal->m_typeBeingRegistered, it->m_attributes[i], it->m_fileFilters[fileIndex++], (FileMode)it->m_attributeTypes[i]); break; default: break; } } } // start generating our AE template, and ensure it's wrapped in a scroll layout. oss << "global proc AE" << m_internal->m_typeBeingRegistered << "Template(string $nodeName) {\n"; oss << " editorTemplate -beginScrollLayout;\n"; // loop through each collapsible frame it = m_internal->m_frames.rbegin(); for(; it != end; ++it) { // frame layout begin! oss << " editorTemplate -beginLayout \"" << it->m_title << "\" -collapse 0;\n"; for(size_t i = 0; i < it->m_attributes.size(); ++i) { switch(it->m_attributeTypes[i]) { // If we have a file path attribute, use the custom callbacks case Frame::kLoadFilePath: case Frame::kSaveFilePath: case Frame::kDirPathWithFiles: case Frame::kDirPath: case Frame::kMultiLoadFilePath: oss << " editorTemplate -callCustom \"AE" << m_internal->m_typeBeingRegistered << "Template_" << it->m_attributes[i] << "New\" " << "\"AE" << m_internal->m_typeBeingRegistered << "Template_" << it->m_attributes[i] << "Replace\" \"" << it->m_attributes[i] << "\";\n"; break; // for all other attributes, just add a normal control default: oss << " editorTemplate -addControl \"" << it->m_attributes[i] << "\";\n"; break; } } oss << " editorTemplate -endLayout;\n"; } // add all of our base templates that have been added for(size_t i = 0; i < m_internal->m_baseTemplates.size(); ++i) { oss << " " << m_internal->m_baseTemplates[i] << " $nodeName;\n"; } // finish off the call by adding in the custom attributes section oss << " editorTemplate -addExtraControls;\n"; oss << " editorTemplate -endScrollLayout;\n"; oss << "}\n"; if (AL_MAYAUTILS_DEBUG) { std::cout << oss.str() + "\n" << std::endl; } // run our script (AE template command will now exist in memory) MGlobal::executeCommand(MString(oss.str().c_str(), oss.str().size())); // get rid of our internal rubbish. delete m_internal; m_internal = 0; } #define report_get_error(attribute, type, status) \ { \ MFnAttribute fn(attribute); \ std::cerr << "Unable to get attribute \"" << fn.name().asChar() << "\" of type " << #type << std::endl; \ std::cerr << " - " << status.errorString().asChar() << std::endl; \ } //---------------------------------------------------------------------------------------------------------------------- bool NodeHelper::inputBoolValue(MDataBlock& dataBlock, const MObject& attribute) { MStatus status; MDataHandle inDataHandle = dataBlock.inputValue(attribute, &status); if(status) { return inDataHandle.asBool(); } report_get_error(attribute, bool, status); return false; } //---------------------------------------------------------------------------------------------------------------------- int8_t NodeHelper::inputInt8Value(MDataBlock& dataBlock, const MObject& attribute) { MStatus status; MDataHandle inDataHandle = dataBlock.inputValue(attribute, &status); if(status) { return inDataHandle.asChar(); } report_get_error(attribute, int8_t, status); return 0; } //---------------------------------------------------------------------------------------------------------------------- int16_t NodeHelper::inputInt16Value(MDataBlock& dataBlock, const MObject& attribute) { MStatus status; MDataHandle inDataHandle = dataBlock.inputValue(attribute, &status); if(status) { return inDataHandle.asShort(); } report_get_error(attribute, int16_t, status); return 0; } //---------------------------------------------------------------------------------------------------------------------- int32_t NodeHelper::inputInt32Value(MDataBlock& dataBlock, const MObject& attribute) { MStatus status; MDataHandle inDataHandle = dataBlock.inputValue(attribute, &status); if(status) { return inDataHandle.asInt(); } report_get_error(attribute, int32_t, status); return 0; } //---------------------------------------------------------------------------------------------------------------------- int64_t NodeHelper::inputInt64Value(MDataBlock& dataBlock, const MObject& attribute) { MStatus status; MDataHandle inDataHandle = dataBlock.inputValue(attribute, &status); if(status) { return inDataHandle.asInt64(); } report_get_error(attribute, int64_t, status); return 0; } //---------------------------------------------------------------------------------------------------------------------- float NodeHelper::inputFloatValue(MDataBlock& dataBlock, const MObject& attribute) { MStatus status; MDataHandle inDataHandle = dataBlock.inputValue(attribute, &status); if(status) { return inDataHandle.asFloat(); } report_get_error(attribute, float, status); return 0; } //---------------------------------------------------------------------------------------------------------------------- double NodeHelper::inputDoubleValue(MDataBlock& dataBlock, const MObject& attribute) { MStatus status; MDataHandle inDataHandle = dataBlock.inputValue(attribute, &status); if(status) { return inDataHandle.asDouble(); } report_get_error(attribute, double, status); return 0; } //---------------------------------------------------------------------------------------------------------------------- MTime NodeHelper::inputTimeValue(MDataBlock& dataBlock, const MObject& attribute) { MStatus status; MDataHandle inDataHandle = dataBlock.inputValue(attribute, &status); if(status) { return inDataHandle.asTime(); } report_get_error(attribute, MTime, status); return MTime(); } //---------------------------------------------------------------------------------------------------------------------- MMatrix NodeHelper::inputMatrixValue(MDataBlock& dataBlock, const MObject& attribute) { MStatus status; MDataHandle inDataHandle = dataBlock.inputValue(attribute, &status); if(status) { return inDataHandle.asMatrix(); } report_get_error(attribute, MMatrix, status); return MMatrix(); } //---------------------------------------------------------------------------------------------------------------------- MPoint NodeHelper::inputPointValue(MDataBlock& dataBlock, const MObject& attribute) { MStatus status; MDataHandle inDataHandle = dataBlock.inputValue(attribute, &status); if(status) { const double3& v = inDataHandle.asDouble3(); return MPoint(v[0], v[1], v[2]); } report_get_error(attribute, MPoint, status); return MPoint(); } //---------------------------------------------------------------------------------------------------------------------- MFloatPoint NodeHelper::inputFloatPointValue(MDataBlock& dataBlock, const MObject& attribute) { MStatus status; MDataHandle inDataHandle = dataBlock.inputValue(attribute, &status); if(status) { const float3& v = inDataHandle.asFloat3(); return MFloatPoint(v[0], v[1], v[2]); } report_get_error(attribute, MFloatPoint, status); return MFloatPoint(); } //---------------------------------------------------------------------------------------------------------------------- MVector NodeHelper::inputVectorValue(MDataBlock& dataBlock, const MObject& attribute) { MStatus status; MDataHandle inDataHandle = dataBlock.inputValue(attribute, &status); if(status) { const double3& v = inDataHandle.asDouble3(); return MVector(v[0], v[1], v[2]); } report_get_error(attribute, MVector, status); return MVector(); } //---------------------------------------------------------------------------------------------------------------------- MFloatVector NodeHelper::inputFloatVectorValue(MDataBlock& dataBlock, const MObject& attribute) { MStatus status; MDataHandle inDataHandle = dataBlock.inputValue(attribute, &status); if(status) { const float3& v = inDataHandle.asFloat3(); return MFloatVector(v[0], v[1], v[2]); } report_get_error(attribute, MFloatVector, status); return MFloatVector(); } //---------------------------------------------------------------------------------------------------------------------- MString NodeHelper::inputStringValue(MDataBlock& dataBlock, const MObject& attribute) { MStatus status; MDataHandle inDataHandle = dataBlock.inputValue(attribute, &status); if(status) { return inDataHandle.asString(); } report_get_error(attribute, MString, status); return MString(); } //---------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------- MColor NodeHelper::inputColourValue(MDataBlock& dataBlock, const MObject& attribute) { MStatus status; MDataHandle inDataHandle = dataBlock.inputValue(attribute, &status); if(status) { const float3& v = inDataHandle.asFloat3(); return MColor(v[0], v[1], v[2]); } report_get_error(attribute, MColor, status); return MColor(); } //---------------------------------------------------------------------------------------------------------------------- MPxData* NodeHelper::inputDataValue(MDataBlock& dataBlock, const MObject& attribute) { MStatus status; MDataHandle inDataHandle = dataBlock.inputValue(attribute, &status); if(status) { return inDataHandle.asPluginData(); } report_get_error(attribute, MPxData, status); return 0; } #define report_set_error(attribute, type, status) \ { \ MFnAttribute fn(attribute); \ std::cerr << "Unable to set attribute \"" << fn.name().asChar() << "\" of type " << #type << std::endl; \ std::cerr << " - " << status.errorString().asChar() << std::endl; \ } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelper::outputBoolValue(MDataBlock& dataBlock, const MObject& attribute, const bool value) { MStatus status; MDataHandle outDataHandle = dataBlock.outputValue(attribute, &status); if(status) { outDataHandle.setBool(value); outDataHandle.setClean(); } else { report_set_error(attribute, bool, status); } return status; } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelper::outputInt8Value(MDataBlock& dataBlock, const MObject& attribute, const int8_t value) { MStatus status; MDataHandle outDataHandle = dataBlock.outputValue(attribute, &status); if(status) { outDataHandle.setChar(value); outDataHandle.setClean(); } else { report_set_error(attribute, int8_t, status); } return status; } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelper::outputInt16Value(MDataBlock& dataBlock, const MObject& attribute, const int16_t value) { MStatus status; MDataHandle outDataHandle = dataBlock.outputValue(attribute, &status); if(status) { outDataHandle.setShort(value); outDataHandle.setClean(); } else { report_set_error(attribute, int16_t, status); } return status; } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelper::outputInt32Value(MDataBlock& dataBlock, const MObject& attribute, const int32_t value) { MStatus status; MDataHandle outDataHandle = dataBlock.outputValue(attribute, &status); if(status) { outDataHandle.setInt(value); outDataHandle.setClean(); } else { report_set_error(attribute, int32_t, status); } return status; } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelper::outputInt64Value(MDataBlock& dataBlock, const MObject& attribute, const int64_t value) { MStatus status; MDataHandle outDataHandle = dataBlock.outputValue(attribute, &status); if(status) { outDataHandle.setInt64(value); outDataHandle.setClean(); } else { report_set_error(attribute, int64_t, status); } return status; } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelper::outputFloatValue(MDataBlock& dataBlock, const MObject& attribute, const float value) { MStatus status; MDataHandle outDataHandle = dataBlock.outputValue(attribute, &status); if(status) { outDataHandle.setFloat(value); outDataHandle.setClean(); } else { report_set_error(attribute, float, status); } return status; } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelper::outputDoubleValue(MDataBlock& dataBlock, const MObject& attribute, const double value) { MStatus status; MDataHandle outDataHandle = dataBlock.outputValue(attribute, &status); if(status) { outDataHandle.setDouble(value); outDataHandle.setClean(); } else { report_set_error(attribute, double, status); } return status; } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelper::outputMatrixValue(MDataBlock& dataBlock, const MObject& attribute, const MMatrix& value) { MStatus status; MDataHandle outDataHandle = dataBlock.outputValue(attribute, &status); if(status) { outDataHandle.setMMatrix(value); outDataHandle.setClean(); } else { report_set_error(attribute, MMatrix, status); } return status; } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelper::outputPointValue(MDataBlock& dataBlock, const MObject& attribute, const MPoint& value) { MStatus status; MDataHandle outDataHandle = dataBlock.outputValue(attribute, &status); if(status) { outDataHandle.set(value.x, value.y, value.z); outDataHandle.setClean(); } else { report_set_error(attribute, MPoint, status); } return status; } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelper::outputFloatPointValue(MDataBlock& dataBlock, const MObject& attribute, const MFloatPoint& value) { MStatus status; MDataHandle outDataHandle = dataBlock.outputValue(attribute, &status); if(status) { outDataHandle.set(value.x, value.y, value.z); outDataHandle.setClean(); } else { report_set_error(attribute, MFloatPoint, status); } return status; } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelper::outputVectorValue(MDataBlock& dataBlock, const MObject& attribute, const MVector& value) { MStatus status; MDataHandle outDataHandle = dataBlock.outputValue(attribute, &status); if(status) { outDataHandle.set(value.x, value.y, value.z); outDataHandle.setClean(); } else { report_set_error(attribute, MVector, status); } return status; } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelper::outputEulerValue(MDataBlock& dataBlock, const MObject& attribute, const MEulerRotation& value) { MStatus status; MDataHandle outDataHandle = dataBlock.outputValue(attribute, &status); if(status) { outDataHandle.set(value.x, value.y, value.z); outDataHandle.setClean(); } else { report_set_error(attribute, MEulerRotation, status); } return status; } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelper::outputFloatVectorValue(MDataBlock& dataBlock, const MObject& attribute, const MFloatVector& value) { MStatus status; MDataHandle outDataHandle = dataBlock.outputValue(attribute, &status); if(status) { outDataHandle.set(value.x, value.y, value.z); outDataHandle.setClean(); } else { report_set_error(attribute, MFloatVector, status); } return status; } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelper::outputColourValue(MDataBlock& dataBlock, const MObject& attribute, const MColor& value) { MStatus status; MDataHandle outDataHandle = dataBlock.outputValue(attribute, &status); if(status) { outDataHandle.set(value.r, value.g, value.b); outDataHandle.setClean(); } else { report_set_error(attribute, MColor, status); } return status; } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelper::outputStringValue(MDataBlock& dataBlock, const MObject& attribute, const MString& value) { MStatus status; MDataHandle outDataHandle = dataBlock.outputValue(attribute, &status); if(status) { outDataHandle.setString(value); outDataHandle.setClean(); } else { report_set_error(attribute, MString, status); } return status; } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelper::outputTimeValue(MDataBlock& dataBlock, const MObject& attribute, const MTime& value) { MStatus status; MDataHandle outDataHandle = dataBlock.outputValue(attribute, &status); if(status) { outDataHandle.set(value); outDataHandle.setClean(); } else { report_set_error(attribute, MTime, status); } return status; } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelper::outputDataValue(MDataBlock& dataBlock, const MObject& attribute, MPxData* value) { MStatus status; MDataHandle outDataHandle = dataBlock.outputValue(attribute, &status); if(status) { outDataHandle.set(value); outDataHandle.setClean(); } else { report_set_error(attribute, MPxData, status); } return status; } //---------------------------------------------------------------------------------------------------------------------- MPxData* NodeHelper::outputDataValue(MDataBlock& dataBlock, const MObject& attribute) { MStatus status; MDataHandle outDataHandle = dataBlock.outputValue(attribute, &status); if(status) { return outDataHandle.asPluginData(); } report_get_error(attribute, MPxData, status); return 0; } //---------------------------------------------------------------------------------------------------------------------- MPxData* NodeHelper::createData(const MTypeId& dataTypeId, MObject& data) { MStatus status; MFnPluginData pluginDataFactory; data = pluginDataFactory.create(dataTypeId, &status); if(!status) { std::cerr << "Unable to create data object of type id: " << dataTypeId.id() << ":" << dataTypeId.className() << std::endl; return 0; } return pluginDataFactory.data(); } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelper::addStringAttr(const MObject& node, const char* longName, const char* shortName, uint32_t flags, bool forceShow, MObject* attribute) { try { MStatus status; MFnDependencyNode fn(node, &status); if(!status) { throw status; } MObject attr = addStringAttr(longName, shortName, flags | kDynamic, forceShow); status = fn.addAttribute(attr); if(!status) { MGlobal::displayError(MString("Unable to add string attribute ") + longName + " to node " + fn.name()); throw status; } if(attribute) *attribute = attr; } catch(MStatus status) { return status; } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelper::addFilePathAttr(const MObject& node, const char* longName, const char* shortName, uint32_t flags, FileMode forSaving, const char* fileFilter, MObject* attribute) { try { MStatus status; MFnDependencyNode fn(node, &status); if(!status) { throw status; } MObject attr = addFilePathAttr(longName, shortName, flags | kDynamic, forSaving, fileFilter); status = fn.addAttribute(attr); if(!status) { MGlobal::displayError(MString("Unable to add filename attribute ") + longName + " to node " + fn.name()); throw status; } if(attribute) *attribute = attr; } catch(MStatus status) { return status; } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelper::addInt8Attr(const MObject& node, const char* longName, const char* shortName, int8_t defaultValue, uint32_t flags, MObject* attribute) { try { MStatus status; MFnDependencyNode fn(node, &status); if(!status) { throw status; } MObject attr = addInt8Attr(longName, shortName, defaultValue, flags | kDynamic); status = fn.addAttribute(attr); if(!status) { MGlobal::displayError(MString("Unable to add int attribute ") + longName + " to node " + fn.name()); throw status; } if(attribute) *attribute = attr; } catch(MStatus status) { return status; } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelper::addInt16Attr(const MObject& node, const char* longName, const char* shortName, int16_t defaultValue, uint32_t flags, MObject* attribute) { try { MStatus status; MFnDependencyNode fn(node, &status); if(!status) { throw status; } MObject attr = addInt16Attr(longName, shortName, defaultValue, flags | kDynamic); status = fn.addAttribute(attr); if(!status) { MGlobal::displayError(MString("Unable to add int attribute ") + longName + " to node " + fn.name()); throw status; } if(attribute) *attribute = attr; } catch(MStatus status) { return status; } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelper::addInt32Attr(const MObject& node, const char* longName, const char* shortName, int32_t defaultValue, uint32_t flags, MObject* attribute) { try { MStatus status; MFnDependencyNode fn(node, &status); if(!status) { throw status; } MObject attr = addInt32Attr(longName, shortName, defaultValue, flags | kDynamic); status = fn.addAttribute(attr); if(!status) { MGlobal::displayError(MString("Unable to add int attribute ") + longName + " to node " + fn.name()); throw status; } if(attribute) *attribute = attr; } catch(MStatus status) { return status; } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelper::addInt64Attr(const MObject& node, const char* longName, const char* shortName, int64_t defaultValue, uint32_t flags, MObject* attribute) { try { MStatus status; MFnDependencyNode fn(node, &status); if(!status) { throw status; } MObject attr = addInt64Attr(longName, shortName, defaultValue, flags | kDynamic); status = fn.addAttribute(attr); if(!status) { MGlobal::displayError(MString("Unable to add int attribute ") + longName + " to node " + fn.name()); throw status; } if(attribute) *attribute = attr; } catch(MStatus status) { return status; } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelper::addFloatAttr(const MObject& node, const char* longName, const char* shortName, float defaultValue, uint32_t flags, MObject* attribute) { try { MStatus status; MFnDependencyNode fn(node, &status); if(!status) { throw status; } MObject attr = addFloatAttr(longName, shortName, defaultValue, flags | kDynamic); status = fn.addAttribute(attr); if(!status) { MGlobal::displayError(MString("Unable to add float attribute ") + longName + " to node " + fn.name()); throw status; } if(attribute) *attribute = attr; } catch(MStatus status) { return status; } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelper::addDoubleAttr(const MObject& node, const char* longName, const char* shortName, double defaultValue, uint32_t flags, MObject* attribute) { try { MStatus status; MFnDependencyNode fn(node, &status); if(!status) { throw status; } MObject attr = addDoubleAttr(longName, shortName, defaultValue, flags | kDynamic); status = fn.addAttribute(attr); if(!status) { MGlobal::displayError(MString("Unable to add double attribute ") + longName + " to node " + fn.name()); throw status; } if(attribute) *attribute = attr; } catch(MStatus status) { return status; } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelper::addTimeAttr(const MObject& node, const char* longName, const char* shortName, const MTime& defaultValue, uint32_t flags, MObject* attribute) { try { MStatus status; MFnDependencyNode fn(node, &status); if(!status) { throw status; } MObject attr = addTimeAttr(longName, shortName, defaultValue, flags | kDynamic); status = fn.addAttribute(attr); if(!status) { MGlobal::displayError(MString("Unable to add time attribute ") + longName + " to node " + fn.name()); throw status; } if(attribute) *attribute = attr; } catch(MStatus status) { return status; } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelper::addDistanceAttr(const MObject& node, const char* longName, const char* shortName, const MDistance& defaultValue, uint32_t flags, MObject* attribute) { try { MStatus status; MFnDependencyNode fn(node, &status); if(!status) { throw status; } MObject attr = addDistanceAttr(longName, shortName, defaultValue, flags | kDynamic); status = fn.addAttribute(attr); if(!status) { MGlobal::displayError(MString("Unable to add distance attribute ") + longName + " to node " + fn.name()); throw status; } if(attribute) *attribute = attr; } catch(MStatus status) { return status; } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelper::addAngleAttr(const MObject& node, const char* longName, const char* shortName, const MAngle& defaultValue, uint32_t flags, MObject* attribute) { try { MStatus status; MFnDependencyNode fn(node, &status); if(!status) { throw status; } MObject attr = addAngleAttr(longName, shortName, defaultValue, flags | kDynamic); status = fn.addAttribute(attr); if(!status) { MGlobal::displayError(MString("Unable to add angle attribute ") + longName + " to node " + fn.name()); throw status; } if(attribute) *attribute = attr; } catch(MStatus status) { return status; } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelper::addBoolAttr(const MObject& node, const char* longName, const char* shortName, bool defaultValue, uint32_t flags, MObject* attribute) { try { MStatus status; MFnDependencyNode fn(node, &status); if(!status) { throw status; } MObject attr = addBoolAttr(longName, shortName, defaultValue, flags | kDynamic); status = fn.addAttribute(attr); if(!status) { MGlobal::displayError(MString("Unable to add bool attribute ") + longName + " to node " + fn.name()); throw status; } if(attribute) *attribute = attr; } catch(MStatus status) { return status; } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelper::addFloat3Attr(const MObject& node, const char* longName, const char* shortName, float defaultX, float defaultY, float defaultZ, uint32_t flags, MObject* attribute) { try { MStatus status; MFnDependencyNode fn(node, &status); if(!status) { throw status; } MObject attr = addFloat3Attr(longName, shortName, defaultX, defaultY, defaultZ, flags | kDynamic); status = fn.addAttribute(attr); if(!status) { MGlobal::displayError(MString("Unable to add float3 attribute ") + longName + " to node " + fn.name()); throw status; } if(attribute) *attribute = attr; } catch(MStatus status) { return status; } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelper::addAngle3Attr(const MObject& node, const char* longName, const char* shortName, float defaultX, float defaultY, float defaultZ, uint32_t flags, MObject* attribute) { try { MStatus status; MFnDependencyNode fn(node, &status); if(!status) { throw status; } MObject attr = addAngle3Attr(longName, shortName, defaultX, defaultY, defaultZ, flags | kDynamic); status = fn.addAttribute(attr); if(!status) { MGlobal::displayError(MString("Unable to add angle3 attribute ") + longName + " to node " + fn.name()); throw status; } if(attribute) *attribute = attr; } catch(MStatus status) { return status; } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelper::addPointAttr(const MObject& node, const char* longName, const char* shortName, const MPoint& defaultValue, uint32_t flags, MObject* attribute) { try { MStatus status; MFnDependencyNode fn(node, &status); if(!status) { throw status; } MObject attr = addPointAttr(longName, shortName, defaultValue, flags | kDynamic); status = fn.addAttribute(attr); if(!status) { MGlobal::displayError(MString("Unable to add point attribute ") + longName + " to node " + fn.name()); throw status; } if(attribute) *attribute = attr; } catch(MStatus status) { return status; } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelper::addVectorAttr(const MObject& node, const char* longName, const char* shortName, const MVector& defaultValue, uint32_t flags, MObject* attribute) { try { MStatus status; MFnDependencyNode fn(node, &status); if(!status) { throw status; } MObject attr = addVectorAttr(longName, shortName, defaultValue, flags | kDynamic); status = fn.addAttribute(attr); if(!status) { MGlobal::displayError(MString("Unable to add vector attribute ") + longName + " to node " + fn.name()); throw status; } if(attribute) *attribute = attr; } catch(MStatus status) { return status; } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelper::addMatrixAttr(const MObject& node, const char* longName, const char* shortName, const MMatrix& defaultValue, uint32_t flags, MObject* attribute) { try { MStatus status; MFnDependencyNode fn(node, &status); if(!status) { throw status; } MObject attr = addMatrixAttr(longName, shortName, defaultValue, flags | kDynamic); status = fn.addAttribute(attr); if(!status) { MGlobal::displayError(MString("Unable to add matrix attribute ") + longName + " to node " + fn.name()); throw status; } if(attribute) *attribute = attr; } catch(MStatus status) { return status; } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelper::addMatrix2x2Attr(const MObject& node, const char* longName, const char* shortName, const float defaultValue[2][2], uint32_t flags, MObject* attribute) { try { MStatus status; MFnDependencyNode fn(node, &status); if(!status) { throw status; } MObject attr = addMatrix2x2Attr(longName, shortName, defaultValue, flags | kDynamic); status = fn.addAttribute(attr); if(!status) { MGlobal::displayError(MString("Unable to add matrix2x2 attribute ") + longName + " to node " + fn.name()); throw status; } if(attribute) *attribute = attr; } catch(MStatus status) { return status; } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelper::addMatrix3x3Attr(const MObject& node, const char* longName, const char* shortName, const float defaultValue[3][3], uint32_t flags, MObject* attribute) { try { MStatus status; MFnDependencyNode fn(node, &status); if(!status) { throw status; } MObject attr = addMatrix3x3Attr(longName, shortName, defaultValue, flags | kDynamic); status = fn.addAttribute(attr); if(!status) { MGlobal::displayError(MString("Unable to add matrix3x3 attribute ") + longName + " to node " + fn.name()); throw status; } if(attribute) *attribute = attr; } catch(MStatus status) { return status; } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelper::addDataAttr(const MObject& node, const char* longName, const char* shortName, MFnData::Type type, uint32_t flags, MFnAttribute::DisconnectBehavior behaviour, MObject* attribute) { try { MStatus status; MFnDependencyNode fn(node, &status); if(!status) { throw status; } MObject attr = addDataAttr(longName, shortName, type, flags | kDynamic, behaviour); status = fn.addAttribute(attr); if(!status) { MGlobal::displayError(MString("Unable to add data attribute ") + longName + " to node " + fn.name()); throw status; } if(attribute) *attribute = attr; } catch(MStatus status) { return status; } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelper::addDataAttr(const MObject& node, const char* longName, const char* shortName, const MTypeId& type, uint32_t flags, MFnAttribute::DisconnectBehavior behaviour, MObject* attribute) { try { MStatus status; MFnDependencyNode fn(node, &status); if(!status) { throw status; } MObject attr = addDataAttr(longName, shortName, type, flags | kDynamic, behaviour); status = fn.addAttribute(attr); if(!status) { MGlobal::displayError(MString("Unable to add data attribute ") + longName + " to node " + fn.name()); throw status; } if(attribute) *attribute = attr; } catch(MStatus status) { return status; } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelper::addMessageAttr(const MObject& node, const char* longName, const char* shortName, uint32_t flags, MObject* attribute) { try { MStatus status; MFnDependencyNode fn(node, &status); if(!status) { throw status; } MObject attr = addMessageAttr(longName, shortName, flags | kDynamic); status = fn.addAttribute(attr); if(!status) { MGlobal::displayError(MString("Unable to add message attribute ") + longName + " to node " + fn.name()); throw status; } if(attribute) *attribute = attr; } catch(MStatus status) { return status; } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelper::addVec2fAttr(const MObject& node, const char* longName, const char* shortName, uint32_t flags, MObject* attribute) { try { MStatus status; MFnDependencyNode fn(node, &status); if(!status) { throw status; } MObject attr = addVec2fAttr(longName, shortName, flags | kDynamic); status = fn.addAttribute(attr); if(!status) { MGlobal::displayError(MString("Unable to add vec2 attribute ") + longName + " to node " + fn.name()); throw status; } if(attribute) *attribute = attr; } catch(MStatus status) { return status; } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelper::addVec2iAttr(const MObject& node, const char* longName, const char* shortName, uint32_t flags, MObject* attribute) { try { MStatus status; MFnDependencyNode fn(node, &status); if(!status) { throw status; } MObject attr = addVec2iAttr(longName, shortName, flags | kDynamic); status = fn.addAttribute(attr); if(!status) { MGlobal::displayError(MString("Unable to add vec2 attribute ") + longName + " to node " + fn.name()); throw status; } if(attribute) *attribute = attr; } catch(MStatus status) { return status; } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelper::addVec2dAttr(const MObject& node, const char* longName, const char* shortName, uint32_t flags, MObject* attribute) { try { MStatus status; MFnDependencyNode fn(node, &status); if(!status) { throw status; } MObject attr = addVec2dAttr(longName, shortName, flags | kDynamic); status = fn.addAttribute(attr); if(!status) { MGlobal::displayError(MString("Unable to add vec2 attribute ") + longName + " to node " + fn.name()); throw status; } if(attribute) *attribute = attr; } catch(MStatus status) { return status; } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelper::addVec3fAttr(const MObject& node, const char* longName, const char* shortName, uint32_t flags, MObject* attribute) { try { MStatus status; MFnDependencyNode fn(node, &status); if(!status) { throw status; } MObject attr = addVec3fAttr(longName, shortName, flags | kDynamic); status = fn.addAttribute(attr); if(!status) { MGlobal::displayError(MString("Unable to add vec3 attribute ") + longName + " to node " + fn.name()); throw status; } if(attribute) *attribute = attr; } catch(MStatus status) { return status; } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelper::addVec3iAttr(const MObject& node, const char* longName, const char* shortName, uint32_t flags, MObject* attribute) { try { MStatus status; MFnDependencyNode fn(node, &status); if(!status) { throw status; } MObject attr = addVec3iAttr(longName, shortName, flags | kDynamic); status = fn.addAttribute(attr); if(!status) { MGlobal::displayError(MString("Unable to add vec3 attribute ") + longName + " to node " + fn.name()); throw status; } if(attribute) *attribute = attr; } catch(MStatus status) { return status; } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelper::addVec3dAttr(const MObject& node, const char* longName, const char* shortName, uint32_t flags, MObject* attribute) { try { MStatus status; MFnDependencyNode fn(node, &status); if(!status) { throw status; } MObject attr = addVec3dAttr(longName, shortName, flags | kDynamic); status = fn.addAttribute(attr); if(!status) { MGlobal::displayError(MString("Unable to add vec3 attribute ") + longName + " to node " + fn.name()); throw status; } if(attribute) *attribute = attr; } catch(MStatus status) { return status; } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelper::addVec4fAttr(const MObject& node, const char* longName, const char* shortName, uint32_t flags, MObject* attribute) { try { MStatus status; MFnDependencyNode fn(node, &status); if(!status) { throw status; } MObject attr = addVec4fAttr(longName, shortName, flags | kDynamic); status = fn.addAttribute(attr); if(!status) { MGlobal::displayError(MString("Unable to add vec4 attribute ") + longName + " to node " + fn.name()); throw status; } if(attribute) *attribute = attr; } catch(MStatus status) { return status; } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelper::addVec4iAttr(const MObject& node, const char* longName, const char* shortName, uint32_t flags, MObject* attribute) { try { MStatus status; MFnDependencyNode fn(node, &status); if(!status) { throw status; } MObject attr = addVec4iAttr(longName, shortName, flags | kDynamic); status = fn.addAttribute(attr); if(!status) { MGlobal::displayError(MString("Unable to add vec4 attribute ") + longName + " to node " + fn.name()); throw status; } if(attribute) *attribute = attr; } catch(MStatus status) { return status; } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelper::addVec4dAttr(const MObject& node, const char* longName, const char* shortName, uint32_t flags, MObject* attribute) { try { MStatus status; MFnDependencyNode fn(node, &status); if(!status) { throw status; } MObject attr = addVec4dAttr(longName, shortName, flags | kDynamic); status = fn.addAttribute(attr); if(!status) { MGlobal::displayError(MString("Unable to add vec4 attribute ") + longName + " to node " + fn.name()); throw status; } if(attribute) *attribute = attr; } catch(MStatus status) { return status; } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- } // utils } // maya } // AL //----------------------------------------------------------------------------------------------------------------------
33.311703
198
0.568527
sopvop
dc890a98b0b0213c56e0104fdb93a5bbc767409d
744
hpp
C++
samples/omp/KSC-daphne/include/ndt_worker.hpp
rubis-lab/popt-dev
f52b213005fcbce38f326bbd798fa015cca171bc
[ "MIT" ]
1
2021-10-12T09:02:47.000Z
2021-10-12T09:02:47.000Z
samples/omp/KSC-daphne/include/ndt_worker.hpp
rubis-lab/popt-dev
f52b213005fcbce38f326bbd798fa015cca171bc
[ "MIT" ]
null
null
null
samples/omp/KSC-daphne/include/ndt_worker.hpp
rubis-lab/popt-dev
f52b213005fcbce38f326bbd798fa015cca171bc
[ "MIT" ]
null
null
null
// #ifndef __NDTDLWORKER_H__ // #define __NDTDLWORKER_H__ // #include <omp.h> // #include <cmath> // #include <string> // #include <vector> // #include <rts/core/pt.hpp> // #include <rts/op/exp.hpp> // #include "ndt_kernel.hpp" // #include "sched_log.hpp" // #include "sched_core.hpp" // #include "sched_deadline.hpp" // #include "spdlog/spdlog.h" // #include "spdlog/async.h" // #include "spdlog/sinks/basic_file_sink.h" // class NDTWorker { // public: // std::string name; // std::shared_ptr<spdlog::logger> thr_log; // std::vector<int> omp_thr_ids; // rts::Pt pt; // SchedLog sl; // NDTWorker(rts::Pt _pt, rts::Exp _exp); // void apply_rt(); // void msec_work(int msec); // void work(); // }; // #endif
24
47
0.625
rubis-lab
dc893fd46df1575862244fb3ec44f42cbb74d463
532
cpp
C++
Codeforces/HelpfulMaths.cpp
canis-majoris123/CompetitiveProgramming
be6c208abe6e0bd748c3bb0e715787506d73588d
[ "MIT" ]
null
null
null
Codeforces/HelpfulMaths.cpp
canis-majoris123/CompetitiveProgramming
be6c208abe6e0bd748c3bb0e715787506d73588d
[ "MIT" ]
null
null
null
Codeforces/HelpfulMaths.cpp
canis-majoris123/CompetitiveProgramming
be6c208abe6e0bd748c3bb0e715787506d73588d
[ "MIT" ]
null
null
null
//https://codeforces.com/problemset/problem/339/A #include<bits/stdc++.h> using namespace std ; #define aakriti string int main() { ios_base::sync_with_stdio(false); cin.tie(0); aakriti s ; int a ; cin >> s ; sort(s.begin(), s.end()); vector<char>v; for(int i = 0; i < s.size(); i++) { if(s[i] != '+') { v.push_back(s[i]); } } a = v.size(); for(int i = 0; i < a-1; i++) { cout << v[i] << "+"; } cout << v[a-1]; }
19
50
0.443609
canis-majoris123
dc89c2265d0f73f7387fa1aef8b5a46382e8a74f
165,042
cxx
C++
dev/ese/src/ese/dbutil.cxx
augustoproiete-forks/microsoft--Extensible-Storage-Engine
a38945d2147167e3fa749594f54dae6c7307b8da
[ "MIT" ]
1
2021-02-02T07:04:07.000Z
2021-02-02T07:04:07.000Z
dev/ese/src/ese/dbutil.cxx
augustoproiete-forks/microsoft--Extensible-Storage-Engine
a38945d2147167e3fa749594f54dae6c7307b8da
[ "MIT" ]
null
null
null
dev/ese/src/ese/dbutil.cxx
augustoproiete-forks/microsoft--Extensible-Storage-Engine
a38945d2147167e3fa749594f54dae6c7307b8da
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include "std.hxx" #include "_bt.hxx" #include "_dump.hxx" #include "_space.hxx" #include "stat.hxx" LOCAL ERR ErrDBUTLDumpTables( DBCCINFO *pdbccinfo, PFNTABLE pfntable, VOID* pvCtx = NULL ); #if !defined( MINIMAL_FUNCTIONALITY ) || defined( DEBUGGER_EXTENSION ) VOID DBUTLSprintHex( __out_bcount(cbDest) CHAR * const szDest, const INT cbDest, const BYTE * const rgbSrc, const INT cbSrc, const INT cbWidth, const INT cbChunk, const INT cbAddress, const INT cbStart) { static const CHAR rgchConvert[] = { '0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f' }; const BYTE * const pbMax = rgbSrc + cbSrc; const INT cchHexWidth = ( cbWidth * 2 ) + ( cbWidth / cbChunk ); const BYTE * pb = rgbSrc; CHAR * szDestCurrent = szDest; Assert( cbDest >= sizeof(CHAR) ); if ( cbDest < sizeof(CHAR) ) { return; } Assert( cchHexWidth ); if ( 0 == cchHexWidth ) { return; } CHAR * const szDestMax = szDestCurrent + cbDest - 1; while( pbMax != pb && szDestCurrent < szDestMax ) { if ( cbAddress ) { StringCbPrintfA( szDestCurrent, szDestMax - szDestCurrent + 1, "%*.*lx ", cbAddress, cbAddress, (INT)(pb - rgbSrc + cbStart) ); (*szDestMax) = 0; szDestCurrent += strlen(szDestCurrent); if ( szDestMax <= szDestCurrent ) break; } CHAR * szCurrentRightSide = szDestCurrent + cchHexWidth; if ( szDestMax <= ( szCurrentRightSide + 2 ) ) break; *szCurrentRightSide++ = '\\'; *szCurrentRightSide++ = ' '; memset( szDestCurrent, ' ', cchHexWidth ); do { Assert( szDestCurrent < szCurrentRightSide ); for( INT cb = 0; cbChunk > cb && pbMax != pb && szCurrentRightSide <= szDestMax && szDestCurrent < szDestMax; ++cb, ++pb ) { *szDestCurrent++ = rgchConvert[ *pb >> 4 ]; *szDestCurrent++ = rgchConvert[ *pb & 0x0F ]; *szCurrentRightSide++ = isprint( *pb ) ? *pb : '.'; } szDestCurrent++; } while( ( ( pb - rgbSrc ) % cbWidth ) && pbMax > pb && szCurrentRightSide < szDestMax); if ( szCurrentRightSide < szDestMax ) { *szCurrentRightSide++ = '\n'; *szCurrentRightSide = '\0'; } szDestCurrent = szCurrentRightSide; } Assert( szDestCurrent<= szDestMax ) ; (*szDestMax) = 0; } #pragma prefast(push) #pragma prefast(disable:6262, "This function uses a lot of stack (33k) because of szBuff[g_cbPageMax].") VOID DBUTLDumpRec( const LONG cbPage, const FUCB * const pfucbTable, const VOID * const pv, const INT cb, CPRINTF * pcprintf, const INT cbWidth ) { CHAR szBuf[g_cbPageMax]; TDB* const ptdb = ( pfucbTable != pfucbNil ? pfucbTable->u.pfcb->Ptdb() : ptdbNil ); TDB* const ptdbTemplate = ( ptdb != ptdbNil && ptdb->PfcbTemplateTable() != pfcbNil ? ptdb->PfcbTemplateTable()->Ptdb() : ptdbNil ); const REC * const prec = reinterpret_cast<const REC *>( pv ); const CHAR * szColNameSeparator = " - "; const CHAR * szNullValue = "<NULL>"; const CHAR * szTemplate = " (template)"; const CHAR * szDerived = " (derived)"; #define SzTableColType( ptdbTemplateIn, fTemplateColumnIn ) ( ( ptdbTemplateIn == NULL ) ? "" : ( fTemplateColumnIn ? szTemplate : szDerived ) ) FID fid; const FID fidFixedFirst = fidFixedLeast; const FID fidFixedLast = prec->FidFixedLastInRec(); const INT cColumnsFixed = max( 0, fidFixedLast - fidFixedFirst + 1 ); (*pcprintf)( " Fixed Columns: %d\n", cColumnsFixed ); (*pcprintf)( "=================\n" ); for( fid = fidFixedFirst; fid <= fidFixedLast; ++fid ) { const UINT ifid = fid - fidFixedLeast; const BYTE * const prgbitNullity = prec->PbFixedNullBitMap() + ifid/8; const BOOL fTemplateColumn = ptdbTemplate == ptdbNil ? fFalse : fid <= ptdbTemplate->FidFixedLast() ? fTrue : fFalse; const COLUMNID columnid = ColumnidOfFid( fid, fTemplateColumn ); const FIELD * const pfield = ( ptdb != ptdbNil ) ? ptdb->Pfield( columnid ) : NULL; BOOL fDeleted = fFalse; const CHAR * szType = "UnknownColType"; const CHAR * szColumn = "UnknownColName "; if ( pfield ) { fDeleted = ( 0 == pfield->itagFieldName ); szType = ( fDeleted ? "<deleted>" : SzColumnType( pfield->coltyp ) ); szColumn = ( fDeleted ? "<deleted>" : ( fTemplateColumn ? ptdbTemplate : ptdb )->SzFieldName( pfield->itagFieldName, ptdbTemplate != NULL && !fTemplateColumn ) ); } const CHAR * const szHddlSrc = SzTableColType( ptdbTemplate, fTemplateColumn ); (*pcprintf)( "%u (0x%x): [%-16hs] %hs%hs", columnid, columnid, szType, szColumn, szHddlSrc ); if ( FFixedNullBit( prgbitNullity, ifid ) ) { (*pcprintf)( "%hs%hs\n", szColNameSeparator, szNullValue ); } else { (*pcprintf)( "\n" ); if ( pfucbTable ) { DATA dataRec; dataRec.SetPv( (void*)prec ); dataRec.SetCb( cb ); DATA dataCol; const ERR errRet = ErrRECRetrieveNonTaggedColumn( pfucbTable->u.pfcb, columnid, dataRec, &dataCol, pfieldNil ); if ( errRet >= JET_errSuccess ) { Expected( dataCol.Cb() < 257 ); szBuf[0] = 0; DBUTLSprintHex( szBuf, sizeof(szBuf), (BYTE*)dataCol.Pv(), dataCol.Cb(), cbWidth ); (*pcprintf)( "%s", szBuf ); } else { (*pcprintf)( "<ERR: got %d trying retrieve column value>\n", errRet ); } } else { (*pcprintf)( "<ERR: need at least copy of FCB to dump fixed cols>\n" ); } } } (*pcprintf)( "\n" ); const FID fidVariableFirst = fidVarLeast ; const FID fidVariableLast = prec->FidVarLastInRec(); const INT cColumnsVariable = max( 0, fidVariableLast - fidVariableFirst + 1 ); (*pcprintf)( "Variable Columns: %d\n", cColumnsVariable ); (*pcprintf)( "=================\n" ); const UnalignedLittleEndian<REC::VAROFFSET> * const pibVarOffs = ( const UnalignedLittleEndian<REC::VAROFFSET> * const )prec->PibVarOffsets(); for( fid = fidVariableFirst; fid <= fidVariableLast; ++fid ) { const UINT ifid = fid - fidVarLeast; const REC::VAROFFSET ibStartOfColumn = prec->IbVarOffsetStart( fid ); const REC::VAROFFSET ibEndOfColumn = IbVarOffset( pibVarOffs[ifid] ); const BOOL fTemplateColumn = ptdbTemplate == ptdbNil ? fFalse : fid <= ptdbTemplate->FidVarLast() ? fTrue : fFalse; const COLUMNID columnid = ColumnidOfFid( fid, fTemplateColumn ); const FIELD * const pfield = ( ptdb != ptdbNil ) ? ptdb->Pfield( columnid ) : NULL; BOOL fDeleted = fFalse; const CHAR * szType = "UnknownColType"; const CHAR * szColumn = "UnknownColName "; if ( pfield ) { fDeleted = ( 0 == pfield->itagFieldName ); szType = ( fDeleted ? "<deleted>" : SzColumnType( pfield->coltyp ) ); szColumn = ( fDeleted ? "<deleted>" : ( fTemplateColumn ? ptdbTemplate : ptdb )->SzFieldName( pfield->itagFieldName, ptdbTemplate != NULL && !fTemplateColumn ) ); } const CHAR * const szHddlSrc = SzTableColType( ptdbTemplate, fTemplateColumn ); (*pcprintf)( "%u (0x%x): [%-16hs] %hs%hs", columnid, columnid, szType, szColumn, szHddlSrc ); if ( FVarNullBit( pibVarOffs[ifid] ) ) { (*pcprintf)( "%hs%hs\n", szColNameSeparator, szNullValue ); } else { const VOID * const pvColumn = prec->PbVarData() + ibStartOfColumn; const INT cbColumn = ibEndOfColumn - ibStartOfColumn; (*pcprintf)( "%hs%d bytes\n", szColNameSeparator, cbColumn ); DBUTLSprintHex( szBuf, sizeof(szBuf), (BYTE *)pvColumn, cbColumn, cbWidth ); (*pcprintf)( "%s\n", szBuf ); } } (*pcprintf)( "\n" ); (*pcprintf)( " Tagged Columns:\n" ); (*pcprintf)( "=================\n" ); DATA dataRec; dataRec.SetPv( (VOID *)pv ); dataRec.SetCb( cb ); if ( !TAGFIELDS::FIsValidTagfields( cbPage, dataRec, pcprintf ) ) { (*pcprintf)( "Tagged column corruption detected.\n" ); } (*pcprintf)( "TAGFIELDS array begins at offset 0x%x from start of record.\n\n", prec->PbTaggedData() - (BYTE *)prec ); TAGFIELDS_ITERATOR ti( dataRec ); ti.MoveBeforeFirst(); while( JET_errSuccess == ti.ErrMoveNext() ) { const CHAR * szComma = " "; const BOOL fTemplateColumn = ptdbTemplate == ptdbNil ? fFalse : ti.Fid() <= ptdbTemplate->FidTaggedLast() ? fTrue : fFalse; const COLUMNID columnid = ColumnidOfFid( ti.Fid(), fTemplateColumn ); const FIELD * const pfield = ( ptdb != ptdbNil ) ? ptdb->Pfield( columnid ) : NULL; BOOL fDeleted = fFalse; const CHAR * szType = "UnknownColType"; const CHAR * szColumn = "UnknownColName "; if ( pfield ) { fDeleted = ( 0 == pfield->itagFieldName ); szType = ( fDeleted ? "<deleted>" : SzColumnType( pfield->coltyp ) ); szColumn = ( fDeleted ? "<deleted>" : ( fTemplateColumn ? ptdbTemplate : ptdb )->SzFieldName( pfield->itagFieldName, ptdbTemplate != NULL && !fTemplateColumn ) ); Assert( !!ti.FLV() == ( ( pfield->coltyp == JET_coltypLongText ) || ( pfield->coltyp == JET_coltypLongBinary ) ) ); } const CHAR * const szHddlSrc = SzTableColType( ptdbTemplate, !ti.FDerived() ); (*pcprintf)( "%u (0x%x): [%-16hs] %hs%hs", ti.Fid(), ti.Fid(), szType, szColumn, szHddlSrc ); if( ti.FNull() ) { (*pcprintf)( "%hs%hs", szColNameSeparator, szNullValue ); szComma = ", "; } (*pcprintf)( "\r\n" ); ti.TagfldIterator().MoveBeforeFirst(); INT itag = 1; while( JET_errSuccess == ti.TagfldIterator().ErrMoveNext() ) { const BOOL fSeparated = ti.TagfldIterator().FSeparated(); const BOOL fCompressed = ti.TagfldIterator().FCompressed(); const BOOL fEncrypted = ti.TagfldIterator().FEncrypted(); (*pcprintf)( ">> itag %d: %d bytes (offset 0x%x): ", itag, ti.TagfldIterator().CbData(), ti.TagfldIterator().PbData() - (BYTE *)prec ); if ( fSeparated ) { (*pcprintf)( "separated" ); } if ( fCompressed ) { (*pcprintf)( " compressed" ); } if ( fEncrypted ) { (*pcprintf)( " encrypted" ); } (*pcprintf)( "\r\n" ); const INT cbPrintMax = 512; if( fCompressed && !fEncrypted && !fSeparated ) { szBuf[0] = 0; DBUTLSprintHex( szBuf, sizeof(szBuf), ti.TagfldIterator().PbData(), min( ti.TagfldIterator().CbData(), 64 ), cbWidth ); (*pcprintf)( "%s%s\r\n", szBuf, ( ti.TagfldIterator().CbData() > 64 ? "...\r\n" : "" ) ); BYTE rgbDecompressed[cbPrintMax]; DATA dataCompressed; dataCompressed.SetPv( (void *)ti.TagfldIterator().PbData() ); dataCompressed.SetCb( ti.TagfldIterator().CbData() ); INT cbDecompressed; CallSx( ErrPKDecompressData( dataCompressed, NULL, rgbDecompressed, sizeof(rgbDecompressed), &cbDecompressed ), JET_wrnBufferTruncated ); size_t cbToPrint = min( sizeof(rgbDecompressed ), cbDecompressed ); (*pcprintf)( ">> %d bytes uncompressed:\r\n", cbDecompressed ); szBuf[0] = 0; DBUTLSprintHex( szBuf, sizeof(szBuf), rgbDecompressed, min( cbToPrint, cbPrintMax ), cbWidth ); (*pcprintf)( "%s%s\r\n", szBuf, ( cbDecompressed > cbPrintMax ? "...\r\n" : "" ) ); } else { szBuf[0] = 0; DBUTLSprintHex( szBuf, sizeof(szBuf), ti.TagfldIterator().PbData(), min( ti.TagfldIterator().CbData(), cbPrintMax ), cbWidth ); (*pcprintf)( "%s%s\r\n", szBuf, ( ti.TagfldIterator().CbData() > cbPrintMax ? "...\r\n" : "" ) ); } ++itag; } } (*pcprintf)( "\n" ); } #pragma prefast(push) #endif #ifdef MINIMAL_FUNCTIONALITY #else const JET_COLUMNDEF rgcolumndefPageInfoTable[] = { {sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed | JET_bitColumnTTKey}, {sizeof(JET_COLUMNDEF), 0, JET_coltypBit, 0, 0, 0, 0, 0, JET_bitColumnFixed | JET_bitColumnNotNULL}, {sizeof(JET_COLUMNDEF), 0, JET_coltypBit, 0, 0, 0, 0, 0, JET_bitColumnFixed }, {sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed}, {sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed }, {sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed } }; const INT icolumnidPageInfoPgno = 0; const INT icolumnidPageInfoFChecked = 1; const INT icolumnidPageInfoFAvail = 2; const INT icolumnidPageInfoFreeSpace = 3; const INT icolumnidPageInfoPgnoLeft = 4; const INT icolumnidPageInfoPgnoRight = 5; const INT ccolumndefPageInfoTable = ( sizeof ( rgcolumndefPageInfoTable ) / sizeof(JET_COLUMNDEF) ); LOCAL JET_COLUMNID g_rgcolumnidPageInfoTable[ccolumndefPageInfoTable]; typedef ERR(*PFNDUMP)( PIB *ppib, FUCB *pfucbCatalog, VOID *pfnCallback, VOID *pvCallback ); #endif LOCAL ERR ErrDBUTLDump( JET_SESID sesid, const JET_DBUTIL_W *pdbutil ); LOCAL VOID DBUTLPrintfIntN( INT iValue, INT ichMax ) { CHAR rgchT[17]; INT ichT; _itoa_s( iValue, rgchT, _countof(rgchT), 10 ); for ( ichT = 0; ichT < sizeof(rgchT) && rgchT[ichT] != '\0' ; ichT++ ) ; if ( ichT > ichMax ) { for ( ichT = 0; ichT < ichMax; ichT++ ) printf( "#" ); } else { for ( ichT = ichMax - ichT; ichT > 0; ichT-- ) printf( " " ); for ( ichT = 0; rgchT[ichT] != '\0'; ichT++ ) printf( "%c", rgchT[ichT] ); } return; } #ifdef MINIMAL_FUNCTIONALITY #else LOCAL_BROKEN VOID DBUTLPrintfStringN( __in_bcount(ichMax) const CHAR *sz, INT ichMax ) { INT ich; for ( ich = 0; ich < ichMax && sz[ich] != '\0' ; ich++ ) printf( "%c", sz[ich] ); for ( ; ich < ichMax; ich++ ) printf( " " ); printf( " " ); return; } LOCAL_BROKEN ERR ErrDBUTLRegExt( DBCCINFO *pdbccinfo, PGNO pgnoFirst, CPG cpg, BOOL fAvailT ) { ERR err = JET_errSuccess; PGNO pgnoLast = (PGNO)( pgnoFirst + cpg - 1 ); PGNO pgno; PIB *ppib = pdbccinfo->ppib; JET_SESID sesid = (JET_SESID) pdbccinfo->ppib; JET_TABLEID tableid = pdbccinfo->tableidPageInfo; BYTE fAvail = (BYTE) fAvailT; Assert( tableid != JET_tableidNil ); if ( pgnoFirst > pgnoLast ) { return ErrERRCheck( JET_errInvalidParameter ); } for ( pgno = pgnoFirst; pgno <= pgnoLast; pgno++ ) { BOOL fFound; BYTE fChecked = fFalse; CallR( ErrIsamBeginTransaction( (JET_SESID) ppib, 41189, NO_GRBIT ) ); CallS( ErrDispMakeKey( sesid, tableid, (BYTE *)&pgno, sizeof(pgno), JET_bitNewKey ) ); err = ErrDispSeek( sesid, tableid, JET_bitSeekEQ ); if ( err < 0 && err != JET_errRecordNotFound ) { Assert( fFalse ); Call( err ); } fFound = ( err == JET_errRecordNotFound ) ? fFalse : fTrue; if ( fFound ) { ULONG cbActual; BYTE fAvailT2; Call( ErrDispRetrieveColumn( sesid, tableid, g_rgcolumnidPageInfoTable[icolumnidPageInfoFAvail], (BYTE *)&fAvailT2, sizeof(fAvailT2), &cbActual, 0, NULL ) ); Assert( err == JET_wrnColumnNull || cbActual == sizeof(fAvailT2) ); if ( err != JET_wrnColumnNull ) { Assert( !fAvail || fAvailT2 ); } if ( !fAvail ) goto Commit; Call( ErrDispRetrieveColumn( sesid, tableid, g_rgcolumnidPageInfoTable[icolumnidPageInfoFChecked], (BYTE *)&fChecked, sizeof(fChecked), &cbActual, 0, NULL ) ); Assert( cbActual == sizeof(fChecked) ); Call( ErrDispPrepareUpdate( sesid, tableid, JET_prepReplaceNoLock ) ); } else { Call( ErrDispPrepareUpdate( sesid, tableid, JET_prepInsert ) ); Call( ErrDispSetColumn( sesid, tableid, g_rgcolumnidPageInfoTable[icolumnidPageInfoPgno], (BYTE *) &pgno, sizeof(pgno), 0, NULL ) ); } Call( ErrDispSetColumn( sesid, tableid, g_rgcolumnidPageInfoTable[icolumnidPageInfoFChecked], (BYTE *)&fChecked, sizeof(fChecked), 0, NULL ) ); if ( fAvail ) { Call( ErrDispSetColumn( sesid, tableid, g_rgcolumnidPageInfoTable[icolumnidPageInfoFAvail], (BYTE *) &fAvail, sizeof(fAvail), 0, NULL ) ); } Call( ErrDispUpdate( sesid, tableid, NULL, 0, NULL, 0 ) ); Commit: Assert( ppib->Level() == 1 ); Call( ErrIsamCommitTransaction( ( JET_SESID ) ppib, 0 ) ); } return JET_errSuccess; HandleError: CallS( ErrIsamRollback( (JET_SESID) ppib, JET_bitRollbackAll ) ); return err; } LOCAL_BROKEN ERR ErrDBUTLPrintPageDump( DBCCINFO *pdbccinfo ) { ERR err; const JET_SESID sesid = (JET_SESID) pdbccinfo->ppib; const JET_TABLEID tableid = pdbccinfo->tableidPageInfo; ULONG cbT; FUCBSetSequential( reinterpret_cast<FUCB *>( tableid ) ); Assert( pdbccinfo->grbitOptions & JET_bitDBUtilOptionPageDump ); err = ErrDispMove( sesid, tableid, JET_MoveFirst, 0 ); if ( JET_errNoCurrentRecord != err ) { err = JET_errSuccess; goto HandleError; } Call( err ); printf( "\n\n ***************** PAGE DUMP *******************\n\n" ); printf( "PGNO\tAVAIL\tCHECK\tLEFT\tRIGHT\tFREESPACE\n" ); for( ; JET_errSuccess == err; err = ErrDispMove( sesid, tableid, JET_MoveNext, 0 ) ) { PGNO pgnoThis = pgnoNull; PGNO pgnoLeft = pgnoNull; PGNO pgnoRight = pgnoNull; BYTE fChecked = fFalse; BYTE fAvail = fFalse; ULONG cbFreeSpace = 0; Call( ErrDispRetrieveColumn( sesid, tableid, g_rgcolumnidPageInfoTable[icolumnidPageInfoPgno], (BYTE *) &pgnoThis, sizeof(pgnoThis), &cbT, 0, NULL ) ); Assert( sizeof(pgnoThis) == cbT ); Call( ErrDispRetrieveColumn( sesid, tableid, g_rgcolumnidPageInfoTable[icolumnidPageInfoFAvail], (BYTE *) &fAvail, sizeof(fAvail), &cbT, 0, NULL ) ); Assert( sizeof(fAvail) == cbT || JET_wrnColumnNull == err ); Call( ErrDispRetrieveColumn( sesid, tableid, g_rgcolumnidPageInfoTable[icolumnidPageInfoFChecked], (BYTE *)&fChecked, sizeof(fChecked), &cbT, 0, NULL ) ); Assert( cbT == sizeof(fChecked) ); Assert( fChecked || fAvail ); Call( ErrDispRetrieveColumn( sesid, tableid, g_rgcolumnidPageInfoTable[icolumnidPageInfoPgnoLeft], (BYTE *)&pgnoLeft, sizeof(pgnoLeft), &cbT, 0, NULL ) ); Assert( cbT == sizeof(pgnoLeft) ); Call( ErrDispRetrieveColumn( sesid, tableid, g_rgcolumnidPageInfoTable[icolumnidPageInfoPgnoRight], (BYTE *) &pgnoRight, sizeof(pgnoRight), &cbT, 0, NULL ) ); Assert( cbT == sizeof(pgnoRight) ); Call( ErrDispRetrieveColumn( sesid, tableid, g_rgcolumnidPageInfoTable[icolumnidPageInfoFreeSpace], (BYTE *) &cbFreeSpace, sizeof(cbFreeSpace), &cbT, 0, NULL ) ); Assert( cbT == sizeof(cbFreeSpace) ); printf( "%u\t%s\t%s", pgnoThis, fAvail ? "FAvail" : "", fChecked ? "FCheck" : "" ); if( fChecked ) { printf( "\t%u\t%u\t%u", pgnoLeft, pgnoRight, cbFreeSpace ); } printf( "\n" ); } if ( JET_errNoCurrentRecord == err ) err = JET_errSuccess; HandleError: return err; } #ifdef DEBUG LOCAL ERR ErrDBUTLISzToData( const CHAR * const sz, DATA * const pdata ) { DATA& data = *pdata; const LONG cch = (LONG)strlen( sz ); if( cch % 2 == 1 || cch <= 0 ) { return ErrERRCheck( JET_errInvalidParameter ); } const LONG cbInsert = cch / 2; BYTE * pbInsert = (BYTE *)PvOSMemoryHeapAlloc( cbInsert ); if( NULL == pbInsert ) { return ErrERRCheck( JET_errOutOfMemory ); } for( INT ibInsert = 0; ibInsert < cbInsert; ++ibInsert ) { CHAR szConvert[3]; szConvert[0] = sz[ibInsert * 2 ]; szConvert[1] = sz[ibInsert * 2 + 1]; szConvert[2] = 0; CHAR * pchEnd; const ULONG lConvert = strtoul( szConvert, &pchEnd, 16 ); if( lConvert > 0xff || 0 != *pchEnd ) { OSMemoryHeapFree( pbInsert ); return ErrERRCheck( JET_errInvalidParameter ); } pbInsert[ibInsert] = (BYTE)lConvert; } data.SetCb( cbInsert ); data.SetPv( pbInsert ); return JET_errSuccess; } LOCAL ERR ErrDBUTLIInsertNode( PIB * const ppib, const IFMP ifmp, const PGNO pgno, const LONG iline, const DATA& data, CPRINTF * const pcprintf ) { ERR err = JET_errSuccess; CPAGE cpage; CallR( cpage.ErrGetReadPage( ppib, ifmp, pgno, bflfNoTouch ) ); Call( cpage.ErrUpgradeReadLatchToWriteLatch() ); cpage.Dirty( bfdfFilthy ); (*pcprintf)( "inserting data at %d:%d\r\n", pgno, iline ); cpage.Insert( iline, &data, 1, 0 ); HandleError: cpage.ReleaseWriteLatch( fTrue ); return err; } LOCAL ERR ErrDBUTLIReplaceNode( PIB * const ppib, const IFMP ifmp, const PGNO pgno, const LONG iline, const DATA& data, CPRINTF * const pcprintf ) { ERR err = JET_errSuccess; CPAGE cpage; CallR( cpage.ErrGetReadPage( ppib, ifmp, pgno, bflfNoTouch ) ); Call( cpage.ErrUpgradeReadLatchToWriteLatch() ); cpage.Dirty( bfdfFilthy ); (*pcprintf)( "replacing data at %lu:%d\r\n", pgno, iline ); cpage.Replace( iline, &data, 1, 0 ); HandleError: cpage.ReleaseWriteLatch( fTrue ); return err; } LOCAL ERR ErrDBUTLISetNodeFlags( PIB * const ppib, const IFMP ifmp, const PGNO pgno, const LONG iline, const INT fFlags, CPRINTF * const pcprintf ) { ERR err = JET_errSuccess; CPAGE cpage; CallR( cpage.ErrGetReadPage( ppib, ifmp, pgno, bflfNoTouch ) ); Call( cpage.ErrUpgradeReadLatchToWriteLatch() ); cpage.Dirty( bfdfFilthy ); (*pcprintf)( "settings flags at %lu:%d to 0x%x\r\n", pgno, iline, fFlags ); cpage.ReplaceFlags( iline, fFlags ); HandleError: cpage.ReleaseWriteLatch( fTrue ); return err; } LOCAL ERR ErrDBUTLIDeleteNode( PIB * const ppib, const IFMP ifmp, const PGNO pgno, const LONG iline, CPRINTF * const pcprintf ) { ERR err = JET_errSuccess; CPAGE cpage; CallR( cpage.ErrGetReadPage( ppib, ifmp, pgno, bflfNoTouch ) ); Call( cpage.ErrUpgradeReadLatchToWriteLatch() ); cpage.Dirty( bfdfFilthy ); (*pcprintf)( "deleting %lu:%d\r\n", pgno, iline ); cpage.Delete( iline ); HandleError: cpage.ReleaseWriteLatch( fTrue ); return err; } LOCAL ERR ErrDBUTLISetExternalHeader( PIB * const ppib, const IFMP ifmp, const PGNO pgno, const DATA& data, CPRINTF * const pcprintf ) { ERR err = JET_errSuccess; CPAGE cpage; CallR( cpage.ErrGetReadPage( ppib, ifmp, pgno, bflfNoTouch ) ); Call( cpage.ErrUpgradeReadLatchToWriteLatch() ); cpage.Dirty( bfdfFilthy ); (*pcprintf)( "setting external header of %lu\r\n", pgno ); cpage.SetExternalHeader( &data, 1, 0 ); HandleError: cpage.ReleaseWriteLatch( fTrue ); return err; } LOCAL ERR ErrDBUTLISetPgnoNext( PIB * const ppib, const IFMP ifmp, const PGNO pgno, const PGNO pgnoNext, CPRINTF * const pcprintf ) { ERR err = JET_errSuccess; CPAGE cpage; CallR( cpage.ErrGetReadPage( ppib, ifmp, pgno, bflfNoTouch ) ); Call( cpage.ErrUpgradeReadLatchToWriteLatch() ); cpage.Dirty( bfdfFilthy ); (*pcprintf)( "setting pgnoNext of %lu to %lu (was %lu)\r\n", pgno, pgnoNext, cpage.PgnoNext() ); cpage.SetPgnoNext( pgnoNext ); HandleError: cpage.ReleaseWriteLatch( fTrue ); return err; } LOCAL ERR ErrDBUTLISetPgnoPrev( PIB * const ppib, const IFMP ifmp, const PGNO pgno, const PGNO pgnoPrev, CPRINTF * const pcprintf ) { ERR err = JET_errSuccess; CPAGE cpage; CallR( cpage.ErrGetReadPage( ppib, ifmp, pgno, bflfNoTouch ) ); Call( cpage.ErrUpgradeReadLatchToWriteLatch() ); cpage.Dirty( bfdfFilthy ); (*pcprintf)( "setting pgnoPrev of %lu to %lu (was %lu)\r\n", pgno, pgnoPrev, cpage.PgnoPrev() ); cpage.SetPgnoPrev( pgnoPrev ); HandleError: cpage.ReleaseWriteLatch( fTrue ); return err; } LOCAL ERR ErrDBUTLISetPageFlags( PIB * const ppib, const IFMP ifmp, const PGNO pgno, const ULONG fFlags, CPRINTF * const pcprintf ) { ERR err = JET_errSuccess; CPAGE cpage; CallR( cpage.ErrGetReadPage( ppib, ifmp, pgno, bflfNoTouch ) ); Call( cpage.ErrUpgradeReadLatchToWriteLatch() ); cpage.Dirty( bfdfFilthy ); (*pcprintf)( "setting flags of %lu to 0x%x (was 0x%x)\r\n", pgno, fFlags, cpage.FFlags() ); cpage.SetFlags( fFlags ); HandleError: cpage.ReleaseWriteLatch( fTrue ); return err; } LOCAL_BROKEN ERR ErrDBUTLMungeDatabase( PIB * const ppib, const IFMP ifmp, const CHAR * const rgszCommand[], const INT cszCommand, CPRINTF * const pcprintf ) { ERR err = JET_errSuccess; if( 3 == cszCommand && _stricmp( rgszCommand[0], "insert" ) == 0 ) { PGNO pgno; LONG iline; DATA data; if( 2 != sscanf_s( rgszCommand[1], "%lu:%d", &pgno, &iline ) ) { return ErrERRCheck( JET_errInvalidParameter ); } CallR( ErrDBUTLISzToData( rgszCommand[2], &data ) ); err = ErrDBUTLIInsertNode( ppib, ifmp, pgno, iline, data, pcprintf ); OSMemoryHeapFree( data.Pv() ); return err; } if( 3 == cszCommand && _stricmp( rgszCommand[0], "replace" ) == 0 ) { PGNO pgno; LONG iline; DATA data; if( 2 != sscanf_s( rgszCommand[1], "%lu:%d", &pgno, &iline ) ) { return ErrERRCheck( JET_errInvalidParameter ); } CallR( ErrDBUTLISzToData( rgszCommand[2], &data ) ); err = ErrDBUTLIReplaceNode( ppib, ifmp, pgno, iline, data, pcprintf ); OSMemoryHeapFree( data.Pv() ); return err; } if( 3 == cszCommand && _stricmp( rgszCommand[0], "setflags" ) == 0 ) { PGNO pgno; LONG iline; if( 2 != sscanf_s( rgszCommand[1], "%lu:%d", &pgno, &iline ) ) { return ErrERRCheck( JET_errInvalidParameter ); } const ULONG fFlags = strtoul( rgszCommand[2], NULL, 0 ); err = ErrDBUTLISetNodeFlags( ppib, ifmp, pgno, iline, fFlags, pcprintf ); return err; } else if( 2 == cszCommand && _stricmp( rgszCommand[0], "delete" ) == 0 ) { PGNO pgno; LONG iline; if( 2 != sscanf_s( rgszCommand[1], "%lu:%d", &pgno, &iline ) ) { return ErrERRCheck( JET_errInvalidParameter ); } err = ErrDBUTLIDeleteNode( ppib, ifmp, pgno, iline, pcprintf ); return err; } if( 3 == cszCommand && _stricmp( rgszCommand[0], "exthdr" ) == 0 ) { char * pchEnd; const PGNO pgno = strtoul( rgszCommand[1], &pchEnd, 0 ); if( pgnoNull == pgno || 0 != *pchEnd ) { return ErrERRCheck( JET_errInvalidParameter ); } DATA data; CallR( ErrDBUTLISzToData( rgszCommand[2], &data ) ); err = ErrDBUTLISetExternalHeader( ppib, ifmp, pgno, data, pcprintf ); OSMemoryHeapFree( data.Pv() ); return err; } if( 3 == cszCommand && _stricmp( rgszCommand[0], "pgnonext" ) == 0 ) { char * pchEnd; const PGNO pgno = strtoul( rgszCommand[1], &pchEnd, 0 ); if( pgnoNull == pgno || 0 != *pchEnd ) { return ErrERRCheck( JET_errInvalidParameter ); } const PGNO pgnoNext = strtoul( rgszCommand[2], NULL, 0 ); if( 0 != *pchEnd ) { return ErrERRCheck( JET_errInvalidParameter ); } err = ErrDBUTLISetPgnoNext( ppib, ifmp, pgno, pgnoNext, pcprintf ); return err; } if( 3 == cszCommand && _stricmp( rgszCommand[0], "pgnoprev" ) == 0 ) { char * pchEnd; const PGNO pgno = strtoul( rgszCommand[1], &pchEnd, 0 ); if( pgnoNull == pgno || 0 != *pchEnd ) { return ErrERRCheck( JET_errInvalidParameter ); } const PGNO pgnoPrev = strtoul( rgszCommand[2], NULL, 0 ); if( 0 != *pchEnd ) { return ErrERRCheck( JET_errInvalidParameter ); } err = ErrDBUTLISetPgnoPrev( ppib, ifmp, pgno, pgnoPrev, pcprintf ); return err; } if( 3 == cszCommand && _stricmp( rgszCommand[0], "pageflags" ) == 0 ) { char * pchEnd; const PGNO pgno = strtoul( rgszCommand[1], &pchEnd, 0 ); if( pgnoNull == pgno || 0 != *pchEnd ) { return ErrERRCheck( JET_errInvalidParameter ); } const ULONG fFlags = strtoul( rgszCommand[2], NULL, 0 ); if( 0 != *pchEnd ) { return ErrERRCheck( JET_errInvalidParameter ); } err = ErrDBUTLISetPageFlags( ppib, ifmp, pgno, fFlags, pcprintf ); return err; } if( 1 == cszCommand && _stricmp( rgszCommand[0], "help" ) == 0 ) { (*pcprintf)( "insert <pgno>:<iline> <data> - insert a node\r\n" ); (*pcprintf)( "replace <pgno>:<iline> <data> - replace a node\r\n" ); (*pcprintf)( "delete <pgno>:<iline> - delete a node\r\n" ); (*pcprintf)( "setflags <pgno>:<iline> <flags> - set flags on a node\r\n" ); (*pcprintf)( "exthdr <pgno> <data> - set external header\r\n" ); (*pcprintf)( "pgnonext <pgno> <pgnonext> - set pgnonext on a page\r\n" ); (*pcprintf)( "pgnoprev <pgno> <pgnoprev> - set pgnoprev on a page\r\n" ); (*pcprintf)( "pageflags <pgno> <flags> - set flags on a page\r\n" ); } else { (*pcprintf)( "unknown command \"%s\"\r\n", rgszCommand[0] ); return ErrERRCheck( JET_errInvalidParameter ); } return err; } #endif LOCAL ERR ErrDBUTLDumpOneColumn( PIB * ppib, FUCB * pfucbCatalog, VOID * pfnCallback, VOID * pvCallback ) { JET_RETRIEVECOLUMN rgretrievecolumn[10]; COLUMNDEF columndef; ERR err = JET_errSuccess; INT iretrievecolumn = 0; memset( rgretrievecolumn, 0, sizeof( rgretrievecolumn ) ); memset( &columndef, 0, sizeof( columndef ) ); rgretrievecolumn[iretrievecolumn].columnid = fidMSO_Name; rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)columndef.szName; rgretrievecolumn[iretrievecolumn].cbData = sizeof( columndef.szName ); rgretrievecolumn[iretrievecolumn].itagSequence = 1; ++iretrievecolumn; rgretrievecolumn[iretrievecolumn].columnid = fidMSO_Id; rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&( columndef.columnid ); rgretrievecolumn[iretrievecolumn].cbData = sizeof( columndef.columnid ); rgretrievecolumn[iretrievecolumn].itagSequence = 1; ++iretrievecolumn; rgretrievecolumn[iretrievecolumn].columnid = fidMSO_Coltyp; rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&( columndef.coltyp ); rgretrievecolumn[iretrievecolumn].cbData = sizeof( columndef.coltyp ); rgretrievecolumn[iretrievecolumn].itagSequence = 1; ++iretrievecolumn; rgretrievecolumn[iretrievecolumn].columnid = fidMSO_Localization; rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&( columndef.cp ); rgretrievecolumn[iretrievecolumn].cbData = sizeof( columndef.cp ); rgretrievecolumn[iretrievecolumn].itagSequence = 1; ++iretrievecolumn; rgretrievecolumn[iretrievecolumn].columnid = fidMSO_Flags; rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&( columndef.fFlags ); rgretrievecolumn[iretrievecolumn].cbData = sizeof( columndef.fFlags ); rgretrievecolumn[iretrievecolumn].itagSequence = 1; ++iretrievecolumn; rgretrievecolumn[iretrievecolumn].columnid = fidMSO_SpaceUsage; rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&( columndef.cbLength ); rgretrievecolumn[iretrievecolumn].cbData = sizeof( columndef.cbLength ); rgretrievecolumn[iretrievecolumn].itagSequence = 1; ++iretrievecolumn; rgretrievecolumn[iretrievecolumn].columnid = fidMSO_RecordOffset; rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&( columndef.ibRecordOffset ); rgretrievecolumn[iretrievecolumn].cbData = sizeof( columndef.ibRecordOffset ); rgretrievecolumn[iretrievecolumn].itagSequence = 1; ++iretrievecolumn; rgretrievecolumn[iretrievecolumn].columnid = fidMSO_Callback; rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&( columndef.szCallback ); rgretrievecolumn[iretrievecolumn].cbData = sizeof( columndef.szCallback ); rgretrievecolumn[iretrievecolumn].itagSequence = 1; ++iretrievecolumn; rgretrievecolumn[iretrievecolumn].columnid = fidMSO_CallbackData; rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&( columndef.rgbCallbackData ); rgretrievecolumn[iretrievecolumn].cbData = sizeof( columndef.rgbCallbackData ); rgretrievecolumn[iretrievecolumn].itagSequence = 1; ++iretrievecolumn; rgretrievecolumn[iretrievecolumn].columnid = fidMSO_DefaultValue; rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)columndef.rgbDefaultValue; rgretrievecolumn[iretrievecolumn].cbData = sizeof( columndef.rgbDefaultValue ); rgretrievecolumn[iretrievecolumn].itagSequence = 1; ++iretrievecolumn; CallR( ErrIsamRetrieveColumns( (JET_SESID)ppib, (JET_TABLEID)pfucbCatalog, rgretrievecolumn, iretrievecolumn ) ); columndef.cbDefaultValue = rgretrievecolumn[iretrievecolumn-1].cbActual; columndef.cbCallbackData = rgretrievecolumn[iretrievecolumn-2].cbActual; columndef.fFixed = !!FFixedFid( FidOfColumnid( columndef.columnid ) ); columndef.fVariable = !!FVarFid( FidOfColumnid( columndef.columnid ) ); columndef.fTagged = !!FTaggedFid( FidOfColumnid( columndef.columnid ) ); const FIELDFLAG ffield = FIELDFLAG( columndef.fFlags ); columndef.fVersion = !!FFIELDVersion( ffield ); columndef.fNotNull = !!FFIELDNotNull( ffield ); columndef.fMultiValue = !!FFIELDMultivalued( ffield ); columndef.fAutoIncrement = !!FFIELDAutoincrement( ffield ); columndef.fDefaultValue = !!FFIELDDefault( ffield ); columndef.fEscrowUpdate = !!FFIELDEscrowUpdate( ffield ); columndef.fVersioned = !!FFIELDVersioned( ffield ); columndef.fDeleted = !!FFIELDDeleted( ffield ); columndef.fFinalize = !!FFIELDFinalize( ffield ); columndef.fDeleteOnZero = !!FFIELDDeleteOnZero( ffield ); columndef.fUserDefinedDefault = !!FFIELDUserDefinedDefault( ffield ); columndef.fTemplateColumnESE98 = !!FFIELDTemplateColumnESE98( ffield ); columndef.fPrimaryIndexPlaceholder = !!FFIELDPrimaryIndexPlaceholder( ffield ); columndef.fCompressed = !!FFIELDCompressed( ffield ); columndef.fEncrypted = !!FFIELDEncrypted( ffield ); PFNCOLUMN const pfncolumn = (PFNCOLUMN)pfnCallback; return (*pfncolumn)( &columndef, pvCallback ); } LOCAL ERR ErrDBUTLDumpOneCallback( PIB * ppib, FUCB * pfucbCatalog, VOID * pfnCallback, VOID * pvCallback ) { JET_RETRIEVECOLUMN rgretrievecolumn[3]; CALLBACKDEF callbackdef; ERR err = JET_errSuccess; INT iretrievecolumn = 0; memset( rgretrievecolumn, 0, sizeof( rgretrievecolumn ) ); memset( &callbackdef, 0, sizeof( callbackdef ) ); rgretrievecolumn[iretrievecolumn].columnid = fidMSO_Name; rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)callbackdef.szName; rgretrievecolumn[iretrievecolumn].cbData = sizeof( callbackdef.szName ); rgretrievecolumn[iretrievecolumn].itagSequence = 1; ++iretrievecolumn; rgretrievecolumn[iretrievecolumn].columnid = fidMSO_Flags; rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&( callbackdef.cbtyp ); rgretrievecolumn[iretrievecolumn].cbData = sizeof( callbackdef.cbtyp ); rgretrievecolumn[iretrievecolumn].itagSequence = 1; ++iretrievecolumn; rgretrievecolumn[iretrievecolumn].columnid = fidMSO_Callback; rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)callbackdef.szCallback; rgretrievecolumn[iretrievecolumn].cbData = sizeof( callbackdef.szCallback ); rgretrievecolumn[iretrievecolumn].itagSequence = 1; ++iretrievecolumn; CallR( ErrIsamRetrieveColumns( (JET_SESID)ppib, (JET_TABLEID)pfucbCatalog, rgretrievecolumn, iretrievecolumn ) ); PFNCALLBACKFN const pfncallback = (PFNCALLBACKFN)pfnCallback; return (*pfncallback)( &callbackdef, pvCallback ); } LOCAL ERR ErrDBUTLDumpPage( PIB * ppib, IFMP ifmp, PGNO pgno, PFNPAGE pfnpage, VOID * pvCallback ) { ERR err = JET_errSuccess; CSR csr; Call( csr.ErrGetReadPage( ppib, ifmp, pgno, bflfNoTouch ) ); PAGEDEF pagedef; pagedef.dbtime = csr.Cpage().Dbtime(); pagedef.pgno = pgno; pagedef.objidFDP = csr.Cpage().ObjidFDP(); pagedef.pgnoNext = csr.Cpage().PgnoNext(); pagedef.pgnoPrev = csr.Cpage().PgnoPrev(); pagedef.pbRawPage = reinterpret_cast<BYTE *>( csr.Cpage().PvBuffer() ); pagedef.cbFree = csr.Cpage().CbPageFree(); pagedef.cbUncommittedFree = csr.Cpage().CbUncommittedFree(); pagedef.clines = SHORT( csr.Cpage().Clines() ); pagedef.fFlags = csr.Cpage().FFlags(); pagedef.fLeafPage = !!csr.Cpage().FLeafPage(); pagedef.fInvisibleSons = !!csr.Cpage().FInvisibleSons(); pagedef.fRootPage = !!csr.Cpage().FRootPage(); pagedef.fPrimaryPage = !!csr.Cpage().FPrimaryPage(); pagedef.fParentOfLeaf = !!csr.Cpage().FParentOfLeaf(); if( pagedef.fInvisibleSons ) { Assert( !pagedef.fLeafPage ); INT iline; for( iline = 0; iline < pagedef.clines; iline++ ) { KEYDATAFLAGS kdf; csr.SetILine( iline ); NDIGetKeydataflags( csr.Cpage(), csr.ILine(), &kdf ); Assert( kdf.data.Cb() == sizeof( PGNO ) ); pagedef.rgpgnoChildren[iline] = *((UnalignedLittleEndian< PGNO > *)kdf.data.Pv() ); } pagedef.rgpgnoChildren[pagedef.clines] = pgnoNull; } else { Assert( pagedef.fLeafPage ); } Call( (*pfnpage)( &pagedef, pvCallback ) ); HandleError: csr.ReleasePage(); return err; } LOCAL INT PrintCallback( const CALLBACKDEF * pcallbackdef, void * ) { PFNCALLBACKFN pfncallback = PrintCallback; Unused( pfncallback ); char szCbtyp[255]; szCbtyp[0] = 0; if( JET_cbtypNull == pcallbackdef->cbtyp ) { OSStrCbAppendA( szCbtyp, sizeof(szCbtyp), "NULL" ); } if( pcallbackdef->cbtyp & JET_cbtypFinalize ) { OSStrCbAppendA( szCbtyp, sizeof(szCbtyp), "Finalize|" ); } if( pcallbackdef->cbtyp & JET_cbtypBeforeInsert ) { OSStrCbAppendA( szCbtyp, sizeof(szCbtyp), "BeforeInsert|" ); } if( pcallbackdef->cbtyp & JET_cbtypAfterInsert ) { OSStrCbAppendA( szCbtyp, sizeof(szCbtyp), "AfterInsert|" ); } if( pcallbackdef->cbtyp & JET_cbtypBeforeReplace ) { OSStrCbAppendA( szCbtyp, sizeof(szCbtyp), "BeforeReplace|" ); } if( pcallbackdef->cbtyp & JET_cbtypAfterReplace ) { OSStrCbAppendA( szCbtyp, sizeof(szCbtyp), "AfterReplace|" ); } if( pcallbackdef->cbtyp & JET_cbtypBeforeDelete ) { OSStrCbAppendA( szCbtyp, sizeof(szCbtyp), "BeforeDelete|" ); } if( pcallbackdef->cbtyp & JET_cbtypAfterDelete ) { OSStrCbAppendA( szCbtyp, sizeof(szCbtyp), "AfterDelete|" ); } szCbtyp[strlen( szCbtyp ) - 1] = 0; printf( " %2.2d (%s) %s\n", pcallbackdef->cbtyp, szCbtyp, pcallbackdef->szCallback ); return 0; } LOCAL VOID PrintSpaceHintMetaData( __in const CHAR * const szIndent, __in const CHAR * const szObjectType, __in const JET_SPACEHINTS * const pSpaceHints ) { printf( "%s%s Space Hints: cbStruct: %d, grbit=0x%x\n", szIndent, szObjectType, pSpaceHints->cbStruct, pSpaceHints->grbit ); printf( "%s Densities: Initial=%u%%, Maintenance=%u%%\n", szIndent, pSpaceHints->ulInitialDensity , pSpaceHints->ulMaintDensity ); printf( "%s Growth Hints: cbInitial=%u, ulGrowth=%u%%, cbMinExtent=%u, cbMaxExtent=%u\n", szIndent, pSpaceHints->cbInitial, pSpaceHints->ulGrowth, pSpaceHints->cbMinExtent, pSpaceHints->cbMaxExtent ); } LOCAL INT PrintIndexMetaData( const INDEXDEF * pindexdef, void * ) { PFNINDEX pfnindex = PrintIndexMetaData; Unused( pfnindex ); Assert( pindexdef ); printf( " %-15.15s ", pindexdef->szName ); DBUTLPrintfIntN( pindexdef->pgnoFDP, 8 ); printf( " " ); DBUTLPrintfIntN( pindexdef->objidFDP, 8 ); printf( " " ); DBUTLPrintfIntN( pindexdef->density, 6 ); printf( "%%\n" ); if ( pindexdef->fUnique ) printf( " Unique=yes\n" ); if ( pindexdef->fPrimary ) printf( " Primary=yes\n" ); if ( pindexdef->fTemplateIndex ) printf( " Template=yes\n" ); if ( pindexdef->fDerivedIndex ) printf( " Derived=yes\n" ); if ( pindexdef->fNoNullSeg ) printf( " Disallow Null=yes\n" ); if ( pindexdef->fAllowAllNulls ) printf( " Allow All Nulls=yes\n" ); if ( pindexdef->fAllowFirstNull ) printf( " Allow First Null=yes\n" ); if ( pindexdef->fAllowSomeNulls ) printf( " Allow Some Nulls=yes\n" ); if ( pindexdef->fSortNullsHigh ) printf( " Sort Nulls High=yes\n" ); if ( pindexdef->fMultivalued ) printf( " Multivalued=yes\n" ); if ( pindexdef->fTuples ) { printf( " Tuples=yes\n" ); printf( " LengthMin=%d\n", (ULONG) pindexdef->le_tuplelimits.le_chLengthMin ); printf( " LengthMax=%d\n", (ULONG) pindexdef->le_tuplelimits.le_chLengthMax ); printf( " ToIndexMax=%d\n", (ULONG) pindexdef->le_tuplelimits.le_chToIndexMax ); printf( " CchIncrement=%d\n", (ULONG) pindexdef->le_tuplelimits.le_cchIncrement ); printf( " IchStart=%d\n", (ULONG) pindexdef->le_tuplelimits.le_ichStart ); } if ( pindexdef->fLocalizedText ) { WCHAR wszLocaleName[NORM_LOCALE_NAME_MAX_LENGTH]; QWORD qwCurrSortVersion; SORTID sortID; printf( " Localized Text=yes\n" ); printf( " Locale Id=%d\n", pindexdef->lcid ); printf( " Locale Name=%ws\n", pindexdef->wszLocaleName ); printf( " LCMap flags=0x%08x\n", pindexdef->dwMapFlags ); if ( ( ( 0 != pindexdef->lcid ) && JET_errSuccess == ErrNORMLcidToLocale( pindexdef->lcid, wszLocaleName, _countof( wszLocaleName ) ) && JET_errSuccess == ErrNORMGetSortVersion( wszLocaleName, &qwCurrSortVersion, &sortID ) ) || ( JET_errSuccess == ErrNORMGetSortVersion( pindexdef->wszLocaleName, &qwCurrSortVersion, &sortID ) ) ) { WCHAR wszSortID[ PERSISTED_SORTID_MAX_LENGTH ] = L""; WCHAR wszIndexDefSortID[ PERSISTED_SORTID_MAX_LENGTH ] = L""; WszCATFormatSortID( pindexdef->sortID, wszIndexDefSortID, _countof( wszIndexDefSortID ) ); WszCATFormatSortID( sortID, wszSortID, _countof( wszSortID ) ); printf( " NLSVersion=%d (current OS: %d)\n", pindexdef->dwNLSVersion, DWORD( ( qwCurrSortVersion >> 32 ) & 0xFFFFFFFF ) ); printf( " DefinedVersion=%d (current OS: %d)\n", pindexdef->dwDefinedVersion, DWORD( qwCurrSortVersion & 0xFFFFFFFF ) ); printf( " SortID=%ws (current OS: %ws)\n", wszIndexDefSortID, wszSortID ); } else { WCHAR wszIndexDefSortID[ PERSISTED_SORTID_MAX_LENGTH ] = L""; WszCATFormatSortID( pindexdef->sortID, wszIndexDefSortID, _countof( wszIndexDefSortID ) ); printf( " NLSVersion=%d (current OS: <unknown>)\n", pindexdef->dwNLSVersion ); printf( " DefinedVersion=%d (current OS: <unknown>)\n", pindexdef->dwDefinedVersion ); printf( " SortID=%ws (current OS: <unknown>)\n", wszIndexDefSortID ); } } if ( pindexdef->fExtendedColumns ) printf( " Extended Columns=yes\n" ); printf( " Flags=0x%08x\n", pindexdef->fFlags ); if ( pindexdef->cbVarSegMac ) { printf( " Index Key Segment Length Specified=yes\n" ); printf( " Maximum Key Segment Length=0x%08x\n", pindexdef->cbVarSegMac ); } if ( pindexdef->cbKeyMost ) { printf( " Index Key Length Specified=yes\n" ); printf( " Maximum Key Length=0x%08x\n", pindexdef->cbKeyMost ); } PrintSpaceHintMetaData( " ", "Index", &(pindexdef->spacehints) ); UINT isz; Assert( pindexdef->ccolumnidDef > 0 ); if ( pindexdef->fExtendedColumns ) { printf( " Key Segments (%d)\n", pindexdef->ccolumnidDef ); printf( " -----------------\n" ); } else { printf( " Key Segments (%d - ESE97 format)\n", pindexdef->ccolumnidDef ); printf( " --------------------------------\n" ); } for( isz = 0; isz < (ULONG)pindexdef->ccolumnidDef; isz++ ) { printf( " %-15.15s (0x%08x)\n", pindexdef->rgszIndexDef[isz], pindexdef->rgidxsegDef[isz].Columnid() ); } if( pindexdef->ccolumnidConditional > 0 ) { if ( pindexdef->fExtendedColumns ) { printf( " Conditional Columns (%d)\n", pindexdef->ccolumnidConditional ); printf( " ------------------------\n" ); } else { printf( " Conditional Columns (%d - ESE97 format)\n", pindexdef->ccolumnidConditional ); printf( " ---------------------------------------\n" ); } for( isz = 0; isz < (ULONG)pindexdef->ccolumnidConditional; isz++ ) { printf( " %-15.15s (0x%08x,%s)\n", ( pindexdef->rgszIndexConditional[isz] ) + 1, pindexdef->rgidxsegConditional[isz].Columnid(), ( pindexdef->rgidxsegConditional[isz] ).FMustBeNull() ? "JET_bitIndexColumnMustBeNull" : "JET_bitIndexColumnMustBeNonNull" ); } } return 0; } LOCAL INT PrintColumn( const COLUMNDEF * pcolumndef, void * ) { PFNCOLUMN pfncolumn = PrintColumn; Unused( pfncolumn ); Assert( pcolumndef ); printf( " %-15.15s ", pcolumndef->szName ); DBUTLPrintfIntN( pcolumndef->columnid, 9 ); const CHAR * szType; const CHAR * szFVT; CHAR szUnknown[50]; if( pcolumndef->fFixed ) { szFVT = "(F)"; } else if( pcolumndef->fTagged ) { szFVT = "(T)"; } else if( pcolumndef->fVariable ) { szFVT = "(V)"; } else { AssertSz( fFalse, "Unknown column type is not fixed, tagged, or variable." ); szFVT = "(?)"; } switch ( pcolumndef->coltyp ) { case JET_coltypBit: szType = "Bit"; break; case JET_coltypUnsignedByte: szType = "UnsignedByte"; break; case JET_coltypShort: szType = "Short"; break; case JET_coltypUnsignedShort: szType = "UnsignedShort"; break; case JET_coltypLong: szType = "Long"; break; case JET_coltypUnsignedLong: szType = "UnsignedLong"; break; case JET_coltypLongLong: szType = "LongLong"; break; case JET_coltypUnsignedLongLong: szType = "UnsignedLongLong"; break; case JET_coltypCurrency: szType = "Currency"; break; case JET_coltypIEEESingle: szType = "IEEESingle"; break; case JET_coltypIEEEDouble: szType = "IEEEDouble"; break; case JET_coltypDateTime: szType = "DateTime"; break; case JET_coltypGUID: szType = "GUID"; break; case JET_coltypBinary: szType = "Binary"; break; case JET_coltypText: szType = "Text"; break; case JET_coltypLongBinary: szType = "LongBinary"; break; case JET_coltypLongText: szType = "LongText"; break; case JET_coltypNil: szType = "Deleted"; break; default: OSStrCbFormatA( szUnknown, sizeof(szUnknown), "???(%d)", pcolumndef->coltyp ); szType = szUnknown; break; } printf(" %-12.12s%3.3s ", szType, szFVT ); if ( pcolumndef->cbLength > 9999999 ) { DBUTLPrintfIntN( pcolumndef->cbLength / ( 1024 * 1024 ), 5 ); printf("MB"); } else { DBUTLPrintfIntN( pcolumndef->cbLength, 7 ); } if ( 0 != pcolumndef->cbDefaultValue ) { printf( " Yes" ); } printf( "\n" ); if ( pcolumndef->fFixed ) printf( " Offset=%d (0x%x)\n", pcolumndef->ibRecordOffset, pcolumndef->ibRecordOffset ); if ( FRECTextColumn( pcolumndef->coltyp ) ) { printf( " Code Page=%d (0x%x)\n", pcolumndef->cp, pcolumndef->cp ); } if ( pcolumndef->fVersion ) printf( " Version=yes\n" ); if ( pcolumndef->fNotNull ) printf( " Disallow Null=yes\n" ); if ( pcolumndef->fMultiValue ) printf( " Multi-value=yes\n" ); if ( pcolumndef->fAutoIncrement ) printf( " Auto-increment=yes\n" ); if ( pcolumndef->fEscrowUpdate ) printf( " EscrowUpdate=yes\n" ); if ( pcolumndef->fFinalize ) printf( " Finalize=yes\n" ); if ( pcolumndef->fDeleteOnZero ) printf( " DeleteOnZero=yes\n" ); if ( pcolumndef->fDefaultValue ) { printf( " DefaultValue=yes\n" ); printf( " Length=%d bytes\n", pcolumndef->cbDefaultValue ); } if ( pcolumndef->fUserDefinedDefault ) { printf( " User-defined Default=yes\n" ); printf( " Callback=%s\n", pcolumndef->szCallback ); printf( " CallbackData=%d bytes\n", pcolumndef->cbCallbackData ); } if ( pcolumndef->fTemplateColumnESE98 ) printf( " TemplateColumnESE98=yes\n" ); if ( pcolumndef->fPrimaryIndexPlaceholder ) printf( " PrimaryIndexPlaceholder=yes\n" ); if ( pcolumndef->fCompressed ) printf( " Compressed=yes\n" ); if ( pcolumndef->fEncrypted ) printf( " Encrypted=yes\n" ); printf( " Flags=0x%x\n", pcolumndef->fFlags ); return 0; } LOCAL INT PrintTableMetaData( const TABLEDEF * ptabledef, void * pv ) { PFNTABLE pfntable = PrintTableMetaData; Unused( pfntable ); Assert( ptabledef ); JET_DBUTIL_A * pdbutil = (JET_DBUTIL_A *)pv; printf( "Table Name PgnoFDP ObjidFDP PgnoLV ObjidLV Pages Density\n" "==========================================================================\n" "%hs\n", ptabledef->szName ); printf( " " ); DBUTLPrintfIntN( ptabledef->pgnoFDP, 8 ); printf( " " ); DBUTLPrintfIntN( ptabledef->objidFDP, 8 ); printf( " " ); DBUTLPrintfIntN( ptabledef->pgnoFDPLongValues, 8 ); printf( " " ); DBUTLPrintfIntN( ptabledef->objidFDPLongValues, 8 ); printf( " " ); DBUTLPrintfIntN( ptabledef->pages, 8 ); printf( " " ); DBUTLPrintfIntN( ptabledef->density, 6 ); printf( "%%\n" ); printf( " LV ChunkSize=%d\n", ptabledef->cbLVChunkMax ); if ( ptabledef->fFlags & JET_bitObjectSystem ) printf( " System Table=yes\n" ); if ( ptabledef->fFlags & JET_bitObjectTableFixedDDL ) printf( " FixedDDL=yes\n" ); if ( ptabledef->fFlags & JET_bitObjectTableTemplate ) printf( " Template=yes\n" ); if ( NULL != ptabledef->szTemplateTable && '\0' != ptabledef->szTemplateTable[0] ) { Assert( ptabledef->fFlags & JET_bitObjectTableDerived ); printf( " Derived From: %5s\n", ptabledef->szTemplateTable ); } else { Assert( !( ptabledef->fFlags & JET_bitObjectTableDerived ) ); } PrintSpaceHintMetaData( " ", "Table", &(ptabledef->spacehints) ); if ( ptabledef->spacehintsDeferredLV.cbStruct == sizeof(ptabledef->spacehintsDeferredLV) ) { PrintSpaceHintMetaData( " ", "Deferred LV", &(ptabledef->spacehintsDeferredLV) ); } JET_DBUTIL_W dbutil; ERR err = JET_errSuccess; printf( " Column Name Column Id Column Type Length Default\n" " -----------------------------------------------------------\n" ); memset( &dbutil, 0, sizeof( dbutil ) ); dbutil.cbStruct = sizeof( dbutil ); dbutil.op = opDBUTILEDBDump; dbutil.sesid = pdbutil->sesid; dbutil.dbid = pdbutil->dbid; dbutil.pgno = ptabledef->objidFDP; dbutil.pfnCallback = (void *)PrintColumn; dbutil.pvCallback = &dbutil; dbutil.edbdump = opEDBDumpColumns; err = ErrDBUTLDump( pdbutil->sesid, &dbutil ); printf( " Index Name PgnoFDP ObjidFDP Density\n" " --------------------------------------------\n" ); memset( &dbutil, 0, sizeof( dbutil ) ); dbutil.cbStruct = sizeof( dbutil ); dbutil.op = opDBUTILEDBDump; dbutil.sesid = pdbutil->sesid; dbutil.dbid = pdbutil->dbid; dbutil.pgno = ptabledef->objidFDP; dbutil.pfnCallback = (void *)PrintIndexMetaData; dbutil.pvCallback = &dbutil; dbutil.edbdump = opEDBDumpIndexes; err = ErrDBUTLDump( pdbutil->sesid, &dbutil ); printf( " Callback Type Callback\n" " --------------------------------------------\n" ); memset( &dbutil, 0, sizeof( dbutil ) ); dbutil.cbStruct = sizeof( dbutil ); dbutil.op = opDBUTILEDBDump; dbutil.sesid = pdbutil->sesid; dbutil.dbid = pdbutil->dbid; dbutil.pgno = ptabledef->objidFDP; dbutil.pfnCallback = (void *)PrintCallback; dbutil.pvCallback = &dbutil; dbutil.edbdump = opEDBDumpCallbacks; err = ErrDBUTLDump( pdbutil->sesid, &dbutil ); return err; } ERR ErrDBUTLGetIfmpFucbOfPage( _Inout_ JET_SESID sesid, PCWSTR wszDatabase, _In_ const CPAGE& cpage, _Out_ IFMP * pifmp, _Out_ FUCB ** ppfucb, _Out_writes_bytes_opt_(cbObjName) WCHAR * wszObjName = NULL, _In_ ULONG cbObjName = 0 ); #define cbDbutlObjNameMost ( JET_cbNameMost + 40 + 1 ) ERR ErrDBUTLGetIfmpFucbOfPage( _Inout_ JET_SESID sesid, PCWSTR wszDatabase, _In_ const CPAGE& cpage, _Out_ IFMP * pifmp, _Out_ FUCB ** ppfucbObj, _Out_writes_bytes_opt_(cbObjName) WCHAR * wszObjName, _In_ ULONG cbObjName ) { ERR err = JET_errSuccess; JET_DBID jdbid = JET_dbidNil; *pifmp = ifmpNil; *ppfucbObj = pfucbNil; TRY { (void)SetParam( reinterpret_cast<PIB*>( sesid )->m_pinst, NULL, JET_paramEnableIndexChecking, JET_IndexCheckingOff, NULL ); Call( ErrIsamAttachDatabase( sesid, wszDatabase, fFalse, NULL, 0, JET_bitDbReadOnly ) ); err = ErrIsamOpenDatabase( sesid, wszDatabase, NULL, &jdbid, JET_bitDbReadOnly ); if ( err < JET_errSuccess ) { CallS( ErrIsamDetachDatabase( sesid, NULL, wszDatabase ) ); Assert( jdbid == JET_dbidNil ); jdbid = JET_dbidNil; } Call( err ); Expected( reinterpret_cast<PIB*>( sesid )->Level() == 0 ); PGNO pgnoFDP = pgnoNull; CHAR szObjName[JET_cbNameMost+1]; Call( ErrCATSeekTableByObjid( reinterpret_cast<PIB*>( sesid ), (IFMP)jdbid, cpage.ObjidFDP(), szObjName, sizeof( szObjName ), &pgnoFDP ) ); Call( ErrFILEOpenTable( reinterpret_cast<PIB*>( sesid ), (IFMP)jdbid, ppfucbObj, szObjName ) ); Assert( (*ppfucbObj)->u.pfcb->FTypeTable() ); if ( wszObjName ) { Assert( ( cbDbutlObjNameMost - JET_cbNameMost ) > ( wcslen( L"::LV::[Space Tree]" ) * 2 ) ); OSStrCbFormatW( wszObjName, cbObjName, L"%hs", szObjName ); if ( (*ppfucbObj)->u.pfcb->FTypeLV() ) { OSStrCbAppendW( wszObjName, cbObjName, L"::LV" ); } if ( cpage.FFlags() & CPAGE::fPageSpaceTree ) { OSStrCbAppendW( wszObjName, cbObjName, L"::[Space Tree]" ); } } } EXCEPT( efaExecuteHandler ) { wprintf( L"WARNING: Hit exception or AV trying to attach database or lookup object or table, continuing without detailed info/strings.\n" ); *pifmp = ifmpNil; *ppfucbObj = pfucbNil; err = ErrERRCheck( JET_errDiskIO ); } Call( err ); *pifmp = (IFMP)jdbid; jdbid = JET_dbidNil; Assert( *pifmp != ifmpNil ); Assert( *ppfucbObj != pfucbNil ); return JET_errSuccess; HandleError: wprintf( L"WARNING: Hit error %d trying to attach, open or lookup object or table, continuing without detailed info/strings.\n", err ); Assert( *pifmp == ifmpNil ); Assert( *ppfucbObj == pfucbNil ); if ( jdbid != JET_dbidNil ) { CallS( ErrIsamCloseDatabase( sesid, jdbid, NO_GRBIT ) ); CallS( ErrIsamDetachDatabase( sesid, NULL, wszDatabase ) ); } return err; } void DBUTLCloseIfmpFucb( _Inout_ JET_SESID sesid, PCWSTR wszDatabase, _In_ IFMP ifmp, _Inout_ FUCB * pfucbObj ) { if ( pfucbObj != pfucbNil ) { Assert( pfucbObj->u.pfcb->FTypeTable() ); CallS( ErrFILECloseTable( reinterpret_cast<PIB*>( sesid ), pfucbObj ) ); } if ( ifmp != ifmpNil ) { CallS( ErrIsamCloseDatabase( sesid, ifmp, NO_GRBIT ) ); CallS( ErrIsamDetachDatabase( sesid, NULL, wszDatabase ) ); } } LOCAL ERR ErrDBUTLDumpNode( JET_SESID sesid, IFileSystemAPI *const pfsapi, const WCHAR * const wszFile, const PGNO pgno, const INT iline, const JET_GRBIT grbit ) { ERR err = JET_errSuccess; KEYDATAFLAGS kdf; CPAGE cpage; IFileAPI* pfapi = NULL; QWORD ibOffset = OffsetOfPgno( pgno ); VOID* pvPage = NULL; CHAR* szBuf = NULL; const INT cbWidth = UtilCprintfStdoutWidth() >= 116 ? 32 : 16; INT ilineCurrent; TraceContextScope tcUtil ( iorpDirectAccessUtil ); IFMP ifmp = ifmpNil; FUCB * pfucbTable = pfucbNil; pvPage = PvOSMemoryPageAlloc( g_cbPage, NULL ); if( NULL == pvPage ) { Call( ErrERRCheck( JET_errOutOfMemory ) ); } err = CIOFilePerf::ErrFileOpen( pfsapi, reinterpret_cast<PIB*>( sesid )->m_pinst, wszFile, IFileAPI::fmfReadOnly, iofileDbAttached, qwDumpingFileID, &pfapi ); if ( err < 0 ) { wprintf( L"Cannot open file %ws.\n\n", wszFile ); Call( err ); } Call( pfapi->ErrIORead( *tcUtil, ibOffset, g_cbPage, (BYTE* const)pvPage, qosIONormal ) ); cpage.LoadPage( 1, pgno, pvPage, g_cbPage ); if ( iline < -1 || iline >= cpage.Clines() ) { printf( "Invalid iline: %d\n\n", iline ); Call( ErrERRCheck( cpage.FPageIsInitialized() ? JET_errInvalidParameter : JET_errPageNotInitialized ) ); } if ( !cpage.FNewRecordFormat() && cpage.FPrimaryPage() && !cpage.FRepairedPage() && cpage.FLeafPage() && !cpage.FSpaceTree() && !cpage.FLongValuePage() ) { if ( iline == -1 ) { printf( "Cannot dump all nodes on old format page\n\n" ); Call( ErrERRCheck( JET_errInvalidParameter ) ); } VOID * pvBuf = PvOSMemoryPageAlloc( g_cbPage, NULL ); if( NULL == pvBuf ) { Call( ErrERRCheck( JET_errOutOfMemory ) ); } err = ErrUPGRADEConvertNode( &cpage, iline, pvBuf ); OSMemoryPageFree( pvBuf ); Call( err ); } szBuf = (CHAR *)PvOSMemoryPageAlloc( g_cbPage * 8, NULL ); if( NULL == szBuf ) { Call( ErrERRCheck( JET_errOutOfMemory ) ); } ilineCurrent = ( iline == -1 ) ? 0 : iline; do { if ( ilineCurrent >= cpage.Clines() ) { Assert( ilineCurrent == 0 ); printf( "ERROR: This page doesn't even have one valid iline. Q: Blank? A: %hs\n", cpage.FPageIsInitialized() ? "No" : "Yes" ); Call( ErrERRCheck( cpage.FPageIsInitialized() ? JET_errInvalidParameter : JET_errPageNotInitialized ) ); } NDIGetKeydataflags( cpage, ilineCurrent, &kdf ); printf( " Node: %d:%d\n\n", pgno, ilineCurrent ); printf( " Flags: 0x%4.4x\n", kdf.fFlags ); printf( "===========\n" ); if( FNDVersion( kdf ) ) { printf( " Versioned\n" ); } if( FNDDeleted( kdf ) ) { printf( " Deleted\n" ); } if( FNDCompressed( kdf ) ) { printf( " Compressed\n" ); } printf( "\n" ); printf( "Key Prefix: %4d bytes\n", kdf.key.prefix.Cb() ); printf( "===========\n" ); szBuf[0] = 0; DBUTLSprintHex( szBuf, g_cbPage * 8, reinterpret_cast<BYTE *>( kdf.key.prefix.Pv() ), kdf.key.prefix.Cb(), cbWidth ); printf( "%s\n", szBuf ); printf( "Key Suffix: %4d bytes\n", kdf.key.suffix.Cb() ); printf( "===========\n" ); szBuf[0] = 0; DBUTLSprintHex( szBuf, g_cbPage * 8, reinterpret_cast<BYTE *>( kdf.key.suffix.Pv() ), kdf.key.suffix.Cb(), cbWidth ); printf( "%s\n", szBuf ); printf( " Data: %4d bytes\n", kdf.data.Cb() ); printf( "===========\n" ); szBuf[0] = 0; DBUTLSprintHex( szBuf, g_cbPage * 8, reinterpret_cast<BYTE *>( kdf.data.Pv() ), kdf.data.Cb(), cbWidth ); printf( "%s\n", szBuf ); printf( "\n\n" ); if( !cpage.FLeafPage() ) { if( sizeof( PGNO ) == kdf.data.Cb() ) { const PGNO pgnoChild = *(reinterpret_cast<UnalignedLittleEndian< PGNO > *>( kdf.data.Pv() ) ); printf( "pgnoChild = %lu (0x%x)\n", pgnoChild, pgnoChild ); } } else if( cpage.FSpaceTree() ) { PGNO pgnoLast; CPG cpg; SpacePool sppPool; Call( ErrSPIGetExtentInfo( &kdf, &pgnoLast, &cpg, &sppPool ) ); printf( "%d (0x%x) pages ending at %lu (0x%x) in pool %lu (%ws)\n", cpg, cpg, pgnoLast, pgnoLast, (ULONG)sppPool, WszPoolName( sppPool ) ); } else if( cpage.FPrimaryPage() ) { if( cpage.FLongValuePage() ) { } else { if ( ifmp == ifmpNil && pfucbTable == pfucbNil ) { tcUtil->iorReason.SetIorp( iorpNone ); OnDebug( ERR errT = )ErrDBUTLGetIfmpFucbOfPage( sesid, wszFile, cpage, &ifmp, &pfucbTable ); tcUtil->iorReason.SetIorp( iorpDirectAccessUtil ); Assert( errT < JET_errSuccess || ifmp != ifmpNil ); Assert( errT < JET_errSuccess || pfucbTable != pfucbNil ); Assert( errT >= JET_errSuccess || ifmp == ifmpNil ); Assert( errT >= JET_errSuccess || pfucbTable == pfucbNil ); } DBUTLDumpRec( cpage.CbPage(), pfucbTable, kdf.data.Pv(), kdf.data.Cb(), CPRINTFSTDOUT::PcprintfInstance(), cbWidth ); } } ilineCurrent++; } while ( iline == -1 && ilineCurrent < cpage.Clines() ); HandleError: DBUTLCloseIfmpFucb( sesid, wszFile, ifmp, pfucbTable ); if ( cpage.FLoadedPage() ) { cpage.UnloadPage(); } OSMemoryPageFree( szBuf ); OSMemoryPageFree( pvPage ); delete pfapi; return err; } LOCAL BOOL FDBUTLConvertHexDigit_( const CHAR cHexDigit, __out_bcount_full(1) CHAR * const pcHexValue ) { if ( cHexDigit >= '0' && cHexDigit <= '9' ) { *pcHexValue = cHexDigit - '0'; return fTrue; } else if ( cHexDigit >= 'A' && cHexDigit <= 'F' ) { *pcHexValue = cHexDigit - 'A' + 0xa; return fTrue; } else if ( cHexDigit >= 'a' && cHexDigit <= 'f' ) { *pcHexValue = cHexDigit - 'a' + 0xa; return fTrue; } else { return fFalse; } } LOCAL BOOL FDBUTLPrintedKeyToRealKey( __in_bcount(2 * cbKey) const CHAR * const szPrintedKey, __out_bcount_full(cbKey) CHAR * const szKey, const ULONG cbKey ) { for ( ULONG i = 0; i < cbKey; i++ ) { const ULONG j = i * 2; CHAR cHighNibble; CHAR cLowNibble; if ( 0 == i ) { printf( "%c%c", szPrintedKey[j], szPrintedKey[j+1] ); } else { printf( " %c%c", szPrintedKey[j], szPrintedKey[j+1] ); } if ( !FDBUTLConvertHexDigit_( szPrintedKey[j], &cHighNibble ) || !FDBUTLConvertHexDigit_( szPrintedKey[j+1], &cLowNibble ) ) { return fFalse; } szKey[i] = ( cHighNibble << 4 ) + cLowNibble; } return fTrue; } LOCAL ERR ErrDBUTLSeekToKey_( IFileAPI * pfapi, PGNO pgnoRoot, CPAGE& cpage, VOID * const pvPageBuf, const CHAR * const szPrintedKey, const CHAR * const szPrintedData ) { ERR err; CHAR szKey[cbKeyAlloc]; CHAR szData[cbKeyAlloc]; const ULONG cbPrintedKey = (ULONG)strlen( szPrintedKey ); const ULONG cbPrintedData = ( NULL != szPrintedData ? (ULONG)strlen( szPrintedData ) : 0 ); BOOKMARK bm; INT compare; INT iline; PGNO pgnoCurr = pgnoRoot; if ( cbPrintedKey % 2 != 0 || cbPrintedKey > ( cbKeyAlloc * 2 ) || cbPrintedData % 2 != 0 || cbPrintedData > ( cbKeyAlloc * 2 ) ) { return ErrERRCheck( JET_errInvalidBookmark ); } printf( " Seek bookmark: \"" ); bm.Nullify(); bm.key.suffix.SetPv( szKey ); bm.key.suffix.SetCb( cbPrintedKey / 2 ); if ( cpage.FNonUniqueKeys() && 0 != cbPrintedData ) { bm.data.SetPv( szData ); bm.data.SetCb( cbPrintedData / 2 ); } const INT cbSuffix = bm.key.suffix.Cb(); AssertPREFIX( sizeof( szKey ) >= cbSuffix ); if ( !FDBUTLPrintedKeyToRealKey( szPrintedKey, szKey, cbSuffix ) ) { printf( "...\"\n\n" ); return ErrERRCheck( JET_errInvalidBookmark ); } const INT cbData = bm.data.Cb(); if ( cbData > 0 ) { printf( " | " ); AssertPREFIX( sizeof( szData ) >= cbData ); if ( !FDBUTLPrintedKeyToRealKey( szPrintedData, szData, cbData ) ) { printf( "...\"\n\n" ); return ErrERRCheck( JET_errInvalidBookmark ); } } printf( "\"\n" ); while ( !cpage.FLeafPage() ) { iline = IlineNDISeekGEQInternal( cpage, bm, &compare ); if ( 0 == compare ) { iline++; } printf( " pgno/iline: %lu-%d (", pgnoCurr, iline ); if ( cpage.FRootPage() ) printf( "root," ); if ( cpage.FParentOfLeaf() ) printf( "parent-of-leaf" ); else printf( "internal" ); printf( ")\n" ); KEYDATAFLAGS kdf; NDIGetKeydataflags( cpage, iline, &kdf ); if ( sizeof(PGNO) != kdf.data.Cb() ) { printf( "\n" ); return ErrERRCheck( JET_errBadPageLink ); } const PGNO pgnoChild = *(UnalignedLittleEndian< PGNO > *)kdf.data.Pv(); cpage.UnloadPage(); err = pfapi->ErrIORead( *TraceContextScope( iorpDirectAccessUtil ), OffsetOfPgno( pgnoChild ), g_cbPage, (BYTE* const)pvPageBuf, qosIONormal ); if ( err < 0 ) { printf( "\n" ); return err; } cpage.LoadPage( 1, pgnoChild, pvPageBuf, g_cbPage ); pgnoCurr = pgnoChild; } iline = IlineNDISeekGEQ( cpage, bm, !cpage.FNonUniqueKeys(), &compare ); Assert( iline < cpage.Clines( ) ); if ( iline < 0 ) { iline = cpage.Clines( ) - 1; } printf( " pgno/iline: %lu-%d (%sleaf)\n\n", pgnoCurr, iline, ( cpage.FRootPage() ? "root," : "" ) ); return JET_errSuccess; } LOCAL ERR ErrDBUTLDumpPage( INST * const pinst, const WCHAR * wszFile, const PGNO pgno, const WCHAR * const wszPrintedKeyToSeek, const WCHAR * const wszPrintedDataToSeek, const JET_GRBIT grbit ) { ERR err = JET_errSuccess; IFileSystemAPI * const pfsapi = pinst->m_pfsapi; IFileAPI * pfapi = NULL; CPAGE cpage; TraceContextScope tcUtil ( iorpDirectAccessUtil ); VOID * const pvPage = PvOSMemoryPageAlloc( g_cbPage, NULL ); if( NULL == pvPage ) { CallR( ErrERRCheck( JET_errOutOfMemory ) ); } err = CIOFilePerf::ErrFileOpen( pfsapi, pinst, wszFile, IFileAPI::fmfReadOnly, iofileDbAttached, qwDumpingFileID, &pfapi ); if ( err < 0 ) { printf( "Cannot open file %ws.\n\n", wszFile ); Call( err ); } Call( pfapi->ErrIORead( *tcUtil, OffsetOfPgno( pgno ), g_cbPage, (BYTE* const)pvPage, qosIONormal ) ); cpage.LoadPage( 1, pgno, pvPage, g_cbPage ); if ( cpage.Clines() == -1 ) { AssertSz( cpage.ObjidFDP() == 0 || cpage.FPreInitPage(), "Odd page (%d):0 TAG page should be all 0s\r\n", cpage.PgnoThis() ); } else { Call( cpage.ErrCheckPage( CPRINTFSTDOUT::PcprintfInstance() ) ); } if ( NULL != wszPrintedKeyToSeek && 0 != cpage.Clines() ) { CAutoSZ szPrintedKeyToSeek; CAutoSZ szPrintedDataToSeek; Call( szPrintedKeyToSeek.ErrSet( wszPrintedKeyToSeek ) ); Call( szPrintedDataToSeek.ErrSet( wszPrintedDataToSeek ) ); Call( ErrDBUTLSeekToKey_( pfapi, pgno, cpage, pvPage, (CHAR*)szPrintedKeyToSeek, (CHAR*)szPrintedDataToSeek ) ); } #ifdef DEBUGGER_EXTENSION (VOID)cpage.DumpHeader( CPRINTFSTDOUT::PcprintfInstance() ); printf( "\n" ); (VOID)cpage.DumpTags( CPRINTFSTDOUT::PcprintfInstance() ); printf( "\n" ); #endif if( grbit & JET_bitDBUtilOptionDumpVerbose ) { (VOID)cpage.DumpAllocMap( CPRINTFSTDOUT::PcprintfInstance() ); printf( "\n" ); const INT cbWidth = UtilCprintfStdoutWidth() >= 116 ? 32 : 16; CHAR * szBuf = new CHAR[g_cbPage * 8]; if( NULL == szBuf ) { Call( ErrERRCheck( JET_errOutOfMemory ) ); } printf( "Raw dump (cbPage = %d / cbBuffer = %d) in big-endian quartets of bytes (not little endian DWORDs):\n", g_cbPage, g_cbPage ); DBUTLSprintHex( szBuf, g_cbPage * 8, reinterpret_cast<BYTE *>( pvPage ), g_cbPage, cbWidth ); printf( "%s\n", szBuf ); delete [] szBuf; } HandleError: if ( cpage.FLoadedPage() ) { cpage.UnloadPage(); } delete pfapi; OSMemoryPageFree( pvPage ); return err; } class CDBUTLIRunCalculator { CStats * m_pStats; ULONG * m_pcForwardScans; ULONG m_cpgCurrRun; PGNO m_pgnoPrevious; public: CDBUTLIRunCalculator( CStats * pStat, ULONG * pcHaltedForwardProgress ) : m_pStats( pStat ), m_pcForwardScans( pcHaltedForwardProgress ) { m_cpgCurrRun = 0; m_pgnoPrevious = 0x0; Assert( m_pStats ); Assert( m_pcForwardScans ); Assert( *m_pcForwardScans == 0 ); } ~CDBUTLIRunCalculator( ) { Assert( m_pgnoPrevious == pgnoDoneSentinel ); Assert( m_cpgCurrRun == 0 ); m_pStats = NULL; m_pcForwardScans = NULL; } ERR ErrBreak( void ) { ERR err = JET_errSuccess; if ( m_cpgCurrRun != 0 ) { if ( m_pStats->ErrAddSample( m_cpgCurrRun ) == CStats::ERR::errOutOfMemory ) { return ErrERRCheck( JET_errOutOfMemory ); } m_cpgCurrRun = 0; } return err; } static const PGNO pgnoDoneSentinel = 0xFFFFFFFF; ERR ErrProcessPage( PGNO pgno ) { ERR err = JET_errSuccess; Assert( pgno != 0x0 ); if ( m_pgnoPrevious == pgnoDoneSentinel ) { Assert( m_pgnoPrevious != pgnoDoneSentinel ); return JET_errSuccess; } if ( pgnoDoneSentinel == pgno ) { Call( ErrBreak() ); if ( m_pStats->C() ) { (*m_pcForwardScans)++; } } else { if ( pgno < m_pgnoPrevious ) { (*m_pcForwardScans)++; } if ( m_pgnoPrevious != 0x0 ) { if ( m_pgnoPrevious + 1 != pgno ) { Call( ErrBreak() ); } } m_cpgCurrRun++; } m_pgnoPrevious = pgno; return JET_errSuccess; HandleError: Assert( err == JET_errOutOfMemory ); return err; } }; class CBTreeStatsManager { private: BTREE_STATS_BASIC_CATALOG m_btsBasicCatalog; BTREE_STATS_SPACE_TREES m_btsSpaceTrees; BTREE_STATS_PARENT_OF_LEAF m_btsParentOfLeaf; BTREE_STATS_PAGE_SPACE m_btsInternalPageSpace; BTREE_STATS_PAGE_SPACE m_btsFullWalk; BTREE_STATS_LV m_btsLvData; CPerfectHistogramStats m_rgHistos[20]; BTREE_STATS m_bts; public: CBTreeStatsManager( JET_GRBIT grbit, BTREE_STATS * pbtsParent ) { memset( &m_btsBasicCatalog, 0, sizeof(m_btsBasicCatalog) ); m_btsBasicCatalog.cbStruct = sizeof(m_btsBasicCatalog); memset( &m_btsSpaceTrees, 0, sizeof(m_btsSpaceTrees) ); m_btsSpaceTrees.cbStruct = sizeof(m_btsSpaceTrees); memset( &m_btsParentOfLeaf, 0, sizeof(m_btsParentOfLeaf) ); m_btsParentOfLeaf.cbStruct = sizeof(m_btsParentOfLeaf); memset( &m_btsInternalPageSpace, 0, sizeof(m_btsInternalPageSpace) ); m_btsInternalPageSpace.cbStruct = sizeof(m_btsInternalPageSpace); memset( &m_btsFullWalk, 0, sizeof(m_btsFullWalk) ); m_btsFullWalk.cbStruct = sizeof(m_btsFullWalk); memset( &m_btsLvData, 0, sizeof(m_btsLvData) ); m_btsLvData.cbStruct = sizeof(m_btsLvData); m_btsParentOfLeaf.phistoIOContiguousRuns = (JET_HISTO*)&m_rgHistos[0]; m_btsFullWalk.phistoFreeBytes = (JET_HISTO*)&m_rgHistos[1]; m_btsFullWalk.phistoNodeCounts = (JET_HISTO*)&m_rgHistos[2]; m_btsFullWalk.phistoKeySizes = (JET_HISTO*)&m_rgHistos[3]; m_btsFullWalk.phistoDataSizes = (JET_HISTO*)&m_rgHistos[4]; m_btsFullWalk.phistoKeyCompression = (JET_HISTO*)&m_rgHistos[5]; m_btsFullWalk.phistoUnreclaimedBytes = (JET_HISTO*)&m_rgHistos[6]; m_btsFullWalk.cVersionedNodes = 0; m_btsInternalPageSpace.phistoFreeBytes = (JET_HISTO*)&m_rgHistos[7]; m_btsInternalPageSpace.phistoNodeCounts = (JET_HISTO*)&m_rgHistos[8]; m_btsInternalPageSpace.phistoKeySizes = (JET_HISTO*)&m_rgHistos[9]; m_btsInternalPageSpace.phistoDataSizes = (JET_HISTO*)&m_rgHistos[10]; m_btsInternalPageSpace.phistoKeyCompression = (JET_HISTO*)&m_rgHistos[11]; m_btsInternalPageSpace.phistoUnreclaimedBytes = (JET_HISTO*)&m_rgHistos[12]; m_btsLvData.phistoLVSize = (JET_HISTO*)&m_rgHistos[13]; m_btsLvData.phistoLVComp = (JET_HISTO*)&m_rgHistos[14]; m_btsLvData.phistoLVRatio = (JET_HISTO*)&m_rgHistos[15]; m_btsLvData.phistoLVSeeks = (JET_HISTO*)&m_rgHistos[16]; m_btsLvData.phistoLVBytes = (JET_HISTO*)&m_rgHistos[17]; m_btsLvData.phistoLVExtraSeeks = (JET_HISTO*)&m_rgHistos[18]; m_btsLvData.phistoLVExtraBytes = (JET_HISTO*)&m_rgHistos[19]; memset( &m_bts, 0, sizeof(m_bts) ); m_bts.cbStruct = sizeof(m_bts); m_bts.grbitData = grbit; m_bts.pParent = pbtsParent; m_bts.pBasicCatalog = ( m_bts.grbitData & JET_bitDBUtilSpaceInfoBasicCatalog ) ? &m_btsBasicCatalog : NULL; m_bts.pSpaceTrees = ( m_bts.grbitData & JET_bitDBUtilSpaceInfoSpaceTrees ) ? &m_btsSpaceTrees : NULL; m_bts.pParentOfLeaf = ( m_bts.grbitData & JET_bitDBUtilSpaceInfoParentOfLeaf ) ? &m_btsParentOfLeaf : NULL; if ( m_bts.pParentOfLeaf ) { m_bts.pParentOfLeaf->pInternalPageStats = &m_btsInternalPageSpace; } m_bts.pFullWalk = ( m_bts.grbitData & JET_bitDBUtilSpaceInfoFullWalk ) ? &m_btsFullWalk : NULL; m_bts.pLvData = ( m_bts.grbitData & JET_bitDBUtilSpaceInfoBasicCatalog && m_bts.grbitData & JET_bitDBUtilSpaceInfoFullWalk ) ? &m_btsLvData : NULL; } static void ResetParentOfLeaf( BTREE_STATS_PARENT_OF_LEAF * pPOL ) { Assert( pPOL ); Assert( pPOL->cbStruct == sizeof(*pPOL) ); Assert( pPOL->phistoIOContiguousRuns ); pPOL->fEmpty = fFalse; pPOL->cpgInternal = 0; pPOL->cpgData = 0; pPOL->cDepth = 0; Assert( pPOL->phistoIOContiguousRuns ); CStatsFromPv(pPOL->phistoIOContiguousRuns)->Zero(); pPOL->cForwardScans = 0; Assert( pPOL->pInternalPageStats ); Assert( pPOL->pInternalPageStats->phistoFreeBytes ); CStatsFromPv(pPOL->pInternalPageStats->phistoFreeBytes)->Zero(); CStatsFromPv(pPOL->pInternalPageStats->phistoNodeCounts)->Zero(); CStatsFromPv(pPOL->pInternalPageStats->phistoKeySizes)->Zero(); CStatsFromPv(pPOL->pInternalPageStats->phistoDataSizes)->Zero(); CStatsFromPv(pPOL->pInternalPageStats->phistoKeyCompression)->Zero(); CStatsFromPv(pPOL->pInternalPageStats->phistoUnreclaimedBytes)->Zero(); } static void ResetFullWalk( BTREE_STATS_PAGE_SPACE * pFW ) { Assert( pFW ); Assert( pFW->cbStruct == sizeof(*pFW) ); Assert( pFW->phistoFreeBytes ); CStatsFromPv(pFW->phistoFreeBytes)->Zero(); Assert( pFW->phistoNodeCounts ); CStatsFromPv(pFW->phistoNodeCounts)->Zero(); Assert( pFW->phistoKeySizes ); CStatsFromPv(pFW->phistoKeySizes)->Zero(); Assert( pFW->phistoDataSizes ); CStatsFromPv(pFW->phistoDataSizes)->Zero(); Assert( pFW->phistoKeyCompression ); CStatsFromPv(pFW->phistoKeyCompression)->Zero(); Assert( pFW->phistoUnreclaimedBytes ); CStatsFromPv(pFW->phistoUnreclaimedBytes)->Zero(); pFW->cVersionedNodes = 0; } static void ResetSpaceTreeInfo( BTREE_STATS_SPACE_TREES * pbtsST ) { Assert( pbtsST ); if ( pbtsST->prgOwnedExtents ) { delete [] pbtsST->prgOwnedExtents; pbtsST->prgOwnedExtents = NULL; } if ( pbtsST->prgAvailExtents ) { delete [] pbtsST->prgAvailExtents; pbtsST->prgAvailExtents = NULL; } Assert( pbtsST->prgOwnedExtents == NULL ); Assert( pbtsST->prgAvailExtents == NULL ); memset( pbtsST, 0, sizeof(*pbtsST) ); pbtsST->cbStruct = sizeof(*pbtsST); } static void ResetLvData( BTREE_STATS_LV * pLvData ) { if ( pLvData ) { Assert( pLvData->cbStruct == sizeof(*pLvData) ); pLvData->cLVRefs = 0; pLvData->cCorruptLVs = 0; pLvData->cSeparatedRootChunks = 0; pLvData->cPartiallyDeletedLVs = 0; pLvData->lidMax = 0; CStatsFromPv( pLvData->phistoLVSize )->Zero(); CStatsFromPv( pLvData->phistoLVComp )->Zero(); CStatsFromPv( pLvData->phistoLVRatio )->Zero(); CStatsFromPv( pLvData->phistoLVSeeks )->Zero(); CStatsFromPv( pLvData->phistoLVBytes )->Zero(); CStatsFromPv( pLvData->phistoLVExtraSeeks )->Zero(); CStatsFromPv( pLvData->phistoLVExtraBytes )->Zero(); } } ~CBTreeStatsManager () { if ( m_bts.pParentOfLeaf ) { ResetParentOfLeaf( m_bts.pParentOfLeaf ); } if ( m_bts.pFullWalk ) { ResetFullWalk( m_bts.pFullWalk ); } if ( m_bts.pSpaceTrees ) { ResetSpaceTreeInfo( m_bts.pSpaceTrees ); } if ( m_bts.pLvData ) { ResetLvData( m_bts.pLvData ); } } BTREE_STATS * Pbts( void ) { return &m_bts; } }; LOCAL ERR ErrEnumDataNodes( PIB * ppib, const IFMP ifmp, const PGNO pgnoFDP, PFNVISITPAGE pfnErrVisitPage, void * pvVisitPageCtx, CPAGE::PFNVISITNODE pfnErrVisitNode, void * pvVisitNodeCtx ) { ERR err; FUCB *pfucb = pfucbNil; BOOL fForceInit = fFalse; DIB dib; PGNO pgnoLastSeen = pgnoNull; CPG cpgSeen = 0; CallR( ErrBTOpen( ppib, pgnoFDP, ifmp, &pfucb ) ); Assert( pfucbNil != pfucb ); Assert( pfcbNil != pfucb->u.pfcb ); if ( !pfucb->u.pfcb->FInitialized() ) { Assert( pgnoSystemRoot != pgnoFDP ); Assert( pgnoFDPMSO != pgnoFDP ); Assert( pgnoFDPMSO_NameIndex != pgnoFDP ); Assert( pgnoFDPMSO_RootObjectIndex != pgnoFDP ); Assert( pfucb->u.pfcb->WRefCount() == 1 ); pfucb->u.pfcb->Lock(); pfucb->u.pfcb->CreateComplete(); pfucb->u.pfcb->Unlock(); fForceInit = fTrue; } else if ( pgnoSystemRoot == pgnoFDP || pgnoFDPMSO == pgnoFDP || pgnoFDPMSO_NameIndex == pgnoFDP || pgnoFDPMSO_RootObjectIndex == pgnoFDP ) { } BTUp( pfucb ); if ( pfucb->u.pfcb->FPrimaryIndex() || pfucb->u.pfcb->FTypeLV() || FFUCBSpace( pfucb ) ) { FUCBSetSequential( pfucb ); FUCBSetPrereadForward( pfucb, cpgPrereadSequential ); } dib.dirflag = fDIRNull; dib.pos = posFirst; err = ErrBTDown( pfucb, &dib, latchReadNoTouch ); if ( err != JET_errRecordNotFound ) { Call( err ); forever { if( pgnoLastSeen != Pcsr( pfucb )->Pgno() ) { pgnoLastSeen = Pcsr( pfucb )->Pgno(); ++cpgSeen; if ( pfnErrVisitPage ) { Call( pfnErrVisitPage( pgnoLastSeen, 0xFFFFFFFF , &(Pcsr( pfucb )->Cpage()), pvVisitPageCtx ) ); } if ( pfnErrVisitNode ) { Call( Pcsr( pfucb )->Cpage().ErrEnumTags( pfnErrVisitNode, pvVisitNodeCtx ) ); } } err = ErrBTNext( pfucb, fDIRNull ); if ( err < 0 ) { if ( err != JET_errNoCurrentRecord ) { goto HandleError; } break; } } } err = JET_errSuccess; HandleError: Assert( pfucbNil != pfucb ); if ( fForceInit ) { Assert( pfucb->u.pfcb->WRefCount() == 1 ); pfucb->u.pfcb->Lock(); pfucb->u.pfcb->CreateCompleteErr( errFCBUnusable ); pfucb->u.pfcb->Unlock(); } BTClose( pfucb ); return err; } ERR ErrAccumulatePageStats( const CPAGE::PGHDR * const ppghdr, INT itag, DWORD fNodeFlags, const KEYDATAFLAGS * const pkdf, void * pvCtx ); LOCAL ERR ErrDBUTLGetDataPageStats( PIB * ppib, IFMP ifmp, const PGNO pgnoFDP, BTREE_STATS_PAGE_SPACE * pFullWalk, BTREE_STATS_LV * pLvData ) { ERR err = JET_errSuccess; CBTreeStatsManager::ResetFullWalk( pFullWalk ); Assert( pFullWalk->phistoFreeBytes ); CBTreeStatsManager::ResetLvData( pLvData ); if ( fFalse ) { err = ErrEnumDataNodes( ppib, ifmp, pgnoFDP, NULL, NULL, ErrAccumulatePageStats, pFullWalk ); } else { if ( pLvData ) { EVAL_LV_PAGE_CTX ctx = { 0 }; ctx.cpgAccumMax = 0; ctx.rgpgnoAccum = NULL; ctx.pLvData = pLvData; CPAGE::PFNVISITNODE rgpfnzErrVisitNode[3] = { ErrAccumulatePageStats, ErrAccumulateLvNodeData, NULL }; void * rgpvzVisitNodeCtx[3] = { pFullWalk, &ctx, NULL }; err = ErrBTUTLAcross( ifmp, pgnoFDP, CPAGE::fPageLeaf, ErrAccumulateLvPageData, &ctx, rgpfnzErrVisitNode, rgpvzVisitNodeCtx ); if ( ctx.rgpgnoAccum != NULL ) { delete[] ctx.rgpgnoAccum; ctx.cpgAccumMax = 0; ctx.rgpgnoAccum = NULL; } } else { err = ErrBTUTLAcross( ifmp, pgnoFDP, CPAGE::fPageLeaf, NULL, NULL, ErrAccumulatePageStats, pFullWalk ); } } return err; } LOCAL ERR ErrDBUTLGetSpaceTreeInfo( PIB *ppib, const IFMP ifmp, const OBJID objidFDP, const PGNO pgnoFDP, BTREE_STATS_SPACE_TREES * pbtsSpaceTree, CPRINTF * const pcprintf ) { ERR err; FUCB *pfucb = pfucbNil; BOOL fForceInit = fFalse; CPG rgcpgExtent[4]; CallR( ErrBTOpen( ppib, pgnoFDP, ifmp, &pfucb ) ); Assert( pfucbNil != pfucb ); Assert( pfcbNil != pfucb->u.pfcb ); CBTreeStatsManager::ResetSpaceTreeInfo( pbtsSpaceTree ); if ( !pfucb->u.pfcb->FInitialized() ) { Assert( pgnoSystemRoot != pgnoFDP ); Assert( pgnoFDPMSO != pgnoFDP ); Assert( pgnoFDPMSO_NameIndex != pgnoFDP ); Assert( pgnoFDPMSO_RootObjectIndex != pgnoFDP ); Assert( pfucb->u.pfcb->WRefCount() == 1 ); pfucb->u.pfcb->Lock(); pfucb->u.pfcb->CreateComplete(); pfucb->u.pfcb->Unlock(); fForceInit = fTrue; } else if ( pgnoSystemRoot == pgnoFDP || pgnoFDPMSO == pgnoFDP || pgnoFDPMSO_NameIndex == pgnoFDP || pgnoFDPMSO_RootObjectIndex == pgnoFDP ) { } Call( ErrBTIGotoRoot( pfucb, latchReadNoTouch ) ); NDGetExternalHeader ( pfucb, noderfIsamAutoInc ); if ( pfucb->kdfCurr.data.Cb() != 0 && pfucb->kdfCurr.data.Pv() != NULL ) { pbtsSpaceTree->fAutoIncPresents = fTrue; const QWORD qwAutoInc = *(QWORD*)pfucb->kdfCurr.data.Pv(); pbtsSpaceTree->qwAutoInc = qwAutoInc; } else { Assert( pfucb->kdfCurr.data.Cb() == 0 ); Assert( pfucb->kdfCurr.data.Pv() == NULL ); pbtsSpaceTree->fAutoIncPresents = fFalse; } NDGetExternalHeader ( pfucb, noderfSpaceHeader ); Assert( sizeof( SPACE_HEADER ) == pfucb->kdfCurr.data.Cb() ); const SPACE_HEADER * const psph = reinterpret_cast <SPACE_HEADER *> ( pfucb->kdfCurr.data.Pv() ); if ( psph->Fv1() ) { pbtsSpaceTree->cpgPrimary = psph->CpgPrimary(); pbtsSpaceTree->cpgLastAlloc = 0; } else { Assert( psph->Fv2() ); pbtsSpaceTree->cpgPrimary = 0; pbtsSpaceTree->cpgLastAlloc = psph->CpgLastAlloc(); } pbtsSpaceTree->fMultiExtent = psph->FMultipleExtent(); if ( pbtsSpaceTree->fMultiExtent ) { pbtsSpaceTree->pgnoOE = psph->PgnoOE(); pbtsSpaceTree->pgnoAE = psph->PgnoAE(); Assert( ( pbtsSpaceTree->pgnoOE + 1 ) == pbtsSpaceTree->pgnoAE ); } else { pbtsSpaceTree->pgnoOE = pgnoNull; pbtsSpaceTree->pgnoAE = pgnoNull; } BTUp( pfucb ); Call( ErrSPGetInfo( ppib, ifmp, pfucb, (BYTE *)rgcpgExtent, sizeof(rgcpgExtent), fSPOwnedExtent | fSPAvailExtent | fSPReservedExtent | fSPShelvedExtent, pcprintf ) ); pbtsSpaceTree->cpgOwned = rgcpgExtent[0]; pbtsSpaceTree->cpgAvailable = rgcpgExtent[1]; pbtsSpaceTree->cpgReserved = rgcpgExtent[2]; pbtsSpaceTree->cpgShelved = rgcpgExtent[3]; Call( ErrSPGetExtentInfo( ppib, ifmp, pfucb, fSPOwnedExtent, &( pbtsSpaceTree->cOwnedExtents ), &( pbtsSpaceTree->prgOwnedExtents ) ) ); Call( ErrSPGetExtentInfo( ppib, ifmp, pfucb, fSPAvailExtent, &( pbtsSpaceTree->cAvailExtents ), &( pbtsSpaceTree->prgAvailExtents ) ) ); HandleError: Assert( pfucbNil != pfucb ); if ( fForceInit ) { Assert( pfucb->u.pfcb->WRefCount() == 1 ); pfucb->u.pfcb->Lock(); pfucb->u.pfcb->CreateCompleteErr( errFCBUnusable ); pfucb->u.pfcb->Unlock(); } BTClose( pfucb ); return err; } typedef struct { CDBUTLIRunCalculator * pRC; BTREE_STATS_PARENT_OF_LEAF * pPOL; } EVAL_INT_PAGE_CTX; ERR EvalInternalPages( const PGNO pgno, const ULONG iLevel, const CPAGE * pcpage, void * pvCtx ) { EVAL_INT_PAGE_CTX * pEval = (EVAL_INT_PAGE_CTX*)pvCtx; Assert( pEval ); if ( pcpage->FLeafPage() ) { Assert( pcpage->FRootPage() ); Assert( pEval->pPOL->cpgInternal == 0 ); pEval->pPOL->cpgData++; if ( pEval->pRC ) { pEval->pRC->ErrProcessPage(pgno); } } else { pEval->pPOL->cpgInternal++; #ifdef SPACE_DUMP_ACOUNT_FOR_RUNS_BROKEN_BY_INTERNAL_PAGES if ( pEval->pRC ) { pEval->pRC->ErrBreak(); } #endif } if ( pEval->pPOL->cDepth == 0 && ( pcpage->FParentOfLeaf() || pcpage->FLeafPage() ) ) { pEval->pPOL->cDepth = 1 + ( pcpage->FLeafPage() ? 0 : ( iLevel + 1 ) ); } return JET_errSuccess; } ERR EvalInternalPageNodes( const CPAGE::PGHDR * const ppghdr, INT itag, DWORD fNodeFlags, const KEYDATAFLAGS * const pkdf, void * pvCtx ) { ERR err = JET_errSuccess; EVAL_INT_PAGE_CTX * pEval = (EVAL_INT_PAGE_CTX*)pvCtx; Assert( pEval ); if( !( ppghdr->fFlags & CPAGE::fPageLeaf ) ) { if ( pEval->pPOL->pInternalPageStats ) { CallR( ErrAccumulatePageStats( ppghdr, itag, fNodeFlags, pkdf, pEval->pPOL->pInternalPageStats ) ); } } if ( pkdf == NULL ) { Assert( itag == 0 ); return JET_errSuccess; } if ( pEval->pPOL->fEmpty ) { pEval->pPOL->fEmpty = fFalse; } if( ppghdr->fFlags & CPAGE::fPageParentOfLeaf ) { PGNO pgnoLeaf = *((UnalignedLittleEndian<ULONG>*)pkdf->data.Pv()); pEval->pPOL->cpgData++; if ( pEval->pRC ) { pEval->pRC->ErrProcessPage(pgnoLeaf); } } return err; } ERR ErrDBUTLGetParentOfLeaf( __in const IFMP ifmp, __in const PGNO pgnoFDP, __out BTREE_STATS_PARENT_OF_LEAF * pParentOfLeaf ) { ERR err = JET_errSuccess; CBTreeStatsManager::ResetParentOfLeaf( pParentOfLeaf ); Assert( pParentOfLeaf->phistoIOContiguousRuns ); pParentOfLeaf->fEmpty = fTrue; CDBUTLIRunCalculator RC( (CStats*)(pParentOfLeaf->phistoIOContiguousRuns), &(pParentOfLeaf->cForwardScans) ); EVAL_INT_PAGE_CTX ctx = { &RC, pParentOfLeaf }; Call( ErrBTUTLAcross( ifmp, pgnoFDP, CPAGE::fPageParentOfLeaf, EvalInternalPages, &ctx, EvalInternalPageNodes, &ctx ) ); RC.ErrProcessPage(CDBUTLIRunCalculator::pgnoDoneSentinel); Assert( pParentOfLeaf->cDepth ); Assert( !pParentOfLeaf->fEmpty || ( pParentOfLeaf->cDepth == 1 ) ); Assert( ( pParentOfLeaf->cpgInternal == 1 ) || ( pParentOfLeaf->cDepth != 2 ) ); Assert( pParentOfLeaf->fEmpty || pParentOfLeaf->cForwardScans ); HandleError: return err; } ERR ErrDBUTLGetAdditionalSpaceData( PIB * ppib, const IFMP ifmp, const OBJID objidFDP, const PGNO pgnoFDP, BTREE_STATS * const pbts, CPRINTF * const pcprintf ) { ERR err = JET_errSuccess; if( pbts->pSpaceTrees ) { Call( ErrDBUTLGetSpaceTreeInfo( ppib, ifmp, objidFDP, pgnoFDP, pbts->pSpaceTrees, pcprintf ) ); } if ( pbts->pParentOfLeaf ) { Call( ErrDBUTLGetParentOfLeaf( ifmp, pgnoFDP, pbts->pParentOfLeaf ) ); } if ( pbts->pFullWalk ) { Expected( pbts->pBasicCatalog->eType != eBTreeTypeInternalLongValue || pbts->pLvData != NULL ); Call( ErrDBUTLGetDataPageStats( ppib, ifmp, pgnoFDP, pbts->pFullWalk, pbts->pBasicCatalog->eType == eBTreeTypeInternalLongValue ? pbts->pLvData : NULL ) ); } HandleError: return err; } typedef struct { JET_SESID ppib; IFMP ifmp; JET_GRBIT grbitDbUtilOptions; WCHAR * wszSelectedTable; BTREE_STATS * pbts; OBJID objidCurrentTable; JET_PFNSPACEDATA pfnBTreeStatsAnalysisFunc; JET_API_PTR pvBTreeStatsAnalysisFuncCtx; } DBUTIL_ENUM_SPACE_CTX; ERR ErrDBUTLEnumSingleSpaceTree( PIB * ppib, const IFMP ifmp, const JET_BTREETYPE eBTType, BTREE_STATS * const pbts, JET_PFNSPACEDATA pfnBTreeStatsAnalysisFunc, JET_API_PTR pvBTreeStatsAnalysisFuncCtx ) { ERR err = JET_errSuccess; Assert( pbts ); Assert( pbts->pParent ); Assert( pbts->pSpaceTrees ); Assert( pbts->pParent->pSpaceTrees->fMultiExtent ); Assert( eBTType == eBTreeTypeInternalSpaceOE || eBTType == eBTreeTypeInternalSpaceAE ); memset( pbts->pSpaceTrees, 0, sizeof(*(pbts->pSpaceTrees)) ); pbts->pSpaceTrees->cbStruct = sizeof(*(pbts->pSpaceTrees)); pbts->pSpaceTrees->pgnoOE = pbts->pParent->pSpaceTrees->pgnoOE; pbts->pSpaceTrees->pgnoAE = pbts->pParent->pSpaceTrees->pgnoAE; PGNO pgnoFDP = ( eBTType == eBTreeTypeInternalSpaceOE ) ? pbts->pSpaceTrees->pgnoOE : pbts->pSpaceTrees->pgnoAE; if ( pbts->pBasicCatalog ) { pbts->pBasicCatalog->eType = eBTType; pbts->pBasicCatalog->pgnoFDP = pgnoFDP; Assert( pbts->pBasicCatalog->objidFDP ); Assert( pbts->pParent->pBasicCatalog->objidFDP == pbts->pBasicCatalog->objidFDP ); if ( pbts->pBasicCatalog->eType == eBTreeTypeInternalSpaceOE ) { OSStrCbCopyW( pbts->pBasicCatalog->rgName, sizeof(pbts->pBasicCatalog->rgName), L"[Owned Extents]" ); } else { Assert( pbts->pBasicCatalog->eType == eBTreeTypeInternalSpaceAE ); OSStrCbCopyW( pbts->pBasicCatalog->rgName, sizeof(pbts->pBasicCatalog->rgName), L"[Avail Extents]" ); } pbts->pBasicCatalog->pSpaceHints = NULL; } if ( pbts->pSpaceTrees ) { Assert( pbts->pSpaceTrees->cbStruct == sizeof(*(pbts->pSpaceTrees)) ); pbts->pSpaceTrees->cpgPrimary = 1; Assert( ( pbts->pSpaceTrees->pgnoOE + 1 ) == pbts->pSpaceTrees->pgnoAE ); pbts->pSpaceTrees->cpgAvailable = 0; BTREE_STATS_PARENT_OF_LEAF btsSpaceTree = { 0 }; EVAL_INT_PAGE_CTX ctx = { NULL, &btsSpaceTree }; Call( ErrBTUTLAcross( ifmp, pgnoFDP, CPAGE::fPageParentOfLeaf, EvalInternalPages, &ctx, EvalInternalPageNodes, &ctx ) ); pbts->pSpaceTrees->cpgOwned = btsSpaceTree.cpgInternal + btsSpaceTree.cpgData; pbts->pSpaceTrees->fMultiExtent = (btsSpaceTree.cpgInternal != 0); } if ( pbts->pParentOfLeaf ) { Call( ErrDBUTLGetParentOfLeaf( ifmp, pgnoFDP, pbts->pParentOfLeaf ) ); } if ( pbts->pFullWalk ) { Call( ErrDBUTLGetDataPageStats( ppib, ifmp, pgnoFDP, pbts->pFullWalk, NULL ) ); } Call( pfnBTreeStatsAnalysisFunc( pbts, pvBTreeStatsAnalysisFuncCtx ) ); HandleError: return err; } ERR ErrDBUTLEnumSpaceTrees( PIB * ppib, const IFMP ifmp, const OBJID objidParent, BTREE_STATS * const pbts, JET_PFNSPACEDATA pfnBTreeStatsAnalysisFunc, JET_API_PTR pvBTreeStatsAnalysisFuncCtx ) { ERR err = JET_errSuccess; Assert( pbts ); Assert( pbts->pParent ); Assert( pbts->pSpaceTrees ); Assert( pbts->pParent->pSpaceTrees->fMultiExtent ); if ( pbts->pBasicCatalog ) { memset( pbts->pBasicCatalog, 0, sizeof(*(pbts->pBasicCatalog)) ); pbts->pBasicCatalog->cbStruct = sizeof(*(pbts->pBasicCatalog)); pbts->pBasicCatalog->objidFDP = pbts->pParent->pBasicCatalog->objidFDP; Assert( pbts->pParent->pBasicCatalog->objidFDP == objidParent ); Assert( pbts->pBasicCatalog->objidFDP == objidParent ); pbts->pBasicCatalog->pSpaceHints = NULL; } Call( ErrDBUTLEnumSingleSpaceTree( ppib, ifmp, eBTreeTypeInternalSpaceOE, pbts, pfnBTreeStatsAnalysisFunc, pvBTreeStatsAnalysisFuncCtx ) ); Call( ErrDBUTLEnumSingleSpaceTree( ppib, ifmp, eBTreeTypeInternalSpaceAE, pbts, pfnBTreeStatsAnalysisFunc, pvBTreeStatsAnalysisFuncCtx ) ); HandleError: return err; } ERR ErrDBUTLEnumIndexSpace( const INDEXDEF * pindexdef, void * pv ) { PFNINDEX pfnindex = ErrDBUTLEnumIndexSpace; ERR err = JET_errSuccess; DBUTIL_ENUM_SPACE_CTX *pdbues = (DBUTIL_ENUM_SPACE_CTX *)pv; PIB *ppib = (PIB*)pdbues->ppib; const IFMP ifmp = pdbues->ifmp; BTREE_STATS * pbts = pdbues->pbts; Unused( pfnindex ); Assert( pbts ); Assert( pbts->pParent ); Assert( pindexdef ); if ( pindexdef->fPrimary ) { return JET_errSuccess; } if ( pbts->pBasicCatalog ) { BTREE_STATS_BASIC_CATALOG * pbtsBasicCatalog = pbts->pBasicCatalog; pbtsBasicCatalog->cbStruct = sizeof(*pbtsBasicCatalog); pbtsBasicCatalog->eType = eBTreeTypeUserSecondaryIndex; CAutoWSZDDL cwszDDL; CallR( cwszDDL.ErrSet(pindexdef->szName) ); OSStrCbCopyW( pbtsBasicCatalog->rgName, sizeof(pbtsBasicCatalog->rgName), cwszDDL.Pv() ); pbtsBasicCatalog->objidFDP = pindexdef->objidFDP; pbtsBasicCatalog->pgnoFDP = pindexdef->pgnoFDP; pbts->pBasicCatalog->pSpaceHints = (JET_SPACEHINTS*) &(pindexdef->spacehints); } CPRINTF * const pcprintf = ( pdbues->grbitDbUtilOptions & JET_bitDBUtilOptionDumpVerbose ) ? CPRINTFSTDOUT::PcprintfInstance() : NULL; CallR( ErrDBUTLGetAdditionalSpaceData( ppib, ifmp, pindexdef->objidFDP, pindexdef->pgnoFDP, pbts, pcprintf ) ); Call( pdbues->pfnBTreeStatsAnalysisFunc( pbts, pdbues->pvBTreeStatsAnalysisFuncCtx ) ); if ( pbts->pSpaceTrees && pbts->pSpaceTrees->fMultiExtent ) { CBTreeStatsManager btsIdxSpaceTreesManager( pdbues->grbitDbUtilOptions, pbts ); Call( ErrDBUTLEnumSpaceTrees( ppib, ifmp, pindexdef->objidFDP, btsIdxSpaceTreesManager.Pbts(), pdbues->pfnBTreeStatsAnalysisFunc, pdbues->pvBTreeStatsAnalysisFuncCtx ) ); } HandleError: return err; } ERR ErrDBUTLEnumTableSpace( const TABLEDEF * ptabledef, void * pv ) { PFNTABLE pfntable = ErrDBUTLEnumTableSpace; ERR err; DBUTIL_ENUM_SPACE_CTX *pdbues = (DBUTIL_ENUM_SPACE_CTX *)pv; PIB *ppib = (PIB *)pdbues->ppib; const IFMP ifmp = (IFMP)pdbues->ifmp; BTREE_STATS * pbts = pdbues->pbts; CBTreeStatsManager btsTableChildrenManager( pdbues->grbitDbUtilOptions, pbts ); Unused( pfntable ); Assert( ptabledef ); Assert( pbts ); Assert( pbts->pParent ); if ( pbts->pBasicCatalog ) { BTREE_STATS_BASIC_CATALOG * pbtsBasicCatalog = pbts->pBasicCatalog; pbtsBasicCatalog->cbStruct = sizeof(*pbtsBasicCatalog); pbtsBasicCatalog->eType = eBTreeTypeUserClusteredIndex; CAutoWSZDDL cwszDDL; CallR( cwszDDL.ErrSet( ptabledef->szName ) ); OSStrCbCopyW( pbtsBasicCatalog->rgName, sizeof(pbtsBasicCatalog->rgName), cwszDDL.Pv() ); pbtsBasicCatalog->objidFDP = ptabledef->objidFDP; pbtsBasicCatalog->pgnoFDP = ptabledef->pgnoFDP; pbts->pBasicCatalog->pSpaceHints = (JET_SPACEHINTS*) &(ptabledef->spacehints); } if ( pgnoNull != ptabledef->pgnoFDPLongValues ) { (void)ErrBFPrereadPage( ifmp, ptabledef->pgnoFDPLongValues, bfprfDefault, ppib->BfpriPriority( ifmp ), TcCurr() ); } CPRINTF * const pcprintf = ( pdbues->grbitDbUtilOptions & JET_bitDBUtilOptionDumpVerbose ) ? CPRINTFSTDOUT::PcprintfInstance() : NULL; Call( ErrDBUTLGetAdditionalSpaceData( ppib, ifmp, ptabledef->objidFDP, ptabledef->pgnoFDP, pbts, pcprintf ) ); Call( pdbues->pfnBTreeStatsAnalysisFunc( pbts, pdbues->pvBTreeStatsAnalysisFuncCtx ) ); pbts = btsTableChildrenManager.Pbts(); if ( pbts->pSpaceTrees && pbts->pParent->pSpaceTrees->fMultiExtent ) { Call( ErrDBUTLEnumSpaceTrees( ppib, ifmp, ptabledef->objidFDP, pbts, pdbues->pfnBTreeStatsAnalysisFunc, pdbues->pvBTreeStatsAnalysisFuncCtx ) ); } if ( pgnoNull != ptabledef->pgnoFDPLongValues ) { if ( pbts->pBasicCatalog ) { BTREE_STATS_BASIC_CATALOG * pbtsBasicCatalog = pbts->pBasicCatalog; pbtsBasicCatalog->cbStruct = sizeof(*pbtsBasicCatalog); pbtsBasicCatalog->eType = eBTreeTypeInternalLongValue; OSStrCbCopyW( pbtsBasicCatalog->rgName, sizeof(pbtsBasicCatalog->rgName), L"[Long Values]" ); pbtsBasicCatalog->objidFDP = ptabledef->objidFDPLongValues; pbtsBasicCatalog->pgnoFDP = ptabledef->pgnoFDPLongValues; pbtsBasicCatalog->pSpaceHints = (JET_SPACEHINTS*) &(ptabledef->spacehintsLV); } if ( pbts->pLvData ) { pbts->pLvData->cbLVChunkMax = ptabledef->cbLVChunkMax; } Call( ErrDBUTLGetAdditionalSpaceData( ppib, ifmp, ptabledef->objidFDPLongValues, ptabledef->pgnoFDPLongValues, pbts, pcprintf ) ); Call( pdbues->pfnBTreeStatsAnalysisFunc( pbts, pdbues->pvBTreeStatsAnalysisFuncCtx ) ); CBTreeStatsManager btsLVSpaceTreesManager( pdbues->grbitDbUtilOptions, pbts ); if ( pbts->pSpaceTrees && pbts->pSpaceTrees->fMultiExtent ) { Call( ErrDBUTLEnumSpaceTrees( ppib, ifmp, ptabledef->objidFDPLongValues, btsLVSpaceTreesManager.Pbts(), pdbues->pfnBTreeStatsAnalysisFunc, pdbues->pvBTreeStatsAnalysisFuncCtx ) ); } } DBUTIL_ENUM_SPACE_CTX dbuesIdx; memcpy( &dbuesIdx, pdbues, sizeof(dbuesIdx) ); dbuesIdx.pbts = btsTableChildrenManager.Pbts(); JET_DBUTIL_W dbutil; memset( &dbutil, 0, sizeof( dbutil ) ); dbutil.cbStruct = sizeof( dbutil ); dbutil.op = opDBUTILEDBDump; dbutil.sesid = pdbues->ppib; dbutil.dbid = (JET_DBID)pdbues->ifmp; dbutil.pgno = ptabledef->objidFDP; dbutil.pfnCallback = (void *)ErrDBUTLEnumIndexSpace; dbutil.pvCallback = &dbuesIdx; dbutil.edbdump = opEDBDumpIndexes; dbutil.grbitOptions = pdbues->grbitDbUtilOptions; pdbues->objidCurrentTable = ptabledef->objidFDP; err = ErrDBUTLDump( pdbues->ppib, &dbutil ); HandleError: return err; } LOCAL INT PrintIndexBareMetaData( const INDEXDEF * pindexdef, void * pv ) { PFNINDEX pfnindex = PrintIndexBareMetaData; Unused( pfnindex ); Assert( pindexdef ); printf( " %-49.49s %s ", pindexdef->szName, ( pindexdef->fPrimary ? "Pri" : "Idx" ) ); DBUTLPrintfIntN( pindexdef->objidFDP, 10 ); printf( " " ); DBUTLPrintfIntN( pindexdef->pgnoFDP, 10 ); printf( "\n" ); return JET_errSuccess; } LOCAL INT PrintTableBareMetaData( const TABLEDEF * ptabledef, void * pv ) { PFNTABLE pfntable = PrintTableBareMetaData; ERR err; JET_DBUTIL_A *pdbutil = (JET_DBUTIL_A *)pv; Unused( pfntable ); Assert( ptabledef ); printf( "%-51.51s Tbl ", ptabledef->szName ); DBUTLPrintfIntN( ptabledef->objidFDP, 10 ); printf( " " ); DBUTLPrintfIntN( ptabledef->pgnoFDP, 10 ); printf( "\n" ); if ( pgnoNull != ptabledef->pgnoFDPLongValues ) { printf( " %-49.49s LV ", "<Long Values>" ); DBUTLPrintfIntN( ptabledef->objidFDPLongValues, 10 ); printf( " " ); DBUTLPrintfIntN( ptabledef->pgnoFDPLongValues, 10 ); printf( "\n" ); } JET_DBUTIL_W dbutil; memset( &dbutil, 0, sizeof( dbutil ) ); dbutil.cbStruct = sizeof( dbutil ); dbutil.op = opDBUTILEDBDump; dbutil.sesid = pdbutil->sesid; dbutil.dbid = pdbutil->dbid; dbutil.pgno = ptabledef->objidFDP; dbutil.pfnCallback = (void *)PrintIndexBareMetaData; dbutil.pvCallback = &dbutil; dbutil.edbdump = opEDBDumpIndexes; dbutil.grbitOptions = pdbutil->grbitOptions; err = ErrDBUTLDump( pdbutil->sesid, &dbutil ); return err; } LOCAL VOID DBUTLDumpDefaultSpaceHints( __inout JET_SPACEHINTS * const pSpacehints, __in const CPG cpgInitial, __in const BOOL fTable ) { if ( 0 == pSpacehints->cbInitial ) { pSpacehints->cbInitial = g_cbPage * cpgInitial; } if ( 0 == pSpacehints->ulMaintDensity ) { pSpacehints->ulMaintDensity = ulFILEDefaultDensity; } if ( 0 == pSpacehints->cbMinExtent ) { if ( fTable || ( 0 == ( pSpacehints->grbit & JET_bitSpaceHintsUtilizeParentSpace ) ) ) { pSpacehints->cbMinExtent = cpgSmallGrow * g_cbPage; } else { pSpacehints->cbMinExtent = g_cbPage; } } if ( 0 == pSpacehints->cbMaxExtent ) { if ( fTable || ( 0 == ( pSpacehints->grbit & JET_bitSpaceHintsUtilizeParentSpace ) ) ) { pSpacehints->cbMaxExtent = cpageSEDefault * g_cbPage; } else { pSpacehints->cbMaxExtent = g_cbPage; } } if ( 0 == pSpacehints->ulGrowth ) { pSpacehints->ulGrowth = 100; } } ERR ErrCATIUnmarshallExtendedSpaceHints( __in INST * const pinst, __in const SYSOBJ sysobj, __in const BOOL fDeferredLongValueHints, __in const BYTE * const pBuffer, __in const ULONG cbBuffer, __in const LONG cbPageSize, __out JET_SPACEHINTS * pSpacehints ); LOCAL ERR ErrDBUTLDumpOneIndex( PIB * ppib, FUCB * pfucbCatalog, VOID * pfnCallback, VOID * pvCallback ) { JET_RETRIEVECOLUMN rgretrievecolumn[17]; BYTE pbufidxseg[JET_ccolKeyMost*sizeof(IDXSEG)]; BYTE pbufidxsegConditional[JET_ccolKeyMost*sizeof(IDXSEG)]; BYTE pbExtendedSpaceHints[cbExtendedSpaceHints]; INDEXDEF indexdef; ERR err = JET_errSuccess; INT iretrievecolumn = 0; OBJID objidTable; USHORT cbVarSegMac = 0; USHORT cbKeyMost = 0; QWORD qwSortVersion = 0; memset( &indexdef, 0, sizeof( indexdef ) ); memset( rgretrievecolumn, 0, sizeof( rgretrievecolumn ) ); rgretrievecolumn[iretrievecolumn].columnid = fidMSO_ObjidTable; rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&objidTable; rgretrievecolumn[iretrievecolumn].cbData = sizeof(objidTable); rgretrievecolumn[iretrievecolumn].itagSequence = 1; ++iretrievecolumn; rgretrievecolumn[iretrievecolumn].columnid = fidMSO_PgnoFDP; rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&indexdef.pgnoFDP; rgretrievecolumn[iretrievecolumn].cbData = sizeof(indexdef.pgnoFDP); rgretrievecolumn[iretrievecolumn].itagSequence = 1; ++iretrievecolumn; rgretrievecolumn[iretrievecolumn].columnid = fidMSO_Id; rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&indexdef.objidFDP; rgretrievecolumn[iretrievecolumn].cbData = sizeof(indexdef.objidFDP); rgretrievecolumn[iretrievecolumn].itagSequence = 1; ++iretrievecolumn; rgretrievecolumn[iretrievecolumn].columnid = fidMSO_Name; rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)indexdef.szName; rgretrievecolumn[iretrievecolumn].cbData = sizeof(indexdef.szName); rgretrievecolumn[iretrievecolumn].itagSequence = 1; ++iretrievecolumn; rgretrievecolumn[iretrievecolumn].columnid = fidMSO_SpaceUsage; rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&indexdef.density; rgretrievecolumn[iretrievecolumn].cbData = sizeof(indexdef.density); rgretrievecolumn[iretrievecolumn].itagSequence = 1; ++iretrievecolumn; rgretrievecolumn[iretrievecolumn].columnid = fidMSO_Localization; rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&indexdef.lcid; rgretrievecolumn[iretrievecolumn].cbData = sizeof(indexdef.lcid); rgretrievecolumn[iretrievecolumn].itagSequence = 1; ++iretrievecolumn; rgretrievecolumn[iretrievecolumn].columnid = fidMSO_LocaleName; rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&indexdef.wszLocaleName; rgretrievecolumn[iretrievecolumn].cbData = sizeof(indexdef.wszLocaleName); rgretrievecolumn[iretrievecolumn].itagSequence = 1; ++iretrievecolumn; rgretrievecolumn[iretrievecolumn].columnid = fidMSO_SortID; rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&indexdef.sortID; rgretrievecolumn[iretrievecolumn].cbData = sizeof(indexdef.sortID); rgretrievecolumn[iretrievecolumn].itagSequence = 1; ++iretrievecolumn; rgretrievecolumn[iretrievecolumn].columnid = fidMSO_LCMapFlags; rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&indexdef.dwMapFlags; rgretrievecolumn[iretrievecolumn].cbData = sizeof(indexdef.dwMapFlags); rgretrievecolumn[iretrievecolumn].itagSequence = 1; ++iretrievecolumn; rgretrievecolumn[iretrievecolumn].columnid = fidMSO_Flags; rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&indexdef.fFlags; rgretrievecolumn[iretrievecolumn].cbData = sizeof(indexdef.fFlags); rgretrievecolumn[iretrievecolumn].itagSequence = 1; ++iretrievecolumn; const INT iretcolTupleLimits = iretrievecolumn; rgretrievecolumn[iretrievecolumn].columnid = fidMSO_TupleLimits; rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&indexdef.le_tuplelimits; rgretrievecolumn[iretrievecolumn].cbData = sizeof(indexdef.le_tuplelimits); rgretrievecolumn[iretrievecolumn].itagSequence = 1; ++iretrievecolumn; const INT iretcolIdxsegConditional = iretrievecolumn; rgretrievecolumn[iretrievecolumn].columnid = fidMSO_ConditionalColumns; rgretrievecolumn[iretrievecolumn].pvData = pbufidxsegConditional; rgretrievecolumn[iretrievecolumn].cbData = sizeof(pbufidxsegConditional); rgretrievecolumn[iretrievecolumn].itagSequence = 1; ++iretrievecolumn; const INT iretcolIdxseg = iretrievecolumn; rgretrievecolumn[iretrievecolumn].columnid = fidMSO_KeyFldIDs; rgretrievecolumn[iretrievecolumn].pvData = pbufidxseg; rgretrievecolumn[iretrievecolumn].cbData = sizeof(pbufidxseg); rgretrievecolumn[iretrievecolumn].itagSequence = 1; ++iretrievecolumn; rgretrievecolumn[iretrievecolumn].columnid = fidMSO_VarSegMac; rgretrievecolumn[iretrievecolumn].pvData = &cbVarSegMac; rgretrievecolumn[iretrievecolumn].cbData = sizeof(cbVarSegMac); rgretrievecolumn[iretrievecolumn].itagSequence = 1; ++iretrievecolumn; rgretrievecolumn[iretrievecolumn].columnid = fidMSO_KeyMost; rgretrievecolumn[iretrievecolumn].pvData = &cbKeyMost; rgretrievecolumn[iretrievecolumn].cbData = sizeof(cbKeyMost); rgretrievecolumn[iretrievecolumn].itagSequence = 1; ++iretrievecolumn; rgretrievecolumn[iretrievecolumn].columnid = fidMSO_Version; rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&qwSortVersion; rgretrievecolumn[iretrievecolumn].cbData = sizeof(qwSortVersion); rgretrievecolumn[iretrievecolumn].itagSequence = 1; ++iretrievecolumn; const INT iretcolExtSpaceHints = iretrievecolumn; rgretrievecolumn[iretrievecolumn].columnid = fidMSO_SpaceHints; rgretrievecolumn[iretrievecolumn].pvData = pbExtendedSpaceHints; rgretrievecolumn[iretrievecolumn].cbData = sizeof(pbExtendedSpaceHints); rgretrievecolumn[iretrievecolumn].itagSequence = 1; ++iretrievecolumn; Assert( iretrievecolumn <= sizeof( rgretrievecolumn ) / sizeof( rgretrievecolumn[0] ) ); CallR( ErrIsamRetrieveColumns( (JET_SESID)ppib, (JET_TABLEID)pfucbCatalog, rgretrievecolumn, iretrievecolumn ) ); const IDBFLAG idbflag = (IDBFLAG)indexdef.fFlags; const IDXFLAG idxflag = (IDXFLAG)( indexdef.fFlags >> sizeof(IDBFLAG) * 8 ); indexdef.fUnique = !!FIDBUnique( idbflag ); indexdef.fPrimary = !!FIDBPrimary( idbflag ); indexdef.fAllowAllNulls = !!FIDBAllowAllNulls( idbflag ); indexdef.fAllowFirstNull = !!FIDBAllowFirstNull( idbflag ); indexdef.fAllowSomeNulls = !!FIDBAllowSomeNulls( idbflag ); indexdef.fNoNullSeg = !!FIDBNoNullSeg( idbflag ); indexdef.fSortNullsHigh = !!FIDBSortNullsHigh( idbflag ); indexdef.fMultivalued = !!FIDBMultivalued( idbflag ); indexdef.fTuples = ( JET_wrnColumnNull == rgretrievecolumn[iretcolTupleLimits].err ? fFalse : fTrue ); indexdef.fLocaleSet = !!FIDBLocaleSet( idbflag ); indexdef.fLocalizedText = !!FIDBLocalizedText( idbflag ); indexdef.fTemplateIndex = !!FIDBTemplateIndex( idbflag ); indexdef.fDerivedIndex = !!FIDBDerivedIndex( idbflag ); indexdef.fExtendedColumns = !!FIDXExtendedColumns( idxflag ); indexdef.cbVarSegMac = cbVarSegMac; indexdef.cbKeyMost = cbKeyMost; indexdef.dwDefinedVersion = (DWORD)( ( qwSortVersion >> 32 ) & 0xFFFFFFFF ); indexdef.dwNLSVersion = (DWORD)( qwSortVersion & 0xFFFFFFFF ); if ( !indexdef.fPrimary && indexdef.fDerivedIndex ) { const INT cchTableName = JET_cbNameMost + 1; CHAR szTableName[cchTableName]; FUCB * pfucbDerivedTable; FCB * pfcbDerivedIndex; CallR( ErrCATSeekTableByObjid( ppib, pfucbCatalog->ifmp, objidTable, szTableName, cchTableName, NULL ) ); CallR( ErrFILEOpenTable( ppib, pfucbCatalog->u.pfcb->Ifmp(), &pfucbDerivedTable, szTableName, JET_bitTableReadOnly ) ); const TDB * ptdbDerivedTable = pfucbDerivedTable->u.pfcb->Ptdb(); for ( pfcbDerivedIndex = pfucbDerivedTable->u.pfcb; NULL != pfcbDerivedIndex; pfcbDerivedIndex = pfcbDerivedIndex->PfcbNextIndex() ) { if ( NULL != pfcbDerivedIndex->Pidb() && ( UtilCmpName( indexdef.szName, ptdbDerivedTable->SzIndexName( pfcbDerivedIndex->Pidb()->ItagIndexName(), pfcbDerivedIndex->FDerivedIndex() ) ) == 0 ) ) { break; } } Assert( pfcbDerivedIndex ); if ( NULL == pfcbDerivedIndex ) { CallR( JET_errCatalogCorrupted ); } pfcbDerivedIndex->GetAPISpaceHints( &indexdef.spacehints ); CallS( ErrFILECloseTable( ppib, pfucbDerivedTable ) ); } else { indexdef.spacehints.cbStruct = sizeof(indexdef.spacehints); indexdef.spacehints.ulInitialDensity = indexdef.density; if( rgretrievecolumn[iretcolExtSpaceHints].cbActual ) { CallR( ErrCATIUnmarshallExtendedSpaceHints( PinstFromPfucb( pfucbCatalog ), sysobjIndex, fFalse, pbExtendedSpaceHints, rgretrievecolumn[iretcolExtSpaceHints].cbActual, g_rgfmp[ pfucbCatalog->ifmp ].CbPage(), &indexdef.spacehints ) ); } } DBUTLDumpDefaultSpaceHints( &indexdef.spacehints, cpgInitialTreeDefault, fFalse ); Assert( rgretrievecolumn[iretcolIdxseg].cbActual > 0 ); if ( indexdef.fExtendedColumns ) { INT iidxseg; Assert( sizeof(IDXSEG) == sizeof(JET_COLUMNID) ); Assert( rgretrievecolumn[iretcolIdxseg].cbActual <= sizeof(JET_COLUMNID) * JET_ccolKeyMost ); Assert( rgretrievecolumn[iretcolIdxseg].cbActual % sizeof(JET_COLUMNID) == 0 ); Assert( rgretrievecolumn[iretcolIdxseg].cbActual / sizeof(JET_COLUMNID) <= JET_ccolKeyMost ); indexdef.ccolumnidDef = rgretrievecolumn[iretcolIdxseg].cbActual / sizeof(JET_COLUMNID); for ( iidxseg = 0; iidxseg < indexdef.ccolumnidDef; iidxseg++ ) { const LE_IDXSEG * const ple_idxseg = (LE_IDXSEG *)pbufidxseg + iidxseg; indexdef.rgidxsegDef[iidxseg] = *ple_idxseg; Assert( FCOLUMNIDValid( indexdef.rgidxsegDef[iidxseg].Columnid() ) ); } Assert( rgretrievecolumn[iretcolIdxsegConditional].cbActual <= sizeof(JET_COLUMNID) * JET_ccolKeyMost ); Assert( rgretrievecolumn[iretcolIdxsegConditional].cbActual % sizeof(JET_COLUMNID) == 0 ); Assert( rgretrievecolumn[iretcolIdxsegConditional].cbActual / sizeof(JET_COLUMNID) <= JET_ccolKeyMost ); indexdef.ccolumnidConditional = rgretrievecolumn[iretcolIdxsegConditional].cbActual / sizeof(JET_COLUMNID); for ( iidxseg = 0; iidxseg < indexdef.ccolumnidConditional; iidxseg++ ) { const LE_IDXSEG * const ple_idxsegConditional = (LE_IDXSEG *)pbufidxsegConditional + iidxseg; indexdef.rgidxsegConditional[iidxseg] = *ple_idxsegConditional; Assert( FCOLUMNIDValid( indexdef.rgidxsegConditional[iidxseg].Columnid() ) ); } } else { Assert( sizeof(IDXSEG_OLD) == sizeof(FID) ); Assert( rgretrievecolumn[iretcolIdxseg].cbActual <= sizeof(FID) * JET_ccolKeyMost ); Assert( rgretrievecolumn[iretcolIdxseg].cbActual % sizeof(FID) == 0); Assert( rgretrievecolumn[iretcolIdxseg].cbActual / sizeof(FID) <= JET_ccolKeyMost ); indexdef.ccolumnidDef = rgretrievecolumn[iretcolIdxseg].cbActual / sizeof( FID ); SetIdxSegFromOldFormat( (UnalignedLittleEndian< IDXSEG_OLD > *)pbufidxseg, indexdef.rgidxsegDef, indexdef.ccolumnidDef, fFalse, fFalse, NULL ); Assert( rgretrievecolumn[iretcolIdxsegConditional].cbActual <= sizeof(FID) * JET_ccolKeyMost ); Assert( rgretrievecolumn[iretcolIdxsegConditional].cbActual % sizeof(FID) == 0); Assert( rgretrievecolumn[iretcolIdxsegConditional].cbActual / sizeof(FID) <= JET_ccolKeyMost ); indexdef.ccolumnidConditional = rgretrievecolumn[iretcolIdxsegConditional].cbActual / sizeof( FID ); SetIdxSegFromOldFormat( (UnalignedLittleEndian< IDXSEG_OLD > *)pbufidxsegConditional, indexdef.rgidxsegConditional, indexdef.ccolumnidConditional, fTrue, fFalse, NULL ); } CallR( ErrCATGetIndexSegments( ppib, pfucbCatalog->u.pfcb->Ifmp(), objidTable, indexdef.rgidxsegDef, indexdef.ccolumnidDef, fFalse, !indexdef.fExtendedColumns, indexdef.rgszIndexDef ) ); CallR( ErrCATGetIndexSegments( ppib, pfucbCatalog->u.pfcb->Ifmp(), objidTable, indexdef.rgidxsegConditional, indexdef.ccolumnidConditional, fTrue, !indexdef.fExtendedColumns, indexdef.rgszIndexConditional ) ); PFNINDEX const pfnindex = (PFNINDEX)pfnCallback; return (*pfnindex)( &indexdef, pvCallback ); } LOCAL ERR ErrGetSpaceHintsForLV( PIB * ppib, const IFMP ifmp, const OBJID objidTable, JET_SPACEHINTS * const pSpacehints ) { ERR err = JET_errSuccess; FUCB * pfucbTable = pfucbNil; FUCB * pfucbLV = pfucbNil; PGNO pgnoFDP; CHAR szTableName[JET_cbNameMost+1]; Call( ErrCATSeekTableByObjid( ppib, ifmp, objidTable, szTableName, sizeof( szTableName ), &pgnoFDP ) ); CallR( ErrFILEOpenTable( ppib, ifmp, &pfucbTable, szTableName ) ); Call( ErrFILEOpenLVRoot( pfucbTable, &pfucbLV, fFalse ) ); if( pfucbLV != pfucbNil ) { pfucbLV->u.pfcb->GetAPISpaceHints( pSpacehints ); } HandleError: if( pfucbNil != pfucbTable ) { if( pfucbNil != pfucbLV ) { DIRClose( pfucbLV ); pfucbLV = pfucbNil; } ErrFILECloseTable( ppib, pfucbTable ); pfucbTable = pfucbNil; } return err; } LOCAL ERR ErrDBUTLDumpOneTable( PIB * ppib, FUCB * pfucbCatalog, PFNTABLE pfntable, VOID * pvCallback ) { JET_RETRIEVECOLUMN rgretrievecolumn[11]; BYTE pbExtendedSpaceHints[cbExtendedSpaceHints]; BYTE pbExtendedSpaceHintsDeferredLV[cbExtendedSpaceHints]; TABLEDEF tabledef; ERR err = JET_errSuccess; INT iretrievecolumn = 0; memset( &tabledef, 0, sizeof( tabledef ) ); memset( rgretrievecolumn, 0, sizeof( rgretrievecolumn ) ); rgretrievecolumn[iretrievecolumn].columnid = fidMSO_Name; rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)tabledef.szName; rgretrievecolumn[iretrievecolumn].cbData = sizeof( tabledef.szName ); rgretrievecolumn[iretrievecolumn].itagSequence = 1; ++iretrievecolumn; rgretrievecolumn[iretrievecolumn].columnid = fidMSO_TemplateTable; rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)tabledef.szTemplateTable; rgretrievecolumn[iretrievecolumn].cbData = sizeof( tabledef.szTemplateTable ); rgretrievecolumn[iretrievecolumn].itagSequence = 1; ++iretrievecolumn; rgretrievecolumn[iretrievecolumn].columnid = fidMSO_PgnoFDP; rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&( tabledef.pgnoFDP ); rgretrievecolumn[iretrievecolumn].cbData = sizeof( tabledef.pgnoFDP ); rgretrievecolumn[iretrievecolumn].itagSequence = 1; ++iretrievecolumn; rgretrievecolumn[iretrievecolumn].columnid = fidMSO_Id; rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&( tabledef.objidFDP ); rgretrievecolumn[iretrievecolumn].cbData = sizeof( tabledef.objidFDP ); rgretrievecolumn[iretrievecolumn].itagSequence = 1; ++iretrievecolumn; rgretrievecolumn[iretrievecolumn].columnid = fidMSO_Pages; rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&( tabledef.pages ); rgretrievecolumn[iretrievecolumn].cbData = sizeof( tabledef.pages ); rgretrievecolumn[iretrievecolumn].itagSequence = 1; ++iretrievecolumn; rgretrievecolumn[iretrievecolumn].columnid = fidMSO_SpaceUsage; rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&( tabledef.density ); rgretrievecolumn[iretrievecolumn].cbData = sizeof( tabledef.density ); rgretrievecolumn[iretrievecolumn].itagSequence = 1; ++iretrievecolumn; rgretrievecolumn[iretrievecolumn].columnid = fidMSO_Flags; rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&( tabledef.fFlags ); rgretrievecolumn[iretrievecolumn].cbData = sizeof( tabledef.fFlags ); rgretrievecolumn[iretrievecolumn].itagSequence = 1; ++iretrievecolumn; const INT iretcolExtSpaceHints = iretrievecolumn; rgretrievecolumn[iretrievecolumn].columnid = fidMSO_SpaceHints; rgretrievecolumn[iretrievecolumn].pvData = pbExtendedSpaceHints; rgretrievecolumn[iretrievecolumn].cbData = sizeof(pbExtendedSpaceHints); rgretrievecolumn[iretrievecolumn].itagSequence = 1; ++iretrievecolumn; const INT iretcolExtSpaceHintsDeferredLV = iretrievecolumn; rgretrievecolumn[iretrievecolumn].columnid = fidMSO_SpaceLVDeferredHints; rgretrievecolumn[iretrievecolumn].pvData = pbExtendedSpaceHintsDeferredLV; rgretrievecolumn[iretrievecolumn].cbData = sizeof(pbExtendedSpaceHintsDeferredLV); rgretrievecolumn[iretrievecolumn].itagSequence = 1; ++iretrievecolumn; rgretrievecolumn[iretrievecolumn].columnid = fidMSO_LVChunkMax; rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&( tabledef.cbLVChunkMax ); rgretrievecolumn[iretrievecolumn].cbData = sizeof( tabledef.cbLVChunkMax ); rgretrievecolumn[iretrievecolumn].itagSequence = 1; ++iretrievecolumn; Call( ErrIsamRetrieveColumns( (JET_SESID)ppib, (JET_TABLEID)pfucbCatalog, rgretrievecolumn, iretrievecolumn ) ); if ( tabledef.cbLVChunkMax == 0 ) { tabledef.cbLVChunkMax = (LONG)UlParam( JET_paramLVChunkSizeMost ); } if ( ( tabledef.fFlags & JET_bitObjectTableDerived ) && ( 0 == rgretrievecolumn[iretcolExtSpaceHints].cbActual ) ) { FUCB *pfucbTemplateTable; Assert( ( NULL != tabledef.szTemplateTable ) && ( '\0' != tabledef.szTemplateTable[0] ) ); CallR( ErrFILEOpenTable( ppib, pfucbCatalog->u.pfcb->Ifmp(), &pfucbTemplateTable, tabledef.szTemplateTable, JET_bitTableReadOnly ) ); Assert( pfcbNil != pfucbTemplateTable->u.pfcb ); Assert( pfucbTemplateTable->u.pfcb->FTemplateTable() ); Expected( pfucbTemplateTable->u.pfcb->FFixedDDL() ); pfucbTemplateTable->u.pfcb->GetAPISpaceHints( &tabledef.spacehints ); CallS( ErrFILECloseTable( ppib, pfucbTemplateTable ) ); } else { tabledef.spacehints.cbStruct = sizeof(tabledef.spacehints); tabledef.spacehints.ulInitialDensity = tabledef.density; if( rgretrievecolumn[iretcolExtSpaceHints].cbActual ) { Call( ErrCATIUnmarshallExtendedSpaceHints( PinstFromPfucb( pfucbCatalog ), sysobjTable, fFalse, pbExtendedSpaceHints, rgretrievecolumn[iretcolExtSpaceHints].cbActual, g_rgfmp[ pfucbCatalog->ifmp ].CbPage(), &tabledef.spacehints ) ); } if( rgretrievecolumn[iretcolExtSpaceHintsDeferredLV].cbActual ) { memset( &tabledef.spacehintsDeferredLV, 0, sizeof(tabledef.spacehintsDeferredLV) ); tabledef.spacehintsDeferredLV.cbStruct = sizeof(tabledef.spacehints); tabledef.spacehintsDeferredLV.ulInitialDensity = tabledef.density; Call( ErrCATIUnmarshallExtendedSpaceHints( PinstFromPfucb( pfucbCatalog ), sysobjTable, fTrue, pbExtendedSpaceHintsDeferredLV, rgretrievecolumn[iretcolExtSpaceHintsDeferredLV].cbActual, g_rgfmp[ pfucbCatalog->ifmp ].CbPage(), &tabledef.spacehintsDeferredLV ) ); } } DBUTLDumpDefaultSpaceHints( &tabledef.spacehints, tabledef.pages, fTrue ); Call( ErrCATAccessTableLV( ppib, pfucbCatalog->u.pfcb->Ifmp(), tabledef.objidFDP, &tabledef.pgnoFDPLongValues, &tabledef.objidFDPLongValues ) ); err = ErrGetSpaceHintsForLV( ppib, pfucbCatalog->u.pfcb->Ifmp(), tabledef.objidFDP, &tabledef.spacehintsLV ); if ( err >= JET_errSuccess ) { DBUTLDumpDefaultSpaceHints( &tabledef.spacehintsLV, 0, fFalse ); } else { err = JET_errSuccess; } Call( (*pfntable)( &tabledef, pvCallback ) ); HandleError: return err; } LOCAL ERR ErrDBUTLDumpTables( PIB * ppib, IFMP ifmp, __in PCWSTR wszTableName, PFNTABLE pfntable, VOID * pvCallback ) { ERR err; FUCB *pfucbCatalog = pfucbNil; CallR( ErrCATOpen( ppib, ifmp, &pfucbCatalog ) ); Assert( pfucbNil != pfucbCatalog ); Call( ErrIsamSetCurrentIndex( ppib, pfucbCatalog, szMSORootObjectsIndex ) ); if ( NULL != wszTableName ) { const BYTE bTrue = 0xff; CAutoSZDDL szTableName; Call( szTableName.ErrSet( wszTableName ) ); Call( ErrIsamMakeKey( ppib, pfucbCatalog, &bTrue, sizeof(bTrue), JET_bitNewKey ) ); Call( ErrIsamMakeKey( ppib, pfucbCatalog, (CHAR*)szTableName, (ULONG)strlen((CHAR*)szTableName), NO_GRBIT ) ); err = ErrIsamSeek( ppib, pfucbCatalog, JET_bitSeekEQ ); if ( JET_errRecordNotFound == err ) err = ErrERRCheck( JET_errObjectNotFound ); Call( err ); CallS( err ); Call( ErrDBUTLDumpOneTable( ppib, pfucbCatalog, pfntable, pvCallback ) ); } else { err = ErrIsamMove( ppib, pfucbCatalog, JET_MoveFirst, NO_GRBIT ); while ( JET_errNoCurrentRecord != err ) { Call( err ); Call( ErrDBUTLDumpOneTable( ppib, pfucbCatalog, pfntable, pvCallback ) ); err = ErrIsamMove( ppib, pfucbCatalog, JET_MoveNext, NO_GRBIT ); } } err = JET_errSuccess; HandleError: CallS( ErrCATClose( ppib, pfucbCatalog ) ); return err; } LOCAL ERR ErrDBUTLDumpTableObjects( PIB *ppib, const IFMP ifmp, const OBJID objidFDP, const SYSOBJ sysobj, PFNDUMP pfnDump, VOID *pfnCallback, VOID *pvCallback ) { ERR err; FUCB *pfucbCatalog = pfucbNil; CallR( ErrCATOpen( ppib, ifmp, &pfucbCatalog ) ); Assert( pfucbNil != pfucbCatalog ); FUCBSetSequential( pfucbCatalog ); Call( ErrIsamSetCurrentIndex( ppib, pfucbCatalog, szMSONameIndex ) ); Call( ErrIsamMakeKey( ppib, pfucbCatalog, (BYTE *)&objidFDP, sizeof(objidFDP), JET_bitNewKey ) ); Call( ErrIsamMakeKey( ppib, pfucbCatalog, (BYTE *)&sysobj, sizeof(sysobj), NO_GRBIT ) ); err = ErrIsamSeek( ppib, pfucbCatalog, JET_bitSeekGT ); if ( err < 0 ) { if ( JET_errRecordNotFound != err ) goto HandleError; } else { CallS( err ); Call( ErrIsamMakeKey( ppib, pfucbCatalog, (BYTE *)&objidFDP, sizeof(objidFDP), JET_bitNewKey ) ); Call( ErrIsamMakeKey( ppib, pfucbCatalog, (BYTE *)&sysobj, sizeof(sysobj), JET_bitStrLimit ) ); err = ErrIsamSetIndexRange( ppib, pfucbCatalog, JET_bitRangeUpperLimit ); Assert( err <= 0 ); while ( JET_errNoCurrentRecord != err ) { Call( err ); Call( (*pfnDump)( ppib, pfucbCatalog, pfnCallback, pvCallback ) ); err = ErrIsamMove( ppib, pfucbCatalog, JET_MoveNext, NO_GRBIT ); } } err = JET_errSuccess; HandleError: CallS( ErrCATClose( ppib, pfucbCatalog ) ); return err; } #endif LOCAL ERR ErrDBUTLDumpPageUsage( JET_SESID sesid, const JET_DBUTIL_W * pdbutil ) { ERR err; PIB * ppib = (PIB *)sesid; const FUCB * pfucb = (FUCB *)pdbutil->tableid; PGNO pgnoFDP; CallR( ErrPIBCheck( ppib ) ); if ( JET_tableidNil == pdbutil->tableid || pfucbNil == pfucb ) { CallR( ErrERRCheck( JET_errInvalidTableId ) ); } CheckTable( ppib, pfucb ); CheckSecondary( pfucb ); if ( pdbutil->grbitOptions & JET_bitDBUtilOptionDumpLVPageUsage ) { Call( ErrCATAccessTableLV( ppib, pfucb->ifmp, pfucb->u.pfcb->ObjidFDP(), &pgnoFDP ) ); } else { if ( pfucbNil != pfucb->pfucbCurIndex ) pfucb = pfucb->pfucbCurIndex; pgnoFDP = pfucb->u.pfcb->PgnoFDP(); } Call( ErrBTDumpPageUsage( ppib, pfucb->ifmp, pgnoFDP ) ); HandleError: return err; } #ifdef MINIMAL_FUNCTIONALITY #else LOCAL ERR ErrDBUTLDump( JET_SESID sesid, const JET_DBUTIL_W *pdbutil ) { ERR err; switch( pdbutil->edbdump ) { case opEDBDumpTables: { PFNTABLE const pfntable = (PFNTABLE)( pdbutil->pfnCallback ); err = ErrDBUTLDumpTables( (PIB *)sesid, IFMP( pdbutil->dbid ), pdbutil->szTable, pfntable, pdbutil->pvCallback ); } break; case opEDBDumpIndexes: err = ErrDBUTLDumpTableObjects( (PIB *)sesid, IFMP( pdbutil->dbid ), (OBJID)pdbutil->pgno, sysobjIndex, &ErrDBUTLDumpOneIndex, pdbutil->pfnCallback, pdbutil->pvCallback ); break; case opEDBDumpColumns: err = ErrDBUTLDumpTableObjects( (PIB *)sesid, IFMP( pdbutil->dbid ), OBJID( pdbutil->pgno ), sysobjColumn, &ErrDBUTLDumpOneColumn, pdbutil->pfnCallback, pdbutil->pvCallback ); break; case opEDBDumpCallbacks: err = ErrDBUTLDumpTableObjects( (PIB *)sesid, IFMP( pdbutil->dbid ), OBJID( pdbutil->pgno ), sysobjCallback, &ErrDBUTLDumpOneCallback, pdbutil->pfnCallback, pdbutil->pvCallback ); break; case opEDBDumpPage: { PFNPAGE const pfnpage = (PFNPAGE)( pdbutil->pfnCallback ); err = ErrDBUTLDumpPage( (PIB *)sesid, (IFMP) pdbutil->dbid, pdbutil->pgno, pfnpage, pdbutil->pvCallback ); } break; default: Assert( fFalse ); err = ErrERRCheck( JET_errFeatureNotAvailable ); break; } return err; } LOCAL ERR ErrDBUTLDumpTables( DBCCINFO *pdbccinfo, PFNTABLE pfntable, VOID * pvCtx ) { JET_SESID sesid = (JET_SESID)pdbccinfo->ppib; JET_DBID dbid = (JET_DBID)pdbccinfo->ifmp; JET_DBUTIL_W dbutil; memset( &dbutil, 0, sizeof( dbutil ) ); dbutil.cbStruct = sizeof( dbutil ); dbutil.op = opDBUTILEDBDump; dbutil.sesid = sesid; dbutil.dbid = dbid; dbutil.pfnCallback = (void *)pfntable; dbutil.pvCallback = pvCtx ? pvCtx : &dbutil; dbutil.edbdump = opEDBDumpTables; dbutil.grbitOptions = pdbccinfo->grbitOptions; dbutil.szTable = ( NULL == pdbccinfo->wszTable || L'\0' == pdbccinfo->wszTable[0] ? NULL : pdbccinfo->wszTable ); return ErrDBUTLDump( sesid, &dbutil ); } #endif LOCAL ERR ErrDBUTLDumpFlushMap( INST* const pinst, const WCHAR* const wszFlushMapFilePath, const FMPGNO fmpgno, const JET_GRBIT grbit ) { if ( grbit & JET_bitDBUtilOptionVerify ) { return CFlushMapForDump::ErrChecksumFlushMapFile( pinst, wszFlushMapFilePath ); } else { return CFlushMapForDump::ErrDumpFlushMapPage( pinst, wszFlushMapFilePath, fmpgno, grbit & JET_bitDBUtilOptionDumpVerbose ); } } LOCAL ERR ErrDBUTLDumpSpaceCat( JET_SESID sesid, JET_DBUTIL_W *pdbutil ) { ERR err = JET_errSuccess; JET_DBID dbid = JET_dbidNil; BOOL fDbAttached = fFalse; BOOL fDbOpen = fFalse; if ( ( pdbutil->spcatOptions.pgnoFirst < 1 ) || ( ( pdbutil->spcatOptions.pgnoLast != pgnoMax ) && ( pdbutil->spcatOptions.pgnoFirst > pdbutil->spcatOptions.pgnoLast ) ) ) { Error( ErrERRCheck( JET_errInvalidParameter ) ); } Call( ErrIsamAttachDatabase( sesid, pdbutil->spcatOptions.szDatabase, fFalse, NULL, 0, JET_bitDbReadOnly ) ); fDbAttached = fTrue; Call( ErrIsamOpenDatabase( sesid, pdbutil->spcatOptions.szDatabase, NULL, &dbid, JET_bitDbExclusive | JET_bitDbReadOnly ) ); fDbOpen = fTrue; if ( pdbutil->spcatOptions.pgnoLast == pgnoMax ) { Call( g_rgfmp[ (IFMP)dbid ].ErrPgnoLastFileSystem( &( pdbutil->spcatOptions.pgnoLast ) ) ); } pdbutil->spcatOptions.pgnoFirst = UlFunctionalMin( pdbutil->spcatOptions.pgnoFirst, pdbutil->spcatOptions.pgnoLast ); Assert( pdbutil->spcatOptions.pgnoFirst >= 1 ); Assert( pdbutil->spcatOptions.pgnoLast >= 1 ); Assert( pdbutil->spcatOptions.pgnoFirst <= pdbutil->spcatOptions.pgnoLast ); Call( ErrSPGetSpaceCategoryRange( (PIB*)sesid, (IFMP)dbid, pdbutil->spcatOptions.pgnoFirst, pdbutil->spcatOptions.pgnoLast, !!( pdbutil->grbitOptions & JET_bitDBUtilFullCategorization ), (JET_SPCATCALLBACK)pdbutil->spcatOptions.pfnSpaceCatCallback, pdbutil->spcatOptions.pvContext ) ); err = JET_errSuccess; HandleError: if ( fDbOpen ) { (void)ErrIsamCloseDatabase( sesid, dbid, NO_GRBIT ); fDbOpen = fFalse; } if ( fDbAttached ) { (void)ErrIsamDetachDatabase( sesid, NULL, pdbutil->spcatOptions.szDatabase ); fDbAttached = fFalse; } return err; } LOCAL ERR ErrDBUTLDumpCachedFileHeader( const WCHAR* const wszFilePath, const JET_GRBIT grbit ) { ERR err = JET_errSuccess; Call( ErrOSBCDumpCachedFileHeader( wszFilePath, grbit, CPRINTFSTDOUT::PcprintfInstance() ) ); HandleError: return err; } LOCAL ERR ErrDBUTLDumpCacheFile( const WCHAR* const wszFilePath, const JET_GRBIT grbit ) { ERR err = JET_errSuccess; Call( ErrOSBCDumpCacheFile( wszFilePath, grbit, CPRINTFSTDOUT::PcprintfInstance() ) ); HandleError: return err; } BOOL g_fDisableDumpPrintF = fFalse; ERR ISAMAPI ErrIsamDBUtilities( JET_SESID sesid, JET_DBUTIL_W *pdbutil ) { ERR err = JET_errSuccess; INST *pinst = PinstFromPpib( (PIB*)sesid ); PIBTraceContextScope tcScope = ( (PIB*)sesid )->InitTraceContextScope(); tcScope->nParentObjectClass = tceNone; Assert( pdbutil ); Assert( pdbutil->cbStruct == sizeof( JET_DBUTIL_W ) ); if ( opDBUTILEDBDump != pdbutil->op && opDBUTILDumpPageUsage != pdbutil->op && opDBUTILChecksumLogFromMemory != pdbutil->op && opDBUTILDumpSpaceCategory != pdbutil->op && opDBUTILDumpRBSPages != pdbutil->op ) { if ( NULL == pdbutil->szDatabase || L'\0' == pdbutil->szDatabase[0] ) { return ErrERRCheck( JET_errDatabaseInvalidName ); } } if ( opDBUTILDumpRBSPages == pdbutil->op ) { if ( NULL == pdbutil->rbsOptions.szDatabase || L'\0' == pdbutil->rbsOptions.szDatabase[0] ) { return ErrERRCheck( JET_errDatabaseInvalidName ); } } if ( opDBUTILChecksumLogFromMemory == pdbutil->op ) { if ( pinst->m_plog->FLGFileOpened() || !pinst->FComputeLogDisabled() ) { return ErrERRCheck( JET_errInvalidParameter ); } } if ( ( pdbutil->grbitOptions & JET_bitDBUtilOptionSuppressConsoleOutput ) != 0 ) { g_fDisableDumpPrintF = fTrue; } switch ( pdbutil->op ) { #ifdef MINIMAL_FUNCTIONALITY #else case opDBUTILChecksumLogFromMemory: return ErrDUMPLogFromMemory( pinst, pdbutil->checksumlogfrommemory.szLog, pdbutil->checksumlogfrommemory.pvBuffer, pdbutil->checksumlogfrommemory.cbBuffer ); case opDBUTILDumpLogfile: return ErrDUMPLog( pinst, pdbutil->szDatabase, pdbutil->lGeneration, pdbutil->isec, pdbutil->grbitOptions, pdbutil->szIntegPrefix ); case opDBUTILDumpFlushMapFile: return ErrDBUTLDumpFlushMap( pinst, pdbutil->szDatabase, pdbutil->pgno, pdbutil->grbitOptions ); case opDBUTILDumpLogfileTrackNode: return JET_errSuccess; case opDBUTILEDBDump: return ErrDBUTLDump( sesid, pdbutil ); case opDBUTILDumpNode: return ErrDBUTLDumpNode( sesid, pinst->m_pfsapi, pdbutil->szDatabase, pdbutil->pgno, pdbutil->iline, pdbutil->grbitOptions ); #ifdef DEBUG case opDBUTILSetHeaderState: return ErrDUMPFixupHeader( pinst, pdbutil->szDatabase, pdbutil->grbitOptions & JET_bitDBUtilOptionDumpVerbose ); #endif case opDBUTILDumpPage: return ErrDBUTLDumpPage( pinst, pdbutil->szDatabase, pdbutil->pgno, pdbutil->szIndex, pdbutil->szTable, pdbutil->grbitOptions ); case opDBUTILDumpHeader: return ErrDUMPHeader( pinst, pdbutil->szDatabase, pdbutil->grbitOptions & JET_bitDBUtilOptionDumpVerbose ); case opDBUTILDumpCheckpoint: return ErrDUMPCheckpoint( pinst, pdbutil->szDatabase ); case opDBUTILDumpCachedFileHeader: return ErrDBUTLDumpCachedFileHeader( pdbutil->szDatabase, pdbutil->grbitOptions ); case opDBUTILDumpCacheFile: return ErrDBUTLDumpCacheFile( pdbutil->szDatabase, pdbutil->grbitOptions ); #endif case opDBUTILEDBRepair: return ErrDBUTLRepair( sesid, pdbutil, CPRINTFSTDOUT::PcprintfInstance() ); #ifdef MINIMAL_FUNCTIONALITY #else case opDBUTILEDBScrub: return ErrDBUTLScrub( sesid, pdbutil ); case opDBUTILDumpData: return ErrESEDUMPData( sesid, pdbutil ); case opDBUTILDumpPageUsage: return ErrDBUTLDumpPageUsage( sesid, pdbutil ); #endif case opDBUTILDBDefragment: { ERR errDetach; if ( (ULONG)UlParam( pinst, JET_paramEngineFormatVersion ) == JET_efvUsePersistedFormat ) { DBFILEHDR * pdbfilehdr = NULL; JET_ENGINEFORMATVERSION efvSourceDb = JET_efvExchange55Rtm; AllocR( pdbfilehdr = (DBFILEHDR * )PvOSMemoryPageAlloc( g_cbPage, NULL ) ); memset( pdbfilehdr, 0, g_cbPage ); IFileAPI * pfapi = NULL; if ( CIOFilePerf::ErrFileOpen( pinst->m_pfsapi, pinst, pdbutil->szDatabase, ( IFileAPI::fmfReadOnly | ( BoolParam( JET_paramEnableFileCache ) ? IFileAPI::fmfCached : IFileAPI::fmfNone ) ), iofileDbAttached, qwDefragFileID, &pfapi ) >= JET_errSuccess ) { err = ErrUtilReadShadowedHeader( pinst, pinst->m_pfsapi, pfapi, (BYTE*)pdbfilehdr, g_cbPage, OffsetOf( DBFILEHDR, le_cbPageSize ), urhfReadOnly ); if ( err >= JET_errSuccess ) { const FormatVersions * pfmtvers = NULL; err = ErrDBFindHighestMatchingDbMajors( pdbfilehdr->Dbv(), &pfmtvers, fTrue ); if ( err >= JET_errSuccess ) { efvSourceDb = pfmtvers->efv; } } delete pfapi; } CallR( err ); Assert( efvSourceDb != JET_efvUsePersistedFormat ); Assert( efvSourceDb != JET_efvExchange55Rtm ); err = SetParam( pinst, NULL, JET_paramEngineFormatVersion, efvSourceDb, NULL ); } Assert( JET_efvUsePersistedFormat != UlParam( pinst, JET_paramEngineFormatVersion ) ); err = ErrIsamAttachDatabase( sesid, pdbutil->szDatabase, fFalse, NULL, 0, JET_bitDbReadOnly ); if ( JET_errSuccess != err ) { return err; } err = ErrIsamCompact( sesid, pdbutil->szDatabase, pinst->m_pfsapi, pdbutil->szTable, JET_PFNSTATUS( pdbutil->pfnCallback ), NULL, pdbutil->grbitOptions ); errDetach = ErrIsamDetachDatabase( sesid, NULL, pdbutil->szDatabase ); if ( err >= JET_errSuccess && errDetach < JET_errSuccess ) { err = errDetach; } return err; } case opDBUTILDBTrim: { ERR errDetach; err = ErrIsamAttachDatabase( sesid, pdbutil->szDatabase, fFalse, NULL, 0, JET_bitDbExclusive ); if ( JET_errSuccess != err ) { return err; } err = ErrIsamTrimDatabase( sesid, pdbutil->szDatabase, pinst->m_pfsapi, CPRINTFSTDOUT::PcprintfInstance(), pdbutil->grbitOptions ); errDetach = ErrIsamDetachDatabase( sesid, NULL, pdbutil->szDatabase ); if ( err >= JET_errSuccess && errDetach < JET_errSuccess ) { err = errDetach; } return err; } case opDBUTILDumpSpaceCategory: return ErrDBUTLDumpSpaceCat( sesid, pdbutil ); case opDBUTILDumpRBSPages: return ErrDUMPRBSPage( pinst, pdbutil->rbsOptions.szDatabase, pdbutil->rbsOptions.pgnoFirst, pdbutil->rbsOptions.pgnoLast, pdbutil->grbitOptions & JET_bitDBUtilOptionDumpVerbose ); case opDBUTILDumpRBSHeader: return ErrDUMPRBSHeader( pinst, pdbutil->szDatabase, pdbutil->grbitOptions & JET_bitDBUtilOptionDumpVerbose ); } #ifdef MINIMAL_FUNCTIONALITY #else DBCCINFO dbccinfo; JET_DBID dbid = JET_dbidNil; JET_GRBIT grbitAttach; memset( &dbccinfo, 0, sizeof(DBCCINFO) ); dbccinfo.tableidPageInfo = JET_tableidNil; dbccinfo.tableidSpaceInfo = JET_tableidNil; dbccinfo.op = opDBUTILConsistency; switch ( pdbutil->op ) { #ifdef DEBUG case opDBUTILMunge: #endif case opDBUTILDumpMetaData: case opDBUTILDumpSpace: dbccinfo.op = pdbutil->op; break; } Assert( NULL != pdbutil->szDatabase ); OSStrCbCopyW( dbccinfo.wszDatabase, sizeof(dbccinfo.wszDatabase), pdbutil->szDatabase ); if ( NULL != pdbutil->szTable ) { OSStrCbCopyW( dbccinfo.wszTable, sizeof(dbccinfo.wszTable), pdbutil->szTable ); } if ( NULL != pdbutil->szIndex ) { OSStrCbCopyW( dbccinfo.wszIndex, sizeof(dbccinfo.wszIndex), pdbutil->szIndex ); } if ( pdbutil->grbitOptions & JET_bitDBUtilOptionStats ) { dbccinfo.grbitOptions |= JET_bitDBUtilOptionStats; } if ( pdbutil->grbitOptions & JET_bitDBUtilOptionDumpVerbose ) { dbccinfo.grbitOptions |= JET_bitDBUtilOptionDumpVerbose; } grbitAttach = ( opDBUTILMunge == dbccinfo.op ) ? 0 : JET_bitDbReadOnly; CallR( ErrIsamAttachDatabase( sesid, dbccinfo.wszDatabase, fFalse, NULL, 0, grbitAttach ) ); Assert( JET_wrnDatabaseAttached != err ); Call( ErrIsamOpenDatabase( sesid, dbccinfo.wszDatabase, NULL, &dbid, grbitAttach ) ); dbccinfo.ppib = (PIB*)sesid; dbccinfo.ifmp = dbid; switch ( dbccinfo.op ) { case opDBUTILConsistency: Call( ErrERRCheck( JET_errFeatureNotAvailable ) ); break; case opDBUTILDumpSpace: { if ( NULL == pdbutil->pfnCallback ) { Call( ErrERRCheck( JET_errFeatureNotAvailable ) ); } Call( ErrOLDDumpMSysDefrag( dbccinfo.ppib, dbccinfo.ifmp ) ); Call( ErrSCANDumpMSysScan( dbccinfo.ppib, dbccinfo.ifmp ) ); Call( MSysDBM::ErrDumpTable( dbccinfo.ifmp ) ); CBTreeStatsManager btsDbRootManager( pdbutil->grbitOptions, NULL ); BTREE_STATS * pbts = btsDbRootManager.Pbts(); if ( pbts->pBasicCatalog ) { BTREE_STATS_BASIC_CATALOG * pbtsBasicCatalog = pbts->pBasicCatalog; memset( pbtsBasicCatalog, 0, sizeof(*pbtsBasicCatalog) ); pbtsBasicCatalog->cbStruct = sizeof(*pbtsBasicCatalog); pbtsBasicCatalog->eType = eBTreeTypeInternalDbRootSpace; (void)ErrOSStrCbCopyW( pbtsBasicCatalog->rgName, sizeof(pbtsBasicCatalog->rgName), dbccinfo.wszDatabase ); pbtsBasicCatalog->objidFDP = objidSystemRoot; pbtsBasicCatalog->pgnoFDP = pgnoSystemRoot; } if ( pbts->pSpaceTrees ) { CPRINTF * const pcprintf = ( pdbutil->grbitOptions & JET_bitDBUtilOptionDumpVerbose ) ? CPRINTFSTDOUT::PcprintfInstance() : NULL; CallR( ErrDBUTLGetSpaceTreeInfo( dbccinfo.ppib, dbccinfo.ifmp, objidSystemRoot, pgnoSystemRoot, pbts->pSpaceTrees, pcprintf ) ); } if ( pbts->pParentOfLeaf ) { pbts->pParentOfLeaf->cpgData = 1; } Call( ((JET_PFNSPACEDATA)pdbutil->pfnCallback)( pbts, (JET_API_PTR)pdbutil->pvCallback ) ); CBTreeStatsManager btsTableManager( pdbutil->grbitOptions, pbts ); if( pbts->pSpaceTrees ) { Call( ErrDBUTLEnumSpaceTrees( dbccinfo.ppib, dbccinfo.ifmp, objidSystemRoot, btsTableManager.Pbts(), (JET_PFNSPACEDATA)pdbutil->pfnCallback, (JET_API_PTR)pdbutil->pvCallback ) ); } DBUTIL_ENUM_SPACE_CTX dbues = { 0 }; dbues.ppib = (JET_SESID)dbccinfo.ppib; dbues.ifmp = dbccinfo.ifmp; dbues.grbitDbUtilOptions = pdbutil->grbitOptions; dbues.wszSelectedTable = ( NULL == dbccinfo.wszTable || L'\0' == dbccinfo.wszTable[0] ? NULL : dbccinfo.wszTable ); dbues.pbts = btsTableManager.Pbts(); dbues.pfnBTreeStatsAnalysisFunc = (JET_PFNSPACEDATA)pdbutil->pfnCallback; dbues.pvBTreeStatsAnalysisFuncCtx = (JET_API_PTR) pdbutil->pvCallback; Call( ErrDBUTLDumpTables( &dbccinfo, ErrDBUTLEnumTableSpace, (VOID*)&dbues ) ); } break; case opDBUTILDumpMetaData: if ( dbccinfo.grbitOptions & JET_bitDBUtilOptionDumpVerbose ) { printf( "******************************* MSysLocales **********************************\n" ); err = ErrCATDumpMSLocales( NULL, dbccinfo.ifmp ); if ( err != JET_errSuccess ) { printf( "Failed to dump %hs table with: %d (continuing on ...).\n", szMSLocales, err ); } printf( "******************************************************************************\n" ); } printf( "******************************* META-DATA DUMP *******************************\n" ); if ( dbccinfo.grbitOptions & JET_bitDBUtilOptionDumpVerbose ) { Call( ErrDBUTLDumpTables( &dbccinfo, PrintTableMetaData ) ); } else { printf( "Name Type ObjidFDP PgnoFDP\n" ); printf( "==============================================================================\n" ); printf( "%-51.5ws Db ", dbccinfo.wszDatabase ); DBUTLPrintfIntN( objidSystemRoot, 10 ); printf( " " ); DBUTLPrintfIntN( pgnoSystemRoot, 10 ); printf( "\n\n" ); Call( ErrDBUTLDumpTables( &dbccinfo, PrintTableBareMetaData ) ); } printf( "******************************************************************************\n" ); break; default: err = ErrERRCheck( JET_errFeatureNotAvailable ); Call( err ); break; } HandleError: if ( JET_tableidNil != dbccinfo.tableidPageInfo ) { Assert( dbccinfo.grbitOptions & JET_bitDBUtilOptionPageDump ); CallS( ErrDispCloseTable( (JET_SESID)dbccinfo.ppib, dbccinfo.tableidPageInfo ) ); dbccinfo.tableidPageInfo = JET_tableidNil; } if ( JET_dbidNil != dbid ) { (VOID)ErrIsamCloseDatabase( sesid, dbid, 0 ); } (VOID)ErrIsamDetachDatabase( sesid, NULL, dbccinfo.wszDatabase ); fflush( stdout ); #endif return err; }
33.47029
222
0.559197
augustoproiete-forks
dc8beb7e0e475f5430bc7ce23d8e16ac69573998
3,338
cpp
C++
src/collision.cpp
vcoutasso/AmiaMond
958a5a935ffd8c702147f1a53dd964dccb566a12
[ "MIT" ]
3
2020-05-13T21:44:25.000Z
2021-09-23T20:21:52.000Z
src/collision.cpp
vcoutasso/AmiaMond
958a5a935ffd8c702147f1a53dd964dccb566a12
[ "MIT" ]
1
2019-06-18T02:08:15.000Z
2019-07-01T18:29:15.000Z
src/collision.cpp
vcoutasso/AmiaMond
958a5a935ffd8c702147f1a53dd964dccb566a12
[ "MIT" ]
1
2020-06-23T17:59:24.000Z
2020-06-23T17:59:24.000Z
/* * File: collision.cpp * Author: Nick (original version), ahnonay (SFML2 compatibility) */ #include <SFML/Graphics.hpp> #include "collision.hpp" namespace Collision { sf::Vector2f GetSpriteCenter(const sf::Sprite & Object) { sf::FloatRect AABB = Object.getGlobalBounds(); return sf::Vector2f(AABB.left + AABB.width / 2.f, AABB.top + AABB.height / 2.f); } sf::Vector2f GetSpriteSize(const sf::Sprite & Object) { sf::IntRect OriginalSize = Object.getTextureRect(); sf::Vector2f Scale = Object.getScale(); return sf::Vector2f(OriginalSize.width * Scale.x, OriginalSize.height * Scale.y); } bool CircleTest(const sf::Sprite & Object1, const sf::Sprite & Object2) { sf::Vector2f Obj1Size = GetSpriteSize(Object1); sf::Vector2f Obj2Size = GetSpriteSize(Object2); float Radius1 = (Obj1Size.x + Obj1Size.y) / 4; float Radius2 = (Obj2Size.x + Obj2Size.y) / 4; sf::Vector2f Distance = GetSpriteCenter(Object1) - GetSpriteCenter(Object2); return (Distance.x * Distance.x + Distance.y * Distance.y <= (Radius1 + Radius2) * (Radius1 + Radius2)); } class OrientedBoundingBox // Used in the BoundingBoxTest { public: OrientedBoundingBox(const sf::Sprite& Object) // Calculate the four points of the OBB from a transformed (scaled, rotated...) sprite { sf::Transform trans = Object.getTransform(); sf::IntRect local = Object.getTextureRect(); Points[0] = trans.transformPoint(0.f, 0.f); Points[1] = trans.transformPoint(local.width, 0.f); Points[2] = trans.transformPoint(local.width, local.height); Points[3] = trans.transformPoint(0.f, local.height); } sf::Vector2f Points[4]; void ProjectOntoAxis(const sf::Vector2f& Axis, float& Min, float& Max) // Project all four points of the OBB onto the given axis and return the dotproducts of the two outermost points { Min = (Points[0].x * Axis.x + Points[0].y * Axis.y); Max = Min; for (int j = 1; j < 4; j++) { float Projection = (Points[j].x * Axis.x + Points[j].y * Axis.y); if (Projection < Min) Min = Projection; if (Projection > Max) Max = Projection; } } }; bool BoundingBoxTest(const sf::Sprite & Object1, const sf::Sprite & Object2) { OrientedBoundingBox OBB1(Object1); OrientedBoundingBox OBB2(Object2); // Create the four distinct axes that are perpendicular to the edges of the two rectangles sf::Vector2f Axes[4] = { sf::Vector2f(OBB1.Points[1].x - OBB1.Points[0].x, OBB1.Points[1].y - OBB1.Points[0].y), sf::Vector2f(OBB1.Points[1].x - OBB1.Points[2].x, OBB1.Points[1].y - OBB1.Points[2].y), sf::Vector2f(OBB2.Points[0].x - OBB2.Points[3].x, OBB2.Points[0].y - OBB2.Points[3].y), sf::Vector2f(OBB2.Points[0].x - OBB2.Points[1].x, OBB2.Points[0].y - OBB2.Points[1].y) }; for (int i = 0; i < 4; i++) // For each axis... { float MinOBB1, MaxOBB1, MinOBB2, MaxOBB2; // ... project the points of both OBBs onto the axis ... OBB1.ProjectOntoAxis(Axes[i], MinOBB1, MaxOBB1); OBB2.ProjectOntoAxis(Axes[i], MinOBB2, MaxOBB2); // ... and check whether the outermost projected points of both OBBs overlap. // If this is not the case, the Separating Axis Theorem states that there can be no collision between the rectangles if (!((MinOBB2 <= MaxOBB1) && (MaxOBB2 >= MinOBB1))) return false; } return true; } }
33.717172
185
0.674356
vcoutasso
dc8f0cc38547939dcee1d3a977d40d96e1f7a7d6
2,177
cpp
C++
infer/tests/codetoanalyze/cpp/pulse/fbstring.cpp
JacobBarthelmeh/infer
12c582a69855e17a2cf9c7b6cdf7f8e9c71e5341
[ "MIT" ]
30
2019-06-28T15:20:25.000Z
2021-08-25T11:37:30.000Z
infer/tests/codetoanalyze/cpp/pulse/fbstring.cpp
JacobBarthelmeh/infer
12c582a69855e17a2cf9c7b6cdf7f8e9c71e5341
[ "MIT" ]
39
2019-06-28T15:08:12.000Z
2020-07-17T01:44:33.000Z
infer/tests/codetoanalyze/cpp/pulse/fbstring.cpp
JacobBarthelmeh/infer
12c582a69855e17a2cf9c7b6cdf7f8e9c71e5341
[ "MIT" ]
17
2019-06-28T14:40:41.000Z
2021-03-11T19:26:13.000Z
/* * 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. */ #include <stdlib.h> // Caricature of folly::basic_fbstring without the union between small // and medium/large data representations, and with an explicit field // for category_ instead of bitmasking part of the data value. // ref: // https://github.com/facebook/folly/blob/72850c2ebfb94d87bea74d89fcf79f3aaa91a627/folly/FBString.h enum category { small = 0, // ignore small strings for now medium = 1, large = 2, }; void* checkedMalloc(size_t size) { void* ptr = malloc(size); if (ptr == nullptr) { exit(1); } return ptr; } struct LikeFBString { int category_; char* buffer_; size_t size_; unsigned int* refcount_; LikeFBString() {} LikeFBString(const LikeFBString& src) { category_ = src.category(); switch (src.category_) { case medium: copyMedium(src); break; case large: copyLarge(src); break; default: exit(2); } } ~LikeFBString() { if (category() == medium) { free(buffer_); } else { decr_ref_count(); } } void copySmall(const LikeFBString& src) {} void copyMedium(const LikeFBString& src) { buffer_ = (char*)checkedMalloc(src.size_); size_ = src.size_; } void copyLarge(const LikeFBString& src) { buffer_ = src.buffer_; size_ = src.size_; refcount_ = src.refcount_; *refcount_ = *refcount_ + 1; } int category() const { return category_; } void decr_ref_count() { if (*refcount_ <= 0) { exit(1); } *refcount_ = *refcount_ - 1; if (*refcount_ == 0) { free(buffer_); } } }; void copy_fbstring(LikeFBString& s) { // this might alias the underlying buffers if the string is large in // that case the destruction of t does not de-allocate its buffer // but pulse might think it does if it fails to remember which // category t belongs to and follows impossibly control flow LikeFBString t = s; } void pass_to_copy_ok() { LikeFBString s; copy_fbstring(s); }
22.214286
99
0.649977
JacobBarthelmeh
dc8ffd8eb171620b43a8b04ac703d218ae42e844
9,300
cpp
C++
Amcl/cpp_armv7l/ecdh_NIST256.cpp
UoS-SCCS/ecc-daa
eebd40d01aed7a3ccb8dc33df8a4b6415f02dda9
[ "BSD-2-Clause" ]
2
2020-02-28T10:40:12.000Z
2021-02-18T03:32:28.000Z
Amcl/cpp_armv7l/ecdh_NIST256.cpp
UoS-SCCS/ecc-daa
eebd40d01aed7a3ccb8dc33df8a4b6415f02dda9
[ "BSD-2-Clause" ]
null
null
null
Amcl/cpp_armv7l/ecdh_NIST256.cpp
UoS-SCCS/ecc-daa
eebd40d01aed7a3ccb8dc33df8a4b6415f02dda9
[ "BSD-2-Clause" ]
null
null
null
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* ECDH/ECIES/ECDSA Functions - see main program below */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <time.h> #include "ecdh_NIST256.h" using namespace B256_28; using namespace NIST256; /* Calculate a public/private EC GF(p) key pair. W=S.G mod EC(p), * where S is the secret key and W is the public key * and G is fixed generator. * If RNG is NULL then the private key is provided externally in S * otherwise it is generated randomly internally */ int NIST256::ECP_KEY_PAIR_GENERATE(csprng *RNG,octet* S,octet *W) { BIG r,gx,gy,s; ECP G; int res=0; ECP_generator(&G); BIG_rcopy(r,CURVE_Order); if (RNG!=NULL) { BIG_randomnum(s,r,RNG); } else { BIG_fromBytes(s,S->val); BIG_mod(s,r); } #ifdef AES_S BIG_mod2m(s,2*AES_S); // BIG_toBytes(S->val,s); #endif S->len=EGS_NIST256; BIG_toBytes(S->val,s); ECP_mul(&G,s); ECP_toOctet(W,&G,false); // To use point compression on public keys, change to true /* #if CURVETYPE_NIST256!=MONTGOMERY ECP_get(gx,gy,&G); #else ECP_get(gx,&G); #endif #if CURVETYPE_NIST256!=MONTGOMERY W->len=2*EFS_NIST256+1; W->val[0]=4; BIG_toBytes(&(W->val[1]),gx); BIG_toBytes(&(W->val[EFS_NIST256+1]),gy); #else W->len=EFS_NIST256+1; W->val[0]=2; BIG_toBytes(&(W->val[1]),gx); #endif */ return res; } /* Validate public key */ int NIST256::ECP_PUBLIC_KEY_VALIDATE(octet *W) { BIG q,r,wx,k; ECP WP; int valid,nb; int res=0; BIG_rcopy(q,Modulus); BIG_rcopy(r,CURVE_Order); valid=ECP_fromOctet(&WP,W); if (!valid) res=ECDH_INVALID_PUBLIC_KEY; /* BIG_fromBytes(wx,&(W->val[1])); if (BIG_comp(wx,q)>=0) res=ECDH_INVALID_PUBLIC_KEY; #if CURVETYPE_NIST256!=MONTGOMERY BIG wy; BIG_fromBytes(wy,&(W->val[EFS_NIST256+1])); if (BIG_comp(wy,q)>=0) res=ECDH_INVALID_PUBLIC_KEY; #endif */ if (res==0) { //#if CURVETYPE_NIST256!=MONTGOMERY // valid=ECP_set(&WP,wx,wy); //#else // valid=ECP_set(&WP,wx); //#endif // if (!valid || ECP_isinf(&WP)) res=ECDH_INVALID_PUBLIC_KEY; // if (res==0 ) // {/* Check point is not in wrong group */ nb=BIG_nbits(q); BIG_one(k); BIG_shl(k,(nb+4)/2); BIG_add(k,q,k); BIG_sdiv(k,r); /* get co-factor */ while (BIG_parity(k)==0) { ECP_dbl(&WP); BIG_fshr(k,1); } if (!BIG_isunity(k)) ECP_mul(&WP,k); if (ECP_isinf(&WP)) res=ECDH_INVALID_PUBLIC_KEY; // } } return res; } /* IEEE-1363 Diffie-Hellman online calculation Z=S.WD */ int NIST256::ECP_SVDP_DH(octet *S,octet *WD,octet *Z) { BIG r,s,wx; int valid; ECP W; int res=0; BIG_fromBytes(s,S->val); valid=ECP_fromOctet(&W,WD); /* BIG_fromBytes(wx,&(WD->val[1])); #if CURVETYPE_NIST256!=MONTGOMERY BIG wy; BIG_fromBytes(wy,&(WD->val[EFS_NIST256+1])); valid=ECP_set(&W,wx,wy); #else valid=ECP_set(&W,wx); #endif */ if (!valid) res=ECDH_ERROR; if (res==0) { BIG_rcopy(r,CURVE_Order); BIG_mod(s,r); ECP_mul(&W,s); if (ECP_isinf(&W)) res=ECDH_ERROR; else { #if CURVETYPE_NIST256!=MONTGOMERY ECP_get(wx,wx,&W); #else ECP_get(wx,&W); #endif Z->len=MODBYTES_B256_28; BIG_toBytes(Z->val,wx); } } return res; } #if CURVETYPE_NIST256!=MONTGOMERY /* IEEE ECDSA Signature, C and D are signature on F using private key S */ int NIST256::ECP_SP_DSA(int sha,csprng *RNG,octet *K,octet *S,octet *F,octet *C,octet *D) { char h[128]; octet H= {0,sizeof(h),h}; BIG r,s,f,c,d,u,vx,w; ECP G,V; ehashit(sha,F,-1,NULL,&H,sha); ECP_generator(&G); BIG_rcopy(r,CURVE_Order); BIG_fromBytes(s,S->val); int hlen=H.len; if (H.len>MODBYTES_B256_28) hlen=MODBYTES_B256_28; BIG_fromBytesLen(f,H.val,hlen); if (RNG!=NULL) { do { BIG_randomnum(u,r,RNG); BIG_randomnum(w,r,RNG); /* side channel masking */ #ifdef AES_S BIG_mod2m(u,2*AES_S); #endif ECP_copy(&V,&G); ECP_mul(&V,u); ECP_get(vx,vx,&V); BIG_copy(c,vx); BIG_mod(c,r); if (BIG_iszilch(c)) continue; BIG_modmul(u,u,w,r); BIG_invmodp(u,u,r); BIG_modmul(d,s,c,r); BIG_add(d,f,d); BIG_modmul(d,d,w,r); BIG_modmul(d,u,d,r); } while (BIG_iszilch(d)); } else { BIG_fromBytes(u,K->val); BIG_mod(u,r); #ifdef AES_S BIG_mod2m(u,2*AES_S); #endif ECP_copy(&V,&G); ECP_mul(&V,u); ECP_get(vx,vx,&V); BIG_copy(c,vx); BIG_mod(c,r); if (BIG_iszilch(c)) return ECDH_ERROR; BIG_invmodp(u,u,r); BIG_modmul(d,s,c,r); BIG_add(d,f,d); BIG_modmul(d,u,d,r); if (BIG_iszilch(d)) return ECDH_ERROR; } C->len=D->len=EGS_NIST256; BIG_toBytes(C->val,c); BIG_toBytes(D->val,d); return 0; } /* IEEE1363 ECDSA Signature Verification. Signature C and D on F is verified using public key W */ int NIST256::ECP_VP_DSA(int sha,octet *W,octet *F, octet *C,octet *D) { char h[128]; octet H= {0,sizeof(h),h}; BIG r,wx,wy,f,c,d,h2; int res=0; ECP G,WP; int valid; ehashit(sha,F,-1,NULL,&H,sha); ECP_generator(&G); BIG_rcopy(r,CURVE_Order); OCT_shl(C,C->len-MODBYTES_B256_28); OCT_shl(D,D->len-MODBYTES_B256_28); BIG_fromBytes(c,C->val); BIG_fromBytes(d,D->val); int hlen=H.len; if (hlen>MODBYTES_B256_28) hlen=MODBYTES_B256_28; BIG_fromBytesLen(f,H.val,hlen); //BIG_fromBytes(f,H.val); if (BIG_iszilch(c) || BIG_comp(c,r)>=0 || BIG_iszilch(d) || BIG_comp(d,r)>=0) res=ECDH_INVALID; if (res==0) { BIG_invmodp(d,d,r); BIG_modmul(f,f,d,r); BIG_modmul(h2,c,d,r); valid=ECP_fromOctet(&WP,W); /* BIG_fromBytes(wx,&(W->val[1])); BIG_fromBytes(wy,&(W->val[EFS_NIST256+1])); valid=ECP_set(&WP,wx,wy); */ if (!valid) res=ECDH_ERROR; else { ECP_mul2(&WP,&G,h2,f); if (ECP_isinf(&WP)) res=ECDH_INVALID; else { ECP_get(d,d,&WP); BIG_mod(d,r); if (BIG_comp(d,c)!=0) res=ECDH_INVALID; } } } return res; } /* IEEE1363 ECIES encryption. Encryption of plaintext M uses public key W and produces ciphertext V,C,T */ void NIST256::ECP_ECIES_ENCRYPT(int sha,octet *P1,octet *P2,csprng *RNG,octet *W,octet *M,int tlen,octet *V,octet *C,octet *T) { int i,len; char z[EFS_NIST256],vz[3*EFS_NIST256+1],k[2*AESKEY_NIST256],k1[AESKEY_NIST256],k2[AESKEY_NIST256],l2[8],u[EFS_NIST256]; octet Z= {0,sizeof(z),z}; octet VZ= {0,sizeof(vz),vz}; octet K= {0,sizeof(k),k}; octet K1= {0,sizeof(k1),k1}; octet K2= {0,sizeof(k2),k2}; octet L2= {0,sizeof(l2),l2}; octet U= {0,sizeof(u),u}; if (ECP_KEY_PAIR_GENERATE(RNG,&U,V)!=0) return; if (ECP_SVDP_DH(&U,W,&Z)!=0) return; OCT_copy(&VZ,V); OCT_joctet(&VZ,&Z); KDF2(sha,&VZ,P1,2*AESKEY_NIST256,&K); K1.len=K2.len=AESKEY_NIST256; for (i=0; i<AESKEY_NIST256; i++) { K1.val[i]=K.val[i]; K2.val[i]=K.val[AESKEY_NIST256+i]; } AES_CBC_IV0_ENCRYPT(&K1,M,C); OCT_jint(&L2,P2->len,8); len=C->len; OCT_joctet(C,P2); OCT_joctet(C,&L2); HMAC(sha,C,&K2,tlen,T); C->len=len; } /* IEEE1363 ECIES decryption. Decryption of ciphertext V,C,T using private key U outputs plaintext M */ int NIST256::ECP_ECIES_DECRYPT(int sha,octet *P1,octet *P2,octet *V,octet *C,octet *T,octet *U,octet *M) { int i,len; char z[EFS_NIST256],vz[3*EFS_NIST256+1],k[2*AESKEY_NIST256],k1[AESKEY_NIST256],k2[AESKEY_NIST256],l2[8],tag[32]; octet Z= {0,sizeof(z),z}; octet VZ= {0,sizeof(vz),vz}; octet K= {0,sizeof(k),k}; octet K1= {0,sizeof(k1),k1}; octet K2= {0,sizeof(k2),k2}; octet L2= {0,sizeof(l2),l2}; octet TAG= {0,sizeof(tag),tag}; if (ECP_SVDP_DH(U,V,&Z)!=0) return 0; OCT_copy(&VZ,V); OCT_joctet(&VZ,&Z); KDF2(sha,&VZ,P1,2*AESKEY_NIST256,&K); K1.len=K2.len=AESKEY_NIST256; for (i=0; i<AESKEY_NIST256; i++) { K1.val[i]=K.val[i]; K2.val[i]=K.val[AESKEY_NIST256+i]; } if (!AES_CBC_IV0_DECRYPT(&K1,C,M)) return 0; OCT_jint(&L2,P2->len,8); len=C->len; OCT_joctet(C,P2); OCT_joctet(C,&L2); HMAC(sha,C,&K2,T->len,&TAG); C->len=len; if (!OCT_ncomp(T,&TAG,T->len)) return 0; return 1; } #endif
21.330275
126
0.605806
UoS-SCCS
dc942c79cd64ccf6f1695c44efd44629642dc60b
194
hpp
C++
src/icons.hpp
nagalun/guimachi
571ffcb762d12c14e019106d7324232f90b02729
[ "0BSD" ]
null
null
null
src/icons.hpp
nagalun/guimachi
571ffcb762d12c14e019106d7324232f90b02729
[ "0BSD" ]
null
null
null
src/icons.hpp
nagalun/guimachi
571ffcb762d12c14e019106d7324232f90b02729
[ "0BSD" ]
null
null
null
#pragma once #include <QIcon> #include <QColor> QIcon loadSvgIconReplacingColor(const char * file, QColor newColor); QIcon loadSvgIconReplacingColor(const char * file, const char * newColor);
24.25
74
0.783505
nagalun
dc94724dd0deb1a74db111bf376f1677049459a9
2,118
cpp
C++
factories/UltrasonicFactory.cpp
Team302/2018PowerUp
f681304ce67593e80ade0376ef82abb90ceb201f
[ "MIT" ]
null
null
null
factories/UltrasonicFactory.cpp
Team302/2018PowerUp
f681304ce67593e80ade0376ef82abb90ceb201f
[ "MIT" ]
2
2018-09-07T14:16:18.000Z
2018-09-07T14:18:49.000Z
factories/UltrasonicFactory.cpp
Team302/2018PowerUp
f681304ce67593e80ade0376ef82abb90ceb201f
[ "MIT" ]
null
null
null
/* * UltrasonicFactory.cpp * * Created on: Feb 10, 2018 * Author: team302 */ #include <factories/UltrasonicFactory.h> #include <subsys/components/DragonUltrasonic.h> UltrasonicFactory* UltrasonicFactory::m_ultrasonicFactory = nullptr; DragonUltrasonic* UltrasonicFactory::m_ultrasonic = nullptr; UltrasonicFactory* UltrasonicFactory::GetUltrasonicFactory() { if ( UltrasonicFactory::m_ultrasonicFactory == nullptr ) { UltrasonicFactory::m_ultrasonicFactory = new UltrasonicFactory(); } return UltrasonicFactory::m_ultrasonicFactory; } DragonUltrasonic* UltrasonicFactory::GetDragonUltrasonic ( DragonUltrasonic::ULTRASONIC_USAGE usage ) { DragonUltrasonic* ultra = nullptr; if ( usage == DragonUltrasonic::LEFT_SIDE_DISTANCE ) { ultra = m_left; } else if ( usage == DragonUltrasonic::RIGHT_SIDE_DISTANCE ) { ultra = m_right; } else { printf( "UltrasonicFactory::GetDragonUltrasonic invalid usage %d \n", usage ); } return ultra; } //======================================================================================= // Method: CreateUltrasonic // Description: Create an ultrasonic from the inputs // Returns: DragonUltrasonic* //======================================================================================= DragonUltrasonic* UltrasonicFactory::CreateUltrasonic ( DragonUltrasonic::ULTRASONIC_USAGE usage, int analogInChannel ) { DragonUltrasonic* ultra = nullptr; if ( usage == DragonUltrasonic::LEFT_SIDE_DISTANCE ) { ultra = new DragonUltrasonic( usage, analogInChannel );; } else if ( usage == DragonUltrasonic::RIGHT_SIDE_DISTANCE ) { ultra = new DragonUltrasonic( usage, analogInChannel );; } else { printf( "UltrasonicFactory::GetDragonUltrasonic invalid usage %d \n", usage ); } return ultra; } UltrasonicFactory::UltrasonicFactory() : m_left( nullptr ), m_right( nullptr ) { }
26.810127
90
0.598678
Team302
dc960644bd4b4287355cafc309349aa9403b371c
17,578
cpp
C++
SXR/SDK/sxrsdk/src/main/jni/objects/vertex_buffer.cpp
xcaostagit/sxrsdk
f9fe29de2bdc010cc9cbfc63a4b3d25e910a6de6
[ "Apache-2.0" ]
15
2018-10-24T19:46:44.000Z
2021-11-14T19:57:04.000Z
SXR/SDK/sxrsdk/src/main/jni/objects/vertex_buffer.cpp
xcaostagit/sxrsdk
f9fe29de2bdc010cc9cbfc63a4b3d25e910a6de6
[ "Apache-2.0" ]
84
2018-10-25T15:55:49.000Z
2019-12-10T23:26:45.000Z
SXR/SDK/sxrsdk/src/main/jni/objects/vertex_buffer.cpp
xcaostagit/sxrsdk
f9fe29de2bdc010cc9cbfc63a4b3d25e910a6de6
[ "Apache-2.0" ]
19
2018-10-26T20:44:33.000Z
2019-06-28T14:40:03.000Z
/**** * * VertexBuffer maintains a vertex data array with locations, normals, * colors and texcoords. * ****/ #include "vertex_buffer.h" #include <sstream> #include "glm/gtc/matrix_inverse.hpp" #define NO_LOGGING #include "util/sxr_log.h" namespace sxr { VertexBuffer::VertexBuffer(const char* layout_desc, int vertexCount) : DataDescriptor(layout_desc), mVertexCount(0), mVertexData(NULL) { mVertexData = NULL; setVertexCount(vertexCount); removePunctuations(layout_desc); } VertexBuffer::~VertexBuffer() { if (mVertexData != NULL) { free(mVertexData); mVertexData = NULL; } mVertexCount = 0; } void VertexBuffer::getBoundingVolume(BoundingVolume& bv) const { const float* verts = getVertexData(); int stride = getVertexSize(); bv.reset(); for (int i = 0; i < mVertexCount; ++i) { glm::vec3 v; const float* src = verts + i * stride; v.x = *src++; v.y = *src++; v.z = *src; bv.expand(v); } } const void* VertexBuffer::getData(int index, int& size) const { if ((index < 0) || (index > mLayout.size())) { return NULL; } std::lock_guard<std::mutex> lock(mLock); const DataEntry& e = mLayout[index]; const float* p = getVertexData(); size = e.Size; if (p) { return p + (e.Offset / sizeof(float)); } return nullptr; } const void* VertexBuffer::getData(const char* attributeName, int& size) const { std::lock_guard<std::mutex> lock(mLock); const DataEntry* e = find(attributeName); if ((e == NULL) || !e->IsSet) { return NULL; } const float* p = getVertexData(); size = e->Size; if (p) { return p + (e->Offset / sizeof(float)); } return nullptr; } /** * Update a float vertex attribute from memory data. * @param attributeName name of attribute to update * @param src pointer to source array of float data * @param srcSize total number of floats in source array * @param srcStride number of floats in a single entry of source array. * this is provided to allow copies from source vertex * formats that are not closely packed. * If it is zero, it is assumed the source array is * closely packed and the stride is the size of the attribute. * @return true if attribute was updated, false on error */ int VertexBuffer::setFloatVec(const char* attributeName, const float* src, int srcSize, int srcStride) { std::lock_guard<std::mutex> lock(mLock); DataEntry* attr = find(attributeName); const float* srcend; float* dest; int dstStride; int nverts = mVertexCount; int attrStride; LOGD("VertexBuffer::setFloatVec %s %d", attributeName, srcSize); if (attr == NULL) { LOGE("VertexBuffer: ERROR attribute %s not found in vertex buffer", attributeName); return 0; } if (src == NULL) { LOGE("VertexBuffer: cannot set attribute %s, source array not found", attributeName); return 0; } attrStride = attr->Size / sizeof(float); // # of floats in vertex attribute if (srcStride == 0) { srcStride = attrStride; nverts = srcSize / srcStride; // # of vertices in input array int rc = setVertexCount(nverts); if (rc <= 0) { LOGE("VertexBuffer: cannot enlarge vertex array %s, vertex count mismatch", attributeName); return rc; } } else if (attrStride > srcStride) // stride too small for this attribute? { LOGE("VertexBuffer: cannot copy to vertex array %s, stride is %d should be >= %d", attributeName, srcStride, attrStride); return 0; } nverts = srcSize / srcStride; // # of vertices in input array if (mVertexCount > nverts) { LOGE("VertexBuffer: cannot copy to vertex array %s, not enough vertices in source", attributeName); return false; } else if (mVertexCount == 0) { int rc = setVertexCount(nverts); if (rc <= 0) { return rc; } } dest = reinterpret_cast<float*>(mVertexData) + attr->Offset / sizeof(float); dstStride = getTotalSize() / sizeof(float); srcend = src + srcSize; markDirty(); for (int i = 0; i < mVertexCount; ++i) { for (int j = 0; j < attrStride; ++j) { dest[j] = src[j]; } dest += dstStride; if (src >= srcend) { LOGE("VertexBuffer: error copying to vertex array %s, not enough vertices in source array", attributeName); break; } src += srcStride; } markDirty(); attr->IsSet = true; return 1; } bool VertexBuffer::getFloatVec(const char* attributeName, float* dest, int destSize, int destStride) const { std::lock_guard<std::mutex> lock(mLock); const DataEntry* attr = find(attributeName); const float* dstend; const float* src = reinterpret_cast<float*>(mVertexData); int attrSize = attr->Size / sizeof(float); int srcStride = getVertexSize(); if ((attr == NULL) || !attr->IsSet) { LOGE("VertexBuffer: ERROR attribute %s not found in vertex buffer", attributeName); return false; } if (src == NULL) { LOGD("VertexBuffer: cannot set attribute %s", attributeName); return false; } src += attr->Offset / sizeof(float); dstend = dest + destSize; if (destStride == 0) { destStride = attrSize; } for (int i = 0; i < mVertexCount; ++i) { for (int j = 0; j < attrSize; ++j) { dest[j] = src[j]; } src += srcStride; dest += destStride; if (dest > dstend) { LOGE("VertexBuffer: error reading from vertex array %s, not enough room in destination array", attributeName); return false; } } return true; } /** * Update an integer vertex attribute from memory data. * @param attributeName name of attribute to update * @param src pointer to source array of int data * @param srcSize total number of ints in source array * @param srcStride number of ints in a single entry of source array. * this is provided to allow copies from source vertex * formats that are not closely packed. * If it is zero, it is assumed the source array is * closely packed and the stride is the size of the attribute. * @return true if attribute was updated, false on error */ int VertexBuffer::setIntVec(const char* attributeName, const int* src, int srcSize, int srcStride) { std::lock_guard<std::mutex> lock(mLock); DataEntry* attr = find(attributeName); const int* srcend; int* dest; int dstStride; int nverts = mVertexCount; int attrStride; LOGV("VertexBuffer::setIntVec %s %d", attributeName, srcSize); if (attr == NULL) { LOGE("VertexBuffer: ERROR attribute %s not found in vertex buffer", attributeName); return 0; } if (src == NULL) { LOGE("VertexBuffer: cannot set attribute %s, source array not found", attributeName); return 0; } attrStride = attr->Size / sizeof(int); if (srcStride == 0) { srcStride = attrStride; nverts = srcSize / srcStride; // # of vertices in input array int rc = setVertexCount(nverts); if (rc <= 0) { LOGE("VertexBuffer: cannot enlarge vertex array %s, vertex count mismatch", attributeName); return rc; } } else if (attrStride > srcStride) // stride too small for this attribute? { LOGE("VertexBuffer: cannot copy to vertex array %s, stride is %d should be >= %d", attributeName, srcStride, attrStride); return 0; } nverts = srcSize / srcStride; // # of vertices in input array if (mVertexCount > nverts) { LOGE("VertexBuffer: cannot copy to vertex array %s, not enough vertices in source", attributeName); return false; } else if (mVertexCount == 0) { int rc = setVertexCount(nverts); if (rc <= 0) { LOGE("VertexBuffer: cannot enlarge vertex array %s, vertex count mismatch", attributeName); return rc; } } markDirty(); dest = reinterpret_cast<int*>(mVertexData) + attr->Offset / sizeof(int); dstStride = getTotalSize() / sizeof(int); srcend = src + srcSize; for (int i = 0; i < mVertexCount; ++i) { for (int j = 0; j < attrStride; ++j) { dest[j] = src[j]; } dest += dstStride; if (src >= srcend) { LOGE("VertexBuffer: error copying to vertex array %s, not enough vertices in source array", attributeName); break; } src += srcStride; } markDirty(); attr->IsSet = true; return 1; } bool VertexBuffer::getIntVec(const char* attributeName, int* dest, int destSize, int destStride) const { std::lock_guard<std::mutex> lock(mLock); const DataEntry* attr = find(attributeName); const int* dstend; const int* src = reinterpret_cast<int*>(mVertexData); int attrSize = attr->Size / sizeof(int); int srcStride = getTotalSize() / sizeof(int); if ((attr == NULL) || !attr->IsSet) { LOGE("VertexBuffer: ERROR attribute %s not found in vertex buffer", attributeName); return false; } if (src == NULL) { LOGE("VertexBuffer: cannot set attribute %s", attributeName); return false; } src += attr->Offset / sizeof(int); dstend = dest + destSize; if (destStride == 0) { destStride = attrSize; } for (int i = 0; i < mVertexCount; ++i) { for (int j = 0; j < attrSize; ++j) { dest[j] = src[j]; } src += srcStride; if (dest > dstend) { LOGE("VertexBuffer: error reading from vertex array %s, not enough room in destination array", attributeName); return false; } dest += destStride; } return true; } bool VertexBuffer::getInfo(const char* attributeName, int& index, int& offset, int& size) const { std::lock_guard<std::mutex> lock(mLock); const DataEntry* attr = find(attributeName); if ((attr == NULL) || !attr->IsSet) return false; offset = attr->Offset; index = attr->Index; size = attr->Size; return true; } int VertexBuffer::setVertexCount(int count) { if ((mVertexCount != 0) && (mVertexCount != count)) { LOGE("VertexBuffer: cannot change size of vertex buffer from %d vertices to %d", mVertexCount, count); return 0; } if (mVertexCount == count) { return true; } if (count > 0) { int vsize = getTotalSize(); int datasize = vsize * count; LOGV("VertexBuffer: allocating vertex buffer of %d bytes with %d vertices\n", datasize, count); mVertexData = (char*) malloc(datasize); if (mVertexData) { mVertexCount = count; return 1; } LOGE("VertexBuffer: out of memory cannot allocate room for %d vertices\n", count); return -1; } LOGE("VertexBuffer: ERROR: no vertex buffer allocated\n"); return 0; } void VertexBuffer::transform(glm::mat4& mtx, bool doNormals) { const DataEntry* normEntry = find("a_normal"); float* data = reinterpret_cast<float*>(mVertexData); int stride = getVertexSize(); if (data == NULL) { return; } markDirty(); if (doNormals && normEntry) { std::lock_guard<std::mutex> lock(mLock); glm::mat4 invTranspose = glm::transpose(glm::inverse(mtx)); int normOfs = normEntry->Offset / sizeof(float); for (int i = 0; i < mVertexCount; ++i) { glm::vec4 p(data[0], data[1], data[2], 1); glm::vec4 n(data[normOfs], data[normOfs + 1], data[normOfs + 2], 1); p = p * mtx; data[0] = p.x; data[1] = p.y; data[2] = p.z; n = n * invTranspose; data[normOfs] = n.x; data[normOfs + 1] = n.y; data[normOfs + 2] = n.z; data += stride; } } else { for (int i = 0; i < mVertexCount; ++i) { std::lock_guard<std::mutex> lock(mLock); glm::vec4 p(data[0], data[1], data[2], 1); p = p * mtx; data[0] = p.x; data[1] = p.y; data[2] = p.z; data += stride; } } } bool VertexBuffer::forAllVertices(std::function<void(int iter, const float* vertex)> func) const { std::lock_guard<std::mutex> lock(mLock); const float* data = reinterpret_cast<const float*>(mVertexData); int stride = getVertexSize(); if (data == NULL) { return false; } for (int i = 0; i < mVertexCount; ++i) { func(i, data); data += stride; } return true; } bool VertexBuffer::forAllVertices(const char* attrName, std::function<void (int iter, const float* vertex)> func) const { std::lock_guard<std::mutex> lock(mLock); const DataEntry* attr = find(attrName); const float* data = reinterpret_cast<float*>(mVertexData); int stride = getVertexSize(); int ofs; if ((attr == NULL) || !attr->IsSet) { LOGE("VertexBuffer: ERROR attribute %s not found in vertex buffer", attrName); return false; } if (data == NULL) { LOGD("VertexBuffer: cannot find attribute %s", attrName); return false; } ofs = attr->Offset / sizeof(float); for (int i = 0; i < mVertexCount; ++i) { func(i, data + ofs); data += stride; } return true; } void VertexBuffer::dump() const { int vsize = getVertexSize(); forAllVertices([vsize](int iter, const float* vertex) { const float* v = vertex; std::ostringstream os; os.precision(3); for (int i = 0; i < vsize; ++i) { float f = *v++; os << std::fixed << f << " "; } LOGV("%s", os.str().c_str()); }); } void VertexBuffer::dump(const char* attrName) const { int vsize = getVertexSize(); const DataEntry* attr = find(attrName); if (attr == NULL) { LOGE("Attribute %s not found", attrName); return; } forAllVertices(attrName, [attr](int iter, const float* vertex) { std::ostringstream os; os.precision(3); int asize = attr->Size / sizeof(float); if (attr->IsInt) { const int* iv = (const int*) vertex; for (int i = 0; i < asize; ++i) { os << *iv++ << " "; } } else { const float* v = vertex; for (int i = 0; i < asize; ++i) { float f = *v++; os << std::fixed << f << " "; } } LOGV("%s", os.str().c_str()); }); } } // end sxrsdk
32.372007
133
0.490898
xcaostagit
dc968986514ea0009709d2dae96c4023c687eb2a
1,486
cpp
C++
altitude.cpp
ErofeevAA/taskCats
16fbcba6a0b824a581c7fed9c720b523a65fb2da
[ "MIT" ]
2
2021-05-02T04:44:00.000Z
2021-07-08T09:39:42.000Z
altitude.cpp
ErofeevAA/taskCats
16fbcba6a0b824a581c7fed9c720b523a65fb2da
[ "MIT" ]
null
null
null
altitude.cpp
ErofeevAA/taskCats
16fbcba6a0b824a581c7fed9c720b523a65fb2da
[ "MIT" ]
null
null
null
#include <fstream> #include <stack> #include <vector> int main() { std::ifstream in_file("input.txt"); int N; in_file >> N; std::vector<int> a(N); for(int i = 0; i < N; ++i) { in_file >> a[i]; } in_file.close(); std::stack<int> stack; std::vector<int> nums_global_end(N); std::vector<int> radii(N); for(int i = 0; i < N; ++i) { nums_global_end[i] = -1; radii[i] = 0; } for(int i = 0; i < N; ++i) { while (!stack.empty() && a[stack.top()] < a[i]) { int j = stack.top(); stack.pop(); if (nums_global_end[j] == -1 || i - j < j - nums_global_end[j]) { nums_global_end[j] = i; radii[j] = i - j; } } if (stack.empty()) { nums_global_end[i] = -1; radii[i] = 0; } else { if (a[i] != a[stack.top()]) { nums_global_end[i] = stack.top(); radii[i] = i - stack.top(); } else { nums_global_end[i] = nums_global_end[stack.top()]; if (nums_global_end[i] != -1) { radii[i] = i - nums_global_end[stack.top()]; } else { radii[i] = 0; } } } stack.push(i); } std::ofstream out_file("output.txt"); for(int i = 0; i < N; ++i) { out_file << radii[i] << ' '; } out_file.close(); }
27.018182
77
0.415882
ErofeevAA
dc9b1735c27afca52d4377bf2214dcab05521598
7,466
cc
C++
atom/browser/extensions/api/atom_extensions_api_client.cc
kewde/muon
43661f9a8ceefda8e3aba0e8944a72995aa53281
[ "MIT" ]
1,027
2016-12-24T13:05:29.000Z
2022-02-21T11:07:32.000Z
atom/browser/extensions/api/atom_extensions_api_client.cc
kewde/muon
43661f9a8ceefda8e3aba0e8944a72995aa53281
[ "MIT" ]
366
2016-12-24T05:58:54.000Z
2018-12-31T23:02:03.000Z
atom/browser/extensions/api/atom_extensions_api_client.cc
kewde/muon
43661f9a8ceefda8e3aba0e8944a72995aa53281
[ "MIT" ]
122
2017-01-14T23:48:49.000Z
2022-03-09T01:51:53.000Z
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/browser/extensions/api/atom_extensions_api_client.h" #include <memory> #include <string> #include "atom/browser/extensions/atom_extension_web_contents_observer.h" #include "atom/browser/extensions/tab_helper.h" #include "base/memory/ptr_util.h" #include "brave/browser/guest_view/brave_guest_view_manager_delegate.h" #include "chrome/browser/extensions/api/messaging/chrome_messaging_delegate.h" #include "content/public/browser/resource_request_info.h" #include "extensions/browser/api/management/management_api_delegate.h" #include "extensions/browser/api/storage/local_value_store_cache.h" #include "extensions/browser/api/storage/settings_observer.h" #include "extensions/browser/api/web_request/web_request_event_details.h" #include "extensions/browser/api/web_request/web_request_event_router_delegate.h" #include "extensions/browser/disable_reason.h" #include "extensions/browser/requirements_checker.h" #include "extensions/browser/value_store/value_store_factory.h" #include "extensions/common/manifest_handlers/icons_handler.h" namespace extensions { class AtomExtensionWebRequestEventRouterDelegate : public WebRequestEventRouterDelegate { public: AtomExtensionWebRequestEventRouterDelegate() {} ~AtomExtensionWebRequestEventRouterDelegate() override {} void NotifyWebRequestWithheld(int render_process_id, int render_frame_id, const std::string& extension_id) override { // TODO(bridiver) - will this ever be called? } private: DISALLOW_COPY_AND_ASSIGN(AtomExtensionWebRequestEventRouterDelegate); }; class AtomManagementAPIDelegate : public ManagementAPIDelegate { public: AtomManagementAPIDelegate() {} ~AtomManagementAPIDelegate() override {} void LaunchAppFunctionDelegate( const Extension* extension, content::BrowserContext* context) const override { } bool IsNewBookmarkAppsEnabled() const override { return false; } bool CanHostedAppsOpenInWindows() const override { return false; } GURL GetFullLaunchURL(const Extension* extension) const override { NOTIMPLEMENTED(); return GURL(); } LaunchType GetLaunchType(const ExtensionPrefs* prefs, const Extension* extension) const override { NOTIMPLEMENTED(); return LaunchType::LAUNCH_TYPE_INVALID; } void GetPermissionWarningsByManifestFunctionDelegate( ManagementGetPermissionWarningsByManifestFunction* function, const std::string& manifest_str) const override { NOTIMPLEMENTED(); } std::unique_ptr<InstallPromptDelegate> SetEnabledFunctionDelegate( content::WebContents* web_contents, content::BrowserContext* browser_context, const Extension* extension, const base::Callback<void(bool)>& callback) const override { NOTIMPLEMENTED(); return base::WrapUnique(install_prompt_delegate_); } // Enables the extension identified by |extension_id|. void EnableExtension(content::BrowserContext* context, const std::string& extension_id) const override { NOTIMPLEMENTED(); } // Disables the extension identified by |extension_id|. void DisableExtension( content::BrowserContext* context, const Extension* source_extension, const std::string& extension_id, disable_reason::DisableReason disable_reason) const override { NOTIMPLEMENTED(); } // Used to show a confirmation dialog when uninstalling |target_extension|. std::unique_ptr<UninstallDialogDelegate> UninstallFunctionDelegate( ManagementUninstallFunctionBase* function, const Extension* target_extension, bool show_programmatic_uninstall_ui) const override { NOTIMPLEMENTED(); return base::WrapUnique(uninstall_dialog_delegate_); } // Uninstalls the extension. bool UninstallExtension(content::BrowserContext* context, const std::string& transient_extension_id, UninstallReason reason, base::string16* error) const override { NOTIMPLEMENTED(); return false; } // Creates an app shortcut. bool CreateAppShortcutFunctionDelegate( ManagementCreateAppShortcutFunction* function, const Extension* extension, std::string* error) const override { NOTIMPLEMENTED(); return false; } // Forwards the call to launch_util::SetLaunchType in chrome. void SetLaunchType(content::BrowserContext* context, const std::string& extension_id, LaunchType launch_type) const override { NOTIMPLEMENTED(); } // Creates a bookmark app for |launch_url|. std::unique_ptr<AppForLinkDelegate> GenerateAppForLinkFunctionDelegate( ManagementGenerateAppForLinkFunction* function, content::BrowserContext* context, const std::string& title, const GURL& launch_url) const override { NOTIMPLEMENTED(); return base::WrapUnique(app_for_link_delegate_); } GURL GetIconURL( const extensions::Extension* extension, int icon_size, ExtensionIconSet::MatchType match, bool grayscale) const override { GURL icon_url(base::StringPrintf("%s%s/%d/%d%s", "chrome://extension-icon/", extension->id().c_str(), icon_size, match, grayscale ? "?grayscale=true" : "")); CHECK(icon_url.is_valid()); return icon_url; } private: InstallPromptDelegate* install_prompt_delegate_; UninstallDialogDelegate* uninstall_dialog_delegate_; AppForLinkDelegate* app_for_link_delegate_; DISALLOW_COPY_AND_ASSIGN(AtomManagementAPIDelegate); }; AtomExtensionsAPIClient::AtomExtensionsAPIClient() { } void AtomExtensionsAPIClient::AddAdditionalValueStoreCaches( content::BrowserContext* context, const scoped_refptr<ValueStoreFactory>& factory, const scoped_refptr<base::ObserverListThreadSafe<SettingsObserver>>& observers, std::map<settings_namespace::Namespace, ValueStoreCache*>* caches) { // Add temporary (fake) support for chrome.storage.sync. (*caches)[settings_namespace::SYNC] = new LocalValueStoreCache(factory); } std::unique_ptr<guest_view::GuestViewManagerDelegate> AtomExtensionsAPIClient::CreateGuestViewManagerDelegate( content::BrowserContext* context) const { return std::make_unique<brave::BraveGuestViewManagerDelegate>(context); } void AtomExtensionsAPIClient::AttachWebContentsHelpers( content::WebContents* web_contents) const { AtomExtensionWebContentsObserver::CreateForWebContents(web_contents); } MessagingDelegate* AtomExtensionsAPIClient::GetMessagingDelegate() { if (!messaging_delegate_) messaging_delegate_ = std::make_unique<ChromeMessagingDelegate>(); return messaging_delegate_.get(); } std::unique_ptr<WebRequestEventRouterDelegate> AtomExtensionsAPIClient::CreateWebRequestEventRouterDelegate() const { return base::WrapUnique( new extensions::AtomExtensionWebRequestEventRouterDelegate()); } ManagementAPIDelegate* AtomExtensionsAPIClient::CreateManagementAPIDelegate() const { return new AtomManagementAPIDelegate(); } } // namespace extensions
36.960396
81
0.731181
kewde
dc9c070e7a3f13d868daa5d58b9ca8870f42ead4
3,611
cc
C++
cpp/src/parquet/encryption/key_toolkit_internal.cc
davisusanibar/arrow
07ac9fd86c6225f493943e4ab0ff35b0fdbfb2ae
[ "CC-BY-3.0", "Apache-2.0", "CC0-1.0", "MIT" ]
1
2021-12-03T13:50:32.000Z
2021-12-03T13:50:32.000Z
cpp/src/parquet/encryption/key_toolkit_internal.cc
davisusanibar/arrow
07ac9fd86c6225f493943e4ab0ff35b0fdbfb2ae
[ "CC-BY-3.0", "Apache-2.0", "CC0-1.0", "MIT" ]
2
2021-11-17T14:36:51.000Z
2022-01-23T16:49:53.000Z
cpp/src/parquet/encryption/key_toolkit_internal.cc
davisusanibar/arrow
07ac9fd86c6225f493943e4ab0ff35b0fdbfb2ae
[ "CC-BY-3.0", "Apache-2.0", "CC0-1.0", "MIT" ]
null
null
null
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "arrow/util/base64.h" #include "parquet/encryption/encryption_internal.h" #include "parquet/encryption/key_toolkit_internal.h" namespace parquet { namespace encryption { namespace internal { // Acceptable key lengths in number of bits, used to validate the data key lengths // configured by users and the master key lengths fetched from KMS server. static constexpr const int32_t kAcceptableDataKeyLengths[] = {128, 192, 256}; std::string EncryptKeyLocally(const std::string& key_bytes, const std::string& master_key, const std::string& aad) { AesEncryptor key_encryptor(ParquetCipher::AES_GCM_V1, static_cast<int>(master_key.size()), false, false /*write_length*/); int encrypted_key_len = static_cast<int>(key_bytes.size()) + key_encryptor.CiphertextSizeDelta(); std::string encrypted_key(encrypted_key_len, '\0'); encrypted_key_len = key_encryptor.Encrypt( reinterpret_cast<const uint8_t*>(key_bytes.data()), static_cast<int>(key_bytes.size()), reinterpret_cast<const uint8_t*>(master_key.data()), static_cast<int>(master_key.size()), reinterpret_cast<const uint8_t*>(aad.data()), static_cast<int>(aad.size()), reinterpret_cast<uint8_t*>(&encrypted_key[0])); return ::arrow::util::base64_encode( ::arrow::util::string_view(encrypted_key.data(), encrypted_key_len)); } std::string DecryptKeyLocally(const std::string& encoded_encrypted_key, const std::string& master_key, const std::string& aad) { std::string encrypted_key = ::arrow::util::base64_decode(encoded_encrypted_key); AesDecryptor key_decryptor(ParquetCipher::AES_GCM_V1, static_cast<int>(master_key.size()), false, false /*contains_length*/); int decrypted_key_len = static_cast<int>(encrypted_key.size()) - key_decryptor.CiphertextSizeDelta(); std::string decrypted_key(decrypted_key_len, '\0'); decrypted_key_len = key_decryptor.Decrypt( reinterpret_cast<const uint8_t*>(encrypted_key.data()), static_cast<int>(encrypted_key.size()), reinterpret_cast<const uint8_t*>(master_key.data()), static_cast<int>(master_key.size()), reinterpret_cast<const uint8_t*>(aad.data()), static_cast<int>(aad.size()), reinterpret_cast<uint8_t*>(&decrypted_key[0])); return decrypted_key; } bool ValidateKeyLength(int32_t key_length_bits) { int32_t* found_key_length = std::find( const_cast<int32_t*>(kAcceptableDataKeyLengths), const_cast<int32_t*>(std::end(kAcceptableDataKeyLengths)), key_length_bits); return found_key_length != std::end(kAcceptableDataKeyLengths); } } // namespace internal } // namespace encryption } // namespace parquet
43.506024
90
0.715037
davisusanibar
dc9e975a21fb35347041fff95a802f04d365349e
1,049
cpp
C++
modules/imgproc/perf/perf_morph.cpp
thisisgopalmandal/opencv
4e2ef8c8f57644ccb8e762a37f70a61007c6be1c
[ "BSD-3-Clause" ]
56,632
2016-07-04T16:36:08.000Z
2022-03-31T18:38:14.000Z
modules/imgproc/perf/perf_morph.cpp
thisisgopalmandal/opencv
4e2ef8c8f57644ccb8e762a37f70a61007c6be1c
[ "BSD-3-Clause" ]
13,593
2016-07-04T13:59:03.000Z
2022-03-31T21:04:51.000Z
modules/imgproc/perf/perf_morph.cpp
thisisgopalmandal/opencv
4e2ef8c8f57644ccb8e762a37f70a61007c6be1c
[ "BSD-3-Clause" ]
54,986
2016-07-04T14:24:38.000Z
2022-03-31T22:51:18.000Z
// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. #include "perf_precomp.hpp" namespace opencv_test { #define TYPICAL_MAT_TYPES_MORPH CV_8UC1, CV_8UC4 #define TYPICAL_MATS_MORPH testing::Combine(SZ_ALL_GA, testing::Values(TYPICAL_MAT_TYPES_MORPH)) PERF_TEST_P(Size_MatType, erode, TYPICAL_MATS_MORPH) { Size sz = get<0>(GetParam()); int type = get<1>(GetParam()); Mat src(sz, type); Mat dst(sz, type); declare.in(src, WARMUP_RNG).out(dst); int runs = (sz.width <= 320) ? 15 : 1; TEST_CYCLE_MULTIRUN(runs) erode(src, dst, noArray()); SANITY_CHECK(dst); } PERF_TEST_P(Size_MatType, dilate, TYPICAL_MATS_MORPH) { Size sz = get<0>(GetParam()); int type = get<1>(GetParam()); Mat src(sz, type); Mat dst(sz, type); declare.in(src, WARMUP_RNG).out(dst); TEST_CYCLE() dilate(src, dst, noArray()); SANITY_CHECK(dst); } } // namespace
24.395349
102
0.681602
thisisgopalmandal
dca124941f50c7350815deef4062cbbb64b65b3c
952
cpp
C++
net-p2p/tekcoin/files/patch-src__net.cpp
tuaris/FreeBSD-Coin-Ports
330d9f5a10cf7dc1cddc3566b897bd4e6e265d9f
[ "BSD-2-Clause" ]
4
2016-04-07T23:38:13.000Z
2021-11-19T10:46:46.000Z
net-p2p/tekcoin/files/patch-src__net.cpp
tuaris/FreeBSD-Coin-Ports
330d9f5a10cf7dc1cddc3566b897bd4e6e265d9f
[ "BSD-2-Clause" ]
1
2018-01-20T15:45:23.000Z
2018-01-22T16:22:54.000Z
net-p2p/tekcoin/files/patch-src__net.cpp
tuaris/FreeBSD-Coin-Ports
330d9f5a10cf7dc1cddc3566b897bd4e6e265d9f
[ "BSD-2-Clause" ]
6
2016-04-07T23:41:03.000Z
2019-03-05T08:31:21.000Z
--- src/net.cpp.orig 2015-11-30 23:06:15 UTC +++ src/net.cpp @@ -58,7 +58,7 @@ static bool vfLimited[NET_MAX] = {}; static CNode* pnodeLocalHost = NULL; CAddress addrSeenByPeer(CService("0.0.0.0", 0), nLocalServices); uint64 nLocalHostNonce = 0; -array<int, THREAD_MAX> vnThreadsRunning; +boost::array<int, THREAD_MAX> vnThreadsRunning; static std::vector<SOCKET> vhListenSocket; CAddrMan addrman; @@ -1124,10 +1124,14 @@ void ThreadMapPort2(void* parg) #ifndef UPNPDISCOVER_SUCCESS /* miniupnpc 1.5 */ devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0); -#else +#elif MINIUPNPC_API_VERSION < 14 /* miniupnpc 1.6 */ int error = 0; devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error); +#else + /* miniupnpc 1.9.20150730 */ + int error = 0; + devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, 2, &error); #endif struct UPNPUrls urls;
34
84
0.663866
tuaris
dca417e020360b0ff967b917e4575725dfaa9038
404
cc
C++
experiment/memory-referencing-bug-experiment/main.cc
SeanChao/Computer-Systems
00e24308412916f345380fcb4d4a3de257b0c3ec
[ "MIT" ]
null
null
null
experiment/memory-referencing-bug-experiment/main.cc
SeanChao/Computer-Systems
00e24308412916f345380fcb4d4a3de257b0c3ec
[ "MIT" ]
null
null
null
experiment/memory-referencing-bug-experiment/main.cc
SeanChao/Computer-Systems
00e24308412916f345380fcb4d4a3de257b0c3ec
[ "MIT" ]
1
2021-12-21T08:49:42.000Z
2021-12-21T08:49:42.000Z
#include <iostream> struct str{ int a[2]; double d; }; double fun(int i) { str s; s.a[i] = 1073741824; s.d = 3.14; return s.d; } int main() { std::cout << fun(0) << '\n'; std::cout << fun(1) << '\n'; std::cout << fun(2) << '\n'; std::cout << fun(3) << '\n'; std::cout << fun(4) << '\n'; std::cout << fun(6) << '\n'; return 0; }
17.565217
33
0.408416
SeanChao