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
2428972f73d42fd2acf52e40e4f95f5ab8762a9a
C++
lacrymose/3bem
/unit_tests/test_nearfield_operator.cpp
UTF-8
5,000
2.671875
3
[]
no_license
#include "catch.hpp" #include "nearfield_operator.h" #include "continuity_builder.h" #include "gauss_quad.h" #include "laplace_kernels.h" #include "elastic_kernels.h" #include "mesh_gen.h" #include "integral_operator.h" #include "gte_wrapper.h" #include "util.h" //TODO: remove #include <iomanip> using namespace tbem; void test_polygon(const std::vector<Vec<double,2>>& polygon, size_t refine) { // turn the points into a 3bem mesh std::vector<Mesh<2>> mesh_pieces; for (size_t i = 0; i < polygon.size() - 1; i++) { mesh_pieces.push_back(line_mesh(polygon[i], polygon[i + 1])); } auto m = Mesh<2>::create_union(mesh_pieces).refine_repeatedly(refine); // generate the observation points for a galerkin evaluation auto pts = galerkin_obs_pts(m, gauss_facet<2>(2), m); // and check that they are all with the polygon for(auto p: pts) { auto furthest_limit_pt = p.loc + p.richardson_dir; auto success = is_point_in_polygon(furthest_limit_pt, polygon); // std::cout << "polygon:" << std::endl; // for (size_t i = 0; i < polygon.size(); i++) { // std::cout << polygon[i] << std::endl; // } // std::cout << "loc: " << std::setprecision(17) << p.loc << std::endl; // std::cout << "dir: " << p.richardson_dir << std::endl; // std::cout << "limitpt: " << furthest_limit_pt << std::endl; REQUIRE(success); } } TEST_CASE("richardson points always inside", "[nearfield_operator]") { //TODO: This test should probably be in the test_limit_direction file for (size_t i = 0; i < 30; i++) { // make a random triangle auto polygon = random_pts<2>(3); // then ensure that it is oriented counterclockwise by flipping the // orientation if it isn't auto normal = unscaled_normal({ Vec<double,3>{polygon[0][0], polygon[0][1], 0.0}, Vec<double,3>{polygon[1][0], polygon[1][1], 0.0}, Vec<double,3>{polygon[2][0], polygon[2][1], 0.0} }); if (normal[2] < 0) { std::swap(polygon[0], polygon[1]); } // the polygon must be closed (note that this cannot be done before // the clockwise check because vertices are swapped polygon.push_back(polygon[0]); test_polygon(polygon, 5); } } TEST_CASE("richardson points inside wedge -- regression test", "[nearfield_operator]") { test_polygon({{0, 0}, {150e3, -25e3}, {200e3, 0}, {150e3, 5e3}, {0, 0}}, 6); } TEST_CASE("interior obs pts", "[nearfield_operator]") { auto pts = interior_obs_pts<2>({{0, 1}, {1, 0}}, {{0, 1}, {0, 1}}, Mesh<2>{{ {{ {0, 0}, {1, 0} }} }} ); REQUIRE(pts.size() == 2); REQUIRE(hypot(pts[0].richardson_dir) == 0.0); auto correct = std::sqrt(1.25) * 0.4; REQUIRE_CLOSE(hypot(pts[1].richardson_dir), correct, 1e-12); } TEST_CASE("nearfield obs pts", "[nearfield_operator]") { auto m = circle_mesh({0, 0}, 1.0, 1); REQUIRE(m.facets.size() == 8); auto pts = galerkin_obs_pts(m, gauss(2), m); REQUIRE(pts.size() == 16); } TEST_CASE("Constrained nearfield matrix", "[nearfield_operator]") { auto m = circle_mesh({0, 0}, 1.0, 2); // Use a very large nearfield range (300000) to force everything to // be nearfield. LaplaceDouble<2> k; auto mthd = make_adaptive_integrator(1e-4, 4, 4, 3, 8, 300000, k); auto galerkin = make_galerkin_operator(1, m, mthd.obs_far_quad); auto obs_pts = galerkin_obs_pts(m, mthd.obs_far_quad, m); auto nearfield = make_nearfield_operator(obs_pts, m, mthd); auto matrix = galerkin.right_multiply(nearfield); auto dense_matrix = matrix.to_dense(); SECTION("Dense operator equals galerkin nearfield") { auto dense_matrix2 = *dense_boundary_operator(m, m, mthd, {m}).storage; REQUIRE_ARRAY_CLOSE(dense_matrix2, dense_matrix, dense_matrix2.size(), 1e-12); } SECTION("Dense condensation and sparse condensation are the same") { auto cm = from_constraints( convert_to_constraints(mesh_continuity(m.begin())) ); auto test = condense_matrix(cm, cm, matrix).to_dense().data(); auto correct = condense_matrix(cm, cm, dense_matrix).data(); REQUIRE(test.size() == correct.size()); REQUIRE_ARRAY_CLOSE(test, correct, correct.size(), 1e-12); //TODO: add a test for the rhs } } TEST_CASE("nearfield element midpoint", "[nearfield_operator]") { std::vector<Facet<2>> facets; facets.push_back({{{0.0, 0.0}, {1.0, 0.0}}}); Mesh<2> m{facets}; auto obs_pts = interior_obs_pts({{0.5, 0.0}}, {{0.0, 1.0}}, m); ElasticAdjointTraction<2> k(1.0, 0.25); auto mthd = make_adaptive_integrator(1e-4, 4, 4, 3, 8, 300000, k); auto op = make_farfield_correction_operator(obs_pts, m, mthd); for (size_t i = 0; i < op.values.size(); i++) { REQUIRE(!std::isnan(op.values[i])); } }
true
8cf479b64ea603b3f284b3e522b2f8614eb2e5e8
C++
moevm/oop
/8304/Mukhin_Aleksandr/lab4/units/government/Government.h
UTF-8
263
2.578125
3
[]
no_license
#ifndef LAB2_GOVERNMENT_H #define LAB2_GOVERNMENT_H #include "Unit.h" class Government : public Unit { public: Government() = default; Government(int def, int att, int intell) : Unit(def, att, intell) {} void greeting() const override; }; #endif
true
41d7434acaa2153d8eb52c563cbf018235305ef0
C++
LeandroES/EV1-E2
/EV1-E2.cpp
UTF-8
4,054
3.578125
4
[]
no_license
// EV1-E2.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include <iostream> #include <stdio.h> #include<time.h> #include<stdlib.h> int main() { int x, y, x2, y2; while (true) { srand(time(0)); std::cout << "<<Suma de los elementos de las Columnas y Filas, independiente," << "de una matriz, con valores ingresados por el usuario >> " << std::endl; std::cout << std::endl; std::cout << std::endl; std::cout << "Ingrese la cantidad de filas: " << std::endl; std::cin >> x; std::cout << "Ingrese la cantidad de columnas: " << std::endl; std::cin >> y; std::cout << std::endl; std::cout << std::endl; int a[x][y]; for (int i = 0; i < x; i++) { //i=0 & i<x & i++ ---> 1 + 1 + 1 for (int j = 0; j < y; j++) //j=0 & j<y & j++ ---> 1 + 1 + 1 { std::cout << "Ingrese valor para la posicion" << "[" << i + 1 << "]" << "[" << j + 1 << "]" << ":" << std::endl; //i+1 & j + 1 ---> 1 + 1 std::cin >> a[i][j]; }//Tf1(n) = (1 + n * ( 1 + 2 + 1) + 1) = 4n + 2 }//Tf2(n) = (1 + n * ( 1 + 4n + 2 + 1) + 1) = (4n^2)+4n+2 std::cout << "Su Matriz: " << std::endl; for (int i = 0; i < x; i++) { for (int j = 0; j < y; j++) { std::cout << a[i][j] << '\t'; }//Tf3(n) = (1 + n * (1 + 0 + 1)+ 1) = 2n + 2 std::cout << std::endl; }//Tf4(n) = (1 + n * (1 + 2n + 2 + 1)+ 1) = (2n^2)+4n+2 std::cout << std::endl; std::cout << std::endl; int sf[x]; std::cout << "Suma de cada fila: " << std::endl; int sum; for (int i = 0; i < y; i++) { sum = 0; for (int j = 0; j < x; j++) { sum = sum + a[i][j]; }//Tf5(n) = (1 + 1 + n * (1 + 2 + 1)+ 1) = 4n+3 sf[i] = sum; std::cout << "Suma de la fila: " << i + 1 << " es: " << sum << std::endl; }//Tf6(n) = (1 + n * (1 + (4n + 3 + 1 + 1 ) + 1) + 1) = (4n^2) + 7n + 2 int sc[y]; std::cout << "\nSuma de cada columna: " << std::endl; int suma; for (int i = 0; i < y; i++) { suma = 0; for (int j = 0; j < x; j++) { suma = suma + a[j][i]; }//Tf7(n) = (1 + 1 + n * (1 + 2 + 1)+ 1) = 4n + 3 sc[i] = suma; std::cout << "Suma de la columna: " << i + 1 << " es: " << suma << std::endl; }//Tf8(n) = (1 + n * (1 + (4n + 3 + 1 + 1 ) + 1) + 1) = (4n^2) + 7n + 2 std::cout << std::endl; std::cout << std::endl; std::cout << "Vector de sumas de filas = { "; for (int i = 0; i < x; i++) { std::cout << sf[i] << ", "; }//Tf9(n) = (1 + n * (1 + 0 + 1) + 1) = 2n + 2 std::cout << " } " << std::endl; std::cout << "Vector de sumas de columnas = { "; for (int i = 0; i < y; i++) { std::cout << sc[i] << ", "; }//Tf10(n) = (1 + n * (1 + 0 + 1) + 1) = 2n + 2 std::cout << " } " << std::endl; std::cout << std::endl; std::cout << std::endl; std::cout << std::endl; std::cout << std::endl; std::cout << std::endl; } return 0; //---> 1 } // Run program: Ctrl + F5 or Debug > Start Without Debugging menu // Debug program: F5 or Debug > Start Debugging menu // Tips for Getting Started: // 1. Use the Solution Explorer window to add/manage files // 2. Use the Team Explorer window to connect to source control // 3. Use the Output window to see build output and other messages // 4. Use the Error List window to view errors // 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project // 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
true
31131fdeb5c38aac02bac9bda3643f0266048081
C++
arvind-murty/CS135
/assignment4/Murty_Arvind_DA04__s4.cpp
UTF-8
7,046
3.5
4
[]
no_license
// Header Files #include "formatted_cmdline_io_v11.h" #include <cmath> using namespace std; // Global Constant Definitions const int LOWER_COOR = 0.00; const int HIGHER_COOR = 99.99; // Global Function Prototypes // Prints the title // Inputs: none // Outputs: none void printTitle(); // Gets a coordinate // Inputs: lowerCoor, higherCoor // Outputs: coordinate double getCoordinate(lowerCoor, higherCoor); // Prints a divider line // Inputs: none // Outputs: none void printDividerLine(); // Prints the top of the information table // Inputs: none // Outputs: none void printTableTop(); // Prints one line of data // Inputs: testNum, x1, y1, x2, y2, midpoint_x, midpoint_y, distance, slope // Outputs: none void printOneDataLine(int testNum, double x1, double y1, double x2, double y2, double midpoint_x, double midpoint_y, double distance, double slope); // Calculates distance between two points // Inputs: x1, y1, x2, y2 // Outputs: distance double calcDistance(double x1, double y1, double x2, double y2); // Calculates the midpoint of two coordinates // Inputs: coor1, coor2 // Ouputs: midpointCoor double calcMidpoint(double coor1, double coor2); // Calculates the slope of a line using two points // Inputs: x1, y1, x2, y2 // Outputs: slope double calcSlope(double x1, double y1, double x2, double y2); // Main Program Defintion int main() { // initialize program // initialize variables int first_test_number = 0, second_test_number; double first_x1 = 0, first_y1 = 0, first_x2 = 0, first_y2 = 0; double second_x1 = 0, second_y1 = 0, second_x2 = 0, second_y2 = 0; double first_distance = 0, second_distance = 0; double first_midpoint_x = 0, first_midpoint_y, second_midpoint_x, second_midpoint_y = 0; double first_slope = 0, second_slope = 0; // show title, with underline // function: printTitle printTitle(); // output a divider space // function: printEndLines printEndLines(1); // print divider line // function: printDividerLine printDividerLine(); // output a divider space // function: printEndLines printEndLines(1); // input Data // get first data set // acquire first test number from user // function: promptForInt first_test_number = promptForInt("Enter first test number: "); // output a divider space // function: printEndLines printEndLines(1); // get first point from user // acquire x value // function: getCoordinate first_x1 = getCoordinate(LOWER_COOR, HIGHER_COOR); // acquire y value // function: getCoordinate first_y1 = getCoordinate(LOWER_COOR, HIGHER_COOR); // output a divider space // function: printEndLines printEndLines(1); // get second point from user // acquire x value // function: getCoordinate first_x2 = getCoordinate(LOWER_COOR, HIGHER_COOR); // acquire y value // function: getCoordinate first_y2 = getCoordinate(LOWER_COOR, HIGHER_COOR); // output a divider space // function: printEndLines printEndLines(1); // print divider line // function: printDividerLine printDividerLine(); // output a divider space // function: printEndLines printEndLines(1); // get second data set // acquire second test number from user // function: promptForInt second_test_number = promptForInt("Enter second test number: "); // output a divider space // function: printEndLines printEndLines(1); // get first point from user // acquire x value // function: getCoordinate second_x1 = getCoordinate(LOWER_COOR, HIGHER_COOR); // acquire y value // function: getCoordinate second_y1 = getCoordinate(LOWER_COOR, HIGHER_COOR); // output a divider space // function: printEndLines printEndLines(1); // get second point from user // acquire x value // function: getCoordinate second_x2 = getCoordinate(LOWER_COOR, HIGHER_COOR); // acquire y value // function: getCoordinate second_y2 = getCoordinate(LOWER_COOR, HIGHER_COOR); // output a divider space // function: printEndLines printEndLines(1); // calculate midpoints // calculate midpoint one // function: calcMidCoor first_midpoint_x = calcMidCoor(first_x1, first_x2); // function: calcMidCoor first_midpoint_y = calcMidCoor(first_y1, first_y2); // calculate midpoint two // function: calcMidCoor second_midpoint_x = calcMidCoor(second_x1, second_x2); // function: calcMidCoor second_midpoint_y = calcMidCoor(second_y1, second_y2); // calculate distances // calculate distance one // function: calcDistance first_distance = calcDistance(first_x1, first_y1, first_x2, first_y2); // calculate distance two // function: calcDistance second_distance = calcDistance(second_x1, second_y1, second_x2, second_y2); // calculate slopes // calculate slope one // function: calcSlope first_slope = calcSlope(first_x1, first_y1, first_x2, first_y2); // calculate slope two // function: calcSlope second_slope = calcSlope(second_x1, second_y1, second_x2, second_y2); // output Data // print table top // function: printTableTop // print first data set // print first line of data // function: printOneDataLine printOneDataLine(first_test_number, first_x1, first_y1, first_x2, first_y2, first_midpoint_x, first_midpoint_y, first_distance, first_slope); // print second data set // print second line of data // function: printOneDataLine printOneDataLine(second_test_number, second_x1, second_y1, second_x2, second_y2, second_midpoint_x, second_midpoint_y, second_distance, second_slope); // end program // return zero return 0; } // Supporting function implementations
true
cb59fc03b142816845ba5a1714799189fa36330c
C++
Rohith-Rao/DSA-codes
/linkedlist/ckeck l2 in l1 linkedlist.cpp
UTF-8
927
3.328125
3
[]
no_license
#include <iostream> using namespace std; struct node { int data; node *next; }; typedef struct node *lptr; void print(lptr p) { if (p==NULL) { cout<<endl; return; } cout<<p->data<<" "; print(p->next); } void addend(lptr &p,int n) { lptr T; T=new(node); T->data=n; T->next=NULL; if(p==NULL) { p=T; return; } lptr t1=p; while(t1->next!=NULL) { t1=t1->next; } t1->next=T; } int check(lptr p,lptr q) { lptr t,s; while(p!=NULL) { t=q; s=p; int flag=0; if (s->data==t->data) { while(t!=NULL) { if (s->data!=t->data) { flag=1; break; } s=s->next; t=t->next; } if (flag==0) { return 1; } } p=p->next; } return 0; } int main() { lptr L; int n; L=NULL; cin>>n; while(n>0) { addend(L,n); cin>>n; } lptr L1; L1=NULL; cin>>n; while(n>0) { addend(L1,n); cin>>n; } n=check(L,L1); cout<<n<<endl; }
true
8fb7e006629a7dbcab3d3f5f8134b6f548398316
C++
nealwu/UVa
/volume113/11343 - Isolated Segments.cpp
UTF-8
1,798
2.921875
3
[]
no_license
#include <stdio.h> #define min(x, y) ((x) < (y) ? (x) : (y)) #define max(x, y) ((x) > (y) ? (x) : (y)) struct Point { double x, y; }; struct Segment { Point s, t; }; double in(double a, double b, double c) { return c >= a && c <= b; } int onLine(Segment a, Point c) { static double minx, maxx, miny, maxy; minx = min(a.s.x, a.t.x); maxx = max(a.s.x, a.t.x); miny = min(a.s.y, a.t.y); maxy = max(a.s.y, a.t.y); if(in(minx, maxx, c.x) != 0 && in(miny, maxy, c.y) != 0) { if((a.s.x-a.t.x)*(c.y-a.s.y) == (a.s.y-a.t.y)*(c.x-a.s.x)) { return 1; } } return 0; } double cross(Point &o, Point &a, Point &b) { return (a.x-o.x)*(b.y-o.y)-(a.y-o.y)*(b.x-o.x); } int intersection(Segment a, Segment b) { if(onLine(a, b.s) || onLine(a, b.t) || onLine(b, a.s) || onLine(b, a.t)) return 1; if(cross(a.s, a.t, b.s)*cross(a.s, a.t, b.t) < 0 && cross(a.t, a.s, b.s)*cross(a.t, a.s, b.t) < 0 && cross(b.s, b.t, a.s)*cross(b.s, b.t, a.t) < 0 && cross(b.t, b.s, a.s)*cross(b.t, b.s, a.t) < 0 ) return 1; return 0; } int main() { int t, n, i, j; Segment line[1000]; scanf("%d", &t); while(t--) { scanf("%d", &n); for(i = 0; i < n; i++) scanf("%lf %lf %lf %lf", &line[i].s.x, &line[i].s.y, &line[i].t.x, &line[i].t.y); int ans = 0; for(i = 0; i < n; i++) { int flag = 0; for(j = 0; j < n; j++) { if(i == j) continue; if(intersection(line[i], line[j])) { flag = 1; break; } } if(flag == 0) ans++; } printf("%d\n", ans); } return 0; }
true
1dfdac9b2214c0001906319c47870790d1217988
C++
GeekBand/GeekBand-CPP-1501-Homework
/G2015010236/CPP_Homework_Second/shapes.h
ISO-8859-1
2,324
3.765625
4
[]
no_license
#ifndef SHAPES_H #define SHAPES_H #include <iostream> class Shape; class Shape { public: Shape(int no = 0) : no_(no) {} virtual ~Shape() {} virtual int getArea() const = 0; // pure virtual function virtual void outputInfo() const = 0; // pure virtual function int no() const { return no_;} private: int no_; }; class Point { public: Point(int x = 0, int y = 0) : x_(x), y_(y) {} // class without pointer: use default big three ~Point() {} int x() const { return x_; } int y() const { return y_; } private: int x_; int y_; }; inline std::ostream& operator<< (std::ostream& os, const Point& point) { os << "( " << point.x() << " , " << point.y() << " )"; return os; } class Rectangle; class Rectangle: public Shape { public: Rectangle( int width = 0, int height = 0, int x = 0, int y = 0, int no = 0) : Shape(no), width_(width), height_(height), leftUp(Point(x, y)) {} // pure virtual function of base class must be realized by child class virtual int getArea() const { return this->height() * this->width(); } virtual void outputInfo() const; int width() const { return this->width_; } int height() const { return width_; } Point get_leftUp() const { return leftUp; }; private: int width_; int height_; Point leftUp; }; inline void Rectangle::outputInfo() const { std::cout << "Rectangle " << Shape::no() << " Width: " << this->width() << " Height: " << this->height() << " Leftup: " << this->get_leftUp() << " Area: " << this->getArea() << std::endl; } const double pi = 3.1415926; class Circle: public Shape { public: Circle(int radius = 0, int x =0, int y = 0, int no = 0) : Shape(no), center(Point(x, y)), radius_(radius) {} int radius() const { return radius_; } Point get_center() const { return center; } // pure virtual function of base class must be realized by child class virtual int getArea() const { return (int)(radius()*radius()* pi ); } // explicit type conversion double -> int virtual void outputInfo() const; private: Point center; int radius_; }; inline void Circle::outputInfo() const { std::cout << "Circle " << Shape::no() << " Radius: " << this->radius() << " Center: " << this->get_center() << " Area: " << this->getArea() << std::endl; } #endif
true
04f464174689f40968049e5991dde6e4b8ff04b3
C++
fahmiab11/STD-Final-Task
/listMataKuliah.cpp
UTF-8
2,726
3.21875
3
[ "MIT" ]
permissive
#include "listMataKuliah.h" void createListMataKuliah(listMataKuliah & L) { first(L) = NULL; last(L) = NULL; } addressMataKuliah alokasiMataKuliah(infotypeMataKuliah x) { addressMataKuliah P = new elmListMataKuliah; info(P) = x; next(P) = NULL; prev(P) = NULL; return P; } void insertLast(listMataKuliah & L, addressMataKuliah P) { addressMataKuliah q; if (first(L) == NULL) { first(L) = P; } else { q = first(L); while (next(q) != last(L)) { q = next(q); } next(q) = P; prev(P) = q; } } void printInfo(listMataKuliah L) { addressMataKuliah P = first(L); cout << "====================================================================================================" << endl; cout << "\t\t\t\t\t Data Mata Kuliah" << endl; cout << "====================================================================================================" << endl; if (first(L) != NULL) { do { cout << " - " << info(P) << endl; P = next(P); } while (P != NULL); } else { cout << " Maaf, Belum Ada Mata Kuliah yang Terdaftar" << endl; cout << " Silakan Input Terlebih Dahulu!" << endl; } } addressMataKuliah findElm(listMataKuliah L, infotypeMataKuliah x) { addressMataKuliah P = first(L); while ((P != NULL) && (info(P) != x)) { P = next(P); } return P; } void deleteFirst(listMataKuliah & L, addressMataKuliah & P) { if (first(L) == NULL) { cout << " List kosong" << endl; } else if (next(first(L)) == NULL) { P = first(L); first(L) = NULL; } else { P = first(L); first(L) = next(P); next(P) = NULL; prev(first(L)) == NULL; } } void deleteLast(listMataKuliah & L, addressMataKuliah & P) { if (first(L) == NULL) { cout << " List kosong" << endl; } else if (first(L) == last(L)) { P = first(L); first(L) = NULL; last(L) = NULL; } else { P = last(L); last(L) = prev(last(L)); prev(P) = NULL; next(last(L)) = NULL; } } void deleteAfter(listMataKuliah & L, addressMataKuliah Prec, addressMataKuliah & P) { if (first(L) == NULL) { cout << " List kosong" << endl; } else if (next(Prec) == NULL) { cout << " Tidak ada data yang dihapus" << endl; } else if (next(next(Prec)) == NULL) { P = last(L); last(L) = Prec; prev(P) = NULL; next(Prec) = NULL; } else { P = next(Prec); prev(next(P)) = Prec; next(Prec) = next(P); next(P) = NULL; prev(P) = NULL; } } void del(listMataKuliah & L, addressMataKuliah & P) { addressMataKuliah q; addressMataKuliah Prec; if (first(L) == P) { deleteFirst(L, P); } else if (next(P) == first(L)) { deleteLast(L, P); } else { deleteAfter(L, Prec, P); } }
true
b156bbc6af1df8022747575b75e3563fb2fd5be3
C++
pminardo/mojavegl-palm
/project/palm_tapwave/Src/blitter/BL_pixelutil.h
UTF-8
12,850
2.71875
3
[]
no_license
/************************************************************** * Copyright (c) 2006 PDA Performance, Inc. * All rights reserved. **************************************************************/ #ifndef __BL_PIXELUTIL_H_ #define __BL_PIXELUTIL_H_ /************************************************************** * Pixel Utils **************************************************************/ namespace pxutil { // Determines whether the specified surface buffer // is aligned for 32-bit blits. inline BOOL IsAligned32(LONG x, LONG y, LONG xPitch, LONG yPitch, LONG nWidth, LONG nHeight) { return (BOOL)((x%2) == 0 && (y%2) == 0 && (max(abs(xPitch), abs(yPitch))%2) /*xyPitch*/ == 0 && (nWidth%2) == 0 && (nHeight%2) == 0); } inline void OptimizePitch(WORD*& pBuffer, LONG& nWidth, LONG& nHeight, LONG& xPitch, LONG& yPitch) { LONG temp; // abs(xPitch) > abs(yPitch) if((xPitch>0?xPitch:-xPitch) > (yPitch>0?yPitch:-yPitch)) { temp = xPitch; xPitch = yPitch; yPitch = temp; temp = nWidth; nWidth = nHeight; nHeight = temp; } if (xPitch < 0) { pBuffer += (nWidth - 1) * xPitch; xPitch = -xPitch; } } // Computes the average of two alpha/opacity values inline DWORD AverageAlpha (DWORD alpha, DWORD masterOpacity) { return (alpha*masterOpacity) >> 8; } } namespace pxutil16bit { // Retrieve a pointer to a pixel X, Y location in the specified buffer. // NOTE: xPitch and yPitch refer to the number of pixels, **not** the number of bytes! inline WORD* GetBuffPixels(void *buff, LONG xPitch, LONG yPitch, LONG x, LONG y) { return (WORD*)buff + (yPitch * y) + /*(x*xPitch)*/x; } } namespace pxutil565 { inline DWORD ColorrefToNative(COLORREF color) { // m_gxDP.ffFormat & kfDirect565 // KfDirect565 = RRRRRGGG.GGGBBBBB // Red = RRRRRxxx.xxxxxxxx // Green = xxxxxGGG.GGGxxxxx // Blue = xxxxxxxx.xxxBBBBB return (((color & 0xF8) << 8) | ((color & 0xFC00) >> 5) | ((color & 0xF80000) >> 19)); } inline DWORD RGBToNative(DWORD R, DWORD G, DWORD B) { return (((R & 0xF8) << 8) | ((G & 0xFC) << 3) | ((B & 0xF8) >> 3)); }; inline COLORREF NativeToColorref(DWORD color) { // (R) | (G << 8) | (B << 16) return ((color & 0xf800) >> 8) | ((color & 0x07e0) << 5) | ((color & 0x001f) << 19); } inline DWORD GetSurfaceRValue(DWORD color) { return ((color & 0xf800) >> 8); // 5-bit } inline DWORD GetSurfaceGValue(DWORD color) { return ((color & 0x07e0) >> 3); // 6-bit } inline DWORD GetSurfaceBValue(DWORD color) { return ((color & 0x001f) << 3); // 5-bit } // Determines the "alpha" value of the specified color, // assuming the color came from an alpha mask image. inline DWORD GetSurfaceAlphaValue(DWORD color) { // Currently the fastest method is to treat the green // component as the alpha value. return GetSurfaceGValue(color); } // KfDirect565 = RRRRRGGG.GGGBBBBB // Divided2 = xRRRRxGG.GGGxBBBB inline DWORD AlphaBlendFast(DWORD pixel, DWORD backpixel) { return (((pixel & 0xf7de) >> 1) + ((backpixel & 0xf7de) >> 1)); } // Blend image with background, based on opacity inline DWORD AlphaBlend(DWORD pixel, DWORD backpixel, DWORD opacity) { DWORD dw5bitOpacity = opacity >> 3; //split into xGxRxB pixel = (pixel | (pixel<<16)) & 0x07E0F81F; backpixel = (backpixel | (backpixel<<16)) & 0x07E0F81F; //do alpha op pixel = ((((pixel-backpixel)*(dw5bitOpacity))>>5) + backpixel) & 0x07E0F81F; //recombine into RGB return (WORD)(pixel | pixel >> 16); /*DWORD dw5bitOpacity = (opacity-3) >> 3; DWORD temp1, temp2; temp2 = pixel & 0xF81F; pixel &= 0x07E0; temp1 = backpixel & 0xF81F; backpixel &= 0x07E0; // Multiply the source by the factor backpixel = ((((pixel >> 5) - (backpixel >> 5)) * dw5bitOpacity) + backpixel) & 0x07E0; pixel = ((((temp2 - temp1) * dw5bitOpacity) >> 5) + temp1) & 0xF81F; return backpixel | pixel;*/ } inline DWORD AlphaBlendAdditive( DWORD pixel, DWORD backpixel, LONG opacity) { DWORD dw5bitOpacity = opacity >> 3; DWORD res; /* Seperate out the components */ pixel = ((pixel << 16) | pixel) & 0x7C0F81F; /* Multiply the source by the factor */ pixel = ((pixel * dw5bitOpacity) >> 5) & 0x7C0F81F; backpixel = ((backpixel << 16) | backpixel) & 0x7C0F81F; /* Do the conditionless add with saturation */ backpixel += pixel; res = backpixel & 0x8010020; res -= (res >> 5); backpixel |= res; /* Recombine the components */ backpixel &= 0x7C0F81F; backpixel |= (backpixel >> 16); backpixel &= 0xFFFF; return backpixel; } inline DWORD AlphaBlendSubtractive( DWORD pixel, DWORD backpixel, LONG opacity) { DWORD dw5bitOpacity = opacity >> 3; DWORD res; /* Seperate out the components */ pixel = ((pixel << 16) | pixel) & 0x7C0F81F; /* Multiply the source by the factor */ pixel = ((pixel * dw5bitOpacity) >> 5) & 0x7C0F81F; backpixel = ((backpixel << 16) | backpixel) & 0x7C0F81F; /* Do the conditionless add with saturation */ backpixel -= pixel; res = backpixel & 0x8010020; res -= (res >> 5); backpixel &= ~res; /* Recombine the components */ backpixel &= 0x7C0F81F; backpixel |= (backpixel >> 16); backpixel &= 0xFFFF; return backpixel; } // 32-bit fast 50% alpha blending (operates on two pixels simultaneously) inline DWORD AlphaBlendFast32( DWORD pixel, DWORD backpixel) { DWORD dwResult; dwResult = ((pixel & 0xf7def7de) >> 1) + ((backpixel & 0xf7def7de) >> 1); return ((dwResult & 0xFFFF0000) | (dwResult & 0x00007FFFF)); } // 32-bit alpha blending (operates on two pixels simultaneously) inline DWORD AlphaBlend32( DWORD pixel, DWORD backpixel, DWORD opacity) { DWORD dw5bitOpacity = opacity >> 3; DWORD temp1, temp2; temp2 = pixel & 0x7E0F81F; pixel &= 0xF81F07E0; temp1 = backpixel & 0x7E0F81F; backpixel &= 0xF81F07E0; // Multiply the source by the factor backpixel = ((((pixel >> 5) - (backpixel >> 5)) * dw5bitOpacity) + backpixel) & 0xF81F07E0; pixel = ((((temp2 - temp1) * dw5bitOpacity) >> 5) + temp1) & 0x7E0F81F; return backpixel | pixel; } // NOTE: xPitch and yPitch refer to the number of pixels, **not** the number of bytes! inline DWORD GetPixel(void *buff, LONG xPitch, LONG yPitch, LONG x, LONG y) { WORD *pBuff = pxutil16bit::GetBuffPixels(buff, xPitch, yPitch, x, y); return *pBuff; } // NOTE: xPitch and yPitch refer to the number of pixels, **not** the number of bytes! inline void SetPixel(void *buff, LONG xPitch, LONG yPitch, LONG x, LONG y, DWORD dwNativeColor) { WORD *pBuff = pxutil16bit::GetBuffPixels(buff, xPitch, yPitch, x, y); *pBuff = (WORD)dwNativeColor; } // NOTE: xPitch and yPitch refer to the number of pixels, **not** the number of bytes! inline void SetPixelOpacity(void *buff, LONG xPitch, LONG yPitch, LONG x, LONG y, DWORD dwNativeColor, DWORD dwOpacity) { WORD *pBuff = pxutil16bit::GetBuffPixels(buff, xPitch, yPitch, x, y); *pBuff = (WORD)AlphaBlend(dwNativeColor, *pBuff, dwOpacity); } } namespace pxutil555 { /** // m_gxDP.ffFormat & kfDirect555 // KfDirect555 = xRRRRRGG.GGGBBBBB // Red = xRRRRRxx.xxxxxxxx // Green = xxxxxxGG.GGGxxxxx // Blue = xxxxxxxx.xxxBBBBB */ inline DWORD ColorrefToNative(COLORREF color) { return (((color & 0xF8) << 7) | ((color & 0xF800) >> 6) | ((color & 0xF80000) >> 19)); }; inline DWORD RGBToNative(DWORD R, DWORD G, DWORD B) { return (((R & 0xF8) << 7) | ((G & 0xF8) << 2) | ((B & 0xF8) >> 3)); }; inline COLORREF NativeToColorref(DWORD color) { // COLORREF = (R) | (G << 8) | (B << 16) return ((color & 0x7c00) >> 7) | ((color & 0x03e0) << 6) | ((color & 0x001f) << 19); } inline DWORD GetSurfaceRValue(DWORD color) { return ((color & 0x7c00) >> 7); // 5-bit }; inline DWORD GetSurfaceGValue(DWORD color) { return ((color & 0x03e0) >> 2); // 5-bit }; inline DWORD GetSurfaceBValue(DWORD color) { return ((color & 0x001f) << 3); // 5-bit }; // KfDirect555 = xRRRRRGG.GGGBBBBB // Divided2 = xxRRRRxG.GGGxBBBB inline DWORD AlphaBlendFast(DWORD pixel, DWORD backpixel) { return (((pixel & 0x7bde) >> 1) + ((backpixel & 0x7bde) >> 1)); } // Blend image with background, based on opacity inline DWORD AlphaBlend(DWORD pixel, DWORD backpixel, DWORD opacity) { DWORD dw5bitOpacity = opacity >> 3; //split into xGxRxB pixel = (pixel | (pixel<<16)) & 0x03E07C1F; backpixel = (backpixel | (backpixel<<16)) & 0x03E07C1F; //do alpha op pixel = ((((pixel-backpixel)*(dw5bitOpacity))>>5) + backpixel) & 0x03E07C1F; //recombine into RGB return (pixel | pixel >> 16) & 0x0000FFFFL; /*DWORD dw5bitOpacity = opacity >> 3; DWORD temp1, temp2; temp2 = pixel & 0x7C1F; pixel &= 0x03E0; temp1 = backpixel & 0x7C1F; backpixel &= 0x03E0; // Multiply the source by the factor backpixel = ((((pixel >> 5) - (backpixel >> 5)) * dw5bitOpacity) + backpixel) & 0x03E0; pixel = ((((temp2 - temp1) * dw5bitOpacity) >> 5) + temp1) & 0x7C1F; return backpixel | pixel;*/ } inline DWORD AlphaBlendAdditive( DWORD pixel, DWORD backpixel, LONG opacity) { DWORD dw5bitOpacity = opacity >> 3; DWORD res; /* Seperate out the components */ pixel = ((pixel << 16) | pixel) & 0x3E07C1F; /* Multiply the source by the factor */ pixel = ((pixel * dw5bitOpacity) >> 5) & 0x3E07C1F; backpixel = ((backpixel << 16) | backpixel) & 0x3E07C1F; /* Do the conditionless add with saturation */ backpixel += pixel; res = backpixel & 0x4008020; res -= (res >> 5); backpixel |= res; /* Recombine the components */ backpixel &= 0x3E07C1F; backpixel |= (backpixel >> 16); backpixel &= 0x7FFF; return backpixel; } inline DWORD AlphaBlendSubtractive( DWORD pixel, DWORD backpixel, LONG opacity) { DWORD dw5bitOpacity = opacity >> 3; DWORD res; /* Seperate out the components */ pixel = ((pixel << 16) | pixel) & 0x3E07C1F; /* Multiply the source by the factor */ pixel = ((pixel * dw5bitOpacity) >> 5) & 0x3E07C1F; backpixel = ((backpixel << 16) | backpixel) & 0x3E07C1F; /* Do the conditionless add with saturation */ backpixel -= pixel; res = backpixel & 0x4008020; res -= (res >> 5); backpixel &= ~res; /* Recombine the components */ backpixel &= 0x3E07C1F; backpixel |= (backpixel >> 16); backpixel &= 0x7FFF; return backpixel; } // 32-bit fast 50% alpha blending (operates on two pixels simultaneously) inline DWORD AlphaBlendFast32( DWORD pixel, DWORD backpixel) { DWORD dwResult; dwResult = ((pixel & 0x7bde7bde) >> 1) + ((backpixel & 0x7bde7bde) >> 1); return ((dwResult & 0xFFFF0000) | (dwResult & 0x00007FFFF)); } // 32-bit alpha blending (operates on two pixels simultaneously) inline DWORD AlphaBlend32( DWORD pixel, DWORD backpixel, DWORD opacity) { DWORD dw5bitOpacity = opacity >> 3; DWORD temp1, temp2; temp2 = pixel & 0x3E07C1F; pixel &= 0x7C1F03E0; temp1 = backpixel & 0x3E07C1F; backpixel &= 0x7C1F03E0; // Multiply the source by the factor backpixel = ((((pixel >> 5) - (backpixel >> 5)) * dw5bitOpacity) + backpixel) & 0x7C1F03E0; pixel = ((((temp2 - temp1) * dw5bitOpacity) >> 5) + temp1) & 0x3E07C1F; return backpixel | pixel; } // NOTE: xPitch and yPitch refer to the number of pixels, **not** the number of bytes! inline DWORD GetPixel(void *buff, LONG xPitch, LONG yPitch, LONG x, LONG y) { WORD *pBuff = pxutil16bit::GetBuffPixels(buff, xPitch, yPitch, x, y); return *pBuff; } // NOTE: xPitch and yPitch refer to the number of pixels, **not** the number of bytes! inline void SetPixel(void *buff, LONG xPitch, LONG yPitch, LONG x, LONG y, DWORD dwNativeColor) { WORD *pBuff = pxutil16bit::GetBuffPixels(buff, xPitch, yPitch, x, y); *pBuff = (WORD)dwNativeColor; } // NOTE: xPitch and yPitch refer to the number of pixels, **not** the number of bytes! inline void SetPixelOpacity(void *buff, LONG xPitch, LONG yPitch, LONG x, LONG y, DWORD dwNativeColor, DWORD dwOpacity) { WORD *pBuff = pxutil16bit::GetBuffPixels(buff, xPitch, yPitch, x, y); *pBuff = (WORD)AlphaBlend(dwNativeColor, *pBuff, dwOpacity); } } #endif // __BL_PIXELUTIL_H_
true
f6243d59c30e4832fe85db5ac0e4a037b56239c8
C++
marcinstelmaszyk/CLionProjects
/Udemy/02_Learn_Advanced_Cpp_Programming/08_C++11/For_Loop/main.cpp
UTF-8
183
3.0625
3
[]
no_license
#include <iostream> using namespace std; int main() { auto texts = {"one", "two", "three"}; for (auto text: texts) std::cout << text << std::endl; return 0; }
true
49cdd03c68960296669a39b1164fa2b8c9988dd6
C++
mouchtaris/fictional_disco
/test/Tpf/test_def.cpp
UTF-8
2,757
2.515625
3
[]
no_license
#include "test_def.h" #include "fixture/tpfs.h" #include "Tpf/Id.h" #include "Tpf/return_.h" #include <iostream> #include <type_traits> #include <tuple> #define FAIL "Test failure." using namespace test::Tpf; namespace { constexpr auto nl = "\n"; namespace t_def_1_tuplize { struct a; using expected = std::tuple<a>; using def = Tpf::apply<Tpf::def, a>; using subject = Tpf::apply<def, fixture::tuplize>; static_assert(std::is_same_v<subject, expected>, FAIL); } namespace t_def_2_tuplize { struct a; struct b; using expected = std::tuple<a, b>; using def = Tpf::apply<Tpf::def, a, b>; using subject = Tpf::apply<def, fixture::tuplize>; static_assert(std::is_same_v<subject, expected>, FAIL); } namespace t_fixture_Add { using namespace fixture; using Tpf::apply; using Tpf::Id; using Tpf::return_; using _0 = Zero<>; using _1 = Next<_0>; using _2 = Next<_1>; using _3 = Next<_2>; template < typename a, typename b > using plus = apply<apply<Add, a, b>, Id>; template < typename a, typename b > constexpr auto eq = std::conjunction_v<std::is_same<a, b>>; static_assert(eq< plus<_0, _0>, _0>, FAIL); static_assert(eq< plus<_0, _1>, _1>, FAIL); static_assert(eq< plus<_1, _0>, _1>, FAIL); static_assert(eq< plus<_1, _1>, _2>, FAIL); static_assert(eq< plus<_1, _2>, _3>, FAIL); static_assert(eq< plus<_2, _1>, _3>, FAIL); static_assert(eq< plus<_3, _0>, _3>, FAIL); static_assert(eq< plus<_0, _3>, _3>, FAIL); static_assert(eq< plus<_1, _2>, plus<_2, _1> >, FAIL); static_assert(eq< plus<_1, _2>, return_<Add, _2, _1> >, FAIL); static_assert(eq< return_<Add, return_<Add, _1, _0>, return_<Add, _0, _2> >, _3 >, FAIL); static_assert(eq< _3, return_<Add, return_<Add, _1, _1>, return_<Add, _0, _1> > >, FAIL); static_assert(eq< return_<Add, return_<Add, _1, _0>, return_<Add, _0, _2> >, return_<Add, return_<Add, _1, _1>, return_<Add, _0, _1> > >, FAIL); } } void test_def() { std::cerr << "[def] Process initiation." << nl; std::cerr << "[def] Process complete. No results." << nl; }
true
bc7d2a4ce28a23c388b8b33c14795c902a84ea3f
C++
CompilerLuke/NextEngine
/NextCore/include/core/memory/allocator.h
UTF-8
2,278
3
3
[ "MIT" ]
permissive
#pragma once #include <cstddef> #include "core/core.h" #include <string.h> #include <assert.h> struct CORE_API Allocator { virtual void* allocate(std::size_t) { return NULL; }; virtual void deallocate(void* ptr) {}; }; struct CORE_API BlockAllocator : Allocator { static constexpr int block_size = 16000; static constexpr int num_blocks = 20; struct Block { Block* next = NULL; char data[block_size]; size_t offset = 0; uint count = 0; }; Block blocks[num_blocks]; Block* free_block = NULL; BlockAllocator(const BlockAllocator &) = delete; void* allocate(std::size_t); void deallocate(void* ptr); void next_empty_block(); BlockAllocator(); }; struct CORE_API MallocAllocator : Allocator { void* allocate(std::size_t); void deallocate(void* ptr); }; extern CORE_API BlockAllocator block_allocator; extern CORE_API MallocAllocator default_allocator; #define ALLOC(T, ...) new (default_allocator.allocate(sizeof(T)) T((__VA_ARGS__) template<typename T> inline void FREE(T* ptr) { if (ptr == NULL) return; ptr.~T(); default_allocator.deallocate(ptr); } #define ALLOC_ARRAY(T, N) new (default_allocator.allocate(sizeof(T) * N)) T[N] template<typename T> inline void FREE_ARRAY(T* ptr, std::size_t N) { if (ptr == NULL) return; for (int i = 0; i < N; i++) { ptr[i].~T(); } default_allocator.deallocate(ptr); } template<typename T> void destruct(T* ptr) { ptr->~T(); } template<typename T> void memcpy_t(T* a, const T* b, u64 count) { memcpy(a, b, count * sizeof(T)); } template<typename T> void memclear_t(T* a, u64 count) { memset(a, 0, count * sizeof(T)); } template<typename T> T* realloc_t(T* prev, u64 count) { T* ptr = (T*)realloc(prev, count * sizeof(T)); assert(ptr); return ptr; } template<typename T, typename Allocator> T* alloc_t(Allocator& allocator, uint num = 1) { return new (allocator.allocate(num * sizeof(T))) T(); } inline u64 align_offset(u64 offset, uint alignment) { u64 alignment_bytes_minus_one = alignment - 1; return (offset + alignment_bytes_minus_one) & ~alignment_bytes_minus_one; } inline u64 aligned_incr(u64* occupied, u64 size, uint alignment) { u64 offset = align_offset(*occupied, alignment); *occupied = offset + size; return offset; } CORE_API Allocator& get_allocator();
true
e85dc4ce549586716298fb29aca111fa05164754
C++
Zhangh2018/yangyang_2d_avm
/7.pinjie/2.ipm/LDWS/LDWS.h
UTF-8
1,422
2.828125
3
[]
no_license
#ifndef __LDWS_H__ #define __LDWS_H__ #include <opencv2/opencv.hpp> #include"ROI.h" #include"ImageTransformation.h" #include"LaneAnalysis.h" using namespace cv; using namespace std; /* * Project: Lane Departure Warning System (LDWS) * * File: LDWS.cpp * * Contents: The LDWS class stores the attributes needed for the either * the single image, the video or the live video stream algorithms implemented in child classes. * * Author: PIRAUBE Nicolas * * Date : 05/08/2017 */ class LDWS { public: // Default constructor /** * Default constructor initializing the class attributs to zero. */ LDWS(); // Constructor /** * Constructor initializing the class attributs to zero apart for the path string attribute. * Parameters * string path : String storing the path to the algorithm input image or video. */ LDWS(string path); protected: //String inputPath storing the path to the algorithm input image or video. string inputPath; //Matrix storing the input image. Mat img; //Matrix storing the input image on wich the algorithm is applied. Mat sourceImg; //Matrix storing the IPM if the input image. Mat ipmImage; //ImageTransformation object used for the algorithm. ImageTransformation imageTransformation; //ROI object used for the algorithm. ROI roi; //LaneAnalysis object used for the algorithm. LaneAnalysis laneAnalysis; }; #endif
true
b7a2aa043972d64e86ea580ea479b56d38e94b94
C++
Spencer-Stice/UCLA-CS32
/Projects/Project4/winskel/Wurd/Wurd/StudentTextEditor.h
UTF-8
1,055
2.96875
3
[]
no_license
#ifndef STUDENTTEXTEDITOR_H_ #define STUDENTTEXTEDITOR_H_ #include "TextEditor.h" #include "Undo.h" #include <list> #include <map> using namespace std; class StudentTextEditor : public TextEditor { public: StudentTextEditor(Undo* undo); ~StudentTextEditor(); bool load(std::string file); bool save(std::string file); void reset(); void move(Dir dir); void del(); void backspace(); void insert(char ch); void enter(); void getPos(int& row, int& col) const; int getLines(int startRow, int numRows, std::vector<std::string>& lines) const; void undo(); private: int m_r; //store the current row int m_c; //store the current column list<string> editingLines; //Create a list of strings to store lines of text list<string>::iterator m_cLinePtr; //Create a list iterator that will 'point' to the current line to make edits faster int m_numLines; //Store the current number of lines void submitAction(Undo::Action a, int r, int c, char ch); //Helper function for submitting an action to undo }; #endif // STUDENTTEXTEDITOR_H_
true
8a6e8503f19879144cdb78cabefb4ed58383b41d
C++
LMurphy186232/Core_Model
/Behaviors/Windstorm.h
UTF-8
10,129
2.921875
3
[]
no_license
//--------------------------------------------------------------------------- // Windstorm //--------------------------------------------------------------------------- #if !defined(Windstorm_H) #define Windstorm_H #include "BehaviorBase.h" class clGrid; /** * Windstorm version 2.0. * * Windstorm creates storm events and kills trees as a result. * * Windstorm defines 11 different storm return intervals: 1, 5, 10, 20, 40, * 80, 160, 320, 640, 1280, and 2560. (This code was present in pre-6.0 * versions of SORTIE as well. At that point, it did not have the 1-year * return interval. I added it for testing purposes, and thought others might * want access to it as well.) For each return interval, the user provides * a storm severity, from 0 (no damage) to 1 (complete devastation). * * The frequency of storms can optionally be cyclical (sinusoidal), with an * optional overall trend. The actual probability of any storm that uses * a cyclical storm regime is: * * <center>P'(Fi) = P(Fi) * ([d*sin(pi(x-g)/(2f))] + [mx + i])</center> * where: * <ul> * <li>P'(Fi) = this timestep's probability of a storm of the ith return * interval</li> * <li>P(Fi) = the baseline (parameter file) probability of a storm of the ith * return interval; that is, 1 / return interval</li> * <li>The first term represents the sinusoidal portion</li> * <li>The second term represents the trend portion</li> * <li>x = 4*t/Sr, where t = timestep since storms started and Sr = sine * periodicity parameter</li> * <li>d is a parameter that controls the sine curve's amplitude</li> * <li>f is a parameter that controls the sine curve's frequency</li> * <li>g is a parameter that controls where on the curve we are when storms * start occuring</li> * <li>m is a parameter that gives the trend line's slope</li> * <li>i is a parameter that gives the trend line's intercept</li> * </ul> * * Each timestep, this behavior decides what storms will occur. The probability * for each storm is calculated as in the equation above. SORTIE uses * independent random number draws for each year of the timestep for each * return interval. This means multiple storms can happen per timestep, and if * the timestep length is more than one year, multiple storms of the same * severity can happen. * * A tree's probability of dying in a given storm is: * * <center>mort = exp(a + c * s * DBH<sup> b</sup>)/(1 + exp(a + c * s * DBH<sup> b</sup>))</center> * * where: * <ul> * <li>mort is the tree's probability of death from the storm</li> * <li>a, b, and d are parameters</li> * <li>DBH is the tree's DBH in cm</li> * <li>s is the severity for storms of this return interval</li> * </ul> * * Each storm gets a crack at all the trees "independently" of the others. This * means that, if two storms happen in one timestep, this behavior will cycle * twice through all the trees in the plot and assess each one's mortality for * the two storms separately. Of course, the two events cannot be truly * independent, because the second storm can only kill trees not killed by the * first storm. * * Storms of severity below a certain minimum (currently set at 0.1) do not use * the equation above; the storm severity is used directly as a mortality * probability for trees. * * Storms of severity 0 cannot occur. Any return interval with a severity of * 0 is skipped. * * The user has the option to not start storms at the beginning of the run. * They can set a timestep for storms to start. Before this timestep no * storms are allowed to occur. * * This behavior will not kill trees below a minimum DBH set by the user. * Because of the need for DBH, obviously seedlings are ignored. Snags and * already-dead trees are ignored as well. All trees that die get their * "dead" flags set to "storm". (This flag comes from mortality behaviors and is * not added by this behavior.) This behavior then has nothing more to do with * these trees. * * Storm results are placed in a grid called "Windstorm Results". * * This behavior's call string and name string are both "Windstorm". * * Copyright 2011 Charles D. Canham * @author Lora E. Murphy * <br>Edit history: * <br>----------------- * <br>October 20, 2011 - Wiped the slate clean for SORTIE 7.0 (LEM) */ class clWindstorm : virtual public clBehaviorBase { public: /** * Constructor. * @param p_oSimManager Sim Manager object. */ clWindstorm(clSimManager *p_oSimManager); /** * Destructor. Frees memory. */ ~clWindstorm(); /** * Does behavior setup. Calls the following functions: * <ol> * <li>ReadParFile()</li> * <li>DoGridSetup()</li> * <li>GetDeadCodes()</li> * <li>FormatQueryString()</li> * </ol> * @param p_oDoc DOM tree of parsed input file. */ void GetData(xercesc::DOMDocument *p_oDoc); /** * Does windstorms each timestep. If the timestep has not yet reached the * value in m_iFirstStormTimestep, then nothing happens. Otherwise: first, * the "Windstorm Results" grid is cleared. Then the cyclical portion of * storm probability is calculated. Then, a random number is drawn * for each year of the timestep for each storm return interval. If the * random number is less than the probability of that storm, then that * storm occurs. For each storm that occurs, this will fetch all trees that * can be killed in storms, and each that is not already dead has its * probability of dying in the current storm calculated. A random number is * compared to this probability to see if the tree dies. Those trees that die * have their "dead" flag set to "storm". */ void Action(); protected: /** * Windstorm Results grid * This grid is named "Windstorm Results" and it contains the data for all * storms that happened in the previous timestep. There is one grid cell per * plot, and this is not user-changeable. * * Each storm gets one package. The packages occur in the order than the * storms occurred in the timestep. Each package contains the following data * members: One float called "severity", which holds the severity of the * storm as a value from 0 to 1. Then there is one float per species called * "ba_x", where x is the species number. This holds the amount of basal area * per hectare killed in the storm for that species. Then there is another * float per species called "density_x", where x is the species number. This * holds the density per hectare killed in the storm for that species. */ clGrid *mp_oResultsGrid; /**Return codes for the "dead" bool tree data member. Array index one is * sized m_iTotalNumSpecies; array index two is sized 2 (for saplings and * adults).*/ int **mp_iDeadCodes; /** * Annual probability of the occurence of a storm of each return interval. If * the user has set the storm severity of a given return interval to 0, its * probability is also set to 0. Array size is m_iNumReturnIntervals.*/ double *mp_fStormProbabilities; /** Severity of each storm return interval. Array size is m_iNumReturnIntervals. */ double *mp_fStormSeverities; /** Storm intercept for tree mortality (a) parameter. Array size is * total # species. */ double *mp_fA; /** The "b" parameter for each species. Array size is total # species. */ double *mp_fB; /** The "d" parameter for each species. Array size is total # species. */ double *mp_fC; /** Minimum DBH for trees to be killed in storms. Array size is total # * species. */ double *mp_fMinDBH; /** Return codes for the "ba_x" package float data members of the "Windstorm * Results" grid. Array size is total # species.*/ short int *mp_iBa_xCodes; /** Return codes for the "density_x" package float data members of the * "Windstorm Results" grid. Array size is total # species.*/ short int *mp_iDensity_xCodes; /**String to pass to clTreePopulation::Find() in order to get the trees to * apply damage to. This will instigate a species/type search for all the * species and types to which this behavior applies.*/ char *m_cQuery; /** SST periodicity (Sr) */ double m_fSSTPeriod; /** Sine function d */ double m_fSineD; /** Sine function f */ double m_fSineF; /** Sine function g */ double m_fSineG; /** Trend function slope (m) */ double m_fTrendSlopeM; /** Trend function intercept (i) */ double m_fTrendInterceptI; /**The total number of storm return intervals. Hardcoded at 11.*/ int m_iNumReturnIntervals; /** The timestep to start storms. */ int m_iFirstStormTimestep; /** Total number of species. Primarily for the destructor. */ int m_iTotalNumSpecies; /**Return code for the "severity" package float data member of the * "Windstorm Results" grid*/ int m_iSeverityCode; /** * Sets up the "Windstorm Results" grid. Any maps in the parameter file are * ignored. */ void DoGridSetup(); /** * Reads in parameters from the parameter file. This also calculates baseline * storm probabilities. * @param p_oDoc DOM tree of parsed input file. * @param p_oPop Tree population object. * @throws modelErr if: * <ul> * <li>A value in the minimum DBH is less than 0</li> * <li>The timestep to start storms is less than 0</li> * <li>The storm severity for any return interval is not between 0 and 1</li> * <li>The storm periodicity is 0</li> * </ul> */ void ReadParFile(xercesc::DOMDocument *p_oDoc, clTreePopulation *p_oPop); /** * Gets codes for the "dead" data member for each tree type to which this * behavior applies. * @param p_oPop Tree population object. * @throws modelErr if the codes are not available for every tree type to * which this behavior is applied, or if this behavior is applied to * seedlings. */ void GetDeadCodes(clTreePopulation *p_oPop); /** * Formats the string in m_cQuery. This value will be used in Action() to * pass to clTreePopulation::Find() in order to get the trees to act on. * @param p_oPop Tree population object. */ void FormatQueryString(clTreePopulation *p_oPop); }; //--------------------------------------------------------------------------- #endif // Windstorm_H
true
3cf6086ac1c3d99c45ff59e35df86d098a6a4f9a
C++
J-Jun/OOP244-CPP
/WS10/lab/cstring.cpp
UTF-8
682
2.734375
3
[]
no_license
//============================================== // Name: Jason Jun // Student Number: 126 683 200 // Email: jjun10@myseneca.ca // Section: OOP244 NCC // Workshop: Workshop 7 - LAB //============================================== #include "cstring.h" namespace sdds { void strCpy(char* des, const char* src) { // Variable: int i; for (i = 0; src[i] != '\0'; i++) { des[i] = src[i]; } des[i] = '\0'; } int strLen(const char* s) { // Variable: int wordLength = 0; // Looping and counting for number of characters for (int i = 0; s[i] != '\0'; i++) { wordLength++; } return wordLength; } }
true
14a42270d27f9cf413127b172057df34780b646a
C++
GitLeeRepo/Cpp_ProgrammingNotes
/basics/datatype_ex1.cpp
UTF-8
3,369
3.53125
4
[]
no_license
// datatypes_ex1 // // Illustrates the various data types and their limits in C++ #include <iostream> #include <iomanip> #include <climits> #include <cfloat> #include <locale> int main() { using namespace std; bool isTrue = true; signed char myCharMin = CHAR_MIN; signed char myCharMax = CHAR_MAX; unsigned char myUCharMax = UCHAR_MAX; short myShortMin = SHRT_MIN; short myShortMax = SHRT_MAX; unsigned short myUShortMax = USHRT_MAX; int myIntMin = INT_MIN; int myIntMax = INT_MAX; unsigned int myUIntMax = UINT_MAX; long myLongMin = LONG_MIN; long myLongMax = LONG_MAX; unsigned long myULongMax = ULONG_MAX; float myFloatMin = FLT_MIN; float myFloatMax = FLT_MAX; double myDoubleMin = DBL_MIN; double myDoubleMax = DBL_MAX; long double myLongDoubleMin = LDBL_MIN; long double myLongDoubleMax = LDBL_MAX; enum color { red, green, blue}; color myColor = blue; // data type sizes in bytes cout << setw(21) << "Size of bool: " << sizeof(isTrue) << endl; cout << setw(21) << "Size of char: " << sizeof(char) << endl; cout << setw(21) << "Size of short: " << sizeof(short) << endl; cout << setw(21) << "Size of int: " << sizeof(int) << endl; cout << setw(21) << "Size of enum: " << sizeof(myColor) << endl; cout << setw(21) << "Size of long: " << sizeof(long) << endl; cout << setw(21) << "Size of float: " << sizeof(float) << endl; cout << setw(21) << "Size of double: " << sizeof(double) << endl; cout << endl; // min, max and significant digits cout << setw(21) << "Min char: " << setw(26) << (int)myCharMin << endl; cout << setw(21) << "Max char: " << setw(26) << (int)myCharMax << endl; cout << setw(21) << "Max unsigned char: " << setw(26) << (int)myUCharMax << endl; std::cout.imbue(std::locale("en_US.UTF-8")); // use locale thousands separator cout << setw(21) << "Min short: " << setw(26) << myShortMin << endl; cout << setw(21) << "Max short: " << setw(26) << myShortMax << endl; cout << setw(21) << "Max Unsigned short: " << setw(26) << myUShortMax << endl; cout << setw(21) << "Min int: " << setw(26) << myIntMin << endl; cout << setw(21) << "Max int: " << setw(26) << myIntMax << endl; cout << setw(21) << "Max Unsigned int: " << setw(26) << myUIntMax << endl; cout << setw(21) << "Min long: " << setw(26) << myLongMin << endl; cout << setw(21) << "Max long: " << setw(26) << myLongMax << endl; cout << setw(21) << "Max Unsigned Long: " << setw(26) << myULongMax << endl; std::cout.imbue(std::locale("C")); // reset to default no thousand separator cout << setw(21) << "Min float: " << setw(26) << myFloatMin << endl; cout << setw(21) << "Max float: " << setw(26) << myFloatMax << endl; cout << setw(21) << "float sig digits: " << setw(26) << FLT_DIG << endl; cout << setw(21) << "Min double: " << setw(26) << myDoubleMin << endl; cout << setw(21) << "Max double: " << setw(26) << myDoubleMax << endl; cout << setw(21) << "double sig digits: " << setw(26) << DBL_DIG << endl; cout << setw(21) << "Min long double: " << setw(26) << myLongDoubleMin << endl; cout << setw(21) << "Max long double: " << setw(26) << myLongDoubleMax << endl; cout << setw(21) << "long dbl sig digits: " << setw(26) << LDBL_DIG << endl; return 0; }
true
be3c019f7ac5787a3cbc13730da1df93cf697fbe
C++
axrdiv/USACO
/Chapter_5/Section_5.4/Character_Recognition/Character_Recognition.cpp
UTF-8
4,434
2.875
3
[]
no_license
/* ID: axrdiv1 PROG: charrec LANG: C++ */ #include<fstream> #include<iostream> #include<vector> #include<string> #include<stack> using namespace std; ofstream fout("charrec.out"); ifstream fin("charrec.in"); ifstream fontin("font.in"); int read(istream& is, vector<string>& v) { int N; is >> N; string s; for(int i = 0; i < N; i++) { is >> s; v.push_back(s); } return N; } int diff19(int lineno, char &ch, vector<vector<vector<int> > >& linediff, const int M) { int mindiff = -1; for(int i = 0; i < M; i++) { for(int miss = 0; miss < 20; miss++) { int totaldiff = 0; for(int j = 0; j < 19; j++) { if(j < miss) totaldiff += linediff[lineno + j][i][j]; else totaldiff += linediff[lineno + j][i][j + 1]; } if(mindiff < 0 || totaldiff < mindiff) { mindiff = totaldiff; ch = (i == 0 ? ' ' : ('a' + i - 1)); } } } if(mindiff > 20 * 20 * 0.30) ch = '?'; return mindiff; } int diff20(int lineno, char& ch, vector<vector<vector<int> > >& linediff, const int M) { int mindiff = -1; for(int i = 0; i < M; i++) { int totaldiff = 0; for(int j = 0; j < 20; j++) { totaldiff += linediff[lineno + j][i][j]; } if(mindiff < 0 || totaldiff < mindiff) { mindiff = totaldiff; ch = (i == 0 ? ' ': ('a' + i - 1)); } } if(mindiff > 20 * 20 * 0.3) ch = '?'; return mindiff; } int diff21(int lineno, char &ch, vector<vector<vector<int> > >& linediff, const int M) { int mindiff = -1; for(int i = 0; i < M; i++) { for(int dublicated = 1; dublicated <= 20; ++dublicated) { int totaldiff = 0; for(int j = 0; j < 21; ++j) { if(j < dublicated) totaldiff += linediff[lineno + j][i][j]; else if(j == dublicated) { if(linediff[lineno + j][i][j - 1] < linediff[lineno + j - 1][i][j - 1]) totaldiff = totaldiff - linediff[lineno + j - 1][i][j - 1] + linediff[lineno + j][i][j - 1]; } else totaldiff += linediff[lineno + j][i][j - 1]; } if(mindiff < 0 || totaldiff < mindiff) { mindiff = totaldiff; ch = (i == 0 ? ' ' : ('a' + i - 1)); } } } if(mindiff > 20 * 20 * 0.3) ch = '?'; return mindiff; } int main() { vector<string> font; vector<string> regn; int M = read(fontin, font) / 20; int N = read(fin, regn); vector<vector<vector<int> > > linediff(N, vector<vector<int> >(M, vector<int>(20, 0))); for(int i = 0; i < N; i++) { for(int j = 0; j < M; j++) { for(int r = 0; r < 20; r++) { for(int c = 0; c < 20; c++) { linediff[i][j][r] += (regn[i][c] != font[j*20+r][c]); } } } } vector<char> chars(N, '*'); vector<int> prev(N, -1); vector<int> diff(N, -1); char ch; for(int i = 18; i < N; i++) { if(i - 19 == -1 || (i - 19 >= 0 && diff[i - 19] >= 0)) { diff[i] = diff19(i - 18, ch, linediff, M); if(i - 19 != -1) diff[i] += diff[i - 19]; prev[i] = i - 19; chars[i] = ch; } if(i - 20 == -1 || (i - 20 >= 0 && diff[i - 20] >= 0)) { int d = diff20(i - 19, ch, linediff, M); if(i - 20 != -1) d += diff[i - 20]; if(diff[i] < 0 || d < diff[i]) { diff[i] = d; prev[i] = i - 20; chars[i] = ch; } } if(i - 21 == -1 || (i - 21 >= 0 && diff[i - 21] >= 0)) { int d = diff21(i - 20, ch, linediff, M); if(i - 21 != -1) d += diff[i - 21]; if(diff[i] < 0 || d < diff[i]) { diff[i] = d; prev[i] = i - 21; chars[i] = ch; } } } int cur = N - 1; stack<char> st; while(cur != -1) { st.push(chars[cur]); cur = prev[cur]; } while(!st.empty()) { fout << st.top(); st.pop(); } fout << endl; return 0; }
true
8ac395312d4e1d6fb3ff50367836c4d3f29cbbd4
C++
jeffphi/advent-of-code-2018
/jeff/day-05/part-2.cpp
UTF-8
1,615
3.1875
3
[ "MIT" ]
permissive
#include <iostream> #include <vector> #include <stack> #include <string> #include "jefflib.h" #include <algorithm> using namespace std; //using namespace boost; // Ugh, forward declaring a thing... int getPolymerLength(string input); int main() { vector<string> vect; if(GetStringInput(vect)){ cout << "Got data!" << endl; cout << endl; } else { cout << "Failed to read input :( " << cout; return -1; } string input = vect[0]; int shortest = INT_MAX; char targetLetter; string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; for(int i = 0; i < letters.length(); i++ ){ string s = input; s.erase(remove(s.begin(), s.end(), letters[i]), s.end()); s.erase(remove(s.begin(), s.end(), tolower(letters[i])), s.end()); int len = getPolymerLength(s); if (len < shortest){ shortest = len; targetLetter = letters[i]; } } cout << "Bad unit: " << targetLetter << ", length: " << shortest << endl; } int getPolymerLength(string input) { int index = 0; stack<char> stack; while(index < input.length()){ if(stack.empty()){ stack.push(input[index]); index++; continue; } char c1 = stack.top(); char c2 = input[index]; if(c1 != c2 && tolower(c1, locale()) == tolower(c2, locale())){ //cout << c1 << " matches " << c2 << endl; stack.pop(); } else { stack.push(input[index]); } index++; } return stack.size(); }
true
58908c018f40fec0504a2c533260786f3888143f
C++
zhu-he/ACM-Source
/CDOJ/Contest/54/C.cpp
UTF-8
742
2.796875
3
[]
no_license
#include <cstdio> long long C(long long x, long long y) { long long ans = 1; for (int i = 1; i <= x; ++i) { ans *= y - i + 1; ans /= i; } return ans; } int F(long long x,long long y) { int tot=0; while(x%y==0) { tot++; x=x/y; } return tot; } int main() { long long t, m; // scanf("%lld %lld", &t, &m); t = 7; for (m = t; m < 50; m += t) { long long s = 1; while (s * t < m) { s *= t; } long long s2 = s; while (s2 + s <= m) { s2 += s; } long long max = 0; long long maxc = -1; for (int i = 0; i <= m; ++i) { if (F(C(i, m), t) >= max) { max = F(C(i, m), t); maxc = i; } } printf("%lld %lld %lld %lld\n", m, t, s2 - 1, maxc); } return 0; }
true
c43a52d4c25adc855c75f2c774c185fd3f4020f5
C++
appsmonkey/air.nodemcu.full
/lib/Control/RGB_LED/RGB_LED.cpp
UTF-8
2,136
3.203125
3
[ "Apache-2.0" ]
permissive
#include <RGB_LED.h> RGB_LED::RGB_LED(int red, int green, int blue) { pin.red = red; pin.green = green; pin.blue = blue; // listen = "air aqi range"; listen = "AIR_AQI_RANGE"; // Turn it on pinMode(pin.red, OUTPUT); pinMode(pin.green, OUTPUT); pinMode(pin.blue, OUTPUT); control("light rgb levels 6"); addToInterval(this); } void RGB_LED::interval() { static int last_range = -1; if (!listen.length()) { if (debug) { Serial << "RGB LED | Listening not set " << endl << "RGB LED | Use led.listen = \"range name\" to set it." << endl; } return; } if (debug) { Serial << "RGB LED | Listening set to: " << listen << endl; } int current_range = (int) senseValues[listen].value; // no need to update if same as last if (current_range == last_range) { if (debug) { Serial << "RGB LED | Range " << listen << "same as last time - nothing to do" << endl; } return; } int colors[6][3] = { { 1, 200, 255 }, // blue { 60, 255, 1 }, // green { 255, 120, 1 }, // yellow { 255, 40, 1 }, // orange { 255, 1, 170 }, // purple { 255, 1, 1 } // red }; if (current_range >= sizeof(colors)) current_range = sizeof(colors) - 1; int red = map(colors[current_range][0], 0, 255, 0, 1023); int green = map(colors[current_range][1], 0, 255, 0, 1023); int blue = map(colors[current_range][2], 0, 255, 0, 1023); if (debug) { Serial << "RGB LED | Printing for range: " << current_range << endl << "red: " << red << "[" << colors[current_range][0] << "]" << " green: " << green << "[" << colors[current_range][1] << "]" << " blue: " << blue << "[" << colors[current_range][2] << "]" << endl; } analogWrite(pin.red, red); analogWrite(pin.green, green); analogWrite(pin.blue, blue); last_range = current_range; } // RGB_LED::loop
true
d9278909e37d81f140b40095965b57c59c6e56bb
C++
shang-lin/pacman
/final/ServerGameboard.h
UTF-8
1,810
2.71875
3
[]
no_license
#ifndef _SERVERGAMEBOARD_H_ #define _SERVERGAMEBOARD_H_ /* This class contains the server's representation of the level and everything in it. GameServer gets information from this class, makes the necessary decisions, and updates this class accordingly. */ class ServerGameboard; class Level; // The includes for the superclasses are automatically listed. // You need to specify any others #include "drawableobject.h" #include "GameServer.h" #include "../graphics/sidebar.h" #include "../graphics/chatwnd.h" class ServerGameboard : private DrawableObject{ // Data Members private: // This is the range of x-values of spaces in the level. int width; // This is the current level. Level* level; // This is the list of user-controlled players. Player** userPlayers; // This is the list of AI-controlled players. Player** aiPlayers; // The list of players who are merely observing the game. Player** observerList; int numUsers, numAI, numObs; // The GameServer containing the gameboard, null if this is a client gameboard GameServer *server; int ghostkillbonus, pacdeathpenalty, packillbonus, ghostdeathpenalty; public: // Methods public: // Returns the width of the level. int getWidth( void ); // Returns the length (range of y-values) of the level. int getLength( void ); // Returns the number of levels (ie, stories) in the level. int getLevels( void ); Space* getSpace(int x, int y, int z); Level* getLevel(); void Move(Player* p, int x, int y, int z); void Move(Player* p, Space* where); void EatItem(Player* p, BaseItem* item); void EatPlayer(Player* p, Player* eaten); void addPlayer(Player* p, int ai); // Constructor(s) ServerGameboard(Level *newlevel, GameServer *newserver); // Destructor ~ServerGameboard ( void ); }; #endif
true
078ec3021effae2c73241571848eb5c6664155f9
C++
dltech-xyz/WangDao-DataStructure
/经典算法练习题/L13调整数组顺序使得奇数在偶数前面.cpp
UTF-8
937
3.859375
4
[ "Apache-2.0" ]
permissive
// // Created by 安炳旭 on 2020-01-13. // #include <iostream> #include <vector> using namespace std; void reOrderArray(vector<int> &array) { //算法本质:插入排序 --> 将奇数插入到偶数前面 for (int i = 1; i < array.size(); ++i) { //从第二个元素开始比较 若是奇数则向前移动 int temp = array[i];//保存第i个位置应该插入到数 int j = i;//使用临时遍历j用于确定第i个元素的下标j(若不使用i的复制j 则会造成i向前回溯 影响算法的效率) if (temp % 2 == 1) {//是奇数 while (j > 0 && array[j - 1] % 2 == 0) {//若前面是偶数则移动 array[j] = array[j - 1]; j--; } array[j] = temp; } } } //int main() { // // vector<int> a = {1, 2, 3, 4}; // reOrderArray(a); // for (int aa:a) { // cout << aa << endl; // } //}
true
4322370af8d87b47bafa74ab9cd1d2a0df7b82cb
C++
wolwolton/mps
/src/export.cpp
UTF-8
3,086
2.5625
3
[]
no_license
#include <iostream> #include <fstream> #include <memory> #include <vector> #include "environment.h" #include "particle.h" #include "export.h" int Export::exportPara(const std::string name, const std::vector<std::unique_ptr<Particle>>& pcls){ std::ofstream ofs(name); if (!ofs) { ofs.close(); return -1; } int pcls_count = pcls.size(); ofs << "<?xml version='1.0' encoding='UTF-8'?>" << std::endl; ofs << "<VTKFile xmlns='VTK' byte_order='LittleEndian' version='0.1' type='UnstructuredGrid'>" << std::endl; ofs << "<UnstructuredGrid>" << std::endl; ofs << "<Piece NumberOfCells='"<< pcls_count << "' NumberOfPoints='" << pcls_count << "'>"<< std::endl; ofs << "<Points>" << std::endl; ofs << "<DataArray NumberOfComponents='3' type='Float32' Name='Position' format='ascii'>" << std::endl; for(auto &&pcl : pcls){ ofs << pcl->pos.x() << " " << pcl->pos.y() << " " << pcl->pos.z() << std::endl; } ofs << "</DataArray>" << std::endl; ofs << "</Points>" << std::endl; ofs << "<PointData>" << std::endl; ofs << "<DataArray NumberOfComponents='1' type='Int32' Name='ParticleType' format='ascii'>" << std::endl; for(auto &&pcl : pcls){ ofs << pcl->typ << std::endl; } ofs << "</DataArray>" << std::endl; ofs << "<DataArray NumberOfComponents='1' type='Float32' Name='Velocity' format='ascii'>" << std::endl; for(auto &&pcl : pcls){ ofs << (float)pcl->vel.norm() << std::endl; } ofs << "</DataArray>" << std::endl; ofs << "<DataArray NumberOfComponents='1' type='Float32' Name='pressure' format='ascii'>" << std::endl; for(auto &&pcl : pcls){ ofs << (float)pcl->prr << std::endl; } ofs << "</DataArray>" << std::endl; ofs << "</PointData>" << std::endl; ofs << "<Cells>" << std::endl; ofs << "<DataArray type='Int32' Name='connectivity' format='ascii'>" << std::endl; for(int i=0;i<pcls_count; i++){ ofs << i << std::endl; } ofs << "</DataArray>" << std::endl; ofs << "<DataArray type='Int32' Name='offsets' format='ascii'>" << std::endl; for(int i=0;i<pcls_count; i++){ ofs << i+1 << std::endl; } ofs << "</DataArray>" << std::endl; ofs << "<DataArray type='UInt8' Name='types' format='ascii'>" << std::endl; for(int i=0;i<pcls_count; i++){ ofs << 1 << std::endl; } ofs << "</DataArray>" << std::endl; ofs << "</Cells>" << std::endl; ofs << "</Piece>" << std::endl; ofs << "</UnstructuredGrid>" << std::endl; ofs << "</VTKFile>" << std::endl; ofs.close(); return 0; } int Export::exportPara(const std::string name,int i, const std::vector<std::unique_ptr<Particle>>& pcls){ std::string fname = name+std::to_string(i)+".vtu"; std::cout<<fname<<std::endl; return exportPara(fname,pcls); } int Export::exportPara(const std::string name, Environment& env){ return exportPara(name, env.pcls); } int Export::exportPara(const std::string name, int i, Environment& env){ return exportPara(name, i, env.pcls); }
true
826e2a9f981e074e9545a24b19dbc4c8a3f451aa
C++
bishwajit1998/interview-practice
/array.cpp
UTF-8
499
2.984375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; #define MAX 10 int findValue(int arr[], int n) { int ans = 0; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) ans = max(ans, abs(arr[i] - arr[j]) + abs(i - j)); return ans; } int main() { int t; cin>>t; while(t--){ int n; cin>>n; int arr[n]; for(int i = 0;i<n;i++) { cin>>arr[i]; } cout << findValue(arr, n) << endl; } return 0; }
true
db4152488330458189b2a1fcafbff61e1abf57eb
C++
LappenX/neo
/packages/neo/src/util/Exception.h
UTF-8
679
3.25
3
[]
no_license
#ifndef NEO_EXCEPTION_H #define NEO_EXCEPTION_H #include <string> #define RETHROW(CATCH, THROW, ...) \ try \ { \ __VA_ARGS__; \ } \ catch (const CATCH& e) \ { \ throw THROW(e); \ } class Exception : public std::exception { public: Exception(std::string message) : m_message(message) { } Exception(std::string message, const Exception& cause) : m_message(message + "\nCause: " + std::string(cause.what())) { } virtual ~Exception() { } // TODO: remove all Exception.copy() subclass methods const char* what() const throw() { return m_message.c_str(); } private: std::string m_message; }; #endif // NEO_EXCEPTION_H
true
6a62ce146fd598aaab568b105ffce29ed70d1b3f
C++
Abiduddin/Competitive-Programming-Codes
/C++/tuto/15.2.cpp
UTF-8
333
3.296875
3
[]
no_license
#include <iostream> using namespace std; class sum { int a,b; public: void get(int i,int j) { a=i; b=j; } void show(void) { cout<<"sum is "<<a+b<<endl; } }; int main() { sum ob1,ob2; ob1.get(11,23); ob1.show(); ob2=ob1; ob2.show(); return 0; }
true
a4031bfe859d5c23601d7158dc6623251d724553
C++
simran279/100-days-of-DSA
/binary trees/verticalTraversal2.cpp
UTF-8
861
3.15625
3
[]
no_license
#include "binaryTree.h" #include<bits/stdc++.h> #include<map> #include<vector> //O(n) void getVerticalOrder(BinaryTreeNode<int>* root, int hd, map<int, vector<int> > &m){ if(root == NULL) return; m[hd].push_back(root->data); getVerticalOrder(root->left, hd-1, m); getVerticalOrder(root->right, hd+1, m); } void verticalTraversal(BinaryTreeNode<int>* root){ if(root ==NULL) return; map<int, vector<int> > m; int hd=0; getVerticalOrder(root, hd, m); map<int, vector<int> > :: iterator it; for(it= m.begin(); it!=m.end(); it++){ for(int i=0; i<it->second.size(); i++){ cout<<it->second[i]<<" "; } cout<<endl; } } // 1 2 3 4 5 6 7 -1 -1 -1 -1 -1 8 -1 9 -1 -1 -1 -1 int main(){ BinaryTreeNode<int>* root= takeInput(); cout<<endl; verticalTraversal(root); }
true
69c31e8ffffffa074506e0ed8b692cf8a217312f
C++
sandeshghimire/CPPAPIDESIGN
/C++/c01_code/vectortest/vectortest3.cpp
UTF-8
282
3.140625
3
[]
no_license
#include <string> #include <vector> #include <iostream> #include <iterator> using namespace std; template<typename T> T value(T a) { std::cout << a * a << std::endl; return a; } int main() { std::cout << (value(10)) << std::endl; return 0; }
true
4db2422c52bfb1a0c1308895256638cfc0a583ad
C++
Mauzey/UF3366-FdSc-Software-Development
/SDFD212/Robotic-Drawing-Arm/main.ino
UTF-8
2,286
3.375
3
[]
no_license
#include <Servo.h> // Arm lengths #define length1 105 #define length2 121 #define pi 3.141592 #define moveDelay 50 void inverseK(int xPos, yPos); // Position of origin X/Y (Starting at 0, 0 results in the arm not working properly) float x = 40, y = 120; int ang; // Used calculating how to draw circles // Square vertices int a = 40; int b = 120; int c = 120; int d = 180; float angle1, angle2; // The servo's angles Servo servo1, servo2; // Servo definitions void setup() { // Set up serial monitor Serial.begin(9600); // Allocate servo pins servo1.attach(8); servo2.attach(9); } void loop() { // Draw rectangle for (x = a; x < b; x++) inverseK(x, y, false); // First side for (y = c; y < d; y++) inverseK(x, y, false); // Second side for (x = b; x > a; x--) inverseK(x, y, false); // Third side for (y = d; y > c; y--) inverseK(x, y, false); // Fourth side // Draw circle for (x = a; x < 80; x++) inverseK(x, y, false); // Move into position for (int i = 0; i < 800; i++) { ang = ((2.0 * pi) / 800.0) * (float)i; x = 80 - sin(ang) * 30; y = 150 - cos(ang) * 30; inverseK(x, y, true); } // Draw 'S' // Draw top semicircle for (int i = 0; i < 400 i++) { ang = ((2.0 * pi) / 800.0) * (float)i; x = 80 - sin(ang) * 15; y = 135 - cos(ang) * 15; inverseK(x, y, true); } // Draw bottom semicircle for (int i = 0; i < 400; i++) { ang = ((2.0 * pi) / 800.0) * (float)i; x = 80 + sin(ang) * 15; y = 165 - cos(ang) * 15; inverseK(x, y, true); } // Move back to the start point for (x = 80; x > a; x--) inverseK(x, y, false); for (y = d; y > c; y--) inverseK(x, y, false); } // Inverse kinematics function void inverseK(int xPos, int yPos, bool isCircle) { angle1 = degrees(acos((xPos*xPos + yPos*yPos - length1*length1 - legnth2*length2) / (2 * length1 * length2))); angle2 = degrees(atan(yPos/xPos) - acos((xPos*xPos + yPos*yPos + length1*length1 - length2*length2) / (2 * length1 * sqrt(xPos*xPos + yPos*yPos)))); // Debug Serial.println(angle1, 5); Serial.println(angle2, 5); servo1.write(angle1); if (!isCircle) delay(moveDelay); // Don't delay if drawing a circle, for a more fluid drawing servo2.write(angle2); delay(moveDelay); }
true
cb32b055b2fbdc6011f7418cac18c5c230a08783
C++
bhardwaj75/Campus-Placement-Preparation
/priority_queue_with_comp.cpp
UTF-8
605
3.140625
3
[ "Unlicense" ]
permissive
#include <bits/stdc++.h> using namespace std; // for set,map and heap we use function call operator loading //6,4,3,2 //Last element in container will be the top element of heap class custom{ public: bool operator()(const int &a, const int &b){ if(a>b)return true; // Min heap comparision because min element will be in the last return false; } }; int main(){ priority_queue<int,vector<int>,custom>pq; pq.push(2); pq.push(4); pq.push(3); pq.push(6); while(!pq.empty()){ cout<<pq.top()<<" "; pq.pop(); } }
true
8132685ff05a6da9385548e2880cd27063fc46f9
C++
richardscollin/kraken
/deprecated_compiler/include/Table.h
UTF-8
1,012
2.515625
3
[ "MIT" ]
permissive
#include <fstream> #include <string> #include <utility> #include "util.h" #include "ParseRule.h" #include "ParseAction.h" #include "Symbol.h" #include "State.h" #ifndef TABLE_H #define TABLE_H class Table { public: Table(); ~Table(); void exportTable(std::ofstream &file); void importTable(char* tableData); void setSymbols(Symbol EOFSymbol, Symbol nullSymbol); void add(int stateNum, Symbol tranSymbol, ParseAction* action); void remove(int stateNum, Symbol tranSymbol); std::vector<ParseAction*>* get(int state, Symbol token); ParseAction* getShift(int state, Symbol token); std::vector<std::pair<std::string, ParseAction>> stateAsParseActionVector(int state); std::string toString(); private: std::vector< std::vector< std::vector<ParseAction*>* >* > table; std::vector<Symbol> symbolIndexVec; //The EOFSymbol, a pointer because of use in table, etc Symbol EOFSymbol; //The nullSymbol, ditto with above. Also used in comparisons Symbol nullSymbol; }; #endif
true
a635bb81715240af17a1d2ee750f51a3c6200d7d
C++
sonyeo/GSP
/Homework4/EduServer_IOCP/SyncExecutable.h
UHC
1,603
2.875
3
[ "MIT" ]
permissive
#pragma once #include "TypeTraits.h" #include "FastSpinlock.h" #include "Timer.h" class SyncExecutable : public std::enable_shared_from_this<SyncExecutable> { public: SyncExecutable() : mLock(LO_BUSINESS_CLASS) {} virtual ~SyncExecutable() {} template <class R, class T, class... Args> R DoSync(R (T::*memfunc)(Args...), Args... args) { static_assert(true == std::is_convertible<T, SyncExecutable>::value, "T should be derived from SyncExecutable"); //TODO: mLock ȣ ¿, memfunc ϰ R } void EnterLock() { mLock.EnterWriteLock(); } void LeaveLock() { mLock.LeaveWriteLock(); } template <class T> std::shared_ptr<T> GetSharedFromThis() { static_assert(true == std::is_convertible<T, SyncExecutable>::value, "T should be derived from SyncExecutable"); //TODO: this ͸ std::shared_ptr<T>· ȯ. //(HINT: Ŭ std::enable_shared_from_this ӹ޾Ҵ. ׸ static_pointer_cast ) return std::shared_ptr<T>((Player*)this); ///< ̷ ϸ ȵɰ??? } private: FastSpinlock mLock; }; template <class T, class F, class... Args> void DoSyncAfter(uint32_t after, T instance, F memfunc, Args&&... args) { static_assert(true == is_shared_ptr<T>::value, "T should be shared_ptr"); static_assert(true == std::is_convertible<T, std::shared_ptr<SyncExecutable>>::value, "T should be shared_ptr SyncExecutable"); //TODO: instance memfunc bind  LTimer->PushTimerJob() }
true
408ba296104c3c7d61b95f66896c70dc016fe89f
C++
BaeJuneHyuck/BaekJune
/Baekjoon/BJ2839.cpp
UHC
643
3.34375
3
[]
no_license
/* // 2839 // 3,5ųα׷ -> // ϸ ->-1 */ #include <iostream> using namespace std; int getSugar(int suga) { int minCup = -1; if (suga % 5 == 0) { return minCup = suga / 5; }else if ((suga % 3) == 0) { minCup = suga / 3; } int sugar5 = 0; while (suga > 0) { if (suga % 3 == 0) { minCup = sugar5 + suga/3; cout << " = '5' * " << sugar5 << " + '3' * " << suga/ 3 << endl; } suga -= 5; sugar5++; } return minCup; } int main() { int sugar; cin >> sugar; cout << getSugar(sugar) << endl; system("pause"); return 0; }
true
83c262db97ec6cb87672b6395d89edac9102ee0a
C++
JayOfferdahl/eecs560-DataStructures
/Labs/lab1/Node.h
UTF-8
708
3.171875
3
[]
no_license
//*********************************************** // // Author: Jay Offerdahl // Class: EECS 560 (Data Structures) // Lab: Tues. 11a - 12:50p // Lab #: 1 // //*********************************************** #ifndef NODE_H #define NODE_H class Node { public: // Create a Node with value value Node(int); // Return the value stored in this Node int getValue(); // Return the next Node this Node is pointing at Node* getNext(); // Set the value stored in this Node to the input int void setValue(int); // Set the next Node this Node is pointint at to the input void setNext(Node*); private: // Private pointer to the next Node Node* m_next; // Value stored in this Node int m_value; }; #endif
true
89822ddbfdaa14885c3bc5419cc0d9bb6f86ba95
C++
lfresco/Programming_Principles
/CH03/11.cc
UTF-8
1,685
3.921875
4
[]
no_license
#include <iostream> void information_output(int five_cents, int ten_cents, int twenty_cents, int fifty_cents); double from_coins_to_euros(int five_cents, int ten_cents, int twenty_cents, int fifty_cents); int main(int argv, char * argc[]){ std::cout << "How many 5 cents coins do you have?" << std::endl; int five_cents; std::cin >> five_cents; std::cout << "How many 10 cents coins do you have?" << std::endl; int ten_cents; std::cin >> ten_cents; std::cout << "How many 20 cents coins do you have?" << std::endl; int twenty_cents; std::cin >> twenty_cents; std::cout << "How many 50 cents coins do you have?" << std::endl; int fifty_cents; std::cin >> fifty_cents; information_output(five_cents,ten_cents,twenty_cents,fifty_cents); return 0; } void information_output(int five_cents, int ten_cents, int twenty_cents, int fifty_cents){ std::cout << "You've got " << five_cents << " 5 cents coins." << std::endl; std::cout << "You've got " << ten_cents << " 10 cents coins." << std::endl; std::cout << "You've got " << twenty_cents << " 20 cents coins." << std::endl; std::cout << "You've got " << fifty_cents << " 50 cents coins." << std::endl; int total = five_cents + ten_cents + twenty_cents + fifty_cents; std::cout << "This amounts to a total of " << total << "coins." << std::endl; double euros = from_coins_to_euros(five_cents,ten_cents,twenty_cents,fifty_cents); std::cout << "For a total of " << euros << "euros." << std::endl; } double from_coins_to_euros(int five_cents, int ten_cents, int twenty_cents, int fifty_cents){ double euros = 0.05* five_cents + 0.1* ten_cents + 0.2 * twenty_cents + 0.5 * fifty_cents; return euros; }
true
4e38cbac2cccb8ddb27f08c47a782b6e6aeed7c7
C++
stefankurz1/pepper_emotion
/emotional_system/theatre_bot/src/WorldModelDescription/TheatrePlaces.h
UTF-8
1,118
2.828125
3
[]
no_license
/* * TheatrePlaces.h * * Created on: Mar 23, 2015 * Author: julian */ #ifndef THEATREPLACES_H_ #define THEATREPLACES_H_ class TheatrePlaces { public: TheatrePlaces(); virtual ~TheatrePlaces(); void setStageInformation(float maximum_lenght_x, float maximum_lenght_y, float number_rectangles_x, float number_rectangles_y); /* * This method returns true if the id exist or false if not * the place_id is the desire place identification and point_x and point_y are two pointers that are going to be changed with the correct position of the place */ bool getPoinDestination(int place_id, float *point_x, float *point_y); float getMaximumLenghtX(); float getMaximumLenghtY(); float getNumberRectanglesX(); float getNumberRectanglesY(); private: float maximum_lenght_x;//it should set from file float maximum_lenght_y;//it should set from file float number_rectangles_x;//it should set from file float number_rectangles_y;//it should set from file float lenght_rectangle_x; //it is calculated from maximum_lenght/number_rectangles float lenght_rectangle_y; }; #endif /* THEATREPLACES_H_ */
true
f54e888a08d1ef577f274b5af247c6150e0c14cf
C++
anilaksu/Cpp-Codes-and-Practices
/StaticVariableTrials/StaticVariables/StaticVariables/maincpp.cpp
UTF-8
1,713
3.40625
3
[]
no_license
#include<iostream> #include"MathClass.h" using namespace std; class Game { public: Game(int a) { this->a = a; } void showInfo() const { cout << "Game Info: " << endl; cout << this->a << endl; } private: int a; friend void getGameInfo(const Game& game); }; class Gamer { public: static int gamers; // Every class will have the same gamers static void getID(int ID) { cout << "Member ID is " << ID << endl; } int i; Gamer(int age, int Experience) { this->age = age; this->Experience = Experience; gamers++; cout << "New gamer generated" << endl; } private: int age; int Experience; int N_game; Game *game1; friend void showInfos(Gamer gamer); // friend function friend class GameProducer; // friend class }; int Gamer::gamers = 0; void showInfos(Gamer gamer) { //static int i = 3; //i++; cout << " Gamer age: " << gamer.age << endl; cout << " Gamer experience: " << gamer.Experience << endl; } class GameProducer { public: static void getGamerData(Gamer gamer) { cout << " Gamer age: " << gamer.age << endl; cout << " Gamer experience: " << gamer.Experience << endl; } }; void getGameInfo(const Game &game) { cout << "Game ID: " << endl; cout << game.a << endl; } int main() { //Gamer::getID(27); Gamer gamer1(27,5); Game game1(10); //Gamer gamer2; //Gamer gamer3; //int a[] = { 10,20,30,40,50 }; cout << "Number of gamers" << endl; cout << Gamer::gamers << endl; showInfos(gamer1); //cout << game1.a << endl; game1.showInfo(); getGameInfo(game1); //for (int i = 0; i < 5; i++) // cout << a[i] << endl; //Test(); //MathClass::cube(3); GameProducer::getGamerData(gamer1); //Test(); //Test(); return 0; }
true
dbd36602f01ce28fcb43a63da1612ac1d9d7aa7b
C++
PIKACHUIM/Pika-Cpp-App-Structs
/作业提交/第三章/3-2-链表实现队列/main.cpp
UTF-8
482
3.421875
3
[]
no_license
#include "fifo.h" #include <iostream> using namespace std; int main(void) { fifo<int>test; cout<<endl<<"当前队列长度:"<<test.getl()<<endl; cout<<"入队元素:"; for(int loop=1;loop<=10;loop++){ test.push(loop);cout<<loop<<" ";} cout<<endl<<"当前队列长度:"<<test.getl()<<endl; cout<<"出队元素:"; for(int loop=1;loop<=10;loop++) cout<<test.pops()<<" "; cout<<endl<<"当前队列长度:"<<test.getl()<<endl; }
true
6ce6240eb00ddcc1b97148a52347b77c81a2b387
C++
fredsonjr/exercicios-prog
/exercicios-download/Prog/Lista matriz 16I05/ex5..cpp
UTF-8
926
2.5625
3
[ "MIT" ]
permissive
#include <iostream> #include <stdlib.h> using namespace std; int main() { int mat[20][10], soma=0, somat=0, resul=0, vet[20],matr[20][10]; for(int i=0; i<20; i++) { for(int j=0; j<10; j++) { mat[i][j]=rand()%10; } } for(int i=0; i<20; i++) { cout << endl; for(int j=0; j<10; j++) { cout << mat[i][j]<< " "; } } cout << endl; for(int i=0; i<20; i++) { for(int j=0; j<10; j++) { soma=soma+mat[i][j]; vet[i]=soma; } cout << vet[i]<<endl; soma=0; } for(int i=0; i<20; i++) { for(int j=0; j<10; j++) { matr[i][j]=mat[i][j]*vet[i]; } } for(int i=0; i<20; i++) { cout << endl; for(int j=0; j<10; j++) { cout << matr[i][j]<< " "; } } }
true
35112ce52eb78cdf4a3e63702dc12bd7e5a473bc
C++
jooo000hn/cetech
/engine/include/cetech/celib/mat44f.inl
UTF-8
10,709
2.578125
3
[ "CC0-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#ifndef CETECH_MAT44F_H #define CETECH_MAT44F_H //============================================================================== // Includes //============================================================================== #include <string.h> #include "cetech/kernel/macros.h" #include "fmath.inl" #include "vec4f.inl" #include "math_types.h" //============================================================================== // Defines //============================================================================== #define MAT44F_INIT_IDENTITY (mat44f_t) \ { 1.0f, 0.0f, 0.0f, 0.0f, \ 0.0f, 1.0f, 0.0f, 0.0f, \ 0.0f, 0.0f, 1.0f, 0.0f, \ 0.0f, 0.0f, 0.0f, 1.0f } \ //============================================================================== // Interface //============================================================================== CETECH_FORCE_INLINE void mat44f_identity(mat44f_t *result) { memset(result, 0, sizeof(float) * 16); result->f[0] = 1.0f; result->f[5] = 1.0f; result->f[10] = 1.0f; result->f[15] = 1.0f; } CETECH_FORCE_INLINE void mat44f_translate(mat44f_t *result, float x, float y, float z) { mat44f_identity(result); result->f[12] = x; result->f[13] = y; result->f[14] = z; } CETECH_FORCE_INLINE void mat44f_scale(mat44f_t *result, float x, float y, float z) { memset(result, 0, sizeof(float) * 16); result->f[0] = x; result->f[5] = y; result->f[10] = z; result->f[15] = 1.0f; } CETECH_FORCE_INLINE void mat44f_rotate_x(mat44f_t *result, float x) { const float sx = float_sin(x); const float cx = float_cos(x); memset(result, 0, sizeof(float) * 16); result->f[0] = 1.0f; result->f[5] = cx; result->f[6] = -sx; result->f[9] = sx; result->f[10] = cx; result->f[15] = 1.0f; } CETECH_FORCE_INLINE void mat44f_rotate_y(mat44f_t *result, float y) { const float sy = float_sin(y); const float cy = float_cos(y); memset(result, 0, sizeof(float) * 16); result->f[0] = cy; result->f[2] = sy; result->f[5] = 1.0f; result->f[8] = -sy; result->f[10] = cy; result->f[15] = 1.0f; } CETECH_FORCE_INLINE void mat44f_rotate_z(mat44f_t *result, float z) { const float sz = float_sin(z); const float cz = float_cos(z); memset(result, 0, sizeof(float) * 16); result->f[0] = cz; result->f[1] = -sz; result->f[4] = sz; result->f[5] = cz; result->f[10] = 1.0f; result->f[15] = 1.0f; } CETECH_FORCE_INLINE void mat44f_rotate_xy(mat44f_t *result, float x, float y) { const float sx = float_sin(x); const float cx = float_cos(x); const float sy = float_sin(y); const float cy = float_cos(y); memset(result, 0, sizeof(float) * 16); result->f[0] = cy; result->f[2] = sy; result->f[4] = sx * sy; result->f[5] = cx; result->f[6] = -sx * cy; result->f[8] = -cx * sy; result->f[9] = sx; result->f[10] = cx * cy; result->f[15] = 1.0f; } CETECH_FORCE_INLINE void mat44f_rotate_xyz(mat44f_t *result, float x, float y, float z) { const float sx = float_sin(x); const float cx = float_cos(x); const float sy = float_sin(y); const float cy = float_cos(y); const float sz = float_sin(z); const float cz = float_cos(z); memset(result, 0, sizeof(float) * 16); result->f[0] = cy * cz; result->f[1] = -cy * sz; result->f[2] = sy; result->f[4] = cz * sx * sy + cx * sz; result->f[5] = cx * cz - sx * sy * sz; result->f[6] = -cy * sx; result->f[8] = -cx * cz * sy + sx * sz; result->f[9] = cz * sx + cx * sy * sz; result->f[10] = cx * cy; result->f[15] = 1.0f; } CETECH_FORCE_INLINE void mat44f_rotate_zyx(mat44f_t *result, float x, float y, float z) { const float sx = float_sin(x); const float cx = float_cos(x); const float sy = float_sin(y); const float cy = float_cos(y); const float sz = float_sin(z); const float cz = float_cos(z); memset(result, 0, sizeof(float) * 16); result->f[0] = cy * cz; result->f[1] = cz * sx * sy - cx * sz; result->f[2] = cx * cz * sy + sx * sz; result->f[4] = cy * sz; result->f[5] = cx * cz + sx * sy * sz; result->f[6] = -cz * sx + cx * sy * sz; result->f[8] = -sy; result->f[9] = cy * sx; result->f[10] = cx * cy; result->f[15] = 1.0f; }; CETECH_FORCE_INLINE int mat44f_eq(const mat44f_t *__restrict a, const mat44f_t *__restrict b, const float epsilon) { return float_equals(a->f, b->f, 4 * 4, epsilon); } CETECH_FORCE_INLINE int mat44f_is_identity(const mat44f_t *__restrict a, float epsilon) { static mat44f_t _identity = MAT44F_INIT_IDENTITY; return mat44f_eq(a, &_identity, epsilon); } CETECH_FORCE_INLINE void mat44f_mul(mat44f_t *__restrict result, const mat44f_t *__restrict a, const mat44f_t *__restrict b) { vec4f_mul_mat44f(&result->x, &a->x, b); vec4f_mul_mat44f(&result->y, &a->y, b); vec4f_mul_mat44f(&result->z, &a->z, b); vec4f_mul_mat44f(&result->w, &a->w, b); } CETECH_FORCE_INLINE void mat44f_inverse(mat44f_t *__restrict result, const mat44f_t *__restrict a) { float xx = a->f[0]; float xy = a->f[1]; float xz = a->f[2]; float xw = a->f[3]; float yx = a->f[4]; float yy = a->f[5]; float yz = a->f[6]; float yw = a->f[7]; float zx = a->f[8]; float zy = a->f[9]; float zz = a->f[10]; float zw = a->f[11]; float wx = a->f[12]; float wy = a->f[13]; float wz = a->f[14]; float ww = a->f[15]; float det = 0.0f; det += xx * (yy * (zz * ww - zw * wz) - yz * (zy * ww - zw * wy) + yw * (zy * wz - zz * wy)); det -= xy * (yx * (zz * ww - zw * wz) - yz * (zx * ww - zw * wx) + yw * (zx * wz - zz * wx)); det += xz * (yx * (zy * ww - zw * wy) - yy * (zx * ww - zw * wx) + yw * (zx * wy - zy * wx)); det -= xw * (yx * (zy * wz - zz * wy) - yy * (zx * wz - zz * wx) + yz * (zx * wy - zy * wx)); float inv_det = 1.0f / det; result->f[0] = +(yy * (zz * ww - wz * zw) - yz * (zy * ww - wy * zw) + yw * (zy * wz - wy * zz)) * inv_det; result->f[1] = -(xy * (zz * ww - wz * zw) - xz * (zy * ww - wy * zw) + xw * (zy * wz - wy * zz)) * inv_det; result->f[2] = +(xy * (yz * ww - wz * yw) - xz * (yy * ww - wy * yw) + xw * (yy * wz - wy * yz)) * inv_det; result->f[3] = -(xy * (yz * zw - zz * yw) - xz * (yy * zw - zy * yw) + xw * (yy * zz - zy * yz)) * inv_det; result->f[4] = -(yx * (zz * ww - wz * zw) - yz * (zx * ww - wx * zw) + yw * (zx * wz - wx * zz)) * inv_det; result->f[5] = +(xx * (zz * ww - wz * zw) - xz * (zx * ww - wx * zw) + xw * (zx * wz - wx * zz)) * inv_det; result->f[6] = -(xx * (yz * ww - wz * yw) - xz * (yx * ww - wx * yw) + xw * (yx * wz - wx * yz)) * inv_det; result->f[7] = +(xx * (yz * zw - zz * yw) - xz * (yx * zw - zx * yw) + xw * (yx * zz - zx * yz)) * inv_det; result->f[8] = +(yx * (zy * ww - wy * zw) - yy * (zx * ww - wx * zw) + yw * (zx * wy - wx * zy)) * inv_det; result->f[9] = -(xx * (zy * ww - wy * zw) - xy * (zx * ww - wx * zw) + xw * (zx * wy - wx * zy)) * inv_det; result->f[10] = +(xx * (yy * ww - wy * yw) - xy * (yx * ww - wx * yw) + xw * (yx * wy - wx * yy)) * inv_det; result->f[11] = -(xx * (yy * zw - zy * yw) - xy * (yx * zw - zx * yw) + xw * (yx * zy - zx * yy)) * inv_det; result->f[12] = -(yx * (zy * wz - wy * zz) - yy * (zx * wz - wx * zz) + yz * (zx * wy - wx * zy)) * inv_det; result->f[13] = +(xx * (zy * wz - wy * zz) - xy * (zx * wz - wx * zz) + xz * (zx * wy - wx * zy)) * inv_det; result->f[14] = -(xx * (yy * wz - wy * yz) - xy * (yx * wz - wx * yz) + xz * (yx * wy - wx * yy)) * inv_det; result->f[15] = +(xx * (yy * zz - zy * yz) - xy * (yx * zz - zx * yz) + xz * (yx * zy - zx * yy)) * inv_det; } CETECH_FORCE_INLINE void mat44f_transpose(mat44f_t *__restrict result, const mat44f_t *__restrict a) { result->f[0] = a->f[0]; result->f[4] = a->f[1]; result->f[8] = a->f[2]; result->f[12] = a->f[3]; result->f[1] = a->f[4]; result->f[5] = a->f[5]; result->f[9] = a->f[6]; result->f[13] = a->f[7]; result->f[2] = a->f[8]; result->f[6] = a->f[9]; result->f[10] = a->f[10]; result->f[14] = a->f[11]; result->f[3] = a->f[12]; result->f[7] = a->f[13]; result->f[11] = a->f[14]; result->f[15] = a->f[15]; } CETECH_FORCE_INLINE void mat44f_set_perspective_fov(mat44f_t *__restrict result, const float fov, const float aspect_ratio, float near, float far) { float yScale = 1.0f / float_tan(fov * CETECH_float_TORAD * 0.5f); float xScale = yScale / aspect_ratio; result->x.x = xScale; result->x.y = result->x.z = result->x.w = 0.0f; result->y.y = yScale; result->y.x = result->y.z = result->y.w = 0.0f; result->z.x = result->z.y = 0.0f; result->z.z = far / (near - far); result->z.w = -1.0f; result->w.x = result->w.y = result->w.w = 0.0f; result->w.z = near * far / (near - far); } #endif //CETECH_MAT44F_H
true
fa684a2b40a04f4b2c68f6665d9dae2becb88f24
C++
Caturra000/vsJSON
/src/Json.h
UTF-8
6,198
3.078125
3
[]
no_license
#ifndef __JSON_H__ #define __JSON_H__ #include <bits/stdc++.h> #include "internal/Variant.h" #include "internal/TypeCompat.h" #include "JsonValue.h" namespace vsjson { class Json { public: // static template <typename ...Args> static JsonValue array(Args &&...elems); public: Json(): _value(ObjectImpl()) {} template <typename ...Args> Json(Args &&...args): _value(std::forward<Args>(args)...) {} template <size_t N> Json(const char (&str)[N]): _value(StringImpl(str)) {} Json(bool b): _value(BooleanImpl(b)) {} Json(nullptr_t): _value(NullImpl(nullptr)) {} Json(const std::string &str): _value(StringImpl(str)) {} Json(std::string &&str): _value(StringImpl(static_cast<std::string&&>(str))) {} Json(const std::initializer_list<ObjectImpl::value_type> &list): _value(ObjectImpl(list)) {} Json(std::initializer_list<ObjectImpl::value_type> &&list): _value(ObjectImpl(std::move(list))) {} Json(const Json &rhs): _value(rhs._value) {} Json(Json &&rhs): _value(std::move(rhs._value)) {} template <typename T, typename = std::enable_if_t<!std::is_same<std::decay_t<T>, Json>::value>> Json& operator=(T&& obj); Json& operator=(const Json &rhs); Json& operator=(Json &&rhs); template <size_t N> Json& operator=(const char (&str)[N]); Json& operator=(bool b); Json& operator=(nullptr_t); Json& operator=(const std::string &str); Json& operator=(std::string &&str); template <typename T> bool is() const { return _value.is<T>(); } template <typename T> T& as() { return _value.get<T>(); } template <typename T> T to() const & { return _value.to<T>(); } template <typename T> T to() && { return std::move(_value).to<T>(); } bool contains(const StringImpl &index) const; Json& operator[](const StringImpl &index); Json& operator[](size_t index); const Json& operator[](size_t index) const; size_t size() const; size_t arraySize() const; void append(const Json &json); void append(Json &&json); auto begin() -> ObjectImpl::iterator; auto end() -> ObjectImpl::iterator; std::string dump(); template <typename ...Specifieds> std::string dump(Specifieds &&...ses); // FIXME: use swap on operator= void swap(Json &rhs) { std::swap(*this, rhs); } friend std::ostream& operator<<(std::ostream &os, vsjson::Json &json); friend std::ostream& operator<<(std::ostream &os, vsjson::Json &&json) { return os << json._value; } private: JsonValue _value; }; template <typename ...Args> inline JsonValue Json::array(Args &&...elems) { return JsonValue(ArrayImpl{std::forward<Args>(elems)...}); } template <typename T,typename> inline Json& Json::operator=(T&& obj) { this->~Json(); _value = std::forward<T>(obj); return *this; } inline Json& Json::operator=(const Json &rhs) { if(this == &rhs) return *this; this->~Json(); _value = rhs._value; return *this; } inline Json& Json::operator=(Json &&rhs) { if(this == &rhs) return *this; this->~Json(); _value = std::move(rhs._value); return *this; } template <size_t N> inline Json& Json::operator=(const char (&str)[N]) { _value = StringImpl(str); return *this; } inline Json& Json::operator=(bool b) { _value = BooleanImpl(b); return *this; } inline Json& Json::operator=(nullptr_t) { _value = NullImpl(nullptr); return *this; } inline Json& Json::operator=(const std::string &str) { _value = StringImpl(str); return *this; } inline Json& Json::operator=(std::string &&str) { _value = StringImpl(static_cast<std::string&&>(str)); return *this; } inline bool Json::contains(const StringImpl &index) const { return _value.get<ObjectImpl>().count(index); } inline Json& Json::operator[](const StringImpl &index) { return _value.get<ObjectImpl>()[index]; } inline Json& Json::operator[](size_t index) { return _value.get<ArrayImpl>()[index]; } inline const Json& Json::operator[](size_t index) const { return _value.get<ArrayImpl>()[index]; } inline size_t Json::size() const { return _value.get<ObjectImpl>().size(); } inline size_t Json::arraySize() const { return _value.get<ArrayImpl>().size(); } inline void Json::append(const Json &json) { _value.get<ArrayImpl>().emplace_back(json); } inline void Json::append(Json &&json) { _value.get<ArrayImpl>().emplace_back(static_cast<Json&&>(json)); } inline auto Json::begin() -> ObjectImpl::iterator { return _value.get<ObjectImpl>().begin(); } inline auto Json::end() -> ObjectImpl::iterator { return _value.get<ObjectImpl>().end(); } inline std::string Json::dump() { std::stringstream ss; ss << (*this); return ss.str(); } template <typename ...Specifieds> inline std::string Json::dump(Specifieds &&...ses) { std::stringstream ss; // set stream status or put data before dump std::initializer_list<int> {((ss << std::forward<Specifieds>(ses)), 19260817)...}; ss << (*this); return ss.str(); } /// specialization template <> inline bool Json::is<bool>() const { return _value.is<BooleanImpl>(); } template <> inline bool Json::is<nullptr_t>() const { return _value.is<NullImpl>(); } template <> inline bool Json::is<std::string>() const { return _value.is<StringImpl>(); } template <> inline std::string& Json::as<std::string>() { return _value.get<StringImpl>(); } inline std::ostream& operator<<(std::ostream &os, ArrayImpl &vec) { os << '['; for(auto iter = vec.begin(); iter != vec.end(); ++iter) { os << *iter; if(std::distance(iter, vec.end()) > 1) { os << ','; } } os << ']'; return os; } inline std::ostream& operator<<(std::ostream &os, ObjectImpl &map) { os << '{'; for(auto iter = map.begin(); iter != map.end(); ++iter) { os << '\"' << iter->first << "\":" << iter->second; if(std::distance(iter, map.end()) > 1) { os << ','; } } os << '}'; return os; } inline std::ostream& operator<<(std::ostream &os, vsjson::Json &json) { return operator<<(os, static_cast<Json&&>(json)); } } // vsjson #endif
true
1c039a353371953681170378fe1096713cca327c
C++
Population-image/Population
/other/tutorial/iterator_matrix.cpp
UTF-8
2,620
2.953125
3
[ "MIT" ]
permissive
#include"Population.h"//Single header using namespace pop;//Population namespace template<typename PixelType> void fill1(MatN<2,PixelType> & m, PixelType value){ for(unsigned int i =0;i<m.sizeI();i++) for(unsigned int j =0;j<m.sizeJ();j++) m(i,j)=value; } template<typename PixelType> void fill2(MatN<2,PixelType> & m, PixelType value){ ForEachDomain2D(x,m){ m(x)=value; } } template<int DIM,typename PixelType> void fill3(MatN<DIM,PixelType> & m, PixelType value){ typename MatN<DIM,PixelType>::IteratorEDomain it = m.getIteratorEDomain();//in C++11, you can write: auto it = img.getIteratorEDomain(); while(it.next()){ m(it.x())=value; } } template<int DIM,typename PixelType> MatN<DIM,PixelType> erosion1(const MatN<DIM,PixelType> & m, F32 radius, int norm){ MatN<DIM,PixelType> m_ero(m.getDomain()); typename MatN<DIM,PixelType>::IteratorEDomain it_global = m.getIteratorEDomain();//in C++11, you can write: auto it_global = m.getIteratorEDomain(); typename MatN<DIM,PixelType>::IteratorENeighborhood it_local = m.getIteratorENeighborhood(radius,norm);//in C++11, you can write: auto it_local = m.getIteratorENeighborhood(radius,norm); //Global scan while(it_global.next()){ PixelType value = pop::NumericLimits<PixelType>::maximumRange(); it_local.init(it_global.x()); //local scan while(it_local.next()){ value = pop::minimum(value,m(it_local.x())); } m_ero(it_global.x())=value; } return m_ero; } template<int DIM,typename PixelType,typename IteratorEGlobal,typename IteratorELocal> MatN<DIM,PixelType> erosion2(const MatN<DIM,PixelType> & m, IteratorEGlobal it_global, IteratorELocal it_local){ MatN<DIM,PixelType> m_ero(m); //Global scan while(it_global.next()){ PixelType value = pop::NumericLimits<PixelType>::maximumRange(); it_local.init(it_global.x()); //local scan while(it_local.next()){ value = pop::minimum(value,m(it_local.x())); } m_ero(it_global.x())=value; } return m_ero; } int main() { Mat2UI8 m(4,4); fill1(m,UI8(1)); std::cout<<m<<std::endl; fill2(m,UI8(2)); std::cout<<m<<std::endl; Mat3UI8 m3d(4,4,3);//3d matrix fill3(m3d,UI8(3)); std::cout<<m3d<<std::endl; m.load(POP_PROJECT_SOURCE_DIR+std::string("/image/Lena.bmp")); erosion1(m,5,2).display("erosion1",false); erosion2(m,m.getIteratorERectangle(Vec2F32(m.getDomain())*0.25f,Vec2F32(m.getDomain())*0.75f),m.getIteratorENeighborhood(5,2)).display("erosion2"); }
true
73637ed17e5aa7c18c17dbb4e3dc151de88bb1d2
C++
Chansla/Training
/wps/ATeacherFiles/8.03/Samrt_home课件和代码/QJson/QJson/widget.cpp
UTF-8
3,174
2.828125
3
[]
no_license
#include "widget.h" #include "ui_widget.h" Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) { ui->setupUi(this); json_package(); qDebug() << "write data is successful!"; json_analysis(); } Widget::~Widget() { delete ui; } void Widget::json_package() { //1.封装JSON数据 QJsonObject JsonPacket; JsonPacket.insert("enable",true); JsonPacket["length"] = 10; JsonPacket.insert("precision",0.1); JsonPacket.insert("name","Car"); //2.添加json数组的信息 QJsonArray new_array; new_array.append(1); new_array.append(2); new_array.append(3); JsonPacket.insert("array",new_array); //3.封装JSON对象 QJsonObject city_data; city_data.insert("city","黑龙江"); JsonPacket["province"] = city_data; JsonPacket.insert("what",QJsonValue::Null); //输出观察一下JSON数据 qDebug() << JsonPacket; //4.把JSON数据转换为QByteArray数据 QJsonDocument doc; doc.setObject(JsonPacket); QByteArray msg = doc.toJson(); //5.数据可能会经常使用,吧数据封装到一个xx.json文件中 QFile file; file.setFileName("./config.json"); bool ret = file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate); if(!ret) { QMessageBox::warning(NULL,"文件操作","打开文件失败",QMessageBox::Ok); return ; } file.write(msg); file.close(); } void Widget::json_analysis() { //1.从文件中读取数据 QFile file; file.setFileName("./config.json"); bool ret = file.open(QIODevice::ReadOnly); if(!ret) { QMessageBox::warning(NULL,"文件操作","打开文件失败",QMessageBox::Ok); return ; } //2.读取文件信息 QByteArray msg = file.readAll(); //3.转换为QJsonDocument对象 QJsonParseError err; QJsonDocument doc = QJsonDocument::fromJson(msg,&err); if(err.error != QJsonParseError::NoError) { QMessageBox::warning(NULL,"文件操作","解析文件失败",QMessageBox::Ok); return ; } //4.重新转换为QJson对象,进行解析 QJsonObject packet = doc.object(); int array[3]; bool enable; int length; QString name; double precision; QString city; int what; //5.解析数组 QJsonArray data = packet.value("array").toArray(); for(int i = 0;i < data.size();i++) { array[i] = data[i].toInt(); qDebug() << "array[" << i << "] = " << array[i]; } enable = packet.value("enable").toBool(); length = packet.value("length").toInt(); name = packet.value("name").toString(); precision = packet.value("precision").toDouble(); QJsonObject obj = packet["province"].toObject(); city = obj["city"].toString(); QJsonValue value = packet["what"]; if(value.type() == QJsonValue::Null) { what = 0; } qDebug() << "enable = " << enable; qDebug() << "length = " << length; qDebug() << "precision = " << precision; qDebug() << "name = " << name; qDebug() << "city = " << city; qDebug() << "what = " << what; }
true
8b00e6f36b299411e5de3e28ecd43c7edd965ef9
C++
sridharbgr/PowerControl
/PowerControl.ino
UTF-8
4,329
2.578125
3
[]
no_license
/*Header file include */ #include "Func_Init.h" #include "Voltage_Read_Func.h" #include "Current_Read_Func.h" #include <LiquidCrystal.h> /*********************************************************************/ /* Enum declarariom */ enum powerstatus { Highhigh, Lowlow, Normal }; enum powerstatus status_voltage =Normal; /*********************************************************************/ /* define Macros */ #define RELAY_CTRL 8 #define MAXVOLATGE 250 #define MINVOLTAGE 200 #define MAXCURRENT 6.5 #define MINCURRENT 1.7 #define LCD_RS 12 #define LCD_EN 11 #define LCD_D4 5 #define LCD_D5 4 #define LCD_D6 3 #define LCD_D7 2 //const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2; /*********************************************************************/ /* Declare Global variable */ static int Ctrl_Switch =HIGH; // to control current status at startup uint32_t calc_time; int mVperAmp = 100; // use 100 for 20A Module and 66 for 30A Module int Ctrlbit; double Voltage = 0; double Volatge_manipulation = 0; double VRMS = 0; double AmpsRMS = 0; //double voltage_in; static int status_current=2; long int voltage_in; static double Cycle_Time; // initialize the library by associating any needed LCD interface pin // with the arduino pin number it is connected to LiquidCrystal lcd(LCD_RS,LCD_EN,LCD_D4,LCD_D5,LCD_D6,LCD_D7); //char buff[5]; /*********************************************************************/ /* put your setup code here, to run once */ void setup(){ Serial.begin(9600); pinMode(RELAY_CTRL,OUTPUT); pinMode(LCD_RS,OUTPUT); pinMode(LCD_EN,OUTPUT); pinMode(LCD_D4,OUTPUT); pinMode(LCD_D5,OUTPUT); pinMode(LCD_D6,OUTPUT); pinMode(LCD_D7,OUTPUT); digitalWrite(RELAY_CTRL,LOW); // set up the LCD's number of columns and rows: lcd.begin(16, 2); // Print a message to the LCD. //lcd.print("hello, world!"); } /*********************************************************************/ /* put your main code here, to run repeatedly */ void loop() { Voltage = Current_Read_Func(); Volatge_manipulation = Voltage_Read_Func(); VRMS = (Voltage/2.0) *0.707; //root 2 is 0.707 if((calc_time >=200)) { AmpsRMS = (VRMS * 1000)/mVperAmp; if(AmpsRMS >MAXCURRENT) { status_current=0; } else if(AmpsRMS <MINCURRENT ) { status_current=2; } else { status_current=2; } } voltage_in = Volatge_manipulation; Cycle_Time++; if(Cycle_Time >=6) { if(voltage_in > MAXVOLATGE )//max voltage 241v { status_voltage = Highhigh; } else if(voltage_in < MINVOLTAGE )//min voltage 200v { status_voltage = Lowlow; } else { status_voltage = Normal; } //Ctrl_Switch = LOW; Cycle_Time=0; } //if(((status_voltage == Highhigh) ||(status_voltage == Lowlow) ||(status_current == 0)||(status_current == 1)) &&(Ctrl_Switch == HIGH)) if((status_voltage == Highhigh) ||(status_voltage == Lowlow) ||(status_current == 0)||(status_current == 1)) //if(1) { if((status_current == 0) ||(status_current == 1) ) { Ctrl_Switch=LOW; Serial.println('A'); } Serial.println("ALL"); digitalWrite(RELAY_CTRL,HIGH); } else if ((status_voltage != Highhigh) && (status_voltage != Lowlow)) { Serial.println("bye"); Ctrl_Switch=HIGH; digitalWrite(RELAY_CTRL,LOW); } Serial.println(status_current); //Serial.println(Cycle_Time); //Serial.println(RELAY_CTRL); /* Print a message to the LCD */ if(voltage_in >150){ lcd.clear(); lcd.setCursor(0, 0); lcd.print("V="); lcd.setCursor(3, 0); lcd.print(voltage_in); //lcd.setCursor(0, 1); lcd.setCursor(7, 0); lcd.print("C="); lcd.setCursor(9, 0); lcd.print(AmpsRMS); lcd.setCursor(0, 1); lcd.print("Status_amp:"); lcd.setCursor(13, 1); lcd.print(status_current); //sprintf(buff,"%f",AmpsRMS); } else { lcd.setCursor(0, 0); lcd.clear(); lcd.setCursor(0, 0); lcd.print("Low Power mode"); /* END LCD display */ } } /****** Main loop function ends *************************/
true
bab914ab6f4f50aeebbefb6c930d1f257af109ce
C++
koendv/vacuum-pump-controller
/arduino/vacuum_pump/console.cpp
UTF-8
8,911
2.65625
3
[]
no_license
#include "console.h" #include "autotune.h" #include "bytesfree.h" #include "display.h" #include "loopstats.h" #include "motor.h" #include "pidctrl.h" #include "sensor.h" #include "settings.h" #include "uptime.h" #include "watchdog.h" #include <Arduino.h> #define MAXCMDLEN 64 /* console command line interpreter. * A command is a character, optionally followed by an integer or floating-point number. * Status messages are: * "init" - non-volatile storage reset to defaults * "ok" - command successful * "how?" - illegal value * "what?" - syntax error * * To stop pressure being logged to the console, enter 'l0'. */ namespace console { enum err_code { ERR_OK, ERR_SYNTAX, ERR_VALUE }; enum err_code ok = ERR_OK; bool echo_on = true; String cmdline; void reset() { Serial.println("ok"); Serial.flush(); motor::speed(0); motor::setswitch(2, false); motor::setswitch(3, false); watchdog::reboot(); } // m-codes, for easy compatibility with openpnp.org // print sensor s pressure in hPa as m-code response void m_pressure(int m, int s, bool relative) { int32_t p; sensor::readSensors(); p = sensor::ipressure[s]; // pressure in Pa if (relative) { // vacuum can be negative due to small measurement errors, // or if the sensor for measuring atmospheric pressure is missing. p = sensor::ipressure[0] - p; // relative vacuum } p = p / 100; // convert from Pa to hPa Serial.print("[read:"); Serial.print(p); Serial.println(']'); } // parse m-code // m-code format: M8 sensor_number action // where: // sensor_number 0=air, 1=pump, 2=nozzle1, 3=nozzle2 // action 0=off, 1=on, 2=read absolute pressure in hPa, 3=read vacuum in hPa // M115 is used by OpenPnP for detecting the vacuum pump controller void m_code(int m) { switch (m) { case 115: // M115 detect firmware Serial.println("FIRMWARE_NAME:vacuum pump SOURCE_CODE_URL: https://github.com/koendv/vacuum-pump-controller"); break; case 800: // M800, M801 no-op case 801: break; case 802: // M802 read absolute pressure sensor0 (air) m_pressure(m, 0, false); break; case 803: // M803 read vacuum sensor0 (air) - always 0 m_pressure(m, 0, true); break; case 810: // M810 switch vacuum pump off PIDctrl::manual(0); break; case 811: // M811 switch vacuum pump on PIDctrl::automatic(); break; case 812: // M812 read absolute pressure sensor1 (pump) m_pressure(m, 1, false); break; case 813: // M813 read vacuum sensor1 (pump) m_pressure(m, 1, true); break; case 820: // M820 switch nozzle 1 vacuum solenoid off motor::setswitch(2, false); break; case 821: // M821 switch nozzle 1 vacuum solenoid on motor::setswitch(2, true); break; case 822: // M822 read absolute pressure sensor2 (nozzle1) m_pressure(m, 2, false); break; case 823: // M823 read vacuum sensor2 (nozzle1) m_pressure(m, 2, true); break; case 830: // M830 switch nozzle 2 vacuum solenoid off motor::setswitch(3, false); break; case 831: // M831 switch nozzle 2 vacuum solenoid on motor::setswitch(3, true); break; case 832: // M832 read absolute pressure sensor3 (nozzle2) m_pressure(m, 3, false); break; case 833: // M833 read vacuum sensor3 (nozzle2) m_pressure(m, 3, true); break; default: Serial.print("echo:unknown command \""); Serial.print(cmdline); Serial.println('"'); ok = ERR_SYNTAX; break; } return; } void printHelp() { Serial.println("commands, ## = int, #.## = float:"); Serial.println("? print status"); Serial.println("s#.## setpoint"); Serial.println("p#.## proportional gain"); Serial.println("i#.## integral gain"); Serial.println("d#.## derivative gain"); Serial.println("o#.## manual mode"); Serial.println("a autotune"); Serial.println("l## logging on/off"); Serial.println("m## m-code"); Serial.println("v## valve on/off"); Serial.println("w write settings"); Serial.println("r reset"); Serial.println("f firmware"); Serial.println("h help"); } void printStatus() { Serial.print("vacuum hPa: "); Serial.print(sensor::vacuum); Serial.print(" motor: "); Serial.print(motor::pwma_percent); Serial.print("% mode: "); if (PIDctrl::isAuto()) Serial.println("auto"); else Serial.println("manual"); Serial.print("setpoint hPa: "); Serial.print(settings::setpoint); Serial.print(" Kp: "); Serial.print(settings::Kp); Serial.print(" Ki: "); Serial.print(settings::Ki); Serial.print(" Kd: "); Serial.print(settings::Kd); Serial.print(" logging: "); Serial.println(settings::logging); Serial.print("pressure hPa: "); for (int i = 0; i < NUM_SENSOR; i++) { Serial.print(sensor::fpressure[i]); Serial.print(' '); } Serial.println(); sensor::printSensors(); } // print useful firmware info void printFirmware() { Serial.println("compiled " __DATE__); // print firmware version. helpful for support. uptime::print(); // print system uptime Serial.print(bytes_free()); // print free ram. helpful for detecting memory leaks. Serial.println(" bytes free"); Serial.print(loopstats::slowest_loop()); // time of slowest loop(), in ms Serial.println(" ms slowest loop"); } void setValve(int i) { switch (i) { case 00: motor::setswitch(2, false); // v00: TB6612 pin B01 off break; case 01: motor::setswitch(2, true); // v01: TB6612 pin B01 on break; case 10: motor::setswitch(3, false); // v10: TB6612 pin B02 off break; case 11: motor::setswitch(3, true); // v11: TB6612 pin B02 on break; default: ok = ERR_VALUE; break; } } /* * Execute command. Commands are a single character, * optionally followed by a float or an int. */ void doCommand() { double fval = 0; int ival = 0; ok = ERR_OK; cmdline.trim(); // check numeric argument if (cmdline.length() >= 2) { if (isDigit(cmdline[1])) { fval = cmdline.substring(1).toDouble(); ival = cmdline.substring(1).toInt(); } else cmdline[0] = ':'; // cause syntax error } // execute command if (echo_on) Serial.println(); if (cmdline.length() != 0) { switch (cmdline[0]) { case 'p': // set proportional gain settings::Kp = fval; PIDctrl::reload(); break; case 'i': // set integral gain settings::Ki = fval; PIDctrl::reload(); break; case 'd': // set derivative gain settings::Kd = fval; PIDctrl::reload(); break; case 's': // set setpoint settings::setpoint = fval; PIDctrl::reload(); break; case 'o': // output manual mode if (cmdline.length() == 1) PIDctrl::automatic(); else if ((fval >= 0) && (fval <= 100)) PIDctrl::manual(fval / 100.0 * MAXPWM); else ok = ERR_VALUE; break; case 'a': // tune autotune::tune(); loopstats::slowest_loop(); // reset cpu stats break; case 'l': // console pressure logging on/off settings::logging = (ival != 0); break; case 'v': // switch output pin on/off setValve(ival); break; case 'm': // openpnp.org m-codes m_code(ival); break; case 'w': // write settings to non-volatile settings::write(); break; case 'r': // reset sensors and pid controller reset(); // does not return break; case '?': // print all variables and settings printStatus(); break; case 'f': printFirmware(); break; case 'h': // help printHelp(); break; default: ok = ERR_SYNTAX; break; } } if (ok == ERR_SYNTAX) { Serial.println("what?"); } else if (ok == ERR_VALUE) { Serial.println("how?"); } cmdline = ""; Serial.println("ok"); if (echo_on) Serial.print(">"); return; } void setup() { cmdline.reserve(MAXCMDLEN); Serial.begin(115200); // wait up to 1 second for usb serial to connect for (int i = 0; i < 100; i++) if (Serial) break; else delay(10); Serial.println(); Serial.println("vacuum pump - type h for help"); } void loop() { while (Serial.available()) { char ch = Serial.read(); if (isUpperCase(ch)) ch = ch - 'A' + 'a'; switch (ch) { case '\b': if (cmdline.length() > 0) { cmdline.remove(cmdline.length() - 1); if (echo_on) Serial.print("\b \b"); } break; case '\r': case '\n': doCommand(); break; default: if (cmdline.length() != MAXCMDLEN) cmdline += ch; if (ch == 'm') echo_on = false; // don't echo m-code else if (!isDigit(ch)) echo_on = true; // echo interactive command if (echo_on) Serial.print(ch); break; } } } } // namespace console // not truncated
true
c702c2ad731a2f6fc4ed552b382fe19fe16cd700
C++
felax/INF1010_TD2
/Client.cpp
UTF-8
4,915
2.984375
3
[]
no_license
/******************************************** * Titre: Travail pratique #2 - Client.cpp * Date: 25 janvier 2018 * Auteur: Mohammed Esseddik BENYAHIA & Timothée CHAUVIN * Modifié par: Nezha Zahri(1786454) et Félix Montminy(1903263) * FICHIER: TP2 * DATE: 11/02/2018 * DESCRIPTION: Implémentation de la classe Client **************************************************/ #include "Client.h" /** * Constructeur par default * @param nom, prenom, identifiant, codePostal, date */ Client::Client(const string& nom, const string& prenom, int identifiant, const string& codePostal, long date) : nom_ { nom }, prenom_ { prenom }, identifiant_ { identifiant }, codePostal_ { codePostal }, dateNaissance_{ date }, monPanier_ { nullptr } { } /** * Destructeur par default * @param */ Client::~Client() { if (monPanier_ != nullptr) delete monPanier_; } /** * Constructeur de copie. Permet d'effectuer un "deep copy" * @param objetCopie Objet Client a copier */ Client::Client(const Client& objetCopie ) : nom_(objetCopie.nom_), prenom_(objetCopie.prenom_), identifiant_(objetCopie.identifiant_), codePostal_(objetCopie.codePostal_), dateNaissance_(objetCopie.dateNaissance_) ,monPanier_(nullptr) { this->monPanier_ = new Panier(*(objetCopie.monPanier_)); this->monPanier_->modifierTotalAPayer(objetCopie.monPanier_->obtenirTotalApayer()); } /** * Methode d'acces nom * @param */ string Client::obtenirNom() const { return nom_; } /** * Methode d'acces prenom * @param */ string Client::obtenirPrenom() const { return prenom_; } /** * Methode d'acces identifiant * @param */ int Client::obtenirIdentifiant() const { return identifiant_; } /** * Methode d'acces code postal * @param */ string Client::obtenirCodePostal() const { return codePostal_; } /** * Methode d'acces date de naissance * @param */ long Client::obtenirDateNaissance() const { return dateNaissance_; } /** * Methode d'acces panier * @param */ Panier * Client::obtenirPanier() const { return monPanier_; } /** * Methode de modification nom * @param nom Nom a modifier */ void Client::modifierNom(const string& nom) { nom_ = nom; } /** * Methode de modification prenom * @param prenom Prenom a modifier */ void Client::modifierPrenom(const string& prenom) { prenom_ = prenom; } /** * Methode de modification ientifiant * @param identifiant Identifiant a modifier */ void Client::modifierIdentifiant(int identifiant) { identifiant_ = identifiant; } /** * Methode de modification code postal * @param codePostal Code postal a modifier */ void Client::modifierCodePostal(const string& codePostal) { codePostal_ = codePostal; } /** * Methode de modification date de naissance * @param date Date a modifier */ void Client::modifierDateNaissance(long date) { dateNaissance_ = date; } /** * Ajoute un produit au panier du client * @param *produit Pointeur vers le produit a jouter */ void Client::acheter(Produit * produit) { if (monPanier_ == nullptr) { monPanier_ = new Panier(); } *monPanier_ += produit; } /** * Appelle la fonction livrer de la classe panier et enleve le panier du client * @param */ void Client::livrerPanier() { monPanier_->livrer(); delete monPanier_; monPanier_ = nullptr; } /** * Affiche le client et le contenu de son panier * @param os, client ostream& et le Client a afficher */ ostream& operator<< (ostream& os, const Client& client) { if (client.monPanier_ != nullptr) { cout << "Le panier de " << client.prenom_ << ": " << endl; cout << *client.monPanier_; } else { cout << "Le panier de " << client.prenom_ << " est vide !" << endl; } return os; } /** * Remplace les attributs de l'objet par ceux du Client en argument * @param client Le Client dont les attribus vont etre copies */ Client Client::operator= (Client& client) { this->nom_ = client.obtenirNom(); this->prenom_ = client.obtenirPrenom(); this->identifiant_ = client.obtenirIdentifiant(); this->codePostal_ = client.obtenirCodePostal(); this->dateNaissance_ = client.obtenirDateNaissance(); this->monPanier_ = client.obtenirPanier(); return client; } /** * Compare l'identifant du Client avec celui en parametre * @param id Indentifiant a comparer */ bool Client::operator== (const int id) const { bool match = false; if (this->obtenirIdentifiant() == id) { match = true; } return match; } /** * Compare l'identifant du Client avec celui en parametre (autre sens) * @param id, client Indentifiant a comparer et Client avec lequel le comparer */ bool operator== (const int id, const Client& client) { bool match = false; if (client.obtenirIdentifiant() == id) { match = true; } return match; }
true
39c6b480717682dfe2cb38bbda010099dd7ee4e4
C++
salmanshaikh733/Debian-File-Manager
/mydiff.cpp
UTF-8
1,003
2.875
3
[]
no_license
// // Created by salman on 2019-10-03. // // // Created by salman on 2019-10-03. // #include<iostream> #include<grp.h> #include<vector> #include<pwd.h> #include<unistd.h> #include<time.h> #include <fstream> #include "FileManager.h" int main(int argc, char *argv[]) { if(argc==3){ //get the input std::string name1=argv[1]; std::string name2=argv[1]; //create the files FileManager file1=FileManager(name1); FileManager file2=FileManager(name2); //check to see if right type int output; if(file1.getType()=="regular file"&&file2.getType()=="regular file"){ //compare files output=file1.compareFile(file2); } else { std::cout<<"invliad file input"; } //if 0 same file if not different files if(output==0){ std::cout<<"Same files"; } else { std::cout<<"Files not the same"; } } return 0; }
true
61c8cce4a0a13feac5757a080bc1fb258411e42c
C++
yoonho0922/Algorithm
/boj/C++/baek2588.cpp
UTF-8
195
2.578125
3
[]
no_license
#include<iostream> #include<vector> using namespace std; int main(){ int A,B; cin>>A>>B; cout<<A*(B%10)<<'\n'; cout<<A*(B/10%10)<<'\n'; cout<<A*(B/100)<<'\n'; cout<<A*B; return 0; }
true
5a53126495624ce777ee1b6e63ea30f3ed677ae3
C++
Mayureshdindorkar/Engg-SY-DSA-Assignments
/4_stringoprations.cpp
UTF-8
4,829
3.5
4
[]
no_license
#include<iostream> using namespace std; class str { private:char s1[50],s2[50],s3[50]; public:int i,j,k,h,q; void strlen(char *s1) { for(i=0;s1[i]!='\0';i++); cout<<" Length of string is :"<<i; } void strconcat(char *s1,char *s2) { for(i=0;s1[i]!='\0';i++) { s3[i]=s1[i]; } int k=i; //i value has came out incremented by one. for(h=0;s2[h]!='\0';h++) { s3[k]=s2[h]; k++; } s3[k]='\0'; cout<<"\nConcatinated string is :"<<s3; } void strcopy(char *s1,char *s2) { for(i=0;s2[i]!='\0';i++) { s1[i]=s2[i]; }s1[i]='\0'; cout<<"\nCopied string is :"<<s1; } void strrev(char *s1) { int j,k; char temp; i=0; //pointing to first index. for(j=0;s1[j]!='\0';j++); //making j=strlen(s1); k=j-1; //IMPORTANT pointing to last index of array except '\0'. while(i<k) //IMPORTANT. { temp=s1[i]; s1[i]=s1[k]; s1[k]=temp; i++,k--; } cout<<"\nReversed string is :"<<s1; } void strcom(char *s1,char *s2) { int flag,l1,l2; for(l1=0;s1[l1]!='\0';l1++); for(l2=0;s2[l2]!='\0';l2++); if(l1==l2) { for(q=0;q<l1;q++) { flag=1; if(s1[q]!=s2[q]) { flag=0; break; } } if(flag==1) { cout<<" \nStrings are equal."<<endl; cout<<" Boolean value is 1"<<endl; } else { cout<<" \n Strings are not equal."<<endl; cout<<" Boolean value is 0"<<endl; } } else { cout<<" Strings are not equal.\n"; cout<<" Boolean value is 0"<<endl; } } void freq(char *s1) { int counter,i,flag=0; char j; for(j='a';j<='z';j++) { counter=0; for(i=0;s1[i]!='\0';i++) { if(s1[i]==j) { counter++; flag=1; } } if(flag==1) { cout<<j<<" character occurs "<<counter<<" times in given string."<<endl; flag=0; } } } void substring(char *s1,char *s2) { int l; //length of string2 for(l=0;s2[l]!='\0';l++); //length of smaller string. for(i=0,j=0;s1[i]!='\0' && s2[j]!='\0';i++) { if(s1[i]==s2[j]) { j++; } else { j=0; } } if(j==l) //important. { cout<<"\nSubstring is found. "; } else { cout<<"\nNo Substring is found. "; } } }; int main() { str st1; char z; int ch; char s1[50],s2[50],s3[50]; cout<<"\n*****STRING OPERATIONS*****\n"; do { cout<<" Enter \n1.String length \n2.string copy \n3.string concatination \n4.string reverse \n5.string comparison \n6.Frequency count \n7.For Substring"<<endl; cin>>ch; switch(ch) { case 1:cout<<" Enter the string "; cin>>s1; st1.strlen(s1); break; case 2:cout<<" Enter first string \n"; cin>>s1; cout<<" Enter second string \n"; cin>>s2; st1.strcopy(s1,s2); break; case 3:cout<<" Enter first string \n"; cin>>s1; cout<<" Enter second string \n"; cin>>s2; st1.strconcat(s1,s2); break; case 4:cout<<" Enter the string \n"; cin>>s1; st1.strrev(s1); break; case 5: cout<<" Enter first string \n"; cin>>s1; cout<<" Enter second string \n"; cin>>s2; st1.strcom(s1,s2); break; case 6: cout<<" Enter the string whose frequency count you want to calculate in small letters only"<<endl; cin>>s1; st1.freq(s1); break; case 7: cout<<" Enter bigger string \n"; cin>>s1; cout<<" Enter smaller string \n"; cin>>s2; st1.substring(s1,s2); break; default:cout<<"!!!!SORRY!!!!"; break; }cout<<" \nEnter y if you want to do another operation else n "<<endl; cin>>z; }while(z=='y'||z=='Y'); }
true
b28aeb23eeab8ef341ec2a7d1f7a2e102114c69d
C++
leinok/Eigen_related
/test_eigen.cpp
UTF-8
1,716
2.59375
3
[]
no_license
#include <iostream> #include <typeinfo> #include <string> #include "softmax_layer.hpp" #include "fully_connected_layer.hpp" #include "activation_layer.hpp" int main() { int batch_size{4}, input_size{3}, output_size{2}; Eigen::MatrixXf inputs(batch_size, input_size); inputs << 1, -2, 3, 4, -5, 6, 7, -8, -9, 10, 11, -12; Eigen::MatrixXf weights(input_size, output_size); weights << .55, -.88, .75, -1.1, -0.11, 0.002; Eigen::VectorXf bias(output_size); bias << 3, -2; Eigen::VectorXf label(batch_size); label << 1, 0, 1, 1; saicdl::FullyConnectedLayer fcl; saicdl::ActivationLayer al; saicdl::SoftmaxLayer sl; Eigen::MatrixXf fc_outputs; fcl.forward(inputs, weights, bias, fc_outputs); Eigen::MatrixXf relu_outputs; al.sigmoidForward(fc_outputs, relu_outputs); Eigen::MatrixXf d_inputs, d_fc_weights, d_relu_outputs, d_fc_outputs; float loss; sl.softmaxLossForwardBackward(relu_outputs, label, d_relu_outputs, loss); std::cout << "Loss is: " << loss << '\n'; al.sigmoidBackward(relu_outputs, d_relu_outputs, d_fc_outputs); Eigen::VectorXf d_fc_bias; fcl.backward(inputs, weights, bias, d_fc_outputs, d_inputs, d_fc_weights, d_fc_bias); std::cout << "relu_outputs: " << relu_outputs << '\n'; std::cout << "d_relu_outputs: " << d_relu_outputs << '\n'; std::cout << "d_inputs: " << d_inputs << '\n'; std::cout << "d_fc_weights: " << d_fc_weights << '\n'; std::cout << "d_fc_bias: " << d_fc_bias << '\n'; std::cout << "d_fc_outputs: " << d_fc_outputs << '\n'; }
true
5682f2619ebe355715f74e2f0e957c8acb994c51
C++
MijaelTola/icpc
/vjudge/cuadp/B.cpp
UTF-8
840
2.6875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); int t; cin >> t; while(t--) { int n; cin >> n; vector<int> a,b; for (int i = 0; i < n; ++i) { int x; cin >> x; if(x & 1) a.push_back(i); else b.push_back(i); } if(b.size()) { cout << b.size() << "\n"; for (int i = 0; i < (int)b.size(); ++i) cout << b[i] + 1<< " "; cout << "\n"; } else if(a.size() >= 2) { while(a.size() & 1) a.pop_back(); cout << a.size() << "\n"; for (int i = 0; i < (int)a.size(); ++i) cout << a[i] + 1 << " "; cout << "\n"; } else cout << "-1\n"; } return 0; }
true
29854e3b4a11e920b69ec4ce4bf666a802edbf32
C++
dream365/Algorithm-Study
/DP/AS_NUMB3RS/main.cpp
UTF-8
2,079
2.78125
3
[]
no_license
#include <stdio.h> #include <vector> using namespace std; int main() { int c; scanf("%d", &c); for(int i = 0; i < c; i++) { int n, d, p, t; scanf("%d %d %d", &n, &d, &p); vector<vector<int>> A(n); vector<vector<double>> probs(d + 1); vector<vector<bool>> validVils(d + 1); for(int j = 0; j < n; j++) { vector<int> vils(n, 0); A[j] = vils; } for(int j = 0; j < d + 1; j++) { vector<double> prob(n, 0.); vector<bool> vaildVil(n, false); probs[j] = prob; validVils[j] = vaildVil; } validVils[0][p] = true; probs[0][p] = 1.0; for(int j = 0; j < n; j++) for(int k = 0; k < n; k++) { scanf("%d", &A[j][k]); } //Set probability for(int j = 1; j < d + 1; j++) { //get towns to go when day is j - 1 vector<bool> prevVaildVils = validVils[j - 1]; for(int vil = 0; vil < prevVaildVils.size(); vil++) { int validVilNum = 0; vector<int> vils; if(prevVaildVils[vil] == true) { for(int k = 0; k < n; k++) { // if(A[vil][k] == 1) { validVils[j][k] = true; validVilNum++; vils.push_back(k); } } for(int k = 0; k < vils.size(); k++) { probs[j][vils[k]] += 1.0 / (double) validVilNum * probs[j-1][vil]; } } } } //Print scanf("%d", &t); vector<int> vilNums; for(int j = 0; j < t; j++) { int vilNum; scanf("%d", &vilNum); vilNums.push_back(vilNum); } for(int j = 0; j < t; j++) { printf("%.8f ", probs[d][vilNums[j]]); } printf("\n"); } return 0; }
true
a8bc7738363d058d8dbe5e14e63cf677235c7ed9
C++
Xiao-Jian/ACM-Training
/TJU数学-1/G - 找新朋友.cpp
UTF-8
494
2.90625
3
[]
no_license
#include <cstdio> #include <iostream> #define Max 1000001 int euler[Max]; void Init(){ euler[1] = 1; for( int i = 2; i < Max; i ++ ) euler[i] = i; for( int i = 2; i < Max; i ++ ) if( euler[i] == i ) for( int j = i; j < Max; j += i ) euler[j] = euler[j] / i * ( i - 1 ); } int main() { int t,n; scanf( "%d", &t); Init(); while( t -- ) { scanf( "%d", &n ); printf( "%d\n", euler[n] ); } return 0; }
true
741f3dbd089df5baebbe34f139989dc89d37d1c9
C++
bestK1ngArthur/IU5
/Term 1/Basics of programming/Exam/Task13/Source13.cpp
UTF-8
865
3.484375
3
[ "MIT" ]
permissive
#include <iostream> using namespace std; int main() { int K; cout << "Task 13" << endl; cout << "Enter K: "; cin >> K; cout << "Enter array D: "; int *arrayD = new int[K]; int *arrayA = new int[K]; int *arrayB = new int[K]; int average = 0; for (int i = 0; i < K; i++) { cin >> arrayD[i]; average += arrayD[i]; } average /= K; int indexA = 0, indexB = 0; for (int indexD = 0; indexD < K; indexD++) { if (arrayD[indexD] > average) { arrayA[indexA] = arrayD[indexD]; indexA++; } else { arrayB[indexB] = arrayD[indexD]; indexB++; } } cout << "Array A: ["; for (int i = 0; i < indexA; i++) { cout << arrayA[i] << ","; } cout << "\b" << "]" << endl; cout << "Array B: ["; for (int i = 0; i < indexB; i++) { cout << arrayB[i] << ","; } cout << "\b" << "]" << endl; system("pause"); return 0; }
true
3ef527b7a88c97292e56c9ab7cb98d25873c205a
C++
Siriayanur/DSA
/mediumAndHard/inorderIterative.cpp
UTF-8
513
3.109375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; struct Node { int data; Node *left; Node *right; }; vector<int> inOrder(Node *root) { //code here vector<int> result; stack<Node *> st; Node *temp = root; while (temp || !st.empty()) { while (temp != NULL) { st.push(temp); temp = temp->left; } temp = st.top(); st.pop(); result.push_back(temp->data); temp = temp->right; } return result; }
true
5f590ea229339f6c1de278bfbf5b69c921a917cd
C++
e-noyau/wordclock
/libraries/ClockHardware/src/LDRReader.cpp
UTF-8
658
2.828125
3
[ "MIT" ]
permissive
#include "Arduino.h" #include "LDRReader.h" #include "logging.h" LDRReader::LDRReader(int pinNumber, float reactionSpeed) : _pin(pinNumber), _reactionSpeed(reactionSpeed) { DCHECK(reactionSpeed <= 1.0, "Too much"); DCHECK(reactionSpeed > 0, "Not enough"); } void LDRReader::setup() { pinMode(_pin, INPUT); _currentLDR = analogRead(_pin); // Initial value. } void LDRReader::loop() { _currentLDR = analogRead(_pin) * _reactionSpeed + _currentLDR * (1 - _reactionSpeed); DCHECK(_currentLDR <= 4095.0, _currentLDR); DCHECK(_currentLDR >= 0.0, _currentLDR); } float LDRReader::reading() { return _currentLDR / 4095.0; }
true
0f2078d7f30ba826a52deba9df27ced2a3c391bb
C++
jabraham17/StackMachine
/src/memory.h
UTF-8
2,341
2.578125
3
[]
no_license
#ifndef __MEMORY_H__ #define __MEMORY_H__ #include <stdlib.h> #include <stdint.h> #include <map> #include "stringhelper.h" #include <exception> #include <vector> #include <sstream> #include <iomanip> #include <iostream> #if defined(__i386__) || defined(__x86_64__) #include <immintrin.h> #if defined(__AVX512F__) #define _USEAVX512 #endif #if defined(__AVX2__) #define _USEAVX2 #endif #if defined(__SSE2__) #define _USESSE2 #endif #endif typedef size_t ADDRESS; typedef int64_t WORD; typedef int64_t IMMEDIATE; typedef int64_t LABEL; typedef std::map<LABEL, ADDRESS> AddressMap; class MemoryError: public std::exception { public: std::string message; MemoryError(std::string msg) : message(msg) {} MemoryError() : message("Unknown") {} virtual const char* what() const throw() { //const ref trick to allow for copy so string isnt local stack memory const std::string& ret = getString(); return ret.c_str(); } friend std::ostream& operator<<(std::ostream& out, const MemoryError& me) { out << me.getString(); return out; } std::string getString() const { std::stringstream str; str << "Memory Error: " << this->message; return str.str(); } std::string getString() { return const_cast<const MemoryError*>(this)->getString(); } }; namespace MemoryParser { IMMEDIATE getImmediate(std::string); WORD getWord(std::string); extern std::vector<std::string> stringTable; LABEL getLabel(std::string); std::string getLabelName(LABEL); } class Memory { public: explicit Memory(size_t, ADDRESS, ADDRESS); ~Memory(); ADDRESS addData(WORD); ADDRESS addText(WORD); bool setData(ADDRESS, WORD); WORD getData(ADDRESS); WORD getText(ADDRESS); bool setData(LABEL, WORD); WORD getData(LABEL); WORD getText(LABEL); bool addLabel(LABEL, ADDRESS); bool addDataLabel(LABEL); bool addTextLabel(LABEL); ADDRESS getAddress(LABEL); std::string getDataString(); std::string getTextString(); std::string getMemString(); std::string getMemSectionString(size_t,size_t); private: size_t size; WORD* mem; ADDRESS data_start_addr; ADDRESS text_start_addr; ADDRESS data_offset_addr; ADDRESS text_offset_addr; size_t data_size; size_t text_size; AddressMap labels; bool inAddressMap(LABEL); }; #endif
true
4df8b589fd640e120d301558ede46b8b43f78023
C++
ningenMe/compro-library
/non-verified/Maximum_Segment_Sum.cpp
UTF-8
316
2.546875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; //Maximum Segment Sum O(N) template<class T> T Maximum_Segment_Sum(const vector<T> & ar, T inf) { T res = -inf, sum = 0; for (int i = 0; i < ar.size(); ++i) { sum = max(sum + ar[i], ar[i]); res = max(res, sum); } return res; } //verify
true
f00ccab6ca0bbcd7b2fc6c47ab802e3dd0d53e76
C++
KausBoss/Competitive-Codes
/LongestCommonSubSequence.cpp
UTF-8
857
2.703125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; #define ll long long string memo[200][200]; bool comp(string a, string b){ return a.length() < b.length(); } string LCS(int i, int j, string s1, string s2){ //base case if(i==s1.length() || j==s2.length()){ return ""; } //recusrive case if(!memo[i][j].empty()){ return memo[i][j]; } if(s1[i] == s2[j]){ memo[i][j]= s1[i] + LCS(i+1, j+1, s1, s2); return memo[i][j]; } else{ memo[i][j]= max(LCS(i+1, j, s1, s2), LCS(i, j+1, s1, s2), comp); return memo[i][j]; } } int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif string s1, s2; // getline(cin, s1); // getline(cin, s2); cin>>s1>>s2; cout<<LCS(0, 0, s1, s2); }
true
116c0afd46e052cf3ddc4b01355c2b13cc149abf
C++
EthanITA/GOP
/Utils/Colors.h
UTF-8
882
2.6875
3
[]
no_license
// // Created by Marco on 30/05/2018. // #ifndef GOP_COLORS_H #define GOP_COLORS_H #include <string> /* foreground background black 30 40 red 31 41 green 32 42 yellow 33 43 blue 34 44 magenta 35 45 cyan 36 46 white 37 47 */ // per usarlo fare cosi: /// cout << kRed << .... << kStop << ... struct Colors{ const std::string kRed = "\033[1;31m", kGreen = "\033[1;32m", kYellow = "\033[1;33m", kBlue = "\033[1;34m", kMagenta = "\033[1;35m", kCyan = "\033[1;36m", kWhite = "\033[1;37m", kStop ="\033[0m", kRedNoBold = "\033[0;31m", kGreenNoBold = "\033[0;32m", kYellowNoBold = "\033[0;33m", kBlueNoBold = "\033[0;34m", kMagentaNoBold = "\033[0;35m", kCyanNoBold = "\033[0;36m"; }; #endif //GOP_COLORS_H
true
9f1623959b0761b73cf8251c574372dcd462768a
C++
nichoal/apollo
/modules/e2e/online_system/px2_camera_image/src/Checks.hpp
UTF-8
2,341
2.546875
3
[ "Apache-2.0" ]
permissive
#ifndef SAMPLES_COMMON_CHECKS_HPP__ #define SAMPLES_COMMON_CHECKS_HPP__ #include <dw/gl/GL.h> #include <cuda_runtime.h> #include <iostream> #include <string> #include <stdexcept> //------------------------------------------------------------------------------ // Functions //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // print GL error with location inline void getGLError(int line, const char *file, const char *function) { GLenum error = glGetError(); if (error != GL_NO_ERROR) { std::cerr << file << " in function " << function << " in line " << line << ": glError: 0x" << std::hex << error << std::dec << std::endl; exit(1); } } #ifndef __PRETTY_FUNCTION__ #define __PRETTY_FUNCTION__ __FUNCTION__ #endif // macro to easily check for GL errors #define CHECK_GL_ERROR() getGLError(__LINE__, __FILE__, __PRETTY_FUNCTION__); //------------------------------------------------------------------------------ // macro to easily check for dw errors #define CHECK_DW_ERROR(x) { \ dwStatus result = x; \ if(result!=DW_SUCCESS) \ throw std::runtime_error(std::string("DW Error ") \ + dwGetStatusName(result) \ + std::string(" executing DW function:\n " #x) \ + std::string("\n at " __FILE__ ":") + std::to_string(__LINE__)); \ }; //------------------------------------------------------------------------------ // macro to easily check for cuda errors #define CHECK_CUDA_ERROR(x) { \ x; \ auto result = cudaGetLastError(); \ if(result != cudaSuccess) \ throw std::runtime_error(std::string("CUDA Error ") \ + cudaGetErrorString(result) \ + std::string(" executing CUDA function:\n " #x) \ + std::string("\n at " __FILE__ ":") + std::to_string(__LINE__)); \ }; #endif // SAMPLES_COMMON_CHECKS_HPP__
true
8334102dcc59a77a6f9978816855f8f9e22fee92
C++
Dlucky2212/Ejercicio-1
/main.cpp
UTF-8
221
3.09375
3
[]
no_license
#include <iostream> using namespace std; //1 Transformar de millas a kilometros float trans(int milla){ float kilo; kilo = milla * 1.60934; return kilo; } int main() { int a; cin >> a; cout << trans(a); }
true
1d3282f376a94a94862dabe12f1f31e151bada64
C++
ahmedamsoliman-1/NanoDegreeProgrammLessons
/2-ObjectOrientedProgramming-OOP/Lesson2-IntroTpOOP/Structs/AccessModifier.cpp
UTF-8
1,304
3.890625
4
[]
no_license
#include <cassert> #include <iostream> struct Date { public: //Date(){} Date(int a , int b , int c) { day = a; month = b; year = c; } private: int day{00}; int month{00}; int year{00}; public: //Accdssor - getter - get function - return a value int Day() { return day; } //Mutator - setter - set function - set value and return void void Day(int x) { if (x > 0 ) day = x; } //Getter and Setter for the month int GetMonth() { return month; } void SetMonth(int x) { month = x; } //Getter and Setter for the year int GetYear() { return year; } void SetYear(int x) { year = x; } }; int main() { Date date; date.Day(3); date.SetMonth(3); date.SetYear(1988); Date ahmed(2,3,1990); Date abbas(2,4,2010); // assert(date.Day() == 7); // assert(date.GetMonth() == 1); // assert(date.GetYear() == 2000); std::cout << date.Day() << "/" << date.GetMonth() << "/" << date.GetYear() << "\n"; std::cout << ahmed.Day() << "/" << ahmed.GetMonth() << "/" << ahmed.GetYear() << "\n"; std::cout << abbas.Day() << "/" << abbas.GetMonth() << "/" << abbas.GetYear() << "\n"; }
true
dd30bf8bf677fde0dc400883963419b2487193d3
C++
cpa750/TermTwo
/C++/Lab 7/b1.cpp
UTF-8
966
3.640625
4
[]
no_license
#include <iostream> #include <random> #include <ctime> int getUserGuess(); int main() { std::srand(std::time(NULL)); bool correct {false}; int guesses {0}; const int num {rand() % 10}; // Getting a random number from 0 to 10 // TODO: seed random number while ( (guesses < 3) && !correct ) { int guess {getUserGuess()}; if (guess == num) { std::cout << "Correct!" << std::endl; correct = true; } else if (guess < num) std::cout << "Too low" << std::endl; else if (guess > num) std::cout << "Too high" << std::endl; ++guesses; } return 0; } int getUserGuess() { int guess; std::cout << "Guess a number from 0 to 10: "; std::cin >> guess; while ( (guess < 1) || (guess > 10) ) { std::cout << "Please enter an integer from 0 to 10: "; std::cin >> guess; } return guess; }
true
1787656eef4f497bf01b840e3394b93e589bf1b2
C++
Sunil2120/Coding_questions
/DP/zero_square.cpp
UTF-8
1,082
3.015625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int solve(int** input,int row,int col) { int** output = new int*[row]; for(int i=0;i<row;i++) { output[i]=new int[col](); } // first col intialized for(int i=0;i<row;i++) { if(input[i][0] == 1) { output[i][0] = 0; } else if(input[i][0] == 0) { output[i][0] = 1; } } // first row intialized for(int i=0;i<col;i++) { if(input[0][i] == 1) { output[0][i] = 0; } else if(input[0][i] == 0) { output[0][i] = 1; } } int max_ = 1; for(int i=1;i<row;i++) { for(int j=1;j<col;j++) { if(input[i][j]==1) { output[i][j]=0; } else { output[i][j] = min(output[i-1][j-1],min(output[i][j-1],output[i-1][j])) + 1; if(output[i][j] > max_) { max_ = output[i][j]; } } } } delete[] output; return max_; } int main() { int m,n; cin >> m >> n; int** input = new int*[m];// rows for(int i=0;i<m;i++) { input[i]=new int[n]; for(int j=0;j<n;j++) { cin >> input[i][j]; } } cout << solve(input,m,n) << endl; delete[] input; return 0; }
true
95042c28d819fd16553b245fc851121b537ccb8e
C++
PolCorTs/NULL_Engine
/NULL Engine/Source/PathNode.cpp
UTF-8
530
2.578125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// ---------------------------------------------------- // Struct abstraction to deal with files and folders. // Employed by M_FileSystem. // ---------------------------------------------------- #include "VariableTypedefs.h" #include "PathNode.h" PathNode::PathNode() : path("") { } bool PathNode::IsLastFolder() const { for (uint i = 0; i < children.size(); ++i) { if (!children[i].isFile) { return false; } } return true; } bool PathNode::operator ==(const PathNode node) const { return path == node.path; }
true
c2277fa62ad17a3216411df33c3bb30eeb82b508
C++
MechyX/EscapeEnemy
/button.cpp
UTF-8
1,099
3.09375
3
[]
no_license
#include "button.h" Button :: Button(std::string text, sf::Vector2f pos , sf::Vector2f size , sf::Font font){ textFont = font; graphicText.setFont(textFont); graphicText.setString(text); graphicText.setCharacterSize(50); graphicText.setStyle(sf::Text::Bold); graphicButton.setPosition(pos); graphicButton.setSize(size); float xPos = (pos.x + size.x / 2) - (graphicText.getLocalBounds().width / 2); float yPos = (pos.y + size.y / 2) - (graphicText.getLocalBounds().height / 2); graphicText.setPosition(xPos, yPos); } sf::RectangleShape& Button :: returnButton(){ return graphicButton; } bool Button :: isClicked(sf::Vector2f point){ return graphicButton.getGlobalBounds().contains(point); } void Button :: setBackgroundColor(sf::Color buttonColor){ graphicButton.setFillColor(buttonColor); } void Button :: drawButton(sf::RenderWindow& window){ window.draw(graphicButton); window.draw(graphicText); } void Button :: setTextColor(sf::Color textColor){ graphicText.setFillColor(textColor); }
true
1a11015739113f924da791dd7f321e9378930ef0
C++
alfredchavez/IPOO
/practica2/p5/5.cpp
UTF-8
333
2.84375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; vector<string>vec; void leer(){ ifstream archivo("doc1.txt"); string s; while(!archivo.eof()){ getline(archivo,s); vec.push_back(s); } archivo.close(); } int main(){ leer(); for(int i=0;i<vec.size();i++){ cout<<vec[i]<<endl; } return 0; }
true
0563430714e2144d5f61f21817600ba81b0bae67
C++
martinmoene/martin-moene.blogspot.com
/How to fix VC6 template with overload/template-and-override-free.cpp
UTF-8
605
2.765625
3
[]
no_license
#include <iostream> //namespace vc6_detail { template <typename T> T foo( T t ) { return t; } //} // namespace a // //using namespace vc6_detail; struct S {}; struct Q {}; Q foo( S s ) { return Q(); } std::ostream & operator<<( std::ostream & os, Q const & ) { return os << "struct Q"; } int main() { std::cout << "foo( 2 ): " << foo( 2 ) << std::endl << "foo( 3.14 ): " << foo( 3.14 ) << std::endl << "foo( S() ): " << foo( S() ) << std::endl; return 0; } // cl -nologo -EHsc template-and-override-free.cpp && template-and-override-free
true
0686bddc80f92625ab8662d73e7526739c19e67e
C++
amith1893/parallel-iterative-solver
/poisson.cc
UTF-8
5,528
2.5625
3
[]
no_license
#include "poisson.h" #include <iostream> #include <cmath> #include <cassert> #include <sys/time.h> void get_rank_and_size(const MPI_Comm &comm, int &n, int &r) { MPI_Comm_size(comm, &n); MPI_Comm_rank(comm, &r); } void get_my_coord_bounds(const MPI_Comm &grid_comm, int r, int n, int coord_starts[], int coord_ends[]) { int coords[DIM] = {0}; int dims[DIM] = {0}; int trash[DIM] = {0}; MPI_Cart_get(grid_comm, DIM, dims, trash, coords); MPI_Cart_coords(grid_comm, r, DIM, coords); for (int i=0; i<DIM; i++) { coord_starts[i] = n*coords[i]/dims[i]; coord_ends[i] = n*(1+coords[i])/dims[i]; } } void poisson_setup(MPI_Comm &comm, int n, MPI_Comm &grid_comm, std::vector<point_t> &x) { int dims[DIM] = {0}; int periods[DIM] = {0}; int n_p; int r; get_rank_and_size(comm, n_p, r); MPI_Dims_create(n_p, DIM, dims); MPI_Cart_create(comm, DIM, dims, periods, 0, &grid_comm); int coord_starts[DIM]; int coord_ends[DIM]; get_my_coord_bounds(grid_comm, r, n, coord_starts, coord_ends); point_t next_pt; x.clear(); for (int i=coord_starts[0]; i<coord_ends[0]; i++) { for (int j=coord_starts[1]; j<coord_ends[1]; j++) { for (int k=coord_starts[2]; k<coord_ends[2]; k++) { next_pt.x = static_cast<real_t>(i)/(n-1); next_pt.y = static_cast<real_t>(j)/(n-1); next_pt.z = static_cast<real_t>(k)/(n-1); x.push_back(next_pt); } } } } //void poisson_residual(MPI_Comm &grid_comm, int n, std::vector<real_t> &a, //std::vector<real_t> &f, std::vector<real_t> &v, real_t &res) void laplacian(const MPI_Comm &grid_comm, int n, const std::vector<real_t> &a, const std::vector<real_t> &u, std::vector<real_t> &lu) { std::vector<real_t> r_h(u.size(), 0); std::vector<real_t> send_buffers[DIM][2]; std::vector<real_t> recv_buffers[DIM][2]; int neighbors[DIM][2]; int coord_starts[DIM]; int coord_ends[DIM]; int r; int n_p; get_rank_and_size(grid_comm, n_p, r); get_my_coord_bounds(grid_comm, r, n, coord_starts, coord_ends); int mi = coord_ends[0] - coord_starts[0]; int mj = coord_ends[1] - coord_starts[1]; int mk = coord_ends[2] - coord_starts[2]; assert(mi*mj*mk == u.size()); real_t h = 1.0/n; #if 0 for (int i=0; i<mi*mj*mk; i++) { //lu[i] = (a[i]*u[i] - r_h[i]); printf("u[i] %lf\n", u[i]); } printf("==============================================================================================\n"); #endif // neighbor[0][0] has coords < coord_starts[0] (i) // neighbor[0][1] has coords > coord_ends[0] // neighbor[1][0] has coords < coord_starts[1] (j) // neighbor[1][1] has coords > coord_ends[1] // neighbor[2][0] has coords < coord_starts[2] (k) // neighbor[2][1] has coords > coord_ends[2] for (int i=0; i<DIM; i++) { MPI_Cart_shift(grid_comm, i, 1, &(neighbors[i][0]), &(neighbors[i][1])); } for (int i=0; i<mi; i++) { for (int j=0; j<mj; j++) { send_buffers[2][0].push_back(u[ i*mj*mk + j*mk + 0]); send_buffers[2][1].push_back(u[ i*mj*mk + j*mk + (mk-1)]); } } for (int i=0; i<mi; i++) { for (int k=0; k<mk; k++) { send_buffers[1][0].push_back(u[ i*mj*mk + 0*mk + k]); send_buffers[1][1].push_back(u[ i*mj*mk + (mj-1)*mk + k]); } } for (int j=0; j<mj; j++) { for (int k=0; k<mk; k++) { send_buffers[0][0].push_back(u[ 0*mj*mk + j*mk + k]); send_buffers[0][1].push_back(u[(mi-1)*mj*mk + j*mk + k]); } } MPI_Request is_req[6]; MPI_Request ir_req[6]; for (int dim=0; dim<DIM; dim++) { for (int dir=0; dir<2; dir++) { size_t s = send_buffers[dim][dir].size(); recv_buffers[dim][dir].assign(s, 0); MPI_Isend(send_buffers[dim][dir].data(), s, MPI_DOUBLE, neighbors[dim][dir], 0, grid_comm, &(is_req[2*dim+dir])); MPI_Irecv(recv_buffers[dim][dir].data(), s, MPI_DOUBLE, neighbors[dim][dir], 0, grid_comm, &(ir_req[2*dim+dir])); } } for (int i=0; i<mi; i++) { for (int j=0; j<mj; j++) { for (int k=0; k<mk; k++) { r_h[i*mj*mk + j*mk + k] = -6*u[i*mj*mk + j*mk + k]; if (i>0) { r_h[i*mj*mk + j*mk + k] += u[(i-1)*mj*mk + j*mk + k]; } if (i<mi-1) { r_h[i*mj*mk + j*mk + k] += u[(i+1)*mj*mk + j*mk + k]; } if (j>0) { r_h[i*mj*mk + j*mk + k] += u[i*mj*mk + (j-1)*mk + k]; } if (j<mj-1) { r_h[i*mj*mk + j*mk + k] += u[i*mj*mk + (j+1)*mk + k]; } if (k>0) { r_h[i*mj*mk + j*mk + k] += u[i*mj*mk + j*mk + (k-1)]; } if (k<mj-1) { r_h[i*mj*mk + j*mk + k] += u[i*mj*mk + j*mk + (k+1)]; } } } } MPI_Status ir_stat[6]; MPI_Waitall(6, ir_req, ir_stat); for (int i=0; i<mi; i++) { for (int j=0; j<mj; j++) { r_h[i*mj*mk + j*mk + 0] += recv_buffers[2][0][i*mj+j]; r_h[i*mj*mk + j*mk + (mk-1)] += recv_buffers[2][1][i*mj+j]; } } for (int i=0; i<mi; i++) { for (int k=0; k<mk; k++) { r_h[i*mj*mk + 0*mk + k] += recv_buffers[1][0][i*mk+k]; r_h[i*mj*mk + (mj-1)*mk + k] += recv_buffers[1][1][i*mk+k]; } } for (int j=0; j<mj; j++) { for (int k=0; k<mk; k++) { r_h[0*mj*mk + j*mk + k] += recv_buffers[0][0][j*mk+k]; r_h[(mi-1)*mj*mk + j*mk + k] += recv_buffers[0][1][j*mk+k]; } } for (int i=0; i<mi*mj*mk; i++) { lu[i] = (a[i]*u[i] - r_h[i]); //printf("lu[i] %lf\n", lu[i]); } }
true
a8090ff8a24844618d6553dcb9dd9dc2ff3c5a66
C++
intel/MLSL
/src/pointer_checker.cpp
UTF-8
3,291
2.703125
3
[ "Intel", "Apache-2.0" ]
permissive
/* Copyright 2016-2018 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "log.hpp" #include "mlsl.hpp" #include "pointer_checker.hpp" namespace MLSL { PointerChecker::PointerChecker() {} PointerChecker::~PointerChecker() { MLSL_ASSERT(bufList.empty(), "all buffers should be freed explicitly"); } void PointerChecker::Add(void* ptr, size_t size) { MLSL_LOG(DEBUG, "ptr %p, size %zu", ptr, size); MLSL_ASSERT(CheckInternal(ptr, size) == PCRT_UNKNOWN_PTR, "this pointer already allocated (ptr %p, sz %zu)", ptr, size); BufInfo bufInfo; bufInfo.start = (char*)ptr; bufInfo.stop = (char*)ptr + size; bufInfo.size = size; bufList.push_back(bufInfo); } void PointerChecker::Remove(void* ptr) { MLSL_LOG(DEBUG, "ptr %p", ptr); MLSL_ASSERT(!bufList.empty(), "attempt to remove pointer (%p) from empty list", ptr); list<BufInfo>::iterator it = bufList.begin(); for (; it != bufList.end(); it++) { if ((*it).start == (char*)ptr) break; } MLSL_ASSERT(it != bufList.end(), "unknown pointer"); bufList.erase(it); } PointerCheckerResultType PointerChecker::CheckInternal(void* ptr, size_t size) { MLSL_LOG(DEBUG, "ptr %p, size %zu", ptr, size); PointerCheckerResultType res = PCRT_NONE; list<BufInfo>::iterator it = bufList.begin(); for(; it != bufList.end(); it++) { if ((*it).start <= (char*)ptr && (*it).stop >= (char*)ptr) { if ((*it).stop >= (char*)ptr + size) res = PCRT_NONE; else { size_t beyondBoundary = (size_t)(((char*)ptr + size) - (*it).stop); MLSL_LOG(INFO, "ptr %p is %zu bytes beyond the array boundary %p", ((char*)ptr + size), beyondBoundary, (*it).stop); res = PCRT_OUT_OF_RANGE; } break; } } if (it == bufList.end()) res = PCRT_UNKNOWN_PTR; return res; } void PointerChecker::Check(void* ptr, size_t size) { MLSL_LOG(DEBUG, "ptr %p, size %zu", ptr, size); Print(CheckInternal(ptr, size)); } void PointerChecker::Print(PointerCheckerResultType result) { switch (result) { case PCRT_NONE: break; case PCRT_UNKNOWN_PTR: MLSL_LOG(DEBUG, "unknown ptr"); break; case PCRT_OUT_OF_RANGE: MLSL_ASSERT(0, "out of range"); break; default: MLSL_ASSERT(0, "unknown result (%d)", result); } } }
true
9f68d923b43a4b72e5a151545dc0679d82ff8f5a
C++
Pr0gramWizard/Escape-TheGame-
/Escape/bloom/preBloomFBO.cpp
UTF-8
2,133
2.796875
3
[]
no_license
#include "preBloomFBO.hpp" PreBloomFBO::PreBloomFBO(GLuint pWidth, GLuint pHeight) { this->init(pWidth, pHeight); } PreBloomFBO::~PreBloomFBO() { } void PreBloomFBO::unbind() { glBindFramebuffer(GL_FRAMEBUFFER, 0); } void PreBloomFBO::bind() { glBindFramebuffer(GL_FRAMEBUFFER, mFBO); } GLuint PreBloomFBO::getColorBuffer(GLboolean pIndex) { return mColorbuffers[pIndex]; } void PreBloomFBO::init(GLuint pWidth, GLuint pHeight) { // Set up floating point framebuffer to render scene to glGenFramebuffers(1, &mFBO); glBindFramebuffer(GL_FRAMEBUFFER, mFBO); // - Create 2 floating point color buffers (1 for normal rendering, other for brightness treshold values) glGenTextures(2, mColorbuffers); for (GLuint i = 0; i < 2; i++) { glBindTexture(GL_TEXTURE_2D, mColorbuffers[i]); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, pWidth, pHeight, 0, GL_RGB, GL_FLOAT, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); // We clamp to the edge as the blur filter would otherwise sample repeated texture values! glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); // attach texture to framebuffer glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, mColorbuffers[i], 0); } // - Create and attach depth buffer (renderbuffer) GLuint rboDepth; glGenRenderbuffers(1, &rboDepth); glBindRenderbuffer(GL_RENDERBUFFER, rboDepth); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, pWidth, pHeight); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rboDepth); // - Tell OpenGL which color attachments we'll use (of this framebuffer) for rendering GLuint attachments[2] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 }; glDrawBuffers(2, attachments); // - Finally check if framebuffer is complete if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) std::cout << "Framebuffer not complete!" << std::endl; glBindFramebuffer(GL_FRAMEBUFFER, 0); }
true
f847474cb7f35a7154bd42c799d1926d91cf307d
C++
hpsdy/c-plus
/6/625.cpp
UTF-8
318
2.859375
3
[]
no_license
#include<iostream> #include<typeinfo> using namespace std; int main(int argc,char * argv[]){ string str=""; while(true){ if(*argv!=0){ auto tmp = *argv++; cout<<"type:"<<typeid(tmp).name()<<endl; str += tmp; cout<<tmp<<endl; }else{ break; } } cout<<str<<endl; cout<<argc<<endl; return 0; }
true
f96108acd21a65dab097b3bb581841232e03b1f3
C++
abraxaslee/ACM-ICPC
/Fib.cpp
UTF-8
905
2.953125
3
[ "MIT" ]
permissive
#include <stdio.h> int Fib[5001][120] = {}; int top[5001] = {}; void BigAdd(int n){ int i; for(i=0 ;Fib[n-1][i] + Fib[n-2][i] > 0 ;++i){ Fib[n][i] += Fib[n-1][i] + Fib[n-2][i]; if(Fib[n][i] > 1000000000){ Fib[n][i+1] += Fib[n][i]/1000000000; Fib[n][i] %= 1000000000; } } while(Fib[n][i] > 0){ i++; } top[n] = i; return; } void buildTable(void){ for(int i=3;i<=5000;++i){ BigAdd(i); } return; } void getBigNum(int n){ printf("Fib[%d] = ", n-2); printf("%d", Fib[n][top[n]-1]); for(int i = top[n]-2; i>=0 ;--i){ printf("%09d", Fib[n][i]); } printf(";\n"); return; } int main(){ #ifndef ONLINE_JUDGE freopen("fib.out", "w", stdout); #endif Fib[0][0] = 0; top[0] = 1; Fib[1][0] = 1; top[1] = 1; Fib[2][0] = 1; top[2] = 1; buildTable(); int inputNum; for(int i=2;i<=60;++i) getBigNum(i); return 0; }
true
a0c00b18218f91af161121ffa8f8421d548c2aaf
C++
jamieyello/Input-Scripts
/ScriptExecutionExample/input_script.cpp
UTF-8
14,320
2.546875
3
[]
no_license
#pragma once #include "stdafx.h" #include "input_script.h" namespace InputScripts { InputScript::InputScript() { for (int i = 0; i < scope_limit; i++) { return_address[i] = 0; scope_instruction_type[i] = null_value; initial_function_reference[i] = 0; recursive_function_reference[i] = 0; } // Link input with math parser math_parser.AddExternalValue("pad.a", &result.A); math_parser.AddExternalValue("pad.b", &result.B); math_parser.AddExternalValue("pad.x", &result.X); math_parser.AddExternalValue("pad.y", &result.Y); math_parser.AddExternalValue("pad.up", &result.Up); math_parser.AddExternalValue("pad.down", &result.Down); math_parser.AddExternalValue("pad.left", &result.Left); math_parser.AddExternalValue("pad.right", &result.Right); math_parser.AddExternalValue("pad.r", &result.R); math_parser.AddExternalValue("pad.zr", &result.ZR); math_parser.AddExternalValue("pad.l", &result.L); math_parser.AddExternalValue("pad.zl", &result.ZL); math_parser.AddExternalValue("pad.start", &result.Start); math_parser.AddExternalValue("pad.select", &result.Select); math_parser.AddExternalValue("pad.home", &result.Home); math_parser.AddExternalValue("pad.leftStickX", &result.LeftStickX); math_parser.AddExternalValue("pad.leftStickY", &result.LeftStickY); math_parser.AddExternalValue("pad.rightStickX", &result.RightStickX); math_parser.AddExternalValue("pad.rightStickY", &result.RightStickY); math_parser.AddExternalValue("pad.touchDown", &result.TouchScreenDown); math_parser.AddExternalValue("pad.touchX", &result.TouchScreenX); math_parser.AddExternalValue("pad.touchY", &result.TouchScreenY); } InputScript::~InputScript() { } bool InputScript::LoadScript(std::string file_path) { std::string script = string_functions.LoadTextFromFile(file_path); ModifyScript(script); EvaluateScript(script); // Convert the text script into an array of instructions. SetInstructions(script); return true; } bool InputScript::ExecuteFrame(Input input) { result.SetInput(input); current_scope = 0; if (text_output_enabled) { text_output = ""; } int i = 0; while (i < instruction.size()) { i = ExecuteInstruction(instruction[i], i); } if (current_scope) { text_output += "Warning; scope was " + string_functions.numToString(current_scope) + " on exit.\n"; } return true; } // Execute single instruction. Address only relevent when used with looping commands. int InputScript::ExecuteInstruction(Instruction &inst, int address) { switch (inst.instruction_type) { case opening_bracket: if (skip_next_scope) { int needed_closing_brackets = 1; for (address++; (address < instruction.size()) && (needed_closing_brackets != 0); address++) { if (instruction[address].instruction_type == opening_bracket) { needed_closing_brackets++; }; if (instruction[address].instruction_type == closing_bracket) { needed_closing_brackets--; }; } skip_next_scope = false; return address; } else { return_address[current_scope] = address; current_scope++; } break; case closing_bracket: if (current_scope < 1) { cout << loaded_script << "\n" << GetInstructionDebug(instruction) << "on closing bracket at line " << address << " scope was " << current_scope << "\nProgram will now likely crash.\n"; system("PAUSE"); } switch (instruction[return_address[current_scope - 1] - 1].instruction_type) { case while_statement: if (math_parser.Solve(instruction[return_address[current_scope - 1] - 1].math_string[0]) > 0) { address = return_address[current_scope - 1]; } else { current_scope--; } break; case do_statement: if (instruction[address + 1].instruction_type == while_statement) { if (math_parser.Solve(instruction[address + 1].math_string[0]) > 0) { address = return_address[current_scope - 1]; } else { current_scope--; } } else { // Throw error here std::cout << "do matching while statement not found.\n"; current_scope--; } break; case for_loop: ExecuteInstruction(embedded_functions[instruction[return_address[current_scope - 1] - 1].embedded_function_reference[1]], 0); if (math_parser.Solve(instruction[return_address[current_scope - 1] - 1].math_string[0]) > 0) { address = return_address[current_scope - 1]; } else { current_scope--; } break; case if_statement: current_scope--; break; case else_statement: current_scope--; break; default: text_output += "Warning: an ending bracket had no type.\n"; current_scope--; break; } break; case set_value: math_parser.SetVariableValue(inst.value_to_modify[0], math_parser.Solve(inst.math_string[0])); break; case inc_value_by: math_parser.SetVariableValue(inst.value_to_modify[0], math_parser.GetVariableValue(inst.value_to_modify[0]) + math_parser.Solve(inst.math_string[0])); break; case dec_value_by: math_parser.SetVariableValue(inst.value_to_modify[0], math_parser.GetVariableValue(inst.value_to_modify[0]) - math_parser.Solve(inst.math_string[0])); break; case mul_value_by: math_parser.SetVariableValue(inst.value_to_modify[0], math_parser.GetVariableValue(inst.value_to_modify[0]) * math_parser.Solve(inst.math_string[0])); break; case div_value_by: math_parser.SetVariableValue(inst.value_to_modify[0], math_parser.GetVariableValue(inst.value_to_modify[0]) / math_parser.Solve(inst.math_string[0])); break; case inc_value: math_parser.SetVariableValue(inst.value_to_modify[0], math_parser.GetVariableValue(inst.value_to_modify[0]) + 1); break; case dec_value: math_parser.SetVariableValue(inst.value_to_modify[0], math_parser.GetVariableValue(inst.value_to_modify[0]) - 1); break; case for_loop: scope_instruction_type[current_scope] = for_loop; // Execute initial function ExecuteInstruction(embedded_functions[inst.embedded_function_reference[0]], 0); break; case if_statement: if (math_parser.Solve(inst.math_string[0])) { math_parser.ifResult = true; scope_instruction_type[current_scope] = if_statement; } else { math_parser.ifResult = false; skip_next_scope = true; } break; case else_statement: if (math_parser.ifResult) { skip_next_scope = true; } else { scope_instruction_type[current_scope] = else_statement; } break; case do_statement: scope_instruction_type[current_scope] = do_statement; break; case while_statement: if (math_parser.Solve(inst.math_string[0])) { scope_instruction_type[current_scope] = while_statement; } else { skip_next_scope = true; } break; case print_statement: if (text_output_enabled) { text_output += string_functions.numToString(math_parser.Solve(inst.math_string[0])) + "\n"; } break; case clear_statement: if (text_output_enabled) { text_output = ""; } break; default: break; } return address + 1; } // Gets the total number of commands in a given script int InputScript::EvaluateScript(std::string script) { int result = 0; int open_parenthesis_count = 0; // Counts the # of ;'s in the string, skips content in parenthesis (for statements) for (int i = 0; i < script.length(); i++) { if (script[i] == '(') { open_parenthesis_count++; } if (script[i] == ')') { open_parenthesis_count--; } if ((script[i] == ';') && (open_parenthesis_count == 0)) { result++; } if (open_parenthesis_count < 0) { /* Throw error here, "Invalid code, too many closing parenthesis at line ." + result */ } } if (open_parenthesis_count > 0) { /* Throw error here, "Invalid code, not enough closing parenthesis detected."*/ } return result; } // apply "cheats" to script for easier compilation void InputScript::ModifyScript(std::string &script) { string_functions.SearchAndReplace(script, "&&", "~A~"); string_functions.SearchAndReplace(script, "||", "~O~"); string_functions.SearchAndReplace(script, "^", "~X~"); string_functions.SearchAndReplace(script, "|", "~Q~"); string_functions.SearchAndReplace(script, "&", "~W~"); script = string_functions.RemoveSpaces(script); if (script == "") { return; } string_functions.SearchAndReplace(script, "==", "~E~"); string_functions.SearchAndReplace(script, "!=", "~D~"); string_functions.SearchAndReplace(script, ">=", "~S~"); string_functions.SearchAndReplace(script, "<=", "~M~"); string_functions.SearchAndReplace(script, ">", "~L~"); string_functions.SearchAndReplace(script, "<", "~P~"); string_functions.SearchAndReplace(script, "else{", "else;{"); string_functions.SearchAndReplace(script, "do{", "do;{"); // Add a semicolon after every bracket. } -> }; for (int i = 0; i < script.length(); i++) { if (script[i] == '{') { script.insert(i+ 1, ";"); } if (script[i] == '}') { script.insert(i + 1, ";"); } } // Add a semicolon after certain commands ("if() {}" -> if(); {}) ApplyParenthesisSemicolonCheat(script, "if"); ApplyParenthesisSemicolonCheat(script, "for"); ApplyParenthesisSemicolonCheat(script, "while"); loaded_script = script; } bool InputScript::SetInstructions(std::string script) { while (script != "") { instruction.push_back(GetInstructionFromLine(GetNextLineInScript(script))); } return true; } // This will take a single line of code and convert it into an instruction. Instruction InputScript::GetInstructionFromLine(std::string line) { Instruction result; std::string word = string_functions.GetWord(line, 0, true); std::string c_word = string_functions.Capitalize(word); //std::cout << "line - " << line << "\n"; if (c_word == "IF") { result.instruction_type = if_statement; result.math_string[0] = string_functions.getParenthesis(line, 0); return result; } if (c_word == "FOR") { result.instruction_type = for_loop; std::string for_funcs = string_functions.getParenthesis(line, 0); // Throw error here if {}'s are detected in the for commands. // (this part;;) embedded_functions.push_back(GetInstructionFromLine(GetNextLineInScript(for_funcs))); result.embedded_function_reference[0] = embedded_functions.size() - 1; // (;this part;) result.math_string[0] = GetNextLineInScript(for_funcs); // (;;this part) embedded_functions.push_back(GetInstructionFromLine(GetNextLineInScript(for_funcs))); result.embedded_function_reference[1] = embedded_functions.size() - 1; return result; } if (c_word == "WHILE") { result.instruction_type = while_statement; result.math_string[0] = string_functions.getParenthesis(line, 0); return result; } if (c_word == "ELSE") { result.instruction_type = else_statement; return result; } if (c_word == "DO") { result.instruction_type = do_statement; return result; } if (c_word == "PRINT") { result.instruction_type = print_statement; result.math_string[0] = string_functions.getParenthesis(line, 0); return result; } if (c_word == "CLS") { result.instruction_type = clear_statement; } // = if (line[word.length()] == '=') { result.instruction_type = set_value; result.value_to_modify[0] = word.c_str(); result.math_string[0] = line.replace(0, word.length() + 1, ""); return result; } // += if ((line[word.length()] == '+') && (line[word.length() + 1] == '=')) { result.instruction_type = inc_value_by; result.value_to_modify[0] = word.c_str(); result.math_string[0] = line.replace(0, word.length() + 2, ""); return result; } // -= if ((line[word.length()] == '-') && (line[word.length() + 1] == '=')) { result.instruction_type = dec_value_by; result.value_to_modify[0] = word.c_str(); result.math_string[0] = line.replace(0, word.length() + 2, ""); return result; } // *= if ((line[word.length()] == '*') && (line[word.length() + 1] == '=')) { result.instruction_type = mul_value_by; result.value_to_modify[0] = word.c_str(); result.math_string[0] = line.replace(0, word.length() + 2, ""); return result; } // /= if ((line[word.length()] == '/') && (line[word.length() + 1] == '=')) { result.instruction_type = div_value_by; result.value_to_modify[0] = word.c_str(); result.math_string[0] = line.replace(0, word.length() + 2, ""); return result; } // ++ if ((line[word.length()] == '+') && (line[word.length() + 1] == '+')) { result.instruction_type = inc_value; result.value_to_modify[0] = word.c_str(); return result; } // -- if ((line[word.length()] == '-') && (line[word.length() + 1] == '-')) { result.instruction_type = dec_value; result.value_to_modify[0] = word.c_str(); return result; } // { if (line == "{") { result.instruction_type = opening_bracket; return result; } // } if (line == "}") { result.instruction_type = closing_bracket; return result; } // Throw error here. "Syntax error in user code at " + line return result; } // This will return the next line up until a semicolon and remove that line from the script. std::string InputScript::GetNextLineInScript(std::string &script) { int open_parenthesis_count = 0; int length = 0; for (int i = 0; i < script.length(); i++) { if (script[i] == '(') { open_parenthesis_count++; } if (script[i] == ')') { open_parenthesis_count--; } if ((script[i] == ';') && (open_parenthesis_count == 0)) { std::string result = script.substr(0, length); script = script.substr(length + 1, script.length()); // + 1 to skip the semi-colon return result; } length++; } // End of the script was reached, returns what was left without semi-colon. std::string result = script.substr(0, length); script = script.substr(length, script.length()); return result; } // Add a semicolon after certain commands ("if() {}" -> if(); {}) void InputScript::ApplyParenthesisSemicolonCheat(std::string &script, std::string search_for) { std::size_t f = script.find(search_for); int insert_at; while (f != std::string::npos) { insert_at = f + search_for.size() + 2 + string_functions.getParenthesis(script, f).size(); if (script[insert_at] != ';') { script.insert(insert_at, ";"); } f = script.find(search_for, insert_at); } } std::string InputScript::GetInstructionDebug(vector<Instruction>& inst) { std::string result = ""; for (int i = 0; i < inst.size(); i++) { result += "Line " + string_functions.numToString(i) + " instruction_type: " + string_functions.numToString(inst[i].instruction_type) + "\n"; } return result; } }
true
be7cc223ee1f00bab6d51d0f00255842f074c01c
C++
CJFulford/Modeling-Project
/Project/Lighting.cpp
UTF-8
1,183
2.890625
3
[]
no_license
#include "Header.h" #include <typeinfo> #include <string> using namespace glm; // assuming that the incoming normal is normalized vec3 Blinn_Phong(Ray *ray, float scalar, glm::vec3 normal, Object *object) { #define SELECTED_BRIGHTEN_AMOUNT 1.5f vec3 intersect = ray->applyScalar(scalar), viewRay = normalize(ray->origin - intersect), lightRay = normalize(LIGHT_POS - intersect), halfRay = normalize((viewRay + lightRay)), col = object->colour * ((object->selected) ? SELECTED_BRIGHTEN_AMOUNT : 1.f); // specular colour is always white, add ambient for no black sides return (col * AMBIENT) + (WHITE * ((col * max(0.f, dot(normal, lightRay))) + (WHITE * pow(max(0.f, dot(normal, halfRay)), object->phong)))); } vec3 getColour(Ray *ray, std::vector<Object*> *objectVec) { for (unsigned int i = 0; i < objectVec->size(); i++) { Object *object = (*objectVec)[i]; object->getVolume(ray); } float scalar = 0; glm::vec3 normal(0.f); Object *obj= ray->getClosestScalar(&scalar, &normal); if (scalar != 0) return Blinn_Phong(ray, scalar, normal, obj); else return BACKGROUND_COLOUR; }
true
3a19de26c6cfb3d317b832229fb2c3af624a3499
C++
MatthewAChang/DnDMysteryDungeon
/World/Characters/Enemy.h
UTF-8
844
3.046875
3
[]
no_license
#ifndef ENEMY_H #define ENEMY_H #include "Character.h" class Armour; class Weapon; class Enemy: public Character { public: Enemy(int id, std::string name, std::vector<int> abilityScores, int health, std::shared_ptr<Armour> armour, std::shared_ptr<Weapon> weapon, Location location, CharacterDefinitions::EnemyStateEnum state); ~Enemy() {} void SetState(CharacterDefinitions::EnemyStateEnum state) { m_state = state; } CharacterDefinitions::EnemyStateEnum GetState() const { return m_state; } void SetTarget(std::shared_ptr<Character> target) { m_target = target; } std::shared_ptr<Character> GetTarget() const { return m_target; } CharacterDefinitions::EnemyStateEnum m_state; std::shared_ptr<Character> m_target; }; #endif // ENEMY_H
true
8a33a839971439ab41eb50750cd37453661c271f
C++
Osurac/EDA-FAL
/FAL/Ejercicio 3/main.cpp
UTF-8
2,117
3.203125
3
[]
no_license
// Nombre y apellidos del alumno //Álvaro Miguel Rodríguez Mateos // Usuario del juez de clase //A64 #include <iostream> #include <iomanip> #include <fstream> #include <vector> #include <algorithm> #include <string> #include <utility> // Explicación del algoritmo utilizado // Coste del algoritmo utilizado struct solucion { int suma; int valor; }; // Función que resuelve el problema // Recibe un vector con los datos // Devuelve suma de los valores y número de sumandos de la suma solucion resolver(std::vector<int> const& v) { // Inicialización de variables // Codigo del alumno int cnt=1, min=v[0], sum = v[0], res=0; solucion sol; for (int i = 1; i < v.size(); ++i) { if (v[i] < min) { min = v[i]; cnt = 1; } else if (v[i] == min) { cnt++; } sum = sum + v[i]; } res = min * cnt; sum = (sum - res) ; if (cnt == v.size()) { sol.suma = 0; sol.valor = 0; } else { sol.suma = sum; sol.valor = v.size() - cnt; } return sol; } // Resuelve un caso de prueba, leyendo de la entrada la // configuración, y escribiendo la respuesta void resuelveCaso() { // Lectura de los datos int numElem; std::cin >> numElem; std::vector<int> v(numElem); for (int& i : v) std::cin >> i; // LLamar a la función resolver solucion s = resolver(v); // Escribir los resultados std::cout << s.suma << ' ' << s.valor << '\n'; } int main() { // Para la entrada por fichero. Comentar para mandar a acepta el reto //#ifndef DOMJUDGE // std::ifstream in("sample03.in"); // auto cinbuf = std::cin.rdbuf(in.rdbuf()); //save old buf and redirect std::cin to casos.txt //#endif int numCasos; std::cin >> numCasos; for (int i = 0; i < numCasos; ++i) resuelveCaso(); // Para restablecer entrada. Comentar para mandar a acepta el reto //#ifndef DOMJUDGE // para dejar todo como estaba al principio // std::cin.rdbuf(cinbuf); // system("PAUSE"); //#endif return 0; }
true
fc3b669580f9039cbc04d60518660d030b7db3cc
C++
Gary-0111/RoughJudger
/main.cpp
UTF-8
14,664
2.609375
3
[]
no_license
/* * Author: Felix * * usage: * ./Judge [OPTIONS] * * options: * -l The solution's language [C|C++|Java] * -p Problem ID. * -t Time limit. Millisecond by default. * -m Memory limit. Kilo-Bytes by default. [K|M] */ #include <iostream> #include <unistd.h> #include <stdio.h> #include <cstring> #include <sys/reg.h> #include <sys/wait.h> #include <sys/resource.h> #include <sys/ptrace.h> #include <dirent.h> #include <pwd.h> #include <sys/stat.h> #include "Time.h" #include "whiteList.h" using namespace std; const char *datadir = "./data/"; const char *tempdir = "temp"; enum Result { Result_Running, // := 0 Result_Accepted, // := 1 Result_WrongAnswer, // := 2 Result_TimeLimitExceed, // := 3 Result_MemoryLimitExceed, // := 4 Result_OutputLimitExceed, // := 5 Result_RuntimeError, // := 6 Result_PresentationError, // := 7 Result_CompilationError, // := 8 Result_SystemError, // := 9 Result_DangerouCode // := 10 }; const char *result_str[] = { "Running", "Accepted", "Wrong Answer", "Time Limit Exceed", "Memory Limit Exceed", "Output Limit Exceed", "Runtime Error", "Presentation Error", "Compilation Error", "System Error", "Dangerous Code" }; enum Language { Lang_Unknown, Lang_C, Lang_Cpp, Lang_Java }; struct Options { Language lang; string data_dir; const char *judge_user_name = "judger"; unsigned long time_limit; // ms unsigned long memory_limit; // KB }; Options opt; Result result; Language getLang(char *lang) { if(strcmp(lang, "C") == 0) return Lang_C; else if(strcmp(lang, "C++") == 0) return Lang_Cpp; else if(strcmp(lang, "Java") == 0) return Lang_Java; return Lang_Unknown; } void parseParameter(int argc, char *argv[]) { int ch; while((ch = getopt(argc, argv, "l:p:t:m:")) != -1) { switch(ch) { case 'l': opt.lang = getLang(optarg); break; case 'p': opt.data_dir = optarg; break; case 't': sscanf(optarg, "%lu", &opt.time_limit); break; case 'm': sscanf(optarg, "%lu", &opt.memory_limit); break; case '?': cerr << "Invalid options."; break; default: break; } } } void outputResult() { clog << "#################### RESULT ####################\n"; clog << result_str[result] << "\n"; } int compile() { int ret = 0; pid_t pid; while((pid = fork()) == -1) ; if(pid == 0) { const char * const cmd[20] = {"g++", "Main.cpp", "-o", "Main", "--static"}; execvp(cmd[0], (char* const*)cmd); cerr << cmd[0] << " error: " << errno << "\n"; ret = -1; } else { int status; wait(&status); if(WIFEXITED(status) && WEXITSTATUS(status) == EXIT_SUCCESS) { clog << "Successful compile!\n"; } else { result = Result_CompilationError; cerr << "Compile user's code failed.\n"; outputResult(); exit(1); } } return ret; } void setLimit() { rlimit lim; //时间限制 lim.rlim_cur = (opt.time_limit + 999) / 1000; lim.rlim_max = lim.rlim_cur; if(setrlimit(RLIMIT_CPU, &lim) < 0) { cerr << "Set rlimit error.\n"; return; } } void alarm(int which, int milliseconds) { struct itimerval it; it.it_value.tv_sec = milliseconds / 1000; it.it_value.tv_usec = (milliseconds % 1000) * 1000; it.it_interval.tv_sec = 0; it.it_interval.tv_usec = 0; setitimer(which, &it, NULL); } void timeoutHandler(int signo) { switch (signo) { case SIGPROF: cerr << "Timeout!\n"; exit(-1); default: break; } } unsigned long getMemory(pid_t pid) { char buffer[256]; sprintf(buffer, "/proc/%d/status", pid); FILE* fp = fopen(buffer, "r"); if (fp == NULL) { cerr << "Open " << buffer << " failed.\n"; exit(1); } unsigned long vmPeak = 0, vmSize = 0, vmExe = 0, vmLib = 0, vmStack = 0; while (fgets(buffer, 32, fp)) { if (!strncmp(buffer, "VmPeak:", 7)) { sscanf(buffer + 7, "%lu", &vmPeak); } else if (!strncmp(buffer, "VmSize:", 7)) { sscanf(buffer + 7, "%lu", &vmSize); } else if (!strncmp(buffer, "VmExe:", 6)) { sscanf(buffer + 6, "%lu", &vmExe); } else if (!strncmp(buffer, "VmLib:", 6)) { sscanf(buffer + 6, "%lu", &vmLib); } else if (!strncmp(buffer, "VmStk:", 6)) { sscanf(buffer + 6, "%lu", &vmStack); } } fclose(fp); if (vmPeak) { vmSize = vmPeak; } return vmSize - vmExe - vmLib - vmStack; } bool isInputFile(const char *filename) { return strcmp(filename + strlen(filename) - 3, ".in") == 0; } void compareUntilNonspace(FILE *&fd_std, int &ch_std, FILE *&fd_usr, int &ch_usr, Result &ret) { while(isspace(ch_std) || isspace(ch_usr)) { if(ch_std != ch_usr) { // Deal with the files from Windows. // The end-of-line is CRLF(\r\n) in Windows, LF(\n) in *nix and CR("\r") in Mac. if(ch_std == '\r' && ch_usr == '\n') { ch_std = fgetc(fd_std); if(ch_std != ch_usr) { ret = Result_PresentationError; } } else { ret = Result_PresentationError; } } if(isspace(ch_std)) ch_std = fgetc(fd_std); if(isspace(ch_usr)) ch_usr = fgetc(fd_usr); if(ret == Result_PresentationError) return; } } Result compareOutput(const char *std_file, const char *usr_file) { Result ret = Result_Running; FILE *fd_std = fopen(std_file, "r"); FILE *fd_usr = fopen(usr_file, "r"); if(!fd_std) { cerr << "Can not open standard file!\n" << std_file << ": No such file.\n"; return Result_RuntimeError; } if(!fd_usr) { cerr << "Can not open user's file!\n" << usr_file << ": No such file.\n"; return Result_RuntimeError; } bool isEnd = false; int ch_std = fgetc(fd_std); int ch_usr = fgetc(fd_usr); while(ret == Result_Running) { if(isEnd) break; compareUntilNonspace(fd_std, ch_std, fd_usr, ch_usr, ret); if(ret == Result_PresentationError) break; while((!isspace(ch_std)) && (!isspace(ch_usr))) { if(ch_std == EOF && ch_usr == EOF) { isEnd = true; break; } if(ch_std != ch_usr) { ret = Result_WrongAnswer; break; } ch_std = fgetc(fd_std); ch_usr = fgetc(fd_usr); } } if(fd_std) fclose(fd_std); if(fd_usr) fclose(fd_usr); return ret; } int removeTempDir() { DIR *dir; dirent *ptr; if(chdir(tempdir)) { cerr << "Change directory failed.\n"; return -1; } if((dir = opendir(".")) == NULL) { cerr << "Open directory failed.\n" << tempdir << ": No such directory.\n"; return -1; } while((ptr = readdir(dir)) != NULL) { if(strcmp(".", ptr->d_name) == 0 || strcmp("..", ptr->d_name) == 0) continue; if(remove(ptr->d_name)) { cerr << "Remove file failed.\n" << ptr->d_name << "\n"; break; } } closedir(dir); if(chdir("..")) { cerr << "Change directory failed.\n"; return -1; } if(rmdir(tempdir)) { cerr << "Remove directory failed.\n"; return -1; } return 0; } int run(const char *dirpath) { int ret = 0; pid_t pid = -1; DIR *dir; dirent *ptr; if((dir = opendir(dirpath)) == NULL) { cerr << "Open directory failed.\n" << dirpath << ": No such directory.\n"; exit(1); } passwd* judge_user = getpwnam(opt.judge_user_name); if(judge_user == NULL) { cerr << "No such user: " << opt.judge_user_name << "\n"; exit(1); } if(mkdir(tempdir, 0777)) { cerr << "Create directory failed.\n"; exit(1); } char tmpName[1024]; unsigned long memUsed = 0; Time timeUsed, timeLimit((timeval){opt.time_limit/1000, (opt.time_limit%1000) * 1000}); // Traverse all input files in dirpath. while((result == Result_Running || result == Result_PresentationError) && (ptr = readdir(dir)) != NULL) { if(strcmp(".", ptr->d_name) == 0 || strcmp("..", ptr->d_name) == 0) continue; if(!isInputFile(ptr->d_name)) continue; int len = strlen(ptr->d_name); strcpy(tmpName, ptr->d_name); tmpName[len - 3] = '\0'; char std_input_file[256], std_output_file[256], usr_output_file[256]; strcpy(std_input_file, (string(dirpath) + "/" + ptr->d_name).c_str()); strcpy(std_output_file, (string(dirpath) + "/" + tmpName + ".out").c_str()); strcpy(usr_output_file, ("temp/" + string(tmpName) + ".out").c_str()); clog << "\n************** Test case #" << tmpName << " *****************\n"; clog << "standard input file: " << std_input_file << "\n"; clog << "standard output file: " << std_output_file << '\n'; clog << "user's output file: " << usr_output_file << '\n'; while((pid = fork()) == -1) ; if(pid == 0) { // I/O redirect. freopen(std_input_file, "r", stdin); freopen(usr_output_file, "w", stdout); // Set euid. if(seteuid(judge_user->pw_uid) != EXIT_SUCCESS) { cerr << "Set euid failed.\n"; } clog << "The Judger's id is " << judge_user->pw_uid << "\n"; clog << "The child process's uid is " << getuid() << "\n"; clog << "The child process's euid is " << geteuid() << "\n"; // Trace the child process. ptrace(PTRACE_TRACEME, 0, NULL, NULL); // Set the resources limits. setLimit(); // signal(SIGPROF, timeoutHandler); // alarm(ITIMER_REAL, 1000); // Execute the user's program. execvp("./Main", NULL); cerr << "execv error: " << errno << '\n'; ret = -1; } else { // 监控子进程的系统调用,并监测子进程使用的内存及时间 int status; memset(syscall_cnt, 0, sizeof(syscall_cnt)); initWhiteList(); outputWhiteList(); rusage rused; while (true) { wait4(pid, &status, 0, &rused); // Get the system call ID. int syscall_id = ptrace(PTRACE_PEEKUSER, pid, 4 * ORIG_EAX, NULL); syscall_cnt[syscall_id]++; // Check if the child process is terminated normally. if(WIFEXITED(status)) { outputSyscall(); clog << "Userexe was normally terminated.\n"; result = compareOutput(std_output_file, usr_output_file); break; } // Check if the child process is TLE, RE or OLE. if(WIFSIGNALED(status) || (WIFSTOPPED(status) && WSTOPSIG(status) != SIGTRAP)) { int signo = 0; if(WIFSIGNALED(status)) signo = WTERMSIG(status); else signo = WSTOPSIG(status); switch(signo){ //TLE case SIGXCPU: case SIGKILL: case SIGPROF: result = Result_TimeLimitExceed; break; //OLE case SIGXFSZ: break; // RE case SIGSEGV: case SIGABRT: default: result = Result_RuntimeError; break; } ptrace(PTRACE_KILL, pid); outputSyscall(); clog << "Userexe was killed! The terminated signal is: " << signo << "\n"; if(result == Result_TimeLimitExceed) timeUsed = timeLimit; break; } // Check if the system call is valid. if(!isValidSyscall(syscall_id)) { clog << "The child process trys to call a limited system call: " << syscall_list[syscall_id] << "\n"; ptrace(PTRACE_KILL, pid); result = Result_DangerouCode; break; } // Check if the child process is MLE. memUsed = max(memUsed, getMemory(pid)); if(memUsed > opt.memory_limit) { ptrace(PTRACE_KILL, pid); memUsed = opt.memory_limit; result = Result_MemoryLimitExceed; break; } // Continue the child process until next time it calls a system call. ptrace(PTRACE_SYSCALL, pid, NULL, NULL); } // if(result == Result_Running || result == Result_PresentationError) timeUsed = timeUsed + Time(rused.ru_stime) + Time(rused.ru_utime); if(timeLimit < timeUsed) { result = Result_TimeLimitExceed; timeUsed = timeLimit; } } } if(pid > 0) { if(result == Result_Running) result = Result_Accepted; if(removeTempDir()) { exit(-1); } outputResult(); clog << "Used Time: " << timeUsed << " Used Memory: " << memUsed << "KB\n"; } closedir(dir); return ret; } int main(int argc, char *argv[]) { parseParameter(argc, argv); cout << opt.lang << " " << opt.data_dir << " " << opt.time_limit << " " << opt.memory_limit << '\n'; compile(); initSyscallList(); result = Result_Running; run((datadir + opt.data_dir).c_str()); //clog << sizeof(cpp_limit)/sizeof(SyscallLimit) << "\n"; return 0; }
true
d87aafd90641462a1cb98cc2f8bbc583694cdaa5
C++
BenjaminDecoene/2DAE01_Decoene_Benjamin_GameEngine
/Game/Map.cpp
UTF-8
4,050
2.53125
3
[]
no_license
#include "pch.h" #include "Map.h" #include "Tile.h" #include "Scene.h" #include "Player.h" #include "Renderer.h" #include "Utils.h" #include "GameStats.h" #include "PhysxComponent.h" #include "SceneManager.h" Map::Map(Player* player) :m_Player(player) { LoadTiles(); AddTiles(); InitBorder(); AddObserver(&GameStats::GetInstance()); } Map::~Map() { for(int r{}; r < m_nrTileRows; r++) { for(int c{}; c < m_nrTileColumns; c++) { delete m_Tiles[c][r]; m_Tiles[c][r] = nullptr; } } } void Map::InitBorder() { // make border so the player cant go outside of the level const auto windowSize = GameInfo::GetInstance().GetWindowSize(); const float ppm = GameInfo::GetInstance().GetPPM(); m_Transform.SetPosition(windowSize.x / 2, windowSize.y / 2); auto bodyDef = new b2BodyDef(); bodyDef->type = b2_staticBody; bodyDef->position = {(windowSize.x / 2), 0.f}; auto physxComp = new PhysxComponent(this, SceneManager::GetInstance().GetScene().GetWorld(), bodyDef); physxComp->FixedToParent(false); b2PolygonShape boxShapeLeft; boxShapeLeft.SetAsBox((windowSize.x / ppm) / 2, (50 / ppm) / 2, {((-windowSize.x - 25.f) / ppm), 0.f}, float(M_PI / 2)); const auto fixtureDefLeft = new b2FixtureDef(); fixtureDefLeft->shape = &boxShapeLeft; fixtureDefLeft->density = 1.0f; fixtureDefLeft->friction = 0.3f; fixtureDefLeft->restitution = 0.3f; physxComp->AddFixture(fixtureDefLeft); b2PolygonShape boxShapeDown; boxShapeDown.SetAsBox((windowSize.x / ppm) / 2, (50 / ppm) / 2, {(-windowSize.x / 2) / ppm, ((-windowSize.y / 2 - 25.f) / ppm)}, 0.f); const auto fixtureDefDown = new b2FixtureDef(); fixtureDefDown->shape = &boxShapeDown; fixtureDefDown->density = 1.0f; fixtureDefDown->friction = 0.3f; fixtureDefDown->restitution = 0.3f; physxComp->AddFixture(fixtureDefDown); b2PolygonShape boxShapeRight; boxShapeRight.SetAsBox((windowSize.x / ppm) / 2, (50 / ppm) / 2, {25.f / ppm, 0.f}, float(M_PI / 2)); const auto fixtureDefRight = new b2FixtureDef(); fixtureDefRight->shape = &boxShapeRight; fixtureDefRight->density = 1.0f; fixtureDefRight->friction = 0.3f; fixtureDefRight->restitution = 0.3f; physxComp->AddFixture(fixtureDefRight); b2PolygonShape boxShapeUp; boxShapeUp.SetAsBox((windowSize.x / ppm) / 2, (50 / ppm) / 2, {(-windowSize.x / 2) / ppm, ((windowSize.y / 2 + 25.f - 40.f) / ppm)}, 0.f); const auto fixtureDefUp = new b2FixtureDef(); fixtureDefUp->shape = &boxShapeUp; fixtureDefUp->density = 1.0f; fixtureDefUp->friction = 0.3f; fixtureDefUp->restitution = 0.3f; physxComp->AddFixture(fixtureDefUp); AddComponent(physxComp); } void Map::AddTiles() { auto& scene = SceneManager::GetInstance().GetScene(); for(int r{}; r < m_nrTileRows; r++) { for(int c{}; c < m_nrTileColumns; c++) { if(m_Tiles[c][r]) scene.Add(m_Tiles[c][r]); } } } Tile* Map::GetTile(const b2Vec2& pos) { const int column = int(pos.x) / m_TileSize; const int row = int(pos.y) / m_TileSize; // safety checks if(column >= m_nrTileColumns || column < 0) return nullptr; if(row >= m_nrTileRows || row < 0) return nullptr; return m_Tiles[int(pos.x) / m_TileSize][int(pos.y) / m_TileSize]; } void Map::LoadTiles() { for(int r{}; r < m_nrTileRows; r++) { for(int c{}; c < m_nrTileColumns; c++) { m_Tiles[c][r] = new Tile({(m_TileSize / 2.f) + (c * m_TileSize), (m_TileSize / 2.f) + (r * m_TileSize)}, TileState::broken); } } } bool Map::GetIsDone() { for(int r{}; r < m_nrTileRows; r++) { for(int c{}; c < m_nrTileColumns; c++) { if(m_Tiles[c][r]->GetState() == TileState::emerald) return false; } } return true; } void Map::Update() { Object::Update(); UpdatePlayer(); } void Map::UpdatePlayer() { const auto diggerPoint = m_Player->GetDigPoint(); Tile* diggerTile = m_Tiles[int(diggerPoint.x) / m_TileSize][int(diggerPoint.y) / m_TileSize]; switch(diggerTile->Break()) { case TileState::emerald: Notify(*this, "Emerald"); break; case TileState::dirt: Notify(*this, "Dirt"); break; case TileState::broken: break; } }
true
2a467019f30b5cb2a2509f59423f695b09ec797d
C++
euseibus/MACE
/src/Utility/Color.cpp
UTF-8
3,755
3.171875
3
[ "MIT" ]
permissive
/* The MIT License (MIT) Copyright (c) 2016 Liav Turkia Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. */ #include <MACE/Utility/Color.h> namespace mc { namespace { float trimFloat(const float& color) { return color < 0.0f ? 0.0f : (color>1.0f ? 1.0f : color); } Byte convertFloatToRGBA(const float& color) { return static_cast<Byte>(trimFloat(color)*254.0f); } float convertRGBAToFloat(const Byte& color) { return color / 254.0f; } }//anon namespace Color Color::lighten() const { return Color(trimFloat(r + 0.05f), trimFloat(g + 0.05f), trimFloat(b + 0.05f), a); } Byte Color::getRed() const { return convertFloatToRGBA(this->r); } Byte Color::getGreen() const { return convertFloatToRGBA(this->g); } Byte Color::getBlue() const { return convertFloatToRGBA(this->b); } Byte Color::getAlpha() const { return convertFloatToRGBA(this->a); } void Color::setRed(const Byte& red) { this->r = convertRGBAToFloat(red); } void Color::setGreen(const Byte& green) { this->g = convertRGBAToFloat(green); } void Color::setBlue(const Byte& blue) { this->b = convertRGBAToFloat(blue); } void Color::setAlpha(const Byte& alpha) { this->a = convertRGBAToFloat(alpha); } Color::Color(const int red, const int green, const int blue, const int alpha) noexcept: Color(static_cast<Byte>(red), static_cast<Byte>(green), static_cast<Byte>(blue), static_cast<Byte>(alpha)) {} Color::Color(const Byte red, const Byte green, const Byte blue, const Byte alpha) noexcept { setRed(red); setGreen(green); setBlue(blue); setAlpha(alpha); } Color::Color(const float red, const float green, const float blue, const float alpha) noexcept: r(red), g(green), b(blue), a(alpha) {} Color::Color(const std::array<float, 4>& rgba) { this->setValues(rgba); } Color::Color(const Color & copy) noexcept : Color(copy.r, copy.g, copy.b, copy.a) {} Color::Color() noexcept : Color(0.0f, 0.0f, 0.0f, 1.0f) {} Color Color::darken() const { return Color(trimFloat(r - 0.05f), trimFloat(g - 0.05f), trimFloat(b - 0.05f), a); } bool Color::operator==(const Color & other) const { return r == other.r&&g == other.g&&b == other.b&&a == other.a; } bool Color::operator!=(const Color & other) const { return !operator==(other); } void Color::setValues(const std::array<float, 3>& rgb) { this->r = rgb[0]; this->g = rgb[1]; this->b = rgb[2]; } void Color::setValues(const std::array<float, 4>& rgba) { this->r = rgba[0]; this->g = rgba[1]; this->b = rgba[2]; this->a = rgba[3]; } std::array<float, 4> Color::getValues() const { return { { r,g,b,a } }; } const float * Color::flatten(float arr[4]) const { arr[0] = r; arr[1] = g; arr[2] = b; arr[3] = a; return arr; }; bool Color::operator<(const Color& other) const { //the real g right here return other.r < r && other.g < g && other.b < b && other.a < a; } bool Color::operator<=(const Color& other) const { return operator<(other) || operator==(other); } bool Color::operator>(const Color& other) const { //the real g right here return !operator<=(other); } bool Color::operator>=(const Color& other) const { //the real g right here return !operator<(other); } }//mc
true
91509b14984369b1117d17e560e073129d22a13e
C++
dr0pdb/competitive
/uva/Chapter 4/p11953 accepted.cpp
UTF-8
943
2.5625
3
[]
no_license
#include<bits/stdc++.h> #define ABS(a) ((a < 0) ? ((-1)*(a)) : (a)) using namespace std; int t,n,counter; char matrix[105][105]; int rowDir[]={0,1,0,-1}; int colDir[]={1,0,-1,0}; void dfs(int j,int k){ if(j<0 || j>=n || k<0 || k>=n || matrix[j][k]=='.'){ return; } matrix[j][k]='.'; for (int i = 0; i < 4; ++i) { dfs(j+rowDir[i],k+colDir[i]); } } int main() { std::ios::sync_with_stdio(false); cin>>t; for (int i = 1; i <= t; ++i) { counter=0; cin>>n; for (int j = 0; j < n; ++j) { for (int k = 0; k < n; ++k) { cin>>matrix[j][k]; } } //dfs based flood fill for (int j = 0; j < n; ++j) { for (int k = 0; k < n; ++k) { if (matrix[j][k]=='x') { dfs(j,k); counter++; } } } cout<<"Case "<<i<<": "<<counter<<"\n"; } return 0; }
true
e756f35fdf4321866a924ad48edfa7f12c5a0c21
C++
Tygydyk/Boost
/main.cpp
UTF-8
980
2.859375
3
[]
no_license
#include "stdafx.h" #include <iostream> #include <boost/filesystem.hpp> using std::cout; using namespace boost::filesystem; int main(int argc, char* argv[]) { if (argc < 2) { cout << "Usage: tut3 path\n"; return 1; } path p (argv[1]); try { if (exists(p)) { if (is_regular_file(p)) cout << p << " size is " << file_size(p) << '\n'; else if (is_directory(p)) { cout << p << " is a directory containing:\n"; for (directory_entry& x : directory_iterator(p)) cout << " " << x.path() << '\n'; } else cout << p << " exists, but is not a regular file or directory\n"; } else cout << p << " does not exist\n"; } catch (const filesystem_error& ex) { cout << ex.what() << '\n'; } for (const auto &x : report) { for (const auto &y : x.second) { std::cout << "broker:" << x.first << " account:" << y.first << " files:" << y.second.first << " lastdate:" << y.second.second << std::endl; } } return 0; }
true
0fe14b3914fe321c2301023786ae08c47159c9a5
C++
Extron/NLH
/Source/NLH/Public/GCClip.h
UTF-8
1,911
2.84375
3
[]
no_license
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "NLHGunComponent.h" #include "NLHGun.h" #include "GCClip.generated.h" /** * Clips are gun components that dictate the type of projectiles that are fired from a weapon and how many the weapon holds. */ UCLASS(Abstract) class NLH_API AGCClip : public ANLHGunComponent { GENERATED_BODY() /** * The current amount of projectiles that are in the clip. */ UPROPERTY() int32 Count; public: /** * The amount of projectiles that the clip can hold. */ UPROPERTY(BlueprintReadWrite) int32 Capacity; /** * The type of projectile that this clip contains. */ UPROPERTY(BlueprintReadWrite) TSubclassOf<class ANLHProjectile> ProjectileType; /** * The damage type that the projectiles in this clip do when they hit something. */ UPROPERTY(BlueprintReadWrite) TSubclassOf<class UNLHDamageType> DamageType; /** * Creates a new clip and initializes its properties. */ AGCClip(const FObjectInitializer& ObjectInitializer); /** * A clip will always be able to return a definite projectile type. * * @param outProjType - The projectile type that this clip stores. * @return Clips always return true, since they have a definite projectile type. */ virtual bool FindProjectile(TSubclassOf<class ANLHProjectile>& outProjType) override; /** * A clip will always be able to return a definite damage type. * * @param outDmgType - The damage type that this clip stores. * @return Clips always return true, since they have a definite damage type. */ virtual bool FindDamageType(TSubclassOf<class UNLHDamageType>& outDmgType) override; /** * Removes a single projectile from the clip. */ virtual void Fire() override; /** * Refills the clip with fresh ammo, and decreases the amount of clips being carried by the player. */ virtual void Reload() override; };
true
a8f6feb446529fa26f7b56c7b2d1fd21a7b12c9d
C++
Harrix/Harrix-MathLibrary
/src/Генетические алгоритмы/HML_SelectItemOnProbability.cpp
UTF-8
1,317
3.015625
3
[ "MIT", "Apache-2.0" ]
permissive
int HML_SelectItemOnProbability(double *P, int VHML_N) { /* Функция выбирает случайно номер элемента из вектора, где вероятность выбора каждого элемента определяется значением в векторе P. Входные параметры: P - вектор вероятностей выбора каждого элемента, то есть его компоненты должны быть из отрезка [0;1], а сумма их равна 1; VHML_N - размер вектора. Возвращаемое значение: Номер выбранного элемента. Примечание: Проверка на правильность вектора P не проводится, так как функция обычно вызывается многократно, а проводить постоянно проверку накладно. Всё на Вашей совести. */ int i=0; int VHML_Result=-1;//номер выбранного элемента double s=0; double r; r=HML_RandomNumber();//случайное число while ((VHML_Result==-1)&&(i<VHML_N)) { //определяем выбранный элемент s+=P[i]; if (s>r) VHML_Result=i; i++; } return VHML_Result; }
true
0fca5629c10feaf948bbb3d47ede8538bef1346f
C++
drleq/CppDicom
/Dicom/dicom/io/part10/detail/OutputContext.h
UTF-8
4,828
2.703125
3
[ "MIT" ]
permissive
#pragma once #include "dicom/data/buffer.h" #include "dicom/data/encoded_string.h" #include "dicom/data/StringEncodingType.h" #include "dicom/data/VRType.h" #include "dicom/detail/intrinsic.h" #include "dicom/io/part10/detail/apply_endian.h" #include "dicom/io/part10/OutputStream.h" #include "dicom/io/TransferSyntax.h" #include "dicom/tag_number.h" namespace dicom::io::part10::detail { class OutputContext { public: OutputContext( const OutputStreamPtr& stream, const TransferSyntax* transfer_syntax, data::StringEncodingType string_encoding ); OutputContext(const OutputContext&) = delete; OutputContext& operator = (const OutputContext&) = delete; //---------------------------------------------------------------------------------------------------- [[nodiscard]] bool Failed() const { return m_serialization_failure; } void SetFailed() { m_serialization_failure = true; } //---------------------------------------------------------------------------------------------------- [[nodiscard]] EndianType Endian() const { return m_endian; } [[nodiscard]] TagEncodingType Encoding() const { return m_encoding; } [[nodiscard]] data::StringEncodingType GetStringEncoding() const { return m_string_encoding; } void SetStringEncoding(data::StringEncodingType encoding) { m_string_encoding = encoding; } //---------------------------------------------------------------------------------------------------- [[nodiscard]] const OutputStreamPtr& Stream() const { return m_stream; } //---------------------------------------------------------------------------------------------------- void WriteTagNumber(tag_number tag) { tag_number val; if (m_endian == EndianType::Little) { // [b,a,d,c] -> [d,c,b,a] val = dicom::detail::rotate_left32(tag, 16); } else { // [b,a,d,c] -> [c,d,a,b] val = dicom::detail::byte_swap32(tag); } m_stream->WriteValue(val); } //---------------------------------------------------------------------------------------------------- void WriteImplicitTagLength(std::streamsize length) { if (length > 0xFFFFFFFF) { SetFailed(); return; } uint32_t val = static_cast<uint32_t>(length); if (m_endian == EndianType::Big) { val = dicom::detail::byte_swap32(val); } m_stream->WriteValue(val); } void WriteExplicitTagLength(data::VRType vr_type, std::streamsize length); void WriteSQLength(std::streamsize length) { // This is the same as Implicit tag length handling WriteImplicitTagLength(length); } //---------------------------------------------------------------------------------------------------- void WriteString(const std::string& src); void WriteUIString(const std::string& src); void WriteUnicode(const data::encoded_string& src); //---------------------------------------------------------------------------------------------------- template <typename TVR> void WriteBinary(const TVR* attribute) { auto& binary = attribute->Value(); if (m_endian == EndianType::Little) { // If endian conversion is not required then simply write the data. m_stream->Write(binary, binary.ByteLength()); } else { // If endian conversion is required then convert it in chunks. const size_t TmpCapacity = 4096; auto tmp = std::make_unique<typename TVR::value_type[]>(TmpCapacity); auto binary_ptr = binary.Get(); size_t remaining = binary.Length(); while (remaining != 0) { // Copy the next chunk size_t len = std::min(remaining, TmpCapacity); memcpy(tmp.get(), binary_ptr, len * sizeof(typename TVR::value_type)); // Convert to big endian apply_endian<sizeof(typename TVR::value_type)>::Apply(tmp.get(), len); // Write the data m_stream->Write(tmp.get(), len * sizeof(typename TVR::value_type)); remaining -= len; binary_ptr += len; } } } private: const EndianType m_endian; const TagEncodingType m_encoding; data::StringEncodingType m_string_encoding; OutputStreamPtr m_stream; bool m_serialization_failure; }; }
true
38d28e7aef8424f348f4ae3a9fa77b2ab5339af6
C++
ManhKhoa1507/CryptoFinalProject
/Code/test/tethys_store.cpp
UTF-8
5,773
2.640625
3
[]
no_license
#include "tethys_test_utils.hpp" #include <sse/schemes/tethys/encoders/encode_encrypt.hpp> #include <sse/schemes/tethys/encoders/encode_separate.hpp> #include <sse/schemes/tethys/tethys_store.hpp> #include <sse/schemes/tethys/tethys_store_builder.hpp> #include <gtest/gtest.h> namespace sse { namespace tethys { namespace test { using namespace details; struct Hasher { TethysAllocatorKey operator()(const key_type& key) { TethysAllocatorKey tk; static_assert(sizeof(tk.h) == sizeof(key_type), "Invalid source key size"); memcpy(tk.h, key.data(), sizeof(tk.h)); return tk; } }; const std::string test_dir = "tethys_store_test"; const std::string table_path = test_dir + "/tethys_table.bin"; const std::string stash_path = test_dir + "/tethys_stash.bin"; // construct key-value pairs that force an overflow after the lists have a // certain size std::vector<std::pair<key_type, std::vector<size_t>>> test_key_values( size_t v_size) { std::vector<std::pair<key_type, std::vector<size_t>>> kv_vec; key_type key_0 = {{0x00}}; std::vector<size_t> v_0(v_size, 0xABABABABABABABAB); for (size_t i = 0; i < v_0.size(); i++) { v_0[i] += i; } kv_vec.emplace_back(std::make_pair(key_0, v_0)); // force overflow key_type key_1 = key_0; key_1[8] = 0x01; std::vector<size_t> v_1(v_size, 0xCDCDCDCDCDCDCDCD); for (size_t i = 0; i < v_1.size(); i++) { v_1[i] += i; } kv_vec.emplace_back(std::make_pair(key_1, v_1)); key_type key_2 = key_0; key_2[0] = 0x01; key_2[8] = 0x00; std::vector<size_t> v_2(v_size, 0xEFEFEFEFEFEFEFEF); for (size_t i = 0; i < v_2.size(); i++) { v_2[i] += i; } kv_vec.emplace_back(std::make_pair(key_2, v_2)); key_type key_3 = key_0; key_3[0] = 0x01; key_3[8] = 0x01; std::vector<size_t> v_3(v_size, 0x6969696969696969); for (size_t i = 0; i < v_3.size(); i++) { v_3[i] += i; } kv_vec.emplace_back(std::make_pair(key_3, v_3)); key_type key_4 = key_0; key_4[0] = 0x01; key_4[8] = 0x02; std::vector<size_t> v_4(v_size, 0x7070707070707070); for (size_t i = 0; i < v_4.size(); i++) { v_4[i] += i; } kv_vec.emplace_back(std::make_pair(key_4, v_4)); key_type key_5 = key_0; key_5[0] = 0x02; key_5[8] = 0x01; std::vector<size_t> v_5(v_size, 0x4242424242424242); for (size_t i = 0; i < v_5.size(); i++) { v_5[i] += i; } kv_vec.emplace_back(std::make_pair(key_5, v_5)); key_type key_6 = key_0; key_6[0] = 0x02; key_6[8] = 0x02; std::vector<size_t> v_6(v_size, 0x5353535353535353); for (size_t i = 0; i < v_6.size(); i++) { v_6[i] += i; } kv_vec.emplace_back(std::make_pair(key_6, v_6)); return kv_vec; } template<class Encoder> size_t get_encoded_number_elements( const std::vector<std::pair<key_type, std::vector<size_t>>>& kv_vec) { size_t n_elts = 0; for (const auto& kv : kv_vec) { n_elts += kv.second.size() + Encoder::kBucketControlValues; } return n_elts; } void build_store(size_t v_size, bool& valid_v_size) { TethysStoreBuilderParam builder_params; builder_params.max_n_elements = 0; builder_params.tethys_table_path = table_path; builder_params.tethys_stash_path = stash_path; builder_params.epsilon = 0.1; using encoder_type = encoders::EncodeSeparateEncoder<key_type, size_t, kPageSize>; auto test_kv = test_key_values(v_size); builder_params.max_n_elements = get_encoded_number_elements<encoder_type>(test_kv); TethysStoreBuilder<kPageSize, key_type, size_t, Hasher, encoder_type> store_builder(builder_params); if (v_size > store_builder.kMaxListSize) { valid_v_size = false; } else { valid_v_size = true; } for (const auto& kv : test_kv) { if (v_size > store_builder.kMaxListSize) { ASSERT_THROW(store_builder.insert_list(kv.first, kv.second), std::invalid_argument); } else { store_builder.insert_list(kv.first, kv.second); } } store_builder.build(); } void test_store(size_t v_size) { TethysStore<kPageSize, key_type, size_t, Hasher, encoders::EncodeSeparateDecoder<key_type, size_t, kPageSize>> store(table_path, stash_path); auto test_kv = test_key_values(v_size); for (const auto& kv : test_kv) { std::vector<size_t> res = store.get_list(kv.first); ASSERT_EQ(std::set<size_t>(res.begin(), res.end()), std::set<size_t>(kv.second.begin(), kv.second.end())); } } static void cleanup_store() { sse::utility::remove_directory(test_dir); } class TethysStoreTest : public testing::TestWithParam<size_t> { void SetUp() override { cleanup_store(); sse::utility::create_directory(test_dir, static_cast<mode_t>(0700)); } void TearDown() override { cleanup_store(); } }; class TethysStoreOverflowTest : public TethysStoreTest { }; TEST_P(TethysStoreOverflowTest, build_and_get) { size_t v_size = GetParam(); bool valid_v_size; build_store(v_size, valid_v_size); if (valid_v_size) { test_store(v_size); } cleanup_store(); } INSTANTIATE_TEST_SUITE_P(VariableListLengthTest, TethysStoreOverflowTest, testing::Values(20, 450, 600), testing::PrintToStringParamName()); } // namespace test } // namespace tethys } // namespace sse
true
ba77e75d4e0de9307c4f8bcd01e1f54a5af71612
C++
sehee0531/C-homework
/큰 실수 출력.cpp
UHC
286
3.09375
3
[]
no_license
#include<iostream> using namespace std; void main() { double big[5]; double max = big[0]; cout << "5 Ǽ Է϶>>"; for (int i = 0; i < 4; i++) { cin >> big[i]; if (big[i] > max) { max = big[i]; } } cout << " ū =" << max; }
true
ca6a5d30660fac3b3ce0442afbc5e9b581ba803a
C++
bithead942/Comm_Pad
/CommPad.ino
UTF-8
2,746
2.578125
3
[ "Apache-2.0" ]
permissive
/* X-Wing Pilot Comm Pad Lights by Bithead942 Arduino Pro Mini (5V, ATMega328, 16MHz) Adafruit LED Sequens turn on-off in sequence */ int i = 0; // the setup function runs once when you press reset or power the board void setup() { pinMode(2, OUTPUT); pinMode(4, OUTPUT); pinMode(6, OUTPUT); } // the loop function runs over and over again forever void loop() { //all on digitalWrite(2, HIGH); digitalWrite(4, HIGH); digitalWrite(6, HIGH); delay(1000); digitalWrite(2, LOW); digitalWrite(4, LOW); digitalWrite(6, LOW); delay(1000); //one at at time digitalWrite(2, HIGH); delay(1000); digitalWrite(2, LOW); delay(1000); digitalWrite(4, HIGH); delay(1000); digitalWrite(4, LOW); delay(1000); digitalWrite(6, HIGH); delay(1000); digitalWrite(6, LOW); delay(1000); //two at a time digitalWrite(2, HIGH); digitalWrite(4, HIGH); delay(1000); digitalWrite(2, LOW); digitalWrite(4, LOW); delay(1000); digitalWrite(4, HIGH); digitalWrite(6, HIGH); delay(1000); digitalWrite(4, LOW); digitalWrite(6, LOW); delay(1000); digitalWrite(6, HIGH); digitalWrite(2, HIGH); delay(1000); digitalWrite(6, LOW); digitalWrite(2, LOW); delay(1000); //chasing slow for (i=0; i < 10; i++) { digitalWrite(2, HIGH); digitalWrite(4, LOW); digitalWrite(6, LOW); delay(500); digitalWrite(2, LOW); digitalWrite(4, HIGH); digitalWrite(6, LOW); delay(500); digitalWrite(2, LOW); digitalWrite(4, LOW); digitalWrite(6, HIGH); delay(500); } //all on digitalWrite(2, HIGH); digitalWrite(4, HIGH); digitalWrite(6, HIGH); delay(1000); digitalWrite(2, LOW); digitalWrite(4, LOW); digitalWrite(6, LOW); delay(1000); //one at at time digitalWrite(2, HIGH); delay(500); digitalWrite(2, LOW); delay(500); digitalWrite(4, HIGH); delay(500); digitalWrite(4, LOW); delay(500); digitalWrite(6, HIGH); delay(500); digitalWrite(6, LOW); delay(500); //two at a time digitalWrite(2, HIGH); digitalWrite(4, HIGH); delay(500); digitalWrite(2, LOW); digitalWrite(4, LOW); delay(500); digitalWrite(4, HIGH); digitalWrite(6, HIGH); delay(500); digitalWrite(4, LOW); digitalWrite(6, LOW); delay(500); digitalWrite(6, HIGH); digitalWrite(2, HIGH); delay(500); digitalWrite(6, LOW); digitalWrite(2, LOW); delay(500); //chasing fast for (i=0; i < 50; i++) { digitalWrite(2, HIGH); digitalWrite(4, LOW); digitalWrite(6, LOW); delay(100); digitalWrite(2, LOW); digitalWrite(4, HIGH); digitalWrite(6, LOW); delay(100); digitalWrite(2, LOW); digitalWrite(4, LOW); digitalWrite(6, HIGH); delay(100); } }
true
2f34be69601255fa8e1e0c35b3d4202a110b292c
C++
lisongs1995/leetcode
/54_Spiral_matrix.cpp
UTF-8
1,092
2.765625
3
[]
no_license
class Solution { public: vector<int> spiralOrder(vector<vector<int>>& matrix) { vector<int> ans; if (matrix.size() == 0 || matrix[0].size() == 0) return ans; int n = matrix.size(), m = matrix[0].size(); bool vis[n][m]; memset(vis, 0, sizeof(vis)); int cnt = 1, x, y; ans.pus_back(matrix[x=0][y=0]); vis[x][y] = true; while (cnt < n * m) { while (y + 1 < m && !vis[x][y+1]) { vis[x][y+1] = true; ans.push_back(matrix[x][++y]); cnt++; } while (x + 1 < n && !vis[x+1][y]) { vis[x+1][y] = true; ans.push_back(matrix[x][++y]); cnt++; } while (y - 1 >= 0 && !vis[x][y-1]) { vis[x][y-1] = true; ans.push_back(matrix[x][--y]); cnt++; } while (x - 1 >= 0 && !vis[x-1][y]) {vis[x-1][y] = true; ans.push_back(matrix[x-1][y]); cnt++; } } return ans; } vector<int> spiralOrder1(vector<vector<int>>& matrix) { //https://leetcode.com/problems/spiral-matrix/discuss/20719/0ms-Clear-C%2B%2B-Solution // best answer ever see } };
true
8d9b46757fcf5ee6a54521f3a3a368dc44977497
C++
pchintalapudi/virtual-machine
/platform/memory.cpp
UTF-8
1,278
2.5625
3
[]
no_license
#include "memory.h" using namespace oops::platform; #include "platform_selector.h" #ifdef OOPS_COMPILE_FOR_WINDOWS #include <memoryapi.h> #include <sysinfoapi.h> std::optional<void*> oops::platform::reserve_virtual_memory(std::size_t amount) { auto result = VirtualAlloc(NULL, amount, MEM_RESERVE, PAGE_READWRITE); if (result) { return result; } else { return {}; } } std::optional<void*> oops::platform::commit_virtual_memory(void* reserved, std::size_t amount) { auto result = VirtualAlloc(reserved, amount, MEM_COMMIT, PAGE_READWRITE); if (result) { return result; } else { return {}; } } void oops::platform::decommit_virtual_memory(void* committed, std::size_t amount) { VirtualFree(committed, amount, MEM_DECOMMIT); } void oops::platform::dereserve_virtual_memory(void* reserved) { VirtualFree(reserved, 0, MEM_RELEASE); } const system_info& oops::platform::get_system_info() { static bool initialized = false; static system_info value; if (!initialized) { SYSTEM_INFO storage; GetNativeSystemInfo(&storage); value.page_size = storage.dwAllocationGranularity; value.processor_count = storage.dwNumberOfProcessors; } return value; } #endif
true
61afe16d3900ac6104da0c920c2964412a96b980
C++
Caslship/cs354-assn4
/lightnode.cpp
UTF-8
1,845
3.03125
3
[]
no_license
/* * Assignment #4 * Name: Jason Palacios * UT EID: jap4839 * UTCS: jason777 */ #include "lightnode.h" #include <GL/glut.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <string> // Upon deconstructing the light node, disable the light LightNode::~LightNode(void) { glDisable(light_id); } // Get light type std::string LightNode::getLightType(void) { return light_type; } // Get light id GLenum LightNode::getLightId(void) { return light_id; } // Set light id void LightNode::setId(GLenum light_id) { this->light_id = light_id; } // Set light type void LightNode::setType(std::string light_type) { this->light_type = light_type; } // Given a transform to define camera position, set OpenGL light settings and then enable the light void LightNode::traverseNode(glm::mat4 transform, std::string render_type) { // Have lights always start off at origin glm::vec4 pos(0.0, 0.0, 0.0, 1.0); // Have transformation matrix define where it should be placed pos = transform * pos; GLfloat light_pos[] = { pos.x, pos.y, pos.z, pos.w }; GLfloat light_diffuse_specular[] = { 1.0, 1.0, 1.0, 1.0 }; // Set w component to 0 if we have a directional light if (light_type == "Directional") light_pos[3] = 0.0; // Enable light glEnable(light_id); glLightfv(light_id, GL_POSITION, light_pos); glLightfv(light_id, GL_DIFFUSE, light_diffuse_specular); glLightfv(light_id, GL_SPECULAR, light_diffuse_specular); // Visualize light position glDisable(GL_LIGHTING); glPointSize(20.0); glBegin(GL_POINTS); glColor4f(1.0, 0.95, 0.3, 1.0); glVertex3f(light_pos[0], light_pos[1], light_pos[2]); glColor4f(1.0, 1.0, 1.0, 1.0); glEnd(); glPointSize(1.0); glEnable(GL_LIGHTING); }
true
cd24d6e9db62955c7d23e5ef93da03b5b867e451
C++
wakira/naivetweet
/tweetop.h
UTF-8
1,512
2.921875
3
[]
no_license
#ifndef TWEETOP_H #define TWEETOP_H #include <string> #include <vector> #include "naivedb.h" class TweetLine { public: int64_t publisher; int64_t author; std::string content; int32_t time; TweetLine(const std::string &content,int64_t publisher, int64_t author,int32_t time) { this->content = content; this->publisher = publisher; this->author = author; this->time = time; } }; inline bool operator<(const TweetLine &lval,const TweetLine &rval) { return lval.time >= rval.time; } namespace TweetOp { // userExist(...) note that it returns true even when user is deleted // it's not a bug bool userExist(NaiveDB *db, const char *user); // login(...) returns uid when success, -1 when user is not found, 0 when password is incorrect int64_t login(NaiveDB *db, const char *user, const char *passwd); // registerAccount(...) // call this function after confirming that user does not exist // be careful about these arguments void registerAccount(NaiveDB *db,const char *user, const char *passwd, const char *birthday, const char *name, const char *gender, const char *intro); // follow(...) make uid follow id void follow(NaiveDB *db, int64_t uid, int64_t id); // unfollow(...) make uid unfollow id void unfollow(NaiveDB *db, int64_t uid, int64_t id); // retweet(...) retweet helper void retweet(NaiveDB *db, int64_t uid, const TweetLine &tweet); // newTweet(...) new tweet void newTweet(NaiveDB *db, int64_t uid, const char *content); } #endif // TWEETOP_H
true
8cf01463541cf03d47ff68813990bd6c744d2c12
C++
stonetree/AdmissionPlacement
/cBaseVM.cpp
UTF-8
674
2.546875
3
[]
no_license
#include "StdAfx.h" #include "cBaseVM.h" cBaseVM::cBaseVM(void) { } cBaseVM::~cBaseVM(void) { } cBaseVM::cBaseVM(VMtype _type,double _cpu_required,double _mem_required,double _disk_required) { type = _type; cpu_required = _cpu_required; mem_required = _mem_required; disk_required = _disk_required; } cBaseVM::cBaseVM(const cBaseVM& _base_vm_type) { this->operator=(_base_vm_type); } cBaseVM& cBaseVM::operator=(const cBaseVM& _base_vm_type) { if (this != &_base_vm_type) { type = _base_vm_type.type; cpu_required = _base_vm_type.cpu_required; mem_required = _base_vm_type.mem_required; disk_required = _base_vm_type.disk_required; } return *this; }
true
30205b0564041859cff2a85c0125692702c561c7
C++
pKrumov/SoftUni-C-PB
/8.9.exc Left and Right Sum.cpp
UTF-8
642
3.46875
3
[]
no_license
#include <iostream> #include <cmath> #include <string> using namespace std; int main(){ int numToRead; cin >> numToRead; int leftSum = 0; int rightSum = 0; int num = 0; for(int i = 0; i < numToRead ; i++){ cin >> num; leftSum += num; } for(int i = 0; i < numToRead ; i++){ cin >> num; rightSum += num; } int sum = (leftSum - rightSum) ; if(leftSum == rightSum){ cout << "Yes, sum = " << leftSum << endl; } else if(leftSum != rightSum){ cout << "No, diff = " << abs(sum) << endl; } return 0; }
true
ac5c32c6033ec2c434c878116c6a5c5eb009d247
C++
Perinze/oi
/hdu/37573/g.cpp
UTF-8
770
2.71875
3
[]
no_license
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int maxn = 100010; int n; int bit[maxn]; int query(int i) { int s = 0; for (; i > 0; i -= i & -i) s += bit[i]; return s; } void add(int i, int x) { for (; i <= n; i += i & -i) bit[i] += x; } void add(int l, int r, int x) { add(l, x), add(r + 1, -x); } int main() { while (~scanf("%d", &n)) { if (!n) break; memset(bit, 0, sizeof(bit)); int l, r; for (int i = 0; i < n; i++) { scanf("%d%d", &l, &r); add(l, r, 1); } for (int i = 1; i <= n; i++) { if (i > 1) putchar(' '); printf("%d", query(i)); } puts(""); } return 0; }
true
b44843e67111975b94c917f055f695e4dbe0598e
C++
zlsun/leetcode
/406. Queue Reconstruction by Height/solution.cpp
UTF-8
735
3.40625
3
[ "MIT" ]
permissive
/** 406. Queue Reconstruction by Height Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers (h, k), where h is the height of the person and k is the number of people in front of this person who have a height greater than or equal to h. Write an algorithm to reconstruct the queue. Note: The number of people is less than 1,100. Example Input: [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]] Output: [[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]] **/ #include <iostream> #include "../utils.h" using namespace std; class Solution { public: vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) { } }; int main() { Solution s; return 0; }
true
c5e79ec8d3a375ca70332186a642d59e85a1a886
C++
Rabidza/COS1511
/Assignment1/Question26.cpp
UTF-8
417
3.03125
3
[]
no_license
#include <iostream> using namespace std; int main() { int x = 5; if( x < 3) { cout << "small\n"; } else { if( x < 4) { cout << "medium\n"; } else { if( x < 6) { cout << "large\n"; } else { cout << "giant\n"; } } } }
true
7705c6fbd6fcba8e820cb365cb6b8eca7992c7da
C++
liretta/Students
/Functions.hpp
WINDOWS-1251
8,617
3.375
3
[]
no_license
#include <iostream> #include <time.h> #include <iomanip> #include <stdio.h> #include <conio.h> #define NAME_SIZE 15 //size student's name and surname #define MARK_COUNT 5 //count of mark using namespace std; struct Student { char Name[NAME_SIZE]; char Surname[NAME_SIZE]; unsigned int Age; unsigned int Mark[MARK_COUNT]; double Averadge; }; void InitStudent(int nSize, Student *pStud) { const char *sNames[] = { "Bill", "Jhon", "Julia", "Pavel", "Alisa", "Vladimir", "Sergey" }; const int nNameSize = sizeof(sNames) / sizeof(char *); int randNameSize[nNameSize]; for (int i = 0; i <nNameSize; ++i) randNameSize[i] = strlen(sNames[i]) + 1; const char *sSurNames[] = { "Clinton", "Linkoln", "Cherchel", "Ivanov", "Petrov", "Sidorov", "Tolkien" }; const int nSurNameSize = sizeof(sSurNames) / sizeof(char *); int randSurNameSize[nSurNameSize]; for (int i = 0; i <nSurNameSize; ++i) randSurNameSize[i] = strlen(sSurNames[i]) + 1; int numbName; double sumMarks = 0; for (int i = 0; i < nSize; ++i) { //create random name numbName = rand() % nNameSize; //randNameSize = strlen(sNames[numbName])+1; memcpy(pStud[i].Name, sNames[numbName], randNameSize[numbName]); //create random surname numbName = rand() % nSurNameSize; //randNameSize = strlen(sSurNames[numbName])+1; memcpy(pStud[i].Surname, sSurNames[numbName], randSurNameSize[numbName]); //create random age pStud[i].Age = (rand() % 10) + 16; //create random marks for (int j = 0; j < MARK_COUNT; ++j) { pStud[i].Mark[j] = rand() % 5 + 1; sumMarks += pStud[i].Mark[j]; } //create average marks pStud[i].Averadge = sumMarks / MARK_COUNT; sumMarks = 0; } } void ShowStudent(int nSize, Student *pStud) { cout << setw(3) << "#"; cout << setw(NAME_SIZE + 1) << "Name"; cout << setw(NAME_SIZE + 1) << "Sourname"; cout << setw(7) << "Age"; cout << setw(MARK_COUNT) << "Makr"; cout << setw(20) << "Averadge makr" << endl; for (int i = 0; i < nSize; ++i) { cout << setw(3) << i + 1; cout << setw(NAME_SIZE + 1) << pStud[i].Name; //cout.setf(ios::left); cout << setw(NAME_SIZE + 1) << pStud[i].Surname; cout << setw(7) << pStud[i].Age; //cout.setf(ios::right); for (int j = 0; j < MARK_COUNT; ++j) cout << setw(2) << pStud[i].Mark[j]; //cout.setf(ios::right); cout << setw(5) << pStud[i].Averadge << endl; } } void sortStudentByName(int nSize, Student *pAr) { char *nMin = new char[300]; int iMinInd; Student pTemp; for (int i = 0; i < nSize; ++i) { memcpy(nMin, pAr[i].Name, sizeof(Student)); iMinInd = i; for (int j = i + 1; j < nSize; ++j) if (_stricmp(pAr[j].Name, nMin) < 0) { memcpy(nMin, pAr[j].Name, sizeof(Student)); iMinInd = j; } pTemp = pAr[i]; pAr[i] = pAr[iMinInd]; pAr[iMinInd] = pTemp; } delete[] nMin; } void sortStudentBySurname(int nSize, Student *pAr) { char *nMin = new char[300]; int iMinInd; Student pTemp; for (int i = 0; i < nSize; ++i) { memcpy(nMin, pAr[i].Surname, sizeof(Student)); iMinInd = i; for (int j = i + 1; j < nSize; ++j) if (_stricmp(pAr[j].Surname, nMin) < 0) { memcpy(nMin, pAr[j].Surname, sizeof(Student)); iMinInd = j; } pTemp = pAr[i]; pAr[i] = pAr[iMinInd]; pAr[iMinInd] = pTemp; } delete[] nMin; } void sortStudentByAge(int nSize, Student *pAr) { int iMinInd; double nMin; Student pTemp; for (int i = 0; i < nSize; ++i) { nMin = pAr[i].Age; iMinInd = i; for (int j = i + 1; j < nSize; ++j) if (pAr[j].Age<nMin) { nMin = pAr[j].Age; iMinInd = j; } pTemp = pAr[i]; pAr[i] = pAr[iMinInd]; pAr[iMinInd] = pTemp; } } void sortStudentByMarks(int nSize, Student *pAr) { double nMin; int iMinInd; Student pTemp; for (int i = 0; i < nSize; ++i) { nMin = pAr[i].Averadge; iMinInd = i; for (int j = i + 1; j < nSize; ++j) if (pAr[j].Averadge<nMin) { nMin = pAr[j].Averadge; iMinInd = j; } pTemp = pAr[i]; pAr[i] = pAr[iMinInd]; pAr[iMinInd] = pTemp; } } void newStudent(int nSize, Student *pAr) { system("cls"); cout << "Create new student" << endl; cin.getline(pAr[nSize - 1].Name, NAME_SIZE + 1); cin.sync();//clear threads from enter //create new name cout << "Enter name of new student (max - 15 symbols)" << endl; cin.getline(pAr[nSize - 1].Name, NAME_SIZE + 1); cout << "Enter surname of new student (max - 15 symbols)" << endl; cin.getline(pAr[nSize - 1].Surname, NAME_SIZE + 1); unsigned int ageBuff; cout << "Enter age of new student (the integer number from 16 to 60)" << endl; while (!(cin >> ageBuff) || cin.get() != '\n' || ageBuff <= 16 || ageBuff >= 60) // { cin.clear(); cin.ignore(); cout << "Invalid Input!" << endl; cout << "enter the integer number from 16 to 60: "; }; pAr[nSize - 1].Age = ageBuff; int markBuff; double Sum = 0; for (int i = 0; i < MARK_COUNT; ++i) { cout << "Enter " << i + 1 << " makr of new student (the integer number from 1 to 5)" << endl; while (!(cin >> markBuff) || cin.get() != '\n' || markBuff < 1 || markBuff > 5) // { cin.clear(); cin.ignore(); cout << "Invalid Input!" << endl; cout << "enter the integer number from 1 to 5: "; } pAr[nSize - 1].Mark[i] = markBuff; Sum += pAr[nSize - 1].Mark[i]; } pAr[nSize - 1].Averadge = Sum / MARK_COUNT; } //void deleteStudent(int nSize, Student pStud2) //{ // system("cls"); // // // cout << "Create new student" << endl; // cin.getline(pAr[nSize - 1].Name, NAME_SIZE + 1); // // // cin.sync();// // // //create new name // cout << "Enter name of new student (max - 15 symbols)" << endl; // cin.getline(pAr[nSize - 1].Name, NAME_SIZE + 1); // // cout << "Enter surname of new student (max - 15 symbols)" << endl; // cin.getline(pAr[nSize - 1].Surname, NAME_SIZE + 1); // // unsigned int ageBuff; // cout << "Enter age of new student (the integer number from 16 to 60)" << endl; // while (!(cin >> ageBuff) || cin.get() != '\n' || ageBuff <= 16 || ageBuff >= 60) // // { // cin.clear(); // ( ) // cin.ignore(); // \n ( , ) // cout << "Invalid Input!" << endl; // cout << "enter the integer number from 16 to 60: "; // }; // // pAr[nSize - 1].Age = ageBuff; // // int markBuff; // double Sum = 0; // for (int i = 0; i < MARK_COUNT; ++i) // { // cout << "Enter " << i + 1 << " makr of new student (the integer number from 1 to 5)" << endl; // while (!(cin >> markBuff) || cin.get() != '\n' || markBuff < 1 || markBuff > 5) // // { // cin.clear(); // ( ) // cin.ignore(); // \n ( , ) // cout << "Invalid Input!" << endl; // cout << "enter the integer number from 1 to 5: "; // } // pAr[nSize - 1].Mark[i] = markBuff; // Sum += pAr[nSize - 1].Mark[i]; // } // // pAr[nSize - 1].Averadge = Sum / MARK_COUNT; //} int searchByName(int nSize, Student *pStud, Student *pBuff, int *nIndex, char *cBuff) { int nSize_search = 0; for (int i = 0; i < nSize; ++i) { if (_stricmp(pStud[i].Name, cBuff) == 0) { memcpy(pBuff[nSize_search].Name, pStud[i].Name, sizeof(Student)); memcpy(pBuff[nSize_search].Surname, pStud[i].Surname, sizeof(Student)); pBuff[nSize_search].Age = pStud[i].Age; for (int j = 0; j < MARK_COUNT; ++j) pBuff[nSize_search].Mark[j] = pStud[i].Mark[j]; pBuff[nSize_search].Averadge = pStud[i].Averadge; nIndex[nSize_search] = i; nSize_search += 1; } } return nSize_search; } void deleteStudent(int Index, int *nIndex, Student *pStud2, int nSize2) { Index = nIndex[Index]; for (int i = Index;i < nSize2; ++i) { memcpy(pStud2[i].Name, pStud2[i + 1].Name, sizeof(Student)); memcpy(pStud2[i].Surname, pStud2[i + 1].Name, sizeof(Student)); pStud2[i].Age = pStud2[i + 1].Age; for (int j = 0;j < MARK_COUNT;++j) pStud2[i].Mark[j] = pStud2[i + 1].Mark[j]; pStud2[i].Averadge = pStud2[i + 1].Averadge; } nSize2--; } void Mem() { if (_CrtDumpMemoryLeaks()) cout << "Warning! Memory leaks!!" << endl; else cout << "Memory ok :-)" << endl; }
true