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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
341cd45e42fad9beefd8346a755e6a9b33fc3647 | C++ | Maxence53/P2RV_Sujet1 | /src/main.cpp | UTF-8 | 2,302 | 2.546875 | 3 | [] | no_license | // inclusion des biblioth�ques, dont OpenCV
#include <string.h>
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include <vector>
// Inclusion des fichiers utiles à la reconnaissance de visage
#include "faceDetection.hpp"
// namespace
using namespace std;
using namespace cv;
// Default wdth and height of the video
#define DEFAULT_VIDEO_WIDTH 800
#define DEFAULT_VIDEO_HEIGHT 600
#define pixelParMetre 0.000264 ///http://www.yourwebsite.fr/index.php/documents/287-relation-entre-pixel-et-taille-s-des-images
// Defining escape key
#define KEY_ESCAPE 27
VideoCapture cap; //la vid�o
Mat curImg ; //! l'image courante
int key = 0; //! touche du clavier
Mat imgFen; //! l'image d�coup�e
Mat imgFen2; //! l'image d�coup�e avec mouvement de la tete
float distanceCameraPaysage = 0.5f; //! distance paysage cam�ra (en m)
int decalagePixelHorizontal = 0; //! d�calage horizontal entre l'image obtenue par effet fen�tre et celle avec mouvement de la t�te
int decalagePixelVertical = 0; //! d�calage vertical entre l'image obtenue par effet fen�tre et celle avec mouvement de la t�te
int main(){
//! on r�cup�re l'image de la cam�ra avant dans une matrice
//on r�cup�re l'image
cap.open(0);
if(!cap.isOpened()) {
cerr << "Erreur lors de l'initialisation de la capture de la camera !"<< endl;
cerr << "Fermeture..." << endl;
exit(EXIT_FAILURE);
}
else{
// on joue la premi�re image
cap >> curImg;
}
//! cr�ation des fenetres OpenCV
//! Ce que renvoit la cam�ra
string windowNameCapture = "Image obtenue par la caméra";
namedWindow(windowNameCapture, CV_WINDOW_AUTOSIZE);
string windowNameVisage = "Image après détection de visage";
namedWindow(windowNameVisage, CV_WINDOW_AUTOSIZE);
//! on l'affiche en boucle !
while(key!= KEY_ESCAPE){
cap>>curImg;
imshow(windowNameCapture, curImg);
// Analyse de l'image et détection des yeux
detectAndDraw(curImg, 1);
imshow(windowNameVisage, curImg);
//! on r�cup�re la position de la t�te relative a la camera (ici elle est fix�e)
//float positionTete[3]=...
key = waitKey(1);
}
cv::destroyAllWindows();
return 0;
}
| true |
d938903f867885160e62e0bfee2a5fef41513e18 | C++ | urashima0429/keipro_practice | /arihon/3_2頻出テクニック/poj2785.cpp | UTF-8 | 774 | 2.5625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(){
const int MAX_N = 4000 + 10;
int N, A[MAX_N], B[MAX_N], C[MAX_N], D[MAX_N];
vector<int> v;
cin >> N;
for (int i = 0; i < N; ++i){
cin >> A[i] >> B[i] >> C[i] >> D[i];
}
for (int i = 0; i < N; ++i){
for (int j = 0; j < N; ++j){
v.push_back(C[i] + D[j]);
}
}
sort(v.begin(), v.end());
long long ans = 0;
for (int i = 0; i < N; ++i){
for (int j = 0; j < N; ++j){
int _ab = -(A[i] + B[j]);
ans += upper_bound(v.begin(), v.end(), _ab) - lower_bound(v.begin(), v.end(), _ab);
}
}
cout << ans << endl;
return 0;
}
| true |
987e5b7e4d11fc3d13c34cf343088ef1404029ce | C++ | GonzaPM7/TPV_Practica6 | /SDLProject/InputHandler.h | UTF-8 | 1,342 | 2.984375 | 3 | [] | no_license | #pragma once
#include <iostream>
#include <vector>
#include "sdl_includes.h"
#include "Vector2D.h"
class InputHandler {
public:
enum mouse_buttons {
LEFT = 0, MIDDLE = 1, RIGHT = 2
};
static InputHandler* instance() {
if (instance_ == 0) {
instance_.reset( new InputHandler() );
}
return instance_.get();
}
// update the input handler
void update();
// keyboard events
bool isKeyDown(SDL_Scancode key) const;
bool isKeyDown(SDL_Keycode key) const;
bool anyKeyDown() const;
// mouse events
bool getMouseButtonState(int buttonNumber) const;
const Vector2D& getMousePosition() const;
bool isMouseMoved() const;
// delete copy constructor and assignemnt operator
InputHandler(const InputHandler&) = delete;
InputHandler& operator=(const InputHandler&) = delete;
~InputHandler();
private:
InputHandler();
// private functions to handle different event types
void reset();
// handle keyboard events
void onKeyDown();
void onKeyUp();
// handle mouse events
void onMouseMove(SDL_Event& event);
void onMouseButtonDown(SDL_Event& event);
void onMouseButtonUp(SDL_Event& event);
// member variables
// keyboard specific
const Uint8* keystates_;
// mouse specific
std::vector<bool> mouseButtonStates_;
Vector2D mousePosition_;
// singleton
static unique_ptr<InputHandler> instance_;
};
| true |
d8c2677bbdf8d200b0988d573f96d3fca13ff66a | C++ | emiliev/IS-OOP-2018 | /Inheritance/SProgrammer.cpp | UTF-8 | 702 | 2.953125 | 3 | [
"MIT"
] | permissive | //
// SProgrammer.cpp
// inheritance
//
// Created by Emil Iliev on 29.04.18.
// Copyright © 2018 Emil Iliev. All rights reserved.
//
#include "SProgrammer.hpp"
SProgramer::SProgramer() {
numBooks = 0;
}
SProgramer::SProgramer(char* name, double salary, char* newLanguage,WorkingTime _wTime, int readBooks): JProgrammer(name,salary,newLanguage, _wTime){
setBooks(readBooks);
}
void SProgramer::setBooks(int numOfBooks) {
if (numOfBooks > 0) {
numBooks = numOfBooks;
} else {
numBooks = 1;
}
}
int SProgramer::getBooks() {
return numBooks;
}
void SProgramer::represent() {
JProgrammer::represent();
std::cout<<"num books:"<<numBooks<<std::endl;
}
| true |
b5fe381df2b2cfb0495c03d75e25aeb1aadfcd9b | C++ | everitt257/CarND-Kidnapped-Vehicle-Project | /src/particle_filter.cpp | UTF-8 | 7,884 | 2.703125 | 3 | [] | no_license | /*
* particle_filter.cpp
*
* Created on: Dec 12, 2016
* Author: Tiffany Huang
*/
#include <random>
#include <algorithm>
#include <iostream>
#include <numeric>
#include "particle_filter.h"
void ParticleFilter::init(double x, double y, double theta, double std[]) {
// TODO: Set the number of particles. Initialize all particles to first position (based on estimates of
// x, y, theta and their uncertainties from GPS) and all weights to 1.
// Add random Gaussian noise to each particle.
// NOTE: Consult particle_filter.h for more information about this method (and others in this file).
// Assign weights
num_particles = 200;
double init_weight = 1;
weights.assign(num_particles, init_weight);
// Initialize all particles to first position, with some noise
std::default_random_engine gen;
double std_x, std_y, std_psi;
std_x = std[0];
std_y = std[1];
std_psi = std[2];
std::normal_distribution<double> dist_x(x,std_x);
std::normal_distribution<double> dist_y(y,std_y);
std::normal_distribution<double> dist_psi(theta,std_psi);
Particle temp_p;
for(int i = 0; i < num_particles; i++){
temp_p.id = i;
temp_p.x = dist_x(gen);
temp_p.y = dist_y(gen);
temp_p.theta = dist_psi(gen);
temp_p.weight = 1.0;
// Push back
particles.push_back(temp_p);
}
is_initialized = true;
}
void ParticleFilter::prediction(double delta_t, double std_pos[], double velocity, double yaw_rate) {
// TODO: Add measurements to each particle and add random Gaussian noise.
// NOTE: When adding noise you may find std::normal_distribution and std::default_random_engine useful.
// http://en.cppreference.com/w/cpp/numeric/random/normal_distribution
// http://www.cplusplus.com/reference/random/default_random_engine/
std::default_random_engine gen;
for(int i = 0; i < particles.size(); i++){
double x_temp = particles[i].x;
double y_temp = particles[i].y;
double theta_temp = particles[i].theta;
// Split into two cases
if(fabs(yaw_rate) > 0.001){
x_temp = x_temp + velocity/yaw_rate * ( sin (theta_temp + yaw_rate*delta_t) - sin(theta_temp));
y_temp = y_temp + velocity/yaw_rate * ( cos(theta_temp) - cos(theta_temp+yaw_rate*delta_t) );
theta_temp = theta_temp + yaw_rate*delta_t;
}
else{
x_temp = x_temp + velocity*delta_t*cos(theta_temp);
y_temp = y_temp + velocity*delta_t*cos(theta_temp);
}
// Add some noise to measurement
std::normal_distribution<double> dist_x(x_temp,std_pos[0]);
std::normal_distribution<double> dist_y(y_temp,std_pos[1]);
std::normal_distribution<double> dist_psi(theta_temp,std_pos[2]);
particles[i].x = dist_x(gen);
particles[i].y = dist_y(gen);
particles[i].theta = dist_psi(gen);
//std::cout << "p.x = " << particles[i].x << " | " << "p.theta = " << particles[i].theta << " | ";
//std::cout << std::endl;
}
}
void ParticleFilter::dataAssociation(std::vector<LandmarkObs> predicted, std::vector<LandmarkObs>& observations) {
// TODO: Find the predicted measurement that is closest to each observed measurement and assign the
// observed measurement to this particular landmark.
// NOTE: this method will NOT be called by the grading code. But you will probably find it useful to
// implement this method and use it as a helper during the updateWeights phase.
// Not implemented
}
void ParticleFilter::updateWeights(double sensor_range, double std_landmark[],
std::vector<LandmarkObs> observations, Map map_landmarks) {
// TODO: Update the weights of each particle using a mult-variate Gaussian distribution. You can read
// more about this distribution here: https://en.wikipedia.org/wiki/Multivariate_normal_distribution
// NOTE: The observations are given in the VEHICLE'S coordinate system. Your particles are located
// according to the MAP'S coordinate system. You will need to transform between the two systems.
// Keep in mind that this transformation requires both rotation AND translation (but no scaling).
// The following is a good resource for the theory:
// https://www.willamette.edu/~gorr/classes/GeneralGraphics/Transforms/transforms2d.htm
// and the following is a good resource for the actual equation to implement (look at equation
// 3.33. Note that you'll need to switch the minus sign in that equation to a plus to account
// for the fact that the map's y-axis actually points downwards.)
// http://planning.cs.uiuc.edu/node99.html
// clear previous computed weights
weights.clear();
// define standard deviations
double std_x = std_landmark[0];
double std_y = std_landmark[1];
double std_x_sq2 = std_x*std_x;
double std_y_sq2 = std_y*std_y;
long double constant_1 = 1 / (2 * M_PI * std_x * std_y);
// for each particle
for(int i = 0; i < particles.size(); i++){
// save particle information for later use
double theta_temp = particles[i].theta;
double x_temp = particles[i].x;
double y_temp = particles[i].y;
long double weight_p = 1.0;
// given a particle's location, find all transformed measurement
for(int j = 0; j < observations.size(); j++){
// measurement in vehicle coordinates
double x_v = observations[j].x;
double y_v = observations[j].y;
// coordinate transformation starts here
// 1. Rotation
double x_m = x_v*cos(theta_temp) - y_v*sin(theta_temp);
double y_m = x_v*sin(theta_temp) + y_v*cos(theta_temp);
// 2. Add translational vector
x_m += x_temp;
y_m += y_temp;
// See if the transformed measuremnt is within the sensor range.
// if not within sensor range, skip
if(dist(x_temp, y_temp, x_m, y_m) > sensor_range)
continue;
// Setup a tempory minimum id for this observation:
int min_id = -1;
double threshhold = 50;
// given a transformed measurement find the closest landmark
for(int k = 0; k < map_landmarks.landmark_list.size(); k++){
// save each landmark's x,y coordiante for computing distance
double x_land = map_landmarks.landmark_list[k].x_f;
double y_land = map_landmarks.landmark_list[k].y_f;
int id_land = map_landmarks.landmark_list[k].id_i-1;
double smallest_distance = dist(x_m, y_m, x_land, y_land);
if (smallest_distance < threshhold){
min_id = id_land;
threshhold = smallest_distance;
}
}
//std::cout << "min id : " << min_id << std::endl;
if(min_id >= 0){
// Update the weight
long double u_x = map_landmarks.landmark_list[min_id].x_f;
long double u_y = map_landmarks.landmark_list[min_id].y_f;
long double x_diff_sq2 = (x_m - u_x)*(x_m - u_x);
long double y_diff_sq2 = (y_m - u_y)*(y_m - u_y);
long double part2 = x_diff_sq2 / std_x_sq2 + y_diff_sq2 / std_y_sq2;
long double weight_temp = constant_1*exp( (-1/2.) * (part2));
//std::cout << "weight temp : " << weight_temp << std::endl;
weight_p *= weight_temp;
}
}
particles[i].weight = weight_p;
//std::cout << "#" << i << ": " << weight_p << std::endl;
weights.push_back(weight_p);
}
}
void ParticleFilter::resample() {
// TODO: Resample particles with replacement with probability proportional to their weight.
// NOTE: You may find std::discrete_distribution helpful here.
// http://en.cppreference.com/w/cpp/numeric/random/discrete_distribution
std::default_random_engine gen;
std::discrete_distribution<int> distribution(weights.begin(), weights.end());
int weighted_index = distribution(gen);
std::vector<Particle> resampled_particles;
for(int i = 0; i < particles.size(); i++){
resampled_particles.push_back(particles[weighted_index]);
}
particles = resampled_particles;
}
void ParticleFilter::write(std::string filename) {
// You don't need to modify this file.
std::ofstream dataFile;
dataFile.open(filename, std::ios::app);
for (int i = 0; i < num_particles; ++i) {
dataFile << particles[i].x << " " << particles[i].y << " " << particles[i].theta << "\n";
}
dataFile.close();
}
| true |
1ccb59beaf7fec092435ae22ebcb992ff631817c | C++ | mauscarelli/Comptetitive-Programming | /mazes.cpp | UTF-8 | 759 | 2.546875 | 3 | [] | no_license | #include<bits/stdc++.h>
#define MAXV 10001
using namespace std;
vector<int> cor[MAXV];
bool find(int a,int b){
vector<int>::iterator it;
while(a!=b){
it = find(cor[a].begin(),cor[a].end(),a+1);
if(it != cor[a].end()) a++;
else return false;
}
return true;
}
int main(){
int r,c,q,a,b;
while(cin >> r >> c >> q, r){
for(int i=1;i<=r;i++)
cor[i].clear();
for(int i=0;i<c;i++){
cin >> a >> b;
cor[a].push_back(b);
cor[b].push_back(a);
}
for(int i=0;i<q;i++){
cin >> a >> b;
if(find(a,b)) cout << "Y" <<endl;
else cout << "N" << endl;
}
cout << "-" <<endl;
}
return 0;
} | true |
9dacd665a5859ffa27ceec8b4c91b7053fc70230 | C++ | liulanz/Study-Personal-Lab | /Programming Languae/Syracuse C++/554Lec/2019_01_22_Lecture_Linked_list_Reverse_RemoveOne.cpp | UTF-8 | 2,468 | 4.3125 | 4 | [] | no_license | #include <iostream>
using namespace std;
class ThreeD {
public:
int ht;
int wid;
int dep;
//constructor: the standard initializing methods
ThreeD(int i, int j, int k) {
ht = i * i; wid = j * j; dep = k * k;
}
ThreeD() { ht = wid = dep = 0; }
int vol() { return ht * wid*dep; }//return this->ht * this->wid * this->dep;
int area();
};
int ThreeD::area() { return 2 * (ht*wid + wid * dep + dep * ht); }
class node {
public:
int value;
node * next;
node(int i) { value = i; next = nullptr; }//NULL
node() { next = nullptr; }
};
class linked_list {
public:
node * head;
linked_list() { head = nullptr; }
void make_random_list(int m, int n);
void reverse();
void remove_one(int k); //remove the first occurance of node with value k
void print();
};
void linked_list::remove_one(int k) {
if (head == nullptr) return;
node * p1, *p2;
if (head->value == k) {
p1 = head;
head = head->next;
delete p1;
return;
}
p1 = head; p2 = p1->next;
while (p2 != nullptr) {
if (p2->value == k) {
p1->next = p2->next;
delete p2;
return;
}
p1 = p2;
p2 = p2->next;
}
}
void linked_list::reverse() {
if (head == nullptr || head->next == nullptr) return;
// if (head->next == nullptr || head == nullptr) return; might lead to error
//if (head = nullptr) return;
node * p1 = head, *p2, *p3;
p2 = p1->next;
while (p2 != nullptr) {
p3 = p2->next;
p2->next = p1;
if (p1 == head) p1->next = nullptr;
p1 = p2;
p2 = p3;
}
head = p1;
}
void linked_list::print() {
node * p1 = head;
while (p1 != nullptr) {
cout << p1->value << " ";
p1 = p1->next;
}
cout << endl;
}
void linked_list::make_random_list(int m, int n) { //create n nodes with random value between 0 and m-1
node * p1;
for (int i = 0; i < n; i++) {
p1 = new node(rand() % m);
p1->next = head;
head = p1;
}
}
int main() {
//default initializer_list
ThreeD t1 = { 3,4,5 };//= is optinal
cout << t1.ht << " " << t1.wid << " " << t1.dep << endl;
//3 4 5 if no constructor
//9 16 25 with constructor
ThreeD t2; //t2 has no initial values
cout << t2.ht << " " << t2.wid << " " << t2.dep << endl;
ThreeD *p1 = new ThreeD(10, 20, 30);
cout << (*p1).vol() << endl;
cout << p1->vol() << endl;//-> is pronounced as select
cout << p1->ht << " " << p1->wid << " " << p1->dep << endl;
linked_list L1;
L1.make_random_list(50, 10);
L1.print();
L1.reverse();
L1.print();
L1.remove_one(17);
L1.print();
getchar();
getchar();
return 0;
}
| true |
babdacca84f34f3795ff1d86440cb98cd29e77d8 | C++ | dgpark/Study | /AlgoStudy2020/p43165.cpp | UTF-8 | 1,220 | 3.578125 | 4 | [] | no_license | #include <string>
#include <vector>
using namespace std;
void plusNum(const vector<int>& numbers, int sum, const int& n_th, const int& target, int& answer);
void minusNum(const vector<int>& numbers, int sum, const int& n_th, const int& target, int& answer);
int solution(vector<int> numbers, int target) {
int answer = 0;
int sum = 0;
plusNum(numbers, sum, 0, target, answer);
minusNum(numbers, sum, 0, target, answer);
return answer;
}
void plusNum(const vector<int>& numbers, int sum, const int& n_th, const int& target, int& answer) {
sum += numbers[n_th];
if (n_th + 1 == numbers.size()) {
if (sum == target) answer++;
}
else {
plusNum(numbers, sum, n_th + 1, target, answer);
minusNum(numbers, sum, n_th + 1, target, answer);
}
}
void minusNum(const vector<int>& numbers, int sum, const int& n_th, const int& target, int& answer) {
sum -= numbers[n_th];
if (n_th + 1 == numbers.size()) {
if (sum == target) answer++;
}
else {
plusNum(numbers, sum, n_th + 1, target, answer);
minusNum(numbers, sum, n_th + 1, target, answer);
}
}
//https://programmers.co.kr/learn/courses/30/lessons/43165?language=cpp | true |
357f91fe51990d3a6b665d2c1ab7bfddab6cb312 | C++ | Jiltseb/Leetcode-Solutions | /solutions/1218.longest-arithmetic-subsequence-of-given-difference.323576884.ac.cpp | UTF-8 | 298 | 2.515625 | 3 | [
"MIT"
] | permissive | class Solution {
public:
int longestSubsequence(vector<int> &arr, int difference) {
int mp[40001] = {};
int off = 20000;
int ans = 0;
for (int n : arr) {
n += off;
mp[n] = max(mp[n], 1 + mp[n - difference]);
ans = max(ans, mp[n]);
}
return ans;
}
};
| true |
22e60cced23f7a549c2bf3672a0a368c01ed80b1 | C++ | fuzzyhunter0608/game-physics | /Mass Aggregate/EGP300-proj1/Moveable.h | UTF-8 | 924 | 2.828125 | 3 | [] | no_license | #pragma once
#include <GLTools.h>
#include "PhysicsEngine/Vector3.h"
class Moveable
{
public:
Moveable();
~Moveable();
void setPosition(const Vector3 &position) { mPosition = position; };
void setPosition(float x, float y, float z);
void setRotation(const Vector3 &rotation) { mRotation = rotation; };
void setRotation(float x, float y, float z);
void moveLeft(float distance);
void moveRight(float distance);
void moveForward(float distance);
void moveBack(float distance);
void moveUp(float distance);
void moveDown(float distance);
void rotateX(float distance);
void rotateY(float distance);
void rotateZ(float distance);
Vector3 getPosition() { return mPosition; };
Vector3 getRotation() { return mRotation; };
Vector3 getForwardVector();
Vector3 getRightVector();
Vector3 getUpVector();
void getRotationMatrix(M3DMatrix33f &matrix);
protected:
Vector3 mPosition;
Vector3 mRotation;
};
| true |
964f2d59481ed36c0f225665b76947740f0e1c51 | C++ | ansungho22/algorithm-practice | /[프로그래머스]완주하지못한선수/소스.cpp | UHC | 658 | 3 | 3 | [] | no_license | //
#include <string>
#include <vector>
#include <map>
#include <iostream>
using namespace std;
string solution(vector<string> participant, vector<string> completion) {
string answer = "";
map<string, int> m;
map<string, int> ::iterator it;
for (auto i : participant) {
if (m.find(i) != m.end()) {
m[i] += 1;
continue;
}
m.insert(make_pair(i, 1));
}
for (auto i : completion) {
if (m.find(i) != m.end()) {
if (m[i] == 1)m.erase(i);
else m[i] -=1;
}
}
it = m.begin();
answer = it->first;
return answer;
}
| true |
ef14c71d64f0870ea14b28bbb68030659a1383d5 | C++ | hophacker/algorithm_coding | /topcoder/programs/SixteenBricks.cpp | UTF-8 | 456 | 3.140625 | 3 | [] | no_license | #include <vector>
#include <algorithm>
using namespace std;
#define F(i,L,R) for (int i = L; i < R; i++)
class SixteenBricks
{
public:
int maximumSurface(vector <int> height)
{
sort(height.begin(), height.end());
int sum = 0;
F(i,8,16) sum += height[i] * 4;
F(i,0,2) sum -= height[i] * 4;
F(i,2,6) sum -= height[i] * 2;
return sum + 16;
}
};
| true |
3252369f3d8bab2a91806c93d38d3469b354390a | C++ | JoelEarps/C-Essentials-Training-Course | /Ex_Files_CPlusPlus_EssT/Exercise Files/Chap04/typeid.cpp | UTF-8 | 472 | 2.953125 | 3 | [] | no_license | // typeid.cpp by Bill Weinman <http://bw.org/>
// version of 2018-10-28
#include <cstdio>
#include <typeinfo> //need to keep this
#include <string>
using namespace std;
struct A { int x; };
struct B { int x; };
A a1;
B b1;
int main() {
printf("type of %s\n", typeid(string).name());
if(typeid(a1) == typeid(A)) {
puts("same");
} else {
puts("different");
}
return 0;
}
//returns a type info object which is contained from type info header
| true |
9409e58fa4b2e8cb2ed98ae858350573cc4b24d2 | C++ | amelco/lp1-2020.5 | /aula11/include/Diary.h | UTF-8 | 502 | 2.75 | 3 | [] | no_license | #ifndef DIARY_H
#define DIARY_H
#include "Message.h"
#include <string>
#include <vector>
struct Diary
{
Diary(const std::string& filename);
~Diary();
std::string filename;
std::vector<Message> messages;
bool add(const std::string& message); // adiciona string mensagem na lista de mensagens
bool write(); // escreve no arquivo
std::vector<Message*> search(std::string what); // retorna um vector de ponteiros de Mesage
std::string formated_message(Message message);
};
#endif
| true |
7a02d249486c38d9b0249436cc745caa777dee8f | C++ | Goto-Renato/yacre | /src/Materials/Diffuse.cc | UTF-8 | 451 | 2.515625 | 3 | [
"MIT"
] | permissive | #include "Diffuse.hh"
#include<glm/gtc/constants.hpp>
bool yacre::Diffuse::Reflection(const glm::vec3& in, const glm::vec3& normal,
glm::vec3& out) const
{
float u = yacre::Material::GetRandomNumber();
float r = glm::sqrt(u);
float t = glm::two_pi<float>() * yacre::Material::GetRandomNumber();
out.x = r * glm::cos(t);
out.y = r * glm::sin(t);
out.z = glm::sqrt(1.0f - u);
return true;
}
| true |
1661b7bbab321b1ed2fc84ce57858788ae196f29 | C++ | jnrdrgz/opengl_learning | /begginer/controls/listBox/listBox.h | UTF-8 | 496 | 2.921875 | 3 | [] | no_license | #ifndef LISTBOX_H
#define LISTBOX_H
#include "control.h"
#include <vector>
class ListBox : public Control
{
public:
ListBox(int posX, int posY, int w, int h);
void addItem(std::string item);
void removeItem(int index);
void setCurrent(int index);
int getIndex(void);
int getCount(void);
virtual bool updateControl(MouseState& state);
virtual void drawControl(void);
virtual std::string getType(void);
protected:
int index;
std::vector<std::string> items;
};
#endif //LISTBOX_H | true |
cf6f6a527a65311867eb31cac8a86febaa8aa44f | C++ | ArnisLielturks/Urho3D-Project-Template | /app/src/main/cpp/Levels/Splash.h | UTF-8 | 959 | 2.546875 | 3 | [
"MIT"
] | permissive | #pragma once
#include "../BaseLevel.h"
namespace Levels {
class Splash : public BaseLevel
{
URHO3D_OBJECT(Splash, BaseLevel);
public:
Splash(Context* context);
virtual ~Splash();
static void RegisterObject(Context* context);
void HandleUpdate(StringHash eventType, VariantMap& eventData);
protected:
void Init () override;
private:
void CreateScene();
/**
* Create the actual splash screen content
*/
void CreateUI();
void SubscribeToEvents();
/**
* Show next screen
*/
void HandleEndSplash();
/**
* Timer to check splash screen lifetime
*/
Timer timer_;
/**
* Current logo index
*/
int logoIndex_;
/**
* List of all the logos that splash screen should show
*/
Vector<String> logos_;
};
}
| true |
b982245a6219f806c00c63b9f637aeaae4e7982f | C++ | BSU2016gr09/AsonovDmitriy | /1term/2.3.cpp | UTF-8 | 2,541 | 2.953125 | 3 | [] | no_license | //Ìàññèâ À ÷èñåë ðàçìåðà N ïðîèíèöèàëèçèðîâàòü ñëó÷àéíûìè ÷èñëàìè èç ïðîìåæóòêà îò -N äî N.
// Íå èñïîëüçóÿ ôóíêöèè èç çàäà÷è 2-2 Íàïèñàòü ôóíêöèè (áåç swap è àíàëîãîâ) öèêëè÷åñêîãî ñäâèãà
// ýëåìåíòîâ ìàññèâà âïðàâî íà k ýëåìåíòîâ (1-é ñòàíåò 1+k -ûì, 2-é ñòàíåò 2+k -ûì è ò.ä.)
// è âëåâî íà k ýëåìåíòîâ.  main íàïèñàòü âûçîâ ýòèõ ôóíêöèé äëÿ ÷èñëà k,
//êîòîðîå ââîäèò ïîëüçîâàòåëü. (k ìîæåò áûòü â ÷àñòíîñòè =0, òîãäà ñäâèãà íåò,
// k=1 - çàäà÷à àíàëîãè÷íî ïðåäûäóùåé 2-2.cpp è ò.ä)
#include <iostream>
#include <ctime>
void createArray(float A[], int N);
void rightShiftArray(float A[], float B[], int N, int k);//зачем передавать N если это - глобальная константа????
void leftShiftArray(float A[], float B[], int N, int k);//зачем передавать N если это - глобальная константа????
void printArray(float A[], int N); //зачем передавать N если это - глобальная константа????
using namespace std;
const int N = 13;
void createArray(float A[], int N)
{
for (int i = 0; i < N; ++i)
A[i] = (rand() % 101 - 50) / 10.0;// по условию от -N до N
}
void rightShiftArray(float A[], float B[], int N, int k)
{
for (int i = 0; i < N; i++)
B[(i + k%N) % N] = A[i];
}
void leftShiftArray(float A[], float B[], int N, int k)
{
for (int i = 0; i < N; i++)
B[((i + N)- k%N) % N] = A[i];
}
void printArray(float A[], int N)
{
for (int i = 0; i < N; i++)
cout << a[i] << " "; cout << '\n';
}
int main()
{
srand(time(NULL));
setlocale(LC_ALL, "Russian");
float A[N], B[N];
int k;
cout << "Ââåäèòå êîëè÷åñòâî ýëåìåíòîâ íà êîòîðîå íåîáõîäèìî ñäâèíóòü ìàññèâ"<<'\n';
cin >> k;
createArray(A, N);
cout << "Íà÷àëüíûé ìàññèâ"<<'\n';
printArray(A, N);
rightShiftArray(A, B, N, k);
cout << "Ìàññèâ ñäâèíóòûé íà k ýëåìåíòîâ âïðàâî"<<'\n';
printArray(B, N);
leftShiftArray(B, A, N, k);
cout << "Ìàññèâ ñäâèíóòûé íà k ýëåìåíòîâ âëåâî"<<'\n';
printArray(A, N);
system("pause");
}
| true |
4b5c9f1f8f0eacee7b74681c53f4f453d2588e58 | C++ | namirinz/O-Com-TU-2563 | /Lab1_pointer/1.cpp | UTF-8 | 991 | 3.265625 | 3 | [] | no_license | #include <iostream>
#include <stdio.h>
using namespace std;
int main(){
double x = 5.1231;
int y = 2;
char s = 'a';
double *px;
px = &x;
char *ps;
ps = &s;
int *py;
py = &y;
cout << "Value of int is " << y << endl;
cout << "Address of int is "; printf("%p\n",py);
cout << "Size of of int is " << sizeof(y) << endl;
cout << "Size of of pinter to int is "; printf("%lu\n",sizeof(py));
cout << endl;
cout << "Value of double is " << *px << endl;
cout << "Address of double is "; printf("%p\n",px);
cout << "Size of of double is " << sizeof(x) << endl;
cout << "Size of of pinter to double is " << sizeof(*px) << endl;
cout << endl;
cout << "Value of char is " << *ps << endl;
cout << "Address of char is "; printf("%p\n",ps);
cout << "Size of of char is " << sizeof(s) << endl;
cout << "Size of of pinter to char is " << sizeof(*ps) << endl;
} | true |
341ddf24b92698fe4a9c564b19a8f0c26c4001e6 | C++ | sureshmangs/Code | /competitive programming/codeforces/1527B1 - Palindrome Game (easy version).cpp | UTF-8 | 2,740 | 4.0625 | 4 | [
"MIT"
] | permissive | /*
The only difference between the easy and hard versions is that the given string s in the easy version is initially a palindrome, this condition is not always true for the hard version.
A palindrome is a string that reads the same left to right and right to left. For example, "101101" is a palindrome, while "0101" is not.
Alice and Bob are playing a game on a string s (which is initially a palindrome in this version) of length n consisting of the characters '0' and '1'. Both players take alternate turns with Alice going first.
In each turn, the player can perform one of the following operations:
Choose any i (1=i=n), where s[i]= '0' and change s[i] to '1'. Pay 1 dollar.
Reverse the whole string, pay 0 dollars. This operation is only allowed if the string is currently not a palindrome, and the last operation was not reverse. That is, if Alice reverses the string, then Bob can't reverse in the next move, and vice versa.
Reversing a string means reordering its letters from the last to the first. For example, "01001" becomes "10010" after reversing.
The game ends when every character of string becomes '1'. The player who spends minimum dollars till this point wins the game and it is a draw if both spend equal dollars. If both players play optimally, output whether Alice wins, Bob wins, or if it is a draw.
Input
The first line contains a single integer t (1=t=103). Then t test cases follow.
The first line of each test case contains a single integer n (1=n=103).
The second line of each test case contains the string s of length n, consisting of the characters '0' and '1'. It is guaranteed that the string s is a palindrome and contains at least one '0'.
Note that there is no limit on the sum of n over test cases.
Output
For each test case print a single word in a new line:
"ALICE", if Alice will win the game,
"BOB", if Bob will win the game,
"DRAW", if the game ends in a draw.
Example
inputCopy
2
4
1001
1
0
outputCopy
BOB
BOB
Note
In the first test case of the example,
in the 1-st move Alice has to perform the 1-st operation, since the string is currently a palindrome.
in the 2-nd move Bob reverses the string.
in the 3-rd move Alice again has to perform the 1-st operation. All characters of the string are '1', game over.
Alice spends 2 dollars while Bob spends 0 dollars. Hence, Bob always win
*/
#include<bits/stdc++.h>
using namespace std;
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
string s;
cin >> s;
int zero = 0;
for (auto &x: s){
if (x == '0') zero++;
}
if (zero == 1) cout << "BOB\n";
else if (zero % 2) cout << "ALICE\n";
else cout << "BOB\n";
}
return 0;
}
| true |
ea8f50cfcb259f425f68f481bdd78f419e9fb0a7 | C++ | 1160208849wfl/cpp-primer5e | /snippets/c++/template/chapter3/basics/varprint2.hpp | UTF-8 | 450 | 3.71875 | 4 | [] | no_license | #include <iostream>
// If two function templates only differ by a tailing parameter pack,
// the function template without the trailing parameter pack is preferred.
template <typename T>
void print(T arg)
{
std::cout << arg << '\n';
}
template <typename T, typename... Types>
void print(T firstArg, Types... args)
{
std::cout << sizeof...(Types) << '\n';
std::cout << sizeof...(args) << '\n';
print(firstArg);
print(args...);
} | true |
e973ffa3e675f6aeb7f2742261300db2bc2a5ec7 | C++ | P14141609/CW1_GameEngine | /Projects/GameEngine/include/scene.h | UTF-8 | 2,065 | 3 | 3 | [] | no_license | #ifndef SCENE_H
#define SCENE_H
// Imports
#include "player.h"
#include "camera.h"
#include "gameobject.h"
#include "collectable.h"
#include "staticobject.h"
#include "light.h"
#include "xmlloader.h"
#include <memory>
#include <vector>
/////////////////////////////////////////////////
///
/// \brief Class for world handling
///
/////////////////////////////////////////////////
class Scene
{
private:
std::shared_ptr<Player> m_pPlayer; //!< Player member for character handling
std::vector<std::shared_ptr<Camera>> m_pCameras; //!< Vector of Camera pointers for Cameras within the Scene
std::vector<std::shared_ptr<GameObject>> m_pGameObjects; //!< Vector of GameObject pointers for GameObjects within the Scene
std::vector<std::shared_ptr<Light>> m_pLights; //!< Vector of Light pointers for Lights within the Scene
std::shared_ptr<Camera> m_pActiveCamera; //!< Pointer to the Camera currently being used
protected:
public:
/////////////////////////////////////////////////
///
/// \brief Constructor
///
/// \param kfAspectRatio The display aspect ratio
///
/////////////////////////////////////////////////
Scene(const float kfAspectRatio);
/////////////////////////////////////////////////
///
/// \brief Processes input
///
/// \param kfElapsedTime The time since last update
///
/////////////////////////////////////////////////
void processInput(const float kfElapsedTime);
/////////////////////////////////////////////////
///
/// \brief Called to update the Scene
///
/// \param kfElapsedTime The time since last update
///
/////////////////////////////////////////////////
void update(const float kfElapsedTime);
/////////////////////////////////////////////////
///
/// \brief Called to render the Scene
///
/////////////////////////////////////////////////
void render();
std::vector<std::shared_ptr<Camera>> getCameras() { return m_pCameras; } //!< Returns a vector of Camera ptrs
std::shared_ptr<Camera> getActiveCamera() { return m_pActiveCamera; } //!< Returns the active Camera ptr
};
#endif | true |
d84cfc5bad342ff541234e8f687c6ede2db034cf | C++ | Timeligers/MoTa | /monsterlist_item.cpp | UTF-8 | 3,913 | 2.578125 | 3 | [] | no_license | #include "monsterlist_item.h"
#include <QWidget>
MonsterList_item::MonsterList_item(QWidget *parent): QWidget(parent)
{
}
//初始化item
void MonsterList_item::initItem()
{
head = new QLabel(this);
label_hp = new QLabel(this);
label_atk = new QLabel(this);
label_pdef = new QLabel(this);
label_exp = new QLabel(this);
label_gold = new QLabel(this);
label_damage = new QLabel(this);
label_hp_val = new QLabel(this);
label_atk_val = new QLabel(this);
label_pdef_val = new QLabel(this);
label_exp_val = new QLabel(this);
label_gold_val = new QLabel(this);
label_damage_val = new QLabel(this);
//设置颜色,对齐方式
label_hp->setStyleSheet("color: rgb(160, 160, 160);font: 15pt;");
label_hp->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
label_hp->setFixedSize(100, 30);
label_hp->setText("生命");
label_atk->setStyleSheet("color: rgb(160, 160, 160);font: 15pt;");
label_atk->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
label_atk->setFixedSize(100, 30);
label_atk->setText("攻击");
label_pdef->setStyleSheet("color: rgb(160, 160, 160);font: 15pt;");
label_pdef->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
label_pdef->setFixedSize(100, 30);
label_pdef->setText("防御");
label_exp->setStyleSheet("color: rgb(160, 160, 160);font: 15pt;");
label_exp->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
label_exp->setFixedSize(100, 30);
label_exp->setText("经验");
label_gold->setStyleSheet("color: rgb(160, 160, 160);font: 15pt;");
label_gold->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
label_gold->setFixedSize(100, 30);
label_gold->setText("金币");
label_damage->setStyleSheet("color: rgb(160, 160, 160);font: 15pt;");
label_damage->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
label_damage->setFixedSize(200, 30);
label_damage->setText("预计最高伤害");
label_hp_val->setStyleSheet("color:white;font: 15pt;");
label_hp_val->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
label_hp_val->setFixedSize(150, 30);
label_atk_val->setStyleSheet("color:white;font: 15pt;");
label_atk_val->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
label_atk_val->setFixedSize(150, 30);
label_pdef_val->setStyleSheet("color:white;font: 15pt;");
label_pdef_val->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
label_pdef_val->setFixedSize(150, 30);
label_exp_val->setStyleSheet("color:white;font: 15pt;");
label_exp_val->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
label_exp_val->setFixedSize(150, 30);
label_gold_val->setStyleSheet("color:white;font: 15pt;");
label_gold_val->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
label_gold_val->setFixedSize(150, 30);
label_damage_val->setStyleSheet("color:white;font: 15pt;");
label_damage_val->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
label_damage_val->setFixedSize(300, 30);
//设置头像大小
head->setFixedSize(60,60);
//布局
head->move(40, 30);
label_hp->move(120, 30);
label_atk->move(270, 30);
label_pdef->move(410, 30);
label_hp_val->move(150, 30);
label_atk_val->move(300, 30);
label_pdef_val->move(440, 30);
label_exp->move(120, 70);
label_gold->move(270, 70);
label_damage->move(420, 70);
label_exp_val->move(150, 70);
label_gold_val->move(300, 70);
label_damage_val->move(490, 70);
}
| true |
9a70f2a6066168275abb5ba8cfb480026c0be72c | C++ | MrFrangipane/raytracer | /C++/node/sphere.cpp | UTF-8 | 1,417 | 3.03125 | 3 | [] | no_license | #include "sphere.h"
namespace frangiray {
// Pseudo Static Member
bool Sphere::traceable() const
{
return Sphere::_traceable;
}
// Set Radius
void Sphere::set_radius(f_real radius_)
{
radius = radius_;
_radius2 = radius_ * radius_;
}
// Intersection Distance
f_real Sphere::intersection_distance(const Ray &ray) const
{
// Init
f_real tca, thc, d2, t0, t1;
// Compute
Vector L = position() - ray.origin;
tca = L.dot_product(ray.direction);
// Exit
if (tca < 0) return -1;
d2 = L.dot_product(L) - (tca * tca);
if (d2 > _radius2) return -1;
thc = sqrt(_radius2 - d2);
t0 = tca - thc;
t1 = tca + thc;
if (t0 > t1) std::swap(t0, t1);
if (t0 < 0) {
t0 = t1;
// Exit
if (t0 < 0) return -1;
}
// Return
return t0;
}
// Surface Attributes
SurfaceAttributes Sphere::surface_attributes_at(const Vector &position_) const
{
SurfaceAttributes attributes;
attributes.diffuse_color = diffuse_color;
attributes.emission_color = emission_color;
attributes.reflection_amount = reflection_amount;
attributes.reflection_roughness = reflection_roughness;
attributes.normal = (position_ - position()).normalize();
return attributes;
}
Vector Sphere::random_position() const
{
Vector random_pos = random_direction();
random_pos *= radius;
return position() + random_pos;
}
}
| true |
d4f1e1704336ceab703d513841d0ee508c390ab7 | C++ | zzJinux/cmpt-prog | /fbcup2018/qr1.cc | UTF-8 | 1,199 | 2.59375 | 3 | [] | no_license | /* Tourist */
#include <iostream>
#include <queue>
using namespace std;
struct Attr {
int idx, vcnt;
bool operator<(Attr const rhs) const {
return (vcnt > rhs.vcnt) or (vcnt == rhs.vcnt and idx > rhs.idx);
}
} attrs[50];
using PQ = priority_queue<Attr>;
using LL = long long;
int N, K;
LL V;
char titles[50][21];
bool ansbool[50];
int gcd(int a, int b) {
int t;
while(b) {
t=b;
b=a%b;
a=t;
}
return a;
}
int main() {
int T, test_case;
cin >> T;
for(test_case=1; test_case<=T; ++test_case) {
cin >> N >> K >> V;
int g, period;
g = gcd(N, K);
period = N/g;
V = (V-1)%period+1;
PQ pq;
for(int i=0; i<N; ++i) {
cin >> titles[i];
pq.push({i, 0});
}
for(int i=0; i<V-1; ++i) {
for(int j=0; j<K; ++j) {
auto e = pq.top();pq.pop();
++e.vcnt;
pq.push(e);
}
}
for(int j=0; j<N; ++j) ansbool[j]=false;
for(int j=0; j<K; ++j) {
auto e = pq.top();pq.pop();
ansbool[e.idx]=true;
}
cout << "Case #" << test_case << ":";
for(int j=0; j<N; ++j) {
if(!ansbool[j]) continue;
cout << ' ' << titles[j];
}
cout << '\n';
}
return 0;
}
| true |
20e960195ae6d5cf27b209fc532585072c78e9f4 | C++ | jandujar/multipong | /multipong/src/Bola.cpp | UTF-8 | 8,004 | 2.65625 | 3 | [
"MIT"
] | permissive | #include "Bola.h"
#include <stdlib.h>
#include <math.h>
#include "Constants.h"
#include <iostream>
Bola::Bola()
{
//ctor
}
Bola::~Bola()
{
//dtor
closeMedia();
}
//Initialization
void Bola::Init(SDL_Renderer *renderer){
rect.h = BOLA_SIZE;
rect.w = BOLA_SIZE;
rect.y = WIN_HEIGHT/2;
rect.x = WIN_WIDTH/2;
//Iniciar con un angulo random, pero que nunca sea completamente horizontal o vertical
int type = rand() % 4;
switch (type)
{
case 0: //15-75
angle = rand() % 60 + 15;
break;
case 1: //105-165
angle = rand() % 60 + 105;
break;
case 2: //195-255
angle = rand() % 60 + 195;
break;
case 3://285-345
angle = rand() % 60 + 285;
break;
}
SDL_Surface *surf = IMG_Load("assets/pelota.png");
imagen = SDL_CreateTextureFromSurface(renderer, surf);
dx = dy = 0.0f;
speed = 0.4f;
rebotandoY = rebotandoX = false;
speedX = (float)cos(angle*M_PI / 180.0f) * speed;
speedY = (float)sin(angle*M_PI / 180.0f) * speed;
MAX_speed = speed *2;
InitMedia();
}
void Bola::InitMedia(){
//The music that will be played
gMusic = NULL;
//The sound effects that will be used
gGol = NULL;
gColision = NULL;
gNewPj = NULL;
//Initialize SDL_mixer
if( SDL_Init( SDL_INIT_AUDIO ) < 0 ){
std::cout << "SDL could not initialize! SDL Error: " << SDL_GetError() << std::endl;
}
if( Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 2, 2048 ) < 0 ){
std::cout << "SDL_mixer could not initialize! SDL_mixer Error: " << Mix_GetError() << std::endl;
}
if(loadMedia()){
//Play the music
if(Mix_PlayMusic( gMusic, -1 ))
std::cout << "Musica carregada" << std::endl;
}
}
//Update para la IA
void Bola::Update(std::vector<Pala*>palas, Marcador *marcador1, Marcador *marcador2, float deltaTime){
//Si no esta ya rebotando (efecto bullet), rebota contra la pared
if (!rebotandoY){
if (rect.y + rect.h >= WIN_HEIGHT || rect.y <= 0){
//nueva direccion
angle = 360 -angle;
speedX = (float)cos(angle*M_PI / 180.0f) * speed;
speedY = (float)sin(angle*M_PI / 180.0f) * speed;
rebotandoY = true;
//
}
}
//Si no esta ya rebotando (efecto bullet), rebota contra la tabla
for(unsigned int i=0; i < palas.size(); i++){
Pala* pala = palas[i];
//Choca con la tabla
if ((rect.x + rect.w >=pala->getRect()->x && rect.x <= (pala->getRect()->x + pala->getRect()->w)) && (rect.y >= pala->getRect()->y && rect.y + rect.h <= pala->getRect()->y + pala->getRect()->h)){
if(rebotandoX)
break;
//Numero del player (impar izquierda, par derecha)
if((i+1)%2 != 0){
//Calculo el punto de interseccion con la tabla, y obtengo el angulo y la nueva velocidad
//Cuanto mas al centro de la bola, mas recta y mas lenta sale
int intersection = (pala->getRect()->y + (pala->getRect()->h / 2)) - (rect.y + (rect.h / 2));
intersection /= (pala->getRect()->h / 2); //[-1,1]
int newAngle = abs(intersection * 65) + 10; //nunca horizontal!
speed += (abs(intersection) * (MAX_speed - speed)) + speed * 0.05f;
if (angle <= 180){
angle = newAngle;
}
else{
angle = 360 - newAngle;
}
}
else{
int intersection = (pala->getRect()->y + (pala->getRect()->h / 2)) - (rect.y + (rect.h / 2));
intersection /= (pala->getRect()->h / 2);
int newAngle = abs(intersection * 65) + 10; //nunca horizontal!
//speed = (abs(intersection) + 0.2) * MAX_speed;
speed += (abs(intersection) * (MAX_speed - speed)) + speed * 0.05f;
if (angle <= 90){
angle = 180 - newAngle;
}
else{
angle = 180 + newAngle;
}
}
Rebote();
}else rebotandoX = false;
}
//Actualiza posiciones
dx += deltaTime * speedX *1000;
dy += deltaTime * speedY * 1000;
//Si se ha acumulado un pixel de movimiento, se mueve
if (fabs(dx) >= 1){
int aux = 0;
if (dx > 0)
aux = (int)(dx + 0.5f);
else
aux = (int)(dx - 0.5f);
rect.x += aux;
dx = 0;
//Ya no choca contra nada?
}
//Si se ha acumulado un pixel de movimiento, se mueve
if (fabs(dy) >= 1){
int aux = 0;
if (dy > 0)
aux = (int)(dy + 0.5f);
else
aux = (int)(dy - 0.5f);
rect.y += aux;
dy = 0;
//Ya no choca contra nada?
if (rebotandoY && rect.y + rect.h < WIN_WIDTH && rect.y > 0)
rebotandoY = false;
//Comprueba si sigue chocando contra un bloque
}
if(rect.x < 0 ){
std::cout << "Punto Equipo 2" << std::endl;
if (marcador2->getScore() < MAX_SCORE)
marcador2->incrementScore(1);
Gol();
}else if(rect.x > WIN_WIDTH){
std::cout << "Punto Equipo 1" << std::endl;
if (marcador1->getScore() < MAX_SCORE)
marcador1->incrementScore(1);
Gol();
}
}
void Bola::Gol(){
//Se inicia la bola en el centro y se cambia el angulo de salida
rect.y = WIN_HEIGHT/2;
rect.x = WIN_WIDTH/2;
dx = dy = 0.0f;
speed = 0.4f;
//std::cout << "Angle = " << angle << std::endl;
//std::cout << "SpeedX = " << speedX << std::endl;
//nueva direccion
angle = (angle +180) % 360;
speedX = (float)cos(angle*M_PI / 180.0f) * speed ;
speedY = (float)sin(angle*M_PI / 180.0f) * speed ;
rebotandoY = rebotandoX = false;
//Play sound effect.
Mix_PlayChannel( -1, gGol, 0 );
}
//render
void Bola::Render(SDL_Renderer* renderer){
///SDL_FillRect(surf,&rect,COLOR_BOLA);
SDL_Rect srcRect;
srcRect.x = 0;
srcRect.y = 0;
srcRect.w = rect.w;
srcRect.h = rect.h;
SDL_RenderCopy(renderer, imagen, &srcRect, &rect);
}
SDL_Rect* Bola::getRect(){
return ▭
}
void Bola::Rebote(){
//Incremento de la velocidad cada vez que rebota!
MAX_speed += MAX_speed *0.05f;
speedX = (float)cos(angle*M_PI / 180.0f) * speed;
speedY = (float)sin(angle*M_PI / 180.0f) * speed;
rebotandoX = true;
//Play sound effect.
Mix_PlayChannel( -1, gColision, 0 );
}
bool Bola::loadMedia(){
//Loading success flag
bool success = true;
//Load music
gMusic = Mix_LoadMUS( "assets/sounds/musicPong.wav" );
if( gMusic == NULL ){
std::cout << "Failed to load beat music! SDL_mixer Error: " << Mix_GetError() << std::endl;
success = false;
}
//Load sound effects
gGol = Mix_LoadWAV( "assets/sounds/goalBall.wav" );
if( gGol == NULL ){
std::cout << "Failed to load beat music! SDL_mixer Error: " << Mix_GetError() << std::endl;
success = false;
}
gColision = Mix_LoadWAV( "assets/sounds/colisionBall.wav" );
if( gColision == NULL ){
std::cout << "Failed to load beat music! SDL_mixer Error: " << Mix_GetError() << std::endl;
success = false;
}
gNewPj = Mix_LoadWAV( "assets/sounds/newPlayer.wav" );
if( gNewPj == NULL ){
std::cout << "Failed to load beat music! SDL_mixer Error: " << Mix_GetError() << std::endl;
success = false;
}
return success;
}
void Bola::closeMedia(){
//Free the sound effects
Mix_FreeChunk( gGol );
Mix_FreeChunk( gColision );
Mix_FreeChunk( gNewPj );
gGol = NULL;
gColision = NULL;
gNewPj = NULL;
//Free the music
Mix_FreeMusic( gMusic );
gMusic = NULL;
//Quit SDL subsystems
Mix_Quit();
SDL_Quit();
}
| true |
e6816a840ed075cd86453592c72a9bac67c4ffce | C++ | imsaiguy/TTGO-Projects | /TTGO_ADC_DAC.ino | UTF-8 | 1,572 | 2.6875 | 3 | [] | no_license | /*
12 bit ADC
full range 4095
8 bit DAC1 DAC2
full range 255
#########################################################################
###### DON'T FORGET TO UPDATE THE User_Setup.h FILE IN THE LIBRARY ######
#########################################################################
*/
#include <TFT_eSPI.h> // Graphics and font library for ST7735 driver chip
#include <SPI.h>
TFT_eSPI tft = TFT_eSPI(); // Invoke library, pins defined in User_Setup.h
#define button0 0
#define button1 35
#define ADC 2 // input pin for ADC
#define bat_volts 34 // ready battery volts/2
#define DAC1 25 // output DAC
#define DAC2 26 // output DAC
#define backlit 4 // LCD Backlight, set low to turn off
int volts = 64; // DAC bit setting (8 bits)
void setup(void) {
pinMode(button0, INPUT);
pinMode(button1, INPUT);
tft.init();
tft.setRotation(1); // rotate display every 90 degrees 1...3
tft.setTextColor(TFT_GREEN,TFT_BLACK);
}
void loop() {
tft.fillScreen(TFT_BLACK);
tft.setCursor(0, 0, 4); // size 4 font
dacWrite(DAC1, 128); // fixed DAC
dacWrite(DAC2, volts); // varying DAC
tft.print(3.68*float(analogRead(ADC))/4095);
tft.println(" Volts Pin 2");
tft.println();
tft.println("DAC1 set at 128");
tft.println("DAC2 up/down");
tft.print(2*3.68*float(analogRead(bat_volts))/4095);
tft.println(" Volts Battery");
if(digitalRead(button1) != 1) if (volts<255) volts++;
if(digitalRead(button0) != 1) if (volts>0) volts--;
delay(500);
}
| true |
0110c6453fd4466db75132592fe46795fa699263 | C++ | ishdutt/CP | /Gasoline.cpp | UTF-8 | 1,851 | 3.390625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
struct Item
{
ll value, weight;
// Constructor
Item(ll value, ll weight)
: value(value)
, weight(weight)
{
}
};
// Comparison function to sort Item according to val/weight
// ratio
bool cmp(struct Item a, struct Item b)
{
double r1 = ( double)a.value / ( double)a.weight;
double r2 = ( double)b.value / ( double)b.weight;
return r1 < r2;
}
double fractionalKnapsack(ll W, vector<Item> arr, ll n)
{
sort(arr.begin(), arr.end(), cmp);
ll curWeight = 0;
double finalvalue = 0.0;
for (ll i = 0; i < n; i++)
{
if (curWeight + arr[i].weight <= W)
{
curWeight += arr[i].weight;
finalvalue += ( double)arr[i].value;
}
else
{
ll remain = W - curWeight;
finalvalue += ( double)arr[i].value * (( double)remain / ( double)arr[i].weight);
break;
}
}
// double temp=finalvalue;
// cout<<"TEST="<<temp<<endl;
return finalvalue;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
ll t;
cin>>t;
while (t--)
{
ll n;
cin>>n;
vector<ll> fuel(n,0);
//ARRAY
for(ll i=0;i<n;i++)
cin>>fuel[i];
vector<ll> cost(n,0);
//COST ARRAY
for(ll i=0;i<n;i++)
cin>>cost[i];
for(ll i=0;i<n;i++)
cost[i]*=fuel[i];
vector<Item>arr;
for(ll i=0;i<n;i++)
arr.push_back(Item(cost[i],fuel[i]));
double res=fractionalKnapsack(n, arr, n);
printf("%lli\n",(ll)res);
// ll ans= (ll)fractionalKnapsack(n, arr, n);
// cout<<ans<<endl;
}
}
| true |
b6aa215b73df7bbd91d476afe9b1e78f7b089899 | C++ | dakeryas/CosmogenicAnalyser | /include/RootObjectExtractor.hpp | UTF-8 | 1,098 | 2.796875 | 3 | [] | no_license | #ifndef COSMOGENIC_ANALYSER_ROOT_OBJECT_EXTRACTOR_H
#define COSMOGENIC_ANALYSER_ROOT_OBJECT_EXTRACTOR_H
#include "TFile.h"
#include <stdexcept>
namespace CosmogenicAnalyser{
template <class T>
class RootObjectExtractor{
public:
static T extract(const std::string& keyName, TFile& file);
};
template <class T>
T RootObjectExtractor<T>::extract(const std::string& keyName, TFile& file){
auto object = dynamic_cast<T*>(file.Get(keyName.c_str()));
if(object != nullptr) return *object;
else throw std::runtime_error("Could not extact '"+keyName+"' from "+file.GetName());
}
template <class T>
class RootObjectExtractor<T*>{
public:
static T* extract(const std::string& keyName, TFile& file);
};
template <class T>
T* RootObjectExtractor<T*>::extract(const std::string& keyName, TFile& file){
auto object = dynamic_cast<T*>(file.Get(keyName.c_str()));
if(object != nullptr) return object;
else throw std::runtime_error("Could not extact '"+keyName+"' from "+file.GetName());
}
}
#endif | true |
108fa2660bf6cdd7964745436922bf70b9a62cc3 | C++ | ivanovdimitur00/programs | /Programs/zadachi praktikum 6/symmetrical_array.cpp | UTF-8 | 462 | 3.59375 | 4 | [] | no_license | #include <iostream>
int main()
{
int array[100];
int numbers_array;
std::cin>>numbers_array;
for (int i = 0; i < numbers_array ; i++) {
std::cin>>array[i];
}
int counter = 0;
for (int i = 0; i < numbers_array/2 ; i++) {
if (array[i] == array[numbers_array-1-i]) {
counter++;
}
}
if (counter == numbers_array/2) {
std::cout<<"symmetrical";
} else {
std::cout<<"not symmetrical";
}
return 0;
}
| true |
fd1ac0a124c7f50f4301e525d1df7155fd22deab | C++ | sundsx/RevBayes | /src/revlanguage/parser/SyntaxUnaryExpr.h | UTF-8 | 3,542 | 3.15625 | 3 | [] | no_license | /**
* @file
* This file contains the declaration of SyntaxUnaryExpr, which is
* used to hold unary expressions in the syntax tree.
*
* @brief Declaration of SyntaxUnaryExpr
*
* (c) Copyright 2009- under GPL version 3
* @date Last modified: $Date$
* @author The RevBayes Development Core Team
* @license GPL version 3
*
* $Id$
*/
#ifndef SyntaxUnaryExpr_H
#define SyntaxUnaryExpr_H
#include "SyntaxElement.h"
#include <iostream>
#include <vector>
/**
* This is the class used to hold binary expressions in the syntax tree.
*
* We store the operands and a flag signalling the type of operation to
* be performed when getValue is called or to be represented when
* getDAGNodeExpr is called.
*
*/
namespace RevLanguage {
/**
* @brief Unary expression syntax element
*
* This syntax element is used to hold binary expressions. Member
* variables are the operand and the operator type.
*
* Unary expressions are expressions of the type
*
* -a
*
* and they effectively correspond to calls of internal univariate
* functions.
*
* Just like function calls, unary expressions evaluate in
* differently ways in dynamic and static expression contexts. For
* more explanation of this, see the function call syntax element.
*
* The operand argument of unary expressions is understood to
* be a dynamic argument. See the function call syntax element
* for more details on different argument types.
*/
class SyntaxUnaryExpr : public SyntaxElement {
public:
// Unary operator types
enum operatorT { UMinus, UPlus, UNot, UAnd }; //!< Operator types
static std::string opCode[]; //!< Operator codes for printing
// Constructors and destructor
SyntaxUnaryExpr(SyntaxUnaryExpr::operatorT op, SyntaxElement* oper); //!< Standard constructor
SyntaxUnaryExpr(const SyntaxUnaryExpr& x); //!< Copy constructor
virtual ~SyntaxUnaryExpr(); //!< Destroy operands
// Assignment operator
SyntaxUnaryExpr& operator=(const SyntaxUnaryExpr& x); //!< Assignment operator
// Basic utility functions
SyntaxUnaryExpr* clone() const; //!< Clone object
void printValue(std::ostream& o) const; //!< Print info about object
// Regular functions
RevPtr<Variable> evaluateContent(Environment& env); //!< Get semantic value (static version)
RevPtr<Variable> evaluateDynamicContent(Environment& env); //!< Get semantic value (dynamic version)
bool isConstExpression(void) const; //!< Is the expression constant?
protected:
SyntaxElement* operand; //!< The operand
enum operatorT operation; //!< The type of operation
};
}
#endif
| true |
63739bae7df005e7988770b81cf73bd7e1067afe | C++ | MFornander/kingjelly | /src/RainEffect.cpp | UTF-8 | 2,060 | 2.625 | 3 | [
"MIT"
] | permissive |
/*---------------------------------------------------------
* Includes
*--------------------------------------------------------*/
#include "KingJelly.h"
#include "RainEffect.h"
/*---------------------------------------------------------
* Macros
*--------------------------------------------------------*/
#define ABS(x) ((x<=0)?-x:x)
/*---------------------------------------------------------
* Utility Functions
*--------------------------------------------------------*/
uint32_t mod(int32_t a, int32_t b)
{
return (a%b+b)%b;
}
const vector<uint32_t> RainEffect::mMods_vect = {97,100,103,138};
/*---------------------------------------------------------
* Methods
*--------------------------------------------------------*/
RainEffect::RainEffect() :
mOffset(0),
mHue(0.5f),
mModIdx(0),
mLen(10)
{}
void RainEffect::beginFrame(const FrameInfo& frame)
{
if (InputClicked(JoyUp))
mModIdx++;
if (InputClicked(JoyDown))
mModIdx--;
mModIdx %= mMods_vect.size();
mHue = Input(Pot1);
mLen = (int) (Input(Pot2)*50) + 1;
mOffset += (frame.timeDelta*32);
}
void RainEffect::shader(Vec3& rgb, const PixelInfo& pixel) const
{
// position within a given strand
uint32_t pos = pixel.index % mMods_vect.at(mModIdx);
uint32_t off = ((int)mOffset) % JellyPixel::kLedCount;
// distance from the center pixel of the wave
int distance = ABS(min(mod(pos - off, JellyPixel::kLedCount),
mod(off - pos, JellyPixel::kLedCount)));
// get dimmer based on distance from center
float wave = max(0.0, (mLen-distance)/(double)mLen);
/*
if(pixel.index > 80 && pixel.index < 100)
if(wave != 0.0)
printf("%d %d %d (%d = %d, %d = %d) %d %f\n",
mOffset, pos, off, (pos - off), mod(pos - off,100),
off - pos, mod(off - pos, 100), distance,wave);
*/
if(wave == 0)
{
hsv2rgb(rgb, fmodf(mHue+0.1,1.0), 1.0f, Input(Pot3));
}
else
{
hsv2rgb(rgb, mHue, 1.0f, wave);
}
//printf("%d : (%f %f %f) : %f %f %f\n", pixel.index, rgb[0], rgb[1], rgb[2],mHue,1.0,wave);
}
| true |
505eb3a35b1c271f6e3190e8dee2661edbac7bfe | C++ | meedan/alegre | /threatexchange/tmk/cpp/bin/tmk-compare-two-tmks.cpp | UTF-8 | 3,387 | 2.671875 | 3 | [
"BSD-2-Clause",
"MIT"
] | permissive | // ================================================================
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
// ================================================================
// ================================================================
// Given a pair of `.tmk` files (see section below on file formats), uses
// tmk compare tmks to see if the .tmk files are the same to a certain
// relative error.
//
// This sees if two `.tmk` files are the same, within roundoff error anyway.
// This is **not** intended for video-matching between potential variations of
// a video -- see `tmk-query` for that. Rather, this program is intended for
// comparing hashes of the **exact same video**, for regression or portability
// concerns.
// ================================================================
#include <tmk/cpp/algo/tmkfv.h>
#include <tmk/cpp/lib/vec.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace facebook::tmk;
using namespace facebook::tmk::algo;
// ================================================================
void usage(const char* argv0, int exit_rc) {
FILE* fp = (exit_rc == 0) ? stdout : stderr;
fprintf(
fp, "Usage: %s [options] {tmk file name 1} {tmk file name 2}\n", argv0);
fprintf(fp, "Options:\n");
fprintf(fp, "-s|--strict Use cosine and sine equality.\n");
fprintf(fp, "-v|--verbose Print intermediate info for debugging.\n");
exit(exit_rc);
}
// ================================================================
int main(int argc, char** argv) {
bool strict = false;
bool verbose = false;
int argi = 1;
while ((argi < argc) && argv[argi][0] == '-') {
char* flag = argv[argi++];
if (!strcmp(flag, "-h") || !strcmp(flag, "--help")) {
usage(argv[0], 0);
} else if (!strcmp(flag, "-s") || !strcmp(flag, "--strict")){
strict = true;
} else if (!strcmp(flag, "-v") || !strcmp(flag, "--verbose")){
verbose = true;
} else {
usage(argv[0], 1);
}
}
if ((argc - argi) != 2) {
usage(argv[0], 1);
}
char* tmkFileNameA = argv[argi];
char* tmkFileNameB = argv[argi + 1];
std::shared_ptr<TMKFeatureVectors> pfva =
TMKFeatureVectors::readFromInputFile(tmkFileNameA, argv[0]);
std::shared_ptr<TMKFeatureVectors> pfvb =
TMKFeatureVectors::readFromInputFile(tmkFileNameB, argv[0]);
if (pfva == nullptr || pfvb == nullptr) { // error message already printed out
exit(1);
}
float tol = 0.08;
bool ok;
float minScore = 1.0 - tol; // Perfect matches will have level 1 and 2 scores of 1.0
if (strict){
ok = TMKFeatureVectors::compare(*pfva, *pfvb, tol);
if(verbose){
fprintf(stderr, "Using sine and cosine similarity.\n");
}
} else {
float score1 = TMKFeatureVectors::computeLevel1Score(*pfva, *pfvb) > minScore;
float score2 = TMKFeatureVectors::computeLevel2Score(*pfva, *pfvb) > minScore;
ok = (score1 > minScore) && (score2 > minScore);
if(verbose){
fprintf(stderr, "Level 1 Score: %f Level 2 Score: %f Tolerance: %f\n", score1, score2, tol);
}
}
if (!ok) {
fprintf(
stderr,
"TMK files do not match:\n%s\n%s\n",
tmkFileNameA,
tmkFileNameB);
exit(1);
} else {
fprintf(
stderr,
"TMK files match:\n%s\n%s\n",
tmkFileNameA,
tmkFileNameB);
exit(0);
}
}
| true |
dffcc1806a2c8ea684d6cbaa9d679afc2131dbb2 | C++ | RobinMeyler/SpookyPirateShip | /SpookyPirateShip/YearProject/src/MovingDown.cpp | UTF-8 | 3,020 | 2.8125 | 3 | [] | no_license | #include "MovingDown.h"
MovingDown::MovingDown(int t_animationType)
{
// switch statement to see what texture to load
m_animationType = t_animationType;
switch (t_animationType)
{
case 0:
{
// Player Case
/*texture.loadFromFile("Assets\\playerSpriteSheet.png");
animatedSprite = new AnimatedSprite(texture);
sf::IntRect rectOne(0, 0, 64, 77.5);
sf::IntRect rectTwo(64, 0, 64, 77.5);
sf::IntRect rectThree(64 * 2, 0, 64, 77.5);
animatedSprite->addFrame(rectOne);
animatedSprite->addFrame(rectTwo);
animatedSprite->addFrame(rectThree);*/
texture.loadFromFile("Assets\\Lorenzo.png");
animatedSprite = new AnimatedSprite(texture);
sf::IntRect rectOne(128, 0, 64, 64);
sf::IntRect rectTwo(192, 0, 64, 64);
sf::IntRect rectThree(0, 64, 64, 64);
sf::IntRect rectFour(192, 0, 64, 64);
animatedSprite->addFrame(rectOne);
animatedSprite->addFrame(rectTwo);
animatedSprite->addFrame(rectThree);
animatedSprite->addFrame(rectFour);
break;
}
case 1:
{
//Enemy Case
/*texture.loadFromFile("Assets\\zombie_n_skeleton2.png");
animatedSprite = new AnimatedSprite(texture);
sf::IntRect rectOne(32 * 3, 0, 32, 64);
sf::IntRect rectTwo(32 * 4, 0, 32, 64);
sf::IntRect rectThree(32 * 5, 0, 32, 64);
sf::IntRect rectFour(32 * 6, 0, 32, 64);
sf::IntRect rectFive(32 * 7, 0, 32, 64);
sf::IntRect rectSix(32 * 8, 0, 32, 64);
animatedSprite->addFrame(rectOne);
animatedSprite->addFrame(rectTwo);
animatedSprite->addFrame(rectThree);
animatedSprite->addFrame(rectFour);
animatedSprite->addFrame(rectFive);
animatedSprite->addFrame(rectSix);*/
texture.loadFromFile("Assets\\SpikeManSet.png");
animatedSprite = new AnimatedSprite(texture);
sf::IntRect rectOne(0, 0, 64, 64);
sf::IntRect rectTwo(64, 0, 64, 64);
sf::IntRect rectThree(128, 0, 64, 64);
sf::IntRect rectFour(192, 0, 64, 64);
animatedSprite->addFrame(rectOne);
animatedSprite->addFrame(rectTwo);
animatedSprite->addFrame(rectThree);
animatedSprite->addFrame(rectFour);
break;
}
default:
break;
}
}
MovingDown::~MovingDown()
{
}
void MovingDown::update()
{
animatedSprite->update();
}
sf::Sprite& MovingDown::getSprite()
{
int frame = animatedSprite->getCurrentFrame();
animatedSprite->setTextureRect(animatedSprite->getFrame(frame));
//animatedSprite->setOrigin(animatedSprite->getTextureRect().width / 2, animatedSprite->getTextureRect().height / 2);
return *animatedSprite;
}
void MovingDown::setSpritePos(MyVector3 pos)
{
getSprite().setPosition(pos);
}
void MovingDown::idle(StateChangeHandler* t_state)
{
t_state->setCurrent(new Idle(m_animationType));
delete this;
}
void MovingDown::movingUp(StateChangeHandler* t_state)
{
t_state->setCurrent(new MovingUp(m_animationType));
delete this;
}
void MovingDown::movingRight(StateChangeHandler* t_state)
{
t_state->setCurrent(new MovingRight(m_animationType));
delete this;
}
void MovingDown::movingLeft(StateChangeHandler* t_state)
{
t_state->setCurrent(new MovingLeft(m_animationType));
delete this;
}
| true |
bd83a669b251f7d7774e02d6da7db50d3b32d121 | C++ | gcoayla/Ciencia-de-la-Computaci-n-2 | /problem set 1/paso por valor y referencia.cpp | UTF-8 | 216 | 2.875 | 3 | [] | no_license | #include <iostream>
using namespace std;
void imprir(int *numero){
cout<<*numero<<endl;
}
void impri(int numero){
cout<<numero<<endl;
}
int main(){
int numero=5;
impri(numero);
imprir(&numero);
}
| true |
7e489be3b5cb6ea2ab3da85fa82522d39115a5c0 | C++ | NicolasHo/openvkl | /testing/volume/dcm/write_visitor.cpp | UTF-8 | 3,181 | 2.65625 | 3 | [
"Apache-2.0"
] | permissive | #include "./write_visitor.h"
#include "./data_element.h"
#include "./data_sequence.h"
#include "./data_set.h"
#include "./util.h"
#include "./writer.h"
namespace dcm {
WriteVisitor::WriteVisitor(Writer* writer) : writer_(writer) {
}
void WriteVisitor::VisitDataElement(const DataElement* data_element) {
tag_ = data_element->tag();
// Tag
WriteUint16(tag_.group());
WriteUint16(tag_.element());
// Special data element for SQ.
if (tag_ == tags::kSeqDelimatation || tag_ == tags::kSeqItemDelimatation ||
tag_ == tags::kSeqItemPrefix) {
// Value length of kSeqDelimatation and kSeqItemDelimatation should
// both be 0.
WriteUint32(data_element->length());
return;
}
VR vr = data_element->vr();
std::uint32_t length = data_element->length();
// VR
if (vr_type_ == VR::EXPLICIT || tag_.group() == 2) {
writer_->WriteByte(vr.byte1());
writer_->WriteByte(vr.byte2());
if (vr.Is16BitsFollowingReversed()) {
WriteUint16(0); // 2 bytes reversed
WriteUint32(length); // 4 bytes value length
} else {
// 2 bytes value length.
WriteUint16(static_cast<std::uint16_t>(length));
}
} else {
// Implicit VR
// 4 bytes value length.
WriteUint32(length);
}
if (vr != VR::SQ) {
if (length > 0) {
const Buffer& buffer = data_element->buffer();
writer_->WriteBytes(&buffer[0], length);
}
}
}
void WriteVisitor::VisitDataSequence(const DataSequence* data_sequence) {
// Visit the sequence as a normal data element.
VisitDataElement(data_sequence);
// Visit sequence items.
for (std::size_t i = 0; i < data_sequence->size(); ++i) {
const auto& item = data_sequence->At(i);
VisitDataElement(item.prefix);
VisitDataSet(item.data_set);
if (item.delimitation != nullptr) {
VisitDataElement(item.delimitation);
}
}
}
void WriteVisitor::VisitDataSet(const DataSet* data_set) {
if (level_ == 0) {
vr_type_ = data_set->vr_type();
byte_order_ = data_set->byte_order();
// Root data set.
// Just write the preamble and DICOM prefix.
// Preamble (128 bytes)
for (std::size_t i = 0; i < 32; ++i) {
WriteUint32(0);
}
// Prefix
writer_->WriteBytes("DICM", 4);
}
++level_;
// Visit the child data elements one by one.
for (std::size_t i = 0; i < data_set->size(); ++i) {
data_set->At(i)->Accept(*this);
}
--level_;
}
void WriteVisitor::WriteUint16(std::uint16_t value) {
if (value != 0) {
if (tag_.group() == 2) {
// Meta header always in Little Endian.
if (kByteOrderOS != ByteOrder::LE) {
util::Swap16(&value);
}
} else {
if (kByteOrderOS != byte_order_) {
util::Swap16(&value);
}
}
}
writer_->WriteUint16(value);
}
void WriteVisitor::WriteUint32(std::uint32_t value) {
if (value != 0) {
if (tag_.group() == 2) {
// Meta header always in Little Endian.
if (kByteOrderOS != ByteOrder::LE) {
util::Swap32(&value);
}
} else {
if (kByteOrderOS != byte_order_) {
util::Swap32(&value);
}
}
}
writer_->WriteUint32(value);
}
} // namespace dcm
| true |
0273bb6731e6fc4eedfc81ffeb1fa03c3645678f | C++ | Ventura-CS-V13-Spring2021/assignments-KarishaDel | /Quiz/Quiz1/Q5.cpp | UTF-8 | 550 | 3.53125 | 4 | [] | no_license | #include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int range1, range2 ;
bool done {false};
int i;
while (!done)
{
cout << "Type a range of integers to test for prime numbers: " << endl;
cin >> range1 >> range2;
for (int num = range1; num <= range2; num++)
{
for (i = 2; i < num; i++)
{
if (num % i == 0)
break;
}
if (i == num)
cout << num << " is a prime number."<< endl;
else
{
cout << num << " is not a prime number." << endl;
done = true;
}
}
}
} | true |
ca52b20f5b3fe61a7198ed3cabef7c7baf6b88f4 | C++ | kelby-amerson/binarytree | /Main.cpp | UTF-8 | 3,753 | 3.59375 | 4 | [] | no_license | #include <iostream>
#include <string>
#include <fstream>
#include <cstdio>
#include <sstream>
#include <cstdlib>
#include <string.h>
#include "BinaryTree.h"
using namespace std;
int main(int argc, char *argv[]){
BinaryTree list;
ItemType item4;
int input;
fstream fs;//opens up file
if(argv[1] != NULL){//opens up passed text file to input numbers in list
fs.open(argv[1],fstream::in);
if(fs.is_open()){
fs >> input;
while(!fs.eof()){
ItemType item4(input);
list.insert(item4);
fs >> input;
}
}else{
cout << "Failed to open the input file" << endl;
}
}
//interface
cout << "Commands: insert (i), delete (d), retrieve (r), length (l), in-order (n),pre-order (p), post-order (o), quit (q), getSameLevelNonSiblings (c), quit (q)" << endl;
cout << endl;
while(true){
string s1;
cout << "Enter a command: ";//gets command from user, and stores it in a string
getline(cin, s1);
if(s1 == "q"){//probably could've been in switch statement, but whatever
cout << "Quitting program.." << endl;//quits program
exit(EXIT_SUCCESS);
}else if(s1=="i"){//inserts object
//list.print();
cout << "Enter a number: ";
int val;
cin >> val;
cin.ignore(1,'\n');
ItemType item(val);
list.insert(item);
cout << endl;
cout << "In-Order: ";
list.inOrder();
cout << endl;
}else if(s1=="d"){//deletes object
//list.print();
cout << "Item to delete: ";
int val;
cin >> val;
cin.ignore(1,'\n');
ItemType item2(val);
list.deleteItem(item2);
cout << endl;
cout << "In-Order: ";
list.inOrder();
cout << endl;
}else if(s1=="r"){//retrieves object
//list.print();
cout << "Item to be retrieved: ";
int val;
cin >> val;
cin.ignore(1,'\n');
ItemType item2(val);
bool found = false;
list.retrieve(item2, found);
cout << endl;
}else if(s1=="c"){//samelevelnonsiblings
cout << "Item to find level for: ";
int val;
cin >> val;
cin.ignore(1,'\n');
ItemType item3(val);
list.getSameLevelNonSiblings(item3);
cout << endl;
}else if(s1=="o"){//post-order
cout << "Post-Order: ";
list.postOrder();
cout << endl;
}else if(s1=="p"){//pre-order
cout << "Pre-Order: ";
list.preOrder();
cout << endl;
}else if(s1=="n"){//in-order
cout << "In-Order: ";
list.inOrder();
cout << endl;
// cout << "Length: " << list.getLength() << endl;
}else if(s1=="l"){//returns length
cout << "Length: " << list.getLength() << endl;
}else{//if it's not a command, print it out and go through the loop again
cout << "Command not recognized. Try again" << endl;
}
cout << endl;
}
}
| true |
3088a9559d1400180b1465e2572552acb243c2a7 | C++ | M4t3B4rriga/Team5-DataStructure-3688 | /II-PARCIAL/Homewrok02Polaca_Calculator/Poland_Calculator/Poland_Calculator/Operation.h | UTF-8 | 2,844 | 2.875 | 3 | [] | no_license | /** UNIVERSIDAD DE LAS FUERZAS ARMADAS "ESPE"
* INGENIERIA SOFTWARE
*
*
*@author THEO ROSERO
*@author YULLIANA ROMAN
*@author JUNIOR JURADO
*@author ALEX PAGUAY
*@author SANTIAGO SAÑAY
*TEMA: Calculadora Polaca inversa
*FECHA DE CREACION : 3 DE JULIO DE 2021
*FECHA DE MODIFICACION: 6 DE JUNIO 2021
*/
#pragma once
#include "mystring.h"
#include "Stack.h"
class Operation
{
public:
/**
* @brief infix a prefix
*
* @return string
*/
string infix_to_prefix(string);
/**
* @brief infix a prefix
*
* @return Stack<string>
*/
Stack<string> infix_to_prefix1(Stack<string>);
/**
* @brief infix a postfix
*
* @return string
*/
string infix_to_postfix(string);
/**
* @brief infix a postfix
*
* @return Stack<string>
*/
Stack<string> infix_to_postfix1(Stack<string>);
/**
* @brief infix a funcional
*
* @return string
*/
string infix_to_funtional(string);
/**
* @brief prefix a infix
*
* @return string
*/
string prefix_to_infix(string);
/**
* @brief prefix a postfix
*
* @return string
*/
string prefix_to_postfix(string);
/**
* @brief prefix a funcional
*
* @return string
*/
string prefix_to_funtional(string);
/**
* @brief postfix a infix
*
* @return string
*/
string postfix_to_infix(string);
/**
* @brief postfix a prefix
*
* @return string
*/
string postfix_to_prefix(string);
/**
* @brief postfix a funcional
*
* @return string
*/
string postfix_to_funtional(string);
/**
* @brief comprobar operador
*
* @return true
* @return false
*/
bool is_operator(char);
/**
* @brief comprobar operador
*
* @return true
* @return false
*/
bool is_operator1(string);
/**
* @brief comprobar char trigonometrica
*
* @return true
* @return false
*/
bool is_trig_fun(char);
/**
* @brief comprobar trigonometrica
*
* @return true
* @return false
*/
bool is_trig_fun1(string);
/**
* @brief comprobar operando
*
* @return true
* @return false
*/
bool is_operand(char);
/**
* @brief char precedente
*
* @return int
*/
int precedence(char);
/**
* @brief elemento precedente
*
* @return int
*/
int precedence1(string);
/**
* @brief calcular
*
* @return double
*/
double calculate(Stack<string>);
/**
* @brief ingresar datos
*
* @return Stack<string>
*/
Stack<string> ingresar_datos();
Stack<string> ingresar_datos_enteros();
/**
* @brief invertir pila
*
* @return Stack<string>
*/
Stack<string> invertir_pila(Stack<string>);
/**
* @brief copiar pila
*
* @return Stack<string>
*/
Stack<string> copiar_pila(Stack<string>);
Stack<string> desencolar_pila_cifrada(Stack<string>,int);
string cifrar(string, int);
bool evaluar_expresion(Stack<string>);
char* ingreso(const char*);
};
| true |
9705d0211409d29f96482bc020970042ac881ee7 | C++ | Slackoth/Algoritmos | /SDA_Exam_04/ej_i.cpp | UTF-8 | 137 | 2.6875 | 3 | [] | no_license | #include <iostream>
using namespace std;
void spaceArr(char* arr, int size) {
for(int i = 0; i < size; i++)
arr[i] = ' ';
} | true |
cfdb6ea9fa6a8bc92f6ccd6125ce2c8aa81947a9 | C++ | Daniel-del-Castillo/CC1 | /headers/transition.hpp | UTF-8 | 797 | 3.3125 | 3 | [
"Unlicense"
] | permissive | #pragma once
#include <string>
#include <vector>
#define EPSILON '.'
// Represents a transition. It also contains an id, so the transitions
// are easier to identify in the traces
class Transition {
int id;
std::string destination;
char tape_token;
char stack_token;
std::vector<char> new_stack_tokens;
public:
Transition(
int id,
std::string destination,
char tape_token,
char stack_token,
std::vector<char> new_stack_tokens
);
bool is_epsilon() const;
std::string get_destination() const;
int get_id() const;
char get_tape_token() const;
char get_stack_token() const;
std::vector<char> get_new_stack_tokens() const;
bool is_valid_transition(char tape_token, char stack_token) const;
}; | true |
fc093ada62cde1d1307350ff44e4c9351907ca7a | C++ | kai04/Programming | /Number System/sieveEratosthenes.cpp | UTF-8 | 1,299 | 2.84375 | 3 | [] | no_license | //
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
vector<bool> Prime(ll n){
vector<bool> isPrime(n+1,true);
isPrime[0]=isPrime[1]=true;
for(ll i=2;i<=sqrt(n);i++){
if(isPrime[i]){
for(ll j=i*i;j<=n;j=j+i){
isPrime[j]=false;
}
}
}
return isPrime;
}
int main(){
ll n;
cin>>n;
vector<ll> res;
vector<bool> isPrime=Prime(n);
for(ll i=1;i<isPrime.size();i++){
if(isPrime[i]){
res.push_back(i);
}
}
ll cnt=1;
/*for(ll i=0;i<res.size();i++){
cout<<res[i]<<" ";
}*/
for(ll i=1;i<=n;i++){
for(ll j=1;j<=res.size();j++){
if(i%res[j]==0){
int p=0;
while(i%res[j]==0)
{i=i/res[j];p++;}
for(ll k=1;k<=res.size();k++){
if(k!=j&&i%res[k]==0){
int q=0;
while(i%res[k]==0)
{i=i/res[k];q++;}
if(i<=n){
cnt+=((p+1)*(q+1)/2);
cout<<"("<<res[j]<<"^"<<p<<") * ("<<res[k]<<")"<<endl;
}
}
}
}
}
}
//cout<<endl;
/*set<ll> res1;
for(ll i=1;i<res.size();i++){
for(ll k=1;pow(res[i],k)<=n;k++){
ll term1=pow(res[i],k);
for(ll j=1;j<res.size();j++){
if(j!=i && res[j]*term1 <= n){
res1.insert(term1*res[j]);
cout<<cnt<<") t1:"<<term1<<" t2:"<<res[j]<<endl;
cnt++;
}
}
}
}*/
cout<<"cnt:"<<cnt<<endl;
//cout<<res1.size()<<endl;
return 0;
} | true |
4afb602ae47df536884e5fbcc0a69ed09bfb780e | C++ | Yixuan-Lee/LeetCode | /algorithms/src/Ex_148/Sort_list.cpp | UTF-8 | 2,017 | 3.828125 | 4 | [] | no_license | // references:
// https://leetcode.com/problems/sort-list/discuss/46714/Java-merge-sort-solution
#include <iostream>
struct ListNode {
int val;
ListNode *next;
explicit ListNode(int x) : val(x), next(nullptr) {}
};
class Solution {
public:
ListNode *sortList(ListNode *head) {
if (head == nullptr || head->next == nullptr) {
return head;
}
// cut the entire list to two halves
ListNode *prevSlow = nullptr;
ListNode *slow = head;
ListNode *fast = head;
while (fast != nullptr && fast->next != nullptr) {
prevSlow = slow;
slow = slow->next;
fast = fast->next->next;
}
if (prevSlow) {
prevSlow->next = nullptr;
}
// sort two halves respectively
ListNode *l1 = sortList(head);
ListNode *l2 = sortList(slow);
// merge l1 and l2;
return merge(l1, l2);
}
private:
ListNode *merge(ListNode *l1, ListNode *l2) {
auto newHeadHolder = new ListNode(0);
auto it = newHeadHolder;
auto itL1 = l1;
auto itL2 = l2;
while (itL1 != nullptr && itL2 != nullptr) {
if (itL1->val < itL2->val) {
it->next = itL1;
itL1 = itL1->next;
} else {
it->next = itL2;
itL2 = itL2->next;
}
it = it->next;
}
// append the rest if itL1 or itL2 does not reach its end
if (itL1 != nullptr) {
it->next = itL1;
}
if (itL2 != nullptr) {
it->next = itL2;
}
return newHeadHolder->next;
}
};
int main() {
Solution s;
ListNode a1(4), a2(2), a3(1), a4(3);
a1.next = &a2;
a2.next = &a3;
a3.next = &a4;
ListNode *res = s.sortList(&a1);
for (ListNode *it = res; it; it = it->next) {
std::cout << it->val << "->";
}
std::cout << std::endl;
return 0;
}
| true |
82a61b426bdff40a59433812ef612c6062a359ff | C++ | UmbrellaSampler/carnd-term2-4_pid_control | /src/PID.cpp | UTF-8 | 988 | 3.0625 | 3 | [
"MIT"
] | permissive | #include "PID.h"
PID::PID() {}
PID::~PID() {}
void PID::Init(double Kp_, double Ki_, double Kd_) {
Kp = Kp_;
Ki = Ki_;
Kd = Kd_;
p_error = 0.0;
d_error = 0.0;
i_error = 0.0;
prev_cte = 0.0;
}
void PID::UpdateError(double cte) {
// Proportional error: this term is proportional to the cte.
// Effect: The stronger we are off-located from the center of the road the more we steer towards it.
// Using this error only leads to oscillations.
p_error = cte;
// Differential error: this term is driven by the difference in cte (d(cte)/dt) with respect to previous steps.
// Effect: It reduces/damps the oscillations induced by p_error.
d_error = cte - prev_cte;
// Integral error: this term represents the sum of all ctes of previous steps.
// Effect: It accounts for constant steering biases.
i_error += cte;
prev_cte = cte;
}
double PID::TotalError() {
return p_error * Kp + d_error * Kd + i_error * Ki;
} | true |
ab301989d98482babf7d42b2c6b9e33e5d3a2d6a | C++ | spookyboo/Memorytracker | /MemoryTracker.h | UTF-8 | 6,558 | 3.5625 | 4 | [] | no_license | /*
* ----------------------------------------------- Memorytracker -----------------------------------------------
* This one-header file can be used to determine memoryleaks. Instead of overriding the 'new' and 'delete'
* operator, this tracker implements alternative functions. Usage:
*
* 1. Add this headerfile to your project
*
* 2. Instead of using 'new', use the MT_NEW() macro. Eg. creating a new 'Test' class:
* Test* t1 = MT_NEW (Test (arg1, arg2));
* Note, that brackets must be used around the object to be created
*
* 3. Instead of using 'delete', use the MT_DELETE() macro, for example:
* MT_DELETE (t1);
* Note, that brackets must be used around the object to be deleted
*
* 4. Uncomment the line #define ENABLED_MEMORY_TRACKER if you want to track memory.
* Comment it, if you don't want to track memory (no additional overhead)
*
* 5. Run the application and check the file MemoryTracker.txt
*/
#ifndef _MEM_TRACKER_H_
#define _MEM_TRACKER_H_
// Comment next line to enable memory tracking
// Uncomment next line to disable memory tracking
#define ENABLED_MEMORY_TRACKER
#ifdef ENABLED_MEMORY_TRACKER
#include <iostream>
#include <fstream>
#include <map>
#include <string>
using namespace std;
// This struct contains the data involved with memory allocation
struct MemoryStruct
{
string typeName;
string file;
int line;
string functionAlloc;
size_t allocatedBytes;
};
/* This singleton class tracks the memory allocations by storing the relevant data in a map.
* When the MemoryTracker object object is deleted, it checks which entries in the map are not deleted.
* Any existing entry in the map represents a memory leak.
*/
class MemoryTracker
{
public:
// Constructor
MemoryTracker(void)
{
// Create the output file
mTrackerFile.open("MemoryTracker.txt");
mTrackerFile << "Initialize MemoryTracker\n";
}
// Destructor
virtual ~MemoryTracker(void)
{
// Validate the map; if there are still entries in the map, there are also memory leaks
size_t numberOfLeaks = memoryStructMap.size();
if (numberOfLeaks == 0)
{
mTrackerFile << "No memory leaks\n";
}
else
{
numberOfLeaks == 1 ?
(mTrackerFile << numberOfLeaks << " memory leak occurence detected\n") :
(mTrackerFile << numberOfLeaks << " memory leak occurences detected\n");
dumpTrackMemory();
}
mTrackerFile << "Shutdown MemoryTracker\n";
mTrackerFile.close();
}
// Get the Singleton
static MemoryTracker& getInstance()
{
static MemoryTracker instance;
return instance;
}
/* Track allocated data.
* When this function is called, an entry is added to the internal map
*/
template<typename T>
T* trackMemory(T* ptr, size_t size, char* file, int line, char* functionAlloc)
{
//mTrackerFile << "memory tracked: " << size << "bytes\n";
MemoryStruct memoryData;
memoryData.typeName.assign(typeid (T).name());
memoryData.file.assign(file);
memoryData.line = line;
memoryData.functionAlloc.assign(functionAlloc);
memoryData.allocatedBytes = size;
memoryStructMap[ptr] = memoryData;
return ptr;
}
/* Untrack allocated data.
* When this function is called, the corresponding entry is removed from the internal map
*/
void unTrackMemory(void* ptr)
{
if (memoryStructMap.size() == 0)
return;
// Find the pointer in the map and erase the memory data entry
//mTrackerFile << "untrackMemory\n";
map<void*, MemoryStruct>::const_iterator it;
it = memoryStructMap.find(ptr);
if (it != memoryStructMap.end())
{
//mTrackerFile << "memory untracked\n";
memoryStructMap.erase(it);
}
}
protected:
ofstream mTrackerFile;
// This map is filled with an entry after each allocation
map<void*, MemoryStruct> memoryStructMap;
/* Dump the content of the memory data map
*/
void dumpTrackMemory(void)
{
map<void*, MemoryStruct>::const_iterator it = memoryStructMap.begin();
map<void*, MemoryStruct>::const_iterator itEnd = memoryStructMap.end();
MemoryStruct memoryData;
while (it != itEnd)
{
memoryData = (*it).second;
mTrackerFile << "Leak in '"
<< memoryData.functionAlloc
<< "' when allocating '"
<< memoryData.typeName
<< "' on line "
<< memoryData.line
<< " in file "
<< memoryData.file
<< "\n";
++it;
}
}
private:
// Don't Implement private constructor and = operator
MemoryTracker(MemoryTracker const&);
void operator=(MemoryTracker const&);
};
/** Template function for MT_NEW
*/
template<typename T>
static T* MT_NEW(T* ptr, char* file, int line, char* function)
{
MemoryTracker::getInstance().trackMemory(ptr, sizeof(T), file, line, function);
return ptr;
}
/** Template function for MT_DELETE
*/
template<typename T>
static void MT_DELETE(T* ptr)
{
MemoryTracker::getInstance().unTrackMemory(ptr);
free(ptr);
}
/** Redefine MT_NEW and MT_DELETE to the MT_NEW and MT_DELETE template functions
*/
#define MT_NEW(T) MT_NEW(new T, (char*)__FILE__, __LINE__, (char*)__FUNCTION__)
#define MT_DELETE MT_DELETE
#else
/** Redefine MT_NEW and MT_DELETE to standard new and delete
*/
#define MT_NEW(T) new T
#define MT_DELETE(T) delete T
#endif
#endif
| true |
4dfa747783ada0163ecc6831cdb519f64bc0e2d8 | C++ | byznrdmrr/cs-sakaryauniversity | /BSM207 - VERİ YAPILARI/Ders Notları/Göstericiler/dizi_gostericisi.cpp | UTF-8 | 180 | 3.203125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(){
int x[]={10,5,21};
int *p;
p=x;
cout<<*p<<endl; // 10
cout<<*(p+1)<<endl; // 5
cout<<*(p+2)<<endl; // 21
return 0;
} | true |
a2be1c4b2d817d31f494388e8af08e4fa7db449c | C++ | chrillomat/AstroEQ | /AstroEQ-Firmware/SerialLink.cpp | UTF-8 | 3,418 | 2.515625 | 3 | [
"LicenseRef-scancode-other-permissive"
] | permissive |
#include "SerialLink.h"
#include <avr/io.h>
#include <avr/interrupt.h>
#ifndef USART0_TX_vect
#define USART0_TX_vect USART0_TXC_vect
#endif
#ifndef USART0_RX_vect
#define USART0_RX_vect USART0_RXC_vect
#endif
typedef struct {
unsigned char buffer[64];
volatile unsigned char head;
volatile unsigned char tail;
} RingBuffer;
RingBuffer txBuf = {{0},0,0};
RingBuffer rxBuf = {{0},0,0};
void Serial_initialise(const unsigned long baud){
Byter baud_setting;
UCSR0A = _BV(U2X0);
baud_setting.integer = (F_CPU / 4 / baud - 1) / 2;
if (baud_setting.high & 0xF0)
{
UCSR0A = 0;
baud_setting.integer = (F_CPU / 8 / baud - 1) / 2;
}
// assign the baud_setting, a.k.a. ubbr (USART Baud Rate Register)
UBRR0H = baud_setting.high & 0x0F;
UBRR0L = baud_setting.low;
sbi(UCSR0B, RXEN0);
sbi(UCSR0B, TXEN0);
sbi(UCSR0B, RXCIE0);
cbi(UCSR0B, UDRIE0);
}
byte Serial_available(void){
return ((rxBuf.head - rxBuf.tail) & 0x3F); //number of bytes available
}
char Serial_read(void){
byte tail = rxBuf.tail;
if (rxBuf.head == tail) {
return -1;
} else {
char c = rxBuf.buffer[tail];
rxBuf.tail = ((tail + 1) & 0x3F);
return c;
}
}
void Serial_write(char ch){
unsigned char head = ((txBuf.head + 1) & 0x3F);
while (head == txBuf.tail); //wait for buffer to empty
txBuf.buffer[txBuf.head] = ch;
txBuf.head = head;
sbi(UCSR0B, UDRIE0);
}
void Serial_writeStr(char* str){
while(*str){
Serial_write(*str++);
}
}
void Serial_writeArr(char* arr, byte len){
while(len--){
Serial_write(*arr++);
}
}
ISR(USART0_RX_vect,ISR_NAKED)
{
register unsigned char c asm("r18");
register unsigned char head asm("r25");
register unsigned char tail asm("r24");
asm volatile (
"push %0 \n\t"
:: "a" (c):
);
c = SREG;
asm volatile (
"push %0 \n\t"
"push %1 \n\t"
"push %2 \n\t"
"push r30 \n\t"
"push r31 \n\t"
:: "a" (c), "r" (head), "r" (tail):
);
//Read in from the serial data register
c = UDR0;
//get the current head
head = rxBuf.head;
head++;
head &= 0x3F;
tail = rxBuf.tail;
if (head != tail) {
rxBuf.buffer[rxBuf.head] = c;
rxBuf.head = head;
}
asm volatile (
"pop r31 \n\t"
"pop r30 \n\t"
"pop %2 \n\t"
"pop %1 \n\t"
"pop %0 \n\t"
: "=a" (c), "=r" (head), "=r" (tail)::
);
SREG = c;
asm volatile (
"pop %0 \n\t"
"reti \n\t"
: "=a" (c)::
);
}
ISR(USART0_UDRE_vect, ISR_NAKED)
{
register unsigned char tail asm("r25");
register unsigned char temp asm("r24");
asm volatile (
"push %0 \n\t"
:: "r" (temp):
);
temp = SREG;
asm volatile (
"push %0 \n\t"
"push %1 \n\t"
"push r30 \n\t"
"push r31 \n\t"
:: "r" (temp), "r" (tail):
);
tail = txBuf.tail;
temp = txBuf.head;
if (temp == tail) {
// Buffer empty, so disable interrupts
cbi(UCSR0B, UDRIE0);
} else {
// There is more data in the output buffer. Send the next byte
temp = txBuf.buffer[tail];
tail++;
tail &= 0x3F;
txBuf.tail = tail;
UDR0 = temp;
}
asm volatile (
"pop r31 \n\t"
"pop r30 \n\t"
"pop %1 \n\t"
"pop %0 \n\t"
:"=r" (temp), "=r" (tail)::
);
SREG = temp;
asm volatile (
"pop %0 \n\t"
"reti \n\t"
:"=r" (temp)::
);
}
| true |
8b370c748ee699d42f26a9e48f1231b857fe78b2 | C++ | cgcollector/PatternLabel | /ImageViewer.cpp | UTF-8 | 4,321 | 2.5625 | 3 | [] | no_license | #include "ImageViewer.h"
#include <qevent.h>
#include <qpainter.h>
#include <set>
#include <stack>
#include "util.h"
#include "global_data_holder.h"
ImageViewer::ImageViewer(QWidget* parent)
:QWidget(parent)
{
setMouseTracking(true);
setBackgroundRole(QPalette::ColorRole::Dark);
setAutoFillBackground(true);
}
ImageViewer::~ImageViewer()
{
}
void ImageViewer::setViewType(ViewType type)
{
m_viewType = type;
update();
}
ImageViewer::ViewType ImageViewer::getViewType()const
{
return m_viewType;
}
void ImageViewer::setColorImage(const QImage& img)
{
m_colorImage = img;
updateViewRect();
setViewType(ViewColorImage);
}
const QImage* ImageViewer::getColorImage()const
{
return &m_colorImage;
}
static std::vector<QRgb> gen_color_table()
{
std::vector<QRgb> table;
table.push_back(qRgb(0, 0, 0));
table.push_back(qRgb(200, 150, 100));
table.push_back(qRgb(150, 200, 100));
table.push_back(qRgb(100, 200, 150));
table.push_back(qRgb(200, 100, 150));
table.push_back(qRgb(100, 150, 200));
table.push_back(qRgb(150, 100, 200));
table.push_back(qRgb(160, 120, 80));
table.push_back(qRgb(120, 160, 80));
table.push_back(qRgb(80, 160, 120));
table.push_back(qRgb(160, 80, 120));
table.push_back(qRgb(80, 120, 160));
table.push_back(qRgb(120, 80, 160));
while (table.size() < 255)
table.push_back(qRgb(rand()%255, rand()%255, rand()%255));
return table;
}
float ImageViewer::getViewScale()const
{
if (m_viewRect.isEmpty() || m_colorImage.width()==0)
return 1.f;
return (float)m_viewRect.width() / (float)m_colorImage.width();
}
void ImageViewer::updateViewRect(bool allowScale)
{
// calc view rect
float scale = std::max(float(m_colorImage.rect().width()) / float(rect().width()),
float(m_colorImage.rect().height()) / float(rect().height()));
float oldScale = getViewScale();
m_viewRect = m_colorImage.rect();
m_viewRect.setSize(m_viewRect.size()*oldScale);
if (allowScale)
{
if (scale > 1)
m_viewRect.setSize(m_colorImage.rect().size() / scale*0.9);
else
m_viewRect = m_colorImage.rect();
}
m_viewRect.moveCenter(rect().center());
QPointF lt = m_viewRect.topLeft();
lt.setX(std::max(0., lt.x()));
lt.setY(std::max(0., lt.y()));
m_viewRect.moveTopLeft(lt);
update();
}
void ImageViewer::scaleViewRect(QPoint c, float s)
{
float newScale = s * getViewScale();
if (newScale > 64 || newScale < 1.f / 64)
return;
QPointF sz1 = m_viewRect.topLeft() - c;
QPointF sz2 = m_viewRect.bottomRight() - c;
m_viewRect.setTopLeft(sz1*s + c);
m_viewRect.setBottomRight(sz2*s + c);
update();
}
void ImageViewer::timerEvent(QTimerEvent* ev)
{
update();
}
QPointF ImageViewer::image2view(QPointF imgPt)
{
QPointF viewPt = imgPt * getViewScale() + QPointF(m_viewRect.x(), m_viewRect.y());
return viewPt;
}
QPointF ImageViewer::view2image(QPointF viewPt)
{
QPointF imgPt = (viewPt - QPointF(m_viewRect.x(), m_viewRect.y())) / getViewScale();
return imgPt;
}
void ImageViewer::paintEvent(QPaintEvent* ev)
{
QPainter painter(this);
painter.fillRect(rect(), Qt::gray);
switch (m_viewType)
{
case ImageViewer::ViewColorImage:
painter.drawImage(m_viewRect, m_colorImage);
break;
default:
break;
}
}
void ImageViewer::resizeEvent(QResizeEvent* ev)
{
updateViewRect(true);
}
void ImageViewer::mousePressEvent(QMouseEvent* ev)
{
m_buttons = ev->buttons();
if (m_buttons == Qt::MiddleButton)
{
updateViewRect(true);
}
if (m_buttons == Qt::LeftButton)
{
}
}
void ImageViewer::mouseReleaseEvent(QMouseEvent* ev)
{
if (m_buttons == Qt::LeftButton)
{
}
m_buttons = Qt::NoButton;
}
void ImageViewer::mouseMoveEvent(QMouseEvent* ev)
{
m_mousePos = ev->pos();
setFocus();
// selection event
QPointF imgPt = view2image(m_mousePos);
update();
}
void ImageViewer::wheelEvent(QWheelEvent* ev)
{
int delta = ev->delta();
float s = 0.8;
if (delta > 0)
s = 1.2;
scaleViewRect(m_mousePos, s);
}
void ImageViewer::keyPressEvent(QKeyEvent* ev)
{
switch (ev->key())
{
default:
break;
case Qt::Key_Space:
setViewType(ViewType(((int)getViewType()+1)%ViewTypeEnd));
printf("view mode: %d\n", getViewType());
break;
}
} | true |
89d3de4a040526500c1e56bbead5e792681bcab3 | C++ | dongryoung/Class_Examples | /10. Raspberry Pi/_15_Arduino_LED_PWM/_15_Arduino_LED_PWM.ino | UTF-8 | 301 | 2.65625 | 3 | [] | no_license | int led = 10; //~ mark port
int val = 0;
void setup() {
Serial.begin(9600);
Serial.println("input 0 ~ 255");
pinMode(led, OUTPUT);
} //setup()
void loop() {
if(Serial.available()) {
val = Serial.parseInt();
Serial.println(val);
analogWrite(led, val);
}
delay(50);
} //loop()
| true |
cf3093270c8225bf1396d1e35de1a4e4e2e97243 | C++ | alexisurvoy/Personal-Projects | /SuperPushBoy/Box.cpp | UTF-8 | 2,071 | 3.203125 | 3 | [] | no_license | /*
* Box.cpp
* sdlgame
*
* Created by Alexis Urvoy on 29/12/12.
* Copyright 2012 __MyCompanyName__. All rights reserved.
*
*/
#include "Box.h"
Box::Box(SDL_Surface* _screen): screen(_screen){
boxIm = IMG_Load("/Users/alex/Documents/sdlgame/images/box.png");
}
Box::~Box(){}
void Box::move(int direction){
switch(direction){
case Character::UP:
position.y -= 62;
break;
case Character::DOWN:
position.y += 62;
break;
case Character::LEFT:
position.x -= 62;
break;
case Character::RIGHT:
position.x += 62;
break;
default: break;
}
redraw();
}
void Box::setPosition(SDL_Rect newPos){
position = newPos;
}
void Box::setLevelArray(char* _levelArray){
levelArray = _levelArray;
}
void Box::redraw(){
SDL_BlitSurface(boxIm, NULL, screen, &position);
SDL_Flip(screen);
}
int Box::canMove(int direction){
int possible = 0;
char c;
switch(direction){
case Character::UP:
c = levelArray[(position.y/62-1)*20+position.x/62];
if(c!='1'){
if(c=='4')possible = 2;
else possible = 1;
levelArray[(position.y/62-1)*20+position.x/62]='2';
levelArray[(position.y/62)*20+position.x/62]='0';
position.y -= 62;
redraw();
}
break;
case Character::DOWN:
c = levelArray[(position.y/62+1)*20+position.x/62];
if(c!='1'){
possible = 1;
levelArray[(position.y/62+1)*20+position.x/62]='2';
levelArray[(position.y/62)*20+position.x/62]='0';
position.y += 62;
redraw();
}
break;
case Character::LEFT:
c = levelArray[(position.y/62)*20+position.x/62-1];
if(c!='1'){
possible = 1;
levelArray[(position.y/62)*20+position.x/62-1]='2';
levelArray[(position.y/62)*20+position.x/62]='0';
position.x -= 62;
redraw();
}
break;
case Character::RIGHT:
c = levelArray[(position.y/62)*20+position.x/62+1];
if(c!='1'){
possible = 1;
levelArray[(position.y/62)*20+position.x/62+1]='2';
levelArray[(position.y/62)*20+position.x/62]='0';
position.x += 62;
redraw();
}
break;
default: break;
}
return possible;
} | true |
0fc4ae26b8a1e8bc10e717c7a2cf56ac39f9bb04 | C++ | papan01/cvCrayon | /cvlib/imgproc/smoothing.cpp | UTF-8 | 3,216 | 2.984375 | 3 | [] | no_license | #include "smoothing.h"
namespace imgproc
{
GaussCache::GaussCache(const float& sigma, const int& gauss_window_factor)
{
kernel_window_factor = static_cast<int>(ceil(0.3 * (sigma / 2 - 1) + 0.8) * gauss_window_factor);
if (kernel_window_factor % 2 == 0) kernel_window_factor++;
kernel_horizontal_buf.reset(new float[kernel_window_factor]);
kernel_vertical_buf.reset(new float[kernel_window_factor]);
const int center = kernel_window_factor / 2;
kernel_horizontal = kernel_horizontal_buf.get() + center;
kernel_vertical = kernel_vertical_buf.get() + center;
kernel_horizontal[0] = 1;
float exp_coeff = -1.0f / (sigma * sigma * 2.0f), wsum = 1.0f;
for (int i = 1; i <= center; i++)
{
wsum += (kernel_horizontal[i] = exp(i * i * exp_coeff)) * 2;
kernel_vertical[i] = kernel_horizontal[i];
}
float fac = 1.0f / wsum;
kernel_horizontal[0] = fac;
kernel_vertical[0] = fac;
for (int i = 1; i <= center; i++)
{
kernel_horizontal[-i] = (kernel_horizontal[i] *= fac);
kernel_vertical[-i] = (kernel_vertical[i] *= fac);
std::cout << kernel_horizontal[-i] << " " << kernel_horizontal[i] << std::endl;
std::cout << kernel_vertical[-i] << " " << kernel_vertical[i] << std::endl;
}
}
BoxCache::BoxCache(const int & box_window_factor)
{
kernel_window_factor = box_window_factor;
if (kernel_window_factor % 2 == 0) kernel_window_factor++;
kernel_horizontal_buf.reset(new float[kernel_window_factor]);
kernel_vertical_buf.reset(new float[kernel_window_factor]);
const int center = kernel_window_factor / 2;
kernel_horizontal = kernel_horizontal_buf.get() + center;
kernel_vertical = kernel_vertical_buf.get() + center;
float fac = 1.0f / static_cast<float>(kernel_window_factor);
kernel_horizontal[0] = fac;
kernel_vertical[0] = fac;
for (int i = 1; i <= center; i++)
{
kernel_horizontal[-i] = kernel_horizontal[i] = fac;
kernel_vertical[-i] = kernel_vertical[i] = fac;
}
}
SobelCache::SobelCache(SobelWindowFactor swf)
{
if (swf == SobelWindowFactor::Size3x3)
{
kernel_window_factor = 3;
kernel_horizontal_buf.reset(new float[kernel_window_factor]);
kernel_vertical_buf.reset(new float[kernel_window_factor]);
const int center = kernel_window_factor / 2;
kernel_vertical = kernel_vertical_buf.get() + center;
kernel_vertical[-1] = 1.0f, kernel_vertical[0] = 2.0f, kernel_vertical[1] = 1.0f;
kernel_horizontal = kernel_horizontal_buf.get() + center;
kernel_horizontal[-1] = 1.0f, kernel_horizontal[0] = 0.0f, kernel_horizontal[1] = -1.0f ;
}
else if (swf == SobelWindowFactor::Size5x5)
{
kernel_window_factor = 5;
kernel_horizontal_buf.reset(new float[kernel_window_factor]);
kernel_vertical_buf.reset(new float[kernel_window_factor]);
const int center = kernel_window_factor / 2;
kernel_vertical = kernel_vertical_buf.get() + center;
kernel_vertical[-2] = 1, kernel_vertical[-1] = 4, kernel_vertical[0] = 6, kernel_vertical[1] = 4, kernel_vertical[2] = 1;
kernel_horizontal = kernel_horizontal_buf.get();
kernel_horizontal[-2] = 1, kernel_horizontal[-1] = 2, kernel_horizontal[0] = 0, kernel_horizontal[1] = -2, kernel_horizontal[2] = -1;
}
}
}
| true |
7a6d8956ec4ab7b05613bba6fcfebff3b17ba26e | C++ | tigarto/whatsprogrammer | /data-structures-in-cpp/graph/MST/kruskal/ListUDG.cpp | UTF-8 | 15,347 | 3.578125 | 4 | [
"MIT"
] | permissive | /**
* C++: prim算法生成最小生成树(邻接表)
*
* @author skywang
* @date 2014/04/23
*/
#include <iomanip>
#include <iostream>
#include <vector>
using namespace std;
// 示例类:边的结构体(用来演示)
class EData
{
public:
char start; // 边的起点
char end; // 边的终点
int weight; // 边的权重
public:
EData(){}
EData(char s, char e, int w):start(s),end(e),weight(w){}
};
// 邻接表
class ListUDG
{
#define MAX 100
#define INF (~(0x1<<31)) // 最大值(即0X7FFFFFFF)
private: // 内部类
// 邻接表中表对应的链表的顶点
class ENode
{
int ivex; // 该边所指向的顶点的位置
int weight; // 该边的权
ENode *nextEdge; // 指向下一条弧的指针
friend class ListUDG;
};
// 邻接表中表的顶点
class VNode
{
char data; // 顶点信息
ENode *firstEdge; // 指向第一条依附该顶点的弧
friend class ListUDG;
};
private: // 私有成员
int mVexNum; // 图的顶点的数目
int mEdgNum; // 图的边的数目
VNode mVexs[MAX];
public:
// 创建邻接表对应的图(自己输入)
ListUDG();
// 创建邻接表对应的图(用已提供的数据)
ListUDG(char vexs[], int vlen, EData *edges[], int elen);
~ListUDG();
// 深度优先搜索遍历图
void DFS();
// 广度优先搜索(类似于树的层次遍历)
void BFS();
// 打印邻接表图
void print();
// prim最小生成树
void prim(int start);
// 克鲁斯卡尔(Kruskal)最小生成树
void kruskal();
private:
// 读取一个输入字符
char readChar();
// 返回ch的位置
int getPosition(char ch);
// 深度优先搜索遍历图的递归实现
void DFS(int i, int *visited);
// 将node节点链接到list的最后
void linkLast(ENode *list, ENode *node);
// 获取边<start, end>的权值;若start和end不是连通的,则返回无穷大。
int getWeight(int start, int end);
// 获取图中的边
EData* getEdges();
// 对边按照权值大小进行排序(由小到大)
void sortEdges(EData* edges, int elen);
// 获取i的终点
int getEnd(int vends[], int i);
};
/*
* 创建邻接表对应的图(自己输入)
*/
ListUDG::ListUDG()
{
char c1, c2;
int v, e;
int i, p1, p2;
int weight;
ENode *node1, *node2;
// 输入"顶点数"和"边数"
cout << "input vertex number: ";
cin >> mVexNum;
cout << "input edge number: ";
cin >> mEdgNum;
if ( mVexNum < 1 || mEdgNum < 1 || (mEdgNum > (mVexNum * (mVexNum-1))))
{
cout << "input error: invalid parameters!" << endl;
return ;
}
// 初始化"邻接表"的顶点
for(i=0; i<mVexNum; i++)
{
cout << "vertex(" << i << "): ";
mVexs[i].data = readChar();
mVexs[i].firstEdge = NULL;
}
// 初始化"邻接表"的边
for(i=0; i<mEdgNum; i++)
{
// 读取边的起始顶点和结束顶点
cout << "edge(" << i << "): ";
c1 = readChar();
c2 = readChar();
cin >> weight;
p1 = getPosition(c1);
p2 = getPosition(c2);
// 初始化node1
node1 = new ENode();
node1->ivex = p2;
node1->weight = weight;
// 将node1链接到"p1所在链表的末尾"
if(mVexs[p1].firstEdge == NULL)
mVexs[p1].firstEdge = node1;
else
linkLast(mVexs[p1].firstEdge, node1);
// 初始化node2
node2 = new ENode();
node2->ivex = p1;
node2->weight = weight;
// 将node2链接到"p2所在链表的末尾"
if(mVexs[p2].firstEdge == NULL)
mVexs[p2].firstEdge = node2;
else
linkLast(mVexs[p2].firstEdge, node2);
}
}
/*
* 创建邻接表对应的图(用已提供的数据)
*/
ListUDG::ListUDG(char vexs[], int vlen, EData *edges[], int elen)
{
char c1, c2;
int i, p1, p2;
int weight;
ENode *node1, *node2;
// 初始化"顶点数"和"边数"
mVexNum = vlen;
mEdgNum = elen;
// 初始化"邻接表"的顶点
for(i=0; i<mVexNum; i++)
{
mVexs[i].data = vexs[i];
mVexs[i].firstEdge = NULL;
}
// 初始化"邻接表"的边
for(i=0; i<mEdgNum; i++)
{
// 读取边的起始顶点和结束顶点
c1 = edges[i]->start;
c2 = edges[i]->end;
weight = edges[i]->weight;
p1 = getPosition(c1);
p2 = getPosition(c2);
// 初始化node1
node1 = new ENode();
node1->ivex = p2;
node1->weight = weight;
// 将node1链接到"p1所在链表的末尾"
if(mVexs[p1].firstEdge == NULL)
mVexs[p1].firstEdge = node1;
else
linkLast(mVexs[p1].firstEdge, node1);
// 初始化node2
node2 = new ENode();
node2->ivex = p1;
node2->weight = weight;
// 将node2链接到"p2所在链表的末尾"
if(mVexs[p2].firstEdge == NULL)
mVexs[p2].firstEdge = node2;
else
linkLast(mVexs[p2].firstEdge, node2);
}
}
/*
* 析构函数
*/
ListUDG::~ListUDG()
{
}
/*
* 将node节点链接到list的最后
*/
void ListUDG::linkLast(ENode *list, ENode *node)
{
ENode *p = list;
while(p->nextEdge)
p = p->nextEdge;
p->nextEdge = node;
}
/*
* 返回ch的位置
*/
int ListUDG::getPosition(char ch)
{
int i;
for(i=0; i<mVexNum; i++)
if(mVexs[i].data==ch)
return i;
return -1;
}
/*
* 读取一个输入字符
*/
char ListUDG::readChar()
{
char ch;
do {
cin >> ch;
} while(!((ch>='a'&&ch<='z') || (ch>='A'&&ch<='Z')));
return ch;
}
/*
* 深度优先搜索遍历图的递归实现
*/
void ListUDG::DFS(int i, int *visited)
{
ENode *node;
visited[i] = 1;
cout << mVexs[i].data << " ";
node = mVexs[i].firstEdge;
while (node != NULL)
{
if (!visited[node->ivex])
DFS(node->ivex, visited);
node = node->nextEdge;
}
}
/*
* 深度优先搜索遍历图
*/
void ListUDG::DFS()
{
int i;
int visited[MAX]; // 顶点访问标记
// 初始化所有顶点都没有被访问
for (i = 0; i < mVexNum; i++)
visited[i] = 0;
cout << "DFS: ";
for (i = 0; i < mVexNum; i++)
{
if (!visited[i])
DFS(i, visited);
}
cout << endl;
}
/*
* 广度优先搜索(类似于树的层次遍历)
*/
void ListUDG::BFS()
{
int head = 0;
int rear = 0;
int queue[MAX]; // 辅组队列
int visited[MAX]; // 顶点访问标记
int i, j, k;
ENode *node;
for (i = 0; i < mVexNum; i++)
visited[i] = 0;
cout << "BFS: ";
for (i = 0; i < mVexNum; i++)
{
if (!visited[i])
{
visited[i] = 1;
cout << mVexs[i].data << " ";
queue[rear++] = i; // 入队列
}
while (head != rear)
{
j = queue[head++]; // 出队列
node = mVexs[j].firstEdge;
while (node != NULL)
{
k = node->ivex;
if (!visited[k])
{
visited[k] = 1;
cout << mVexs[k].data << " ";
queue[rear++] = k;
}
node = node->nextEdge;
}
}
}
cout << endl;
}
/*
* 打印邻接表图
*/
void ListUDG::print()
{
int i,j;
ENode *node;
cout << "List Graph:" << endl;
for (i = 0; i < mVexNum; i++)
{
cout << i << "(" << mVexs[i].data << "): ";
node = mVexs[i].firstEdge;
while (node != NULL)
{
cout << node->ivex << "(" << mVexs[node->ivex].data << ") ";
node = node->nextEdge;
}
cout << endl;
}
}
/*
* 获取边<start, end>的权值;若start和end不是连通的,则返回无穷大。
*/
int ListUDG::getWeight(int start, int end)
{
ENode *node;
if (start==end)
return 0;
node = mVexs[start].firstEdge;
while (node!=NULL)
{
if (end==node->ivex)
return node->weight;
node = node->nextEdge;
}
return INF;
}
/*
* prim最小生成树
*
* 参数说明:
* start -- 从图中的第start个元素开始,生成最小树
*/
void ListUDG::prim(int start)
{
int min,i,j,k,m,n,tmp,sum;
int index=0; // prim最小树的索引,即prims数组的索引
char prims[MAX]; // prim最小树的结果数组
int weights[MAX]; // 顶点间边的权值
// prim最小生成树中第一个数是"图中第start个顶点",因为是从start开始的。
prims[index++] = mVexs[start].data;
// 初始化"顶点的权值数组",
// 将每个顶点的权值初始化为"第start个顶点"到"该顶点"的权值。
for (i = 0; i < mVexNum; i++ )
weights[i] = getWeight(start, i);
for (i = 0; i < mVexNum; i++)
{
// 由于从start开始的,因此不需要再对第start个顶点进行处理。
if(start == i)
continue;
j = 0;
k = 0;
min = INF;
// 在未被加入到最小生成树的顶点中,找出权值最小的顶点。
while (j < mVexNum)
{
// 若weights[j]=0,意味着"第j个节点已经被排序过"(或者说已经加入了最小生成树中)。
if (weights[j] != 0 && weights[j] < min)
{
min = weights[j];
k = j;
}
j++;
}
// 经过上面的处理后,在未被加入到最小生成树的顶点中,权值最小的顶点是第k个顶点。
// 将第k个顶点加入到最小生成树的结果数组中
prims[index++] = mVexs[k].data;
// 将"第k个顶点的权值"标记为0,意味着第k个顶点已经排序过了(或者说已经加入了最小树结果中)。
weights[k] = 0;
// 当第k个顶点被加入到最小生成树的结果数组中之后,更新其它顶点的权值。
for (j = 0 ; j < mVexNum; j++)
{
// 获取第k个顶点到第j个顶点的权值
tmp = getWeight(k, j);
// 当第j个节点没有被处理,并且需要更新时才被更新。
if (weights[j] != 0 && tmp < weights[j])
weights[j] = tmp;
}
}
// 计算最小生成树的权值
sum = 0;
for (i = 1; i < index; i++)
{
min = INF;
// 获取prims[i]在矩阵表中的位置
n = getPosition(prims[i]);
// 在vexs[0...i]中,找出到j的权值最小的顶点。
for (j = 0; j < i; j++)
{
m = getPosition(prims[j]);
tmp = getWeight(m, n);
if (tmp < min)
min = tmp;
}
sum += min;
}
// 打印最小生成树
cout << "PRIM(" << mVexs[start].data <<")=" << sum << ": ";
for (i = 0; i < index; i++)
cout << prims[i] << " ";
cout << endl;
}
/*
* 获取图中的边
*/
EData* ListUDG::getEdges()
{
int i,j;
int index=0;
ENode *node;
EData *edges;
edges = new EData[mEdgNum];
for (i=0; i < mVexNum; i++)
{
node = mVexs[i].firstEdge;
while (node != NULL)
{
if (node->ivex > i)
{
edges[index].start = mVexs[i].data; // 起点
edges[index].end = mVexs[node->ivex].data; // 终点
edges[index].weight = node->weight; // 权
index++;
}
node = node->nextEdge;
}
}
return edges;
}
/*
* 对边按照权值大小进行排序(由小到大)
*/
void ListUDG::sortEdges(EData* edges, int elen)
{
int i,j;
for (i=0; i<elen; i++)
{
for (j=i+1; j<elen; j++)
{
if (edges[i].weight > edges[j].weight)
{
// 交换"边i"和"边j"
swap(edges[i], edges[j]);
}
}
}
}
/*
* 获取i的终点
*/
int ListUDG::getEnd(int vends[], int i)
{
while (vends[i] != 0)
i = vends[i];
return i;
}
/*
* 克鲁斯卡尔(Kruskal)最小生成树
*/
void ListUDG::kruskal()
{
int i,m,n,p1,p2;
int length;
int index = 0; // rets数组的索引
int vends[MAX]={0}; // 用于保存"已有最小生成树"中每个顶点在该最小树中的终点。
EData rets[MAX]; // 结果数组,保存kruskal最小生成树的边
EData *edges; // 图对应的所有边
// 获取"图中所有的边"
edges = getEdges();
// 将边按照"权"的大小进行排序(从小到大)
sortEdges(edges, mEdgNum);
for (i=0; i<mEdgNum; i++)
{
p1 = getPosition(edges[i].start); // 获取第i条边的"起点"的序号
p2 = getPosition(edges[i].end); // 获取第i条边的"终点"的序号
m = getEnd(vends, p1); // 获取p1在"已有的最小生成树"中的终点
n = getEnd(vends, p2); // 获取p2在"已有的最小生成树"中的终点
// 如果m!=n,意味着"边i"与"已经添加到最小生成树中的顶点"没有形成环路
if (m != n)
{
vends[m] = n; // 设置m在"已有的最小生成树"中的终点为n
rets[index++] = edges[i]; // 保存结果
}
}
delete[] edges;
// 统计并打印"kruskal最小生成树"的信息
length = 0;
for (i = 0; i < index; i++)
length += rets[i].weight;
cout << "Kruskal=" << length << ": ";
for (i = 0; i < index; i++)
cout << "(" << rets[i].start << "," << rets[i].end << ") ";
cout << endl;
}
int main()
{
// 顶点
char vexs[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G'};
// 边
EData *edges[] = {
// 起点 终点 权
new EData('A', 'B', 12),
new EData('A', 'F', 16),
new EData('A', 'G', 14),
new EData('B', 'C', 10),
new EData('B', 'F', 7),
new EData('C', 'D', 3),
new EData('C', 'E', 5),
new EData('C', 'F', 6),
new EData('D', 'E', 4),
new EData('E', 'F', 2),
new EData('E', 'G', 8),
new EData('F', 'G', 9),
};
int vlen = sizeof(vexs)/sizeof(vexs[0]);
int elen = sizeof(edges)/sizeof(edges[0]);
ListUDG* pG;
// 自定义"图"(输入矩阵队列)
//pG = new ListUDG();
// 采用已有的"图"
pG = new ListUDG(vexs, vlen, edges, elen);
//pG->print(); // 打印图
//pG->DFS(); // 深度优先遍历
//pG->BFS(); // 广度优先遍历
//pG->prim(0); // prim算法生成最小生成树
pG->kruskal(); // Kruskal算法生成最小生成树
return 0;
}
| true |
41b56d510ec49e2e07c793433a5a611e5ba333ba | C++ | tiyunes/Lab_2sem_2 | /STACK.H | UTF-8 | 1,457 | 3.625 | 4 | [] | no_license | #ifndef STACK_H
#define STACK_H
#include "ArraySequence.h"
#include "LinkedListSequence.h"
template<class T>
class Stack
{
public:
Stack()
{
this->elements = (Sequence<T>*) new LinkedListSequence<T>();
//this->elements = (Sequence<T>*) new ArraySequence<T>();
}
Stack(T* items, int size) //0.001 s (List) and 0.019 s (Array) for 1000 elements
{
this->elements = (Sequence<T>*) new LinkedListSequence<T>(items, size);
//this->elements = (Sequence<T>*) new ArraySequence<T>(items, size);
this->elements->Reverse();
}
T Top() //0.452 s (List) and 0.284 s (Array) for 1M iterations
{
return this->elements->GetFirst();
}
bool Empty()
{
if (this->elements->GetLength() == 0) return true;
else return false;
}
int Size()
{
return this->elements->GetLength();
}
void Push(T item) // 0.002 s (List) and 0.384 s (Array) for 1000 elements
{
return this->elements->Prepend(item);
}
void Pop() // 0.167 s (List) for 1M iterations and 0.135 s (Array) for 1000 iterations
{
this->elements->Pop();
}
void Concat(Stack<T>* s)
{
for(int i = 0; i < s->elements->GetLength(); i++)
{
this->Push(s->elements->Get(i));
}
}
~Stack()
{
delete this->elements;
}
protected:
private:
Sequence<T>* elements;
};
#endif // STACK_H
| true |
90d1093fe32cd8aa5d50590f37d41d250223aa9e | C++ | Cogitus/DCA1202---Projeto-1 | /tratamentoDePoligonos/ponto.cpp | UTF-8 | 1,055 | 3.453125 | 3 | [] | no_license | #include <cmath>
#include <iostream>
#include "ponto.h"
using namespace std;
Ponto::Ponto() { //construtor
}
void Ponto::setX(float _x) {
x = _x;
}
void Ponto::setY(float _y) {
y = _y;
}
void Ponto::setXY(float _x, float _y) {
x = _x;
y = _y;
}
float Ponto::getX(void) {
return x;
}
float Ponto::getY(void) {
return y;
}
Ponto Ponto::add(Ponto p1) {
Ponto pontoAuxiliar;
pontoAuxiliar.x = p1.x + x;
pontoAuxiliar.y = p1.x + y;
return pontoAuxiliar;
}
Ponto Ponto::sub(Ponto p1) {
Ponto pontoAuxiliar;
pontoAuxiliar.x = p1.x + x; //o x avulso pertence ao meu objeto que chama o método sub.
pontoAuxiliar.y = p1.y + y; //o y avulso pertence ao meu objeto que chama o método sub.
//não estamos usando os métodos set() e get() por otimização!
return pontoAuxiliar;
}
float Ponto::norma(void) {
return sqrt(x*x + y*y);
}
void Ponto::translada(float a, float b) {
x = x+a;
y = y+b;
}
void Ponto::imprime(void) {
cout << "(" << x << ", " << y << ")";
}
| true |
7dfe33bb98baf0ce504f345f37fe55f9de6f313c | C++ | hljgirl/DesignPatterns | /Composite/Employee.h | UTF-8 | 334 | 3.296875 | 3 | [] | no_license | #pragma once
#include <string>
using namespace std;
class Employee
{
public:
Employee(string name, int age, int salary);
virtual ~Employee();
virtual void add(Employee* employee) = 0;
virtual void ShowInformation() = 0;
string GetName();
int GetAge();
int GetSalary();
private:
string _name;
int _age;
int _salary;
};
| true |
4861a8e06362a5fb981645aec2cdac899138eb1e | C++ | YadamD/HalProg | /Matrix/matr2D.h | UTF-8 | 10,966 | 3.375 | 3 | [] | no_license | #include <vector>
#include <algorithm>
#include <iostream>
#include <string>
#include <sstream>
#include <numeric>
#include <initializer_list>
#include <cmath>
#include <ostream>
namespace detail
{
template<typename M1, typename M2, typename F>
void transform_matrix1(M1 const& m1, M2& m2, F f)
{
std::transform(m1.cbegin(), m1.cend(), m2.begin(), f);
}
template<typename M1, typename M2, typename M3, typename F>
void transform_matrix2(M1 const& m1, M2 const& m2, M3& m3, F f)
{
std::transform(m1.cbegin(), m1.cend(), m2.cbegin(), m3.begin(), f);
}
}
auto add = [](auto const& x, auto const& y){ return x + y; };
auto sub = [](auto const& x, auto const& y){ return x - y; };
/*
template<typename T>
std::vector<T> matmul(std::vector<T> const& m1, std::vector<T> const& m2, int l){
int const len=static_cast<int>(m1.size());
T sum=0;
int n=l*l;
std::vector<T> u(len);
if(len!=static_cast<int>(m2.size()) || n!=len){
std::cout<<"Multiplication error"<<std::endl;
return u;
}
for(int i=0; i<l; i++){
for(int j=0; j<l; j++){
sum=0;
for(int k=0; k<l; k++){
sum+=(m1[i*l+k])*(m2[k*l+j]);
}
u[i*l+j]=sum;
}
}
return u;
}
*/
template<typename T>
class smatrix
{
public:
int l;
std::vector<T> data;
smatrix(): l{1}, data{{0}}{};
smatrix(int i): l(i), data(i*i, 0){};
smatrix(int i, std::vector<T> const& v){
if(i*i!=static_cast<int>(v.size())){
std::cout<<"Parameter error!"<<std::endl;
}
else{
l=i;
data=v;
}
}
smatrix<T>(smatrix<T> const& copy): l{copy.l}, data{copy.data}{
if(l!=copy.l){
std::cout<<"Error with copying"<<std::endl;
exit(-1);
}
}
T & operator[](int i){return data[i];}
T & operator()(int i, int j){return data[l*i+j];}
T const& operator[](int i) const {return data[i];}
T const& operator()(int i, int j)const {return data[l*i+j];}
smatrix<T>& operator=(smatrix<T>&&)=default;
smatrix<T>(smatrix<T>&& o) noexcept : l(std::exchange(o.l, 0)), data(std::move(o.data)) {}
smatrix<T>& operator=(const smatrix<T> &)=default;
smatrix<T>& operator+=(smatrix<T> const& m){
detail::transform_matrix2((*this).data, m.data, (*this).data, add);
return *this;
}
smatrix<T>& operator-=(smatrix<T> const& m){
detail::transform_matrix2((*this).data, m.data, (*this).data, sub);
return *this;
}
smatrix<T>& operator*=(T const& c){
detail::transform_matrix1((*this).data, (*this).data, [=](T const& x){return x*c;});
return *this;
}
smatrix<T>& operator/=(T const& c){
detail::transform_matrix1((*this).data, (*this).data, [=](T const& x){return x/c;});
return *this;
}
/*smatrix<T>& operator*=(smatrix<T> const& m){
std::vector<T> u=matmul((*this).data, m.data, (*this).l);
(*this).data.swap(u);
return *this;
}*/
smatrix<T>& operator*=(smatrix<T> const& m);
int size() const{
return l*l;
}
int dimension() const{
return l;
}
auto begin(){
return data.begin();
}
auto cbegin() const{
return data.cbegin();
}
auto end(){
return data.end();
}
auto cend() const{
return data.cend();
}
std::vector<T> dat() const&{
return data;
}
};
template<typename T>
smatrix<T> matmul(smatrix<T> const& m1, smatrix<T> const& m2, int l){
//int const len=static_cast<int>(m1.size());
T sum=0;
int n=l*l;
smatrix<T> u(l);
if(static_cast<int>(m2.dimension())!=static_cast<int>(m1.dimension())){
std::cout<<"Multiplication error"<<std::endl;
return u;
}
for(int i=0; i<l; i++){
for(int j=0; j<l; j++){
sum=0;
for(int k=0; k<l; k++){
sum+=(m1(i,k))*(m2(k,j));
}
u(i,j)=sum;
}
}
return u;
}
//Addition
template<typename T>
smatrix<T> operator+(smatrix<T> const& m1, smatrix<T> const& m2){
smatrix<T> result(m1.dimension());
detail::transform_matrix2(m1, m2, result, add);
return result;
}
template<typename T>
smatrix<T>&& operator+( smatrix<T>&& m1, smatrix<T>const& m2){
detail::transform_matrix2(m1,m2,m1,add);
return std::move(m1);
}
template<typename T>
smatrix<T>&& operator+( smatrix<T>const& m1, smatrix<T>&& m2){
detail::transform_matrix2(m1,m2,m2,add);
return std::move(m2);
}
template<typename T>
smatrix<T>&& operator+( smatrix<T>&& m1, smatrix<T>&& m2){
detail::transform_matrix2(m1,m2,m1,add);
return std::move(m1);
}
//Subtraction
template<typename T>
smatrix<T> operator-(smatrix<T> const& m1, smatrix<T> const& m2){
smatrix<T> result(m1.dimension());
detail::transform_matrix2(m1, m2, result, sub);
return result;
}
template<typename T>
smatrix<T>&& operator-( smatrix<T>&& m1, smatrix<T>const& m2){
detail::transform_matrix2(m1,m2,m1,sub);
return std::move(m1);
}
template<typename T>
smatrix<T>&& operator-( smatrix<T>const& m1, smatrix<T>&& m2){
detail::transform_matrix2(m1,m2,m2,sub);
return std::move(m2);
}
template<typename T>
smatrix<T>&& operator-( smatrix<T>&& m1, smatrix<T>&& m2){
detail::transform_matrix2(m1,m2,m1,sub);
return std::move(m1);
}
//Scalar Multiplication
template<typename T>
smatrix<T> operator*(T const& c, smatrix<T> const& m){
smatrix<T> result(m.dimension());
detail::transform_matrix2(m, result, [c](T const& x){return c*x;});
return result;
}
template<typename T>
smatrix<T>&& operator*(T const& c, smatrix<T>&& m){
detail::transform_matrix1(m, m, [c](T const& x){return c*x;});
return std::move(m);
}
template<typename T>
smatrix<T> operator*(smatrix<T> const& m, T const& c){
smatrix<T> result(m.dimension());
detail::transform_matrix2(m, result, [c](T const& x){return c*x;});
return result;
}
template<typename T>
smatrix<T>&& operator*(smatrix<T>&& m, T const& c){
detail::transform_matrix1(m, m, [c](T const& x){return c*x;});
return std::move(m);
}
//Division
template<typename T>
smatrix<T> operator/(smatrix<T> const& m, T const& c){
smatrix<T> result(m.dimension());
detail::transform_matrix1(m, result, [c](T const& x){return x/c;});
return result;
}
template<typename T>
smatrix<T>&& operator/(smatrix<T>&& m, T const& c){
detail::transform_matrix1(m.data, m.data, [c](T const& x){return x/c;});
return std::move(m);
}
template<typename T>
int matmul2(smatrix<T>& m1, smatrix<T>& m2, int hlp){
int n = m1.dimension();
std::vector<T> temp(n);
if(hlp == 1){
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
double temp_d = 0;
for(int k = 0; k < n; k++){
temp_d += m1(i, k) * m2(k, j);
}
temp[j] = temp_d;
}
for(int j = 0; j < n; j++){
m1(i, j) = temp[j];
}
}
return 0;
}
else if(hlp == 2){
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
double temp_d = 0;
for(int k = 0; k < n; k++){
temp_d += m1(j, k) * m2(k, i);
}
temp[j] = temp_d;
}
for(int j = 0; j < n; j++){
m2(j, i) = temp[j];
}
}
return 0;
}
return -1;
}
//Matrix Multiplication
template<typename T>
smatrix<T>& smatrix<T>::operator*=(smatrix<T> const& m){
smatrix<T> u=matmul(*this, m, m.dimension());
*this=u;
return *this;
}
template<typename T>
smatrix<T> operator*(smatrix<T> const& m1, smatrix<T> const& m2){
smatrix<T> v = matmul(m1, m2, m1.dimension());
return v;
}
template<typename T>
smatrix<T>&& operator*(smatrix<T> && m1, smatrix<T> & m2){
if(matmul2(m1, m2, 1) != 0){
std::cout<<"Matrix multiplication error!"<<std::endl;
}
return std::move(m1);
}
template<typename T>
smatrix<T>&& operator*(smatrix<T> & m1, smatrix<T>&& m2){
if(matmul2(m1, m2, 2) != 0){
std::cout<<"Matrix multiplication error!"<<std::endl;
}
return std::move(m2);
}
template<typename T>
smatrix<T>&& operator*(smatrix<T> && m1, smatrix<T>&& m2){
if(matmul2(m1, m2, 1) != 0){
std::cout<<"Matrix multiplication error!"<<std::endl;
}
return std::move(m1);
}
template<typename T>
std::ostream& operator<<(std::ostream& o, smatrix<T> const& m){
o<<m.dimension()<<';';
int n={m.dimension()};
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
o<<m(i,j)<<',';
}
}
return o;
}
template<typename T>
std::istream& operator>>(std::istream& s, smatrix<T>& m){
auto rewind = [state = s.rdstate(), pos = s.tellg(), &s](){s.seekg(pos); s.setstate(state);};
std::string temp_string;
std::getline(s, temp_string);
if(!s){rewind(); std::cout<<"Read error!"<<std::endl; return s;}
std::stringstream ss(temp_string);
if(!ss){rewind(); std::cout<<"Read error!"<<std::endl; return s;}
std::getline(ss, temp_string, ';');
if(static_cast<int>(temp_string.size()) > 0){
int dim = std::stoi(temp_string);
std::vector<T> temp_vec;
for(int i = 0; i < dim * dim; i++){
std::getline(ss, temp_string, ',');
if(static_cast<int>(temp_string.size()) > 0){
std::stringstream temp_ss(temp_string);
T temp;
temp_ss >> temp;
temp_vec.push_back(temp);
}
else{
rewind();
std::cout<<"Dimension error!1"<<std::endl;
return s;
}
}
if(dim * dim == static_cast<int>(temp_vec.size())){
m.data = std::move(temp_vec);
m.l = dim;
}
else{
rewind();
std::cout<<"Dimension error!2"<<std::endl;
}
}
else{
rewind();
std::cout<<"Dimension error!3"<<std::endl;
}
return s;
}
template<typename T>
bool matr_not_eq(smatrix<T> const& m1, smatrix<T> const& m2, double err){
int n=m1.dimension();
if(n!=m2.dimension() || m1.size()!=n*n || m2.size() != n*n){
return true;
}
for(int i=0; i<n*n; i++){
if(std::abs(m1[i]-m2[i])>err){
return true;
}
}
return false;
} | true |
12e675bd2465c6db2edb9894b5b85fee9df00e30 | C++ | imanisaskia/Engis-Farm-Prototype | /Farm_Product/FarmProduct.hpp | UTF-8 | 319 | 2.5625 | 3 | [] | no_license | #ifndef FARMPRODUCT_HPP
#define FARMPRODUCT_HPP
class FarmProduct {
public:
/*virtual dtor*/
virtual ~FarmProduct(){};
/*virtual function to get FarmProduct type*/
virtual int getType()=0;
/*virtual function to get FarmProduct price*/
virtual int getPrice()=0;
};
#endif
| true |
259d145662d5e6989e1d45b8e58c4afe03bfcecd | C++ | etsaf/cpp-algorithms | /dijkstra.cpp | UTF-8 | 1,766 | 2.53125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <utility>
#include <set>
#include <climits>
#include <algorithm>
#include <tuple>
using namespace std;
struct edge {
public:
int to, l;
};
const int64_t inf = numeric_limits<int64_t>::max();
int main() {
int n, start, finish;
cin >> n >> start >> finish;
vector<vector<edge>> graph(n, vector<edge>());
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
int elem;
cin >> elem;
if (elem != -1 && i != j) {
graph[i].push_back({j, elem});
}
}
}
vector<int64_t> dist(n, inf);
vector<int> prev(n, -1);
set<pair<int64_t, int>> next;
--start;
--finish;
dist[start] = 0;
next.insert({0, start});
while (!next.empty()) {
auto it = next.begin();
int curr = it->second;
next.erase(it);
for (int i = 0; i < graph[curr].size(); ++i) {
auto to = graph[curr][i].to;
auto len = graph[curr][i].l;
int64_t better = dist[curr] + len;
if (better < dist[to]) {
auto ptr = next.find({dist[to], to});
if (ptr != next.end()) {
next.erase(ptr);
}
prev[to] = curr;
dist[to] = better;
next.insert({dist[to], to});
}
}
}
if (dist[finish] == inf) {
cout << "-1\n";
} else {
vector<int> res;
int v = finish;
while (v != -1) {
res.push_back(v);
v = prev[v];
}
reverse(res.begin(), res.end());
for (auto elem : res) {
cout << elem + 1 << ' ';
}
cout << '\n';
}
} | true |
00df11ba4f926ce7816731fda4a1ace883c004ac | C++ | Abdulrahman-Khalid/Algorithmic-Toolbox-Coursera-San-Diego | /week3_greedy_algorithms/4_maximum_advertisement_revenue/dot_product.cpp | UTF-8 | 520 | 2.75 | 3 | [
"MIT"
] | permissive | #include <bits/stdc++.h>
using namespace std;
typedef vector<int> VI;
typedef long long ll;
void max_dot_product()
{
int n, x;
scanf("%d", &n);
VI a, c;
for (int i = 0; i < n; i++)
{
scanf("%d", &x);
a.push_back(x);
}
for (int i = 0; i < n; i++)
{
scanf("%d", &x);
c.push_back(x);
}
sort(a.begin(), a.end());
sort(c.begin(), c.end());
ll sum = 0;
for (int i = 0; i < n; i++)
sum += (ll)a[i] * c[i];
printf("%lld", sum);
}
int main()
{
max_dot_product();
return 0;
}
| true |
294f957be26800814f37999b0a70de8f0c046834 | C++ | SohyunDev/ImageProcessing_EquationResolver | /Color.cpp | UTF-8 | 605 | 3.234375 | 3 | [] | no_license | #include "Color.h"
// Vec3s
Color::Color(Vec3s color)
{
this->blue = color[0];
this->green = color[1];
this->red = color[2];
}
Color::Color()
{
this->blue = 255;
this->green = 255;
this->red = 255;
}
Color::~Color()
{
}
short Color::getRedColor()
{
return this->red;
}
short Color::getBlueColor()
{
return this->blue;
}
short Color::getGreenColor()
{
return this->green;
}
void Color::setRedColor(short r) {
this->red = r;
}
void Color::setBlueColor(short b) {
this->blue = b;
}
void Color::setGreenColor(short g) {
this->green = g;
}
| true |
dd5fb9b34118d2d496bc922be7829dfa235e63b7 | C++ | xuehanshuo/ref-cpp-ood | /16 装饰模式/16 装饰模式.cpp | UTF-8 | 1,722 | 2.984375 | 3 | [] | no_license | //This is a C++ program
//Designed and supported by Hodor
//High cohesion & Low coupling
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
//替代继承 动态给一个类增加功能
//——————————————————————————————————————————————————————————————————————————————————————————
class AbsHero {
public:
virtual void ShowStatus() = 0;
public:
int mHp;
int mMp;
};
class FrostMaster :public AbsHero {
public:
FrostMaster(){
this->mHp = 0;
this->mMp = 0;
}
virtual void ShowStatus() {
cout << "HP is " << this->mHp << endl
<< "MP is " << this->mMp << endl;
}
};
class AbsEquipment :public AbsHero {
public:
AbsEquipment(AbsHero* hero):hero(hero){}
virtual void ShowStatus() {};
public:
AbsHero* hero;
};
class Stick :public AbsEquipment {
public:
Stick(AbsHero* hero):AbsEquipment(hero){}
//新加的功能,用父类指针承接,父类指针不能延申调用,所以应在virtual中自己调用
void PutOn() {
this->mHp = this->hero->mHp;
this->mMp = this->hero->mMp+1000;
delete this->hero;
}
virtual void ShowStatus() {
PutOn();
cout << "HP is " << this->mHp << endl
<< "MP is " << this->mMp << endl;
}
};
void case01() {
AbsHero* hero = new FrostMaster;
hero->ShowStatus();
cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << endl;
hero = new Stick(hero);
hero->ShowStatus();
}
int main() {
case01();
return 0;
}
/*
*
*
*
*
*/
| true |
442117abd82480fecabdef46a07aa6dfb9667deb | C++ | SandeepMaithani/DS_and_Algo_practice | /DS/Graphs_DS/Topological Sort Algorithm with DFS.cpp | UTF-8 | 1,068 | 3.1875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
#define MOD 1000000007
#define endl "\n"
typedef long long int ll;
void topologicalSortHelper(vector<vector<int>>& graph, vector<bool>& visited, stack<int>& st, int source) {
visited[source] = true;
for (auto neighbour : graph[source]) {
if (visited[neighbour] == false) {
topologicalSortHelper(graph, visited, st, neighbour);
}
}
st.push(source);
}
void topologicalSort(vector<vector<int>>& graph, vector<bool>& visited) {
stack<int>st;
for (int vertex = 0; vertex < graph.size(); vertex++) {
if (visited[vertex] == false) {
topologicalSortHelper(graph, visited, st, vertex);
}
}
while (!st.empty()) {
cout << st.top() << " ";
st.pop();
}
}
int main() {
int vertexCount, edgeCount;
cin >> vertexCount >> edgeCount;
vector<vector<int>>graph(vertexCount);
vector<bool>visited(vertexCount, false);
for (int i = 0; i < edgeCount; i++) {
int vertex1, vertex2;
cin >> vertex1 >> vertex2;
graph[vertex1].push_back(vertex2);
}
topologicalSort(graph, visited);
return 0;
}
| true |
b02971dbf1cab9093bf6c42d56951fe11b0c2f3a | C++ | MichJadams/btr | /Assembly/SsePackedIntegerArithmatic/SsePackedIntegerArithmatic/SsePackedIntegerArithmatic.cpp | UTF-8 | 1,078 | 2.65625 | 3 | [] | no_license | #include "pch.h"
#include <iostream>
#include "XmmVal.h"
#include <math.h>
extern "C" void SsePackedInt16_add(const XmmVal * a,const XmmVal *b, XmmVal c[2]);
extern "C" void SsePackedInt32_sub(const XmmVal * a, const XmmVal *b, XmmVal *c);
extern "C" void SsePackedInt32_mul(const XmmVal * a, const XmmVal *b, XmmVal c[2]);
int main()
{
_declspec(align(16)) XmmVal a;
_declspec(align(16)) XmmVal b;
_declspec(align(16)) XmmVal c[2];
int count;
char buff[256];
a.r32[0] = 10;
a.r32[1] = 10;
a.r32[2] = 10;
a.r32[3] = 10;
b.r32[0] = 10;
b.r32[1] = 30;
b.r32[2] = 40;
b.r32[3] = 50;
SsePackedInt16_add(&a, &b, c);
printf("result: \n");
printf("c: %s\n", c[0].ToString_r32(buff, sizeof(buff)));
printf("c: %s\n", c[1].ToString_r32(buff, sizeof(buff)));
printf("c: %s\n", c[2].ToString_r32(buff, sizeof(buff)));
printf("c: %s\n", c[3].ToString_r32(buff, sizeof(buff)));
printf("c: %s\n", c[4].ToString_r32(buff, sizeof(buff)));
printf("c: %s\n", c[5].ToString_r32(buff, sizeof(buff)));
printf("c: %s\n", c[6].ToString_r32(buff, sizeof(buff)));
}
| true |
53a4c427163812ed7e89bafae5c9a7ceffb13248 | C++ | pavelkryukov/puzzles | /sudoku/source/main.cpp | UTF-8 | 997 | 3.03125 | 3 | [
"MIT"
] | permissive | /*
* main.cpp
*
* Sudoku solver main program
*
* Kryukov Pavel (C) 2011
*/
#include <ctime>
#include <iostream>
#include "sudoku.h"
int main(int argc, char* argv[]) {
if (argc != 2) {
std::cout << "Syntax error" << std::endl;
return -1;
}
std::ifstream inputfile;
inputfile.open(argv[1]);
Sudoku sudoku(3,3,inputfile);
inputfile.close();
std::cout << sudoku;
clock_t t0 = std::clock();
sudoku.solve();
std::cout << "Time: " << (float)(std::clock() - t0) / CLOCKS_PER_SEC << " s" << std::endl;
switch (sudoku.getStatus()) {
case Sudoku::INCORRECT:
std::cout << "Incorrect" << std::endl;
break;
case Sudoku::UNSOLVABLE:
std::cout << "Unsolvable" << std::endl;
break;
case Sudoku::SOLVED:
std::cout << sudoku;
break;
default:
std::cout << "Unrecognized error" << std::endl;
}
// delete sudoku;
return 0;
}
| true |
08bab62c15d687171249b45fd57f957346d76721 | C++ | lojpark/CodeForces | /Round #568 Div. 2/C2 - Exam in BerSU (hard version).cpp | UTF-8 | 972 | 2.546875 | 3 | [] | no_license | #include <iostream>
#include <queue>
#include <functional>
using namespace std;
int n, m;
int t[200010];
priority_queue<int, vector<int>, less<int>> pq_max;
priority_queue<int, vector<int>, greater<int>> pq_min;
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
cin >> n >> m;
for (int i = 1; i <= n; i++)
cin >> t[i];
int sum = 0, fail_count = 0;
for (int i = 1; i <= n; i++) {
sum += t[i];
while (!pq_max.empty() && !pq_min.empty() && pq_max.top() > pq_min.top()) {
sum -= pq_max.top();
pq_min.push(pq_max.top());
pq_max.pop();
sum += pq_min.top();
pq_max.push(pq_min.top());
pq_min.pop();
while (!pq_min.empty() && sum + pq_min.top() <= m) {
fail_count--;
sum += pq_min.top();
pq_max.push(pq_min.top());
pq_min.pop();
}
}
while (sum > m) {
fail_count++;
sum -= pq_max.top();
pq_min.push(pq_max.top());
pq_max.pop();
}
pq_max.push(t[i]);
cout << fail_count << " ";
}
return 0;
} | true |
dc1bd40da93efb48692c356c458560d9e1e869fe | C++ | dickynovanto1103/Sliding-Window-Protocol-Simulation | /src/recvfile.cpp | UTF-8 | 4,555 | 2.796875 | 3 | [] | no_license | #include "message.cpp"
#include "packet_validator.cpp"
#include "response.cpp"
#include "window.cpp"
#include <arpa/inet.h>
#include <fstream>
#include <iostream>
#include <netinet/in.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <unistd.h>
#define FILE_ENDING 0x26
#define SLEEP_TIME 100000
using namespace std;
string filename;
ReceiverWindow receiverWindow(256);
ReceiverBuffer receiverBuffer(256);
sockaddr_in senderAddress;
int senderAddressSize = sizeof(senderAddress);
int sock;
bool pushToBuffer(unsigned char character, int seqnum,
ReceiverBuffer &receiverBuffer) {
if (receiverBuffer.size == receiverBuffer.maxSize)
return false;
if (receiverBuffer.size == 0) {
receiverBuffer.front = 0;
}
receiverBuffer.back = (receiverBuffer.back + 1) % receiverBuffer.maxSize;
receiverBuffer.data[receiverBuffer.back] = character;
receiverBuffer.seqnum[receiverBuffer.back] = seqnum;
receiverBuffer.size++;
return true;
}
void *writeFromBuffer(void *) {
while (true) {
if (receiverBuffer.size == 0)
continue;
ofstream outputFile;
outputFile.open(filename, ios_base::app);
unsigned char character = receiverBuffer.data[receiverBuffer.front];
outputFile << character;
outputFile.close();
receiverWindow.isReceived[receiverBuffer.seqnum[receiverBuffer.front]] =
false;
receiverBuffer.front =
(receiverBuffer.front + 1) % receiverBuffer.maxSize;
receiverBuffer.size--;
if (receiverBuffer.size == 0) {
receiverBuffer.front = -1;
receiverBuffer.back = -1;
}
usleep(SLEEP_TIME);
}
}
void sendResponse(Response response, int sock, struct sockaddr_in senderAddress,
int senderAddressSize) {
if (sendto(sock, &response, sizeof(Response), 0,
(struct sockaddr *)&senderAddress, senderAddressSize) == -1) {
exit(EXIT_FAILURE);
}
}
int main(int argc, char *argv[]) {
// receive arguments
if (argc < 5) {
exit(EXIT_FAILURE);
}
filename = argv[1];
int windowsize = atoi(argv[2]);
int buffersize = atoi(argv[3]);
int port = atoi(argv[4]);
// open socket
sock = socket(PF_INET, SOCK_DGRAM, 0);
if (sock < 0) {
exit(EXIT_FAILURE);
}
// initialize receiver address
sockaddr_in receiverAddress;
receiverAddress.sin_family = AF_INET;
receiverAddress.sin_addr.s_addr = htonl(INADDR_ANY);
receiverAddress.sin_port = htons(port);
// bind receiver address to socket
if (bind(sock, (sockaddr *)&receiverAddress, sizeof(receiverAddress)) < 0) {
exit(EXIT_FAILURE);
}
// empty output file
ofstream outputFile;
outputFile.open(filename, ios::out | ios::trunc);
// create child thread for receiving message
pthread_t child_thread;
if (pthread_create(&child_thread, NULL, &writeFromBuffer, NULL) < 0) {
exit(EXIT_FAILURE);
}
// send response after receiving packet
Message message;
while (true) {
if (recvfrom(sock, &message, sizeof(Message), 0,
(struct sockaddr *)&senderAddress,
(socklen_t *)&senderAddressSize) == -1) {
exit(EXIT_FAILURE);
}
PacketValidator validator;
if (validator.isPacketValid(message) &&
receiverBuffer.size < receiverWindow.maxSize) {
unsigned char data = message.data;
receiverWindow.data[message.seqnum] = data;
if (!receiverWindow.isReceived[message.seqnum]) {
if (pushToBuffer(receiverWindow.data[message.seqnum],
message.seqnum, receiverBuffer)) {
receiverWindow.isReceived[message.seqnum] = true;
}
}
Response response(message.seqnum, windowsize, message.checksum);
response.ack = ACK;
sendResponse(response, sock, senderAddress, senderAddressSize);
if (data == FILE_ENDING)
break;
} else if (receiverBuffer.size >= receiverWindow.maxSize) {
} else {
Response response(message.seqnum, windowsize, message.checksum);
response.ack = NAK;
sendResponse(response, sock, senderAddress, senderAddressSize);
}
while (receiverBuffer.size > 0) {
// waiting for receiverWindow to be empty
}
}
return 0;
}
| true |
e6aa05ba3e2a775d70ead3a0df8fd5a5c147a877 | C++ | haruka-mt/paiza | /Rank_C/C023.cpp | UTF-8 | 563 | 2.765625 | 3 | [] | no_license | #include <iostream>
#include <array>
#include <algorithm>
using namespace std;
int main(void)
{
int n;
array<int, 6> winNum;
int myNum;
int i, j;
for (j = 0; j < 6; ++j)
{
cin >> winNum[j];
}
cin >> n;
int sum;
for (i = 0; i < n; ++i)
{
sum = 0;
for (j = 0; j < 6; ++j)
{
cin >> myNum;
if(find(winNum.begin(), winNum.end(), myNum) != winNum.end())
{
sum++;
}
}
cout << sum << endl;
}
return 0;
} | true |
2d496bcf4e3019d5271238e9e8efa9e6deaba897 | C++ | RhedensSpaceEngineering/RMGS | /Arduino/Core/SD_Card.ino | UTF-8 | 2,638 | 3.015625 | 3 | [] | no_license | /*
* SD_Card
*
* Connects the MicroSD to the arduino so it can be read out.
* Adds SD_Card, sdCardOpenFile, sdCardPrint, sdCardCloseFile\
*
* Pin layout:
* MicroSD --------- Arduino
* VCC ------------- 5V
* CS ------------- D10
* DI ------------- D11
* SCK ------------- D13
* D0 ------------- D12
* GND ------------- GND
*
* Created by Tim Hiemstra & Arend-Jan Hengst, RMSG, 12-11-2017
*
* Hookup Guide: https://learn.sparkfun.com/tutorials/microsd-breakout-with-level-shifter-hookup-guide, https://learn.adafruit.com/adafruit-micro-sd-breakout-board-card-tutorial/wiring
* Library: Inbuild Arduino SD library: https://www.arduino.cc/en/Reference/SD
*/
#include <SPI.h> // Load SPI library
#include <SD.h> // Load SD library
// Define constant variables
const byte CHIP_SELECT = 10;
const String FILE_NAME = "log.txt";
File dataFile;
/*
* SD_Card
*
* Tries to initialise a connection with the SD-card,
* when SD-card cannot be initialised,
* the program goes in an infinite loop and tells to RESET.
*
*/
void SD_Card() {
Serial.println("SD Card Called");
// check if SD-card can be initialised
while (!SD.begin(CHIP_SELECT)) {
delay(1000); // wait
Serial.println("SD Card initialization failed!");
displayDraw("3D0", 1); // notify that the SD-Card hasn't been initialised
delay(sleep); // wait
}
delay(1000); // wait
//Serial.println("SD Card Display");
displayDraw("1D0", 1); // notify that the SD-Card has been initialised
//Serial.println("SD Card Initialised");
delay(sleep); // wait
}
/*
* sdCaredOpenFile
*
* opens the standard file, as declared in FILE_NAME
* Tries 1 more time when failed to open file.
*
* return boolean True if the file has been opened
* Flase if the file hasn't been opened
*/
boolean sdCardOpenFile() {
dataFile = SD.open(FILE_NAME, FILE_WRITE); // opening file
// check if file is opened
if (!dataFile) {
// notify
displayDraw("2D1", 0);
// wait
delay(1000);
// try again once
dataFile = SD.open(FILE_NAME, FILE_WRITE); // opening file
// Check if file opened
if (!dataFile) {
// file didn't open, so return false
return false;
}
}
// file openend, so return true
return true;
}
/*
* sdCardPrint
*
* Put a text/int/double/float/long/boolean in file
*
* String/int/double/float/long/boolean input String that needs to be saved
*/
template <class sdCardData> void sdCardPrint(sdCardData input) {
dataFile.println(input);
}
/*
* sdCardCloseFile
*
* closes file opened by sdCardOpenFile()
*/
void sdCardCloseFile() {
dataFile.close();
}
| true |
ec32653280a45b7dc5da1b8cfff8bf85dc5081b1 | C++ | hoangnamwar/data-structure | /first_test/list.h | UTF-8 | 561 | 3.28125 | 3 | [] | no_license | #ifndef LIST_H
#define LIST_H
#include "node.h"
class List
{
private:
Node* head;
public:
List()
{
head = 0;
}
void add(int value)
{
Node* newNode = new Node;
newNode->data = value;
newNode->next = 0;
if (head == 0)
{
head = newNode;
}
else
{
Node* shipper = head;
while (shipper->next != 0)
{
shipper = shipper->next;
}
shipper->next = newNode;
}
}
int get(int pos) const
{
Node* shipper = head;
for (int i = 1; i < pos; i++)
{
shipper = shipper->next;
}
return shipper->data;
}
};
#endif
| true |
a22d455426be4e750dd8e64a9fcd8f7468441a84 | C++ | gsmnit/coding_for_interview | /c/c++/str_property.cpp | UTF-8 | 296 | 2.578125 | 3 | [
"MIT"
] | permissive | #include<iostream>
using namespace std;
int main(int argc, char const *argv[])
{ string str1 = "praising";
string char1 = str1.substr(1);
cout << char1 << endl;
string substr1 = str1.substr(1,5);
cout << substr1 << endl;
cout << str1[0] << endl;
return 0;
}
| true |
33b5134ecfa304833c111699236cbae43b23222f | C++ | DoobleD/Air | /Air/src/OS/win32/Screen.cpp | UTF-8 | 3,161 | 2.671875 | 3 | [] | no_license | #include "OS/Screen.hpp"
using namespace air::os;
Screen::Screen(void)
{
m_threadRunning = false;
}
Screen::~Screen(void)
{
if (m_threadRunning)
{
m_threadRunning = false;
Wait();
}
}
int Screen::getResX(void)
{
RECT rc;
GetWindowRect(GetDesktopWindow(), &rc);
return rc.right;
}
int Screen::getResY(void)
{
RECT rc;
GetWindowRect(GetDesktopWindow(), &rc);
return rc.bottom;
}
void Screen::clear(void)
{
m_mutex.Lock();
std::list<Rectangle>::iterator begin = m_rectangles.begin();
std::list<Rectangle>::iterator end = m_rectangles.end();
while (begin != end)
{
begin->erased = true;
++begin;
}
m_mutex.Unlock();
}
void Screen::drawRectangle(int x, int y,
int sizeX, int sizeY,
const air::Color & color)
{
if (x >= 0 && x < getResX() &&
y >= 0 && y < getResY())
{
Rectangle rect;
rect.coord.left = x;
rect.coord.top = y;
rect.coord.right = x + sizeX;
rect.coord.bottom = y + sizeY;
rect.color = RGB(color.r, color.g, color.b);
m_mutex.Lock();
m_rectangles.push_back(rect);
m_mutex.Unlock();
}
}
void Screen::display(void)
{
if (!m_threadRunning)
{
m_threadRunning = true;
Launch();
}
}
void Screen::restoreOSScreen(void)
{
// Redraw modified zones of screen
std::list<Rectangle>::iterator begin = m_rectangles.begin();
std::list<Rectangle>::iterator end = m_rectangles.end();
while (begin != end)
{
RedrawWindow(0, &(begin->coord), 0, RDW_INVALIDATE | RDW_ALLCHILDREN);
if (begin->erased)
begin = m_rectangles.erase(begin);
else
++begin;
}
}
void Screen::paintRectangles(void)
{
std::list<Rectangle>::iterator begin = m_rectangles.begin();
std::list<Rectangle>::iterator end = m_rectangles.end();
HBRUSH brush;
while (begin != end)
{
brush = CreateSolidBrush(begin->color);
FillRect(m_memDC, &(begin->coord), brush);
BitBlt(m_screenDC, begin->coord.left, begin->coord.top,
begin->coord.right - begin->coord.left,
begin->coord.bottom - begin->coord.top,
m_memDC, begin->coord.left, begin->coord.top, SRCCOPY);
DeleteObject(brush);
++begin;
}
}
void Screen::paintAll(void)
{
paintRectangles();
// In future: paintCircles, paintPoints, etc
}
void Screen::destroyGDIComponents(void)
{
SelectObject(m_memDC, m_bmapHandle);
DeleteObject(m_bmap);
DeleteDC(m_memDC);
ReleaseDC(0, m_screenDC);
}
void Screen::initializeGDIComponents(void)
{
m_screenDC = GetDC(0);
m_memDC = CreateCompatibleDC(m_screenDC);
m_bmap = CreateCompatibleBitmap(m_screenDC, getResX(), getResY());
m_bmapHandle = SelectObject(m_memDC, m_bmap);
}
void Screen::Run(void)
{
sf::Clock clock;
float fps = 1.f / _FPS;
initializeGDIComponents();
clock.Reset();
while (m_threadRunning)
{
clock.Reset();
m_mutex.Lock();
restoreOSScreen();
paintAll();
m_mutex.Unlock();
sf::Sleep(fps - clock.GetElapsedTime());
}
destroyGDIComponents();
}
| true |
c9d447f0e965fef222c050b98ccfa0943d8eb328 | C++ | vinitjindal/Data_Structure | /doubly linked list_4a.cpp | UTF-8 | 2,081 | 3.078125 | 3 | [] | no_license | #include<iostream>
using namespace std;
struct node{
struct node *pre;
int data;
struct node *next;
};
int main(){
struct node * n;
struct node *start3,*start4;
struct node *start2;
struct node *start1;
struct node *ptr1;
struct node *ptr;
char flag,flag1,flag2;
int num;
struct node * start=NULL;
cout<<"you want to add a node"<<endl;
cin>>flag;
if(flag=='y'){
n=new(struct node);
n->pre=start;
cin>>n->data;
n->next=start;
start=n;
ptr=n;
}do{
cout<<"want to creat a node.."<<endl;
cin>>flag;
if(flag=='y'){
n=new(struct node);
n->pre=NULL;
cin>>n->data;
n->next=start;
start->pre=n;
start=n;
}
}while(flag!='n');
start3=start;
start2=start;
start4=start;
start1=start;
while(start!=NULL){
cout<<start->data<<endl;
start=start->next;
}
cout<<"you want to add a node in end or middle";
cin>>flag;
if(flag=='e'){
n=new(struct node);
n->pre=ptr;
cin>>n->data;
n->next=NULL;
ptr->next=n;
ptr1=n;
cout<<"do you want to continue.."<<endl;
cin>>flag1;
do{
if(flag1=='y'){
n=new(struct node);
n->pre=ptr1;
cin>>n->data;
n->next=NULL;
ptr1->next=n;
cout<<"do you want to continue"<<endl;
cin>>flag1;
}
}while(flag1!='n');
while(start1!=NULL){
cout<<start1->data;
start1=start1->next;
}
}else if(flag=='m'){
cout<<"after which element you want to add"<<endl;
cin>>num;
while(start2!=NULL){
if(start2->data==num){
n=new(struct node);
n->pre=start2;
cin>>n->data;
n->next=start2->next;
start2->next=n;
break;
}
start2=start2->next;
}
cout<<"do you want to delete the element if yes press 'y' else 'n'";
cin>>flag2;
if(flag2=='y'){
while(start4!=NULL){
if(start4->data==num){
start2=start4->pre;
start2->next=start4->next;
delete(start4);
break;
}
start4=start4->next;
}
}
while(start3!=NULL){
cout<<start3->data;
start3=start3->next;
}
}
return 0;
}
| true |
a7934db5c4c73571c8c6a8598de2570ea073c0cc | C++ | rajataneja101/leetcode_August_challenge | /Day_27(Right_insert_interval)/Solution.cpp | UTF-8 | 831 | 2.8125 | 3 | [] | no_license | class Solution {
public:
vector<int> findRightInterval(vector<vector<int>>& intervals) {
multimap<int, int> starttable;
multimap<int, int> endtable;
int len = intervals.size();
for (int i = 0; i < len; ++i)
{
starttable.insert(pair<int,int>(intervals[i][0], i));
endtable.insert(pair<int, int>(intervals[i][1], i));
}
vector<int> result(len);
multimap<int, int>::iterator itstart = starttable.begin();
for (multimap<int, int>::iterator it = endtable.begin(); it != endtable.end(); ++it)
{
int val = it->first;
if (itstart != starttable.end())
{
while (itstart != starttable.end() && itstart->first < val)
++itstart;
if (itstart == starttable.end())
result[it->second] = -1;
else
result[it->second] = itstart->second;
}
else {
result[it->second] = -1;
}
}
return result;
}
}; | true |
b838b4418d948385887ee79ece0728740310f43a | C++ | ehnryx/acm | /wf2016/h.cpp | UTF-8 | 8,591 | 2.84375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
#define _USE_MATH_DEFINES
typedef double ld;
//typedef complex<ld> pt;
struct pt {
ld x, y;
pt(const ld& _x=0, const ld& _y=0): x(_x), y(_y) {}
pt operator * (const pt& o) const { return pt(x*o.x - y*o.y, x*o.y + y*o.x); }
pt operator - () const { return pt(-x, -y); }
pt operator - (const pt& o) const { return pt(x-o.x, y-o.y); };
pt operator + (const pt& o) const { return pt(x+o.x, y+o.y); };
pt operator / (const ld& c) const { return pt(x/c, y/c); }
ld real() const { return x; }
ld imag() const { return y; }
};
ld real(const pt& a) { return a.x; }
ld imag(const pt& a) { return a.y; }
pt conj(const pt& a) { return pt(a.x, -a.y); }
ld abs(const pt& a) { return sqrt(a.x*a.x + a.y*a.y); }
pt operator * (const ld& c, const pt& a) { return pt(c*a.x, c*a.y); }
const char nl = '\n';
const ld EPS = 1e-9;
ld cp(const pt& a, const pt& b) {
return imag(conj(a) * b);
}
ld dp(const pt& a, const pt& b) {
return real(conj(a) * b);
}
ld area(const vector<pt>& p) {
int n = p.size();
ld s = 0;
for(int j=n-1, i=0; i<n; j=i++) {
s += cp(p[j], p[i]);
}
return s;
}
vector<pt> read() {
int n;
cin >> n;
vector<pt> out;
for(int i=0; i<n; i++) {
int x, y;
cin >> x >> y;
out.push_back(pt(x, y));
}
if(area(out) < 0) {
reverse(out.begin(), out.end());
}
return out;
}
vector<pt> reflect(const vector<pt>& p) {
vector<pt> out;
for(const pt& v : p) {
out.push_back(-v);
}
return out;
}
vector<pt> orient(const vector<pt>& p, int e) {
pt base = p[e];
pt dir = p[(e+1)%p.size()] - p[e];
dir = conj(dir / abs(dir));
vector<pt> out;
for(const pt& v : p) {
out.push_back((v - base) * dir);
}
return out;
}
enum {
END_BAD,
START_FRONT,
END_FRONT,
START_ALL,
END_ALL,
START_BACK,
END_BACK,
START_BAD,
};
struct Event {
ld x;
int t;
ld v;
Event(const ld& _x, int _t, const ld& _v=0): x(_x), t(_t), v(_v) {}
bool operator < (const Event& o) const {
if(x != o.x) return x < o.x;
return t < o.t;
}
};
pt get_point(const pt& a, const pt& b, ld y) {
pt v = (y - a.imag()) / (b.imag() - a.imag()) * (b-a);
return a + v;
}
pair<ld,ld> get_range(pt a, pt b, pt c, pt d) {
if(a.imag() > b.imag()) swap(a, b);
if(c.imag() > d.imag()) swap(c, d);
ld s = max(a.imag(), c.imag());
ld t = min(b.imag(), d.imag());
return make_pair(s, t);
}
void intersect_edges(const pt& v, const pt& w, const vector<pt>& p, vector<Event>& ev) {
int n = p.size();
for(int i=0; i<n; i++) {
const pt& a = p[i];
const pt& b = p[(i+1)%n];
auto [s, t] = get_range(v, w, a, b);
if(s > t + EPS) continue; // no intersection
if(abs(cp(a-b, v-w)) < EPS) {
// parallel
if(dp(a-b, v-w) > 0) continue; // wrong orientation
if(abs(a.imag() - b.imag()) < EPS) {
// horizontal
ld lfix = min(a.real(), b.real());
ld rfix = max(a.real(), b.real());
ld lmov = min(v.real(), w.real());
ld rmov = max(v.real(), w.real());
ld left = lfix - rmov;
ld right = rfix - lmov;
ld front = min(lfix - lmov, rfix - rmov);
ld back = max(lfix - lmov, rfix - rmov);
ld overlap = min(rfix - lfix, rmov - lmov);
ev.push_back(Event(left, START_FRONT, left));
ev.push_back(Event(front, END_FRONT, left));
ev.push_back(Event(front, START_ALL, overlap));
ev.push_back(Event(back, END_ALL, overlap));
ev.push_back(Event(back, START_BACK, right));
ev.push_back(Event(right, END_BACK, right));
}
else {
// not horizontal
pt u = get_point(a, b, s);
ld x = u.real() - get_point(v, w, s).real();
ld overlap = abs(u - get_point(a, b, t));
ev.push_back(Event(x - EPS, START_ALL, overlap));
ev.push_back(Event(x + EPS, END_ALL, overlap));
}
}
else {
// not parallel
if(abs(a.imag() - b.imag()) < EPS) {
// ab is horizontal
if(cp(b-a, v-a) < EPS && cp(b-a, w-a) < EPS) continue; // all on the good side
pt u = get_point(v, w, a.imag());
ld left = min(a.real(), b.real()) - u.real();
ld right = max(a.real(), b.real()) - u.real();
ev.push_back(Event(left + EPS, START_BAD));
ev.push_back(Event(right - EPS, END_BAD));
}
else if(abs(v.imag() - w.imag()) < EPS) {
// vw is horizontal
if(cp(w-v, a-v) < EPS && cp(w-v, b-v) < EPS) continue; // all on the good side
pt c = get_point(a, b, v.imag());
ld left = c.real() - max(v.real(), w.real());
ld right = c.real() - min(v.real(), w.real());
ev.push_back(Event(left + EPS, START_BAD));
ev.push_back(Event(right - EPS, END_BAD));
}
else {
// neither is horizontal
ld left = get_point(a, b, s).real() - get_point(v, w, s).real();
ld right = get_point(a, b, t).real() - get_point(v, w, t).real();
if(left > right) swap(left, right);
if(abs(left - right) < EPS) continue;
ev.push_back(Event(left + EPS, START_BAD));
ev.push_back(Event(right - EPS, END_BAD));
}
}
}
}
void intersect_points(const pt& v, const vector<pt>& p, vector<Event>& ev) {
int n = p.size();
ld y = v.imag();
for(int i=0; i<n; i++) {
const pt& a = p[i];
const pt& b = p[(i+1)%n];
const pt& c = p[(i+2)%n];
ld s = min(a.imag(), b.imag());
ld t = max(a.imag(), b.imag());
bool push_start = false;
bool push_end = false;
ld x = b.real() - v.real();
if(s + EPS < y && y < t - EPS) {
// intersects edge
x = get_point(a, b, y).real() - v.real();
if(a.imag() < b.imag()) {
push_end = true; // up edge -> end
} else {
push_start = true; // down edge -> start
}
}
else if(abs(b.imag() - y) < EPS) {
// intersects vertex
s = min(a.imag(), c.imag());
t = max(a.imag(), c.imag());
if(s + EPS < y && y < t - EPS) {
// hits normal turn
if(a.imag() < c.imag()) {
push_end = true;
} else {
push_start = true;
}
}
else if(cp(a-b, c-b) > 0) {
// should be concave
if(abs(s - y) < EPS || abs(t - y) < EPS) {
// orthogonal
if(a.imag() < c.imag()) {
push_end = true;
} else {
push_start = true;
}
} else {
// v shaped
push_end = true;
push_start = true;
}
}
}
if(push_start) {
ev.push_back(Event(x + EPS, START_BAD));
}
if(push_end) {
ev.push_back(Event(x - EPS, END_BAD));
}
}
}
ld sweep(const vector<pt>& p, const vector<pt>& q) {
int n = p.size();
int m = q.size();
vector<pt> ref_p = reflect(p);
vector<pt> ref_q = reflect(q);
vector<Event> ev;
for(int i=0; i<n; i++) {
intersect_edges(p[i], p[(i+1)%n], q, ev);
intersect_points(p[i], q, ev);
intersect_points((p[i]+p[(i+1)%n])/(ld)2, q, ev);
}
for(int j=0; j<m; j++) {
intersect_points(ref_q[j], ref_p, ev);
intersect_points((ref_q[j]+ref_q[(j+1)%m])/(ld)2, ref_p, ev);
}
sort(ev.begin(), ev.end());
ld best = 0;
ld all = 0;
ld front = 0;
ld back = 0;
int fcnt = 0;
int bcnt = 0;
int bad = 0;
for(const auto& [x, t, v] : ev) {
if(!bad) {
ld cur = all + (fcnt*x - front) + (back - bcnt*x);
best = max(best, cur);
}
if(t == START_FRONT) {
fcnt++;
front += v;
} else if(t == END_FRONT) {
fcnt--;
front -= v;
} else if(t == START_ALL) {
all += v;
} else if(t == END_ALL) {
all -= v;
} else if(t == START_BACK) {
bcnt++;
back += v;
} else if(t == END_BACK) {
bcnt--;
back -= v;
} else if(t == START_BAD) {
bad++;
} else { // t == END_BAD
bad--;
}
if(!bad) {
ld cur = all + (fcnt*x - front) + (back - bcnt*x);
best = max(best, cur);
}
}
//assert(bad == 0);
//assert(fcnt == 0);
//assert(bcnt == 0);
//assert(abs(front) < EPS);
//assert(abs(back) < EPS);
return best;
}
int main() {
ios::sync_with_stdio(0); cin.tie(0);
cout << fixed << setprecision(10);
vector<pt> p = read();
vector<pt> q = read();
int n = p.size();
int m = q.size();
ld ans = 0;
for(int i=0; i<n; i++) {
vector<pt> rotp = orient(p, i);
for(int j=0; j<m; j++) {
vector<pt> rotq = reflect(orient(q, j));
ans = max(ans, sweep(rotp, rotq));
}
}
cout << ans << nl;
return 0;
}
| true |
d32c28f292567bd887d39603dc2ebf5ea5cd9671 | C++ | webturing/ACM-1 | /按 OJ 分类/51Nod/f-51Nod-1552-白兰地定位系统/f-51Nod-1552-白兰地定位系统/main.cpp | UTF-8 | 1,574 | 2.546875 | 3 | [] | no_license | //
// main.cpp
// f-51Nod-1552-白兰地定位系统
//
// Created by ZYJ on 2017/7/31.
// Copyright ? 2017年 ZYJ. All rights reserved.
//
#include <cstdio>
#include <iostream>
using namespace std;
typedef long long ll;
const int MAXN = 2e5 + 10;
const ll INF = 0x3f3f3f3f3f3f3f3f;
int n, m;
ll a[MAXN];
ll b[MAXN];
template <class T>
inline void scan_d(T &ret)
{
char c;
ret = 0;
while ((c = getchar()) < '0' || c > '9');
while (c >= '0' && c <= '9')
{
ret = ret * 10 + (c - '0'), c = getchar();
}
}
int main()
{
scan_d(n);
for (int i = 1; i <= n; i++)
{
scan_d(a[i]);
}
scan_d(m);
int x;
for (int i = 1; i <= m; i++)
{
scan_d(x);
b[x]++;
if (x == 1 || x == n)
{
b[x]++;
}
}
ll mx = 0, mn = INF;
for (int i = 1; i <= n; i++)
{
mx = max(mx, b[i]);
mn = min(mn, b[i]);
}
if (mn == mx)
{
int flag = 0;
for (int i = 1; i <= n - 2; i++)
{
if (a[i + 1] - a[i] != a[i + 2] - a[i + 1])
{
flag = 1;
break;
}
}
if (flag)
{
puts("-1");
}
else
{
printf("%lld", (a[n] - a[1]) * mn - (a[2] - a[1]));
}
}
else
{
ll ans = 0;
for (int i = 2; i <= n; i++)
{
ans += (a[i] - a[i - 1]) * min(b[i], b[i - 1]);
}
cout << ans << endl;
}
return 0;
}
| true |
23313aa6cf0e49dddcf7271b901db3162618e9b0 | C++ | dduynam/tutorial | /C++/study/algorithm/sort/src/quicksort.cpp | UTF-8 | 1,206 | 4.0625 | 4 | [] | no_license | #include "../lib/quicksort.h"
void swap(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
/* The partition function
1. Take the last element as pivot
2. Place the pivot to the correct position by comparing
3. Move the smaller value to the left
4. Move the greater value to the right
Note: low --> starting index ; high --> ending index ; return the pivot index
*/
int partition(std::vector<int> &_arr, int low, int high)
{
int pivot = _arr[high];
int i = low - 1; // idex of the smaller element
for (int j = low; j < high; j++)
{
if (_arr[j] <= pivot)
{
i++;
swap(_arr[i], _arr[j]);
}
}
swap(_arr[i + 1], _arr[high]);
return (i + 1);
}
void displayQuickSort(std::vector<int> &_arr)
{
std::cout << "QuickSortArray: ";
for (int i = 0; i < _arr.size(); i++)
{
std::cout << _arr[i] << " ";
}
std::cout << std::endl;
}
void quickSort(std::vector<int> &arr, int low, int high)
{
if (low < high)
{
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
// 4 8 7 3 5 0 3 4
// 4 3 0 3 4 7 8 5 | true |
4949dc5261e80840641eda52083fa0f7d6e6cd51 | C++ | Mohammed-Shoaib/Coding-Problems | /HackerRank/Algorithms/Easy/E0090.cpp | UTF-8 | 785 | 3.15625 | 3 | [
"MIT"
] | permissive | /*
Problem Statement: https://www.hackerrank.com/challenges/largest-permutation/problem
*/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> largestPermutation(int n, int k, vector<int> arr) {
vector<int> sorted(arr);
sort(sorted.rbegin(), sorted.rend());
for (int j, i = 0; k > 0; k--, i++) {
while (i < n && sorted[i] == arr[i])
i++;
if (i == n)
break;
j = distance(arr.begin(), find(arr.begin() + i, arr.end(), sorted[i]));
swap(arr[i], arr[j]);
}
return arr;
}
int main() {
int n, k;
cin >> n >> k;
vector<int> arr(n), permutation;
for (int i = 0; i < n; i++)
cin >> arr[i];
permutation = largestPermutation(n, k, arr);
for (int i = 0; i < n; i++)
cout << permutation[i] << " ";
cout << endl;
return 0;
} | true |
266cbda3eb0959f3fc2ac843b0a8c593e349eea8 | C++ | pkc232/OperatingSystemLab | /Cpu_Scheduling/SJF.cpp | UTF-8 | 372 | 2.515625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main(){
int n,i,j;
cout<<"Enter the no of processes\n";
cin>>n;
vector<pair<int,int> >tim;
int x;
for(i=0;i<n;i++)
{
cin>>x;
tim.push_back(make_pair(x,i+1));
}
sort(tim.begin(),tim.end());
int t=0;
for(i=0;i<n;i++){
cout<<tim[i].second<<" :"<<t<<" "<<t+tim[i].first<<endl;
t+=tim[i].first;
}
} | true |
6c0250a7aca056b463f704aa2ecae864b3d635d8 | C++ | schafar92/antlr-cpp | /antlr.cpp | UTF-8 | 2,706 | 2.515625 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include "antlr4-runtime/antlr4-runtime.h"
#include "antlr4-runtime/CPP14Lexer.h"
#include "antlr4-runtime/CPP14Parser.h"
#include "ImageVisitor.h"
#include <experimental/filesystem>
#include "csv-writer/include/CSVWriter.h"
using namespace std;
using namespace antlr4;
namespace fs = std::experimental::filesystem;
int main(int argc, const char** argv) {
// Name the command line args
const char* cpp_file_directory = argv[1];
const char* output_file = argv[2];
const char* features_type = argv[3];
// Open stream to a csv file which will contain the results
ofstream csvfile;
csvfile.open(((string) "../") + output_file);
CSVWriter csv_headers(",");
csv_headers.newRow() << "code" << "pragma" << "line";
csvfile << csv_headers << endl;
// Loop through every cpp-file inside the provided directory
fs::path path = ((string) "../") + cpp_file_directory;
for (auto &filename: fs::directory_iterator(path)) {
cout << "Parsing file " << filename.path().string() << "..." << endl;
// Read and parse the file
std::ifstream stream;
stream.open(filename.path().string());
ANTLRInputStream input(stream);
CPP14Lexer lexer(&input);
CommonTokenStream tokens(&lexer);
CPP14Parser parser(&tokens);
std::stringstream buffer;
std::streambuf * old = std::cerr.rdbuf(buffer.rdbuf());
CPP14Parser::TranslationunitContext* tree = parser.translationunit();
std::cerr.rdbuf(old);
// Only process the file if there were no parsing errors
bool no_errors = (buffer.str() == "");
if (no_errors) {
// Create temporary csv file for processing with python script
ofstream csvfile_current;
csvfile_current.open("../tmp.csv");
csvfile_current << csv_headers << endl;
// Parse the code
CSVWriter csv(",");
ImageVisitor visitor(&tokens, &csv, features_type);
visitor.visitTranslationunit(tree);
// Save the results
csvfile << csv << endl;
csvfile_current << csv << endl;
// Close stream to tmp file
csvfile_current.close();
if ((string) features_type == (string) "process") {
// Execute python script
string command("python ../optimize_cpp_file.py ../_train.csv ../tmp.csv ");
command.append(filename.path().string());
command.append(" ../output/");
command.append(filename.path().string().substr(filename.path().string().find_last_of("/") + 1));
cout << "Executing command: " << command << endl;
system(command.c_str());
}
} else {
cout << "Skipping file due to parsing error: " << filename.path().string() << endl;
}
}
csvfile.close();
return 0;
} | true |
bc149b64c2d825b3fdc94d3d96353650bdc9915b | C++ | Wafiifaw55/Arduino-control-Servo-with-ultrasonic | /start_simulating1.ino | UTF-8 | 1,095 | 2.546875 | 3 | [] | no_license | #include<Servo.h>
int trig=8;
int echo=9;
int dt=10;
Servo servo1,servo2,servo3,servo4,servo5,servo6;
void setup() {
pinMode(trig,OUTPUT);
pinMode(echo,INPUT);
Serial.begin(9600);
servo1.attach(2);
servo2.attach(12);
servo3.attach(3);
servo4.attach(13);
servo5.attach(4);
servo6.attach(11);
}
int b=30,s=945,e=90,w=90,n=45,p=30;
void loop() {
// put your main code here, to run repeatedly:
if (calc_dis()<10)
{
for (int i=0;i<=540;i++)
{
servo1.write(i+b);
servo2.write(i+s);
servo3.write(i+e);
servo4.write(i+w);
servo5.write(i+n);
servo6.write(i+p);
delay(1);
}
delay(100);
for (int i=540;i>=0;i--)
{
servo1.write(i);
servo2.write(i);
servo3.write(i);
servo4.write(i);
servo5.write(i);
servo6.write(i);
delay(1);
}
delay(100);
}
}
//This code is written to calculate the DISTANCE using ULTRASONIC SENSOR
int calc_dis()
{
int duration,distance;
digitalWrite(trig,HIGH);
delay(dt);
digitalWrite(trig,LOW);
duration=pulseIn(echo,HIGH);
distance = (duration/2) / 29.1;
return distance;
} | true |
458a13cd35205327e6ed8b4fa1dd0022519de7b2 | C++ | cohenor1112/BlackJack-with-Cpp- | /BlackJack_ariel/Card.h | UTF-8 | 808 | 3.078125 | 3 | [] | no_license | #ifndef _CARD_H_
#define _CARD_H_
#include <string>
#include <iostream>
using namespace std;
class Card {
public:
//de/constractors:
Card(int card_serial);
~Card();
Card(Card& c);
//getters,setters:
char get_name() const;
char get_game_value() const;
static int toss_val();
static int get_max_cards();
static int get_max_kind_cards();
//statics:
static char n_cards_made;
static char n_cards_kind[13];
private:
//members:
unsigned char m_value;
unsigned char m_game_value;
char m_name;
//statics:
const static char n_max_cards = 52;
const static char n_max_kind_cards = 4;
//functions:
unsigned char serial_2_name(const int card_serial);
unsigned char serial_2_gv(const int card_serial);
//friends:
friend ostream& operator<<(ostream& os, const Card& card);
};
#endif // !_CARD_H_ | true |
6d07b53d303f0757ba6fbcf4113cd804599eb1c5 | C++ | tobiashienzsch/examples | /cxx_wdf/main.cpp | UTF-8 | 5,211 | 3.203125 | 3 | [
"MIT"
] | permissive | #include <array>
namespace mc
{
template<typename T>
struct State
{
T Rp {1}; // Port resistance
T a {0}; // incident wave (incoming wave)
T b {0}; // reflected wave (outgoing wave)
};
template<typename T>
struct ElectricalComponent
{
[[nodiscard]] auto voltage() noexcept
{
auto& state = static_cast<T*>(this)->getState();
return (state.a + state.b) / 2.0;
}
[[nodiscard]] auto current() noexcept
{
auto& state = static_cast<T*>(this)->getState();
return (state.a - state.b) / (state.Rp + state.Rp);
}
[[nodiscard]] auto R() noexcept
{ // resistance
auto& state = static_cast<T*>(this)->getState();
return state.Rp;
}
[[nodiscard]] auto G() noexcept
{ // conductance
auto& state = static_cast<T*>(this)->getState();
return 1.0 / state.Rp;
}
};
template<typename T>
struct Resistor : ElectricalComponent<Resistor<T>>
{
explicit Resistor(T R) noexcept : state_ {R, 0, 0} { }
[[nodiscard]] auto getState() noexcept -> State<T>& { return state_; }
auto incident(T wave) noexcept -> void { state_.a = wave; }
[[nodiscard]] auto reflected() noexcept -> T
{
state_.b = 0;
return state_.b;
}
private:
State<T> state_ {};
};
template<typename T>
struct Capacitor : ElectricalComponent<Capacitor<T>>
{
Capacitor(T C, T sampleRate) noexcept
: state_ {sampleRate / T {2} * C, 0, 0}
{
}
[[nodiscard]] auto getState() noexcept -> State<T>& { return state_; }
auto incident(T wave) noexcept -> void
{
state_.a = wave;
capState_ = state_.a;
}
[[nodiscard]] auto reflected() noexcept -> T
{
state_.b = capState_;
return state_.b;
}
private:
State<T> state_ {};
T capState_ {0};
};
template<typename T>
struct Inductor : ElectricalComponent<Inductor<T>>
{
Inductor(T L, T sampleRate) noexcept : state_ {T {2} * L / sampleRate, 0, 0}
{
}
[[nodiscard]] auto getState() noexcept -> State<T>& { return state_; }
auto incident(T wave) noexcept -> void
{
state_.a = wave;
capState_ = state_.a;
}
[[nodiscard]] auto reflected() noexcept -> T
{
state_.b = -capState_;
return state_.b;
}
private:
State<T> state_ {};
T capState_ {0};
};
template<typename T>
struct OpenCircuit : ElectricalComponent<OpenCircuit<T>>
{
explicit OpenCircuit(T R) noexcept : state_ {R, 0, 0} { }
[[nodiscard]] auto getState() noexcept -> State<T>& { return state_; }
auto incident(T wave) noexcept -> void { state_.a = wave; }
[[nodiscard]] auto reflected() noexcept -> T
{
state_.b = state_.a;
return state_.b;
}
private:
State<T> state_ {};
};
template<typename T>
struct ShortCircuit : ElectricalComponent<ShortCircuit<T>>
{
explicit ShortCircuit(T R) noexcept : state_ {R, 0, 0} { }
[[nodiscard]] auto getState() noexcept -> State<T>& { return state_; }
auto incident(T wave) noexcept -> void { state_.a = wave; }
[[nodiscard]] auto reflected() noexcept -> T
{
state_.b = -state_.a;
return state_.b;
}
private:
State<T> state_ {};
};
template<typename T>
struct VoltageSource : ElectricalComponent<VoltageSource<T>>
{
VoltageSource(T V, T R) noexcept : state_ {R, 0, 0}, Vs_ {V} { }
[[nodiscard]] auto getState() noexcept -> State<T>& { return state_; }
auto incident(T wave) noexcept -> void { state_.a = wave; }
[[nodiscard]] auto reflected() noexcept -> T
{
state_.b = -state_.a + 2.0 * Vs_;
return state_.b;
}
private:
State<T> state_ {};
T Vs_;
};
template<typename T>
struct CurrentSource : ElectricalComponent<CurrentSource<T>>
{
CurrentSource(T I, T R) noexcept : state_ {R, 0, 0}, Is_ {I} { }
[[nodiscard]] auto getState() noexcept -> State<T>& { return state_; }
auto incident(T wave) noexcept -> void { state_.a = wave; }
[[nodiscard]] auto reflected() noexcept -> T
{
state_.b = state_.a + 2.0 * this->R() * Is_;
return state_.b;
}
private:
State<T> state_ {};
T Is_;
};
} // namespace mc
auto resistor(mc::Resistor<double>& R, double in) -> double
{
R.incident(in);
return R.reflected();
}
auto capacitor(mc::Capacitor<double>& C, double in) -> double
{
C.incident(in);
return C.reflected();
}
auto inductor(mc::Inductor<double>& L, double in) -> double
{
L.incident(in);
return L.reflected();
}
auto open_circuit(mc::OpenCircuit<double>& OC, double in) -> double
{
OC.incident(in);
return OC.reflected();
}
auto short_circuit(mc::ShortCircuit<double>& SC, double in) -> double
{
SC.incident(in);
return SC.reflected();
}
auto voltage_source(mc::VoltageSource<double>& Vs, double in) -> double
{
Vs.incident(in);
return Vs.reflected();
}
auto current_source(mc::CurrentSource<double>& Is, double in) -> double
{
Is.incident(in);
return Is.reflected();
}
auto ideal_transformer(mc::CurrentSource<double>& Is, double in) -> double
{
Is.incident(in);
return Is.reflected();
}
auto main() -> int { return 0; } | true |
ecc8f3c7e81028dc6323f82e792597e8a014e9e1 | C++ | sergey-shambir/cocos2d-x-extensions-cpp2011 | /serialization-codegen/test_data/SampleGameData.h | UTF-8 | 1,175 | 2.6875 | 3 | [
"MIT"
] | permissive |
struct ISerializableRecord
{
virtual ~ISerializableRecord() {}
virtual void saveDataTo(CCDictionary *dict) const = 0;
virtual void loadDataFrom(CCDictionary *dict) = 0;
};
struct SoldierRecord : public ISerializableRecord
{
SoldierRecord();
void saveDataTo(CCDictionary *dict) const;
void loadDataFrom(CCDictionary *dict);
int getHealth() const;
int getFatigue() const;
void setHealth(int);
void setFatigue(int);
protected:
int health;
int fatigue;
};
struct NinjaRecord : public SoldierRecord
{
NinjaRecord();
void saveDataTo(CCDictionary *dict) const;
void loadDataFrom(CCDictionary *dict);
bool hasKatana() const;
void setHasKatana(bool);
protected:
bool m_hasKatana;
};
struct MerchantRecord : public ISerializableRecord
{
MerchantRecord();
void saveDataTo(CCDictionary *dict) const;
void loadDataFrom(CCDictionary *dict);
bool acceptsBarter() const;
int getMoneyAmount() const;
int getHonor() const;
void setAcceptsBarter(bool);
void setMoneyAmount(int);
void setHonor(int);
protected:
bool m_acceptsBarter;
int moneyAmount;
int honor;
};
| true |
46d0d51c7beb39508bafea07d2e1068526561444 | C++ | yashYRS/UndergraduateLabs | /OperatingSystems/Week_9/Deadlock/deadlock.cpp | UTF-8 | 2,860 | 3.265625 | 3 | [] | no_license | #include<iostream>
#include<stdlib.h>
using namespace std ;
int* take_input(int n, int m) {
int* a = (int*)malloc(sizeof(int)*n*m) ; // n*m
for(int i = 0 ; i < n ; i++) {
cout<<"\n Enter row -> " ;
for(int j = 0 ; j < m ; j++)
cin>>a[i*m + j];
}
return a ;
}
void copy(int *a , int * b, int n) {
for(int i = 0 ; i < n ; i++)
a[i] = b[i] ;
}
void print(int *a , int n, int m ) {
for(int i = 0 ; i < n ;i++ ) {
for(int j = 0 ; j < m ; j++)
cout<<a[i*m + j]<<" " ;
cout<<endl ;
}
}
int detect(int *allocate, int *request , int *work, int n, int m) {
int *finish = (int*)malloc(n*sizeof(int)) ;
for(int i = 0 ; i < n ; i++ ) {
finish[i] = 1 ;
for(int j = 0 ; j < m ; j++)
if(allocate[i*m + j] > 0) {
finish[i] = 0 ;
break ;
}
} // set up finish ...
int flag , found = 1 , break_flag = 1 ;
while(found) { // thus, nothing was found in one run, the loop breaks ...
found = 0 ;
for( int i = 0 ; i < n ; i++ ) {
break_flag = 1 ;
if (finish[i] == 0 ) {
for(int j = 0 ; j < m ; j++) {
if ( request[i*m + j] > work[j] ){
break_flag = 0 ; // don't execute step->3
break ;
}
}
if (break_flag) { // that i found, so step-> 3
found = 1 ;
for(int j = 0 ; j < m ; j++)
work[j] = work[j] + allocate[i*m + j] ;
finish[i] = 1;
}
}
}
}
for(int i = 0 ; i < n ; i++) {
if (finish[i] == 0)
return 0 ; // deadlock
}
return 1 ; // no deadlock
}
int prompt() {
int a ;
cout<<"\n\n Enter choice - 1. Detect Deadlock 2. exit \n" ;
cin>> a;
return a ;
}
int main() {
int n , m ; // n -> no of processors, m -> no of resource types
int *available, *avail_copy , *request , *request_copy, *allocation , *alloc_copy ;
available = (int*)malloc(sizeof(int)*m*n) ;
request = (int*)malloc(sizeof(int)*m*n) ;
allocation = (int*)malloc(sizeof(int)*m*n) ;
cout<<" Enter the number of resources " ; cin >> m ;
cout<<" Enter the number of processes " ; cin>> n ;
cout<<" Enter the available resources "<<endl ; available = take_input(1,m) ; print(available,1,m) ;
cout<<" Enter the request/process [row wise]"<<endl ; request = take_input(n,m) ; print(request,n,m) ;
cout<<" Enter the allocation/process [row wise]"<<endl ; allocation = take_input(n,m) ; print(allocation,n,m) ;
avail_copy = (int*)malloc(sizeof(int)*m) ;
request_copy = (int*)malloc(sizeof(int)*m*n) ;
alloc_copy = (int*)malloc(sizeof(int)*m*n) ;
while(1) {
switch(prompt()) {
case 1 :
copy(avail_copy,available , m) ;
copy(alloc_copy, allocation, n*m) ;
copy(request_copy, request, n*m) ;
if (detect(alloc_copy,request_copy,avail_copy,n,m) == 0 )
cout<<" Deadlock "<<endl ;
else
cout<<" No Deadlock "<<endl ;
break ;
case 2 : exit(0) ;
}
}
} | true |
3580ce73b36c3b3e2952adbc9384fe5c2c492e96 | C++ | johnmryan/TowerDefense | /Towers/Tower.h | UTF-8 | 2,001 | 3.1875 | 3 | [] | no_license | /* Jack Ryan
* CSE 20212
* Final Project
* Tower.h
* Tower interface for abstract base class
*/
#ifndef TOWER_H
#define TOWER_H
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <stdio.h>
#include <string>
#include <sys/time.h>
#include <iostream>
#include <cmath>
#include "../Enemies/Enemy.h"
using namespace std;
class Tower : public Object {
public:
Tower(SDL_Renderer **gRendererPtr, vector<Enemy*> *, vector<Tower*> *);
~Tower(); // deconstructor frees allocated memory
void attack(int*); // function to begin attacking (decreasing health) of target
void render(); // makes Tower class abstract
bool inRange(); // senses if any enemy is in the specific tower's range
void resetTarget(Enemy *);
void handleMouseClick(int x, int y);
private:
double MAX_DISTORTION;
struct timeval timeStruct; // allows for milliseconds of current time, for attack frequency
long long lastAttackTime; // last time that an Enemy was attacked
protected:
int pts_per_kill;
int MAX_DIMENSION; // share this value with derived towers
int towerX;
int towerY;
int range;
int damage;
int attackDelay; // number of seconds tower will wait before attacking another enemy
bool renderRange; // bool flag to display range or not
SDL_Renderer** gRenderer; // double pointer to renderer
SDL_Texture* gTower; // texture containing tower's image
SDL_Rect gTowerRect; // container for gTower texture
SDL_Texture* gRange; // texture for Range radius
SDL_Rect gRangeRect; // container for Range radius
Enemy* target; // target is a pointer to the enemy that is the target
vector<Enemy*> *enemies; // ref to vector of addresses of enemies from main.cpp
vector<Tower*> *towers; // ref to vector of address of towers from main.cpp
};
#endif
| true |
27705910cbee3dff5812a9e2620910a987af8048 | C++ | dlvguo/NoobOJCollection | /LeetCode/Normal/900-999/908.cpp | UTF-8 | 328 | 2.59375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int smallestRangeI(vector<int> &nums, int k)
{
int minNum = *min_element(nums.begin(), nums.end());
int maxNum = *max_element(nums.begin(), nums.end());
return maxNum - minNum <= 2 * k ? 0 : maxNum - minNum - 2 * k;
}
};
| true |
ab7017e32b513d8069da16a3bc72ae6b786b3cfc | C++ | ztelur/sicp | /构造过程抽象/习题/1.11/f.cpp | UTF-8 | 290 | 3.03125 | 3 | [] | no_license |
/**
* c++的实现啊,先转换一下思想
*/
int a = 0;
int b = 1;
int c = 2
int f2(int n) {
int i = 0;
while(i!=n) {
inter_f2(i,n);
i++;
}
return c;
}
int inter_f2(int i,int n) {
if (i <3) return i;
int res = c+ 2*b + 3*a;
a = b;
b = c;
c = res;
return res;
}
| true |
cf776f88934f18cb7316879853b196a2bdc4ec70 | C++ | ejohns6/Simple-Operator-Overloading-Polymorphism | /Pair.h | UTF-8 | 849 | 2.953125 | 3 | [] | no_license | #ifndef PAIR_H_INCLUDED
#define PAIR_H_INCLUDED
#include <iostream>
#include <string>
using namespace std;
template <class T>
class Pair{
public:
Pair();
Pair(T first, T second);
T first();//return the first member of the pair
T second();//reutrn the second member of the pair
bool operator==(const Pair<T>& rhs) const;
private:
T m_first;
T m_second;
};
#include "Pair.cpp"
#endif // PAIR_H_INCLUDED
/*
#ifndef PAIR_H_INCLUDED
#define PAIR_H_INCLUDED
#include <iostream>
#include <string>
using namespace std;
class Pair{
public:
Pair();
Pair(int first, int second);
int first();//return the first member of the pair
int second();//reutrn the second member of the pair
bool operator==(const Pair& rhs) const;
private:
int m_first;
int m_second;
};
#endif // PAIR_H_INCLUDED
*/
| true |
26e18e060f6c8a8a2d770f526d183955c31ce857 | C++ | ZeroNerodaHero/USACO-Training-Gateway | /3.1/agrinet.cpp | UTF-8 | 1,430 | 2.90625 | 3 | [] | no_license | /*
ID: billyz43
PROG: agrinet
LANG: C++
*/
#include <iostream>
#include <fstream>
#include <queue>
#include <cstring>
using namespace std;
std::ifstream in("agrinet.in");
std::ofstream out("agrinet.out");
struct node{
int cur, d;
node(int cur,int d): cur(cur),d(d) {}
bool operator <(const node &o) const{
return d > o.d;
}
};
int main(){
int N;
in >> N;
int con[100][100];
for(int i = 0; i < N; i++){
for(int j = 0; j < N; j++){
in >> con[i][j];
}
}
bool visited[N];
int weight[N];
int sum = 0,edge = 1;
memset(visited,0,sizeof(visited));
memset(weight,0x1F,sizeof(weight));
priority_queue<node> q;
visited[0] = true;
// int m = 1;
for(int i = 1; i < N; i++){
weight[i] = con[0][i];
q.push(node(i,con[0][i]));
//if(con[0][m]>con[0][i]) m = i;
}
//q.push(node(0,m,con[0][m]);
while(!q.empty()){
// while(edge < N){
node tmp = q.top();
q.pop();
int u = tmp.cur;
// cout << edge << endl;
if(visited[u]) continue;
edge++;
visited[u] = true;
sum += tmp.d;
for(int i = 0; i < N; i++){
//if((!visited[i])&&(con[u][i] < weight[i])){
if(!visited[i]){
weight[i] = con[u][i];
q.push(node(i,con[u][i]));
}
}
}
out << sum << endl;
}
| true |
097cd3e2cd18b063867e21def85e63c4a1e64872 | C++ | mostriki/computer-science-161 | /in-class/wk08/practice-problem-03/main.cpp | UTF-8 | 2,128 | 4.1875 | 4 | [] | no_license | /**********************************************************************************************************************
* *
* * Author: Riki Montgomery
* * Date: March 17, 2019
* * Program Name: Number Swap
* * Filename: practice-problem-03
* * Description: Swaps the first and last numbers in an array of integers.
* *
* * Sources: None
* *
* *******************************************************************************************************************/
#include <iostream>
using namespace std;
void swapEnds(int array[], int size);
void printArray(int array[], int size);
int main () {
const int SIZE = 10;
int numbersArray[SIZE] = {6, -6, 1, 3, -3, 4, 8, -1, 2, 7};
cout << "The array before: ";
printArray(numbersArray, SIZE);
swapEnds(numbersArray, SIZE);
cout << "The array after: ";
printArray(numbersArray, SIZE);
return 0;
}
/**********************************************************************************************************************
* *
* * Function: swapEnds
* * Parameters: An array of integers and its size as an integer
* * Description: This function takes an array and swaps the first and last integers in that array.
* *
* *******************************************************************************************************************/
void swapEnds(int array[], int size) {
int temp = 0;
temp = array[0];
array[0] = array[size -1];
array[size - 1] = temp;
}
/**********************************************************************************************************************
* *
* * Function: printArray
* * Parameters: An array of integers and its size as an integer
* * Description: This function takes an array and prints it contents to standard out.
* *
* *******************************************************************************************************************/
void printArray(int array[], int size) {
for (int i = 0; i < size; i++)
cout << "[ " << array[i] << " ]";
cout << endl;
}
| true |
fb65eb247b354644f01ceffafa196ee7d2409323 | C++ | katarina995/Monopoly | /Board.cpp | UTF-8 | 1,281 | 3.015625 | 3 | [] | no_license | //
// Created by rtrk on 9.10.19..
//
#include "Board.h"
#include <algorithm>
Board::Board(){
initializeFields();
}
Board::~Board(){
for(auto field: fields)
delete field;
}
void Board::initializeFields() {
vector<Street*> streets = readingFromFile();
for(auto street : streets){
Field *field;
field = new Field(street->name, street->price, street->rent);
fields.push_back(field);
}
}
vector<Street*> Board::readingFromFile() {
vector<Street*> streets;
string nameOfFile;
cout << "Please enter file name" << endl;
getline(cin,nameOfFile);
cout << nameOfFile << endl;
ifstream inputs;
inputs.open(nameOfFile);
if(inputs){
for (string street; getline (inputs, street);)
{
auto const pos = street.find_last_of(' ');
Street *str;
str = new Street(street.substr(0, pos + 1), stoi(street.substr(pos + 1)),
stoi(street.substr(pos + 1)) * 0.25);
cout << str->name << '\n';
streets.push_back(str);
}
inputs.close();
}
else {
cout << "Unable to open file\n";
exit(1);
}
return streets;
}
vector<Field*> Board::getFields() {
return fields;
}
| true |
356cbc83023a808fa02c900b8d023a34e200bfa7 | C++ | rpuntaie/c-examples | /cpp/container_unordered_map_equal_range.cpp | UTF-8 | 570 | 3.09375 | 3 | [
"MIT"
] | permissive | /*
g++ --std=c++20 -pthread -o ../_build/cpp/container_unordered_map_equal_range.exe ./cpp/container_unordered_map_equal_range.cpp && (cd ../_build/cpp/;./container_unordered_map_equal_range.exe)
https://en.cppreference.com/w/cpp/container/unordered_map/equal_range
*/
#include <iostream>
#include <unordered_map>
int main()
{
std::unordered_map<int,char> map = {{1,'a'},{1,'b'},{1,'d'},{2,'b'}};
auto range = map.equal_range(1);
for (auto it = range.first; it != range.second; ++it) {
std::cout << it->first << ' ' << it->second << '\n';
}
}
| true |
19191aa6dc440caa539b573fcd2be1c6b57df9d5 | C++ | OutOfTheVoid/Kernel | /include/hw/cpu/IO.h | UTF-8 | 1,287 | 2.671875 | 3 | [] | no_license | #ifndef HW_CPU_IO_H
#define HW_CPU_IO_H
#include <hw/HW.h>
#include <hw/cpu/CPU.h>
namespace HW
{
namespace CPU
{
class IO
{
public:
static inline void Out8 ( uint16_t Port, uint8_t Value )
{
__asm__ volatile ( "outb %1, %0" : : "a" ( Value ), "dN" ( Port ) );
};
static inline void Out16 ( uint16_t Port, uint16_t Value )
{
__asm__ volatile ( "outw %1, %0" : : "a" ( Value ), "dN" ( Port ) );
};
static inline void Out32 ( uint16_t Port, uint32_t Value )
{
__asm__ volatile ( "out %1, %0" : : "a" (Value), "dN" (Port) );
};
static inline uint8_t In8 ( uint16_t Port )
{
uint8_t Ret;
__asm__ volatile ( "inb %0, %1" : "=a" ( Ret ) : "dN" ( Port ) );
return Ret;
};
static inline uint16_t In16 ( uint16_t Port )
{
uint16_t Ret;
__asm__ volatile ( "inw %0, %1" : "=a" ( Ret ) : "d" ( Port ) );
return Ret;
};
static inline uint32_t In32 ( uint16_t Port )
{
uint32_t Ret;
__asm__ volatile ( "in %0, %1" : "=a" ( Ret ) : "d" ( Port ) );
return Ret;
};
static inline void IOWait ()
{
Out8 ( 0x80, 0 );
};
};
};
};
#endif
| true |
a01cc3853f0a0792c21c538571615291e67857ae | C++ | olasalem/MPS | /mps_parser/stack.cpp | UTF-8 | 1,281 | 3.28125 | 3 | [] | no_license | #include <QString>
#include <QDebug>
#include "stack.h"
using namespace std;
stack::stack(){
}
stack::stack(const stack & s){ //copy constructor
for(int i=0;i<maxSize;i++){
stackPointer[i] = s.at(i);
}
}
stack::~stack(){ //destructor
}
bool stack::isEmpty() const{
return (topValue==-1);
}
bool stack::isFull() const{
return (topValue==maxSize+1);
}
void stack::push(int i){
QString StackPushError = "Invalid Jump, Stack OverFlow";
if(!this->isFull()){
topValue++;
stackPointer[topValue]= i;
}
else throw (StackPushError);
}
int stack::pop(){
QString StackPopError = "Invalid Return, The Function is not a Callee";
if(!this->isEmpty()){
int temp = stackPointer[topValue];
topValue--;
return temp;
}
else throw (StackPopError);
}
int stack::top() const{
return stackPointer[topValue];
}
int stack::at(int i) const{
QString StackAccessError = "Invalid Stack Access at Index: ";
if(i>=0 && i<=topValue)
return stackPointer[i];
else
throw (StackAccessError + QString::number(i));
}
| true |
33af5a723804ebddad6b5b473bfc3c16d29aba36 | C++ | pawanchoure2000/C-Language- | /recursion.cpp | UTF-8 | 777 | 3.953125 | 4 | [] | no_license | //direct recursive if it calls the same function
//called indirect recursive if it calls another function
// A C++ program to demonstrate working of
// recursion
#include<bits/stdc++.h>
using namespace std;
void printFun(int test)
{
if (test < 1)
{
printf("hi \n ");
return;
}
else
{
cout << test << " ";
printFun(test-1); // memory is allocated on top of memory // different copy of local variables is created for each function call.
printf("hello \n"); //base case is reached // memory is de-allocated and the process continues
cout << test << " ";
return;
}
}
int main()
{
int test = 3;
printFun(test); //function is called from main(), the memory is allocated to it on the stack.
}
| true |
8616966308403b78a393db0c3c6768be617f8dac | C++ | egross91/Summer2013 | /Cards/Cards/Poker.h | UTF-8 | 617 | 2.546875 | 3 | [] | no_license | #ifndef POKER_H
#define POKER_H
#include "Dealer.h"
class Poker : public Dealer
{
private:
typedef Dealer super;
public:
Poker();
void play();
int printResult(std::vector<Card>);
int determineHand(std::vector<Card>);
bool royalFlush(std::vector<Card>);
bool flush(std::vector<Card>);
bool straight(std::vector<Card>);
bool fourOfAKind(std::vector<Card>);
bool fullHouse(std::vector<Card>);
bool threeOfAKind(std::vector<Card>);
bool twoPair(std::vector<Card>);
bool pair(std::vector<Card>);
bool fold();
bool playAgain();
void erasePlayers(std::vector<Player>&, std::vector<int>);
};
#endif POKER_H | true |
1f684423a85f26e81576d8fa1054a82dfabd2bce | C++ | ganaganan/Reverse-Game | /反対/Source/Light.h | SHIFT_JIS | 1,476 | 2.765625 | 3 | [] | no_license | #pragma once
#include <DirectXMath.h>
struct PointLight {
float index;
float range;//͈̓͂
float type; //L
float dummy;
DirectX::XMFLOAT4 pos;
DirectX::XMFLOAT4 color;
};
class Light
{
public:
enum ConsumptionAmount
{
Small,
Midium,
Big,
};
static int amountState;
private:
static DirectX::XMFLOAT3 pos;
public:
static const int POINT_MAX = 32;
static int CONSUMPTION_SMALL;
static int CONSUMPTION_MIDIUM;
static int CONSUMPTION_BIG;
static DirectX::XMFLOAT4 lightDir;
static DirectX::XMFLOAT4 dirLightColor;
static DirectX::XMFLOAT4 ambient;
static PointLight pointLight[POINT_MAX];
static bool isEnableBattery;
static long int battery;
public:
static void Init();
static void Update();
static void SetDirLight(DirectX::XMFLOAT3 _dir, DirectX::XMFLOAT3 _color);
static void SetAmbient(DirectX::XMFLOAT3 _amb);
static void SetPointLight(int _index, DirectX::XMFLOAT3 _pos, DirectX::XMFLOAT3 _color, float _range);
// operation light fuction
static void TurnOffPointLight(int _index);
static void TurnOnPointLight(int _index);
static void SwitchPointLight(int _index);
//Check do light is enable
static bool JudgeLightEnable(int _index)
{
if (pointLight[_index].type == 1)return true;
return false;
}
// setter and getter
static void SetPos(DirectX::XMFLOAT3 _pos) { pos = _pos; }
static DirectX::XMFLOAT3 GetPos() { return pos; }
static int GetBattery() { return battery; }
}; | true |
c4436041ae6b25fd53706a731e179622e3c4fb4f | C++ | JesusSerna/UberChat | /Project_Current_Test/Server/chat/chat_session.hpp | UTF-8 | 9,032 | 2.90625 | 3 | [] | no_license | /*
chat_session.hpp
*/
#pragma once
#include "chat_room.hpp"
class chat_server;
class chat_session
: public chat_participant,
public enable_shared_from_this<chat_session>
{
public:
chat_session(tcp::socket socket, vector<chat_room>& rooms)
: socket_(move(socket)),
rooms_(rooms)
{
}
void start()
{
if(rooms_.size() < 1)
{
rooms_.push_back(chat_room("Lobby", 0));
rooms_.push_back(chat_room("Chatroom A"));
}
participant_join_room(shared_from_this(), rooms_[0]);
do_read_header();
}
void deliver(const chat_message& msg)
{
bool write_in_progress = !write_msgs_.empty();
write_msgs_.push_back(msg);
if (!write_in_progress)
{
do_write();
}
}
private:
void addNewChatroom(string room_name)
{
cout << "Adding new chatroom!" << endl;
rooms_.push_back(chat_room(room_name));
cout << "New chatroom! " << room_name << ", UUID = " << rooms_.at(rooms_.size()-1).getUUID() << endl;
}
void deleteChatroom(string room_name)
{
cout << "Deleting chatroom!" << endl;
int iterator = 0;
int size = rooms_.size();
for(int i = 1; i< size; i++)
{
string name = rooms_[i].getName();
if((room_name == name)){
iterator = i;
}
}
cout << "Chatroom deleted! " << endl;
rooms_.erase(rooms_.begin()+iterator);
}
chat_room& getRoomFromUUID(uint64_t UUID)
{
for(chat_room& room : rooms_)
{
if(room.getUUID() == UUID)
return room;
}
return rooms_[0];
}
void participant_join_room(std::shared_ptr<chat_session> participant, chat_room& room)
{
uint64_t room_id = participant->getCurrentChatRoomID();
if(room_id == (uint64_t)-1)
{
room.join(participant);
participant->setCurrentChatRoom(room.getUUID());
tellAllChatUsersToUpdateTheirUserLists(room);
}
}
void participant_leave_room(std::shared_ptr<chat_session> participant)
{
uint64_t room_id = participant->getCurrentChatRoomID();
if(room_id != (uint64_t)-1)
{
chat_room& room = getRoomFromUUID(room_id);
room.leave(participant);
tellAllChatUsersToUpdateTheirUserLists(room);
participant->setCurrentChatRoom(-1);
}
}
void switch_chat_rooms(std::shared_ptr<chat_session> participant, chat_room& next_room)
{
uint64_t room_id = participant->getCurrentChatRoomID();
if(room_id != (uint64_t)-1)
{
chat_room& room = getRoomFromUUID(room_id);
room.leave(participant);
tellAllChatUsersToUpdateTheirUserLists(room);
next_room.join(participant);
participant->setCurrentChatRoom(next_room.getUUID());
tellAllChatUsersToUpdateTheirUserLists(next_room);
}
}
void tellAllChatUsersToUpdateTheirUserLists(chat_room& room)
{
uint64_t roomID = room.getUUID();
if(roomID == 0 || roomID == (uint64_t)-1)
return;
string users_str = room.getListOfNicknames();
if(users_str.length() > 0){
string msg_str = string("USERS ") + users_str;
read_msg_.body_length(msg_str.length());
strcpy(read_msg_.body(), msg_str.c_str());
read_msg_.encode_header();
room.deliver(read_msg_);
}
}
void tellAllChatUsersToUpdateTheirChatrooms()
{
for(chat_room& room : rooms_){
uint64_t roomID = room.getUUID();
if(roomID == (uint64_t)-1) return;
string chat_rooms_str = listChatRooms();
string users_str = room.getListOfNicknames();
if(chat_rooms_str.length() > 0 && users_str.length() > 0){
string pre_str = string("CHATROOMS ");
read_msg_.body_length(chat_rooms_str.length() + pre_str.length());
strcpy(read_msg_.body(), chat_rooms_str.c_str());
prepend(read_msg_.body(), pre_str.c_str());
read_msg_.encode_header();
room.deliver(read_msg_);
}
}
}
string listChatRooms()
{
string out;
for(size_t i = 1; i < rooms_.size(); i++)
{
out += rooms_[i].getName();
if(i < rooms_.size() - 1)
out += ",";
}
return out;
}
void do_read_header()
{
auto self(shared_from_this());
boost::asio::async_read(socket_,
boost::asio::buffer(read_msg_.data(), chat_message::header_length),
[this, self](boost::system::error_code ec, size_t /*length*/)
{
if (!ec && read_msg_.decode_header())
{
do_read_body();
}
else
{
//room_.leave(shared_from_this());
participant_leave_room(shared_from_this());
}
});
}
void prepend(char* s, const char* t)
{
size_t len = strlen(t);
size_t i;
memmove(s + len, s, strlen(s) + 1);
for (i = 0; i < len; ++i)
{
s[i] = t[i];
}
}
bool checkIfNicknameAvaliable(string nickname)
{
for(chat_room& room : rooms_)
{
if(room.isNicknameTaken(nickname))
return false;
}
return true;
}
bool checkIfRoomNameIsAvaliable(string nickname)
{
for(chat_room& room : rooms_)
{
if(room.getName() == nickname)
return false;
}
return true;
}
void do_read_body()
{
auto self(shared_from_this());
boost::asio::async_read(socket_,
boost::asio::buffer(read_msg_.body(), read_msg_.body_length()),
[this, self](boost::system::error_code ec, size_t /*length*/)
{
if (!ec)
{
uint64_t room_id = shared_from_this()->getCurrentChatRoomID();
if(room_id != (uint64_t)-1)
{
chat_room& room_ = getRoomFromUUID(room_id);
//cout << "Room UUID = " << room_id << endl;
cout << "cmd = " << string(read_msg_.body(), read_msg_.body_length()) << endl;
Command cmd(string(read_msg_.body(), read_msg_.body_length()));
if(cmd.isValid()) { // Checks if the command is safe to use.
string major_command = cmd.getMajorCommand();
//cout << "Command = " << major_command << endl;
if(major_command == "SENDTEXT") {
string text = cmd.getArgument();
string time_stamp = cmd.getTimeStamp();
//cout << "Text = " << text << endl;
string client_nickname = string("TEXT ["+shared_from_this()->getNickname()+"] ");
read_msg_.body_length(text.length()+client_nickname.length());
strcpy(read_msg_.body(), text.c_str());
prepend(read_msg_.body(), client_nickname.c_str());
read_msg_.encode_header();
room_.deliver(read_msg_);
} else if (major_command == "REQNICK") {
string new_nickname = cmd.getArgument();
int counter = 1;
while(!checkIfNicknameAvaliable(new_nickname)) {
counter++;
new_nickname = cmd.getArgument() + to_string(counter);
}
shared_from_this()->setNickname(new_nickname);
string nickstr = string("NICKNAME ") + new_nickname;
read_msg_.body_length(nickstr.length());
strcpy(read_msg_.body(), nickstr.c_str());
read_msg_.encode_header();
room_.deliver_to_participant(read_msg_, shared_from_this());
tellAllChatUsersToUpdateTheirUserLists(room_);
} else if (major_command == "NAMECHATROOM") {
string room_name = cmd.getArgument();
int counter = 1;
while(!checkIfRoomNameIsAvaliable(room_name)) {
counter++;
room_name = cmd.getArgument() + to_string(counter);
}
addNewChatroom(room_name);
tellAllChatUsersToUpdateTheirChatrooms();
} else if (major_command == "JOINCHATROOM") {
string room_name = cmd.getArgument();
for(chat_room& room : rooms_)
{
if(room.getName() == room_name) {
switch_chat_rooms(shared_from_this(), room);
break;
}
}
} else if (major_command == "REQCHATROOMS") {
string chat_rooms_str = listChatRooms();
if(chat_rooms_str.length() > 0){
string pre_str = string("CHATROOMS ");
read_msg_.body_length(chat_rooms_str.length() + pre_str.length());
strcpy(read_msg_.body(), chat_rooms_str.c_str());
prepend(read_msg_.body(), pre_str.c_str());
read_msg_.encode_header();
room_.deliver_to_participant(read_msg_, shared_from_this());
}
} else if (major_command == "REQUSERS") {
tellAllChatUsersToUpdateTheirUserLists(room_);
} else if (major_command == "DELETE"){
string room_name = cmd.getArgument();
deleteChatroom(room_name);
tellAllChatUsersToUpdateTheirChatrooms();
}
do_read_header();
} else {
cerr << "Command not valid: " << cmd.getNotValidReason() << endl;
}
}
}
else
{
//room_.leave(shared_from_this());
participant_leave_room(shared_from_this());
}
});
}
void do_write()
{
auto self(shared_from_this());
boost::asio::async_write(socket_,
boost::asio::buffer(write_msgs_.front().data(),
write_msgs_.front().length()),
[this, self](boost::system::error_code ec, size_t /*length*/)
{
if (!ec)
{
write_msgs_.pop_front();
if (!write_msgs_.empty())
{
do_write();
}
}
else
{
participant_leave_room(shared_from_this());
//room_.leave(shared_from_this());
}
});
}
tcp::socket socket_;
vector<chat_room>& rooms_;
chat_message read_msg_;
chat_message_queue write_msgs_;
};
| true |
97dbc9c45363aea365ca1c32a369847f156e83a1 | C++ | megatelesync/ResourceManager | /MathUtil/h/!DEPRECATED/3DMath/MathUtil_3DMath_AngleDirectedPosition.h | UTF-8 | 3,192 | 2.875 | 3 | [] | no_license | #ifndef _MathUtil_3DMath_AngleDirectedPosition_h_
#define _MathUtil_3DMath_AngleDirectedPosition_h_
#include <DirectXMath.h>
#include "../Core/MathUtil_Core_AnglePair.h"
#include <boost/property_tree/ptree.hpp>
#include "MathUtil_3DMath_Utils.h"
namespace DvUtils
{
namespace Math
{
struct AngleDirectedPosition
{
/***********************************************************************************************
* public variables
************************************************************************************************/
DirectX::XMFLOAT3 position;
AnglePair direction;
/***********************************************************************************************
* helper getters
************************************************************************************************/
float GetHorzAngle () const { return direction.horz; }
float GetVerticalAngle () const { return direction.horz; }
/***********************************************************************************************
* ctors
************************************************************************************************/
// default ctor: initialize as the object with zero position and direction vector with zero angles
inline AngleDirectedPosition () :
position(DirectX::XMFLOAT3(0.0F,0.0F,0.0F)),
direction() {}
inline AngleDirectedPosition (const DirectX::XMFLOAT3& positionIn, const AnglePair& directionIn);
inline AngleDirectedPosition (const DirectX::XMFLOAT3& positionIn, float horzAngleIn, float verticalAngleIn);
};
AngleDirectedPosition LoadAngleDirectedPosition_FromPropertyTree(const boost::property_tree::ptree& ptree);
inline DirectX::XMMATRIX CalcAffineMatrix(const AngleDirectedPosition& AngleDirectedPosition);
inline DirectX::XMMATRIX CalcViewMatrix(const AngleDirectedPosition& AngleDirectedPosition);
inline DirectX::XMMATRIX CalcViewMatrix(const AngleDirectedPosition& angleDirectedPosition)
{
DirectX::XMMATRIX affineMatrix = CalcAffineMatrix(angleDirectedPosition);
DirectX::XMMATRIX resMatrix = DirectX::XMMatrixInverse(nullptr, affineMatrix);
return resMatrix;
}
inline DirectX::XMMATRIX CalcAffineMatrix(const AngleDirectedPosition& angleDirectedPosition)
{
DirectX::XMMATRIX resMatrix = RotationMatrixXVertYHorz(angleDirectedPosition.direction);
DirectX::XMFLOAT4 position4 (angleDirectedPosition.position.x, angleDirectedPosition.position.y, angleDirectedPosition.position.z, 1.0F);
resMatrix.r[3] = DirectX::XMLoadFloat4(&position4);
return resMatrix;
}
// AngleDirectedPosition impl
inline AngleDirectedPosition::AngleDirectedPosition
(
const DirectX::XMFLOAT3& positionIn, const AnglePair& directionIn
) : position(positionIn), direction(directionIn) {}
inline AngleDirectedPosition::AngleDirectedPosition
(
const DirectX::XMFLOAT3& positionIn, float horzAngleIn, float verticalAngleIn
) : position(positionIn), direction(AnglePair(horzAngleIn,verticalAngleIn))
{
}
} // Math
} // DvUtils
#endif // _MathUtil_3DMath_AngleDirectedPosition_h_ | true |
79a105c2db50160ddfa4eacc48e24b98ea726ed1 | C++ | nsarang/motif_bionet | /src/Graph.h | UTF-8 | 1,612 | 2.65625 | 3 | [] | no_license | //============================================================================
// Name : Graph.h
// Author : Nima Sarang
// Version :
// Copyright :
// Description :
//============================================================================
#ifndef __GRAPH_H
#define __GRAPH_H
#include <vector>
#include <set>
#include <unordered_map>
#include <string>
using namespace std;
typedef string Vertex;
struct Edge
{
Edge(Vertex a, Vertex b) : u( a ), v( b ) {}
Vertex u, v;
};
class Graph
{
public:
Graph(bool sortbyDegree = true);
Graph(vector<Vertex> inpNodes, vector<Edge> inpEdges, bool sortbyDegree = true);
bool existEdge(Edge e) const;
void addEdge(Edge e);
void addNode(Vertex v);
bool existNode(Vertex v) const;
void deleteNode(Vertex v);
int deg(Vertex v) const;
void join(const Graph& P);
bool edgeIntersection(const Graph& P, bool explicitPartly = false) const;
bool nodeIntersection(const Graph& P) const;
bool operator<(const Graph& P) const;
bool operator==(const Graph& P) const;
friend ostream &operator<<(ostream &out, const Graph &G);
bool isIsomorphic(Graph &P);
int order() const {return nodeVec.size();}
int size() const {return edgeCount;}
int components() const;
void sortNodeVec();
void calcLables();
vector<Vertex> nodeVec;
unordered_map<Vertex, set<Vertex>> adjList;
bool sortbyDeg;
bool chLables;
int edgeCount;
vector<double> canoLabels;
};
#endif /* __GRAPH_H */
| true |