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 |
---|---|---|---|---|---|---|---|---|---|---|---|
200088635e14a884674f08ad75fe096a46f58de1
|
C++
|
Jerrydepon/C_plus_plus_Practice
|
/Chapter 14/14-3/main.cpp
|
UTF-8
| 473 | 3.59375 | 4 |
[] |
no_license
|
#include <iostream>
using namespace std;
int numChars(char, char[], int);
int main()
{
char array[] = "adbcdddef";
cout << "The letter d appears " << numChars('d', array, 0) << " times.\n";
return 0;
}
int numChars(char search, char str[], int subscript)
{
if (str[subscript] == '\0')
return 0;
if (str[subscript] == search)
return (1 + numChars(search, str, subscript + 1));
else
return (numChars(search, str, subscript + 1));
}
| true |
78cbdc5192bd8517a3cf9641d6f0b659b3d58bdb
|
C++
|
Ashish-k-1997/C-ENCRYPT-DECRYPT
|
/main.cpp
|
UTF-8
| 1,972 | 3.21875 | 3 |
[] |
no_license
|
#include <iostream>
#include <conio.h>
#include <fstream>
#include <string.h>
#include <stdlib.h>
using namespace std;
char pass[50];
void encrypt()
{
char ch;
int z[50], i;
ifstream ifile;
ofstream ofile;
ifile.open("input.txt");
ofile.open("output.txt");
cout << "\n\n\tPASSWORD CAN ONLY BE a-z WITHOUT SPACES" ;
cout << "\n\n\tENTER PASSWORD : " ;
cin>>pass;
for(int i=0; i<strlen(pass);i++)
{
z[i]=pass[i]-96;
}
system("cls");
cout<<"\n\n\n\n\n\t\t\t\t\t PLEASE WAIT.";
i=0;
while(ifile.get(ch))
{
if(i==strlen(pass))
i=0;
ofile.put(ch+z[i]);
i++;
}
system("cls");
cout<<"\n\n\n\n\n\t\t\t\t\tENCRYPT DONE, PRESS ANY KEY.";
getch();
ifile.close();
ofile.close();
}
void decrypt()
{
char ch;
int z[50], i;
ifstream ifile;
ofstream ofile;
ifile.open("input.txt");
ofile.open("output.txt");
cout << "\n\n\tPASSWORD CAN ONLY BE a-z WITHOUT SPACES" ;
cout << "\n\n\tENTER PASSWORD : " ;
cin>>pass;
for(int i=0; i<strlen(pass);i++)
{
z[i]=pass[i]-96;
}
system("cls");
cout<<"\n\n\n\n\n\t\t\t\t\t PLEASE WAIT.";
i=0;
while(ifile.get(ch))
{
if(i==strlen(pass))
i=0;
ofile.put(ch-z[i]);
i++;
}
system("cls");
cout<<"\n\n\n\n\n\t\t\t\t\tDECRYPT DONE, PRESS ANY KEY.";
getch();
ifile.close();
ofile.close();
}
int main()
{
int choice;
while(1)
{
system("cls");
cout << "\n\n\n\t\t0. To Exit" ;
cout << "\n\t\t1. To Encrypt" ;
cout << "\n\t\t2. TO Decrypt" ;
cout << "\n\n\t\t Your choice : " ;
cin>>choice;
system("cls");
switch(choice)
{
case 0 : exit(0); break;
case 1 : encrypt(); break ;
case 2 : decrypt(); break;
default : system("cls");
cout<<"\n\n\n\t\t\tWRONG CHOICE";
}
}
return 0;
}
| true |
1f38188a365b6d34146e85380d30a2b0aaf9b051
|
C++
|
Voyager2718/Bug-Analyser
|
/src/Report.cpp
|
UTF-8
| 944 | 2.984375 | 3 |
[] |
no_license
|
#include<memory>
#include<string>
#include<vector>
#include<map>
#include"Report.h"
using std::string;
using std::map;
using std::vector;
using std::shared_ptr;
void Report::add_report(map< string, string > report){
reports.push_back(report);
}
void Report::add_reports(vector< map< string, string > > report) {
this->reports.insert(this->reports.end(), reports.begin(), reports.end());
}
vector< map < string, string> > Report::get_reports() const {
return reports;
}
map < string, string > Report::get_report(int index) const {
return reports[index];
}
Report Report::operator+(const Report& report){
Report temp;
temp.add_reports(this->reports);
temp.add_reports(report.get_reports());
return report;
}
void Report::merge_reports(shared_ptr< Report > reports){
vector< map < string, string> >temp = reports->get_reports();
this->reports.insert(this->reports.end(), temp.begin(), temp.end());
}
| true |
ddd7108525f6115fa22fe5f5ebf5b8e0f8c47b82
|
C++
|
tpl2go/ProjectEuler
|
/src/12.cpp
|
UTF-8
| 2,897 | 3.765625 | 4 |
[] |
no_license
|
/*
* 12.cpp
*
* Created on: Jul 9, 2016
* Author: tpl
*/
# include <vector>
# include <math.h>
# include <iostream>
using namespace std;
#include <stdexcept>
//The sequence of triangle numbers is generated by adding the natural numbers.
//So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28.
//The first ten terms would be:
//
//1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
//
//Let us list the factors of the first seven triangle numbers:
//
// 1: 1
// 3: 1,3
// 6: 1,2,3,6
// 10: 1,2,5,10
// 15: 1,3,5,15
// 21: 1,3,7,21
// 28: 1,2,4,7,14,28
//
//We can see that 28 is the first triangle number to have over five divisors.
//
//What is the value of the first triangle number to have over five hundred divisors?
// Generate triangle numbers
// deprecated
long triangle_number(int n) {
long sum=0;
for (int i=1; i<(n+1); i++) {
sum += i;
}
return sum;
}
class TriangleNumberStream {
// generates a stream of triangle numbers
private:
long tn=0;
int index=0;
public:
long next();
};
long TriangleNumberStream::next() {
index++;
tn +=index;
return tn;
}
class PrimeTable {
// Imagine the primetable object as an infinite table of prime numbers
// Generate a table of primes lazily
private:
vector<int> primes;
bool isPrime(int);
int nextPrime();
public:
int get(int);
};
int PrimeTable::get(int n) {
/**
* n: index of prime number
* n=0 : 2
* n=1 : 3
* n=2 : 4
*/
if (primes.size()==0) {
primes.push_back(2);
}
if (n<0) {
throw std::invalid_argument( "received negative value" );
}
while ((n+1)>primes.size()) {
nextPrime();
}
return primes.at(n);
}
bool PrimeTable::isPrime(int n){
for (int i=0; i<primes.size(); i++){
if (n%primes[i] == 0) {
return false;
}
}
return true;
}
int PrimeTable::nextPrime() {
// finding the next prime
int cur;
if (primes.back() == 2) {
cur = primes.back() + 1;
}
else {
cur = primes.back() + 2;
}
while (!this->isPrime(cur)) {
cur+=2;
}
primes.push_back(cur);
return cur;
}
vector<int> exp_list(PrimeTable& ps, long tn) {
// construct a list of exponents
vector<int> exp;
int p = 0; // prime being tested
long stop = sqrt(tn) + 1;
int i=-1;
while (p < stop){
i++;
int n = tn;
int count = 0;
p = ps.get(i);
while (n%p==0) {
count++;
n = n/p;
}
exp.push_back(count);
}
return exp;
}
int num_divisors(vector<int> exp) {
// multiply exponent list
int num = 1;
for (int i=0; i<exp.size(); i++){
if (exp[i]>0) {
num *= (exp[i]+1);
}
}
return num;
}
long problem12() {
// fastest way to count number of divisors is to
// multiply the exponents in the prime factorization
PrimeTable ps = PrimeTable();
TriangleNumberStream tns = TriangleNumberStream();
int num = 0;
long tn = 0;
while(num < 501){
tn = tns.next();
vector<int> exp = exp_list(ps,tn);
num = num_divisors(exp);
}
return tn;
}
| true |
1ace25fb2f1e157d918a5f698a8f5a77d95c9ed0
|
C++
|
pedroleite21/20162
|
/AulaSobrecarga/circulo.cpp
|
UTF-8
| 1,675 | 3.390625 | 3 |
[] |
no_license
|
#include "circulo.h"
float Circulo::area_circulo() {
float area1;
area1 = 3.14 * (raio * raio);
return area1;
}
float Circulo::distancia_centros(Circulo outro) {
float x2, y2, Xquadr, Yquadr;
outro.getCentro(x2,y2);
Xquadr = (x2 - x) * (x2 - x);
Yquadr = (y2 - x) * (y2 - y);
return sqrt(Xquadr + Yquadr);
}
float Circulo::circunferencia() {
float circun;
circun = 2 * 3.14 * raio;
return circun;
}
Circulo::Circulo() {
x = y = 0;
raio = 1;
}
Circulo::Circulo(float _raio) {
x = y = 0;
raio = _raio;
}
Circulo::Circulo(float _x, float _y) {
x = _x;
y = _y;
raio = 1;
}
Circulo::Circulo(float _x, float _y, float _raio) {
x = _x;
y = _y;
raio = _raio;
}
float Circulo::getRaio() {
return raio;
}
void Circulo::setRaio(float _raio) {
raio = _raio;
}
float Circulo::aumentar_raio(int percentual) {
int aumentar;
aumentar = 100 + percentual;
raio = (raio * aumentar) / 100;
return raio;
}
void Circulo::definir_centro(float _x, float _y) {
x = _x;
y = _y;
}
void Circulo::getCentro (float &_x, float &_y) {
_x = x;
_y = y;
}
void Circulo::imprimir_raio() {
cout << "O tamanho do raio é: " << raio << endl;
}
void Circulo::imprimir_centro() {
cout << "O centro está em: [" << x << ", " << y << "] " << endl;
}
void Circulo::imprimir_area() {
cout << "A área é de: " << area_circulo() << endl;
}
void Circulo::imprimir_distancia(Circulo outro) {
cout << "A distância entre os dois círculos é de: " << distancia_centros(outro) << endl;
}
string Circulo::toString() {
stringstream tmpss;
string tmpstr;
tmpss << "px:" << this->x << ";px:" << this->y << ";r:" << this->raio;
tmpss >> tmpstr;
return tmpstr;
}
| true |
abea73ac712caaadaf6645238b3a1f654d3c7c0a
|
C++
|
roberchenc/homework_oop
|
/homework_oop/oop2_queue.cpp
|
GB18030
| 1,261 | 3.625 | 4 |
[] |
no_license
|
#include "oop2_queue.h"
template <class T>
MyQueue<T>::MyQueue()
{
index = 0;
tail = 0;
size = 10;
header = new T[size];
}
template <class T>
int MyQueue<T>::getElementNum()
{
if ((tail+1) % size == index)
return size;
else
return (tail-index+size) % size;
}
template <class T>
void MyQueue<T>::push(T t)
{
if (getElementNum() == size)
{
getBigSpace();
}
header[tail] = t; //TҪʵ
tail = (tail + 1) % size;
}
template <class T>
T& MyQueue<T>::pop()
{
T temp = *(header + index); //TҪʵ
index = (index+1) % size;
return temp;
}
template <class T>
T& MyQueue<T>::getElement()
{
return *(header+index);
}
template <class T>
void MyQueue<T>::getBigSpace()
{
int newSize = size * 2;
T *temp = new T[newSize];
int k = 0;
for(int i=index; i != tail; i++)
{
i = i % size;
temp[k++] = header[i];
}
delete [] header;
header = temp;
temp = NULL;
size = newSize;
index = 0;
tail = k;
}
template <class T>
MyQueue<T>::~MyQueue()
{
delete []header;
}
int main()
{
MyQueue<int> q;
for(int i=0; i<20; i++)
q.push(i);
cout << q.getElement() << endl;
q.pop();
cout << q.getElementNum() << endl;
cout << q.getElement() << endl;
getchar();
}
| true |
45acb349a95c4e531131f0cf898c463eced5fcd8
|
C++
|
TurtleMan64/SAB2
|
/NewSonicThing/src/menu/Button.cpp
|
UTF-8
| 3,839 | 2.875 | 3 |
[] |
no_license
|
#include <string>
#include "button.hpp"
#include "../engineTester/main.hpp"
#include "../fontMeshCreator/guitext.hpp"
#include "../fontMeshCreator/fonttype.hpp"
#include "../guis/guimanager.hpp"
#include "../guis/guiimage.hpp"
#include "../renderEngine/display.hpp"
/*
Basic button with normal/highlight texture and text
* label: text to display on button
* posX, posY: coordinates to center the button, where
(0,0) is top-left, and (1,1) is bottom-right
* scaleX, scaleY: scale for the button, where
1.0f is the whole screen
* visible: draw the button after creating it
*/
Button::Button(std::string label, FontType* font, GLuint texture, GLuint highlight, float posX, float posY, float scaleX, float scaleY, bool visible)
{
this->text = new GUIText(label, scaleY, font, posX, posY, 4, true); INCR_NEW("GUIText");
this->texture = new GuiImage(texture, posX, posY, scaleX, scaleY, 0); INCR_NEW("GuiImage");
this->textureHighlight = new GuiImage(highlight, posX, posY, scaleX, scaleY, 0); INCR_NEW("GuiImage");
this->textIsLeftAnchored = false;
this->scaleX = scaleX;
setVisible(visible);
}
Button::Button(std::string label, FontType* font, GLuint textureId, GLuint highlight, float posX, float posY, float scaleX, float scaleY, bool visible, bool leftAnchored)
{
float aspectRatio = Display::ASPECT_RATIO;
anchorOffset = 0.02f*aspectRatio;
if (!leftAnchored)
{
text = new GUIText(label, scaleY, font, posX, posY, 4, true); INCR_NEW("GUIText");
}
else
{
text = new GUIText(label, scaleY, font, posX - scaleX/2 + anchorOffset, posY, 3, true); INCR_NEW("GUIText");
}
this->scaleX = scaleX;
textIsLeftAnchored = leftAnchored;
texture = new GuiImage(textureId, posX, posY, scaleX, scaleY, 0); INCR_NEW("GuiImage");
textureHighlight = new GuiImage(highlight, posX, posY, scaleX, scaleY, 0); INCR_NEW("GuiImage");
setVisible(visible);
}
Button::~Button()
{
this->text->deleteMe(); delete this->text; INCR_DEL("GUIText");
delete texture; INCR_DEL("GuiImage");
delete textureHighlight; INCR_DEL("GuiImage");
}
void Button::generateText(std::string newText)
{
float textScale = text->getFontSize();
FontType* textFont = text->getFont();
float textPosX = text->position.x;
float textPosY = text->position.y;
text->deleteMe(); delete text; INCR_DEL("GUIText");
text = nullptr;
if (textIsLeftAnchored)
{
text = new GUIText(newText, textScale, textFont, textPosX, textPosY, 3, true); INCR_NEW("GUIText");
}
else
{
text = new GUIText(newText, textScale, textFont, textPosX, textPosY, 4, true); INCR_NEW("GUIText");
}
}
void Button::generateText(std::string newText, bool darkText)
{
generateText(newText);
if (darkText)
{
text->color.set(0.5f, 0.5f, 0.5f);
}
}
void Button::setPos(float xPos, float yPos)
{
if (textIsLeftAnchored)
{
text->getPosition()->x = xPos - scaleX/2 + anchorOffset;
text->getPosition()->y = yPos;
}
else
{
text->getPosition()->x = xPos;
text->getPosition()->y = yPos;
}
texture->setX(xPos);
texture->setY(yPos);
textureHighlight->setX(xPos);
textureHighlight->setY(yPos);
}
void Button::setVisible(bool isVisible)
{
visible = isVisible;
text->visible = isVisible;
if (!isVisible)
{
GuiManager::removeImageToRender(texture);
visibleHighlight = false;
}
else
{
GuiManager::addImageToRender(texture);
}
}
void Button::setHighlight(bool isHighlight)
{
if (isHighlight)
{
visibleHighlight = true;
texture->alpha = 1.0f;
}
else
{
visibleHighlight = false;
texture->alpha = 0.35f;
}
}
GUIText* Button::getText()
{
return text;
}
| true |
ccc546f9233137b350ec243d0f887096a0c74cd2
|
C++
|
zxc0115/parallel_project
|
/project/openMP_inv.cpp
|
UTF-8
| 2,152 | 3.40625 | 3 |
[] |
no_license
|
#include <iostream>
#include <cmath>
#include <algorithm>
#include "omp.h"
using namespace std;
/** matrix inverse */
void inv(float** matrix, int row_dim, int col_dim,float** inverse)
{
// check square matrix
if(col_dim == row_dim)
{
for(int j = 0;j < col_dim; j++)
{
//find max magnitude
float tmp = 0;
int p = -1;
for(int i = j; i < row_dim; i++)
{
if(abs(matrix[i][j]) > tmp)
{
tmp = abs(matrix[i][j]);
p = i;
}
}
// have zero row
if(p == -1)
{
cout << "it's singular";
return;
}
if( j!=p )
{
swap(matrix[j],matrix[p]);
swap(inverse[j],inverse[p]);
}
//row operation
for (int i = 0; i < row_dim; i++)
{
if (i == j)
{
float pivot = matrix[i][j];
#pragma omp parallel for
for (int k =0;k < col_dim; k++)
{
inverse[i][k] /= pivot;
matrix[i][k] /= pivot;
}
matrix[i][j]=1;
}
else
{
float pivot = matrix[i][j]/matrix[j][j];
#pragma omp parallel for
for (int k = 0;k < col_dim; k++)
{
matrix[i][k] -= (pivot * matrix[j][k]);
inverse[i][k] -= (pivot * inverse[j][k]);
}
matrix[i][j]=0;
}
}
}
}
else
{
cout << "it isn't sqare matrix";
return;
}
}
/** matrix print */
void print(float** matrix, int row_dim, int col_dim)
{
for(int i=0; i < row_dim; i++)
{
for(int j=0; j < row_dim; j++)
{
cout << matrix[i][j]<<" ";
}
cout<<endl;
}
}
int main ()
{
//random seed
srand(0);
//set dimention
int row_dim = 2000;
int col_dim = 2000;
//initial array
float** inverse = new float* [row_dim];
float** result = new float* [row_dim];
for(int i = 0; i < row_dim; i++)
{
inverse[i] = new float [col_dim];
result[i] = new float [col_dim];
for(int j = 0;j < col_dim; j++)
{
inverse[i][j] = float(rand()%9);
result[i][j] = (i == j)?1.0f:0.0f;
}
}
//check input
//print(inverse, row_dim, col_dim);
cout << "----------------------\n";
//test inverse
inv(inverse, row_dim, col_dim, result);
//check result
//print(result, row_dim, col_dim);
return 0;
}
| true |
3ef25754002d605b766bfaf7e8e8ac06a8ad82c3
|
C++
|
whatiskeptiname/Air-Play
|
/Air-Play.ino
|
UTF-8
| 2,858 | 3.203125 | 3 |
[] |
no_license
|
#define trig1 22 // pin declaration for ultrasonic sensor 1
#define echo1 23
#define trig2 24 // pin declaration for ultrasonic sensor 2
#define echo2 25
#define trig3 26 // pin declaration for ultrasonic sensor 3
#define echo3 27
#define trig4 28 // pin declaration for ultrasonic sensor 4
#define echo4 29
#define trig5 30 // pin declaration for ultrasonic sensor 5
#define echo5 31
#define buzz 11 // pin declaration for buzzer
int s1, s2, s3, s4, s5; // proximity from respective ultrasonic sensor (s1 - s5)
void setup()
{
Serial.begin(9600); // set up serial communication at 9600 baud
// I/O pin declaration
pinMode(trig1, OUTPUT);
pinMode(echo1, INPUT);
pinMode(trig2, OUTPUT);
pinMode(echo2, INPUT);
pinMode(trig3, OUTPUT);
pinMode(echo3, INPUT);
pinMode(trig4, OUTPUT);
pinMode(echo4, INPUT);
pinMode(trig5, OUTPUT);
pinMode(echo5, INPUT);
pinMode(buzz, OUTPUT);
}
int proximity(int trig, int echo) // function to calculate the proximity of an object from a ultrasonic sensor
{
digitalWrite(trig, LOW);
delay(50);
digitalWrite(trig, HIGH);
delay(10);
digitalWrite(trig, LOW);
unsigned long duration = pulseIn(echo, HIGH);
return int(duration * 0.034 / 2);
}
int base_frequency(int s1, int s2, int s3, int s4, int s5, int s)
{// function to select the base frequency based on the position of sensor with lowest proximity
int adf = 0; // base frequency to play when individual ultrasonic sensor is trigerred without considering the proximity value
if (s == s1) adf = 400;
else if (s == s2) adf = 600;
else if (s == s3) adf = 800;
else if (s == s4) adf = 1000;
else if (s == s5) adf = 1200;
else (s == 0);
return adf;
}
void play(int s, int adf) // add proximity factor to base frequency and play the tone at that frequency
{
if (s >= 5 && s < 10)
{
tone(buzz, adf); // play tone at adf frequency for 300 milliseconds
delay(300);
noTone(buzz); // stop playing the tone
}
else if (s >= 10 && s < 15)
{
tone(buzz, adf - 50);
delay(300);
noTone(buzz);
}
else if (s >= 15 && s < 20)
{
tone(buzz, adf - 100);
delay(300);
noTone(buzz);
}
else if (s >= 20 && s < 25)
{
tone(buzz, adf - 150);
delay(300);
noTone(buzz);
}
else tone(buzz, 0);
}
void loop()
{
// get proximity from respective ultrasonic sensor
s1 = proximity(trig1, echo1);
s2 = proximity(trig2, echo2);
s3 = proximity(trig3, echo3);
s4 = proximity(trig4, echo4);
s5 = proximity(trig5, echo5);
int s = min(min(min(min(s1, s2), s3), s4), s5); // get minimum of all the proximity values
int adf = base_frequency(s1, s2, s3, s4, s5, s); // calculate the base frequency
Serial.println("s = " + String(s) + " and adf = " + String(adf)); // print s and adf to serial monitor
play(s, adf); // play the tone
}
| true |
95eeaea151c13b97b5bb1addb6503302da791fb6
|
C++
|
dackerson/project-absent-lambda
|
/src/mesh.h
|
UTF-8
| 2,213 | 2.828125 | 3 |
[] |
no_license
|
// 3D mesh code from Figs. 6.13, 6.15, 6.78 on pp.296, 298, 348
// of Hill, F.S. "Computer Graphics Using
// OpenGL", 2nd edition, Prentice Hall, NJ, 2001.
// Modified Oct. 2006 by B.G. Nickerson.
#include<GL/glut.h>
#include<math.h>
#include <iostream>
#include <fstream>
using namespace std;
//@@@@@@@@@@@@@@@@@@ VertexID class @@@@@@@@@@@@@@@@
class VertexID
{
public:
int vertIndex; // index of this vertex in the vertex list
int normIndex; // index of this vertex's normal
};
//@@@@@@@@@@@@@@@@@@ Face class @@@@@@@@@@@@@@@@
class Face
{
public:
int nVerts; // number of vertices in this face
VertexID * vert; // the list of vertex and normal indices
Face(){nVerts = 0; vert = NULL;} // constructor
~Face(){delete[] vert; nVerts = 0;} // destructor
};
//###################### Mesh #######################
class Mesh{
private:
int numVerts; // number of vertices in the mesh
Point3* pt; // array of 3D vertices
int numNormals; // number of normal vectors for the mesh
Vector3 *norm; // array of normals
int numFaces; // number of faces in the mesh
Face* face; // array of face data
public:
Mesh(); // constructor
// ~Mesh(); // destructor
void draw();
int isEmpty(){ return (numVerts = 0) || (numFaces == 0) || (numNormals == 0);}
void makeEmpty() { numVerts = numFaces = numNormals = 0;}
Vector3 newell4(int indx[]);
Vector3 newell3(int indx[]);
void makeSurfaceMesh(); // Make a surface mesh
void makePrism(PolyLine P, float H);
void drawReticle();
void makeShip(); //Creates the mesh for a Cretaceous class fighter
void drawCylinder();
double X(double u, double v); // Parametric definition
double Y(double u, double v); // of a surface in terms
double Z(double u, double v); // of its parametric components
double nx(double u, double v); // Parametric definition
double ny(double u, double v); // of a surface normal in terms
double nz(double u, double v); // of its parametric components
};
| true |
b62f82dbdb64192e136c9910934a5f910d5c8029
|
C++
|
makredzic/strukturepodataka-zadaca2
|
/zadatak1/main.cpp
|
UTF-8
| 1,900 | 3.609375 | 4 |
[] |
no_license
|
#include "stack_arr.hpp"
#include "stack_interface.h"
#include "stack_linked.hpp"
template<typename T>
static void printDim(const StackArr<T>& s) {
std::cout << "Capacity: " << s.capacity() << std::endl;
std::cout << "Size: " << s.size() << std::endl;
}
template <typename T>
static void fillNumeric(stack_interface<T>* const stack) {
for (T i = 0; i < 50; i+=3) stack->push(i);
}
int main() {
StackArr<int> stackArr;
StackLinked<int> stackLinked;
fillNumeric(&stackArr);
fillNumeric(&stackLinked);
std::cout << "Top Elements\n";
std::cout << "Arr: " << stackArr.top() << std::endl;
std::cout << "Linked: " << stackLinked.top() << std::endl;
std::cout << "\nAll the elements\n";
std::cout << "Arr: " << stackArr;
std::cout << "Linked: " << stackLinked;
stackArr.push(1);
stackArr.push(3);
stackArr.push(5);
stackArr.push(7);
stackLinked.push(1);
stackLinked.push(3);
stackLinked.push(5);
stackLinked.push(7);
std::cout << "\nStack Copy\n";
StackArr<int> stackArrCpy{stackArr};
StackLinked<int> stackLinkedCpy{stackLinked};
std::cout << "Arr: " << stackArrCpy;
std::cout << "Linked: " << stackLinkedCpy;
StackArr<double> test1;
StackLinked<double> test2;
fillNumeric(&test1);
fillNumeric(&test2);
std::cout<< "\nMoved Stack\n";
auto arr{std::move(test1)};
auto linked{std::move(test2)};
std::cout << "Arr: " << arr;
std::cout << "Linked: " << linked;
std::cout << "Empty moved stacks"<<std::endl;
std::cout << "Arr: " << arr;
std::cout << "Linked: " << arr;
stackArr = StackArr<int>{};
fillNumeric(&stackArr);
stackLinked = StackLinked<int>{};
fillNumeric(&stackLinked);
StackArr<int> a;
StackLinked<int> b;
a = stackArr;
b = std::move(stackLinked);
StackLinked<int> b1;
b1.push(55);
if (a == stackArr) std::cout << "\na == stackArr" << std::endl;
if (b != b1) std::cout << "b != stackLinked" << std::endl;
return 0;
}
| true |
5c82762d663c99e2651cb6c05677cbf2927a21f7
|
C++
|
0702Keeprunning/C_Basic_knowledge
|
/数据类型/数据类型/008 new操作符.cpp
|
GB18030
| 855 | 3.671875 | 4 |
[] |
no_license
|
//#include <iostream>
//#include <string>
//using namespace std;
//
////newĻ
//int *func()
//{
// //ڶһ
// //صǸ͵ָ
// int *p = new int(10);
// return p;
//}
//void test01()
//{
// int *p = func();
// cout << *p << endl;
// cout << *p << endl;
// cout << *p << endl;
// //ɳԱͷ delet
// delete p;
// //cout << *p << endl; //ڴѾͷţٴηʻᱨ
//
//}
//
////ڶnewһ
//void test02()
//{
// //ڶ
// int *arr = new int[10];
// for (int i = 0; i < 10; i++)
// {
// arr[i] = i + 100;
// cout << arr[i] << endl;
// }
// //ͷŶ עͷҪ
// delete[] arr;
//}
//int main()
//{
// test01();
// test02();
// system("pause");
// return 0;
//}
| true |
292c96b00562ab636c30d9ed0a84b16b2c9debeb
|
C++
|
RPG-NJU/NJU-AdvancedProgramming
|
/Homework 3/PersonManage/main.cpp
|
WINDOWS-1250
| 749 | 2.59375 | 3 |
[
"MIT"
] |
permissive
|
#include <iostream>
#include "Manager.h"
#include "Member.h"
#include "Student.h"
#include "Teacher.h"
using namespace std;
int main()
{
Manager m; //Manager
m.add(new Teacher(1069, "Cai", 2018, "Economics", "Prof"));
m.add(new Student(161011, "Alice", 2016, "CS", "CS"));
m.add(new Student(150886, "Wang", 2015, "EE", "CE"));
m.add(new Student(183210, "Zhang", 2018, "Science", "Mathematics"));
m.add(new Teacher(11240, "Huang", 2012, "Art", "AProf"));
m.add(new Teacher(11421, "Zh'ng", 2014, "Economics", "AP"));
m.add(new Teacher(10530, "Wu", 2005, "Law", "rof"));
m.printAll();
m.sortById();
m.printAll();
m.printSearch(11421);
m.printSearch(10824);
m.sortByDate();
m.printAll();
return 0;
}
| true |
ffbbd1f9a64ddc805c61e8b45a596850ca7807b2
|
C++
|
esadakcam/CPP-OOP
|
/assignment3/Dwarves.cpp
|
UTF-8
| 1,797 | 3.25 | 3 |
[] |
no_license
|
/*Author: Mehmed Esad AKÇAM
150190725
*/
#include "Dwarves.h"
#include <iostream>
// since there are not any different attributes in Dwarves faction, body part of constructor is empty
Dwarves::Dwarves(string name , int numberOfUnits, int attackPoint, int healthPoint, int regen):Faction(
name, numberOfUnits, attackPoint, healthPoint, regen){};
void Dwarves::PerformAttack(){
if(!firstEnemy->IsAlive() && secondEnemy->IsAlive()){ //only second enemy alive
secondEnemy->ReceiveAttack(numOfUnits, attackPoint, "Dwarves");
}else if(firstEnemy->IsAlive() && !secondEnemy->IsAlive()){ //only first enemy alive
firstEnemy->ReceiveAttack(numOfUnits,attackPoint,"Dwarves");
}else if(firstEnemy->IsAlive() && secondEnemy->IsAlive()) { //both enemies are alive
//integer division done in order not to crop additinal units
firstEnemy->ReceiveAttack(numOfUnits -(numOfUnits*5/10), attackPoint, "Dwarves");
secondEnemy->ReceiveAttack(numOfUnits - (numOfUnits*5/10), attackPoint, "Dwarves");
}
};
void Dwarves::ReceiveAttack(int unit, double attackedPoint, string attacking){
int damage = unit*attackedPoint;//integer division done in order not to crop additinal units
numOfUnits-= damage/healthPoint;
};
int Dwarves::PurchaseWeapons(int amount){
attackPoint += amount; //increase attack point with purchased amount
return amount * 10; //pay 10 each weapon
}
int Dwarves::PurchaseArmors(int amount){
healthPoint += amount * 2; //increase health point with double of purchased amount
return amount * 3; //pay 3 each armor
}
void Dwarves::Print() const{
cout<<"\"Taste the power of our axes!\""<<endl; //war cry
Faction::Print(); //Faction print method
}
| true |
9421e8a5d5f3297d2bed70eb2f3aaba817105b9c
|
C++
|
nemzutkovic/Coding-Challenges
|
/HackerRank/BasicDataTypes.cpp
|
UTF-8
| 437 | 3.25 | 3 |
[] |
no_license
|
// Basic Data Types
#include <iostream>
#include <cstdio>
using namespace std;
int main() {
// Complete the code.
int integer;
long num;
char character;
float decimal;
double complex;
cin >> integer >> num >> character >> decimal >> complex;
printf("%d \n",integer);
printf("%ld \n", num);
printf("%c \n", character);
printf("%f \n", decimal);
printf("%lf \n", complex);
return 0;
}
| true |
7e5c5c4c6fe439f60a58286fde9fa4fbaeb77057
|
C++
|
Tresky/bearded-wookie
|
/inc/tile_engine/sf_world.hpp
|
UTF-8
| 1,275 | 2.859375 | 3 |
[] |
no_license
|
#ifndef SF_WORLD_H
#define SF_WORLD_H
#include <string>
using std::string;
#include <map>
using std::map;
#include <memory>
using std::shared_ptr;
#include <SFML/Graphics.hpp>
#include "sf_tilemap.hpp"
#include "sf_loader.hpp"
namespace sftile
{
class World
{
public:
// Default constructor
explicit World(sf::RenderWindow& _window);
// Destructor
~World();
void RegisterCamera(shared_ptr<Camera> _camera);
void ChangeTilemap(const string _key);
shared_ptr<Tilemap> AddTilemap(const string _path, const string _key);
shared_ptr<Tilemap> RemoveTilemap(const string _key);
void Update(sf::Time _elapsed_time);
void Render(sf::RenderWindow& _window);
private:
// Disabled copy constructor
World(const World& _copy) = delete;
// Disabled copy assignment operator
World& operator=(const World& _copy) = delete;
// Disabled move constuctor
World(const World&& _moveable) = delete;
// Map of key associated tilemaps
map<string, shared_ptr<Tilemap>> tilemaps;
// Current tilemap being used in game
string current_tilemap;
// Camera to display the world with
shared_ptr<Camera> camera;
// Object to parse TMX data into a tilemap
Loader parser;
};
}
#endif
| true |
ceee78b838eef5a23471b7841bca4ae97ca3c21e
|
C++
|
Han8464/PTA-code
|
/1017/1017/solution.cpp
|
UTF-8
| 2,361 | 3.140625 | 3 |
[] |
no_license
|
/*
#include <cstdio>
#include <cstdlib>
#include <algorithm>
using namespace std;
typedef struct Time
{
int h, m, s;
}time;
typedef struct Customer
{
time t;
int p;
}customer;
customer customers[10010] ;
bool com(customer c1, customer c2)
{
if(c1.t.h > c2.t.h)
{
return false;
}else if(c1.t.h == c2.t.h)
{
if(c1.t.m > c2.t.m)
{
return false;
}else if(c1.t.m == c2.t.m)
{
if(c1.t.s > c2.t.s)
return false;
}
}
return true;
}
bool time_com(time t1, time t2)
{
if(t1.h > t2.h)
{
return false;
}else if(t1.h == t2.h)
{
if(t1.m > t2.m)
{
return false;
}else if(t1.m == t2.m)
{
if(t1.s > t2.s)
return false;
}
}
return true;
}
double time_minus(time t1, time t2)
{
time t;
double m = 0;
if(t1.s >= t2.s)
{
t.s = t1.s - t2.s;
}else
{
t.s = t1.s + 60 - t2.s;
t1.m = t1.m - 1;
}
if(t1.m >= t2.m)
{
t.m = t1.m - t2.m;
}else
{
t.m = t1.m + 60 - t2.m;
t1.h = t1.h - 1;
}
t.h = t1.h - t2.h;
m = (double)t.s / 60 + t.h * 60 + t.m;
return m;
}
time time_plus(time t1, int m)
{
time t;
t.s = t1.s;
t.m = t1.m + m;
if(t.m >= 60)
{
t.m -= 60;
t.h = t1.h + 1;
}else
{
t.h = t1.h;
}
return t;
}
int main()
{
int n, k;
scanf("%d%d", &n, &k);
for(int i = 0; i < n; i++)
{
scanf("%d:%d:%d", &customers[i].t.h, &customers[i].t.m, &customers[i].t.s);
scanf("%d", &customers[i].p);
}
sort(customers, customers + n, com);
double total_time = 0;
time end_time[110];
int x = 1;
int no_count = 0;
time start = {8, 0, 0};
time end = {17, 0, 0};
for(int i = 0; i < n; i++)
{
if(!time_com(customers[i].t, end))
{
no_count ++;
continue;
}
if(x <= k)
{
if(customers[i].t.h < 8)
{
total_time += time_minus(start, customers[i].t);
end_time[x] = time_plus(start, customers[i].p);
x++;
}else
{
end_time[x] = time_plus(customers[i].t, customers[i].p);
x++;
}
}else
{
sort(end_time + 1, end_time + k + 1, time_com);
if(!time_com(customers[i].t, end_time[1]))
{
end_time[1] = time_plus(customers[i].t, customers[i].p);
}else
{
double tmp = time_minus(end_time[1], customers[i].t);
total_time += tmp;
end_time[1] = time_plus(end_time[1], customers[i].p);
}
}
}
n -= no_count;
if(n != 0)
{
printf("%.1lf", total_time / n);
}else
{
printf("0.0");
}
system("pause");
return 0;
}
*/
| true |
222e9a6db9790aca042610ccd7cb783e23b5fc45
|
C++
|
vulnerabivoro/deadbeef
|
/deadbeef/deadbeef.cpp
|
UTF-8
| 2,978 | 2.90625 | 3 |
[] |
no_license
|
#include <bitset>
#include <string>
#include <iomanip>
#include <iostream>
#include <sstream>
#include "deadbeef.h"
void cipher32b_WORD(uintptr_t input, std::string key, std::string& output)
{
std::string hexkey = "";
std::string xoredBinString = "";
std::string xoredHexString = "";
stream2hex(key, hexkey, false);
std::bitset<32> binaryKeyRep= std::bitset<32>(std::stoul(hexkey, nullptr, 16));
std::string stringKeyRep = binaryKeyRep.to_string();
std::bitset<32> binaryRep = std::bitset<32>(input);
std::string stringRep = binaryRep.to_string();
if (stringRep.length() == stringKeyRep.length()) {
for (int i = 0; i < stringRep.length(); ++i) {
if (stringRep.at(i) == stringKeyRep.at(i))
xoredBinString.append("0");
else
xoredBinString.append("1");
//printf("- string: %c key: %c xor: %c\n", stringRep.at(i), stringKeyRep.at(i), xoredString.at(i));
}
xoredHexString = strBin2hex(xoredBinString);
}
//std::cout << xoredHexString;
}
void decipher32b_WORD(std::string input, std::string key, std::string& output)
{
std::string hexkey = "";
std::string xoredBinString = "";
std::string xoredHexString = "";
stream2hex(key, hexkey, false);
std::bitset<32> binaryKeyRep = std::bitset<32>(std::stoul(hexkey, nullptr, 16));
std::string stringKeyRep = binaryKeyRep.to_string();
std::bitset<32> binaryRep = std::bitset<32>(input);
std::string stringRep = binaryRep.to_string();
if (stringRep.length() == stringKeyRep.length()) {
for (int i = 0; i < stringRep.length(); ++i) {
if (stringRep.at(i) == stringKeyRep.at(i))
xoredBinString.append("0");
else
xoredBinString.append("1");
//printf("- string: %c key: %c xor: %c\n", stringRep.at(i), stringKeyRep.at(i), xoredString.at(i));
}
xoredHexString = strBin2hex(xoredBinString);
}
//std::cout << xoredHexString;
}
// Convert string of chars to its representative string of hex numbers
void stream2hex(const std::string str, std::string& hexstr, bool capital = false)
{
hexstr.resize(str.size() * 2);
const size_t a = capital ? 'A' - 1 : 'a' - 1;
for (size_t i = 0, c = str[0] & 0xFF; i < hexstr.size(); c = str[i / 2] & 0xFF)
{
hexstr[i++] = c > 0x9F ? (c / 16 - 9) | a : c / 16 | '0';
hexstr[i++] = (c & 0xF) > 9 ? (c % 16 - 9) | a : c % 16 | '0';
}
}
// Convert string of hex numbers to its equivalent char-stream
void hex2stream(std::string hexstr, std::string& str)
{
str.resize((hexstr.size() + 1) / 2);
for (size_t i = 0, j = 0; i < str.size(); i++, j++)
{
str[i] = (hexstr[j] & '@' ? hexstr[j] + 9 : hexstr[j]) << 4, j++;
str[i] |= (hexstr[j] & '@' ? hexstr[j] + 9 : hexstr[j]) & 0xF;
}
}
std::string strBin2hex(std::string strBinary)
{
int result = 0;
for (size_t count = 0; count < strBinary.length(); ++count)
{
result *= 2;
result += strBinary[count] == '1' ? 1 : 0;
}
std::stringstream ss;
ss << "0x" << std::hex << std::setw(8) << std::setfill('0') << result;
return ss.str();
}
| true |
8a48f8506a86bfc409305ff9376b860676e87d91
|
C++
|
jsphLim/algorithms
|
/hdoj/hdu2009.cpp
|
UTF-8
| 369 | 2.59375 | 3 |
[] |
no_license
|
#include<stdio.h>
#include<math.h>
int main(){
int m,n;
int flag=0;
int i;
while(scanf("%d%d",&n,&m)!=EOF){
if(n>m){
int t=n;
n=m;
m=t;
}
for(i=n;i<=m;i++){
if(i==pow(i/100,3)+pow(i%100/10,3)+pow(i%100%10,3)){
if(i==m) printf("%d",i);
else printf("%d ",i);
flag=1;
}
}
if(!flag) printf("no\n");
flag=0;
}
return 0;
}
| true |
32432579061dbde24985103982476a25329c676d
|
C++
|
shandaming/Martial_arts
|
/Smjy/src/server/database/update/update_fetcher.cpp
|
UTF-8
| 11,760 | 2.59375 | 3 |
[] |
no_license
|
/*
* Copyright (C) 2019
*/
#include <chrono>
#include <fstream>
#include <sstream>
#include "update_fetcher.h"
#include "db_update.h"
#include "field.h"
#include "query_result.h"
#include "log.h"
#include "sha1.h"
struct update_fetcher::directory_entry
{
directory_entry(const fs::path& path_, state state_) : path(path_), _state(state_) {}
const fs::path path;
const state _state;
};
update_fetcher::update_fetcher(const fs::path& source_directory,
const std::function<void(const std::string&)>& apply,
const std::function<void(const fs::path&)>& apply_file,
const std::function<query_result(const std::string&)>& retrieve) :
source_directory_(std::make_unique<fs::path>(source_directory)),
apply_(apply), apply_file_(apply_file), retrieve_(retrieve) {}
update_fetcher::locale_file_storage update_fetcher::get_file_list() const
{
locale_file_storage files;
directory_storage directories = receive_include_directories();
for(auto& entry : directories)
{
fill_file_list_recursively(entry.path, files, entry._state, 1);
}
return files;
}
void update_fetcher::fill_file_list_recursively(const fs::path& path,
locale_file_storage& storage,
const state state,
const uint32_t depth) const
{
static const uint32_t max_depth = 10;
static const fs::directory_iterator end;
for(fs::directory_iterator it(path); it != end; ++it)
{
if(fs::is_directory(it->path()))
{
if(depth< max_depth)
{
fill_file_list_recursively(it->path(), storage, state, depth - 1);
}
}
else if(it->path().extension() == ".sql")
{
LOG_TRACE("sql.updates", "Added locale file \"%s\".", it->path().filename().generic_string().c_str());
const locale_file_entry entry = {it->path(), state};
// 检查加倍的文件名。 因为元素只是通过文件名进行比较,所以这没关系
if(storage.find(entry) != storage.end())
{
LOG_FATAL("sql.updates", "Duplicate filename \"%s\" occurred. Because updates are ordered by their filenames, every name needs to be unique!", it->path().generic_string().c_str());
throw update_exception("Updating failed. see the log for details.");
}
storage.insert(entry);
}
}
}
update_fetcher::directory_storage update_fetcher::receive_include_directories() const
{
directory_storage directories;
const query_result result = retrieve_("SELECT 'path', 'state' from updates_include");
if(!result)
{
return directories;
}
do
{
field* fields = result->fetch();
std::string path = fields[0].get_string();
if(path.substr(0, 1) == "S")
{
path = source_directory_->generic_string() + path.substr(1);
}
const fs::path p(path);
if(!is_directory(p))
{
LOG_WARN("sql.updates", "db_updater: given update include directory \"%s\" does not exist, skipped.", p.generic_string().c_str());
continue;
}
const directory_entry entry = {p, applied_file_entry::state_convert(fields[1].get_string())};
directories.push_back(entry);
LOG_TRACE("sql.updates", "Added applied file \"%s\" from remote.", p.filename().generic_string().c_str());
}
while(result->next_row());
return directories;
}
update_fetcher::applied_file_storage update_fetcher::receive_applied_files() const
{
applied_file_storage map;
query_result result = retrieve_("select 'name', 'hash', 'state', unix_timestamp('timestamp') from updates order by 'name' asc");
if(!result)
{
return map;
}
do
{
field* fields = result->fetch();
const applied_file_entry entry = {fields[0].get_string(), fields[1].get_string(), applied_file_entry::state_convert(fields[2].get_string()), fields[3].get_uint64()};
map.insert(std::make_pair(entry.name, entry));
}
while(result->next_row());
return map;
}
std::string update_fetcher::read_sql_update(const fs::path& file) const
{
std::ifstream in(file);
if(!in.is_open())
{
LOG_FATAL("sql.updates", "Failed to open the sql update \"%s\" for reading! Stopping the server to keep the database intergrity. try to identify and solve the issue or disable the database updater.", file.generic_string().c_str());
throw update_exception("Opening the sql update failed!");
}
auto update = [&in]
{
std::ostringstream os;
os << in.rdbuf();
return os.str();
}();
in.close();
return update;
}
update_result update_fetcher::update(const bool redundancy_checks,
const bool allow_rehash, const bool archived_redundancy,
const int32_t clean_dead_references_max_count) const
{
const locale_file_storage available = get_file_list();
applied_file_storage applied = receive_applied_files();
size_t count_recent_updates = 0;
size_t count_archived_updates = 0;
for(const auto& i : applied)
{
if(i.second._state == RELEASED)
{
++count_recent_updates;
}
else
{
++count_archived_updates;
}
}
// 填充哈希到名称缓存
hash_to_file_name_storage hash_to_name;
for(auto i : applied)
{
hash_to_name.insert(std::make_pair(i.second.hash, i.first));
}
size_t imported_updates = 0;
for(auto& i : available)
{
LOG_DEBUG("sql.updates", "Checking update \"%s\"...", i.first.filename().generic_string().c_str());
auto it = applied.find(i.first.filename().string());
if(it != applied.end())
{
// 如果禁用冗余,请跳过它,因为已应用更新。
if(!redundancy_checks)
{
LOG_DEBUG("sql.updates", ">> Update is already applied, skipping redundancy checks.");
applied.erase(it);
continue;
}
// 如果更新位于存档目录中并在我们的数据库中标记为已存档,则跳过冗余检查(存档更新永远不会更改)。
if(!archived_redundancy && (it->second._state == ARCHIVED) && (i.second == ARCHIVED))
{
LOG_DEBUG("sql.updates", ">> Update is archived and marked as archived in database, skipping redundancy checks.");
applied.erase(it);
continue;
}
}
// 根据查询内容计算Sha1哈希值。
const std::string hash = calculate_sha1_hash(read_sql_update(i.first));
update_mode mode = MODE_APPLY;
// 更新不在我们的应用列表中
if(it != applied.end())
{
// 捕获重命名(不同的文件名,但相同的哈希)
auto hash_it = hash_to_name.find(hash);
if(hash_it != hash_to_name.end())
{
// 检查原始文件是否已删除。 如果没有,我们就遇到了问题。
locale_file_storage::const_iterator locale_it;
// 向前推送localeIter
for(locale_it = available.begin(); (locale_it != available.end()) &&
(locale_it->first.filename().string() != hash_it->second); ++locale_it)
{
;
}
// 冲突!
if(locale_it != available.end())
{
LOG_WARN("sql updates", ">> It seems like the update \"%s\" \"%d\" was renamed, but the old file is still there! Treating it as a new file! (It is probably an unmodified copy of the file \"%s\")", i.first.filename().string().c_str(), hash.substr(0, 7), locale_it->first.filename().string().c_str());
}
// 将文件视为此处重命名是安全的
else
{
LOG_INFO("sql.updates", ">> Renaming update\"%s\" to \"%s\" \"%s\".", hash_it->second.c_str(), i.first.filename().string().c_str(), hash.substr(0, 7).c_str());
rename_entry(hash_it->second, i.first.filename().string());
applied.erase(hash_it->second);
continue;
}
}
// 如果以前从未见过,请应用更新。
else
{
LOG_INFO("sql.updates", ">> Applying update \"%s\" \"%s\"...", i.first.filename().string().c_str(), hash.substr(0, 7).c_str());
}
}
// 如果更新条目存在于我们的数据库中,则使用空哈希重新更新更新条目。
else if(allow_rehash && it->second.hash.empty())
{
mode = MODE_REHASH;
LOG_INFO("sql.updates", ">> Re-hashing update \"%s\" \"%s\"...", i.first.filename().string().c_str(), hash.substr(0, 7).c_str());
}
else
{
// 如果文件的哈希值与我们数据库中存储的哈希值不同,请重新应用更新(因为它已更改)。
if(it->second.hash != hash)
LOG_INFO("sql.updates", ">> Reapplying update \"%s\" \"%s\" -> \"%s\" (it changed)...", i.first.filename().string().c_str(), it->second.hash.substr(0, 7).c_str(), hash.substr(0, 7).c_str());
else
{
// 如果文件未更改且刚刚移动,请更新其状态(如有必要)。
if(it->second._state != i.second)
{
LOG_DEBUG("sql.update", ">> Updating the state of \"%s\" to \"%s\"...", i.first.filename().string().c_str(), applied_file_entry::state_convert(i.second).c_str());
update_state(i.first.filename().string(), i.second);
}
LOG_DEBUG("sql.updates", ">> Update is already applied and matches the hash \"%s\"", hash.substr(0, 7).c_str());
applied.erase(it);
continue;
}
}
uint32_t speed = 0;
const applied_file_entry file = {i.first.filename().string(), hash, i.second, 0};
switch(mode)
{
case MODE_APPLY:
speed = apply(i.first);
case MODE_REHASH:
update_entry(file, speed);
break;
default:
break;
}
if(it != applied.end())
{
applied.erase(it);
}
if(mode == MODE_APPLY)
{
++imported_updates;
}
}
// 清理孤立的条目(如果已启用)
if(!applied.empty())
{
const bool do_cleanup = (clean_dead_references_max_count < 0) ||
(applied.size() <= static_cast<size_t>(clean_dead_references_max_count));
for(auto& i : applied)
{
LOG_WARN("sql.updates", "The file \"%s\" was applied to the database, but is missing in your update directory now!", i.first.c_str());
if(do_cleanup)
{
LOG_INFO("sql.updates", "Deleting orphaned entry \"%s\"", i.first.c_str());
}
}
if(do_cleanup)
{
clean_up(applied);
}
else
{
LOG_ERROR("sql.updates", "Cleanup is disabled! There were %u dirty files applied to ypur database, but they are now missing in your source directory", applied.size());
}
}
return update_result(imported_updates, count_recent_updates, count_archived_updates);
}
uint32_t update_fetcher::apply(const fs::path& path) const
{
using time = std::chrono::high_resolution_clock;
// 基准查询速度
auto begin = time::now();
// 更新数据库
apply_file_(path);
// 返回查询应用的时间
return uint32_t(std::chrono::duration_cast<std::chrono::milliseconds>(time::now() - begin).count());
}
void update_fetcher::update_entry(const applied_file_entry& entry, const uint32_t speed) const
{
const std::string update = "replace into updates (name, hash, state, speed) values('" + entry.name + "', '" + entry.hash + "', '" + entry.get_state_as_string() + "', '" + std::to_string(speed) + "')";
// 更新数据库
apply_(update);
}
void update_fetcher::rename_entry(const std::string& from, const std::string& to) const
{
// 删除目标(如果存在)
std::string update = "delete from updates where name = '" + to + "'";
apply_(update);
// 改名
update = "update updates set name = '" + to + "' where name = '" + from + "'";
apply_(update);
}
void update_fetcher::clean_up(const applied_file_storage& storage) const
{
if(storage.empty())
{
return;
}
std::stringstream update;
size_t remaining = storage.size();
update << "delete from updates where name in(";
for(auto& i : storage)
{
update << "'" << i.first << "'";
if((--remaining) > 0)
{
update << ",";
}
}
update << ")";
// 更新数据库
apply_(update.str());
}
void update_fetcher::update_state(const std::string& name, const state state) const
{
const std::string update = "update updates set state = '" + applied_file_entry::state_convert(state) + "' + where name = '" + name + "'";
// 更新数据库
apply_(update);
}
bool update_fetcher::path_compare::operator()(const locale_file_entry& l,
const locale_file_entry& r) const
{
return l.first.filename().string() < r.first.filename().string();
}
| true |
ba792db1103195d2249c14a1f8050074cc978b66
|
C++
|
aFleetingTime/Cpp
|
/13.CopyControl/28/BinStrTree.cpp
|
UTF-8
| 910 | 3.390625 | 3 |
[] |
no_license
|
#include "BinStrTree.h"
BinStrTree::BinStrTree() : root(nullptr)
{
;
}
BinStrTree::~BinStrTree()
{
delete root;
root = nullptr;
}
BinStrTree::BinStrTree(const BinStrTree &tree) : root(new TreeNode(*tree.root))
{
;
}
BinStrTree& BinStrTree::operator=(const BinStrTree &tree)
{
auto temp = new TreeNode(*tree.root);
delete root;
root = temp;
return *this;
}
bool BinStrTree::insert(const std::string &s)
{
return insertTree(s, root);
}
void BinStrTree::printTree(TreeNode *node)
{
if(!node)
return;
printTree(node->left);
std::cout << node->value << std::endl;
printTree(node->right);
}
void BinStrTree::print()
{
printTree(root);
}
bool BinStrTree::insertTree(const std::string &s, TreeNode *&node)
{
if(!node)
{
node = new TreeNode(s);
return true;
}
else if(node->value > s)
insertTree(s, node->left);
else if(node->value < s)
insertTree(s, node->right);
return false;
}
| true |
0618f2fb017aadc4f5c8a871ee5d35b473346a6e
|
C++
|
chenyilin0110/EasyAttendSystem
|
/EasyAttendSystem_c++/macversion/total.cpp
|
UTF-8
| 849 | 2.5625 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc,char* argv[])
{
FILE *fptr;
char num[10] = {},empty[] = "EOF";
int all = 0,count = 0,i,j,total = 0;
long long int array[1000][2]={};
int fl = 0;
fptr = fopen("noattend.txt","r");
while(fscanf(fptr,"%s",num) != EOF)
{
if(strcmp(num,empty) != 0)
{
if(all != 0)
{
long long int temp = atoll(num);
for(i=0;i<all;i++)
{
if(array[i][0] == temp)
{
array[i][0] = temp;
array[i][1]++;
fl = 1;
}
}
if(fl == 0)
{
array[all][0] = temp;
array[all][1]++;
all++;
}
}
else
{
array[all][0] = atoll(num);
array[all][1]++;
all++;
}
}
else
break;
}
fclose(fptr);
for(i=0;i<all;i++)
{
printf("%lld %lld\n",array[i][0],array[i][1]);
}
}
| true |
e806fabf60140afd672c0b8c199fb7f004162afd
|
C++
|
pyc-ycy/ClassicalSample
|
/ClassicalSample/Horse.h
|
UTF-8
| 1,167 | 3.5 | 4 |
[] |
no_license
|
#pragma once
#include <iostream>
#include <string>
using namespace std;
class Horse
{
protected:
int weight;
int speed;
int age;
public:
Horse()
{
this->weight = 0;
this->speed = 0;
this->age = 0;
cout << "use the constructor of Horse" << endl;
}
Horse(int weight, int speed, int age)
{
this->weight = weight;
this->speed = speed;
this->age = age;
}
void setWeight(int w)
{
this->weight = w;
}
void setSpeed(int s = 0)
{
this->speed = s;
}
void setAge(int a = 2)
{
this->age = a;
}
int getWeight()
{
return this->weight;
}
int getSpeed()
{
return this->speed;
}
int getAge()
{
return this->age;
}
};
class HorseColor
{
protected:
string color;
public:
HorseColor()
{
}
HorseColor(string color)
{
this->color = color;
}
void setColor(string c)
{
this->color = c;
}
string getColor()
{
return this->color;
}
};
class WhiteHorse :public Horse, public HorseColor
{
public:
string getColor()
{
return "white";
}
};
class BlackHorse :public Horse, public HorseColor
{
public:
BlackHorse(int weight, int speed, int age, string color = "black") :Horse(weight, speed, age), HorseColor(color) {}
};
| true |
ad26d5635dcf83338e7311d1de93ae3d8ebd456f
|
C++
|
ihsonnet/DIU-ACM-PC-Green-Division
|
/DIU-PC Weekly Contest-02/D.cpp
|
UTF-8
| 434 | 2.859375 | 3 |
[] |
no_license
|
#include<bits/stdc++.h>
using namespace std;
long long int f91(int n)
{
if(n==91)
return 91;
else if(n<=100)
return f91(f91(n+11));
else if(n>=101)
{
return n-10;
}
}
int main()
{
int n;
long long int res;
while(cin>>n)
{
if(n==0)
break;
else
{
res = f91(n);
cout<<"f91("<<n<<") = "<<res<<endl;
}
}
}
| true |
53ac765b69e5e7e6981d67c4910e7580c9cd4289
|
C++
|
ARM-software/armnn
|
/src/backends/tosaReference/TosaRefMemoryManager.cpp
|
UTF-8
| 2,157 | 2.75 | 3 |
[
"BSD-3-Clause",
"CC0-1.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//
// Copyright © 2022 Arm Ltd and Contributors. All rights reserved.
// SPDX-License-Identifier: MIT
//
#include "TosaRefMemoryManager.hpp"
#include <armnn/utility/Assert.hpp>
#include <algorithm>
namespace armnn
{
TosaRefMemoryManager::TosaRefMemoryManager()
{}
TosaRefMemoryManager::~TosaRefMemoryManager()
{}
TosaRefMemoryManager::Pool* TosaRefMemoryManager::Manage(unsigned int numBytes)
{
if (!m_FreePools.empty())
{
Pool* res = m_FreePools.back();
m_FreePools.pop_back();
res->Reserve(numBytes);
return res;
}
else
{
m_Pools.push_front(Pool(numBytes));
return &m_Pools.front();
}
}
void TosaRefMemoryManager::Allocate(TosaRefMemoryManager::Pool* pool)
{
ARMNN_ASSERT(pool);
m_FreePools.push_back(pool);
}
void* TosaRefMemoryManager::GetPointer(TosaRefMemoryManager::Pool* pool)
{
return pool->GetPointer();
}
void TosaRefMemoryManager::Acquire()
{
for (Pool &pool: m_Pools)
{
pool.Acquire();
}
}
void TosaRefMemoryManager::Release()
{
for (Pool &pool: m_Pools)
{
pool.Release();
}
}
TosaRefMemoryManager::Pool::Pool(unsigned int numBytes)
: m_Size(numBytes),
m_Pointer(nullptr)
{}
TosaRefMemoryManager::Pool::~Pool()
{
if (m_Pointer)
{
Release();
}
}
void* TosaRefMemoryManager::Pool::GetPointer()
{
ARMNN_ASSERT_MSG(m_Pointer, "TosaRefMemoryManager::Pool::GetPointer() called when memory not acquired");
return m_Pointer;
}
void TosaRefMemoryManager::Pool::Reserve(unsigned int numBytes)
{
ARMNN_ASSERT_MSG(!m_Pointer, "TosaRefMemoryManager::Pool::Reserve() cannot be called after memory acquired");
m_Size = std::max(m_Size, numBytes);
}
void TosaRefMemoryManager::Pool::Acquire()
{
ARMNN_ASSERT_MSG(!m_Pointer, "TosaRefMemoryManager::Pool::Acquire() called when memory already acquired");
m_Pointer = ::operator new(size_t(m_Size));
}
void TosaRefMemoryManager::Pool::Release()
{
ARMNN_ASSERT_MSG(m_Pointer, "TosaRefMemoryManager::Pool::Release() called when memory not acquired");
::operator delete(m_Pointer);
m_Pointer = nullptr;
}
}
| true |
b871d5ff2e70063a4c2b8f7d32dbc1ddba097dd7
|
C++
|
jjocram/sydevs
|
/src/examples/test_systems/basic/basic_double_processor_node.h
|
UTF-8
| 3,312 | 2.765625 | 3 |
[
"BSL-1.0",
"Apache-2.0"
] |
permissive
|
#pragma once
#ifndef SYDEVS_EXAMPLES_BASIC_DOUBLE_PROCESSOR_NODE_H_
#define SYDEVS_EXAMPLES_BASIC_DOUBLE_PROCESSOR_NODE_H_
#include <examples/test_systems/basic/basic_processor_node.h>
#include <sydevs/systems/composite_node.h>
#include <sydevs/systems/function_node.h>
namespace sydevs_examples {
using namespace sydevs;
using namespace sydevs::systems;
class basic_double_processor_node : public composite_node
{
public:
// Constructor/Destructor:
basic_double_processor_node(const std::string& node_name, const node_context& external_context);
virtual ~basic_double_processor_node() = default;
// Ports:
port<flow, input, duration> response_dt_A_input;
port<flow, input, duration> response_dt_B_input;
port<message, input, int64> job_id_input;
port<message, output, int64> job_id_output;
port<flow, output, int64> miss_count_output;
// Nested Classes:
class miss_count_adder_node : public function_node {
public:
miss_count_adder_node(const std::string& node_name, const node_context& external_context);
port<flow, input, int64> miss_count_A_input;
port<flow, input, int64> miss_count_B_input;
port<flow, output, int64> miss_count_output;
protected:
virtual void flow_event();
};
// Components:
basic_processor_node processor_A;
basic_processor_node processor_B;
miss_count_adder_node adder;
};
basic_double_processor_node::basic_double_processor_node(const std::string& node_name, const node_context& external_context)
: composite_node(node_name, external_context)
, response_dt_A_input("response_dt_A_input", external_interface())
, response_dt_B_input("response_dt_B_input", external_interface())
, job_id_input("job_id_input", external_interface())
, job_id_output("job_id_output", external_interface())
, miss_count_output("miss_count_output", external_interface())
, processor_A("processor_A", internal_context())
, processor_B("processor_B", internal_context())
, adder("adder", internal_context())
{
// Initialization Links
inward_link(response_dt_A_input, processor_A.response_dt_input);
inward_link(response_dt_B_input, processor_B.response_dt_input);
// Simulation Links
inward_link(job_id_input, processor_A.job_id_input);
inner_link(processor_A.job_id_output, processor_B.job_id_input);
outward_link(processor_B.job_id_output, job_id_output);
// Finalization Links
inner_link(processor_A.miss_count_output, adder.miss_count_A_input);
inner_link(processor_B.miss_count_output, adder.miss_count_B_input);
outward_link(adder.miss_count_output, miss_count_output);
}
basic_double_processor_node::miss_count_adder_node::miss_count_adder_node(const std::string& node_name, const node_context& external_context)
: function_node(node_name, external_context)
, miss_count_A_input("miss_count_A_input", external_interface())
, miss_count_B_input("miss_count_B_input", external_interface())
, miss_count_output("miss_count_output", external_interface())
{
}
void basic_double_processor_node::miss_count_adder_node::flow_event()
{
int64 miss_count = miss_count_A_input.value() + miss_count_B_input.value();
miss_count_output.assign(miss_count);
}
} // namespace
#endif
| true |
9dd5558b5f12b585179b225fc721772cd33631cd
|
C++
|
amgregoi/School
|
/K-State/CIS308/Projects/Proj8/proj8/rational.h
|
UTF-8
| 1,353 | 3.546875 | 4 |
[] |
no_license
|
#include "real.h"
#ifndef RATIONAL_H
#define RATIONAL_H
class Rational: public Real {
protected:
int num;
int denom;
public:
/**
* Constructs the rational num/denom.
*
* num: the numerator
* denom: the denominator
*/
Rational(int num, int denom);
/**
* Cleans up memory for this number
*/
~Rational();
/**
* Computes the double value of this number
*
* return: the double value of this number
*/
double value();
/**
* Adds this number and the specified number
*
* n: the number to add to
* return: the most specific number representing
* the result of the addition
*/
Number* plus(Number *n);
/**
* Subtracts the specified number from this number
*
* n: the number to subtract
* Adds this number and the specified number
*
* n: the number to add to
* return: the most specific number representing
* the result of the subtraction
*/
Number* minus(Number *n);
/**
* Multiplies this number and the specified number
*
* n: the number to multiply by
* return: the most specific number representing
* the result of the multiplication
*/
Number* times(Number *n);
/**
* Prints this number to the screen
*/
void print();
private:
/**
* Reduces this fraction to lowest terms
*/
void reduce();
};
#endif
| true |
d908612f2b14f888f539d56470771ed1aed29313
|
C++
|
bautrey37/Parallelized-Graph-Algorithms
|
/OpenMP_examples/helloworld_openmp.cpp
|
UTF-8
| 603 | 2.578125 | 3 |
[] |
no_license
|
// Helloorld_openmp.cpp : Defines the entry point for the console application.s
//
#include "stdafx.h"
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
int main(int argc, char* argv[])
{
// Get the number of processors in this system
int iCPU = omp_get_num_procs();
printf("Number of processors in system: %d\n", iCPU);
// Now set the number of threads
omp_set_num_threads(iCPU);
// omp_get_thread_num() - returns thread rank in parallel region
#pragma omp parallel
{
printf("Thread rank : %d\n", omp_get_num_threads());
}
system("pause");
return 0;
}
| true |
e2bf3e5bd990d65c12933317449ccf0de733f6e6
|
C++
|
theAdamBader/flyAway
|
/flyAway/flyAway/flyAway/src/inGameObjects.h
|
UTF-8
| 642 | 2.53125 | 3 |
[] |
no_license
|
//Run Away (Term 2 Coursework)
//
//inGameObjects.h
//
//Created by Adam M Bader 19.03.2017
#ifndef inGameObjects_h
#define inGameObjects_h
#include <stdio.h>
#include "ofMain.h"
class inGameObjects {
public:
int health = 1;
int points = 1;
bool dead = false;
ofRectangle * boundingBox;
ofVec2f pos, vel; //takes 2 arguements
inGameObjects(float& x, float& y, float width, float height);
virtual ~inGameObjects();
virtual void move() = 0;
virtual void draw() = 0;
virtual void collisionResponse(inGameObjects *other) = 0;
virtual void collide(inGameObjects *other);
virtual bool isAlive();
};
#endif /* inGameObjects_hpp */
| true |
efdbd74baffaeab410bdb587aa7725b02db54df9
|
C++
|
zinsmatt/Programming
|
/LeetCode/easy/Longest_Substring_Without_Repeating_Characters.cxx
|
UTF-8
| 758 | 2.96875 | 3 |
[] |
no_license
|
class Solution {
public:
int lengthOfLongestSubstring(string s) {
if (s.size() == 0) return 0;
std::unordered_set<char> arr;
int a = 0;
int b = 0;
int max = 0;
while (b < s.size())
{
if (arr.find(s[b]) == arr.end())
{
arr.insert(s[b]);
b++;
}
else
{
if (b-a > max)
max = b-a;
while (s[a] != s[b])
{
arr.erase(s[a]);
++a;
}
++a;
++b;
}
}
if (b - a > max)
max = b - a;
return max;
}
| true |
918f44a829bba671a02524843fdad260be950a03
|
C++
|
SJRLL/leetcode2
|
/leetcode-682-棒球比赛/Test.cpp
|
UTF-8
| 3,712 | 3.65625 | 4 |
[] |
no_license
|
你现在是棒球比赛记录员。
给定一个字符串列表,每个字符串可以是以下四种类型之一:
1.整数(一轮的得分):直接表示您在本轮中获得的积分数。
2. "+"(一轮的得分):表示本轮获得的得分是前两轮有效 回合得分的总和。
3. "D"(一轮的得分):表示本轮获得的得分是前一轮有效 回合得分的两倍。
4. "C"(一个操作,这不是一个回合的分数):表示您获得的最后一个有效 回合的分数是无效的,应该被移除。
每一轮的操作都是永久性的,可能会对前一轮和后一轮产生影响。
你需要返回你在所有回合中得分的总和。
示例 1:
输入 : ["5", "2", "C", "D", "+"]
输出 : 30
解释 :
第1轮:你可以得到5分。总和是:5。
第2轮:你可以得到2分。总和是:7。
操作1:第2轮的数据无效。总和是:5。
第3轮:你可以得到10分(第2轮的数据已被删除)。总数是:15。
第4轮:你可以得到5 + 10 = 15分。总数是:30。
示例 2:
输入 : ["5", "-2", "4", "C", "D", "9", "+", "+"]
输出 : 27
解释 :
第1轮:你可以得到5分。总和是:5。
第2轮:你可以得到 - 2分。总数是:3。
第3轮:你可以得到4分。总和是:7。
操作1:第3轮的数据无效。总数是:3。
第4轮:你可以得到 - 4分(第三轮的数据已被删除)。总和是: - 1。
第5轮:你可以得到9分。总数是:8。
第6轮:你可以得到 - 4 + 9 = 5分。总数是13。
第7轮:你可以得到9 + 5 = 14分。总数是27。
//解题思路:
你现在是棒球比赛记录员。
给定一个字符串列表,每个字符串可以是以下四种类型之一:
1.整数(一轮的得分):直接表示您在本轮中获得的积分数。
2. "+"(一轮的得分):表示本轮获得的得分是前两轮有效 回合得分的总和。
3. "D"(一轮的得分):表示本轮获得的得分是前一轮有效 回合得分的两倍。
4. "C"(一个操作,这不是一个回合的分数):表示您获得的最后一个有效 回合的分数是无效的,应该被移除。
每一轮的操作都是永久性的,可能会对前一轮和后一轮产生影响。
你需要返回你在所有回合中得分的总和。
class Solution {
public:
int calPoints(vector<string>& ops) {
if (ops.empty()) return 0;
stack<int> res;//存放每一轮的得分
int result = 0;//存放获得总分
for (int i = 0; i<ops.size(); i++)
{
const char *p = ops[i].data();//将字符串转成字符,原因switch只接收整型或枚举类型
switch (*p)
{
case'+'://得分是前两轮有效 回合得分的总和。
{
if (res.empty())
res.push(0);
else if (res.size() == 1)
res.push(res.top());
else
{
int temp = res.top();
res.pop();
int sumt = res.top() + temp;
res.push(temp);
res.push(sumt);
}
result += res.top();
continue;
}
case'D'://得分是前一轮有效 回合得分的两倍。
{
if (res.empty())
res.push(0);
else
{
res.push(2 * res.top());
result += res.top();
}
continue;
}
case'C'://最后一个有效 回合的分数是无效的
{
if (res.empty())
continue;
else
{
result -= res.top();
res.pop();
}
continue;
}
default://获取到数字
{
stringstream ss(ops[i]);
int t;
ss >> t;
res.push(t);
result += res.top();
}
}
}
return result;
}
};
| true |
fca707901de776f46fc4781d62c6a644e02682ae
|
C++
|
infinixco/WAY-TO-PLACEMENT
|
/coin_change.cpp
|
UTF-8
| 738 | 3.34375 | 3 |
[] |
no_license
|
def numberOfWays(coins,numberOfCoins,value):
ways=[0]*(value+1)
'''
We declare an array that will contain the number of--
ways to make change for all values from 0 to value
This is done as we are working from bottom up. So, obviously, we need to make change for smaller values--
before we can make change for the given values.
'''
ways[0]=1 #We can make change for 0 in 1 ways, that is by choosing nothing.
for coin in coins: #Using a coin, one at a time
for i in range(1,value+1):
if(i>=coin): ##Since it makes no sense to create change for value smaller than coin's denomination
ways[i]=ways[i]+ways[i-coin]
return ways[value]
| true |
072fd4116467773eaca65f5f8340eb81e884d376
|
C++
|
goldsail/Leetcode
|
/Leetcode/Q1171.cpp
|
UTF-8
| 1,288 | 3.078125 | 3 |
[
"Unlicense"
] |
permissive
|
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeZeroSumSublists(ListNode* head) {
head = new ListNode(0, head); // dummy head node
sums = unordered_map<int, ListNode*>();
cache = unordered_map<ListNode*, int>();
ListNode* curr = head;
int sum = 0;
while (curr) {
sum += curr->val;
cache[curr] = sum;
//
if (sums[sum] == nullptr) {
sums[sum] = curr;
} else {
// delete nodes in between
ListNode *prev = sums[sum];
while (prev->next != curr->next) {
ListNode *temp = prev->next;
prev->next = temp->next;
sums[cache[temp]] = nullptr;
}
sums[sum] = prev;
}
curr = curr->next;
}
//
return head->next;
}
private:
unordered_map<int, ListNode*> sums;
unordered_map<ListNode*, int> cache;
};
| true |
673afb81b62e9602b6f2122c4ea9c6a0895ad491
|
C++
|
Mondiegus/Cpp_Learning
|
/My_Tasks/5/T5_7.cpp
|
UTF-8
| 763 | 3.25 | 3 |
[] |
no_license
|
#include <iostream>
#include <cstring>
using namespace std;
struct carsDoc
{
string model;
uint16_t prodYear;
};
int main()
{
int carAmount = 0;
cout << "How many cars do you want to save?" << endl;
cin >> carAmount;
cin.get();
carsDoc *carsTab = new carsDoc[carAmount];
for(int i = 1; i <= carAmount; ++i)
{
cout << endl << "Car #" << i << endl << "Please put a name: " << endl;
getline(cin,carsTab[i-1].model);
cout << endl << "Please production year: " << endl;
cin >> carsTab[i-1].prodYear;
cin.get();
}
for(int i = 1; i <= carAmount; ++i)
{
cout << carsTab[i-1].prodYear << "\t" << carsTab[i-1].model << endl;
}
delete [] carsTab;
}
| true |
6900b81791853fb9da164d0e0938a61007bb1568
|
C++
|
Muha113/6-th-term-labs
|
/osis/lab10/mainwindow.cpp
|
UTF-8
| 1,623 | 2.515625 | 3 |
[] |
no_license
|
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::mousePressEvent(QMouseEvent *event)
{
x = event->pos().x();
y = event->pos().y();
type = emit this->newType();
color = emit this->newColor();
state = emit this->newCheckBoxArg();
//update(0, 0, this->width(), this->height());
update();
}
void MainWindow::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event)
QPainter painter(this);
painter.setPen(color);
if(color != nullptr && type != 0 && state != 0)
{
if(type == 1)
{
QPolygon polygon;
polygon << QPoint(x - 50, y) << QPoint(x, y - 100) << QPoint(x + 50, y)
<< QPoint(x, y + 100) << QPoint(x - 50, y);
painter.drawPolygon(polygon);
}
else if(type == 2)
{
painter.drawRect(x - 50, y - 50, 100, 100);
}
else if(type == 3)
{
painter.drawEllipse(x - 50, y - 50 , 100, 100);
}
else if(type == 4)
{
QPolygon polygon;
polygon << QPoint(x - 100, y) << QPoint(x - 30, y - 30) << QPoint(x, y - 100)
<< QPoint(x + 30, y - 30) << QPoint(x + 100, y) << QPoint(x + 30, y + 30)
<< QPoint(x, y + 100) << QPoint(x - 30, y + 30) << QPoint(x - 100, y);
painter.drawPolygon(polygon);
}
}
}
| true |
a41f3cc9bfef7eeef969c0789f6c0ca3664689fe
|
C++
|
Saprsuu6/Sapper
|
/Sapper/Main.cpp
|
WINDOWS-1251
| 3,773 | 2.671875 | 3 |
[] |
no_license
|
//
#include"Header.h"
int main() {
static bool first = true; //
setlocale(0, "C"); //
int enter = 13; //
int space = 32; //
int esc = 27; //
HANDLE h = GetStdHandle(-11); //
Setings(h);
if (first) { //
Sponsor(h, 10, 4);
first = false;
}
system("cls"); //
system("color 32"); //
Draw(h, 14, 0, 0, 40, 20, 4); //
Draw(h, 14, 44, 0, 31, 3, 0); //
Draw(h, 14, 44, 3, 43, 3, 0); // 1
Draw(h, 14, 44, 6, 27, 3, 0); // 2
setlocale(0, "RUS"); //
Text(h, 10, 45, 1); //
if (Start(enter, space, esc)) { //
system("cls");
int value = Complexity(h); //
system("cls");
setlocale(0, "C");
Draw(h, 10, 22, 8, 40, 3, 0); //
Load(h, 40); //
MusikStart(); //
system("color 32");
int** ar = nullptr; //
int** ar_flags = nullptr; //
if (value == 1) { // 1
int ar_hight = 10; // 1
int ar_width = 20; // 1
Draw(h, 14, 0, 0, ar_width + 2, ar_hight + 2, 4); //
Draw(h, 14, ar_width + 5, 0, 16, 4, 0); //
CreateMass(h, ar, ar_flags, ar_hight, ar_width); //
GamePlay(h, ar, ar_flags, ar_hight, ar_width); //
}
else if (value == 2) { // 2
int ar_hight = 15; // 2
int ar_width = 30; // 2
Draw(h, 14, 0, 0, ar_width + 2, ar_hight + 2, 4); //
Draw(h, 14, ar_width + 5, 0, 16, 4, 0); //
CreateMass(h, ar, ar_flags, ar_hight, ar_width); ;
GamePlay(h, ar, ar_flags, ar_hight, ar_width);
}
if (value == 3) { // 3
int ar_hight = 20; // 3
int ar_width = 40; // 3
Draw(h, 14, 0, 0, ar_width + 2, ar_hight + 2, 4); //
Draw(h, 14, ar_width + 5, 0, 16, 4, 0); //
CreateMass(h, ar, ar_flags, ar_hight, ar_width); ;
GamePlay(h, ar, ar_flags, ar_hight, ar_width);
}
}
else if (!Start(enter, space, esc)) { //
system("cls");
main(); //
}
system("pause > NULL"); //
}
| true |
7a00a84914de0c3aec359e804eaee13974b7e5a7
|
C++
|
tati2327/Gladiators_Project2
|
/Tati/A*/List.h
|
UTF-8
| 1,548 | 3.265625 | 3 |
[
"Apache-2.0"
] |
permissive
|
#ifndef A_LIST_H
#define A_LIST_H
#include <iostream>
#include "Node.h"
template<typename T>
class List {
public:
Node<T> *first; /*!< Primer elemento de la lista*/
Node<T> *last; /*!< Ultimo elemento de la lista*/
Node<T> *curr; /*!< Nodo que funciona para facilitar recorrer la lista en ciertas funciones */
/*!
* List()
*Constructor
*/
List();
/*!#include "Field.h"
* add()
* Agrega un nuevo nodo a la lista.
* @param dato de tipo T
*/
void add(T data);
/*!
* deleteNode()
* Elimina un nodo de la lista por dato.
* @param data de tipo T
*/
void deleteNode(T _node);
/*!
* getData()
* Retorna un dato de tipo T
* @param un indice
* @return un dato de tipo T
*/
T getData(int index);
/*!
* getNode()
* Retorna un nodo de tipo T
* @param un indice
* @return un nodo de tipo T
*/
Node<T> *getNode(int index);
/*!
* Imprime la lista genérica
* PRECAUCUÓN: La imprime mientras sean datos primitivos NO OBJETOS de una clase "X"
*/
void show();
/*!
* size()
* Retorna el tamaño de la lista
* @return un int con la cantidad de elementos de la lista
*/
int size();
/*!
* operator []
* Sobrecarga del operador [] para obtener la posición de un elemento de la lista
* @param un indice
* @return el dato de un elemento de la lista
*/
T operator [](int index);
};
#include "List_def.h"
#endif //A_LIST_H
| true |
ae1a9a7c85221120929bddb0baa86327d8fdf4f1
|
C++
|
yanbai1990/lintcode
|
/C++/find_min_in_rotated_sorted_array.cpp
|
UTF-8
| 543 | 3.328125 | 3 |
[] |
no_license
|
class Solution {
public:
/**
* @param num: a rotated sorted array
* @return: the minimum number in the array
*/
int findMin(vector<int> &num) {
// write your code here
int start=0;
int end=num.size()-1;
while(start+1<end) {
int mid=start+(end-start)/2;
if(num[mid]>num[end]) {
start=mid;
} else {
end=mid;
}
}
if(num[start]<=num[end]) return num[start];
else return num[end];
}
};
| true |
0983e1074f121807f2322320ab6c88742a34b744
|
C++
|
vicentegro/LabPercepcion
|
/Neurona.h
|
UTF-8
| 1,163 | 3 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <math.h>
class Neurona{ //inicio de la clase Neurona
public:
//atributos
float w[5];
float x[5];
float normx[5];
float fx, sum;
float bias;
//metodos
void setpesos(float valuep){
//para asignar los pesos en la neurona y guardarlos en un arreglo w
for(int i=0;i<5;i++){
w[i]=valuep;
}
}
void setbias(float valuec){
//para asignar el bias en la neurona
bias=valuec;
}
void setentradas(float valuex){ //para meter las entradas a la neurona y guardarlas en su arreglo x
for(int m=0;m<5;m++){
x[m]=valuex;
}
//NORMALIZACION DE ENTRADAS, PARA PONERLAS EN UN RANGO DE 0 A 1
normx[0]=(x[0]-0)/(100-0);
normx[1]=(x[1]-20)/(70-20);
normx[2]=(x[2]-20)/(70-20);
normx[3]=(x[3]-0)/(118-0);
normx[4]=(x[4]-9)/(180-9);
}
void sumatoria(){
for(int n=0;n<5;n++){ //sumatoria y activación
sum=sum+w[n]*normx[n];
}
fx=1/(1+exp((sum+bias)*-1));
}//para realizar la sumatoria y activación
float getfx(){
return fx;
}//para obtener la salida de la neurona
};
| true |
4284f6639329325b0081daa373f08ab0986c214d
|
C++
|
swift1719/SPPU-data-structures-assignments
|
/assignment17.cpp
|
UTF-8
| 3,429 | 3.328125 | 3 |
[] |
no_license
|
#include<bits/stdc++.h>
using namespace std;
void linearsearch()
{
int arr[100], i, num, n, c=0, pos;
cout<<"Enter the array size : ";
cin>>n;
cout<<"Enter Array Elements : ";
for(i=0; i<n; i++)
{
cin>>arr[i];
}
cout<<"Enter the number to be search : ";
cin>>num;
for(i=0; i<n; i++)
{
if(arr[i]==num)
{
c=1;
pos=i+1;
break;
}
}
if(c==0)
{
cout<<"Number not found..!!";
}
else
{
cout<<num<<" found at position "<<pos;
}}
void binarysearch()
{
int n, i, arr[50], search, first, last, middle;
cout<<"Enter the array size : ";
cin>>n;
cout<<"Enter Array Elements(NOTE:IN SORTED ORDER) : ";
for (i=0; i<n; i++)
{
cin>>arr[i];
}
cout<<"Enter a number to find :";
cin>>search;
first = 0;
last = n-1;
middle = (first+last)/2;
while (first <= last)
{
if(arr[middle] < search)
{
first = middle + 1;
}
else if(arr[middle] == search)
{
cout<<search<<" found at location "<<middle+1<<"\n";
break;
}
else
{
last = middle - 1;
}
middle = (first + last)/2;
}
if(first > last)
{
cout<<"Not found! "<<search<<" is not present in the list.";
}
}
void sentinelsearch()
{
int arr[100],i, num, n;
cout<<"Enter the array size : ";
cin>>n;
cout<<"Enter Array Elements : ";
for( i=0; i<n; i++)
{
cin>>arr[i];
}
cout<<"Enter the number to be search : ";
cin>>num;
int last = arr[n-1];
arr[n-1] = num;
i = 0;
while(arr[i]!=num)
{
i++;
}
arr[n-1] = last;
if( (i < n-1) || (num == arr[n-1]) )
{
cout << " Found at "<<i+1;
}
else
{
cout << " Not Found";
}
}
int fibo(int j)
{
if(j==0)
return 0;
if(j==1)
return 1;
else
return ((fibo(j-1))+(fibo(j-2)));
}
void fibSearch()
{ int arr[100],num,n,i;
int f1,f2,j,mid;
j=1;
cout<<"Enter the array size : ";
cin>>n;
cout<<"Enter Array Elements :(NOTE:IN SORTED ORDER) ";
for( i=0; i<n; i++)
{
cin>>arr[i];
}
cout<<"Enter the number to be search : ";
cin>>num;
while(fibo(j)<=n)
j++;
f1=fibo(j-2);
f2=fibo(j-3);
mid=n-f1+1;
while(num!=arr[mid])
{
if(num>arr[mid])
{
if(f1==1)
break;
mid=mid+f2;
f1=f1-f2;
f2=f2-f1;
}
else
{
if(f2==0)
break;
mid=mid-f2;
int temp=f1-f2;
f1=f2;
f2=temp;
}
}
if(arr[mid]==num)
cout<<"found at:"<<mid+1;
else
cout<<"Not found";
}
int main()
{
int ch;
char c;
for(;;)
{
cout<<"\n1.LINEAR SEARCH\n2.BINARY SEARCH\n3.SENTINEL SEARCH\n4.FIBBONACCI SEARCH\n5->EXIT";
cout<<"\nENTER YOUR CHOICE:";
cin>>ch;
switch(ch)
{
case 1:
linearsearch();
break;
case 2:
binarysearch();
break;
case 3:
sentinelsearch();
break;
case 4:
fibSearch();
break;
case 5:
exit(0);
break;
default:cout<<"WRONG CHOICE";
}
}
return 0;
}
| true |
af98029055f990e4e017a67c1d443719a21294b8
|
C++
|
chankruze/challenges
|
/sololearn/SecretMessage/SecretMessage.cpp
|
UTF-8
| 735 | 2.71875 | 3 |
[] |
no_license
|
/*
Author: chankruze (chankruze@geekofia.in)
Created: Sun Aug 09 2020 21:23:42 GMT+0530 (India Standard Time)
Copyright (c) Geekofia 2020 and beyond
*/
#include <bits/stdc++.h>
#include <iostream>
#include <vector>
using namespace std;
string encodeWord(string str) {
string enc = "";
string alphabets = "abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < str.length(); i++) {
enc += alphabets[26 - alphabets.find(tolower(str[i]))];
}
return enc + " ";
}
int main(int argc, char const *argv[]) {
string _in, word, encoded = "";
getline(cin >> ws, _in);
stringstream ss(_in);
while (getline(ss, word, ' ')) {
encoded += encodeWord(word);
}
cout << encoded << endl;
return 0;
}
| true |
31ac252872095a3322bb191be29b0ef3b3f88be5
|
C++
|
CRI-MotionLab/movuino-firmware
|
/firmware/Timer.cpp
|
UTF-8
| 1,318 | 2.921875 | 3 |
[] |
no_license
|
#include <Arduino.h>
#include "Timer.h"
void
Timer::setPeriod(unsigned long p) {
period = p;
}
void
Timer::start(unsigned long t) {
if (!running) {
timeout = t;
nextPeriod = period;
startDate = lastDate = millis();
running = true;
// callback();
}
}
void
Timer::stop() {
if (running) {
running = false;
}
}
void
Timer::update() {
if (!running) return;
unsigned long now = millis();
// with error compensation (doesn't work ATM, todo: hunt bugs) :
// long error = now - (lastDate + nextPeriod);
// if (error >= 0) {
// if (timeout == 0 || now - startDate < timeout) {
// callback();
// } else {
// stop();
// return;
// }
// // recompute in case callback took too long
// now = millis();
// error = now - (lastDate + nextPeriod);
// if (period > error) {
// nextPeriod = period - error;
// } else { // // in case the code takes too long to execute, we ignore the error
// nextPeriod = period;
// }
// lastDate = now;
// }
// dumber version :
// seems to work well enough in case there are problems with the version above
if (now >= lastDate + period) {
lastDate = now;
if (timeout == 0 || now - startDate < timeout) {
callback();
} else {
stop();
}
}
}
| true |
71871f08800bd65cc4800510f07631e07cc3b017
|
C++
|
GustavPS/X-runner
|
/states/abstract/state.cc
|
UTF-8
| 574 | 2.640625 | 3 |
[] |
no_license
|
#include "state.h"
State::~State()
{
for (auto &kv : textures)
delete kv.second;
for (auto *object : objects)
delete object;
}
const sf::Sprite& State::get_background() const
{ return background; }
const std::vector<const Object*>& State::get_texturated_objects() const
{ return texturated_objects; }
std::unordered_map<std::string, sf::Text>& State::ref_text_objects()
{ return text_objects; }
void State::soft_reset()
{
for (auto *object : objects)
delete object;
objects.clear();
texturated_objects.clear();
}
| true |
312326a69075e72b4fc20feeee95a447f86a150c
|
C++
|
Comp208-Antism/Antism
|
/zone.cpp
|
UTF-8
| 597 | 2.671875 | 3 |
[] |
no_license
|
#include "zone.h"
Zone::Zone(int width, int height)
{
this->setSize(sf::Vector2f(width, height));
}
Zone::~Zone()
{
}
int Zone::update(sf::Vector2f mousePos) {
if (mousePos.x > this->getGlobalBounds().left && mousePos.x < this->getGlobalBounds().left + this->getGlobalBounds().width
&& mousePos.y > this->getGlobalBounds().top && mousePos.y < this->getGlobalBounds().top + this->getGlobalBounds().height) {
if (sf::Mouse::isButtonPressed(sf::Mouse::Left)) {
return leftClicked;
}
if (sf::Mouse::isButtonPressed(sf::Mouse::Right)) {
return rightClicked;
}
}
return 99;
}
| true |
03faa80f407d5b80c145d81207552f1823079194
|
C++
|
samuelokrent/virtual_socket
|
/src/client_proxy.cpp
|
UTF-8
| 1,104 | 2.90625 | 3 |
[] |
no_license
|
#include <string>
#include <unistd.h>
#include "client_proxy.h"
#include "network_util.h"
using std::cout;
using std::endl;
using std::string;
#define CLIENT_PORT "6071"
ClientProxy::ClientProxy(string id) {
this->id = id;
}
void ClientProxy::start() {
cout << "Starting client proxy" << endl;
// Create connection to proxy server
if(connect() < 0) {
cout << "Error: Could not connect to proxy server" << endl;
return;
}
cout << "Sending connect request..." << endl;
string connectReq = protocol.makeConnectRequest(id);
Protocol::Response connectRes = sendRequest(connectReq);
if(connectRes.isOK()) {
cout << "Connected. Start listening for connections on port " << CLIENT_PORT << endl;
// Start listening for the service-client connection
run(CLIENT_PORT);
} else {
cout << "Error: " << connectRes.getErrorMessage() << endl;
close(connection);
}
}
int ClientProxy::handleRequest(int requestFd) {
cout << "Received connection. Begin facilitating" << endl;
NetworkUtil::facilitateConnection(requestFd, connection);
exit(0);
return 0;
}
| true |
0161410b5cc2fc3bb370f9db731face82cbf3082
|
C++
|
Natador/2playerSocketSnake
|
/source/server/serves.cpp
|
UTF-8
| 5,798 | 2.78125 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/select.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <string.h>
#include <unistd.h>
#include <iostream>
#include "server.h"
#include "../include/SnakeFood.h"
#include "../include/SnakeHead.h"
bool looper(int master_socket, int max_clients, int client_socket[2], sockaddr_in address, int addrlen, BoardState& currentState, int &pInt)
{
fd_set readfds;
int max_sd,
activity,
valread,
sd, // current socket connected to
new_socket,
i; // iterators
char buffer[1025];
//clear the socket set
FD_ZERO(&readfds);
//add master socket to set
FD_SET(master_socket, &readfds);
max_sd = master_socket;
//add child sockets to set
for ( i = 0 ; i < max_clients ; i++)
{
//socket descriptor
sd = client_socket[i];
//if valid socket descriptor then add to read list
if(sd > 0)
FD_SET( sd , &readfds);
//highest file descriptor number, need it for the select function
if(sd > max_sd)
max_sd = sd;
}
//wait for an activity on one of the sockets , timeout is NULL ,
//so wait indefinitely
printf("Waiting for connection\n");
activity = select( max_sd + 1 , &readfds , NULL , NULL , NULL);
printf("Got some activity\n");
if ((activity < 0) && (errno!=EINTR))
{
printf("select error");
}
// If the activity is on the master socket, then it is a new connection.
// Accept only if the number of players is less than 2
if (FD_ISSET(master_socket, &readfds)) {
if ((new_socket = accept(master_socket, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
perror("accept");
exit(EXIT_FAILURE);
}
//inform user of socket number - used in send and receive commands
printf("New connection , socket fd is %d , ip is : %s , port : %d\n", new_socket , inet_ntoa(address.sin_addr) , ntohs(address.sin_port));
// Send player their player number (1 or 2)
memcpy(buffer, &pInt, sizeof(int));
if( send(new_socket, buffer, sizeof(int ), 0) != sizeof(int)) {
perror("send");
}
// increasements player number and displays to the server screen
std::cout << "Player "<< pInt++ << " has joined.\n";
//add new socket to array of sockets
for (i = 0; i < max_clients; i++) {
//if position is empty
if( client_socket[i] == 0 ) {
client_socket[i] = new_socket;
break;
}
}
}
//else its some IO operation on some other socket
bool playFlag = true; // determines if there is a winner or if they should keep playing
BoardState tempState;
for (i = 0; i < max_clients && pInt > 2; i++)
{
sd = client_socket[i]; // gets a client
if (FD_ISSET( sd , &readfds))
{
// Check for a request or disconnect from the client
printf("Listening for request\n");
if ( (valread = read(sd, buffer, sizeof(BoardState))) == 0 )
{
//Somebody disconnected , get his details and print
getpeername(sd, (struct sockaddr*)&address, (socklen_t*)&addrlen);
printf("Client %d disconnected, ip %s, port %d\n", i, inet_ntoa(address.sin_addr), ntohs(address.sin_port));
//Close the socket and mark as 0 in list for reuse
close( sd );
client_socket[i] = 0;
// Do not continue playing
playFlag = false;
}
// Send the client the updated board state and receive their new
else
{
printf("Sending state to client\n");
if (send(sd, ¤tState, sizeof(BoardState), 0) != sizeof(BoardState)) {
perror("BoardState send");
exit(1);
}
// Receive updated state from client
printf("Reading reply from client\n");
valread = read(sd, &tempState, sizeof(BoardState));
// If return value is zero, client disconnected.
if (valread == 0) {
//Somebody disconnected , get his details and print
getpeername(sd, (struct sockaddr*)&address, (socklen_t*)&addrlen);
printf("Client %d disconnected, ip %s, port %d\n", i, inet_ntoa(address.sin_addr), ntohs(address.sin_port));
//Close the socket and mark as 0 in list for reuse
close( sd );
client_socket[i] = 0;
// Do not continue playing
playFlag = false;
// Set game over
currentState.game_on = false;
} else {
// Update state from client
currentState = tempState;
// Check if the player won
if (!currentState.game_on) {
// Do not continue playing
playFlag = false;
// Send the current state to the other player
//
// Get the request and check for disconnect
if ( (valread = read(sd, buffer, sizeof(BoardState))) == 0 )
{
//Somebody disconnected , get his details and print
getpeername(sd, (struct sockaddr*)&address, (socklen_t*)&addrlen);
printf("Client %d disconnected, ip %s, port %d\n", i, inet_ntoa(address.sin_addr), ntohs(address.sin_port));
//Close the socket and mark as 0 in list for reuse
close( sd );
client_socket[i] = 0;
} else {
if (send(sd, ¤tState, sizeof(BoardState), 0) != sizeof(BoardState)) {
perror("BoardState send");
exit(1);
}
}
// Exit the loop
break;
// Do not continue playing
playFlag = false;
}
}
}// end of else statement
}// end of outer if statement
} // end of for loop, looping over max_clients
return playFlag;
} //end of looper
| true |
e882de56975e22a680232b7aca0d9e6047025bfb
|
C++
|
kshigedomi/RFSE
|
/src/Util.h
|
UTF-8
| 3,535 | 2.9375 | 3 |
[] |
no_license
|
#ifndef UTIL_H_
#define UTIL_H_
/*
* Util.h
*
* Created on: 2012. 11. 27.
* Author: chaerim
*/
#ifndef COMMON_H_
#include "Common.h"
#endif
#include <setjmp.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
namespace MyUtil {
// For IO
string numberToRational(const string &num);
string toString(const int val);
string rationalToString(const PreciseNumber &val);
string resultToString(const Result &result);
int toInteger(const string &val);
string spaceToString(const string &s, const int size);
vector<string> splitAtSpace(istream &fin);
vector<string> splitAtSpace(const string &s);
vector<string> split(const string &s, const char &c);
ostream& operator << (ostream& os, const vector<vector<PreciseNumber> > &matrix);
ostream& operator << (ostream& os, const vector<PreciseNumber> &vec);
// For next
bool next(vector<PreciseNumber> &v, const vector<PreciseNumber> &start, const vector<PreciseNumber> &interval, const vector<PreciseNumber> &end);
bool normalNextMatrix(vector<vector<PreciseNumber> >&matrix, const vector<vector<PreciseNumber> > &start, const PreciseNumber &interval, const vector<vector<PreciseNumber> > &end);
bool normalNext(vector<PreciseNumber> &v, const vector<PreciseNumber> &start, const PreciseNumber &interval, const vector<PreciseNumber> &end);
bool increment(vector<int> &vec, const int limit);
bool increment(vector<PreciseNumber> &vec, const PreciseNumber &from, const PreciseNumber &interval, const PreciseNumber &to);
bool increment(vector<vector<PreciseNumber> > &matrix, const PreciseNumber &from, const PreciseNumber &interval, const PreciseNumber &to);
bool slide(vector<int> &vec);
// For matrix
vector<vector<PreciseNumber> > getTransposedMatrix(const vector<vector<PreciseNumber> > &matrix);
vector<vector<PreciseNumber> > getIdentityMatrix(const vector<vector<PreciseNumber> >::size_type size);
vector<vector<PreciseNumber> > matrixMul(const vector<vector<PreciseNumber> > &m1, const vector<vector<PreciseNumber> > &m2);
vector<PreciseNumber> matrixVectorProduct(const vector<vector<PreciseNumber> > &matrix, const vector<PreciseNumber> &vec);
vector<PreciseNumber> vectorMatrixProduct(const vector<PreciseNumber> &vec, const vector<vector<PreciseNumber> > &matrix);
PreciseNumber innerProduct(const vector<PreciseNumber> &vec1, const vector<PreciseNumber> &vec2);
bool checkRegularity(const vector<vector<PreciseNumber> > &matrix, const int endTurn);
bool checkRegularity(const vector<vector<int> > &matrix, const int endTurn);
vector<PreciseNumber> normalize(const vector<PreciseNumber> &vec);
// For rational number
bool equal(const PreciseNumber &, const PreciseNumber &);
int getIndex(const vector<string> &list, const string &value);
PreciseNumber pow(const PreciseNumber &x, const int y);
PreciseNumber sqrt(const PreciseNumber &x);
bool nonumber(const char &c);
bool nextWord(istream &is, string &buf);
};
/*
* 機能: メッセージを出力
* メモ: 特別な意味はないが,プリントデバックをcout,cerr に,
* プログラムとしての出力をこの関数に任せると後が楽
*/
namespace Message {
template<typename T>
void display(const T &msg) {
cout << msg << endl;
}
template<typename T>
void alert(const T &msg) {
cerr << "* Error : " << msg << endl;
}
};
#endif /* UTIL_H_ */
| true |
e072fa997c243c94f735df4d86b1b42ff861769e
|
C++
|
VanishRan/leetcode
|
/RanLeetCode/RanLeetCode/树/145二叉树的后序遍历.cpp
|
UTF-8
| 1,452 | 3.3125 | 3 |
[] |
no_license
|
//
// 145二叉树的后序遍历.cpp
// RanLeetCode
//
// Created by mahuanran on 2020/8/17.
// Copyright © 2020 mahuanran. All rights reserved.
//
#include "common.h"
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
if (root == NULL) {
return res;
}
map<TreeNode *, bool> mp;
stack<TreeNode *> s;
s.push(root);
while (!s.empty()) {
TreeNode *cur = s.top();
bool leftVisited = true;
bool rightVisited = true;
if (cur->right && !mp[cur->right]) {
s.push(cur->right);
rightVisited = false;
}
if (cur->left && !mp[cur->left]) {
s.push(cur->left);
leftVisited = false;
}
if (leftVisited && rightVisited) {
res.push_back(cur->val);
mp[cur] = true;
s.pop();
}
}
return res;
}
};
/*
给定一个二叉树,返回它的 后序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [3,2,1]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-postorder-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
| true |
795c322ae96e6fbaddceb0a11686c3d3a1f94d4a
|
C++
|
broune/mathic
|
/src/mathic/PackedKDTree.h
|
UTF-8
| 23,315 | 2.59375 | 3 |
[] |
no_license
|
#ifndef MATHIC_PACKED_K_D_TREE_GUARD
#define MATHIC_PACKED_K_D_TREE_GUARD
#include "stdinc.h"
#include "DivMask.h"
#include "KDEntryArray.h"
#include <memtailor.h>
#include <ostream>
namespace mathic {
template<class C>
class PackedKDTree {
public:
typedef typename C::Monomial Monomial;
typedef typename C::Entry Entry;
typedef typename C::Exponent Exponent;
typedef typename DivMask::Extender<Entry, C::UseDivMask> ExtEntry;
typedef typename DivMask::Extender<const Monomial&,C::UseDivMask> ExtMonoRef;
typedef typename DivMask::Calculator<C> DivMaskCalculator;
struct ExpOrder {
ExpOrder(size_t var, const C& conf): _var(var), _conf(conf) {}
bool operator()(const ExtEntry& a, const ExtEntry& b) const {
return _conf.getExponent(a.get(), _var) < _conf.getExponent(b.get(), _var);
}
private:
const size_t _var;
const C& _conf;
};
private:
typedef C Configuration;
static const bool UseDivMask = C::UseDivMask;
class Node {
public:
static Node* makeNode(memt::Arena& arena, const C& conf) {
return new (arena.alloc(sizeOf(0)))
Node(arena, conf);
}
template<class Iter>
static Node* makeNode(Iter begin, Iter end, memt::Arena& arena,
const C& conf, size_t childCount) {
return new (arena.alloc(sizeOf(childCount)))
Node(begin, end, arena, conf, childCount);
}
template<class Iter>
static Node* makeNode(Iter begin, Iter end, memt::Arena& arena,
const DivMaskCalculator& calc, const C& conf, size_t childCount) {
return new (arena.alloc(sizeOf(childCount)))
Node(begin, end, arena, calc, conf, childCount);
}
static size_t sizeOf(size_t childCount) {
if (childCount > 0)
--childCount; // array has size 1, so one element already there
return sizeof(Node) + childCount * sizeof(Child);
}
struct Child : public mathic::DivMask::HasDivMask<C::UseTreeDivMask> {
size_t var;
Exponent exponent;
Node* node;
};
typedef Child* iterator;
typedef Child const* const_iterator;
iterator childBegin() {return _childrenMemoryBegin;}
const_iterator childBegin() const {return _childrenMemoryBegin;}
iterator childEnd() {return _childrenEnd;}
const_iterator childEnd() const {return _childrenEnd;}
bool hasChildren() const {return childBegin() != childEnd();}
template<class ME> // ME is MonomialOrEntry
bool inChild(const_iterator child, const ME me, const C& conf) const {
return child->exponent < conf.getExponent(me, child->var);
}
mathic::KDEntryArray<C, ExtEntry>& entries() {return _entries;}
const KDEntryArray<C, ExtEntry>& entries() const {return _entries;}
Node* splitInsert(
const ExtEntry& extEntry,
Child* childFromParent,
memt::Arena& arena,
const C& conf);
/// Asserts internal invariants if asserts are turned on.
bool debugIsValid() const;
private:
Node(const Node&); // unavailable
void operator=(const Node&); // unavailable
Node(memt::Arena& arena, const C& conf);
template<class Iter>
Node(Iter begin, Iter end, memt::Arena& arena,
const C& conf, size_t childCount);
template<class Iter>
Node(Iter begin, Iter end, memt::Arena& arena,
const DivMaskCalculator& calc, const C& conf, size_t childCount);
class SplitEqualOrLess;
KDEntryArray<C, ExtEntry> _entries;
// Array has size 1 to appease compiler since size 0 produces warnings
// or errors. Actual size can be greater if more memory has been
// allocated for the node than sizeof(Node).
Child* _childrenEnd; // points into _childrenMemoryBegin
Child _childrenMemoryBegin[1];
};
public:
PackedKDTree(const C& configuration);
~PackedKDTree();
template<class MultipleOutput>
size_t removeMultiples(const ExtMonoRef& monomial, MultipleOutput& out);
bool removeElement(const Monomial& monomial);
void insert(const ExtEntry& entry);
template<class Iter>
void reset(Iter begin, Iter end, const DivMaskCalculator& calc);
inline Entry* findDivisor(const ExtMonoRef& monomial);
template<class DivisorOutput>
inline void findAllDivisors
(const ExtMonoRef& monomial, DivisorOutput& out);
template<class DivisorOutput>
inline void findAllMultiples
(const ExtMonoRef& monomial, DivisorOutput& out);
template<class EntryOutput>
void forAll(EntryOutput& out);
void clear();
size_t getMemoryUse() const;
void print(std::ostream& out) const;
C& getConfiguration() {return _conf;}
bool debugIsValid() const;
private:
PackedKDTree(const PackedKDTree<C>&); // unavailable
void operator=(const PackedKDTree<C>&); // unavailable
template<class Iter>
struct InsertTodo {
Iter begin;
Iter end;
Exponent exp;
size_t var;
typename Node::Child* fromParent;
};
memt::Arena _arena; // Everything permanent allocated from here.
C _conf; // User supplied configuration.
mutable std::vector<Node*> _tmp; // For navigating the tree.
Node* _root; // Root of the tree. Can be null!
};
template<class C>
PackedKDTree<C>::PackedKDTree(const C& configuration):
_conf(configuration), _root(0) {
MATHIC_ASSERT(C::LeafSize > 0);
MATHIC_ASSERT(debugIsValid());
}
template<class C>
PackedKDTree<C>::~PackedKDTree() {
clear();
}
template<class C>
PackedKDTree<C>::Node::Node(memt::Arena& arena, const C& conf):
_entries(arena, conf) {
_childrenEnd = childBegin();
}
template<class C>
template<class Iter>
PackedKDTree<C>::Node::Node(
Iter begin,
Iter end,
memt::Arena& arena,
const C& conf,
size_t childCount):
_entries(begin, end, arena, conf) {
_childrenEnd = childBegin() + childCount;
}
template<class C>
template<class Iter>
PackedKDTree<C>::Node::Node(
Iter begin,
Iter end,
memt::Arena& arena,
const DivMaskCalculator& calc,
const C& conf,
size_t childCount):
_entries(begin, end, arena, calc, conf) {
_childrenEnd = childBegin() + childCount;
}
template<class C>
template<class MO>
size_t PackedKDTree<C>::removeMultiples(
const ExtMonoRef& extMonomial,
MO& out
) {
MATHIC_ASSERT(_tmp.empty());
if (_root == 0)
return 0;
size_t removedCount = 0;
Node* node = _root;
while (true) {
for (typename Node::const_iterator it = node->childBegin();
it != node->childEnd(); ++it) {
_tmp.push_back(it->node);
if (node->inChild(it, extMonomial.get(), _conf))
goto stopped;
}
removedCount += node->entries().removeMultiples(extMonomial, out, _conf);
stopped:;
if (_tmp.empty())
break;
node = _tmp.back();
_tmp.pop_back();
}
MATHIC_ASSERT(_tmp.empty());
MATHIC_ASSERT(debugIsValid());
return removedCount;
}
template<class C>
bool PackedKDTree<C>::removeElement(const Monomial& monomial) {
MATHIC_ASSERT(_tmp.empty());
if (_root == 0)
return false;
Node* node = _root;
typename Node::iterator child = node->childBegin();
while (child != node->childEnd()) {
if (node->inChild(child, monomial, _conf)) {
node = child->node;
child = node->childBegin();
} else
++child;
}
const bool value = node->entries().removeElement(monomial, _conf);
MATHIC_ASSERT(debugIsValid());
return value;
}
template<class C>
void PackedKDTree<C>::insert(const ExtEntry& extEntry) {
MATHIC_ASSERT(debugIsValid());
// find node in which to insert extEntry
typename Node::Child* parentChild = 0;
if (_root == 0)
_root = Node::makeNode(_arena, _conf);
Node* node = _root;
typename Node::iterator child = node->childBegin();
while (true) {
if (child == node->childEnd()) {
MATHIC_ASSERT(node->entries().size() <= C::LeafSize);
if (node->entries().size() < C::LeafSize)
node->entries().insert(extEntry, _conf);
else { // split full node
node = node->splitInsert(extEntry, parentChild, _arena, _conf);
if (parentChild == 0)
_root = node;
}
break;
}
if (C::UseTreeDivMask)
child->updateToLowerBound(extEntry);
if (node->inChild(child, extEntry.get(), _conf)) {
parentChild = &*child;
node = child->node;
child = node->childBegin();
} else
++child;
}
MATHIC_ASSERT(debugIsValid());
}
template<class C>
template<class Iter>
void PackedKDTree<C>::reset(Iter insertBegin, Iter insertEnd, const DivMaskCalculator& calc) {
clear();
if (insertBegin == insertEnd)
return;
typedef InsertTodo<Iter> Task;
typedef std::vector<Task> TaskCont;
TaskCont todo;
TaskCont children;
{
Task initialTask;
initialTask.begin = insertBegin;
initialTask.end = insertEnd;
initialTask.var = static_cast<size_t>(-1);
initialTask.fromParent = 0;
todo.push_back(initialTask);
}
while (!todo.empty()) {
Iter begin = todo.back().begin;
Iter end = todo.back().end;
size_t var = todo.back().var;
typename Node::Child* fromParent = todo.back().fromParent;
if (fromParent != 0) {
fromParent->var = var;
fromParent->exponent = todo.back().exp;
}
todo.pop_back();
// split off children until reaching few enough entries
while (C::LeafSize < static_cast<size_t>(std::distance(begin, end))) {
Task child;
Iter middle = KDEntryArray<C, ExtEntry>::
split(begin, end, var, child.exp, _conf);
MATHIC_ASSERT(begin < middle && middle < end);
MATHIC_ASSERT(var < _conf.getVarCount());
child.begin = middle;
child.end = end;
child.var = var;
children.push_back(child);
// now operate on the equal-or-less part of the range
end = middle;
}
Node* node = Node::makeNode
(begin, end, _arena, calc, _conf, children.size());
if (_root == 0)
_root = node;
if (fromParent != 0)
fromParent->node = node;
for (size_t child = 0; child < children.size(); ++child) {
children[child].fromParent = &*(node->childBegin() + child);
todo.push_back(children[child]);
}
children.clear();
}
MATHIC_ASSERT(_root != 0);
if (C::UseTreeDivMask) {
// record nodes in tree using breadth first search
typedef std::vector<Node*> NodeCont;
NodeCont nodes;
nodes.push_back(_root);
for (size_t i = 0; i < nodes.size(); ++i) {
Node* node = nodes[i];
for (typename Node::iterator child = node->childBegin();
child != node->childEnd(); ++child)
nodes.push_back(child->node);
}
// compute div masks in reverse order of breath first search
typename NodeCont::reverse_iterator it = nodes.rbegin();
typename NodeCont::reverse_iterator end = nodes.rend();
for (; it != end; ++it) {
Node* node = *it;
typedef std::reverse_iterator<typename Node::iterator> riter;
riter rbegin = riter(node->childEnd());
riter rend = riter(node->childBegin());
for (riter child = rbegin; child != rend; ++child) {
child->resetDivMask();
if (child == rbegin)
child->updateToLowerBound(node->entries());
else {
riter prev = child;
--prev;
child->updateToLowerBound(*prev);
}
if (child->node->hasChildren())
child->updateToLowerBound(*child->node->childBegin());
else
child->updateToLowerBound(child->node->entries());
}
MATHIC_ASSERT(node->debugIsValid());
}
}
MATHIC_ASSERT(debugIsValid());
}
template<class C>
typename PackedKDTree<C>::Entry* PackedKDTree<C>::findDivisor
(const ExtMonoRef& extMonomial) {
MATHIC_ASSERT(_tmp.empty());
if (_root == 0)
return 0;
Node* node = _root;
while (true) {
// record relevant children for later processing
for (typename Node::const_iterator it = node->childBegin();
it != node->childEnd(); ++it) {
if (C::UseTreeDivMask &&
!it->getDivMask().canDivide(extMonomial.getDivMask()))
goto next;
if (node->inChild(it, extMonomial.get(), _conf))
_tmp.push_back(it->node);
}
// look for divisor in entries of node
{
typename KDEntryArray<C, ExtEntry>::iterator it =
node->entries().findDivisor(extMonomial, _conf);
if (it != node->entries().end()) {
MATHIC_ASSERT(_conf.divides(it->get(), extMonomial.get()));
_tmp.clear();
return &it->get();
}
}
next:
// grab next node to process
if (_tmp.empty())
break;
node = _tmp.back();
_tmp.pop_back();
}
MATHIC_ASSERT(_tmp.empty());
return 0;
}
template<class C>
template<class DO>
void PackedKDTree<C>::findAllDivisors(
const ExtMonoRef& extMonomial,
DO& output
) {
MATHIC_ASSERT(_tmp.empty());
if (_root == 0)
return;
Node* node = _root;
while (true) {
for (typename Node::const_iterator it = node->childBegin();
it != node->childEnd(); ++it) {
if (C::UseTreeDivMask &&
!it->getDivMask().canDivide(extMonomial.getDivMask()))
goto next; // div mask rules this sub tree out
if (node->inChild(it, extMonomial.get(), _conf))
_tmp.push_back(it->node);
}
if (!node->entries().findAllDivisors(extMonomial, output, _conf)) {
_tmp.clear();
break;
}
next:
if (_tmp.empty())
break;
node = _tmp.back();
_tmp.pop_back();
}
MATHIC_ASSERT(_tmp.empty());
}
template<class C>
template<class DO>
void PackedKDTree<C>::findAllMultiples(
const ExtMonoRef& extMonomial,
DO& output
) {
MATHIC_ASSERT(_tmp.empty());
if (_root == 0)
return;
Node* node = _root;
while (true) {
for (typename Node::const_iterator it = node->childBegin();
it != node->childEnd(); ++it) {
_tmp.push_back(it->node);
if (node->inChild(it, extMonomial.get(), _conf))
goto next;
}
if (!node->entries().findAllMultiples(extMonomial, output, _conf)) {
_tmp.clear();
break;
}
next:
if (_tmp.empty())
break;
node = _tmp.back();
_tmp.pop_back();
}
MATHIC_ASSERT(_tmp.empty());
}
template<class C>
template<class EO>
void PackedKDTree<C>::forAll(EO& output) {
MATHIC_ASSERT(_tmp.empty());
if (_root == 0)
return;
Node* node = _root;
while (true) {
if (!node->entries().forAll(output)) {
_tmp.clear();
break;
}
for (typename Node::iterator it = node->childBegin();
it != node->childEnd(); ++it)
_tmp.push_back(it->node);
if (_tmp.empty())
break;
node = _tmp.back();
_tmp.pop_back();
}
MATHIC_ASSERT(_tmp.empty());
}
template<class C>
void PackedKDTree<C>::clear() {
MATHIC_ASSERT(_tmp.empty());
// Call Entry destructors
if (_root != 0)
_tmp.push_back(_root);
while (!_tmp.empty()) {
Node* node = _tmp.back();
_tmp.pop_back();
node->entries().clear(); // calls destructors
for (typename Node::iterator it = node->childBegin();
it != node->childEnd(); ++it)
_tmp.push_back(it->node);
}
_arena.freeAllAllocs();
_root = 0;
}
template<class C>
size_t PackedKDTree<C>::getMemoryUse() const {
// todo: not accurate
size_t sum = _arena.getMemoryUse();
sum += _tmp.capacity() * sizeof(_tmp.front());
return sum;
}
template<class C>
void PackedKDTree<C>::print(std::ostream& out) const {
out << "<<<<<<<< PackedKDTree >>>>>>>>\n";
MATHIC_ASSERT(_tmp.empty());
if (_root == 0)
return;
Node* node = _root;
while (true) {
out << "**** Node " << node << "\nchildren:\n";
for (typename Node::iterator it = node->childBegin();
it != node->childEnd(); ++it) {
_tmp.push_back(it->node);
out << "Child " << ((it - node->childBegin()) + 1) << ": "
<< '>' << (it->var + 1) << '^' << it->exponent
<< ' ' << it->node << '\n';
}
for (size_t i = 0; i < node->entries().size(); ++i) {
out << "Entry " << (i + 1) << ": "
<< node->entries().begin()[i].get() << '\n';
}
out << '\n';
if (_tmp.empty())
break;
node = _tmp.back();
_tmp.pop_back();
}
MATHIC_ASSERT(_tmp.empty());
}
template<class C>
bool PackedKDTree<C>::debugIsValid() const {
#ifndef MATHIC_DEBUG
return true;
#else
//print(std::cerr); std::cerr << std::flush;
MATHIC_ASSERT(_tmp.empty());
MATHIC_ASSERT(!_conf.getDoAutomaticRebuilds() || _conf.getRebuildRatio() > 0);
if (_root == 0)
return true;
// record all nodes
std::vector<Node*> nodes;
nodes.push_back(_root);
for (size_t i = 0; i < nodes.size(); ++i) {
Node* node = nodes[i];
MATHIC_ASSERT(node->entries().debugIsValid());
for (typename Node::iterator it = node->childBegin();
it != node->childEnd(); ++it) {
MATHIC_ASSERT(it->var < _conf.getVarCount());
MATHIC_ASSERT(!C::UseTreeDivMask ||
it->canDivide(node->entries()));
nodes.push_back(it->node);
}
}
// check the recorded nodes
MATHIC_ASSERT(_tmp.empty());
for (size_t i = 0; i < nodes.size(); ++i) {
Node* ancestor = nodes[i];
for (typename Node::iterator ancestorIt = ancestor->childBegin();
ancestorIt != ancestor->childEnd(); ++ancestorIt) {
MATHIC_ASSERT(_tmp.empty());
size_t var = ancestorIt->var;
Exponent exp = ancestorIt->exponent;
// check strictly greater than subtree
_tmp.push_back(ancestorIt->node);
while (!_tmp.empty()) {
Node* node = _tmp.back();
_tmp.pop_back();
for (typename Node::iterator it = node->childBegin();
it != node->childEnd(); ++it) {
MATHIC_ASSERT(!C::UseTreeDivMask || ancestorIt->canDivide(*it));
_tmp.push_back(it->node);
}
MATHIC_ASSERT(node->entries().
allStrictlyGreaterThan(var, exp, _conf));
MATHIC_ASSERT(!C::UseTreeDivMask ||
ancestorIt->canDivide(node->entries()));
}
// check less than or equal to sub tree.
MATHIC_ASSERT(ancestor->entries().
allLessThanOrEqualTo(var, exp, _conf));
// go through the rest of the children
typename Node::iterator restIt = ancestorIt;
for (++restIt; restIt != ancestor->childEnd(); ++restIt) {
MATHIC_ASSERT(!C::UseTreeDivMask || ancestorIt->canDivide(*restIt));
_tmp.push_back(restIt->node);
}
while (!_tmp.empty()) {
Node* node = _tmp.back();
_tmp.pop_back();
for (typename Node::iterator it = node->childBegin();
it != node->childEnd(); ++it) {
MATHIC_ASSERT(!C::UseTreeDivMask || ancestorIt->canDivide(*it));
_tmp.push_back(it->node);
}
MATHIC_ASSERT(node->entries().
allLessThanOrEqualTo(var, exp, _conf));
MATHIC_ASSERT(!C::UseTreeDivMask ||
ancestorIt->canDivide(node->entries()));
}
}
}
return true;
#endif
}
template<class C>
class PackedKDTree<C>::Node::SplitEqualOrLess {
public:
typedef typename C::Exponent Exponent;
typedef typename C::Entry Entry;
SplitEqualOrLess(size_t var, const Exponent& exp, const C& conf):
_var(var), _exp(exp), _conf(conf) {}
bool operator()(const Entry& entry) const {
return !(_exp < _conf.getExponent(entry, _var));
}
private:
size_t _var;
const Exponent& _exp;
const C& _conf;
};
template<class C>
typename PackedKDTree<C>::Node* PackedKDTree<C>::Node::splitInsert(
const ExtEntry& extEntry,
Child* childFromParent,
memt::Arena& arena,
const C& conf
) {
MATHIC_ASSERT(conf.getVarCount() > 0);
MATHIC_ASSERT(entries().size() > 0);
size_t var;
if (hasChildren())
var = (childEnd() - 1)->var;
else if (childFromParent != 0)
var = childFromParent->var;
else
var = static_cast<size_t>(-1);
typename C::Exponent exp;
// there is not room to add another child, so make a
// new Node with more space and put the Node we are splitting
// off into the vacated space. It will fit as it has no
// children at all.
typename KDEntryArray<C, ExtEntry>::iterator middle =
KDEntryArray<C, ExtEntry>::split
(entries().begin(), entries().end(), var, exp, conf, &extEntry);
// ** copy relevant part of *this into new space
Node* copied = makeNode(entries().begin(), middle, arena, conf,
std::distance(childBegin(), childEnd()) + 1);
std::copy(childBegin(), childEnd(), copied->childBegin());
Child& newChild = *(copied->childEnd() - 1);
newChild.var = var;
newChild.exponent = exp;
newChild.node = this;
if (childFromParent != 0)
childFromParent->node = copied;
if (C::UseTreeDivMask) {
newChild.resetDivMask();
newChild.updateToLowerBound(entries());
newChild.updateToLowerBound(extEntry);
}
// ** fix up remaining part of *this to be the child of copied
// OK to call std::copy as begin is not in the range [middle, end).
std::copy(middle, entries().end(), entries().begin());
const size_t targetSize = std::distance(middle, entries().end());
while (entries().size() > targetSize)
entries().pop_back();
if (conf.getSortOnInsert())
std::sort(entries().begin(), entries().end(), Comparer<C>(conf));
if (C::UseTreeDivMask)
entries().recalculateTreeDivMask();
_childrenEnd = childBegin();
if (copied->inChild(copied->childEnd() - 1, extEntry.get(), conf))
entries().insert(extEntry, conf);
else
copied->entries().insert(extEntry, conf);
MATHIC_ASSERT(debugIsValid());
MATHIC_ASSERT(copied->debugIsValid());
return copied;
}
template<class C>
bool PackedKDTree<C>::Node::debugIsValid() const {
#ifndef MATHIC_DEBUG
return true;
#else
MATHIC_ASSERT(entries().debugIsValid());
MATHIC_ASSERT(childBegin() <= childEnd());
if (C::UseTreeDivMask) {
for (const_iterator child = childBegin(); child != childEnd(); ++child) {
if (child != childEnd() - 1)
MATHIC_ASSERT(child->canDivide(*(child + 1)));
else
MATHIC_ASSERT(child->canDivide(entries()));
if (child->node->hasChildren())
MATHIC_ASSERT(child->canDivide(*child->node->childBegin()));
else
MATHIC_ASSERT(child->canDivide(child->node->entries()));
}
}
return true;
#endif
}
}
#endif
| true |
504172da1e516b3186f0bc2c956f977a51c60254
|
C++
|
nevern00b/SHUMP
|
/src/Rendering/ParticleSystem.h
|
UTF-8
| 540 | 2.59375 | 3 |
[] |
no_license
|
#pragma once
#include "ObjectPool.h"
class Mesh;
class Material;
class ParticleSystem : public ObjectPool
{
public:
ParticleSystem(uint size, Mesh* mesh, Material* material);
virtual ~ParticleSystem();
void createRadial(float x, float y, uint count);
};
class Particle : public PoolObject
{
public:
Particle();
virtual ~Particle();
virtual bool update();
virtual void create(float x, float y, float vx, float vy);
virtual glm::vec4 getTransform();
float m_x;
float m_y;
float m_z;
float m_vx;
float m_vy;
float m_vz;
};
| true |
da45347c3ecfa91c3d3b315630bf368c2b89fdfc
|
C++
|
shyamnathp/Competitive_Coding_C-17
|
/Top_k_frequent/Search_Suggestions_SearchWord_Products.cpp
|
UTF-8
| 1,097 | 2.90625 | 3 |
[] |
no_license
|
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
#include<sstream>
#include<map>
#include<queue>
using namespace std;
vector<string> suggestedProducts(vector<string>& products, string subWord) {
int subWordSize = subWord.size();
vector<string> suggestions;
auto i = std::find_if(products.begin(), products.end(), [&](string& product) {
string subProduct = product.substr(0, subWordSize);
auto s1 = subProduct.c_str();
auto s2 = subWord.c_str();
int compare = strcmp(s1,s2);
if (compare == 0)
{
suggestions.push_back(product);
if (suggestions.size() == 3)
return true;
}
return false;
});
return suggestions;
}
int main()
{
vector<string> products = { "bags","baggage","banner","box","cloths" };
std::sort(products.begin(), products.end());
string searchWord = "tatiana";
int searchWordSize = searchWord.size();
vector<vector<string>> listPorducts(searchWord.size());
for (int i = 1; i <= searchWordSize; ++i)
{
string subSearchWord = searchWord.substr(0, i);
listPorducts[i-1] = suggestedProducts(products, subSearchWord);
}
}
| true |
cf85f18bd480ed43958a14f4405c74ebfcdf945d
|
C++
|
sivangisingh/leet-code
|
/DP Standard Problems/Target Sum.cpp
|
UTF-8
| 477 | 2.8125 | 3 |
[] |
no_license
|
int main() {
vector<int> arr = {1, 2, 7, 1};
int target = 3, sum = 0, n = arr.size();
unordered_map <int, int> curr;
curr.insert(make_pair(0, 1));
for(auto item: arr){
unordered_map <int, int> newh;
for(auto i = curr.begin(); i != curr.end(); i++){
newh[((*i).first) + item] += (*i).second;
newh[((*i).first) - item] += (*i).second;
}
curr = newh;
}
cout << curr[target];
}
| true |
77a6588208a34ad63f6a7dd80616b03e9bfd9a00
|
C++
|
Dgame/Ikarus
|
/include/Expression/LowerEqualExpression.hpp
|
UTF-8
| 515 | 2.59375 | 3 |
[] |
no_license
|
#ifndef IKARUS_LOWER_EQUAL_EXPRESSION_HPP
#define IKARUS_LOWER_EQUAL_EXPRESSION_HPP
#include "BinaryExpression.hpp"
class LowerEqualExpression : public BinaryExpression {
public:
using BinaryExpression::BinaryExpression;
LowerEqualExpression* clone() const override {
return new LowerEqualExpression(this->getLeftExpression()->clone(), this->getRightExpression()->clone());
}
void accept(Visitor& v) override {
v.visit(this);
}
};
#endif //IKARUS_LOWER_EQUAL_EXPRESSION_HPP
| true |
18129b8f789196ac5170623b238716b64a5bdfa2
|
C++
|
lixiang2017/leetcode
|
/cpp/1160.0_Find_Words_That_Can_Be_Formed_by_Characters.cpp
|
UTF-8
| 1,649 | 3.296875 | 3 |
[] |
no_license
|
/*
hash table
执行用时:40 ms, 在所有 C++ 提交中击败了92.97% 的用户
内存消耗:20 MB, 在所有 C++ 提交中击败了56.93% 的用户
通过测试用例:36 / 36
*/
class Solution {
private:
vector<int> freq;
public:
Solution(): freq(26) {};
int countCharacters(vector<string>& words, string chars) {
int ans = 0;
for (char ch: chars) {
freq[ch - 'a']++;
}
auto check = [this](string& word) {
vector<int> f(26);
for (char ch: word) {
int idx = ch - 'a';
f[idx]++;
if (f[idx] > this->freq[idx]) return false;
}
return true;
};
for (string &w: words) {
if (check(w)) {
ans += w.size();
}
}
return ans;
}
};
/*
执行用时:40 ms, 在所有 C++ 提交中击败了92.97% 的用户
内存消耗:19.8 MB, 在所有 C++ 提交中击败了60.72% 的用户
通过测试用例:36 / 36
*/
class Solution {
public:
vector<int> freq = vector<int>(26);
int countCharacters(vector<string>& words, string chars) {
int ans = 0;
for (char ch: chars) {
freq[ch - 'a']++;
}
for (string &w: words) {
if (check(w)) {
ans += w.size();
}
}
return ans;
}
bool check (string& word) {
vector<int> f(26);
for (char ch: word) {
int idx = ch - 'a';
f[idx]++;
if (f[idx] > this->freq[idx]) return false;
}
return true;
}
};
| true |
61338b964f7a5d8911ed24bfcca8b69a8cf33345
|
C++
|
pescoboza/Genesia
|
/HeightMap.cpp
|
UTF-8
| 4,677 | 3.046875 | 3 |
[] |
no_license
|
#include "HeightMap.h"
////////////////////////////////////////////////////////////
HeightMap::HeightMap(unsigned t_w, unsigned t_h, const std::vector<double>& t_values) :
m_height{ t_h }, m_width{ t_w }, m_heights{ t_values }{
if (m_heights.size() > t_w* t_h) {
while (m_heights.size() > t_w* t_h)
m_heights.pop_back();
}
else if (m_heights.size() < t_w * t_h) {
unsigned delta{ t_w * t_h - (unsigned)m_heights.size() };
m_heights.reserve(t_w * t_h);
for (unsigned i{ 0 }; i < delta; i++)
m_heights.emplace_back(0.0);
}
}
////////////////////////////////////////////////////////////
HeightMap::HeightMap(unsigned t_w, unsigned t_h) :
m_height{ t_h }, m_width{ t_w }, m_heights((size_t)(t_w* t_h), 0.0){}
////////////////////////////////////////////////////////////
bool HeightMap::compareDimensions(const HeightMap& t_hm) const {
return m_width == t_hm.m_width && m_height == t_hm.m_height;
}
////////////////////////////////////////////////////////////
double HeightMap::mean() const {
double sum{ 0 };
for (const auto& val : m_heights) {
sum += val;
}
return sum / (m_width * m_height);
}
////////////////////////////////////////////////////////////
double HeightMap::standtDev() const {
double ave{ mean() };
double sum{ 0 };
for (const auto& val : m_heights) {
sum += (val - ave) * (val - ave);
}
return sqrt(sum / (m_width * m_height));
}
////////////////////////////////////////////////////////////
double HeightMap::getValue(unsigned t_x, unsigned t_y) const {
return m_heights[t_y * m_width + t_x];
}
////////////////////////////////////////////////////////////
void HeightMap::setValue(unsigned t_x, unsigned t_y, double t_n) {
m_heights[t_y * m_width + t_x] = t_n;
}
////////////////////////////////////////////////////////////
HeightMap& HeightMap::sediment(const HeightMap& t_hm) {
if (compareDimensions(t_hm)) {
unsigned size{ (unsigned)m_heights.size() };
for (unsigned i{ 0 }; i < size; i++) {
m_heights[i] += t_hm.m_heights[i];
}
}
return *this;
}
////////////////////////////////////////////////////////////
HeightMap& HeightMap::merge(const HeightMap t_hm) {
if (compareDimensions(t_hm)) {
unsigned size{ (unsigned)m_heights.size() };
for (unsigned i{ 0 }; i < size; i++) {
m_heights[i] = std::max(m_heights[i], t_hm.m_heights[i]);
}
}
return *this;
}
////////////////////////////////////////////////////////////
HeightMap& HeightMap::increment(double t_n) {
for (auto& val : m_heights) {
val += t_n;
}
return *this;
}
////////////////////////////////////////////////////////////
double HeightMap::getMax()const {
double max{ -INFINITY };
for (const auto& val : m_heights) {
if (val > max) {
max = val;
}
}
return max;
}
////////////////////////////////////////////////////////////
double HeightMap::getMin()const {
double min{ INFINITY };
for (const auto& val : m_heights) {
if (val < min) {
min = val;
}
}
return min;
}
////////////////////////////////////////////////////////////
std::pair<double, double> HeightMap::getRange() const {
double min{ INFINITY };
double max{ -INFINITY };
for (const auto& val : m_heights) {
if (val < min) {
min = val;
}
else if (val > max) {
max = val;
}
}
return std::move(std::make_pair(min, max));
}
////////////////////////////////////////////////////////////
HeightMap& HeightMap::multiply(double t_n) {
for (auto& val : m_heights) {
val *= t_n;
}
return *this;
}
////////////////////////////////////////////////////////////
HeightMap& HeightMap::clamp(double t_min, double t_max) {
double min{ std::min(t_min, t_max) };
double max{ std::max(t_min, t_max) };
for (auto& val : m_heights) {
if (val < min) {
val = min;
}
else if (val > max) {
val = max;
}
}
return *this;
}
////////////////////////////////////////////////////////////
HeightMap& HeightMap::mapValuesToRange(double t_min, double t_max) {
auto range{ getRange() };
for (auto& val : m_heights) {
val = t_min + (val - range.first) * (t_max - t_min) / (range.second - range.first);
}
return *this;
}
////////////////////////////////////////////////////////////
std::vector<double>::const_iterator HeightMap::cbegin() const {
return m_heights.cbegin();
}
////////////////////////////////////////////////////////////
std::vector<double>::const_iterator HeightMap::cend() const {
return m_heights.cend();
}
////////////////////////////////////////////////////////////
std::vector<double>::iterator HeightMap::begin() {
return m_heights.begin();
}
////////////////////////////////////////////////////////////
std::vector<double>::iterator HeightMap::end() {
return m_heights.end();
}
| true |
f14756ca0c27ec1a256f621fcafa2630131af234
|
C++
|
20-1-SKKU-OSS/2020-1-OSS-7
|
/C-Plus-Plus/BOJ/15879.cpp
|
UTF-8
| 735 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
#include<bits/stdc++.h>
using namespace std;
#define MOD 100000007
int V, E, C, s;
bool chk[110];
vector<int> graph[110];
void dfs(int node){
chk[node] = true; ++s;
for(auto next : graph[node]){
if(chk[next]) continue;
dfs(next);
}
}
int pow2(int x){
if(x<=0) return 1;
int ret=1;
for(;x--;ret*=2)ret%=MOD;
return ret%MOD;
}
int main()
{
scanf("%d%d", &V, &E);
for(int i=1; i<=E; ++i){
int x, y;
scanf("%d%d", &x, &y);
graph[x].push_back(y);
graph[y].push_back(x);
}
for(int i=1; i<=V; ++i){
if(chk[i]) continue;
++C; s = 0;
dfs(i);
if(s%2){ printf("0\n"); return 0; }
}
printf("%d\n", pow2(E-V+C));
}
| true |
2b23f295e42bc931f2550a6e93ec9ce2c1a03ef6
|
C++
|
iamjatin08/DATA-STRUCTURES
|
/dp 1/numof_BT.cpp
|
UTF-8
| 860 | 3.109375 | 3 |
[] |
no_license
|
#include<iostream>
#include<math.h>
using namespace std;
int balancedBTs(int h, int* dp){
if(h<=1 ) return 1;
if(dp[h]!=(-1)) return dp[h];
int mod = pow(10,9)+7;
int x = balancedBTs(h-1,dp);
int y = balancedBTs(h-2,dp);
int temp1 = (int)(((long)(x)*x)%mod);
int temp2 = (int)((2*(long)(x)*y)%mod);
int ans = (temp1 + temp2)%mod;
dp[h] = ans;
return ans;
}
int balancedBTs(int h){
int *dp = new int[h+1];
for(int i = 0 ; i<h+1 ;i++) dp[i] = -1;
int ans = balancedBTs(h,dp);
delete [] dp;
return ans;
}
int balancedBTsDP(int h){
int * dp = new int[h+1];
dp[0] = 1;
dp[1] = 1;
for(int i = 2 ; i<h+1 ; i++){
dp[i] = dp[i-1]+dp[i-2];
}
int ans = dp[h];
delete [] dp;
return ans;
}
int main(int argc, char const *argv[])
{
int h;
cin>>h;
cout<<balancedBTs(h)<<endl;
return 0;
}
| true |
e3c857b2bdc842b550878c5eccdcf9fd9979bd7f
|
C++
|
demeiyan/algorithm
|
/cc/hh.cpp
|
UTF-8
| 1,412 | 2.75 | 3 |
[] |
no_license
|
/*void quickSelect(double a[],int l,int r,int rank){
int i=l,j=r;
double mid=a[(l+r)/2];
do{
while(a[i]<mid)++i;
while(a[j]>mid)j--;
if(i<=j){
swap(a[i],a[j]);
++i;--j;
}
}while(i<=j);
if(l<=j&&rank<=j-l+1)quickSelect(a,l,j,rank);
if(i<=r&&rank>=i-l+1)quickSelect(a,i,r,rank);
}
double quick_select(double a[],int n,int k){
quickSelect(a,0,n,k);
return a[k-1];
}*/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
struct Node{
double x,y;
};
Node node[101];
double dist(Node n1,Node n2){
return sqrt((n1.x - n2.x)*(n1.x - n2.x) + (n1.y - n2.y)*(n1.y - n2.y));
}
double nton[101][101];
int main(){
// freopen("in","r",stdin);
int t;
scanf("%d",&t);
int m,n;
while(t--){
scanf("%d%d",&m,&n);
for(int i=0;i<m;i++){
scanf("%lf%lf",&node[i].x,&node[i].y);
}
for(int i=0;i<m;i++)
for(int j=i;j<m;j++){
nton[i][j] = nton[j][i] = dist(node[i],node[j]);
}
if (n > m){
printf("%d\n",-1 );
continue;
}
int radio = -1;
int min_radio = 9999999;
for(int i=0;i<m;i++){
sort(nton[i],nton[i]+m);
radio = (int)(nton[i][n-1]) + 1;
double tmp = radio * 1.0;
if((n < m)){
if(!(nton[i][n] > tmp))
radio = -1;
}
if(radio != -1){
min_radio = radio<min_radio?radio:min_radio;
}
}
if(min_radio == 9999999)
min_radio = -1;
printf("%d\n", min_radio);
}
}
| true |
cf26be37da643e8094618ab68a6a6eb6d94ffc17
|
C++
|
bikash-das/cppPrograms
|
/BeginningC++17/PointerAndRef/stringSwap.cpp
|
UTF-8
| 316 | 3 | 3 |
[] |
no_license
|
#include <iostream>
int main(){
const char *s1 = {"hello it's me Bikash"};
const char *s2 = {"And I'm from Siliguri"};
//swap
const char *temp = s1;
std::cout << "\n" << *temp << "\n";
std::cout << "Swapped\n";
s1 = s2;
s2 = temp;
std::cout << s1 << std::endl;
std::cout << s2 << std::endl;
}
| true |
0d665b32ccf7738ff1589880ee83d34b547ac121
|
C++
|
IndieLightAndMagic/wolf
|
/src/texture/fastclampedtexturedata.cpp
|
UTF-8
| 919 | 2.671875 | 3 |
[] |
no_license
|
#include "fastclampedtexturedata.h"
QQE::FastClampedTextureData::FastClampedTextureData(int w, int h):QQE::FastTextureData(w,h){
resetTexture();
updateTexture();
}
void QQE::FastClampedTextureData::resetTexture() {
data = new float[m_sz]();
for (auto index = 0; index < m_sz; ++index){
data[index] = 0.0f;
}
}
void QQE::FastClampedTextureData::updateTexture(){
bind();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // set texture wrapping to GL_REPEAT (default wrapping method)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
// set texture filtering parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, 0x1903, m_w, m_h, 0, 0x1903, GL_FLOAT, data);
glGenerateMipmap(GL_TEXTURE_2D);
unbind();
}
| true |
e6f345323a7ed200971ef406763c1543d5b5cebe
|
C++
|
Samhenry97/BulletBash
|
/BulletBash/bullet.h
|
UTF-8
| 1,456 | 2.609375 | 3 |
[] |
no_license
|
#pragma once
#include "gameobject.h"
class Bullet : public GameObject {
protected:
float speed, moveAngle, homingSpeed, homingDeadzone;
float maxDist, dist = 0;
public:
bool splash, homing, bouncy;
int damage, type;
Bullet(int type, vec2 pos, float speed, float angle);
virtual void render();
virtual void update();
virtual void kill();
bool dead();
};
class BBasic : public Bullet {
public:
BBasic(int type, vec2 pos, float speed, float angle);
};
class BHeavy : public Bullet {
public:
BHeavy(int type, vec2 pos, float speed, float angle);
};
class BBubble : public Bullet {
public:
BBubble(int type, vec2 pos, float speed, float angle);
void update();
void kill();
};
class BGun : public Bullet {
private:
float displayAngle, shootClock, shootTime;
public:
BGun(int type, vec2 pos, float speed, float angle);
void update();
void render();
};
class BSteve : public Bullet {
private:
float displayAngle, shootClock, shootTime;
public:
BSteve(int type, vec2 pos, float speed, float angle);
void update();
void render();
};
class BFlame : public Bullet {
public:
BFlame(int type, vec2 pos, float speed, float angle);
};
class BHoming : public Bullet {
public:
BHoming(int type, vec2 pos, float speed, float angle);
};
class BLine : public Bullet {
private:
vec2 endPos;
float animTime, killTime;
public:
BLine(int type, vec2 pos, float angle);
void update();
void render();
bool intersects(GameObject *other);
};
| true |
9e279f1d34cb94de92d2927fb82a698d9640e443
|
C++
|
FeiiYin/acm
|
/poj/3321 BIT+DFS序+前向星优化.cpp
|
UTF-8
| 2,172 | 2.671875 | 3 |
[] |
no_license
|
/*
* @Samaritan_infi
*/
/// 前向星优化了一倍的速度
//#include<bits/stdc++.h>
#include <cstdio>
#include <vector>
#include <iostream>
#include <cstring>
using namespace std;
typedef long long ll;
const int maxn = 200000 + 5;
int tree[maxn];
int n;
int low_bit(int x) { return x & (-x); }
void add(int x, int val) {
for( ; x <= n; x += low_bit(x)) tree[x] += val;
}
int query(int x) {
int ans = 0;
for( ; x > 0; x -= low_bit(x)) ans += tree[x];
return ans;
}
struct node {
int u, next;
node() {}
node(int a, int b) {u = a, next = b;}
}edge[maxn << 1];
int tot_edge;
int head[maxn];
void add_edge(int u, int v) {
edge[tot_edge] = node(v, head[u]);
head[u] = tot_edge ++;
}
int pos;
int in[maxn], out[maxn];
int val[maxn];
void dfs(int x, int pre) {
in[x] = ++ pos;
for(int i = head[x]; ~ i; i = edge[i].next) {
int u = edge[i].u;
if(u == pre) continue;
dfs(u, x);
}
out[x] = pos;
}
void show(int a[], int len) {
for(int i = 0; i <= len; i ++) cout << a[i] << " "; cout << endl;
}
void init(int n) {
tot_edge = 0;
memset(head, -1, sizeof head);
for(int i = 0; i <= n; i ++) val[i] = 1;
pos = 0;
memset(tree, 0, sizeof tree);
for(int i = 1; i <= n; i ++) add(i, 1);
}
int main() {
scanf("%d", &n);
init(n);
int l, r;
for(int i = 1; i < n; i ++) {
scanf("%d %d", &l, &r);
add_edge(l, r);
add_edge(r, l);
}
dfs(1, 0);
int op; scanf("%d", &op);
char read[5];
int x;
while(op --) {
scanf("%s %d", read, &x);
if(read[0] == 'Q') {
// cout << in[x] << " " << out[x] << endl;
// cout << query(in[x] - 1) << " " << query(out[x]) << endl;
printf("%d\n", query(out[x]) - query(in[x] - 1));
} else {
if(val[ in[x] ]) {
val[ in[x] ] = 0;
add(in[x], -1);
} else {
val[ in[x] ] = 1;
add(in[x], 1);
}
}
}
return 0;
}
| true |
4f42da4beab30c0cbe33182f87cc2c5b012f415a
|
C++
|
QuantumGorilla/Benchmark
|
/CalculatePI.cpp
|
UTF-8
| 1,091 | 2.890625 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <iostream>
const int n = 250000;
const int m = ((10 * n) / 3);
int main (void){
int n;
std::cout << "Digite la cantidad de digitos de PI que quiere mostrar: ";
std::cin >> n;
int resto, digant, nueves, aux;
int pi [m + 1];
for (int i=1;i<= m;i++) pi[i]=2;
nueves=0; digant=0;
for (int i=1;i<=n;i++)
{
resto=0;
for (int j= m;j>=1;j--)
{
aux=10*pi[j]+resto*j;
pi[j]=aux % (2*j-1);
resto=aux/(2*j-1);
}
pi[1]=resto % 10;
resto=resto/10;
if (resto==9) nueves++;
else if (resto==10)
{
printf("%i",digant);
for (int k=1;k<=nueves;k++) printf("0");
digant=0;
nueves=0;
}
else
{
printf("%i",digant);
digant=resto;
if (nueves!=0)
{
for(int k=1;k<=nueves;k++) printf("9");
nueves=0;
}
}
}
scanf_s("%i",digant);
system("pause");
}
| true |
ed43dec0754c5ff6c3ddcf7200d404dd10c7d8c8
|
C++
|
ChristopherMurray194/OpenGL_assignment
|
/GameWorld.cpp
|
UTF-8
| 740 | 2.53125 | 3 |
[] |
no_license
|
/*
* GameWorld.cpp
*
* Created on: 21 Apr 2015
* Author: cmurray
*/
#include "GameWorld.h"
GameWorld::GameWorld() {
game_manager = boost::make_shared<GameManager>();
std::string earth_texture = "textures/earth_texture.png";
std::string moon_texture = "textures/moon_texture.jpg";
game_manager->AddAsset(boost::make_shared<Light>());
game_manager->AddAsset(boost::make_shared<SphereAsset>(earth_texture.c_str(), 3.0, 30, 60)); // Earth
game_manager->AddAsset(boost::make_shared<SphereAsset>(earth_texture.c_str(), 0.5, 30, 60, 5.0)); // Moon
game_manager->AddAsset(boost::make_shared<Camera>());
}
GameWorld::~GameWorld() {
// TODO Auto-generated destructor stub
}
void GameWorld::Draw()
{
game_manager->Draw();
}
| true |
ab7b4d39b8526834d7f4c5c87d80bcf3548a7633
|
C++
|
Sukarnapaul1893/Code-for-Popular-Topics-of-Contest-Programming
|
/DP/Bit Mask DP/bitmask dp.cpp
|
UTF-8
| 408 | 2.53125 | 3 |
[] |
no_license
|
// Sample problem codeforces contest Hello 2019 problem B
unordered_map<int,int>dp;
void Calc(int mask){
if(dp.count(mask)!=0)return;
//.. calculate ans here...//
for(int i=0;i<n;i++){
//if(mask&(1<<i)) ....;
//else ....;
}
dp[mask] = ans;
for(int i=0;i<n;i++){
if(mask&(1<<i)) continue;
else Calc(mask | (1<<i));
}
}
| true |
a82a423061bf4cad7f4d7f718fa8fb2564113c86
|
C++
|
kgasniko/ZeeD2p76
|
/ZeeDHist/src/ZeeDEffHistManager.cxx
|
UTF-8
| 6,138 | 2.546875 | 3 |
[] |
no_license
|
#include "ZeeDHist/ZeeDEffHistManager.h"
#include <TMath.h>
//------------------------------------------------------
ZeeDEffHistManager::ZeeDEffHistManager(TString name) : ZeeDHistManager(name)
{
// The Named Constructor
}
//------------------------------------------------------
ZeeDEffHistManager::~ZeeDEffHistManager()
{
// The Destructor
}
//------------------------------------------------------
Double_t* ZeeDEffHistManager::GetLogBinGrid(Int_t n, Double_t xlow, Double_t xhigh)
{
// Returns logarifmic bin grid
Double_t* BinGrid = NULL;
if (n <= 0 || xlow >= xhigh) {
Error("ZeeDEffHistManager::GetLogBinGrid",
"Input variable are not correct! n = %i xlow = %f xhigh = %f", n, xlow, xhigh);
return BinGrid;
}
BinGrid = new Double_t[n + 1];
BinGrid[0] = xlow;
Double_t delta_x_log = (TMath::Log(xhigh) - TMath::Log(xlow)) / n;
// Put equidistant binwith on a logarithmic scale
for (Int_t i = 1; i <= n; ++i) {
BinGrid[i] = TMath::Exp(TMath::Log(BinGrid[i - 1]) + delta_x_log);
}
return BinGrid;
}
//------------------------------------------------------
Double_t* ZeeDEffHistManager::GetLinBinGrid(Int_t n, Double_t xlow, Double_t xhigh)
{
// Returns linear bin grid
Double_t* BinGrid = NULL;
if (n <= 0 || xlow >= xhigh) {
Error("ZeeDEffHistManager::GetLinBinGrid",
"Input variable are not correct! n = %i xlow = %f xhigh = %f", n, xlow, xhigh);
return BinGrid;
}
BinGrid = new Double_t[n + 1];
BinGrid[0] = xlow;
Double_t delta_x = (xhigh - xlow) / n;
// Put equidistant binwith on a linear scale
for (Int_t i = 1; i <= n; ++i) {
BinGrid[i] = BinGrid[i - 1] + delta_x;
}
return BinGrid;
}
//------------------------------------------------------
ZeeDEffHistManager::Histogram ZeeDEffHistManager::DefineHisto(TString name,
Int_t nbins, Double_t* bounds, TString title)
{
// Declares histogram
Histogram histo;
histo.Name = name;
histo.NXBins = nbins;
histo.XLow = 0.0;
histo.XUp = 0.0;
histo.NYBins = 0;
histo.YLow = 0;
histo.YUp = 0;
histo.XBounds = bounds;
histo.YBounds = NULL;
histo.XTitle = title;
histo.YTitle = "";
return histo;
}
//------------------------------------------------------
ZeeDEffHistManager::Histogram ZeeDEffHistManager::DefineHisto(TString name,
Int_t nxbins, Double_t* xbounds, Int_t nybins,
Double_t* ybounds, TString xtitle, TString ytitle)
{
// Declares histogram
Histogram histo;
histo.Name = name;
histo.NXBins = nxbins;
histo.XLow = 0.0;
histo.XUp = 0.0;
histo.NYBins = nybins;
histo.YLow = 0;
histo.YUp = 0;
histo.XBounds = xbounds;
histo.YBounds = ybounds;
histo.XTitle = xtitle;
histo.YTitle = ytitle;
return histo;
}
//------------------------------------------------------
ZeeDEffHistManager::Histogram ZeeDEffHistManager::DefineHisto(TString name,
Int_t nxbins, Double_t xlow, Double_t xup, Int_t nybins,
Double_t ylow, Double_t yup, TString xtitle, TString ytitle)
{
// Declares histogram
Histogram histo;
histo.Name = name;
histo.NXBins = nxbins;
histo.XLow = xlow;
histo.XUp = xup;
histo.NYBins = nybins;
histo.YLow = ylow;
histo.YUp = yup;
histo.XBounds = NULL;
histo.YBounds = NULL;
histo.XTitle = xtitle;
histo.YTitle = ytitle;
return histo;
}
//------------------------------------------------------
void ZeeDEffHistManager::DeclareHistos(TString effName,
Int_t nEntries, Histogram* histos)
{
// Adds "Top" and "Bot" histos for efficiency calculations to the histarray
TString TopBot[2];
TopBot[0] = "Top";
TopBot[1] = "Bot";
for (Int_t j = 0; j < 2; ++j) {
for (Int_t i = 0; i < nEntries; ++i) {
TString name = TString(effName + histos[i].Name + TopBot[j]);
if(histos[i].NYBins == 0) {
Int_t n_bins = histos[i].NXBins;
Double_t* bounds = histos[i].XBounds;
TString xTitle = histos[i].XTitle;
TString yTitle = TString("#varepsilon_{" + effName + "}");
AddTH1D(name, n_bins, bounds, xTitle, yTitle);
} else if (histos[i].YBounds == NULL) {
Int_t nx_bins = histos[i].NXBins;
Int_t ny_bins = histos[i].NYBins;
Double_t xlow = histos[i].XLow;
Double_t xup = histos[i].XUp;
Double_t ylow = histos[i].YLow;
Double_t yup = histos[i].YUp;
TString yTitle = histos[i].YTitle;
TString xTitle = TString(histos[i].XTitle + ", (" + effName + ")");
AddTH2D(name, nx_bins, xlow, xup, ny_bins, ylow, yup, xTitle, yTitle);
} else {
Int_t nx_bins = histos[i].NXBins;
Int_t ny_bins = histos[i].NYBins;
Double_t* xbounds = histos[i].XBounds;
Double_t* ybounds = histos[i].YBounds;
TString yTitle = histos[i].YTitle;
TString xTitle = TString(histos[i].XTitle + ", (" + effName + ")");
AddTH2D(name, nx_bins, xbounds, ny_bins, ybounds, xTitle, yTitle);
}
}
}
return;
}
//------------------------------------------------------
void ZeeDEffHistManager::FillHistos1D(Int_t nEntries,
Double_t* variables, Double_t weight, Int_t index)
{
// Fills 1D histos
for(Int_t i = 0; i < nEntries; ++i) {
FillTH1(variables[i], weight, TString::Format("%d",index + i));
}
return;
}
| true |
7e96dedad4fb88c4aab372321d538a1ad590b2c9
|
C++
|
renyajie/Learning
|
/Algorithm/基础/数学知识/拓展欧几里得/exgcd.cpp
|
GB18030
| 470 | 3.390625 | 3 |
[] |
no_license
|
// չŷ㷨x,yʹax + by = gcd(a, b) (1)
// ŷԼĻϣ˳x, yֵ
// ֻΪһ(1)
// ax + by = dǷн⣬ȼdDzgcd(a,b)ı
// x, yʹax + by = gcd(a, b)
int exgcd(int a, int b, int &x, int &y)
{
if(!b)
{
x = 1, y = 0;
return a;
}
int d = exgcd(b, a % b, y, x);
y = y - (a / b) * x;
return d;
}
| true |
2b5c6a123468866270c6091510e46c2413f6e42b
|
C++
|
TaeBeomShin/1day-1ps
|
/6. 구현(Simulation)/PGM_실패율.cpp
|
UHC
| 1,025 | 3.03125 | 3 |
[] |
no_license
|
#include <bits/stdc++.h>
using namespace std;
/*
https://programmers.co.kr/learn/courses/30/lessons/42889
ؼ ؼ ȯϴ .
c++ compare ǿ.
*/
double arr[502]={0,};
bool compare(const pair<int,double> & a,const pair<int,double> &b){
if(a.second!=b.second)
return a.second>b.second;
else
return a.first<b.first;
}
vector<int> solution(int N, vector<int> stages) {
int size=stages.size();// .
vector<int> v;
vector<pair<int,double>> answer;
for(int i=0;i<size;i++) arr[stages[i]]++;
for(int i=1;i<=N;i++){
double sum=0;
if(arr[i]==0){
answer.push_back({i,0});
continue;
}
for(int j=1;j<i;j++) sum+=arr[j];//ܰ
answer.push_back({i,arr[i]/(size-sum)});
}
sort(answer.begin(),answer.end(),compare);
for(int i=0;i<answer.size();i++) v.push_back(answer[i].first);
return v;
}
| true |
befda229a5e88e71d29f233e23b87ad6463b1b15
|
C++
|
Cryrivers/SPA
|
/SPA/FollowsTest.cpp
|
UTF-8
| 6,064 | 3.28125 | 3 |
[] |
no_license
|
/*
* FollowsTest.cpp
*
* Created on: 30 Oct 2012
* Author: ray
*/
#include <iostream>
#include "Follows.h"
void printVector(vector<int> );
void f1()
{
Follows f;
//case 1a, should print false
vector<int> va;
vector<int> vb;
cout << f.follows(&va, &vb, 0) << endl;
f.addFollows(1, 2);
f.addFollows(2, 3);
f.addFollows(3, 4);
f.addFollows(4, 5);
f.addFollows(5, 6);
f.addFollows(6, 7);
f.addFollows(7, 15);
f.addFollows(8, 9);
f.addFollows(9, 14);
f.addFollows(10, 11);
f.addFollows(12, 13);
/* Follow table is
* 1 2 3 4 5 6 7 8 9 10 12
* 2 3 4 5 6 7 15 9 14 11 13
*
*/
//case 1a, should print true
cout << f.follows(&va, &vb, 0) << endl;
//case 1b, should print false
vb.push_back(8);
cout << f.follows(&va, &vb, 0) << endl;
//case 1b, should print false
vb.push_back(10);
cout << f.follows(&va, &vb, 0) << endl;
//case 1b, should print true
vb.push_back(5);
cout << f.follows(&va, &vb, 0) << endl;
vb.clear();
//case 1c, should print false
va.push_back(11);
cout << f.follows(&va, &vb, 0) << endl;
//case 1c, should print false
va.push_back(13);
cout << f.follows(&va, &vb, 0) << endl;
//case 1c, should print true
va.push_back(4);
cout << f.follows(&va, &vb, 0) << endl;
//case 1d, should print false
vb.push_back(6);
cout << f.follows(&va, &vb, 0) << endl;
//case 1d, should print true
vb.push_back(5);
cout << f.follows(&va, &vb, 0) << endl;
//should print 0 1 0 0 1 0 0 1 0 1
}
void f2()
{
Follows f;
f.addFollows(1, 2);
f.addFollows(2, 3);
f.addFollows(3, 4);
f.addFollows(4, 5);
f.addFollows(5, 6);
f.addFollows(6, 7);
f.addFollows(7, 15);
f.addFollows(8, 9);
f.addFollows(9, 14);
f.addFollows(10, 11);
f.addFollows(12, 13);
/* Follow table is
* 1 2 3 4 5 6 7 8 9 10 12
* 2 3 4 5 6 7 15 9 14 11 13
*
*/
vector<int> va;
vector<int> vb;
//case 2a, should print true\n2 3 4 5 6 7 15 9 14 11 13
cout << f.follows(&va, &vb, 1) << endl;
printVector(vb);
//case 2b, should print false\n no element
vb.clear();
va.push_back(11);
cout << f.follows(&va, &vb, 1) << endl;
printVector(vb);
//case 2b, should print true\n 6
va.clear();
va.push_back(5);
cout << f.follows(&va, &vb, 1) << endl;
printVector(vb);
va.clear();
vb.clear();
//case 2c, should print true\n 2 4 15 13
vb.push_back(2);
vb.push_back(1);
vb.push_back(4);
vb.push_back(15);
vb.push_back(12);
vb.push_back(13);
vb.push_back(16);
cout << f.follows(&va, &vb, 1) << endl;
printVector(vb);
//case 2d, should print false\n no element
va.clear();
vb.clear();
va.push_back(11);
vb.push_back(1);
vb.push_back(2);
vb.push_back(3);
cout << f.follows(&va, &vb, 1) << endl;
printVector(vb);
//case 2d, should print true\n 15
va.clear();
va.push_back(7);
vb.push_back(5);
vb.push_back(8);
vb.push_back(15);
cout << f.follows(&va, &vb, 1) << endl;
printVector(vb);
}
void f3()
{
Follows f;
f.addFollows(1, 2);
f.addFollows(2, 3);
f.addFollows(3, 4);
f.addFollows(4, 5);
f.addFollows(5, 6);
f.addFollows(6, 7);
f.addFollows(7, 15);
f.addFollows(8, 9);
f.addFollows(9, 14);
f.addFollows(10, 11);
f.addFollows(12, 13);
/* Follow table is
* 1 2 3 4 5 6 7 8 9 10 12
* 2 3 4 5 6 7 15 9 14 11 13
*
*/
vector<int> va;
vector<int> vb;
//case 3a, should print true\n1 2 3 4 5 6 7 8 9 10 12
cout << f.follows(&va, &vb, 2) << endl;
printVector(va);
//case 3b, should print false\n no element
va.clear();
vb.push_back(12);
cout << f.follows(&va, &vb, 2) << endl;
printVector(va);
//case 3b, should print true\n 10
vb.clear();
vb.push_back(11);
cout << f.follows(&va, &vb, 2) << endl;
printVector(va);
va.clear();
vb.clear();
//case 3c, should print true\n 2 1 4 12
va.push_back(2);
va.push_back(1);
va.push_back(4);
va.push_back(15);
va.push_back(12);
va.push_back(13);
va.push_back(16);
cout << f.follows(&va, &vb, 2) << endl;
printVector(va);
//case 3d, should print false\n no element
va.clear();
vb.clear();
vb.push_back(12);
va.push_back(1);
va.push_back(2);
va.push_back(3);
cout << f.follows(&va, &vb, 2) << endl;
printVector(va);
//case 3d, should print true\n 6
vb.clear();
vb.push_back(7);
va.push_back(6);
va.push_back(8);
va.push_back(15);
cout << f.follows(&va, &vb, 2) << endl;
printVector(va);
}
void f4()
{
Follows f;
f.addFollows(1, 2);
f.addFollows(2, 3);
f.addFollows(3, 4);
f.addFollows(4, 5);
f.addFollows(5, 6);
f.addFollows(6, 7);
f.addFollows(7, 15);
f.addFollows(8, 9);
f.addFollows(9, 14);
f.addFollows(10, 11);
f.addFollows(12, 13);
/* Follow table is
* 1 2 3 4 5 6 7 8 9 10 12
* 2 3 4 5 6 7 15 9 14 11 13
*
*/
vector<int> va;
vector<int> vb;
//case 4a, should print true
//1 2 3 4 5 6 7 8 9 10 12
//2 3 4 5 6 7 15 9 14 11 13
cout << f.follows(&va, &vb, 3) << endl;
printVector(va);
printVector(vb);
//case 4b, should print true
//7 8
//15 9
va.clear();
vb.clear();
vb.push_back(12);
vb.push_back(15);
vb.push_back(9);
vb.push_back(16);
cout << f.follows(&va, &vb, 3) << endl;
printVector(va);
printVector(vb);
va.clear();
vb.clear();
//case 4c, should print true
//2 12
//3 13
va.push_back(2);
va.push_back(11);
va.push_back(13);
va.push_back(12);
cout << f.follows(&va, &vb, 3) << endl;
printVector(va);
printVector(vb);
//case 4d, should print false
//no element
//no element
va.clear();
vb.clear();
vb.push_back(12);
vb.push_back(12);
va.push_back(1);
va.push_back(3);
cout << f.follows(&va, &vb, 3) << endl;
printVector(va);
printVector(vb);
//case 3d, should print true
//6 7
//7 15
vb.push_back(7);
vb.push_back(7);
vb.push_back(7);
vb.push_back(15);
va.push_back(6);
va.push_back(8);
va.push_back(15);
va.push_back(7);
cout << f.follows(&va, &vb, 3) << endl;
printVector(va);
printVector(vb);
}
int follows_main()
{
//f1();
//f2();
//f3();
f4();
return(0);
}
void printVector(vector<int> v)
{
int size = v.size();
if (size == 0) {
cout << "no element" << endl;
}else {
for (int i = 0; i < v.size(); i++) {
cout << v.at(i) << " ";
}
cout << endl;
}
}
| true |
8fc975f6dfe7eabeb90ecc902616d7dae769f802
|
C++
|
shivam2146/Learning-C-
|
/templates_class.cpp
|
UTF-8
| 474 | 3.75 | 4 |
[] |
no_license
|
#include<iostream>
using namespace std;
template<class T,class U=char>
class test{
T mem1;
U mem2;
public:
test(T a,U b);
void display();
};
template<class T,class U>
test<T,U>::test(T a,U b){
mem1 = a;
mem2 = b;
}
template<class T,class U>
void test<T,U>::display(){
cout << "members are: " << mem1 << " " << mem2;
}
int main(){
test<int> obj(1,'a');
obj.display();
test<int,float> obj1(1,'a'); //takes a ascii value as float i.e 97
obj1.display();
}
| true |
dedd4b1eed6c5471530d1eac67277f09aafbf4a5
|
C++
|
alexeyprov/MyStuff
|
/CryptoSign/CryptCtx.h
|
UTF-8
| 1,327 | 2.828125 | 3 |
[] |
no_license
|
#pragma once
class CCryptoContext
{
public:
CCryptoContext()
{
m_pKey = NULL;
m_hProv = NULL;
if (!CryptAcquireContext(&m_hProv, NULL, NULL, PROV_RSA_FULL, 0))
{
throw CCryptoException(CCryptoException::fnAcquireContext);
}
m_pKey = new CKey(m_hProv, true);
m_pKey->CreateKey(_T("if you want to f$ck 4 funny, f$ck yourself and save your money!"));
}
~CCryptoContext()
{
if (m_pKey != NULL)
{
delete[] m_pKey;
m_pKey = NULL;
}
// Release the provider handle.
if (m_hProv != 0)
{
CryptReleaseContext(m_hProv, 0);
}
}
// Operations
DWORD Encrypt(LPBYTE pBuffer, DWORD dwBufLen, bool bEstimate = false) throw(...)
{
DWORD dwLen = dwBufLen;
if (bEstimate)
{
if (!CryptEncrypt(*m_pKey, NULL, TRUE, 0, NULL, &dwLen, dwBufLen))
{
throw CCryptoException(CCryptoException::fnEncrypt);
}
}
else
{
if (!CryptEncrypt(*m_pKey, NULL, TRUE, 0, pBuffer, &dwLen, dwBufLen))
{
throw CCryptoException(CCryptoException::fnEncrypt);
}
}
return dwLen;
}
DWORD Decrypt(LPBYTE pBuffer, DWORD dwBufLen) throw(...)
{
DWORD dwLen = dwBufLen;
if (!CryptDecrypt(*m_pKey, NULL, TRUE, 0, pBuffer, &dwLen))
{
throw CCryptoException(CCryptoException::fnDecrypt);
}
return dwLen;
}
// Data Members
private:
CKey* m_pKey;
HCRYPTPROV m_hProv;
};
| true |
0061f7d8110d5b2bf4c565fc17f2627aef7a0cbb
|
C++
|
tallerify/app-server
|
/src/api/controllers/PlayController.h
|
UTF-8
| 1,212 | 2.625 | 3 |
[] |
no_license
|
#ifndef FIUBA_TALLER2_TALLERIFY_APP_SERVER_PLAYCONTROLLER_H
#define FIUBA_TALLER2_TALLERIFY_APP_SERVER_PLAYCONTROLLER_H
#include <regex>
#include "Controller.h"
#include "../networking/JSONResponse.h"
/**
* @file PlayController.h
*/
class PlayController : public Controller {
public:
/**
* Constructor
*/
PlayController();
/**
* Destructor
*/
virtual ~PlayController();
/**
* Returns if current controller handles the given method and url
* @param method the http method of the request
* @param url of the request
* @return true if handles, false otherwise
*/
bool handles(std::string method, std::string url);
/**
* Process the given request and respond accordingly
* @param request to process
* @return the corresponding response
*/
Response *process(Request &request);
/**
* Get the static file *.mp3
* @param request request with the song to play
* @param response with the static file if file exists, 404 otherwise
*/
void get(Request &request, JSONResponse &response);
private:
std::regex playRegex;
};
#endif //FIUBA_TALLER2_TALLERIFY_APP_SERVER_PLAYCONTROLLER_H
| true |
2d3bc488e31bd4776f474d7740bf90048a59acba
|
C++
|
GF2595/HW_First_Semester
|
/06.10/06.10 (3)/06.10 (3)/main.cpp
|
WINDOWS-1251
| 1,068 | 3.484375 | 3 |
[] |
no_license
|
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <string>
using namespace std;
int main()
{
setlocale(LC_ALL, "rus");
ifstream file("../text.txt", ios::in);
if (!file.is_open())
{
cout << " " << endl;
return EXIT_FAILURE;
}
const int n = 50;
int numberOfStrings = 0;
bool isStringEmpty = true;
while (!file.eof())
{
char s[n] = { "" };
file.getline(s, n);
for (int i = 0; s[i] != '\0'; i++)
{
if ((s[i] != ' ') && (s[i] != '\t'))
{
isStringEmpty = false;
}
}
if (!isStringEmpty)
{
numberOfStrings++;
isStringEmpty = true;
}
}
file.close();
cout << " " << numberOfStrings << " " << endl;
return EXIT_SUCCESS;
}
/* :
:
:
7
*/
| true |
6c22e89a90a887c6d1376b6f85ab24d3132239b2
|
C++
|
DeepBlue14/rqt_ide
|
/modules/ide_old/src/MsgFileDat.cpp
|
UTF-8
| 1,700 | 2.53125 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
#include "MsgFileDat.h"
MsgFileDat::MsgFileDat()
{
//msgFileNameStrPtr = new QString();
msgFileHeaderStrPtr = new QString();
//msgFieldDatPtrVecPtr = new QVector<MsgFieldDat*>();
}
void MsgFileDat::setMsgFileNameStrPtr(QString msgFileNameStrPtr)
{
this->msgFileNameStrPtr = msgFileNameStrPtr;
}
QString MsgFileDat::getMsgFileNameStrPtr()
{
return msgFileNameStrPtr;
}
void MsgFileDat::setMsgFileHeaderStrPtr(QString* msgFileHeaderStrPtr)
{
this->msgFileHeaderStrPtr = msgFileHeaderStrPtr;
}
QString* MsgFileDat::getMsgFileHeaderStrPtr()
{
return msgFileHeaderStrPtr;
}
void MsgFileDat::pushToMsgFieldDatPtrVecPtr(MsgFieldDat* msgFieldDatPtr)
{
msgFieldDatPtrVecPtr.push_back(msgFieldDatPtr);
}
MsgFieldDat* MsgFileDat::popFromMsgFieldDatPtrVecPtr()
{
MsgFieldDat* tmp = new MsgFieldDat();
*tmp = *msgFieldDatPtrVecPtr.back();
msgFieldDatPtrVecPtr.pop_back();
return tmp;
}
QVector<MsgFieldDat*> MsgFileDat::getMsgFieldDatPtrVecPtr()
{
return msgFieldDatPtrVecPtr;
}
QString* MsgFileDat::toString()
{
QString* tmp = new QString();
tmp->append("msgFileName: " + getMsgFileNameStrPtr() );
tmp->append("\nmsgFileHeader: " + *getMsgFileHeaderStrPtr() );
tmp->append("\nmsgFieldDatPtrs:");
for(size_t i = 0; i < msgFieldDatPtrVecPtr.size(); i++)
{
tmp->append("\n\tField Type: " + *msgFieldDatPtrVecPtr.at(i)->getFieldTypeStrPtr()
+ "\tField Name: " + *msgFieldDatPtrVecPtr.at(i)->getFieldNameStrPtr()
+ "\tField Comment: " + *msgFieldDatPtrVecPtr.at(i)->getFieldCommentsStrPtr() );
}
return tmp;
}
MsgFileDat::~MsgFileDat()
{
;
}
| true |
e08e2c9e459af2ada63db6c666092941e04e288c
|
C++
|
wahidulalamriyad/Pharmacy_Management_System
|
/PCPP/Extra/Pharmacy-master/Users/Manager.cpp
|
UTF-8
| 20,064 | 2.515625 | 3 |
[] |
no_license
|
//
// Created by houss on 4/26/2017.
//
#include "Manager.hpp"
#include "../Headers/DBMS.hpp"
#include <iostream>
#include <sstream>
#include <algorithm>
using namespace std;
//Products
const std::string Manager::insertProduct = "INSERT_PRODUCT";
const std::string Manager::changeProductPriceByName = "CHANGE_PRODUCT_PRICE_BY_NAME";
const std::string Manager::changeProductPriceByID = "CHANGE_PRODUCT_PRICE_BY_ID";
const std::string Manager::changeProductQuantityByName = "CHANGE_PRODUCT_QUANTITY_BY_NAME";
const std::string Manager::changeProductQuantityByID = "CHANGE_PRODUCT_QUANTITY_BY_ID";
const std::string Manager::getOrdersTotalPrice = "GET_ORDERS_TOTAL_PRICE";
const std::string Manager::getEachOrderTotalPrice = "GET_EACH_ORDER_TOTAL_PRICE";
const std::string Manager::insertCategory = "INSERT_CATEGORY";
const std::string Manager::getTotalNumberOfTransactions = "GET_TOTAL_NUMBER_OF_TRANSACTIONS";
const std::string Manager::getTransactionOfSpecificProduct = "GET_TRANSACTION_OF_SPECIFIC_PRODUCT";
const std::string Manager::getTransactionsDoneByUserID = "GET_TRANSACTIONS_DONE_BY_USER_ID";
const std::string Manager::getTransactionsDoneByUserName = "GET_TRANSACTIONS_DONE_BY_USER_NAME";
void Manager::InitPreparedStatements() {
if (!S.getPreparedStatement(getOrdersTotalPrice)) {
stringstream query;
query << "SELECT SUM (Price*productQuantity) FROM Products JOIN orders USING (productid)" << endl;
S.requestNewPreparedStatement(getOrdersTotalPrice, query.str());
}
if (!S.getPreparedStatement(getEachOrderTotalPrice)) {
stringstream query;
query
<< "SELECT orderID, SUM (Price*productQuantity) FROM Products JOIN orders USING (productid) GROUP BY orderID ORDER BY orderid"
<< endl;
S.requestNewPreparedStatement(getEachOrderTotalPrice, query.str());
}
if (!S.getPreparedStatement(changeProductQuantityByID)) {
stringstream query;
query << "UPDATE products SET quantity = $1 WHERE productid = $2;" << endl;
S.requestNewPreparedStatement(changeProductQuantityByID, query.str());
}
if (!S.getPreparedStatement(insertProduct)) {
stringstream query;
query << "INSERT INTO products" << endl;
query << "VALUES (default, $1, $2, $3, $4, $5, $6)";
S.requestNewPreparedStatement(insertProduct, query.str());
}
if (!S.getPreparedStatement(changeProductPriceByName)) {
stringstream query;
query << "UPDATE products SET price = $1 WHERE productname LIKE $2;" << endl;
S.requestNewPreparedStatement(changeProductPriceByName, query.str());
}
if (!S.getPreparedStatement(changeProductPriceByID)) {
stringstream query;
query << "UPDATE products SET price = $1 WHERE productid = $2;" << endl;
S.requestNewPreparedStatement(changeProductPriceByID, query.str());
}
if (!S.getPreparedStatement(changeProductQuantityByName)) {
stringstream query;
query << "UPDATE products SET quantity = $1 WHERE productname LIKE $2;" << endl;
S.requestNewPreparedStatement(changeProductQuantityByName, query.str());
}
if (!S.getPreparedStatement(insertCategory)) {
stringstream query;
query << "INSERT INTO category VALUES ( default, $1);" << endl;
S.requestNewPreparedStatement(insertCategory, query.str());
}
if (!S.getPreparedStatement(getTotalNumberOfTransactions)) {
stringstream query;
query << "SELECT COUNT(transactionid) FROM transactions;" << endl;
S.requestNewPreparedStatement(getTotalNumberOfTransactions, query.str());
}
if (!S.getPreparedStatement(getTransactionOfSpecificProduct)) {
stringstream query;
query << "SELECT * FROM transactions WHERE productname LIKE $1 ORDER BY transactionid;" << endl;
S.requestNewPreparedStatement(getTransactionOfSpecificProduct, query.str());
}
if (!S.getPreparedStatement(getTransactionsDoneByUserID)) {
stringstream query;
query << "SELECT * FROM transactions WHERE userid = $1;" << endl;
S.requestNewPreparedStatement(getTransactionsDoneByUserID, query.str());
}
if (!S.getPreparedStatement(getTransactionsDoneByUserName)) {
stringstream query;
query << "SELECT * FROM transactions JOIN users USING(userid) WHERE users.username LIKE $1;"
<< endl;
S.requestNewPreparedStatement(getTransactionsDoneByUserName, query.str());
}
}
void Manager::insertProductf() {
std::string productname;
std::string productdetails;
std::string productIMG;
int quantity;
int categoryID;
double price;
cout << "Please enter the product name: ";
cin >> productname;
cout << "Please enter the product details: ";
cin >> productdetails;
cout << "Please enter the product IMG: ";
cin >> productIMG;
cout << "Please enter the product quantity: ";
cin >> quantity;
cout << "Please enter product category ID: ";
cin >> categoryID;
cout << "Please enter the product price: ";
cin >> price;
transform(productname.begin(),productname.end(),productname.begin(),::toupper);
const PreparedStatement *ps = S.getPreparedStatement("INSERT_PRODUCT");
SQLResult sqlResult = ps->run({productname, productdetails, productIMG, to_string(quantity), to_string(categoryID), to_string(price)});
if(sqlResult.hasError()){
cerr << sqlResult.getErrorMessage();
}
if (sqlResult.hasTableResult()) {
const SQLResultTable &sqlResultTable = sqlResult.getResultTable();
//cout << sqlResult << endl;
unsigned long tuple = sqlResultTable.getNumberOfTuples();
for (int i = 0; i < tuple; i++) {
cout << "\n " << sqlResultTable[i]->getString(0) << endl;
}
}
}
void Manager::changeProductPriceByNamef() {
std::string productname;
double price;
cout << "Please enter the product name: ";
cin >> productname;
cout << "Please enter the new product price: ";
cin >> price;
transform(productname.begin(),productname.end(),productname.begin(),::toupper);
const PreparedStatement *ps = S.getPreparedStatement("CHANGE_PRODUCT_PRICE_BY_NAME");
SQLResult sqlResult = ps->run({to_string(price), "%"+productname+"%"});
if(sqlResult.hasError()){
cerr << sqlResult.getErrorMessage();
}
if (sqlResult.hasTableResult()) {
const SQLResultTable &sqlResultTable = sqlResult.getResultTable();
//cout << sqlResult << endl;
unsigned long tuple = sqlResultTable.getNumberOfTuples();
for (int i = 0; i < tuple; i++) {
cout << "\n " << sqlResultTable[i]->getString(0) << endl;
}
}
}
void Manager::changeProductPriceByIDf() {
int ID;
double price;
cout << "Please enter the product ID: ";
cin >> ID;
cout << "Please enter the new product price: ";
cin >> price;
const PreparedStatement *ps = S.getPreparedStatement("CHANGE_PRODUCT_PRICE_BY_ID");
SQLResult sqlResult = ps->run({to_string(price), to_string(ID)});
if(sqlResult.hasError()){
cerr << sqlResult.getErrorMessage();
}
if (sqlResult.hasTableResult()) {
const SQLResultTable &sqlResultTable = sqlResult.getResultTable();
//cout << sqlResult << endl;
unsigned long tuple = sqlResultTable.getNumberOfTuples();
for (int i = 0; i < tuple; i++) {
cout << "\n " << sqlResultTable[i]->getString(0) << endl;
}
}
}
void Manager::changeProductQuantityByNamef() {
std::string productname;
int quantity;
cout << "Please enter the product name: ";
cin >>productname;
cout << "Please enter the product quantity: ";
cin >> quantity;
transform(productname.begin(),productname.end(),productname.begin(),::toupper);
const PreparedStatement *ps = S.getPreparedStatement("CHANGE_PRODUCT_QUANTITY_BY_NAME");
SQLResult sqlResult = ps->run({to_string(quantity), "%"+productname+"%"});
if(sqlResult.hasError()){
cerr << sqlResult.getErrorMessage();
}
if (sqlResult.hasTableResult()) {
const SQLResultTable &sqlResultTable = sqlResult.getResultTable();
//cout << sqlResult << endl;
unsigned long tuple = sqlResultTable.getNumberOfTuples();
for (int i = 0; i < tuple; i++) {
cout << "\n " << sqlResultTable[i]->getString(0) << endl;
}
}
}
void Manager::changeProductQuantityByIDf() {
int ID;
int quantity;
cout << "Please enter the product ID: ";
cin >> ID;
cout << "Please enter the product quantity: ";
cin >> quantity;
const PreparedStatement *ps = S.getPreparedStatement("CHANGE_PRODUCT_QUANTITY_BY_ID");
SQLResult sqlResult = ps->run({to_string(quantity), to_string(ID)});
if(sqlResult.hasError()){
cerr << sqlResult.getErrorMessage();
}
if (sqlResult.hasTableResult()) {
const SQLResultTable &sqlResultTable = sqlResult.getResultTable();
//cout << sqlResult << endl;
unsigned long tuple = sqlResultTable.getNumberOfTuples();
for (int i = 0; i < tuple; i++) {
cout << "\n " << sqlResultTable[i]->getString(0) << endl;
}
}
}
void Manager::getOrdersTotalPricef() {
const PreparedStatement *ps = S.getPreparedStatement("GET_ORDERS_TOTAL_PRICE");
SQLResult sqlResult = ps->run({});
if(sqlResult.hasError()){
cerr << sqlResult.getErrorMessage();
}
if (sqlResult.hasTableResult()) {
const SQLResultTable &sqlResultTable = sqlResult.getResultTable();
//cout << sqlResult << endl;
unsigned long tuple = sqlResultTable.getNumberOfTuples();
for (int i = 0; i < tuple; i++) {
cout << "All orders total price: " << sqlResultTable[i]->getString(0)<< "$" << endl;
}
}
}
void Manager::getEachOrderTotalPricef() {
const PreparedStatement *ps = S.getPreparedStatement("GET_EACH_ORDER_TOTAL_PRICE");
SQLResult sqlResult = ps->run({});
if(sqlResult.hasError()){
cerr << sqlResult.getErrorMessage();
}
if (sqlResult.hasTableResult()) {
const SQLResultTable &sqlResultTable = sqlResult.getResultTable();
//cout << sqlResult << endl;
unsigned long tuple = sqlResultTable.getNumberOfTuples();
for (int i = 0; i < tuple; i++) {
cout << "\nOrder ID: " << sqlResultTable[i]->getString(0)<< endl;
cout << "Total price: " << sqlResultTable[i]->getString(1)<< "$" << endl;
}
}
}
void Manager::insertCategoryf() {
std::string categoryname;
cout << " Please enter the category name: ";
cin >> categoryname;
const PreparedStatement *ps = S.getPreparedStatement("INSERT_CATEGORY");
SQLResult sqlResult = ps->run({categoryname});
if(sqlResult.hasError()){
cerr << sqlResult.getErrorMessage();
}
if (sqlResult.hasTableResult()) {
const SQLResultTable &sqlResultTable = sqlResult.getResultTable();
//cout << sqlResult << endl;
unsigned long tuple = sqlResultTable.getNumberOfTuples();
for (int i = 0; i < tuple; i++) {
cout << "\n" << sqlResultTable[i]->getString(0)<< endl;
}
}
}
void Manager::getTotalNumberOfTransactionsf() {
const PreparedStatement *ps = S.getPreparedStatement("GET_TOTAL_NUMBER_OF_TRANSACTIONS");
SQLResult sqlResult = ps->run({});
if(sqlResult.hasError()){
cerr << sqlResult.getErrorMessage();
}
if (sqlResult.hasTableResult()) {
const SQLResultTable &sqlResultTable = sqlResult.getResultTable();
//cout << sqlResult << endl;
unsigned long tuple = sqlResultTable.getNumberOfTuples();
for (int i = 0; i < tuple; i++) {
cout << "\nTotal number of Transactions: " << sqlResultTable[i]->getString(0)<< endl;
}
}
}
void Manager::getTransactionOfSpecificProductf() {
std::string productname;
cout << "Please enter the product name: ";
cin >> productname;
transform(productname.begin(),productname.end(),productname.begin(),::toupper);
const PreparedStatement *ps = S.getPreparedStatement("GET_TRANSACTION_OF_SPECIFIC_PRODUCT");
SQLResult sqlResult = ps->run({"%"+productname+"%"});
if(sqlResult.hasError()){
cerr << sqlResult.getErrorMessage();
}
if (sqlResult.hasTableResult()) {
const SQLResultTable &sqlResultTable = sqlResult.getResultTable();
//cout << sqlResult << endl;
unsigned long tuple = sqlResultTable.getNumberOfTuples();
for (int i = 0; i < tuple; i++) {
cout << "\nTransaction ID: " << sqlResultTable[i]->getString(0)<< endl;
cout << "Product price: " << sqlResultTable[i]->getString(1)<< "$" << endl;
cout << "Total quantity " << sqlResultTable[i]->getString(2)<< endl;
cout << "User ID: " << sqlResultTable[i]->getString(3) << endl;
cout << "Product name: " << sqlResultTable[i]->getString(4) << endl;
cout << "Date: " << sqlResultTable[i]->getString(5)<< endl;
}
}
}
void Manager::getTransactionsDoneByUserIDf() {
int ID;
cout << "Please enter the product ID: ";
cin >> ID;
const PreparedStatement *ps = S.getPreparedStatement("GET_TRANSACTIONS_DONE_BY_USER_ID");
SQLResult sqlResult = ps->run({to_string(ID)});
if(sqlResult.hasError()){
cerr << sqlResult.getErrorMessage();
}
if (sqlResult.hasTableResult()) {
const SQLResultTable &sqlResultTable = sqlResult.getResultTable();
//cout << sqlResult << endl;
unsigned long tuple = sqlResultTable.getNumberOfTuples();
for (int i = 0; i < tuple; i++) {
cout << "\nUser ID: " << sqlResultTable[i]->getString(0)<< endl;
cout << "Transaction ID: " << sqlResultTable[i]->getString(1)<< endl;
cout << "Product price: " << sqlResultTable[i]->getString(2)<< "$" << endl;
cout << "Product quantity " << sqlResultTable[i]->getString(3)<< endl;
cout << "Product name: " << sqlResultTable[i]->getString(4)<< endl;
cout << "Date: " << sqlResultTable[i]->getString(5)<< endl;
}
}
}
void Manager::getTransactionsDoneByUserNamef() {
std::string username;
cout << "Please enter the user name: ";
cin >> username;
const PreparedStatement *ps = S.getPreparedStatement("GET_TRANSACTIONS_DONE_BY_USER_NAME");
SQLResult sqlResult = ps->run({"%"+username+"%"});
if(sqlResult.hasError()){
cerr << sqlResult.getErrorMessage();
}
if (sqlResult.hasTableResult()) {
const SQLResultTable &sqlResultTable = sqlResult.getResultTable();
//cout << sqlResult << endl;
unsigned long tuple = sqlResultTable.getNumberOfTuples();
for (int i = 0; i < tuple; i++) {
cout << "\nTransaction ID: " << sqlResultTable[i]->getString(0)<< endl;
cout << "Product price: " << sqlResultTable[i]->getString(1)<< "$" << endl;
cout << "Product quantity " << sqlResultTable[i]->getString(2)<< endl;
cout << "User ID: " << sqlResultTable[i]->getString(3)<< endl;
cout << "Product name: " << sqlResultTable[i]->getString(4)<< endl;
cout << "Date: " << sqlResultTable[i]->getString(5)<< endl;
}
}
}
void Manager::userManager() {
cout << "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tCustomer selections: \n\n" ;
cout << "\t\t\t\t1- Get a product by the product ID." ;
cout << "\t\t\t\t\t\t\t\t2- Get a product by the product name."<< endl;
cout << "\t\t\t\t3- Get a product price by the product name." ;
cout << "\t\t\t\t\t\t4- Get a product ID."<< endl;
cout << "\t\t\t\t5- Get a product name" ;
cout << "\t\t\t\t\t\t\t\t\t\t\t6- Get a product details by the product name."<< endl;
cout << "\t\t\t\t7- Get a product IMG. " ;
cout << "\t\t\t\t\t\t\t\t\t\t\t8- Get a product quantity by the product name."<< endl;
cout << "\t\t\t\t9- Get a product quantity by the product ID." ;
cout << "\t\t\t\t\t10- Get a product by the product category ID."<< endl;
cout << "\t\t\t\t11- Get the number of products available." ;
cout << "\t\t\t\t\t\t12- Get a product price by the product ID."<< endl;
cout << "\t\t\t\t13- Get a product by the product description." ;
cout << "\t\t\t\t\t14- Get all the products in a category by ID."<< endl;
cout << "\t\t\t\t15- Get all the products in a category by name.\n\n\n" ;
cout << "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tEmployee selections:\n\n"<<endl;
cout << "\t\t\t\t16- Add Order";
cout << "\t\t\t\t\t\t\t\t\t\t\t\t\t17- Remove order by order name ID." << endl;
cout << "\t\t\t\t18- Update order quantity.";
cout << "\t\t\t\t\t\t\t\t\t\t19- Insert Transaction." << endl;
cout << "\t\t\t\t20- Get transaction by transaction date.";
cout << "\t\t\t\t\t\t21- Get all transactions of a specific product." << endl;
cout << "\t\t\t\t22- Get all Categories.";
cout << "\t\t\t\t\t\t\t\t\t\t\t23- Get products by category ID." << endl;
cout << "\t\t\t\t24- Add Bill.";
cout << "\t\t\t\t\t\t\t\t\t\t\t\t\t25- Get Bill by ID.\n\n" << endl;
cout << "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tManager selections: \n\n"<<endl;
cout << "\t\t\t\t26- Insert a new Product.";
cout << "\t\t\t\t\t\t\t\t\t\t27- Change a product price by product name." << endl;
cout << "\t\t\t\t28- Change a product price by product ID.";
cout << "\t\t\t\t\t\t29- Change a product quantity by product name." << endl;
cout << "\t\t\t\t30- Change a product quantity by product ID.";
cout << "\t\t\t\t\t31- Get all orders total price." << endl;
cout << "\t\t\t\t32- Get each order total price.";
cout << "\t\t\t\t\t\t\t\t\t33- Insert a new category." << endl;
cout << "\t\t\t\t34- Get the total number of Transactions done.";
cout << "\t\t\t\t\t35- Get transaction of a specific product." << endl;
cout << "\t\t\t\t36- Get all Transactions done by an Employee by Employee ID.";
cout << "\t37- Get Transactions done by an Employee by Employee name.\n\n" << endl;
int choice;
cout << "\n\t\t\t\tSelect: ";
cin >> choice;
cout << "\n\n";
switch (choice)
{
case 1: getProductFromIDf();
case 2: getProductFromNamef();
case 3: getProductPriceByNamef();
case 4: getProductIDf();
case 5: getProductNamef();
case 6: getProductDetailsByNamef();
case 7: getProductIMGf();
case 8: getProductQuantityByNamef();
case 9: getProductQuantityByIDf();
case 10: getProductCategoryIDf();
case 11: getNumberOfProductsf();
case 12: getProductPriceByIDf();
case 13: getProductByDescriptionf();
case 14: getAllProductsByCategoryIDf();
case 15: getAllProductsByCategoryNamef();
case 16: addOrderf();
case 17: removeOrderByNameIDf();
case 18: updateOrderQuantityf();
case 19: insertTransactionf();
case 20: getTransactionFromDatef();
case 21: getAllTransactionsOfAProductf();
case 22: getAllCategoriesf();
case 23: getProductsByCategoryIDf();
case 24: addBillf();
case 25: getBillByIDf();
case 26: insertProductf();
case 27: changeProductPriceByNamef();
case 28: changeProductPriceByIDf();
case 29: changeProductQuantityByNamef();
case 30: changeProductQuantityByIDf();
case 31: getOrdersTotalPricef();
case 32: getEachOrderTotalPricef();
case 33: insertCategoryf();
case 34: getTotalNumberOfTransactionsf();
case 35: getTransactionOfSpecificProductf();
case 36: getTransactionsDoneByUserIDf();
case 37: getTransactionsDoneByUserNamef();
default: "Error! Please enter a number from 1 to 37.";
}
}
| true |
79b1e7e781d5c02f1da8c327ca7b79b7642347b0
|
C++
|
MatthewASimonson/C-fundamentals
|
/Referencing Data/rd.cpp
|
UTF-8
| 616 | 3.375 | 3 |
[] |
no_license
|
/*
* rd.cpp
*
* Created on: Mar 3, 2010
* Author: Matthew Simonson
*/
# include <iostream>
using namespace std;
int main()
{
int num;
int& rnum=num;// At the address in memory of rnum, a value is stored, this value is num
rnum=400;
cout<<"Value direct: "<<num<<endl;
cout<<"Value via reference: "<<rnum<<endl;
cout<<"Address direct: "<<&num<<endl; //output the address in memory of num
cout<<"Address via reference: "<<&rnum<<endl; //refers to rnum, which refers to num, so nums address will be output
rnum*=2;
cout<<"Value direct:"<<num<<endl;
cout<<"Value via reference: "<<rnum<<endl;
return 0;
}
| true |
12c781dc3cc7165d241efaa72a0c486e6cc36f55
|
C++
|
AmitShmuel/FileSystem-June16
|
/Folder.h
|
UTF-8
| 604 | 2.796875 | 3 |
[] |
no_license
|
#ifndef _FOLDER_
#define _FOLDER_
#include "FileComponent.h"
#include <list>
using namespace std;
class Folder : public FileComponent { // acts as the composite
// implements clone() as part of the prototype pattern
list<FileComponent*> files;
public:
Folder(string fileName = "new file") : FileComponent(fileName) { ; }
Folder(const Folder& f);
void addFile(FileComponent* f, int dst);
void copy(int id);
void remove(int id);
virtual string toString();
virtual FileComponent* clone() { return new Folder(*this); }
bool isFolder() const { return true; }
};
#endif // !_FOLDER_
| true |
c150c155dea2dfae39016c54c94f75490105cd9a
|
C++
|
denys-hrulov/ToDOlist
|
/src/core/utils/data_transfer/TaskDTOConverter.h
|
UTF-8
| 955 | 2.75 | 3 |
[] |
no_license
|
//
// Created by denis on 03.08.20.
//
#ifndef TODOLIST_TASKDTOCONVERTER_H
#define TODOLIST_TASKDTOCONVERTER_H
#include "core/memory_model/api/RepositoryTaskDTO.h"
#include "core/memory_model/data/Task.h"
#include "core/memory_model/structure/TaskNode.h"
/*
* Class providing some conversions between Task, TaskNode, TaskDTO objects.
*
* @author Denys Hrulov
*/
class TaskDTOConverter {
public:
/*
* Method to create Task instance from DTO fields.
*
* @param DTO representing the task. Task ID will be ignored.
*
* @return Task instance built by dto fields.
*/
static Task getTask(const RepositoryTaskDTO& dto);
/*
* Method to create TaskDTO instance from TaskNode.
*
* @param TaskNode to extract data.
*
* @return DTO describing task in the node.
*
*/
static RepositoryTaskDTO getDTO(const std::shared_ptr<TaskNode>& node);
};
#endif //TODOLIST_TASKDTOCONVERTER_H
| true |
b9418a9279eef9771f603f4c5b85900c144aa172
|
C++
|
msk4862/DS-Algo
|
/Practice/EulerProject/smallestMult.cpp
|
UTF-8
| 529 | 3.15625 | 3 |
[] |
no_license
|
#include<iostream>
using namespace std;
int smallestMult(int n) {
long num = 2*n;
bool divisible = true;
while(true) {
divisible = true;
for (int i = 2; i <= n; i++)
{
if(num%i != 0) {
divisible = false;
break;
}
}
if(divisible)
return num;
else
num += n;
}
}
int main() {
int n;
cout<<"Enter no.";
cin>>n;
cout<<smallestMult(n);
return 0;
}
| true |
2b469817c10d156417aacc6b44647c33803a0660
|
C++
|
18292677162/TextSimilarity
|
/TextSimilarity/TextSimilarity/test.cpp
|
UTF-8
| 2,301 | 2.515625 | 3 |
[] |
no_license
|
#include "TextSimilarity.h"
#include <fstream>
#include <cassert>
#include <string>
#include <Windows.h>
using namespace std;
//const char* const DICT_PATH = "jieba.dict.utf8";
//const char* const HMM_PATH = "hmm_model.utf8";
//const char* const USER_DICT_PATH = "user.dict.utf8";
//const char* const IDF_PATH = "idf.utf8";
//const char* const STOP_WORD_PATH = "stop_words.utf8";
int main() {
TextSimilarity test("dict");
TextSimilarity::wordFreq exWF1;
TextSimilarity::wordFreq exWF2;
exWF1 = test.getWordFreq("test1.txt");
exWF2 = test.getWordFreq("test2.txt");
vector<pair<string, int>> wfVec1 = test.sortByValueReverse(exWF1);
vector<pair<string, int>> wfVec2 = test.sortByValueReverse(exWF2);
cout << "wfVec1:" << endl;
for (int i = 0; i < 10; i++){
cout << test.UTF8ToGBK(wfVec1[i].first) << ":" << wfVec1[i].second << " , ";
}
cout << endl;
cout << "wfVec2:" << endl;
for (int i = 0; i < 10; i++){
cout << test.UTF8ToGBK(wfVec2[i].first) << ":" << wfVec2[i].second << " , ";
}
cout << endl;
/*
TestSimilarity::wordFreq::const_iterator map_it;
for (map_it = wf.begin(); map_it != wf.end(); map_it++)
{
cout << "(\"" << test.UTF8ToGBK(map_it->first) << "\"," << map_it->second << ")" << endl;
}
*/
/*
TestSimilarity::wordSet wSet1;
TestSimilarity::wordSet wSet2;
test.selectAimWords(wfVec1, wSet1);
cout << "wSet1:" << endl;
for (const auto& e : wSet1){
cout << test.UTF8ToGBK(e) << ", ";
}
cout << endl;
test.selectAimWords(wfVec2, wSet2);
cout << "wSet2:" << endl;
for (const auto& e : wSet2){
cout << test.UTF8ToGBK(e) << ", ";
}
cout << endl;
*/
TextSimilarity::wordSet wSet;
test.selectAimWords(wfVec1, wSet);
cout << "wSet:" << endl;
test.selectAimWords(wfVec2, wSet);
for (const auto& e : wSet){
cout << test.UTF8ToGBK(e) << ", ";
}
cout << endl;
vector<double> exVec1;
vector<double> exVec2;
exVec1 = test.getOneHot(wSet, exWF1);
exVec2 = test.getOneHot(wSet, exWF2);
cout << "exVec1:" << endl;
for (const auto& v : exVec1){
cout << v << ", ";
}
cout << endl;
cout << "exVec2:" << endl;
for (const auto& v : exVec2){
cout << v << ", ";
}
cout << endl;
double db = 0;
db = test.cosine(exVec1, exVec2);
cout << "文本相似度为:" << db * 100 <<"%"<< endl;
system("pause");
return 0;
}
| true |
1b4b7361da5993d121167f4e97b0308554dac494
|
C++
|
rodrigobmg/ECSE
|
/ECSETest/TestInputManager.cpp
|
UTF-8
| 13,413 | 3.140625 | 3 |
[
"MIT"
] |
permissive
|
#include "gtest/gtest.h"
#include "ECSE/InputManager.h"
class InputManagerTest : public ::testing::Test
{
public:
ECSE::InputManager manager;
InputManagerTest()
{
manager.setRequireFocus(false);
}
};
class InputManagerRunTest : public InputManagerTest
{
public:
InputManagerRunTest()
{
resetValues();
std::function<bool()> boolfn = []() { return false; };
std::function<int8_t()> intfn = []() { return 0; };
std::function<float()> floatfn = []() { return 0.0f; };
std::function<bool()> dynamicfn = [&]() { return dynamicValue; };
manager.bindInput(0, 0, boolfn);
manager.bindInput(1, 0, intfn);
manager.bindInput(2, 0, floatfn, 0.2f);
manager.bindInput(3, 0, dynamicfn);
manager.bindInput(0, 1, boolfn);
manager.bindInput(1, 1, intfn);
manager.bindInput(2, 1, floatfn, 0.4f);
manager.bindInput(3, 1, dynamicfn);
}
void resetValues()
{
a = 0;
b = 0;
c = 0;
d = 0;
e = 0;
frames = 0;
mouseAvg = sf::Vector2i();
}
void runLoop(int length)
{
for (int i = 0; i < length; ++i)
{
manager.update();
bool anyPressed = false;
if (manager.getIntValue(0) > 0)
{
a += 1;
anyPressed = true;
}
if (manager.getFloatValue(1) >= 0.7)
{
b += 1;
anyPressed = true;
}
if (manager.getIntValue(2) < 1)
{
c += 1;
anyPressed = true;
}
if (manager.getIntValue(3) > 0)
{
d += 1;
anyPressed = true;
}
if (!anyPressed)
{
e += 1;
}
mouseAvg = (mouseAvg * frames + manager.getMousePosition()) / (frames + 1);
++frames;
}
}
int a, b, c, d, e;
int frames;
bool dynamicValue;
sf::Vector2i mouseAvg;
};
TEST_F(InputManagerTest, TestIsBound)
{
std::function<bool()> fn = []() { return false; };
manager.bindInput(0, 0, fn);
ASSERT_TRUE(manager.isBound(0));
}
TEST_F(InputManagerTest, TestBoolInput)
{
bool value;
std::function<bool()> fn = [&value]() { return value; };
manager.bindInput(0, 0, fn);
value = false;
manager.update();
ASSERT_EQ(0, manager.getIntValue(0));
ASSERT_FLOAT_EQ(0.f, manager.getFloatValue(0));
value = true;
manager.update();
ASSERT_EQ(1, manager.getIntValue(0));
ASSERT_FLOAT_EQ(1.f, manager.getFloatValue(0));
}
TEST_F(InputManagerTest, TestIntInput)
{
int value;
std::function<int8_t()> fn = [&value]() { return value; };
manager.bindInput(0, 0, fn);
value = 0;
manager.update();
ASSERT_EQ(0, manager.getIntValue(0));
ASSERT_FLOAT_EQ(0.f, manager.getFloatValue(0));
value = 1;
manager.update();
ASSERT_EQ(1, manager.getIntValue(0));
ASSERT_FLOAT_EQ(1.f, manager.getFloatValue(0));
value = -1;
manager.update();
ASSERT_EQ(-1, manager.getIntValue(0));
ASSERT_FLOAT_EQ(-1.f, manager.getFloatValue(0));
}
TEST_F(InputManagerTest, TestFloatInput)
{
float value;
std::function<float()> fn = [&value]() { return value; };
manager.bindInput(0, 0, fn);
value = 0.f;
manager.update();
ASSERT_EQ(0, manager.getIntValue(0));
ASSERT_FLOAT_EQ(0.f, manager.getFloatValue(0));
value = 1.f;
manager.update();
ASSERT_EQ(1, manager.getIntValue(0));
ASSERT_FLOAT_EQ(1.f, manager.getFloatValue(0));
value = -1.f;
manager.update();
ASSERT_EQ(-1, manager.getIntValue(0));
ASSERT_FLOAT_EQ(-1.f, manager.getFloatValue(0));
}
TEST_F(InputManagerTest, TestDelta)
{
int value;
std::function<int8_t()> fn = [&value]() { return value; };
manager.bindInput(0, 0, fn);
value = 0;
manager.update();
ASSERT_EQ(0, manager.getIntDelta(0));
ASSERT_FLOAT_EQ(0.f, manager.getFloatDelta(0));
value = 1;
manager.update();
ASSERT_EQ(1, manager.getIntDelta(0));
ASSERT_FLOAT_EQ(1.f, manager.getFloatDelta(0));
value = -1;
manager.update();
ASSERT_EQ(-2, manager.getIntDelta(0));
ASSERT_FLOAT_EQ(-2.f, manager.getFloatDelta(0));
}
TEST_F(InputManagerTest, TestSensitivity)
{
float value;
float precision = 1 << ECSE_INPUT_PRECISION;
std::function<float()> fn = [&value]() { return value; };
manager.bindInput(0, 0, fn, 0.3f);
value = 0.1f;
manager.update();
ASSERT_EQ(0, manager.getIntValue(0));
ASSERT_NEAR(0.f, manager.getFloatValue(0), precision);
value = 0.4f;
manager.update();
ASSERT_EQ(1, manager.getIntValue(0));
ASSERT_NEAR(0.4f, manager.getFloatValue(0), precision);
value = -0.4f;
manager.update();
ASSERT_EQ(-1, manager.getIntValue(0));
ASSERT_NEAR(-0.4f, manager.getFloatValue(0), precision);
}
TEST_F(InputManagerTest, TestMultipleInputs)
{
int val1, val2;
std::function<int8_t()> fn1 = [&val1]() { return val1; };
manager.bindInput(0, 0, fn1);
std::function<int8_t()> fn2 = [&val2]() { return val2; };
manager.bindInput(1, 0, fn2);
val1 = 0;
val2 = 0;
manager.update();
ASSERT_EQ(0, manager.getIntValue(0));
ASSERT_EQ(0, manager.getIntValue(1));
val1 = 1;
val2 = 0;
manager.update();
ASSERT_EQ(1, manager.getIntValue(0));
ASSERT_EQ(0, manager.getIntValue(1));
val1 = 1;
val2 = 1;
manager.update();
ASSERT_EQ(1, manager.getIntValue(0));
ASSERT_EQ(1, manager.getIntValue(1));
val1 = 0;
val2 = 1;
manager.update();
ASSERT_EQ(0, manager.getIntValue(0));
ASSERT_EQ(1, manager.getIntValue(1));
}
TEST_F(InputManagerTest, TestSwitchModes)
{
int val1, val2;
std::function<int8_t()> fn1 = [&val1]() { return val1; };
manager.bindInput(0, 0, fn1);
std::function<int8_t()> fn2 = [&val2]() { return val2; };
manager.bindInput(0, 1, fn2);
val1 = 0;
val2 = 0;
manager.update();
manager.setInputMode(0);
ASSERT_EQ(0, manager.getIntValue(0));
manager.setInputMode(1);
ASSERT_EQ(0, manager.getIntValue(0));
val1 = 1;
val2 = 0;
manager.update();
manager.setInputMode(0);
ASSERT_EQ(1, manager.getIntValue(0));
manager.setInputMode(1);
ASSERT_EQ(0, manager.getIntValue(0));
val1 = 1;
val2 = 1;
manager.update();
manager.setInputMode(0);
ASSERT_EQ(1, manager.getIntValue(0));
manager.setInputMode(1);
ASSERT_EQ(1, manager.getIntValue(0));
val1 = 0;
val2 = 1;
manager.update();
manager.setInputMode(0);
ASSERT_EQ(0, manager.getIntValue(0));
manager.setInputMode(1);
ASSERT_EQ(1, manager.getIntValue(0));
}
TEST_F(InputManagerTest, TestMultipleModes)
{
int val1, val2;
std::function<int8_t()> fn1 = [&val1]() { return val1; };
manager.bindInput(0, 0, fn1);
std::function<int8_t()> fn2 = [&val2]() { return val2; };
manager.bindInput(0, 1, fn2);
val1 = 0;
val2 = 0;
manager.update();
ASSERT_EQ(0, manager.getIntValue(0, 0));
ASSERT_EQ(0, manager.getIntValue(0, 1));
val1 = 1;
val2 = 0;
manager.update();
ASSERT_EQ(1, manager.getIntValue(0, 0));
ASSERT_EQ(0, manager.getIntValue(0, 1));
val1 = 1;
val2 = 1;
manager.update();
ASSERT_EQ(1, manager.getIntValue(0, 0));
ASSERT_EQ(1, manager.getIntValue(0, 1));
val1 = 0;
val2 = 1;
manager.update();
ASSERT_EQ(0, manager.getIntValue(0, 0));
ASSERT_EQ(1, manager.getIntValue(0, 1));
}
TEST_F(InputManagerTest, TestDemoDelta)
{
int value;
std::stringstream stream;
std::function<int8_t()> fn = [&value]() { return value; };
manager.bindInput(0, 0, fn);
// Record pressing only once
manager.startRecording(stream);
value = 1;
manager.update();
value = 0;
manager.update();
manager.update();
manager.stopRecording();
ASSERT_EQ(0, manager.getIntDelta(0));
manager.playDemo(stream);
manager.update();
manager.update();
ASSERT_EQ(-1, manager.getIntDelta(0));
manager.update();
ASSERT_EQ(0, manager.getIntDelta(0)) << "Input delta sticks when demo has no changes";
}
TEST_F(InputManagerTest, TestPreDemoDelta)
{
int value = 0;
std::stringstream stream;
std::function<int8_t()> fn = [&value]() { return value; };
manager.bindInput(0, 0, fn);
// Before the demo started, value was 1
value = 1;
manager.update();
manager.startRecording(stream);
manager.update();
manager.update();
manager.stopRecording();
// Now value is 0
value = 0;
manager.update();
manager.playDemo(stream);
manager.update();
ASSERT_EQ(0, manager.getIntDelta(0)) << "Demo starts with incorrect delta value";
}
TEST_F(InputManagerTest, TestPostDemoDelta)
{
int value = 0;
std::stringstream stream;
std::function<int8_t()> fn = [&value]() { return value; };
manager.bindInput(0, 0, fn);
manager.startRecording(stream);
value = 1;
manager.update();
manager.stopRecording();
value = 0;
manager.update();
manager.update();
manager.playDemo(stream);
manager.update();
ASSERT_EQ(-1, manager.getIntDelta(0)) << "Input delta does not account for demo values";
}
TEST_F(InputManagerRunTest, TestMonkey)
{
manager.startMonkeyMode();
runLoop(1000);
// These always increase, so if the monkey is at all good at pressing buttons this should work
ASSERT_FALSE(a == 0) << "Monkey may not be pressing buttons";
ASSERT_FALSE(b == 0) << "Monkey may not be pressing buttons";
ASSERT_FALSE(c == 0) << "Monkey may not be pressing buttons";
// This should be pretty unlikely
ASSERT_FALSE(a == b && b == c);
}
TEST_F(InputManagerRunTest, TestDemo)
{
std::stringstream stream;
manager.startMonkeyMode();
manager.startRecording(stream);
runLoop(1000);
manager.stopRecording();
manager.stopMonkeyMode();
int prevA = a;
int prevB = b;
int prevC = c;
int prevE = e;
resetValues();
manager.playDemo(stream);
runLoop(1000);
ASSERT_EQ(prevA, a);
ASSERT_EQ(prevB, b);
ASSERT_EQ(prevC, c);
ASSERT_EQ(prevE, e);
ASSERT_FALSE(manager.isPlayingDemo());
}
TEST_F(InputManagerRunTest, TestHoldDemo)
{
std::stringstream stream;
dynamicValue = true;
manager.startRecording(stream);
runLoop(1000);
manager.stopRecording();
int prevD = d;
// Real value is now false
dynamicValue = false;
manager.update();
resetValues();
manager.playDemo(stream);
runLoop(1000);
ASSERT_EQ(prevD, d) << "Demo cancelled early";
}
TEST_F(InputManagerRunTest, TestMouseDemo)
{
std::stringstream stream;
manager.startMonkeyMode();
manager.startRecording(stream, true);
runLoop(1000);
manager.stopRecording();
manager.stopMonkeyMode();
auto prevMouseAvg = mouseAvg;
resetValues();
manager.playDemo(stream);
runLoop(1000);
ASSERT_EQ(prevMouseAvg.x, mouseAvg.x);
ASSERT_EQ(prevMouseAvg.y, mouseAvg.y);
}
TEST_F(InputManagerRunTest, TestModeSwitchDemo)
{
std::stringstream stream;
manager.startMonkeyMode();
manager.startRecording(stream);
for (int i = 0; i < 100; ++i)
{
runLoop(10);
if (rand() % 100 > 90)
{
manager.setInputMode(manager.getInputMode() == 0 ? 1 : 0);
}
}
manager.stopRecording();
manager.stopMonkeyMode();
auto str = stream.str();
int prevA = a;
int prevB = b;
int prevC = c;
int prevE = e;
resetValues();
manager.playDemo(stream);
runLoop(1000);
ASSERT_EQ(prevA, a);
ASSERT_EQ(prevB, b);
ASSERT_EQ(prevC, c);
ASSERT_EQ(prevE, e);
}
TEST_F(InputManagerRunTest, TestInputGapDemo)
{
std::stringstream stream;
manager.startMonkeyMode();
manager.startRecording(stream);
for (int i = 0; i < 5; ++i)
{
runLoop(500);
if (manager.isInMonkeyMode()) manager.stopMonkeyMode();
else manager.startMonkeyMode();
}
manager.stopRecording();
manager.stopMonkeyMode();
int prevA = a;
int prevB = b;
int prevC = c;
int prevE = e;
resetValues();
manager.playDemo(stream);
runLoop(2500);
ASSERT_EQ(prevA, a);
ASSERT_EQ(prevB, b);
ASSERT_EQ(prevC, c);
ASSERT_EQ(prevE, e);
}
TEST_F(InputManagerRunTest, TestModeSwitchInputGapDemo)
{
std::stringstream stream;
manager.startMonkeyMode();
manager.startRecording(stream);
for (int i = 0; i < 20; ++i)
{
runLoop(50);
if (rand() % 100 > 90)
{
manager.setInputMode(manager.getInputMode() == 0 ? 1 : 0);
}
if (i % 10 == 0)
{
if (manager.isInMonkeyMode()) manager.stopMonkeyMode();
else manager.startMonkeyMode();
}
}
manager.stopRecording();
manager.stopMonkeyMode();
int prevA = a;
int prevB = b;
int prevC = c;
int prevE = e;
resetValues();
manager.playDemo(stream);
runLoop(1000);
ASSERT_EQ(prevA, a);
ASSERT_EQ(prevB, b);
ASSERT_EQ(prevC, c);
ASSERT_EQ(prevE, e);
}
| true |
710e8e241739f9130f0de9be53591a9cf81aa2de
|
C++
|
Akeepers/algorithm
|
/leetcode/240.cpp
|
UTF-8
| 549 | 3.0625 | 3 |
[
"MIT"
] |
permissive
|
#include <iostream>
#include <vector>
using namespace std;
class Solution
{
public:
bool searchMatrix(vector<vector<int>> &matrix, int target)
{
int m = matrix.size();
if (m == 0)
return false;
int n = matrix.front().size();
int i = 0, j = n - 1;
while (i < m && j >= 0)
{
if (matrix[i][j] == target)
return true;
matrix[i][j] > target ? j-- : i++;
}
return false;
}
};
int main()
{
system("pause");
return 0;
}
| true |
9229b49a4c18683578e0762fa6bf5da7e6ff52f3
|
C++
|
JeffLiuGar/gitPractice
|
/binaryGap/ConsoleApplication1/ConsoleApplication1.cpp
|
GB18030
| 3,479 | 2.84375 | 3 |
[] |
no_license
|
// ConsoleApplication1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <vector>
#include<iostream>
using namespace std;
//1
//2
//3 admended
//4
//2-5
//1-6
//2-7
//1-8
class Solution {
public:
bool judgeCircle(string moves) {
int x=0, y = 0;
for (int i = 0; i<moves.size(); i++){
switch (moves[i]){
case 'L':
x--;
break;
case 'R':
x++;
break;
case 'U':
y++;
break;
case 'D':
y--;
break;
}
if (0 == x && 0 == y)
return true;
else
return false;
}
}
int pivotIndex(vector<int>& nums) {
long sum = 0;
for (int i = 0; i < nums.size(); i++){
sum += nums[i];
}
int sumLeft = 0;
int pivot = 0;
for (int i = 0; i < nums.size() - 2; i++){
sumLeft += nums[i];
if (sum - sumLeft - nums[i + 1] == sumLeft){
pivot = i + 1;
break;
}
}
return pivot;
}
};
class Solution2 {
public:
vector<int> selfDividingNumbers(int left, int right) {
int N = right - left + 1;
vector<int> v;
v.reserve(N);
for (int i = 0; i<N; i++)
{
int test = left + i;
do
{
int m = test % 10;
if (m != 0 && test%m != 0)
break;
} while (test /= 10);
if (test == 0)
v.push_back(left + i);
}
return v;
}
};
vector<int> solution(vector<int> &A, int K) {
// write your code in C++14 (g++ 6.2.0)
int i = 0;
int N = A.size();
int times = K%N;
if (N <= 1)
return A;
for (i = 0; i<times; i++)
{
int temp = A.back();
for (int j = N - 1; j>0; j++)
{
A[j] = A[j - 1];
}
//memcpy(&A[1], &A[0], sizeof(int)*(N - 1));
A[0] = temp;
}
return A;
}
int countdiv()
{
int A = 6;
int B = 11;
int K = 2;
int ret = 0;
if (K>B)
return 0;
int rbound = ((B / K) + 1)*K;
ret = (rbound - A) / K;
int ttt = 5;
ret = 5;
}
int compare(const void * a, const void * b)
{
return (*(int*)a - *(int*)b);
}
int _tmain(int argc, _TCHAR* argv[])
{
int tem = countdiv();
const int values[] = { 80099, 16114, 63108, 25032,
31044, 59069, 39099, 13110, 34101, 66120, 19116, 72105, 70045, 38032, 41110, 12105, 75110, 27105, 1105, 9114, 67117, 20101, 21100, 11032, 79046, 32112, 5111, 6117, 45116, 22032, 61097, 65120, 49110, 15101, 82109, 50103, 54110, 17101, 46032, 4121,
76097, 7032, 57105, 2102, 58044, 8097, 44099, 73064, 81111, 43097, 30112, 14116, 60109, 74104, 77105, 35097, 64058, 29112, 55032, 33108, 71108, 40111, 47088, 52117, 56076, 68097, 37101, 78114, 24110, 53097, 69110, 48105, 18115, 26072, 3032,
42116, 62105, 51120, 28065, 10101, 23105, 36115 };
const int size = sizeof(values) / sizeof(int);
//vector<int> v(&values[0], &values[0]+sizeof(values));
std::qsort((void *)values, size, sizeof(int), compare);
char string[size + 1] = "";
for (int i = 0; i < size; i++){
string[i] = (char)(values[i] % 1000);
}
string[size] = 0;
printf("%s ", string);
char * ss = "0123456789";
//size_t len = strlen(*ss);
// int sss[100] = "0123456789";
/*
Solution s;
int A[] = { 3, 8, 9, 7, 6 };
vector<int> v(&A[0],&A[0]+5);
vector<int> v2 = solution(v, 3);
//v.reserve(10);
int i = sizeof(v[0]);
int iarray[] = { 1, 2, 3, 4, 5, 1, 2, 3, 4, 0 };
//count iarray
size_t count = sizeof(iarray) / sizeof(int);
//intʼ ivec3
vector<int> ivec3(iarray, iarray + count);
string str = "UD";
bool bout = s.judgeCircle(str);
int out = s.pivotIndex(ivec3);
cout << out << endl;
*/
return 0;
}
| true |
b01fb7fbfbd6a9886c0ce14eb9a8025b560f01a6
|
C++
|
kshitij86/code-examples
|
/prac/del_nHead.cpp
|
UTF-8
| 1,360 | 3.0625 | 3 |
[] |
no_license
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<int> veci;
typedef vector<string> vecs;
typedef vector<long> vecl;
typedef vector<vector<int>> vecvi;
typedef vector<vector<string>> vecvs;
#define REP(i, a, b) for (i = a; i < b; i++)
#define rep(i, n) REP(i, 0, n)
void print_arr(int arr[], int n)
{
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
cout << endl;
}
void print_vector(veci arr)
{
for (int i : arr)
{
cout << i << " ";
}
cout << endl;
}
void print_vectorv(vecvi arr)
{
for (veci i : arr)
{
print_vector(i);
}
cout << endl;
}
struct Node {
int data;
Node *next;
Node(int data) {
this->data = data;
this->next = NULL;
}
};
void print_list(Node *root) {
Node *temp = root;
while (temp != NULL) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
// b->c->d
// Data in the node is irrelevant
void del_nHead(Node *nHead) {
Node *temp = nHead->next;
nHead->data = nHead->next->data;
nHead->next = nHead->next->next;
free(temp);
}
int main()
{
cin.tie(NULL);
ios_base::sync_with_stdio(0);
int test;
Node *root = new Node(1);
root->next = new Node(3);
root->next->next = new Node(4);
root->next->next->next = new Node(5);
// Points to *not* the head
Node *nHead = root->next;
print_list(root);
del_nHead(nHead);
print_list(root);
}
| true |
efd891268e71384e616da7cd5d065410108a6954
|
C++
|
utkarshlath/Programs
|
/InterviewBit/Arrays/NextPermutation.cpp
|
UTF-8
| 549 | 2.953125 | 3 |
[] |
no_license
|
vector<int> Solution::nextPermutation(vector<int> &A) {
vector<int> ans = A;
sort(ans.begin(),ans.end(),greater<int>());
if(ans==A)
{
sort(A.begin(),A.end());
return A;
}
int n = A.size();
int index=-1;
for(int i=n-2;i>=0;i--){
if(A[i]<A[i+1]){
index=i;
break;
}
}
sort(A.begin() + index + 1, A.end());
for (int i=index+1; i<n; i++) {
if (A[i] > A[index]) {
swap(A[i],A[index]);
break;
}
}
return A;
}
| true |
c2f40764e92288da61463639fd619ca19c9c365b
|
C++
|
kuonanhong/UVa-2
|
/437 - The Tower of Babylon.cpp
|
UTF-8
| 1,565 | 3.03125 | 3 |
[] |
no_license
|
/**
UVa 437 - The Tower of Babylon
by Rico Tiongson
Submitted: September 20, 2013
Accepted 0.015s C++
O(3n^2) time
*/
#include<iostream>
#include<cstring>
#include<vector>
#include<set>
#include<algorithm>
#define MX 35
using namespace std;
struct block{
private:
int x, y, z;
public:
int length()const{ return x; }
int width()const{ return y; }
int height()const{ return z; }
void normalize(){
if( x>y ) swap(x,y);
}
block() {}
block( int X, int Y, int Z ): x(X), y(Y), z(Z) {}
block( const block& _ ): x(_.x), y(_.y), z(_.z) { normalize(); }
void rotate(){
swap(x,y);
swap(y,z);
}
void in(){
cin >> x >> y >> z;
}
void out() const{
cout << x << " " << y << " " << z << endl;
}
bool operator<( const block& _ ) const{
return ( x < _.x || ( x==_.x && y < _.y ) );
}
} b;
vector<block> v;
int n, i, j, tc, h;
int dp[95];
int main(){
while( cin >> n, n ){
v.clear();
for( i=0; i<n; ++i ){
b.in();
for( j=0; j<3; ++j ){
v.push_back( block(b) );
b.rotate();
}
}
sort( v.begin(), v.end() );
memset( dp, -1, sizeof dp );
for( i=0; i<v.size(); ++i ){
if( dp[i]==-1 ) dp[i] = v[i].height();
for( j=i+1; j<v.size(); ++j ){
if( v[i].length() == v[j].length() ) continue;
if( v[i].width() < v[j].width() ){
dp[j] = max( dp[i]+v[j].height(), dp[j] );
}
}
}
h = 0;
for( i=0; i<v.size(); ++i ){
h = max( dp[i], h );
}
cout << "Case " << ++tc << ": maximum height = " << h << endl;
}
}
| true |
88e21ffb666a164e04cc2958750d0776f0cca3ca
|
C++
|
jamesdorevski/CV
|
/CSCI251 (C++)/Assignment 3/Braille.cpp
|
UTF-8
| 551 | 2.84375 | 3 |
[] |
no_license
|
#include <iostream>
#include <string>
#include <map>
#include "Latin.h"
#include "Braille.h"
using namespace std;
map<string, char> Braille::brailleToLatinRules;
Braille::Braille(char _brailleBit) {
brailleBit = _brailleBit;
}
bool operator< (const Braille& lhs, const Braille& rhs) {
return lhs.brailleBit < rhs.brailleBit;
}
bool operator== (const Braille& lhs, const Braille& rhs) {
return lhs.brailleBit == rhs.brailleBit;
}
std::ostream& operator<< (std::ostream& out, const Braille& braille) {
out << braille.brailleBit;
return out;
}
| true |
ae506f353d32ef937a410dfa81a5c670c3b51836
|
C++
|
samuelassis/TPs-2020
|
/Algoritmos1/TP2/graphCP.cpp
|
UTF-8
| 2,403 | 3.09375 | 3 |
[] |
no_license
|
#include "graph.h"
using namespace std;
Graph::Graph(int n){
this-> n_vertex = n;
this-> graph = new vector<Vertex>[n];
this-> tourist_values = new int [n];
}
void Graph::add_edge(int A,int B,int ec){
Vertex vA,vB;
int tv = tourist_values[A] + tourist_values[B];
vA.index = A;
vB.index = B;
vA.edge_cost = vB.edge_cost = ec;
vA.value = vB.value = ec-tv;
graph[A].push_back(vB);
graph[B].push_back(vA);
}
void Graph::add_tv(string s){
istringstream ss (s);
string aux;
int i=0, v;
while(ss >> aux){
v = stoi(aux);
this->tourist_values[i] = v;
i++;
}
}
int Graph::min_cost_idx(int *cost, bool *set){
int min = INT_MAX, idx = 0;
for(int i = 0; i < n_vertex;i++){
if(!set[i] && cost[i] < min){
min = cost[i];
idx = i;
}
}
return idx;
}
void Graph::show_results(){
Vertex mst [this->n_vertex];
int acc_appeal = 0, total_cost=0;
int incidence[this->n_vertex];
// cout<<"* "<<p<<" *"<<endl;
MST(mst);
for(int i = 0;i<n_vertex;i++)
incidence[i] = 0;
for(int i=0;i<n_vertex;i++){
if(mst[i].index == -1) continue;
acc_appeal += tourist_values[i] + tourist_values[mst[i].index];
total_cost += mst[i].edge_cost;
incidence[i]++;
incidence[mst[i].index]++;
}
cout<<total_cost<<" "<<acc_appeal<<endl;
for(int i =0;i<n_vertex;i++){
cout<<incidence[i]<<" ";
}
printf("\n");
for(int i=0; i <n_vertex;i++){
if(mst[i].index == -1) continue;
cout<<i<<" "<<mst[i].index<<" "<<mst[i].edge_cost<<endl;
}
}
void Graph::MST(Vertex* parent){
int bst_cost[this->n_vertex];
bool MSTset[this->n_vertex];
for(int i = 0; i < n_vertex;i++){
parent[i].index = INT_MAX;
bst_cost[i] = INT_MAX;
MSTset[i] = false;
}
parent[0].index = -1;
bst_cost[0] = 0;
vector<Vertex>::iterator it;
for(int i=0;i < n_vertex -1;i++){
int v = min_cost_idx(bst_cost,MSTset);
MSTset[v] = true;
for(it = graph[v].begin(); it != graph[v].end();it++){
if(MSTset[(*it).index] == false && bst_cost[(*it).index] > (*it).value){
bst_cost[(*it).index] = (*it).edge_cost;
parent[(*it).index].index = v;
parent[(*it).index].edge_cost = (*it).edge_cost;
}
}
}
}
void Graph::print(){
vector<Vertex>::iterator it;
for(int i = 0; i<this->n_vertex;i++){
cout<<"."<<i<<"."<<"("<<tourist_values[i]<<") -> ";
for(it = graph[i].begin(); it != graph[i].end();it++){
cout<<(*it).index<<" ($"<<(*it).edge_cost<<")"<<" - ";
}
printf("\n");
}
}
| true |
03f6c078a7db398823583efc99e9b77ccc045488
|
C++
|
gakarak/UAV_Projects
|
/TrajectoryVisualizer/model/entities/trajectory.h
|
UTF-8
| 2,198 | 2.78125 | 3 |
[] |
no_license
|
#ifndef TRAJECTORY_H
#define TRAJECTORY_H
#include <vector>
#include <opencv2/features2d.hpp>
#include "map.h"
namespace modelpkg
{
struct Trajectory
{
Trajectory() {}
void pushBackFrame(const Map &frame);
void removeFrame(int frame_num);
void setFrameKeyPoints(int frame_num, const std::vector<cv::KeyPoint> &frame_key_points);
void setFrameDescription(int frame_num, const cv::Mat &description);
void setFrameQuality(int frame_num, double quality);
size_t getFramesCount() const { return frames.size(); }
std::vector<cv::KeyPoint>& getFrameAllKeyPoints(int frame_num) { return key_points[frame_num]; }
cv::Mat& getFrameDescription(int frame_num) { return descriptions[frame_num]; }
Map& getFrame(int frame_num) { return frames[frame_num]; }
const Map& getFrame(int frame_num) const { return frames[frame_num]; }
const std::vector<cv::KeyPoint>& getFrameAllKeyPoints(int frame_num) const { return key_points[frame_num]; }
const cv::KeyPoint& getFrameKeyPoint(int frame_num, int kp_num) const { return key_points[frame_num][kp_num]; }
const cv::Mat& getFrameDescription(int frame_num) const { return descriptions[frame_num]; }
double getFrameQuality(int frame_num) const { return frames_quality[frame_num]; }
std::vector<Map>& getAllFrames() { return frames; }
const std::vector<Map>& getAllFrames() const { return frames; }
const std::vector<std::vector<cv::KeyPoint>>& getAllKeyPoints() const { return key_points; }
const std::vector<cv::Mat>& getAllDescriptions() const { return descriptions; }
const std::vector<double>& getAllFramesQuality() const { return frames_quality; }
private:
std::vector<Map> frames;
std::vector<std::vector<cv::KeyPoint>> key_points;
std::vector<cv::Mat> descriptions; //for each frame of key points
std::vector<double> frames_quality;
};
}
#endif // TRAJECTORY_H
| true |
64db358a40ed2aefaf3c3fbbf2b9bcc86b694725
|
C++
|
OscarShiang/QtChess
|
/button.cpp
|
UTF-8
| 1,154 | 2.75 | 3 |
[] |
no_license
|
#include "button.h"
#include <QPen>
#include <QBrush>
#include <QFont>
Button::Button(QString label_name, int width, int height, int size) : font_size(size) {
setAcceptHoverEvents(true);
rect = new QGraphicsRectItem();
rect->setRect(0, 0, width, height);
QPen pen;
pen.setColor(Qt::red);
pen.setWidth(height / 10);
rect->setPen(pen);
rect->setBrush(Qt::red);
text = new QGraphicsTextItem();
text->setFont(QFont(font_family, font_size));
text->setPlainText(label_name);
text->setDefaultTextColor(Qt::white);
addToGroup(rect);
addToGroup(text);
text->setPos(rect->rect().width() / 2 - text->boundingRect().width() / 2, rect->rect().height() / 2 - text->boundingRect().height() / 2);
}
void Button::hoverEnterEvent(QGraphicsSceneHoverEvent *event) {
rect->setBrush(Qt::darkRed);
}
void Button::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) {
rect->setBrush(Qt::red);
}
void Button::mousePressEvent(QGraphicsSceneMouseEvent *event) {
emit clicked();
}
qreal Button::width() {
return rect->rect().width();
}
qreal Button::height() {
return rect->rect().height();
}
| true |
18b81a336f70bd0056c82f2db3f15963fbd1c727
|
C++
|
spiderxm/Competitive-Coding
|
/Kickstart/1.cpp
|
UTF-8
| 742 | 2.53125 | 3 |
[] |
no_license
|
//
// Created by Mrigank Anand on 19/04/20.
//
//shuru apni marzi se kiye the ab fhodne ka man kar raha hai
#include<iostream>
#include <maps>
#define ll long long
#define sq(a) (a)*(a)
#define endl "\n"
#define boost ios::sync_with_stdio(0); cin.tie(0); cout.tie(0)
using namespace std;
int main() {
//Hello world
ll t;
cin >> t;
for (ll j = 0; j < t; j++) {
ll n;
cin >> n;
ll h[n];
for (ll i = 0; i < n; i++) {
cin >> h[i];
}
ll count = 0;
for (ll i = 1; i < n - 1; i++) {
if (h[i] > h[i - 1] && h[i] > h[i + 1]) {
count++;
}
}
cout << "Case #" << j + 1 << ": " << count << "\n";
}
return 0;
}
| true |
3e0ac31c2d5d93be0b4f96574e8d90bed2b16d66
|
C++
|
xQQsHia/AyDA-B2018
|
/week_1/homework_solution.cpp
|
UTF-8
| 755 | 2.984375 | 3 |
[
"MIT"
] |
permissive
|
# include <iostream>
# include <vector>
using namespace std;
using ull = unsigned long long int;
bool filter(int a)
{
return a > 9 and a < 27;
}
ull test_char(vector<ull> &v, int i, string s)
{
string conv;
conv = s[i - 2];
conv += s[i - 1];
if(filter(atoi(conv.c_str())))
return v[i - 2];
else
return 0;
}
int main()
{
string s;
while(true){
getline(cin, s);
if(s == "0")
break;
size_t n = s.size();
vector<ull> v(5000);
v[0] = v[1] = 1;
for(int i = 2; i <= n; i++)
{
if(s[i - 1] != '0')
v[i] = v[i - 1];
v[i] += test_char(v, i, s);
}
cout << v[n] << endl;
}
return 0;
}
| true |
6c589f3d578c71508ed2b0a77dc251a4ae367706
|
C++
|
mbachm/CarND-PID-Control-Project
|
/src/PID.cpp
|
UTF-8
| 2,184 | 2.9375 | 3 |
[] |
no_license
|
#include "PID.h"
#include <math.h>
#include <iostream>
using namespace std;
/*
* TODO: Complete the PID class.
*/
PID::PID() {}
PID::~PID() {}
void PID::Init(double Kp, double Ki, double Kd) {
p_error = 0.0;
i_error = 0.0;
d_error = 0.0;
p = {Kp, Ki, Kd};
dp = {0.2, 0.2, 0.2};
step_ = 0;
number_of_settle_steps_ = 200;
number_of_steps_to_twiddle_ = 1500;
actual_param_to_twiddle_ = 0;
best_error_ = numeric_limits<double>::max();
twiddle_ = false;
this->Kp = Kp;
this->Ki = Ki;
this->Kd = Kd;
}
void PID::UpdateError(double cte) {
cte_prev_ = cte_;
cte_ = cte;
cte_mem_ = cte_mem_ + cte_;
p_error = Kp * cte_;
i_error = Ki * cte_mem_;
d_error = Kd * (cte_-cte_prev_);
if (twiddle_
&& step_ > number_of_settle_steps_
&& step_ < (number_of_settle_steps_+ number_of_steps_to_twiddle_)) {
Twiddle(cte);
}
++step_;
}
void PID::Twiddle(double cte) {
double actual_error = pow(cte, 2);
cout << "step: " << step_ << endl;
cout << "total error: " << total_error_ << endl;
cout << "best error: " << best_error_ << endl;
cout << "actual error: " << actual_error << endl;
if(actual_error < best_error_) {
best_error_ = actual_error;
dp[actual_param_to_twiddle_] *= 1.1;
// next parameter
NextTwiddleParameter();
}
if (!tried_adding_ && !tried_subtracting_){
p[actual_param_to_twiddle_] += dp[actual_param_to_twiddle_];
Kp = p[0];
Ki = p[1];
Kd = p[2];
tried_adding_ = true;
} else if (tried_adding_ && !tried_subtracting_) {
p[actual_param_to_twiddle_] -= 2 * dp[actual_param_to_twiddle_];
Kp = p[0];
Ki = p[1];
Kd = p[2];
tried_subtracting_ = true;
} else {
p[actual_param_to_twiddle_] += dp[actual_param_to_twiddle_];
Kp = p[0];
Ki = p[1];
Kd = p[2];
dp[actual_param_to_twiddle_] *= 0.9;
// next parameter
NextTwiddleParameter();
}
}
double PID::TotalError() {
total_error_= p_error + d_error + i_error;
return total_error_;
}
void PID::NextTwiddleParameter() {
actual_param_to_twiddle_ = (actual_param_to_twiddle_ + 1) % 3;
tried_adding_ = false;
tried_subtracting_ = false;
}
| true |
aff7b4e0db79ee9d135e94a3ac230807e8baba00
|
C++
|
georgy-schukin/rage-rts
|
/src/Rage/expression.h
|
UTF-8
| 353 | 2.59375 | 3 |
[] |
no_license
|
#pragma once
#include "codeargs.h"
namespace rage {
class Expression
{
public:
enum Type
{
BINARY = 0,
UNARY,
DATA_ITEM,
CONST_ITEM
};
public:
virtual Type getType() const = 0;
virtual int evalInt(const CodeArgs &args) = 0;
virtual bool evalBoolean(const CodeArgs &args) = 0;
virtual string evalData(const CodeArgs &args) = 0;
};
}
| true |
4870ca9e3c1b5260657628306912cd7c038ff265
|
C++
|
abdarker/Divide-and-Concure
|
/Untitled2.cpp
|
UTF-8
| 939 | 3.484375 | 3 |
[] |
no_license
|
#include<bits/stdc++.h>
void DivnCon(int arr[],int i,int j,int& min,int& max)
{
if (i==j)
{
if (max<arr[i])
max=arr[i];
if (min>arr[j])
min=arr[j];
return;
}
if (j-i==1)
{
if (arr[i]<arr[j])
{
if (min>arr[i])
min=arr[i];
if (max<arr[j])
max=arr[j];
}
else
{
if (min>arr[j])
min=arr[j];
if (max<arr[i])
max=arr[i];
}
return;
}
int mid=(i+j)/2;
DivnCon(arr,i,mid,min,max);
DivnCon(arr, mid + 1,j, min, max);
}
int main()
{
int arr[] = {1,2,3,4,5,6};
int n = sizeof(arr)/sizeof(arr[0]);
int max = INT_MIN, min = INT_MAX;
DivnCon(arr,0, n-1, min, max);
printf("%d\n",min);
printf("%d",max);
}
| true |
034732ff20b388d7c1813c8d697d10a61c788bbf
|
C++
|
soni-sachin/CP1_CIPHERSCHOOLS
|
/leetcode2/single no .cpp
|
UTF-8
| 245 | 2.890625 | 3 |
[] |
no_license
|
class Solution {
public:
int singleNumber(vector<int>& nums) {
if(nums.empty()) return 0;
int ptr = nums[0];
for(int i = 1; i<nums.size();i++) {
ptr = ptr ^ nums[i];
}
return ptr;
}
};
| true |
a52e65d660f8f4535af4b3fa409f6c2a8db4a60b
|
C++
|
Robofever/AutoBot
|
/serial_comm/serial_comm.ino
|
UTF-8
| 812 | 2.890625 | 3 |
[] |
no_license
|
void setup(){
Serial.begin(9600); // same baud rate (bits per second) for proper serial communication
pinMode(LED_BUILTIN, OUTPUT); // LED built-in at digital pin 13 and ground pin besides it
}
// run the below command in pi terminal to list out all the ports with the beginning of "tty"
// ls /dev/tty*
// this will display all available ports
// now on attaching Arduino via USB to Raspberry Pi, a new port appears i.e., port for Arduino
// note the new port name for Python code in RPi
void loop() {
if (Serial.available() > 0) {
String data = Serial.readStringUntil('\n');
printf(data);
if (data=="Panel is unclean") {
digitalWrite(LED_BUILTIN, HIGH);
Serial.println("Done");
}
else {
digitalWrite(LED_BUILTIN, LOW);
}
}
}
| true |
aa6e45130eae99e86888930260c40f563146afc9
|
C++
|
BioroboticsLab/pipeline
|
/pipeline/util/opencv_fill_poly/lines_impl.h
|
UTF-8
| 1,389 | 2.96875 | 3 |
[] |
no_license
|
/*
* lines_impl.h
*
* Created on: Mar 2, 2015
* Author: tobias
*/
#ifndef LINES_IMPL_H_
#define LINES_IMPL_H_
namespace heyho {
template<typename F>
inline F hline(F f, no_boundaries_tag, int x_left, int x_right, int y)
{
for(; x_left <= x_right; ++x_left) {
f(cv::Point(x_left, y));
}
return std::move(f);
}
template<typename F>
inline F hline(F f, cv::Size boundaries, int x_left, int x_right, int y)
{
if (y >= 0 && y < boundaries.height)
{
return hline(
std::move(f),
no_boundaries_tag{},
std::max(x_left, 0),
std::min(x_right, boundaries.width - 1),
y
);
}
return std::move(f);
}
template<typename F>
inline F hline(F f, cv::Rect boundaries, int x_left, int x_right, int y) {
if (y >= boundaries.tl().y && y < boundaries.br().y)
{
return hline(
std::move(f),
no_boundaries_tag{},
std::max(x_left, boundaries.tl().x ),
std::min(x_right, boundaries.br().x - 1),
y
);
}
return std::move(f);
}
template<typename LINE_IT, typename F, typename B>
F line(F f, B boundaries, cv::Point pt1, cv::Point pt2, connectivity line_type, bool left_to_right)
{
if (left_to_right && pt1.x > pt2.x) {
using std::swap;
swap(pt1, pt2);
}
for (LINE_IT it(boundaries, pt1, pt2, line_type); !it.end(); ++it) {
f(*it);
}
return std::move(f);
}
}
#endif /* LINES_IMPL_H_ */
| true |
e6922f662f9d26a8730585494d5016809c0945c6
|
C++
|
Marcel1804/comp3801
|
/CollisionDetection.cpp
|
UTF-8
| 6,788 | 2.875 | 3 |
[] |
no_license
|
#include <stdio.h>
#define SENSOR_LIMIT 2.60 // maximum reading distance of sensor in meters
#define LEFT_SECTION 0
#define RIGHT_SECTION 1
#define FRONT_SECTION 2
#define BACK_SECTION 3
#define FpinBuzzer 5
#define BUZZER_PIN FpinBuzzer
// global variables
//previous times
unsigned long prevTime[4] = { 0 };
// previous speeds
float prevDistance[4] = { 0.0f };
// jump filter
bool prevSignal[4] = { false };
// front section
int FpinRL = 4;
int FpinGL = 3;
int FpinUSecho = 9;
int FpinUStri = 13;
// left section
int LpinRL = A0; //Analog pin
int LpinGL = A3; //Analog pin
int LpinUSecho = 8;
int LpinUStri = 12;
// right section
int RpinRL = A1; //Analog pin
int RpinGL = A4; //Analog pin
int RpinUSecho = 7;
int RpinUStri = 11;
// back section
int BpinRL = A2; //Analog pin
int BpinGL = A5; //Analog pin
int BpinUSecho = 6;
int BpinUStri = 10;
void setup()
{
Serial.begin(9600);
// buzzer
pinMode(FpinBuzzer, OUTPUT);
//front board
pinMode(FpinUStri, OUTPUT);
pinMode(FpinUSecho, INPUT);
pinMode(FpinGL, OUTPUT);
pinMode(FpinRL, OUTPUT);
//left board
pinMode(LpinUStri, OUTPUT);
pinMode(LpinUSecho, INPUT);
pinMode(LpinGL, OUTPUT);
pinMode(LpinRL, OUTPUT);
//rigth board
pinMode(RpinUStri, OUTPUT);
pinMode(RpinUSecho, INPUT);
pinMode(RpinGL, OUTPUT);
pinMode(RpinRL, OUTPUT);
//back board
pinMode(BpinUStri, OUTPUT);
pinMode(BpinUSecho, INPUT);
pinMode(BpinGL, OUTPUT);
pinMode(BpinRL, OUTPUT);
}
void loop()
{
double distance = 0.0f;
float _time = 0.0f;
float velc = 0.0f;
unsigned long curTime = 0;
bool s = false;
// clear pin signals
ResetAllPins();
//front board
distance = ReadSensor(FpinUStri, FpinUSecho);
if (distance < 0) {
digitalWrite(FpinGL, LOW);
digitalWrite(FpinRL, HIGH);
Serial.println("Front section has echo.");
}
else {
curTime = millis();
_time = (float)(curTime - prevTime[FRONT_SECTION]) / 1000;
velc = (prevDistance[FRONT_SECTION] - distance) / _time;
prevDistance[FRONT_SECTION] = distance;
prevTime[FRONT_SECTION] = curTime;
/*Serial.print("distance[Front]: ");
Serial.print(distance);
Serial.println(" meters");
Serial.print("velocity[Front]: ");
Serial.print(velc);
Serial.println(" m/s");*/
if (distance <= 0.5 && velc >= 0.2) {
s = true;
if (s and prevSignal[FRONT_SECTION]) {
tone(BUZZER_PIN, 500, 200);
}
//Serial.println("back CONTINUEOUS side trigger");
}
else if (distance < 1 && velc > 0.2) {
s = true;
if (s and prevSignal[FRONT_SECTION]) {
tone(BUZZER_PIN, 500, 50);
}
//Serial.println("back side trigger");
}
prevSignal[FRONT_SECTION] = s;
}
//left board
s = false;
distance = ReadSensor(LpinUStri, LpinUSecho);
if (distance < 0) {
analogWrite(LpinGL, LOW);
analogWrite(LpinRL, HIGH);
Serial.println("Left section has echo.");
}
else {
curTime = millis();
_time = (float)(curTime - prevTime[LEFT_SECTION]) / 1000;
velc = (prevDistance[LEFT_SECTION] - distance) / _time;
prevDistance[LEFT_SECTION] = distance;
prevTime[LEFT_SECTION] = curTime;
/*Serial.print("distance[Left]: ");
Serial.print(distance);
Serial.println(" meters");
Serial.print("velocity[Left]: ");
Serial.print(velc);
Serial.println(" m/s");*/
if (distance <= 0.5 && velc >= 0.2) {
s = true;
if (s and prevSignal[LEFT_SECTION]) {
tone(BUZZER_PIN, 900, 200);
}
//Serial.println("back CONTINUEOUS side trigger");
}
else if (distance < 1 && velc > 0.2) {
s = true;
if (s and prevSignal[LEFT_SECTION]) {
tone(BUZZER_PIN, 900, 50);
}
//Serial.println("back side trigger");
}
prevSignal[LEFT_SECTION] = s;
}
//rigth board
s = false;
distance = ReadSensor(RpinUStri, RpinUSecho);
if (distance < 0) {
analogWrite(RpinGL, LOW);
analogWrite(RpinRL, HIGH);
Serial.println("Right section has echo.");
}
else {
curTime = millis();
_time = (float)(curTime - prevTime[RIGHT_SECTION]) / 1000;
velc = (prevDistance[RIGHT_SECTION] - distance) / _time;
prevDistance[RIGHT_SECTION] = distance;
prevTime[RIGHT_SECTION] = curTime;
/*Serial.print("distance[Right]: ");
Serial.print(distance);
Serial.println(" meters");
Serial.print("velocity[Right]: ");
Serial.print(velc);
Serial.println(" m/s");*/
if (distance <= 0.5 && velc >= 0.2) {
s = true;
if (s and prevSignal[RIGHT_SECTION]) {
tone(BUZZER_PIN, 1500, 200);
}
//Serial.println("back CONTINUEOUS side trigger");
}
else if (distance < 1 && velc > 0.2) {
s = true;
if (s and prevSignal[RIGHT_SECTION]) {
tone(BUZZER_PIN, 1500, 50);
}
//Serial.println("back side trigger");
}
prevSignal[RIGHT_SECTION] = s;
}
//back board
s = false;
distance = ReadSensor(BpinUStri, BpinUSecho);
if (distance < 0) {
analogWrite(BpinGL, LOW);
analogWrite(BpinRL, HIGH);
Serial.println("Back section has echo.");
}
else {
curTime = millis();
_time = (float)(curTime - prevTime[BACK_SECTION]) / 1000;
velc = (prevDistance[BACK_SECTION] - distance) / _time;
prevDistance[BACK_SECTION] = distance;
prevTime[BACK_SECTION] = curTime;
/*Serial.print("distance[Back]: ");
Serial.print(distance);
Serial.println(" meters");
Serial.print("velocity[Back]: ");
Serial.print(velc);
Serial.println(" m/s");*/
if (distance <= 0.5 && velc >= 0.2) {
s = true;
if (s and prevSignal[BACK_SECTION]) {
tone(BUZZER_PIN, 3500, 200);
}
//Serial.println("back CONTINUEOUS side trigger");
}
else if (distance < 1 && velc > 0.2) {
s = true;
if (s and prevSignal[BACK_SECTION]) {
tone(BUZZER_PIN, 3500, 50);
}
//Serial.println("back side trigger");
}
prevSignal[BACK_SECTION] = s;
}
delay(50);
}
// sets all output and input pins to the connected devices to low
void ResetAllPins(void)
{
// sensor triggers
digitalWrite(FpinUStri, LOW);
digitalWrite(LpinUStri, LOW);
digitalWrite(RpinUStri, LOW);
digitalWrite(BpinUStri, LOW);
// sensor echos
digitalWrite(FpinUSecho, LOW);
digitalWrite(LpinUSecho, LOW);
digitalWrite(RpinUSecho, LOW);
digitalWrite(BpinUSecho, LOW);
// lights
digitalWrite(FpinGL, LOW);
digitalWrite(FpinRL, LOW);
analogWrite(LpinGL, LOW);
analogWrite(LpinRL, LOW);
analogWrite(RpinGL, LOW);
analogWrite(RpinRL, LOW);
analogWrite(BpinGL, LOW);
analogWrite(BpinRL, LOW);
// buzzer
//digitalWrite(BUZZER_PIN, LOW);
}
// returns the distance read from the sensor in meters.
double ReadSensor(int sensorTrig, int sensorEcho)
{
double result = 0.0f;
digitalWrite(sensorTrig, LOW);
delayMicroseconds(2);
digitalWrite(sensorTrig, HIGH);
delayMicroseconds(10);
digitalWrite(sensorTrig, LOW);
result = pulseIn(sensorEcho, HIGH);
result = (result / 58.2) / 100;
if (result > SENSOR_LIMIT) {
result = -1.0f;
}
return result;
}
| true |
7b8fcaea8420a46b2c1482d9c3db1f29154d04a5
|
C++
|
zuhalpolat/hackerrank-algorithms-solutions
|
/WarmUp/Compare the Triplets.cpp
|
UTF-8
| 339 | 3.15625 | 3 |
[] |
no_license
|
// Complete the compareTriplets function below.
vector<int> compareTriplets(vector<int> a, vector<int> b) {
vector<int> sumOfArrays = { 0, 0 };
for (int i = 0; i < a.size(); i++) {
if (a[i] > b[i])
sumOfArrays[0]++;
else if (b[i] > a[i])
sumOfArrays[1]++;
}
return sumOfArrays;
}
| true |