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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
cdb783a08c78f70b22e544245fb92303b99a740b | C++ | grapple-system/Backend | /engine/src/preproc/preproc.cpp | UTF-8 | 7,440 | 2.671875 | 3 | [] | no_license | #include "preproc.h"
bool compareV(const pair<int, string> &lhs, const pair<int, string> &rhs);
Preproc::Preproc(Context &context) {
vitSize = context.getNumPartitions();
numVertex = 0;
}
void Preproc::countNum(Context &context)
{
FILE *fp;
char buf[512];
char *p_token = NULL;
char *text = NULL;
int src, dst;
char ctemp[10];
dataSize = 0;
count = 0;
//fisrt file scan for count how many src is in the file
//for malloc
fp = fopen(context.getGraphFile().c_str(), "r");
if (fp != NULL) {
while (NULL != fgets(buf, sizeof(buf), fp)) {
p_token = strtok_r(buf, "\n", &text);
p_token = strtok_r(buf, "\t", &text);
src = atoi(p_token);
if (src > dataSize)
dataSize = src;
}
fclose(fp);
dataSize++;
}
else {
// assert(false, "Cannot open graph_file ");
}
}
void Preproc::saveData(Context & context)
{
data = new vector<pair<int, string>>[dataSize];
dataCheck = new int[dataSize];
for (int i = 0; i < dataSize; i++)
dataCheck[i] = 0;
FILE *fp;
string label;
char buf[512];
char ctemp[10];
int src, dst;
int i;
set<string>::iterator it_e; //for eRules
fp = fopen(context.getGraphFile().c_str(), "r");
if (fp != NULL) {
while (fscanf(fp, "%d\t%d\t%s\n", &src, &dst, ctemp) != EOF) {
label += ctemp;
data[src].push_back(std::make_pair(dst, label));
dataCheck[dst] = 1;
dataCheck[src] = 1;
count++;
label = "";
}
fclose(fp);
}
else {
// assert(false, "cannot open graph_file");
}
cout << "count " << count << endl;
//add E-rules
for (i = 0; i < dataSize; i++) {
if (data[i].size() == 0 && dataCheck[i] == 0)
continue;
for (it_e = eRules.begin(); it_e != eRules.end(); it_e++) {
label = *it_e;
data[i].push_back(std::make_pair(i, label));
}
std::sort(data[i].begin(), data[i].end(), compareV);
data[i].erase(unique(data[i].begin(), data[i].end()), data[i].end());
numVertex++;
}
}
void Preproc::makeVIT(Context &context) {
clock_t begin, end;
int src, dst;
unsigned long long int mSize = 0;
int size;
int i = 0, j = 0;
int startS = -1, endS = 0;
int sum = 0;
count = 0;
vector<pair<vertexid_t, vertexid_t>> &tempVIT = context.vit.getVIT();
vector<int> &vitDegree = context.vit.getDegree();
//read file and save on the memory
//add edges according to E-rules and count srcs.
for (i = 0; i < dataSize; i++)
count += data[i].size();
cout << "count =" << count << endl;
//calculate mSize following the bytes.
mSize = numVertex * 8 + count * 5;
cout << "numVer =" << numVertex << endl;
vitSize = 0;
startS = -1;
size = context.getNumPartitions();
cout << "size =" << size << endl;
if (mSize / (unsigned long long int)size > context.getMemBudget() / (unsigned long long int)4) {
size = mSize / (context.getMemBudget() / (unsigned long long int) 4);
size++;
}
cout << "size =" << size << endl;
//mSize is limit size per parititons.
mSize /= (unsigned long long int)size;
vitSize = 0;
startS = -1;
for (i = 0; i < dataSize; i++) {
if (data[i].size() == 0)
continue;
if (startS == -1) {
startS = i;
endS = i;
}
sum += data[i].size() * 5;
sum += 8;
//if size is last one then we put data over the limit
//because it exceeds just around 1kb.
if (sum > mSize && vitSize != size - 1) {
vitDegree.push_back(0);
if (i == dataSize - 1)
endS = i;
tempVIT.push_back(std::make_pair(startS, endS));
startS = -1;
sum = 0;
vitSize++;
if (i != dataSize - 1)
i--;
}
endS = i;
}
if (sum != 0) {
tempVIT.push_back(std::make_pair(startS, endS));
vitDegree.push_back(0);
vitSize++;
}
context.setNumPartitions(vitSize);
context.vit.setDegree(vitSize);
sum = 0;
j = 0;
int mSum = 0;
//this is for remember the each size of partition for get DDM.
for (i = 0; i < dataSize; i++) {
if (data[i].size() == 0)
continue;
sum += data[i].size();
mSum += data[i].size() * 5;
mSum += 8;
if (mSum > mSize && j != size - 1) {
if (i != dataSize - 1)
sum -= data[i].size();
vitDegree[j++] = sum;
sum = 0;
mSum = 0;
if (i != dataSize - 1)
i--;
}
}
if (sum != 0) {
vitDegree[j] = sum;
}
//make vit file
context.vit.writeToFile(context.getGraphFile() + ".vit");
}
void Preproc::makePart(Context &context) {
FILE *f;
string str;
string name;
int start = 0;
//make partition files
for (int i = 0; i < vitSize; i++) {
//if (f != NULL) {
for (int j = start; j <= context.vit.getEnd(i); j++) {
if (data[j].size() != 0) {
//fprintf(f, "%d\t%d\t", j, data[j].size());
for (int k = 0; k < data[j].size(); k++) {
for (int l = 1; l < mapInfo.size(); l++) {
if (strcmp(data[j][k].second.c_str(), mapInfo[l].c_str()) == 0) {
//fprintf(f, "%d\t%d\t", data[j][k].first, l);
break;
}
}
}
//fprintf(f, "\n");
}
}
start = context.vit.getEnd(i) + 1;
}
}
void Preproc::makeBinaryPart(Context &context) {
FILE *f;
string str;
string name;
int start = 0;
int degree, dst;
char label;
//make partition files in binary files
for (int i = 0; i < vitSize; i++) {
str = std::to_string((long long)i);
name = context.getGraphFile() + "." + PART + "." + BINA + "." + str.c_str();
f = fopen(name.c_str(), "ab");
if (f != NULL) {
for (int j = start; j <= context.vit.getEnd(i); j++) {
if (data[j].size() != 0) {
fwrite((const void*)& j, sizeof(int), 1, f);
degree = data[j].size();
fwrite((const void*)°ree, sizeof(int), 1, f);
for (int k = 0; k < data[j].size(); k++) {
for (int l = 0; l < mapInfo.size(); l++) {
if (strcmp(data[j][k].second.c_str(), mapInfo[l].c_str()) == 0) {
dst = data[j][k].first;
fwrite((const void*)& dst, sizeof(int), 1, f);
label = l;
fwrite((const void*)& label, sizeof(char), 1, f);
continue;
}
}
}
}
else {
fwrite((const void*)& j, sizeof(int), 1, f);
degree = 0;
fwrite((const void*)°ree, sizeof(int), 1, f);
}
}
fclose(f);
start = context.vit.getEnd(i) + 1;
}
else {
// assert(false, "Cannot make Binary file ");
}
}
}
void Preproc::makeDDM(Context & context)
{
vector<vector<double> > &ddmMap = context.ddm.getDdmMap();
int start = 0;
for (int i = 0; i < vitSize; i++) {
for (int j = start; j <= context.vit.getEnd(i); j++) {
if (data[j].size() != 0) {
for (int k = 0; k < data[j].size(); k++) {
if (i != context.vit.partition(data[j][k].first) && context.vit.partition(data[j][k].first) != -1) {
ddmMap[i][context.vit.partition(data[j][k].first)] ++;
}
}
}
}
start = context.vit.getEnd(i) + 1;
}
for (int i = 0; i < ddmMap[0].size(); i++) {
for (int j = 0; j < ddmMap[0].size(); j++) {
ddmMap[i][j] /= (double)context.vit.getDegree(i);
}
}
context.ddm.save_DDM(context.getGraphFile() + ".ddm");
}
void Preproc::setMapInfo(vector<string> mapInfo, set<char> eRules)
{
set<char>::iterator it_e; //for eRules
this->mapInfo.assign(mapInfo.begin(), mapInfo.end());
for (it_e = eRules.begin(); it_e != eRules.end(); it_e++)
this->eRules.insert(mapInfo[(int)*it_e]);
}
int Preproc::getNumOfPartitions()
{
return vitSize;
}
Preproc::~Preproc()
{
for (int i = 0; i < dataSize; i++)
data[i].clear();
delete[]data;
}
bool compareV(const pair<int, string> &lhs, const pair<int, string> &rhs)
{
if (lhs.first == rhs.first)
return lhs.second < rhs.second;
return lhs.first < rhs.first;
}
| true |
eeea7bd5aabd517710773d2563ed7d2b403b63c1 | C++ | flow03/cpp | /codingame/binary_search.cpp | UTF-8 | 2,666 | 3.3125 | 3 | [] | no_license | #include <iostream>
#include <string>
//#include <vector>
//#include <algorithm>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
int middle(int a, int b)
{
return (a+b)/2;
}
int main()
{
int w; // width of the building.
int h; // height of the building.
cin >> w >> h; cin.ignore();
int n; // maximum number of turns before game over.
cin >> n; cin.ignore();
int x0;
int y0;
cin >> x0 >> y0; cin.ignore();
int x_lower = 0;
int x_upper = w;
int y_lower = 0;
int y_upper = h;
auto move_up = [&y0, &y_lower, &y_upper]()
{
y_upper = y0-1;
y0 = middle(y_upper, y_lower);
};
auto move_down = [&y0, &y_lower, &y_upper]()
{
y_lower = y0+1;
y0 = middle(y_lower, y_upper);
};
auto move_left = [&x0, &x_lower, &x_upper]()
{
x_upper=x0-1;
x0 = middle(x_upper, x_lower);
};
auto move_right = [&x0, &x_lower, &x_upper]()
{
x_lower=x0+1;
x0 = middle(x_lower, x_upper);
};
// game loop
while (1) {
string bomb_dir; // the direction of the bombs from batman's current location (U, UR, R, DR, D, DL, L or UL)
cin >> bomb_dir; cin.ignore();
// Write an action using cout. DON'T FORGET THE "<< endl"
// To debug: cerr << "Debug messages..." << endl;
cerr << "x0="<<x0<<" y0="<<y0<<endl;
if (bomb_dir == "U")
{
move_up();
}
else if (bomb_dir == "D")
{
move_down();
}
if (bomb_dir == "L")
{
move_left();
}
else if (bomb_dir == "R")
{
move_right();
}
else if (bomb_dir == "UR")
{
move_up();
move_right();
}
else if (bomb_dir == "DR")
{
move_down();
move_right();
}
else if (bomb_dir == "DL")
{
move_down();
move_left();
}
else if (bomb_dir == "UL")
{
move_up();
move_left();
}
cerr << bomb_dir << " w="<<w<<" h="<<h<<endl;
//cerr << "x0="<<x0<<" y0="<<y0<<endl;
cerr << "x_lower="<<x_lower<<" x_upper="<<x_upper<<endl;
cerr << "y_lower="<<y_lower<<" y_upper="<<y_upper<<endl;
// the location of the next window Batman should jump to.
cout << x0 << ' ' << y0 << endl;
}
} | true |
0a8df0092533e5b30b1238baf86301c75814a926 | C++ | m0saan/CP | /PAPS/listing2-20.cpp | UTF-8 | 432 | 3.625 | 4 | [] | no_license | #include <iostream>
using namespace std;
struct Point {
double x;
double y;
Point(double theX, double theY) {
x = theX;
y = theY;
}
Point mirror() {
return Point(x, -y);
}
Point translate(double X, double Y) { return Point(X, Y); }
};
int main(){
Point p1(2.5, 4.5);
Point p2 = p1.translate(10.5, 15.2);
cout << p2.x << " " << p2.y << endl;
return 0;
}
| true |
34261a1c871d93e6744d37f004431ca3d1d73617 | C++ | avadapal/Combinatorial-Min-Cost-Flow | /src/hybrid_queue.h | UTF-8 | 1,546 | 3.328125 | 3 | [] | no_license | #pragma once
#include <queue>
#include <vector>
#include <utility>
template<
class K,
class V
>
class hybrid_queue {
public:
using value_type = std::pair<K, V>;
hybrid_queue():
bucket(),
pqueue([](const value_type &lhs, const value_type &rhs) { return lhs.first > rhs.first; }) {}
void reserve_bucket(size_t new_cap) const {
bucket.reserve(new_cap);
}
void push(const value_type &value) {
const auto &key = value.first;
if (key > min_key) {
pqueue.push(value);
return;
}
if (key == min_key) {
bucket.push_back(value);
return;
}
move_bucket_to_queue();
bucket.push_back(value);
min_key = key;
}
auto top() -> value_type {
assert(!empty());
if (bucket.empty())
return pqueue.top();
#ifndef NDEBUG
if (!pqueue.empty())
for (const auto &entry : bucket)
assert(entry.first <= pqueue.top().first);
#endif
return bucket.back();
}
void pop() {
assert(!empty());
if (bucket.empty()) {
min_key = pqueue.top().first;
pqueue.pop();
} else {
bucket.pop_back();
}
}
auto empty() const -> bool {
return bucket.empty() && pqueue.empty();
}
void clear() {
bucket.clear();
pqueue.clear();
}
private:
void move_bucket_to_queue() {
for (const auto &entry : bucket)
pqueue.push(entry);
bucket.clear();
}
K min_key;
std::vector<value_type> bucket;
std::priority_queue<value_type, std::vector<value_type>, bool (*)(const value_type &, const value_type &rhs)> pqueue;
};
| true |
84085c762b9789334effcd6e553db2fb74e4c62c | C++ | Yanick-Salzmann/carpi | /common_utils/src/string.cpp | UTF-8 | 2,689 | 3.4375 | 3 | [
"Apache-2.0"
] | permissive | #include "common_utils/string.hpp"
#include <algorithm>
#include <sstream>
namespace carpi::utils {
auto trim_left(const std::string &value) -> std::string {
const auto itr = std::find_if(value.begin(), value.end(), [](const auto &chr) { return !std::isspace(chr); });
if (itr == value.end()) {
return {};
}
return std::string{itr, value.end()};
}
auto trim_right(const std::string &value) -> std::string {
const auto itr = std::find_if(value.rbegin(), value.rend(), [](const auto &chr) { return !std::isspace(chr); });
if (itr == value.rend()) {
return {};
}
return std::string{value.begin(), itr.base()};
}
auto to_lower(const std::string &value) -> std::string {
std::string ret{};
std::transform(value.begin(), value.end(), std::back_inserter(ret), [](const auto &chr) { return std::tolower(chr); });
return ret;
}
auto split(const std::string &value, const char &delimiter) -> std::vector<std::string> {
std::vector<std::string> ret{};
std::stringstream sstream;
sstream.str(value);
std::string cur_line;
while (std::getline(sstream, cur_line, delimiter)) {
ret.emplace_back(cur_line);
}
return ret;
}
void split(const std::string &value, const char &delimiter, std::vector<std::string> &parts) {
auto cur_index = std::string::size_type{0};
auto last_index = std::string::size_type{0};
auto index = 0;
while((cur_index = value.find(delimiter)) != std::string::npos) {
parts[index++] = value.substr(last_index, cur_index - last_index);
}
if(last_index != value.size()) {
parts[index] = value.substr(last_index);
}
}
std::string replace_all(const std::string &str, const char &chr, const char &replace) {
std::string ret = str;
auto next_pos = ret.find(chr);
while(next_pos != std::string::npos) {
ret[next_pos] = replace;
next_pos = ret.find(chr, next_pos + 1);
}
return ret;
}
bool starts_with(const std::string &str, const std::string &pattern, bool ignore_case) {
if(str.length() < pattern.length()) {
return false;
}
if(!ignore_case) {
return str.substr(0, pattern.length()) == pattern;
} else {
for(auto i = 0u; i < pattern.length(); ++i) {
if(std::tolower(str[i]) != std::tolower(pattern[i])) {
return false;
}
}
}
return true;
}
}
| true |
a02de672b25734f6208c6e4bed5eaf84d7b25eaa | C++ | cjmhef/c-_test | /add/array.cpp | UTF-8 | 277 | 2.703125 | 3 | [] | no_license | #include <iostream>
using namespace std;
#include <iomanip>
using std::setw;
int main()
{ int n[10];
for(int i=0;i<10;i++)
{ n[i]=100+i;
}
cout<<"element"<<setw(13)<<"value"<<endl;
for(int j=0;j<10;j++)
{cout<<setw(7)<<j<<setw(13)<<n[j]<<endl;
}
return 0;
}
| true |
465b560feb14f78c73a943b6bebaa016c7e00964 | C++ | confiture/M2 | /vision/tp6/src/imagePPM.cpp | UTF-8 | 8,779 | 2.78125 | 3 | [] | no_license | #include "imagePPM.hpp"
using namespace std;
double& imagePPM::operator()(int i,int j,color c){
assert(i>=0);
assert(i<hauteur);
assert(j>=0);
assert(j<largeur);
switch(c){
case R:
return bufferR[i*largeur+j];
break;
case G:
return bufferG[i*largeur+j];
break;
case B:
return bufferB[i*largeur+j];
break;
}
}
double imagePPM::operator()(int i,int j,color c)const{
assert(i>=0);
assert(i<hauteur);
assert(j>=0);
assert(j<largeur);
switch(c){
case R:
return bufferR[i*largeur+j];
break;
case G:
return bufferG[i*largeur+j];
break;
case B:
return bufferB[i*largeur+j];
break;
}
}
int imagePPM::getHauteur(){
return hauteur;
}
int imagePPM::getLargeur(){
return largeur;
}
int imagePPM::getValmax(){
return valmax;
}
void imagePPM::updateValmax(){
valmax=bufferR[0];
for(int i=0;i<hauteur*largeur;i++){
if(bufferR[i]>valmax)valmax=bufferR[i];
if(bufferG[i]>valmax)valmax=bufferG[i];
if(bufferB[i]>valmax)valmax=bufferB[i];
}
}
imagePPM::imagePPM(int hauteur, int largeur,int valmax){
this->bufferR = new double[hauteur*largeur];
this->bufferG = new double[hauteur*largeur];
this->bufferB = new double[hauteur*largeur];
this->hauteur=hauteur;
this->largeur=largeur;
this->valmax=valmax;
for(int i=0;i<hauteur*largeur;i++)
{
bufferR[i]=valmax;
bufferG[i]=valmax;
bufferB[i]=valmax;
}
}
imagePPM::imagePPM(const imagePPM & im){
this->bufferR = new double[hauteur*largeur];
this->bufferG = new double[hauteur*largeur];
this->bufferB = new double[hauteur*largeur];
this->hauteur=im.hauteur;
this->largeur=im.largeur;
this->valmax=im.valmax;
for(int i=0;i<hauteur;i++){
for(int j=0;j<largeur;j++){
(*this)(i,j,R)=im(i,j,R);
(*this)(i,j,G)=im(i,j,G);
(*this)(i,j,B)=im(i,j,B);
}
}
}
imagePPM::imagePPM(const char* nomFichier){
/* Ouverture */
FILE* ifp = fopen(nomFichier,"r");
/* LelistPixcture du Magic number */
int ich1 = getc( ifp );
if ( ich1 == EOF )
std::cerr<<"EOF / read error reading magic number"<<std::endl;
int ich2 = getc( ifp );
if ( ich2 == EOF )
std::cerr<<"EOF / read error reading magic number"<<std::endl;
/*if(ich2 != '2'){
std::cerr<<" wrong ifp format "<<std::endl;
exit(-1);
}*/
/*Lecture des dimensions*/
largeur = pm_getint( ifp );
hauteur = pm_getint( ifp );
valmax = pm_getint( ifp );
bufferR = new double[hauteur*largeur];
bufferG = new double[hauteur*largeur];
bufferB = new double[hauteur*largeur];
if(ich2=='6'){
/*Lecture*/
for(int i=0; i < hauteur; i++){
for(int j=0; j < largeur ; j++){
(*this)(i,j,R)=pm_getrawbyte(ifp);
(*this)(i,j,G)=pm_getrawbyte(ifp);
(*this)(i,j,B)=pm_getrawbyte(ifp);
}
}
/* fermeture */
}
else if(ich2=='3'){
for(int i=0; i < hauteur; i++){
for(int j=0; j < largeur ; j++){
(*this)(i,j,R)=pm_getint(ifp);
(*this)(i,j,G)=pm_getint(ifp);
(*this)(i,j,B)=pm_getint(ifp);
}
}
}
else{
std::cout<<"wrong format : P"<<ich2<<std::endl;
fclose(ifp);
exit(-1);
}
fclose(ifp);
}
imagePPM::imagePPM(int k, std::list<pixPPM> * tab,int hauteur, int largeur){
this->hauteur=hauteur;
this->largeur=largeur;
bufferR = new double[hauteur*largeur];
bufferG = new double[hauteur*largeur];
bufferB = new double[hauteur*largeur];
valmax=0;
for(int i=0;i<k;i++){
if(!tab[i].empty()){
pixPPM moy = pixPPM::moyenne(tab[i]);
std::list<pixPPM>::const_iterator it=tab[i].begin();
for(it;it!=tab[i].end();it++){
(*this)((*it).i,(*it).j,R)=moy.valR;
(*this)((*it).i,(*it).j,G)=moy.valG;
(*this)((*it).i,(*it).j,B)=moy.valB;
}
valmax=max(valmax,max(moy.valR+0.5,max(moy.valG+0.5,moy.valB+0.5)))+0.5;
}
}
std::cout<<"c'est juste"<<std::endl;
}
int imagePPM::EcrireImagePPM(const char* nomFichier)const{
int pixR;
int pixG;
int pixB;
char str[50];
/* Ouverture */
filebuf fb;
fb.open(nomFichier,ios::out);
ostream os(&fb);
/* Ecriture */
os<<"P3"<<endl;
os<<largeur<<" "<<hauteur<<endl;
os<<valmax<<endl;
for(int i=0; i < hauteur; i++){
for(int j=0; j < largeur ; j++){
pixR=(int)((*this)(i,j,R)+0.5);
pixG=(int)((*this)(i,j,G)+0.5);
pixB=(int)((*this)(i,j,B)+0.5);
os<<pixR<<" "<<pixG<<" "<<pixB;;
os<<std::endl;
}
}
fb.close();
return 1;
}
void imagePPM::drawCross(int i,int j,int r,int g,int b){
int epais=1;
int grand=4;
//int epais=5;
//int grand=15;
//la verticale
//cout<<"i "<<i<<endl;
//cout<<"j "<<j<<endl;
for(int ii=i-grand;ii<=i+grand;ii++){
for(int jj=j-epais;jj<=j+epais;jj++){
if(ii>=0 && ii<hauteur && jj<largeur && jj>=0){
(*this)(ii,jj,R)=r;
(*this)(ii,jj,G)=g;
(*this)(ii,jj,B)=b;
}
}
}
//l'horizontale
for(int jj=j-grand;jj<=j+grand;jj++){
for(int ii=i-epais;ii<=i+epais;ii++){
if(ii>=0 && ii<hauteur && jj<largeur && jj>=0){
(*this)(ii,jj,R)=r;
(*this)(ii,jj,G)=g;
(*this)(ii,jj,B)=b;
}
}
}
}
pixPPM* imagePPM::initCentroids(int k)const{
pixPPM* centroids=new pixPPM[k];;
int kk;
if(k%2==1){kk=k+1;}
else{kk=k;}
int ind=0;
int j1=largeur/3;
int j2=2*largeur/3;
for(int i=0;i<kk/2-1;i++){
std::cout<<"ici 1"<<endl;
int posi=hauteur/(kk/2+1)*(i+1);
cout<<posi<<endl;
pixPPM pix1(posi,j1,(*this)(posi,j1,R),(*this)(posi,j1,G),(*this)(posi,j1,B));
pixPPM pix2(posi,j2,(*this)(posi,j2,R),(*this)(posi,j2,G),(*this)(posi,j2,B));
centroids[ind]=pix1;
ind++;
centroids[ind]=pix2;
ind++;
}
if(k%2==1){
std::cout<<"ici 2"<<endl;
int posi=hauteur/(kk/2+1)*kk/2;
int j=largeur/2;
pixPPM pix(posi,j,(*this)(posi,j,R),(*this)(posi,j,G),(*this)(posi,j,B));
centroids[ind]=pix;
}
else{
std::cout<<"ici 3"<<endl;
int posi=hauteur/(kk/2+1)*kk/2;
pixPPM pix1(posi,j1,(*this)(posi,j1,R),(*this)(posi,j1,G),(*this)(posi,j1,B));
pixPPM pix2(posi,j2,(*this)(posi,j2,R),(*this)(posi,j2,G),(*this)(posi,j2,B));
centroids[ind]=pix1;
ind++;
centroids[ind]=pix2;
ind++;
}
return centroids;
}
std::list<pixPPM>* imagePPM::kMean(int k,pixPPM* repres,int niter,
double (*distFun)(const pixPPM &,const pixPPM &))const{
std::list<pixPPM>* groups=new std::list<pixPPM>[k];
for(int iter=0;iter<niter;iter++){
for(int kind=0;kind<k;kind++){
groups[kind].clear();
}
for(int i=0;i<hauteur;i++){
for(int j=0;j<largeur;j++){
pixPPM currentPix(i,j,(*this)(i,j,R),(*this)(i,j,G),(*this)(i,j,B));
int belongInd;//le numéro du représentant auquel appartiendra currentPix
double dist=numeric_limits<double>::infinity();
for(int kind=0;kind<k;kind++){//on cherche le représentant de currentPix
double currentDist=(*distFun)(currentPix,repres[kind]);
if(currentDist<dist){
belongInd=kind;
dist=currentDist;
if(dist<0){
exit(-1);
}
}
}
groups[belongInd].push_back(currentPix);
}
}
//on met les représentants à jour
for(int kind=0;kind<k;kind++){
repres[kind]=pixPPM::moyenne(groups[kind]);
std::cout<<repres[kind];
}
}
return groups;
}
void imagePPM::kMeanTrace(int k,pixPPM* repres,int niter,double (*distFun)(const pixPPM &,const pixPPM &),
char * filePat)const{
std::list<pixPPM>* groups=new std::list<pixPPM>[k];
for(int iter=0;iter<niter;iter++){
for(int kind=0;kind<k;kind++){
groups[kind].clear();
}
for(int i=0;i<hauteur;i++){
for(int j=0;j<largeur;j++){
pixPPM currentPix(i,j,(*this)(i,j,R),(*this)(i,j,G),(*this)(i,j,B));
int belongInd;//le numéro du représentant auquel appartiendra currentPix
double dist=numeric_limits<double>::infinity();
for(int kind=0;kind<k;kind++){//on cherche le représentant de currentPix
double currentDist=(*distFun)(currentPix,repres[kind]);
if(currentDist<dist){
belongInd=kind;
dist=currentDist;
if(dist<0){
exit(-1);
}
}
}
groups[belongInd].push_back(currentPix);
}
}
//on écrit le nom la trace
std::string name(filePat);
ostringstream ss;
ss<<(iter+1);
name+=ss.str();
name+=".ppm";
//on écrit la trace
imagePPM im(k,groups,hauteur,largeur);
im.EcrireImagePPM(name.c_str());
//on met les représentants à jour
for(int kind=0;kind<k;kind++){
repres[kind]=pixPPM::moyenne(groups[kind]);
std::cout<<repres[kind];
}
}
}
pixPPM* imagePPM::randInitCentroids(int k,int seed)const{
srand((double)seed*RAND_MAX/(k+1));
pixPPM* repres=new pixPPM[k];
for(int j=0;j<k;j++){
int pixi=(double)rand()/RAND_MAX*hauteur;
int pixj=(double)rand()/RAND_MAX*largeur;
repres[j].i=pixi;
repres[j].j=pixj;
repres[j].valR=(*this)(pixi,pixj,R);
repres[j].valG=(*this)(pixi,pixj,G);
repres[j].valB=(*this)(pixi,pixj,B);
std::cout<<repres[j];
}
std::cout<<"====================================="<<std::endl;
return repres;
}
| true |
f585f1112fadc1500eb557769f29016c452226b4 | C++ | finominal/CoCoPoCoLoCoArtCar | /CoCoPoCoLoCoArtCar.ino | UTF-8 | 9,938 | 2.71875 | 3 | [] | no_license | //#include <Adafruit_NeoPixel.h>
#include "SPI.h"
#include "Adafruit_WS2801.h"
#include <BeaconEntity.h>
#define p(x) Serial.print(x)
#define pl(x) Serial.println(x)
const bool DEV = true;
const int dataPin = 6; // Yellow wire on Adafruit Pixels
const int clockPin = 7; // Green wire on Adafruit Pixels
int brightness = 255; //0-255
const int countEntities = 3;//dont change this
const int StripLength = 50;
volatile int entitySize = 8;
Entity ENTITIES[countEntities];
// Set the first variable to the NUMBER of pixels. 25 = 25 pixels in a row
Adafruit_WS2801 strip = Adafruit_WS2801(StripLength, dataPin, clockPin);
//Adafruit_NeoPixel strip = Adafruit_NeoPixel(StripLength, PIN, NEO_GRB + NEO_KHZ400);
uint32_t pixels[StripLength];
const uint32_t red = Color(255,0,0);
const uint32_t green = Color(0,255,0);
const uint32_t blue = Color(0,0,255);
const uint32_t purple = Color(128,0,128);
const uint32_t yellow = Color(128,128,0);
const uint32_t black = Color(0,0,0);
void setup() {
Serial.begin(115200);
pl("*** ARDUINO RESTART ***");
InitializeEntities();
InitializeStrip();
}
void loop() {
ThreeEntities(1000,30, 14); //itterations, wait, size
Random(200, 200); //itterations, wait
RainbowCycle(10, 20);
ColorWipes(10);
ThreeEntities(3000,5,14);
Cycle(100);
}
void InitializeStrip()
{
strip.begin();
strip.show();
}
void ColorWipes(int waitMs)
{
colorWipe(red, waitMs);
delay(100);
colorWipe(black, waitMs);
delay(100);
colorWipe(green, waitMs);
delay(100);
colorWipe(black, waitMs);
delay(100);
colorWipe(blue, waitMs);
delay(100);
colorWipe(black, waitMs);
delay(100);
colorWipe(purple, waitMs);
delay(100);
colorWipe(black, waitMs);
delay(100);
}
void Random(int itterations, int wait)
{
ShowBlack();
int counter = 0;
int pixel;
while(counter < itterations)
{
SetAllOneColor(Color(32,0,32));
pixel = random(0,StripLength-2);
//pick a random a random led and flash it
switch(random(0,4))
{
case 0:
PulsePixel(pixel, red, wait);
break;
case 1:
PulsePixel(pixel, green, wait);
break;
case 2:
PulsePixel(pixel, blue, wait);
break;
case 3:
PulsePixel(pixel, purple, wait);
break;
case 4:
PulsePixel(pixel, yellow, wait);
break;
}
counter++;
}
}
void SetAllOneColor(uint32_t color)
{
for(int i = 0;i<StripLength;i++)
{
strip.setPixelColor(i, color);
}
strip.show();
}
void PulsePixel(int pixel, uint32_t color, int wait)
{
strip.setPixelColor(pixel, HalfColor(color));
strip.setPixelColor(pixel+1, HalfColor(color));
strip.show();
delay(wait/2);
strip.setPixelColor(pixel, color);
strip.setPixelColor(pixel+1, color);
strip.show();
delay(wait/2);
strip.setPixelColor(pixel, HalfColor(color));
strip.setPixelColor(pixel+1, HalfColor(color));
strip.show();
delay(wait/2);
}
// Create a 24 bit color value from R,G,B
uint32_t HalfColor(uint32_t color)
{
uint8_t r, g, b;
b = (color & 0x0000FF) /5;
color >>= 8;
g = (color & 0x0000FF) /5;
color >>= 8;
r = (color & 0x0000FF) /5;
return Color(r, g, b);
}
void RainbowCycle(int itterations, uint8_t wait)
{
int counter = 0;
while(counter < itterations)
{
int i, j;
for (j=0; j < 256 * 5; j++)
{ // 5 cycles of all 25 colors in the wheel
for (i=0; i < strip.numPixels(); i++)
{
// tricky math! we use each pixel as a fraction of the full 96-color wheel
// (thats the i / strip.numPixels() part)
// Then add in j which makes the colors go around per pixel
// the % 96 is to make the wheel cycle around
strip.setPixelColor(i, WheelHalfBrightness( ((i * 256 / strip.numPixels()) + j) % 256) );
}
strip.show(); // write all the pixels out
delay(wait);
}
counter++;
}
}
void SetBrightness()
{
ENTITIES[0].color = Color(brightness,0,0); //red
ENTITIES[0].colorHalf = Color(brightness/3,0,0); //red
ENTITIES[2].color = Color(0,0,brightness); //blue
ENTITIES[2].colorHalf = Color(0,0,brightness/3); //blue
ENTITIES[1].color = Color(0,brightness,0); //green
ENTITIES[1].colorHalf = Color(0,brightness/3,0); //green
}
void InitializeEntities()
{
//pl("Initialize Entities");
SetBrightness();
ENTITIES[0].direction = up;
ENTITIES[0].position = 0;
ENTITIES[1].direction = up;
ENTITIES[1].position = StripLength*2/3*2*-1;
ENTITIES[2].direction = up;
ENTITIES[2].position = StripLength*2/3*2*2*-1;
}
void ThreeEntities(int itterations, int wait, int entSize)
{
// pl();
// pl("ThreeEntities");
entitySize = entSize;
int counter = 0;
while(counter < itterations)
{
displayEntities();
moveEntities();
delay(wait);
counter++;
}
}
void displayEntities()
{
clearLedBuffer();
processEntitiesToLEDBuffer();
pushPixelsToStrip();
}
void clearLedBuffer()
{
//pl(" clearLedBuffer");
for(int i = 0;i<StripLength;i++)
{
pixels[i] = 0;
}
}
void processEntitiesToLEDBuffer()
{
//pl(" processEntitiesToLEDBuffer");
for(int i = 0; i < countEntities; i++)//for each entity
{
if(ENTITIES[i].position>=0)//check if position is in frame yet
{
if(ENTITIES[i].halfStep)
{
if(ENTITIES[i].direction == up)
{
pixels[ENTITIES[i].position-1] |= ENTITIES[i].colorHalf; //half fade the first pixel
//if(DEV) pl(ENTITIES[i].color);
//if(DEV) pl(pixels[ENTITIES[i].position-1]);
for(int j = 0; j < entitySize-1; j++)//full brightness for the middle pixels
{
pixels[ENTITIES[i].position+j] |= ENTITIES[i].color;
}
pixels[ENTITIES[i].position+entitySize-1] |= ENTITIES[i].colorHalf; //half fade the last pixel
ENTITIES[i].halfStep = false;//next step will NOT a half step
}
else //if(ENTITIES[i].direction == down)
{
pixels[ENTITIES[i].position] |= ENTITIES[i].colorHalf; //half fade the first pixel
for(int j = 1; j < entitySize; j++)//full brightness for the middle pixels
{
pixels[ENTITIES[i].position+j] |= ENTITIES[i].color;
}
pixels[ENTITIES[i].position+entitySize] |= ENTITIES[i].colorHalf; //half fade the last pixel
ENTITIES[i].halfStep = false;//next step will NOT be a half step
}
}
else //not half step, display full unit
{
for(int j = 0; j < entitySize; j++)//for entity size (each pixel)
{
pixels[ENTITIES[i].position+j] |= ENTITIES[i].color;
}
ENTITIES[i].halfStep = true;//next step WILL be a half step
}
}
}
//if(DEV) showPixels();
}
void ShowBlack()
{
//pl(" pushPixelsToStrip");
for(int i = 0; i<StripLength; i++)
{
strip.setPixelColor(i,0);
}
strip.show();
}
void pushPixelsToStrip()
{
//pl(" pushPixelsToStrip");
for(int i = 0; i<StripLength; i++)
{
strip.setPixelColor(i,pixels[i]);
}
strip.show();
}
void showPixels()
{
//pl("ShowPixels");
for(int i = 0; i<StripLength; i++)
{
pl(pixels[i]);
}
}
void moveEntities()
{
//pl(" moveEntities");
for(int i = 0;i<countEntities;i++)
{
if(ENTITIES[i].position <0){ENTITIES[i].position++;}//startup, enter from off screen
else if(ENTITIES[i].halfStep == true) //only move entities that have completed a half step(false = complete)
{
if( ENTITIES[i].direction == up)
{
if(ENTITIES[i].position == StripLength - entitySize)
{
ENTITIES[i].direction = down;
ENTITIES[i].position--;
}
else
{
ENTITIES[i].position++;
}
}
else //diretion is down
{
if(ENTITIES[i].position == 0)
{
ENTITIES[i].direction = up;
ENTITIES[i].position++;
}
else
{
ENTITIES[i].position--;
}
}
}//end if(ENTITIES[i].halfStep == true)
}//end for each entity
//if(DEV)showEntityPositions();
}
void showEntityPositions()
{
p(" ~Entity 0 Position: ");
pl(ENTITIES[0].position);
p(" ~Entity 1 Position: ");
pl(ENTITIES[1].position);
p(" ~Entity 2 Position: ");
pl(ENTITIES[2].position);
}
// fill the dots one after the other with said color
// good for testing purposes
void colorWipe(uint32_t c, uint8_t wait) {
int i;
for (i=0; i < strip.numPixels(); i++) {
strip.setPixelColor(i, c);
strip.show();
delay(wait);
}
}
/* Helper functions */
void Cycle(uint8_t wait) {
int i, j;
for (j=0; j < 2560; j++) { // 3 cycles of all 256 colors in the wheel
for (i=0; i < strip.numPixels(); i++) {
strip.setPixelColor(i, WheelHalfBrightness( (i + j) % 255));
}
strip.show(); // write all the pixels out
delay(wait);
}
}
/* Helper functions */
// Create a 24 bit color value from R,G,B
uint32_t Color(byte r, byte g, byte b)
{
uint32_t c;
c = r;
c <<= 8;
c |= g;
c <<= 8;
c |= b;
return c;
}
//Input a value 0 to 255 to get a color value.
//The colours are a transition r - g -b - back to r
uint32_t Wheel(byte WheelPos)
{
if (WheelPos < 85) {
return Color(WheelPos * 3, 255 - WheelPos * 3, 0);
} else if (WheelPos < 170) {
WheelPos -= 85;
return Color(255 - WheelPos * 3, 0, WheelPos * 3);
} else {
WheelPos -= 170;
return Color(0, WheelPos * 3 , 255 - WheelPos * 3 );
}
}
uint32_t WheelHalfBrightness(byte WheelPos)
{
if (WheelPos < 85) {
return Color((WheelPos * 3)/2, (255 - WheelPos * 3)/2, 0);
} else if (WheelPos < 170) {
WheelPos -= 85;
return Color((255 - WheelPos * 3)/2, 0, (WheelPos * 3)/2);
} else {
WheelPos -= 170;
return Color(0, (WheelPos * 3 )/2, (255 - WheelPos * 3)/2 );
}
}
| true |
e3bf5bed78300df8ea88611b051189bf0fb644fd | C++ | Valeria-Bravo/lp-2019 | /Basic2/cod_01.cpp | UTF-8 | 326 | 3.078125 | 3 | [] | no_license | #include <iostream>
using namespace std;
//int area ( int length, int width );
int area ( int length, int width )
{
return length*width ;
}
int main ( )
{
int s1 =area(7,7) ;//(7);
int s2 =area (7,7) ;//( 7 )
int s3 =area (7,7) ; //(7);
int s4 =area (7,7) ; //() ;
return area ( 4 , 4 ) ;
} | true |
ffbeddf310b08d2be06861b2a94ae746a4775116 | C++ | 2032463198/C_exercise | /exersice7-3.cpp | UTF-8 | 353 | 3.234375 | 3 | [] | no_license | #include<stdio.h>
int isprime(int a)
{
int i,x=0;
for(i=2;i<=a/2;i++)
{
if(a%i==0)
{x=1;
break;}
}
return(x);
}
int main()
{
int isprime(int a),a;
printf("please input an int:\n");
scanf("%d",&a);
if(isprime(a)==1)
{printf("yes\n");}
else
{printf("no\n");}
} | true |
c293ffe82754e70b6173a4e08708c4d3f143b33a | C++ | inyeolsohnn/ConsoleApp4 | /Matrix.h | UTF-8 | 3,267 | 3.421875 | 3 | [] | no_license | #pragma once
#include <iostream>
namespace Moo {
class Matrix
{
public:
Matrix();
Matrix(Matrix&& src) {
std::cout << "move constructor" << std::endl;
rowCount = src.rowCount;
colCount = src.colCount;
values = src.values;
src.rowCount = 0;
src.colCount = 0;
src.values = nullptr;
}
Matrix(const Matrix& copyMat) :rowCount(copyMat.rowCount), colCount(copyMat.colCount){
std::cout << "copy operator" << std::endl;
values = new float*[rowCount];
for (int i = 0; i < rowCount; i++) {
values[i] = new float[colCount];
}
for (int i = 0; i < rowCount; i++) {
for (int j = 0; j < colCount; j++) {
values[i][j] = copyMat.values[i][j];
}
}
}
Matrix(int x, int y) :rowCount(y), colCount(x)
{
values = new float*[y];
for (int i = 0; i < y; i++) {
values[i] = new float[x];
}
for (int i = 0; i < rowCount; i++) {
for (int j = 0; j < colCount; j++) {
values[i][j] = 0.0f;
}
}
}
~Matrix() {
for (int i = 0; i < rowCount; i++) {
delete[] values[i];
}
delete[] values;
}
Matrix& operator=(Matrix&& src) {
std::cout << "move assignment operator" << std::endl;
if (this == &src) {
return *this;
}
else {
for (int i = 0; i < rowCount; i++) {
delete[] values[i];
}
delete[] values;
values = nullptr;
rowCount = src.rowCount;
colCount = src.colCount;
values = src.values;
src.rowCount = 0;
src.colCount = 0;
src.values = nullptr;
return *this;
}
}
Matrix& operator=(const Matrix& rhs) {
std::cout << "assignment operator" << std::endl;
if (this == &rhs) {
return *this;
}
else {
for (int i = 0; i < rowCount; i++) {
delete[] values[i];
}
delete[] values;
values = nullptr;
rowCount = rhs.rowCount;
colCount = rhs.colCount;
values = new float*[rowCount];
for (int i = 0; i < rowCount; i++) {
values[i] = new float[colCount];
}
for (int i = 0; i < rowCount; i++) {
for (int j = 0; j < colCount; j++) {
values[i][j] = rhs.values[i][j];
}
}
return *this;
}
}
Matrix operator *(const Matrix& mat) {
//this*mat
//check row column count
if (colCount == mat.rowCount) {
//carry out the operation
Matrix resultMat(mat.colCount, this->rowCount);
for (int r = 0; r < resultMat.rowCount; r++) {
for (int c = 0; c < resultMat.colCount; c++) {
float temp = 0.0f;
for (int leftC = 0; leftC < colCount; leftC++) {
for (int rightR = 0; rightR < mat.rowCount; rightR++) {
temp += values[r][leftC] * mat.values[rightR][c];
}
}
std::cout << "row :"<<r <<", col : "<< c<<", temp : " << temp << std::endl;;
resultMat.values[r][c] = temp;
}
}
return resultMat;
}
else {
//don't carry out the operation
//throw exception;
std::cout << "mat * operation error" << std::endl;
return Matrix(0,0);
}
}
void print() {
for (int i = 0; i < rowCount; i++) {
for (int j = 0; j < colCount; j++) {
std::cout << this->values[i][j]<<" ";
}
std::cout << std::endl;
}
}
private:
public:
float** values;
int colCount;
int rowCount;
private:
};
}
| true |
8fffaca8f6ed6082656bc711224083534c41b642 | C++ | kyuhwang3/AwayTeamstar | /study/2178.cpp | UTF-8 | 2,700 | 2.796875 | 3 | [] | no_license | #include <iostream>
#include <queue>
#include <cstdio>
using namespace std;
int source, target;
//int adj[100005];
int dist[100005];
int prop[100005];
int vis[100005];
int counter;
struct node{
int cur;
int count;
};
int calc(){
int ans = 1;
if (target - 1 >= 0 && dist[target - 1] == dist[target] - 1){
ans += prop[target - 1];
}
else if (target + 1 <= 100000 && dist[target + 1] == dist[target] - 1){
ans += prop[target + 1];
}
else if (target % 2 == 0 && dist[target / 2] == dist[target] - 1){
ans += prop[target / 2];
}
return ans;
}
void bfs(int src)
{
queue<node> q;
node tempNode;
tempNode.cur = src;
tempNode.count = 0;
q.push(tempNode);
dist[src] = 0;
vis[src] = 1;
while(!q.empty()){
node cur=q.front(); q.pop();
tempNode.count = cur.count + 1;
if (cur.cur - 1 >= 0){
if ((vis[cur.cur - 1] == 1 && dist[cur.cur - 1] == dist[cur.cur]) || (vis[cur.cur - 1] != 1)){
if (dist[cur.cur] + 1 < dist[cur.cur - 1]){
dist[cur.cur - 1] = cur.count + 1;
}
tempNode.cur = cur.cur - 1;
if (cur.cur - 1 == target){
dist[target] = cur.count + 1;
prop[target] = calc();
return;
}
q.push(tempNode);
vis[cur.cur - 1] = 1;
}
prop[cur.cur - 1] ++;
}
if (cur.cur + 1 <= 100000){
if ((vis[cur.cur + 1] == 1 && dist[cur.cur + 1] == dist[cur.cur]) || (vis[cur.cur + 1] != 1)){
if (dist[cur.cur] + 1 < dist[cur.cur + 1]){
dist[cur.cur + 1] = cur.count + 1;
}
tempNode.cur = cur.cur + 1;
if (cur.cur + 1 == target){
dist[target] = cur.count + 1;
prop[target] = calc();
return;
}
q.push(tempNode);
vis[cur.cur + 1] = 1;
}
prop[cur.cur + 1] ++;
}
if (cur.cur * 2 <= 100000){
if ((vis[cur.cur * 2] == 1 && dist[cur.cur * 2] == dist[cur.cur]) || vis[cur.cur * 2] != 1){
if (dist[cur.cur] + 1 < dist[cur.cur * 2]){
dist[cur.cur * 2] = cur.count + 1;
}
tempNode.cur = cur.cur * 2;
if (cur.cur * 2 == target){
dist[target] = cur.count + 1;
prop[target] = calc();
return;
}
q.push(tempNode);
vis[cur.cur * 2] = 1;
}
prop[cur.cur * 2] ++;
}
}
}
int main()
{
counter = 0;
for (int i = 0; i < 100005; ++i){
dist[i] = 100005;
vis[i] = 0;
prop[i] = 0;
}
cin >> source >> target;
bfs(source);
//counter = 0;
//dfs(source, 0);
/*
bfs(source);
for (int i = 0; i <= 25; ++i){
cout << i << ": " << propCount[i] << endl;
}
*/
cout << dist[target] << endl;
if (source == target){
cout << 0 << endl;
}
else{
cout << prop[target] << endl;
}
}
| true |
686029cd88592585b28e131c9420733785c47d1c | C++ | zos12/programming | /纸牌游戏,最优策略.cpp | UTF-8 | 1,042 | 3.484375 | 3 | [] | no_license | /*牛牛和羊羊正在玩一个纸牌游戏。这个游戏一共有n张纸牌, 第i张纸牌上写着数字ai。
牛牛和羊羊轮流抽牌, 牛牛先抽, 每次抽牌他们可以从纸牌堆中任意选择一张抽出, 直到纸牌被抽完。
他们的得分等于他们抽到的纸牌数字总和。
现在假设牛牛和羊羊都采用最优策略, 请你计算出游戏结束后牛牛得分减去羊羊得分等于多少。*/
/*最优策略即纸牌从大到小排列,两个人依次抽取,(sort函数是从小到大排列),用布尔类型0 1 确定谁抽纸牌*/
#include<iostream>
#include<algorithm>
using namespace std;
int main(){
long n;
scanf("%ld",&n);
long a[n];
for(int i = 0; i < n; i++){
scanf("%ld",&a[i]);
}
sort(a,a+n); //从小到大
long rest = 0;
int flag = 1;
for(int j = n - 1; j>=0; j--){
if(flag){
rest += a[j];
flag = 0;
}else{
rest -= a[j];
flag = 1;
}
}
printf("%ld",rest);
} | true |
b5f7090d5dccf111aa6f4afbc587e9e29d5bdb2f | C++ | AU-PSL/demon_simulation_code | /DrivingForce.h | UTF-8 | 1,265 | 2.84375 | 3 | [
"BSD-3-Clause"
] | permissive | /**
* @file DrivingForce.h
* @brief Defines the data and methods of the DrivingForce class
*
* @license This file is distributed under the BSD Open Source License.
* See LICENSE.TXT for details.
**/
#ifndef DRIVINGFORCE_H
#define DRIVINGFORCE_H
#include "Force.h"
#include "VectorCompatibility.h"
class DrivingForce : public Force {
public:
DrivingForce(Cloud * const C, const double dampConst, const double amp, const double drivingShift)
: Force(C), amplitude(amp), driveConst(-dampConst), shift(drivingShift) {}
~DrivingForce() {}
void force1(const double currentTime); // rk substep 1
void force2(const double currentTime); // rk substep 2
void force3(const double currentTime); // rk substep 3
void force4(const double currentTime); // rk substep 4
void writeForce(fitsfile * const file, int * const error) const;
void readForce(fitsfile * const file, int * const error);
private:
double amplitude; //!< Amplitude of driving force [N]
double driveConst; //!< [m^2]
double shift; //!< [m]
static const double waveNum; //!< [m^-1]
static const double angFreq; //!< [rad*Hz]
void force(const cloud_index currentParticle, const doubleV currentTime, const doubleV currentPositionX);
};
#endif // DRIVINGFORCE_H
| true |
a94488d24c944238902293f1293230d2924cc71f | C++ | cowtony/ACM | /ZOJ/2807 Electrical Outlets.cpp | GB18030 | 667 | 2.96875 | 3 | [] | no_license | /*
ǽֻһͷ߰壬߰ϵIJͷмòͷ
ÿ߰IJͷ
ڱĵطԻҪһ
в߰IJͷĺͼȥ߰
Ϊտʼʱһټ1
ؼʣ⣬㷨
*/
#include<iostream>
using namespace std;
int main()
{
int n;
cin>>n;
while(n--)
{
int k;
cin>>k;
int sum=0;
for(int i=0;i<k;i++)
{
int t;
cin>>t;
sum+=t;
}
cout<<sum-k+1<<endl;
}
}
| true |
a1a90590dea9738c8949984b3f769acc0ef96687 | C++ | LuisDa/Riego_Rpi | /libcomms/testReceive.cpp | UTF-8 | 2,152 | 2.5625 | 3 | [] | no_license | /*
* testReceive.cpp
*
* Created on: 27/05/2012
* Author: luisda
*/
#include "include/message_receiver.hpp"
#include "include/network_interface_manager.hpp"
#include <stdexcept>
#include <signal.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
using std::runtime_error;
using namespace std;
bool g_undefined_loop;
void sigsegv(int sig);
void sigusr1(int sig);
void sigusr2(int sig);
void show_help(void) {
printf(" Usage: ./testReceive <netIf> <Port_number> [<Continuous(0=false, other=true)>]\n");
printf("\n");
}
int main (int argc, char* argv[]) {
g_undefined_loop = false;
CMessageReceiver *cMsgRcv;
if (argc < 3) {
show_help();
exit(0);
} else if (argc == 4) {
g_undefined_loop = true;
}
sockaddr_in sdrInfo;
sockaddr_in* sdrInfo_p = NULL;
word port;
char* netIf;
netIf = argv[1];
/*
char* ifIP = NULL;
ifIP = new char[NI_MAXHOST];
//TODO Crear un Unit Test aparte para CNetworkInterfaceManager
CNetworkInterfaceManager *cNetIfMgr = new CNetworkInterfaceManager();
cNetIfMgr -> getInterfaceIP(netIf, ifIP);
printf("IP Address for interface %s is %s\n", netIf, ifIP);
delete[] ifIP;
ifIP = NULL;
*/
port = (word)(atoi(argv[2]));
signal((int)SIGSEGV, sigsegv);
signal((int)SIGUSR1, sigusr1);
signal((int)SIGUSR2, sigusr2);
cMsgRcv = new CMessageReceiver(port, netIf);
do {
cMsgRcv -> receiveMessage();
sdrInfo = cMsgRcv -> getSenderInfo();
char* msg = cMsgRcv -> getReceivedMessage();
printf("MENSAJE RECIBIDO: %s\n", msg);
printf("HOST ORIGEN: IP = %s, PUERTO = %d \n", inet_ntoa(sdrInfo.sin_addr), ntohs(sdrInfo.sin_port));
sdrInfo_p = cMsgRcv -> getSenderInformation();
printf("LO MISMO, CON PUNTEROS: IP = %s, PORT = %d\n",
inet_ntoa(sdrInfo_p -> sin_addr), ntohs(sdrInfo_p -> sin_port));
} while(g_undefined_loop);
printf("SOLID ROCK!!!!!!\n");
delete cMsgRcv;
cMsgRcv = NULL;
}
void sigsegv(int sig) {
printf ("MALO MALO... ESTO HA PEGADO UN PETARDAZO\n");
exit(-1);
}
void sigusr1(int sig) {
printf("Recibido SIGUSR1 \n");
g_undefined_loop = false;
}
void sigusr2(int sig) {
printf("RECIBIDO SIGUSR2, no hago nada y te comes un MOHON\n");
}
| true |
0ec3fbba139827018dcbb77cfe40d530a6ad9d01 | C++ | tachikawa-syota/3D_BattleGame | /Source/3DGame/DirectX/AnimMesh.h | SHIFT_JIS | 4,216 | 2.703125 | 3 | [] | no_license | /**
* @file AnimMesh.h
* @brief Aj[VbV
* @author Syota Tachikawa
*/
#ifndef ___ANIMMESH_H
#define ___ANIMMESH_H
#include "Mesh.h"
#include "AnimHierarchy.h"
/// Aj[Vx
#define ANIM_SPEED 1.0f/60
/**
* @brief XLbVNX
*/
class SkinMesh : public Mesh, public Hierachy
{
public:
/**
* @brief RXgN^
*/
SkinMesh();
/**
* @brief fXgN^
*/
~SkinMesh();
/**
* @brief Aj[VbV̓ǂݍ
* @param path - pX
* @param xFileName - wt@C̖O
*/
bool LoadAnimeXMesh(string path, LPSTR xFileName);
/**
* @brief Aj[VbV̕`
*/
void RenderAnimeXMesh();
/**
* @brief Aj[VbV̕`(VF[_[)
*/
void RenderAnimeXMesh(const Matrix& view, const Matrix& proj);
/**
* @brief e`悷
*/
void DrawShadow(LPD3DXFRAME pFrameBase);
/**
* @brief Aj[Vt[̍XV
*/
void UpdateFrame();
/**
* @brief Aj[Vt[̍XV
*/
void UpdateFrame(float speed);
/**
* @brief Aj[VŌ܂ōĐς݂
*/
bool IsAnimPeriod();
/**
* @brief Aj[VRg[[̎擾
*/
LPD3DXANIMATIONCONTROLLER GetController();
/**
* @brief Aj[V^C擾
*/
float GetTime();
/**
* @brief Aj[Vԍ擾
*/
int GetNowAnimNo();
/**
* @brief At@l̎擾
*/
float GetAlpha();
/**
* @brief OŃ{[p[c
* @param name Aj[V
*/
bool GetPartsMatrixByName(Matrix *pOut, LPCSTR name);
/**
* @brief At@lݒ
*/
void SetAlpha(float alpha);
/**
* @brief Aj[Vւ
* @param dwSetNo Aj[Vԍ
* @param bLoop Aj[vtO
*/
void SetAnimNo(DWORD dwAnimNo, bool bLoop);
/**
* @brief Aj[VO
* @param dwSetNo Aj[Vԍ
* @param bLoop Aj[vtO
*/
void SetAnimName(LPCSTR szName, bool bLoop);
/**
* @brief Aj[ṼVtgԂݒ
*/
void SetAnimShiftTime(float fTime);
private:
static const int MaxBoneMatrix = 12;
/// foCX
LPDIRECT3DDEVICE9 m_pDevice;
/// Aj[VRg[[
LPD3DXANIMATIONCONTROLLER m_pAnimController;
/// Aj[VZb^[
LPD3DXANIMATIONSET* m_pAnimSet;
/// ݂̃Aj[Vԍ
int m_nNowAnimeNo;
/// Aj[VZbg
DWORD m_uNumAnimSet;
/// At@l
float m_alpha;
float m_animCurWeight;
/// Aj[ṼVtg
float m_totalShiftTime;
/// Aj[VI
float m_animPeriod;
/// ւtO
bool m_bChanging;
/**
* @brief
*/
void Initialize();
/**
* @brief Aj[V
*/
void FreeAnim(LPD3DXFRAME pFrame);
/**
* @brief `t[
*/
void DrawFrame(LPD3DXFRAME pFrameBase);
/**
* @brief `t[(VF[_[)
*/
void DrawFrame(const Matrix& view, const Matrix& proj, LPD3DXFRAME pFrameBase);
/**
* @brief t[XV
*/
void UpdateFrameMatrices(LPD3DXFRAME pFrameBase, LPD3DXMATRIX pParentMatrix);
/**
* @brief _ORei
*/
void RenderMeshContainer(const MeshContainer *pMeshContainer, const Frame *pFrame);
/**
* @brief _ORei(VF[_[)
*/
void RenderMeshContainer(const Matrix& view, const Matrix& proj, const MeshContainer *pMeshContainer, const Frame *pFrame);
/**
* @brief OŃp[cċAp
* @param name Aj[V
*/
bool _GetPartsMatrixByName(Matrix *pOut, LPD3DXFRAME pFrameBase, LPCSTR szName);
/**
* @brief {[s̏
*/
HRESULT AllocateBoneMatrix(LPD3DXMESHCONTAINER pMeshContainerBase);
/**
* @brief SẴ{[s
*/
HRESULT AllocateAllBoneMatrices(LPD3DXFRAME pFrame);
};
/// XLbṼX}[g|C^
using SkinMeshPtr = shared_ptr<SkinMesh>;
#endif | true |
853fe2242edb321a524ff379740cdf34ffc4af0b | C++ | JeppeNielsen/MiniEngine | /Mini/Logic/Gui/DroppableSystem.cpp | UTF-8 | 2,855 | 2.515625 | 3 | [] | no_license | //
// DroppableSystem.h
// GUIEditor
//
// Created by Jeppe Nielsen on 03/10/15.
// Copyright (c) 2015 Jeppe Nielsen. All rights reserved.
//
#include "DroppableSystem.hpp"
#include "Draggable.hpp"
#include "Mesh.hpp"
using namespace Mini;
void DroppableSystem::Initialize() {
//touchSystem = &scene->CreateSystem<TouchSystem>();
}
void DroppableSystem::ObjectAdded(GameObject object) {
object.GetComponent<Touchable>()->Down.Bind(this, &DroppableSystem::TouchDown, object);
object.GetComponent<Touchable>()->Up.Bind(this, &DroppableSystem::TouchUp, object);
}
void DroppableSystem::ObjectRemoved(GameObject object) {
object.GetComponent<Touchable>()->Down.Unbind(this, &DroppableSystem::TouchDown, object);
object.GetComponent<Touchable>()->Up.Unbind(this, &DroppableSystem::TouchUp, object);
auto it = downObjects.find(object);
if (it!=downObjects.end()) {
downObjects.erase(it);
}
}
void DroppableSystem::Update(float dt) {
for(auto it = downObjects.begin(); it!=downObjects.end();) {
Vector2 pos = Input()->GetTouchPosition(it->second.touchData.Index);
Vector2 delta = pos - it->second.prevPosition;
if (delta.Length()>it->second.maxMovement) {
DropStarted(it->second.touchData, it->first);
it = downObjects.erase(it);
} else {
++it;
}
}
}
void DroppableSystem::TouchDown(TouchData d, GameObject object) {
DownObject& downObject = downObjects[object];
downObject.touchData = d;
downObject.prevPosition = d.Position;
downObject.maxMovement = object.GetComponent<Droppable>()->activateThreshhold;
downObject.createdObject = 0;
}
void DroppableSystem::DropStarted(TouchData d, GameObject object) {
Droppable* droppable = object.GetComponent<Droppable>();
GameObject clone = droppable->OnCreate(object, d);
clone.AddComponent<Draggable>();
touchSystem->EnqueueDown(clone, d);
objectToClone[object] = clone;
}
void DroppableSystem::TouchUp(TouchData d, GameObject object) {
auto it = downObjects.find(object);
if (it!=downObjects.end()) {
downObjects.erase(it);
} else {
DroppedData droppedData;
droppedData.object = object;
droppedData.touchData = d;
TouchEvent e(d.Index, d.Input->GetTouchPosition(d.Index));
touchSystem->FindTouchedObjects(droppedData.droppedTouches, e, true);
for (int i=0; i<droppedData.droppedTouches.size(); ++i) {
if (droppedData.droppedTouches[i].object == object) {
droppedData.droppedTouches.erase(droppedData.droppedTouches.begin()+i);
break;
}
}
object.GetComponent<Droppable>()->Dropped(droppedData);
auto it = objectToClone.find(object);
it->second.Remove();
//objectToClone.erase(it);
}
}
| true |
f265d3a9e58bcd186807f5bd33f3633c439d2e36 | C++ | HowCanidothis/DevLib | /SharedModule/Process/processbase.cpp | UTF-8 | 2,335 | 2.75 | 3 | [
"MIT"
] | permissive | #include "processbase.h"
#include "processfactory.h"
ProcessBase::ProcessBase()
: m_interruptor(nullptr)
, m_silentIfOneStep(false)
{
}
ProcessBase::~ProcessBase()
{
if(m_interruptor != nullptr) {
m_interruptor->OnInterrupted() -= this;
}
}
void ProcessBase::SetInterruptor(const Interruptor& interruptor)
{
Q_ASSERT(m_interruptor == nullptr);
m_interruptor = ::make_scoped<Interruptor>(interruptor);
m_interruptor->OnInterrupted() += { this, [this]{
m_processValue->finish();
}};
}
const QString& ProcessBase::GetTitle() const
{
return m_processValue->GetTitle();
}
void ProcessBase::BeginProcess(const ProcessBaseIndeterminateParams& params)
{
m_processValue = nullptr;
m_processValue.reset(ProcessFactory::Instance().createIndeterminate());
m_processValue->SetId(m_id);
m_processValue->init(m_interruptor.get(), params.Title);
}
void ProcessBase::BeginProcess(const ProcessBaseDeterminateParams& params)
{
auto stepsCount = params.StepsCount;
auto wantedCount = params.WantedCount;
if((stepsCount != 0) && (wantedCount != 0) && (stepsCount > wantedCount)) {
m_divider = stepsCount / wantedCount;
} else {
m_divider = 0;
}
m_processValue = nullptr;
auto value = ProcessFactory::Instance().createDeterminate();
value->SetDummy(m_silentIfOneStep && m_divider < 2);
value->init(m_interruptor.get(), params.Title, stepsCount);
value->SetId(m_id);
m_processValue.reset(value);
}
void ProcessBase::SetProcessTitle(const QString& title)
{
m_processValue->setTitle(title);
}
void ProcessBase::SetId(const Name& id)
{
m_id = id;
}
void ProcessBase::BeginProcess(const QString& title)
{
BeginProcess(ProcessBaseIndeterminateParams(title));
}
void ProcessBase::BeginProcess(const QString& title, int stepsCount, int wantedCount)
{
BeginProcess(ProcessBaseDeterminateParams(title, stepsCount).SetWantedCount(wantedCount));
}
void ProcessBase::IncreaseProcessStepsCount(int stepsCount)
{
if(auto determinate = m_processValue->AsDeterminate()) {
determinate->increaseStepsCount(stepsCount);
}
}
void ProcessBase::IncrementProcess()
{
m_processValue->incrementStep(m_divider);
}
bool ProcessBase::IsProcessCanceled() const
{
return m_processValue->IsFinished();
}
| true |
5fcadf66056a40c3d8989897de16e0422aa1f9a7 | C++ | juliatoklowicz/Programowanie-obiektowe | /lab1/HelloCpp/hello.cpp | UTF-8 | 524 | 3.421875 | 3 | [] | no_license | #include <iostream>
#include <string>
int main(){
std::string fellow = "world";
std::cout << "Hello " << fellow << std::endl;
while (fellow != "exit") {
std::cout << "Introduce yourself: ";
std::cout.flush();
std::getline(std::cin, fellow);
if(fellow != "exit")
std::cout << "Hello" << fellow << std::endl;
}
return 0;
}
//do funkcji while trzeba bylo dodac if, ktory sprawdza czy uzytkownik podal "exit" aby program dzialal poprawnie | true |
540ba7b4464a79cdd7f894233277ea0842814b7a | C++ | thematyld/Arduino | /MembraneKey/bejvak/bejvak.ino | UTF-8 | 1,820 | 2.671875 | 3 | [] | no_license | #include "IRremote.h"
#define KEY_COUNT 2
//-----------------------------------------------------------------------------//
const int rele[4]={8,9,10,11};
const int keys[4]={2,3,4,5};
const int IR=12;
IRrecv irrecv(IR);
decode_results IRresult;
int key[4];
char keyOn[4];
unsigned long prevTime[4];
//-----------------------------------------------------------------------------//
void decodeIR();
void turnKey(byte numKey,unsigned int minTime,int device,unsigned long *lastTime);
//-----------------------------------------------------------------------------//
void setup() {
for(int i=0;i<KEY_COUNT;i++){
keyOn[i]=true;
prevTime[i]=0;
pinMode(rele[i],OUTPUT);
digitalWrite(rele[i],HIGH);
pinMode(keys[i],INPUT_PULLUP);
}
irrecv.enableIRIn();
Serial.begin(9600);
}
void loop() {
turnKey(0,750,rele[0],&prevTime[0]);
turnKey(1,750,rele[1],&prevTime[1]);
if(irrecv.decode(&IRresult)){
decodeIR();
irrecv.resume();
}
delay(10);
}
void decodeIR(){
switch(IRresult.value){
case 0xFF40BF:
case 0xFF6897: IRturning(rele[0],&keyOn[0]); break;
case 0xFFEA15:
case 0xFF9867: IRturning(rele[1],&keyOn[1]); break;
}
}
void IRturning(int device,char *state){
if(*state){
digitalWrite(device,LOW);
*state=false;
}
else{
digitalWrite(device,HIGH);
*state=true;
}
}
void turnKey(byte numKey,unsigned int minTime,int device,unsigned long *lastTime){
if(numKey>=KEY_COUNT)
return;
key[numKey]=digitalRead(keys[numKey]);
unsigned int Time=millis()-(*lastTime);
if(!key[numKey] && Time>minTime){
(*lastTime)=millis();
if(keyOn[numKey]==false){
digitalWrite(device,HIGH);
keyOn[numKey]=true;
}
else{
digitalWrite(device,LOW);
keyOn[numKey]=false;
}
}
}
| true |
5154c5f5bf321799e9c89b1267feb0c44e30a4ee | C++ | JacobHensley/Gaia | /GaiaEngine/src/utils/FileUtils.h | UTF-8 | 507 | 2.703125 | 3 | [] | no_license | #pragma once
#include "GaPCH.h"
#include "Common.h"
static String ReadFile(const String& path)
{
FILE* file = fopen(path.c_str(), "rb");
if (!file) {
std::cout << "Failed to open file at path: " << path.c_str() << std::endl;
return String();
}
fseek(file, 0, SEEK_END);
long size = ftell(file);
String result(size, 0);
fseek(file, 0, SEEK_SET);
fread(&result[0], 1, size, file);
fclose(file);
result.erase(std::remove(result.begin(), result.end(), '\r'), result.end());
return result;
} | true |
7bcca32b2581198b5cbc3b241a407c8603cc27d6 | C++ | caixuanting/trading_system | /utils/queue_test.cc | UTF-8 | 916 | 2.59375 | 3 | [] | no_license | // Copyright 2016, Xuanting Cai
// Email: caixuanting@gmail.com
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE
#include <thread>
#include <boost/test/unit_test.hpp>
#include "utils/queue.h"
namespace util {
struct QueueFixture {
QueueFixture() { queue.reset(new Queue<int32_t>()); }
virtual ~QueueFixture() {}
std::unique_ptr<Queue<int32_t>> queue;
};
BOOST_FIXTURE_TEST_SUITE(QueueTest, QueueFixture)
BOOST_AUTO_TEST_CASE(Wait) {
std::thread wait_thread([this] {
this->queue->Wait();
this->queue->Insert(20);
});
int32_t front = queue->Next();
BOOST_CHECK_EQUAL(0, front);
BOOST_CHECK_EQUAL(0, queue->Size());
queue->Notify();
wait_thread.join();
BOOST_CHECK_EQUAL(1, queue->Size());
front = queue->Next();
BOOST_CHECK_EQUAL(20, front);
BOOST_CHECK_EQUAL(0, queue->Size());
}
BOOST_AUTO_TEST_SUITE_END()
} // namespace util
| true |
159e5eb134a2634b6d1bdb516f8244ddb60978ca | C++ | radsn/cplusplus | /p10b/hwk3/string/main.cpp | UTF-8 | 5,721 | 3.375 | 3 | [] | no_license | /**
@file Source.cpp
@brief This file has a running main routine for a string class. Read the remarks below, especially item 4 if your are not using
Visual Studio for compilation.
This file makes use of a string class defined and implemented in BasicString.h and BasicString.cpp
Important Remarks:
1. The real std::string class has more bells and whistles but this is a hopefully friendly introduction to
RAII classes and memory management.
2. The resulting outputs could vary from compiler to compiler due to various optimizations. There are differences
between Windows Visual Studio 2017 and g++, for example, in how well they elide initializations.
3. The .print() commands could be replaced by overloading and defining the << operator
but at this point in time we stick to just using the print function. This implementation
also deletes the implementations of the assignment operators.
4. To be discussed later: it can be dangerous to initialize a raw pointer with a new expression within the constructor
initializer list: this is why we initially set it to nullptr.
*/
#include "String.h"
#include "SimpleMemory.h"
/**
This function returns a basic::string storing "Hello world!". Note that it makes a local variable and then returns
a copy of that local variable.
@return a string with "Hello world!"
*/
basic::string named() {
basic::string s("Hello world!");
return s;
}
/**
This function returns a basic::string storing "!dlrow olleH". Note that it does not name its return value - it may
behave differently than named() above on some compilers as a result.
@return a basic::string with "!dlrow olleH"
*/
basic::string unnamed() {
return "!dlrow olleH";
}
int main() {
_BEGIN_MEMORY_CHECK_
// new scope, stringNumber0 is first on the stack
basic::string stringNumber0; // default
std::cout << "stringNumber0: ";
stringNumber0.print();
std::cout << '\n';
{ // new scope, stringNumber1, stringNumber2, stringNumber3, stringNumber4 added to stack
basic::string stringNumber1 = "A"; // with const char: may optimize away copy
std::cout << "stringNumber1: ";
stringNumber1.print();
std::cout << '\n';
basic::string stringNumber2("B"); // direct with const char*
basic::string stringNumber3("CDE");
basic::string stringNumber4("");
std::cout << "stringNumber2: ";
stringNumber2.print();
std::cout << '\n';
std::cout << "stringNumber3: ";
stringNumber3.print();
std::cout << '\n';
std::cout << "stringNumber4: ";
stringNumber4.print();
std::cout << '\n';
std::cout << "stringNumber3 after concatenting stringNumber2: ";
stringNumber3.concat(stringNumber2); // now stringNumber3 is CDEB
stringNumber3.print();
std::cout << '\n';
// but stringNumber2 unchanged
std::cout << "stringNumber2 still unchanged: ";
stringNumber2.print();
std::cout << '\n';
{ // new scope stringNumber5 added to stack
basic::string stringNumber5 = stringNumber2; // implicitly calls copy constructor when = used!
std::cout << "stringNumber5: ";
stringNumber5.print();
std::cout << '\n';
std::cout << "leaving a scope: " << '\n';
std::cout << '\n';
} // stringNumber5 destroyed
basic::string stringNumber6 = std::move(stringNumber2); // will implicitly invoke move constructor, move = rvalue
basic::string stringNumber7(std::move(stringNumber3)); // directly calls move constructor
std::cout << '\n' << "stringNumber6: ";
stringNumber6.print();
std::cout << '\n';
std::cout << "stringNumber7: ";
stringNumber7.print();
std::cout << '\n';
std::cout << "stringNumber2 after moved from: ";
stringNumber2.print();
std::cout << '\n';
std::cout << "stringNumber3 after moved from: ";
stringNumber3.print();
std::cout << '\n';
// Now we get to the wierd stuff with copy elision: there are no guarantees as to what the
// string numbers actually will be because the temporary objects within the functions
// may or may not be used in constructing the strings below...
basic::string stringW = unnamed(); // the return value was unnamed in this function
basic::string stringX(unnamed());
std::cout << "stringW: ";
stringW.print();
std::cout << '\n';
std::cout << "stringX: ";
stringX.print();
std::cout << '\n';
basic::string stringY = named(); // the return value was named in this function
std::cout << "stringY: ";
stringY.print();
std::cout << '\n';
basic::string stringZ(named());
std::cout << "stringZ: ";
stringZ.print();
stringW = stringZ; // copy assignment
std::cout << "stringW: ";
stringW.print();
std::cout << '\n';
stringX = std::move(stringW); // move assignment
std::cout << "stringX and stringW:\n";
stringX.print();
stringW.print();
std::cout << '\n';
std::cout << "stringX char 0: " << stringX.at(0) << '\n';
std::cout << "Now everything goes out of scope: " << '\n';
} // some descending series of ids will be displayed, but they may not be consecutive
_END_MEMORY_CHECK_
std::cin.get();
return 0;
}
| true |
db7313944b7c94d4b7a920e9100b68f26c6e9265 | C++ | withelm/Algorytmika | /leetcode/algorithms/c++/Boats to Save People/Boats to Save People.cpp | UTF-8 | 519 | 2.828125 | 3 | [] | no_license | class Solution
{
public:
int numRescueBoats(vector<int> &people, int limit)
{
sort(people.begin(), people.end());
int r = 0;
int begin = 0;
int n = people.size();
int end = n - 1;
while (begin <= end)
{
if (people[begin] + people[end] <= limit)
{
++begin;
--end;
}
else
{
--end;
}
++r;
}
return r;
}
}; | true |
21b9c61724c57ff8039c6fb7e3ecbc29edd12e65 | C++ | dolremi/data_structure | /Linked_list/Kth/LinkedList.cpp | UTF-8 | 3,110 | 3.8125 | 4 | [] | no_license | #include "LinkedList.h"
#include <iostream>
#include <map>
using namespace std;
LinkedList::LinkedList(LinkedList &rhs){
operator=(rhs);
}
LinkedList::~LinkedList(){
clearList();
}
void LinkedList::clearList(){
ListNode *runner = head;
while(runner){
ListNode *temp = runner;
runner = runner->Next;
delete temp;
}
size = 0;
head = 0;
}
const LinkedList & LinkedList::operator=(const LinkedList &rhs){
// check for self-assignment
if(this != &rhs){
clearList();
ListNode *copy = rhs.currentHead();
while(copy){
append(copy->val);
copy = copy->Next;
}
size = rhs.currentSize();
}
return *this;
}
void LinkedList::insert(int pos, int val){
ListNode * insertOne = head;
if(pos < size && pos > 0){
for(int i = 0; i < pos - 1; i++){
insertOne = insertOne -> Next;
}
ListNode *newNode = new ListNode(val);
newNode -> Next = insertOne -> Next;
insertOne ->Next = newNode;
size = size + 1;
}else{
cout << "Error! The position should be between 0 and " << size << endl;
}
}
void LinkedList::append(int val){
if(!head){
head = new ListNode(val);
}
else{
ListNode *lastNode = head;
while(lastNode->Next)
lastNode = lastNode->Next;
ListNode *temp = new ListNode(val);
lastNode->Next = temp;
}
size = size + 1;
}
int LinkedList::deleteNode(int input){
if(!head )
return -9999999;
if(head->val == input){
ListNode *temp = head;
head = head->Next;
delete temp;
--size ;
return input;
}
ListNode *p1 = head;
while(p1->Next != NULL){
if(p1->Next->val == input){
ListNode *temp = p1->Next;
p1->Next = p1->Next->Next;
delete temp;
--size;
return input;
}
p1 = p1->Next;
}
return -9999999;
}
void LinkedList::display(){
ListNode *p1 = head;
while(p1){
cout << p1 -> val << " -> ";
p1 = p1 -> Next;
}
cout << " NULL" << endl;
}
// Iteration version use the "runnner" technique with O(n) of running time and O(1) of space
ListNode * LinkedList::kthlastIter(int k){
ListNode *p1 = head;
ListNode *p2 = head;
// if k is out of bound 0 is returned
if(k >= size) return 0;
//Fast runner p2 is k nodes ahead of p1
for(int i = 0; i < k-1; i++){
p2 = p2->Next;
}
// When the fast runner reached the end, the slow runner reached the kth to the last element
while(p2->Next){
p2 = p2->Next;
p1 = p1->Next;
}
return p1;
}
ListNode * LinkedList::currentHead(){
return head;
}
int LinkedList::currentSize(){
return size;
}
// A recursive version of kth to last, k is a reference to the value which will
// record the position relative the the last element, nth to last : k = n, this number
// will change across the function calls, the space is O(n)
ListNode * LinkedList::kthlastRecur(ListNode *input, int &j, int k){
// Base case or head is NULL
if(!input)
return 0;
ListNode *result = kthlastRecur(input->Next, j, k);
j = j + 1;
if(j == k){
return input;
}
return result;
}
| true |
90cfa5119e8477ba390bce98243184d55579c711 | C++ | davidcox/mworks | /core/Core/XMLParser/ExpressionParser/ParsedColorTrio.h | UTF-8 | 1,042 | 2.515625 | 3 | [
"MIT"
] | permissive | /*
* ColorTrio.h
* MWorksCore
*
* Created by bkennedy on 12/10/08.
* Copyright 2008 mit. All rights reserved.
*
*/
#ifndef PARSED_COLOR_TRIO_H
#define PARSED_COLOR_TRIO_H
#include <string>
#include <boost/regex.hpp>
#include "ComponentRegistry.h"
#include "GenericVariable.h"
BEGIN_NAMESPACE_MW
struct RGBColor {
double red;
double green;
double blue;
};
class ParsedColorTrio {
public:
ParsedColorTrio(ComponentRegistry *reg, const std::string &color_string);
VariablePtr getR() const { return r; }
VariablePtr getG() const { return g; }
VariablePtr getB() const { return b; }
RGBColor getValue() const;
double getRedValue() const { return r->getValue().getFloat(); }
double getGreenValue() const { return g->getValue().getFloat(); }
double getBlueValue() const { return b->getValue().getFloat(); }
private:
static const boost::regex color_regex;
VariablePtr r;
VariablePtr g;
VariablePtr b;
};
END_NAMESPACE_MW
#endif
| true |
c77843617e4f1ab6c1c199d857a684f8bea9066a | C++ | bostoncleek/CUDA-RRT | /rrt.cpp | UTF-8 | 17,456 | 2.6875 | 3 | [] | no_license |
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <iostream>
#include <fstream>
#include <limits>
// #include <cuda.h>
// #include <cuda_runtime.h>
#include "rrt.hpp"
#include "collision_check.h"
double distance(const double *p1, const double *p2)
{
const double dx = p1[0] - p2[0];
const double dy = p1[1] - p2[1];
return std::sqrt(std::pow(dx, 2) + std::pow(dy, 2));
}
RRT::RRT(double *start, double *goal, int rando)
: start_(start),
goal_(goal),
delta_(0.05),
epsilon_(0),
xmin_(0),
xmax_(100),
ymin_(0),
ymax_(100),
resolution_(1.0),
max_iter_(10000),
vertex_count_(0)
{
// // add start to graph
// vertex v_start;
// v_start.x = start[0];
// v_start.y = start[1];
// addVertex(v_start);
// seed random generator
std::srand(rando);
}
bool RRT::collision_check(const vertex &v_new, const vertex &v_near)
{
for(unsigned int i = 0; i < circles_.size(); i++)
{
Circle circ = circles_.at(i);
const double p3[2] = {circ.x, circ.y};
const double p1[2] = {v_new.x, v_new.y};
const double p2[2] = {v_near.x, v_near.y};
const double num = (p3[0]-p1[0])*(p2[0]-p1[0]) + (p3[1]-p1[1])*(p2[1]-p1[1]);
const double denom = std::pow((p2[0]-p1[0]), 2) + std::pow((p2[1]-p1[1]), 2); //trying distance squared
const double u = num/denom;
const double x = p1[0] + u*(p2[0]-p1[0]);
const double y = p1[1] + u*(p2[1]-p1[1]);
const double P[2] = {x,y};
const double dist_to_line = distance(P, p3);
//if shortest distance to line lays outside circle youre good
// std::cout << "circ at: " << circ.x << ", " << circ.y << std::endl;
// std::cout << "dist to line: " << dist_to_line << " radius: " << circ.r << std::endl;
if (dist_to_line > circ.r){
continue;
}
//now we know the shortest distance lays within the circle
//must determine if its on the line or merely the ray
//check if either point exists in circle
const double dist_p1 = distance(p1,p3);
// const double dist_p2 = distance(p2,p3);
if ((dist_p1 > circ.r) /*&& (dist_p2 > circ.r)*/)
{
//check if the shortest point exists on line
if ((u < 1) && (u > 0))
{
return true;
}
else
{
continue;
}
}
else
{
//one of the end points of line in circle
return true;
}
}
return false;
}
bool RRT::exploreObstacles()
{
// add start to graph
vertex v_start;
v_start.x = start_[0];
v_start.y = start_[1];
addVertex(v_start);
bool success = false;
int ctr = 0;
while(!success)
{
if (ctr > max_iter_)
{
std::cout << "Goal not achieved" << std::endl;
return false;
}
// std::cout << "Iter: " << ctr << std::endl;
// 1) random point
double q_rand[2];
randomConfig(q_rand);
// 2) nearest node in graph
vertex v_near;
nearestVertex(v_near, q_rand);
// 3) new node
vertex v_new;
if(!newConfiguration(v_new, v_near, q_rand))
{
continue;
}
// std::cout << "v new at: " << v_new.x << ", " << v_new.y <<std::endl;
ctr++;
// 4) check for collisions
if (collision_check(v_new, v_near))
{
// std::cout << "Collision" << std::endl;
continue;
}
// std::cout << v_new.x << " " << v_new.y << "\n";
// 6) add new node
addVertex(v_new);
addEdge(v_near, v_new);
// 7) win check
bool win_flag = win_check(v_new, goal_);
if (win_flag)
{
std::cout << "Goal reached on CPU" << std::endl;
// add goal to graph
vertex v_goal;
v_goal.x = goal_[0];
v_goal.y = goal_[1];
addVertex(v_goal);
addEdge(v_new, v_goal);
success = true;
break;
}
}
return success;
}
bool RRT::win_check(const vertex &v_new, const double *goal)
{
//cast goal to vertex //TODO: overlead collision to optionally take double as second arg
vertex v_goal(goal[0],goal[1]);
// std::cout << "SURUR\n";
bool collis_check = collision_check(v_new, v_goal);
return !collis_check;
}
bool RRT::exploreCuda()
{
////////////////////////////////////////////////////////////////////////////
// set up variables for host
uint32_t num_circles = circles_.size();
// float3 *h_c = (float3 *)malloc(num_circles * sizeof(float3));
// size of grid
// uint32_t x_size = std::ceil((xmax_ - xmin_) / resolution_);
// uint32_t y_size = std::ceil((ymax_ - ymin_) / resolution_);
// uint32_t grid_size = x_size * y_size;
// max circles per grid cell
// uint32_t max_circles_cell = 100;
// uint32_t mem_size = max_circles_cell * grid_size;
// float3 *h_bins = (float3 *)malloc(mem_size * sizeof(float3));
float *h_x = (float *)malloc(num_circles * sizeof(float));
float *h_y = (float *)malloc(num_circles * sizeof(float));
float *h_r = (float *)malloc(num_circles * sizeof(float));
float *h_qnew = (float *)malloc(2 * sizeof(float));
float *h_qnear = (float *)malloc(2 * sizeof(float));
uint32_t *h_flag = (uint32_t *)malloc(sizeof(uint32_t));
// fill circles with data
circleData(h_x, h_y, h_r);
// circleDatafloat3(h_c);
// for(int i = 0; i < num_circles; i++)
// {
// printf("[x: %f y: %f r: %f] \n", h_c[i].x, h_c[i].y, h_c[i].z);
// }
/////////////////////_///////////////////////////////////////////////////////
// set up variables for device
// float3 *d_c = (float3 *)allocateDeviceMemory(num_circles * sizeof(float3));
// float3 *d_bins = (float3 *)allocateDeviceMemory(mem_size * sizeof(float3));
float *d_x = (float *)allocateDeviceMemory(num_circles * sizeof(float));
float *d_y = (float *)allocateDeviceMemory(num_circles * sizeof(float));
float *d_r = (float *)allocateDeviceMemory(num_circles * sizeof(float));
float *d_qnew = (float *)allocateDeviceMemory(2 * sizeof(float));
float *d_qnear = (float *)allocateDeviceMemory(2 * sizeof(float));
uint32_t *d_flag = (uint32_t *)allocateDeviceMemory(sizeof(uint32_t));
copyToDeviceMemory(d_x, h_x, num_circles * sizeof(float));
copyToDeviceMemory(d_y, h_y, num_circles * sizeof(float));
copyToDeviceMemory(d_r, h_r, num_circles * sizeof(float));
// copy circles to device
// copyToDeviceMemory(d_c, h_c, num_circles * sizeof(float3));
////////////////////////////////////////////////////////////////////////////
// pre process grid
// bin_call(d_c, d_bins, mem_size);
//
// copyToHostMemory(h_bins, d_bins, mem_size * sizeof(float3));
// for(int i = 0; i < max_circles_cell; i++)
// {
// for(int j = 0; j < grid_size; j++)
// {
// int index = j * max_circles_cell + i;
// printf("[x: %f y: %f r: %f] ", h_bins[index].x, h_bins[index].y, h_bins[index].z);
// }
// printf("\n");
// }
// ////////////////////////////////////////////////////////////////////////////
// start RRT
// clear graph each time
vertices_.clear();
vertex_count_ = 0;
// add start to graph
vertex v_start;
v_start.x = start_[0];
v_start.y = start_[1];
addVertex(v_start);
bool success = false;
int ctr = 0;
while(!success)
{
if (ctr == max_iter_)
{
std::cout << "Goal not achieved" << std::endl;
return false;
}
// 1) random point
double q_rand[2];
randomConfig(q_rand);
// 2) nearest node in graph
vertex v_near;
nearestVertex(v_near, q_rand);
// 3) new node
vertex v_new;
if(!newConfiguration(v_new, v_near, q_rand))
{
continue;
}
////////////////////////////////////////////////////////////////////////////
// call device for obstacle collisions
// 4)/5) collision btw new vertex and circles
h_qnew[0] = ((float)v_new.x);
h_qnew[1] = ((float)v_new.y);
h_qnear[0] = ((float)v_near.x);
h_qnear[1] = ((float)v_near.y);
// copy nominal new vertex
copyToDeviceMemory(d_qnew, h_qnew, 2 * sizeof(float));
// copy nearest vertex
copyToDeviceMemory(d_qnear, h_qnear, 2 * sizeof(float));
// calls obstalce kernel
// collision_call_1(d_x, d_y, d_r, d_qnew, d_qnear, d_flag);
collision_call_2(d_x, d_y, d_r, d_qnew, d_qnear, d_flag, num_circles);
// collision_call_3(d_x, d_y, d_r, d_qnew, d_qnear, d_flag);
// copy flag to host
copyToHostMemory(h_flag, d_flag, sizeof(uint32_t));
////////////////////////////////////////////////////////////////////////////
ctr++;
// if (ctr % 100 == 0)
// {
// std::cout << "count " << ctr << std::endl;
// }
if (((int)*h_flag))
{
// std::cout << "Collision" << std::endl;
continue;
}
// std::cout << v_new.x << " " << v_new.y << "\n";
// 6) add new node
addVertex(v_new);
addEdge(v_near, v_new);
// 7) win check
bool win_flag = win_check(v_new, goal_);
if (win_flag)
{
std::cout << "CUDA Goal reached" << std::endl;
// add goal to graph
vertex v_goal;
v_goal.x = goal_[0];
v_goal.y = goal_[1];
addVertex(v_goal);
addEdge(v_new, v_goal);
success = true;
break;
}
}
////////////////////////////////////////////////////////////////////////////
// tear down host variables
// free(h_c);
// free(h_bins);
free(h_x);
free(h_y);
free(h_r);
free(h_qnew);
free(h_qnear);
free(h_flag);
////////////////////////////////////////////////////////////////////////////
// tear down device variables
// freeDeviceMemory(d_c);
// freeDeviceMemory(d_bins);
freeDeviceMemory(d_x);
freeDeviceMemory(d_y);
freeDeviceMemory(d_r);
freeDeviceMemory(d_qnew);
freeDeviceMemory(d_qnear);
freeDeviceMemory(d_flag);
return success;
}
void RRT::randomCircles(int num_cirles, double r_min, double r_max)
{
for(int i = 0; i < num_cirles; i++)
{
// circle center within bounds of world
const double x = xmin_+static_cast<double>(std::rand()) / (static_cast<double>(RAND_MAX/(xmax_-xmin_)));
const double y = xmin_+static_cast<double>(std::rand()) / (static_cast<double>(RAND_MAX/(xmax_-xmin_)));
// radius between r_min and r_max;
const double r = r_min+static_cast<double>(std::rand()) / (static_cast<double>(RAND_MAX/(r_max-r_min)));
const double center[] = {x, y};
// make sure start and goal are not within an obstacle
const double d_init = distance(center, start_);
const double d_goal = distance(center, goal_);
if (d_init > r + epsilon_ and d_goal > r + epsilon_)
{
Circle c;
c.x = x;
c.y = y;
c.r = r;
circles_.push_back(c);
}
}
// for(const auto &circle: circles_)
// {
// std::cout << "Circle: " << circle.r << " [" << circle.x << " " << circle.y << "]" << std::endl;
// }
}
void RRT::circleData(float *h_x, float *h_y, float *h_r)
{
for(unsigned int i = 0; i < circles_.size(); i++)
{
h_x[i] = ((float)circles_.at(i).x);
h_y[i] = ((float)circles_.at(i).y);
h_r[i] = ((float)circles_.at(i).r);
}
}
void RRT::circleDatafloat3(float3 *h_c)
{
for(unsigned int i = 0; i < circles_.size(); i++)
{
h_c[i].x = ((float)circles_.at(i).x);
h_c[i].y = ((float)circles_.at(i).y);
h_c[i].z = ((float)circles_.at(i).r);
}
}
void RRT::traverseGraph(std::vector<vertex> &path) const
{
// path.reserve(vertices_.size());
std::ofstream pathout;
pathout.open("rrtout/path.csv");
int start_idx = 0; // first vertex added
int goal_idx = vertex_count_-1; // last vertex added
// std::cout << "start: " << start_idx << std::endl;
// std::cout << "goal: " << goal_idx << std::endl;
// path is backwards
path.push_back(vertices_.at(goal_idx));
// current vertex is the goal
vertex curr_v = vertices_.at(goal_idx);
int curr_idx = goal_idx;
while(curr_idx != start_idx)
{
int parent_idx = findParent(curr_v);
pathout << vertices_.at(curr_idx).x << "," << vertices_.at(curr_idx).y << "," << vertices_.at(parent_idx).x << "," << vertices_.at(parent_idx).y << "\n";
path.push_back(vertices_.at(parent_idx));
// update current node and current index
curr_v = vertices_.at(parent_idx);
curr_idx = parent_idx;
}
}
void RRT::printGraph() const
{
for(unsigned int i = 0; i < vertices_.size(); i++)
{
std::cout << "vertex: " << vertices_.at(i).id << " -> ";
for(unsigned int j = 0; j < vertices_.at(i).adjacent_vertices.size(); j++)
{
std::cout << vertices_.at(i).adjacent_vertices.at(j) << " ";
}
std::cout << std::endl;
}
}
void RRT::visualizeGraph() const
{
std::ofstream obstacles;
std::ofstream graph;
obstacles.open("rrtout/obstacles.csv");
graph.open("rrtout/graph.csv");
double x1, y1;
int mark;
if (graph.is_open())
{
std::cout << "rrtout/graph.csv is open" << std::endl;
}
if (obstacles.is_open())
{
std::cout << "rrtout/obstacles.csv is open" << std::endl;
}
//log obstacles
for (unsigned int i = 0; i < circles_.size(); i++){
obstacles << circles_.at(i).x << "," << circles_.at(i).y << "," << circles_.at(i).r << "\n";
}
//log graph (nodes and vertices)
for(unsigned int i = 0; i < vertices_.size(); i++)
{
//mark if root or goal -1 for root, 1 for goal, 0 for all else
if (i == 0){
mark = -1;
} else if (i == (vertices_.size() -1)){ //TODO: figure out why its not setting last el to 1
mark = 1;
} else {
mark = 0;
}
x1 = vertices_.at(i).x;
y1 = vertices_.at(i).y;
for(unsigned int j = 0; j < vertices_.at(i).adjacent_vertices.size(); j++)
{
int v_id = vertices_.at(i).adjacent_vertices.at(j);
graph << vertices_.at(v_id).x << "," << vertices_.at(v_id).y << "," << x1 << "," << y1 << "," << mark << "\n";
}
}
graph << goal_[0] << "," << goal_[1] << "," << vertices_.back().x << "," << vertices_.back().y << "," << 1 <<"\n";
obstacles.close();
graph.close();
}
void RRT::addVertex(vertex &v)
{
v.id = vertex_count_;
vertices_.push_back(v);
vertex_count_++;
// std::cout << "New vertex count: " << vertex_count_ << std::endl;
}
void RRT::addEdge(const vertex &v_near, const vertex &v_new)
{
// search for node1 and node2
// addes edge btw both
bool added = false;
for(unsigned int i = 0; i < vertices_.size(); i++)
{
// found node 1
if (vertices_.at(i).id == v_near.id)
{
for(unsigned int j = 0; j < vertices_.size(); j++)
{
// do not add vertex to itself
// found node 2
if(vertices_.at(j).id == v_new.id && i != j)
{
// edge connecting node 1 to node 2
// std::cout << "adding edge " << v_near.id << "->" << v_new.id << std::endl;
// v_near.adjacent_vertices.push_back(v_new.id);
vertices_.at(v_near.id).adjacent_vertices.push_back(v_new.id);
added = true;
}
} // end inner loop
}
} // end outer loop
if (!added)
{
std::cout << "Error: 'addEdge' edge not added" << std::endl;
}
}
bool RRT::newConfiguration(vertex &v_new, const vertex &v_near, const double *q_rand) const
{
// difference btw q_rand and v_near
const double vx = q_rand[0] - v_near.x;
const double vy = q_rand[1] - v_near.y;
// distance between v_near and q_rand
const double magnitude = std::sqrt(std::pow(vx, 2) + std::pow(vy, 2));
if (magnitude == 0)
{
return false;
}
// unit vector in driection of q_rand
const double ux = vx / magnitude;
const double uy = vy / magnitude;
// place v_new a delta away from v_near
v_new.x = v_near.x + delta_ * ux;
v_new.y = v_near.y + delta_ * uy;
// make sure still within bounds
if (v_new.x > xmax_ || v_new.x < xmin_ || v_new.y > ymax_ || v_new.y < ymin_)
{
return false;
}
return true;
}
void RRT::nearestVertex(vertex &v, double *q_rand) const
{
double point[2];
std::vector<double> d;
for(unsigned int i = 0; i < vertices_.size(); i++)
{
point[0] = vertices_.at(i).x;
point[1] = vertices_.at(i).y;
d.push_back(distance(point, q_rand));
}
// index of nearest node
const int idx = std::min_element(d.begin(), d.end()) - d.begin();
// int idx = 0;
// double smallest = d.at(0);
//
// for(unsigned int i = 1; i < d.size(); i++)
// {
// if(d.at(i) < smallest)
// {
// smallest = d.at(i);
// idx = i;
// }
// }
// std::cout << "minElementIndex:" << idx
// << ", minElement: [" << vertices_[idx].x << " " << vertices_[idx].y << "]\n";
// vertex v_near = vertices_.at(idx);
v = vertices_.at(idx);
}
void RRT::randomConfig(double *q_rand) const
{
// x position
q_rand[0] = xmin_+static_cast<double>(std::rand()) / (static_cast<double>(RAND_MAX/(xmax_-xmin_)));
// y position
q_rand[1] = ymin_+static_cast<double>(std::rand()) / (static_cast<double>(RAND_MAX/(ymax_-ymin_)));
}
int RRT::findParent(const vertex &v) const
{
// iterate over vertices
for(unsigned int i = 0; i < vertices_.size(); i++)
{
for(unsigned int j = 0; j < vertices_.at(i).adjacent_vertices.size(); j++)
{
if (vertices_.at(i).adjacent_vertices.at(j) == v.id)
{
// std::cout << "Parent found" << std::endl;
return i;
}
} // end inner loop
} // end outer loop
std::cout << "Parent not found" << std::endl;
return -1;
}
// end file
| true |
fd786ec9c04b3b0066f7743ffdcdceefec862da2 | C++ | tanishq1g/cp_codes | /GeeksForGeeks/Detect cycle in a directed graph.cpp | UTF-8 | 952 | 2.75 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <string>
#include <vector>
#include <locale>
#include <algorithm>
#include <cmath>
#include <unordered_map>
#include <bitset>
#include <climits>
#include <queue>
#include <stack>
using namespace std;
// GRAPH
bool dfsrec(vector<int> adj[], vector<bool> &vis, vector<bool> &recvis, int ind){
vis[ind] = true;
recvis[ind] = true;
int sadj = adj[ind].size();
for(int i = 0; i < sadj; i++){
if(vis[adj[ind][i]] == false){
if(dfsrec(adj, vis, recvis, adj[ind][i]))
return true;
}
else if(recvis[adj[ind][i]] == true){
return true;
}
}
recvis[ind] = false;
return false;
}
bool isCyclic(int V, vector<int> adj[]){
if(V == 0)
return false;
vector<bool> vis(V, false), recvis(V, false);
for(int i = 0; i < V; i++){
if(dfsrec(adj, vis, recvis, i))
return true;
}
return false;
} | true |
383edb1172b56bab735f30321e7cbb79755ca5a7 | C++ | gambiting/Racer-PS3 | /GCM Framework/ItemTrap.h | UTF-8 | 367 | 2.84375 | 3 | [] | no_license | /*
Will leave a fake item box in the world which hurts players who hit it
*/
#pragma once
#include "Item.h"
class Trap : public Item{
public:
Trap();
Trap(int power);
virtual void useItem(Player* player);
void useItem(Player* player, std::vector<Trap*>& traps);
ItemType getItemEffectType();
Player* getOwner(){ return owner; }
private:
Player* owner;
}; | true |
b87a19183efbf594064021d3dad98f9c82125c2b | C++ | Dipakam/Courses | /ESO207/assignment/ass1/ass1.cpp | UTF-8 | 2,104 | 3.453125 | 3 | [] | no_license | #include<iostream>
using namespace std;
struct numop{
char type;
char op;
int num;
};
typedef struct numop numop;
struct node{
numop * item;
struct node * next;
};
node * head=NULL;
int isEmpty(node * stack){
if(stack==NULL){
return 1;
}
else return 0;
}
void push(node * key){
key->next = head;
head = key;
return;
}
numop * Top(){
return head->item;
}
void deleteNode(node * key){
delete key->item;
delete key;
return;
}
void Pop(){
node * clear=head;
head = clear->next;
deleteNode (clear);
return;
}
typedef struct node node;
numop * CreateStack(){
numop * pointer=NULL;
//pointer = new numop;
return pointer;
}
node * CreateNode(numop * key){
node * Node = NULL;
Node = new node;
Node->item = key;
Node->next = NULL;
return Node;
}
int main(){
/*numop test;
test.type ='n';
test.num = 4;*/
/*numop * test = CreateStack();
if(test==NULL){
std::/* message cout << "ok" << '\n';
}*/
/*node * testnode=NULL;
testnode = new node;
testnode->next = NULL;
testnode->item = &test;
push(testnode);
Pop();*/
//delete test;
//std::cout << (head->item)->num << '\n';
//delete testnode;
//std::cout << isEmpty(head) << '\n';
int Q;
std::cin >> Q;
while (Q>0) {
Q--;
char typ;
std::cin >>typ ;
if(typ=='1'){
int no=0;
std::cin >> no;
numop * input=CreateStack();
input = new numop;
input->type = 'n';
input->num = no;
node * Node = CreateNode(input);
push(Node);
std::cout << "$" << '\n';
}
else if(typ=='2'){
char sym;
//std::cin >> sym;
std::cin >> sym;
numop * input = CreateStack();
input = new numop;
input->type = 'c';
if(sym=='+' || sym=='-' || sym=='/' || sym=='*'){
input->op=sym;
node * Node = CreateNode(input);
push(Node);
std::cout << "$" << '\n';
}
}
else if(typ=='3'){
if(isEmpty(head)==1){
std::cout << "error" << '\n';
}
else{
}
}
}
while(isEmpty(head)==0){
Pop();
}
return 0;
}
| true |
0bd2b9ca0913b7b061fccaf274425868ae77e08b | C++ | mukundkedia/DSA | /string/makePallindrome.cpp | UTF-8 | 1,468 | 3.40625 | 3 | [] | no_license | //https://www.geeksforgeeks.org/lexicographically-first-palindromic-string/
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
void findfreq(string s,vector<int>& freq){
int len = s.size();
for(char c:s){
freq[c-'a']++;
}
}
bool possible(vector<int> freq,int len){
int count_odd=0;
for(int i=0;i<26;i++){
if(freq[i]%2!=0){
count_odd++;
}
}
if(len%2==0){
if(count_odd>0){
return false;
}
}
if(len%2==1){
if(count_odd!=1){
return false;
}
}
return true;
}
string findmid(vector<int>& freq){
string res="";
for(int i=0;i<26;i++){
if(freq[i]%2==1){
freq[i]--;
res+=char(i+'a');
return res;
}
}
return res;
}
int main()
{
string s;
cin>>s;
int len = s.size();
vector<int> freq(26,0);
findfreq(s,freq);
if(possible(freq,len)){
string oddlen = findmid(freq);
string front="",rear="";
for(int i=0;i<26;i++){
string temp="";
if(freq[i]!=0){
char ch = char(i+'a');
for(int j=1;j<=freq[i]/2;j++){
temp+=ch;
}
front=temp+front;
rear=rear+temp;
}
}
cout<<front+oddlen+rear;
}
else{
cout<<"Not possible";
}
} | true |
602e9b3f7853e9c8ef2324eafcae6a0c17db98ee | C++ | KrusnikViers/RaspClock | /src/ui/display.cpp | UTF-8 | 1,216 | 2.59375 | 3 | [
"MIT"
] | permissive | #include "ui/display.h"
#include "ui/util/text_helpers.h"
namespace rclock::ui {
Display::Display(core::MainTimer* main_timer, data::TimeProvider* time_provider)
: time_provider_(time_provider) {
ui_.setupUi(this);
connect(main_timer, &core::MainTimer::updateClock, //
this, &Display::updateClock);
updateClock();
}
void Display::updateClock() {
if (this->geometry() != calculated_geometry_) {
fitTextSize(ui_.time_label, 1.5);
fitTextSize(ui_.day_of_week_label, 0.5);
fitTextSize(ui_.date_label, 0.25);
calculated_geometry_ = this->geometry();
}
QDateTime current_datetime = time_provider_->getDateTime();
const QString time = locale_.toString(current_datetime, "hh:mm");
const QString seconds = locale_.toString(current_datetime, "ss");
const QString dow = locale_.toString(current_datetime, "dddd");
const QString date = locale_.toString(current_datetime, "d MMMM yyyy");
ui_.time_label->setText(
time + "<span style='font-size:" +
QString::number(ui_.time_label->font().pointSize() / 3) + "pt;'>" +
seconds + "</span>");
ui_.day_of_week_label->setText(dow);
ui_.date_label->setText(date);
}
} // namespace rclock::ui
| true |
27ac09ac5ce2f37fd75d26fbabb16933bc540d7a | C++ | Alexander198961/tcp-server | /server.cpp | UTF-8 | 1,120 | 2.84375 | 3 | [] | no_license | /*
C socket server example
*/
#include<stdio.h>
#include<string.h> //strlen
#include<sys/socket.h>
#include<arpa/inet.h> //inet_addr
#include<unistd.h> //write
#include <iostream>
int main(int argc , char *argv[])
{
int sd = socket( AF_INET,SOCK_STREAM, 0);
socklen_t clien;
char buffer[256];
struct sockaddr_in serv_addr , cli_addr;
//memset
bzero((char * ) &serv_addr,sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(509);
if (bind(sd, (struct sockaddr * ) &serv_addr ,sizeof(serv_addr) ) < 0 ) {
perror("bind");
}
listen(sd,3);
clien = sizeof (cli_addr);
int newsockfd = accept (sd, (struct sockaddr *) &cli_addr, &clien );
bzero(buffer,256);
while(1)
{
int n = read(newsockfd,buffer , 255 );
std::cout << buffer<< std::endl;
//sleep
bzero(buffer,256);
}
//int response = connect(sd, ( struct sockaddr * ) &serv_addr ,sizeof(serv_addr));
// std::cout << response << std::endl;
//listen(sd,3);
//clien
return 0;
}
| true |
888ecdbf1af3586f011335db3706a9fc43bb105d | C++ | courageousillumination/olympus | /src/render/renderer.cpp | UTF-8 | 5,048 | 2.609375 | 3 | [] | no_license | #include <fstream>
#include <exception>
#include <stdexcept>
#include <GL/glew.h>
#include "debug/logger.hpp"
#include "render/renderer.hpp"
using namespace olympus;
std::string Renderer::_read_file(const char *path) {
std::string line;
std::string code;
std::ifstream fin(path);
if (!fin.good()) {
LOG(Logger::ERROR, "Failed to open shader %s", path);
throw std::runtime_error("Failed to open shader");
}
while(fin.good()) {
getline(fin, line);
code += "\n" + line;
}
fin.close();
return code;
}
unsigned Renderer::_compile_shader(const char *path, unsigned type) {
std::string code = _read_file(path);
LOG(Logger::DEBUG, "Starting compile of %s", path);
unsigned shader_id = glCreateShader(type);
const char *source = code.c_str();
glShaderSource(shader_id, 1, &source, NULL);
glCompileShader(shader_id);
//Check that compilation finished
int result, info_log_length;
glGetShaderiv(shader_id, GL_COMPILE_STATUS, &result);
if (result != GL_TRUE) {
glGetShaderiv(shader_id, GL_INFO_LOG_LENGTH, &info_log_length);
char *errors = new char[info_log_length];
glGetShaderInfoLog(shader_id, info_log_length, NULL, errors);
LOG(Logger::ERROR, "Failed to compile shader %s. Error(s): %s", path, errors);
glDeleteProgram(shader_id);
delete []errors;
throw std::runtime_error("Failed to compile shader.");
}
LOG(Logger::DEBUG, "Compiled %s", path);
return shader_id;
}
unsigned Renderer::_link(unsigned num_shaders, unsigned shaders[]) {
LOG(Logger::DEBUG, "Begin linking shader");
unsigned program_id = glCreateProgram();
for (unsigned i = 0; i < num_shaders; i++) {
glAttachShader(program_id, shaders[i]);
}
glLinkProgram(program_id);
//Check for link errors
int result, info_log_length;
glGetProgramiv(program_id, GL_LINK_STATUS, &result);
if (result != GL_TRUE) {
glGetProgramiv(program_id, GL_INFO_LOG_LENGTH, &info_log_length);
char *errors = new char[info_log_length];
glGetProgramInfoLog(program_id, info_log_length, NULL, errors);
LOG(Logger::ERROR, "Failed to link shader. Error(s): %s", errors);
delete []errors;
//Clean up, clean up, everybody everywhere
for (unsigned i = 0; i < num_shaders; i++) {
glDeleteShader(shaders[i]);
}
glDeleteProgram(program_id);
throw std::runtime_error("Failed to link shader.");
}
LOG(Logger::DEBUG, "Linked shaders");
return program_id;
}
Renderer::Renderer(const char *vertex_shader_path,
const char *fragment_shader_path) {
unsigned shaders[2];
shaders[0] = _compile_shader(vertex_shader_path, GL_VERTEX_SHADER);
shaders[1] = _compile_shader(fragment_shader_path, GL_FRAGMENT_SHADER);
_shader_id = _link(2, shaders);
//Clean up
glDeleteShader(shaders[0]);
glDeleteShader(shaders[1]);
}
Renderer::~Renderer() {
glDeleteProgram(_shader_id);
}
void Renderer::bind() {
glUseProgram(_shader_id);
}
unsigned Renderer::get_internal_id() {
return _shader_id;
}
bool Renderer::has_uniform(std::string id) {
return (glGetUniformLocation(_shader_id, id.c_str()) != -1);
}
unsigned Renderer::get_uniform_location(std::string id) {
int value = glGetUniformLocation(_shader_id, id.c_str());
if (value == -1) {
LOG(Logger::WARN, "Tried to fetch location of a non-existent uniform %s from a shader", id.c_str());
}
return (unsigned) value;
}
void Renderer::set_uniform(std::string id, glm::vec3 value) {
glUniform3fv(get_uniform_location(id), 1, &value[0]);
}
void Renderer::set_uniform(std::string id, glm::vec2 value) {
glUniform2fv(get_uniform_location(id), 1, &value[0]);
}
void Renderer::set_uniform(std::string id, glm::mat4 value) {
glUniformMatrix4fv(get_uniform_location(id), 1, GL_FALSE, &value[0][0]);
}
void Renderer::set_uniform(std::string id, float value) {
glUniform1f(get_uniform_location(id), value);
}
void Renderer::set_uniform(std::string id, int value) {
glUniform1i(get_uniform_location(id), value);
}
void Renderer::set_uniform(std::string id, glm::mat4 *values, unsigned num_values) {
glUniformMatrix4fv(get_uniform_location(id), num_values, GL_FALSE, &values[0][0][0]);
}
void Renderer::set_uniform(std::string id, glm::vec3 *values, unsigned num_values) {
glUniform3fv(get_uniform_location(id), num_values, &values[0][0]);
}
void Renderer::set_uniform(std::string id, glm::vec2 *values, unsigned num_values) {
glUniform2fv(get_uniform_location(id), num_values, &values[0][0]);
}
void Renderer::set_uniform(std::string id, int *values, unsigned num_values) {
glUniform1iv(get_uniform_location(id), num_values, values);
}
void Renderer::set_uniform(std::string id, float *values, unsigned num_values) {
glUniform1fv(get_uniform_location(id), num_values, values);
} | true |
a8d3b2f0769cd2d3149428923a11c1716fd9bd5e | C++ | huanCode/study | /数据结构和算法/code/DemoStudy/DemoStudy/InsertSort.cpp | UTF-8 | 392 | 3.5 | 4 | [] | no_license | #include "InsertSort.h"
void InsertSort::Demo()
{
vector<int> arr = { 50,10,90,30,70,40,80,60,20 };
Sort(arr);
}
void InsertSort::Sort(vector<int>& arr)
{
int value = 0;
for (int i = 1; i < arr.size(); i++)
{
value = arr[i];
int j = 0;
for (j = i-1; j >= 0; j--)
{
if (arr[j] > value)
{
arr[j + 1] = arr[j];
continue;
}
break;
}
arr[j+1] = value;
}
} | true |
6ce5ca664c37edb3256dcba601fa4ca1368a682a | C++ | yahyatawil/RGB_resistor_calculator | /RGB_resistor_calculator.ino | UTF-8 | 9,145 | 2.59375 | 3 | [] | no_license | /*
Yahya tawil
2013-2014
Licence:CC-BY-SA
*/
#include <Keypad.h>
/* TIPs
adjust values with steps until you have the right color
http://www.instructables.com/id/RGB-LED-Color-Selector/?ALLSTEPS
GUI res calc http://www.dannyg.com/examples/res2/resistor.htm
ASCII : http://en.wikipedia.org/wiki/ASCII
keypad : http://playground.arduino.cc/Code/Keypad
*/
#define red_led_pin 9
#define green_led_pin 6
#define blue_led_pin 5
#define second_chip_en 3 //also used for common anode of 7seg third_digit
#define first_chip_en 7 ////also used for common anode of 7seg second_digit
#define led_sel 2 ////also used for common anode of 7seg first_digit
#define ROW0 8
#define ROW1 10
#define ROW2 11
#define ROW3 12
#define COL0 A5
#define COL1 A4
#define COL2 A3
//address for 7seg IC
#define AD0 4
#define AD1 A2
#define AD2 A1
#define AD3 A0
/*
first band is connected to first LED channed x , second with channedl y and third is connected with second chip channel x
*/
/*
#define Black 0
#define Brown 1
#define Red 2
#define Orange 3
#define Yellow 4
#define Green 5
#define Blue 6
#define Violet 7
#define Grey 8
#define White 9
*/
int press ;
char key ;
int digits [6] = {0,0,0,0,0,0}; // first (first number) , second (maybe ',' or '.' or just a number or '\n' or 'k') , third ('\n' or 'k' or 0)
int colorcode[3]; // store the real DEC values of band here in this array
int val;//used for reading values
int i=0;//global counter , used for input
int numofdigits = 0 ;//counting of real numbers of input values excluding ',' or 'k' or '.'
boolean Do =false; // explained in loop , enable loop to enter number using serial
boolean Do2 =false; // enable the loop for entering number by keypad , make it false to disaple keypad option
byte seven_seg_digits[10][4] = {//a,b,c,d,e,f,g
{ 0,0,0,0 }, // = 0
{ 0,0,0,1 }, // = 1
{ 0,0,1,0 }, // = 2
{ 0,0,1,1 }, // = 3
{ 0,1,0,0 }, // = 4
{ 0,1,0,1 }, // = 5
{ 0,1,1,0}, // = 6
{ 0,1,1,1 }, // = 7
{ 1,0,0,0 }, // = 8
{ 1,0,0,1 } // = 9
};
const byte ROWS = 4; // Four rows
const byte COLS = 3; // Three columns
// Define the Keymap
char keys[ROWS][COLS] = {
{'1','2','3'},
{'4','5','6'},
{'7','8','9'},
{',','0','k'}
};
// Connect keypad ROW0, ROW1, ROW2 and ROW3 to these Arduino pins.
byte rowPins[ROWS] = { ROW0, ROW1, ROW2, ROW3 };
// Connect keypad COL0, COL1 and COL2 to these Arduino pins.
byte colPins[COLS] = { COL0, COL1, COL2 };
Keypad KPD = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
void setup()
{
Serial.begin(9600);
pinMode(AD0,OUTPUT);
pinMode(AD1,OUTPUT);
pinMode(AD2,OUTPUT);
pinMode(AD3,OUTPUT);
pinMode(red_led_pin,OUTPUT);
pinMode(green_led_pin,OUTPUT);
pinMode(blue_led_pin,OUTPUT);
pinMode(second_chip_en,OUTPUT);
pinMode(first_chip_en,OUTPUT);
pinMode(led_sel,OUTPUT);
digitalWrite(second_chip_en,LOW);
digitalWrite(first_chip_en,LOW);
digitalWrite(led_sel,LOW);
digitalWrite(second_chip_en,HIGH);
digitalWrite(first_chip_en,HIGH);
KPD.setDebounceTime(50);
}
void seven_seg_disp(int num){
digitalWrite(AD0,seven_seg_digits[num][3]);
digitalWrite(AD1,seven_seg_digits[num][2]);
digitalWrite(AD2,seven_seg_digits[num][1]);
digitalWrite(AD3,seven_seg_digits[num][0]);
}
void rgbled(int r,int g,int b) //255-value because I used common anode RGB leds
{
analogWrite(red_led_pin, 255-r);
analogWrite(green_led_pin, 255-g);
analogWrite(blue_led_pin, 255-b);
}
void colortorgb(int color){
//token after tests
switch (color) {
case 0 :
rgbled(0,0,0);
break ;
case 1 :
rgbled(180,15,0);
break ;
case 2 :
rgbled(255,0,0);
break ;
case 3 :
rgbled(255,31,0);
break ;
case 4 :
rgbled(145,24,0);
break ;
case 5 :
rgbled(0,255,0);
break ;
case 6 :
rgbled(0,0,255);
break ;
case 7 :
rgbled(204,0,53);
break ;
case 8 :
rgbled(204,100,80);
break ;
case 9 :
rgbled(240,190,100);
break ;
}
}
void rgbdisp()
{
/*
the idea is we turn off second chip and sel the channels of first chip for 1st and 2nd band
then trurn off first chip and sel channel for third band
*/
//RGB section
digitalWrite(second_chip_en,HIGH);
digitalWrite(first_chip_en,LOW);
digitalWrite(led_sel,LOW);
colortorgb(colorcode[0]) ;
delay(1);
digitalWrite(second_chip_en,HIGH);
digitalWrite(first_chip_en,LOW);
digitalWrite(led_sel,HIGH);
colortorgb(colorcode[1]) ;
delay(1);
digitalWrite(second_chip_en,LOW);
digitalWrite(first_chip_en,HIGH);
digitalWrite(led_sel,LOW);
colortorgb(colorcode[2]) ;
delay(1);
/*
//7seg section
digitalWrite(second_chip_en,HIGH);
digitalWrite(first_chip_en,LOW);
digitalWrite(led_sel,LOW);
rgbled(0,0,0);
seven_seg_disp(colorcode[2]) ;
delay(1);
digitalWrite(second_chip_en,LOW);
digitalWrite(first_chip_en,HIGH);
digitalWrite(led_sel,LOW);
//rgbled(0,0,0);
seven_seg_disp(colorcode[1]) ;
delay(1);
digitalWrite(second_chip_en,LOW);
digitalWrite(first_chip_en,LOW);
digitalWrite(led_sel,HIGH);
//rgbled(0,0,0);
seven_seg_disp(colorcode[0]) ;
delay(1);
*/
}
int printbandcolor(int band)
{
switch (band) {
case 0 :
Serial.print("Black ");
return 0;
case 1 :
Serial.print("Brown ");
return 1;
case 2 :
Serial.print("Red ");
return 2;
case 3 :
Serial.print("Orange ");
return 3;
case 4 :
Serial.print("Yellow ");
return 4;
case 5 :
Serial.print("Green ");
return 5;
case 6 :
Serial.print("Blue ");
return 6;
case 7 :
Serial.print("Violet ");
return 7;
case 8 :
Serial.print("Gray ");
return 8;
case 9 :
Serial.print("white ");
return 9;
}
}
void value(){
//ex:1,5k or 1.5k
if(numofdigits==2 && (digits[1]==('.'-'0') || digits[1]==(','-'0')) && digits[3]==('k'-'0') )
{
digits[1]=digits[2];
digits[2]=2;
for(int j=0;j<3;j++) {colorcode[j]=printbandcolor(digits[j]) ;}
}
//ex:1ohm
else if(numofdigits==1 && digits[1]!=('k'-'0') )
{
digits[1] = digits[0] ;digits[0] = 0 ;digits[2]=0;
for(int j=0;j<3;j++) {colorcode[j]=printbandcolor(digits[j]);}
}
//ex:27ohm
else if(numofdigits==2 && digits[2]==0)
{
digits[2]=0;
for(int j=0;j<3;j++) { colorcode[j]=printbandcolor(digits[j]);}
}
//ex:470ohm
else if(numofdigits==3 && digits[3]==0)
{
if(digits[2]!=0) Serial.println("error1") ; //must be zero 3rd brand don't have values
else{
digits[2]=1;
for(int j=0;j<3;j++) {colorcode[j]=printbandcolor(digits[j]);}
}
}
//ex:1k
else if(numofdigits==1 && digits[1]==('k'-'0') )
{
digits[1]=0 ; digits[2]=2;
for(int j=0;j<3;j++) {colorcode[j]=printbandcolor(digits[j]); }
}
//ex:15k
else if(numofdigits==2 && digits[2]==('k'-'0'))
{
digits[2]=3;
for(int j=0;j<3;j++){ colorcode[j]=printbandcolor(digits[j]); }
}
//ex:100k
else if(numofdigits==3 && digits[3]==('k'-'0') )
{
if(digits[2]!=0) Serial.println("error2") ;
else{
digits[2]= 4;
for(int j=0;j<3;j++) {colorcode[j]=printbandcolor(digits[j]); }
}
}
}
void serialEvent()
{
while(Serial.available()) {
val=Serial.read() -'0';
if(val==('\n'-'0')) Do=true ;
else{digits[i]=val;
if(val!=('.'-'0') && val!=(','-'0') && val!=('k'-'0')) numofdigits++;
i++ ;
}
}
}
void start()
{
Serial.println(" \n ---------- ");
numofdigits = 0;
i=0;
press=0;
digits[5]=digits[4]=digits[3]= digits[2] = digits[1]= digits[0]=0;
}
void loop()
{
// do is for making show color execute just one time when the resistor value is revived (\n recived)
while(Do==true) {value() ; Do=false; start();}
if(KPD.getKey()==',') {Serial.println("keypad unlocked");Do2=true; };
for (int j=0 ; j<6 ; j++){
if(Do2 == false) break ;
key = KPD.waitForKey() ;
digits[j]=key - '0' ;
if(key!='k' && key!=',') numofdigits++;
if(digits[j]==(','-'0') && digits[j-1]==(','-'0')){
digits[j]=digits[j-1]=0;
Serial.println("value is entered");
Do2=false ;
Do=true;
break;
}
if(key == ',') Serial.print(',');
else if(key=='k') Serial.print('k');
else Serial.print(key) ;
}
rgbdisp();
}
| true |
9135f8591713971e6dff9ac360c6bd9bf61ef652 | C++ | BiglandUK/WhiteBoard-Prototype | /WhiteBoard-Proto-Stage-1/Window.cpp | UTF-8 | 2,830 | 2.71875 | 3 | [] | no_license | #include "Window.h"
Window::Window() { Setup("Window", sf::Vector2u(640, 480)); }
Window::Window(const std::string& title, const sf::Vector2u& size)
{
Setup(title, size);
mMouseClicked = false;
}
Window::~Window() {
mWindow.close();
}
void Window::Setup(const std::string& title, const sf::Vector2u& size)
{
mWindowTitle = title;
mWindowSize = size;
mIsFullscreen = false;
mIsDone = false;
mIsFocused = true; // Default value for focused flag.
/*mEventManager.AddCallback(StateType(0), "Fullscreen_toggle",
&Window::ToggleFullscreen, this);
mEventManager.AddCallback(StateType(0), "Window_close",
&Window::Close, this);*/
Create();
}
void Window::Create() {
/*auto style = (mIsFullscreen ? sf::Style::Fullscreen : sf::Style::Default);
mWindow.create({ mWindowSize.x, mWindowSize.y, 32 }, mWindowTitle, style);*/
sf::Uint32 style = sf::Style::Default;
if (mIsFullscreen) { style = sf::Style::Fullscreen; }
mWindow.create(sf::VideoMode(mWindowSize.x, mWindowSize.y, 32), mWindowTitle, style);
mWindow.clear(sf::Color::Black);
}
void Window::BeginDraw() { mWindow.clear(sf::Color::Black); }// (240, 240, 240, 0)); }
void Window::EndDraw() { mWindow.display(); }
bool Window::IsDone() { return mIsDone; }
bool Window::IsFullscreen() { return mIsFullscreen; }
bool Window::IsFocused() { return mIsFocused; }
bool Window::MouseClicked() { return mMouseClicked; }
bool Window::MouseReleased() { return mMouseReleased; }
void Window::ClearMouseClick() { mMouseClicked = false; mMouseReleased = false; }
sf::RenderWindow* Window::GetRenderWindow() { return &mWindow; }
//EventManager* Window::GetEventManager() { return &mEventManager; }
sf::Vector2u Window::GetWindowSize() { return mWindowSize; }
sf::FloatRect Window::GetViewSpace() {
sf::Vector2f viewCentre = mWindow.getView().getCenter();
sf::Vector2f viewSize = mWindow.getView().getSize();
sf::Vector2f viewSizeHalf(viewSize.x / 2, viewSize.y / 2);
sf::FloatRect viewSpace(viewCentre - viewSizeHalf, viewSize);
return viewSpace;
}
//void Window::ToggleFullscreen(EventDetails* details) {
// mIsFullscreen = !mIsFullscreen;
// mWindow.close();
// Create();
//}
//void Window::Close(EventDetails* details) { mIsDone = true; }
void Window::Update() {
sf::Event event;
while (mWindow.pollEvent(event)) {
if (event.type == sf::Event::LostFocus) {
mIsFocused = false;
//mEventManager.SetFocus(false);
}
else if (event.type == sf::Event::GainedFocus) {
mIsFocused = true;
//mEventManager.SetFocus(true);
}
else if (event.type == sf::Event::Closed) {
mIsDone = true;
}
else if (event.type == sf::Event::MouseButtonPressed) {
mMouseClicked = true;
}
else if (event.type == sf::Event::MouseButtonReleased) {
mMouseReleased = true;
}
//mEventManager.HandleEvent(event);
}
//mEventManager.Update();
} | true |
f6ca5ca38ba85c56c8e96a9a1afa7a08daaef7f3 | C++ | luningcowboy/DesignPatternTest | /DesignPattern/Observer.h | UTF-8 | 663 | 2.828125 | 3 | [] | no_license | #ifndef _OBSERVER_H_
#define _OBSERVER_H_
#include "Subject.h"
#include <string>
using namespace std;
typedef string StateStr;
class Observer
{
public:
virtual ~Observer();
virtual void UpDate(Sub * sub) = 0;
virtual void PrintInfo()=0;
protected:
Observer();
StateStr _st;
};
class ObserverA :public Observer
{
public:
virtual Sub* GetSubject();
ObserverA(Sub * sub);
virtual ~ObserverA();
void UpDate(Sub * sub);
void PrintInfo();
private:
Sub * _sub;
};
class ObserverB : public Observer
{
public:
virtual Sub * GetSubject();
ObserverB(Sub * sub);
virtual ~ObserverB();
void UpDate(Sub * sub);
void PrintInfo();
private:
Sub * _sub;
};
#endif | true |
b4a753b4d5e0bbe2cbe87a4fa14115ac3969552a | C++ | codyroux/lean0.1 | /src/library/simplifier/rewrite_rule_set.h | UTF-8 | 6,469 | 2.515625 | 3 | [
"Apache-2.0"
] | permissive | /*
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#pragma once
#include <memory>
#include <functional>
#include "util/lua.h"
#include "util/list.h"
#include "util/splay_tree.h"
#include "util/name.h"
#include "kernel/environment.h"
#include "kernel/metavar.h"
#include "kernel/formatter.h"
#include "library/io_state_stream.h"
#include "library/simplifier/congr.h"
namespace lean {
class rewrite_rule_set;
class rewrite_rule {
friend class rewrite_rule_set;
name m_id;
expr m_lhs;
expr m_rhs;
expr m_ceq;
expr m_proof;
unsigned m_num_args;
bool m_is_permutation;
bool m_must_check_types; // if true, then we must check if the given types are convertible to the expected types
rewrite_rule(name const & id, expr const & lhs, expr const & rhs, expr const & ceq, expr const & proof,
unsigned num_args, bool is_permutation, bool must_check);
public:
name const & get_id() const { return m_id; }
expr const & get_lhs() const { return m_lhs; }
expr const & get_rhs() const { return m_rhs; }
expr const & get_ceq() const { return m_ceq; }
expr const & get_proof() const { return m_proof; }
unsigned get_num_args() const { return m_num_args; }
bool is_permutation() const { return m_is_permutation; }
bool must_check_types() const { return m_must_check_types; }
};
/**
\brief Actual implementation of the \c rewrite_rule_set class.
*/
class rewrite_rule_set {
typedef splay_tree<name, name_quick_cmp> name_set;
ro_environment::weak_ref m_env;
list<rewrite_rule> m_rule_set; // TODO(Leo): use better data-structure, e.g., discrimination trees
name_set m_disabled_rules;
list<congr_theorem_info> m_congr_thms; // This is probably ok since we usually have very few congruence theorems
bool enabled(rewrite_rule const & rule) const;
public:
rewrite_rule_set(ro_environment const & env);
rewrite_rule_set(rewrite_rule_set const & other);
~rewrite_rule_set();
/**
\brief Convert the theorem \c th with proof \c proof into conditional rewrite rules, and
insert the rules into this rule set. The new rules are tagged with the given \c id.
*/
void insert(name const & id, expr const & th, expr const & proof, optional<ro_metavar_env> const & menv);
/**
\brief Convert the theorem/axiom named \c th_name in the environment into conditional rewrite rules,
and insert the rules into this rule set. The new rules are tagged with the theorem name.
This method throws an exception if the environment does not have a theorem/axiom named \c th_name.
*/
void insert(name const & th_name);
/** \brief Return true iff the conditional rewrite rules tagged with the given id are enabled. */
bool enabled(name const & id) const;
/** \brief Enable/disable the conditional rewrite rules tagged with the given identifier. */
void enable(name const & id, bool f);
/** \brief Add a new congruence theorem. */
void insert_congr(expr const & e);
void insert_congr(name const & th_name);
typedef std::function<bool(rewrite_rule const &)> match_fn; // NOLINT
typedef std::function<void(rewrite_rule const &, bool)> visit_fn;
/**
\brief Execute <tt>fn(rule)</tt> for each (enabled) rule whose the left-hand-side may
match \c e.
The traversal is interrupted as soon as \c fn returns true.
*/
bool find_match(expr const &, match_fn const & fn) const;
/** \brief Execute <tt>fn(rule, enabled)</tt> for each rule in this rule set. */
void for_each(visit_fn const & fn) const;
typedef std::function<void(congr_theorem_info const &)> visit_congr_fn; // NOLINT
/** \brief Execute <tt>fn(congr_th)</tt> for each congruence theorem in this rule set. */
void for_each_congr(visit_congr_fn const & fn) const;
/** \brief Pretty print this rule set. */
format pp(formatter const & fmt, options const & opts) const;
};
io_state_stream const & operator<<(io_state_stream const & out, rewrite_rule_set const & rs);
name const & get_default_rewrite_rule_set_id();
/**
\brief Create a rewrite rule set inside the given environment.
\remark The rule set is saved when the environment is serialized.
\remark This procedure throws an exception if the environment already contains a rule set named \c rule_set_id.
*/
void mk_rewrite_rule_set(environment const & env, name const & rule_set_id = get_default_rewrite_rule_set_id());
/**
\brief Convert the theorem named \c th_name into conditional rewrite rules
and insert them in the rule set named \c rule_set_id in the given environment.
\remark This procedure throws an exception if the environment does not have a theorem/axiom named \c th_name.
\remark This procedure throws an exception if the environment does not have a rule set named \c rule_set_id.
*/
void add_rewrite_rules(environment const & env, name const & rule_set_id, name const & th_name);
inline void add_rewrite_rules(environment const & env, name const & th_name) {
add_rewrite_rules(env, get_default_rewrite_rule_set_id(), th_name);
}
/**
\brief Enable/disable the rewrite rules whose id is \c rule_id in the given rule set.
\remark This procedure throws an exception if the environment does not have a rule set named \c rule_set_id.
*/
void enable_rewrite_rules(environment const & env, name const & rule_set_id, name const & rule_id, bool flag);
inline void enable_rewrite_rules(environment const & env, name const & rule_id, bool flag) {
enable_rewrite_rules(env, get_default_rewrite_rule_set_id(), rule_id, flag);
}
/**
\brief Add a new congruence theorem to the given rewrite rule set.
*/
void add_congr_theorem(environment const & env, name const & rule_set_id, name const & th_name);
inline void add_congr_theorem(environment const & env, name const & th_name) {
add_congr_theorem(env, get_default_rewrite_rule_set_id(), th_name);
}
/**
\brief Return the rule set name \c rule_set_id in the given environment.
\remark This procedure throws an exception if the environment does not have a rule set named \c rule_set_id.
*/
rewrite_rule_set get_rewrite_rule_set(ro_environment const & env, name const & rule_set_id = get_default_rewrite_rule_set_id());
void open_rewrite_rule_set(lua_State * L);
}
| true |
1bfb3340fbe598da0a9440c519d9df7c75ba67bd | C++ | congard/algine | /include/common/algine/core/widgets/Layout.h | UTF-8 | 1,005 | 2.515625 | 3 | [
"MIT"
] | permissive | #ifndef ALGINE_LAYOUT_H
#define ALGINE_LAYOUT_H
#include <algine/core/widgets/Container.h>
namespace algine {
class Layout: public Container {
public:
static void setMargin(Widget *widget, int left, int top, int right, int bottom);
static void setMarginLeft(Widget *widget, int margin);
static void setMarginTop(Widget *widget, int margin);
static void setMarginRight(Widget *widget, int margin);
static void setMarginBottom(Widget *widget, int margin);
static int getMarginLeft(Widget *widget);
static int getMarginTop(Widget *widget);
static int getMarginRight(Widget *widget);
static int getMarginBottom(Widget *widget);
static void setAlignment(Widget *widget, uint alignment);
static uint getAlignment(Widget *widget);
protected:
static void setChildXDirectly(Widget *child, int x);
static void setChildYDirectly(Widget *child, int y);
static void childGeometryChanged(Widget *child, const RectI &geometry);
};
}
#endif //ALGINE_LAYOUT_H
| true |
77cedaffe1d02b220dd6b9bdb0cc3a681fcf7db6 | C++ | stephen-standridge/ofxLSystem | /src/ofxLSBuilder.cpp | UTF-8 | 1,515 | 2.5625 | 3 | [
"MIT"
] | permissive | #include "ofxLSBuilder.h"
ofxLSBuilder::ofxLSBuilder(string _axiom, vector<string> _rules, int _depth){
//check if axiom, rules and theta are ok,
// if not, define some default
if(validateInput(_axiom, _rules)) {
axiom = _axiom;
rulesContainer = _rules;
}
depth = _depth;
}
void ofxLSBuilder::setAxiom(string _axiom){
axiom = _axiom;
};
void ofxLSBuilder::setRules(vector<string> _rulesContainer){
rulesContainer = _rulesContainer;
};
void ofxLSBuilder::setup() {
reset();
build();
}
void ofxLSBuilder::reset() {
currentSentences.clear();
}
void ofxLSBuilder::build() {
currentSentences = ofxLSystemGrammar::buildSentences(rulesContainer, depth, axiom, constants);
}
bool ofxLSBuilder::isAxiomInRules(string _axiom, vector<string> _rulesContainer){
auto lettersInAxiom = ofxLSUtils::matchesInRegex(_axiom, "[a-zA-Z]");
for(auto letter : lettersInAxiom){
for(string rule : _rulesContainer){
if(ofxLSUtils::countSubstring(rule, letter) > 0){
return true;
}
}
}
return false;
}
bool ofxLSBuilder::validateInput(string _axiom, vector<string> _strRules){
try {
if(!isAxiomInRules(_axiom, _strRules)){
throw ofxLSBuilderError("axiom is not in rules container");
}
} catch (ofxLSBuilderError& e) {
ofLogError(e.what());
axiom = "F";
rulesContainer = {"F -> F[+F][-F]"};
return false;
}
return true;
}
| true |
9c4663c9d290aa38b13fb28844759453631bf56c | C++ | joeshmoe57/PARIS | /gcdfinder/keyGenerator/cInterface/getKeys.cpp | UTF-8 | 3,337 | 3.03125 | 3 | [] | no_license | /*
* Reads in 1024 bit RSA keys from the keys sub directory, and sticks them
* into our internal 1024 bit representation.
*/
#include <stdio.h>
#include <string.h>
#include <vector>
//provides generic fmemopen for non linux systems
#include "cfmemopen.h"
#include "sqlite3.h"
//OpenSSL stuff
#include "lcrypto.h"
#include "lrsa.h"
#include "lpem.h"
#include "lbn.h"
#include "getKeys.h"
/*
* Gets the specified number of keys out of the specified database and puts them in two places:
* a vector of RSA* private keys, and a vector of uint32_t[1024] n's, set to
* out endian-ness.
* Returns the number of keys retreived on success, negative on failure.
*/
int getAllKeys(char* fileName, int num, std::vector<RSA*> *privKeys, uint32_t pubKeys[][32]) {
//according to dox, DO NOT malloc this. Open creates it
sqlite3 *db = NULL;
sqlite3_stmt *statement;
char *zErrMsg = 0;
int res = 0;
int keyIndex;
//connect to the db
if(!fileName || !privKeys || !pubKeys){
puts("bad file name!");
return -1;
}
res = sqlite3_open(fileName, &db);
if(res){
printf("Error opening DB: %s\n", sqlite3_errmsg(db));
sqlite3_close(db);
return -1;
}
//run a query (get all keys in this case)
char qGetAll[] = "SELECT * FROM keys;";
res = sqlite3_prepare_v2(db, qGetAll, strlen(qGetAll), &statement, (const char**)&zErrMsg);
printf("res was %d\n", res);
if(res != SQLITE_OK){
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
sqlite3_close(db);
return -1;
}
//now loop through the entire database, adding things to the vector
int bufSize;
RSA* tkey;
uint8_t* buf;
uint32_t* ourform;
FILE* pem;
keyIndex = 0;
while(keyIndex < num && (res = sqlite3_step(statement)) == SQLITE_ROW){
//get the actual blob out
bufSize = sqlite3_column_bytes(statement, 0);
buf = (uint8_t*)sqlite3_column_text(statement, 0);
//open the PEM byffer as a FILE* so we can convert to RSA
pem = SCFmemopen(buf, bufSize, "r");
//convert it to an RSA*
tkey = RSA_new();
PEM_read_RSAPrivateKey(pem, &tkey, NULL, 0);
if(!tkey){
puts("error decoding PEM string into RSA key");
return -1;
}
privKeys->push_back(tkey);
//RSA_print_fp(stdout, privKeys->at(0), 0);
//now convert N into our format, and store that as well
ourform = (uint32_t*)calloc(32, sizeof(uint32_t));
res = bnToUs(tkey->n, ourform);
if(res != 0){
puts("Error convering big num types");
return -1;
}
//pubKeys->push_back(ourform);
memcpy(pubKeys[keyIndex], ourform, 32);
keyIndex++;
}
sqlite3_finalize(statement);
sqlite3_close(db);
return keyIndex;
}
/*
* Converts a BIGNUM into one of our 1024 bit ints (with opposing endianness).
* BIGNUMs have slot [max] = MSB. We have slot [0] as MSB. It expects everything
* incoming to be pre-allocated
* Returns -1 on failure (null buffer), 1 on success.
*/
int bnToUs(BIGNUM *bn, uint32_t *us){
if(!bn || !us){
puts("null to reverse");
return -1;
}
//go through the bn forward, and the us in reverse to store each byte
int i;
for(i = 0; i < bn->top; i++){
us[31-i] = bn->d[i];
}
return 0;
}
| true |
9168f815e3f36b482470ef0eb1a16627c9c73653 | C++ | GIPdA/ZetaRF | /examples/SimpleRxTx/SimpleRxTx.ino | UTF-8 | 6,039 | 2.5625 | 3 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /*
* Zeta RF v2 Getting Started Code Example.
* Basic example on how to send messages back and forth between two modules using fixed size packets.
*
* Usage: write this sample on both boards and chat over serial!
*/
#include <ZetaRf.hpp>
// Zeta modules transmit messages using fixed size packets, define here the max size you want to use. For variable length packets, see the corresponding example.
// Radio configurations also sets a default packet size, usually 8, that you can get using zeta.defaultPacketLength().
constexpr size_t ZetaRfPacketLength {8};
ZetaRf868<ZetaRf::nSEL<10>, ZetaRf::SDN<9>, ZetaRf::nIRQ<8>> zeta;
//old- ZetaRf zeta(10,9,8);
char data[ZetaRfPacketLength] = "Hello ";
void setup()
{
Serial.begin(115200);
while (!Serial); // Might wait for actual serial terminal to connect when over USB
Serial.println("Starting Zeta TxRx...");
// Initialize Zeta module with a specific packet size
if (!zeta.beginWithPacketLengthOf(ZetaRfPacketLength)) {
//old- if (!zeta.begin(4, ZetaRfPacketLength)) {
Serial.println(F("ZetaRf begin failed. Check wiring?"));
while(true);
}
// Print some info about the chip
auto const& pi = zeta.readPartInformation();
//old- const Si4455_PartInfo &pi = zeta.readPartInfo();
Serial.println("----------");
Serial.print("Chip rev: "); Serial.println(pi.CHIPREV);
Serial.print("Part : "); Serial.println(pi.PART, HEX);
Serial.print("PBuild : "); Serial.println(pi.PBUILD);
Serial.print("ID : "); Serial.println(pi.ID);
Serial.print("Customer: "); Serial.println(pi.CUSTOMER);
Serial.print("Rom ID : "); Serial.println(pi.ROMID);
//Serial.print("Bond : "); Serial.println(pi.BOND);
Serial.print('\n');
/*auto const& fi = zeta.readFunctionRevisionInformation();
//old- const Si4455_FuncInfo &fi = zeta.readFuncInfo();
Serial.print("Rev Ext : "); Serial.println(fi.REVEXT);
Serial.print("Rev Branch: "); Serial.println(fi.REVBRANCH);
Serial.print("Rev Int : "); Serial.println(fi.REVINT);
Serial.print("Patch : "); Serial.println(fi.PATCH);
Serial.print("Func : "); Serial.println(fi.FUNC);
Serial.print("SVN Flags : "); Serial.println(fi.SVNFLAGS);
Serial.print("SVN Rev : "); Serial.println(fi.SVNREV, HEX);
Serial.println("----------");//*/
// Start continuous listening on channel 4 (auto-returns to listening after reception of a packet)
//zeta.startListeningOnChannel(4);
//old- zeta.startListening();
// Or just listen for one packet then wait (needed to be able to read a packet's RSSI)
zeta.startListeningSinglePacketOnChannel(4);
Serial.println(F("Init done."));
}
void loop()
{
// At least one of the zeta.checkFor*Event*() methods must be called in order to update the library.
// checkForEvent() returns any event of: Event::CrcError | Event::PacketTransmitted | Event::PacketReceived | Event::LatchedRssi
// | Event::TxFifoAlmostEmpty | Event::RxFifoAlmostFull | Event::FifoUnderflowOrOverflowError
// checkForAnyEventOf(filter) enables you to filter events.
// checkForAllEventsOf(filter) will return ZetaRf::Event::None unless all events in filter are present.
//
// Unfiltered events are accessible via zeta.events(). Use zeta.clearEvents([event]) to clear all or specified events.
if (ZetaRf::Events const ev = zeta.checkForEvent()) {
if (ev & ZetaRf::Event::DeviceBusy) {
// DeviceBusy error usually means the radio module is unresponding and need a reset.
Serial.println(F("Error: Device Busy! Restarting..."));
if (!zeta.beginWithPacketLengthOf(ZetaRfPacketLength)) {
Serial.println(F("ZetaRf begin failed after comm error."));
while (true);
}
zeta.restartListeningSinglePacket();
}
/*if (ev & ZetaRf::Event::LatchedRssi) {
// Latched RSSI is cleared when restarting RX
uint8_t rssi = zeta.latchedRssiValue();
Serial.print(F("RSSI: "));
Serial.println(rssi);
}//*/
if (ev & ZetaRf::Event::PacketReceived) {
// We'll read data later
// Get RSSI (only valid in single packet RX, before going back to RX)
uint8_t const rssi = zeta.latchedRssiValue();
// Restart listening on the same channel
zeta.restartListeningSinglePacket();
Serial.print(F("Packet received with RSSI: "));
Serial.println(rssi);
}
if (ev & ZetaRf::Event::PacketTransmitted) {
// Back to RX afer TX
zeta.restartListeningSinglePacket();
Serial.println(F("Packet transmitted"));
}
/*if (ev & ZetaRf::Event::TxFifoAlmostEmpty) {
Serial.println("TX Fifo almost empty");
}//*/
}
// Read incoming packet and print it
if (zeta.available()) {
if (zeta.readPacketTo((uint8_t*)data)) { // Uses packet length set at zeta.beginWithPacketLengthOf(). Data buffer must be large enough!
//zeta.readPacketTo((uint8_t*)data, ZetaRfPacketLength); // Alternative way, but be careful to not read more than the packet length.
//old- zeta.readPacket(data)
//zeta.restartListeningSinglePacket(); // If not in checkForEvent
// Print!
Serial.print("RX >");
Serial.write(data, ZetaRfPacketLength);
Serial.println("<");
// Print in HEX
Serial.println("HEX >");
for (uint8_t i = 0; i < zeta.packetLength(); i++) {
Serial.print(data[i], HEX);
}
Serial.println("<");
}
}
// Send any data received from serial
if (Serial.available()) {
// Check FIFO space first
if (zeta.requestBytesAvailableInTxFifo() >= ZetaRfPacketLength) {
int const s = Serial.readBytes(data, ZetaRfPacketLength);
// Pad with zeros
for (uint8_t i = s; i < ZetaRfPacketLength; i++) {
data[i] = 0;
}
Serial.print("TX >");
Serial.write(data, ZetaRfPacketLength);
Serial.println("<");
// Send buffer
zeta.sendFixedLengthPacketOnChannel(4, (const uint8_t*)data);
}
}
delay(10); // Hooo, not too fast! But you could...
}
| true |
1b40ec412f561748ef007fc75805501e2727a912 | C++ | nlevashov/matrix | /main.cpp | UTF-8 | 288 | 2.6875 | 3 | [] | no_license | #include <iostream>
#include "matrix.h"
using namespace std;
int main () {
matrix<double> a;
cin >> a;
cout << a[0][1] << endl;
matrix<int> b = a;
cout << b.inv();
matrix<float> c;
c = b.inv();
cout << c;
cout << c.transp() << c.trace() << endl << c.det() << endl;
return 0;
}
| true |
e519729a9f19598e8ef782057085a6e4393ee064 | C++ | kamal01k/learnOpenGl | /helloWindow/helloWindow.cpp | UTF-8 | 2,708 | 3.171875 | 3 | [] | no_license | #include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <iostream>
using namespace std;
// Function definition for window resize callback function
void framebuffer_size_callback(GLFWwindow* window, int width, int height);
// Function definition for handling key inputs
void processInput(GLFWwindow * window);
// Main
int main()
{
// Initialize GLFW
glfwInit();
// Configure GLFW
// First argument defines option to configure
// Second argument sets the value of option
// Define version of OpenGL in use
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR,3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR,3);
// Define Core_Profile mode
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
// Create window object
GLFWwindow* window = glfwCreateWindow(800, 600, "LearnOpenGL", NULL, NULL);
if (window == NULL){
cout << "Failed to create GLFW window" << endl;
return -1;
}
// Make the context of window the main context for current thread
glfwMakeContextCurrent(window);
// Initialize glad
if(!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
cout << "Failed to initialize GLAD" << endl;
return -1;
}
// Pass glad the function to load address of OpenGL function pointers which is OS-specific
// GLFW gives glfwGetProcAddress that defines correct function based on OS
// Set up viewport
glViewport(0,0,800,600);
// First two parameters: set location of lower left corner of window
// Third & fourth parameter: Set width and height
// glViewport transforms 2D coordinates to coordinates on screen
// callback function for resizing window
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
// Set-up render loop
// Check if GLFW has been instructed to close
while(!glfwWindowShouldClose(window))
{
//Catch inputs
processInput(window);
// Rendering commands here:
// Clear screen with color of choice
// Define clear color
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
// Clear
glClear(GL_COLOR_BUFFER_BIT);
// Swap color buffer that has been used to draw in
// during this iteration and show as output onto screen
glfwSwapBuffers(window);
// Check if any events are triggered
glfwPollEvents();
}
// Terminate after exiting render loop
glfwTerminate();
return 0;
}
// Function for window resize callback function
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
glViewport(0,0,width,height);
}
// Function to handle inputs
void processInput(GLFWwindow *window)
{
// glfwGetKey: get whether a key is being pressed
if(glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
// Close window if escape key pressed
glfwSetWindowShouldClose(window,true);
}
| true |
65a9a8d2a5a21231c876ea73ef7fbe116d00bc2b | C++ | tommy85/test | /schedule/schedule.cpp | UTF-8 | 5,555 | 3.09375 | 3 | [] | no_license | #include<iostream>
#include<map>
#include<iterator>
#include <algorithm>
#include <assert.h>
#include <string.h>
using namespace std;
typedef struct _Date
{
int year;
int month;
int day;
//int hour;
//int min;
//int seconds;
bool operator<(const _Date &d2) const
{
if (month == d2.month)
return day < d2.day;
else
return month < d2.month;
}
bool operator<=(const _Date &d2) const
{
if (month == d2.month)
return day <= d2.day;
else
return month < d2.month;
}
bool operator>(const _Date &d2) const
{
if (month == d2.month)
return day > d2.day;
else
return month > d2.month;
}
bool operator>=(const _Date &d2) const
{
if (month == d2.month)
return day >= d2.day;
else
return month > d2.month;
}
bool operator==(const _Date &d2) const
{
return day == d2.day && month == d2.month;
}
bool operator!=(const _Date &d2) const
{
return day != d2.day || month != d2.month;
}
} Date;
typedef struct _Timezone
{
Date start;
Date end;
int type;
// friend bool operator<(const _Timezone &t1,const _Timezone &t2);
/*
bool operator<(const _Timezone &t2) const
{
if (type == 1 || t2.type == 1)
{
_Timezone tmp;
//compare time point
assert(!(type == 1 && t2.type == 1));
tmp = (type == 1)?*this:t2;
assert(t2.start != t2.end);
if (t2.start > t2.end)
{
return (tmp.start < t2.start);
}
else
{
return (tmp.start < t2.start);
}
}
else
{
assert(start != end);
assert(t2.start != t2.end);
if (start > end || t2.start > t2.end)
{
assert(!(start > end && t2.start > t2.end));
return (start > end)?false:true;
}
else
{
return (end < start);
}
}
}
*/
/*
friend bool operator==(_Timezone &t1,_Timezone &t2)
{
if (t1.type == 1 || t2.type == 1)
{
//compare time point
_Timezone tmp;
assert(!(t1.type == 1 && t2.type == 1));
tmp = (t1.type == 1)?t1:t2;
assert(t2.start != t2.end);
if (t2.start > t2.end)
{
return (tmp.start >= t2.start) || (tmp.start <= t2.end);
}
else
{
return (tmp.start <= t2.end && tmp.start >= t2.start);
}
}
else
{
//compare time zone
assert(t1.start != t1.end);
assert(t2.start != t2.end);
return (t1.start == t2.start && t1.end == t2.end);
}
}
*/
} Timezone;
bool operator<(const Timezone &t1,const Timezone &t2)
{
if (t1.type == 1 || t2.type == 1)
{
Timezone tmp1,tmp2;
//compare time point
assert(!(t1.type == 1 && t2.type == 1));
if (t1.type == 1)
{
return t1.start < t2.start;
}
else
{
return t1.end < t2.start;
}
}
else
{
assert(t1.start < t1.end);
assert(t2.start < t2.end);
return (t1.end < t2.start);
}
}
class Schedule
{
public:
Schedule(Timezone &zone,string &_uri):timezone(zone),uri(_uri){};
virtual ~Schedule(){};
void do_schedule()
{
cout<<"timezone,start year month day"<<timezone.start.year<<" "<<
timezone.start.month<<" "<<timezone.start.day<<endl;
cout<<"timezone,end year month day"<<timezone.end.year<<" "<<
timezone.end.month<<" "<<timezone.end.day<<endl;
cout<<"play "<<uri<<endl;
}
inline Timezone & GetTime()
{
return timezone;
}
private:
Timezone timezone;
string uri;
};
typedef map<Timezone,Schedule> SchMap;
class ScheduleList
{
public:
ScheduleList(){}
~ScheduleList(){}
void AddSchedule(Schedule &sch)
{
if (schmap.find(sch.GetTime()) == schmap.end())
{
schmap.insert(make_pair(sch.GetTime(),sch));
}
else
{
cout<<"Schedule is already exist,Sch day="<<sch.GetTime().start.day<<
" "<<sch.GetTime().end.day<<endl;
}
}
void Display(Date &date)
{
Timezone tz;
tz.start = date;
tz.start.month = 0;
tz.type = 1;
SchMap::iterator it;
cout<<"Display"<<endl;
if ((it = schmap.find(tz)) != schmap.end())
{
it->second.do_schedule();
}
else
{
cout<<"find second times"<<endl;
tz.start.month = 1;
if ((it = schmap.find(tz)) != schmap.end())
{
it->second.do_schedule();
}
else
{
cout<<"Schedule is not exist,Date day="<<date.day<<endl;
}
}
}
void ShowSch()
{
cout<<"Show Schedule"<<endl;
SchMap::iterator it = schmap.begin();
for (;it !=schmap.end();it++)
{
it->second.do_schedule();
}
}
private:
SchMap schmap;
};
int main()
{
ScheduleList schlist;
Timezone tz1,tz2,tz3;
memset(&tz1,0,sizeof(Timezone));
memset(&tz2,0,sizeof(Timezone));
memset(&tz3,0,sizeof(Timezone));
/* 25~3*/
tz1.start.day = 25;
tz1.end.day = 3;
tz1.end.month = 1;
/* 7-13*/
tz2.start.day = 7;
tz2.end.day = 15;
/*14-22*/
tz3.start.day = 17;
tz3.end.day = 22;
/*
if (tz2 < tz3)
{
cout<<"tz2<tz3"<<endl;
}
less<Timezone> i;
if(i(tz2,tz3))
{
cout<<"tz2<tz3"<<endl;
}
*/
string str1("uri1");
string str2("uri2");
string str3("uri3");
Schedule sch1(tz1,str1);
Schedule sch2(tz2,str2);
Schedule sch3(tz3,str3);
schlist.AddSchedule(sch1);
schlist.AddSchedule(sch2);
schlist.AddSchedule(sch3);
cout<<"----------------------"<<endl;
schlist.ShowSch();
cout<<"----------------------"<<endl;
Date date;
date.year = 1985;
date.month = 5;
date.day = 18;
schlist.Display(date);
}
| true |
d19ab0926c37e7b14684152005b63a5fb5377f34 | C++ | JuicyJerry/mincoding | /(훈련반1) Level22.5 - 문제5번.cpp | UTF-8 | 357 | 3 | 3 | [] | no_license | #include <iostream>
using namespace std;
char y, x;
char map[3][7] = { "354223", "133342", "544235" };
char price[6] = "TPGKC";
int main()
{
cin >> y >> x;
if (y == 'A') y = ('0' - 48);
else if (y == 'B') y = ('1' - 48);
else if (y == 'C') y = ('2' - 48);
if (x >= 48 && x <= 57) x = (x - 48) - 1;
cout << price[(map[y][x] - 48) - 1];
return 0;
} | true |
de4e8049a26ff0f5ce29502488dfbf68582de64e | C++ | cYKatherine/ProgrammingContest | /ANZAC5/L.cpp | UTF-8 | 1,108 | 2.96875 | 3 | [] | no_license | #include <iostream>
#include <map>
#include <set>
#include <vector>
#define FIDX(_x, _y) (_x*n+_y)
#define SETFRIEND(_x, _y) { friends[_x*n+_y] = true; friends[_y*n+_x] = true; }
#define ISFRIEND(_x, _y) (friends[FIDX(_x, _y)])
long traverse(std::vector<bool> &checked, std::vector<bool> &friends, std::vector<int> &owes, int i)
{
long total = 0;
int n = owes.size();
if(!checked[i]) {
total += owes[i];
checked[i] = true;
for(int k = 0; k < n; ++k) {
if(ISFRIEND(i, k)) total += traverse(checked, friends, owes, k);
}
}
return total;
}
int main(int argc, char **argv)
{
int n, m;
std::cin >> n >> m;
std::vector<int> owes;
for(int i = 0; i < n; ++i) {
int o;
std::cin >> o;
owes.push_back(o);
}
std::vector<bool> friends(n*n);
for(int i = 0; i < m; ++i) {
int x, y;
std::cin >> x >> y;
SETFRIEND(x, y);
}
std::vector<bool> checked(n);
bool possible = true;
for(int i = 0; i < n; ++i) {
if(!checked[i]) {
if(traverse(checked, friends, owes, i) != 0) { possible = false; break; }
}
}
std::cout << (possible ? "POSSIBLE" : "IMPOSSIBLE") << std::endl;
}
| true |
786276ac0b3b897b5541a872977661de7efad87f | C++ | tianpi/thekla | /src/common/Exception.cpp | UTF-8 | 590 | 2.59375 | 3 | [
"MIT"
] | permissive |
#include "Exception.h"
//--------------------------------------------------------------------------------
Log Exception::exceptLog = rootLog;
//--------------------------------------------------------------------------------
Exception::Exception(const std::string & msg)
: std::runtime_error(msg)
{
}
//--------------------------------------------------------------------------------
Exception::~Exception()
throw ()
{
}
//--------------------------------------------------------------------------------
Exception::Exception(const Exception & rhs)
: runtime_error(rhs)
{
}
| true |
e2d1d665ec1be0d81603534bfbaa3086db119d6f | C++ | SCeruso/MaquinaRAM | /MaquinaRam/includes/Tag.h | UTF-8 | 259 | 2.765625 | 3 | [] | no_license | /*
*Author: Sabato Ceruso
*Date: 05/02/2015
*/
#pragma once
#include <string>
using namespace std;
class Tag
{
private:
string tag_;
int line_;
public:
Tag(string, int);
Tag(string);
~Tag();
string get_tag();
int get_line();
bool operator == (Tag&);
};
| true |
7780db82f29b9be246028ed95bec335765162f4f | C++ | ahmedibrahim404/CompetitiveProgramming | /UVA/11953 - UVA/main.cpp | UTF-8 | 893 | 2.53125 | 3 | [] | no_license | #include <iostream>
#include <cstring>
using namespace std;
int T, n;
char ns[100+1][100+1];
bool vis[100+1][100+1];
int main(){
cin >> T;
int ts=1;
while(T--){
int cnt=0;
cin >> n;
memset(vis, 0, sizeof vis);
for(int i=0;i<n;i++)cin >> ns[i];
for(int i=0;i<n;i++) for(int j=0;j<n;j++){
if(ns[i][j]=='x' && !vis[i][j]){
int nx=i+1, ny=j;
while(ns[nx][ny]=='x' || ns[nx][ny] == '@'){
vis[nx][ny]=1;
nx++;
}
nx=i, ny=j+1;
while(ns[nx][ny]=='x' || ns[nx][ny] == '@'){
vis[nx][ny]=1;
ny++;
}
cnt++;
}
}
cout << "Case " << ts ++ << ": " << cnt << endl;
}
return 0;
}
| true |
4110b4f99e786f00696cd9bef11593dba2241587 | C++ | lyoos/Hyper-NetworkSystem | /hypns.hpp | ISO-8859-1 | 4,121 | 2.6875 | 3 | [
"BSD-3-Clause"
] | permissive | #pragma once
#include<iostream>
#include<string>
#include<vector>
#include<map>
#ifdef DEBUG
#include"debugTools.hpp"
#endif
#if defined FILE_H
#define D_BUG_INCLUDE ((bool)true)
#else
#define D_BUG_INCLUDE ((bool)false)
#endif
namespace hns {
struct PackageObject {
protected:
string poType;
string poData;
public:
PackageObject(const char* type, const char* datas) {
if (sizeof(type) != 0 && sizeof(datas) != 0) {
this->poType = type;
this->poData = datas;
}
}
PackageObject(string type, string datas) { PackageObject(type.c_str(), datas.c_str()); }
const char* GiveObjectType() { return poType.c_str(); }
const char* GiveOjectData() { return poData.c_str(); }
bool itsusd() { if (poData.size() != 0 && poType.size() != 0) return true; else return false; }
string GiveObjectHash();
};
/*
Speichert alle wichtigen Paket Objekte ab
*/
struct PackageObjectDatas{std::vector<const char*> fObjectTypes; std::map<const char*, std::string> objDatas;};
/* berprft ob es sich bei dem String um eine IDv Handelt */
bool itsaCorrectIDv(std::string str);
/*
in einem IDvString knnen nur IDv Adressen gespeichert werden.
*/
struct IDvString {
private:
std::string buffer;
std::string IDvHash;
bool func_string;
int type;
bool itsUsed;
// Schreibt einen String in den IDv String sofern dieser gltig ist
int write(const char*);
public:
// Erstellt einen Leeren IDv String
IDvString() { itsUsed = false; func_string = false; }
// Dieser String gibt die ID aus
std::string GiveID() { return buffer; }
// Dieser String gibt den Hasch-Wert der IDv aus
std::string GiveHash() { return IDvHash; }
// Dieser int gibt an um was fr eine ID es sich Handelt
int GiveStringType() { return type; }
// Gibt an ob der String beschrieben wurde
bool StringUsedCheck() { return itsUsed; }
friend class PackageHandler;
friend IDvString SelfID();
friend IDvString UnkownID();
};
IDvString SelfID();
IDvString UnkownID();
/*
Speichert alle wichtigen Paket Meta Datan ab
*/
struct PackageMeteDatas { IDvString from, to; };
/*
Eine Package speichert eine Package ab hnlich wie in einem String.
*/
class Package {
protected:
// Speichert alle Paket Objekte ab
PackageObjectDatas ObjectBuff;
// Speichert die Meta Data eines Paketes ab, zb von, an, Session ID, Package ID
PackageMeteDatas MeteBuff;
// Gibt den Status des Aktuellen Paketes an
int cpstate();
// Gibt an ob das Paket beschrieben wurde
bool psww();
public:
};
/*
Package Handler, sind die erste Instance wenn es darum geht Rohdaten in eine Package zu laden,
hierbei kann dies z.b aus einer Datei heraus oder aus einem String passieren.
*/
class PackageHandler {
private:
int L_O_state = 0; // Gibt den Statuscode der Letzten Operation aus
int nlType = 0; // Gibt an ob das Paket mit UDP oder TCP versand wurde
int mType = 0; // Gibt z.b aus ob das Paket ein Stream oder eine DirektSend ist
int pType = 0; // Gibt den Pakettypen an
bool cann_used = false; // Solange dieser Wert auf False steht kann ein solches Paket nicht verwendet werden
PackageObjectDatas ObjectBuff; // Speichert alle Paket Objekte ab
PackageMeteDatas MeteBuff; // Speichert die Meta Data eines Paketes ab, zb von, an, Session ID, Package ID
public:
// Erstellt aus einem String ein Package, solange der Synatx richtig ist
PackageHandler(const char*);
// Erstellt aus einem String ein Package, solange der Synatx richtig ist
PackageHandler(std::string);
// Diese Funkion gibt aus ob das Package richtig ist und ob eine Ausgabe als Package mglich ist
bool coutpck();
// Gibt die ausgewerteten Daten in ein Package weiter
Package GivePackage();
};
/*
Package Creator, mit diesem Objekt knnen sie neue Pakete erstellen, defenieren sie dabei Genau wie das Paket aufgebaut werden soll und befllen es am nurnoch mit Daten und knnen es Direkt absenden
*/
class PackageCreator {
};
} | true |
479da52b445ae231e00367697023a9f153e1e87d | C++ | derekniess/3D-Physics-Engine-Framework | /Controller.h | UTF-8 | 1,154 | 2.5625 | 3 | [
"MIT"
] | permissive | #pragma once
#include "Component.h"
#include "Transform.h"
#include "InputManager.h"
#include "FrameRateController.h"
class Controller : public Component
{
/*----------MEMBER VARIABLES----------*/
private:
InputManager const & InputManagerReference;
FramerateController const & FrameRateControllerReference;
vector3 upVector = vector3(0.0f, 1.0f, 0.0f);
vector3 leftVector = vector3(1.0f, 0.0f, 0.0f);
vector3 forwardVector = vector3(0.0f, 0.0f, -1.0f);
public:
float MovementSpeed = 1.f;
Transform * TargetTransform = nullptr;
/*----------MEMBER FUNCTIONS----------*/
public:
Controller(InputManager const & in, FramerateController const & frame) : InputManagerReference(in), FrameRateControllerReference(frame), Component(Component::CONTROLLER) {}
virtual ~Controller() {};
static inline ComponentType GetComponentID() { return Component::ComponentType::CONTROLLER; }
static inline const char * GetComponentName() { return ComponentTypeName[ComponentType::CONTROLLER]; }
virtual void Update() override;
virtual void Deserialize(TextFileData & aTextData) override {};
virtual void Serialize(TextFileData & aTextData) override {};
}; | true |
f5e1153d2c29925c89d77fcb304391b97beb7ec0 | C++ | Gabriel-98/HPC | /Reto 2: OpenMP/src/openMP/dartboard.cpp | UTF-8 | 3,058 | 3.171875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
// Variables de la configuracion
string version;
int N;
int numberOfThreads;
int show;
// Salida del problema
int hits;
double pi;
// Estructura para generar numeros aleatorios
struct RandomGenerator{
long long a = 6542315, b = 5617565, mod = 1e9 + 7;
long long x;
RandomGenerator() : x(time(NULL) % mod) {}
int random(){
x = (a * x + b) % mod;
return x;
}
};
//---- Caracteristicas para realizar las pruebas con el metodo de dartboard:
//---- - Tipo de dato: double
//---- - Los valores de X,Y se generan con 4 decimales en el intervalo [-1,1]
int dartboardTest(RandomGenerator &randomGenerator){
double x = ((randomGenerator.random() % 20001) / 10000.0) - 1.0;
double y = ((randomGenerator.random() % 20001) / 10000.0) - 1.0;
if(x*x + y*y <= 1.0)
return 1;
return 0;
}
//---- SOLUCION: Montecarlo - Dartboard
//---- Metodo de asignacion de tareas: Asignacion estatica del numero de pruebas
//---- Generador de numeros aleatorios: Una instancia distinta de la estructura para cada hilo
//---- Mecanismo de actualizacion: Region critica
void dartboardCritical(){
hits = 0;
#pragma omp parallel num_threads(numberOfThreads)
{
RandomGenerator randomGenerator;
#pragma omp for schedule(static)
for(int i=0; i<N; i++){
#pragma omp critical
hits += dartboardTest(randomGenerator);
}
}
pi = (4.0 * hits) / N;
}
//---- SOLUCION: Montecarlo - Dartboard
//---- Metodo de asignacion de tareas: Asignacion estatica del numero de pruebas
//---- Generador de numeros aleatorios: Una instancia distinta de la estructura para cada hilo
//---- Mecanismo de actualizacion: Operacion atomica
void dartboardAtomic(){
hits = 0;
#pragma omp parallel num_threads(numberOfThreads)
{
RandomGenerator randomGenerator;
#pragma omp for schedule(static)
for(int i=0; i<N; i++){
#pragma omp atomic
hits += dartboardTest(randomGenerator);
}
}
pi = (4.0 * hits) / N;
}
//---- SOLUCION: Montecarlo - Dartboard
//---- Metodo de asignacion de tareas: Asignacion estatica del numero de pruebas
//---- Generador de numeros aleatorios: Una instancia distinta de la estructura para cada hilo
//---- Mecanismo de actualizacion: Reduccion
void dartboardReduction(){
hits = 0;
#pragma omp parallel num_threads(numberOfThreads) reduction(+: hits)
{
RandomGenerator randomGenerator;
#pragma omp for schedule(static)
for(int i=0; i<N; i++)
hits += dartboardTest(randomGenerator);
}
pi = (4.0 * hits) / N;
}
int main(int argc, char** argv){
// Configuracion
version = argv[1];
N = atoi(argv[2]);
numberOfThreads = atoi(argv[3]);
show = atoi(argv[4]);
// Calculo del numero pi
if(version == "critical")
dartboardCritical();
else if(version == "atomic")
dartboardAtomic();
else if(version == "reduction")
dartboardReduction();
else
cout<<"Error! Nombre de version incorrecto"<<endl;
// Mostrar el resultado
if(show){
cout<<"Numero de intentos: "<<N<<endl;
cout<<"Numero de aciertos: "<<hits<<endl;
cout<<"Numero pi: "<<fixed<<setprecision(6)<<pi<<endl;
}
} | true |
48052e32123de48000377330a7c57aa8a1bc6f6d | C++ | ParsaWolf-mr/Aufgabe-1 | /D2VectorDet/D2VectorDet.cpp | UTF-8 | 1,579 | 3.484375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <fstream>
#include <math.h>
double Determinat(std::vector<std::vector<double>>& myVector);
void print(const double& T, const std::vector<std::vector<double>>& vec);
int main(int argc, char* argv[]) {
double t;
std::vector <std::vector<double>>D2Vec;
if (argc == 1){
std::cerr << "this ist argument\n";
return EXIT_FAILURE;
}
auto text = argv[1];
std::ifstream File(text);
if (File.fail()) {
std::cerr << "thie isn' t such file in this dirctory\n";
return 0;
}
if (File.is_open()) {
for (unsigned int i = 0; i < 3; i++) {
std::vector<double>temp;
for (unsigned int j = 0; j < 3; j++) {
File >> t;
temp.push_back(t);
}
D2Vec.push_back(temp);
}
}
double sum = Determinat(D2Vec);
print(sum, D2Vec);
return 0;
}
double Determinat(std::vector<std::vector<double>>& myVector)
{
double sum = 0, p;
int x, y;
x = 1;
y = 2;
for (unsigned int i = 0; i <= 2; i++) {
if (i == 2) y = 1;
for (i = 0; i <= 2; i++) {
p = pow(-1, i);
sum = sum + (myVector[0][i] * (myVector[1][x] * myVector[2][y] - myVector[2][x] * myVector[1][y])) * p;
x = 0;
}
}
return sum;
}
void print(const double & T, const std::vector<std::vector<double>>& vec) {
for (int i =1 ; i<= 3; i++){
if (i == 2) {
std::cout << "det[";
}
else {
std::cout << " [";
}
for (int j = 1; j <= 3; j++) {
std::cout <<vec[i-1][j-1] ;
if (j<= 2)
std::cout << ",";
}
if (i == 2) {
std::cout << "]= " << T << std::endl;
}
else {
std::cout << "]\n";
}
}
} | true |
9f108afdf8fe15e751a3df8c781e4eedcef060be | C++ | Hermera/OI | /Code/Codeforces/671A.cpp | UTF-8 | 820 | 2.75 | 3 | [] | no_license | #include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
int read() {
char ch = getchar(); int x = 0;
while(ch < '0' || ch > '9') ch = getchar();
while(ch >= '0' && ch <= '9') x = x*10+ch-'0', ch = getchar();
return x;
}
struct Point {
double x, y;
void init() {
x = read(), y = read();
}
} A, B, T, D;
double dis(Point a, Point b) {
return sqrt( (a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y));
}
int N;
int main() {
A.init();
B.init();
T.init();
double ans = 0;
double fa = 1e20, fb = 1e20, fab = 1e20;
N = read();
while(N--) {
D.init();
ans += 2*dis(D, T);
double af = dis(A, D)-dis(D, T);
double bf = dis(B, D)-dis(D, T);
fab = min(fab, min(fa+bf, fb+af));
fa = min(fa, af);
fb = min(fb, bf);
}
printf("%.12lf\n", ans + min(fab, min(fa, fb)));
return 0;
}
| true |
cdbb3a4c0847f879dd87178cf4424bb472085a16 | C++ | TeamProjectChocolate/ChocoBall_New | /Project/ChocoBall/StageManager.cpp | SHIFT_JIS | 1,448 | 2.546875 | 3 | [] | no_license | #include "stdafx.h"
#include "StageManager.h"
#include "GameManager.h"
#include "ShadowRender.h"
CStageManager* CStageManager::m_instance = nullptr;
int CStageManager::m_ClearNum = 0;
void CStageManager::Initialize()
{
m_NowStage = STAGE_ID::STAGE_NONE;
#ifdef TEISYUTU_YOU
ChangeStage(STAGE_ID::FIRST);
#else
ChangeStage(STAGE_ID::FIRST);
#endif
SetNextStage();
}
void CStageManager::Update(){
m_pStage->Update();
}
void CStageManager::Draw()
{
m_pStage->Draw();
}
void CStageManager::ChangeStage(STAGE_ID id){
m_NextStage = id;
}
void CStageManager::SetNextStage(){
if (m_IsContinue){
if (m_ContinueStage >= STAGE_ID::MAX && m_ContinueStage != STAGE_ID::STAGE_NONE){
// Ō܂ŃNAĂ炱̏ʂ
SINSTANCE(CShadowRender)->CleanManager();
SINSTANCE(CObjectManager)->CleanManager();
SAFE_DELETE(m_pStage);
m_pStage = nullptr;
m_IsContinue = false;
SINSTANCE(CGameManager)->ChangeScene(_T("Title"));
SINSTANCE(CGameManager)->SetNextScene();
return;
}
}
if (m_NowStage != m_NextStage){
if (m_IsContinue){
m_NowStage = m_ContinueStage;
}
else{
m_NowStage = m_NextStage;
}
SINSTANCE(CShadowRender)->CleanManager();
SINSTANCE(CObjectManager)->CleanManager();
SAFE_DELETE(m_pStage);
m_pStage = new CStage;
m_pAudio->DeleteAll();
m_pStage->Initialize(m_pAudio,m_NowStage);
m_ContinueStage = m_NowStage;
}
}
void CStageManager::DeleteAll(){
}
| true |
c12dbbc97a6cd65eff7d5630b00f8c4c73377bcd | C++ | jube/std_hmi | /src/renderer.cc | UTF-8 | 8,980 | 2.625 | 3 | [
"MIT"
] | permissive | #include <bits/renderer.h>
#include <cassert>
#include <iostream>
#include <memory>
#include <SDL.h>
#include <glad/glad.h>
#include <bits/color.h>
#include <bits/mat_ops.h>
#include <bits/vec_ops.h>
namespace hmi {
namespace {
constexpr const char *g_vertex_shader = R"shader(
#version 100
attribute vec2 a_position;
attribute vec4 a_color;
varying vec4 v_color;
uniform mat3 u_transform;
void main(void) {
v_color = a_color;
vec3 worldPosition = vec3(a_position, 1);
vec3 normalizedPosition = worldPosition * u_transform;
gl_Position = vec4(normalizedPosition.xy, 0, 1);
}
)shader";
constexpr const char *g_fragment_shader = R"shader(
#version 100
precision mediump float;
varying vec4 v_color;
void main(void) {
gl_FragColor = v_color;
}
)shader";
GLuint compile_shader(const char *code, GLenum type) {
GLuint id = glCreateShader(type);
if (id == 0) {
return 0;
}
// compile
const char *source[1] = { code };
glShaderSource(id, 1, source, nullptr);
glCompileShader(id);
// and check
GLint compile_status = GL_FALSE;
glGetShaderiv(id, GL_COMPILE_STATUS, &compile_status);
if (compile_status == GL_FALSE) {
GLint info_log_length = 0;
glGetShaderiv(id, GL_INFO_LOG_LENGTH, &info_log_length);
assert(info_log_length > 0);
std::unique_ptr<char[]> info_log(new char[info_log_length]);
glGetShaderInfoLog(id, info_log_length, nullptr, info_log.get());
std::cerr << "Error while compiling shader: " << info_log.get() << std::endl;
return 0;
}
return id;
}
constexpr
vec2f affine_transform(const mat3f& mat, vec2f point) {
return { mat.xx * point.x + mat.xy * point.y + mat.xz, mat.yx * point.x + mat.yy * point.y + mat.yz };
}
}
renderer::renderer(SDL_Window *window)
: m_window(window)
, m_context(nullptr)
, m_program(0)
{
// create context
m_context = SDL_GL_CreateContext(window);
if (m_context == nullptr) {
std::cerr << "Failed to create a context: " << SDL_GetError() << std::endl;
return;
}
int err = SDL_GL_MakeCurrent(m_window, m_context);
if (err != 0) {
std::cerr << "Failed to make the context current: " << SDL_GetError() << std::endl;
}
// load GLES2 functions
if (gladLoadGLES2Loader(SDL_GL_GetProcAddress) == 0) {
std::cerr << "Failed to load GLES2" << std::endl;
}
glEnable(GL_BLEND);
glBlendEquationSeparate(GL_FUNC_ADD, GL_FUNC_ADD);
glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
// create view
m_view_size = get_size();
m_view_center = m_view_size / 2.0f;
// create shader
m_program = glCreateProgram();
GLuint vertex_shader_id = compile_shader(g_vertex_shader, GL_VERTEX_SHADER);
glAttachShader(m_program, vertex_shader_id);
glDeleteShader(vertex_shader_id); // the shader is still here because it is attached to the program
GLuint fragment_shader_id = compile_shader(g_fragment_shader, GL_FRAGMENT_SHADER);
glAttachShader(m_program, fragment_shader_id);
glDeleteShader(fragment_shader_id); // the shader is still here because it is attached to the program
glLinkProgram(m_program);
GLint link_status = GL_FALSE;
glGetProgramiv(m_program, GL_LINK_STATUS, &link_status);
if (link_status == GL_FALSE) {
GLint info_log_length;
glGetProgramiv(m_program, GL_INFO_LOG_LENGTH, &info_log_length);
assert(info_log_length > 0);
std::unique_ptr<char[]> info_log(new char[info_log_length]);
glGetProgramInfoLog(m_program, info_log_length, nullptr, info_log.get());
std::cerr << "Error while linking the program: " << info_log.get() << std::endl;
}
// initialize the screen
clear(color::black);
}
renderer::~renderer() {
// delete shader
if (m_program != 0) {
glDeleteProgram(m_program);
}
// delete context
if (m_context != nullptr) {
SDL_GL_DeleteContext(m_context);
}
}
vec2i renderer::get_size() {
vec2i size;
SDL_GL_GetDrawableSize(m_window, &size.x, &size.y);
return size;
}
vec2f renderer::get_coords_from_position(vec2i position) {
vec2f viewport_position = { 0.0f, 0.0f };
vec2f viewport_size = get_size();
vec2f normalized;
normalized.x = 2.0f * (position.x - viewport_position.x) / viewport_size.width - 1;
normalized.y = 1 - 2.0f * (position.y - viewport_position.y) / viewport_size.height;
mat3f inverse_transform = invert(get_view_matrix());
return affine_transform(inverse_transform, normalized);
}
void renderer::clear(color4f color) {
glClearColor(color.r, color.g, color.b, color.a);
glClear(GL_COLOR_BUFFER_BIT);
}
void renderer::fill_rectangle(vec2f coords, vec2f size, color4f color) {
vertex vertices[4];
vertices[0].position = { coords.x, coords.y };
vertices[1].position = { coords.x, coords.y + size.height };
vertices[2].position = { coords.x + size.width, coords.y };
vertices[3].position = { coords.x + size.width, coords.y + size.height };
vertices[0].color = vertices[1].color = vertices[2].color = vertices[3].color = color;
draw(&vertices[0], 4, GL_TRIANGLE_STRIP);
}
void renderer::draw_rectangle(vec2f coords, vec2f size, color4f color) {
vertex vertices[4];
vertices[0].position = { coords.x, coords.y };
vertices[1].position = { coords.x, coords.y + size.height };
vertices[2].position = { coords.x + size.width, coords.y + size.height };
vertices[3].position = { coords.x + size.width, coords.y };
vertices[0].color = vertices[1].color = vertices[2].color = vertices[3].color = color;
draw(&vertices[0], 4, GL_LINE_LOOP);
}
void renderer::fill_circle(vec2f center, float radius, color4f color) {
static constexpr int POINT_COUNT = 50;
static constexpr float PI = 3.14159265359f;
vertex vertices[POINT_COUNT + 2];
vertices[0].position = center;
vertices[0].color = color;
for (int i = 0; i < POINT_COUNT + 1; ++i) {
float angle = 2 * PI * i / POINT_COUNT;
vertices[i + 1].position = center + radius * vec2f(std::sin(angle), std::cos(angle));
vertices[i + 1].color = color;
}
draw(&vertices[0], POINT_COUNT + 2, GL_TRIANGLE_FAN);
}
void renderer::draw_circle(vec2f center, float radius, color4f color) {
static constexpr int POINT_COUNT = 50;
static constexpr float PI = 3.14159265359f;
vertex vertices[POINT_COUNT];
for (int i = 0; i < POINT_COUNT; ++i) {
float angle = 2 * PI * i / POINT_COUNT;
vertices[i].position = center + radius * vec2f(std::sin(angle), std::cos(angle));
vertices[i].color = color;
}
draw(&vertices[0], POINT_COUNT, GL_LINE_LOOP);
}
void renderer::display() {
SDL_GL_SwapWindow(m_window);
}
mat3f renderer::get_view_matrix() const {
mat3f scaling(
2.0f / m_view_size.x, 0.0f, 0.0f,
0.0f, - 2.0f / m_view_size.y, 0.0f,
0.0f, 0.0f, 1.0f
);
mat3f translation(
1.0f, 0.0f, - m_view_center.x,
0.0f, 1.0f, - m_view_center.y,
0.0f, 0.0f, 1.0f
);
return scaling * translation;
}
void renderer::draw(const vertex *vertices, std::size_t count, int primitive) {
// set viewport
vec2i size = get_size();
glViewport(0, 0, size.width, size.height);
// set transformation matrix
mat3f transform = get_view_matrix();
GLint loc = glGetUniformLocation(m_program, "u_transform");
if (loc == -1) {
std::cerr << "Uniform not found" << std::endl;
return;
}
glUniformMatrix3fv(loc, 1, GL_FALSE, &transform.data[0][0]);
// send data
glUseProgram(m_program);
GLint position_loc = glGetAttribLocation(m_program, "a_position");
if (loc == -1) {
std::cerr << "Attribute not found: a_position" << std::endl;
return;
}
GLint color_loc = glGetAttribLocation(m_program, "a_color");
if (loc == -1) {
std::cerr << "Attribute not found: a_color" << std::endl;
return;
}
glEnableVertexAttribArray(position_loc);
glEnableVertexAttribArray(color_loc);
const void *position_pointer = &vertices[0].position;
const void *color_pointer = &vertices[0].color;
glVertexAttribPointer(position_loc, 2, GL_FLOAT, GL_FALSE, sizeof(vertex), position_pointer);
glVertexAttribPointer(color_loc, 4, GL_FLOAT, GL_FALSE, sizeof(vertex), color_pointer);
glDrawArrays(primitive, 0, count);
glDisableVertexAttribArray(position_loc);
glDisableVertexAttribArray(color_loc);
}
}
| true |
faa3f76a4cf82d85069c4728a650c2d2560345de | C++ | GCarneiroA/blog-article-sources | /network-protocol-parsing/parser.cpp | UTF-8 | 1,446 | 2.90625 | 3 | [] | no_license | #include "parser.h"
#ifdef _WIN32
#include <WinSock2.h>
#else
#include <arpa/inet.h>
#endif
bool
Parser::parse(uint8_t* data, size_t len, size_t& bytesRead, Packet& packet)
{
bytesRead = 0;
for (size_t i = 0; i < len; ++i)
{
const auto b = data[i];
bytesRead++;
switch (_step)
{
// Header.
case 0:
if (b != 0xAF)
{
_step = 0;
continue;
}
packet.header = b;
_step++;
break;
// Flags.
case 1:
packet.flags = b;
_step++;
break;
// Type (2 bytes!).
case 2:
packet.type = uint16_t(b) << 8;
_step++;
break;
case 3:
packet.type |= uint16_t(b) << 0;
packet.type = ntohs(packet.type);
_step++;
break;
// Size (4 bytes!).
case 4:
packet.size = uint32_t(b) << 24;
_step++;
break;
case 5:
packet.size |= uint32_t(b) << 16;
_step++;
break;
case 6:
packet.size |= uint32_t(b) << 8;
_step++;
break;
case 7:
packet.size |= uint32_t(b) << 0;
packet.size = ntohl(packet.size);
_step++;
packet.data.clear();
if (packet.size > 0)
{
packet.data.reserve(packet.size);
}
else
{
_step++; // Skip data step.
}
break;
// Data.
case 8:
packet.data.push_back(b);
if (packet.data.size() == packet.size)
_step++;
break;
// Checksum.
case 9:
packet.checksum = b;
_step = 0;
return true;
}
}
return false;
} | true |
98a7f0436c284925a94a88fec2005a148c254a1f | C++ | ranjan103/Parallel-Graph-Colouring- | /Graph.h | UTF-8 | 1,211 | 3.4375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
class Graph {
public:
int nodeCount, edgeCount;
int maxDegree;
int *adjacencyList, *adjacencyListPointers;
public:
int getNodeCount() {
return nodeCount;
}
int getEdgeCount() {
return edgeCount;
}
int getMaxDegree() {
return maxDegree;
}
void readGraph() {
int u, v;
cin >> nodeCount >> edgeCount;
// Use vector of vectors temporarily to input graph
vector<int> *adj = new vector<int>[nodeCount];
for (int i = 0; i < edgeCount; i++) {
cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
}
// Copy into compressed adjacency List
adjacencyListPointers = new int[nodeCount +1];
adjacencyList = new int[2 * edgeCount +1];
int pos = 0;
for(int i=0; i<nodeCount; i++) {
adjacencyListPointers[i] = pos;
for(int node : adj[i])
adjacencyList[pos++] = node;
}
adjacencyListPointers[nodeCount] = pos;
// Calculate max degree
maxDegree = INT_MIN;
for(int i=0; i<nodeCount; i++)
maxDegree = max(maxDegree, (int)adj[i].size());
delete[] adj;
}
int *getAdjacencyList(int node) {
return adjacencyList;
}
int *getAdjacencyListPointers(int node) {
return adjacencyListPointers;
}
}; | true |
5121f80d299a7806879191d7c5ca32177c38ff91 | C++ | ThereGoesMySanity/led-tetris | /input_handler.h | UTF-8 | 1,482 | 2.71875 | 3 | [] | no_license | #include <curses.h>
#include <locale.h>
#include <linux/input.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <map>
#ifndef _INPUT_HANDLER_H
#define _INPUT_HANDLER_H
const int INPUTS[] = {KEY_LEFT, KEY_RIGHT, KEY_DOWN, KEY_UP, KEY_Z, KEY_X, KEY_C};
class InputHandler {
public:
InputHandler(){}
virtual int getKey() = 0;
virtual bool canGetKeyState() = 0;
virtual void update() = 0;
virtual void keyOff() = 0;
std::map<int, bool> keyState;
virtual void setMove(int* left, int* right) = 0;
};
class NCursesHandler : public InputHandler {
public:
NCursesHandler() ;
int getKey();
bool canGetKeyState(){return false;}
void update() {}
void keyOff() {}
};
class LinuxInputHandler : public InputHandler {
public:
LinuxInputHandler();
int getKey();
bool canGetKeyState() {return true;}
void update() {
getKey();
}
void setMove(int* l, int* r){
left = l;
right = r;
}
void keyOff();
private:
void move(bool l){
if(l && left){
(*left)++;
printf("%i\n", *left);
} else if(right){
(*right)++;
printf("%i\n", *right);
}
}
int file;
int* left = nullptr, *right = nullptr;
};
#endif
| true |
eb1fffcb92b9cf4bb90811fc8b7d40e7ce06808f | C++ | 0suddenly0/nullptr-recode | /nullptr-recode/helpers/config_sys/config_sys.h | UTF-8 | 11,656 | 2.78125 | 3 | [] | no_license | #pragma once
#include "../math/math.h"
#include "../../utils/utils.h"
#include "../input.h"
#include "../../settings/settings.h"
#include <string>
#include <vector>
namespace config {
enum class var_t {
_int = 0,
_float = 1,
_bool = 2,
_string = 3,
_color = 4,
_bind = 5,
_window = 6
};
enum class line_t {
group = 0,
var = 1
};
namespace config_utils {
std::string del_last_simbols(std::string* string, int num);
std::string del_first_simbols(std::string* string, int num);
std::string del_last_simbols(std::string string, int num);
std::string del_first_simbols(std::string string, int num);
void load_group(std::vector<std::string>& groups_list, std::string line);
std::string get_var_name(std::string line);
std::string get_var_value(std::string line);
line_t get_line_type(std::string line);
}
class c_var {
public:
template <typename T>
c_var(std::string _name, T* var, std::vector<std::string> last_groups) {
for (std::string group : last_groups) {
name += group;
}
name += _name;
if (std::is_same<T, int>::value) {
type = var_t::_int;
var_int = (int*)var;
} else if (std::is_same<T, float>::value) {
type = var_t::_float;
var_float = (float*)var;
} else if (std::is_same<T, bool>::value) {
type = var_t::_bool;
var_bool = (bool*)var;
} else if (std::is_same<T, std::string>::value) {
type = var_t::_string;
var_string = (std::string*)var;
} else if (std::is_same<T, color>::value) {
type = var_t::_color;
var_color = (color*)var;
} else if (std::is_same<T, key_bind_t>::value) {
type = var_t::_bind;
var_bind = (key_bind_t*)var;
} else if (std::is_same<T, window_settings_t>::value) {
type = var_t::_window;
var_window = (window_settings_t*)var;
}
}
static bool find_var(std::vector<c_var>* var_list, std::string line, std::string full_var_name) {
for (int i = 0; i < var_list->size(); i++) {
c_var& var = var_list->at(i);
std::string var_value = config_utils::get_var_value(line);
if (var.name == full_var_name) {
var.load(var_value);
var_list->erase(var_list->begin() + i);
return true;
}
}
return false;
}
void load(std::string var_value) {
switch (type) {
case var_t::_float: {
*var_float = std::stof(var_value);
} break;
case var_t::_int: {
*var_int = std::stoi(var_value);
} break;
case var_t::_bool: {
*var_bool = var_value == "true" ? true : false;
} break;
case var_t::_string: {
config_utils::del_last_simbols(&var_value, 1);
config_utils::del_first_simbols(&var_value, 1);
*var_string = var_value;
} break;
case var_t::_color: {
std::string red_string = config_utils::del_last_simbols(var_value, var_value.length() - var_value.find("-"));
std::string green_string = config_utils::del_first_simbols(var_value, red_string.length() + 1);
config_utils::del_last_simbols(&green_string, green_string.length() - green_string.find("-"));
std::string blue_string = config_utils::del_first_simbols(var_value, red_string.length() + green_string.length() + 2);
config_utils::del_last_simbols(&blue_string, blue_string.length() - blue_string.find("-"));
std::string alpha_string = config_utils::del_first_simbols(var_value, red_string.length() + green_string.length() + blue_string.length() + 3);
*var_color = color(std::stoi(red_string), std::stoi(green_string), std::stoi(blue_string), std::stoi(alpha_string));
} break;
case var_t::_bind: {
std::string key_string = config_utils::del_last_simbols(var_value, var_value.length() - var_value.find("-"));
std::string type_string = config_utils::del_first_simbols(var_value, key_string.length() + 1);
config_utils::del_last_simbols(&type_string, type_string.length() - type_string.find("-"));
std::string state_string = config_utils::del_first_simbols(var_value, key_string.length() + type_string.length() + 2);
*var_bind = key_bind_t{ std::stoi(key_string), std::stoi(type_string), state_string == "true" ? true : false };
} break;
case var_t::_window: {
std::string show_string = config_utils::del_last_simbols(var_value, var_value.length() - var_value.find("-"));
std::string pos_x_string = config_utils::del_first_simbols(var_value, show_string.length() + 1);
config_utils::del_last_simbols(&pos_x_string, pos_x_string.length() - pos_x_string.find("-"));
std::string pos_y_string = config_utils::del_first_simbols(var_value, show_string.length() + pos_x_string.length() + 2);
config_utils::del_last_simbols(&pos_y_string, pos_y_string.length() - pos_y_string.find("-"));
std::string alpha_string = config_utils::del_first_simbols(var_value, show_string.length() + pos_x_string.length() + pos_y_string.length() + 3);
null_gui::deep::set_window_pos(var_window->name.c_str(), vec2(std::stoi(pos_x_string), std::stoi(pos_y_string)), false);
*var_window = window_settings_t{ var_window->name, std::stoi(alpha_string), vec2(std::stoi(pos_x_string), std::stoi(pos_y_string)), show_string == "true" ? true : false };
} break;
}
}
std::string name;
var_t type;
// int
int* var_int;
// float
float* var_float;
// bool
bool* var_bool;
// string
std::string* var_string;
// color
color* var_color;
// bind
key_bind_t* var_bind;
//window
window_settings_t* var_window;
};
class c_config {
public:
c_config(std::string dir) {
dir_name = dir;
}
void clear() {
cur_group = 0;
config_text.clear();
vars.clear();
last_groups.clear();
}
void add_space() {
for (int i = 0; i < cur_group; i++) {
if (i == cur_group - 1) config_text += "|- ";
else config_text += "| ";
}
}
template<typename T>
void add_var(std::string name, T& var) {
c_var _var = c_var{ name, &var, last_groups };
vars.push_back(_var);
switch (vars.back().type) {
case var_t::_float:
config_text += utils::snprintf("%s = %.3f;\n", name.c_str(), *_var.var_float);
break;
case var_t::_int:
config_text += utils::snprintf("%s = %d;\n", name.c_str(), *_var.var_int);
break;
case var_t::_bool:
config_text += utils::snprintf("%s = %s;\n", name.c_str(), *_var.var_bool == true ? "true" : "false");
break;
case var_t::_string:
config_text += utils::snprintf("%s = '%s';\n", name.c_str(), _var.var_string->c_str());
break;
case var_t::_color:
config_text += utils::snprintf("%s = %d-%d-%d-%d;\n", name.c_str(), _var.var_color->r(), _var.var_color->g(), _var.var_color->b(), _var.var_color->a());
break;
case var_t::_bind:
config_text += utils::snprintf("%s = %d-%d-%s;\n", name.c_str(), _var.var_bind->key_id, _var.var_bind->bind_type, _var.var_bind->enable ? "true" : "false");
break;
case var_t::_window:
config_text += utils::snprintf("%s = %s-%.0f-%.0f-%d;\n", name.c_str(), _var.var_window->show ? "true" : "false", _var.var_window->pos.x, _var.var_window->pos.y, _var.var_window->alpha);
break;
}
}
void add_group(std::string name) {
config_text += utils::snprintf("[ %s ]\n", name.c_str());
last_groups.push_back(utils::snprintf("[ %s ] ", name.c_str()));
cur_group++;
}
void end_group() {
last_groups.pop_back();
cur_group--;
add_space();
config_text += "[ end ]\n";
}
bool load(std::string name) {
if (name.empty()) return false;
CreateDirectoryA((LPCSTR)utils::snprintf("C:\\nullptr\\%s\\", dir_name.c_str()).c_str(), NULL);
std::vector<c_var> local_vars = vars;
std::vector<std::string> last_groups;
std::string line;
std::ifstream in(utils::snprintf("C:\\nullptr\\%s\\%s.null", dir_name.c_str(), name.c_str()));
if (in.is_open()) {
while (getline(in, line)) {
if (config_utils::get_line_type(line) == line_t::group) {
config_utils::load_group(last_groups, line);
} else if(local_vars.size() > 0){
std::string becup = line;
std::string end_var_name;
for (std::string group : last_groups) {
end_var_name = utils::snprintf("%s%s ", end_var_name.c_str(), group.c_str());
}
end_var_name = utils::snprintf("%s%s", end_var_name.c_str(), config_utils::get_var_name(line).c_str());
std::string var_value = config_utils::get_var_value(line);
if (local_vars.front().name == end_var_name) {
c_var& var = local_vars.front();
var.load(var_value);
local_vars.erase(local_vars.begin());
} else {
c_var::find_var(&local_vars, line, end_var_name);
}
}
}
}
in.close();
return true;
}
std::string dir_name;
std::vector<std::string> last_groups;
std::string config_text;
std::vector<c_var> vars;
int cur_group = 0;
};
namespace standart {
c_config _config = c_config("standart");
void setup();
bool save(std::string name);
bool load(std::string name);
}
namespace skins {
c_config _config = c_config("skins");
void setup();
bool save(std::string name);
bool load(std::string name);
}
void push_config(c_config* cfg);
void add_group(std::string name);
void end_group();
void add_var(std::string name, int& var);
void add_var(std::string name, float& var);
void add_var(std::string name, bool& var);
void add_var(std::string name, std::string& var);
void add_var(std::string name, color& var);
void add_var(std::string name, key_bind_t& var);
void add_var(std::string name, window_settings_t& var);
} | true |
ef138c2cbb3fd98243602985f76f24c35dff6958 | C++ | faddeys-studies/oop_lab3 | /src/app/db.hpp | UTF-8 | 2,261 | 3.3125 | 3 | [] | no_license | #ifndef LAB3_DB_HPP
#define LAB3_DB_HPP
#include <ios>
#include <json.hpp>
#include "model/Employee.hpp"
using json = nlohmann::json;
namespace CM { namespace DB {
inline void _hierarchy_to_json(const Employee::Ptr& empl, json& store) {
store["first_name"] = *empl->get_first_name();
store["last_name"] = *empl->get_last_name();
store["position"] = *empl->get_position();
store["salary"] = *empl->get_salary();
store["subordinates"] = json::array();
for(auto& sub: empl->get_subordinates()) {
json sub_store;
_hierarchy_to_json(sub, sub_store);
store["subordinates"] += sub_store;
}
}
inline Employee::Ptr _load_with_subordinates(const Employee::Ptr& supervisor, json& store) {
auto empl = Employee::New(
mk_string(store["first_name"].get<std::string>()),
mk_string(store["last_name"].get<std::string>())
);
empl->employ(
supervisor,
mk_string(store["position"].get<std::string>()),
mk_int(store["salary"].get<int>())
);
for(auto &sub_store: store["subordinates"]) {
_load_with_subordinates(empl, sub_store);
}
return empl;
}
inline void save(const Company::Ptr& company, json& store) {
store["company_name"] = *company->get_name();
_hierarchy_to_json(company->get_director(), store["hierarchy"]);
}
inline void save(const Company::Ptr& company, std::ostream& stream) {
json data;
save(company, data);
stream << data;
}
inline Company::Ptr load(std::istream &stream) {
json data = json::parse(stream);
auto ceo = Employee::New(
mk_string(data["hierarchy"]["first_name"].get<std::string>()),
mk_string(data["hierarchy"]["last_name"].get<std::string>())
);
auto company = ceo->create_company(mk_string(data["company_name"].get<std::string>()));
ceo->set_salary(mk_int(data["hierarchy"]["salary"].get<int>()));
for(auto &sub_store: data["hierarchy"]["subordinates"]) {
_load_with_subordinates(ceo, sub_store);
}
return company;
}
}}
#endif //LAB3_DB_HPP
| true |
07962e1979682f43d47ba756cca2c80bfa7f1314 | C++ | panluDreamer/PAT-A | /A1064.cpp | GB18030 | 2,250 | 3.0625 | 3 | [] | no_license | #include<iostream>
#include<algorithm>
#include<cmath>
#include<queue>
using namespace std;
struct node {
int id;
int data;
int left;
int right;
};
const int maxn = 1020;
node buf[maxn];
int d[maxn];
int n;
int t = 0;
int full_layer = 0, max_layer = 0;
int node_count = 0;
bool cmp(int a,int b) {
return a < b;
}
void get_layer(int n) {
int pre = -1, now = 0;
for (int i = 0; i < 20;i++) {
int cur = pow(2.0, i + 1) - 1;
int next = pow(2.0, i + 2) - 1;
if (n == cur) {//պÿһ
pre = now = i;
break;
}
else if (n > cur&&n < next) {//һû
pre = i;
now = i + 1;
break;
}
}
full_layer = pre;
max_layer = now;
}
void bfs(int u) {
queue<int> q;
q.push(u);
while (!q.empty()) {
int front = q.front();
q.pop();
node_count++;
cout << buf[front].data;
if (node_count != n) {
cout << " ";
}
if (buf[front].left != -1) {
q.push(buf[front].left);
}
if (buf[front].right != -1) {
q.push(buf[front].right);
}
}
}
void inorder(int u) {
if (u == -1) {
return;
}
inorder(buf[u].left);
buf[u].data = d[t++];
inorder(buf[u].right);
}
int main() {
cin >> n;
for (int i = 0; i < n;i++) {
cin >> d[i];
}
for (int i = 0; i < n;i++) {
buf[i].data = -1;
buf[i].id = i;
buf[i].left = -1;
buf[i].right = -1;
}
get_layer(n);
//cout << "full_layer = " << full_layer << " max_layer = " << max_layer << endl;
//create structure
if (full_layer != max_layer) {
int c1 = pow(2.0, full_layer + 1) - 1 - pow(2.0, full_layer);
int c2 = pow(2.0, full_layer);
int index = 1;
for (int i = 0; i < c1; i++) {
buf[i].left = index++;
buf[i].right = index++;
}
for (int i = c1; i < c1 + c2; i++) {
buf[i].left = index++;
if (index == n) {
break;
}
buf[i].right = index++;
if (index == n) {
break;
}
}
sort(d, d + n, cmp);
inorder(0);
bfs(0);
//cout << "node_count = " << node_count << endl;
}
else {
//cout << "complete" << endl;
int index = 1;
int c1 = pow(2.0, full_layer + 1) - 1 - pow(2.0, full_layer);
for (int i = 0; i < c1; i++) {
buf[i].left = index++;
buf[i].right = index++;
}
sort(d, d + n, cmp);
inorder(0);
bfs(0);
//cout << "node_count = " << node_count << endl;
}
} | true |
c37c8a0466f18f37ab6acae3b763d99af4f17355 | C++ | JacobMedeiros/UtPod_Final2 | /prog05_jrm7276/UtPod.cpp | UTF-8 | 4,615 | 3.265625 | 3 | [] | no_license | //Jacob Medeiros & Reed Hopkins
#include "UtPod.h"
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
UtPod::UtPod(){
songs = NULL;
memSize = MAX_MEMORY;
}
UtPod::UtPod(int size){
songs = NULL;
memSize = size;
}
int UtPod::addSong(Song const &s){
if(s.getSize() <= getRemainingMemory()) { //if the size will allow
SongNode *newSong = new SongNode; // create new song node
newSong->song.setArtist(s.getArtist());
newSong->song.setTitle(s.getTitle());
newSong->song.setSize(s.getSize());
newSong->next = songs;
songs = newSong;
return(SUCCESS);
}
else{
return(NO_MEMORY);
}
}
int UtPod::removeSong(Song const &s){
SongNode *travel, *previous;
previous = NULL;
travel = songs;
while(travel != NULL){
if(travel->song == s){
if(previous == NULL){ // if the first element is the song to be removed
songs = travel->next; // head pointer points to next;
return(SUCCESS);
}
previous->next = travel->next;
delete(travel);// removes the song from actual memory
return(SUCCESS);
}
previous = travel;
travel = travel->next;
}
return(NOT_FOUND);
}
void UtPod::shuffle() {
if(songs == NULL){
return;
}
SongNode *travel, *current;
Song sSwap;
int sizeList = 0;
int randomNum = 0;
unsigned int ourTime;
travel = songs;
while(travel != NULL){ //traverses list to find size of it
sizeList++;
travel = travel->next;
}
ourTime = (unsigned)time(0); //grabs calendar time
srand(ourTime);
if(sizeList >= 2){
for(int i = 0; i < 100; i++){
sSwap.setArtist(songs->song.getArtist());
sSwap.setTitle(songs->song.getTitle());
sSwap.setSize(songs->song.getSize());
travel = songs;
randomNum = (rand() % sizeList);
travel = travel->next;
if(randomNum !=0) {
for (int index = 0; index < (randomNum-1); index++) {
travel = travel->next;
}
}
songs->song.setArtist(travel->song.getArtist());
songs->song.setTitle(travel->song.getTitle());
songs->song.setSize(travel->song.getSize());
travel->song.setArtist(sSwap.getArtist());
travel->song.setTitle(sSwap.getTitle());
travel->song.setSize(sSwap.getSize());
}
}
}
void UtPod::showSongList() {
SongNode *travel;
travel = songs;
while(travel != NULL){
cout << travel->song.getTitle() << ", " << travel->song.getArtist() << ", " << travel->song.getSize() << endl;
travel = travel->next;
}
}
void UtPod::sortSongList() {
if(songs == NULL){
return;
}
if(songs->next == NULL){
return;
}
SongNode *travel1 = songs;
SongNode *travel2 = songs;
SongNode *temp;
SongNode *prev = songs;
int counter = 0;
while(travel1 != NULL){
counter++;
travel1 = travel1->next;
}
for(int i = 0; i<counter; i++){
while(travel2->next != NULL){
if(travel2->song > travel2->next->song){
if(prev == travel2){
temp = travel2->next;
travel2->next = temp->next;
temp->next = travel2;
songs = temp;
}
else {
while (prev->next != travel2) {
prev = prev->next;
}
temp = travel2->next;
travel2->next = temp->next;
temp->next = travel2;
prev->next = temp;
}
prev = songs;
}
else{
travel2 = travel2->next;
}
}
travel2 = songs;
}
}
void UtPod::clearMemory() {
SongNode *temp;
while(songs != NULL){
temp = songs->next;
delete(songs);
songs = temp;
}
}
int UtPod::getRemainingMemory() {
SongNode *travel;
travel = songs;
int usedMem = 0;
while(travel != NULL){
usedMem += travel->song.getSize();
travel = travel->next;
}
return(memSize - usedMem);
}
UtPod::~UtPod() {
clearMemory();
}
| true |
006b11b819c7a51bbc1b73e0b80b347105ce25fa | C++ | vlad4400/diff_code | /fan_c/II lab [2017]/c_win_lab_6.cpp | UTF-8 | 452 | 2.703125 | 3 | [] | no_license | #include <iostream>
#include <ctime>
#include <Windows.h>
using namespace std;
int main()
{
srand(time(NULL));
int n = 0;
n = 5;
int **a = new int*[n];
for (int i = 0; i < n; i++)
{
a[i] = new int[n];
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
a[i][j] = rand() % 10;
cout << a[i][j] << " ";
}
cout << endl;
}
for (int i = 0; i < n; i++)
{
delete[]a[i];
}
delete[] a;
Sleep(1500);
return 0;
} | true |
31700ee6f94bbe2718dcceddfec1e450571616a1 | C++ | wolves3d/idea | /_Shared/Math/vec4.h | UTF-8 | 1,413 | 2.765625 | 3 | [] | no_license | ////////////////////////////////////////////////////////////////////////////////
#ifndef __vec4_h_included__
#define __vec4_h_included__
////////////////////////////////////////////////////////////////////////////////
class vec4
{
public :
inline vec4()
{
}
inline vec4( float _x, float _y, float _z, float _w ) :
x( _x ),
y( _y ),
z( _z ),
w( _w )
{
}
inline void Set( float _x, float _y, float _z, float _w )
{
x = _x;
y = _y;
z = _z;
w = _w;
}
inline void Set(const vec3 & direction, float _w)
{
x = direction.x;
y = direction.y;
z = direction.z;
w = _w;
}
inline void vec4::Multiply( const mat4 & mTrans );
union
{
struct { scalar x, y, z, w; };
struct { scalar r, g, b, a; };
struct { scalar pos_x, pos_y, width, height; };
scalar pArray[ 4 ];
};
static vec4 vNull;
};
class ivec4
{
public :
inline ivec4()
{
}
inline ivec4( int _x, int _y, int _z, int _w ) :
x( _x ),
y( _y ),
z( _z ),
w( _w )
{
}
union
{
struct { int x, y, z, w; };
struct { int pos_x, pos_y, width, height; };
int pArray[ 4 ];
};
};
////////////////////////////////////////////////////////////////////////////////
#endif // #ifndef __vec4_h_included__
//////////////////////////////////////////////////////////////////////////////// | true |
dbbf2566868b723a4d8e9788b9dfa8261302d7ce | C++ | moecia/GAME-230-PONG | /Ball.h | UTF-8 | 713 | 2.515625 | 3 | [] | no_license | #pragma once
#include <SFML/Audio.hpp>
#include "Paddle.h"
#include "Score.h"
using namespace sf;
using namespace std;
class Ball : public Entity
{
public:
Vector2f ballAngle;
float ballVelocity;
virtual void Update(sf::RenderWindow* window);
Ball(Score* score1, Score* score2, Paddle* player1, Paddle* player2, Paddle* obstacle, int ballIndex); // Ball index: 0 for Original ball, 1 for Generated ball
void Reset(RenderWindow* window);
void AddBall2(RenderWindow* window, int direction);
~Ball();
private:
Score* score1;
Score* score2;
Paddle* player1;
Paddle* player2;
Paddle* obstacle;
SoundBuffer* bufferWall;
SoundBuffer* bufferPaddle;
Sound* soundWall;
Sound* soundPaddle;
int ballIndex;
}; | true |
e6faa4696fd870e4f97b4d36d87893bbd75ef3c0 | C++ | hG3n/glwarp-configurator-qt | /src/model/projector_frustum.hpp | UTF-8 | 2,235 | 2.9375 | 3 | [] | no_license | //
// Created by everest on 14.03.18.
//
#ifndef RAYCAST_PROJECTOR_FRUSTUM_H
#define RAYCAST_PROJECTOR_FRUSTUM_H
#include <iostream>
#include <string>
#include <map>
#include <QVector3D>
/**
* @brief The ProjectorFrustum class describes a light projector frustum
*/
class ProjectorFrustum {
public:
enum ClippingPlane {
NEAR, FAR
};
enum Corner {
TL, TR, BL, BR
};
/**
* @brief ProjectorFrustum
*/
ProjectorFrustum();
/**
* @brief Creates a new frustum with the given values.
* @param _aspect_ratio
* @param _fov
* @param _near
* @param _far
*/
ProjectorFrustum(float _aspect_ratio, float _fov, float _near, float _far);
/**
* @brief Translate to current position.
* @param position
*/
void translate(QVector3D const &position);
/**
* @brief Rotate by given degree angle around specified axis.
* @param angle
* @param axis
*/
void rotate(float angle, QVector3D const &axis);
/**
* @brief Set the frustum field of view.
* @param fov
*/
void setFOV(float fov);
/**
* @brief Returns near clipping plane corners.
* @return
*/
std::map<Corner, QVector3D> const& getNearCorners() const;
/**
* @brief Returns far clipping plane corners.
* @return
*/
std::map<Corner, QVector3D> const& getFarCorners() const;
/**
* @brief Returns frustum eye ray.
* @return
*/
QVector3D const& getEye() const;
/**
* @brief Returns the position.
* @return
*/
QVector3D const& getPosition() const;
private:
void initialize();
private:
float _aspect_ratio;
float _fov;
float _near;
float _far;
QVector3D _eye;
QVector3D _position;
QVector3D _rotation;
std::map<Corner, QVector3D> _near_corners;
std::map<Corner, QVector3D> _far_corners;
};
#endif //RAYCAST_PROJECTOR_FRUSTUM_H
| true |
e7e18dfe034765d7a733585e30f7ed835105b9dc | C++ | yupeihua/algorithm | /glqw/b/a.cc | UTF-8 | 578 | 2.5625 | 3 | [] | no_license | #include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
int main() {
int t;
scanf("%d", &t);
int a[110];
double dp[110];
int CASE = 1;
while (t--) {
int n;
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d", a + i);
}
dp[n] = a[n];
for (int i = n - 1; i > 0; i--) {
double div = min(6, n - i);
double sum = 0;
for (int j = 1; j <= div; j++) {
sum += dp[i + j];
}
dp[i] = sum / div + a[i];
sum += dp[i];
}
printf("Case %d: %lf\n", CASE++, dp[1]);
}
return 0;
}
| true |
74ef16722bd1a334f9d6609d92c902ffac4e46d7 | C++ | zhu-he/ACM-Source | /cf/291/A.cpp | UTF-8 | 285 | 3.03125 | 3 | [] | no_license | #include <cstdio>
int main()
{
char s[20];
scanf("%s", s);
for (int i = 0; s[i] != '\0'; ++i)
{
if (s[i] == '9' && i == 0)
{
putchar(s[i]);
}
else if (s[i] >= '5')
{
putchar(9 - s[i] + '0' * 2);
}
else
{
putchar(s[i]);
}
}
putchar('\n');
return 0;
}
| true |
d61277d084fc6f01bb319edfc9b858bcfd45e934 | C++ | BrandonMitchell1920/CSCI232 | /lab02-boxes/ToyBox/ToyBox.cpp | UTF-8 | 1,120 | 3.28125 | 3 | [] | no_license | /** ToyBox Implementation - Has a color and holds a single item that can be changed
* Implemented with Templates
*
* CSCI 232 Data Structures and Algorithms
*
* Phillip J. Curtiss, Associate Professor
* pcurtiss@mtech.edu, 406-496-4807
* Department of Computer Science, Montana Tech
*/
#ifndef TOY_BOX_IMP
#define TOY_BOX_IMP
#include "ToyBox.h"
// Default contructor - uses initializer to set Box color to Black
template<class ItemType>
ToyBox<ItemType>::ToyBox() : boxColor(BLACK)
{
} // end default constructor
// Constructor setting initial Box Color using initializer
template<class ItemType>
ToyBox<ItemType>::ToyBox(const Color& theColor) : boxColor(theColor)
{
} // end constructor
// Constructor setting initial Box Color and Item using initializers
template<class ItemType>
ToyBox<ItemType>::ToyBox(const ItemType& theItem, const Color& theColor)
:PlainBox<ItemType>(theItem), boxColor(theColor) // Initialize item data fields
{
} // end constructor
// Method returns the current color fo the Box
template<class ItemType>
Color ToyBox<ItemType>::getColor() const
{
return boxColor;
} // end getColor
#endif | true |
87386af95541023bb9d82d3243d617c76b5cb865 | C++ | sanketgautam/Hackerrank_Submissions | /submissions/Attending Workshops.cpp | UTF-8 | 1,307 | 3.421875 | 3 | [] | no_license | /*-----------------------------------------------------------------------
Problem Title: Attending Workshops
Problem Link: https://www.hackerrank.com/challenges/attending-workshops
Author: sanketgautam
Language : C++
-----------------------------------------------------------------------*/
//Define the structs Workshop and Available_Workshops.
//Implement the functions initialize and CalculateMaxWorkshops
struct Workshop {
int start, duration, end;
};
struct Available_Workshops {
int n;
Workshop w[100000];
};
Available_Workshops* initialize(int start_time[], int duration[], int& n)
{
Available_Workshops* ws = new Available_Workshops;
ws->n = n;
for (int i = 0; i < n; i++) {
ws->w[i].start = start_time[i];
ws->w[i].duration = duration[i];
ws->w[i].end = start_time[i] + duration[i];
}
return ws;
}
bool comparator(Workshop& a, Workshop& b)
{
return a.end < b.end;
}
int CalculateMaxWorkshops(Available_Workshops* ptr)
{
int n = ptr->n, max_workshops = 1;
sort(ptr->w, (ptr->w) + n, comparator);
Workshop* prev = &(ptr->w[0]);
for (int i = 1; i < n; i++) {
if (prev->end <= (ptr->w[i]).start) {
prev = &(ptr->w[i]);
max_workshops++;
}
}
return max_workshops;
} | true |
de470103b19eb0fabb8c5de78c46ce8f8a240aef | C++ | jendralhxr/blinkie-reconst | /blinkthreadfile.cpp | UTF-8 | 4,010 | 2.5625 | 3 | [] | no_license | #include "blinkthreadfile.h"
#include <QFileDialog>
#define FPS_SOURCE 10000
#define FPS_VIEW 30
char lum_max, lum_min, lum_current;
char parity;
blinkThreadFile::blinkThreadFile(QThread *parent) : QThread(parent)
{
}
blinkThreadFile::~blinkThreadFile()
{
}
void blinkThreadFile::updatePath(QString setpath){
path = setpath;
qDebug("path set to %s",path.toStdString().c_str());
}
void blinkThreadFile::startReading(){
start(QThread::HighPriority);
}
void blinkThreadFile::setSequenceNumber(int num){
framecount = num;
qDebug("framecount set to %d",framecount);
}
void blinkThreadFile::setThreshold(int thres){
threshold= thres;
qDebug("threshold set to %d",threshold);
}
void blinkThreadFile::run(){
value_current= 0;
value_prev= 0;
value_temp= 0;
index_char= 0;
char state= 0; // 0= waiting for data; 1=just read data, waiting for 0
for (int framenum=0; framenum<framecount; framenum++){
filename.sprintf("%s%04d.jpg",path.toStdString().c_str(),framenum);
image.release();
tmp.release();
image = cv::imread(filename.toStdString());
if(!image.data) qDebug ("%d not found",framenum);
else {
// some image parsing here on intersections!!!
// qDebug("%d open %s",framenum,filename.toStdString().c_str());
// work on grayscale instead of BGR
cvtColor(image, tmp, CV_BGR2GRAY);
//qDebug("%d;%d;%d;%d;%d;%d;%d;%d",\
// tmp.data[axisY*image.cols + axisX[0]], tmp.data[axisY*image.cols + axisX[1]],\
// tmp.data[axisY*image.cols + axisX[2]], tmp.data[axisY*image.cols + axisX[3]],\
// tmp.data[axisY*image.cols + axisX[4]], tmp.data[axisY*image.cols + axisX[5]],\
// tmp.data[axisY*image.cols + axisX[6]], tmp.data[axisY*image.cols + axisX[7]]\
// );
// read current frame's character value
value_temp= 0;
lum_max= 0;
lum_min= 255;
parity= 0;
for (char n=0; n<8; n++){
lum_current = tmp.data[(axisY*image.cols + axisX[n])];
if (lum_current > lum_max) lum_max= lum_current;
if (lum_current < lum_min) lum_min= lum_current;
if ( lum_current> threshold){
if (n<7) value_temp |= (1<<n); //7-bit only ascii
parity++;
}
}
qDebug("%d;%x;%d;%d;%d;%d",framenum,value_temp,lum_min,lum_max,lum_max-lum_min,parity&1);
// temporal character being read
// if (parity&1) qDebug("%d;%c %x: %d %d %d",framenum,value_temp,value_temp,lum_min,lum_max,lum_max-lum_min);
// else qDebug("%d reads %c %x: %d %d %d",framenum,value_temp,value_temp,lum_min,lum_max,lum_max-lum_min);
// render more recent frame
// 10k fps (source) / 30 fps (viewing) = 304 fps (factor)
if (!(framenum%30)){
switch (image.type()) {
case CV_8UC1:
cv::cvtColor(image, tmp, CV_GRAY2RGB);
break;
case CV_8UC3:
cv::cvtColor(image, tmp, CV_BGR2RGB);
break;
}
assert(tmp.isContinuous());
fresh = QImage(tmp.data, tmp.cols, tmp.rows, tmp.cols*3, QImage::Format_RGB888);
emit newFrame(fresh);
}
}
}
}
void blinkThreadFile::setAxisY0(int y){
axisY= y;
}
void blinkThreadFile::setAxisX0(int x){
axisX[0]= x;
}
void blinkThreadFile::setAxisX1(int x){
axisX[1]= x;
}
void blinkThreadFile::setAxisX2(int x){
axisX[2]= x;
}
void blinkThreadFile::setAxisX3(int x){
axisX[3]= x;
}
void blinkThreadFile::setAxisX4(int x){
axisX[4]= x;
}
void blinkThreadFile::setAxisX5(int x){
axisX[5]= x;
}
void blinkThreadFile::setAxisX6(int x){
axisX[6]= x;
}
void blinkThreadFile::setAxisX7(int x){
axisX[7]= x;
}
| true |
f6255938b7e2ca3d2b558a9056e8eddbd587fef9 | C++ | oulrich1/windmill_farm | /plane.cpp | UTF-8 | 3,688 | 2.953125 | 3 | [] | no_license |
#include "plane.h"
Plane::Plane(Camera* _cam){
max_throttle = THROTTLE_MAX;
cur_throttle = 0;
min_throttle = 0;
thetas = vec4(0,0,0,0);
direction = vec4(0,0,0,0);
cam = _cam;
delegated_camera_control = (cam ? true: false);
current_control_state = 0; // the state mask that is used to control the orientation of the camera..
cam_frozen = false;
plane_frozen = false;
drag_factor = 0.034123; // random
ROTATE_FACTOR = 0.03f;
}
Plane::~Plane(){
}
/* simulates the flying.. */
bool Plane::fly(){
if(current_control_state & YAW_LEFT) {
controlStick(vec4(0,-ROTATE_FACTOR,0,0));
}
if(current_control_state & YAW_RIGHT) {
controlStick(vec4(0,ROTATE_FACTOR,0,0));
}
if(current_control_state & ROLL_LEFT) {
controlStick(vec4(0,0,-ROTATE_FACTOR, 0));
}
if(current_control_state & ROLL_RIGHT) {
controlStick(vec4(0,0,ROTATE_FACTOR, 0));
}
if(current_control_state & PITCH_DOWN) {
controlStick(vec4(-ROTATE_FACTOR,0,0, 0));
}
if(current_control_state & PITCH_UP) {
controlStick(vec4(ROTATE_FACTOR,0,0, 0));
}
if (plane_frozen == false) {
if (delegated_camera_control){
cam->walk(vec4(0,0,-((float)cur_throttle/max_throttle) * MAX_SPEED, 0) + this->direction );
cam->adjust(thetas);
}
this->thetas -= this->thetas * drag_factor; // drag the change in angle..
this->direction -= this->direction * drag_factor;
return true;
}
return false;
}
bool Plane::resetOrientation(vec4 up){
thetas = vec4(0,0,0,0);
cam->set_up(up);
return true;
}
bool Plane::pause(){
if (plane_frozen == false) {
plane_frozen = true;
return false;
}
return true;
}
bool Plane::unpause(){
if (plane_frozen == true) {
plane_frozen = false;
return false;
}
return true;
}
string Plane::throttleMessage(){
return "Throttle: " + toString((float)cur_throttle/max_throttle);
}
bool Plane::increaseThrottle(){
if (cur_throttle < max_throttle) {
cur_throttle += INCR_THROTTLE_FACTOR;
if (cur_throttle > max_throttle){
cur_throttle = max_throttle;
}
return true;
}
return false;
}
bool Plane::decreaseThrottle(){
if (cur_throttle > min_throttle){
cur_throttle -= INCR_THROTTLE_FACTOR;
if (cur_throttle < min_throttle){
cur_throttle = min_throttle;
}
return true;
}
return false;
}
float Plane::getThrottle(){
return cur_throttle;
}
bool Plane::setThrottle(float throttle){
if (throttle < min_throttle){
cur_throttle = min_throttle;
} else if (throttle > max_throttle){
cur_throttle = max_throttle;
} else{
cur_throttle = throttle;
return true;
}
return false;
}
void Plane::setControlState(int state){
current_control_state |= state; // set the state
}
void Plane::unsetControlState(int state){
current_control_state &= (~state); // clear the state
}
/* STRAFE: FORWARD(w), BACKWARDS(s),
LEFT(a), RIGHT(d),
UP(x), DOWN(z), */
bool Plane::controlDirection(vec4 dir){
direction = dir;
if(delegated_camera_control){
// cam->walk(this->direction);
}
return true;
}
/* ROLL, PITCH, YAW */
bool Plane::controlStick(vec4 angle_dir){
thetas += angle_dir;
return true;
}
bool Plane::collided(){
if (cam->eye.y < -13){
resetOrientation();
cam->eye.y = -5;
return true;
}
return false;
} | true |
5dfe376581ef89b9502903c3bbf52516107c09f2 | C++ | JoshuaJacoboBandera1AV6/Guia-del-examen-Primer-Parcial | /Ejercicio 23a.cpp | UTF-8 | 285 | 2.59375 | 3 | [] | no_license | #include<stdlib.h>
#include<stdio.h>
#include<conio.h>
int main (void){
int i=2,n=1,s=0;
printf("Suma de cada tercer numero cuando i=2.\n");
while(n<100){
printf("%d+%d=",s,i);
s=s+i;
i+=3;
printf("%d\n",s);
n++;
}
printf("El resultado de la suma es:%d\n",s);
}
| true |
d488431434aa2c93af287b2add362b7238c87b02 | C++ | calmackenzie/VG1819 | /ability/status/statusLV/Status_LV.h | UTF-8 | 3,107 | 2.5625 | 3 | [] | no_license | #pragma once
#include "ability/status/statusEvent/TimePointEvent.h"
#include "ability/status/Status.h"
namespace ability
{
class Status_LV : public Status
{
//this class handle the attribute change for all lv up status
public:
Status_LV();
virtual Status* clone() const { return new Status_LV(*this); };
virtual int effect() override;
virtual int effect(const TimePointEvent::TPEventType& p_type, ability::TimePointEvent* p_event);
protected:
void setLvUpAttributes(const std::string& p_attribute, const std::string& p_baseAttribute);
};
class Status_Priest_LV3 : public Status_LV
{
//this is trigger when preiest is lv3
private:
bool m_activate = false;
public:
Status_Priest_LV3();
Status* clone() const { return new Status_Priest_LV3(*this); };
int effect(const TimePointEvent::TPEventType& p_type, ability::TimePointEvent* p_event);
};
class Status_Archer_LV3 : public Status_LV
{
//this is trigger when Archer is lv3
public:
Status_Archer_LV3();
Status* clone() const { return new Status_Archer_LV3(*this); };
int effect(const TimePointEvent::TPEventType& p_type, ability::TimePointEvent* p_event);
};
class Status_Duelist_LV3 : public Status_LV
{
//this is trigger when Duelist is lv3
public:
Status_Duelist_LV3();
Status* clone() const { return new Status_Duelist_LV3(*this); };
int effect(const TimePointEvent::TPEventType& p_type, ability::TimePointEvent* p_event);
};
class Status_Eternal_Eye_LV3 : public Status_LV
{
//this is trigger when Eternal Eye is lv3
public:
Status_Eternal_Eye_LV3();
Status* clone() const { return new Status_Eternal_Eye_LV3(*this); };
int effect(const TimePointEvent::TPEventType& p_type, ability::TimePointEvent* p_event);
};
class Status_Lancer_LV2 : public Status_LV
{
//this is trigger when Lancer is lv2
public:
Status_Lancer_LV2();
Status* clone() const { return new Status_Lancer_LV2(*this); };
int effect(const TimePointEvent::TPEventType& p_type, ability::TimePointEvent* p_event);
private:
bool m_active = false;
void generateArmor();
};
class Status_Wraith_LV2 : public Status_LV
{
public:
Status_Wraith_LV2();
Status* clone() const { return new Status_Wraith_LV2(*this); };
int effect(const TimePointEvent::TPEventType& p_type, ability::TimePointEvent* p_event);
};
class Status_Evil_Fiend_LV : public Status_LV
{
public:
Status_Evil_Fiend_LV();
Status* clone() const { return new Status_Evil_Fiend_LV(*this); };
int effect(const TimePointEvent::TPEventType& p_type, ability::TimePointEvent* p_event);
};
class Status_Gorefiend_LV3 : public Status_LV
{
public:
Status_Gorefiend_LV3();
Status* clone() const { return new Status_Gorefiend_LV3(*this); };
int effect(const TimePointEvent::TPEventType& p_type, ability::TimePointEvent* p_event);
};
class Status_Slime_LV3 : public Status_LV
{
//this is trigger when Archer is lv3
public:
Status_Slime_LV3();
Status* clone() const { return new Status_Slime_LV3(*this); };
int effect(const TimePointEvent::TPEventType& p_type, ability::TimePointEvent* p_event);
};
} | true |
0ce7fc0d04ff4320383296cd6a525a38592deb66 | C++ | zhuli19901106/hdoj | /HDU1263(AC).cpp | UTF-8 | 758 | 2.8125 | 3 | [] | no_license | #define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
int t, ti;
int n;
int i;
map<string, map<string, int> > mm;
string ff, pp;
int num;
while(cin >> t){
for(ti = 0; ti < t; ++ti){
if(ti > 0){
cout << endl;
}
mm.clear();
cin >> n;
for (i = 0; i != n; ++i){
cin >> ff >> pp >> num;
mm[pp][ff] += num;
}
for(map<string, map<string, int> >::iterator mit1 = mm.begin(); mit1 != mm.end(); ++mit1){
cout << mit1->first << endl;
for(map<string, int>::iterator mit2 = mit1->second.begin(); mit2 != mit1->second.end(); ++mit2){
cout << " |----" << mit2->first << "(" << mit2->second << ")" << endl;
}
}
}
}
return 0;
}
| true |
e7736ce2e0765e1c93e96cff2b42edd833bedb1b | C++ | haying/madlib | /src/modules/sample/weighted_sample.cpp | UTF-8 | 3,302 | 2.625 | 3 | [] | no_license | /* ----------------------------------------------------------------------- *//**
*
* @file weighted_sample.cpp
*
* @brief Generate a single weighted random sample
*
*//* ----------------------------------------------------------------------- */
#include <dbconnector/dbconnector.hpp>
#include <modules/shared/HandleTraits.hpp>
#include <boost/tr1/random.hpp>
#include "weighted_sample.hpp"
// Import TR1 names (currently used from boost). This can go away once we make
// the switch to C++11.
namespace std {
using tr1::bernoulli_distribution;
}
namespace madlib {
namespace modules {
namespace sample {
/**
* @brief Transition state for weighted sample
*
* Note: We assume that the DOUBLE PRECISION array is initialized by the
* database with length 2, and all elemenets are 0.
*/
template <class Handle>
class WeightedSampleTransitionState {
public:
WeightedSampleTransitionState(const AnyType &inArray)
: mStorage(inArray.getAs<Handle>()),
sample_id(&mStorage[1]),
weight_sum(&mStorage[0]) { }
inline operator AnyType() const {
return mStorage;
}
private:
Handle mStorage;
public:
typename HandleTraits<Handle>::ReferenceToInt64 sample_id;
typename HandleTraits<Handle>::ReferenceToDouble weight_sum;
};
/**
* @brief Perform the weighted-sample transition step
*/
AnyType
weighted_sample_transition::run(AnyType& args) {
WeightedSampleTransitionState<MutableArrayHandle<double> > state = args[0];
uint64_t identifier = args[1].getAs<int64_t>();
double weight = args[2].getAs<double>();
// Instead of throwing an error, we will just ignore rows with a negative
// weight
if (weight > 0.) {
state.weight_sum += weight;
std::bernoulli_distribution success(weight / state.weight_sum);
// Note that a NativeRandomNumberGenerator object is stateless, so it
// is not a problem to instantiate an object for each RN generation...
NativeRandomNumberGenerator generator;
if (success(generator))
state.sample_id = identifier;
}
return state;
}
/**
* @brief Perform the merging of two transition states
*/
AnyType
weighted_sample_merge::run(AnyType &args) {
WeightedSampleTransitionState<MutableArrayHandle<double> > stateLeft
= args[0];
WeightedSampleTransitionState<ArrayHandle<double> > stateRight = args[1];
// FIXME: Once we have more modular states (independent of transition/merge
// function), implement using the logic from the transition function
stateLeft.weight_sum += stateRight.weight_sum;
std::bernoulli_distribution success(
stateRight.weight_sum / stateLeft.weight_sum);
// Note that a NativeRandomNumberGenerator object is stateless, so it
// is not a problem to instantiate an object for each RN generation...
NativeRandomNumberGenerator generator;
if (success(generator))
stateLeft.sample_id = stateRight.sample_id;
return stateLeft;
}
/**
* @brief Perform the weighted-sample final step
*/
AnyType
weighted_sample_final::run(AnyType &args) {
WeightedSampleTransitionState<ArrayHandle<double> > state = args[0];
return static_cast<int64_t>(state.sample_id);
}
} // namespace stats
} // namespace modules
} // namespace madlib
| true |
41b4acf43798f6b8d77d843fedca62de310fc3bb | C++ | gykovacs/vessel | /src/lib/openipDS/openipDS/Voxel.cc | UTF-8 | 475 | 2.703125 | 3 | [] | no_license | #include <openipDS/Voxel.h>
namespace openip
{
Voxel3::Voxel3()
{
s= r= c= 0;
}
Voxel3::Voxel3(const Voxel3& v)
{
this->s= v.s;
this->r= v.r;
this->c= v.c;
}
Voxel3::Voxel3(int s, int r, int c)
{
this->s= s;
this->r= r;
this->c= c;
}
Voxel3::~Voxel3()
{
}
int Voxel3::getVoxel1(int rows, int columns)
{
return s*rows*columns + r*columns + c;
}
}
| true |
68625c4d2787b984dc3724e033f7f0ff55760dd6 | C++ | aanna/amodsimulator | /src/EmptyTrip.hpp | UTF-8 | 846 | 2.703125 | 3 | [] | no_license | /*
* EmptyTrip.hpp
*
* Created on: 4 Apr, 2016
* Author: kasia
*/
/*
* EmptyBookings.hpp
*
* Created on: 4 Apr, 2016
* Author: kasia
*/
#include "Types.hpp"
#include <istream>
namespace amod {
struct EmptyTrip {
public:
/**
* Constructor
* @param from - from node id
* @param to - to node id
* @param rebTime - when the vehicles should be sent
* @param count - how many vehicles should be sent
*/
EmptyTrip(
int from_ = 0,
int to_ = 0,
int rebTime = 0,
int id_ = 0):
from(from_),
to(to_),
rebalancingTime(rebTime),
tripId(id_){}
/**
* Destructor
*/
virtual ~EmptyTrip() {}
/// Source node id (should be changed to Positions)
int from;
/// Desitination node id
int to;
// rebalancing time in seconds
int rebalancingTime;
// id of the trip
int tripId;
};
}
| true |
cfa9f64620874caadba6f2893d4e21b8884d1961 | C++ | imgag/ngs-bits | /src/cppREST/UrlManager.cpp | UTF-8 | 4,050 | 2.796875 | 3 | [
"MIT"
] | permissive | #include "UrlManager.h"
#include "Helper.h"
UrlManager::UrlManager()
: backup_file_(Helper::openFileForWriting(ServerHelper::getUrlStorageBackupFileName(), false, true))
, url_storage_()
{
}
UrlManager& UrlManager::instance()
{
static UrlManager url_manager;
return url_manager;
}
void UrlManager::saveEverythingToFile()
{
instance().mutex_.lock();
QMapIterator<QString, UrlEntity> i(instance().url_storage_);
QTextStream out(instance().backup_file_.data());
while (i.hasNext())
{
i.next();
if (!i.value().filename.isEmpty())
{
out << i.key() << "\t" << i.value().filename << "\t" << i.value().path << "\t" << i.value().filename_with_path <<
"\t" << i.value().file_id << "\t" << i.value().created.toString() << "\n";
}
}
instance().mutex_.unlock();
}
void UrlManager::saveUrlToFile(QString id, UrlEntity in)
{
QTextStream out(instance().backup_file_.data());
if (!in.isEmpty())
{
out << id << "\t" << in.filename << "\t" << in.path << "\t" << in.filename_with_path << "\t" << in.file_id << "\t" << in.created.toSecsSinceEpoch() << "\n";
}
}
void UrlManager::restoreFromFile()
{
// the method is not intended to be used when the server is running, since
// we do not handle concurrency
if (QFile(ServerHelper::getUrlStorageBackupFileName()).exists())
{
int restored_items = 0;
if (instance().backup_file_.data()->isOpen()) instance().backup_file_.data()->close();
instance().backup_file_ = Helper::openFileForReading(ServerHelper::getUrlStorageBackupFileName());
while(!instance().backup_file_.data()->atEnd())
{
QString line = instance().backup_file_.data()->readLine();
if(line.isEmpty()) break;
QList<QString> line_list = line.split("\t");
if (line_list.count() > 4)
{
bool ok;
restored_items++;
addNewUrl(line_list[0], UrlEntity(line_list[1], line_list[2], line_list[3], line_list[4], QDateTime::fromSecsSinceEpoch(line_list[5].toLongLong(&ok,10))), false);
}
}
Log::info("Number of restored URLs: " + QString::number(restored_items));
instance().backup_file_.data()->close();
removeExpiredUrls();
instance().backup_file_ = Helper::openFileForWriting(ServerHelper::getUrlStorageBackupFileName(), false, false);
QMapIterator<QString, UrlEntity> i(instance().url_storage_);
while (i.hasNext())
{
i.next();
saveUrlToFile(i.key(), i.value());
}
instance().backup_file_ = Helper::openFileForWriting(ServerHelper::getUrlStorageBackupFileName(), false, true);
}
else
{
Log::info("URL backup has not been found: nothing to restore");
}
}
void UrlManager::addNewUrl(QString id, UrlEntity in, bool save_to_file)
{
instance().mutex_.lock();
instance().url_storage_.insert(id, in);
if (save_to_file) saveUrlToFile(id, in);
instance().mutex_.unlock();
}
void UrlManager::removeUrl(const QString& id)
{
if (instance().url_storage_.contains(id))
{
instance().mutex_.lock();
instance().url_storage_.remove(id);
instance().mutex_.unlock();
}
}
bool UrlManager::isInStorageAlready(const QString& filename_with_path)
{
QMapIterator<QString, UrlEntity> i(instance().url_storage_);
while (i.hasNext()) {
i.next();
if (i.value().filename_with_path == filename_with_path)
{
return true;
}
}
return false;
}
UrlEntity UrlManager::getURLById(const QString& id)
{
if (instance().url_storage_.contains(id))
{
return instance().url_storage_[id];
}
return UrlEntity{};
}
void UrlManager::removeExpiredUrls()
{
// URL lifetime in seconds
int url_lifetime = ServerHelper::getNumSettingsValue("url_lifetime");
if (url_lifetime == 0)
{
url_lifetime = 600; // default value, if not set in the config
}
QList<QString> to_be_removed {};
QMapIterator<QString, UrlEntity> i(instance().url_storage_);
while (i.hasNext()) {
i.next();
int lifetime = (QDateTime::currentDateTime().toSecsSinceEpoch() - i.value().created.toSecsSinceEpoch()) / 60;
if (lifetime >= url_lifetime)
{
to_be_removed.append(i.key());
}
}
for (int i = 0; i < to_be_removed.count(); ++i)
{
removeUrl(to_be_removed[i]);
}
}
| true |
528957eef00b9160b5c0e953cb13604910cf4a6a | C++ | ccdxc/logSurvey | /data/crawl/squid/hunk_7575.cpp | UTF-8 | 3,086 | 2.609375 | 3 | [] | no_license | +#ifdef MAIL_HEADERS
+From: richard@hekkihek.hacom.nl (Richard Huveneers)
+To: squid-users@nlanr.net
+Subject: Save 15% on your bandwidth...
+Date: 12 Sep 1996 21:21:55 GMT
+==============================================================================
+
+I have downloaded the multi-megabyte files from Netscape and Microsoft that
+our users like to download from every mirror in the world, defeating the usual
+caching.
+
+I put these files in a separate directory and installed a basic redirector
+for Squid that checks if the file (so hostname and pathname are disregarded)
+is present in this directory.
+
+After a few days of testing (the redirector looks very stable) it looks like
+this is saving us approx. 15% on our cache flow. Also, our own WWW server has
+become more popular than ever :)
+
+I'm sure this code will be useful to others too, so I've attached it at the end
+of this message. Improvements, extensions etc. are welcome.
+
+I'm going on holidays now, so I won't be able to respond to e-mail quickly.
+
+Enjoy, Richard.
+#endif
+
+/*
+** rredir - redirect to local directory
+**
+** version 0.1, 7 sep 1996
+** - initial version (Richard Huveneers <Richard.Huveneers@hekkihek.hacom.nl>)
+*/
+
+#include <stdio.h>
+#include <unistd.h>
+#include <string.h>
+#include <ctype.h>
+
+#define ACCESS_LOCAL_DIR "/var/lib/httpd/htdocs/local/rredir"
+#define REDIRECT_TO_URL "http://www.hacom.nl/local/rredir"
+#define BUFFER_SIZE (16*1024)
+
+int main()
+{
+ char buf[BUFFER_SIZE];
+ char *s, *t;
+ int tlu = 0;
+
+ /* make standard output line buffered */
+ if (setvbuf(stdout, NULL, _IOLBF, 0) != 0) return 1;
+
+ /* speed up the access() calls below */
+ if (chdir(ACCESS_LOCAL_DIR) == -1) return 1;
+
+ /* scan standard input */
+ while (fgets(buf, BUFFER_SIZE, stdin) != NULL)
+ {
+ /* check for too long urls */
+ if (strchr(buf, '\n') == NULL)
+ {
+ tlu = 1;
+ continue;
+ }
+ if (tlu) goto dont_redirect;
+
+ /* determine end of url */
+ if ((s = strchr(buf, ' ')) == NULL) goto dont_redirect;
+ *s = '\0';
+
+ /* determine first character of filename */
+ if ((s = strrchr(buf, '/')) == NULL) goto dont_redirect;
+ s++;
+
+ /* security: do not redirect to hidden files, the current
+ ** directory or the parent directory */
+ if (*s == '.' || *s == '\0') goto dont_redirect;
+
+ /* map filename to lower case */
+ for (t = s; *t != '\0'; t++) *t = (char) tolower((int) *t);
+
+ /* check for a local copy of this file */
+ if (access(s, R_OK) == 0)
+ {
+ (void) printf("%s/%s\n", REDIRECT_TO_URL, s);
+ continue;
+ }
+
+dont_redirect:
+ tlu = 0;
+ (void) printf("\n");
+ }
+
+ return 0;
+} | true |
740550624c06e015e03dfe5339f6f8b26d8f9232 | C++ | yutakage/mit-ros-pkg | /branches/sandbox/furniture_ops/src/convertpcd.cpp | UTF-8 | 394 | 2.765625 | 3 | [] | no_license | /*
* convertpcd.cpp
*
* Created on: Oct 4, 2010
* Author: garratt
*/
#include <iostream>
#include <fstream>
int main(){
std::ifstream infile("asd.dat");
double x,y,z;
double xoff=-2.1513, yoff= 1.1796, zoff= 1.029;
while(infile.good() && !infile.eof()){
infile>>x>>y>>z;
std::cout<<x-xoff<<" "<<y-yoff<<" "<<z-zoff<<std::endl;
}
infile.close();
return 0;
}
| true |
fa112acbe0fbfb239e31d2d35422f79e333ea6b0 | C++ | boynux/arduino-display | /src/Renderer.cpp | UTF-8 | 327 | 2.515625 | 3 | [
"MIT"
] | permissive | #include "Renderer.h"
void Renderer::render() {
uint8_t *buffer = _grid->nextFrame();
if (buffer == 0) {
_grid->reset();
buffer = _grid->nextFrame();
}
for(int i = 0; i < _grid->height(); i++) {
for(int j = 0; j < _grid->width() / 8; j++) {
_control->setRow(j, i, buffer[i + j * 8]);
}
}
}
| true |
62dcdffb0c3e768f630bb5f32a34110d97adfbe6 | C++ | Ryan-Walsh-6/ISC3UR-Unit2-01-CPP | /circle.cpp | UTF-8 | 449 | 3.390625 | 3 | [] | no_license | // Copyright (c) 2020 Ryan Walsh All rights reserved
//
// Created by Ryan Walsh
// Created on November 22 2020
// This program calculates the area and perimeter of a circle
#include <iostream>
#include <cmath>
int main() {
std::cout << "If circle has radius of 15mm" << std::endl;
std::cout << std::endl;
std::cout << "Area is" << M_PI *pow(15, 2) << "mm^2" << std::endl;
std::cout << "Perimeter is " << 2*M_PI*15 << "mm" << std::endl;
}
| true |
004b24156283f57f0ee006e1999dee7b8c101f74 | C++ | aliosmanulusoy/Probabilistic-Volumetric-3D-Reconstruction | /core/vgui/tests/test_image_tableau.cxx | UTF-8 | 1,859 | 2.75 | 3 | [] | no_license | #include <vgui/vgui_image_tableau.h>
#include <testlib/testlib_test.h>
#include <vil1/vil1_image.h>
#include <vil1/vil1_load.h>
static void test_image_tableau(int argc, char* argv[])
{
// Make sure that constructing a vgui_image_tableau with a filename
// results in the vil1_image being loaded, since this is expected by
// older code.
//
const char* input_file = argc>1 ? argv[1] : "Please give it as command line parameter";
vil1_image img = vil1_load( input_file );
if ( !img ) {
std::cout << "Couldn't load test image \"" << input_file << "\"\n";
} else {
vgui_image_tableau_new img_tab( input_file );
vil1_image img2 = img_tab->get_image();
TEST( "Construct with filename", !img2, false);
TEST( "Size is correct",
img.width() == img2.width() &&
img.height() == img2.height() &&
img.components() == img2.components() &&
img.planes() == img2.planes() &&
img.bits_per_component() == img2.bits_per_component(), true);
unsigned buf_size = img.width() * img.height() *
img.planes() * img.components() *
( (img.bits_per_component()+7) / 8 );
char* img1_buf = new char[buf_size];
char* img2_buf = new char[buf_size];
TEST( "Get section from img1",
!img.get_section( img1_buf, 0, 0, img.width(), img.height() ), false);
TEST( "Get section from img2",
!img2.get_section( img2_buf, 0, 0, img2.width(), img2.height() ), false);
bool okay = true;
for ( unsigned i = 0; i < buf_size; ++i ) {
if ( img1_buf[i] != img2_buf[i] ) {
okay = false;
break;
}
}
TEST( "Contents are correct", okay, true);
delete [] img1_buf;
delete img2_buf;
}
}
// Supply a test image as the first argument
TESTMAIN_ARGS(test_image_tableau);
| true |
50b274938408bfe32ca4beb860379c53144f7f23 | C++ | michaeledryan/LUMI | /lumi/sleeves/sleeves.ino | UTF-8 | 5,238 | 2.65625 | 3 | [] | no_license | #include <Adafruit_NeoPixel.h>
#define START_CMD_CHAR 'a'
#define RED 'r'
#define ORANGE 'o'
#define YELLOW 'y'
#define GREEN 'g'
#define BLUE 'b'
#define INDIGO 'i'
#define PINK 'v'
#define WHITE 'w'
#define RAINBOW 'f'
#define TWINKLE 't'
#define NONE 0
#define LAST_WAS_RAINBOW 2
#define LAST_WAS_TWINKLE 4
#define PIN 11
int sdata;
int lastAction;
Adafruit_NeoPixel strip = Adafruit_NeoPixel(60, PIN, NEO_GRB + NEO_KHZ800);
void setup(){
Serial.begin(9600);
pinMode(11, OUTPUT);
strip.begin();
strip.show();
}
void loop(){
/*colorWipe(strip.Color(255, 0, 255), 100);
colorWipe(strip.Color(0, 255, 255), 100);
rainbowCycle(30);
theaterChaseRainbow(70);
theaterChase(strip.Color(127, 127, 127), 70);*/
Serial.flush();
int pin_num = 0;
int pin_val = 0;
if(Serial.available()<1){
//theaterChase(strip.Color(150, 150, 150), 70);
if (lastAction == LAST_WAS_RAINBOW) {
rainbowCycle(30);
}
else if (lastAction == LAST_WAS_TWINKLE) {
theaterChase(strip.Color(150, 150, 150), 70);
}
return;}
sdata = Serial.read();
// This setup means we buffer requests instead of fulfilling them instantly.
// Is that a problem?
if(sdata != START_CMD_CHAR){
// Do last thing.
return;
}
delay(20);
pin_num = Serial.read();
switch (pin_num) {
case RED:
colorWipe(strip.Color(255, 0, 0), 100);
lastAction = NONE;
break;
case ORANGE:
colorWipe(strip.Color(255, 140, 0), 100);
lastAction = NONE;
break;
case YELLOW:
colorWipe(strip.Color(255, 255, 0), 100);
lastAction = NONE;
break;
case GREEN:
colorWipe(strip.Color(0, 255, 0), 100);
lastAction = NONE;
break;
case BLUE:
colorWipe(strip.Color(0, 0, 255), 100);
lastAction = NONE;
break;
case INDIGO:
colorWipe(strip.Color(75, 0, 130), 100);
lastAction = NONE;
break;
case PINK:
colorWipe(strip.Color(255, 0, 255), 100);
lastAction = NONE;
break;
case WHITE:
colorWipe(strip.Color(150, 150, 150), 100);
lastAction = NONE;
break;
case TWINKLE:
theaterChase(strip.Color(150, 150, 150), 70);
lastAction = LAST_WAS_TWINKLE;
break;
case RAINBOW:
rainbowCycle(30);
lastAction = LAST_WAS_RAINBOW;
//default:
//rgbLedRainbow(numRGBleds, 10, 1, 27); // slow rainbow
}
}
// Colorwipe that works on the sleeves
void colorWipe(uint32_t c, uint8_t wait) {
// Four distinct sleeves, really only two though.
for(uint16_t i=0; i<28; i++) {
for(uint16_t j=0; j<2; j++) {
strip.setPixelColor(i + 28*j, c);
strip.setPixelColor(55 - 28*j - i, c);
// 0 -> 13, 28 -> 41 Forward
// 27 -> 14, 55 -> 42 Back
delay(wait);
}
strip.show();
}
}
void rainbow(uint8_t wait) {
uint16_t i, j, k;
for(j=0; j<256; j++) {
for(i=0; i<14; i++) {
for(k=0; k<2; k++) {
strip.setPixelColor(i + 28*k, Wheel((j) % 255));
strip.setPixelColor(55-28*k - i, Wheel((j) % 255));
}
}
strip.show();
delay(wait);
}
}
// Slightly different, this makes the rainbow equally distributed throughout
void rainbowCycle(uint8_t wait) {
uint16_t i, j, k;
for(j=0; j<256*1; j++) { // 5 cycles of all colors on wheel
for(i=0; i< 14; i++) {
for(k=0; k<2; k++) {
strip.setPixelColor(i + 28*k, Wheel(((8*i * 256) + j) % 255));
strip.setPixelColor(55-28*k - i, Wheel(((8*i * 256) + j) % 255));
// 0 -> 13, 28 -> 41 Forward
// 27 -> 14, 55 -> 42 Back
}
}
strip.show();
delay(wait);
}
}
// Input a value 0 to 255 to get a color value.
// The colours are a transition r - g - b - back to r.
uint32_t Wheel(byte WheelPos) {
if(WheelPos < 85) {
return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0);
} else if(WheelPos < 170) {
WheelPos -= 85;
return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3);
} else {
WheelPos -= 170;
return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3);
}
}
// Fix these?
//Theatre-style crawling lights with rainbow effect
void theaterChaseRainbow(uint8_t wait) {
for (int j=0; j < 256; j++) { // cycle all 256 colors in the wheel
for (int q=0; q < 3; q++) {
for (int i=0; i < strip.numPixels(); i=i+3) {
strip.setPixelColor(i+q, Wheel( (i+j) % 255)); //turn every third pixel on
}
strip.show();
delay(wait);
for (int i=0; i < strip.numPixels(); i=i+3) {
strip.setPixelColor(i+q, 0); //turn every third pixel off
}
}
}
}
void theaterChase(uint32_t c, uint8_t wait) {
for (int j=0; j<10; j++) { //do 10 cycles of chasing
for (int q=0; q < 3; q++) {
for (int i=0; i < strip.numPixels(); i=i+3) {
strip.setPixelColor(i+q, c); //turn every third pixel on
}
strip.show();
delay(wait);
for (int i=0; i < strip.numPixels(); i=i+3) {
strip.setPixelColor(i+q, 0); //turn every third pixel off
}
}
}
}
| true |
6759cd8aa75bd54c6efd89bf1dd97002c5f835c5 | C++ | Acka1357/ProblemSolving | /BeakjoonOJ/15000/15765_FamilyTree.cpp | UTF-8 | 1,605 | 2.703125 | 3 | [] | no_license | #include <stdio.h>
#include <iostream>
#include <string>
#include <map>
#include <vector>
#include <memory.h>
using namespace std;
int par[202], chk[202][2], cnt;
string A, B, name[202];
map<string, int> mp;
void set_chk(int cur, int dist, int idx){
chk[cur][idx] = dist;
if(par[cur] >= 0) set_chk(par[cur], dist + 1, idx);
}
int main()
{
memset(par, 0xff, sizeof(par));
memset(chk, 0xff, sizeof(chk));
int N; cin >> N >> A >> B;
mp[name[cnt] = A] = cnt; cnt++;
mp[name[cnt] = B] = cnt; cnt++;
for(int i = 0; i < N; i++){
cin >> A >> B;
if(!mp.count(A)) mp[name[cnt] = A] = cnt, cnt++;
if(!mp.count(B)) mp[name[cnt] = B] = cnt, cnt++;
par[mp[B]] = mp[A];
}
set_chk(0, 0, 0);
set_chk(1, 0, 1);
int lca = -1;
for(int i = 0; i < cnt; i++){
if(chk[i][0] < 0 || chk[i][1] < 0) continue;
if(lca < 0 || (chk[i][0] + chk[i][1] < chk[lca][0] + chk[lca][1]))
lca = i;
}
string ans;
if(lca < 0) ans = "NOT RELATED";
else if(chk[lca][0] == 1 && chk[lca][1] == 1) ans = "SIBLINGS";
else if(lca == 0 || lca == 1){
ans = (lca == 0 ? name[0] : name[1]) + " is the ";
for(int i = max(chk[lca][0], chk[lca][1]) - 2; i > 0; i--)
ans += "great-";
if(max(chk[lca][0], chk[lca][1]) > 1) ans += "grand-";
ans += "mother of " + (lca == 0 ? name[1] : name[0]);
}
else if(chk[lca][0] == 1 || chk[lca][1] == 1){
ans = (chk[lca][0] == 1 ? name[0] : name[1]) + " is the ";
for(int i = max(chk[lca][0], chk[lca][1]) - 2; i > 0; i--)
ans += "great-";
ans += "aunt of " + (chk[lca][0] == 1 ? name[1] : name[0]);
}
else ans = "COUSINS";
cout << ans << "\n";
return 0;
}
| true |
da185eeff940ac01239b65f1bbf1ef7faea0196e | C++ | michaelnguyen408/CodeForces | /580A - Kefa and First Steps.cpp | UTF-8 | 297 | 2.671875 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
int len;
cin >> len;
int result = 1, sum = 1;
int next, n;
cin >> n;
for (int i = 1; i < len; i++)
{
cin >> next;
if (next >= n)
{
sum++;
if (sum > result) result = sum;
}
else sum = 1;
n = next;
}
cout << result;
} | true |
f91c4548b10bffc11f3817b4de30f0f252b3d38a | C++ | Evalir/Algorithms | /Problems/CSES/IncreasingArray/main.cpp | UTF-8 | 462 | 2.609375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
using ll = long long;
int main() {
int n;
cin >> n;
vector<ll> s(n);
for(auto &t : s) cin >> t;
ll ans = 0;
for(int i = 0 ; i < n; i++) {
if (i) {
if (s[i-1] > s[i]) {
ans += abs(s[i-1]-s[i]);
s[i] += abs(s[i-1]-s[i]);
}
}
}
cout << ans << endl;
return 0;
} | true |
fa04d8a5bdf74f6d3a223f0ae9a3dae9ffee2de4 | C++ | xTCry/among-us-replayer | /source/scene/map.cpp | UTF-8 | 2,005 | 2.71875 | 3 | [
"MIT"
] | permissive | #include "map.hpp"
#include "player.hpp"
#include <resources/config.hpp>
#include <fmt/format.h>
#include <stdexcept>
namespace scene {
void map::load_map() {
m_background.load(resources::config::get_map_path(m_id));
m_converter = resources::config::get_map_position_converter(m_id);
}
player& map::get_player(std::uint8_t id) {
auto it = std::find_if(m_players.begin(), m_players.end(), [id](auto& pl) {
return pl->get_id() == id;
});
if (it == m_players.end()) {
throw std::runtime_error(fmt::format("player {} not found", id));
}
return **it;
}
map::map(int id) : m_id(id) {
load_map();
}
map::~map() = default;
void map::add_player(std::unique_ptr<player> player) {
player->set_scale(
resources::config::get_player_scale(m_id),
resources::config::get_ghost_scale(m_id),
resources::config::get_body_scale(m_id)
);
m_players.emplace_back(std::move(player));
}
void map::set_player_state(std::uint8_t id, const std::array<float, 2>& position, const std::array<float, 2>& velocity, bool is_dead) {
auto& player = get_player(id);
player.set_position(m_converter({ position[0], position[1] }), velocity[0] > 0);
player.set_is_dead(is_dead);
}
void map::set_meeting(std::uint8_t id) {
get_player(id).on_meeting();
}
sf::Vector2f map::get_center() const {
return m_converter(resources::config::get_center(m_id));
}
float map::get_default_zoom() const {
return resources::config::get_default_zoom(m_id);
}
void map::draw(sf::RenderTarget& target, const sf::Transform& parent_transform) const {
const sf::Transform transform = parent_transform * m_transform;
target.draw(m_background, transform);
for (const auto& player : m_players) {
player->draw(target, transform);
}
}
sf::Vector2f map::convert_position(const std::array<float, 2>& game_position) const {
return m_converter({ game_position[0], game_position[1] });
}
} // namespace scene
| true |
37729513bcb945346d8bb31d15334e7c98eed7b3 | C++ | Kuailun/Leetcode | /_278_First_Bad_Version/_278_First_Bad_Version.cpp | UTF-8 | 1,473 | 3.046875 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <unordered_map>
using namespace std;
bool isBadVersion(int version);
int firstBadVersion(int n);
int main()
{
int input=2;
int output = firstBadVersion(input);
cout << output << endl;
system("pause");
}
bool isBadVersion(int version)
{
int n = 1;
if (version >= n)
return true;
else
return false;
}
int firstBadVersion(int n) {
long left = 1;
long right = n;
bool l = false;
bool r = false;
bool mid = false;
if (isBadVersion(1))
return 1;
if (!isBadVersion(n - 1))
return n;
while (left < right)
{
if (!l & r && right - left == 1)
{
return right;
}
mid = isBadVersion((left + right + 1) / 2);
if (mid)
{
right = (left + right + 1) / 2;
r = mid;
}
if (!mid)
{
left = (left + right + 1) / 2;
r = mid;
}
}
return right;
}
// Run program: Ctrl + F5 or Debug > Start Without Debugging menu
// Debug program: F5 or Debug > Start Debugging menu
// Tips for Getting Started:
// 1. Use the Solution Explorer window to add/manage files
// 2. Use the Team Explorer window to connect to source control
// 3. Use the Output window to see build output and other messages
// 4. Use the Error List window to view errors
// 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project
// 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
| true |
3ba6d3fcb285c6446e1ee21a75a12b13e6454b70 | C++ | ascheglov/cpp-rce-lib | /test/test_splicing.cpp | UTF-8 | 3,136 | 2.546875 | 3 | [
"MIT"
] | permissive | /* C++ RCE Library
* http://code.google.com/p/cpp-rce-lib/
* (c) 2010-2011 Abyx. MIT License.
*
* Splicing tests
*/
#include <rce/detail/splicing.h>
#pragma warning(push)
#pragma warning(disable: 4265 4619 4548)
#include <boost/test/unit_test.hpp>
#pragma warning(pop)
#include <algorithm>
#include <vector>
#pragma warning(push)
#pragma warning(disable: 4242 4244 4512)
#include <boost/assign/std/vector.hpp>
#pragma warning(pop)
#include "dump.h"
using namespace boost::assign;
struct SplicingFixture
{
static const auto HOOK_FN_ADDR = 0;
typedef std::vector<unsigned char> vector_t;
vector_t expected_;
vector_t code_;
vector_t saved_;
SplicingFixture() : expected_(), code_(), saved_(24, 0x55) {}
vector_t& expected() { return expected_; }
vector_t& code() { return code_; }
// don't add data to code_ after calling this : code_'s data may relocate
void expected_write_rel32(int fromEndIdx, int destIdx)
{
*(int*)&expected_[fromEndIdx - 4] = &code_[destIdx] - &saved_[fromEndIdx];
}
void do_splice()
{
hook::detail::splice(&code_[0], (void*)HOOK_FN_ADDR, &saved_[0]);
}
boost::test_tools::predicate_result check() const
{
vector_t savedCode(saved_.begin(), std::find(saved_.begin(), saved_.end(), 0x55));
if(savedCode == expected_)
return true;
boost::test_tools::predicate_result res(false);
res.message()
<< "Saved not expected_ bytes:"
<< "\n saved: " << dump(savedCode)
<< "\n expected: " << dump(expected_);
return res;
}
};
BOOST_FIXTURE_TEST_CASE(test_spliced_code, SplicingFixture)
{
code() += 0x90, 0x90, 0x90, 0x90, 0x90, 0x90;
do_splice();
BOOST_CHECK_EQUAL(code_[0], 0xE9);
BOOST_CHECK_EQUAL(*(int*)&code_[1], (unsigned char*)HOOK_FN_ADDR - &code_[5]);
BOOST_CHECK_EQUAL(code_[5], 0x90);
}
BOOST_FIXTURE_TEST_CASE(test_splice_fn_5_bytes_length, SplicingFixture)
{
code() +=
0x90, 0x90, 0x90, 0x90, // 0:4
0xC3, // 4:5
0x55; // added to make index "5" valid
expected() +=
0x90, 0x90, 0x90, 0x90, // 0:4
0xC3, // 4:5
0xE9, 0, 0, 0, 0; // 5:10
expected_write_rel32(10, 5);
do_splice();
BOOST_CHECK(check());
}
BOOST_FIXTURE_TEST_CASE(test_splice_fn_with_call_rel32, SplicingFixture)
{
code() +=
0xE8, 0x01, 0x00, 0x00, 0x00, // 0:5
0xC3, // 5:6
0xC3; // 6:7
expected() +=
0xE8, 0, 0, 0, 0, // 0:5
0xE9, 0, 0, 0, 0; // 5:10
expected_write_rel32(5, 6);
expected_write_rel32(10, 5);
do_splice();
BOOST_CHECK(check());
}
BOOST_FIXTURE_TEST_CASE(test_splice_fn_with_jmp_rel32, SplicingFixture)
{
code() +=
0x90, // 0:1
0xE9, 0x00, 0x00, 0x00, 0x00, // 1:6
0xC3; // 6:7
expected() +=
0x90, // 0:1
0xE9, 0, 0, 0, 0; // 1:6
expected_write_rel32(6, 6);
do_splice();
BOOST_CHECK(check());
}
| true |
5be59f876df42f508ce22dc664d6e71c8a1f7217 | C++ | navneetyadav/lab7 | /q_6.cpp | UTF-8 | 742 | 3.921875 | 4 | [] | no_license | //calling the libraries
#include<iostream>
#include<cmath>
using namespace std;
//writing the recursive function
int rev(int a, int num)
{
//declaring the field variables
int x, y, z;
x=a; y=0; z=1;
//while loop for counting the number of digits
while(x>0)
{
x=x/10;
y++;
}
//changing the position of the digits
z=a%10;
num=num+z*(pow(10,y-1));
a=a/10;
if(a!=0)
{
//recursing the function
rev(a,num);
}
else
{
cout<<"the reverse of the number is = "<<num<<endl;
return 1;
}
}
//calling the main function
int main()
{
//declaring variables for the task
int nm;
//asking user to enter a number
cout<<"Enter a number."<<endl;
cin>>nm;
//calling function to perform the task
rev(nm, 0);
return 0;
}
| true |
bb299df619e7c1c014ae29380ab4067246270a27 | C++ | fengwang/tetris-lspe | /include/f/matrix/matrix/matrix/shrink_to_size.hpp | UTF-8 | 3,031 | 2.703125 | 3 | [] | no_license | #ifndef TILVRAWFEKOGUQEEWGEMBQWAYLDIJSWSLEXQDJLUYWTKJCVNUYUIFLKAVGWAVMSIKQMKHBIJK
#define TILVRAWFEKOGUQEEWGEMBQWAYLDIJSWSLEXQDJLUYWTKJCVNUYUIFLKAVGWAVMSIKQMKHBIJK
namespace f
{
template<typename Matrix, typename Type, typename Allocator>
struct crtp_shrink_to_size
{
typedef Matrix zen_type;
typedef crtp_typedef<Type, Allocator> type_proxy_type;
typedef typename type_proxy_type::size_type size_type;
typedef typename type_proxy_type::value_type value_type;
#if 0
zen_type& shrink_to_size( const size_type new_row, const size_type new_col = 1 )
{
assert( new_row && new_col );
zen_type& zen = static_cast<zen_type&>( *this );
if ( new_row == zen.row() && new_col == zen.col() )
return zen;
assert( new_row <= zen.row() && new_col <= zen.col() );
zen_type other{ new_row, new_col };
if ( new_col >= new_row )
for ( size_type r = 0; r != new_row; ++r )
std::copy( zen.row_begin( r ), zen.row_begin( r ) + new_col, other.row_begin( r ) );
else
for ( size_type c = 0; c != new_col; ++c )
std::copy( zen.col_begin( c ), zen.col_begin( c ) + new_row, other.col_begin( c ) );
zen.swap( other );
return zen;
}
#endif
zen_type& shrink_to_size( const size_type new_row, const size_type new_col )
{
assert( new_row && new_col );
zen_type& zen = static_cast<zen_type&>( *this );
if ( new_row == zen.row() && new_col == zen.col() )
return zen;
zen_type other{ new_row, new_col };
std::fill( other.begin(), other.end(), value_type{} );
size_type const the_rows_to_copy = std::min( zen.row(), new_row );
size_type const the_cols_to_copy = std::min( zen.col(), new_col );
for ( size_type r = 0; r != the_rows_to_copy; ++r )
std::copy( zen.row_begin( r ), zen.row_begin( r ) + the_rows_to_copy, other.row_begin( r ) );
zen.swap( other );
return zen;
}
#if 0
//TODO:
// impl a local method to impl all these shink methods ...
//
zen_type& shrink_to_upper_left( const size_type new_row, const size_type new_col = 1 )
{
}
zen_type& shrink_to_upper_right( const size_type new_row, const size_type new_col = 1 )
{
}
zen_type& shrink_to_lower_left( const size_type new_row, const size_type new_col = 1 )
{
}
zen_type& shrink_to_lower_right( const size_type new_row, const size_type new_col = 1 )
{
}
#endif
};//struct crtp_shrink_to_size
}
#endif//TILVRAWFEKOGUQEEWGEMBQWAYLDIJSWSLEXQDJLUYWTKJCVNUYUIFLKAVGWAVMSIKQMKHBIJK
| true |
5537eca756cab9782f31932ccf4eba08d61e2065 | C++ | Linfanty/Code-in-Freshman | /2017 Summer Training/Day5博弈论&SG函数&NIM/LL.cpp | GB18030 | 1,384 | 3.3125 | 3 | [] | no_license | #include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int cmp1(char a,char b) //
{
return a<b;
}
int cmp2(char a,char b) //
{
return a>b;
}
int main()
{
char a[300005],b[300005],map[300005];
int n,i,alen1,alen2,blen1,blen2,s,e;
while(cin>>a>>b)
{
n=strlen(a);
sort(a,a+n,cmp1);
sort(b,b+n,cmp2);
alen1=0;alen2=n%2==0?n/2:n/2+1;alen2--; //aȷţaǵaһ
blen1=0;blen2=n/2-1;
s=0,e=n-1;
for(i=0;i<n;i++)
{
if(i%2==0) //a
{
if(a[alen1]<b[blen1]) //aַbַ
{
map[s++]=a[alen1++]; //˳ŷ
}
else
{
map[e--]=a[alen2--]; //ַβ
}
}
else //b
{
if(b[blen1]>a[alen1]) //bַaַ
{
map[s++]=b[blen1++]; //˳ŷ
}
else
{
map[e--]=b[blen2--]; //ַβaַǰһλ
}
}
}
map[n]='\0';
cout<<map<<endl;
}
return 0;
}
| true |
061018b7798d578864aee1ef7e51a2d520c2aa64 | C++ | zacharyvincze/nintendo-emulation-system | /src/cpu.h | UTF-8 | 5,093 | 2.75 | 3 | [] | no_license | #ifndef CPU_H
#define CPU_H
#include <thread>
#include <chrono>
#include "definitions.h"
#include "register.h"
#include "memory.h"
namespace {
const long CPU_CLOCK_SPEED_HZ = 1789773;
const long PPU_CLOCK_SPEED_HZ = CPU_CLOCK_SPEED_HZ * 3;
const long APU_CLOCK_SPEED_HZ = 1789773;
}
class CPU {
public:
CPU(Memory& memory);
~CPU();
/*
NES 6502 has a clock that runs at about 1.79MHz (1789773Hz)
*/
void tick(); // Emulates a single opcode execution
/*
Three general purpose 8-bit registers: A, X, and Y, with A being the accumulator
one stack pointer register which is 8 bits long
a status register which acts the same as any other 8-bit register
and a program counter register that is 16-bits to keep track of the current
execution address.
*/
ByteRegister regA, regX, regY;
ByteRegister regSP;
StatusRegister regStatus;
WordRegister regPC;
// The CPU has full access to the system's memory
Memory& memory;
u8 get_byte_from_pc();
r8 get_signed_byte_from_pc();
u16 get_word_from_pc();
private:
// Timers and loop breaks
unsigned long cpu_cycles;
unsigned int loop_cycles;
bool cpu_running;
void execute_opcode(u8 opcode);
// Stack operations
u8 stack_pop();
void stack_push(u8 byte);
// Addressing modes
u8 zero_page(unsigned int cycles);
u8 zero_page_x(unsigned int cycles);
u8 zero_page_y(unsigned int cycles);
u16 pre_indexed_indirect(unsigned int cycles);
u16 post_indexed_indirect(unsigned int cycles);
u16 absolute(unsigned int cycles);
u16 absolute_x(unsigned int cycles);
u16 absolute_y(unsigned int cycles);
// Utilities
void set_flags_nz(u8 value);
// General opcode commands
// GENERAL LOGICAL AND ARITHMETIC COMMANDS
void ORA(u8 byte);
void AND(u8 byte);
void EOR(u8 byte);
void ADC(s8 byte);
void SBC(s8 byte);
void CMP(u8 byte);
void CPX(u8 byte);
void CPY(u8 byte);
void DEC(u16 memory_address);
void INC(u16 memory_address);
void ASL(u16 memory_address);
void ROL(u16 memory_address);
void LSR(u16 memory_address);
void ROR(u16 memory_address);
// GENERAL MOVE COMMANDS
void LDA(u8 byte);
void STA(u16 memory_address);
void LDX(u8 byte);
void STX(u16 memory_address);
void LDY(u8 byte);
void STY(u16 memory_address);
// BRANCH COMMANDS
void branch(bool condition);
// Note: Any missing general opcodes don't have enough unique addressing
// modes to constitute a general function declaration.
// LOGICAL AND ARITHMETIC COMMANDS
void ORA_09();
void ORA_05();
void ORA_15();
void ORA_01();
void ORA_11();
void ORA_0D();
void ORA_1D();
void ORA_19();
void AND_29();
void AND_25();
void AND_35();
void AND_21();
void AND_31();
void AND_2D();
void AND_3D();
void AND_39();
void EOR_49();
void EOR_45();
void EOR_55();
void EOR_41();
void EOR_51();
void EOR_4D();
void EOR_5D();
void EOR_59();
void ADC_69();
void ADC_65();
void ADC_75();
void ADC_61();
void ADC_71();
void ADC_6D();
void ADC_7D();
void ADC_79();
void SBC_E9();
void SBC_E5();
void SBC_F5();
void SBC_E1();
void SBC_F1();
void SBC_ED();
void SBC_FD();
void SBC_F9();
void CMP_C9();
void CMP_C5();
void CMP_D5();
void CMP_C1();
void CMP_D1();
void CMP_CD();
void CMP_DD();
void CMP_D9();
void CPX_E0();
void CPX_E4();
void CPX_EC();
void CPY_C0();
void CPY_C4();
void CPY_CC();
void DEC_C6();
void DEC_D6();
void DEC_CE();
void DEC_DE();
void DEX_CA();
void DEY_88();
void INC_E6();
void INC_F6();
void INC_EE();
void INC_FE();
void INX_E8();
void INY_C8();
void ASL_0A();
void ASL_06();
void ASL_16();
void ASL_0E();
void ASL_1E();
void ROL_2A();
void ROL_26();
void ROL_36();
void ROL_2E();
void ROL_3E();
void LSR_4A();
void LSR_46();
void LSR_56();
void LSR_4E();
void LSR_5E();
void ROR_6A();
void ROR_66();
void ROR_76();
void ROR_6E();
void ROR_7E();
// MOVE COMMANDS
void LDA_A9();
void LDA_A5();
void LDA_B5();
void LDA_A1();
void LDA_B1();
void LDA_AD();
void LDA_BD();
void LDA_B9();
void STA_85();
void STA_95();
void STA_81();
void STA_91();
void STA_8D();
void STA_9D();
void STA_99();
void LDX_A2();
void LDX_A6();
void LDX_B6();
void LDX_AE();
void LDX_BE();
void STX_86();
void STX_96();
void STX_8E();
void LDY_A0();
void LDY_A4();
void LDY_B4();
void LDY_AC();
void LDY_BC();
void STY_84();
void STY_94();
void STY_8C();
void TAX_AA();
void TXA_8A();
void TAY_A8();
void TYA_98();
void TSX_BA();
void TXS_9A();
void PLA_68();
void PHA_48();
void PLP_28();
void PHP_08();
// JUMP/FLAG COMMANDS
void BPL_10();
void BMI_30();
void BVC_50();
void BVS_70();
void BCC_90();
void BCS_B0();
void BNE_D0();
void BEQ_F0();
void BRK_00();
void RTI_40();
void JSR_20();
void RTS_60();
void JMP_4C();
void JMP_6C();
void BIT_24();
void BIT_2C();
void CLC_18();
void SEC_38();
void CLD_D8();
void SED_F8();
void CLI_58();
void SEI_78();
void CLV_B8();
void NOP_EA(); // Always found NOP opcodes kinda weird
// seems like they're just there to use up
// cycles for some reason.
};
#endif // CPU_H | true |
9e6211e8dc2f842576a7c3f11fbcd47542944ef4 | C++ | Eagle-E/RubyCompiler | /MRCompiler/DivideByZeroException.cpp | UTF-8 | 298 | 2.765625 | 3 | [] | no_license | #include "DivideByZeroException.h"
DivideByZeroException::DivideByZeroException()
: mExceptionReason("")
{
}
DivideByZeroException::DivideByZeroException(const string& reason)
: mExceptionReason(reason)
{
}
const char* DivideByZeroException::what() const
{
return mExceptionReason.c_str();
}
| true |