blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 117 | path stringlengths 3 268 | src_encoding stringclasses 34
values | length_bytes int64 6 4.23M | score float64 2.52 5.19 | int_score int64 3 5 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | text stringlengths 13 4.23M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
c599382744d0054863cc243c663bdd9ad58d0edb | C++ | TaylorEllington/ScientificHPC | /Project_3/src/Newton_interpolant.cpp | UTF-8 | 668 | 3.359375 | 3 | [] | no_license | /*
Taylor Ellington
Newton_interpolant.cpp
10/25/2015
*/
#include "Newton_interpolant.hpp"
Matrix Newton_coefficients(Matrix& x, Matrix& y){
int n = x.Size() ;
Matrix a( n );
//calculates newton coefficents based on method in the book
for(int i = 0; i < n; i++) {
a(i) = y(i);
}
for(int j = 1; j < n; j++){
for(int i = n-1; i >=j; i--){
a(i) = ( a(i) - a(i-1) )/( x(i) - x(i-j) );
}
}
return a;
}
double Newton_evaluate(Matrix& x, Matrix& c, double z){
int n = x.Size();
//evaluates newton interpolant
double temp = c(n-1);
for( int i = n - 2; i >= 0; i--){
temp = (temp * ( z-x(i) ) );
temp =temp + c(i);
}
return temp;
} | true |
f0ac006813b87708c406a42043cb07553da48790 | C++ | rbnelr/kiss | /kiss/vector/dm4.cpp | UTF-8 | 13,788 | 2.78125 | 3 | [] | no_license | // generated by C:\Users\Me\Desktop\kiss\vector_srcgen\srcgen.py
#include "dm4.hpp"
#include "dm2.hpp"
#include "dm3.hpp"
#include "dm2x3.hpp"
#include "dm3x4.hpp"
#include "fm4.hpp"
namespace vector {
//// Accessors
// get matrix row
dv4 dm4::get_row (int indx) const {
return dv4(arr[0][indx], arr[1][indx], arr[2][indx], arr[3][indx]);
}
//// Constructors
// static rows() and columns() methods are preferred over constructors, to avoid confusion if column or row vectors are supplied to the constructor
// supply all row vectors
dm4 dm4::rows (dv4 row0, dv4 row1, dv4 row2, dv4 row3) {
return dm4(row0[0], row0[1], row0[2], row0[3],
row1[0], row1[1], row1[2], row1[3],
row2[0], row2[1], row2[2], row2[3],
row3[0], row3[1], row3[2], row3[3]);
}
// supply all cells in row major order
dm4 dm4::rows (f64 c00, f64 c01, f64 c02, f64 c03,
f64 c10, f64 c11, f64 c12, f64 c13,
f64 c20, f64 c21, f64 c22, f64 c23,
f64 c30, f64 c31, f64 c32, f64 c33) {
return dm4(c00, c01, c02, c03,
c10, c11, c12, c13,
c20, c21, c22, c23,
c30, c31, c32, c33);
}
// supply all column vectors
dm4 dm4::columns (dv4 col0, dv4 col1, dv4 col2, dv4 col3) {
return dm4(col0[0], col1[0], col2[0], col3[0],
col0[1], col1[1], col2[1], col3[1],
col0[2], col1[2], col2[2], col3[2],
col0[3], col1[3], col2[3], col3[3]);
}
// supply all cells in column major order
dm4 dm4::columns (f64 c00, f64 c10, f64 c20, f64 c30,
f64 c01, f64 c11, f64 c21, f64 c31,
f64 c02, f64 c12, f64 c22, f64 c32,
f64 c03, f64 c13, f64 c23, f64 c33) {
return dm4(c00, c01, c02, c03,
c10, c11, c12, c13,
c20, c21, c22, c23,
c30, c31, c32, c33);
}
// Casting operators
// extend/truncate matrix of other size
dm4::operator dm2 () const {
return dm2(arr[0][0], arr[1][0],
arr[0][1], arr[1][1]);
}
// extend/truncate matrix of other size
dm4::operator dm3 () const {
return dm3(arr[0][0], arr[1][0], arr[2][0],
arr[0][1], arr[1][1], arr[2][1],
arr[0][2], arr[1][2], arr[2][2]);
}
// extend/truncate matrix of other size
dm4::operator dm2x3 () const {
return dm2x3(arr[0][0], arr[1][0], arr[2][0],
arr[0][1], arr[1][1], arr[2][1]);
}
// extend/truncate matrix of other size
dm4::operator dm3x4 () const {
return dm3x4(arr[0][0], arr[1][0], arr[2][0], arr[3][0],
arr[0][1], arr[1][1], arr[2][1], arr[3][1],
arr[0][2], arr[1][2], arr[2][2], arr[3][2]);
}
// typecast
dm4::operator fm4 () const {
return fm4((f32)arr[0][0], (f32)arr[0][1], (f32)arr[0][2], (f32)arr[0][3],
(f32)arr[1][0], (f32)arr[1][1], (f32)arr[1][2], (f32)arr[1][3],
(f32)arr[2][0], (f32)arr[2][1], (f32)arr[2][2], (f32)arr[2][3],
(f32)arr[3][0], (f32)arr[3][1], (f32)arr[3][2], (f32)arr[3][3]);
}
// Elementwise operators
dm4& dm4::operator+= (f64 r) {
*this = *this + r;
return *this;
}
dm4& dm4::operator-= (f64 r) {
*this = *this - r;
return *this;
}
dm4& dm4::operator*= (f64 r) {
*this = *this * r;
return *this;
}
dm4& dm4::operator/= (f64 r) {
*this = *this / r;
return *this;
}
// Matrix multiplication
dm4& dm4::operator*= (dm4 const& r) {
*this = *this * r;
return *this;
}
// Elementwise operators
dm4 operator+ (dm4 const& m) {
return dm4(+m.arr[0][0], +m.arr[1][0], +m.arr[2][0], +m.arr[3][0],
+m.arr[0][1], +m.arr[1][1], +m.arr[2][1], +m.arr[3][1],
+m.arr[0][2], +m.arr[1][2], +m.arr[2][2], +m.arr[3][2],
+m.arr[0][3], +m.arr[1][3], +m.arr[2][3], +m.arr[3][3]);
}
dm4 operator- (dm4 const& m) {
return dm4(-m.arr[0][0], -m.arr[1][0], -m.arr[2][0], -m.arr[3][0],
-m.arr[0][1], -m.arr[1][1], -m.arr[2][1], -m.arr[3][1],
-m.arr[0][2], -m.arr[1][2], -m.arr[2][2], -m.arr[3][2],
-m.arr[0][3], -m.arr[1][3], -m.arr[2][3], -m.arr[3][3]);
}
dm4 operator+ (dm4 const& l, dm4 const& r) {
return dm4(l.arr[0][0] + r.arr[0][0], l.arr[1][0] + r.arr[1][0], l.arr[2][0] + r.arr[2][0], l.arr[3][0] + r.arr[3][0],
l.arr[0][1] + r.arr[0][1], l.arr[1][1] + r.arr[1][1], l.arr[2][1] + r.arr[2][1], l.arr[3][1] + r.arr[3][1],
l.arr[0][2] + r.arr[0][2], l.arr[1][2] + r.arr[1][2], l.arr[2][2] + r.arr[2][2], l.arr[3][2] + r.arr[3][2],
l.arr[0][3] + r.arr[0][3], l.arr[1][3] + r.arr[1][3], l.arr[2][3] + r.arr[2][3], l.arr[3][3] + r.arr[3][3]);
}
dm4 operator+ (dm4 const& l, f64 r) {
return dm4(l.arr[0][0] + r, l.arr[1][0] + r, l.arr[2][0] + r, l.arr[3][0] + r,
l.arr[0][1] + r, l.arr[1][1] + r, l.arr[2][1] + r, l.arr[3][1] + r,
l.arr[0][2] + r, l.arr[1][2] + r, l.arr[2][2] + r, l.arr[3][2] + r,
l.arr[0][3] + r, l.arr[1][3] + r, l.arr[2][3] + r, l.arr[3][3] + r);
}
dm4 operator+ (f64 l, dm4 const& r) {
return dm4(l + r.arr[0][0], l + r.arr[1][0], l + r.arr[2][0], l + r.arr[3][0],
l + r.arr[0][1], l + r.arr[1][1], l + r.arr[2][1], l + r.arr[3][1],
l + r.arr[0][2], l + r.arr[1][2], l + r.arr[2][2], l + r.arr[3][2],
l + r.arr[0][3], l + r.arr[1][3], l + r.arr[2][3], l + r.arr[3][3]);
}
dm4 operator- (dm4 const& l, dm4 const& r) {
return dm4(l.arr[0][0] - r.arr[0][0], l.arr[1][0] - r.arr[1][0], l.arr[2][0] - r.arr[2][0], l.arr[3][0] - r.arr[3][0],
l.arr[0][1] - r.arr[0][1], l.arr[1][1] - r.arr[1][1], l.arr[2][1] - r.arr[2][1], l.arr[3][1] - r.arr[3][1],
l.arr[0][2] - r.arr[0][2], l.arr[1][2] - r.arr[1][2], l.arr[2][2] - r.arr[2][2], l.arr[3][2] - r.arr[3][2],
l.arr[0][3] - r.arr[0][3], l.arr[1][3] - r.arr[1][3], l.arr[2][3] - r.arr[2][3], l.arr[3][3] - r.arr[3][3]);
}
dm4 operator- (dm4 const& l, f64 r) {
return dm4(l.arr[0][0] - r, l.arr[1][0] - r, l.arr[2][0] - r, l.arr[3][0] - r,
l.arr[0][1] - r, l.arr[1][1] - r, l.arr[2][1] - r, l.arr[3][1] - r,
l.arr[0][2] - r, l.arr[1][2] - r, l.arr[2][2] - r, l.arr[3][2] - r,
l.arr[0][3] - r, l.arr[1][3] - r, l.arr[2][3] - r, l.arr[3][3] - r);
}
dm4 operator- (f64 l, dm4 const& r) {
return dm4(l - r.arr[0][0], l - r.arr[1][0], l - r.arr[2][0], l - r.arr[3][0],
l - r.arr[0][1], l - r.arr[1][1], l - r.arr[2][1], l - r.arr[3][1],
l - r.arr[0][2], l - r.arr[1][2], l - r.arr[2][2], l - r.arr[3][2],
l - r.arr[0][3], l - r.arr[1][3], l - r.arr[2][3], l - r.arr[3][3]);
}
dm4 mul_elementwise (dm4 const& l, dm4 const& r) {
return dm4(l.arr[0][0] * r.arr[0][0], l.arr[1][0] * r.arr[1][0], l.arr[2][0] * r.arr[2][0], l.arr[3][0] * r.arr[3][0],
l.arr[0][1] * r.arr[0][1], l.arr[1][1] * r.arr[1][1], l.arr[2][1] * r.arr[2][1], l.arr[3][1] * r.arr[3][1],
l.arr[0][2] * r.arr[0][2], l.arr[1][2] * r.arr[1][2], l.arr[2][2] * r.arr[2][2], l.arr[3][2] * r.arr[3][2],
l.arr[0][3] * r.arr[0][3], l.arr[1][3] * r.arr[1][3], l.arr[2][3] * r.arr[2][3], l.arr[3][3] * r.arr[3][3]);
}
dm4 operator* (dm4 const& l, f64 r) {
return dm4(l.arr[0][0] * r, l.arr[1][0] * r, l.arr[2][0] * r, l.arr[3][0] * r,
l.arr[0][1] * r, l.arr[1][1] * r, l.arr[2][1] * r, l.arr[3][1] * r,
l.arr[0][2] * r, l.arr[1][2] * r, l.arr[2][2] * r, l.arr[3][2] * r,
l.arr[0][3] * r, l.arr[1][3] * r, l.arr[2][3] * r, l.arr[3][3] * r);
}
dm4 operator* (f64 l, dm4 const& r) {
return dm4(l * r.arr[0][0], l * r.arr[1][0], l * r.arr[2][0], l * r.arr[3][0],
l * r.arr[0][1], l * r.arr[1][1], l * r.arr[2][1], l * r.arr[3][1],
l * r.arr[0][2], l * r.arr[1][2], l * r.arr[2][2], l * r.arr[3][2],
l * r.arr[0][3], l * r.arr[1][3], l * r.arr[2][3], l * r.arr[3][3]);
}
dm4 div_elementwise (dm4 const& l, dm4 const& r) {
return dm4(l.arr[0][0] / r.arr[0][0], l.arr[1][0] / r.arr[1][0], l.arr[2][0] / r.arr[2][0], l.arr[3][0] / r.arr[3][0],
l.arr[0][1] / r.arr[0][1], l.arr[1][1] / r.arr[1][1], l.arr[2][1] / r.arr[2][1], l.arr[3][1] / r.arr[3][1],
l.arr[0][2] / r.arr[0][2], l.arr[1][2] / r.arr[1][2], l.arr[2][2] / r.arr[2][2], l.arr[3][2] / r.arr[3][2],
l.arr[0][3] / r.arr[0][3], l.arr[1][3] / r.arr[1][3], l.arr[2][3] / r.arr[2][3], l.arr[3][3] / r.arr[3][3]);
}
dm4 operator/ (dm4 const& l, f64 r) {
return dm4(l.arr[0][0] / r, l.arr[1][0] / r, l.arr[2][0] / r, l.arr[3][0] / r,
l.arr[0][1] / r, l.arr[1][1] / r, l.arr[2][1] / r, l.arr[3][1] / r,
l.arr[0][2] / r, l.arr[1][2] / r, l.arr[2][2] / r, l.arr[3][2] / r,
l.arr[0][3] / r, l.arr[1][3] / r, l.arr[2][3] / r, l.arr[3][3] / r);
}
dm4 operator/ (f64 l, dm4 const& r) {
return dm4(l / r.arr[0][0], l / r.arr[1][0], l / r.arr[2][0], l / r.arr[3][0],
l / r.arr[0][1], l / r.arr[1][1], l / r.arr[2][1], l / r.arr[3][1],
l / r.arr[0][2], l / r.arr[1][2], l / r.arr[2][2], l / r.arr[3][2],
l / r.arr[0][3], l / r.arr[1][3], l / r.arr[2][3], l / r.arr[3][3]);
}
// Matrix ops
dm4 operator* (dm4 const& l, dm4 const& r) {
dm4 ret;
ret.arr[0] = l * r.arr[0];
ret.arr[1] = l * r.arr[1];
ret.arr[2] = l * r.arr[2];
ret.arr[3] = l * r.arr[3];
return ret;
}
dv4 operator* (dm4 const& l, dv4 r) {
dv4 ret;
ret.x = l.arr[0].x * r.x + l.arr[1].x * r.y + l.arr[2].x * r.z + l.arr[3].x * r.w;
ret.y = l.arr[0].y * r.x + l.arr[1].y * r.y + l.arr[2].y * r.z + l.arr[3].y * r.w;
ret.z = l.arr[0].z * r.x + l.arr[1].z * r.y + l.arr[2].z * r.z + l.arr[3].z * r.w;
ret.w = l.arr[0].w * r.x + l.arr[1].w * r.y + l.arr[2].w * r.z + l.arr[3].w * r.w;
return ret;
}
dv4 operator* (dv4 l, dm4 const& r) {
dv4 ret;
ret.x = l.x * r.arr[0].x + l.y * r.arr[0].y + l.z * r.arr[0].z + l.w * r.arr[0].w;
ret.y = l.x * r.arr[1].x + l.y * r.arr[1].y + l.z * r.arr[1].z + l.w * r.arr[1].w;
ret.z = l.x * r.arr[2].x + l.y * r.arr[2].y + l.z * r.arr[2].z + l.w * r.arr[2].w;
ret.w = l.x * r.arr[3].x + l.y * r.arr[3].y + l.z * r.arr[3].z + l.w * r.arr[3].w;
return ret;
}
dm4 transpose (dm4 const& m) {
return dm4::rows(m.arr[0], m.arr[1], m.arr[2], m.arr[3]);
}
#define LETTERIFY \
f64 a = mat.arr[0][0]; \
f64 b = mat.arr[0][1]; \
f64 c = mat.arr[0][2]; \
f64 d = mat.arr[0][3]; \
f64 e = mat.arr[1][0]; \
f64 f = mat.arr[1][1]; \
f64 g = mat.arr[1][2]; \
f64 h = mat.arr[1][3]; \
f64 i = mat.arr[2][0]; \
f64 j = mat.arr[2][1]; \
f64 k = mat.arr[2][2]; \
f64 l = mat.arr[2][3]; \
f64 m = mat.arr[3][0]; \
f64 n = mat.arr[3][1]; \
f64 o = mat.arr[3][2]; \
f64 p = mat.arr[3][3];
f64 det (dm4 const& mat) {
// optimized from: // 40 muls, 28 adds, 0 divs = 68 ops
// to: // 40 muls, 28 adds, 0 divs = 68 ops
LETTERIFY
return +a*(+f*(k*p - l*o) -g*(j*p - l*n) +h*(j*o - k*n))
-b*(+e*(k*p - l*o) -g*(i*p - l*m) +h*(i*o - k*m))
+c*(+e*(j*p - l*n) -f*(i*p - l*m) +h*(i*n - j*m))
-d*(+e*(j*o - k*n) -f*(i*o - k*m) +g*(i*n - j*m));
}
dm4 inverse (dm4 const& mat) {
// optimized from: // 200 muls, 125 adds, 1 divs = 326 ops
// to: // 116 muls, 83 adds, 1 divs = 200 ops
LETTERIFY
f64 in = i * n;
f64 gi = g * i;
f64 io = i * o;
f64 ej = e * j;
f64 ep = e * p;
f64 ho = h * o;
f64 jo = j * o;
f64 hn = h * n;
f64 fo = f * o;
f64 lm = l * m;
f64 gl = g * l;
f64 fl = f * l;
f64 kp = k * p;
f64 hj = h * j;
f64 fm = f * m;
f64 fp = f * p;
f64 hk = h * k;
f64 hm = h * m;
f64 jp = j * p;
f64 fk = f * k;
f64 kn = k * n;
f64 en = e * n;
f64 jm = j * m;
f64 gn = g * n;
f64 eo = e * o;
f64 ip = i * p;
f64 el = e * l;
f64 gm = g * m;
f64 gp = g * p;
f64 lo = l * o;
f64 hi = h * i;
f64 ln = l * n;
f64 gj = g * j;
f64 fi = f * i;
f64 ek = e * k;
f64 km = k * m;
f64 gpho = gp - ho;
f64 jpln = jp - ln;
f64 enfm = en - fm;
f64 flhj = fl - hj;
f64 elhi = el - hi;
f64 fkgj = fk - gj;
f64 iplm = ip - lm;
f64 kplo = kp - lo;
f64 injm = in - jm;
f64 fogn = fo - gn;
f64 ekgi = ek - gi;
f64 iokm = io - km;
f64 glhk = gl - hk;
f64 fphn = fp - hn;
f64 eogm = eo - gm;
f64 ejfi = ej - fi;
f64 ephm = ep - hm;
f64 jokn = jo - kn;
f64 det;
{ // clac determinate
det = +a*(+f*(kplo) -g*(jpln) +h*(jokn))
-b*(+e*(kplo) -g*(iplm) +h*(iokm))
+c*(+e*(jpln) -f*(iplm) +h*(injm))
-d*(+e*(jokn) -f*(iokm) +g*(injm));
}
f64 inv_det = f64(1) / det;
f64 ninv_det = -inv_det;
// calc cofactor matrix
f64 cofac_00 = +f*(kplo) -g*(jpln) +h*(jokn);
f64 cofac_01 = +e*(kplo) -g*(iplm) +h*(iokm);
f64 cofac_02 = +e*(jpln) -f*(iplm) +h*(injm);
f64 cofac_03 = +e*(jokn) -f*(iokm) +g*(injm);
f64 cofac_10 = +b*(kplo) -c*(jpln) +d*(jokn);
f64 cofac_11 = +a*(kplo) -c*(iplm) +d*(iokm);
f64 cofac_12 = +a*(jpln) -b*(iplm) +d*(injm);
f64 cofac_13 = +a*(jokn) -b*(iokm) +c*(injm);
f64 cofac_20 = +b*(gpho) -c*(fphn) +d*(fogn);
f64 cofac_21 = +a*(gpho) -c*(ephm) +d*(eogm);
f64 cofac_22 = +a*(fphn) -b*(ephm) +d*(enfm);
f64 cofac_23 = +a*(fogn) -b*(eogm) +c*(enfm);
f64 cofac_30 = +b*(glhk) -c*(flhj) +d*(fkgj);
f64 cofac_31 = +a*(glhk) -c*(elhi) +d*(ekgi);
f64 cofac_32 = +a*(flhj) -b*(elhi) +d*(ejfi);
f64 cofac_33 = +a*(fkgj) -b*(ekgi) +c*(ejfi);
dm4 ret;
ret.arr[0][0] = cofac_00 * inv_det;
ret.arr[0][1] = cofac_10 * ninv_det;
ret.arr[0][2] = cofac_20 * inv_det;
ret.arr[0][3] = cofac_30 * ninv_det;
ret.arr[1][0] = cofac_01 * ninv_det;
ret.arr[1][1] = cofac_11 * inv_det;
ret.arr[1][2] = cofac_21 * ninv_det;
ret.arr[1][3] = cofac_31 * inv_det;
ret.arr[2][0] = cofac_02 * inv_det;
ret.arr[2][1] = cofac_12 * ninv_det;
ret.arr[2][2] = cofac_22 * inv_det;
ret.arr[2][3] = cofac_32 * ninv_det;
ret.arr[3][0] = cofac_03 * ninv_det;
ret.arr[3][1] = cofac_13 * inv_det;
ret.arr[3][2] = cofac_23 * ninv_det;
ret.arr[3][3] = cofac_33 * inv_det;
return ret;
}
#undef LETTERIFY
} // namespace vector
| true |
df1953259557ade4d0f75ba93605b6d7365447c2 | C++ | francisco-ruiz/UD2 | /U2-22.cpp | UTF-8 | 569 | 3.359375 | 3 | [] | no_license | // Ejercicio Línea 22. For: Ejemplo Satélite
#include <iostream>
using namespace std;
int main (){
double recepcion = 0; double total = 0.0; int repeticiones = 0;
for (int repeticiones = 1; (recepcion >= 0 && repeticiones <= 20); repeticiones++){
cout << "Esperando recepción de datos: ";
cin >> recepcion;
total = total + recepcion;
cout << "Dato recibido número " << repeticiones << ": " << recepcion << endl;
cout << "El valor de medio de los datos recibidos es: " << total/repeticiones << endl;
}
cout << "Fin de la transmisión" << endl;
}
| true |
15f04ba1b776ba414def7ee55ec3d7f197dba5dc | C++ | thirtiseven/CF | /Kick Start 2022 C/A.cc | UTF-8 | 834 | 2.84375 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <string>
int T, n;
std::string s;
int main(int argc, char *argv[]) {
std::ios::sync_with_stdio(false);
std::cin.tie(0);
std::cin >> T;
for (int cas = 1; cas <= T; cas++) {
std::cin >> n;
std::cin >> s;
bool a = 0, b = 0, c = 0, d = 0;
for (int i = 0; i < n; i++) {
if (s[i] <= 'z' && s[i] >= 'a') {
a = 1;
}
if (s[i] <= 'Z' && s[i] >= 'A') {
b = 1;
}
if (s[i] <= '9' && s[i] >= '0') {
c = 1;
}
if (s[i] == '#' || s[i] == '@' || s[i] == '*' || s[i] == '&') {
d = 1;
}
}
if (a == 0) {
s.append("a");
}
if (b == 0) {
s.append("A");
}
if (c == 0) {
s.append("0");
}
if (d == 0) {
s.append("&");
}
while (s.length() < 7) {
s.append("a");
}
std::cout << "Case #" << cas << ": " << s << '\n';
}
} | true |
6448dc9e0d7c3133253d7d9d4f616c36f733ff8b | C++ | missingjs/mustard | /dsb/3/4/11.sample.cpp | UTF-8 | 910 | 3.3125 | 3 | [] | no_license | #include <cstddef>
#include <cstdlib>
#include <iostream>
int solution_count = 0;
void pq(int * cols, int n, int k)
{
if (k == n) {
++solution_count;
std::cout << '[' << solution_count << "] ";
for (int i = 0; i < n; ++i) {
std::cout << '(' << i << ',' << cols[i] << ") ";
}
std::cout << '\n';
return;
}
for (int i = 0; i < n; ++i) {
int row = k, col = i;
int j = 0;
for (; j < k; ++j) {
int r = j, c = cols[j];
if (col == c) {
break;
} else if (abs(row-r) == abs(col-c)) {
break;
}
}
if (j == k) {
cols[k] = i;
pq(cols, n, k + 1);
}
}
}
void print_queens(int n)
{
if (n <= 0) {
return;
}
int * cols = new int[n];
pq(cols, n, 0);
delete[] cols;
}
| true |
3ab25562d2b0d30551091dd8c099e4f8d901930f | C++ | foreverever/baekjoon | /baekjoon/프로그래머스_영어 끝말잇기.cpp | UTF-8 | 569 | 2.953125 | 3 | [] | no_license | #include <string>
#include <vector>
#include <iostream>
#include <unordered_map>
using namespace std;
unordered_map<string, bool> m;
vector<int> solution(int n, vector<string> words) {
vector<int> answer;
m[words[0]] = true;
int person = 0;
int order = 0;
for (int i = 0; i < words.size() - 1; i++) {
if (words[i].back() == words[i + 1].front() && !m.count(words[i + 1])) {
m[words[i + 1]] = true;
continue;
}
person = (i + 1) % n + 1;
order = (i + 1) / n + 1;
break;
}
answer.push_back(person);
answer.push_back(order);
return answer;
} | true |
8be6714d2e5ad001cd79e45657edf50652c6ec5d | C++ | newhandfun/NTNU_PatternRecognition_Kmeans | /include/Image.h | UTF-8 | 1,051 | 3.140625 | 3 | [] | no_license | #ifndef IMAGE_H
#define IMAGE_H
/*Color part of pixel*/
enum Color{
red = 0,green,blue
};
class Image
{
public:
Image();
virtual ~Image();
/* load image by name*/
virtual void loadImage(char* name)=0;
virtual char* getFileName()=0;
/* function that deal with pixel */
virtual unsigned int getPixel(int x,int y,Color col)=0;
virtual unsigned int setPixel(int x,int y,Color col)=0;
virtual unsigned int getGrayPixel(int x,int y)=0;
/* save img by 2 dimention array ,return result */
virtual bool saveIMG(unsigned int** img_data,unsigned int xSize,unsigned int ySize)=0;
/* get size of picture*/
virtual unsigned int getWidth()=0;
virtual unsigned int getHeight()=0;
/* get pixel array*/
virtual void getPixelColorArray(int*** r,int*** g,int*** b)=0;
virtual void getPixelGrayArray(int*** arr)=0;
virtual void deleteArray(int ***ptr_array)=0;
protected:
private:
};
#endif // IIMAGE_H
| true |
b431a4a97f4038fc2087e32060cb69f19975f83e | C++ | researcherben/course-notes | /introduction_to_C++_programming/labfiles_from_zip/examples/3/3-19.cpp | UTF-8 | 424 | 3.578125 | 4 | [] | no_license | //
// 3-19.cpp
//
#include <iostream>
struct Fraction
{
int n, d;
Fraction mult(const Fraction & param)
{
Fraction temp;
temp.n = param.n * n;
temp.d = param.d * d;
return temp;
}
void print()
{
std::cout << n << "/" << d << "\n";
}
};
int main()
{
Fraction a, b, c;
a.n = 1;
a.d = 3;
b.n = 2;
b.d = 5;
c = a.mult(b);
a.print();
b.print();
c.print();
return 0;
}
| true |
909419cac15247871f3ba4049b570d2edf9797a9 | C++ | fsps60312/old-C-code | /C++ code/NTU Online Judge/2629.cpp | UTF-8 | 439 | 2.65625 | 3 | [] | no_license | #include<cstdio>
#include<cassert>
using namespace std;
int N;
int Get(const int v)
{
return (new int[10]{6,2,5,5,4,5,6,3,7,6})[v];
}
int main()
{
//freopen("alarm.in","r",stdin);
//freopen("alarm.out","w",stdout);
while(scanf("%d",&N)==1)
{
for(int h=0;h<24;h++)for(int m=0;m<60;m++)if(Get(h/10)+Get(h%10)+Get(m/10)+Get(m%10)==N)
{
printf("%02d:%02d\n",h,m);
goto index;
}
puts("Impossible");
index:;
}
return 0;
}
| true |
5b869a61f17625f38cfcab17ce45080caf34d91a | C++ | ClockWorkKid/Hexapod-Robot | /Spider_PVC/Code/servo_driver_test/servo_driver_test.ino | UTF-8 | 1,817 | 2.84375 | 3 | [] | no_license | #include <Wire.h>
#include <Adafruit_PWMServoDriver.h>
Adafruit_PWMServoDriver l_limbs = Adafruit_PWMServoDriver(0x41);
Adafruit_PWMServoDriver r_limbs = Adafruit_PWMServoDriver(0x40);
#define SERVOMIN 150 // 'minimum' pulse length count (of 4096)
#define SERVOMAX 600 // 'maximum' pulse length count (of 4096)
#define waist 1
#define knee 2
#define ankle 3
float angle = 50.0;
float angle1;
float angle2;
uint8_t servoNum = 0;
int servo_step = 10;
void setup() {
l_limbs.begin();
r_limbs.begin();
l_limbs.setPWMFreq(50); // Servos run at ~60 Hz
r_limbs.setPWMFreq(50);
for (int limb = 1; limb <= 3; limb++){
for (int joint = 1; joint <= 3; joint++){
servo_write('l', limb, joint, angle);
servo_write('r', limb, joint, angle);
}
}
Serial.begin(9600);
delay(1000);
angle1 = angle;
angle2 = angle;
}
void loop() {
for (int i = 0; i < 50; i++) {
angle1+=0.5;
angle2-=0.5;
for (int limb = 1; limb <= 3; limb++) {
for (int joint = 2; joint <= 3; joint++) {
servo_write('l', limb, joint, angle1);
servo_write('r', limb, joint, angle2);
}
}
delay(servo_step);
}
delay(500);
for (int i = 0; i < 50; i++) {
angle1-=0.5;
angle2+=0.5;
for (int limb = 1; limb <= 3; limb++) {
for (int joint = 2; joint <= 3; joint++) {
servo_write('l', limb, joint, angle1);
servo_write('r', limb, joint, angle2);
}
}
delay(servo_step);
}
delay(500);
}
void servo_write(char limb_side, uint8_t limb_no, uint8_t joint_no, float degree) {
servoNum = limb_no * 4 + joint_no ;
if (limb_side == 'l')
l_limbs.setPWM(servoNum, 0, map(degree, 0, 180, SERVOMIN, SERVOMAX));
else if (limb_side == 'r')
r_limbs.setPWM(servoNum, 0, map(degree, 0, 180, SERVOMIN, SERVOMAX));
}
| true |
26ccf04cdd8aa0d625862f349dabe1040081e5de | C++ | fabr1z10/glib3 | /include/monkey/multitexmesh.h | UTF-8 | 1,780 | 2.890625 | 3 | [] | no_license | #pragma once
#include <monkey/mesh.h>
#include <monkey/engine.h>
#include <monkey/math/earcut.h>
struct Texture {
unsigned int id;
std::string type;
std::string path;
};
template <typename T>
class MultiTexMesh : public Mesh<T> {
public:
MultiTexMesh() = default;
MultiTexMesh(ShaderType type, GLenum prim, const std::vector<Texture>& textures) : Mesh<T>(type), m_textures(textures) {
this->m_primitive = prim;
}
void Setup(Shader* shader) override {
unsigned int diffuseNr = 1;
unsigned int specularNr = 1;
unsigned int normalNr = 1;
unsigned int heightNr = 1;
for(unsigned int i = 0; i < m_textures.size(); i++)
{
glActiveTexture(GL_TEXTURE0 + i); // active proper texture unit before binding
// retrieve texture number (the N in diffuse_textureN)
std::string number;
std::string name = m_textures[i].type;
if(name == "texture_diffuse")
number = std::to_string(diffuseNr++);
else if(name == "texture_specular")
number = std::to_string(specularNr++); // transfer unsigned int to stream
else if(name == "texture_normal")
number = std::to_string(normalNr++); // transfer unsigned int to stream
else if(name == "texture_height")
number = std::to_string(heightNr++); // transfer unsigned int to stream
// now set the sampler to the correct texture unit
glUniform1i(glGetUniformLocation(shader->getProgId(), (name + number).c_str()), i);
// and finally bind the texture
glBindTexture(GL_TEXTURE_2D, m_textures[i].id);
}
}
private:
std::vector<Texture> m_textures;
};
| true |
1ce6fa24a49a66df3afb696cbac8e751e43549bf | C++ | LGPhappy/aim_modules | /DatasetModule/inc/DatasetModuleExt.h | UTF-8 | 1,207 | 2.515625 | 3 | [] | no_license | /**
* @file DatasetModuleExt.h
* @brief DatasetModule extension
*
* This file is created at "Distributed Organisms B.V.". It is open-source software and part of "Robotic Suite".
* This software is published under the GNU General Lesser Public license (LGPLv3).
*
* Copyright © 2014 Anne C. van Rossum <anne@dobots.nl>
*
* @author Anne C. van Rossum
* @date Mar 19, 2014
* @organisation Distributed Organisms B.V.
* @project Robotic Suite
*/
#include <DatasetModule.h>
namespace rur {
/**
* Your Description of this module.
*/
class DatasetModuleExt: public DatasetModule {
public:
//! The constructor
DatasetModuleExt();
//! The destructor
virtual ~DatasetModuleExt();
//! The tick function is the "heart" of your module, it reads and writes to the ports
void Tick();
//! As soon as Stop() returns "true", the DatasetModuleMain will stop the module
bool Stop();
//! First. Tick() will call Train() for a few times
void Train();
//! Second. Tick() will call Test() once
void Test();
//! Third. CheckResult is called, now Test() can be called again if you'd like...
void CheckResult();
private:
int test_index, train_index;
};
}
| true |
5b6ebfbdf99972e9a495b59dc670489b4393bf89 | C++ | lukmccall/UJ | /P/P1/CW/3/eliminacja_liter.cpp | UTF-8 | 737 | 3.015625 | 3 | [] | no_license | // Eliminacja znaku
#include <iostream>
using namespace std;
int main(){
char s[ 100 ]; // tablica wejsciowa
for( int i = 0; i < 100; i++ ) // czyszczenie tablicy
s[ i ] = 0;
char c; // znak do usuniecia
bool find = false; // flaga oznaczajace ze dany element zostal juz przesuniety
cin >> s >> c;
for( int i = 0; i < 100; i++ ) // zastepowanie znaku c 0
if( s[ i ] == c )
s[ i ] = 0;
for( int i = 0; i < 100; i++ ) // iteracja przez tablice wejsciowa
if( s[ i ] == 0 ){ // szykanie 0 w ciagu
find = false;
for( int j = i + 1; j < 100; j++ ) // zamienianie elementow miejscami
if( s[ j ] != 0 && !find ){
s[ i ] = s[ j ];
s[ j ] = 0;
find = true;
}
}
cout << s;
return 0;
}
| true |
55fd80b0ffc48968093b26a49a6ef8484add7b04 | C++ | wangxl12/DataStructure_Algorithms | /排序/直接插入/无哨兵/无哨兵.cpp | GB18030 | 689 | 3.71875 | 4 | [] | no_license | #include<iostream>
using namespace std;
void sort(int array[], int n){
for(int i=1;i<n;i++){
int temp = array[i];
int j = i-1;
for(;array[j]>temp;j--){ // ڱڱ
// ڱҪжj0ĴСҪ֤0Ҳƶ
if(j<0) break;
array[j+1] = array[j];
}
// жjС0˵ȫtempڵ0˵Ѿҵλ
if(j>=0) array[j+1] = temp;
// j<0û룬
else array[0] = temp;
}
}
int main(){
int N = 10;
int array[N] = {4, 3, 6, 8, 4, 5, 1, 2, 9, 6};
sort(array, N);
for(int i=0;i<N;i++){
cout << array[i];
}
cout << endl;
return 0;
}
| true |
d74d4f7c57882186f9591f7ef01d4311bdf33da1 | C++ | KennyWGH/LIV-SLAM | /LidarOdom/src/ImuTracker.h | UTF-8 | 4,847 | 2.78125 | 3 | [] | no_license | /**
* @warning: 所使用的imu必须是右手系类型!!
* @author: wgh--
* @description: 追踪imu坐标系的姿态角,通过角速度积分做预测,再用重力方向做矫正。
* @dependencies: C++, Eigen, C++11::std::chrono, C++11::std::ratio
* 类模板 std::ratio 及相关的模板提供编译时有理数算术支持
* @caller: called by who? --class PoseTracker, or whoever needs to track imu_frame pose
*/
#ifndef IMU_TRACKER_H_
#define IMU_TRACKER_H_
// C++
#include<deque>
#include<string>
// Eigen
//
// 自定义
#include"liv_time.h"
#include"liv_utils.h"
using namespace std;
// wgh-- 解释:假设机器人缓慢移动,则整体来看,加速度测量的均值就是重力加速度。
// wgh-- 解释:重力加速度可以用于矫正roll和pitch的漂移!
// wgh-- 重点:仅用于估算orientation!
// Keeps track of the orientation using angular velocities and linear
// accelerations from an IMU. Because averaged linear acceleration (assuming
// slow movement) is a direct measurement of gravity, roll/pitch does not drift,
// though yaw does.
class ImuTracker {
public:
explicit ImuTracker(double imu_gravity_time_constant);
ImuTracker();
~ImuTracker();
// Interfaces
void addImu(ImuData imu_data);
Eigen::Vector3d getGravity(const common::Time& t_query);
Eigen::Quaterniond getOrientation(const common::Time& t_query);
// 用于外层旋转去畸变
bool setStartTime(const common::Time& t_start);
Eigen::Quaterniond getDeltaOrientationSinceStart(const common::Time& t_query);
Eigen::Quaterniond getDeltaOrientationSinceTime(common::Time t_start);
Eigen::Quaterniond getDeltaOrientation(common::Time t_start, common::Time t_end);
Eigen::Quaterniond getDeltaOrientationPureRot(common::Time t_start, common::Time t_end);
// Query the current time, and the current estimate of orientation and position.
common::Time time() const { return processed_time_; }
Eigen::Quaterniond orientation() const { return orientation_; }
Eigen::Vector3d position() const { return position_; }
Eigen::Quaterniond orientationWithoutG() const { return orient_WithoutG_; }
Eigen::Vector3d gravity() const { return gravity_vector_; }
private:
// wgh-- 用imu的角速度值做积分,预测新时刻的姿态(世界坐标系)以及重力方向(imu坐标系)
// wgh-- 用imu的重力方向观测(线加速度),来矫正姿态预测
void predictOrientation(const Eigen::Vector3d& angular_velocity);
void correctOrientationWithGravity(const Eigen::Vector3d& linear_accel);
// Returns a quaternion representing the same rotation
// as the given 'angle_axis' vector.
// This is typical used for angular velocity integration.
Eigen::Quaterniond AngleAxisVectorToRotationQuaternion(
const Eigen::Matrix<double, 3, 1>& angle_axis);
void trimQueue();
inline bool validateData(const ImuData& input_data){
if (input_data.time==common::Time::min()
|| input_data.linear_acceleration==Eigen::Vector3d::Zero()
|| input_data.angular_velocity==Eigen::Vector3d::Zero())
{ return false; }
return true;
}
// static parameters
const double IMU_GRAVITY_TIME_CONST; // wgh-- 一阶指数滤波参数,平滑更新重力加速度;
/* Cartographer默认该参数为10.0 */ // wgh-- 该常数越小,新观测的影响来的就越快。
const double GRAVITY_CONST; // wgh-- 重力常量
double QUEUE_DURATION = 5.0;
double IMU_FREQUENCY = 167.0;
// containers
std::deque<ImuData> imu_queue_; // wgh-- queue for unprocessed imu data
std::deque<TimedGravity> gravity_queue_;
std::deque<TimedOrient> ort_queue_;
std::deque<TimedOrient> ort_WithoutG_queue_;
// important variables
Eigen::Quaterniond orientation_; // wgh-- 核心变量!
Eigen::Quaterniond orient_WithoutG_;
Eigen::Vector3d gravity_vector_; // wgh-- 核心变量!
Eigen::Vector3d last_angular_velocity_;
Eigen::Vector3d last_linear_accel_corrected_;
// run-time variables
size_t num_received_imu = 0; // wgh-- imu data帧计数
common::Time curr_time_; // wgh-- 实时传入的数据的时间戳
common::Time processed_time_; // wgh-- 当前最新已处理数据的时间
common::Time time_query_start;
size_t index_query_start = 0;
Eigen::Quaterniond orientation_query_start;
// 加速度->速度->位置积分(中值积分法)
bool extrapolate_position_ = false;
Eigen::Vector3d position_ = Eigen::Vector3d::Zero(); // wgh-- 根据传感器数据实时更新
};
#endif // IMU_TRACKER_H_
| true |
e54663df52cb24a3ef5ed19c9756ce86d7b33caf | C++ | mariosal/algo | /coci/2012_2013/1/dom.cc | UTF-8 | 350 | 3 | 3 | [
"ISC"
] | permissive | #include <cstdio>
bool contain( const char *s, char c ) {
char i;
for ( i = 0; s[ i ]; ++i ) {
if ( c == s[ i ] ) {
return true;
}
}
return false;
}
int main() {
const char *s = "CAMBRDIGE";
char i, c;
while ( scanf( "%c", &c ) != EOF ) {
if ( !contain( s, c ) ) {
printf( "%c", c );
}
}
return 0;
}
| true |
9a5baf7d9d5fe6f0f566fdbbdde72a1700dedef9 | C++ | Secondtonumb/OOP_object_oriented_programming | /code/cap4/4_5.cpp | UTF-8 | 405 | 3.265625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(){
static char text[] = {'h', 'e', 'l', 'l', 'o'};
char buff[5];
int i, flag;
for(i = 0; i < 5; i++){
cin >> buff[i];
}
flag = 0;
for(i = 0; i < 5; i++){
if(buff[i] != text[i]){
flag = 1;
break;
}
}
if(flag)
cout << "The string is not Hello " << endl;
else
cout << "The string is Hello " << endl;
}
| true |
27ec8d69892986b3379702300df443c5d88a95b6 | C++ | longo-andrea/QBar | /Modello/Gerarchia/panino.h | UTF-8 | 1,294 | 2.765625 | 3 | [] | no_license | #ifndef PANINO_H
#define PANINO_H
#include "cibo.h"
#include <iostream>
class Panino : public Cibo {
public:
enum Pane { Tartaruga, Arabo, Baguette, Integrale };
private:
class inizializzaPanino{
private:
Panino* ptr;
public:
inizializzaPanino();
~inizializzaPanino();
};
static inizializzaPanino mappaPanino;
static double tassa;
double prezzoPreparazione;
std::string barCode;
Pane pane;
Panino* create(Json::Value&) const override;
public:
Panino(const std::string& ="No Name", double =0, double =0, double =0, double =0, bool =false, const std::string& ="No Bar Code", Pane =Pane::Tartaruga, int = 2020, int = 14);
Panino(const Panino&);
virtual Panino* clone() const override;
virtual ~Panino() = default;
double getPrezzoPreparazione() const override;
std::string getBarCode() const override;
double getPrezzo() const override;
std::string getTipo() const override;
Pane getPane() const;
std::string paneToString() const;
void setPrezzoPreparazione(const double&);
void setBarCode(const std::string&);
void setPane(Pane);
void serialize(Json::Value&) const override;
virtual bool operator==(const Panino&) const;
virtual bool operator!=(const Panino&) const;
static Pane stringToPane(const std::string&);
};
#endif // PANINO_H
| true |
3ccb71f269e0075f1d8248d0d88eb82ee3863e93 | C++ | pinak93/DragonballzGame | /explodingprojectile.cpp | UTF-8 | 577 | 2.5625 | 3 | [] | no_license | #include <iostream>
#include <cmath>
#include "explodingprojectile.h"
ExplodingProjectile::~ExplodingProjectile() {
}
void ExplodingProjectile::draw() const {
Main[currentFrame]->draw(getX(), getY(), getScale());
}
void ExplodingProjectile::advanceFrame(Uint32 ticks) {
timeSinceLastFrame += ticks;
if (timeSinceLastFrame > frameInterval) {
currentFrame = (currentFrame+1) % numberOfFrames;
timeSinceLastFrame = 0;
}
}
void ExplodingProjectile::update(Uint32 ticks) {
advanceFrame(ticks);
if(numberOfFrames-1==currentFrame)
{
DoneExploding=true;
}
} | true |
5d7c8942d92324b60233445d812fccc438d88a16 | C++ | wzj1988tv/code-imitator | /data/dataset_2017/dataset_2017_8_formatted_macrosremoved/splucs/8294486_5654117850546176_splucs.cpp | UTF-8 | 2,971 | 2.734375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int T, N, R, O, Y, G, B, V, caseNo;
bool specialcase() {
if (G == R && G > 0) {
printf("Case #%d: ", caseNo);
if (G + R == N) {
for (int i = 0; i < R; i++)
printf("RG");
printf("\n");
} else
printf("IMPOSSIBLE\n");
return true;
}
if (G > R) {
printf("Case #%d: IMPOSSIBLE\n", caseNo);
return true;
}
if (Y == V && Y > 0) {
printf("Case #%d: ", caseNo);
if (V + Y == N) {
for (int i = 0; i < Y; i++)
printf("YV");
printf("\n");
} else
printf("IMPOSSIBLE\n");
return true;
}
if (V > Y) {
printf("Case #%d: IMPOSSIBLE\n", caseNo);
return true;
}
if (O == B && O > 0) {
printf("Case #%d: ", caseNo);
if (O + B == N) {
for (int i = 0; i < B; i++)
printf("OB");
printf("\n");
} else
printf("IMPOSSIBLE\n");
return true;
}
if (O > B) {
printf("Case #%d: IMPOSSIBLE\n", caseNo);
return true;
}
return false;
}
char lastprinted;
void printred() {
if (G > 0) {
printf("RGR");
G--;
} else
printf("R");
R--;
lastprinted = 'r';
}
void printyellow() {
if (V > 0) {
printf("YVY");
V--;
} else
printf("Y");
Y--;
lastprinted = 'y';
}
void printblue() {
if (O > 0) {
printf("BOB");
O--;
} else
printf("B");
B--;
lastprinted = 'b';
}
int main() {
scanf("%d", &T);
for (caseNo = 1; caseNo <= T; caseNo++) {
scanf("%d %d %d %d %d %d %d", &N, &R, &O, &Y, &G, &B, &V);
if (specialcase())
continue;
R -= G;
Y -= V;
B -= O;
if (R > Y + B || Y > R + B || B > R + Y) {
printf("Case #%d: IMPOSSIBLE\n", caseNo);
continue;
}
lastprinted = 'a';
printf("Case #%d: ", caseNo);
if (R >= Y && R >= B) {
while (R > 0) {
printred();
if (Y > B)
printyellow();
else
printblue();
}
if (B > Y)
printblue();
while (B > 0) {
bool first = (lastprinted != 'b');
if (first)
printblue();
printyellow();
if (!first)
printblue();
}
} else if (B >= R && B >= Y) {
while (B > 0) {
printblue();
if (R > Y)
printred();
else
printyellow();
}
if (R > Y)
printred();
while (R > 0) {
bool first = (lastprinted != 'r');
if (first)
printred();
printyellow();
if (!first)
printred();
}
} else if (Y >= R && Y >= B) {
while (Y > 0) {
printyellow();
if (R > B)
printred();
else
printblue();
}
if (R > B)
printred();
while (R > 0) {
bool first = (lastprinted != 'r');
if (first)
printred();
printblue();
if (!first)
printred();
}
}
printf("\n");
}
return 0;
}
| true |
11279615322a48892561af385e0352c2f9dfb742 | C++ | bmatern/CompGraphicsFall2015 | /Hwk1a/CreateImage.cpp | UTF-8 | 17,280 | 3.734375 | 4 | [] | no_license | /*
* Ben Matern
* Homework 1a
* Getting started with raycasting
* Computer Graphics
*
* This program can create a ASCII Format image from an input file.
* I'm getting better at structuring c++
* Instincts tell me I should break up this file quite a bit.
* I'll have to figure out file includes for the next assignment.
* Main method is at the very bottom.
*
*/
#include <iostream>
#include <fstream>
#include <vector>
#include <math.h>
using namespace std;
//PointType can double as a vector too. It's just numbers. Let's be reasonable.
//It's not the same as a c++ vector. Or a virology vector. How confusing.
typedef struct
{
double x,y,z;
} PointType;
typedef struct
{
PointType origin;
PointType direction;
} RayType;
typedef struct
{
double r, g, b;
} ColorType;
typedef struct
{
PointType center;
double radius;
ColorType color;
} SphereType;
typedef struct
{
PointType topLeft;
PointType topRight;
PointType botLeft;
PointType botRight;
} ViewingWindowType;
double dotProduct(PointType firstVector, PointType secondVector)
{
//Calculate dot product of 2 vectors
//s = x1 x2 + y1 y2 + z1 z2
double results =
firstVector.x * secondVector.x +
firstVector.y * secondVector.y +
firstVector.z * secondVector.z;
return results;
}
PointType crossProduct(PointType firstVector, PointType secondVector)
{
//calculate cross product firstVector X secondVector
//u x v =
// (uy * vz - uz * vy
//, uz * vx - ux * vz
//, ux * vy - uy * vx)
PointType results;
results.x = (firstVector.y * secondVector.z) - (firstVector.z * secondVector.y);
results.y = (firstVector.z * secondVector.x) - (firstVector.x * secondVector.z);
results.z = (firstVector.x * secondVector.y) - (firstVector.y * secondVector.x);
return results;
}
PointType addVectors(PointType firstVector, PointType secondVector)
{
//respectively add the components of the two vectors.
PointType results;
results.x = firstVector.x + secondVector.x;
results.y = firstVector.y + secondVector.y;
results.z = firstVector.z + secondVector.z;
return results;
}
PointType subtractPoints(PointType firstPoint, PointType secondPoint)
{
//subtract the first from the second.
//This finds the vector from firstPoint -> secondPoint
PointType results;
results.x = secondPoint.x - firstPoint.x;
results.y = secondPoint.y - firstPoint.y;
results.z = secondPoint.z - firstPoint.z;
return results;
}
PointType multiplyVector(PointType inputVector, double scalar)
{
//Multiply a vector by a scalar
PointType results;
results.x = inputVector.x * scalar;
results.y = inputVector.y * scalar;
results.z = inputVector.z * scalar;
return results;
}
double vectorLength(PointType inputVector)
{
//calculate the length of a vector
//sqrt(x^2 + y^2 + z^2)
return sqrt(inputVector.x * inputVector.x
+ inputVector.y * inputVector.y
+ inputVector.z * inputVector.z);
}
PointType normalizeVector(PointType inputVector)
{
//normalize the vector to length 1.
double normalizeScalar = 1.0 / vectorLength(inputVector);
PointType results = multiplyVector(inputVector, normalizeScalar);
return results;
}
string trim(string str)
{
//trim whitespace from the beginning and end of a string.
//cout << "trimming:" << str <<"\n";
size_t first = str.find_first_not_of(' ');
size_t last = str.find_last_not_of(' ');
string result = str.substr(first, (last-first+1));
//cout << "result:" << result <<"\n";
return result;
}
vector<string> tokenizeString(string input)
{
//split a string by a space delimiter.
//returns a vector of token strings.
vector<string> tokens;
int spaceLocation;
string tokenBuffer = trim(input);
while(true)
{
//cout << "tokenizing this:" << tokenBuffer << "\n";
spaceLocation = tokenBuffer.find(" ");
if(spaceLocation < 1)
{
if(tokenBuffer.length() > 0)
{
//cout << "Last token:" << tokenBuffer << "\n";
tokens.push_back(tokenBuffer);
}
//cout << "End of tokens.\n";
break;
}
else
{
string token = tokenBuffer.substr(0, spaceLocation);
//cout << "Token found:" << token << "\n";
tokenBuffer = tokenBuffer.substr(spaceLocation + 1, tokenBuffer.length());
tokenBuffer = trim(tokenBuffer);
//cout << "new Buffer:" << tokenBuffer << "\n";
tokens.push_back(token);
}
}
return tokens;
}
string getInputFileName(int argc, char *argv[])
{
//Read commandline args to get input filename.
string inputFileName;
if ( argc == 2 )
{
//cout << "arg0:" << argv[0];
inputFileName = argv[1];
cout << "one argument found. Good. Filename = " << inputFileName << "\n";
}
else
{
cout << "You should have exactly one argument, the input file name. Using default filename instead.\n";
inputFileName = "example_input.txt";
}
return inputFileName;
}
void loadSceneInformation(string inputFileName, RayType& eyeRay, PointType& upVector, int& width, int& height, double& fovH
, ColorType& bgColor, ColorType& currentMaterialColor, vector<SphereType>& spheres)
{
//read input file to determine the components of the scene.
string line;
ifstream myInputfile (inputFileName);
if (myInputfile.is_open())
{
cout << "Input File Found. Good.\n";
while ( getline (myInputfile,line) )
{
//cout << "Line:" << line << "\n";
if(line.length() > 0)
{
vector<string> tokens = tokenizeString(line);
if(tokens.size() > 0)
{
//cout << tokens.size() << " tokens found.\n";
string inputVarName = tokens[0];
//cout << "Found:" << inputVarName << "\n";
if(inputVarName.compare("eye") == 0)
{
eyeRay.origin.x = stof(tokens[1]);
eyeRay.origin.y = stof(tokens[2]);
eyeRay.origin.z = stof(tokens[3]);
}
else if(inputVarName.compare("viewdir") == 0)
{
eyeRay.direction.x = stof(tokens[1]);
eyeRay.direction.y = stof(tokens[2]);
eyeRay.direction.z = stof(tokens[3]);
if(vectorLength(eyeRay.direction) == 0)
{
cout << "View direction vector has length 0. Please fix the input file." << endl;
throw(1);
}
}
else if(inputVarName.compare("updir") == 0)
{
upVector.x = stof(tokens[1]);
upVector.y = stof(tokens[2]);
upVector.z = stof(tokens[3]);
if(vectorLength(upVector) == 0)
{
cout << "Up vector has length 0. Please fix the input file." << endl;
throw(1);
}
}
else if(inputVarName.compare("fovh") == 0)
{
fovH = stof(tokens[1]);
if(vectorLength(upVector) > 180)
{
cout << "fovh should be <= 180. Please fix the input file." << endl;
throw(1);
}
}
else if(inputVarName.compare("imsize") == 0)
{
width = stoi(tokens[1]);
height = stoi(tokens[2]);
}
else if(inputVarName.compare("bkgcolor") == 0)
{
bgColor.r = stof(tokens[1]);
bgColor.g = stof(tokens[2]);
bgColor.b = stof(tokens[3]);
}
else if(inputVarName.compare("mtlcolor") == 0)
{
currentMaterialColor.r = stof(tokens[1]);
currentMaterialColor.g = stof(tokens[2]);
currentMaterialColor.b = stof(tokens[3]);
}
else if(inputVarName.compare("sphere") == 0)
{
SphereType currentSphere;
currentSphere.center.x = stof(tokens[1]);
currentSphere.center.y = stof(tokens[2]);
currentSphere.center.z = stof(tokens[3]);
currentSphere.radius = stof(tokens[4]);
currentSphere.color.r = currentMaterialColor.r;
currentSphere.color.g = currentMaterialColor.g;
currentSphere.color.b = currentMaterialColor.b;
spheres.push_back(currentSphere);
}
else
{
cout << "Something's wrong. Unidentified input:" << inputVarName << "\n";
}
}
else
{
cout << "No tokens on this line.\n";
}
}
//break;
}
myInputfile.close();
}
else
{
//TODO: Defaults. Probably need to default a few more things here.
width = 100;
height = 100;
cout << "Unable to open input file. Using default image size values.\n";
cout << "width:" << width << "\nheight:" << height << "\n";
}
}
void setViewingWindow(ViewingWindowType& viewingWindow, RayType eyeRay, PointType upVector, int width, int height, double fovH
, double& d, double& w, double& h , PointType& u, PointType& v)
{
//calculate the viewing window parameters.
//Mostly we want to find out the u and v vectors, and the
//4 corners of the window.
//the u vector is the unit vector orthogonal to the viewing direction and the up direction.
// u' is the non-normalized u vector.
// view_dir x up_dir = u'
// u = u'/ ||u'||
PointType uPrime = crossProduct(eyeRay.direction , upVector);
u = normalizeVector(uPrime);
//v is a unit vector orthogonal to both the viewing direction and u.
PointType vPrime = crossProduct(u , eyeRay.direction);
v = normalizeVector(vPrime);
// d is an arbitrary viewing distance, from eye to viewing window. It is in world coordinates.
d = 1.0;
// w is the width of the viewing window. In 3d world coordinate units.
// I need to calculate w based on the tangent of fovH and d. Algebra and trig yield this equation:
// w = 2 * d * tan (fovH / 2)
w = 2.0 * d * tan (fovH / 2);
// calculate h, in world coordinates. Use the aspect ratio calculated from the width and height in pixels.
h = w * height / width ;
//n is the normalized view direction vector
PointType n = normalizeVector(eyeRay.direction);
//each of these calculations are one point + 3 vectors.
//This results in a point (well, 4 points)
//ul = view_origin + d⋅n + h/2⋅v – w/2⋅u
//ur = view_origin + d⋅n + h/2⋅v + w/2⋅u
//ll = view_origin + d⋅n – h/2⋅v – w/2⋅u
//lr = view_origin + d⋅n – h/2⋅v + w/2⋅u
viewingWindow.topLeft = addVectors(addVectors(addVectors(
eyeRay.origin
, multiplyVector(n, d))
, multiplyVector(v, h/2))
, multiplyVector(u, -w/2));
viewingWindow.topRight = addVectors(addVectors(addVectors(
eyeRay.origin
, multiplyVector(n, d))
, multiplyVector(v, h/2))
, multiplyVector(u, w/2));
viewingWindow.botLeft = addVectors(addVectors(addVectors(
eyeRay.origin
, multiplyVector(n, d))
, multiplyVector(v, -h/2))
, multiplyVector(u, -w/2));
viewingWindow.botRight = addVectors(addVectors(addVectors(
eyeRay.origin
, multiplyVector(n, d))
, multiplyVector(v, -h/2))
, multiplyVector(u, w/2));
cout << "Double check the aspect ratios to see that they match." << endl;
double pixAspRat = 1.0 * width /height;
cout << "Pixel aspect ratio:" << pixAspRat << endl;
double worldAspRat = (vectorLength(addVectors(viewingWindow.botLeft, viewingWindow.botRight)))
/ (vectorLength(subtractPoints(viewingWindow.botLeft, viewingWindow.topLeft)));
cout << "World aspect ratio:" << pixAspRat << endl;
}
double intersectSphere(RayType inputRay, SphereType inputSphere)
{
//find the location of the intersection between a ray and a sphere.
//return the distance to the intersection.
//return -1 if there is no intersection.
//Solving the combined sphere and ray equation to find an intersection.
//For the quadratic equation
//A = (xd^2 + yd^2 + zd^2) = 1;
//B = 2*(xd * (x0 - xc) + yd*(y0-yc) + zd*(z0-zc))
//C = (x0-xc)^2 + (y0-yc)^2 + (z0-zc)^2 -r^2
double A = 1;
double B = 2 * (
inputRay.direction.x * (inputRay.origin.x - inputSphere.center.x)
+ inputRay.direction.y * (inputRay.origin.y - inputSphere.center.y)
+ inputRay.direction.z * (inputRay.origin.z - inputSphere.center.z));
double C =
pow( inputRay.origin.x - inputSphere.center.x , 2)
+ pow( inputRay.origin.y - inputSphere.center.y , 2)
+ pow( inputRay.origin.z - inputSphere.center.z , 2)
- pow( inputSphere.radius , 2);
//calculate the quadratic equation's discriminant, (B^2 - 4AC)
double discriminant = pow(B,2) - (4*A*C);
if (discriminant > 0)
{
//cout << "2 solutions found" << endl;
//There are 2 solutions. t is the "time" until the ray hits the object.
//We want the minimum positive t
double t1 = (-B + sqrt(discriminant))/(2*A);
double t2 = (-B - sqrt(discriminant))/(2*A);
//t<0 means that the object is behind the eye. Can't see it.
if(t1 < 0)
{
return (t2<0) ? -1 : t2;
}
else if(t2<0)
{
//Can't see t2
return t1;
}
else
{
//return the minimum of the two positive solutions. That's the closest intersection.
return ( t1<t2 ? t1 : t2);
}
}
else if (discriminant == 0)
{
//cout << "1 solution found" << endl;
//Don't reckon this'll happen much. Graze the edge of the sphere. 1 solution.
//Discriminant cancelled out.
double t = (-B)/(2*A);
return (t>0) ? t : -1;
}
else
{
//discriminant is negative. No solution. No intersection.
return -1;
}
}
ColorType trace_ray(ViewingWindowType viewingWindow, RayType eyeRay, int x, int y, PointType deltaH, PointType deltaV
, ColorType bgColor, vector<SphereType> spheres)
{
//default to background color. Switch to sphere color if ray intersects it.
ColorType results = bgColor;
//This is the mapping to the world coordinate point.
//topleft + deltaH*x + deltaV * y
PointType worldCoordinatesPoint = addVectors(addVectors(
viewingWindow.topLeft
,multiplyVector(deltaH, x))
,multiplyVector(deltaV, y));
RayType rayToTrace;
rayToTrace.origin = eyeRay.origin;
rayToTrace.direction = normalizeVector(subtractPoints(rayToTrace.origin, worldCoordinatesPoint));
//determine intersection points with each sphere.
double intersectDistance = -1;
for(int i = 0; i < spheres.size(); i++)
{
double currentIntersectDistance = intersectSphere(rayToTrace, spheres[i]);
if(currentIntersectDistance != -1 &&
(currentIntersectDistance < intersectDistance || intersectDistance == -1))
{
results = spheres[i].color;
}
}
return results;
}
void writeImageFile(ColorType pixelArray[], int width, int height, string inputFileName)
{
string widthString = to_string(width);
string heightString = to_string(height);
string outputFileName = inputFileName.substr(0,inputFileName.length()-4) + ".ppm";
//Write image File
ofstream myfile;
myfile.open (outputFileName);
//Write Header
myfile << "P3\n";
myfile << "# This image was created by Ben Matern from input file " << inputFileName << "\n";
myfile << widthString + " " + heightString + "\n";
myfile << "1\n";
//Loop through each pixel in the picture.
for(int y = 0; y < height ; y++)
{
for(int x = 0; x < width ; x++)
{
string r = to_string(pixelArray[ x + y*width ].r) + " ";
string b = to_string(pixelArray[ x + y*width ].b) + " ";
string g = to_string(pixelArray[ x + y*width ].g) + " ";
myfile << r << g << b;
}
//We just finished a row of pixels.
myfile << "\n";
}
myfile << "";
myfile.close();
}
int main( int argc, char *argv[] )
{
cout << "Creating a new image.\n";
//Declare all the important variables I'll need
//This width and height are in pixels.
int width, height;
//d, w, h are in world coordinates
//d = distance from eye to window. w=width window, h = height window.
double d, w, h;
RayType eyeRay;
PointType upVector;
PointType u;
PointType v;
ColorType bgColor;
ColorType currentMaterialColor;
vector<SphereType> spheres;
//The angle of the horizontal field of view. Theta.
double fovH;
//contains 4 points for the coordinates of the viewing window.
ViewingWindowType viewingWindow;
string inputFileName;
//Read commandline args to get the input file name.
inputFileName = getInputFileName(argc, argv);
cout << "Input:" << inputFileName << ":\n";
//Read input file to get the scene information.
try
{
loadSceneInformation(inputFileName, eyeRay, upVector, width, height, fovH
, bgColor, currentMaterialColor, spheres);
}
catch(int e)
{
cout << "Exception occured during loadSceneInformation. Doublecheck your input file. Cannot recover." << endl;
return(0);
}
//Initialize pixel array for output image
cout << "Initializing Pixel Array" << endl;
ColorType* pixelArray =new ColorType[width*height];
//Perform necessary preliminary calculations.
cout << "Starting Preliminary Calculations" << endl;
setViewingWindow(viewingWindow, eyeRay, upVector, width, height
, fovH, d, w, h ,u , v);
//foreach pixel in image array:
//call trace_ray() with appropriate parameters
//Use value returend by trace_ray to update pixel colors.
cout << "Starting the loop through each pixel" << endl;
//Passing in deltaH and deltaV so I don't need to calculate it every time.
//deltaH and deltaV are VECTORS. they indicate how far to increment the viewing window for each pixel.
//deltaH = (ur - ul)/(pixwidth - 1)
PointType deltaH = multiplyVector( subtractPoints(viewingWindow.topLeft, viewingWindow.topRight)
, (1.0/(width - 1)));
PointType deltaV = multiplyVector( subtractPoints(viewingWindow.topLeft, viewingWindow.botLeft)
, (1.0/(height - 1)));
for(int y = 0; y < height; y++)
{
for(int x = 0; x < width; x++)
{
ColorType currentPixel = trace_ray(viewingWindow, eyeRay, x, y, deltaH, deltaV, bgColor, spheres);
pixelArray [ x + y*width ] = currentPixel;
}
}
//Write the data to a image file.
writeImageFile(pixelArray, width, height, inputFileName);
return 0;
}
| true |
2f2612221a5912a0244bb986c63bae5e43280908 | C++ | Jarczyslaw/HysteresisRegulator-Arduino | /Main/UserPrefs.h | UTF-8 | 1,398 | 2.765625 | 3 | [] | no_license | #pragma once
#include "EEPROMex.h"
#include "Thermometer.h"
class UserPrefs
{
public:
UserPrefs();
void SetSetPoint(float);
float GetSetPoint(float);
void SetRelayInputOn(float);
float GetRelayInputOn(float);
void SetRelayInputOff(float);
float GetRelayInputOff(float);
void SetResolution(Thermometer::Resolution resolution);
Thermometer::Resolution GetThermometerResolution(Thermometer::Resolution);
void Clear();
protected:
private:
enum
{
ADDRESS_FLAG_SET_POINT = 0,
ADDRESS_SET_POINT = 1,
ADDRESS_FLAG_RELAY_INPUT_ON = 5,
ADDRESS_RELAY_INPUT_ON = 6,
ADDRESS_FLAG_RELAY_INPUT_OFF = 10,
ADDRESS_RELAY_INPUT_OFF = 11,
ADDRESS_FLAG_THERM_RESOLUTION = 15,
ADDRESS_THERM_RESOLUTION = 16
};
int totalBytesUsed = 20;
template <class T> void Set(int flagAddress, int valueAddress, T value)
{
EEPROM.updateByte(flagAddress, true);
EEPROM.updateBlock<T>(valueAddress, value);
}
template <class T> T Get(int flagAddress, int valueAddress, T defaultValue)
{
if (EEPROM.readByte(flagAddress))
{
T value;
EEPROM.readBlock<T>(valueAddress, value);
return value;
}
else
return defaultValue;
}
};
| true |
e6c0e6c8b35844d86fe03a00e744e63e5dcce481 | C++ | Kmykhail/Piscine-CPP | /day05_CPP/ex01/main.cpp | UTF-8 | 2,022 | 2.6875 | 3 | [] | no_license | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: kmykhail <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/06/25 19:32:06 by kmykhail #+# #+# */
/* Updated: 2018/06/25 19:32:08 by kmykhail ### ########.fr */
/* */
/* ************************************************************************** */
#include "Form.hpp"
#include "Bureaucrat.hpp"
void checkForm(Bureaucrat bureaucrat, Form format)
{
try
{
bureaucrat.signForm(format);
std::cout << bureaucrat << std::endl;
std::cout << format << std::endl;
}
catch (std::exception &e)
{
std::cout << e.what() << std::endl;
}
return ;
}
int main()
{
Form f1 = Form("A form", 42, 42);
Form f2 = Form("Another one...", 30, 50);
try {
Form f3 = Form("Form Fuck You", 0, 42);
}
catch (std::exception &e)
{
std::cout << e.what() << std::endl;
}
Bureaucrat b1 = Bureaucrat("Marvin", 42);
Bureaucrat b2 = Bureaucrat("Mr. Abraham", 1);
Bureaucrat b3 = Bureaucrat("XYQ", 150);
checkForm(b1, f1);
std::cout << b1 << " " << f1 << std::endl;
checkForm(b1, f2);
std::cout << b2 << " " << f2 << std::endl;
checkForm(b2, f1);
std::cout << b2 << " " << f1 << std::endl;
checkForm(b2, f2);
std::cout << b2 << " " << f2 << std::endl;
//checkForm(b3, f3);
//std::cout << b3 << " " << f3 << std::endl;
return (0);
} | true |
0b5db63de06da6b84f745a958dac9c8477300673 | C++ | JorgeReus/ESCOM | /Distributed Systems/ukranioFest/proyectoUkranio/SocketDatagrama.h | UTF-8 | 603 | 2.53125 | 3 | [] | no_license | #ifndef SOCKETDATAGRAMA_H
#define SOCKETDATAGRAMA_H
#include <netinet/in.h>
#include <sys/time.h>
class SocketDatagrama{
public:
SocketDatagrama(int port);
//~SocketDatagrama();
//Recibe un paquete tipo datagrama proveniente de este socket
unsigned int recibe(PaqueteDatagrama & p);
//Envía un paquete tipo datagrama desde este socket
unsigned int envia(PaqueteDatagrama & p);
int recibeTimeout(PaqueteDatagrama & p, time_t segundos, time_t microsegundos);
private:
struct sockaddr_in direccionLocal;
struct sockaddr_in direccionForanea;
int s; //ID socket
struct timeval timeout;
};
#endif
| true |
eab593d512aff2f30870a873dd7e576ef96b050e | C++ | szekipepe/gsys-dsv | /tests/ConfigTest.cpp | UTF-8 | 2,067 | 3.046875 | 3 | [
"BSD-3-Clause"
] | permissive | #include <functional>
#include <type_traits>
#include <gtest/gtest.h>
#include <GSys/DSV/Config.h>
using namespace GSys::DSV;
TEST(ConfigContructor, Default)
{
EXPECT_TRUE(std::is_default_constructible<Config>::value);
}
TEST(ConfigContructor, CopyNoThrow)
{
EXPECT_TRUE(std::is_nothrow_copy_constructible<Config>::value);
}
TEST(ConfigContructor, MoveNoThrow)
{
EXPECT_TRUE(std::is_nothrow_move_constructible<Config>::value);
}
TEST(ConfigDestructor, NoThrow)
{
EXPECT_TRUE(std::is_nothrow_destructible<Config>::value);
}
TEST(ConfigAssignable, CopyNoThrow)
{
EXPECT_TRUE(std::is_nothrow_copy_assignable<Config>::value);
}
TEST(ConfigAssignable, MoveNoThrow)
{
EXPECT_TRUE(std::is_nothrow_move_constructible<Config>::value);
}
TEST(ConfigDefaultContructorMemberValue, LineEnding)
{
EXPECT_EQ(Config().lineEnding(), Config::LineEnding::Lf);
}
TEST(ConfigDefaultContructorMemberValue, Delimiter)
{
EXPECT_EQ(Config().delimiter(), Config::Delimiter::Comma);
}
TEST(ConfigDefaultContructorMemberValue, AllowedTextData)
{
EXPECT_EQ(Config().allowedTextData(), Config::AllowedTextData::All);
}
TEST(ConfigDefaultContructorMemberValue, Header)
{
EXPECT_EQ(Config().header(), Config::Header::FirstLineHeader);
}
TEST(ConfigSetters, LineEndingFromDefault)
{
auto values = { Config::LineEnding::CrLf, Config::LineEnding::Lf, Config::LineEnding::Cr };
for (auto value : values) {
Config config;
config.setLineEnding(value);
EXPECT_EQ(config.lineEnding(), value);
}
}
TEST(ConfigSetters, LineEndingFromToAnyValues)
{
auto values = { Config::LineEnding::CrLf, Config::LineEnding::Lf, Config::LineEnding::Cr };
for (auto value_from : values) {
for (auto value_to : values) {
Config config;
config.setLineEnding(value_from);
config.setLineEnding(value_to);
EXPECT_EQ(config.lineEnding(), value_to);
}
}
}
int main(int argc, char** argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| true |
dce6899a1c92d559613748164c134d46e3fc1660 | C++ | vcflib/vcflib | /src/cigar.cpp | UTF-8 | 7,060 | 2.84375 | 3 | [
"MIT",
"CC0-1.0"
] | permissive | #include "cigar.hpp"
namespace vcflib {
// generates cigar from allele parsed by parsedAlternates
// Note: this function is not used in vcflib
string varCigar(vector<VariantAllele>& vav, bool xForMismatch) {
string cigar;
pair<int, string> element;
for (vector<VariantAllele>::iterator v = vav.begin(); v != vav.end(); ++v) {
VariantAllele& va = *v;
if (va.ref != va.alt) {
if (element.second == "M") {
cigar += convert(element.first) + element.second;
element.second = ""; element.first = 0;
}
if (va.ref.size() == va.alt.size()) {
cigar += convert(va.ref.size()) + (xForMismatch ? "X" : "M");
} else if (va.ref.size() > va.alt.size()) {
cigar += convert(va.ref.size() - va.alt.size()) + "D";
} else {
cigar += convert(va.alt.size() - va.ref.size()) + "I";
}
} else {
if (element.second == "M") {
element.first += va.ref.size();
} else {
element = make_pair(va.ref.size(), "M");
}
}
}
if (element.second == "M") {
cigar += convert(element.first) + element.second;
}
element.second = ""; element.first = 0;
return cigar;
}
string mergeCigar(const string& c1, const string& c2) {
vector<pair<int, char> > cigar1 = splitCigar(c1);
vector<pair<int, char> > cigar2 = splitCigar(c2);
// check if the middle elements are the same
if (cigar1.back().second == cigar2.front().second) {
cigar1.back().first += cigar2.front().first;
cigar2.erase(cigar2.begin());
}
for (vector<pair<int, char> >::iterator c = cigar2.begin(); c != cigar2.end(); ++c) {
cigar1.push_back(*c);
}
return joinCigar(cigar1);
}
vector<pair<int, char> > splitUnpackedCigar(const string& cigarStr) {
vector<pair<int, char> > cigar;
int num = 0;
char type = cigarStr[0];
// cerr << "[" << cigarStr << "]" << endl; // 18,12,14
for (char c: cigarStr) {
// cerr << "[" << c << "]";
if (isdigit(c)) {
cerr << "Is this a valid unpacked CIGAR? <" << cigarStr << ">?" << endl;
exit(1);
}
if (c != type) {
cigar.push_back(make_pair(num, type));
//cerr << num << ":" << type << ", ";
type = c;
num = 0;
}
num += 1;
}
cigar.push_back(make_pair(num, type));
//cerr << num << ":" << type << ", ";
return cigar;
}
vector<pair<int, char> > splitCigar(const string& cigarStr) {
vector<pair<int, char> > cigar;
string number;
char type = '\0';
// strings go [Number][Type] ...
for (string::const_iterator s = cigarStr.begin(); s != cigarStr.end(); ++s) {
char c = *s;
if (isdigit(c)) {
if (type == '\0') {
number += c;
} else {
// signal for next token, push back the last pair, clean up
cigar.push_back(make_pair(atoi(number.c_str()), type));
number.clear();
type = '\0';
number += c;
}
} else {
type = c;
}
}
if (!number.empty() && type != '\0') {
cigar.push_back(make_pair(atoi(number.c_str()), type));
}
return cigar;
}
list<pair<int, char> > splitCigarList(const string& cigarStr) {
list<pair<int, char> > cigar;
string number;
char type = '\0';
// strings go [Number][Type] ...
for (string::const_iterator s = cigarStr.begin(); s != cigarStr.end(); ++s) {
char c = *s;
if (isdigit(c)) {
if (type == '\0') {
number += c;
} else {
// signal for next token, push back the last pair, clean up
cigar.push_back(make_pair(atoi(number.c_str()), type));
number.clear();
type = '\0';
number += c;
}
} else {
type = c;
}
}
if (!number.empty() && type != '\0') {
cigar.push_back(make_pair(atoi(number.c_str()), type));
}
return cigar;
}
vector<pair<int, char> > cleanCigar(const vector<pair<int, char> >& cigar) {
vector<pair<int, char> > cigarClean;
for (vector<pair<int, char> >::const_iterator c = cigar.begin(); c != cigar.end(); ++c) {
if (c->first > 0) {
cigarClean.push_back(*c);
}
}
return cigarClean;
}
string joinCigar(const vector<pair<int, char> >& cigar) {
string cigarStr;
bool has_error = false;
for (auto c: cigar) {
auto len = c.first;
if (len < 0) has_error = true;
if (len != 0) {
cigarStr += convert(len) + c.second;
}
}
if (has_error) {
cerr << "ERROR: joinCigar creates illegal cigar " << cigarStr << endl;
exit(1);
}
return cigarStr;
}
string joinCigarList(const list<pair<int, char> >& cigar) {
string cigarStr;
for (list<pair<int, char> >::const_iterator c = cigar.begin(); c != cigar.end(); ++c) {
cigarStr += convert(c->first) + c->second;
}
return cigarStr;
}
int cigarRefLen(const vector<pair<int, char> >& cigar) {
int len = 0;
for (vector<pair<int, char> >::const_iterator c = cigar.begin(); c != cigar.end(); ++c) {
if (c->second == 'M' || c->second == 'D' || c->second == 'X') {
len += c->first;
}
}
return len;
}
bool isEmptyCigarElement(const pair<int, char>& elem) {
return elem.first == 0;
}
vector<pair<int, string> > old_splitCigar(const string& cigarStr) {
vector<pair<int, string> > cigar;
string number;
string type;
// strings go [Number][Type] ...
for (string::const_iterator s = cigarStr.begin(); s != cigarStr.end(); ++s) {
char c = *s;
if (isdigit(c)) {
if (type.empty()) {
number += c;
} else {
// signal for next token, push back the last pair, clean up
cigar.push_back(make_pair(atoi(number.c_str()), type));
number.clear();
type.clear();
number += c;
}
} else {
type += c;
}
}
if (!number.empty() && !type.empty()) {
cigar.push_back(make_pair(atoi(number.c_str()), type));
}
return cigar;
}
string old_joinCigar(const vector<pair<int, string> >& cigar) {
string cigarStr;
for (vector<pair<int, string> >::const_iterator c = cigar.begin(); c != cigar.end(); ++c) {
if (c->first) {
cigarStr += convert(c->first) + c->second;
}
}
return cigarStr;
}
string old_joinCigar(const vector<pair<int, char> >& cigar) {
string cigarStr;
for (vector<pair<int, char> >::const_iterator c = cigar.begin(); c != cigar.end(); ++c) {
if (c->first) {
cigarStr += convert(c->first) + string(1, c->second);
}
}
return cigarStr;
}
}
| true |
a2164a06285a65de1d525545b54e5e21b68ed12b | C++ | OppKunG/Assignment | /Stars.cpp | UTF-8 | 681 | 2.96875 | 3 | [] | no_license | #define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int main() {
//Pseudo Code Ex1
/*int in;
scanf("%d",&in);
for (int j = 1; j <= in;) {
printf("\n");
j = j +1;
for (int i = 2; i <= j;) {
printf("*");
i = i +1;
}
}
//Pseudo Code Ex2
/*int m,n;
scanf("%d %d", &m,&n);
for (int j = 1; j <= m;) {
printf("\n");
j = j + 1;
for (int i = 1; i <= n;) {
printf("*");
i = i + 1;
}
}*/
//Pseudo Code Ex3
int in;
scanf("%d",&in);
for (int i = 1; i <= in;) {
printf("*");
i = i + 1;
for (int j = 3; j<=in;) {
printf("-");
j = j + 1;
/* for (int k = 3; k <= in;) {
printf("\n");
k = k + 1;
}*/
}
}
return 0;
} | true |
8b5508912ec7dc9be7feb242ccb16cfb9de356f7 | C++ | megamareep/GameEngineRacer | /GameEngineRacer/source/Game.cpp | UTF-8 | 5,250 | 2.546875 | 3 | [] | no_license | #include "Game.h"
float Game::zoom;
bool Game::keys[1024]= {false};
Game::Game(){
//scene = new CubeScene();
scene[1] = new Scene();
scene[0] = new Scene();
gui = new GUI();
speed = 0.5f;
turnSpeed = 5.5f;
activeScene =0;
x1 = 0;
y1=0;
z1=0;
rot=0;
rManager = ResourceManager::getInstance();
}
Game::~Game()
{
delete gui;
gui = NULL;
for(unsigned int i=0; i < 2; ++i)
{
delete scene[i];
scene[i] = NULL;
}
}
void Game::Run()
{
Initialise();
glfwSetTime(0.0);
double refresh_rate = 1.0/60.0;
//! run the program as long as the window is open
while (!glfwWindowShouldClose(window))
{
handleInput();
if (glfwGetTime() > refresh_rate)
{
glfwSetTime(0.0);
Update();//TimeDelta for timestep.
Render();
}
}
glfwTerminate();
exit(EXIT_SUCCESS);
}
void Game::Initialise()
{
width = 1024;
height = 768;
glfwSetErrorCallback(error_callback);
if (!glfwInit())
exit(EXIT_FAILURE);
window = glfwCreateWindow(width, height, "Most Awesome Game Ever", NULL, NULL);
if (!window)
{
glfwTerminate();
exit(EXIT_FAILURE);
}
glfwSetWindowSizeCallback(window,WindowSizeCB);
glfwMakeContextCurrent(window);
glfwSetMouseButtonCallback(window,mouse_button_callback);
glfwSetCursorPosCallback(window, (GLFWcursorposfun)TwEventMousePosGLFW3);
glfwSetScrollCallback(window, scroll_callback);
glfwSetKeyCallback(window, key_callback);
glfwSetCharCallback(window, (GLFWcharfun)TwEventCharGLFW3);
// Load the OpenGL functions.
gl::exts::LoadTest didLoad = gl::sys::LoadFunctions();
if (!didLoad) {
//Claen up and abort
glfwTerminate();
exit(EXIT_FAILURE);
}
if(!rManager->LoadMaster("splashmaster"))
{
std::cout << "Error loading master\n";
exit(EXIT_FAILURE);
}
scene[0]->InitScene("loading");
scene[0]->Update(keys);
Render();
scene[0]->deleteShader();
rManager->clearAll();
if(!rManager->LoadMaster("basicmaster"))
{
std::cout << "Error loading master\n";
exit(EXIT_FAILURE);
}
scene[1]->InitScene("demolevel");
activeScene =1;
if(rManager->getShaders().size() > 0)
{
ui.initText2D();
}
gui->setup(width,height, scene[activeScene]);
}
void Game::error_callback(int error, const char* description)
{
fputs(description, stderr);
}
void Game::Update()
{
if(keys[GLFW_KEY_LEFT_ALT])
{
scene[activeScene]->GetCamera()->zoom(zoom);
zoom = 0;
glfwGetCursorPos(window,&cursorPositionX,&cursorPositionY);
//See how much the cursor has moved
float deltaX = (float)(lastCursorPositionX - cursorPositionX);
float deltaY = (float)(lastCursorPositionY - cursorPositionY);
//Using a different way (i.e. instead of callback) to check for LEFT mouse button
if (glfwGetMouseButton(window,GLFW_MOUSE_BUTTON_LEFT) )
{
//std::cout << "Left button \n";
//Rotate the camera. The 0.001f is a velocity mofifier to make the speed sensible
scene[activeScene]->GetCamera()->rotate(deltaX*0.001f, deltaY*0.001f);
}
//Using a different way (i.e. instead of callback) to check for RIGHT mouse button
if (glfwGetMouseButton(window,GLFW_MOUSE_BUTTON_RIGHT) )
{
//std::cout << "Right button \n";
//Rotate the camera. The 0.01f is a velocity mofifier to make the speed sensible
scene[activeScene]->GetCamera()->pan(deltaX*0.01f, deltaY*0.01f);
}
}
scene[activeScene]->Update(keys);
gui->saveData(scene[activeScene]);
gui->openFile(scene[activeScene]);
gui->update();
//Store the current cursor position
lastCursorPositionX = cursorPositionX;
lastCursorPositionY = cursorPositionY;
}
void Game::Render()
{
int width, height;
glfwGetFramebufferSize(window, &width, &height);
gl::ClearColor(0.0f,0.5f,0.7f,1.0f);
gl::Clear( gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT );
scene[activeScene]->Render();
if(scene[1]->GetGameObjects().size() >=1)
{
ui.printText2D("EDITOR",20,20,20);
}
gui->draw();
glfwSwapBuffers(window);
glfwPollEvents();
}
void Game::key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)//key callback
{
if(!TwEventKeyGLFW(key, action))
{
}
glfwSetKeyCallback(window,key_callback);
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, gl::TRUE_);
keys[key] = action;
}
void Game::mouse_button_callback(GLFWwindow* window, int button, int action, int mods)
{
if(!TwEventMouseButtonGLFW(button,action))
{
//std::cout << "hello/n";
}
glfwSetMouseButtonCallback(window,mouse_button_callback);
}
void Game::scroll_callback(GLFWwindow *window, double x, double y)
{
zoom = (float)y*2.5f;
}
void Game::handleInput()
{
if(keyPressedOnce(GLFW_KEY_N))
{
scene[activeScene]->nextCamera();
}
}
bool Game::keyPressedOnce(int key)
{
static bool pressed = false;
if(keys[key] == GLFW_PRESS && !pressed)
{
pressed = true;
return true;
}
else if(keys[key] == GLFW_RELEASE )
{
pressed = false;
return false;
}
else return false;
}
void Game::WindowSizeCB(GLFWwindow* window, int width, int height){
// Set OpenGL viewport and camera
gl::Viewport(0, 0, width, height);
// Send the new window size to AntTweakBar
TwWindowSize(width, height);
//gui->onResize(width,height);
//scene[activeScene]->resize(width,height);
}
//void Game::SetZoom(float z)
//{
// zoom = z;
//}
| true |
23ad13d11c181dbe0e562d451fc614d6a421f358 | C++ | halil28450/PoolCPP | /Day 10/ex01/AWeapon.cpp | UTF-8 | 502 | 2.65625 | 3 | [] | no_license | /*
** EPITECH PROJECT, 2021
** B_CPP_300_STG_3_1_CPPD10_arthur_robine
** File description:
** Exercice 01
*/
#include "AWeapon.hpp"
AWeapon::AWeapon(const std::string &name, int apcost, int damage)
{
_name = name;
_apcost = apcost;
_damage = damage;
}
AWeapon::~AWeapon()
{
}
const std::string AWeapon::getName() const
{
return _name;
}
int AWeapon::getAPCost() const
{
return _apcost;
}
int AWeapon::getDamage() const
{
return _damage;
}
void AWeapon::attack() const
{
} | true |
9a7b7916de62aa5a5e209a6bdccfb8102cf1d4d5 | C++ | rokez98/IIPU | /Battery/BatteryLifePercent.h | UTF-8 | 189 | 2.75 | 3 | [] | no_license | #pragma once
class BatteryLifePercent {
int _code = 0;
public:
BatteryLifePercent() {}
BatteryLifePercent(int code) {
this->_code = code;
}
int getValue() {
return _code;
}
};
| true |
91a678cbc53d9b5f92093360bd81accd338c7c4b | C++ | volkit/volkit | /include/cpp/vkt/ExecutionPolicy.hpp | UTF-8 | 3,446 | 2.859375 | 3 | [
"MIT"
] | permissive | // This file is distributed under the MIT license.
// See the LICENSE file for details.
#pragma once
#include "common.hpp"
/*! @file ExecutionPolicy.hpp
* @brief Utilities to query or modify the current thread execution policy
*
* Volkit uses a deferred API where the way that computations are performed
* (e.g., on the CPU or on the GPU, preferred parallel API, etc.) is specified
* in advance before invoking an algorithm and on a per thread basis. With each
* application thread there is associated a @ref vkt::ExecutionPolicy object; the
* user can modify that object to influence how ensuing computations are
* performed.
*
* The following example shows how to set the execution policy to `GPU` for the
* current thread:
* ```
* // Current execution policy is "CPU"
* vkt::StructuredVolume volume;
*
* //...
*
* vkt::ExecutionPolicy ep = vkt::GetThreadExecutionPolicy();
* ep.device = vkt::ExecutionPolicy::Device::GPU;
* vkt::SetThreadExecutionPolicy(ep);
*
* // Execution policy is now "GPU"
* // Data is still on the CPU though as the API is deferred
*
* // The Fill algorithm will determine that the execution policy
* // when the volume was created was "CPU" and will now "migrate"
* // the volume so that the data is on the GPU before performing
* // the fill operation
* vkt::Fill(volume, 0.f);
* ```
* Therefore, setting the execution policy is cheap, but the next algorithm or
* function call might involve data migration and thus a copy over PCIe. Note
* that setting and immediately resetting the execution policy results in a
* noop, i.e., algorithms will not detect changes to the execution policy but
* only the immediate policies specified for current and previous usage.
*/
namespace vkt
{
struct ExecutionPolicy
{
enum class Device
{
CPU,
GPU,
Unspecified,
};
enum class HostAPI
{
Serial,
//Threads,
OpenMP,
//TBB,
Auto,
};
enum class DeviceAPI
{
CUDA,
//OpenCL,
Auto,
};
//! Device to run ensuing operations on
Device device = Device::CPU;
//! API that is used for execution on the CPU
HostAPI hostApi = HostAPI::Serial;
//! API that is used for execution on the GPU
DeviceAPI deviceApi = DeviceAPI::CUDA;
//! Print performance measurements to stdout
Bool printPerformance = False;
};
/*! @brief Set the execution policy of the current thread
*
* Use this function to set the thread execution policy. Setting the execution
* policy affects how the ensuing algorithms and operations are executed.
* @see GetThreadExecutionPolicy()
*/
VKTAPI void SetThreadExecutionPolicy(ExecutionPolicy policy);
/*! @brief Get the execution policy of the current thread
*
* Each application / user thread has its own execution policy. Use this
* function to query the execution policy of the current thread. Note that
* execution policies are not inherited by child threads. This function can
* be used to query the execution policy in the parent thread and then set
* it via @ref SetThreadExecutionPolicy() in the child thread.
* @see SetThreadExecutionPolicy()
*/
VKTAPI ExecutionPolicy GetThreadExecutionPolicy();
} // vkt
| true |
8b408b64e9fc907f95ab2b0ad07b4427974a718f | C++ | DsAizen/liveclass2020 | /l-9/poiter aithmatic.cpp | UTF-8 | 186 | 2.71875 | 3 | [] | no_license | // poiter aithmatic
#include <iostream>
using namespace std;
int main()
{
int x = 5;
int *p = &x;
cout<<p<<endl;
cout << p - 1 <<endl;
cout << p - 2 <<endl;
return 0;
} | true |
8431ebc8f618e8799e8cebcd0b8bf4d6626d8f78 | C++ | BrianRust/3D-Cellular-Automata | /CellularBlockWorld/Game/CubeCell.hpp | UTF-8 | 601 | 2.859375 | 3 | [] | no_license | #ifndef included_CubeCell
#define included_CubeCell
#pragma once
//-------------------------------------------------------------
//-------------------------------------------------------------
class CubeCell
{
public:
CubeCell()
{
m_isSolid = false;
m_cellType = 0;
//m_isBlack = false;
};
CubeCell(bool isSolid)
{
m_isSolid = isSolid;
m_cellType = 0;
//m_isBlack = false;
};
CubeCell(bool isSolid, char cellType)
{
m_isSolid = isSolid;
m_cellType = cellType;
//m_isBlack = isBlack;
};
bool m_isSolid;
//bool m_isBlack;
char m_cellType;
};
#endif //included_CubeCell | true |
e4636fc899a21ed09d28b159ccf7045358cce106 | C++ | MyTFG/raspVtp | /raspVtp/plan.cpp | UTF-8 | 2,303 | 3 | 3 | [] | no_license | #include "plan.h"
Plan::Plan(bool day, std::string text, std::string title)
{
this->currentRow = -1;
this->currentCol = 0;
this->isToday = day;
this->textPt = text;
this->titlePt = title;
this->layout = new QVBoxLayout;
this->layout->setMargin(0);
this->layout->setSpacing(1);
this->nextRow();
}
void Plan::nextRow() {
this->currentRow++;
this->currentCol = 0;
this->row = new QGridLayout;
this->row->setSpacing(0);
this->row->setMargin(1);
QWidget *frame = new QWidget;
frame->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
if (this->isToday) {
frame->setStyleSheet("QWidget { background-color: #0081f2;}");
} else {
frame->setStyleSheet("QWidget { background-color: #00b31b;}");
}
frame->setLayout(this->row);
this->layout->addWidget(frame, 0, Qt::AlignTop);
}
void Plan::addCell(std::string content, int colspan, bool isTitle) {
QWidget *frame = new QWidget;
frame->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
QLabel *label = new QLabel;
label->setMargin(0);
label->setAlignment(Qt::AlignCenter);
QHBoxLayout *frameLayout = new QHBoxLayout;
frameLayout->setSpacing(0);
frameLayout->setMargin(0);
frame->setLayout(frameLayout);
if (isTitle) {
frame->setStyleSheet("QFrame {background-color: #00014a; margin: 0px; padding: 5px; border: 2px solid #AA0000;}");
label->setStyleSheet("QLabel { color : white; border: 0px; font-size: " + QString::fromStdString(this->titlePt) + "; text-align: center;}");
label->setText("<b>" + QString::fromStdString(content) + "</b>");
} else {
label->setText(QString::fromStdString(content));
frame->setStyleSheet("QFrame {background-color: #586FC7; font-size: " + QString::fromStdString(this->textPt) + "; margin: 0px; padding: 5px;}");
label->setStyleSheet("QLabel { color : white; border: 0px; font-weight: bold;}");
}
label->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
frameLayout->addWidget(label);
this->row->addWidget(frame, 0, this->currentCol);
this->row->setColumnStretch(this->currentCol, colspan);
this->currentCol++;
}
QVBoxLayout* Plan::getWidget() {
return this->layout;
}
| true |
f4b1a81247f6812c6aa17a65385240f1d4666a30 | C++ | chenshuyuhhh/acm | /Sort/main57.cpp | UTF-8 | 1,778 | 3.796875 | 4 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
//给出一个无重叠的 ,按照区间起始端点排序的区间列表。
//在列表中插入一个新的区间,你需要确保列表中的区间仍然有序且不重叠(如果有必要的话,可以合并区间)。
bool cmp(vector<int> a, vector<int> b) {
return a[0] < b[0]; // 升序排序
}
vector<vector<int>> insert(vector<vector<int>> intervals, vector<int> newInterval) {
intervals.push_back(newInterval);
sort(intervals.begin(), intervals.end(), cmp);
vector<vector<int>> result;
for (int i = 0; i < intervals.size(); ++i) {
int firstR = intervals[i][1]; // get the right of the first element
int firstL = intervals[i][0];
// find boundary
for (i = i + 1; i < intervals.size(); ++i) {
int nextL = intervals[i][0]; // get the left ele of the next element
int nextR = intervals[i][1];
if (firstR < nextL) {
--i; // back one step
break; // if r is less than l, have found boundary
} else if (firstR < nextR) {
// nextL <= firstR < nextR
firstR = nextR;
}
// else firstR > nextR, keep the firstR
}
// push pair
result.push_back({firstL, firstR});
}
return result;
}
int main57() {
vector<vector<int>> intervals = {{1, 3},
{6, 9}};
vector<int> newInterval = {2, 5};
vector<vector<int>> result = insert(intervals, newInterval);
for (auto &i : result) {
cout << i[0] << i[1] << endl;
}
// 输入: intervals = [[1,3],[6,9]], newInterval = [2,5]
// 输出: [[1,5],[6,9]]
return 0;
}
| true |
ee5eab28b92d3c55f9bd26504ab22f0487fb8c67 | C++ | gunnersaur/Tennis-Ball-Machine | /Machine/Machine.ino | UTF-8 | 6,018 | 3.328125 | 3 | [] | no_license | // Set pins
int LPWM1 = 3;
int RPWM1 = 5;
int LPWM2 = 9;
int RPWM2 = 10;
int mode; //control mode (0 = speed and spin)
int numModes = 2; //number of control modes (makes it easier to add more control later
int midSpeed = 125; //initial speed to start to
int currentSpeed1; //speed of motor one (top)
int currentSpeed2; //speed of motor two (bottom)
int speedDifferential = 5; //amount by which to increase speed
int spinDifferential = 5; //amount by which to increase spin
char input; //character received by serial
void setup() {
// Set pin modes
pinMode (LPWM1, OUTPUT);
pinMode (RPWM1, OUTPUT);
pinMode (LPWM2, OUTPUT);
pinMode (RPWM2, OUTPUT);
//Spin up motor
for (int i = 0; i < midSpeed; i++)
{
analogWrite (LPWM1, i);
analogWrite (LPWM2, i);
delay(10);
}
currentSpeed1 = midSpeed; //set both motor speeds equal to speed reached at spin-up
currentSpeed2 = midSpeed;
mode = 0;
//start serial communication
Serial.begin(9600);
Serial.println("Testing Serial"); //for testing purposes
}
void loop() {
if (Serial.available() > 0)
{
input = Serial.read(); //reads next serial character
Serial.println(input); //For testing purposes
if (input == 'm') //mode change received
{
if (mode == (numModes -1))
{
mode = 0;
} else
{
mode++;
}
Serial.println("Mode Changed");
}
else if (mode == 0) //when in mode zero
{
if (input == 'u') //up signal received
{
addTopspin();
}
if (input == 'd') //down signal received
{
addBackspin();
}
if (input == 'l') //left signal received
{
increaseSpeed();
}
if (input == 'r') //right signal received
{
decreaseSpeed();
}
}
else if (mode == 1) //when in mode one
{
if (input == 'u') //up signal received
{
Serial.println("Moving up");
}
if (input == 'd') //down signal received
{
Serial.println("Moving down");
}
if (input == 'l') //left signal received
{
Serial.println("Moving left");
}
if (input == 'r') //right signal received
{
Serial.println("Moving right");
}
}
}
}
void showSpeed() //print speed of both motors to serial
{
Serial.print("Top motor at: ");
Serial.println(currentSpeed1);
Serial.print("Bottom motor at: ");
Serial.println(currentSpeed2);
}
void increaseSpeed()
{
if (currentSpeed1 < 255 && currentSpeed2 < 255) //if both motors are capable, increase speed by speed differential
{
currentSpeed1 += speedDifferential;
currentSpeed2 += speedDifferential;
analogWrite (LPWM1, currentSpeed1);
analogWrite (LPWM2, currentSpeed2);
showSpeed();
delay(100);
}
else if (currentSpeed1 >= 255 && currentSpeed2 >= 255) //otherwise print that one or both motors are at max speed
{
Serial.println("Max speed of both motors reached");
showSpeed();
}
else if (currentSpeed1 >= 255)
{
Serial.println("Max speed of top motor reached");
showSpeed();
}
else if (currentSpeed2 >= 255)
{
Serial.println("Max speed of bottom motor reached");
showSpeed();
}
}
void decreaseSpeed()
{
if (currentSpeed1 > 0 && currentSpeed2 > 0) //if both motors are capable, decrease speed by speed differential
{
currentSpeed1 -= speedDifferential;
currentSpeed2 -= speedDifferential;
analogWrite (LPWM1, currentSpeed1);
analogWrite (LPWM2, currentSpeed2);
showSpeed();
delay(100);
}
else if (currentSpeed1 <= 0 && currentSpeed2 <= 0) //otherwise print that one or both motors are at min speed
{
Serial.println("Min speed of both motors reached");
showSpeed();
}
else if (currentSpeed1 <= 0)
{
Serial.println("Min speed of top motor reached");
showSpeed();
}
else if (currentSpeed2 <= 0)
{
Serial.println("Min speed of bottom motor reached");
showSpeed();
}
}
void addTopspin()
{
if (currentSpeed1 < 255 && currentSpeed2 > 0) //if both motors are capable, diverge speed by spin differential with top motor increasing
{
currentSpeed1 += spinDifferential;
currentSpeed2 -= spinDifferential;
analogWrite (LPWM1, currentSpeed1);
analogWrite (LPWM2, currentSpeed2);
showSpeed();
delay(100);
}
else if (currentSpeed1 >= 255 && currentSpeed2 <= 0) //otherwise print that one or both motors are at max spin or max/min speed
{
Serial.println("Max topspin reached");
showSpeed();
}
else if (currentSpeed1 >= 255)
{
Serial.println("Max speed of top motor reached");
showSpeed();
}
else if (currentSpeed2 <= 0)
{
Serial.println("Min speed of bottom motor reached");
showSpeed();
}
}
void addBackspin()
{
if (currentSpeed1 > 0 && currentSpeed2 < 255) //if both motors are capable, diverge speed by spin differential with bottom motor increasing
{
currentSpeed1 -= spinDifferential;
currentSpeed2 += spinDifferential;
analogWrite (LPWM1, currentSpeed1);
analogWrite (LPWM2, currentSpeed2);
showSpeed();
delay(100);
}
else if (currentSpeed1 <= 0 && currentSpeed2 >= 255) //otherwise print that one or both motors are at max spin or max/min speed
{
Serial.println("Max backspin reached");
showSpeed();
}
else if (currentSpeed1 <= 0)
{
Serial.println("Min speed of top motor reached");
showSpeed();
}
else if (currentSpeed2 >= 255)
{
Serial.println("Max speed of bottom motor reached");
showSpeed();
}
}
| true |
da9387f1f41612e78d44db091179eaacf0e3010c | C++ | ChenWendi2001/GAMES101 | /assignment1/src/main.cpp | UTF-8 | 4,563 | 2.9375 | 3 | [] | no_license | #include "Triangle.hpp"
#include "rasterizer.hpp"
#include <eigen3/Eigen/Eigen>
#include <iostream>
#include <opencv2/opencv.hpp>
constexpr double MY_PI = 3.1415926;
Eigen::Matrix4f get_view_matrix(Eigen::Vector3f eye_pos)
{
Eigen::Matrix4f view = Eigen::Matrix4f::Identity();
Eigen::Matrix4f translate;
translate << 1, 0, 0, -eye_pos[0], 0, 1, 0, -eye_pos[1], 0, 0, 1,
-eye_pos[2], 0, 0, 0, 1;
view = translate * view;
return view;
}
Eigen::Matrix4f get_model_matrix(float rotation_angle)
{
Eigen::Matrix4f model = Eigen::Matrix4f::Identity();
// TODO: Implement this function
// Create the model matrix for rotating the triangle around the Z axis.
// Then return it.
rotation_angle = rotation_angle / 180.0 * MY_PI;
model(0,0) = cos(rotation_angle);
model(0,1) = -sin(rotation_angle);
model(1,0) = sin(rotation_angle);
model(1,1) = cos(rotation_angle);
return model;
}
Eigen::Matrix4f get_projection_matrix(float eye_fov, float aspect_ratio,
float zNear, float zFar)
{
// Students will implement this function
Eigen::Matrix4f projection = Eigen::Matrix4f::Identity();
// TODO: Implement this function
// Create the projection matrix for the given parameters.
// Then return it.
Eigen::Matrix4f p_to_o ;
p_to_o << zNear, 0, 0, 0,
0, zNear, 0, 0,
0, 0, zNear+zFar, -zNear*zFar,
0, 0, 1, 0;
float r, l, t, b;
eye_fov = eye_fov/180.0 * MY_PI;
t = tan(eye_fov/2.0) * zNear;
b = -t;
r = t * aspect_ratio;
l = -r;
Eigen::Matrix4f o_1 = Eigen::Matrix4f::Identity(), o_2 = Eigen::Matrix4f::Identity();
o_1(0,3) = -(r+l)/2.0;
o_1(1,3) = -(t+b)/2.0;
o_1(2,3) = -(zNear+zFar)/2.0;
o_2(0,0) = 2.0/(r-l);
o_2(1,1) = 2.0/(t-b);
o_2(2,2) = 2.0/(zNear-zFar);
projection = o_2 * o_1 * p_to_o;
return projection;
}
Eigen::Matrix4f get_rotation (Vector3f axis, float angle){
Eigen::Matrix4f model = Eigen::Matrix4f::Identity();
Eigen::Matrix3f I = Eigen::Matrix3f::Identity(), R, N;
angle = angle /180.0 * MY_PI;
N << 0, -axis[2], axis[1],
axis[2], 0, -axis[0],
-axis[1], axis[0], 0;
R = cos(angle)*I + (1-cos(angle))*axis*axis.adjoint() + sin(angle)*N;
for(int i = 0;i<3;i++){
for(int j = 0;j<3;j++){
model(i,j) = R(i,j);
}
}
return model;
}
int main(int argc, const char** argv)
{
float angle = 0;
bool command_line = false;
std::string filename = "output.png";
if (argc >= 3) {
command_line = true;
angle = std::stof(argv[2]); // -r by default
if (argc == 4) {
filename = std::string(argv[3]);
}
else
return 0;
}
rst::rasterizer r(700, 700);
Eigen::Vector3f eye_pos = {0, 0, 5};
std::vector<Eigen::Vector3f> pos{{2, 0, -2}, {0, 2, -2}, {-2, 0, -2}};
std::vector<Eigen::Vector3i> ind{{0, 1, 2}};
auto pos_id = r.load_positions(pos);
auto ind_id = r.load_indices(ind);
int key = 0;
int frame_count = 0;
if (command_line) {
r.clear(rst::Buffers::Color | rst::Buffers::Depth);
r.set_model(get_model_matrix(angle));
r.set_view(get_view_matrix(eye_pos));
r.set_projection(get_projection_matrix(45, 1, 0.1, 50));
r.draw(pos_id, ind_id, rst::Primitive::Triangle);
cv::Mat image(700, 700, CV_32FC3, r.frame_buffer().data());
image.convertTo(image, CV_8UC3, 1.0f);
cv::imwrite(filename, image);
return 0;
}
while (key != 27) {
r.clear(rst::Buffers::Color | rst::Buffers::Depth);
//r.set_model(get_model_matrix(angle));
r.set_model(get_rotation (Vector3f(0,0,1), angle));
r.set_view(get_view_matrix(eye_pos));
r.set_projection(get_projection_matrix(45, 1, 0.1, 50));
r.draw(pos_id, ind_id, rst::Primitive::Triangle);
cv::Mat image(700, 700, CV_32FC3, r.frame_buffer().data());
image.convertTo(image, CV_8UC3, 1.0f);
cv::imshow("image", image);
key = cv::waitKey(10);
std::cout << "frame count: " << frame_count++ << '\n';
if (key == 'a') {
angle += 10;
}
else if (key == 'd') {
angle -= 10;
}
}
return 0;
}
| true |
83a54252361eb91b312ec4278f0126d9f52be39e | C++ | Ridvmodi/UCA-Apc | /Apc/subString.cpp | UTF-8 | 964 | 3.359375 | 3 | [] | no_license | #include<iostream>
using namespace std;
char* getsubStr(char str[], int startIndex, int endIndex) {
char *subStr = new char[20];
int j = 0;
for(int i = startIndex;i< startIndex + (endIndex - startIndex);i++,j++) {
subStr[j] = str[i];
}
subStr[j] = '\0';
return subStr;
}
int main() {
char str[50], subStr[20];
int i = 0, startIndex, endIndex;
bool flag = false;
cout<<"Enter the string"<<endl;
cin.getline(str, 50);
while(str[i] != '\0') {
if(str[i] == ' ') {
if(flag == true) {
endIndex = i;
cout<<getsubStr(str, startIndex, endIndex)<<endl;
}
flag = false;
} else {
if(flag == false) {
startIndex = i;
flag = true;
}
}
i++;
}
if(str[i] == '\0') {
endIndex = i;
cout<<getsubStr(str, startIndex, endIndex)<<endl;
}
}
| true |
5bbacf76f7551d5b86966b82ce6c2d5bc0301e59 | C++ | remar/cats-cpp | /src/SpriteDefinition.h | UTF-8 | 503 | 2.5625 | 3 | [] | no_license | // -*- mode: c++ -*-
#ifndef SPRITE_DEFINITION_H
#define SPRITE_DEFINITION_H
#include <string>
#include <map>
#include "Animation.h"
namespace Cats {
class SpriteDefinition {
public:
SpriteDefinition(std::string filename);
Animation* GetDefaultAnimation() {return animations[defaultAnimation];}
Animation* GetAnimation(std::string animation) {return animations[animation];}
private:
std::map<std::string,Animation*> animations;
std::string defaultAnimation;
};
}
#endif
| true |
ff4fce5bd01b9e7f36a23b9061501aad1b5e33ae | C++ | rocee/CanvasCV | /tutorials/tut_layout_text.cpp | UTF-8 | 1,916 | 2.78125 | 3 | [
"BSD-3-Clause"
] | permissive | #include <canvascv/canvas.h>
#include <canvascv/widgets/text.h>
#include <canvascv/widgets/verticallayout.h>
#include <canvascv/widgets/horizontallayout.h>
using namespace canvascv;
void help(Canvas &c)
{
static bool showHelp = true;
static string helpMsg =
"Usage:\n"
"=====\n"
"h: toggle usage message\n"
"*: toggle canvas on/off\n"
"q: exit";
if (showHelp) c.setScreenText(helpMsg);
else c.setScreenText("");
showHelp = ! showHelp;
}
int main(int argc, char **argv)
{
--argc;
++argv;
if (! argc)
{
Canvas::fatal("Must get a path to an image as a parameter" , -1);
}
Mat image = imread(argv[0]);
if (image.empty())
{
Canvas::fatal(string("Cannot load image ") + argv[0], -2);
}
Canvas c("LayoutTxt", image.size());
c.enableScreenText(); // see it's documentation
help(c);
namedWindow("LayoutTxt", WINDOW_AUTOSIZE); // disable mouse resize
auto vLayout = VerticalLayout::create(c);
vLayout->setStretchXToParent(true);
vLayout->setStretchYToParent(true);
auto hLayout = HorizontalLayout::create(*vLayout);
hLayout->setLayoutAnchor(Widget::CENTER);
hLayout->setStretchYToParent(true);
auto txt = Text::create(*hLayout, "Target Acquired!");
txt->setLayoutAnchor(Widget::CENTER);
txt->setFontHeight(50);
txt->setOutlineColor(Colors::Red);
txt->setThickness(2);
int key = 0;
Mat out;
do
{
switch (key)
{
case 'h':
help(c);
break;
case '*':
c.setOn(! c.getOn());
break;
}
c.redrawOn(image, out); // draw the canvas on the image copy
imshow("LayoutTxt", out);
key = c.waitKeyEx(); // GUI and callbacks happen here
} while (key != 'q');
destroyAllWindows();
return 0;
}
| true |
be571a5ce3a1906de63c5bc5624f2a4c0444d353 | C++ | OtterBub/2013-2-CPP | /Practice/ConstPointer/main.cpp | UTF-8 | 392 | 3.328125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
const int a = 10;
const int b = 20;
const int value = 10;
const int* ptr1 = &a;
int const* ptr2 = &b;
cout << "value::" << value << endl;
cout << "ptr1::" << *ptr1 << endl;
cout << "ptr2::" << *ptr2 << endl;
// *ptr1 = 20;
ptr2 = ptr1;
// *ptr2 = 15;
int* const ptr3 = &b;
*ptr3 = 30;
// ptr3 = ptr2 ;
return 0;
} | true |
b9c57172cd8179ed9477823d8c196a0e9868aae2 | C++ | Ina1206/Surprise_Party | /Surprise_Party/Surprise_Party/SourceCode/UI/SceneUI/TitleUI/TitleStringUI/CTitleStringUI.h | SHIFT_JIS | 2,702 | 2.671875 | 3 | [] | no_license | #ifndef CTITLE_STRING_UI_H
#define CTITLE_STRING_UI_H
#include "..\..\..\CUI.h"
#include "..\..\Sound\PlaySoundManager\CPlaySoundManager.h"
/*********************************************
* ^CgUINX.
*******************/
class CTitleStringUI
: public CUI
{
public:
CTitleStringUI();
~CTitleStringUI();
//====================萔==========================//.
const D3DXVECTOR3 TITLE_POS = D3DXVECTOR3(40.5f, 90.8f, 0.0f); //^CgW.
const int TITLE_STRING_MAX = 2; //^Cg͍̕ől.
const unsigned int FETCH_FLAG = (1 << 0); //ɍstO.
const unsigned int MOVE_FLAG = (1 << 1); //ړtO.
const unsigned int CONTROL_FLAG = (1 << 2); //tO.
//==============================================//.
void Update(); //XV.
void Render(); //`揈.
//==============擾====================//.
//ɍs̍W.
D3DXVECTOR3 GetFetchGhostPos() const { return m_vFetchGhostPos; }
//ړ~tO.
bool GetStopMoveFlag() const { return m_bStopFlag[m_FetchStringNum]; }
//==============u====================//.
//ړ.
void SetMoveDistance(const float& fDistance) { m_fMoveDistance = fDistance; }
//덷͈.
void SetErrorRange(const float& ErrorRange) { m_fErrorRange = ErrorRange; }
//ړtO.
void SetMoveFlag(const unsigned int& Flag) { m_MoveFlag = Flag; }
//͂̕ɔԍύX.
void SetChangeNextStringNum() { m_FetchStringNum++; }
private:
//==============================================//.
void Init(); //.
void Release(); //.
void ControlPos(); //쎞̍W.
void FetchPos(); //ɍsW.
void Move(); //ړ.
//====================ϐ==========================//.
std::vector<CSpriteUI*> m_pCSpriteUI; //XvCgUI.
std::vector<D3DXVECTOR3> m_vTitlePos; //W.
std::vector<D3DXVECTOR2> m_vTitleUV; //UV.
std::vector<D3DXVECTOR3> m_vBeforeMovePos; //ړO̍W.
std::vector<D3DXVECTOR3> m_vLastPos; //ŏIIȍW.
D3DXVECTOR3 m_vFetchGhostPos; //ɍs̍W.
int m_FetchStringNum; //ɍs͔ԍ.
float m_fMoveDistance; //ړ.
std::vector<bool> m_bStopFlag; //~tO.
float m_fErrorRange; //덷͈.
unsigned int m_MoveFlag; //ړtO.
CPlaySoundManager* m_pCPlaySoundManager; //ĐǗNX.
};
#endif //#ifndef CTITLE_STRING_UI_H. | true |
eb6983a471ba010268403d30daff3f2f57e28179 | C++ | NickTikhomirov/Storagehouses | /StorageShoes.h | UTF-8 | 848 | 2.53125 | 3 | [] | no_license | #pragma once
#include <unordered_map>
#include "ShoesDataForType.h"
#include "Storage.h"
#include <string>
using std::unordered_map;
using std::pair;
using std::string;
//Склад обуви
class StorageShoes: public Storage{
unordered_map<string, ShoesDataForType> contents;
public:
StorageShoes();
~StorageShoes();
//Очистка полей. Возможно, избыточное действие, но не убирать же его, раз написал
void destroy();
//Выводы, унаследованные от склада
void consOut() const noexcept;
void contOut() const noexcept;
//Наследство от склада
int capacityLeft() const noexcept;
bool hasSmallSizes() const noexcept;
string filePut() const noexcept;
void addData();
void stringParser(string);
};
| true |
ba85ac55c602d3d2bff5ce83e5d922ed03f4a785 | C++ | tmud/tortilla | /mudclient/src/logsFormatter.cpp | UTF-8 | 12,386 | 2.515625 | 3 | [] | no_license | #include "stdafx.h"
#include "logsFormatter.h"
#include "mudViewString.h"
#include "propertiesPages/propertiesData.h"
#include "palette256.h"
const tchar* month[12] = { L"Янв", L"Фев", L"Мар", L"Апр", L"Май", L"Июн", L"Июл", L"Авг", L"Сен", L"Окт", L"Ноя", L"Дек" };
LogsFormatter::LogsFormatter(PropertiesData *pd) : hfile(INVALID_HANDLE_VALUE), m_propData(pd)
{
}
LogsFormatter::~LogsFormatter()
{
if (hfile != INVALID_HANDLE_VALUE)
CloseHandle(hfile);
}
void LogsFormatter::checkExist(tstring& filename)
{
tstring name(filename);
tstring ext;
int pos = name.rfind(L'.');
if (pos != -1)
{
ext.assign(name.substr(pos));
name = name.substr(0, pos);
}
tchar buffer[16];
for(int i=0;;++i)
{
tstring tmp(name);
if (i != 0) {
swprintf(buffer, L"(%d)", i);
tmp.append(buffer);
}
tmp.append(ext);
if (GetFileAttributes(tmp.c_str()) == INVALID_FILE_ATTRIBUTES)
{
filename.swap(tmp);
break;
}
}
}
bool LogsFormatter::open(const tstring& filename, PrepareMode pmode)
{
if (hfile == INVALID_HANDLE_VALUE)
{
DWORD mode = (pmode == PM_NEW) ? CREATE_ALWAYS : OPEN_ALWAYS;
hfile = CreateFile(filename.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, mode, FILE_ATTRIBUTE_NORMAL, NULL);
if (hfile == INVALID_HANDLE_VALUE)
return false;
DWORD hsize = 0;
DWORD size = GetFileSize(hfile, &hsize);
if (hsize != 0) {
CloseHandle(hfile);
hfile = INVALID_HANDLE_VALUE;
return false;
}
}
m_mode = pmode;
m_filename = filename;
return true;
}
void LogsFormatter::close()
{
CloseHandle(hfile);
hfile = INVALID_HANDLE_VALUE;
}
void LogsFormatter::writeString(const MudViewString* str)
{
std::string data;
convertString(str, &data);
write(data);
}
void LogsFormatter::flushStrings()
{
FlushFileBuffers(hfile);
}
void LogsFormatter::convertString(const MudViewString* str, std::string* out)
{
assert(false);
}
void LogsFormatter::write(const std::string &data)
{
DWORD towrite = data.length();
DWORD written = 0;
WriteFile(hfile, data.c_str(), towrite, &written, NULL);
}
void LogsFormatter::getHeader(std::string* out)
{
tstring tu;
tu.assign(m_propData->title);
size_t pos = tu.rfind(L"-");
if (pos != tstring::npos)
tu = tu.substr(0, pos);
SYSTEMTIME tm;
GetLocalTime(&tm);
tchar buffer[64];
swprintf(buffer, L"- %d %s %d, %d:%02d:%02d\r\n", tm.wDay, month[tm.wMonth], tm.wYear, tm.wHour, tm.wMinute, tm.wSecond);
tu.append(buffer);
out->assign(TW2U(tu.c_str()));
}
LogsFormatterHtml::LogsFormatterHtml(PropertiesData *pd) : LogsFormatter(pd)
{
m_palette = new Palette256(pd);
m_buffer.alloc(4096);
m_color_buffer.alloc(10);
m_color_buffer2.alloc(10);
}
LogsFormatterHtml::~LogsFormatterHtml()
{
delete m_palette;
}
void LogsFormatterHtml::close()
{
std::string finish;
getHeader(&finish);
std::string closed(TW2U(L"Лог закрыт.\r\n"));
if (hfile != INVALID_HANDLE_VALUE)
{
write(finish);
write(closed);
std::string close = "</pre></body></html>";
write(close);
}
LogsFormatter::close();
}
void LogsFormatterHtml::normFilename(tstring &filename)
{
int pos = filename.rfind(L'.');
if (pos == -1)
filename.append(L".html");
else
{
tstring ext(filename.substr(pos + 1));
if (ext != L"htm" && ext != L"html")
filename.append(L".html");
}
}
bool LogsFormatterHtml::prepare()
{
bool result = true;
if (m_mode == PM_APPEND)
{
DWORD inbuffer = 0;
DWORD hsize = 0;
DWORD lsize = GetFileSize(hfile, &hsize);
unsigned __int64 size = hsize; size <<= 32; size |= lsize;
DWORD buffer_len = m_buffer.getSize();
char *buffer = m_buffer.getData();
int pos = 0;
int fileptr = -1;
while (size > 0)
{
DWORD toread = buffer_len - inbuffer;
if (toread > size) toread = (DWORD)size;
char *p = buffer + inbuffer;
DWORD readed = 0;
if (!ReadFile(hfile, p, toread, &readed, NULL) || toread != readed)
{
result = false; break;
}
size -= toread;
toread += inbuffer;
// find teg in data
std::string teg("</body>");
int teg_len = teg.length();
char *s = buffer;
char *e = s + toread;
while (s != e)
{
int len = e - s;
char *m = (char*)memchr(s, teg.at(0), len);
if (m && (e - m) >= teg_len && !memcmp(teg.c_str(), m, teg_len))
{
fileptr = pos + (m - buffer);
break;
}
if (!m) break;
s = s + (m - s) + 1;
}
if (fileptr != -1)
break;
pos += (toread - teg_len);
inbuffer = teg_len;
memcpy(buffer, buffer + (toread - teg_len), teg_len);
}
if (fileptr == -1)
result = false;
else
{
SetFilePointer(hfile, fileptr, NULL, FILE_BEGIN);
SetEndOfFile(hfile);
write("<pre>\r\n");
std::string date;
getHeader(&date);
write(date.c_str());
}
}
if (m_mode == PM_NEW || !result)
{
SetFilePointer(hfile, 0, NULL, FILE_BEGIN);
SetEndOfFile(hfile);
char *buffer = m_buffer.getData();
std::string header("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf8\">\r\n<title>Tortilla Mud Client log");
header.append("</title>\r\n</head>\r\n<style type=\"text/css\">\r\n");
TW2U font(m_propData->font_name.c_str());
sprintf(buffer, "body{ background-color: %s; color: %s; font-size: %dpt; font-weight: %d; font-family: %s }\r\n",
color(m_propData->bkgnd), color2(m_palette->getColor(7)), m_propData->font_heigth, m_propData->font_bold, (const char*)font);
header.append(buffer);
for (int i = 0; i < 16; ++i)
{
COLORREF c = m_palette->getColor(i);
sprintf(buffer, ".c%d { color: %s } .b%d { background: %s }\r\n", i, color(c), i, color2(i == 0 ? m_propData->bkgnd : c));
header.append(buffer);
}
header.append(".u { text-decoration: underline; }\r\n.b { border: 1px solid; }\r\n.i { font-style: italic; }\r\n");
header.append("</style>\r\n<body><pre>");
write(header);
std::string date;
getHeader(&date);
write(date);
}
return true;
}
void LogsFormatterHtml::convertString(const MudViewString* str, std::string* out)
{
char* buffer = m_buffer.getData();
for (int i = 0, e = str->blocks.size(); i < e; ++i)
{
const tstring &s = str->blocks[i].string;
m_converter.convert(s.c_str(), s.length());
if (isOnlySpaces(s)) {
out->append(m_converter);
continue;
}
const MudViewStringParams &p = str->blocks[i].params;
std::string eff;
if (p.italic_status) eff.append("i ");
if (p.underline_status) eff.append("u ");
if (p.blink_status) eff.append("b ");
if (!eff.empty())
{
int len = eff.length();
eff = eff.substr(0, len - 1);
}
if (p.use_ext_colors)
{
std::string text(m_converter);
if (!eff.empty())
{
sprintf(buffer, "<a class=\"%s\">%s</a>", eff.c_str(), text.c_str());
text.assign(buffer);
}
COLORREF c1 = p.ext_text_color; COLORREF c2 = p.ext_bkg_color;
if (p.reverse_video) { c1 = p.ext_bkg_color; c2 = p.ext_text_color; }
sprintf(buffer, "<span style=\"color:%s;background-color:%s\">%s</span>", color(c1), color2(c2), text.c_str());
}
else
{
tbyte txt = p.text_color;
tbyte bkg = p.bkg_color;
if (p.reverse_video) { tbyte x = txt; txt = bkg; bkg = x; }
if (txt <= 7 && p.intensive_status) { txt += 8; } // txt >= 0 always
if (txt < 16 && p.bkg_color < 16)
{
if (!eff.empty())
sprintf(buffer, "%s c%d", eff.c_str(), txt);
else
sprintf(buffer, "c%d", txt);
std::string tmp(buffer);
if (p.bkg_color != 0) {
sprintf(buffer, "%s b%d", tmp.c_str(), bkg);
tmp.assign(buffer);
}
sprintf(buffer, "<a class=\"%s\">%s</a>", tmp.c_str(), (const char*)m_converter);
}
else
{
std::string text(m_converter);
if (!eff.empty()) {
sprintf(buffer, "<a class=\"%s\">%s</a>", eff.c_str(), text.c_str());
text.assign(buffer);
}
COLORREF c1 = m_palette->getColor(txt);
if (p.bkg_color != 0) {
COLORREF c2 = m_palette->getColor(p.bkg_color);
sprintf(buffer, "<span style=\"color:%s;background-color:%s\">%s</span>", color(c1), color2(c2), text.c_str());
} else {
sprintf(buffer, "<span style=\"color:%s\">%s</span>", color(c1), text.c_str());
}
}
}
out->append(buffer);
}
out->append("\r\n");
}
const char* LogsFormatterHtml::color(COLORREF c)
{
char *buffer = m_color_buffer.getData();
sprintf(buffer, "#%.2x%.2x%.2x", GetRValue(c), GetGValue(c), GetBValue(c));
return buffer;
}
const char* LogsFormatterHtml::color2(COLORREF c)
{
char *buffer = m_color_buffer2.getData();
sprintf(buffer, "#%.2x%.2x%.2x", GetRValue(c), GetGValue(c), GetBValue(c));
return buffer;
}
LogsFormatterTxt::LogsFormatterTxt(PropertiesData *pd) : LogsFormatter(pd)
{
}
LogsFormatterTxt::~LogsFormatterTxt()
{
}
void LogsFormatterTxt::close()
{
std::string finish;
getHeader(&finish);
std::string closed(TW2U(L"Лог закрыт.\r\n"));
if (hfile != INVALID_HANDLE_VALUE)
{
write(finish);
write(closed);
}
LogsFormatter::close();
}
void LogsFormatterTxt::normFilename(tstring &filename)
{
int pos = filename.rfind(L'.');
if (pos == -1)
filename.append(L".txt");
else
{
tstring ext(filename.substr(pos + 1));
if (ext != L"txt")
filename.append(L".text");
}
}
bool LogsFormatterTxt::prepare()
{
if (m_mode == PM_APPEND)
{
// append
::SetFilePointer(hfile, 0, NULL, FILE_END);
std::string bin;
DWORD hsize = 0;
DWORD size = GetFileSize(hfile, &hsize);
if (hsize == 0 && size == 0)
{
unsigned char bom[4] = { 0xEF, 0xBB, 0xBF, 0 };
bin.append((char*)bom);
}
std::string date;
getHeader(&date);
bin.append(date);
write(bin);
}
if (m_mode == PM_NEW)
{ // new
SetFilePointer(hfile, 0, NULL, FILE_BEGIN);
SetEndOfFile(hfile);
unsigned char bom[4] = { 0xEF, 0xBB, 0xBF, 0 };
std::string bin;
bin.append((char*)bom);
std::string date;
getHeader(&date);
bin.append(date);
write(bin);
}
return true;
}
void LogsFormatterTxt::convertString(const MudViewString* str, std::string* out)
{
tstring s;
str->getText(&s);
m_converter.convert(s.c_str(), s.length());
out->assign(m_converter);
out->append("\r\n");
}
| true |
eb6a6d028e4a3f1db1f99c6cee96475e692163e2 | C++ | geroge-gao/Algorithm | /Coding Interviews/10_二进制中1的个数.cpp | UTF-8 | 279 | 3.078125 | 3 | [] | no_license | //暴力求解,没有考虑到异常
int numberOf1(int n)
{
int count=0;
whille(n)
{
if(n&1)
count++;
n=n>>1;
}
}
//改进版
int numberOf1(int n)
{
int count=0;
unsigned int flag=1;
while(flag)
{
if(n&flag)
count++;
flag=flag<<1;
}
return count;
} | true |
d4723517b73a4b9344e4658fac3d3ff32201e94a | C++ | baharkholdisabeti/cc3k-villain | /Observer.h | UTF-8 | 375 | 2.640625 | 3 | [] | no_license | #ifndef _OBSERVER_H_
#define _OBSERVER_H_
#include <memory>
class Tile;
class Ground;
class Observer {
public:
// Pass the Subject that called the notify method.
virtual void notify( std::shared_ptr<Tile> whoNotified ){}
virtual void notify( std::shared_ptr<Ground> whoNotified ){}
virtual void notify() = 0;
virtual ~Observer() = default;
};
#endif
| true |
31f01dfc943ee3a7c67e4c49d7ed36c068256c65 | C++ | blacksea3/leetcode | /cpp/leetcode/529. minesweeper.cpp | UTF-8 | 3,633 | 3.1875 | 3 | [] | no_license | #include "public.h"
//96ms, 58.02%, the find_num_neighbour_bombs shall be optimized :(
//DFS problem,
// there are no special tricks..
class Solution {
private:
//if return the num of neighbour_bombs, note board[line][column] shall not be bomb
int find_num_neighbour_bombs(vector<vector<char>>& board, const int& line, const int& column)
{
//if (board[line][column] == 'M') return -1;
int res = 0;
if (line > 0)
{
if (column > 0) if (board[line - 1][column-1] == 'M') res++;
if (column < board[0].size()-1) if (board[line - 1][column + 1] == 'M') res++;
if (board[line-1][column] == 'M') res++;
}
if (line < board.size() - 1)
{
if (column > 0) if (board[line + 1][column - 1] == 'M') res++;
if (column < board[0].size() - 1) if (board[line + 1][column + 1] == 'M') res++;
if (board[line + 1][column] == 'M') res++;
}
if (column > 0) if (board[line][column - 1] == 'M') res++;
if (column < board[0].size() - 1) if (board[line][column + 1] == 'M') res++;
return res;
}
void recu_update_board(vector<vector<char>>& board, const int& line, const int& column)
{
int tempres = find_num_neighbour_bombs(board, line, column);
if (tempres == 0)
{
board[line][column] = 'B';
if (line > 0)
{
if (column > 0) if (board[line - 1][column - 1] == 'E') recu_update_board(board, line - 1, column - 1);
if (column < board[0].size() - 1) if (board[line - 1][column + 1] == 'E') recu_update_board(board, line - 1, column + 1);
if (board[line - 1][column] == 'E') recu_update_board(board, line - 1, column);
}
if (line < board.size() - 1)
{
if (column > 0) if (board[line + 1][column - 1] == 'E') recu_update_board(board, line + 1, column - 1);
if (column < board[0].size() - 1) if (board[line + 1][column + 1] == 'E') recu_update_board(board, line + 1, column + 1);
if (board[line + 1][column] == 'E') recu_update_board(board, line + 1, column);
}
if (column > 0) if (board[line][column - 1] == 'E') recu_update_board(board, line, column - 1);
if (column < board[0].size() - 1) if (board[line][column + 1] == 'E') recu_update_board(board, line, column + 1);
}
else
{
board[line][column] = tempres + '0';
}
}
public:
vector<vector<char>> updateBoard(vector<vector<char>>& board, vector<int>& click) {
int line = click[0];
int column = click[1];
if (board[line][column] == 'M') //only the top call can enter it!
{
board[line][column] = 'X';
return board;
}
else
{
int tempres = find_num_neighbour_bombs(board, line, column);
if (tempres == 0)
{
board[line][column] = 'B';
if (line > 0)
{
if (column > 0) if (board[line - 1][column - 1] == 'E') recu_update_board(board, line - 1, column - 1);
if (column < board[0].size() - 1) if (board[line - 1][column + 1] == 'E') recu_update_board(board, line - 1, column + 1);
if (board[line - 1][column] == 'E') recu_update_board(board, line - 1, column);
}
if (line < board.size() - 1)
{
if (column > 0) if (board[line + 1][column - 1] == 'E') recu_update_board(board, line + 1, column - 1);
if (column < board[0].size() - 1) if (board[line + 1][column + 1] == 'E') recu_update_board(board, line + 1, column + 1);
if (board[line + 1][column] == 'E') recu_update_board(board, line + 1, column);
}
if (column > 0) if (board[line][column - 1] == 'E') recu_update_board(board, line, column - 1);
if (column < board[0].size() - 1) if (board[line][column + 1] == 'E') recu_update_board(board, line, column + 1);
}
else
{
board[line][column] = tempres + '0';
}
}
return board;
}
};
| true |
21b5289b5e3054f214f6c0887cbd7ee46ecf1a10 | C++ | PoRTiLo/IPB | /zaloha/3/geoloc.cc | UTF-8 | 5,981 | 2.71875 | 3 | [] | no_license | #include "geoloc.h"
Geoloc::Geoloc( Tag* tag )
{
clear();
parserTag( tag );
}
float Geoloc::accuracy( void ) {
return this->m_accuracy;
}
void Geoloc::accuracy( const float accuracy ) {
this->m_accuracy = accuracy;
}
float Geoloc::alt( void ) {
return this->m_alt;
}
void Geoloc::alt( const float alt ) {
this->m_alt = alt;
}
std::string Geoloc::area( void ) {
return this->m_area;
}
void Geoloc::area( const std::string area ) {
this->m_area = area;
}
float Geoloc::bearing( void ) {
return this->m_bearing;
}
void Geoloc::bearing( float bearing ) {
this->m_bearing = bearing;
}
std::string Geoloc::building( void ) {
return this->m_building;
}
void Geoloc::building( const std::string building ) {
this->m_building = building;
}
std::string Geoloc::country( void ) {
return this->m_country;
}
void Geoloc::country( const std::string country ) {
this->m_country = country;
}
std::string Geoloc::countrycode( void ) {
return this->m_countrycode;
}
void Geoloc::countrycode( const std::string countrycode ) {
this->m_countrycode = countrycode;
}
std::string Geoloc::datum( void ) {
return this->m_datum;
}
void Geoloc::datum( const std::string datum ) {
this->m_datum = datum;
}
std::string Geoloc::description( void ) {
return this->m_description;
}
void Geoloc::description( const std::string description ) {
this->m_description = description;
}
float Geoloc::error( void ) {
return this->m_error;
}
void Geoloc::error( const float error ) {
this->m_error = error;
}
std::string Geoloc::floor( void ) {
return this->m_floor;
}
void Geoloc::floor( const std::string floor ) {
this->m_floor = floor;
}
float Geoloc::lat( void ) {
return this->m_lat;
}
void Geoloc::lat( const float lat ) {
this->m_lat = lat;
}
std::string Geoloc::locality( void ) {
return this->m_locality;
}
void Geoloc::locality( const std::string locality ) {
this->m_locality = locality;
}
float Geoloc::lon( void ) {
return this->m_lon;
}
void Geoloc::lon( const float lon ) {
this->m_lon = lon;
}
std::string Geoloc::postalcode( void ) {
return this->m_postalcode;
}
void Geoloc::postalcode( const std::string postalcode ) {
this->m_postalcode = postalcode;
}
std::string Geoloc::region( void ) {
return this->m_region;
}
void Geoloc::region( const std::string region ) {
this->m_region = region;
}
std::string Geoloc::street( void ) {
return this->m_street;
}
void Geoloc::street( const std::string street ) {
this->m_street = street;
}
std::string Geoloc::text( void ) {
return this->m_text;
}
void Geoloc::text( const std::string text ) {
this->m_text = text;
}
std::string Geoloc::timestamp( void ) {
return this->m_timestamp;
}
void Geoloc::timestamp( const std::string timestamp ) {
this->m_timestamp = timestamp;
}
float Geoloc::speed( void ) {
return this->m_speed;
}
void Geoloc::speed( const float speed ) {
this->m_speed = speed;
}
std::string Geoloc::uri( void ) {
return this->m_uri;
}
std::string Geoloc::room( void ) {
return this->m_room;
}
void Geoloc::room( const std::string room ) {
this->m_room = room;
}
void Geoloc::uri( const std::string uri ) {
this->m_uri = uri;
}
std::string Geoloc::id( void ) {
return this->m_id;
}
void Geoloc::id( const std::string id ) {
this->m_id = id;
}
JID Geoloc::jid( void ) {
return this->m_jid;
}
void Geoloc::jid( const std::string jid ) {
this->m_jid.setJID(jid);
}
void Geoloc::clear( void ) {
this->m_accuracy = 0.0;
this->m_alt = 0.0;
this->m_bearing = 0.0;
this->m_error = 0.0;
this->m_lat = 0.0;
this->m_lon = 0.0;
this->m_speed = 0.0;
}
void Geoloc::parserTag( const Tag * tag ) {
if( tag->hasChild("item" ))
{
Tag * p_tag1 = tag->findChild("item")->clone();
id( p_tag1->findAttribute("id") );
Tag * p_tag = p_tag1->findChild("geoloc")->clone();
if( !p_tag->children().empty() )
{
if( p_tag->findChild("accuracy") )
accuracy( stringToFloat( (p_tag->findChild("accuracy"))->cdata() ));
if( p_tag->findChild("alt") )
alt( stringToFloat((p_tag->findChild("alt"))->cdata() ));
if( p_tag->findChild("area") )
area( (p_tag->findChild("area"))->cdata() );
if( p_tag->findChild("bearing") )
bearing( stringToFloat( (p_tag->findChild("bearing"))->cdata() ));
if( p_tag->findChild("building") )
building( (p_tag->findChild("building"))->cdata() );
if( p_tag->findChild("country") )
country( (p_tag->findChild("country"))->cdata() );
if( p_tag->findChild("countrycode") )
countrycode( (p_tag->findChild("countrycode"))->cdata() );
if( p_tag->findChild("datum") )
datum( (p_tag->findChild("datum"))->cdata() );
if( p_tag->findChild("description") )
description( (p_tag->findChild("description"))->cdata() );
if( p_tag->findChild("error") )
error( stringToFloat( (p_tag->findChild("error"))->cdata() ));
if( p_tag->findChild("floor") )
floor( (p_tag->findChild("floor"))->cdata() );
if( p_tag->findChild("lat") )
lat( stringToFloat((p_tag->findChild("lat"))->cdata() ));
if( p_tag->findChild("locality") )
locality( (p_tag->findChild("locality"))->cdata() );
if( p_tag->findChild("lon") )
lon( stringToFloat((p_tag->findChild("lon"))->cdata() ));
if( p_tag->findChild("postalcode") )
postalcode( (p_tag->findChild("postalcode"))->cdata() );
if( p_tag->findChild("region") )
region( (p_tag->findChild("region"))->cdata() );
if( p_tag->findChild("room") )
room( (p_tag->findChild("room"))->cdata() );
if( p_tag->findChild("speed") )
speed( stringToFloat((p_tag->findChild("speed"))->cdata() ));
if( p_tag->findChild("street") )
street( (p_tag->findChild("street"))->cdata() );
if( p_tag->findChild("text") )
text( (p_tag->findChild("text"))->cdata() );
if( p_tag->findChild("timestamp") )
timestamp( (p_tag->findChild("timestamp"))->cdata() );
if( p_tag->findChild("uri") )
uri( (p_tag->findChild("uri"))->cdata() );
}
}
}
| true |
17ff868e31478545a75be0b7e9ad128d2b329617 | C++ | squirrelClare/OnlineWrittenExamination | /mogu2/main.cpp | UTF-8 | 284 | 2.65625 | 3 | [] | no_license |
#include <iostream>
#include <cstdlib>
#include <vector>
using namespace std;
int getIndex(string str){
string tmp=str;
return 0;
}
int main()
{
string s="sds12adasdassa";
string str(s.rbegin(),s.rend());
s.insert(0,"a");
cout<<str<<endl;
return 0;
}
| true |
dd91ae1afa075ef43d303e6c6faf1007e98bf7b6 | C++ | antOnioOnio/Algoritmica | /practica2/divideMax.cpp | UTF-8 | 3,177 | 3.546875 | 4 | [] | no_license |
#include <iostream>
#include <cstdlib> // Para generación de números pseudoaleatorios
//#include <pair>
using namespace std;
pair<int, int > MaxMin(int *vector , int tam){
pair<int, int>resultado;
pair<int, int>iz;
pair<int, int>der;
//pair<int, int>segundo_resu;
int maximo , minimo = 200 ;
int pos;
if ( tam == 1){
if (maximo < vector[tam-1]){
maximo = vector[tam-1];
}
if (minimo > vector[tam-1]){
minimo = vector[tam-1];
}
resultado.second = maximo;
resultado.first = minimo;
cout << "minimo actual -->" <<resultado.first << " maximo actual -->" <<resultado.second <<endl;
}
else{
iz=MaxMin(vector,tam/2);
der=MaxMin(vector + tam/2, tam - tam/2);
if(iz.first<der.first){
resultado.first = iz.first;
}
else{
resultado.first = der.first;
}
if( der.second >der.second){
resultado.second = der.first;
}
else{
resultado.second = iz.first;
}
return resultado;
}
return resultado;
}
void intercambiar(int &a, int &b){
int aux = a;
a=b;
b = aux;
}
int pivote(int *v, int i, int j){
int piv, k, l;
k =i;
piv = v[i];
l = j+1;
do{
k = k+1;
}while (v[k] <= piv && k<j);
do{
l = l-1;
}while(v[l] > piv);
while (k<l){
intercambiar(v[k], v[l]);
do{
k=k+1;
}while(v[k] <= piv);
do{
l = l-1;
}while (v[l]>l);
}
intercambiar(v[i], v[l]);
return l;
}
void zapatero(int *zapatos, int *ninios, int i, int n){
int pivote_zapatos, pivote_ninios;
if (i < n){
pivote_zapatos = pivote(zapatos,i, n);
pivote_ninios = pivote(ninios, i, n);
zapatero(zapatos,ninios,i,pivote_zapatos-1);
zapatero(zapatos,ninios,pivote_zapatos+1, n);
zapatero(zapatos,ninios,i,pivote_ninios-1);
zapatero(zapatos,ninios,pivote_ninios+1,n);
}
}
int main (){
// pair<int, int >prueba;
// int vector_prueba[10];
// srand(time(0));
// for (int i = 0 ; i< 10 ; i++){
// vector_prueba[i]=rand() % 100;
// cout << vector_prueba[i]<< endl;
// }
// prueba= MaxMin(vector_prueba, 10);
// cout << "el minimo es " <<prueba.first << endl;
// cout << "el maximo es " <<prueba.second << endl;
// Generación del vector aleatorio
int *Z = new int[20]; // Reserva de memoria
int *P = new int[20]; // Reserva de memoria
int val;
srand(time(0)); // Inicialización del generador de números pseudoaleatorios
for (int i = 0; i < 20; i++){ // Recorrer vector
val = (rand() % 10) ; // Generar aleatorio [0,vmax[
Z[i] = val;
P[i] = val;
cout << Z[i] <<" " << P[i] << endl;
}
random_shuffle(&Z[0], &Z[20]);
random_shuffle(&P[0], &P[20]);
//int piv = Pivote(Z, 0, tam);
for(int i = 0; i < 20; ++i){
cout <<Z[i] << " " << P[i] << endl;
}
cout << "y ahora llamo a la funcion \n\n"<< endl;
zapatero(Z, P, 0, 20);
for(int i = 0; i < 20; ++i){
cout << Z[i] << " " << P[i] << endl;
}
delete[] Z; // Liberamos memoria dinámica
delete[] P; // Liberamos memoria dinámica
}
| true |
ed1a62fb45f8d00fbb315ff8e068339e82d9a25f | C++ | aruizgarciarojas/tc1031 | /00_templates/using_vectors.cpp | UTF-8 | 361 | 3.078125 | 3 | [] | no_license | #include <iostream>
#include <vector>
int main(int argc, char* argv[]) {
int n;
std::string input;
std::vector<std::string> words;
std::cin >> n;
for (int i = 0; i < n; i++) {
std::cin >> input;
words.push_back(input);
}
for (int i = 0; i < words.size(); i++) {
std::cout << words[i] << "\n";
}
return 0;
}
| true |
9c7302546e94557d90b95dd76c3f4e28e0c85451 | C++ | bcmissrain/HeroCat | /100Hero/Classes/Utils/ImageDoctor.cpp | UTF-8 | 2,075 | 2.84375 | 3 | [
"MIT"
] | permissive | #include "ImageDoctor.h"
USING_NS_CC;
bool ImageDoctor::ifSupport(std::string filePath)
{
if (!FileUtils::getInstance()->isFileExist(filePath))
{
return false;
}
Data data = FileUtils::getInstance()->getDataFromFile(filePath);
if (data.isNull())
{
return false;
}
Format fileType = detectFormat(data.getBytes(), data.getSize());
if (fileType == Format::UNKNOWN)
{
return false;
}
return true;
}
ImageDoctor::Format ImageDoctor::detectFormat(const unsigned char * data, ssize_t dataLen)
{
if (isPng(data, dataLen))
{
return Format::PNG;
}
else if (isJpg(data, dataLen))
{
return Format::JPG;
}
else if (isTiff(data, dataLen))
{
return Format::TIFF;
}
else if (isWebp(data, dataLen))
{
return Format::WEBP;
}
else
{
return Format::UNKNOWN;
}
}
bool ImageDoctor::isPng(const unsigned char * data, ssize_t dataLen)
{
if (dataLen <= 8)
{
return false;
}
static const unsigned char PNG_SIGNATURE[] = { 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a };
return memcmp(PNG_SIGNATURE, data, sizeof(PNG_SIGNATURE)) == 0;
}
bool ImageDoctor::isJpg(const unsigned char * data, ssize_t dataLen)
{
if (dataLen <= 4)
{
return false;
}
static const unsigned char JPG_SOI[] = { 0xFF, 0xD8 };
return memcmp(data, JPG_SOI, 2) == 0;
}
bool ImageDoctor::isTiff(const unsigned char * data, ssize_t dataLen)
{
if (dataLen <= 4)
{
return false;
}
static const char* TIFF_II = "II";
static const char* TIFF_MM = "MM";
return (memcmp(data, TIFF_II, 2) == 0 && *(static_cast<const unsigned char*>(data)+2) == 42 && *(static_cast<const unsigned char*>(data)+3) == 0) ||
(memcmp(data, TIFF_MM, 2) == 0 && *(static_cast<const unsigned char*>(data)+2) == 0 && *(static_cast<const unsigned char*>(data)+3) == 42);
}
bool ImageDoctor::isWebp(const unsigned char * data, ssize_t dataLen)
{
if (dataLen <= 12)
{
return false;
}
static const char* WEBP_RIFF = "RIFF";
static const char* WEBP_WEBP = "WEBP";
return memcmp(data, WEBP_RIFF, 4) == 0
&& memcmp(static_cast<const unsigned char*>(data)+8, WEBP_WEBP, 4) == 0;
} | true |
3f4a9614f8d26cb5b6922165c51747d88d5208bc | C++ | cynicconn/Conntendo | /Conntendo/Source/viewer.cpp | UTF-8 | 6,955 | 2.640625 | 3 | [] | no_license | #include "viewer.h"
// Conntendo
#include "ppu.h"
#include "palette.h"
#include "emulator.h"
namespace Viewer
{
// Debug Viewer Buffers
u32 nameTableBuffer[WIDTH_x2 * HEIGHT_x2]; // Screen Buffer 512x480
u32 patternTableBuffer[WIDTH * WIDTH]; // Screen Buffer 256x256
// Draw Tile from NameTable
void DebugDrawTile(int x, int y, u16 ntData, u16 attrData)
{
u16 bgShiftL = 0;
u16 bgShiftH = 0;
u8 bgL = 0;
u8 bgH = 0;
u8 bgAddr = 0;
for (int i = 0; i < 8; i++) // VERT
{
int iter = (i == 0) ? 0 : (i+1); // neccessary to grab first row
// Fetch low and high order byte of an 8x1 pixel sliver
bool bgTableSelected = (PPU::DebugReadMemory(0x2000) & 0x10);
u16 bgTableAddress = bgTableSelected ? K_4 : 0;
u16 bgAddr = bgTableAddress + (ntData * 16) + iter;
bgL = PPU::DebugReadMemory(bgAddr);
bgH = PPU::DebugReadMemory(bgAddr+8);
// Fill bg Low and High with first two lines
if (i == 0)
{
bgShiftL = bgL << 8;
bgShiftH = bgH << 8;
bgAddr = bgTableAddress + (ntData * 16) + 1;
bgL = PPU::DebugReadMemory(bgAddr);
bgH = PPU::DebugReadMemory(bgAddr + 8);
}
bgShiftL = (bgShiftL & 0xFF00) | bgL;
bgShiftH = (bgShiftH & 0xFF00) | bgH;
for (int j = 0; j < 8; j++) // HOR
{
u8 palette = 0;
int yOffset = (i + (y * 8));
int tileOffset = (WIDTH_x2 * yOffset);
int locOffset = (x * 8) + j;
palette = (NTH_BIT(bgShiftH, 15) << 1) | NTH_BIT(bgShiftL, 15); // Get TileMap Data
if (palette)
{
palette |= attrData << 2; // 4 Bit Color
}
bgShiftL <<= 1;
bgShiftH <<= 1;
// Color Pixel
u8 colorIndex = PPU::DebugReadMemory(MEMMAP_PALETTE + palette);
nameTableBuffer[tileOffset + locOffset] = Palette::GetColor(colorIndex);
} // for
} // for
} // DebugDrawTile()
// Grab from Attribute Table
u8 GrabAttribute( u16 attrTable, int tileX, int tileY )
{
int attrAddr = attrTable + ((tileY >> 2) << 3) + (tileX >> 2);
u8 attrVal = PPU::DebugReadMemory(attrAddr);
// Shift Attribute based on Quadrant
int corner = ((tileY & 2) << 1) + (tileX & 2);
attrVal &= (3 << corner);
attrVal >>= corner;
return attrVal;
} // GrabAttribute()
void DrawNametable(int xOff, int yOff, u16 nameTable, u16 attrTable)
{
int nIter = 0;
for (int v = 0; v < 30; v++) // Vert
{
for (int h = 0; h < 32; h++) // Hor
{
u16 tileAddr = nameTable | (nIter & 0x0FFF);
u8 ntData = PPU::DebugReadMemory(tileAddr);
u8 attrData = GrabAttribute(attrTable, h, v);
DebugDrawTile((xOff + h), (yOff + v), ntData, attrData);
nIter++;
} // for
} // for
} // DrawNametable()
// Draw Tile from Pattern Table
void DebugDrawTilePT(int offset, u8 lowTileData, u8 highTileData)
{
for (int i = 0; i < 8; i++)
{
u8 colorIndex = (lowTileData & 0x01) + ((highTileData & 0x01) << 1);
lowTileData >>= 1;
highTileData >>= 1;
u8 index = GrabColorFromPalette(false, 0, colorIndex);
patternTableBuffer[offset + (8 - i)] = Palette::GetColor(index);
} // for
} // DebugDrawTilePT()
void DrawPatternTable(int xOff, int yOff, bool isLeft)
{
u16 patternTab = isLeft ? 0 : K_4;
u16 tableOffset = isLeft ? 0 : 128;
for (int h = 0; h < 16; h++) // VERT
{
for (int i = 0; i < 16; i++) // HOR
{
for (int j = 0; j < 8; j++) // Tile Row
{
u16 lowPlaneAddr = patternTab + j + (i * 16) + (WIDTH * h);
u16 highPlaneAddr = lowPlaneAddr + 8;
u8 lowTileData = PPU:: DebugReadMemory(lowPlaneAddr);
u8 highTileData = PPU:: DebugReadMemory(highPlaneAddr);
int offset = tableOffset + ((WIDTH * 8) * h) + (WIDTH * j) + (i * 8);
DebugDrawTilePT(offset, lowTileData, highTileData);
}
} // for
} // for
} // DrawPatternTable()
// Draw an nxn Solid Colored Tile
void DebugDrawSolidTile(u8 row, u8 column, u32 color, u8 size)
{
int offset = (row*K_2) + (column*size);
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
int row = i * 256;
int pos = offset + row + j;
patternTableBuffer[pos] = color;
}
} // for
} // DebugDrawSolidTile()
// grab one of four color indices from background palette
u8 GrabColorFromPalette(bool forSprite, u8 paletteIndex, u8 colorIndex)
{
// check if out of range
if (paletteIndex < 0 || paletteIndex > 3 || colorIndex < 0 || colorIndex > 3)
{
return PALETTE_BLACK; // Last Color
}
paletteIndex += (forSprite) ? 0x0C : 0; // offset to Sprite Palettes
u16 paletteAddress = MEMMAP_PALETTE + paletteIndex + colorIndex;
return PPU:: DebugReadMemory(paletteAddress);
} // GrabColorFromPalette()
// Draw the Color Palettes (4 Colors each)
void PreviewColorPalettes()
{
u16 address = MEMMAP_PALETTE;
int column = 1;
int row = 17;
u8 tileSize = 12;
u32 universalBGColor = Palette::GetColor(PPU:: DebugReadMemory(MEMMAP_PALETTE));
for (int pal = 0; pal < 8; pal++) // 4 Background Palettes, 4 Sprite Palettes
{
for (int col = 0; col < 4; col++) // 3 unique per palette
{
u8 palette = PPU:: DebugReadMemory(address + col);
u32 color = (col == 0) ? universalBGColor : Palette::GetColor(palette);
DebugDrawSolidTile(row, column, color, tileSize);
column++;
} // for
column++;
address += 0x04;
if (pal == 3) // New row for Sprite Palettes
{
column = 1;
row += 2;
}
} // for
} // PreviewColorPalettes()
// Draw the two Pattern Tables and Color Palettes
void DrawPatternTableViewer()
{
DrawPatternTable(0, 0, true); // Pattern Table 0
DrawPatternTable(0, 0, false); // Pattern Table 1
PreviewColorPalettes();
Emulator::NewDebugFrame(patternTableBuffer, false);
} // DrawPatternTableViewer()
// Render the four Nametables
void DrawNametableViewer()
{
DrawNametable(0, 0, 0x2000, 0x23C0); // Top Left
DrawNametable(32, 0, 0x2400, 0x27C0); // Top Right
DrawNametable(0, 30, 0x2800, 0x2BC0); // Bottom Left
DrawNametable(32, 30, 0x2C00, 0x2FC0); // Bottom Right
// Draw Black Borders
int padding = 1;
for (int i = 0; i < WIDTH_x2; i++)
{
for (int j = -padding; j < padding; j++)
{
nameTableBuffer[(WIDTH_x2 * (HEIGHT + j)) + i] = Palette::GetColor(PALETTE_BLACK);
} // for
} // for
for (int i = 0; i < HEIGHT_x2; i++)
{
for (int j = -padding; j < padding; j++)
{
nameTableBuffer[(WIDTH_x2 * i) + (WIDTH + j)] = Palette::GetColor(PALETTE_BLACK);
} // for
} // for
Emulator::NewDebugFrame(nameTableBuffer, true);
} // DrawNametableViewer()
void Reset()
{
memset(nameTableBuffer, COLOR_BACKDROP_HEX, sizeof(nameTableBuffer));
memset(patternTableBuffer, COLOR_BACKDROP_HEX, sizeof(patternTableBuffer));
} // Reset()
} // Viewer
| true |
518f3e62a785757519b691ed256d65be4e9390f8 | C++ | timminn/Competitive-Programming-Solutions | /Usaco Basit/Bronze 05/(+)Satpix.cpp | UTF-8 | 777 | 2.625 | 3 | [] | no_license | //SORU 477
//PROGRAM C++
#include <iostream>
#include <cstdio>
#include <algorithm>
#define FOR(i,a,b) for(i=a; i<=b; i++)
using namespace std;
FILE *in,*out;
int M,N;
int B[1000005];
int yon[4][2] = { {1,0},{0,1},{-1,0},{0,-1} };
int A[1005][1005];
void read()
{
int i,j;
in=fopen("satpix.in","r");
out=fopen("satpix.out","w");
fscanf(in,"%d %d",&N,&M);
FOR(i,1,M)
FOR(j,1,N)
fscanf(in," %c",&A[i][j]);
}
void solve(int x,int y,int s)
{
int i;
B[s]++;
A[x][y] = '.';
FOR(i,0,3)
if(A[x+yon[i][0]][y+yon[i][1]] == '*')
solve(x+yon[i][0],y+yon[i][1],s);
}
int main()
{
int i,j,k=0;
read();
FOR(i,1,M)
FOR(j,1,N)
if(A[i][j] == '*')
solve(i,j,++k);
fprintf(out,"%d\n",*max_element(B+1,B+k+1));
return 0;
}
| true |
88294fa8df6574b3203be436bf5a93146aed2dbb | C++ | unimportantstuff/cpp-labs | /week8/task1/CustomerCounter.cpp | UTF-8 | 805 | 3.5625 | 4 | [
"Unlicense"
] | permissive | #include "CustomerCounter.h"
#include <iostream>
CustomerCounter::CustomerCounter(int maximum) {
this->customer_count = 0;
this->maximum_customers = maximum;
};
void CustomerCounter::add(int num) {
if (this->customer_count + num > this->maximum_customers)
this->customer_count = this->maximum_customers;
else
this->customer_count += num;
}
void CustomerCounter::subtract(int num) {
if (this->customer_count - num < 0)
this->customer_count = 0;
else
this->customer_count -= num;
}
void CustomerCounter::print() {
std::cout << "[CustomerCounter]\n\n\tCustomer Count: "
<< this->customer_count
<< "\n\tMaximum Customers: "
<< this->maximum_customers
<< "\n"
<< std::endl;
} | true |
3fec80cee5cc3aa9ea27ed096856509675d5c2ca | C++ | fmidev/smartmet-library-calculator | /calculator/MeanCalculator.cpp | ISO-8859-1 | 2,481 | 2.59375 | 3 | [
"MIT"
] | permissive | // ======================================================================
/*!
* \file
* \brief Implementation of class TextGen::MeanCalculator
*/
// ======================================================================
/*!
* \class TextGen::MeanCalculator
*
* \brief Mean intergator
*
*/
// ======================================================================
#include "MeanCalculator.h"
#include "DefaultAcceptor.h"
#include <newbase/NFmiGlobals.h>
namespace TextGen
{
// ----------------------------------------------------------------------
/*!
* \brief Constructor
*/
// ----------------------------------------------------------------------
MeanCalculator::MeanCalculator() : itsAcceptor(new DefaultAcceptor()) {}
// ----------------------------------------------------------------------
/*!
* \brief Integrate a new value
*
* \param theValue
*/
// ----------------------------------------------------------------------
void MeanCalculator::operator()(float theValue)
{
if (itsAcceptor->accept(theValue))
{
++itsCounter;
itsSum += theValue;
}
}
// ----------------------------------------------------------------------
/*!
* \brief Return the integrated value
*
* \return The integrated mean value
*/
// ----------------------------------------------------------------------
float MeanCalculator::operator()() const
{
if (itsCounter == 0) return kFloatMissing;
return itsSum / static_cast<double>(itsCounter);
}
// ----------------------------------------------------------------------
/*!
* \brief Set the internal acceptor
*
* \param theAcceptor The acceptor to be used
*/
// ----------------------------------------------------------------------
void MeanCalculator::acceptor(const Acceptor& theAcceptor)
{
itsAcceptor = boost::shared_ptr<Acceptor>(theAcceptor.clone());
}
// ----------------------------------------------------------------------
/*!
*\brief Clone
*/
// ----------------------------------------------------------------------
boost::shared_ptr<Calculator> MeanCalculator::clone() const
{
return boost::shared_ptr<Calculator>(new MeanCalculator(*this));
}
// ----------------------------------------------------------------------
/*!
* \brief Reset
*/
// ----------------------------------------------------------------------
void MeanCalculator::reset()
{
itsCounter = 0;
itsSum = 0;
}
} // namespace TextGen
// ======================================================================
| true |
372fb308264d32160f5a1b528d1443da3c04d883 | C++ | necromaner/C- | /c-primer/Chapter Four/4.7/4.24/main.cpp | UTF-8 | 419 | 3.5 | 4 | [] | no_license | //4.24:本节示例程序将成绩划分成high pass,pass 和fail三种,它的依据是条件运算符满足右结合率。假如条件运算符满足的是左结合律,求值过程将是怎样的?
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
using std::string;
int main() {
int grade;
cin>>grade;
cout<<endl<<(grade>60)?(grade>90)?"high pass":"pass":"fail";
return 0;
} | true |
766c46d74cb0c25f9961e4f4ee0eecdcce0151fd | C++ | izeki/model_car | /Arduino/libraries/PinChangeInterrupt/examples/PinChangeInterrupt_LowLevel/PinChangeInterrupt_LowLevel.ino | UTF-8 | 1,900 | 2.609375 | 3 | [
"MIT"
] | permissive | /*
Copyright (c) 2014-2015 NicoHood
See the readme for credit to other people.
PinChangeInterrupt_LowLevel
Demonstrates how to use the library without the API
Make sure to comment "//#define PCINT_API" in the settings file.
To maximize speed and size also uncomment all not used pins above.
Then you could also uncomment "#define PCINT_COMPILE_ENABLED_ISR"
to get away the .a linkage overhead.
Connect a button/cable to pin 7 and ground (Uno).
Strong overwritten callback functions are called when an interrupt occurs.
The Led state will change if the pin state does.
PinChangeInterrupts are different than normal Interrupts.
See readme for more information.
Dont use Serial or delay inside interrupts!
This library is not compatible with SoftSerial.
The following pins are usable for PinChangeInterrupt:
Arduino Uno/Nano/Mini: All pins are usable
Arduino Mega: 10, 11, 12, 13, 50, 51, 52, 53, A8 (62), A9 (63), A10 (64),
A11 (65), A12 (66), A13 (67), A14 (68), A15 (69)
Arduino Leonardo/Micro: 8, 9, 10, 11, 14 (MISO), 15 (SCK), 16 (MOSI)
HoodLoader2: All (broken out 1-7) pins are usable
Attiny 24/44/84: All pins are usable
Attiny 25/45/85: All pins are usable
Attiny 13: All pins are usable
ATmega644P/ATmega1284P: All pins are usable
*/
#include "PinChangeInterrupt.h"
// choose a valid PinChangeInterrupt pin of your Arduino board
// manually defined pcint number
#define pinBlink 7
#define interruptBlink 23
void setup()
{
// set pin to input with a pullup, led to output
pinMode(pinBlink, INPUT_PULLUP);
pinMode(LED_BUILTIN, OUTPUT);
// attach the new PinChangeInterrupts and enable event functions below
attachPinChangeInterrupt(interruptBlink, CHANGE);
}
void PinChangeInterruptEvent(interruptBlink)(void) {
// switch Led state
digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
}
void loop() {
// nothing to do here
}
| true |
cc8f49290ceba2831de05fb63e200f59448a54fd | C++ | ymd45921/HUST-ACM-training | /nowcoder/2020通常比赛/contest5203/B.cc | UTF-8 | 1,872 | 2.53125 | 3 | [] | no_license | /**
*
* 怎么还能WA
*
* 改成滚动数组dp就行了
*/
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
using longs = long long;
using longd = long double;
using ulongs = unsigned long long;
const int inf = 0x3f3f3f3f;
const longs INF = 0x3f3f3f3f3f3f3f3f;
const double eps = 1e-8;
const int N = 1e5+5;
const int mod = 3600;
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t, n, a[N], cnt[3605];
bool vis[2][3605];
cin >> t;
while (t --)
{
cin >> n; bool find = false;
memset(cnt, 0, sizeof cnt);
memset(vis, 0, sizeof vis);
for (int i = 1; i <= n; ++ i)
{
cin >> a[i];
a[i] %= mod;
if (!a[i]) find = true;
else ++cnt[a[i]];
}
if (find)
{
cout << "YES" << endl;
continue;
}
// sort(a+1, a+1+n);
int tag = 0;
for (int i = 1; i < 3600; ++ i)
if (!find)
while (cnt[i] --)
{
int ii = tag++ & 1;
if (vis[ii^1][3600 - i])
{
find = vis[ii][3600] = true;
break;
}
for (int x = 0; x <= mod; ++ x)
vis[ii][x] = vis[ii^1][x];
for (int j = i - 1; j; -- j)
if (vis[ii^1][mod + j - i]) vis[ii][j] = true;
for (int j = 3599; j > i; -- j)
if (vis[ii^1][j - i]) vis[ii][j] = true;
vis[ii][i] = true;
}
vis[0][mod] = vis[0][mod] || vis[0][0];
vis[1][mod] = vis[1][mod] || vis[1][0];
cout << (vis[0][mod] || vis[1][mod] ? "YES" : "NO") << endl;
}
return 0;
} | true |
e5915f8bbf5c7a87edc2523593198dbc6c20f2ee | C++ | utia-econometrics/mspp | /include/scenarios.h | UTF-8 | 1,977 | 2.5625 | 3 | [] | no_license | #ifndef SCENARIOS_H
#define SCENARIOS_H
#include "commons.h"
#include "probability.h"
class nxtreestructure: public treestructure
{
public:
nxtreestructure(const std::vector<unsigned int>& ns)
: fns(ns), fstageoffsets(ns.size()), fstagesizes(ns.size())
{
fnumnodes = 0;
for(unsigned int i=0, s = 1; i<ns.size(); i++)
{
s *= ns[i];
fstageoffsets[i] = fnumnodes;
fstagesizes[i] = s;
fnumnodes += s;
}
}
virtual unsigned int numbranches(const path& p, unsigned int k) const
{
assert(k < horizon());
return fns[k];
}
virtual unsigned int horizon() const
{
return fns.size();
}
virtual unsigned int numnodes(unsigned int k) const
{
assert(k < horizon());
return fstagesizes[k];
}
virtual unsigned int stageoffset(unsigned int k) const
{
assert(k < horizon());
return fstageoffsets[k];
}
virtual unsigned int relnodeindex(const path& p, unsigned int k) const
{
assert(p.size() > 0);
assert(p.size() <= horizon());
assert(k < horizon());
unsigned int a=0;
unsigned int n=1;
for(int i=k; i>=0; i--)
{
a += p[i] * n;
n*=fns[i];
}
assert(a < fnumnodes);
return a;
}
virtual unsigned int totalnumnodes() const
{
return fnumnodes;
}
private:
std::vector<unsigned int> fns;
std::vector<unsigned int> fstageoffsets;
std::vector<unsigned int> fstagesizes;
unsigned int fnumnodes;
};
class uniformtreeprobs: public treeprobs
{
public:
/** Default constructor */
uniformtreeprobs(const treestructure_ptr& ts) : treeprobs(ts) {}
/** Default destructor */
virtual double operator()(const path& p, unsigned int k) const
{
return 1.0 / ts().numbranches(p,k);
}
};
#endif // SCENARIOS_H
| true |
5ee06759bde6556fd853df01d2a88e729da3fe87 | C++ | jeroenvlek/evopic | /ImageImp.h | UTF-8 | 1,364 | 3.1875 | 3 | [] | no_license | /**
* ImageImp.h
*
* Created on: Aug 3, 2011
* Author: Jeroen Vlek
* Email: jeroenvlek@gmail.com
* Website: www.perceptivebits.com
* License: Free Beer (Feel free to use it in every
* way possible and if you like it, make
* sure to give me credit and buy me a drink
* if we ever meet ;) )
*/
#ifndef IMAGEIMP_H_
#define IMAGEIMP_H_
#include "Gene.h"
#include "Pixel.h"
#include <string>
class ImageImp
{
public:
virtual ~ImageImp();
/**
* Clears the image to black or transparent, depending on implementation.
*/
virtual void clear() =0;
/**
* Loads image from file.
*
* @param filename
*/
virtual void loadFromFile(const std::string& filename) =0;
/**
* Draws the gene on the image.
*
* @param gene
*/
virtual void drawGene(const Gene& gene) =0;
/**
* @return Width of the image.
*/
virtual unsigned int getWidth() =0;
/**
* @return Height of the image.
*/
virtual unsigned int getHeight() =0;
/**
* @return The pixel at location (x,y)
*/
virtual const PIXEL* get(unsigned int x, unsigned int y) =0;
/**
* Returns the horizontal pixel line at height y
*
* @param y
* @return
*/
virtual const PIXEL* getScanline(unsigned int y) =0;
protected:
ImageImp();
ImageImp(const unsigned int width, const unsigned int height);
};
#endif /* IMAGEIMP_H_ */
| true |
21fe4a5204d1615d4815ffbf93b6769026144e8f | C++ | nutiteq/hellomap3d-ios | /hellomap3/Nuti.framework/Versions/A/Headers/cglib/mat.h | UTF-8 | 23,752 | 2.84375 | 3 | [
"BSD-2-Clause"
] | permissive | #ifndef _CGLIB_MAT_H
#define _CGLIB_MAT_H
#include "vec.h"
#include <array>
#include <initializer_list>
namespace cglib
{
/**
* A square matrix of type T with N rows and N columns.
* T is assumed to be float or double (although should work in other
* instances also).
*/
template <typename T, size_t N, typename Traits = float_traits<T> >
class mat
{
public:
typedef T value_type;
typedef Traits traits_type;
inline mat() = default;
#if defined(__clang__) // XCode 7.2 seems to generate buggy code for ARM64 for default constructor
inline mat(const mat<T, N, Traits> & m)
{
for (size_t i = 0; i < N; i++)
{
for_each_unrolled<N>([&](size_t j)
{
_colrow[i][j] = m._colrow[i][j];
});
}
}
#endif
inline explicit mat(const std::array<std::array<T, N>, N> & colrow)
{
for (size_t i = 0; i < N; i++)
{
for_each_unrolled<N>([&](size_t j)
{
_colrow[i][j] = colrow[i][j];
});
}
}
inline mat(std::initializer_list<std::initializer_list<T> > list)
{
assert(list.size() == N);
for (size_t i = 0; i < N; i++)
{
for_each_unrolled<N>([&](size_t j)
{
assert((list.begin() + j)->size() == N);
_colrow[i][j] = *((list.begin() + j)->begin() + i);
});
}
}
inline T operator () (size_t r, size_t c) const
{
assert(r < N && c < N);
return _colrow[c][r];
}
inline T & operator () (size_t r, size_t c)
{
assert(r < N && c < N);
return _colrow[c][r];
}
inline const std::array<T, N> & operator [] (size_t c) const
{
assert(c < N);
return _colrow[c];
}
inline std::array<T, N> & operator [] (size_t c)
{
assert(c < N);
return _colrow[c];
}
inline const T * data() const
{
return &_colrow[0][0];
}
inline T * data()
{
return &_colrow[0][0];
}
mat<T, N, Traits> & copy(const T * data)
{
for (size_t i = 0; i < N; i++)
{
for (size_t j = 0; j < N; j++)
{
_colrow[i][j] = *data++;
}
}
return *this;
}
mat<T, N, Traits> & copy_row(size_t j, const T * data)
{
for (size_t i = 0; i < N; i++)
{
_colrow[i][j] = *data++;
}
return *this;
}
mat<T, N, Traits> & copy_col(size_t i, const T * data)
{
for (size_t j = 0; j < N; j++)
{
_colrow[i][j] = *data++;
}
return *this;
}
mat<T, N, Traits> operator - () const
{
mat<T, N, Traits> neg;
for (size_t i = 0; i < N; i++)
{
for_each_unrolled<N>([&](size_t j)
{
neg._colrow[i][j] = -_colrow[i][j];
});
}
return neg;
}
mat<T, N, Traits> & operator += (const mat<T, N, Traits> & m)
{
for (size_t i = 0; i < N; i++)
{
for_each_unrolled<N>([&](size_t j)
{
_colrow[i][j] += m._colrow[i][j];
});
}
return *this;
}
mat<T, N, Traits> & operator -= (const mat<T, N, Traits> & m)
{
for (size_t i = 0; i < N; i++)
{
for_each_unrolled<N>([&](size_t j)
{
_colrow[i][j] -= m._colrow[i][j];
});
}
return *this;
}
mat<T, N, Traits> & operator *= (T val)
{
for (size_t i = 0; i < N; i++)
{
for_each_unrolled<N>([&](size_t j)
{
_colrow[i][j] *= val;
});
}
return *this;
}
mat<T, N, Traits> & operator *= (const mat<T, N, Traits> & m2)
{
mat<T, N, Traits> m1(*this);
for (size_t i = 0; i < N; i++)
{
for (size_t j = 0; j < N; j++)
{
T s = 0;
for_each_unrolled<N>([&](size_t k)
{
s += m1(i, k) * m2(k, j);
});
_colrow[j][i] = s;
}
}
return *this;
}
mat<T, N, Traits> & operator /= (const mat<T, N, Traits> & m)
{
mat<T, N, Traits> m2(inverse(m));
return (*this) *= m2;
}
void clear()
{
for (size_t i = 0; i < N; i++)
{
for_each_unrolled<N>([&](size_t j)
{
_colrow[i][j] = 0;
});
}
}
inline void swap(mat<T, N, Traits> & m)
{
for (size_t i = 0; i < N; i++)
{
for_each_unrolled<N>([&](size_t j)
{
std::swap(_colrow[i][j], m._colrow[i][j]);
});
}
}
static mat<T, N, Traits> zero()
{
mat<T, N, Traits> m;
for (size_t i = 0; i < N; i++)
{
for_each_unrolled<N>([&](size_t j)
{
m._colrow[i][j] = 0;
});
}
return m;
}
static mat<T, N, Traits> identity()
{
mat<T, N, Traits> m;
for (size_t i = 0; i < N; i++)
{
for_each_unrolled<N>([&](size_t j)
{
m._colrow[i][j] = static_cast<T>(i == j ? 1 : 0);
});
}
return m;
}
static mat<T, N, Traits> flip(size_t i)
{
mat<T, N, Traits> m = identity();
m(i, i) = -m(i, i);
return m;
}
template <typename S, typename TraitsS>
static mat<T, N, Traits> convert(const mat<S, N, TraitsS> & m)
{
mat<T, N, Traits> n;
for (size_t i = 0; i < N; i++)
{
for_each_unrolled<N>([&](size_t j)
{
n._colrow[i][j] = static_cast<T>(m(j, i));
});
}
return n;
}
private:
T _colrow[N][N];
};
/**
* Create vector from a fixed matrix column.
* @relates vec
*/
template <typename T, size_t N, typename Traits> inline vec<T, N, Traits>
col_vector(const mat<T, N, Traits> & m, size_t c)
{
vec<T, N, Traits> v;
for (size_t i = 0; i < N; i++)
{
v(i) = m(i, c);
}
return v;
}
/**
* Create vector from a fixed matrix row.
* @relates vec
*/
template <typename T, size_t N, typename Traits> inline vec<T, N, Traits>
row_vector(const mat<T, N, Traits> & m, size_t r)
{
vec<T, N, Traits> v;
for (size_t i = 0; i < N; i++)
{
v(i) = m(r, i);
}
return v;
}
/**
* Calculates 3x3 matrix N for 3D vector V such that
* N*W=VxW for all vectors W.
* @relates mat
*/
template <typename T, typename Traits> inline mat<T, 3, Traits>
star_matrix(const vec<T, 3, Traits> & v)
{
mat<T, 3, Traits> m;
m(0, 0) = 0; m(0, 1) = -v(2); m(0, 2) = v(1);
m(1, 0) = v(2); m(1, 1) = 0; m(1, 2) = -v(0);
m(2, 0) = -v(1); m(2, 1) = v(0); m(2, 2) = 0;
return m;
}
/**
* Gives scaling matrix for given scaling coefficents.
* @relates mat
*/
template <typename T, typename Traits> inline mat<T, 3, Traits>
scale3_matrix(const vec<T, 3, Traits> & s)
{
mat<T, 3, Traits> m;
m(0, 0) = s(0); m(0, 1) = 0; m(0, 2) = 0;
m(1, 0) = 0; m(1, 1) = s(1); m(1, 2) = 0;
m(2, 0) = 0; m(2, 1) = 0; m(2, 2) = s(2);
return m;
}
/**
* Gives scaling matrix for given scaling coefficents.
* @relates mat
*/
template <typename T, typename Traits> inline mat<T, 4, Traits>
scale4_matrix(const vec<T, 3, Traits> & s)
{
mat<T, 4, Traits> m;
m(0, 0) = s(0); m(0, 1) = 0; m(0, 2) = 0; m(0, 3) = 0;
m(1, 0) = 0; m(1, 1) = s(1); m(1, 2) = 0; m(1, 3) = 0;
m(2, 0) = 0; m(2, 1) = 0; m(2, 2) = s(2); m(2, 3) = 0;
m(3, 0) = 0; m(3, 1) = 0; m(3, 2) = 0; m(3, 3) = 1;
return m;
}
/**
* Gives translation matrix for given translation vector.
* @relates mat
*/
template <typename T, typename Traits> inline mat<T, 3, Traits>
translate3_matrix(const vec<T, 3, Traits> & t)
{
mat<T, 3, Traits> m;
m(0, 0) = 1; m(0, 1) = 0; m(0, 2) = t(0);
m(1, 0) = 0; m(1, 1) = 1; m(1, 2) = t(1);
m(2, 0) = 0; m(2, 1) = 0; m(2, 2) = t(2);
return m;
}
/**
* Gives translation matrix for given translation vector.
* @relates mat
*/
template <typename T, typename Traits> inline mat<T, 4, Traits>
translate4_matrix(const vec<T, 3, Traits> & t)
{
mat<T, 4, Traits> m;
m(0, 0) = 1; m(0, 1) = 0; m(0, 2) = 0; m(0, 3) = t(0);
m(1, 0) = 0; m(1, 1) = 1; m(1, 2) = 0; m(1, 3) = t(1);
m(2, 0) = 0; m(2, 1) = 0; m(2, 2) = 1; m(2, 3) = t(2);
m(3, 0) = 0; m(3, 1) = 0; m(3, 2) = 0; m(3, 3) = 1;
return m;
}
/**
* Gives Euler matrix for given "head, pitch, bank" parameters.
* @relates mat
*/
template <typename T, typename Traits> inline mat<T, 3, Traits>
euler3_matrix(const vec<T, 3, Traits> & hpb)
{
mat<T, 3, Traits> m;
T sh = Traits::sin(hpb(0)), ch = Traits::cos(hpb(0));
T sp = Traits::sin(hpb(1)), cp = Traits::cos(hpb(1));
T sb = Traits::sin(hpb(2)), cb = Traits::cos(hpb(2));
m(0, 0) = cb*ch - sb*sp*sh;
m(0, 1) = -sb*cp;
m(0, 2) = cb*sh + sb*sp*ch;
m(1, 0) = sb*ch + cb*sp*sh;
m(1, 1) = cb*cp;
m(1, 2) = sb*sh - cb*sp*ch;
m(2, 0) = -cp*sh;
m(2, 1) = sp;
m(2, 2) = cp*ch;
return m;
}
/**
* Gives Euler matrix for given "head, pitch, bank" parameters.
* @relates mat
*/
template <typename T, typename Traits> inline mat<T, 4, Traits>
euler4_matrix(const vec<T, 3, Traits> & hpb)
{
mat<T, 4, Traits> m;
T sh = Traits::sin(hpb(0)), ch = Traits::cos(hpb(0));
T sp = Traits::sin(hpb(1)), cp = Traits::cos(hpb(1));
T sb = Traits::sin(hpb(2)), cb = Traits::cos(hpb(2));
m(0, 0) = cb*ch - sb*sp*sh;
m(0, 1) = -sb*cp;
m(0, 2) = cb*sh + sb*sp*ch;
m(1, 0) = sb*ch + cb*sp*sh;
m(1, 1) = cb*cp;
m(1, 2) = sb*sh - cb*sp*ch;
m(2, 0) = -cp*sh;
m(2, 1) = sp;
m(2, 2) = cp*ch;
m(0, 3) = m(1, 3) = m(2, 3) = m(3, 0) = m(3, 1) = m(3, 2) = 0;
m(3, 3) = 1;
return m;
}
/**
* Gives matrix by applying consecutive rotations about X, Y, Z axis.
* @relates mat
*/
template <typename T, typename Traits> inline mat<T, 4, Traits>
rotate4_xyz_matrix(const vec<T, 3, Traits> & xyz)
{
T s1 = 0, c1 = 1;
if (xyz(0) != 0)
{
c1 = Traits::cos(xyz(0));
s1 = Traits::sin(xyz(0));
}
T s2 = 0, c2 = 1;
if (xyz(1) != 0)
{
c2 = Traits::cos(xyz(1));
s2 = Traits::sin(xyz(1));
}
T s3 = 0, c3 = 1;
if (xyz(2) != 0)
{
c3 = Traits::cos(xyz(2));
s3 = Traits::sin(xyz(2));
}
mat<T, 4, Traits> m;
m(0, 0) = c3*c2;
m(0, 1) = -s3*c1 + c3*s2*s1;
m(0, 2) = s3*s1 + c3*s2*c1;
m(1, 0) = s3*c2;
m(1, 1) = c3*c1 + s3*s2*s1;
m(1, 2) = -c3*s1 + s3*s2*c1;
m(2, 0) = -s2;
m(2, 1) = c2*s1;
m(2, 2) = c2*c1;
m(0, 3) = m(1, 3) = m(2, 3) = m(3, 0) = m(3, 1) = m(3, 2) = 0;
m(3, 3) = 1;
return m;
}
/**
* Gives rotation matrix for given vector and angle.
* @relates mat
*/
template <typename T, typename Traits> inline mat<T, 3, Traits>
rotate3_matrix(const vec<T, 3, Traits> & v, T a)
{
mat<T, 3, Traits> m;
vec<T, 3, Traits> u = unit(v);
T s = Traits::sin(a), c = Traits::cos(a);
T x = u[0], y = u[1], z = u[2];
T xx = x * x, yy = y * y, zz = z * z;
T xy = x * y, yz = y * z, zx = z * x;
T xs = x * s, ys = y * s, zs = z * s;
T one_c = 1 - c;
m(0, 0) = (one_c * xx) + c; m(0, 1) = (one_c * xy) - zs; m(0, 2) = (one_c * zx) + ys;
m(1, 0) = (one_c * xy) + zs; m(1, 1) = (one_c * yy) + c; m(1, 2) = (one_c * yz) - xs;
m(2, 0) = (one_c * zx) - ys; m(2, 1) = (one_c * yz) + xs; m(2, 2) = (one_c * zz) + c;
return m;
}
/**
* Gives rotation matrix for given vector and angle.
* @relates mat
*/
template <typename T, typename Traits> inline mat<T, 4, Traits>
rotate4_matrix(const vec<T, 3, Traits> & v, T a)
{
mat<T, 4, Traits> m;
vec<T, 3, Traits> u = unit(v);
T s = Traits::sin(a), c = Traits::cos(a);
T x = u[0], y = u[1], z = u[2];
T xx = x * x, yy = y * y, zz = z * z;
T xy = x * y, yz = y * z, zx = z * x;
T xs = x * s, ys = y * s, zs = z * s;
T one_c = 1 - c;
m(0, 0) = (one_c * xx) + c; m(0, 1) = (one_c * xy) - zs; m(0, 2) = (one_c * zx) + ys; m(0, 3) = 0;
m(1, 0) = (one_c * xy) + zs; m(1, 1) = (one_c * yy) + c; m(1, 2) = (one_c * yz) - xs; m(1, 3) = 0;
m(2, 0) = (one_c * zx) - ys; m(2, 1) = (one_c * yz) + xs; m(2, 2) = (one_c * zz) + c; m(2, 3) = 0;
m(3, 0) = 0; m(3, 1) = 0; m(3, 2) = 0; m(3, 3) = 1;
return m;
}
template <typename T, typename Traits = float_traits<T> > inline mat<T, 4, Traits>
frustum4_matrix(T left, T right, T bottom, T top, T znear, T zfar)
{
T dxinv = 1 / (right - left);
T dyinv = 1 / (top - bottom);
T dzinv = 1 / (zfar - znear);
mat<T, 4, Traits> proj(mat<T, 4, Traits>::zero());
proj(0, 0) = 2 * znear * dxinv;
proj(1, 1) = 2 * znear * dyinv;
proj(2, 2) = -(zfar + znear) * dzinv;
proj(3, 3) = 0;
proj(0, 2) = (right + left) * dxinv;
proj(1, 2) = (top + bottom) * dyinv;
proj(3, 2) = -1;
proj(2, 3) = -2 * zfar * znear * dzinv;
return proj;
}
template <typename T, typename Traits = float_traits<T> > inline mat<T, 4, Traits>
perspective4_matrix(T fovy, T xaspect, T yaspect, T znear, T zfar)
{
T c = znear * Traits::tan(fovy / 2);
T ymax = c * yaspect;
T ymin = -c * yaspect;
T xmax = c * xaspect;
T xmin = -c * xaspect;
return frustum4_matrix<T, Traits>(xmin, xmax, ymin, ymax, znear, zfar);
}
template <typename T, typename Traits = float_traits<T> > inline mat<T, 4, Traits>
ortho4_matrix(T left, T right, T bottom, T top, T znear, T zfar)
{
T dxinv = 1 / (right - left);
T dyinv = 1 / (top - bottom);
T dzinv = 1 / (zfar - znear);
mat<T, 4, Traits> proj(mat<T, 4, Traits>::zero());
proj(0, 0) = 2 * dxinv;
proj(1, 1) = 2 * dyinv;
proj(2, 2) = -2 * dzinv;
proj(3, 3) = 1;
proj(0, 3) = -(right + left) * dxinv;
proj(1, 3) = -(top + bottom) * dyinv;
proj(2, 3) = -(zfar + znear) * dzinv;
return proj;
}
template <typename T, typename Traits> inline mat<T, 4, Traits>
lookat4_matrix(const vec<T, 3, Traits> & eye, const vec<T, 3, Traits> & center, const vec<T, 3, Traits> & up)
{
vec<T, 3, Traits> f = unit(center - eye);
vec<T, 3, Traits> u = unit(vec<T, 3, Traits>(up));
vec<T, 3, Traits> s = unit(vector_product(f, u));
u = vector_product(s, f);
mat<T, 4, Traits> m(mat<T, 4, Traits>::identity());
m(0, 0) = s[0];
m(0, 1) = s[1];
m(0, 2) = s[2];
m(1, 0) = u[0];
m(1, 1) = u[1];
m(1, 2) = u[2];
m(2, 0) =-f[0];
m(2, 1) =-f[1];
m(2, 2) =-f[2];
m(0, 3) =-dot_product(s, eye);
m(1, 3) =-dot_product(u, eye);
m(2, 3) = dot_product(f, eye);
return m;
}
template <typename T, typename Traits> inline mat<T, 4, Traits>
reflection4_matrix(const vec<T, 4, Traits> & plane)
{
mat<T, 4, Traits> m;
T q = plane(0) * plane(0) + plane(1) * plane(1) + plane(2) * plane(2);
m(0, 0) = q - 2 * plane(0) * plane(0);
m(0, 1) = - 2 * plane(0) * plane(1);
m(0, 2) = - 2 * plane(0) * plane(2);
m(0, 3) = - 2 * plane(0) * plane(3);
m(1, 0) = - 2 * plane(0) * plane(1);
m(1, 1) = q - 2 * plane(1) * plane(1);
m(1, 2) = - 2 * plane(1) * plane(2);
m(1, 3) = - 2 * plane(1) * plane(3);
m(2, 0) = - 2 * plane(0) * plane(2);
m(2, 1) = - 2 * plane(1) * plane(2);
m(2, 2) = q - 2 * plane(2) * plane(2);
m(2, 3) = - 2 * plane(2) * plane(3);
m(3, 0) = 0;
m(3, 1) = 0;
m(3, 2) = 0;
m(3, 3) = q;
return m;
}
/**
* Transform vector by matrix.
* @relates vec
*/
template <typename T, size_t N, typename Traits> inline vec<T, N, Traits>
transform(const vec<T, N, Traits> & v, const mat<T, N, Traits> & m)
{
vec<T, N, Traits> w;
for (size_t i = 0; i < N; i++)
{
T t = m(i, 0) * v(0);
for_each_unrolled<N-1>([&](size_t j)
{
t += m(i, j + 1) * v(j + 1);
});
w(i) = t;
}
return w;
}
/**
* Transform point by matrix.
* @relates vec
*/
template <typename T, size_t N, typename Traits> inline vec<T, N, Traits>
transform_point(const vec<T, N, Traits> & v, const mat<T, N+1, Traits> & m)
{
T s = m(N, N);
for (size_t i = 0; i < N; i++)
{
s += m(N, i) * v(i);
}
T invs = 1 / s;
vec<T, N, Traits> w;
for (size_t i = 0; i < N; i++)
{
T t = m(i, N);
for_each_unrolled<N>([&](size_t j)
{
t += m(i, j) * v(j);
});
w(i) = t * invs;
}
return w;
}
/**
* Transform point by matrix. Assume affine (non-perspective) transformation matrix.
* @relates vec
*/
template <typename T, size_t N, typename Traits> inline vec<T, N, Traits>
transform_point_affine(const vec<T, N, Traits> & v, const mat<T, N + 1, Traits> & m)
{
vec<T, N, Traits> w;
for (size_t i = 0; i < N; i++)
{
T t = m(i, N);
for_each_unrolled<N>([&](size_t j)
{
t += m(i, j) * v(j);
});
w(i) = t;
}
return w;
}
/**
* Transform vector by matrix.
* @relates vec
*/
template <typename T, size_t N, typename Traits> inline vec<T, N, Traits>
transform_vector(const vec<T, N, Traits> & v, const mat<T, N+1, Traits> & m)
{
vec<T, N, Traits> w;
for (size_t i = 0; i < N; i++)
{
T t = m(i, 0) * v(0);
for_each_unrolled<N-1>([&](size_t j)
{
t += m(i, j + 1) * v(j + 1);
});
w(i) = t;
}
return w;
}
/**
* Calculates MxM subdeterminant of NxN matrix with given disabled rows
* and columns.
* @relates mat
*/
template <typename T, size_t N, typename Traits> inline T
fast_subdet(const mat<T, N, Traits> & m, size_t n)
{
assert(n < 4);
switch (n)
{
case 1:
return (m(0, 0));
case 2:
return (m(0, 0) * m(1, 1)) -
(m(0, 1) * m(1, 0));
case 3:
return (m(0, 0) * m(1, 1) * m(2, 2) + m(0, 1) * m(1, 2) * m(2, 0) + m(0, 2) * m(1, 0) * m(2, 1)) -
(m(0, 2) * m(1, 1) * m(2, 0) + m(0, 1) * m(1, 0) * m(2, 2) + m(0, 0) * m(1, 2) * m(2, 1));
}
return 1;
}
template <typename T, size_t N, typename Traits> T
subdeterminant(const mat<T, N, Traits> & m, size_t n)
{
if (n < 4)
return fast_subdet(m, n);
mat<T, N, Traits> ms;
for (size_t i = 1; i < n; i++)
{
for (size_t j = 1; j < n; j++)
{
ms(i - 1, j - 1) = m(i, j);
}
}
T det = m(0, 0) * subdeterminant(ms, n - 1);
T sign = 1;
for (size_t s = 1; s < n; s++)
{
sign = -sign;
for (size_t t = 1; t < n; t++)
{
ms(s - 1, t - 1) = m(s - 1, t);
}
det += m(s, 0) * subdeterminant(ms, n - 1) * sign;
}
return det;
}
/**
* Calculates determinant of NxN matrix.
* @relates mat
*/
template <typename T, size_t N, typename Traits> inline T
determinant(const mat<T, N, Traits> & m)
{
return subdeterminant(m, N);
}
/**
* Transposes NxN matrix.
* @relates mat
*/
template <typename T, size_t N, typename Traits> mat<T, N, Traits>
transpose(const mat<T, N, Traits> & m)
{
mat<T, N, Traits> mt;
for (size_t i = 0; i < N; i++)
{
for (size_t j = 0; j < N; j++)
{
mt(j, i) = m(i, j);
}
}
return mt;
}
/**
* Calculates inversion of NxN matrix M. Assumes that det(M) != 0.
* @relates mat
*/
template <typename T, size_t N, typename Traits> mat<T, N, Traits>
inverse(const mat<T, N, Traits> & m)
{
T det = determinant(m), invdet;
if (Traits::eq(det, 0))
invdet = Traits::infinity();
else
invdet = 1 / det;
mat<T, N, Traits> mi;
for (size_t i = 0; i < N; i++)
{
mat<T, N, Traits> ms;
for (size_t k = 0, r = 0; k < N; k++)
{
if (k == i)
continue;
for (size_t l = 1; l < N; l++)
{
ms(r, l - 1) = m(k, l);
}
r++;
}
T sign = static_cast<T>(1 - ((int) (i % 2) * 2));
mi(0, i) = subdeterminant(ms, N - 1) * sign * invdet;
for (size_t j = 1; j < N; j++)
{
sign = -sign;
for (size_t k = 0, r = 0; k < N; k++)
{
if (k == i)
continue;
ms(r, j - 1) = m(k, j - 1);
r++;
}
mi(j, i) = subdeterminant(ms, N - 1) * sign * invdet;
}
}
return mi;
}
/**
* @relates mat
*/
template <typename T, size_t N, typename Traits> bool
operator == (const mat<T, N, Traits> & m1, const mat<T, N, Traits> & m2)
{
for (size_t i = 0; i < N; i++)
{
for (size_t j = 0; j < N; j++)
{
if (!Traits::eq(m1(i, j), m2(i, j)))
return false;
}
}
return true;
}
/**
* @relates mat
*/
template <typename T, size_t N, typename Traits> inline bool
operator != (const mat<T, N, Traits> & m1, const mat<T, N, Traits> & m2)
{
return !(m1 == m2);
}
/**
* Intended for containers only!
* @relates mat
*/
template <typename T, size_t N, typename Traits> bool
operator < (const mat<T, N, Traits> & m1, const mat<T, N, Traits> & m2)
{
for (size_t i = 0; i < N; i++)
{
for (size_t j = 0; j < N; j++)
{
if (m1(i, j) < m2(i, j))
return true;
if (m2(i, j) < m1(i, j))
return false;
}
}
return false;
}
/**
* @relates mat
*/
template <typename T, size_t N, typename Traits> inline mat<T, N, Traits>
operator + (const mat<T, N, Traits> & m1, const mat<T, N, Traits> & m2)
{
mat<T, N, Traits> ms(m1);
return ms += m2;
}
/**
* @relates mat
*/
template <typename T, size_t N, typename Traits> inline mat<T, N, Traits>
operator - (const mat<T, N, Traits> & m1, const mat<T, N, Traits> & m2)
{
mat<T, N, Traits> md(m1);
return md -= m2;
}
/**
* @relates mat
*/
template <typename T, size_t N, typename Traits> inline mat<T, N, Traits>
operator * (const mat<T, N, Traits> & m, T s)
{
mat<T, N, Traits> mp(m);
return mp *= s;
}
/**
* @relates mat
*/
template <typename T, size_t N, typename Traits> inline mat<T, N, Traits>
operator * (const mat<T, N, Traits> & m1, const mat<T, N, Traits> & m2)
{
mat<T, N, Traits> mp(m1);
return mp *= m2;
}
/**
* @relates mat
*/
template <typename T, size_t N, typename Traits> mat<T, N, Traits>
operator / (const mat<T, N, Traits> & m1, const mat<T, N, Traits> & m2)
{
mat<T, N, Traits> md(m1);
return md /= m2;
}
/**
* Reads matrix from stream. Assumes following format: [(x11,...,x1M),...,(xN1,...,xNM)].
* @relates mat
*/
template <typename T, size_t N, typename Traits, typename CharT, typename CharTraits> std::basic_istream<CharT, CharTraits> &
operator >> (std::basic_istream<CharT, CharTraits> & is, mat<T, N, Traits> & m)
{
CharT ch;
is >> ch;
if (ch == '[')
{
size_t i = 0;
do
{
if (i >= N)
break;
vec<T, N, Traits> v;
is >> v;
for (size_t j = 0; j < N; j++)
{
m(i, j) = v(j);
}
is >> ch;
} while (ch == ',');
if (ch != ']')
{
is.setstate(std::ios_base::failbit);
}
}
else
{
is.setstate(std::ios_base::failbit);
}
return is;
}
/**
* Writes matrix to stream. Uses following format: [(x11,...,x1M),...,(xN1,...,xNM)].
* @relates mat
*/
template <typename T, size_t N, typename Traits, typename CharT, typename CharTraits> std::basic_ostream<CharT, CharTraits> &
operator << (std::basic_ostream<CharT, CharTraits> & os, const mat<T, N, Traits> & m)
{
os << '[';
for (size_t i = 0; i < N; i++)
{
if (i > 0)
{
os << ',';
}
vec<T, N, Traits> v;
for (size_t j = 0; j < N; j++)
{
v(j) = m(i, j);
}
os << v;
}
os << ']';
return os;
}
/**
* Matrix instances for 2D, 3D and 4D cases.
*/
template <typename T, typename Traits = float_traits<T> > using mat2x2 = mat<T, 2, Traits>;
template <typename T, typename Traits = float_traits<T> > using mat3x3 = mat<T, 3, Traits>;
template <typename T, typename Traits = float_traits<T> > using mat4x4 = mat<T, 4, Traits>;
}
#endif
| true |
10f4ac137fd651d0feaf9e025f35d9f1a3b29a23 | C++ | EagleSean/smart_pointer.cpp | /counter.h | UTF-8 | 466 | 3.578125 | 4 | [] | no_license | #include <iostream>
using namespace std;
class counter
{
public:
counter(int c)
{
Count=c;
cout<<Count<<endl;
}
counter()
{
Count=1;
cout<<Count<<endl;
}
counter operator++ (int)
{
counter tmp(*this);
this->Count++;
cout<<Count<<endl;
return tmp;
}
bool Cut()
{
this->Count--;
cout<<Count<<endl;
return Check();
}
private:
int Count;
bool Check()
{
if(Count>0)
{
return true;
}
else
{
return false;
}
}
};
| true |
91ffb5e5556d3337945a29092881bf59531dae40 | C++ | triploit/galdur | /main.cpp | UTF-8 | 623 | 2.640625 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#ifndef MAIN_H
#include "parser.hpp"
char c;
int i = 0;
char getch(FILE *datei);
FILE *datei;
int main(int argc, char* argv[]) {
datei=fopen(argv[1], "r");
if(datei != NULL) {
while( (c=getch(datei)) != EOF)
{
i = i + 1;
ch.push_back(c);
}
for (int i = 0; i<ch.size(); i++)
{
Parser.parse(ch[i], i);
}
}
else {
printf("Konnte Datei nicht finden bzw. oeffnen!\n");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
char getch(FILE *datei)
{
char c = fgetc(datei);
return c;
}
#endif
| true |
1eb39dcf74267a35cf491a5433c1ef44aed6d812 | C++ | rnikhori/Daily_code | /pattern7.cpp | UTF-8 | 310 | 2.875 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
int i,j;
for (i=0;i<=5;i++)
{
for (j=0;j<=9;j++)
{
if(j<=(6-i) || j>=(4+i))
cout<<"*";
else
cout<<" ";
}
cout<<"\n";
}
return 0;
}
| true |
fd4575d3b616810d99cfd8b5f797f6f7fffe1223 | C++ | MuditSrivastava/SPOJ_SOL | /LASTDIG2/12785669.cpp | UTF-8 | 653 | 2.53125 | 3 | [] | no_license | #include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int main()
{
char str[1005];
long long int n;
int t;
int a[][5]={{0},{1},{2,4,8,6},{3,9,7,1},{4,6},{5},{6},{7,9,3,1},{8,4,2,6},{9,1}};
scanf("%d",&t);
while(t--)
{
scanf("%s",str);
int l=strlen(str);
int k = str[l-1]-'0';
scanf("%lld",&n);
if(n==0 || k==1)
printf("1\n");
else if(k==2 || k==3 || k==7 || k==8)
printf("%d\n",a[k][(n-1)%4]);
else if(k==9 || k==4)
printf("%d\n",a[k][(n-1)%2]);
else
printf("%d\n",k);
}
return 0;
}
| true |
5a158fdea6b879b09fc450d9e2106656395f1fd1 | C++ | anatoliy1973/RoverKit | /ExtIO/PinManager.cpp | UTF-8 | 2,285 | 2.90625 | 3 | [
"Apache-2.0"
] | permissive | /*
* PinManager.cpp
*
* Created: 5/4/2015 16:23:11
* Author: Tolik
*/
#include "PinManager.h"
#include <binary.h>
namespace ExtIO
{
//variables
uint8_t PinManagerClass::m_startExtPin;
Extender** PinManagerClass::m_extenders;
uint8_t PinManagerClass::m_extendersCount;
void PinManagerClass::Init(uint8_t startExtPin, Extender** extenders, uint8_t extendersCount)
{
m_startExtPin = startExtPin;
m_extenders = extenders;
m_extendersCount = extendersCount;
}
void PinManagerClass::PinMode(uint8_t pin, uint8_t mode)
{
Extender* extender = NULL;
int ipin = pin;
if (FindExtender(&ipin, &extender))
{
if (ipin > B00)
{
extender->PinMode(ipin, mode);
}
}
else
{
pinMode(pin, mode);
}
}
uint8_t PinManagerClass::DigitalRead(uint8_t pin)
{
Extender* extender = NULL;
int ipin = pin;
if (FindExtender(&ipin, &extender))
{
if (ipin > B00)
{
return extender->DigitalRead(ipin);
}
}
else
{
return digitalRead(pin);
}
return LOW;
}
void PinManagerClass::DigitalWrite(uint8_t pin, uint8_t val)
{
Extender* extender = NULL;
int ipin = pin;
if (FindExtender(&ipin, &extender))
{
if (ipin > B00)
{
extender->DigitalWrite(ipin, val);
}
}
else
{
digitalWrite(pin, val);
}
}
bool PinManagerClass::FindExtender(int* pin, Extender** extender)
{
if (*pin < m_startExtPin)
{
return false;
}
*pin -= m_startExtPin - 1;
for (uint8_t i = 0; i < m_extendersCount; i++)
{
uint8_t extenderPins = m_extenders[i]->get_PinsCount();
if (*pin <= extenderPins)
{
*extender = m_extenders[i];
break;
}
*pin -= extenderPins;
}
return true;
}
}
| true |
7f39e836b34a8c1082f7cd1fd0f764d4aac8c82b | C++ | kikitux/fibonacci | /main.cpp | UTF-8 | 4,072 | 3 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <chrono>
#include <vector>
#include <cmath>
#include <cstdint>
using namespace std;
using namespace std::chrono;
// vector that start with {0,1,1}
// new fibonacci series are calculated from last known value
// upto new value
unsigned long intfibonacci(unsigned long n) {
static std::vector<unsigned long> values = {0,1,1};
if (n < values.size() ) {
return values[n];
}
for (unsigned long loop = values.size(); loop-1 < n ; ++loop){
values.push_back(values[loop-2] + values[loop-1]);
}
return values[n];
}
// http://www.cs.utexas.edu/users/EWD/transcriptions/EWD06xx/EWD654.html
// http://www.cs.utexas.edu/users/EWD/ewd06xx/EWD654.PDF
// F(2n) = (2*F(n-1) + F(n) )*F(n)
// F(2n-1) = F(n-1)^2 + F(n)^2
unsigned long intfibdijkstra(unsigned long n) {
static std::vector<unsigned long> values = {0,1,1};
if (n == 0 ) {
return values[n];
}
if (n < values.size() && values[n] != 0 ) {
return values[n];
}
if (values.size() < n){
values.resize(n);
}
if (n%2==0){
unsigned long num = n/2;
if (values[num-1]==0)
values.at(num-1)=intfibdijkstra(num-1);
if (values[num]==0)
values.at(num)=intfibdijkstra(num);
return (2*values[num-1]+values[num])*values[num];
}
else {
unsigned long num = (n+1)/2;
if (values[num-1]==0)
values.at(num-1)=intfibdijkstra(num-1);
if (values[num]==0)
values.at(num)=intfibdijkstra(num);
return values[num-1]*values[num-1]+values[num]*values[num];
}
}
// from http://pastebin.com/1U2D143s
// https://twitter.com/JSMuellerRoemer/status/637586563346493440
// "the best way to get the right answer on the Internet is not to ask a question, it's to post the wrong answer."
// https://meta.wikimedia.org/wiki/Cunningham%27s_Law
using result_t = uint_fast64_t;
auto mult(result_t (&a)[2][2], result_t const (&b)[2][2]) -> void
{
result_t t[2][2];
for(auto row = 0; row < 2; ++row)
{
for(auto col_b = 0; col_b < 2; ++col_b)
{
auto & out = t[row][col_b];
out = 0;
for(auto col_a = 0; col_a < 2; ++col_a)
out += a[row][col_a] * b[col_a][col_b];
}
}
for(auto row = 0; row < 2; ++row) for(auto col = 0; col < 2; ++col)
a[row][col] = t[row][col];
}
auto fast_fib(unsigned n) -> result_t
{
result_t r[2][2] = {
{1, 0},
{0, 1}
};
result_t a[2][2] = {
{1, 1},
{1, 0}
};
if(n <= 1) return n;
n -= 1;
while(true)
{
if(n & 1)
{
mult(r, a);
if(n == 1) break;
}
n >>= 1;
mult(a, a);
}
return r[0][0];
}
int main() {
cout << "\n";
unsigned int number = 0;
cout << "Insert a number to calculate funtions ?:";
cin >> number ;
cout << "\n";
high_resolution_clock::time_point t1 = high_resolution_clock::now();
cout << "Fibonacci number of " << number << " is " << intfibonacci(number) << "\n";
high_resolution_clock::time_point t2 = high_resolution_clock::now();
cout << "Dijkstra Fibonacci number of " << number << " is " << intfibdijkstra(number) << "\n";
high_resolution_clock::time_point t3 = high_resolution_clock::now();
cout << "Fast_fib Fibonacci number of " << number << " is " << fast_fib(number) << "\n";
high_resolution_clock::time_point t4 = high_resolution_clock::now();
cout << "\n";
auto durationf = std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count();
auto durationd = std::chrono::duration_cast<std::chrono::microseconds>( t3 - t2 ).count();
auto durationfb = std::chrono::duration_cast<std::chrono::microseconds>( t4 - t3 ).count();
cout << "\n";
cout << "duration fibonacci " << durationf << "\n";
cout << "duration dijkstra " << durationd << "\n";
cout << "duration fast_fib " << durationfb << "\n";
cout << "\n";
return 0;
}
| true |
bc48d5847f36439a10ca31843ba4e17b6242cef9 | C++ | Lee-DongWon/SWExperts_Problems | /SW Experts/D3/D3_1216.cpp | UTF-8 | 1,464 | 2.921875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int getMax(int a, int b) {
if (a < b) {
return b;
}
else {
return a;
}
}
int main() {
for (int a = 0; a < 10; a++) {
int t, longestLen = 1;
char arr[100][100];
int len[100][100] = { 0, };
cin >> t;
for (int i = 0; i < 100; i++) {
for (int j = 0; j < 100; j++) {
cin >> arr[i][j];
}
}
for (int i = 0; i < 100; i++) {
for (int j = 0; j < 100; j++) {
int len1 = 0, len2 = 0, len3 = 0, len4 = 0, len5 = 0, len6 = 0;
while (j - len1 >= 0 && j + len1 < 100 && arr[i][j - len1] == arr[i][j + len1]) {
len1++;
}
while (j - len3 >= 0 && j + len3 < 100 && arr[i][j - len3] == arr[i][j + 1 + len3]) {
len3++;
}
while (j - len4 >= 0 && j + len4 < 100 && arr[i][j - 1 - len4] == arr[i][j + len4]) {
len4++;
}
while (i - len2 >= 0 && i + len2 < 100 && arr[i - len2][j] == arr[i + len2][j]) {
len2++;
}
while (i - len5 >= 0 && i + len5 < 100 && arr[i - len5][j] == arr[i + 1 + len5][j]) {
len5++;
}
while (j - len6 >= 0 && j + len6 < 100 && arr[i - 1 - len6][j] == arr[i + len6][j]) {
len6++;
}
len[i][j] = getMax(getMax(getMax(2 * len1 - 1, 2 * len2 - 1), getMax(2 * len3, 2 * len4)), getMax(2 * len5, 2 * len6));
if (longestLen < len[i][j]) {
longestLen = len[i][j];
}
}
}
cout << "#" << t << " " << longestLen << endl;
}
} | true |
2e7f69a76592d605e5a7e2b36be7ad4b1cdec098 | C++ | perryiv/cadkit | /OsgTools/SetDataVariance.h | UTF-8 | 1,313 | 2.59375 | 3 | [] | no_license |
///////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Perry L. Miller IV
// All rights reserved.
// BSD License: http://www.opensource.org/licenses/bsd-license.html
//
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
//
// Functor that sets the data-variance.
//
///////////////////////////////////////////////////////////////////////////////
#ifndef _OSG_TOOLS_SET_DATA_VARIANCE_H_
#define _OSG_TOOLS_SET_DATA_VARIANCE_H_
namespace OsgTools {
struct SetDataVariance
{
SetDataVariance ( const osg::Object::DataVariance &v ) : _variance ( v )
{
}
SetDataVariance ( const SetDataVariance &v ) : _variance ( v._variance )
{
}
SetDataVariance &operator = ( const SetDataVariance &v )
{
_variance = v._variance;
return *this;
}
void operator () ( osg::Object *object )
{
if ( object )
object->setDataVariance ( _variance );
}
const osg::Object::DataVariance &variance() const
{
return _variance;
}
void variance ( const osg::Object::DataVariance &v )
{
_variance = v;
}
private:
osg::Object::DataVariance _variance;
};
}; // namespace OsgTools
#endif // _OSG_TOOLS_SET_DATA_VARIANCE_H_
| true |
27c24bdd62d96165132e092bac4b822a3437f891 | C++ | mandarpatkar/College-Stuffs | /C++ Programs/factorial-using-recursion.cpp | UTF-8 | 241 | 3.59375 | 4 | [] | no_license |
#include<iostream>
using namespace std;
int fact(int b){
if ( b == 0 ) return 1;
else return (b*fact(b-1));
}
int main()
{
int a;
cout<<"Enter Number : ";
cin>>a;
cout<<"Factorial Of "<<a<<" is = "<<fact(a)<<endl;
return 0;
}
| true |
4906ed6cb88d97178d88fdd5e37b5346e641488e | C++ | decden/hotel | /server/netserver.h | UTF-8 | 1,178 | 2.6875 | 3 | [
"MIT"
] | permissive | #ifndef SERVER_NETSERVER_H
#define SERVER_NETSERVER_H
#include "persistence/backend.h"
#include <boost/asio.hpp>
#include <vector>
#include <memory>
#include <thread>
namespace server
{
class NetClientSession;
/**
* @brief The NetServer class implements a network interface to a backend.
*/
class NetServer
{
public:
/**
* @brief Creates a new NetServer instance
* @param backend The real backend which will handle all of the requests
*/
NetServer(std::unique_ptr<persistence::Backend> backend);
~NetServer();
void start();
void stopAndJoin();
private:
/**
* @brief Runs the server message loop.
*/
void run();
// This function is contiunously being executed to accept new connections
void doAccept();
private:
std::thread _serverThread;
std::unique_ptr<persistence::Backend> _backend;
boost::asio::io_service _ioService;
boost::asio::ip::tcp::endpoint _endpoint;
boost::asio::ip::tcp::acceptor _acceptor;
boost::asio::ip::tcp::socket _socket;
std::vector<std::weak_ptr<NetClientSession>> _sessions;
};
} // namespace server
#endif // SERVER_NETSERVER_H
| true |
7d62ba3fb392806b80f690d341add566ed9b1061 | C++ | DHRUV-EDDI/CompetitveCoding | /justEatIt_codeForces.cpp | UTF-8 | 1,268 | 2.5625 | 3 | [] | no_license | #include <iostream>
#define ll long long int
#define ull unsigned long long int
using namespace std;
int main()
{
int t, i, j, n;
ll *a = new ll[100099], maxSum, untilNowSum, sum;
cin >> t;
for (i = 0; i < t; i++)
{
cin >> n;
sum = 0;
maxSum = 0;
untilNowSum = 0;
for (j = 0; j < n; j++)
{
cin >> a[j];
sum += a[j];
}
for (j = 0; j < n - 1; j++)
{
if (untilNowSum < 0)
{
untilNowSum = a[j];
}
else
{
untilNowSum += a[j];
}
if (untilNowSum > maxSum)
{
maxSum = untilNowSum;
}
}
untilNowSum = 0;
for (j = n - 1; j > 0; j--)
{
if (untilNowSum < 0)
{
untilNowSum = a[j];
}
else
{
untilNowSum += a[j];
}
if (untilNowSum > maxSum)
{
maxSum = untilNowSum;
}
}
if (sum > maxSum)
{
cout << "YES\n";
}
else
{
cout << "NO\n";
}
}
}
| true |
0685dc2a88be72c2fc7ed96e40ec6291edf55802 | C++ | OscarDPfuturi/Ejercicios-cc2-Lab | /pigLatin.cpp | UTF-8 | 587 | 3 | 3 | [] | no_license | #include <iostream>
#include <conio.h>
using namespace std;
const string vocales = "aeiou";
string pigLatin(const string s){
if(s.size()==0){//cadena vacia
return s;
}
if(s.find("qu") == 0) { //empieza con "qu"
return s.substr(2, s.size()-2) + "-" + s.substr(0, 2) + "ay";
}
else if(vocales.find(s[0]) != string::npos ){//empieza con una vocal
return s + "-way";
}
else {
return s.substr(1,s.size()-1) + "-" + s[0] + "ay";
}
}
int main(){
string cad = "request";
cout<<pigLatin(cad);
getch();
return 0;
}
| true |
d106941267162a8016ee19d6316704b0f7e6c8b5 | C++ | Fearycxy/lintcode | /821_Time_Intersection.cpp | UTF-8 | 2,225 | 3.46875 | 3 | [] | no_license | /**
* Definition of Interval:
* classs Interval {
* int start, end;
* Interval(int start, int end) {
* this->start = start;
* this->end = end;
* }
* }
*/
class Solution {
public:
/**
* @param seqA: the list of intervals
* @param seqB: the list of intervals
* @return: the time periods
*/
vector<Interval> timeIntersection(vector<Interval> &seqA, vector<Interval> &seqB) {
// Write your code here
//sort(seqA.begin(),seqA.end());
//sort(seqB.begin(),seqB.end());
int i = 0;
int j = 0;
vector<Interval> res;
while(i < seqA.size() && j <seqB.size()){
int maxstart = max(seqA[i].start, seqB[j].start);
int minend = min(seqA[i].end, seqB[j].end);
//cout<<" "<<maxstart<<" "<<minend<<endl;
if(maxstart <= minend){
Interval ii(maxstart, minend);
res.push_back(ii);
}
if(minend == seqA[i].end) i++;
if(minend == seqB[j].end) j++;
}
return res;
}
};
//this is my solution
/**
* Definition of Interval:
* classs Interval {
* int start, end;
* Interval(int start, int end) {
* this->start = start;
* this->end = end;
* }
* }
*/
class Solution {
public:
/**
* @param seqA: the list of intervals
* @param seqB: the list of intervals
* @return: the time periods
*/
vector<Interval> timeIntersection(vector<Interval> &seqA, vector<Interval> &seqB) {
// Write your code here
vector<pair<int,int>> vec;
for(auto i:seqA){
vec.emplace_back(i.start,1);
vec.emplace_back(i.end,-1);
}
for(auto i:seqB){
vec.emplace_back(i.start,1);
vec.emplace_back(i.end,-1);
}
sort(vec.begin(),vec.end());
vector<Interval> an;pair<int,int> last = {-1,-1};int index = 0;
for(auto a:vec){
if(a.second <0 && last.second >0 && index ==2 ){
an.emplace_back(last.first,a.first);
}
index += a.second <0? -1:1;
last = a;
}
return an;
}
};
| true |
9b4f602268311276f703d63d71df32bcdb49f220 | C++ | kevinxusz/QFlow | /FlowLib/FlowObjectStorage.cpp | UTF-8 | 4,488 | 2.71875 | 3 | [
"MIT"
] | permissive | #include "FlowObjectStorage.h"
#include "FlowObject.h"
#include <QDebug>
FlowObjectStorage::FlowObjectStorage(QObject *parent) :
QObject(parent)
{
m_debug = false;
cleanupTimer.setInterval(5 * 1000); // check every 5 seconds
connect(&cleanupTimer,&QTimer::timeout,this,&FlowObjectStorage::cleanupPackets);
cleanupTimer.start();
}
FlowObject *FlowObjectStorage::getByPacket(const QVariantMap &flowPacket)
{
return get(flowPacket.value(FlowObject::flowObjectIdTag()).toString());
}
FlowObject *FlowObjectStorage::get(const QString &uuid)
{
if(debug())
{
if(flowObjectsByHash.contains(uuid))
qDebug() << "[Storage] Get Object Success: " << uuid;
else
qDebug() << "[Storage] Get Object Failure: " << uuid;
}
return flowObjectsByHash.value(uuid,nullptr);
}
void FlowObjectStorage::add(FlowObject *flowObject)
{
if(!flowObject)
return;
flowObject->setFlowGraph((FlowGraph*)parent());
flowObject->setParent(this);
connect(flowObject,&FlowObject::flowObjectExpired,this,&FlowObjectStorage::objectExpiredEvent);
connect(flowObject,&QObject::destroyed,this,&FlowObjectStorage::objectRemovedEvent);
flowObjectsByHash[flowObject->uuid()] = flowObject;
flowObject->storageAddEvent();
emit objectAdded(flowObject->uuid());
if(debug())
qDebug() << "[Storage] Object Added: " << flowObject->uuid();
}
void FlowObjectStorage::removeByPacket(const QVariantMap &flowPacket)
{
return remove(flowPacket.value(FlowObject::flowObjectIdTag()).toString());
}
void FlowObjectStorage::remove(const QString &uuid)
{
FlowObject *flowObject = flowObjectsByHash.take(uuid);
if(!flowObject)
return;
emit objectRemoved(flowObject->uuid());
flowObject->storageRemoveEvent();
if(flowObject->flowObjectDeleteDelay() <= 0)
{
flowObject->deleteLater();
if(debug())
qDebug() << "[Storage] Remove Object InTime: " << uuid;
}else
{
if(debug())
qDebug() << "[Storage] Remove Object Later: " << uuid;
waitingForRemoveList.insert(QDateTime::currentDateTime().addSecs(flowObject->flowObjectDeleteDelay()),flowObject);
}
}
void FlowObjectStorage::cleanupPackets()
{
// do cleanup old packets.
int removedCount = 0;
QDateTime now =QDateTime::currentDateTime();
QMutableMapIterator<QDateTime,QObject *> mit(waitingForRemoveList);
while(mit.hasNext())
{
mit.next();
if(now > mit.key())
{
mit.value()->deleteLater();
mit.remove();
removedCount++;
}
}
if(debug())
qDebug() << "flow objects after cleanup:" << flowObjectsByHash.count() << waitingForRemoveList.count() << removedCount ;
}
void FlowObjectStorage::objectExpiredEvent()
{
if(debug())
qDebug() << "[Storage] Object Expire Event";
QObject *robject = sender();
{
QMutableHashIterator<QString,FlowObject *> hit(flowObjectsByHash);
while(hit.hasNext())
{
hit.next();
if(hit.value() == robject)
{
if(debug())
qDebug() << "[Storage] Object Expired";
FlowObject *flowObject = hit.value();
emit objectRemoved(flowObject->uuid());
flowObject->storageRemoveEvent();
hit.remove();
}
}
}
{
QMutableMapIterator<QDateTime,QObject *> mit(waitingForRemoveList);
while(mit.hasNext())
{
mit.next();
if(mit.value() == robject)
mit.remove();
}
}
robject->deleteLater();
}
void FlowObjectStorage::objectRemovedEvent()
{
QObject *robject = sender();
{
QMutableHashIterator<QString,FlowObject *> hit(flowObjectsByHash);
while(hit.hasNext())
{
hit.next();
FlowObject *flowObject = hit.value();
if(flowObject == robject)
{
qDebug() << "[Storage] Object Remove Event outside of storage!!!";
emit objectRemoved(flowObject->uuid());
hit.remove();
}
}
}
{
QMutableMapIterator<QDateTime,QObject *> mit(waitingForRemoveList);
while(mit.hasNext())
{
mit.next();
if(mit.value() == robject)
mit.remove();
}
}
}
| true |
c382702488b1fab32c5f55c5bc4139f644deb0d8 | C++ | sailor-ux/mycodes | /leetcode_vscode/leetcode_200/leetcode_200_ershua.cpp | GB18030 | 1,287 | 3.421875 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
class Solution {
private:
vector<pair<int, int>> directions{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
public:
int numIslands(vector<vector<char>>& grid) {
int islandNum = 0;
for (int row = 0; row < grid.size(); row++) {
for (int col = 0; col < grid[0].size(); col++) {
if (grid[row][col] == '1') {
dfs(grid, row, col);
islandNum++;
}
}
}
return islandNum;
}
void dfs(vector<vector<char>>& grid, int row, int col) {
if (row < 0 || row >= grid.size() || col < 0 || col >= grid[0].size() || grid[row][col] != '1') {
return;
}
grid[row][col] = '2'; // ı䣬Ϊ2ȣdfsĵݹںdfsݹѭ
for (int i = 0; i < 4; i++) {
dfs(grid, row + directions[i].first, col + directions[i].second);
}
}
};
int main() {
vector<vector<char>> grid{
{'1', '1', '1', '1', '0'},
{'1', '1', '0', '1', '0'},
{'1', '1', '0', '0', '0'},
{'0', '0', '0', '0', '0'}};
Solution sol;
cout << sol.numIslands(grid);
system("pause");
return 0;
} | true |
619c0736be68cb18d17722af64ac90beb2700266 | C++ | MultivacX/leetcode2020 | /algorithms/easy/1991. Find the Middle Index in Array.h | UTF-8 | 636 | 3.34375 | 3 | [
"MIT"
] | permissive | // 1991. Find the Middle Index in Array
// https://leetcode.com/problems/find-the-middle-index-in-array/
// Runtime: 7 ms, faster than 48.29% of C++ online submissions for Find the Middle Index in Array.
// Memory Usage: 12.4 MB, less than 39.79% of C++ online submissions for Find the Middle Index in Array.
class Solution {
public:
int findMiddleIndex(vector<int>& nums) {
int sum = accumulate(nums.begin(), nums.end(), 0);
for (int i = 0, pre = 0; i < nums.size(); ++i) {
if (pre == sum - pre - nums[i])
return i;
pre += nums[i];
}
return -1;
}
}; | true |
f24ebd5c5b0fcea63b9bd18831d2b5ace691080c | C++ | Barrilao/Fundamentos_de_Programaci-n | /Sesion 5/Ejercicio 16 (sesion5).cpp | ISO-8859-1 | 934 | 4.0625 | 4 | [] | no_license | //Juan Snchez Rodrguez
/*Modifique el ejercicio 7 para que el programa nos diga si los tres valores ledos estn
ordenados de forma ascendente, ordenados de forma descendente o no estn
ordenados. Para resolver este problema, debe usar una variable de tipo enumerado.*/
#include <iostream>
using namespace std;
enum class Numeros_en_Orden
{ascendente, descendente, no_ordenado};
int main()
{
int x, y, z;
Orden orden;
cout << "Introduzca los 3 enteros ";
cin >> x;
cin >> y;
cin >> z;
if((x<y&&y<z))
orden = Orden::ascendente;
if((x>y&&y>z))
orden = Orden::descendente;
else
orden = Orden::no_ordenado;
cout << "\n\n";
switch(orden){
case Orden::ascendente:
cout << "\nEs ascendente";
break;
case Orden::descendente:
cout << "\nEs descendente";
break;
case Orden::no_ordenado:
cout << "\nNo esta ordenado";
break;
}
}
| true |
ea6746f26a058e084ae65f6f3e00d7ef098d9cc0 | C++ | mitaka00/Sofia-University | /Introduction to Programming/Homeworks/FourthHomework/secondTask/secondTask.cpp | UTF-8 | 2,971 | 3.453125 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <cmath>
using namespace std;
long findMinNumber(long num1, long num2) {
if (num1 > num2) {
return num2;
}
else {
return num1;
}
}
long findMaxNumber(long num1, long num2) {
if (num1 > num2) {
return num1;
}
else {
return num2;
}
}
int returnDecimalDigit(char lastDigit)
{
if (lastDigit >= '0' && lastDigit <= '9')
return (int)lastDigit - '0';
else
return (int)lastDigit - 'A' + 10;
}
int sumOfDigitsInNumber(char *number, int numberSystem) {
int len = strlen(number);
int sum = 0;
for (int i = len - 1; i >= 0; i--)
{
if (returnDecimalDigit(number[i]) >= numberSystem)
{
cout<<"Invalid Number";
return -1;
}
sum += returnDecimalDigit(number[i]);
}
return sum;
}
int NOD(long num1,long num2) {
for (int i = findMinNumber(num1,num2); i >=1; i--)
{
if (num1 % i == 0 && num2 % i == 0) {
return i;
}
}
}
long findPowOfNumber(long num1, long num2) {
long result = num1;
for (int i = 1; i < num2; i++)
{
result *= num1;
}
return result;
}
bool isNumberGreen(long number) {
long token = number;
unsigned long sum = 0;
while (token > 0) {
int lastDigit = token % 10;
sum += lastDigit * lastDigit * lastDigit;
token /= 10;
}
if (sum == number) {
return true;
}
else {
return false;
}
}
long findSumOfGreenNumbers(long num1, long num2) {
long sum = 0;
for (int i = findMinNumber(num1,num2); i <=findMaxNumber(num1,num2) ; i++)
{
if (isNumberGreen(i)) {
sum += i;
}
}
return sum;
}
bool isNumberRed(long number) {
long token = number;
unsigned long sum = 0;
while (token > 0) {
int lastDigit = token % 10;
sum += lastDigit;
token /= 10;
}
if (number % sum == 0) {
return true;
}
else {
return false;
}
}
long findSumOfRedNumbers(long num1, long num2) {
long sum = 0;
for (int i = findMinNumber(num1, num2); i <= findMaxNumber(num1, num2); i++)
{
if (isNumberRed(i)) {
sum += i;
}
}
return sum;
}
long findDSumOfGreenNumbersMinusSumOfRedNumbers(long num1, long num2) {
return findSumOfGreenNumbers(num1, num2) - findSumOfRedNumbers(num1, num2);
}
double calculateTheCos(double x,int n) {
if (n == 0) {
return 0;
}
else if (n == 1) {
return 1;
}
else {
double sum = 1;
int fakt = 2;
for (int i = 2; i <= n; i++)
{
double currentNum=1.0;
for (int j = 1; j <= fakt; j++)
{
currentNum = currentNum * x / j;
}
cout << currentNum<<endl;
if (i % 2 == 0) {
sum -= currentNum;
}
else {
sum += currentNum;
}
fakt += 2;
}
return sum;
}
}
double calculateTheSin(double x, int n) {
double cos = calculateTheCos(x,n);
return sqrt(1 - cos * cos);
}
double calculateTheTg(double x, int n) {
return sqrt(calculateTheSin(x, n) / calculateTheCos(x, n));
}
double calculateTheCotg(double x, int n) {
return sqrt(calculateTheCos(x, n) / calculateTheSin(x, n));
}
int main() {
char str[] = "723";
cout << sumOfDigitsInNumber(str, 8);
return 0;
} | true |
aa16974e4f048c52100617e03f4e54101d7cbe96 | C++ | felixhe97/notAdBlock | /main.cpp | UTF-8 | 794 | 3.046875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include "rangeFilter.hpp"
#include "medianFilter.hpp"
int main(){
RangeFilter rf;
std::vector<double> test1 = {
0.03, 0.02, 0.0301, 0.0299, 0.3, 5, 49, 49.99, 50, 50.01, 50.0001,
49.999, -234
};
for (double distance : rf.update(test1)) {
std::cout << distance << " ";
}
std::cout << '\n';
MedianFilter mf(3);
std::vector<std::vector<double>> testMedian = {
{0, 1, 2, 1, 3},
{1, 5, 7, 1, 3},
{2, 3, 4, 1, 0},
{3, 3, 3, 1, 3},
{10, 2, 4, 0, 0}
};
for (std::vector<double> &values : testMedian) {
for (double distance : mf.update(values)) {
std::cout << distance << " ";
}
std::cout << '\n';
}
return 0;
} | true |
43d76698a595701a00c367dad52660e58b588f3a | C++ | kmatsu3/Active_Arc | /active_arc_constraint.cpp | UTF-8 | 1,929 | 2.671875 | 3 | [] | no_license | #include "active_arc_state.hpp"
/*
Operation
*/
void state_active_arc_class::initialize_constraint_stress()
{
shear_constraint_stress.clear();
shear_cos_minus_second_power.clear();
for(long int arc_index=0;arc_index<number_of_arcs;arc_index++)
{
shear_constraint_stress.push_back(0.0);
shear_cos_minus_second_power.push_back(0.0);
};
}
//
void state_active_arc_class::calculate_constraint()
{
if(shear_constraint_switch)
{
calculate_shear_cos_minus_second_power();
calculate_constraint_energy();
calculate_constraint_stress();
};
};
//
void state_active_arc_class::calculate_constraint_energy()
{
calculate_constraint_shear_energy();
};
//
void state_active_arc_class::calculate_constraint_stress()
{
calculate_constraint_shear_stress();
};
//
void state_active_arc_class::calculate_shear_cos_minus_second_power()
{
for(
long int arc_index=0;
arc_index<number_of_arcs;
arc_index++
)
{
if(
shear[arc_index] < 0.5*PI-bit_parameter
&&
shear[arc_index] > -0.5*PI+bit_parameter
)
{
shear_cos_minus_second_power[arc_index]
=pow(cos(shear[arc_index]),shear_constraint_power);
}
else
{
shear_cos_minus_second_power[arc_index]
=pow(cos(0.5*PI-bit_parameter),shear_constraint_power);
};
};
};
//
void state_active_arc_class::calculate_constraint_shear_energy()
{
constraint_shear_energy
=std::accumulate(
shear_cos_minus_second_power.begin(),
shear_cos_minus_second_power.end(),
0.0
)*shear_constraint_modulus
/std::fabs(shear_constraint_power);
}
//
void state_active_arc_class::calculate_constraint_shear_stress()
{
for(
long int arc_index=0;
arc_index<number_of_arcs;
arc_index++
)
{
shear_constraint_stress[arc_index]
=tan(shear[arc_index])
*shear_cos_minus_second_power[arc_index]
*shear_constraint_modulus;
};
}
| true |
bf5f53e844cb051af5a550fd96546ae83beb836a | C++ | biagiom/Arduino101-sketches | /temperature_BLE/temperature_BLE.ino | UTF-8 | 4,778 | 2.890625 | 3 | [] | no_license | // include all class and methods related to Arduino/Genuino 101 BLE
#include <CurieBLE.h>
// use Arduino/Genuino 101 as peripheral
BLEPeripheral Genuino101peripheral;
// Define a new service in order to get temperature value
// Use a custom random UUID
BLEService tempService("6F182000-D588-4779-A953-19799C1A112C");
// Define a characteristic attribute with property Read/Notify :
// In this way we can get temperature value every time the value
// read from the sensor is different from the previous value
BLEFloatCharacteristic tempChar("6F182002-D588-4779-A953-19799C1A112C", BLERead | BLENotify);
// the LM35 temperature sensor is connected to analog pin A0
const uint8_t sensorPin = A0;
// variable to store the prevoius temperature value
float oldTempValue;
long startTime;
void setup() {
// start Serial comunication with 9600 bps baudrate
Serial.begin(9600);
// wait for opening the Serial port since Arduino/Genuino 101
// has a native USB and uses virtual serial port
while(!Serial) ;
// get the start time
startTime = millis();
// Set the local name using for advertising
// This name will appear in advertising packets
// and can be used by remote devices to identify Genuino 101
Genuino101peripheral.setLocalName("BleTemp");
Genuino101peripheral.setAppearance(BLE_GAP_APPEARANCE_TYPE_GENERIC_COMPUTER);
// Set the name of the BLE Peripheral Device
Genuino101peripheral.setDeviceName("GENUINO 101");
// set the UUID of temperature service
Genuino101peripheral.setAdvertisedServiceUuid(tempService.uuid());
// Add the new declarated attribute :
// Temperature Service and its characteristics
Genuino101peripheral.addAttribute(tempService);
Genuino101peripheral.addAttribute(tempChar);
pinMode(sensorPin, INPUT);
digitalWrite(sensorPin, LOW);
// get temperature value :
// ADC of Arduino/Genuino 101 has 10-bit resolution, so
// analogRead() returns a value from 0 to 1024.
// Using the following formula we can get the analog read value :
// 3.30 : 1023 = Vout : analogReadvalue;
// moreover according to the LM35 datasheet the LM35 temperature
// sensor produces voltages from 0 to +1V using this
// relationship between the temperature in Celsius degrees and
// the Vout (Voltage output of LM35) : 1°C => 10mV (0.01 V)
// We can get the temperature value using this formula :
// 10mV : 1°C = Vout (V) : temp (°C)
// temp = (Vout * 1°C) / 0.01V ( 10mV = 0,01 V);
// but we can rewrite the above equation in this way :
// temp = (Vout * 1°C) * 100V since 1/0.01 V = 100 V
// Furthermore Vout = (analogReadValue * 3.30) / 1023,
// so replacing the Vout expression in the first formula
// we obtain the temperature value :
// temp = (3.30 * analogRead(sensorPin) * 100.00) / 1023.00
oldTempValue = (3.30 * analogRead(sensorPin) * 100.00) / 1023.00;
Serial.print("Initial temperature value : ");
Serial.print(oldTempValue);
Serial.println(" °C");
// add the initial temperature value to Characteristic Value
tempChar.setValue(oldTempValue);
// start advertising BLE Temperature service
Genuino101peripheral.begin();
Serial.println("Starting Genuino 101 advertising service.");
Serial.println("Waiting for connection with other BLE devices ...");
}
void loop() {
// listen for BLE peripherals to connect:
BLECentral centralDevice = Genuino101peripheral.central();
// if a central is connected to peripheral (Genuino 101):
if(centralDevice) {
Serial.print("Connected to central BLE device with address : ");
// print the central's MAC address:
Serial.println(centralDevice.address());
// while the central device is still connected to peripheral:
while(centralDevice.connected()) {
// if 400 milliseconds have passed, read the new sensor value
// and send the last read value to the Central device
long newTime = millis();
if((newTime - startTime) > 400) {
startTime = newTime;
// update temperature value
updateTempValue();
}
}
Serial.print("Disconnected from central BLE device with address : ");
Serial.println(centralDevice.address());
}
}
void updateTempValue(void) {
// get the new value to the temperature sensor
float newTempValue = (3.30 * analogRead(sensorPin) * 100.00) / 1023.00;
// if the new temperature value which is different from the previous one
if(newTempValue != oldTempValue) {
// print in the Serial Monitor the new temperature value
Serial.print("New temperature value : ");
Serial.print(newTempValue);
Serial.println(" °C");
// send the new value to the BLE Central device
tempChar.setValue(newTempValue);
// update the old temperature value
oldTempValue = newTempValue;
}
}
| true |
973d30e711af33965838ff667fa2287738fd89b5 | C++ | EdCarney/Anytime_RRT_Sharp | /Anytime_RRT_Sharp/src/tests/ManeuverEngineTests.hpp | UTF-8 | 1,264 | 2.59375 | 3 | [] | no_license | #include <gtest/gtest.h>
#include "../Geometry3D.hpp"
#include "../ManeuverEngine.hpp"
#pragma region ObstacleIntersection
TEST(ObstacleIntersection, Bug_001_Forward)
{
State start(87.7206, 102.164, 55.9721, 5.90294, 0.405405);
State final(107.423, 66.3749, 28.3135, 1.18302, -0.019936);
Point rectMinP(84.85440264061208, 78.30774495501349, 0.0);
Point rectMaxP(91.12307617710908, 88.17614485668203, 78.60665605131811);
Rectangle r(rectMinP, rectMaxP);
ManeuverEngine::maneuverType = Dubins3d;
auto path = ManeuverEngine::generatePath(start, final);
bool unsafe = false;
for (auto p : path)
if (r.intersects(p))
unsafe = true;
ASSERT_TRUE(unsafe);
}
TEST(ObstacleIntersection, Bug_001_Reverse)
{
State start(87.7206, 102.164, 55.9721, 5.90294, 0.405405);
State final(107.423, 66.3749, 28.3135, 1.18302, -0.019936);
Point rectMinP(84.85440264061208, 78.30774495501349, 0.0);
Point rectMaxP(91.12307617710908, 88.17614485668203, 78.60665605131811);
Rectangle r(rectMinP, rectMaxP);
auto path = ManeuverEngine::generatePath(final, start);
bool unsafe = false;
for (auto p : path)
if (r.intersects(p))
unsafe = true;
ASSERT_TRUE(unsafe);
} | true |
a71fce9b65659acceadfc6542b75aad89024b385 | C++ | FFMG/myoddweb.piger | /monitor/ActionMonitor/IMessagesHandler.h | UTF-8 | 806 | 3.0625 | 3 | [
"MIT"
] | permissive | #pragma once
class IMessagesHandler
{
public:
IMessagesHandler();
virtual ~IMessagesHandler();
/**
* \brief display a message
* \param sText the text we want to display
* \param elapseMiliSecondsBeforeFadeOut how long we want to display the message for before we fade out.
* \param totalMilisecondsToShowMessage how long we want the message to be displayed before fading out.
* \return if we were able to display the message or not.
*/
virtual bool Show(const std::wstring& sText, long elapseMiliSecondsBeforeFadeOut, long totalMilisecondsToShowMessage) = 0;
/**
* \brief Kill all the currently active message windows.
*/
virtual void CloseAll() = 0;
/**
* \brief Wait for all the active windows to complete.
*/
virtual void WaitForAllToComplete() = 0;
};
| true |
493383cc5aa720b859cb6b2f3041ea7cce224b34 | C++ | satvik007/codes_from_class | /Algorithms and Data Sturctures/Week1/dfs/dlist.cpp | UTF-8 | 1,416 | 3.546875 | 4 | [
"MIT"
] | permissive | #include <bits/stdc++.h>
#include "dlist.h"
Dlist* DlistCreateNew(){
Dlist* new1 = (Dlist*) malloc (sizeof (Dlist*));
new1->root1 = NULL;
new1->root2 = NULL;
new1->size = 0;
return new1;
}
void DlistAddAtBack(Dlist* current, int val){
Node* new1 = (Node*) malloc (sizeof (Node*));
new1->data = val;
current->size += 1;
new1->next = NULL;
new1->prev = NULL;
if(current->root1 == NULL){
current->root1 = new1;
current->root2 = new1;
}
else{
current->root2->next = new1;
new1->prev = current->root2;
current->root2 = new1;
}
}
void DlistAddAtFront(Dlist* current, int val){
Node* new1 = (Node*) malloc (sizeof (Node*));
new1->data = val;
new1->prev = NULL;
new1->next = NULL;
current->size += 1;
if(current->root1 == NULL){
current->root1 = new1;
current->root2 = new1;
}
else{
current->root1->prev = new1;
new1->next = current->root1;
current->root1 = new1;
}
}
void DlistPrintForward(Dlist* current){
if(current == NULL) return;
Node* temp = current->root1;
int flag = 1;
while(temp != NULL && (temp != current->root1 || flag)){
flag = 0;
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
void DlistPrintReverse(Dlist* current){
if(current == NULL) return;
Node* temp = current->root2;
int flag = 1;
while(temp != NULL && (temp != current->root2 || flag)){
flag = 0;
printf("%d ", temp->data);
temp = temp->prev;
}
printf("\n");
}
| true |
1383025c81d614f170d4a33f04b5e1483cccb9fb | C++ | tbbug/CleverManagerV3 | /CleverManagerV3/common/chars/line_drawgraphic.cpp | UTF-8 | 9,444 | 2.59375 | 3 | [] | no_license | /*
* drawgraphic.cpp
* 画布的基本操作
*
* Created on: 2016年10月11日
* Author: Lzy
*/
#include "line_drawgraphic.h"
Line_DrawGraphic::Line_DrawGraphic(QWidget *parent) : QWidget(parent)
{
customPlot = new QCustomPlot(this);
layout = new QGridLayout(this);
layout->addWidget(customPlot);
layout->setSpacing(0);
layout->setContentsMargins(0, 0, 0, 0);
customPlot->setMinimumHeight(150);
m_xRange = 60;
m_startTime = QDateTime::currentDateTime().toMSecsSinceEpoch()/1000; //获取当前时间
// Note: we could have also just called customPlot->rescaleAxes(); instead
// Allow user to drag axis ranges with mouse, zoom with mouse wheel and select graphs by clicking:
// customPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables);
}
Line_DrawGraphic::~Line_DrawGraphic()
{
}
/**
* @brief 默认初始化
*/
void Line_DrawGraphic::initCurVolFun(void)
{
initxAxis(); //初始化时间轴
setxAxis(60); //设置时间轴的范围为60S
QString curStr;
// curStr = tr("电流"); ////====
inityAxis(curStr); //初始化电流轴
setyAxis(0,10); //默认电流范围为20A
QString volStr;
// volStr = tr("电压"); /////====
inityAxis2(volStr); //初始化电压轴
setyAxis2(160,300);
initxAxis2();
initLegende();
}
/**
* @brief 增加功率画布
* @param name
* @return
*/
QCPGraph *Line_DrawGraphic::addPowerGraph(const QString &name)
{
QCPGraph *graph = customPlot->addGraph();
QPen pen;
// pen.setStyle(Qt::DashLine); //虚线
pen.setWidth(3);
pen.setColor(QColor(55,40,255));
// graph->setBrush(QBrush(QColor(255,50,30,20)));
graph->setPen(pen);
graph->setName(name);
return graph;
}
/**
* @brief 画数据
* @param graph
* @param value
*/
void Line_DrawGraphic::addData(QCPGraph *graph, double value,bool onlyEnlarge)
{
int key = QDateTime::currentDateTime().toMSecsSinceEpoch()/1000; //获取当前时间
graph->addData(key,value);
graph->rescaleValueAxis(onlyEnlarge);
if(key - m_startTime > m_xRange) /*最开始与现在时间差大于范围*/
{
graph->removeDataBefore(key-m_xRange-2); /*移除过时数据*/
customPlot->xAxis->setRange(key, m_xRange,Qt::AlignRight);/*调整范围*/
}
customPlot->replot();
}
/**
* @brief 清除所有数据
* @param graph
*/
void Line_DrawGraphic::clearData(QCPGraph *graph)
{
graph->clearData();
}
/**
* @brief 增加电压画布
*/
QCPGraph *Line_DrawGraphic::addVoltageGraph(const QString &name)
{
QCPGraph *graph = customPlot->addGraph(customPlot->xAxis, customPlot->yAxis2);
QPen pen;
// pen.setStyle(Qt::DashLine); //点线
pen.setWidth(3);
pen.setColor(QColor(0,204,255));
// graph->setBrush(QBrush(QColor(216,231,224)));
graph->setPen(pen);
graph->setName(name);
return graph;
}
/**
* @brief 增加电压报警画布
* @param name
* @return
*/
QCPGraph *Line_DrawGraphic::addVolAlarmGraph(void)
{
QCPGraph *graph = customPlot->addGraph(customPlot->xAxis, customPlot->yAxis2);
graph->setPen(QPen(Qt::blue));
setScatterStyle(graph,5);
customPlot->legend->removeItem(customPlot->legend->itemCount()-1);
return graph;
}
/**
* @brief 增加电流画布
*/
QCPGraph *Line_DrawGraphic::addCurrentGraph(const QString &name)
{
QCPGraph *graph = customPlot->addGraph();
QPen pen;
pen.setWidth(3);
pen.setColor(QColor(55,3,152));
// graph->setBrush(QBrush(QColor(221,213,255)));
graph->setPen(pen);
graph->setName(name);
return graph;
}
/**
* @brief 增加电流报警画布
* @return
*/
QCPGraph *Line_DrawGraphic::addCurAlarmtGraph(void)
{
QCPGraph *graph = customPlot->addGraph();
graph->setPen(QPen(Qt::red));
setScatterStyle(graph,6);
customPlot->legend->removeItem(customPlot->legend->itemCount()-1);
return graph;
}
/**
* @brief 显示legend
*/
void Line_DrawGraphic::initLegende(void)
{
customPlot->legend->setVisible(true);
// set locale to english, so we get english decimal separator:
customPlot->setLocale(QLocale(QLocale::English, QLocale::UnitedKingdom));
QFont legendFont = font();
legendFont.setPointSize(9);
customPlot->legend->setFont(legendFont);
//customPlot->legend->setBrush(QBrush(QColor(255,255,255,230))); // 背景色
// by default, the legend is in the inset layout of the main axis rect. So this is how we access it to change legend placement:
//customPlot->axisRect()->insetLayout()->setInsetAlignment(0, Qt::AlignBottom|Qt::AlignRight);
//customPlot->legend->setIconSize(50, 20); // 大小
}
/**
* @brief 报警时选择形状
*
*/
void Line_DrawGraphic::setScatterStyle(QCPGraph *graph, int id)
{
QVector<QCPScatterStyle::ScatterShape> shapes;
shapes << QCPScatterStyle::ssCross;
shapes << QCPScatterStyle::ssPlus;
shapes << QCPScatterStyle::ssCircle;
shapes << QCPScatterStyle::ssDisc;
shapes << QCPScatterStyle::ssSquare;
shapes << QCPScatterStyle::ssDiamond; // 5 电压报警图标
shapes << QCPScatterStyle::ssStar; // 6 电流报警图标
shapes << QCPScatterStyle::ssTriangle;
shapes << QCPScatterStyle::ssTriangleInverted;
shapes << QCPScatterStyle::ssCrossSquare;
shapes << QCPScatterStyle::ssPlusSquare;
shapes << QCPScatterStyle::ssCrossCircle;
shapes << QCPScatterStyle::ssPlusCircle;
shapes << QCPScatterStyle::ssPeace;
shapes << QCPScatterStyle::ssCustom;
graph->setLineStyle(QCPGraph::lsNone);
if (shapes.at(id) != QCPScatterStyle::ssCustom)
graph->setScatterStyle(QCPScatterStyle(shapes.at(id), 10)); // set scatter style:
}
/**
* @brief X轴初始化
*/
void Line_DrawGraphic::initxAxis(void)
{
customPlot->xAxis->setTickLabelType(QCPAxis::ltDateTime);
customPlot->xAxis->setDateTimeFormat("hh:mm:ss");
// customPlot->setFont(QFont("微软雅黑",12));
// customPlot->xAxis->setLabel("Time");
//customPlot->xAxis->setTickLabelRotation(30); //字体角度
// customPlot->xAxis->setAutoTickCount(10); //分配刻度数量
// customPlot->xAxis->setSubTickCount(4);
// customPlot->xAxis->setTickStep(1);
// customPlot->xAxis->setAutoTickStep(false); //设置是不自动分配刻度间距
}
/**
* @brief 时间轴范围增大
* @param range
*/
void Line_DrawGraphic::addxAxis(int range)
{
m_xRange += range;
customPlot->xAxis->setRange(m_startTime, m_xRange,Qt::AlignLeft);
}
/**
* @brief X轴花园设置 以时间 S为单位
*/
void Line_DrawGraphic::setxAxis(int range)
{
m_startTime = QDateTime::currentDateTime().toMSecsSinceEpoch()/1000; //获取当前时间
m_xRange = range;
customPlot->xAxis->setRange(m_startTime, m_xRange,Qt::AlignLeft);
}
/**
* @brief Y轴初始化
*/
void Line_DrawGraphic::inityAxis(const QString &lab)
{
customPlot->yAxis->setLabel(lab);
}
void Line_DrawGraphic::setyAxis(double lower, double upper)
{
customPlot->yAxis->setRange(lower, upper);
}
/**
* @brief 上轴初始化
*/
void Line_DrawGraphic::initxAxis2(void)
{
customPlot->xAxis2->setVisible(false);
customPlot->xAxis2->setTickLabels(false);
// connect(customPlot->yAxis, SIGNAL(rangeChanged(QCPRange)), customPlot->yAxis2, SLOT(setRange(QCPRange)));
}
/**
* @brief 右轴初始化
*/
void Line_DrawGraphic::inityAxis2(const QString &lab)
{
customPlot->yAxis2->setVisible(true);
customPlot->yAxis2->setLabel(lab);
}
/**
* @brief 设置右轴
*/
void Line_DrawGraphic::setyAxis2(double lower, double upper)
{
customPlot->yAxis2->setRange(lower, upper);
}
/**
* @brief 设置标题
*/
void Line_DrawGraphic::setTitle(const QString &title)
{
customPlot->plotLayout()->insertRow(0); // set title of plot:
customPlot->plotLayout()->addElement(0, 0, new QCPPlotTitle(customPlot, title));
}
/**
* @brief 设置画布名字
*/
void Line_DrawGraphic::setName(const QString &name)
{
customPlot->graph()->setName(name); // set graph name, will show up in legend next to icon:
}
/**
* @brief 初始化Axis 设置刻度显示方式
*/
void Line_DrawGraphic::initAxis(QCPAxis *Axis)
{
Axis->setBasePen(QPen(Qt::white, 1));
Axis->setTickPen(QPen(Qt::white, 1));
Axis->setSubTickPen(QPen(Qt::white, 1));
Axis->setTickLabelColor(Qt::white);
Axis->grid()->setPen(QPen(QColor(140, 140, 140), 1, Qt::DotLine));
Axis->grid()->setSubGridPen(QPen(QColor(80, 80, 80), 1, Qt::DotLine));
Axis->grid()->setSubGridVisible(true);
Axis->grid()->setZeroLinePen(Qt::NoPen);
Axis->setUpperEnding(QCPLineEnding::esSpikeArrow);
}
/**
* @brief 设置背景
*/
void Line_DrawGraphic::setBackground(void)
{
QLinearGradient plotGradient;
plotGradient.setStart(0, 0);
plotGradient.setFinalStop(0, 350);
plotGradient.setColorAt(0, QColor(80, 80, 80));
plotGradient.setColorAt(1, QColor(50, 50, 50));
customPlot->setBackground(plotGradient);
QLinearGradient axisRectGradient;
axisRectGradient.setStart(0, 0);
axisRectGradient.setFinalStop(0, 350);
axisRectGradient.setColorAt(0, QColor(80, 80, 80));
axisRectGradient.setColorAt(1, QColor(30, 30, 30));
customPlot->axisRect()->setBackground(axisRectGradient);
//customPlot->axisRect()->setBackground(QPixmap("./solarpanels.jpg"));
}
| true |
31ce4d7c332a00b98adfb50457f57f00fac2a3bc | C++ | MANISH762000/Hacktoberfest-2021 | /c++ basic concepts loops, func, array/11. Functions, Arrays & Pointers/passingArraytoFunction.cpp | UTF-8 | 392 | 3.125 | 3 | [
"MIT"
] | permissive | #include<iostream>
using namespace std;
void arrayIterationFunction(int test[])
{
for (int i = 0; i < 6 ; i++)
{
cout<<"myNum["<<i<<"]="<<test[i]<<endl;
}
}
int main()
{
int myNum[] = {1,3,4,5,6,7};
arrayIterationFunction(myNum);
//pass array to a function by reference
// and then let me know please
} | true |
31d677378424f1f9b46fa5a199f4535e8c2e96ae | C++ | folkerthoogenraad/ApryxEngine | /ApryxEngine/src/graphics/Image.h | UTF-8 | 665 | 3.015625 | 3 | [] | no_license | #pragma once
#include <vector>
#include <memory>
#include "math/Vector4.h"
namespace apryx {
class Image {
int m_Width;
int m_Height;
std::vector<Color32> m_Colors;
public:
Image(int width, int height);
void setColor(int x, int y, Color32 color);
Color32 getColor(int x, int y) const;
int getWidth() const { return m_Width; }
int getHeight() const { return m_Height; }
static Image checkerboard(int width, int height, Color32 a = Color32::white(), Color32 b = Color32::black());
static Image colored(int width, int height, Color32 color = Color32::white());
const std::vector<Color32> &getColors() const { return m_Colors; }
};
} | true |
26752de03f9fd1b99d3143ba3a40e359186717fd | C++ | ZGWJ/PAT | /c/A1006.cpp | UTF-8 | 1,037 | 2.875 | 3 | [] | no_license | #include <cstdio>
#include <cstring>
struct People{
char ID[20]={'\0'};
char sign_in[10]={'\0'};
char sign_out[10]={'\0'};
}first,last,temp;
int main(){
int n;
scanf("%d",&n);
scanf("%s %s %s",temp.ID,temp.sign_in,temp.sign_out);
strcpy(first.ID, temp.ID);
strcpy(last.ID, temp.ID);
strcpy(first.sign_in, temp.sign_in);
strcpy(last.sign_in, temp.sign_in);
strcpy(first.sign_out, temp.sign_out);
strcpy(last.sign_out, temp.sign_out);
for (int i=1; i<n; i++) {
scanf("%s %s %s",temp.ID,temp.sign_in,temp.sign_out);
if (strcmp(temp.sign_in, first.sign_in)<0) {
strcpy(first.ID, temp.ID);
strcpy(first.sign_in, temp.sign_in);
strcpy(first.sign_out, temp.sign_out);
}
if (strcmp(temp.sign_out, last.sign_out)>0) {
strcpy(last.ID, temp.ID);
strcpy(last.sign_in, temp.sign_in);
strcpy(last.sign_out, temp.sign_out);
}
}
printf("%s %s",first.ID,last.ID);
} | true |
5ce3dda3f3fba8970a45bbe126660f2224beb3eb | C++ | yosswi414/Competitive-Programming | /Matrix.h | UTF-8 | 4,047 | 3.515625 | 4 | [] | no_license | /*
* Date : Oct 30 2019
* Author : yosswi414
* Note : I learned a lot about C++ by writing this... basic function/operations like det(A) will be added later
*/
#pragma once
#include <iostream>
#include <vector>
#include <utility>
#include <exception>
extern const double eps;
// 要素の型が T の行列
template<class T>
class Matrix {
std::vector<std::vector<T>> mat;
public:
Matrix() {
mat = std::vector<std::vector<T>>(0);
};
Matrix(size_t r, size_t c, T x = static_cast<T>(0)) {
mat = std::vector<std::vector<T>>(r, std::vector<T>(c, x));
}
Matrix(std::pair<size_t, size_t> S, T x = static_cast<T>(0)) {
mat = std::vector<std::vector<T>>(S.first, std::vector<T>(S.second, x));
}
Matrix(std::initializer_list<std::vector<T>> init) {
size_t newRow = init.size(), newCol = newRow > 0 ? init.begin()->size() : 0;
*this = Matrix(newRow, newCol);
size_t r = 0;
for (const auto v : init) {
if (newCol != v.size()) throw std::invalid_argument("Matrix Operation Error: Cannot interpret non-matrix argument");
mat[r++] = v;
}
}
operator std::vector<std::vector<T>>() { return mat; }
size_t row() const {
return mat.size();
}
size_t column() const {
return row() > 0 ? mat[0].size() : 0;
}
std::vector<T>& operator [] (const size_t i) { return mat[i]; }
const std::vector<T>& operator [] (const size_t i) const { return mat[i]; }
std::pair<size_t, size_t> size() const {
return { row(), column() };
}
Matrix operator +(const Matrix B) const {
const Matrix& A = *this;
if (A.size() != B.size()) throw std::invalid_argument("Matrix Operation Error: Cannot operate two different size matrice (operator: +)");
Matrix X(A.size(), static_cast<T>(0));
for (size_t i = 0; i < row(); ++i) for (size_t j = 0; j < column(); ++j) X[i][j] = A[i][j] + B[i][j];
return X;
}
Matrix& operator +=(const Matrix A) {
return *this = (*this) + A;
}
Matrix operator *(const Matrix B) const {
const Matrix& A = *this;
if (A.column() != B.row()) throw std::invalid_argument("Matrix Operation Error: Column of left and row of right matrix must be equal in terms of multiplication");
Matrix X(A.row(), B.column(), static_cast<T>(0));
for (size_t i = 0; i < A.row(); ++i)for (size_t j = 0; j < B.column(); ++j) {
for (size_t k = 0; k < A.column(); ++k) X[i][j] += A[i][k] * B[k][j];
}
return X;
}
Matrix& operator *=(const Matrix A) {
return *this = (*this) * A;
}
Matrix operator *(const T k) const {
Matrix X = *this;
for (size_t i = 0; i < X.row(); ++i)for (size_t j = 0; j < X.column(); ++j)X[i][j] *= k;
return X;
}
Matrix& operator *=(const T k) {
Matrix& X = *this;
for (size_t i = 0; i < X.row(); ++i)for (size_t j = 0; j < X.column(); ++j)X[i][j] *= k;
return X;
}
Matrix operator ~() const {
const Matrix& A = *this;
Matrix X(column(), row());
for (size_t j = 0; j < column(); ++j)for (size_t i = 0; i < row(); ++i)X[j][i] = A[i][j];
return X;
}
Matrix operator ^(const Matrix& B) const {
const Matrix& A = *this;
if (A.size() != B.size()) throw std::invalid_argument("Matrix Operation Error: Cannot operate two different size matrice (operator: ^)");
Matrix X = A;
for (size_t i = 0; i < X.row(); ++i)for (size_t j = 0; j < X.column(); ++j)X[i][j] = A[i][j] ^ B[i][j];
return X;
}
};
template<class T>
std::ostream& operator<< (std::ostream& os, const Matrix<T> A) {
if (A.row() < 1)return os << std::endl;
if (A.row() == 1) {
os << "( ";
for (size_t i = 0; i < A.column(); ++i) {
try {
os << (fabs(A[0][i]) < eps ? 0.0 : A[0][i]);
}
catch (std::exception & excp) {
os << A[0][i];
}
os << " ";
}
os << ")\n";
return os;
}
else for (size_t i = 0; i < A.row(); ++i) {
os << (i ? (i < A.row() - 1 ? "| " : "\\ ") : "/ ");
for (size_t j = 0; j < A.column(); ++j) {
try {
os << (fabs(A[i][j]) < eps ? 0.0 : A[i][j]);
}
catch (std::exception & excp) {
os << A[i][j];
}
os << " ";
}
os << (i ? (i < A.row() - 1 ? "|" : "/") : "\\") << std::endl;
}
return os;
}
| true |
4ca9e65d8ba9ff53ddb8ceaac47ec3e58b7746ec | C++ | jonas2602/ParserGenerator | /ParserCore/src/Parser/ParseTree/RuleNode.cpp | UTF-8 | 1,507 | 3.03125 | 3 | [] | no_license | #include "RuleNode.h"
namespace ParserCore {
RuleNode::RuleNode()
{
}
RuleNode::~RuleNode()
{
}
ParseTree* RuleNode::GetParent() const
{
return nullptr;
}
ParseTree* RuleNode::GetChild(int Index) const
{
return m_Children[Index];
}
int RuleNode::GetChildCount() const
{
return (int)m_Children.size();
}
void RuleNode::SetParent(ParseTree* InParent)
{
}
std::vector<TokenNode*> RuleNode::GetTokens(int TokenType) const
{
std::vector<TokenNode*> OutTokens;
for (ParseTree* Child : m_Children)
{
TokenNode* ChildToken = (TokenNode*)Child;
if (ChildToken && ChildToken->IsTokenType(TokenType))
{
OutTokens.push_back(ChildToken);
}
}
return OutTokens;
}
TokenNode* RuleNode::GetToken(int TokenType, int Index) const
{
// Index out of bounds
if (Index < 0 || Index >= m_Children.size())
{
return nullptr;
}
int IteratorIndex = -1;
for (ParseTree* Child : m_Children)
{
TokenNode* ChildToken = (TokenNode*)Child;
if (ChildToken && ChildToken->IsTokenType(TokenType))
{
IteratorIndex++;
if (IteratorIndex == Index)
{
return ChildToken;
}
}
}
return nullptr;
}
TokenNode* RuleNode::AddChild(Token* InToken)
{
TokenNode* OutNode = new TokenNode(InToken);
OutNode->SetParent(this);
m_Children.push_back(OutNode);
return OutNode;
}
RuleNode* RuleNode::AddChild(RuleNode* InRuleNode)
{
m_Children.push_back(InRuleNode);
InRuleNode->SetParent(this);
return InRuleNode;
}
}
| true |
f2a7568f047cb79dc8daad5791fde847dd29610e | C++ | dhyoum/cpp | /DAY4/08_chronometry1.cpp | UTF-8 | 390 | 3.28125 | 3 | [] | no_license | #include <iostream>
using namespace std;
class Test
{
public:
void foo() & { cout << "foo &" << endl; }
void foo() && { cout << "foo &&" << endl; }
void operator()() & { cout << "operator () &" << endl; }
void operator()() && { cout << "operator ()&&" << endl; }
};
int main()
{
Test t;
t.foo(); // foo() &
Test().foo(); // foo() &&
t();
Test()();
}
| true |
3f9f9a60f180c443251aa406924fb9785d68eab3 | C++ | eiji03aero/simpledb | /scribbles/block_memory.cpp | UTF-8 | 844 | 3.640625 | 4 | [] | no_license | #include <iostream>
#include <cstring>
using namespace std;
const int page_size = 4;
class Page {
public:
char *content_;
Page() {
content_ = new char[page_size];
}
~Page() {
delete[] content_;
}
};
int main()
{
Page *page { new Page };
int a {4};
int b {8};
int a2;
int b2;
char* content_ptr {page->content_};
memcpy(page->content_, &a, sizeof(int));
memcpy(page->content_ + sizeof(int), &b, sizeof(int));
memcpy(&a2, page->content_, sizeof(int));
memcpy(&b2, page->content_ + sizeof(int), sizeof(int));
cout << a << endl; // 4
cout << b << endl; // 8
cout << a2 << endl; // 4
cout << b2 << endl; // 8
delete page;
memcpy(&a2, content_ptr, sizeof(int));
memcpy(&b2, content_ptr + sizeof(int), sizeof(int));
cout << a2 << endl; // 0
cout << b2 << endl; // 0
return 0;
}
| true |
8f9c675004e0a89e539150811b3a224a29b3d413 | C++ | gganis/AlphappLite | /Driver/src/AlephInteractiveHandler.cpp | UTF-8 | 6,799 | 2.609375 | 3 | [
"Apache-2.0"
] | permissive | //////////////////////////////////////////////////////////
//
// Implementation of
// CLASS AlephInteractiveHandler
// handles the communication with the external world
// for interactive sessions
//
// Author : C. Delaere
//
//////////////////////////////////////////////////////////
#include <iostream>
#include <string>
#include <string.h>
#include <stdio.h>
#include "AlephInteractiveHandler.h"
#include "AlephRegisteredAction.h"
#include "AlephAbstractInteractiveFunction.h"
#include "AlphaBanks.h"
AlephInteractiveHandler* AlephInteractiveHandler::TheAlephInteractiveHandler()
{
if (_theAlephInteractiveHandler)
return _theAlephInteractiveHandler;
else
_theAlephInteractiveHandler = new AlephInteractiveHandler;
return _theAlephInteractiveHandler;
}
AlephInteractiveHandler::AlephInteractiveHandler()
{
kae = true; // want all events (default)
me = "ALPHA++"; // why change it ?
you = "AlVisu"; // default client
}
AlephInteractiveHandler::~AlephInteractiveHandler()
{
ClearAll();
}
void AlephInteractiveHandler::ConfigureProtocol(string myname, string yourname)
{
me = myname;
you = yourname;
}
vector<AlephAbstractInteractiveFunction*> AlephInteractiveHandler::InteractiveFunctionsList = vector<AlephAbstractInteractiveFunction*>(0);
AlephInteractiveHandler* AlephInteractiveHandler::_theAlephInteractiveHandler = NULL;
void AlephInteractiveHandler::ClearAll()
{
for(vector<AlephAbstractInteractiveFunction*>::iterator existing = AlephInteractiveHandler::InteractiveFunctionsList.begin();
existing<AlephInteractiveHandler::InteractiveFunctionsList.end(); existing++)
{
delete *existing;
}
AlephInteractiveHandler::InteractiveFunctionsList.clear();
}
void AlephInteractiveHandler::InitiateConnection(int& ier)
{
//first send the list of user's functions
int funccnt = InteractiveFunctionsList.size();
for(vector<AlephAbstractInteractiveFunction*>::iterator existing = AlephInteractiveHandler::InteractiveFunctionsList.begin();
existing<AlephInteractiveHandler::InteractiveFunctionsList.end(); existing++)
{
vector<float> optionstosend;
optionstosend.push_back(--funccnt); // index
optionstosend.push_back((*existing)->OptionsList().size()); // option[0]
optionstosend.push_back((*existing)->Code()); // option[1]
SendMessage(-1,optionstosend,(*existing)->Name());
vector<pair<string,float> > options = (*existing)->OptionsList();
int cnt = -options.size();
for(vector<pair<string,float> >::iterator subopt=options.begin();subopt<options.end();subopt++)
{
vector<float> optionstosend;
optionstosend.push_back(funccnt); // index
optionstosend.push_back(cnt++); // option[0]
optionstosend.push_back((*existing)->Code()); // option[1]
optionstosend.push_back(subopt->second); // option[2]
SendMessage(-1,optionstosend,subopt->first);
}
}
//then send the ready message
vector<float> options;
options.push_back(0);
SendMessage(0,options,"Ready");
//wait for the first next message
int code = 0;
string comment = "";
while(code!=100)
{
vector<float> options = ReceiveMessage(code, comment);
if(code==999) {ier = 1; code = 100;}
}
kae = !options[0];
}
int AlephInteractiveHandler::HandleEvent(AlphaBanks& bb)
{
// This is the main "event loop" in interactive sessions
// message are received
// then the right function is called
// this is done as long as the user don't request the next event.
vector<float> dummy(0);
int code = 0;
string comment = "";
// first return the general event info...
for(vector<AlephAbstractInteractiveFunction*>::iterator existing = AlephInteractiveHandler::InteractiveFunctionsList.begin();
existing<AlephInteractiveHandler::InteractiveFunctionsList.end(); existing++)
{
if((*existing)->Code() == 100)
{
(*existing)->Run(dummy,bb);
break;
}
}
// now wait for another request...
while(1)
{
vector<float> options = ReceiveMessage(code, comment);
// look in the table for the appropriate function to call
for(vector<AlephAbstractInteractiveFunction*>::iterator existing = AlephInteractiveHandler::InteractiveFunctionsList.begin();
existing<AlephInteractiveHandler::InteractiveFunctionsList.end(); existing++)
{
if((*existing)->Code() == code)
{
(*existing)->Run(options,bb);
break;
}
}
if (code==100) kae = !options[0];
if ((code==100)||(code==999)) break;
}
return (code==999 ? 1 : 0);
}
void AlephInteractiveHandler::CloseConnection()
{
vector<float> options;
options.push_back(0);
SendMessage(999,options,"Terminated");
}
void AlephInteractiveHandler::SendMessage(int code, vector<float>& options, string comment)
{
char buffer[256];
// build the message according to options passed
string message = me;
message += "><";
sprintf ( buffer, "%i><", code);
message += buffer;
for(vector<float>::iterator i=options.begin();i<options.end();i++)
{
sprintf ( buffer, "%f><", *i);
message += buffer;
}
message += comment;
// send the message to the standard output.
cout << message << endl;
}
void Tokenize(const string& str, vector<string>& tokens,const string& delimiters = " ")
{
// Skip delimiters at beginning.
string::size_type lastPos = str.find_first_not_of(delimiters, 0);
// Find first "non-delimiter".
string::size_type pos = str.find_first_of(delimiters, lastPos);
while (string::npos != pos || string::npos != lastPos)
{
// Found a token, add it to the vector.
tokens.push_back(str.substr(lastPos, pos - lastPos));
// Skip delimiters. Note the "not_of"
lastPos = str.find_first_not_of(delimiters, pos);
// Find next "non-delimiter"
pos = str.find_first_of(delimiters, lastPos);
}
}
vector<float> AlephInteractiveHandler::ReceiveMessage(int& code, string& comment)
{
// wait for a full line...
char command[1024] = {0};
cin.getline(command,1024);
// test if it is a formated message (step1)
if(strcspn(command, you.c_str())!=0)
{
code = -1;
comment = "";
vector<float> result;
return result;
}
// put the result in a string
string tobeanalyzed = command;
// decompose the command in tokens
vector<string> tokens;
Tokenize(tobeanalyzed,tokens,"><");
// Now we have got the tokens... interpret them.
// test if it is a formated message (step2)
if(tokens.size()<4)
{
code = -1;
comment = "";
vector<float> result;
return result;
}
// seems ok... use it.
sscanf( tokens[1].c_str(), "%i", &code);
comment = *(tokens.end()-1);
vector<float> result;
for(vector<string>::iterator i=tokens.begin()+2;i<tokens.end()-1;i++)
{
float num;
sscanf( i->c_str(), "%f", &num);
result.push_back(num);
}
return result;
}
| true |
eacf3fbdc9a358f8c67d99ac142b6270eded1d85 | C++ | keaton-freude/NimbleEngine | /include/nimble/Mesh.h | UTF-8 | 8,719 | 2.640625 | 3 | [
"MIT"
] | permissive | #pragma once
#include <cstddef>
#include <initializer_list>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include <assimp/scene.h>
#include <spdlog/spdlog.h>
#include "nimble/IMesh.h"
#include "nimble/opengl-wrapper/VertexBufferFormat.h"
namespace Nimble {
template <typename T>
class Mesh : public IMesh {
friend class MeshFactory;
public:
typedef std::vector<T> VertexStorage;
typedef std::vector<unsigned int> IndexStorage;
private:
VertexStorage _vertices;
IndexStorage _indices;
size_t _numFaces{};
std::shared_ptr<VertexArrayObject> _vao;
public:
// support numFaces, so we could draw lines or points if we want
Mesh(VertexStorage vertices, IndexStorage indices, size_t numFaces, std::shared_ptr<VertexArrayObject> vao)
: _vertices(vertices), _indices(std::move(indices)), _numFaces(numFaces), _vao(std::move(vao)) {
}
Mesh(std::initializer_list<float> vertices, std::initializer_list<unsigned int> indices, std::shared_ptr<VertexArrayObject> vao)
: _vertices(vertices), _indices(indices), _vao(std::move(vao)) {
}
const VertexStorage &VertexData() {
return _vertices;
}
size_t VertexByteCount() {
return _vertices.size() * sizeof(VertexStorage::value_type);
}
size_t NumVertices() {
return _vertices.size();
}
const IndexStorage &IndexData() {
return _indices;
}
size_t IndexByteCount() {
return _indices.size() * sizeof(IndexStorage::value_type);
}
size_t NumIndices() {
return _indices.size();
}
[[nodiscard]] size_t GetNumBytes() const override {
return _vertices.size() * T::SizeInBytes();
}
[[nodiscard]] const void *GetData() const override {
return (void *)(&_vertices[0]);
}
[[nodiscard]] size_t GetNumFaces() const override {
return _numFaces;
}
[[nodiscard]] size_t GetFacesNumBytes() const override {
return _indices.size() * sizeof(unsigned int);
}
[[nodiscard]] const void *GetFaceData() const override {
return (void *)(&_indices[0]);
}
[[nodiscard]] std::shared_ptr<VertexArrayObject> GetVao() const override {
return _vao;
}
static std::shared_ptr<VertexArrayObject> CreateVao() {
auto vao = std::make_shared<VertexArrayObject>(&T::SetVertexAttribPointers);
vao->Bind();
vao->Unbind();
return vao;
}
private:
static std::shared_ptr<Mesh<Position>> BuildMesh_Position(const aiMesh *mesh) {
spdlog::info("[Position]: Building mesh with {} verts and {} faces", mesh->mNumVertices, mesh->mNumFaces);
// Return a mesh where we only read off Positions & Index data
std::vector<Position> verts(mesh->mNumVertices);
for(size_t i = 0; i < mesh->mNumVertices; ++i) {
Position p(mesh->mVertices[i].x, mesh->mVertices[i].y, mesh->mVertices[i].z);
verts[i] = p;
}
std::vector<unsigned int> indices;
for(size_t i = 0; i < mesh->mNumFaces; ++i) {
for(size_t j = 0; j < mesh->mFaces[i].mNumIndices; ++j) {
indices.push_back(mesh->mFaces[i].mIndices[j]);
}
}
return std::make_shared<Mesh<Position>>(verts, indices, mesh->mNumFaces, Mesh<Position>::CreateVao());
}
static std::shared_ptr<Mesh<PositionNormal>> BuildMesh_PositionNormal(const aiMesh *mesh) {
spdlog::info("[PositionNormal]: Building mesh with {} verts and {} faces", mesh->mNumVertices, mesh->mNumFaces);
// Return a mesh where we only read off Positions & Index data
std::vector<PositionNormal> verts(mesh->mNumVertices);
for(size_t i = 0; i < mesh->mNumVertices; ++i) {
PositionNormal p{};
p.position = glm::vec3(mesh->mVertices[i].x, mesh->mVertices[i].y, mesh->mVertices[i].z);
p.normal = glm::vec3(mesh->mNormals[i].x, mesh->mNormals[i].y, mesh->mNormals[i].z);
verts[i] = p;
}
std::vector<unsigned int> indices;
for(size_t i = 0; i < mesh->mNumFaces; ++i) {
for(size_t j = 0; j < mesh->mFaces[i].mNumIndices; ++j) {
indices.push_back(mesh->mFaces[i].mIndices[j]);
}
}
return std::make_shared<Mesh<PositionNormal>>(verts, indices, mesh->mNumFaces, Mesh<PositionNormal>::CreateVao());
}
static std::shared_ptr<Mesh<PositionColor>> BuildMesh_PositionColor(const aiMesh *mesh) {
spdlog::info("[PositionColor]: Building mesh with {} verts and {} faces", mesh->mNumVertices, mesh->mNumFaces);
std::vector<PositionColor> verts(mesh->mNumVertices);
for(size_t i = 0; i < mesh->mNumVertices; ++i) {
PositionColor p{};
p.position = glm::vec3(mesh->mVertices[i].x, mesh->mVertices[i].y, mesh->mVertices[i].z);
p.color = glm::vec4(mesh->mColors[0][i].r, mesh->mColors[0][i].g, mesh->mColors[0][i].b, mesh->mColors[0][i].a);
verts[i] = p;
}
std::vector<unsigned int> indices;
for(size_t i = 0; i < mesh->mNumFaces; ++i) {
for(size_t j = 0; j < mesh->mFaces[i].mNumIndices; ++j) {
indices.push_back(mesh->mFaces[i].mIndices[j]);
}
}
return std::make_shared<Mesh<PositionColor>>(verts, indices, mesh->mNumFaces, Mesh<PositionColor>::CreateVao());
}
static std::shared_ptr<Mesh<PositionNormalUv>> BuildMesh_PositionNormalUv(const aiMesh *mesh) {
spdlog::info("[PositionNormalUv]: Building mesh with {} verts and {} faces", mesh->mNumVertices, mesh->mNumFaces);
std::vector<PositionNormalUv> verts;
verts.resize(mesh->mNumVertices);
for(size_t i = 0; i < mesh->mNumVertices; ++i) {
verts[i] = PositionNormalUv(glm::vec3(mesh->mVertices[i].x, mesh->mVertices[i].y, mesh->mVertices[i].z),
glm::vec3(mesh->mNormals[i].x, mesh->mNormals[i].y, mesh->mNormals[i].z),
glm::vec2(mesh->mTextureCoords[0][i].x, mesh->mTextureCoords[0][i].y));
}
std::vector<unsigned int> indices;
for(size_t i = 0; i < mesh->mNumFaces; ++i) {
for(size_t j = 0; j < mesh->mFaces[i].mNumIndices; ++j) {
indices.push_back(mesh->mFaces[i].mIndices[j]);
}
}
return std::make_shared<Mesh<PositionNormalUv>>(verts, indices, mesh->mNumFaces, Mesh<PositionNormalUv>::CreateVao());
}
static std::shared_ptr<Mesh<PositionNormalUvTangentBitangent>> BuildMesh_PositionNormalUvTangentBitangent(const aiMesh *mesh) {
spdlog::info("[PositionNormalUvTangentBitangent]: Building mesh with {} verts and {} faces", mesh->mNumVertices, mesh->mNumFaces);
std::vector<PositionNormalUvTangentBitangent> verts;
verts.resize(mesh->mNumVertices);
for(size_t i = 0; i < mesh->mNumVertices; ++i) {
verts[i] = PositionNormalUvTangentBitangent(
glm::vec3(mesh->mVertices[i].x, mesh->mVertices[i].y, mesh->mVertices[i].z),
glm::vec3(mesh->mNormals[i].x, mesh->mNormals[i].y, mesh->mNormals[i].z),
glm::vec2(mesh->mTextureCoords[0][i].x, mesh->mTextureCoords[0][i].y),
glm::vec3(mesh->mTangents[i].x, mesh->mTangents[i].y, mesh->mTangents[i].z),
glm::vec3(mesh->mBitangents[i].x, mesh->mBitangents[i].y, mesh->mBitangents[i].z));
}
std::vector<unsigned int> indices;
for(size_t i = 0; i < mesh->mNumFaces; ++i) {
for(size_t j = 0; j < mesh->mFaces[i].mNumIndices; ++j) {
indices.push_back(mesh->mFaces[i].mIndices[j]);
}
}
return std::make_shared<Mesh<PositionNormalUvTangentBitangent>>(verts,
indices,
mesh->mNumFaces,
Mesh<PositionNormalUvTangentBitangent>::CreateVao());
}
};
// Tag for mesh loading to fall back to querying mesh details to try and figure
// out the type of the underlying data which is more expensive and potentially impossible
// to do correctly
struct AutoDetectVertexType;
class MeshFactory {
public:
// Factory
template <typename VertexType = AutoDetectVertexType>
static std::shared_ptr<IMesh> FromFile(const aiMesh *mesh) {
if constexpr(std::is_same_v<VertexType, PositionNormalUv>) {
return Mesh<PositionNormalUv>::BuildMesh_PositionNormalUv(mesh);
} else if constexpr(std::is_same_v<VertexType, PositionNormal>) {
return Mesh<PositionNormal>::BuildMesh_PositionNormal(mesh);
} else if constexpr(std::is_same_v<VertexType, PositionColor>) {
return Mesh<PositionColor>::BuildMesh_PositionColor(mesh);
} else if constexpr(std::is_same_v<VertexType, PositionNormalUvTangentBitangent>) {
return Mesh<PositionNormalUvTangentBitangent>::BuildMesh_PositionNormalUvTangentBitangent(mesh);
} else if constexpr(std::is_same_v<VertexType, AutoDetectVertexType>) {
if(mesh->HasNormals() && mesh->HasTextureCoords(0) && mesh->HasTangentsAndBitangents()) {
return Mesh<PositionNormalUvTangentBitangent>::BuildMesh_PositionNormalUvTangentBitangent(mesh);
} else if(mesh->HasNormals() && mesh->HasTextureCoords(0)) {
return Mesh<PositionNormalUv>::BuildMesh_PositionNormalUv(mesh);
} else if(mesh->HasNormals()) {
return Mesh<PositionNormal>::BuildMesh_PositionNormal(mesh);
} else {
return Mesh<Position>::BuildMesh_Position(mesh);
}
} else {
return Mesh<Position>::BuildMesh_Position(mesh);
}
}
};
} // namespace Nimble | true |
1c91a3df387e36d63fb79cd8a4732fc308af8a1a | C++ | sanwututu/c_plusplus | /平平无奇Rpg/Rpg(shop/Shop.cpp | GB18030 | 1,689 | 2.640625 | 3 | [] | no_license | #include "stdafx.h"
#include "Shop.h"
#include "ConfigMgr.h"
#include "GameMgr.h"
CShop::CShop()
:m_nState(0)
{
}
void CShop::setState(int nState)
{
m_nState = nState;
}
void CShop::update()
{
if (KEY_DOWN(VK_UP))
{
m_nState--;
if (m_nState < 0)
{
m_nState = m_VecData.size() - 1;
}
}
else if (KEY_DOWN(VK_DOWN))
{
m_nState++;
if (m_nState > m_VecData.size() - 1)
{
m_nState = 0;
}
}
else if (KEY_DOWN(VK_ESCAPE)){
CGameMgr::getInstance()->setState(E_STATE_MAP);
}
else if (KEY_DOWN(VK_SPACE))
{
CPlayer* pPlayer = CGameMgr::getInstance()->getGameMap()->getPlayer();
if (pPlayer->getMoney() >= m_VecData[m_nState]->nPrice){
pPlayer->setMoney(pPlayer->getMoney() - m_VecData[m_nState]->nPrice);
pPlayer->addItem(m_VecData[m_nState]);
}
else{
cout << "Ҳ" << endl;
}
}
}
void CShop::render()
{
cout <<shopName <<"ĵ"<< endl;
cout << "Money:" << CGameMgr::getInstance()->getGameMap()->getPlayer()->getMoney() << endl;
cout << " ID\tNAME\tPIC\tHP\tMP\tACK\tDEF\tPRICE" << endl;
for (int i = 0; i < m_VecData.size(); i++)
{
SGoodsDt* pDt = m_VecData[i];
if (m_nState == i)
{
cout << "->";
}
else{
cout << " ";
}
cout << pDt->nID << "\t" << pDt->strName << "\t" << pDt->strPic<< "\t" << pDt->nHp << "\t" << pDt->nMp
<< "\t" << pDt->nAck << "\t" << pDt->nDef << "\t" << pDt->nPrice << endl;
}
cout << " (SPACE) ˳(ESC)" << endl;
}
void CShop::refresh(int nNpcID){
m_VecData = CConfigMgr::getInstance()->m_pGoodsDtMgr->getDataByGoodsID(nNpcID);
shopName = CConfigMgr::getInstance()->m_pNpcDtMgr->getDataByID(nNpcID)->strName;
}
CShop::~CShop()
{
}
| true |
2550a69b00205fd0458b9e20643ee1debc62b286 | C++ | vaibhavdes/competitive-programming | /Interview/Math/SortedPermutationRank.cpp | UTF-8 | 962 | 3.640625 | 4 | [] | no_license | /*
Given a string, find the rank of the string amongst its permutations sorted lexicographically.
Assume that no characters are repeated.
Example :
Input : 'acb'
Output : 2
The order permutations with letters 'a', 'c', and 'b' :
abc
acb
bac
bca
cab
cba
The answer might not fit in an integer, so return your answer % 1000003
*/
int factorial(int n) {
int ans = 1;
for(int i=1;i<=n; i++) {
ans = ans * i;
ans = ans % 1000003;
}
return ans;
}
int Solution::findRank(string A) {
int i = 0;
int j,c;
int ans = 0;
vector<int> R;
while(A[i]!='\0') {
j = i;
c = 0;
while(A[j]!='\0') {
if(A[i]>A[j])
c++;
j++;
}
R.push_back(c);
i++;
}
c = 0;
i = R.size() -1;
j = 0;
while(i >= 0) {
ans += R[i] * factorial(j);
ans = ans % 1000003;
j++;
i--;
}
return ans + 1;
}
| true |
e277d0662554c0dc4c3466b467d39c03695ed9bd | C++ | Corelio/GexFinalProject | /SFML-dynamic/TileMap.cpp | UTF-8 | 2,828 | 2.671875 | 3 | [] | no_license | /**
* @file
* TileMap.cpp
* @author
* Marco Corsini Baccaro 2019
* @version 1.0
*
* @section DESCRIPTION
* Game Experience Development Course
* Class of 2018-2019
* Final Project
*
* @section LICENSE
*
* Copyright 2019
* Permission to use, copy, modify, and/or distribute this software for
* any purpose with or without fee is hereby granted, provided that the
* above copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* @section Academic Integrity
* I certify that this work is solely my own and complies with
* NBCC Academic Integrity Policy (policy 1111)
*/
#include "TileMap.h"
namespace GEX
{
TileMap::TileMap()
{
//Load tileset
tileSet_.loadFromFile(tileSetFile_);
}
TileMap::~TileMap()
{
}
bool TileMap::load(Map* tiles, unsigned int width, unsigned int height)
{
// resize the vertex array to fit the level size
vertices_.setPrimitiveType(sf::Quads);
vertices_.resize(width * height * 4);
// populate the vertex array, with one quad per tile
for (unsigned int i = 0; i < width; ++i)
for (unsigned int j = 0; j < height; ++j)
{
// get the current tile number
int tileNumber = tiles->getTile(i,j);
// if tile number is less than zero, do not draw
if (tileNumber < 0) {
continue; //move to the next tile
}
// find its position in the tileset texture
int tu = tileNumber % (tileSet_.getSize().x / tileSize_.x);
int tv = tileNumber / (tileSet_.getSize().x / tileSize_.x);
// get a pointer to the current tile's quad
sf::Vertex* quad = &vertices_[(i + j * width) * 4];
// define its 4 corners
quad[0].position = sf::Vector2f(i * tileSize_.x, j * tileSize_.y);
quad[1].position = sf::Vector2f((i + 1) * tileSize_.x, j * tileSize_.y);
quad[2].position = sf::Vector2f((i + 1) * tileSize_.x, (j + 1) * tileSize_.y);
quad[3].position = sf::Vector2f(i * tileSize_.x, (j + 1) * tileSize_.y);
// define its 4 texture coordinates
quad[0].texCoords = sf::Vector2f(tu * tileSize_.x + tu, tv * tileSize_.y + tv);
quad[1].texCoords = sf::Vector2f((tu + 1) * tileSize_.x + tu, tv * tileSize_.y + tv);
quad[2].texCoords = sf::Vector2f((tu + 1) * tileSize_.x + tu, (tv + 1) * tileSize_.y + tv);
quad[3].texCoords = sf::Vector2f(tu * tileSize_.x + tu, (tv + 1) * tileSize_.y + tv);
}
return true;
}
}
| true |
6fe90956811e31ba210d1ab3fda57b68ff883772 | C++ | narran22/2020algorithms-start | /x3-4(1).cpp | UTF-8 | 1,110 | 3.09375 | 3 | [
"MIT"
] | permissive | //竖式问题
#include <cstdlib>
#include <sstream>
#include <stdio.h>
#include <string.h>
#define maxn 20
using namespace std;
char s[maxn], buf[99];
//数字转换成字符串 用函数 sprintf
//判断是否在字符串中 用一个函数就行 strchr
int main()
{
scanf("%s", s);
int count = 0;
for (int i = 100; i < 1000; i++)
{
for (int j = 10; j < 100; j++)
{
int d = j / 10, e = j % 10, multi_res = i * j;
int s1 = i * d;
int s2 = i * e;
sprintf(buf, "%d%d%d%d%d", i, j, multi_res, s1, s2);
int ok = 1;
for (int i = 0; i < strlen(buf); i++)
{
if (strchr(s, buf[i]) == NULL)
ok = 0;
}
if (ok)
{
count++;
printf("<%d>\n", count);
printf("%5d\nX%4d\n-----\n%5d\n%4d\n-----\n%5d\n", i, j, s1, s2, multi_res);
}
}
}
printf("\nThe number of solutions = %d\n", count);
system("pause");
return 0;
} | true |