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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
ff20f8ce22289c9e01a7f7c438a2c9f477922233 | C++ | alexandrocw/CP-training | /Codeforces/785A_AntonandPolyhedrons.cpp | UTF-8 | 656 | 3.21875 | 3 | [] | no_license | #include <iostream>
#include <cstring>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
int n, cnt = 0;
string s;
cin >> n;
while(n--) {
cin >> s;
if(s.compare("Tetrahedron") == 0) {
cnt += 4;
} else if (s.compare("Cube") == 0) {
cnt += 6;
} else if (s.compare("Octahedron") == 0) {
cnt += 8;
} else if (s.compare("Dodecahedron") == 0) {
cnt += 12;
} else if (s.compare("Icosahedron") == 0) {
cnt += 20;
}
}
cout << cnt;
return 0;
}
| true |
708dc98887ade134bc0ef60fa354522d401e0191 | C++ | tgtn007/LeetCode-Solutions | /search in sorted and rotated.cpp | UTF-8 | 1,461 | 3.40625 | 3 | [] | no_license | // will not work for duplicates
class Solution {
public:
int get(int lo, int hi, vector<int>& nums, int target)
{
int mid;
while(lo <= hi)
{
mid = lo + (hi - lo)/2;
if(nums[mid] == target)
return true;
if(nums[mid] < target)
lo = mid+1;
else
hi = mid-1;
}
return -1;
}
bool search(vector<int>& nums, int target) {
if(nums.size() == 0)
{
return false;
}
int pivot = -1;
for(int i=0; i<nums.size(); i++)
{
if(nums[i+1] < nums[i])
{
pivot = i+1;
break;
}
}
if(pivot == -1 || nums.size()==1)
{
int ans = get(0, nums.size()-1, nums, target);
if(ans == -1)
{
return false;
}
return true;
}
if(nums[pivot] == target || nums[0] == target || nums[nums.size()-1] == target)
{
return true;
}
int ans = get(0, pivot-1, nums, target);
if(ans != -1)
{
return true;
}
ans = get(pivot, nums.size()-1, nums, target);
if(ans != -1)
{
return true;
}
return false;
}
};
| true |
1d76d4105379ec402e313faf9c29890014a540ff | C++ | maziars/GeometricMedianADMM | /GeometricMedian/GeometricMedian/main.cpp | UTF-8 | 3,110 | 2.65625 | 3 | [
"MIT"
] | permissive | //
// main.cpp
// GeometricMedianADMM
//
// Created by Maziar Sanjabi on 11/6/17.
// Copyright © 2017 Maziar Sanjabi. All rights reserved.
//
#include <iostream>
#include "IO_MANAGER.hpp"
#include "Constants.h"
#include <ctime>
#include "GeoMedianADMM.hpp"
int main(int argc, const char * argv[]) {
// insert code here...
// Read the data from the files
int N;
int d;
FILE *file1 = fopen("/Users/Maziar/Dropbox/GitHub/GeometricMedianADMM/MATLAB/Nd.txt", "r");
if (file1 == NULL){
perror("ERROR:");
}
int sizes[2];
int readl;
readl = fread_int(file1, sizes);
if (readl != 2) {
printf("I/O error in sizes.txt\n");
}
N = sizes[0];
d = sizes[1];
double* Z = (double*) malloc(sizeof(double)*N*d);
double* w = (double*) malloc(sizeof(double)*N);
file1 = fopen("/Users/Maziar/Dropbox/GitHub/GeometricMedianADMM/MATLAB/Z.txt", "r");
if (file1 == NULL){
perror("ERROR:");
}
readl = fread_float(file1, Z);
if (readl != N*d)
printf("I/O error in Z.txt\n");
file1 = fopen("/Users/Maziar/Dropbox/GitHub/GeometricMedianADMM/MATLAB/w.txt", "r");
if (file1 == NULL){
perror("ERROR:");
}
readl = fread_float(file1, w);
if (readl != N)
printf("I/O error in w.txt\n");
//show_row_rect_matrix("Z' is:", Z, N, d); // Z is saved column based
//show_row_rect_matrix("w is:", w, N, 1);
//time_t now;
//time_t after;
struct timespec start, finish;
double elapsed;
double* x_single = (double*) calloc(d, sizeof(double));
algorithmStatistics_t singleT_stat[1];
//now = time(0);
clock_gettime(CLOCK_MONOTONIC, &start);
GeoMedianADMM_SingleThread(x_single, singleT_stat, Z, w, N, d);
clock_gettime(CLOCK_MONOTONIC, &finish);
//after = time(0);
//std::cout <<"\nElapsed time is: "<< after - now << " s"<< std::endl;
//singleT_stat[0].time = after - now;
elapsed = (finish.tv_sec - start.tv_sec);
elapsed += (finish.tv_nsec - start.tv_nsec) / 1000000000.0;
singleT_stat[0].time = elapsed;
printStat("Stats for Single Thread", singleT_stat);
//show_row_rect_matrix("x is:", x, d, 1);
//std::cout << "Hello, World!\n";
//-----------------------------------------------------------
#ifdef MultiThread
double* x_multi = (double*) calloc(d, sizeof(double));
algorithmStatistics_t multiT_stat[1];
clock_gettime(CLOCK_MONOTONIC, &start);
//now = time(0);
GeoMedianADMM_MultiThread(x_multi, multiT_stat, Z, w, N, d);
clock_gettime(CLOCK_MONOTONIC, &finish);
//after = time(0);
//std::cout <<"\nElapsed time is: "<< after - now << " s"<< std::endl;
elapsed = (finish.tv_sec - start.tv_sec);
elapsed += (finish.tv_nsec - start.tv_nsec) / 1000000000.0;
multiT_stat[0].time = elapsed;
printStat("Stats for Multi Thread", multiT_stat);
#endif// MultiThread
return 0;
}
| true |
3ada7a4f929380dd5c8cedbd0542db0afcd9f75a | C++ | soulsystem00/bj_2798 | /bj_2798/bj_1065.cpp | UTF-8 | 507 | 2.921875 | 3 | [] | no_license | //#include <iostream>
//#include <string>
//using namespace std;
//
//bool chkNum(int num)
//{
// string Num = to_string(num);
// if (Num.length() == 1 || Num.length() == 2)
// return true;
//
// for (int i = 0; i < Num.length() - 2; i++)
// {
// if (Num[i + 1] - Num[i] != Num[i + 2] - Num[i + 1])
// return false;
// }
// return true;
//}
//
//int main()
//{
// int num;
// cin >> num;
// int cnt(0);
//
// for (int i = 1; i < num + 1; i++)
// {
// if (chkNum(i))
// cnt++;
// }
// cout << cnt;
//} | true |
50511997da70a8f0a7e1d0baad02c22b948ef9c4 | C++ | matthewnyee/cs202 | /lab/Lab1/cs202_lab1.cpp | UTF-8 | 1,143 | 3.203125 | 3 | [] | no_license | #include "employee.h"
using namespace std;
const int MAX = 100;
//This code is to test out the hierarchy of the clases created
int main()
{
char temp[MAX];
char response;
//experiment with the hourly employee class
person person_applying;
do
{
hourly_employee new_hire;
cout <<"What is the name of the person applying for a job\n";
person_applying.read();
cout <<"\nWe received information about this person:\n";
person_applying.display();
cout <<"\nWould you like to hire them? Y or N ";
cin >>response; cin.ignore(MAX,'\n');
if (toupper(response) == 'Y')
{
new_hire.hire(person_applying);
do
{
cout <<"\nPlease enter their periodic performance review: ";
cin.get(temp, MAX,'\n');
cin.ignore(MAX, '\n');
new_hire.performance_review(temp);
} while (again());
cerr <<"\n\nThis is the complete informatin about the new hire... ";
new_hire.display();
}
} while (again());
return 0;
}
| true |
ba988d055e3803f19b4fd780fd350649527bbb9a | C++ | rodrigocolor/Git | /Projetos/C++/Aula 8 - Pilhas/Exercicio 1.cpp | ISO-8859-1 | 1,724 | 3.34375 | 3 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
#include<string>
#include <conio.h>
#include <locale.h>
struct pilha {
int topo, item[8];
};
void iniciaPilha(pilha &p) {
p.topo = -1;
}
bool pilhaVazia(pilha p) {
if(p.topo == -1) return true;
else return false;
}
bool pilhaCheia(pilha p) {
if(p.topo == 8-1) return true;
else return false;
}
void empilha(pilha &p, int x) {
p.item[++p.topo]=x;
}
int desempilha(pilha &p) {
if (p.item[p.topo--] % 2 != 0) return(p.item[p.topo]);
}
int main() {
setlocale(LC_ALL, "Portuguese");
pilha x;
int i=0, t;
iniciaPilha(x);
while (i != 4) {
system("cls");
printf("1- Verificar s pilha vazia\n");
printf("2- Inserir objetos\n");
printf("3- Mostrar topo\n");
printf("4- Sair\n");
scanf( "%i",&i );
switch (i) {
case 1:
if (pilhaVazia(x)) {
printf("Pilha vazia!\n");
} else {
printf("Pilha nao esta vazia!\n");
}
break;
case 2:
if (pilhaCheia(x)) {
printf("Pilha cheia!!\n\n");
} else {
printf("Informe um numero: ");
scanf("%i",&t);
empilha(x, t);
}
break;
case 3:
if (pilhaVazia(x)) {
printf("Pilha vazia!\n");
} else {
printf("Item desempilhado %i ", desempilha(x));
}
break;
case 4 :
system("exit");
break;
default:
printf( "Opo invalida!!");
break;
}
printf("\n");
system("pause");
}
}
| true |
13cfbe5878aec36e70ed51ee5d3e8a044b152f73 | C++ | MartinEthier/DataStructuresAndAlgorithmsLabs | /Lab 2/patient_record.cpp | UTF-8 | 792 | 2.59375 | 3 | [] | no_license | //
// Martin Ethier, 20660931
//
#include "patient_record.h"
PatientRecord::PatientRecord()
: categoryID(0), patientID(0), name(""), address(""), DOB("")
{}
PatientRecord::PatientRecord(unsigned int newCatID, unsigned int newPatID, string newName, string newAddress,
string newDOB)
: categoryID(newCatID), patientID(newPatID), name(newName), address(newAddress), DOB(newDOB)
{}
PatientRecord::~PatientRecord() {}
unsigned int PatientRecord::getCatID() {
return categoryID;
}
unsigned int PatientRecord::getPatID() {
return patientID;
}
string PatientRecord::getName() {
return name;
}
string PatientRecord::getAddress() {
return address;
}
string PatientRecord::getDOB() {
return DOB;
}
| true |
9bf0cf453d55269a3b7fd79cac15dc96c55cc239 | C++ | Thyagr/programming | /cprogs/filemaxlines.cpp | UTF-8 | 1,419 | 2.984375 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <string>
using namespace std;
#include <queue>
#define NOFILENAME -1
#define FILEOPENERR -2
#define MAXCHARS 512
#define MINHEAPSIZE 50
#define DEBUG 0
struct CustomCompare
{
bool operator()(const string str1, const string str2)
{
return str1.length() > str2.length();
}
};
int main(int argc, char* argv[])
{
if (argc < 2)
{
cout << "Specify file name as argument";
return NOFILENAME;
}
if (DEBUG)
cout << argc << " " << argv[1];
fstream fs;
try
{
// bad for getline
if (DEBUG)
fs.exceptions(fstream::badbit | fstream::failbit);
fs.open(argv[1], fstream::in);
}
catch (const fstream::failure& ex)
{
cout << endl << "File I/O or Access exception";
return FILEOPENERR;
}
priority_queue<string, vector<string>, CustomCompare> longnames_minheap;
string name = "";
while (getline(fs, name))
{
if (longnames_minheap.size() <= MINHEAPSIZE)
{
longnames_minheap.push(name);
}
else
{
if (name.length() > longnames_minheap.top().length())
{
longnames_minheap.pop();
longnames_minheap.push(name);
}
}
}
cout << endl << MINHEAPSIZE << " longest names in the list";
cout << endl;
while (longnames_minheap.size())
{
cout << longnames_minheap.top() << endl;
longnames_minheap.pop();
}
fs.close();
getchar();
return 0;
}
| true |
6922b450ff3c4773b41ed616434846418ee8e40e | C++ | AIBilly/Distributed-Temperature-Control-System | /SubMachine/room.h | UTF-8 | 474 | 2.578125 | 3 | [] | no_license | #ifndef ROOM_H
#define ROOM_H
#include<stdio.h>
class Room
{
private:
float temperature_Outside;
float temperature_Room;
int room_Num;
public:
Room(float temO,float temR,int num);
Room();
void setRoomN(int num);
void setOutT(float out_in);
void setRoomT(float room_in);
int getRoomN();
float getOutT();
float getRoomT();
protected:
void TempNatureDerease();
};
#endif // ROOM_H
| true |
27d42927831f9dd64aa076a65620048ee60acd1c | C++ | 1998factorial/leetcode | /virtual contest/contest91/distanceK.cpp | UTF-8 | 1,455 | 2.984375 | 3 | [] | no_license | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
vector<int> g[500];
class Solution {
public:
void dfs(vector<int>& ans, int from, int dis, vector<bool>& seen){
if(!dis){
ans.push_back(from);
return;
}
int n = g[from].size();
for(int i = 0; i < n; i++){
int node = g[from][i];
if(!seen[node]){
seen[node] = true;
dfs(ans,node,dis-1,seen);
}
}
}
vector<int> distanceK(TreeNode* root, TreeNode* target, int K) {
for(int i = 0; i < 500; i++)g[i].clear();
vector<int> ans;
queue<TreeNode*> q;
q.push(root);
int N = 0;
while(!q.empty()){
N++;
TreeNode* n = q.front();
q.pop();
if(n->left){
g[n->val].push_back(n->left->val);
g[n->left->val].push_back(n->val);
q.push(n->left);
}
if(n->right){
g[n->val].push_back(n->right->val);
g[n->right->val].push_back(n->val);
q.push(n->right);
}
}
vector<bool> seen(N);
seen[target->val] = true;
dfs(ans,target->val,K,seen);
return ans;
}
}; | true |
13e3d97e2312300cb25d24c231456a75c8b4e11f | C++ | jangwoo28/vending_machine | /widget.cpp | UTF-8 | 2,351 | 2.515625 | 3 | [] | no_license | #include "widget.h"
#include "ui_widget.h"
#include <QMessageBox>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
ui->pbCoffee->setEnabled(false);
ui->pbTea->setEnabled(false);
ui->pbCoke->setEnabled(false);
ui->pbReturn->setEnabled(false);
}
Widget::~Widget()
{
delete ui;
}
void Widget::changeMoney(int n){
money += n;
ui->lcdNumber->display(money);
}
void Widget::checkMoney(int m){
if(m>0){
ui->pbReturn->setEnabled(true);
}
else{
ui->pbReturn->setEnabled(false);
}
if(m>=100){
ui->pbCoffee->setEnabled(true);
}
if(m>=150){
ui->pbTea->setEnabled(true);
}
if(m>=200){
ui->pbCoke->setEnabled(true);
}
if(m<100){
ui->pbCoffee->setEnabled(false);
}
if(m<150){
ui->pbTea->setEnabled(false);
}
if(m<200){
ui->pbCoke->setEnabled(false);
}
}
void Widget::on_pb10_clicked()
{
changeMoney(10);
checkMoney(money);
}
void Widget::on_pb50_clicked()
{
changeMoney(50);
checkMoney(money);
}
void Widget::on_pb100_clicked()
{
changeMoney(100);
checkMoney(money);
}
void Widget::on_pb500_clicked()
{
changeMoney(500);
checkMoney(money);
}
void Widget::on_pbCoffee_clicked()
{
changeMoney(-100);
checkMoney(money);
QMessageBox msg;
msg.information(nullptr,"Buy Success","[Coffee]");
}
void Widget::on_pbTea_clicked()
{
changeMoney(-150);
checkMoney(money);
QMessageBox msg;
msg.information(nullptr,"Buy Success","[Tea]");
}
void Widget::on_pbCoke_clicked()
{
changeMoney(-200);
checkMoney(money);
QMessageBox msg;
msg.information(nullptr,"Buy Success","[Coke]");
}
void Widget::on_pbReturn_clicked()
{
int coin_500;
int coin_100;
int coin_50;
int coin_10;
QString res;
QString ret_money = QString::number(money);
QMessageBox msg;
coin_500 = money / 500;
coin_100 = money % 500 / 100;
coin_50 = money % 500 % 100 / 50;
coin_10 = money % 500 % 100 % 50 / 10;
res.sprintf("Total : %d\n500W : %d\n100W : %d\n50W : %d\n10W : %d\n",money,coin_500,coin_100,coin_50,coin_10);
msg.information(nullptr,"Return Money",res);
money = 0;
ui->lcdNumber->display(money);
checkMoney(money);
}
| true |
3f576db6afa912d7b2492883e695967f76d11923 | C++ | lxiaodongdong/practice | /list_traverse.h | UTF-8 | 337 | 2.671875 | 3 | [] | no_license | #pragma once
template < typename T>
void list<T>::traverse(void (*visit)(T &)){
for(ListNodePosi(T) p = header->succ;p != trailer; p = p->succ){
visit(p->data);
}
}
template< typename T >
template<typename VST> void list<T>::traverse(VST & visit){
for(ListNodePosi(T) p = header->succ;p != trailer; p = p->succ) visit(p->data);
} | true |
1b13f4ee3a5cf02889d2c24b9e94b38a11ed0bcb | C++ | NurullahGundogdu/Object-Oriented-Programming-Project-Cpp | /HW3-2017_Matrix_Operation/SparseVector.cpp | ISO-8859-9 | 5,269 | 3.21875 | 3 | [] | no_license | #include "SparseVector.h"
#include <fstream>
#include <iostream>
using namespace std;
SparseVector::SparseVector()
{
}
SparseVector::SparseVector(string vectorFilename){
int a;
double b;
char c;
setFilename(vectorFilename);
ifstream file;
file.open(getFilename()); //okunucak dosya acilir
if(!file.is_open()){
cout<<"Error opening file"<<endl; //dosya acilip acilmama kotrolu yapilir
return;
}
while(!file.eof()){
file>>a>>c>>b; //dosyadan vektor okunur
data.push_back(b);
index.push_back(a);
}
file.close();
}
ostream& operator<<(ostream & output, const SparseVector &vec1){
for(int i=0; i<vec1.index.size(); i++)
output<<vec1.index[i]<<":"<<vec1.data[i]<<" "; //vektor output dosyasna yazadirilir
output<<endl;
return output;
}
SparseVector::SparseVector(vector<double> v,vector<int> v1){
for(int i=0; i<v.size(); i++){
data.push_back(v[i]); //constructor yeni obje olusturur
index.push_back(v1[i]);
}
}
const SparseVector SparseVector::operator +(const SparseVector& vec1){
int theSize, a=0, b=0, count = 0;
int sum = data.size() + vec1.data.size();
vector<double> tempData;
vector<int> tempIndex;
if(data.size() > vec1.data.size())
theSize = data.size();
else
theSize = vec1.data.size();
//yeni vektor icin size hesaplanir
for(int i = 0; i < theSize; i++)
if(index[i]==vec1.index[i])
count++;
sum -= count;
for(int i = 0; i < sum; i++)
if(index[a]==vec1.index[b]){
if(data[a]+vec1.data[b]==0){
a++;
b++;
continue; //indexlerin esitlik durumuna gore toplama ilemi yapilir ve yeni vektore atanir
}
tempIndex.push_back(index[a]);
tempData.push_back(data[a]+vec1.data[b]);
a++;
b++;
}else
if(index[a]>vec1.index[b]){
tempIndex.push_back(vec1.index[b]);
tempData.push_back(vec1.data[b]);
b++;
}else{
tempIndex.push_back(index[a]);
tempData.push_back(data[a]);
a++;
}
return SparseVector(tempData , tempIndex );
}
const SparseVector SparseVector::operator -(const SparseVector& vec1){
int theSize, a=0, b=0, count = 0;
int sum = data.size() + vec1.data.size();
vector<double> tempData;
vector<int> tempIndex;
if(data.size() > vec1.data.size())
theSize = data.size();
else
theSize = vec1.data.size(); //yeni vektor icin size hesaplanir
for(int i = 0; i < theSize; i++)
if(index[i]==vec1.index[i])
count++;
sum -= count;
for(int i = 0; i < sum; i++)
if(index[a]==vec1.index[b]){ //indexlerin esitlik durumuna gore ckaarma ilemi yapilir ve yeni vektore atanir
if(data[a]-vec1.data[b]==0){
a++;
b++;
continue;
}
tempIndex.push_back(index[a]);
tempData.push_back(data[a]-vec1.data[b]);
a++;
b++;
}else
if(index[a]>vec1.index[b]){
tempIndex.push_back(vec1.index[b]);
tempData.push_back((0-vec1.data[b]));
b++;
}else{
tempIndex.push_back(index[a]);
tempData.push_back(data[a]);
a++;
}
return SparseVector(tempData , tempIndex );
}
const SparseVector SparseVector::operator -(){
vector<double> tempData;
for(int i = 0; i < data.size(); i++){
tempData.push_back(data[i]);
}
for(int i = 0; i < tempData.size(); i++){ //vektorun data degerleri 0 dn cikarilir ve kendisine atanr
data.pop_back();
}
for(int i=0; i<tempData.size(); i++)
data.push_back(0-tempData[i]);
return SparseVector(data ,index);
}
const SparseVector SparseVector::operator =(const SparseVector& vec1){
for(int i=0; i<vec1.data.size(); i++){ //gelen vektorun atama islemi yapilir
data.push_back(vec1.data[i]);
index.push_back(vec1.index[i]);
}
return *this;
}
double dot(SparseVector v1, SparseVector v2){
int a=0, b=0, theSize;
double sumDot=0;
if(v1.data.size() > v2.data.size())
theSize = v1.data.size();
else
theSize = v2.data.size(); //vektorlerin ayni indekslerindeki datalari birbiriyle carpilir ve toplanir
for(int i=0; i<theSize; i++){
if(v1.index[a]==v2.index[b]){
sumDot+=v1.data[i]*v2.data[b];
a++;
b++;
}else
if(v1.index[a]>v2.index[b])
b++;
else
a++;
}
return sumDot;
}
| true |
e47d49d7f10c09287bb3c380ac0cafac7dd1341f | C++ | glemerenb/Kernigan-Ritchi | /K-R 1.8/K-R 1.8/Source.cpp | UTF-8 | 339 | 3.421875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int c;
int tab = 0;
int space = 0;
int end = 0;
while ((c = getchar()) != EOF) {
if (c == '\t') {
++tab;
}
if (c == ' ') {
++space;
}
}
if (c == EOF) {
++end;
}
cout << "tab: " << tab << "\tspace: " << space << " end: " << end;
}
| true |
45bdd6d32561349bc0a64fd13407f4213a1ea48d | C++ | rfeynman/jklib | /microsleep.cxx | UTF-8 | 330 | 2.625 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
void microsleep(int sec, int usec)
{
struct timeval tv;
tv.tv_sec = sec;
tv.tv_usec = usec;
int retval = select(1, NULL, NULL, NULL, &tv);
/* Don't rely on the value of tv now! */
}
| true |
9807a617d9e4d94229d8f03ffb9acba8dcdf1d22 | C++ | yifatBi/cppCalendar | /MyDate.h | UTF-8 | 1,915 | 3.515625 | 4 | [] | no_license | /*
This Class handle Date and manipulate the date
*/
/*
* File: MyDate.h
* Author: Yifat Biezuner
*
* Created on 08 March 2016, 17:41
*/
#ifndef MYDATE_H
#define MYDATE_H
#define DAY_SUBMISSION 21
#define MONTH_SUBMISSION 3
#define YEAR_SUBMISSION 2016
#include <iostream>
class MyDate {
private:
int _day;
int _month;
int _year;
char* _comment;
//Given day and month and chak if the February is valid
bool isValidFebruary(int day,int month)const;
// Check the validity of the day
bool isValidDay(int day,int month);
//Check the validity of the month
bool isValidMonth(int month);
//Check the validity of the year
bool isValidYear(int year);
public:
MyDate();
//Change date with month according to the given number
bool changeMonth(int month);
//Init the date with the submission date
void init(){set(DAY_SUBMISSION,MONTH_SUBMISSION,YEAR_SUBMISSION);};
//Set the date according to given numbers if all valid
bool set(const int day,const int month,const int year);
//set day if valid
bool setDay(int day);
//set month if valid
bool setMonth(int month);
//set year if valid
bool setYear(int year);
//Check if the given date is before the current date
bool isBefore(MyDate& dateCompare)const;
//Move the date in given days forward to the future
bool delay(int shiftDays);
//Move the date in given days backward to the past
bool bringForward(int backDays);
//Print current day
void print()const{ std::cout << _day << "/" << _month << "/" << _year << std::endl;}
//Change date according to given days return if new date is valid and changed successfuly
bool changeDate(int day);
// Update the comment if length is valid
void changeComment(char* str);
// Print comment for check
void printComment()const;
virtual ~MyDate();
};
#endif /* MYDATE_H */
| true |
85b690113dacf25c9847e82e73f9890f468e58ca | C++ | osama-afifi/Online-Judges-Solutions | /TopCoder/TopCoder/SRM 563.cpp | UTF-8 | 928 | 2.90625 | 3 | [] | no_license | // 250
class FoxAndHandleEasy
{
public:
string isPossible(string S, string T)
{
int pos=temp.find(S);
if(pos==-1)return"No";
else
{
for(int i = 0; i<T.length();i++)
{
string temp = T.substr(0,i)+S+T.substr(i,T.length()-1-i);
if(temp==T)
return "YES";
}
return "No";
}
}
};
// 1000
class SpellCardsEasy {
public:
int dp[107][107];
int solve(vector <int> &level, vector <int> &damage , int index, int left)
{
if(left>=level.size()-index)return 0;
if(index>=level.size())return 0;
if(dp[index][left]!=-1)return dp[index][left];
int s1=0,s2=0;
s1=solve(level, damage, index+1, max(left-1,0));
if(left+level[index]-1<=level.size()-index-1)
s2=solve(level,damage,index+1,left+level[index]-1)+damage[index];
return dp[index][left]=max(s1,s2);
}
int maxDamage(vector <int> level, vector <int> damage)
{
memset(dp,-1,sizeof dp);
return solve(level,damage,0,0);
}
};
| true |
b88e7b5d5cdd5ff7496862e25c3e60dc772db7f1 | C++ | mdelorme/advent_of_code | /2020/07.cpp | UTF-8 | 1,690 | 3.125 | 3 | [
"Unlicense"
] | permissive | #include <bits/stdc++.h>
using Bag = std::string;
using Storage = std::pair<Bag, int>;
std::map<Bag, std::vector<Storage>> bags;
Bag readBag(std::istream &is) {
Bag b;
std::string type, color;
is >> type >> color;
b = type + " " + color;
return std::move(b);
}
bool findShiny(std::string bag) {
if (bag == "shiny gold")
return true;
for (auto [b, n]: bags[bag]) {
if (findShiny(b))
return true;
}
return false;
}
uint countSubBags(std::string bag) {
uint tot = 0;
for (auto [b, n] : bags[bag])
tot += n * (countSubBags(b) + 1);
return tot;
}
void part1() {
uint tot = 0;
for (auto [b, v]: bags) {
if (b != "shiny gold")
tot += findShiny(b);
}
std::cout << "Part 1 : " << tot << std::endl;
}
void part2() {
uint tot = countSubBags("shiny gold");
std::cout << "Part 2 : " << tot << std::endl;
}
int main(int argc, char **argv) {
std::ifstream f_in;
f_in.open("07.in");
while (true) {
Bag bag = readBag(f_in);
if (!f_in.good())
break;
std::string tmp;
f_in >> tmp >> tmp; // bag contains
std::string line;
std::getline(f_in, line);
std::istringstream iss(line);
while (true) {
int qty;
Bag b;
std::string first, type, color, term;
iss >> first;
b = readBag(iss);
if (!iss.good())
break;
iss >> term;
qty = std::stoi(first);
bags[bag].push_back(std::make_pair(b, qty));
if (bags.find(b) == bags.end()) {
bags[b].resize(0); // Making sure the name appears in the map keys
}
if (term.back() == '.')
break;
}
}
f_in.close();
part1();
part2();
return 0;
} | true |
252e696dc528f58d152ddba2b763520a5fe5f407 | C++ | maiducgiang/CTDLVGT | /DSA03012.cpp | UTF-8 | 903 | 2.53125 | 3 | [] | no_license | #include<bits/stdc++.h>
#include<vector>
#include<string>
using namespace std;
void solve(){
string s, s1 = "";
cin>>s;
int code = 1;
vector <char> c;
vector <int> a;
for(int i = 0; i < s.length(); i++)
{
int code = 0;
if(c.size() == 0){
c.push_back(s[i]);
a.push_back(1);
}
else{
for(int j = 0; j < c.size(); j++)
if(c[j] == s[i]){
code = 1;
a[j] += 1;
break;
}
if(code == 0){
c.push_back(s[i]);
a.push_back(1);
}
}
}
sort(a.begin(), a.end());
cout<<a[a.size() - 1]<<endl;
if(s.length() < a[a.size() - 1] * 2) cout<<-1;
else{
int x = s.length()/a[a.size() - 1], n = s.length();
vector <int> b(n + 1, 0);
for(int i = 1; i <= x * a[a.size() - 1]; i++) if(i % x == 1) b[i] = 1;
for(int i = 1; i <= n; i++) cout<<b[i]<<" "; cout<<endl;
}
}
int main(){
int t;
cin>>t;
while(t--){
solve();
cout<<endl;
}
}
| true |
f4361753a74345755b715f9914959c8d6acb4cad | C++ | deejayslay/Graphing-Algorithms | /graph_algorithms.cpp | UTF-8 | 4,664 | 2.828125 | 3 | [] | no_license | #include "graph.h"
#include <iostream>
#include <map>
#include <list>
#include <algorithm>
#include <deque>
#include <vector>
#include <random>
int get_diameter(Graph graph)
{
int dMax = 0;
std::pair<int, int> furthest;
auto it = graph.adj.begin();
std::advance(it, rand() % graph.adj.size());
int r = it->first;
while (true)
{
furthest = graph.BFS(r);
if (furthest.first > dMax)
{
dMax = furthest.first;
r = furthest.second;
}
else
{
break;
}
}
return dMax;
}
float get_clustering_coefficient(Graph graph)
{
// linear algorithm
// std::cout << r;
// std::cout << ", ";
// std::cout << furthest.first << std::endl;
// degeneration
std::deque<int> l;
std::map<int, bool> hashL;
std::map<int, int> d;
std::map<int, std::list<Node>> bigD;
std::map<int, std::list<int>> bigN;
for (auto const& x : graph.adj)
{
d[x.first] = x.second.size();
bigD[x.second.size()].push_back(Node(x.first));
hashL[x.first] = false;
}
int k = 0;
int smallestIndex;
Node v;
for (unsigned int i=0; i < graph.n; ++i)
{
// find smallest index in bigD
for (unsigned int j=0; j < bigD.size(); ++j)
{
if (bigD[j].size() != 0) // if nonempty
{
smallestIndex = j;
break;
}
}
// set k
if (smallestIndex > k)
{
k = smallestIndex;
}
// select vertex v
v = bigD[smallestIndex].front();
// mark v as being in L
hashL[v.id] = true;
// if v not in L
l.push_front(v.id);
bigD[smallestIndex].remove(v);
// for each neighbor w of v
for (auto const& w : graph.adj[v.id])
{
// if w not in L
if (hashL[w.id] == false)
{
d[w.id] -= 1;
bigD[d[w.id]].push_back(Node(w));
bigN[v.id].push_back(w.id);
}
}
}
// triangle counting
int triangleCt, vertex;
std::list<Node> adjacency;
triangleCt = 0;
std::list<Node>::iterator u;
std::list<Node>::iterator w;
for (int i=l.size()-1; i >= 0; --i)
{
vertex = l[i];
adjacency = graph.adj[vertex];
// for each pair of vertices, u and w
for (auto u = adjacency.begin(); u != adjacency.end(); ++u)
{
auto w = u;
++w;
for (; w != adjacency.end(); ++w)
{
if (std::find(bigN[vertex].begin(), bigN[vertex].end(), u->id) != bigN[vertex].end())
{
if (std::find(bigN[vertex].begin(), bigN[vertex].end(), w->id) != bigN[vertex].end())
{
// if (u, w) an edge in the graph
if (std::find(graph.adj[u->id].begin(), graph.adj[u->id].end(), Node(w->id)) != graph.adj[u->id].end())
{
++triangleCt;
}
}
}
}
}
}
// compute denominator
int denom, lengthTwoPaths;
denom = 0;
for (auto const& v : graph.adj)
{
lengthTwoPaths = (v.second.size() * (v.second.size() - 1))/2;
denom += lengthTwoPaths;
}
int numerator = (3 * triangleCt);
float bigC = ((float)numerator/(float)denom);
return bigC;
// O(n^3) algorithm
// int triangleCt, maxEdges, hashIndex, hashIndex1, hashIndex2;
// maxEdges = (graph.n*(graph.n-1))/2;
// std::vector<int> hashTable[maxEdges];
// for (auto const& v : graph.adj)
// {
// for (auto const& w : v.second)
// {
// hashIndex = (v.first % maxEdges);
// hashTable[hashIndex].push_back(w.id);
// }
// }
// std::vector<int> mappings;
// triangleCt = 0;
// for (auto u = graph.adj.begin(); u != graph.adj.end(); ++u)
// {
// auto v = u;
// ++v;
// for (; v != graph.adj.end(); ++v)
// {
// auto w = v;
// ++w;
// for (; w != graph.adj.end(); ++w)
// {
// // check (u, v)
// hashIndex = (u->first % maxEdges);
// mappings = hashTable[hashIndex];
// if( std::find(mappings.begin(), mappings.end(), v->first) != mappings.end())
// {
// // check (u, w)
// mappings = hashTable[hashIndex];
// if( std::find(mappings.begin(), mappings.end(), w->first) != mappings.end())
// {
// // check (u, v)
// hashIndex = (v->first % maxEdges);
// mappings = hashTable[hashIndex];
// if( std::find(mappings.begin(), mappings.end(), w->first) != mappings.end())
// {
// ++triangleCt;
// }
// }
// }
// }
// }
// }
// int denom, lengthTwoPaths;
// denom = 0;
// for (auto const& v : graph.adj)
// {
// lengthTwoPaths = (v.second.size() * (v.second.size() - 1))/2;
// denom += lengthTwoPaths;
// }
// int numerator = (3 * triangleCt);
// float bigC = ((float)numerator/(float)denom);
// return bigC;
}
std::map<int, int> get_degree_distribution(Graph graph)
{
std::map<int, int> answer;
for (auto const& v : graph.adj)
{
answer[v.second.size()] = 0;
}
for (auto const& v : graph.adj)
{
answer[v.second.size()] += 1;
}
return answer;
}
| true |
1ad0e813dfc2fdf2aa3bdb3af2edd20e7e0d9d30 | C++ | Sosnovskiy2116/oop-1 | /praks/пр 2/ооп пр 2.2.cpp | UTF-8 | 985 | 2.6875 | 3 | [] | no_license | #include "pch.h"
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int main() {
setlocale(LC_ALL, "Russian");
double t, z, a = -0.6, b = 5.3;
if (a < b) { z = pow(abs(a*a - b * b), (1.0 / 2)); }//proverka sootnoshenia a i b
else z = 1 - 2 * cos(a) *sin(b);
if (z < b) { t = pow((z + a * a*b), (1.0 / 3)); }//proverka sootnoshenia z i b
else if (z == b) { t = 1 - log10(z) + cos(a*a*b); }
else t = 1 / cos(z*a);
if (t != t) {//proverka na NAN
if (z != z) { cout << "pri ishodnih dannyh nevozmojno poschitat i t i z, " << "a= " << a << ", b= " << b << endl; }
else { cout << "pri ishodnih dannyh nevozmojno poschitat t, " << "a= " << a << ", b= " << b << ", z= " << z << endl; }
}
else if (z != z) { cout << "pri ishodnih dannyh nevozmojno poschitat z, " << "a= " << a << ", b= " << b << ", t= " << t << endl; }
else cout << "a= " << a << ", b= " << b << ", z= " << z << ", t= " << t << endl;
system("pause");
return 0;
} | true |
64d586be6f5b952b14ac2ec9503f69b8f0d625b3 | C++ | GeroZeppeli/- | /跳台阶/跳台阶.cpp | UTF-8 | 251 | 2.875 | 3 | [] | no_license | #include<iostream>
using namespace std;
void main()
{
int a=1,b=2,c,n,x;
cin>>n;
if(n==1)
x=1;
else if(n==2)
x=2;
else
{
for(n;n>2;n--)
{
c=a+b;
a=b;
b=c;
}
x=c;
}
cout<<x<<endl;
} | true |
5138482e55d9acf79cabbc0d1af25255c4d582f5 | C++ | xuwg/base | /D_Event.cpp | UTF-8 | 1,216 | 2.734375 | 3 | [] | no_license | #include "StdAfx.h"
#include "D_Event.h"
D_Event::D_Event(bool manualReset, bool initialState)
{
m_Event = ::CreateEvent(NULL, manualReset, initialState, NULL);
}
D_Event::~D_Event(void)
{
::CloseHandle(m_Event);
}
bool D_Event::Set()
{
return (::SetEvent(m_Event) == TRUE);
}
bool D_Event::Reset()
{
return (::ResetEvent(m_Event) == TRUE);
}
bool D_Event::Wait()
{
switch(::WaitForSingleObject(m_Event, INFINITE))
{
case WAIT_OBJECT_0:
return true;
default:
return false;
}
}
bool D_Event::Wait(unsigned long milliSeconds)
{
if (milliSeconds > 3600*1000)
return WaitVeryLongTime(milliSeconds);
switch(::WaitForSingleObject(m_Event, milliSeconds))
{
case WAIT_OBJECT_0:
return true;
case WAIT_TIMEOUT:
return false;
default:
return false;
}
}
bool D_Event::WaitVeryLongTime(unsigned long milliSeconds) {
const unsigned long kMaxOneWaitInterval = 3600*1000;
while (milliSeconds > 0) {
unsigned long wait_interval = min(milliSeconds, kMaxOneWaitInterval);
milliSeconds -= wait_interval;
switch(::WaitForSingleObject(m_Event, wait_interval))
{
case WAIT_OBJECT_0:
return true;
case WAIT_TIMEOUT:
continue;
default:
return false;
}
}
return false;
}
| true |
99e4d6a66cb4d88304ae455e168c514071e3eb9a | C++ | JokerSSmile/KPO | /Lab3/Lab3/Point.cpp | UTF-8 | 282 | 2.796875 | 3 | [] | no_license | #include "stdafx.h"
#include "Point.h"
CPoint::CPoint(int x, int y)
: m_x(x)
, m_y(y)
{
}
int CPoint::GetX() const
{
return m_x;
}
int CPoint::GetY() const
{
return m_y;
}
double CPoint::GetPerimeter() const
{
return 0.0;
}
double CPoint::GetArea() const
{
return 0.0;
}
| true |
7a27053d2ac7b9e5ae65378697e7319e98d25ff9 | C++ | MateoParrado/ArtificialIntelligence | /ArtificialIntelligence/SellState.cpp | UTF-8 | 602 | 2.75 | 3 | [] | no_license | #include "SellState.h"
#include "Fisherman.h"
#include "FishingState.h"
using namespace std;
SellState* SellState::instance = nullptr;
void SellState::enter(Fisherman* f)
{
f->display("going to the market to sell my fish");
f->setLocation(Location::MARKET);
}
void SellState::exit(Fisherman* f)
{
f->display("Leaving the market");
}
//sell the fish, gain money, and lose all the fish
void SellState::execute(Fisherman* f)
{
f->display("Selling my fish at the market!");
f->display("I sold them all, time to go back to fishing");
f->money += f->fish;
f->fish = 0;
f->changeState(Fish);
} | true |
9276a197546a76141579739bb225cba1a8a5951f | C++ | vmeno0020/CS-100-Final-Project | /main.cpp | UTF-8 | 1,159 | 3.265625 | 3 | [] | no_license | #include "src/SudokuBoard.cpp"
#include <iostream>
using namespace std;
int main() {
SudokuBoard* test;
char input = 'x';
cout << "Welcome to our Soduku game! Press 1 to start." << endl;
cin >> input;
if (input == '1') {
test = test->getInstance();
test->createGame();
test->printBoard();
} else {
cout << "Invalid input..exiting game. Bye!" << endl;
return 0;
}
input = 'x';
while (input != 'd') {
cout << endl << "Menu Controls:" << endl << "a - Make an entry" << endl << "b - View board" << endl <<
"c - Get current score" << endl << "d - Quit Game" << endl << "e - Show solution" <<endl;
cout << "Select an option:" << endl;
cin.clear();
cin >> input;
if (input == 'a') {
test->makeEntry();
} else if (input == 'b') {
test->printBoard();
} else if (input == 'c') {
test->getScore();
} else if (input == 'd') {
test->exitGame();
} else if(input == 'e'){
test->getSolution();
} else {
cout << "Invalid input! Please try again." << endl;
}
}
delete test;
return 0;
}
| true |
bc2dd3ecb8c3300e05cbce37293461b98588d547 | C++ | hjw21century/Algorithm | /LeetCode/CountSortedVowelStrings/main.cxx | UTF-8 | 904 | 2.984375 | 3 | [] | no_license | #include <bits/stdc++.h>
#include <gtest/gtest.h>
using namespace std;
class Solution {
public:
int countVowelStrings(int n) {
return count(5, n);
}
private:
map<pair<int, int>, int> mm;
int count(int v, int n) {
if (v == 1) return 1;
if (n == 1) return v;
auto f = mm.find({v, n});
if (f != mm.end()) return f->second;
int ret = 0;
for (int i = 0; i < v; i++) {
ret += count(v - i, n - 1);
}
mm[{v, n}] = ret;
return ret;
}
};
struct T {
};
TEST(Solution, test) {
T ts[] = {
{
},
};
for (T t : ts) {
Solution solution;
int n;
while (true) {
cin >> n;
cout << solution.countVowelStrings(n) << endl;
}
}
}
int main() {
testing::InitGoogleTest();
return RUN_ALL_TESTS();
}
| true |
966db51f3fc4fa7862ca68b27384abcf96b41148 | C++ | syshim77/FirstTouch | /2017년 1학기/study 17-2/study 17-2/1932_2.cpp | UTF-8 | 663 | 2.703125 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int n, res;
int tri[501][501] = { 0 };
int sum[501][501] = { 0 };
cin >> n;
for (int i = 0; i < n; i++)
{
for (int j = 0; j <= i; j++)
cin >> tri[i][j];
}
sum[0][0] = tri[0][0];
for (int i = 1; i < n; i++)
{
for (int j = 0; j <= i; j++)
{
if (j == 0)
sum[i][j] = sum[i - 1][j] + tri[i][j];
else if (j == i)
sum[i][j] = sum[i - 1][j - 1] + tri[i][j];
else
sum[i][j] = max(sum[i - 1][j - 1], sum[i - 1][j]) + tri[i][j];
}
}
res = sum[n - 1][0];
for (int i = 1; i < n; i++)
{
res = max(res, sum[n - 1][i]);
}
cout << res;
return 0;
} | true |
2c5c55bc208d8a1d5b428cd51ad548e3eb15bc69 | C++ | intheory0/data_structures | /heap.h | UTF-8 | 344 | 2.75 | 3 | [] | no_license | #ifndef HEAP_H
#define HEAP_H
class Heap
{
private:
int *arr;
int size;
int capacity;
public:
Heap();
Heap(Heap &h);
Heap(int capacity);
Heap(int *arr, int capacity);
void insert(int value);
void shift_down(int i);
void shift_up(int i);
void merge(Heap &h);
void make_heap();
int get_min();
};
#endif
| true |
42eea56a4a2ac01abec89cbe67a7ac814aa9b302 | C++ | asyncvlsi/SPRoute | /include/lefDataBase.h | UTF-8 | 9,444 | 2.703125 | 3 | [
"BSD-3-Clause"
] | permissive | #ifndef LEFDATABASE_H
#define LEFDATABASE_H
#include "header.h"
#include "sprouteDataType.h"
namespace sproute_db
{
class ViaRuleGenerateLayer
{
public:
string layerName;
Rect2D<float> rect;
Size2D<float> spacing;
Size2D<float> enclosureOverhang;
ViaRuleGenerateLayer( ) { }
void print()
{
cout << " layer: " << layerName << endl;
if(!rect.empty())
{
cout << " RECT:";
rect.print();
}
if(!spacing.empty())
{
cout << " SPACING: ";
spacing.print();
}
if(!enclosureOverhang.empty())
{
cout << " ENC: ";
enclosureOverhang.print();
}
}
};
class ViaRuleGenerate
{
public:
string name;
bool isDefault;
ViaRuleGenerateLayer layers[3];
ViaRuleGenerate() {
isDefault = true;
}
void print()
{
cout << "VIARULE: " << name << endl;
for(int i = 0; i < 3; i++)
{
layers[i].print();
}
}
};
class PropertyDef
{
public:
string objectType;
string propName;
string propType;
PropertyDef() { }
PropertyDef(string objType, string propName, string propType) {
this->objectType = objType;
this->propName = propName;
this->propType = propType;
}
};
class SpacingTable
{
public:
int numCols;
int numRows;
std::vector<float> parallelRunLength;
std::vector<float> width;
std::vector<float> spacing;
SpacingTable() { }
SpacingTable(int numCols, int numRows) {
this->numCols = numCols;
this->numRows = numRows;
}
void setSize(int numCols, int numRows) {
this->numCols = numCols;
this->numRows = numRows;
}
void reset()
{
numCols = 0;
numRows = 0;
parallelRunLength.clear();
width.clear();
spacing.clear();
}
void print()
{
cout << "numCols: " << numCols << " numRows: " << numRows << endl;
cout << " parallelRunLength:" ;
for(auto p : parallelRunLength)
{
cout << p << " ";
}
cout << endl;
cout << " width:" ;
for(auto w : width)
{
cout << w << " ";
}
cout << endl;
cout << " spacing:" ;
for(auto s : spacing)
{
cout << s << " ";
}
cout << endl;
}
float getSpacing(int col, int row)
{
return spacing.at(col + row*numCols);
}
};
class Spacing //only EOL spacing for now
{
public:
//metal layer
float spacing;
float eolWidth;
float eolWithin;
float parEdge;
float parWithin;
//cut layer
int adjacentCuts;
float cutWithin;
Spacing ()
{
spacing = 0;
eolWidth = 0;
eolWithin = 0;
parEdge = 0;
parWithin = 0;
adjacentCuts = 0;
cutWithin = 0;
}
void reset()
{
spacing = 0;
eolWidth = 0;
eolWithin = 0;
parEdge = 0;
parWithin = 0;
adjacentCuts = 0;
cutWithin = 0;
}
void print()
{
cout << " spacing: " << spacing << " eolWidth: " << eolWidth << " eolWithin: " << eolWithin << endl;
cout << " parEdge: " << parEdge << " parWithin: " << parWithin << endl;
cout << " adjacentCuts: " << adjacentCuts << " cutWithin: " << cutWithin << endl;
}
};
class Property
{
public:
string propName;
string propString;
};
class CornerSpacing
{
public:
float eolWidth;
std::vector<float> width;
std::vector<float> spacing;
CornerSpacing() {
eolWidth = 0;
}
void reset()
{
eolWidth = 0;
width.clear();
spacing.clear();
}
void print()
{
cout << "cornerSpacing eolWidth: " << eolWidth << endl;
cout << "width: ";
for(auto w : width)
{
cout << " " << w;
}
cout << endl;
cout << "spacing: ";
for(auto s : spacing)
{
cout << " " << s;
}
cout << endl;
}
};
class Layer
{
public:
string name;
string type;
int idx;
//metal layer
string direction;
float pitchx;
float pitchy;
float width;
float area;
float minWidth;
float offset;
SpacingTable spacingTable;
std::vector<Spacing> spacings;
Spacing maxEOLSpacing;
CornerSpacing cornerSpacing;
//cut layer
float spacing;
void reset()
{
name = "";
type = "";
idx = 0;
direction = "";
pitchx = 0;
pitchy = 0;
width = 0;
area = 0;
minWidth = 0;
offset = 0;
spacingTable.reset();
spacings.clear();
cornerSpacing.reset();
spacing = 0;
}
void print()
{
cout << "------------------------------" << endl;
cout << "Layer: " << name << " type: " << type << " direction: " << direction << " idx: " << idx << endl;
cout << "pitch: " << pitchx << " " << pitchy << " width:" << width << " area: " << area << endl;
cout << "minWidth: " << minWidth << " offset: " << offset << " spacing: " << spacing << endl;
if(spacingTable.parallelRunLength.size())
spacingTable.print();
for(auto spacing : spacings)
{
spacing.print();
}
if(cornerSpacing.width.size())
cornerSpacing.print();
}
};
class LayerRect
{
public:
string layerName;
std::vector<Rect2D<float>> rects;
void print()
{
cout << " layer rect : layer " << layerName << endl;
for(auto rect : rects)
rect.print();
}
void reset()
{
layerName = "";
rects.clear();
}
};
class lefVia
{
public:
string name;
bool isDefault;
std::vector<LayerRect> layerRects;
void reset()
{
name = "";
isDefault = false;
layerRects.clear();
}
void print()
{
cout << " Via name: " << name << endl;
for(auto l : layerRects)
l.print();
}
};
class Site
{
public:
string name;
string className;
float width;
float height;
void print()
{
cout << name << " " << className << " " << width << " " << height << endl;
}
};
class Pin
{
public:
string name;
string direction;
string output_tristate;
string use;
string shape;
float antennaDiffArea;
string antennaDiffAreaLayer;
std::vector<string> netExpr;
std::vector<LayerRect> layerRects; // one layer is an element in the vector
void print()
{
cout << "pin name: " << name << " direction: " << direction << endl;
for(auto layerRect : layerRects)
layerRect.print();
}
};
class Obstacle
{
public:
std::vector<LayerRect> layerRects; // one layer is an element in the vector
void reset()
{
layerRects.clear();
}
void print()
{
for(auto layerRect : layerRects)
layerRect.print();
}
};
class Macro
{
public:
string name;
Point2D<float> origin;
Point2D<float> size;
std::vector<Pin> pins;
Obstacle obs;
Macro() {}
void reset()
{
name = "";
origin.reset();
size.reset();
pins.clear();
obs.reset();
}
void setOrigin(float x, float y)
{
origin.x = x;
origin.y = y;
}
void setSize(float x, float y)
{
size.x = x;
size.y = y;
}
void print()
{
cout << "macro name: " << name << endl;
cout << "origin point: " << endl;
origin.print();
cout << "size: " << endl;
size.print();
cout << "width: " << size.x << "height: " << size.y << endl;
cout << "Pins: ";
for(auto pin : pins)
pin.print();
}
};
class Unit
{
public:
string types;
string unit;
int factors;
Unit() {}
Unit(string types, string unit, int factors):
types(types), unit(unit), factors(factors) {}
};
class lefDataBase
{
public:
std::vector<Unit> units;
std::vector<PropertyDef> properties;
std::vector<Layer> layers;
std::vector<lefVia> vias;
std::vector<Site> sites;
std::vector<Macro> macros;
std::vector<ViaRuleGenerate> viaRuleGenerates;
string version;
string busBitChars;
string dividerChar;
int dbuPerMicron;
double manufacturingGrid;
std::map<string, int> layer2idx;
std::map<string, int> macro2idx;
std::map<string, int> lefVia2idx;
std::map<string, int> viaRuleGenerate2idx;
Macro tmpMacro;
Layer tmpLayer;
};
/*int getLefMacros(lefrCallbackType_e , lefiMacro* , lefiUserData );
int getLefString(lefrCallbackType_e , const char* , lefiUserData );
int getLefUnits(lefrCallbackType_e , lefiUnits* , lefiUserData );
int getLefManufacturingGrid(lefrCallbackType_e , double , lefiUserData );
int getLefPins(lefrCallbackType_e , lefiPin* , lefiUserData );
int getLefObs(lefrCallbackType_e , lefiObstruction* , lefiUserData );
int getLefLayers(lefrCallbackType_e , lefiLayer* , lefiUserData );
int getLefVias(lefrCallbackType_e , lefiVia* , lefiUserData );
int getLefViaGenerateRules(lefrCallbackType_e , lefiViaRule* , lefiUserData );*/
} //namespace sproute_db
#endif
| true |
0be9a36fcd0f938bb36ea9c05f3ad42fc7f2dae4 | C++ | estifanos-si/Ares | /include/utils/game/game.hh | UTF-8 | 3,122 | 3.03125 | 3 | [] | no_license | #ifndef GAME_HH
#define GAME_HH
#include "utils/gdl/clause.hh"
#include "utils/memory/namer.hh"
#include "utils/threading/locks.hh"
#include "utils/utils/hashing.hh"
#include <iostream>
#include <thread>
#include <unordered_map>
namespace ares
{
class State;
typedef const Term Move;
typedef const Term Role;
typedef std::vector<Move*> Moves;
typedef std::vector<Role*> Roles;
typedef Moves Action;
typedef std::unique_ptr<Action> uAction;
typedef std::unique_ptr<const Action> ucAction;
typedef std::unique_ptr<Moves> uMoves;
typedef UniqueVector<const Clause*, ClauseHasher, ClauseHasher>
UniqueClauseVec;
struct KnowledgeBase {
KnowledgeBase() {}
KnowledgeBase(const KnowledgeBase&) = delete;
KnowledgeBase& operator=(const KnowledgeBase&) = delete;
KnowledgeBase(const KnowledgeBase&&) = delete;
KnowledgeBase& operator=(const KnowledgeBase&&) = delete;
virtual const UniqueClauseVec* operator[](ushort name) const = 0;
virtual bool add(ushort name, Clause*) = 0;
virtual ~KnowledgeBase() {}
protected:
SpinLock slock;
};
class Game : public KnowledgeBase
{
private:
/*A mapping from head names --> [clauses with the same head name]*/
std::unordered_map<ushort, UniqueClauseVec*> rules;
Roles roles_;
State* init_;
public:
Game(/* args */) : init_(nullptr) {}
virtual const UniqueClauseVec* operator[](ushort name) const
{
const UniqueClauseVec* v = nullptr;
try {
v = rules.at(name);
} catch (const std::exception& e) {
std::cerr << e.what() << '\n';
}
return v;
}
virtual bool add(ushort name, Clause* c)
{
std::lock_guard<SpinLock> lk(slock);
if (rules.find(name) == rules.end())
rules[name] = new UniqueClauseVec();
return rules[name]->push_back(c);
}
std::unordered_map<ushort, UniqueClauseVec*>::iterator begin()
{
return rules.begin();
}
std::unordered_map<ushort, UniqueClauseVec*>::iterator end()
{
return rules.end();
}
std::unordered_map<ushort, UniqueClauseVec*> getRules()
{
return rules;
}
/**
* The roles are static wihin a game no need to compute them.
*/
const Roles& roles() const { return roles_; }
void addRole(const Role* r) { roles_.push_back(r); }
/**
* set the initial state
*/
void init(State* s) { init_ = s; }
/**
* get the initial state
*/
const State* init() const { return init_; }
std::string toString()
{
std::string s;
for (auto&& [name, vec] : rules) {
for (auto&& i : *vec) s.append(i->to_string() + " ");
}
return s;
}
virtual ~Game();
};
} // namespace ares
#endif | true |
5d02a54ffcbaace00297cdf56aa64e733b87d52f | C++ | wuxiang/servercode | /pushServer/src/process/model/selfstock/StkCodeOperate.cpp | GB18030 | 3,967 | 2.703125 | 3 | [] | no_license | #include "StkCodeOperate.h"
#include "../../../util/util.h"
// תС
static const int MaxExchangeBufSize = 1280;
// ʽַĬϳ
static const short DefaultFormatLen = 128;
CStkCodeOperate::CStkCodeOperate(const unsigned short AlignLen)
: m_uAlignLen(AlignLen)
{
}
CStkCodeOperate::~CStkCodeOperate(void)
{
}
// Ӵ
const int
CStkCodeOperate::AddCode(const char *StkCode, char *OutBuf, unsigned int &OccupySize,
const unsigned int MaxBufSize)
{
char cExcBuf[MaxExchangeBufSize] = {0};
if (NULL == StkCode || NULL == OutBuf)
{
return -1;
}
char cFormat[DefaultFormatLen] = {0};
snprintf(cFormat, DefaultFormatLen, "%%%us", m_uAlignLen);
int iRes = 0;
char cCode[16] = {0};
iRes = snprintf(cCode, m_uAlignLen + 1, cFormat, StkCode);
if ((unsigned int)iRes > m_uAlignLen)
{
return -2;
}
char *pFind = strstr(OutBuf, cCode);
if (NULL == pFind)
{
if (OccupySize < MaxBufSize)
{
iRes = snprintf(cExcBuf, MaxExchangeBufSize, "%s%s", cCode, OutBuf);
if (iRes > MaxExchangeBufSize)
{
return -3;
}
OccupySize += m_uAlignLen;
}
else if (OccupySize == MaxBufSize)
{
iRes = snprintf(cExcBuf, MaxExchangeBufSize, "%s", cCode);
strncat(cExcBuf, OutBuf, OccupySize - m_uAlignLen);
}
else
{
return -4;
}
}
else
{
int iRemainLen = OccupySize - strlen(pFind);
iRes = snprintf(cExcBuf, MaxExchangeBufSize, "%s", cCode);
if (iRemainLen > 0)
{
strncat(cExcBuf, OutBuf, iRemainLen);
}
pFind += m_uAlignLen;
if (NULL != pFind && '\0' != *pFind)
{
strcat(cExcBuf, pFind);
}
}
memset(OutBuf, 0, MaxBufSize);
strncpy(OutBuf, cExcBuf, MaxBufSize);
return 0;
}
// ɾ
const int
CStkCodeOperate::RemoveCode(const char *StkCode, char *OutBuf, unsigned int &OccupySize,
const unsigned int MaxBufSize)
{
char cExcBuf[MaxExchangeBufSize] = {0};
if (NULL == StkCode || NULL == OutBuf)
{
return -1;
}
char cFormat[DefaultFormatLen] = {0};
snprintf(cFormat, DefaultFormatLen, "%%%us", m_uAlignLen);
int iRes = 0;
char cCode[16] = {0};
iRes = snprintf(cCode, m_uAlignLen + 1, cFormat, StkCode);
if (iRes > m_uAlignLen)
{
return -2;
}
char *pFind = strstr(OutBuf, cCode);
if (NULL == pFind)
{
return -3;
}
int iRemainLen = OccupySize - strlen(pFind);
if (iRemainLen > 0)
{
strncat(cExcBuf, OutBuf, iRemainLen);
}
pFind += m_uAlignLen;
if (NULL != pFind && '\0' != *pFind)
{
strcat(cExcBuf, pFind);
}
OccupySize -= m_uAlignLen;
memset(OutBuf, 0, MaxBufSize);
strncpy(OutBuf, cExcBuf, MaxBufSize);
return 0;
}
// շ
const int
CStkCodeOperate::ClearAllCode(char *OutBuf, unsigned int &OccupySize,
const unsigned int MaxBufSize)
{
if (NULL == OutBuf)
{
return -1;
}
memset(OutBuf, 0, MaxBufSize);
OccupySize = 0;
return 0;
}
// ȡָг
const char*
CStkCodeOperate::ReadIndexCode(const char *SrcBuf, const unsigned int OccupySize,
const unsigned int CodeIndex, char *OutBuf, const unsigned int BufSize)
{
int iCount = OccupySize / m_uAlignLen;
if (iCount <= 0 || NULL == SrcBuf)
{
return NULL;
}
if (NULL == OutBuf || BufSize < m_uAlignLen || BufSize < 1)
{
return NULL;
}
memset(OutBuf, 0, BufSize);
strncpy(OutBuf, SrcBuf + CodeIndex * m_uAlignLen, m_uAlignLen);
return OutBuf;
}
// ָԴеλ
const int
CStkCodeOperate::FindStkCode(const char *SrcBuf, const unsigned int OccupySize,
const char *StkCode)
{
if (NULL == StkCode || NULL == SrcBuf)
{
return -1;
}
char cFormat[DefaultFormatLen] = {0};
snprintf(cFormat, DefaultFormatLen, "%%%us", m_uAlignLen);
int iRes = 0;
char cCode[16] = {0};
iRes = snprintf(cCode, m_uAlignLen + 1, cFormat, StkCode);
if ((unsigned int)iRes > m_uAlignLen)
{
return -2;
}
char *pFind = strstr(SrcBuf, cCode);
if (NULL == pFind)
{
return -3;
}
int iRemainLen = OccupySize - strlen(pFind);
return iRemainLen / m_uAlignLen;
}
| true |
5e2fd6379069686ed0ba12fb1cf115dbd0e7ad77 | C++ | saswatraj/project_eular | /ques25.cpp | UTF-8 | 792 | 3.125 | 3 | [] | no_license | #include<iostream>
#include<vector>
using namespace std;
vector<int> add(vector<int> num1,vector<int> num2)
{
vector<int> num3;
int carry = 0,sum=0,d1,d2;
while(!((num1.size()==0)&&(num2.size()==0)))
{
if(num1.size()>0){
d1 = num1.back();
num1.pop_back();
}
else
d1 = 0;
if(num2.size()>0){
d2 = num2.back();
num2.pop_back();
}
else
d2 = 0;
sum = d1 + d2 + carry;
num3.insert(num3.begin(),sum%10);
carry = sum/10;
}
while(carry!=0)
{
num3.insert(num3.begin(),carry%10);
carry = carry / 10;
}
return num3;
}
int main()
{
vector<int> v1;
v1.push_back(1);
vector<int> v2;
v2.push_back(1);
vector<int> v3;
int count = 2;
while(v3.size()!=1000)
{
v3 = add(v1,v2);
count++;
v1 = v2;
v2 = v3;
}
cout << count << endl;
return 0;
}
| true |
f8d44547d452b029c26e4a433dd9233eda48d964 | C++ | icecoolr1/c | /前50个素数.cpp | UTF-8 | 319 | 2.984375 | 3 | [] | no_license | #include <stdio.h>
int main()
{
int x;
int count=0;
for(x=1;count<=50;x++){
int i;
int isprime=1;
for(i=2;i<x;i++){
if( x % i==0){
isprime=0;
break;
}}
if(isprime==1){
count++;
printf("%d\t ", x);
if(count%5==0){ printf("\n");
}
}
}
return 0;
}
| true |
18c12b62bc662ed407ea1616a065f43edc386a33 | C++ | sharadregoti/Old_College_Stuff | /AntopHill_Monitoring_Project/Without_Debug_Code/AntopHill_Project/Alarm_Router_On_Off.ino | UTF-8 | 1,511 | 2.671875 | 3 | [
"Apache-2.0"
] | permissive |
// turn on or off alarm or jioRelay
void turnOn_Off(int pos, int value ) {
digitalWrite(pos, value);
}
// whatever the current time go for deep sleep every 30th minute or 60th(00) minute of each hour
void dynamicDeepSleep() {
Serial.println("DYNAMIC SLEEP");
// first parameter: Time zone in floating point (for India); second parameter: 1 for European summer time; 2 for US daylight saving time; 0 for no DST adjustment; (contributed by viewwer, not tested by me)
dateTime = NTPch.getNTPtime(5.5, 0);
// check dateTime.valid before using the returned time
// Use "setSendInterval" or "setRecvTimeout" if required
if (dateTime.valid) {
int dptime = DEEPSLEEP_TIME_IN_MINUTES;
NTPch.printDateTime(dateTime);
int rnd = 0, val = 0;
byte actualMinute = dateTime.minute;
Serial.println(actualMinute);
if ((dateTime.hour == 12) && (actualMinute <= 4)) {
digitalWrite(JIO_RELAY, HIGH);
delay(2000);
digitalWrite(JIO_RELAY, LOW);
delay(60000);
}
// rnd = roundUp(actualMinute, dptime);
// val = abs(rnd - actualMinute);
// Serial.printf("actual time %d", actualMinute);
// Serial.printf("rnd %d", rnd);
// Serial.printf("val %d", val);
// ESP.deepSleep(val * 60 * 1000000); // deep sleep for 30 min dynamically
}
//return -1;
}
int roundUp(int round, int multiple) {
if (multiple == 0) {
return round;
}
int remainder = 0;
remainder = round % multiple;
int val = round + multiple - remainder;
return val;
}
| true |
55688fdbad941e6d891bd61f1d7fae27b84704bc | C++ | Tahfimul/CPlusPlus-Projects | /Program100.cpp | UTF-8 | 452 | 3.234375 | 3 | [] | no_license | #include<iostream>
#include<iomanip>
using namespace std;
//Tahfimul Latif
//Program100
//Print the elements in an array set by users
//March 5, 2018
int main()
{
int n[10];
cout<<"Enter Elements of the array"<<endl;
for(int i = 0; i<(sizeof(n)/sizeof(*n));i++)
{
cout<<"Element"<<setw(13)<<i<<endl;
cin>>n[i];
}
for(int i=0; i<(sizeof(n)/sizeof(*n)); i++)
cout<<"Index"<<setw(7)<<i<<"\tElement"<<setw(13)<<n[i]<<endl;
}
| true |
4bb68131f34cf1369155e4ce3c16a8f71e07db96 | C++ | i-shalev/Stowage-Model | /src/simulator/main.cpp | UTF-8 | 2,883 | 3.046875 | 3 | [] | no_license | #include <algorithm>
#include "main.h"
#define PATH_TO_EMPTY_FILE R"(.\empty.empty_file)"
int main(int argc, char **argv){
std::map<std::string, std::string> args;
std::vector<std::string> errors;
int numThreads;
bool errorInCreateArgs = false;
if(createArgs(args, argc, argv)){
errorInCreateArgs = true;
errors.emplace_back("ERROR: travel_path not provided!");
}
// printArgs(args);
try{
numThreads = stoi(args["-num_threads"]);
} catch (const std::exception& e) {
numThreads = 1;
errors.emplace_back("ERROR: num_threads that provided is not a number!");
}
int res = folderIsExistOrCanBeBuilt(args["-output"]);
if(res == 1){
errors.emplace_back("Warning: output path that provided is non existent folder but we successfully create it.");
} else if (res == 2) {
errors.emplace_back("Warning: output path that provided is not a valid path, the output files will be under the folder you run the program.");
args["-output"] = "./";
}
if(!errorInCreateArgs and !isFolderExist(args["-travel_path"])){
errorInCreateArgs = true;
errors.emplace_back("ERROR: travel_path that provided is not a valid path.");
}
if(errorInCreateArgs){
writeErrorsToFile(args["-output"] + "/errors/" + "general_errors.errors", args["-output"] + "/errors/", &errors);
return EXIT_FAILURE;
}
if(!isFolderExist(args["-algorithm_path"])){
errors.emplace_back("Warning: algorithm_path that provided is not a valid path. so no algorithms runs.");
} else {
if(numThreads == 1) {
runAllAlgo(args["-algorithm_path"], args["-travel_path"], args["-output"]);
} else {
// here we call the threads function.
runThreads(numThreads, args["-algorithm_path"], args["-travel_path"], args["-output"]);
}
}
writeErrorsToFile(args["-output"] + "/errors/" + "general_errors.errors", args["-output"] + "/errors/", &errors);
return EXIT_SUCCESS;
}
int createArgs(std::map<std::string, std::string>& args, int& argc, char **argv){
for(int i = 1; i < argc-1; i += 2){
args[argv[i]] = argv[i+1];
}
if(args["-algorithm_path"].empty()){
args["-algorithm_path"] = "./";
}
if(args["-num_threads"].empty()){
args["-num_threads"] = "1";
}
if(args["-output"].empty()){
args["-output"] = "./";
}
if(args["-travel_path"].empty()){
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
void printArgs(std::map<std::string, std::string>& args){
std::cout << "travel_path: " << args["-travel_path"] << std::endl;
std::cout << "num_threads: " << args["-num_threads"] << std::endl;
std::cout << "algorithm_path: " << args["-algorithm_path"] << std::endl;
std::cout << "output: " << args["-output"] << std::endl;
}
| true |
1e569551db8630820b892dbf051d4cf94226beb3 | C++ | rene128x/OpencvTest_Cpp | /lib/ConfigParser.h | UTF-8 | 628 | 2.921875 | 3 | [] | no_license | #ifndef CONFIGPARSER_H_
#define CONFIGPARSER_H_
#include <map>
#include <string>
using namespace std;
class ConfigParser {
public:
ConfigParser(const string &configFile);
int getProperty(const string &name);
bool getFlag(const string &name);
string getText(const string &name);
void setProperty(const string &name, int val);
void setFlag(const string &name, bool val);
void setText(const string &name, const string &val);
void save();
void save(const string &path);
private:
map<string, bool> flags;
map<string, int> properties;
map<string, string> texts;
string defaultPath;
};
#endif /* CONFIGPARSER_H_ */
| true |
ba010253aabf3c73daaa6dd663ffe37ffdbff0c6 | C++ | Twice22/acceleratedcpp | /Chapter10/chapter10.2/chapter10.2/chapter10.2.cpp | ISO-8859-1 | 1,835 | 3.71875 | 4 | [] | no_license | // chapter10.2.cpp: dfinit le point d'entre pour l'application console.
//
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <list>
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
template <class T, class Iterator>
T median(Iterator b, Iterator e) {
if (b == e)
throw domain_error("median of an empty array");
// can't do
// size_t size = sizepf(b) / sizeof(*b);
// can't do
// sort(e, b)
// because it would have change the order of the element in the array
// which we don't want!
// use vector instead
vector<T> temp;
for (; b != e; ++b) {
temp.push_back(*b);
}
// don't forget to sort
sort(temp.begin(), temp.end());
typedef typename vector<T>::size_type vec_sz;
vec_sz size = temp.size();
vec_sz mid = size / 2;
return size % 2 == 0 ? (temp[mid] + temp[mid-1]) / 2 : temp[mid];
}
int main()
{
vector<double> vdouble{ 14.7, 78.9 ,58.6, 45.6, 46.5 };
vector<int> vint{ 15, 79 ,59, 45, 46 };
cout << "vector: median[double]: " << median<double>(vdouble.begin(), vdouble.end()) << endl;
cout << "vector: median[int]: " << median<int>(vint.begin(), vint.end()) << endl;
double adouble[] = { 14.7, 78.9, 58.6, 45.6, 46.5 };
int aint[] = { 15, 79 ,59, 45, 46 };
size_t size_ad = sizeof(adouble) / sizeof(*adouble);
size_t size_ai = sizeof(aint) / sizeof(*aint);
cout << "array: median[double]: " << median<double>(adouble, adouble + size_ad) << endl;
cout << "array: median[int]: " << median<int>(aint, aint + size_ai) << endl;
// Answer to Q10.3 (ensure elements are still in the same order)
for (size_t i = 0; i < size_ad; ++i) {
cout << adouble[i] << " ";
}
cout << endl;
for (vector<int>::const_iterator it = vint.begin(); it != vint.end(); ++it) {
cout << *it << " ";
}
cout << endl;
system("pause");
return 0;
}
| true |
f90ff2249e49e2e7658a51e9dc194f5eef600686 | C++ | knightzf/review | /leetcode/numberOfAtoms/main.cpp | UTF-8 | 2,118 | 3.1875 | 3 | [] | no_license | #include "header.h"
class Solution {
public:
string countOfAtoms(string formula) {
const map<string, int>& res = impl(formula);
stringstream ss;
for(auto& p : res)
{
ss << p.first;
if(p.second > 1)
ss << p.second;
}
return ss.str();
}
map<string, int> impl(const auto& formula)
{
map<string, int> res;
for(int i = 0, n = formula.size(); i < n;)
{
if(formula[i] == '(')
{
int j = i;
int cnt = 0;
while(j < n)
{
if(formula[j] == '(') ++cnt;
else if(formula[j] == ')') --cnt;
++j;
if(cnt == 0) break;
}
const auto& t = impl(formula.substr(i + 1, j - i - 2));
int multiplier = 1;
if(j < n && isdigit(formula[j]))
{
int k = j;
while(++k < n && isdigit(formula[k])){}
multiplier = stoi(formula.substr(j, k - j));
j = k;
}
for(auto& p : t)
{
res[p.first] += p.second * multiplier;
}
i = j;
}
else
{
int j = i + 1;
while(j < n && islower(formula[j]))
{
++j;
}
const auto& atom = formula.substr(i, j - i);
int multiplier = 1;
if(j < n && isdigit(formula[j]))
{
int k = j;
while(++k < n && isdigit(formula[k])){}
multiplier = stoi(formula.substr(j, k - j));
j = k;
}
res[atom] += multiplier;
i = j;
}
}
return res;
}
};
int main() {
Solution s;
}
| true |
71a0132923ee8cdccaa94ad4407f5f0e93ed0080 | C++ | markstev/arduinoio3 | /bidir_serial_main_for_test.cc | UTF-8 | 1,918 | 2.609375 | 3 | [] | no_license | #include "arduino_simulator.h"
#include "bidir_serial_module.h"
#include "message.h"
#include <cstring>
#include <stdlib.h>
const int kOtherAddress = 1;
int main(int argc, char **argv) {
// arg1 = incoming serial file.
// arg2 = outgoing serial file.
if (argc < 4) {
printf("Call with args:\nbidir_serial_main <incoming serial filename> <outgoing serial filename> <address>");
return 1;
}
arduinoio::SerialAbstraction module_serial;
module_serial.UseFiles(argv[1], argv[2]);
arduinoio::BidirSerialRXModule module(&module_serial, atoi(argv[3]));
char message[7] = "COUNT\0";
arduinoio::Message counter_message(kOtherAddress, 6, message);
bool do_find_replace = false;
arduinoio::Message find_replace_message(kOtherAddress, 6, message);
while (true) {
const arduinoio::Message *incoming = module.Tick();
if (incoming != nullptr) {
int length;
const char *incoming_command = incoming->command(&length);
if (0 == strncmp("SET_COUNT", incoming_command, 9) && length == 10) {
message[5] = incoming->command(&length)[9];
} else if (0 == strncmp("REWRITE", incoming_command, 7) && length >= 10) {
char rewritten[length];
char find = incoming_command[7];
char replace = incoming_command[8];
for (int i = 0; i < length; ++i) {
if (i < 9 || incoming_command[i] != find) {
rewritten[i] = incoming_command[i];
} else {
rewritten[i] = replace;
}
}
find_replace_message.Reset(kOtherAddress, length, rewritten);
do_find_replace = true;
}
}
if (do_find_replace) {
if (module.AcceptMessage(find_replace_message)) {
do_find_replace = false;
}
} else {
if (module.AcceptMessage(counter_message)) {
message[5]++;
counter_message.Reset(kOtherAddress, 6, message);
}
}
}
return 0;
}
| true |
e91a0da4bf8587b699060b6a6b48e332e3739d15 | C++ | Naooki/stroustrup_ppp_exercises | /Chapter-11/ex 12.cpp | UTF-8 | 879 | 3.09375 | 3 | [] | no_license | /*
Okay, so here I have a bug: in input like "ab/n cd" some 1 character just goes nowhere...
Here is a discussion about an issue:
http://www.cplusplus.com/forum/general/120661/
*/
#include "../../../../libs/std_lib_facilities.h"
int main()
try
{
cout << "Input file name: ";
string file_name;
cin >> file_name;
fstream fs{ file_name };
char ch_begin;
char ch_end;
int length = 0;
string line;
for (char ch; fs.get(ch);)
++length;
fs.clear();
for (int i = 0; i<length/2; ++i)
{
fs.seekg(i, ios::beg);
fs.get(ch_begin);
fs.seekg(-i-1, ios::end);
fs.get(ch_end);
fs.seekp(i, ios::beg);
fs << ch_end;
fs.seekp(-i-1, ios::end);
fs << ch_begin;
fs.seekg(i, ios::beg);
}
cout << "Done!" << endl;
}
catch (exception& e)
{
cerr << e.what() << endl;
}
catch (...)
{
cerr << "Exception!" << endl;
}
| true |
b17e3ee5a70415098057e81519f013762a94682d | C++ | shaikhsajid1111/data-structure-and-algorithms | /Algorithms/Sorting Algorithms/insertion sort.cpp | UTF-8 | 2,356 | 4.21875 | 4 | [] | no_license | #include<iostream>
#include<cstdlib>
int *insertion_sort(int arr[],int size);
void printArray(int arr[],int size);
int main(int argc, char const *argv[])
{
int arr[5] = {5,8,9,0,4};
insertion_sort(arr,5);
printArray(arr,5);
/*output : 2,3,4,5,8*/
system("pause");
return 0;
}
int *insertion_sort(int arr[],int size){
/*iterate from 1 - length of array*/
/*logic:
arr = {5,4,3,2,1} ->
start from 1 till the last index of array
1) position is greater than 0? and [position-1] i.e value before this position in
array is greater than the current?,{5,4,3,2,1}, arr[1] and arr[0] > 4. So condition is true
if both condition are true than,
replace current position[value] with the previous one[value], -> {5,5,3,2,1}
so, index will be decremented by 1, so it becomes 0, so while loop will terminate
arr[0] = current_value; which is 4. So array becomes {4,5,3,2,1}
*/
for(int index = 1;index < size;index++){
int current_value = arr[index]; //index's value in array
int position = index; //current index
while(position > 0 & arr[position-1] > current_value){ /*if position is <1 and previous position is larger number*/
arr[position] = arr[position-1]; /*copy the larger one to the previous value*/
position--;
}
arr[position] = current_value;
}
return arr;
}
void printArray(int arr[],int size){
for (int i = 0; i < size; ++i)
{
std::cout << arr[i] << std::endl;
}
}
/*
void insertion_sort(int arr[],int size){
for(int i = 1;i < size;i++){
int value_to_be_sorted = arr[i]; /*value of array,starts iterating from 0*/
/*int j = i; /*iterator*/
/*while(j > 0 && arr[j-1] > value_to_be_sorted){ /*while j is greater than 0 and previous value is greater than the after*/
/* arr[j] = arr[j-1]; /*swap elements,e.g if 6,5 than it follows logic that it'll become it'll become 5,5*/
/* j -= 1;
}
arr[j] = value_to_be_sorted; /*after coming out of iteration, the next value is again 5,6*/
/*}
}*/
/*
array = {5,4,2,3,8};
iteration 1:
i = 1
value_to_be_sorted = 4,because a[1] = 4
j = 1
1 > 0 and 5 > 4
so, arr[1] = 5 and after iteration - arr[0] = 4
after 1 iteration - {4,5,2,3,8}
iteration 2:
i = 2
value_to_be_sorted = 2,because a[2] = 2
j = 2
arr[j-1] = arr[1] = 5
2 > 0 and 5 > 4
so, arr[2] = 2 and after iteration - arr[0] = 4
after 2 iteration - {4,2,5,3,8}
*/
| true |
c78dae71b55eb379dc3070d404eb5d62261da67f | C++ | daniel8060/CodeSnippets | /BruinopolyFiles/statics.h | UTF-8 | 889 | 3.15625 | 3 | [] | no_license | #ifndef STATICS_H
#define STATICS_H
/*
This class will be responsible for taking data from the Game Setting screen and passing to
any other in-game object that need them.
*/
class Statics {
private:
int MONEY_MAX, HOUSES_MAX, HOTELS_MAX, STARTING_AMOUNT;
public:
Statics(
//default settings
int _money_max = 20580,
int _starting_amount = 1500,
int _houses_max = 32,
int _hotels_max = 12
)
{
//values input in starting screen.
MONEY_MAX = _money_max;
HOUSES_MAX = _houses_max;
HOTELS_MAX = _hotels_max;
STARTING_AMOUNT = _starting_amount;
}
int getMONEY_MAX() { return MONEY_MAX; }
int getHOUSES_MAX() { return HOUSES_MAX; }
int getHOTELS_MAX() { return HOTELS_MAX; }
int getSTARTING_AMOUNT() { return STARTING_AMOUNT; }
};
#endif
| true |
5661b937e93ac03bf379e02a68da4383acdfad57 | C++ | masterchef2209/coding-solutions | /codes/codeforces/1093B.cpp | UTF-8 | 475 | 2.546875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin>>t;
while(t--)
{
string s;
cin>>s;
int arr[26];
int bulb=1;
memset(arr,0,sizeof(arr));
for(int i=0;i<s.size();i++)
{
if(i>0)
{
if(s[i]!=s[i-1])
bulb=0;
}
arr[s[i]-'a']++;
}
if(bulb==1)
cout<<-1<<endl;
else
{
for(int i=0;i<26;i++)
{
int count=arr[i];
while(count--)
{
cout<<(char)('a'+i);
}
}
cout<<endl;
}
}
return 0;
} | true |
c2bd45b8ef0df0283bd7178b6d643b2008f2ed8d | C++ | Tecprog-voID/voID | /src/Customs/GameOverScript.cpp | UTF-8 | 3,101 | 2.890625 | 3 | [
"MIT"
] | permissive | /**
@file GameOverScript.cpp
@brief Methods that manages the game over script of the game.
@copyright LGPL. MIT License.
*/
#include "Customs/GameOverScript.hpp"
#include "Log/log.hpp"
#include <cassert>
const int quantityFrameLine = 22;
const int quantityFrameColumn = 12;
GameOverScript::GameOverScript(GameObject *owner) : Script(owner) {
assert((owner != NULL) and "the owner must be equal to NULL");
}
/**
@brief that function starts the game over script. Create the animation,
position, the animator and the input.
*/
void GameOverScript::Start() {
INFO("GameOverScript - Start");
// Starts game-over animations by setting its positions and animator.Sets gameobject's vector zoom proportion.
position = GetOwner()->GetPosition();
animator = (Animator *)GetOwner()->GetComponent("Animator");
input = InputSystem::GetInstance();
GetOwner()->SetZoomProportion(Vector(0, 0));
}
/**
@brief that function creates the animations. Create the snow image, the game
over animation and animator.
*/
void GameOverScript::CreateAnimations() {
INFO("GameOverScript - Create Animations");
/*
Creates game-over animation by setting a image and a animation with
defined frames positions over it.
*/
auto m_snowImage = new Image("assets/image/Ending_show_image.png",0,0,4096, 2048);
auto m_gameOverAnimation= new Animation(GetOwner(), m_snowImage );
for (int line = 0; line < quantityFrameLine; line++) {
for (int column = 0 ; column < quantityFrameColumn ; column++) {
m_gameOverAnimation->AddFrame(new Frame(column * 341,line* 256, 341, 256));
m_gameOverAnimation->AddFrame(new Frame(column * 341,line* 256, 341, 256));
}
}
// animator.
auto m_gameOverAnimator = new Animator(GetOwner());
m_gameOverAnimator->AddAnimation("snowAnimation", m_gameOverAnimation);
}
/**
@brief that function updates the components of the game over.
*/
void GameOverScript::ComponentUpdate() {
INFO("GameOverScript - Component Update");
/*
Updates the game-over component and sets the state of played audios.
*/
animator->PlayAnimation("snowAnimation");
// Check for the player and its animator and input state.
if (play==1) {
animator->PlayAnimation("snowAnimation");
} else {
// Do nothing
}
if (input->GetKeyDown(INPUT_T) and play==0) {
// animator->StopAllAnimations();
AudioController::GetInstance()->PlayAudio("snowSound", -1);
play=1;
}
else if (input->GetKeyDown(INPUT_T) and play==1) {
play=0;
AudioController::GetInstance()->StopAudio("snowSound");
animator->StopAllAnimations();
}
}
/**
@brief that function fixs the component upddate of the game over Script.
They set the position x and y to zero.
*/
void GameOverScript::FixedComponentUpdate() {
INFO("GameOverScript - Fixed Component Update");
// Check the components positions, and end them by setting it to zero.
position->m_x = 0;
position->m_y = 0;
}
| true |
0784d8a7951748db96059c0bf637ff888f7e5dda | C++ | douglascastrorj/compilador | /Exemplos Cython/operadores/expressao.cpp | UTF-8 | 697 | 3.25 | 3 | [] | no_license |
/*Compilador Bolado*/
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int temp1;
int temp2;
int temp3;
int temp4;
float temp5;
float temp6;
float temp7;
float temp8;
float temp9;
float temp10;
float temp11;
float temp12;
float temp13;
float temp14;
int main(void)
{
temp1 = 1;
temp2 = 1;
temp3 = temp1 + temp2;
temp4 = temp3;
temp5 = 0.5;
temp6 = 1.5;
temp7 = temp5 + temp6;
temp8 = temp7;
temp9 = (float) temp4;
temp10 = temp9 + temp8;
temp11 = temp8 * temp10;
temp12 = (float) temp4;
temp13 = temp12 + temp11;
temp14 = temp13;
std::cout << temp4 << std::endl;
std::cout << temp8 << std::endl;
std::cout << temp14 << std::endl;
return 0;
}
| true |
fa56c16e0a8ebe2c64e623075fa9df13152b5004 | C++ | mikechen66/CPP-Programming | /CPP-Programming-Language/chapter22-runtime/ex04.cpp | UTF-8 | 689 | 3.03125 | 3 | [] | no_license | #include <iostream>
#include <map>
#include <numeric>
using namespace std;
void readitems(map<string,int>& m) {
string word;
int val = 0;
while (cin >> word >> val)
m[word] += val;
}
int tally_word(int total, const pair<string,int>& p) {
cout << p.first << '\t' << p.second << '\n';
return total += p.second;
}
int main() {
map<string,int> tbl;
readitems(tbl);
int total = 0;
typedef map<string,int>::const_iterator CI;
total = accumulate(tbl.begin(), tbl.end(), 0, tally_word);
cout << "----------------\ntotal\t" << total << '\n';
return !cin;
}
/* Output */
/*
$g++ -o main *.cpp
$main
----------------
total 0
*/ | true |
569fc05f5862e3268348281032e17aa6c9b4750f | C++ | cisc0f/genealogicalTreeGraph | /main.cpp | UTF-8 | 5,203 | 3.421875 | 3 | [] | no_license | #include "genogram.h"
#if defined(_WIN32) || defined(WIN32)
const char* clearTerminalCmd = "cls";
void prettyPrint(int color, std::string text){
std::cout << text;
}
void prettyPrintError(std::string text){
std::cout << text;
}
#else
const char* clearTerminalCmd = "clear";
void prettyPrint(int color, std::string text){
std::cout << "\033[1;" << color << "m" << text << "\033[0m";
}
void prettyPrintError(std::string text){
prettyPrint(41, text);
}
#endif
int main(){
int mainColor{32}, secondaryColor{31};
int mainBackgroundColor{42}, secondaryBackgroundColor{41}, accentBackgroundColor{46};
int choice{0};
std::string name1{""},name2{""},gender{""},date1{""},date2{""};
gen::Genogram g= gen::createEmptyGen();
do{
std::cout << "--------------------------------------------" << std::endl;
prettyPrint(secondaryBackgroundColor, " MENU ");
std::cout << std::endl;
std::cout << "--------------------------------------------" << std::endl;
prettyPrint(mainColor, "1 - Inserimento genogramma da file\n");
prettyPrint(mainColor, "2 - Inserimento persona nel genogramma\n");
prettyPrint(mainColor, "3 - Inserimento della relazione madre\n");
prettyPrint(mainColor, "4 - Inserimento della relazione padre\n");
prettyPrint(mainColor, "5 - Inserimento della relazione coppia\n");
prettyPrint(mainColor, "6 - Inserimento della relazione figlio ad una coppia\n");
prettyPrint(mainColor, "7 - Imposta data di nascita\n");
prettyPrint(mainColor, "8 - Imposta data di morte\n");
prettyPrint(mainColor, "9 - Cancella persona\n");
prettyPrint(mainColor, "10 - Controlla validità del genogramma\n");
prettyPrint(mainColor, "11 - Stampa genogramma\n");
prettyPrint(secondaryColor, "0 - Exit\n");
std::cout << "--------------------------------------------" << std::endl;
prettyPrint(mainBackgroundColor, " Inserisci opzione: ");
std::cout << " ";
std::cin >> choice;
try{
switch (choice){
case 0:
exit(0);
case 1:
system(clearTerminalCmd);
std::cout << "Nome file: ";
std::cin >> name1;
readGenogramFromFile(name1,g);
break;
case 2:
system(clearTerminalCmd);
std::cout << "Nome persona: ";
std::cin >> name1;
std::cout << "Genere (M/F): ";
std::cin >> gender;
std::cin.ignore();
std::cout << "Data di nascita gg/mm/aaaa: ";
getline(std::cin, date1);
std::cout << "Data di morte gg/mm/aaaa: ";
getline(std::cin, date2);
gen::addPerson(name1,gender,date1,date2,g);
break;
case 3:
system(clearTerminalCmd);
std::cout << "Nome della madre: ";
std::cin >> name1;
std::cout << "Nome del figlio/a: ";
std::cin >> name2;
gen::addRelMother(name1,name2,g);
break;
case 4:
system(clearTerminalCmd);
std::cout << "Nome del padre: ";
std::cin >> name1;
std::cout << "Nome del figlio/a: ";
std::cin >> name2;
gen::addRelFather(name1,name2,g);
break;
case 5:
system(clearTerminalCmd);
std::cout << "Nome prima persona: ";
std::cin >> name1;
std::cout << "Nome seconda persona: ";
std::cin >> name2;
gen::addRelCouple(name1,name2,g);
break;
case 6:
system(clearTerminalCmd);
std::cout << "Nome di uno dei genitori: ";
std::cin >> name1;
std::cout << "Nome del figlio/a: ";
std::cin >> name2;
gen::addRelChildToCouple(name1,name2,g);
break;
case 7:
system(clearTerminalCmd);
std::cout << "Nome persona: ";
std::cin >> name1;
std::cout << "Data di nascita: ";
std::cin >> date1;
gen::setBirthDate(name1,date1,g);
break;
case 8:
system(clearTerminalCmd);
std::cout << "Nome persona: ";
std::cin >> name1;
std::cout << "Data di morte: ";
std::cin >> date1;
gen::setDeathDate(name1,date1,g);
break;
case 9:
system(clearTerminalCmd);
std::cout << "Nome persona da eliminare: ";
std::cin >> name1;
gen::deletePerson(name1,g);
break;
case 10:
system(clearTerminalCmd);
if(gen::isValid(g)){
prettyPrint(accentBackgroundColor, " GENOGRAMMA VALIDO \n");
}else{
prettyPrintError(" GENOGRAMMA NON VALIDO \n");
}
break;
case 11:
system(clearTerminalCmd);
prettyPrint(accentBackgroundColor, "\n RISULTATO \n");
printGenogram(g);
break;
default:
system(clearTerminalCmd);
prettyPrintError(" COMANDO NON RICONOSCIUTO \n");
break;
}
}catch(const char* exception){
std::string msg = " ERRORE: "+std::string(exception)+" \n";
prettyPrintError(msg);
}
}while(true);
return 0;
} | true |
daccd6119cea0cd75748219d2ace4446ea01cc20 | C++ | breadpitt/DU-CS | /CompProg/Assignments/Assignment4/Apartment.cpp | UTF-8 | 2,076 | 3.640625 | 4 | [] | no_license | //
// Created by jasha on 11/5/2017.
//
#include "Dwelling.h"
#include "Apartment.h"
#include <iostream>
// Default Constructor
Apartment::Apartment() : Dwelling(), apartment_number(0), rent(0) {
}
Apartment::Apartment(int rooms, int bathrooms, float square_footage, int apt_number, float temp_rent) :
Dwelling(rooms, bathrooms, square_footage), apartment_number(apt_number), rent(temp_rent) {
apartment_number = apt_number;
rent = temp_rent;
}
// Apartment member function to calculate the $/sqft.
float Apartment::per_sqft(float square_footage, float rent) {
float price_per_sq_ft;
price_per_sq_ft = rent/square_footage;
return price_per_sq_ft;
}
// Output function
std::ostream& operator <<(std::ostream& out, Apartment apartment) {
return out << "Apartment #" << apartment.apartment_number<< " has " << apartment.get_rooms()
<< " bedrooms, " << apartment.get_bathrooms() << " baths, " << apartment.get_sq_ft()
<< " sq ft., the monthly payment is " << apartment.rent << " which is $"
<< apartment.per_sqft(apartment.get_sq_ft(), apartment.rent) << " per sq. ft.\n";
}
// Input function
void Apartment::read_apartment_details(std::istream &in){
using std::cout;
int bedrooms;
int baths;
float square_feet;
cout << "Enter the apartment number \n";
in >> apartment_number;
cout << "Enter number of bedrooms \n";
in >> bedrooms;
set_rooms(bedrooms);
cout << "Enter number of baths \n";
in >> baths;
set_bathrooms(baths);
cout << "Enter square footage \n";
in >> square_feet;
set_sq_ft(square_feet);
cout << "Enter monthly rent \n";
in >> rent;
}
bool Apartment::operator==(Apartment &other_apt) {
return get_rooms() == other_apt.get_rooms() &&
get_bathrooms() == other_apt.get_bathrooms() &&
get_sq_ft() == other_apt.get_sq_ft() &&
apartment_number == other_apt.apartment_number &&
rent == other_apt.rent;
} | true |
97986e220c276ef7fa7faf182ac3e41f29047374 | C++ | TomatoVampire/MySchedulingTest | /ScheduleTest/HRF.h | UTF-8 | 2,105 | 2.890625 | 3 | [] | no_license | #pragma once
#include"Scheduling.h"
#include<vector>
class HRF : Scheduling {
private:
//响应比
double* Rp;
virtual void init() {
}
virtual void schedule() {
int doneCount = 0;
int* doneProcess = new int[num];//[i]:第i个进程是否已经完成 0:未完 1:完成
for (int i = 0; i < num; i++) { doneProcess[i] = 0; }
int nowTime = 500, temp = 0;
//找出最先开始的进程
for (int i = 0; i < num; i++) {
if (pcbs[i].time_start < nowTime) { nowTime = pcbs[i].time_start; temp = i; }
}
//将其加入完成队列
doneProcess[temp] = 1;
ready[doneCount] = temp;
doneCount++;
vector<int> inready;
while (doneCount < num) {
cout << "Now time: " << nowTime;
cout << " process: " << pcbs[temp].name << " service: " << pcbs[temp].time_left;
cout << " Rp: " << Rp[temp] << endl;
nowTime += pcbs[temp].time_need;
inready.clear();
//将此刻到达等待队列的进程加入集合
for (int i = 0; i < num; i++) {
if (doneProcess[i] == 0 && pcbs[i].time_start <= nowTime)
inready.push_back(i);
}
//找出等待队列的最大相应比的进程序号
double nowMax = -1;
for (int i = 0; i < inready.size(); i++) {
//优先权=等待时间/服务时间+1
Rp[inready[i]] = 1.0 + (double)(nowTime - pcbs[inready[i]].time_start) / pcbs[inready[i]].time_need;
if (nowMax == -1 || (nowMax < Rp[inready[i]]))
{
nowMax = Rp[inready[i]];
temp = inready[i];
}
}
//加入排序好的队列
doneProcess[temp] = 1;
ready[doneCount] = temp;
doneCount++;
}
cout << "Now time: " << nowTime;
cout << " process: " << pcbs[temp].name << " service: " << pcbs[temp].time_left;
cout << " Rp: " << Rp[temp] << endl;
}
int findMax() {
int max = -1, maxi=0;
for (int i = 0; i < num; i++) {
}
}
public:
HRF() :Scheduling() {}
HRF(int num, PCB* r) :Scheduling(num, r) {
Rp = new double[num];
for (int i = 0; i < num; i++) Rp[i] = 0.0;
}
void print() {
init();
cout << "------------HRF---------------" << endl;
schedule();
cout << "------------Done--------------\n";
}
}; | true |
1610f9ea17e8f6e2c682b9594fd35ed8ed422263 | C++ | ReFRACtor/framework | /lib/Support/array_with_unit.h | UTF-8 | 6,732 | 3.234375 | 3 | [] | no_license | #ifndef ARRAY_WITH_UNIT_H
#define ARRAY_WITH_UNIT_H
#include "printable.h"
#include "unit.h"
#include "double_with_unit.h"
#include <blitz/array.h>
namespace FullPhysics {
/****************************************************************//**
We frequently have a array of numbers with units associated with
them. This is a simple structure that just keeps these two things
together.
*******************************************************************/
template<class T, int D>
class ArrayWithUnit : public Printable<ArrayWithUnit<T, D> >,
boost::field_operators<ArrayWithUnit<T, D> > {
public:
ArrayWithUnit() { }
ArrayWithUnit(const ArrayWithUnit<T, D>& V)
: value(V.value.copy()), units(V.units) { }
ArrayWithUnit(const blitz::Array<T, D>& Value, const Unit& Value_units)
: value(Value.copy()), units(Value_units) { }
ArrayWithUnit(const blitz::Array<T, D>& Value, const std::string& Value_units_name)
: value(Value.copy()), units(Value_units_name) { }
blitz::Array<T, D> value;
Unit units;
//-----------------------------------------------------------------------
/// Assignment operator so internals are correctly set
//-----------------------------------------------------------------------
ArrayWithUnit<T, D>& operator=(const ArrayWithUnit<T, D>& V)
{ value.reference(V.value.copy()); units = V.units; return *this;}
//-----------------------------------------------------------------------
/// Basic math operators for class.
//-----------------------------------------------------------------------
inline ArrayWithUnit<T, D>& operator*=(const ArrayWithUnit<T, D>& V)
{ value *= V.value; units *= V.units; return *this;}
inline ArrayWithUnit<T, D>& operator/=(const ArrayWithUnit<T, D>& V)
{ value /= V.value; units /= V.units; return *this;}
inline ArrayWithUnit<T, D>& operator+=(const ArrayWithUnit<T, D> & V)
{ value += V.value * FullPhysics::conversion(V.units, units); return *this;}
inline ArrayWithUnit<T, D>& operator-=(const ArrayWithUnit<T, D> & V)
{ value -= V.value * FullPhysics::conversion(V.units, units); return *this;}
DoubleWithUnit operator()(int i1) const
{return DoubleWithUnit(value(i1), units);}
DoubleWithUnit operator()(int i1, int i2) const
{return DoubleWithUnit(value(i1, i2), units);}
DoubleWithUnit operator()(int i1, int i2, int i3) const
{return DoubleWithUnit(value(i1, i2, i3), units);}
DoubleWithUnit operator()(int i1, int i2, int i3, int i4) const
{return DoubleWithUnit(value(i1, i2, i3, i4), units);}
// Convenience wrappers so we don't need to enumerate
// all possible instances where say an int and Range
// are interchanged
template<class I>
ArrayWithUnit<T, D> operator()(I i1) const
{return ArrayWithUnit<T, D>(value(i1), units);}
template<class I>
ArrayWithUnit<T, D> operator()(I i1, I i2) const
{return ArrayWithUnit<T, D>(value(i1, i2), units);}
template<class I>
ArrayWithUnit<T, D> operator()(I i1, I i2, I i3) const
{return ArrayWithUnit<T, D>(value(i1, i2, i3), units);}
template<class I>
ArrayWithUnit<T, D> operator()(I i1, I i2, I i3, I i4) const
{return ArrayWithUnit<T, D>(value(i1, i2, i3, i4), units);}
template<class I, class J>
ArrayWithUnit<T, D-1> operator()(I i1, J i2) const
{return ArrayWithUnit<T, D-1>(value(i1, i2), units);}
template<class I, class J>
ArrayWithUnit<T, D-1> operator()(J i1, I i2, I i3) const
{return ArrayWithUnit<T, D-1>(value(i1, i2, i3), units);}
template<class I, class J>
ArrayWithUnit<T, D-1> operator()(I i1, J i2, I i3) const
{return ArrayWithUnit<T, D-1>(value(i1, i2, i3), units);}
template<class I, class J>
ArrayWithUnit<T, D-1> operator()(I i1, I i2, J i3) const
{return ArrayWithUnit<T, D-1>(value(i1, i2, i3), units);}
template<class I, class J>
ArrayWithUnit<T, D-2> operator()(I i1, J i2, J i3) const
{return ArrayWithUnit<T, D-2>(value(i1, i2, i3), units);}
template<class I, class J>
ArrayWithUnit<T, D-2> operator()(J i1, I i2, J i3) const
{return ArrayWithUnit<T, D-2>(value(i1, i2, i3), units);}
template<class I, class J>
ArrayWithUnit<T, D-2> operator()(J i1, J i2, I i3) const
{return ArrayWithUnit<T, D-2>(value(i1, i2, i3), units);}
// Specializations to resolve ambiguous overloads
ArrayWithUnit<T, D-2> operator()(blitz::Range i1, int i2, int i3) const
{return ArrayWithUnit<T, D-2>(value(i1, i2, i3), units);}
ArrayWithUnit<T, D-2> operator()(int i1, blitz::Range i2, int i3) const
{return ArrayWithUnit<T, D-2>(value(i1, i2, i3), units);}
ArrayWithUnit<T, D-2> operator()(int i1, int i2, blitz::Range i3) const
{return ArrayWithUnit<T, D-2>(value(i1, i2, i3), units);}
//-----------------------------------------------------------------------
/// Convert to the given units.
//-----------------------------------------------------------------------
ArrayWithUnit<T, D> convert(const Unit& R) const
{
ArrayWithUnit<T,D> res;
res.value.reference(blitz::Array<T, D>(value * FullPhysics::conversion(units, R)));
res.units = R;
return res;
}
//-----------------------------------------------------------------------
/// We often need to handle conversion from wavenumber to/from
/// wavelength. This is either a normal conversion of the units before
/// and after match in the power of length (so cm^-1 to m^-1), or do
/// an inversion. Since we do this often enough, it is worth having a
/// function that handles this logic.
//-----------------------------------------------------------------------
ArrayWithUnit<T,D> convert_wave(const Unit& R) const
{
ArrayWithUnit<T,D> res;
res.units = R;
if(units.is_commensurate(R))
res.value.reference(blitz::Array<T, D>(FullPhysics::conversion(units, R) * value));
else
res.value.reference(blitz::Array<T, D>(FullPhysics::conversion(1 / units, R) / value));
return res;
}
int rows() const {return value.rows();}
int cols() const {return value.cols();}
int depth() const {return value.depth();}
void print(std::ostream& Os) const
{
Os << "ArrayWithUnit:\n"
<< "Value: " << value << "\n"
<< units << "\n";
}
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version);
};
typedef ArrayWithUnit<double, 1> ArrayWithUnit_double_1;
typedef ArrayWithUnit<double, 2> ArrayWithUnit_double_2;
typedef ArrayWithUnit<double, 3> ArrayWithUnit_double_3;
typedef ArrayWithUnit<double, 4> ArrayWithUnit_double_4;
}
FP_EXPORT_KEY(ArrayWithUnit_double_1);
FP_EXPORT_KEY(ArrayWithUnit_double_2);
FP_EXPORT_KEY(ArrayWithUnit_double_3);
FP_EXPORT_KEY(ArrayWithUnit_double_4);
#endif
| true |
cad7a5f20106bcf9f1c7a0ac89662be2eb06df7b | C++ | SaintGimp/MPPTSolarCharger | /code/source/console/console_internal.cpp | UTF-8 | 4,311 | 3.015625 | 3 | [] | no_license | #include <stdint.h>
#include <stdlib.h>
#include <cstring>
#include <ctype.h>
#include <utility>
#include "console_io.h"
#include "console_commands.h"
#include "console_internal.h"
namespace console
{
// Local functions
static int32_t StringToNumber(const char *p, char **out_p, int base);
void CommandCompleted()
{
ConsoleIoSend(kConsolePrompt);
}
// Find the start location of the nth parameter in the buffer where the command itself is parameter 0
bool ParamFindN(const char * buffer, const uint8_t parameterNumber, uint32_t *startLocation)
{
uint32_t bufferIndex = 0;
uint32_t parameterIndex = 0;
while ((parameterNumber != parameterIndex) && (bufferIndex < kConsoleCommandMaxLength))
{
if (buffer[bufferIndex] == kParameterSeparator)
{
parameterIndex++;
}
bufferIndex++;
}
if (bufferIndex == kConsoleCommandMaxLength)
{
return false;
}
*startLocation = bufferIndex;
return true;
}
// Identify and obtain a parameter
template <typename T>
bool ReceiveParameter(const char * buffer, const uint8_t parameterNumber, T* parameterValue)
{
uint32_t startIndex = 0;
if (!ParamFindN(buffer, parameterNumber, &startIndex))
{
return false;
}
*parameterValue = StringToNumber(buffer + startIndex, nullptr, 0);
return true;
}
// In order to have the definition of a template function in a cpp file, we need
// to explicitly instantiate the template types we expect to use.
// TODO: not entirely sure this is the best way to do this.
template bool ReceiveParameter<int8_t>(const char * buffer, const uint8_t parameterNumber, int8_t* parameterValue);
template bool ReceiveParameter<uint8_t>(const char * buffer, const uint8_t parameterNumber, uint8_t* parameterValue);
template bool ReceiveParameter<int16_t>(const char * buffer, const uint8_t parameterNumber, int16_t* parameterValue);
template bool ReceiveParameter<uint16_t>(const char * buffer, const uint8_t parameterNumber, uint16_t* parameterValue);
template bool ReceiveParameter<int32_t>(const char * buffer, const uint8_t parameterNumber, int32_t* parameterValue);
template bool ReceiveParameter<uint32_t>(const char * buffer, const uint8_t parameterNumber, uint32_t* parameterValue);
// Identify and obtain a parameter of type uint16
bool ReceiveParamUint16(const char * buffer, const uint8_t parameterNumber, uint16_t* parameterValue)
{
uint32_t startIndex = 0;
if (!ParamFindN(buffer, parameterNumber, &startIndex))
{
return false;
}
*parameterValue = StringToNumber(buffer + startIndex, nullptr, 0);
return true;
}
static int32_t StringToNumber(const char *p, char **out_p, int base)
{
int32_t value = 0;
bool is_neg = false;
while (isspace(*p))
{
p++;
}
if (*p == '-')
{
is_neg = true;
p++;
}
else if (*p == '+')
{
is_neg = false;
}
if (((base == 16) || (base == 0)) && ((*p == '0') && ((p[1] == 'x') || (p[1] == 'X'))))
{
p += 2;
base = 16;
}
else if (((base == 8) || (base == 0)) && (*p == '0'))
{
base = 8;
}
else if (((base == 2) || (base == 0)) && ((*p == 'b') || (*p == 'B')))
{
p += 1;
base = 2;
}
else if (base == 0)
{
base = 10;
}
while (true)
{
char c = *p;
if ((c >= '0') && (c <= '9') && (c - '0' < base))
{
value = (value * base) + (c - '0');
}
else if ((c >= 'a') && (c <= 'z') && (c - 'a' + 10 < base))
{
value = (value * base) + (c - 'a' + 10);
}
else if ((c >= 'A') && (c <= 'Z') && (c - 'A' + 10 < base))
{
value = (value * base) + (c - 'A' + 10);
}
else
{
break;
}
p++;
}
if (is_neg)
{
value = -value;
}
if (out_p)
{
*out_p = (char*)p;
}
return value;
}
} | true |
b88c2e0d42392839b43a80f87d52e104c1f60d0c | C++ | dhk1349/Data_Structure | /2020_TA/Lab3_pointer example/Lab03/TempType.cpp | UTF-8 | 430 | 2.640625 | 3 | [] | no_license | #include "pch.h"
#include "TempType.h"
TempType::TempType()
{
numOfItems = 0;
}
TempType::~TempType()
{
}
void TempType::AddtItem(ItemType* _tItem)
{
tItemList.AddToCircularQueue(_tItem);
numOfItems++;
}
ItemType* TempType::DequeueFromtItemList()
{
ItemType* tmp;
tmp = new ItemType;
tItemList.DeleteFrCircularQueue(tmp);
numOfItems--;
return tmp;
}
void TempType::PrinttItemList()
{
tItemList.PlayInsertOrder();
}
| true |
12fd916af223c9ec936c4c3165d5505bc882c09d | C++ | MrAsminaf/TicTacToe_SFML | /MainWindow.h | UTF-8 | 1,386 | 2.953125 | 3 | [
"MIT"
] | permissive | #pragma once
// SFML headers
#include <SFML\Graphics.hpp>
// my headers
#include "Button.h"
#include "Scoreboard.h"
// other imports...
#include <vector>
class MainWindow
{
public:
MainWindow();
void RunGameLoop();
private:
void PlayerInput();
void Logic();
void RoundEnd(float x_winningLine, float y_winningLine);
void SetField(int);
void ResetWinnerLine();
private:
sf::RenderWindow m_mainWindow;
sf::Sprite m_boardSprite;
sf::Texture m_boardTexture;
std::vector<sf::Sprite> m_xSprites;
sf::Texture m_xTexture;
std::vector<sf::Sprite> m_oSprites;
sf::Texture m_oTexture;
sf::Font m_font;
sf::Text m_currentPlayerText;
sf::Text m_endText;
// the green line that shows up when one player beats the other one
sf::RectangleShape m_winningLine;
Button m_restartButton;
Scoreboard m_scoreBrd;
bool m_gameEnded = false;
// ------------------- //
enum CurrentPlayer {
ENUM_O,
ENUM_X,
};
CurrentPlayer m_currentPlayer = CurrentPlayer::ENUM_O;
struct BoardFields
{
int coords[4];
bool isValid = true;
CurrentPlayer occupiedBy;
};
// coordinates for each field in order: x1, y1, x2, y2
BoardFields m_boardField[9]{
{ 8, 8, 192, 192 }, { 208, 8, 392, 192 }, { 408, 8, 592, 192 },
{ 8, 208, 192, 392 }, { 208, 208, 392, 392 }, { 408, 208, 592, 392 },
{ 8, 408, 192, 592 }, { 208, 408, 392, 592 }, { 408, 408, 592, 592 }
};
}; | true |
6d331437ec063efe1581e55515745587906f67fa | C++ | visotw/test | /src/ringbuffer.h | UTF-8 | 2,034 | 3.234375 | 3 | [
"MIT",
"LicenseRef-scancode-free-unknown",
"GPL-2.0-only",
"Unlicense"
] | permissive | #ifndef RINGBUFFER_H
#define RINGBUFFER_H
#include <algorithm> // for std::min
#include <cstdint>
#include <chrono>
using hrc = std::chrono::high_resolution_clock;
using ms = std::chrono::milliseconds;
using us = std::chrono::microseconds;
using ns = std::chrono::nanoseconds;
using sec = std::chrono::seconds;
class RingBuffer
{
RingBuffer(RingBuffer&) = delete;
public:
RingBuffer();
RingBuffer(size_t capacity);
~RingBuffer();
//size_t write(const char *data, size_t bytes);
//size_t read(char *data, size_t bytes);
// Overwrites old data if nbytes > size()
void write(uint8_t *src, size_t nbytes);
size_t read(uint8_t *dst, size_t nbytes);
// just move pointers around
void write(size_t bytes);
void read(size_t bytes);
template<typename T>
void write(size_t samples) { write(samples * sizeof(T)); }
template<typename T>
void read(size_t samples) { read (samples * sizeof(T)); }
void reserve(size_t size);
// if you care about old data, check how much can be written
// may need to call available/write twice in case write pointer wraps
size_t peek_write(bool overwrite = false) const;
size_t peek_read() const;
template<typename T>
size_t peek_write(bool overwrite = false) const
{
return peek_write(overwrite) / sizeof(T);
}
template<typename T>
size_t peek_read() const
{
return peek_read() / sizeof(T);
}
// amount of valid data, may need to read twice
size_t size() const;
template<typename T>
size_t size() const
{
return size() / sizeof(T);
}
size_t capacity() const { return m_capacity; }
char* front(){ return m_data + m_begin; }
char* back(){ return m_data + m_end; }
template<typename T>
T* front() { return (T*)(m_data + m_begin); }
template<typename T>
T* back() { return (T*)(m_data + m_end); }
long long MilliSecsSinceLastWrite()
{
return std::chrono::duration_cast<ms>(hrc::now()-mLastWrite).count();
}
private:
bool m_overrun;
size_t m_begin, m_end, m_capacity;
char *m_data;
hrc::time_point mLastWrite = hrc::time_point(ns(0));
};
#endif
| true |
9a186f8b2eba8559d1aa2bbfa1b0c84633a9db9c | C++ | JordyMoos/lazyfoo-sdl2 | /Texture.h | UTF-8 | 665 | 2.890625 | 3 | [] | no_license | #pragma once
#include <string>
#include <SDL.h>
class Texture {
public:
Texture();
~Texture();
bool loadFromFile(const std::string &path);
bool loadFromRenderedText(const std::string &text, SDL_Color color);
void free();
void setColor(Uint8 red, Uint8 green, Uint8 blue);
void setAlpha(Uint8 alpha);
void setBlendMode(SDL_BlendMode blendMode);
void render(int x, int y, SDL_Rect* clip = nullptr,
double angle = 0.0, SDL_Point* center = nullptr, SDL_RendererFlip flip = SDL_FLIP_NONE);
int getWidth() const;
int getHeight() const;
private:
SDL_Texture* mTexture;
int mWidth;
int mHeight;
};
| true |
997ed997f3c8817b39399ae37288258dbe5ac145 | C++ | notoraptor/cigmar | /src/cigmar/classes/StringView.hpp | UTF-8 | 1,463 | 3.25 | 3 | [] | no_license | /* Work In Progress. */
#ifndef CIGMAR_CSTRING_HPP
#define CIGMAR_CSTRING_HPP
#include <cstring>
#include <algorithm>
namespace cigmar {
class StringView {
public:
static const char *empty;
static const char* empty_characters;
private:
const char *member;
size_t len;
public:
StringView() : member(empty), len(0) {}
StringView(const char *str) : member(str ? str : empty) {len = strlen(member);}
const char& operator[](size_t pos) const {return member[pos];}
operator const char*() const {return member;}
explicit operator bool() const {return member[0] != '\0';}
size_t length() const {return len;}
const char* begin() const {return member;}
const char* end() const {return member + len;}
size_t ltrimmable(const StringView& characters = empty_characters) const {
size_t count;
for (count = 0; member[count] != '\0' && characters.contains(member[count]); ++count);
return count;
}
size_t rtrimmable(const StringView& characters = empty_characters) const {
size_t count;
for (count = 0; count < len && characters.contains(member[len - 1 - count]); ++count);
return count;
}
StringView& swap(StringView& other) {
std::swap(member, other.member);
std::swap(len, other.len);
return *this;
}
bool contains(char c, size_t start = 0) const {
while (member[start] != '\0') {
if (member[start] == c)
return true;
++start;
}
return false;
}
};
}
#endif //CIGMAR_CSTRING_HPP
| true |
98dc44c7da9dc15f93d5c11d36adc837bf7b4a2e | C++ | n0lavar/qxLib | /include/qx/algo/contains.h | WINDOWS-1252 | 2,397 | 3.359375 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /**
@file contains.h
@brief Contains "contains" functions (ba-dam-tss)
@details ~
@author Khrapov
@date 6.08.2022
@copyright Nick Khrapov, 2022. All right reserved.
**/
#pragma once
#include <algorithm>
namespace qx
{
/**
@brief Check if range contains value
@tparam fwd_it_t - forward iterator type
@tparam T - value type
@param itBegin - range begin iterator
@param itEnd - range end iterator
@param value - value to check
@retval - true if range contains value
**/
template<class fwd_it_t, class T>
bool contains(fwd_it_t itBegin, fwd_it_t itEnd, const T& value)
{
return std::find(itBegin, itEnd, value) != itEnd;
}
/**
@brief Check if container contains value
@tparam container_t - container type
@tparam T - value type
@param container - container to search in
@param value - value to check
@retval - true if container contains value
**/
template<class container_t, class T>
bool contains(const container_t& container, const T& value)
{
return contains(container.begin(), container.end(), value);
}
/**
@brief Check if at least one of range elements satisfies predicate
@tparam fwd_it_t - forward iterator type
@tparam predicate_t - predicate type
@param itBegin - range begin iterator
@param itEnd - range end iterator
@param predicate - predicate to check
@retval - true if at least one of range elements satisfies predicate
**/
template<class fwd_it_t, class predicate_t>
bool contains_if(fwd_it_t itBegin, fwd_it_t itEnd, const predicate_t& predicate)
{
return std::find_if(itBegin, itEnd, predicate) != itEnd;
}
/**
@brief Check if at least one of container elements satisfies predicate
@tparam container_t - container type
@tparam predicate_t - predicate type
@param container - container to search in
@param predicate - predicate to check
@retval - true if at least one of container elements satisfies predicate
**/
template<class container_t, class predicate_t>
bool contains_if(const container_t& container, const predicate_t& predicate)
{
return contains_if(container.begin(), container.end(), predicate);
}
} // namespace qx
| true |
3c29e7bf1f710c8e43afdbeb26498ad528d6ec68 | C++ | pedroamadorb/semana07 | /ejemplo_random.cpp | UTF-8 | 490 | 3.28125 | 3 | [] | no_license | #include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
//Limite maximo
cout << "Limite Maximo de Random :" << RAND_MAX << endl << endl;
//Generar numeros randoms
for (int i=0; i < 10; i++)
{
cout << "numero " << i + 1 << " : " << rand() << endl;
}
//Generar 20 numeros randoms entre el 0 a 99
for (int i=0; i < 10; i++)
{
cout << "numero " << i + 1 << " : " << rand() %100 << endl;
}
return 0;
} | true |
5154f4a790a115a1c0379ba2d5208a36ea3990e7 | C++ | shin-eunji/TIL-1 | /Algorithms/N!_ZeroCount.cpp | UTF-8 | 534 | 2.796875 | 3 | [
"MIT"
] | permissive | #include <iostream>
using namespace std;
int main() {
int n, num, tmp;
int count1=0, count2=0;
cin >> n;
for(int i=2; i<=n; ++i) {
tmp = i;
while(tmp != 0) {
if(tmp%2 == 0) {
count1++;
tmp=tmp/2;
}
if(tmp%5 == 0) {
count2++;
tmp=tmp/5;
}
else {
break;
}
}
}
if(count1 <= count2) num = count1;
else num = count2;
cout << num;
} | true |
3f6accabf15fe70eb51e5febee81996ac13f0049 | C++ | JosanSun/MyNote | /C++/关键字/volatile/volatile/volatile.cpp | GB18030 | 751 | 3.171875 | 3 | [] | no_license | /*
* ---------------------------------------------------
* Copyright (c) 2017 josan All rights reserved.
* ---------------------------------------------------
*
* ߣ Josan
* ʱ䣺 2017/10/2 15:10:51
*/
#include <iostream>
using namespace std;
int main()
{
//α
{
const int a = 100;
int * b = const_cast<int *>(&a);
++*b;
cout << *b << endl; //101
cout << a << endl; //100 ŻʵaֵѾΪ101 ԵʱҲ֤
}
{
volatile const int a = 100;
int * b = const_cast<int *>(&a);
++*b;
cout << *b << endl; //101
cout << a << endl; //101 ָvolatile ȥŻԵõ101
}
return 0;
} | true |
d062dbf98b8fc98b37a94a38086d17e46fbfa6ee | C++ | empireofyt/pat-yiji | /1081/1081.cpp | UTF-8 | 919 | 2.796875 | 3 | [] | no_license | #include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include"string.h"
#define M 20
using namespace std;
int mima(char str[],int n)
{
int shuzi=0,zimu=0,fal=0;
if(6>n)
printf("Your password is tai duan le.\n");
else
{
for(int i=0;i<n-1;i++)
{
if(str[i]>='0'&&str[i]<='9')
shuzi++;
else if((str[i]>='a'&&str[i]<='z')||(str[i]>='A'&&str[i]<='Z'))
zimu++;
else if(str[i]=='.'){
}
else
{
printf("Your password is tai luan le.\n");
return 0;
}
}
if(shuzi==0)
printf("Your password needs shu zi.\n");
else if(zimu==0)
printf("Your password needs zi mu.\n");
else
printf("Your password is wan mei.\n");
}
return 0;
}
int main()
{
int n;
cin>>n;
char str[M];
for(int i=0;i<n;i++)
{
scanf("%s",str);
int num = strlen(str);
mima(str,num);
}
return 0;
}
| true |
ca1de2f934f8ac635f49ae77b3ddae5f13ce2da6 | C++ | barteqx/geo2015 | /geometric/deleted/ruleset.cpp | UTF-8 | 3,607 | 2.796875 | 3 | [] | no_license |
// written by Hans de Nivelle, June 2014.
#include "ruleset.h"
std::ostream& geometric::operator << ( std::ostream& out, rule_use r )
{
switch(r)
{
case rule_use::disj_res_active:
out << "disj_act"; return out;
case rule_use::disj_res_passive:
out << "disj_pass"; return out;
case rule_use::ext_res_active:
out << "ext_act"; return out;
case rule_use::ext_res_passive:
out << "ext_pass"; return out;
case rule_use::copy:
out << "copy"; return out;
case rule_use::inst:
out << "inst"; return out;
}
throw std::runtime_error( "fall through with rule_use" );
}
std::ostream& geometric::operator << ( std::ostream& out, parent p )
{
out << p.u << '(' << p.n << ')';
return out;
}
geometric::annotated_rule::annotated_rule( unsigned int number )
: number{number},
r{ {}, {} }
{ }
geometric::annotated_rule::annotated_rule(
unsigned int number, rule&& r )
: number{number},
r{ std::move(r) }
{ }
geometric::annotated_rule::annotated_rule(
unsigned int number, rule&& r, std::vector< parent > && p )
: number{number},
r{ std::move(r) },
parents{ std::move(p) }
{ }
std::ostream& geometric::operator << (
std::ostream& out, const geometric::annotated_rule& ar )
{
out << ar. number << ": ";
out << "active = " << ar. active << ", ";
out << "applied = " << ar. applications << ", ";
out << "simplified = " << ar. simpl << "\n";
if( ar. parents. size( ))
{
out << " parents: ";
for( auto p = ar. parents. begin( ); p != ar. parents. end( ); ++ p )
{
if( p != ar. parents. begin( ))
out << ", ";
out << *p;
}
out << "\n";
}
out << " " << ar. r << "\n";
return out;
}
unsigned int geometric::ruleset::findindex( unsigned int number ) const
{
if( rules. size( ) == 0 || number < rules [0]. number )
return 0;
unsigned int i0 = 0;
unsigned int i1 = rules. size( );
while( i0 + 1 < i1 )
{
unsigned int i = ( i0 + i1 ) / 2;
if( rules [i]. number <= number )
i0 = i;
else
i1 = i;
}
return i1;
}
geometric::ruleset::iterator
geometric::ruleset::insert( annotated_rule&& ar )
{
unsigned int i = findindex( ar. number );
if( i != 0 && rules [ i - 1 ]. number == ar. number )
throw insert_exists( );
std::vector< annotated_rule > :: iterator
p = rules. begin( ) + i;
return rules. insert( p, std::move(ar) );
}
geometric::ruleset::iterator
geometric::ruleset::find( unsigned int nr )
{
unsigned int i = findindex( nr );
if( i == 0 || rules [ i - 1 ]. number != nr )
return rules. end( );
else
return rules. begin( ) + ( i - 1 );
}
geometric::ruleset::const_iterator
geometric::ruleset::find( unsigned int nr ) const
{
unsigned int i = findindex( nr );
if( i == 0 || rules [ i - 1 ]. number != nr )
return rules. cend( );
else
return rules. cbegin( ) + ( i - 1 );
}
geometric::ruleset::iterator
geometric::ruleset::moveto( iterator it, ruleset& rs )
{
if( &rs != this )
{
iterator res = rs. insert( std::move(*it) );
rules. erase( it );
return res;
}
else
return it; // Wsyo tak budyet kak bywalo.
}
std::ostream& geometric::operator << (
std::ostream& out, const geometric::ruleset& rs )
{
for( auto p = rs. begin( ); p != rs. end( ); ++ p )
{
out << "---------------------------------------------------" <<
"------------------------\n";
out << *p;
}
return out;
}
| true |
1092217d05fbc9223a37eec2c04d6fe1b8f16838 | C++ | pythonicrane/ComptuerGraphics | /Simple.cpp | GB18030 | 1,119 | 3.046875 | 3 | [] | no_license | /**
*ͼѧڶ¸
*@author ZhaoHeln 20171130 17:18:30
*/
#include<gl/glut.h>
void init(void)
{
glutSetColor(0, 0.0f, 0.0f, 0.0f);
glutSetColor(1, 1.0f, 0.0f, 0.0f);
glutSetColor(2, 0.0f, 1.0f, 0.0f);
glutSetColor(3, 0.0f, 0.0f, 1.0f);
glClearColor(1.0, 1.0, 1.0, 0.5);//ڱɫ
glMatrixMode(GL_PROJECTION);//ģͣʲô
gluOrtho2D(0.0, 200.0, 0.0, 150.0);//2DͶӰ
}
void lineSegment(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0, 0.0, 0.0);
glBegin(GL_POINT);
glVertex2i(50, 100);
glVertex2i(75, 150);
glVertex2i(100, 200);
glEnd();
glFlush();
}
int main(int argc, char** argv)
{
/*GLUTʼ*/
glutInit(&argc, argv);//һõĺ
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);//ʾʽ
glutInitWindowPosition(50, 100);//ʾλ
glutInitWindowSize(400, 300);//ڴС
glutCreateWindow("An Example OpenGL Program");//ڲֵ
init();//ʼ
glutDisplayFunc(lineSegment);//ʾ
glutMainLoop();//ѭ
return 0;
}
| true |
7a47efe6404ab36969cf3d6e80bd2353e0bc27cd | C++ | cies96035/CPP_programs | /Kattis/AC/nodup.cpp | UTF-8 | 384 | 2.53125 | 3 | [] | no_license | #include<iostream>
#include<set>
using namespace std;
string ipt;
bool dup;
set<string> dic;
int main()
{
cin.tie(0);
ios_base::sync_with_stdio(0);
while(cin >> ipt){
if(dic.find(ipt) != dic.end()){
dup = true;
}
dic.insert(ipt);
}
if(dup){
cout << "no\n";
}else{
cout << "yes\n";
}
return 0;
} | true |
879966f0fbb73c4408dd821a279c3aa58f327ddb | C++ | Victor-Frocrain/FUN_imageCompressor_2019 | /bonus/imageReader/src/Parser.cpp | UTF-8 | 552 | 2.6875 | 3 | [] | no_license | /*
** EPITECH PROJECT, 2020
** Parser
** File description:
** Parser.cpp
*/
#include "../include/Parser.hpp"
#include "../include/ImageReaderException.hpp"
Parser::Parser(const int &ac, char **&args)
{
if (ac == 2) {
_filePath = args[1];
}
else {
throw ImageReaderException("Please, enter 2 arguments");
}
}
Parser::~Parser()
{}
sf::Image Parser::openFile() const
{
sf::Image image;
if (!image.loadFromFile(_filePath)) {
throw ImageReaderException("Cannot load the file.");
}
return image;
} | true |
7583e725ce83bdd9986b0f7581ac6b7b342b5dd8 | C++ | bluedawnstar/algorithm_study | /library/polynomial/pentagonalNumber.cpp | UTF-8 | 1,713 | 2.78125 | 3 | [
"Unlicense"
] | permissive | #include <vector>
#include <algorithm>
using namespace std;
#include "pentagonalNumber.h"
/////////// For Testing ///////////////////////////////////////////////////////
#include <time.h>
#include <cassert>
#include <string>
#include <iostream>
#include "../common/iostreamhelper.h"
#include "../common/profile.h"
#include "../common/rand.h"
void testPentagonalNumber() {
//return; //TODO: if you want to test, make this line a comment.
cout << "--- Pentagonal Number theorem ----------------" << endl;
{
/*
0, 1, 2, 5, 7, 12, 15, 22, 26, 35, 40, 51, 57, 70, 77, 92, 100, 117, 126, 145, 155, 176, 187, 210, 222, 247, 260, 287, 301, 330, 345, 376, 392, 425, 442, 477, 495, 532, 551, 590, 610, 651, 672, 715, 737, 782, 805, 852, 876, 925, 950
*/
vector<pair<int, int>> gt{
{ 0, 1}, { 1, -1}, { 2, -1}, { 5, 1}, { 7, 1}, { 12, -1}, { 15, -1}, { 22, 1}, { 26, 1},
{ 35, -1}, { 40, -1}, { 51, 1}, { 57, 1}, { 70, -1}, { 77, -1}, { 92, 1}, {100, 1}, {117, -1},
{126, -1}, {145, 1}, {155, 1}, {176, -1}, {187, -1}, {210, 1}, {222, 1}, {247, -1}, {260, -1},
{287, 1}, {301, 1}, {330, -1}, {345, -1}, {376, 1}, {392, 1}, {425, -1}, {442, -1}, {477, 1},
{495, 1}, {532, -1}, {551, -1}, {590, 1}, {610, 1}, {651, -1}, {672, -1}, {715, 1}, {737, 1},
{782, -1}, {805, -1}, {852, 1}, {876, 1}, {925, -1}, {950, -1}
};
auto sequence = PentagonalNumber::generalizedPentagonalNumbers(1000);
if (sequence != gt) {
cout << "Mismatched : " << sequence << ", " << gt << endl;
}
assert(sequence == gt);
}
cout << "OK!" << endl;
}
| true |
14fe24d13fcfcd459cb9dddfaa97c6e2d4a6a4d6 | C++ | tigoe/MakingThingsTalk2 | /chapter9/project27/SonMicroFirmware/SonMicroFirmware.ino | UTF-8 | 924 | 3.0625 | 3 | [] | no_license |
/*
SM130 Firmware reader
Context: Arduino
*/
#include <Wire.h>
void setup() {
// initialize serial and I2C:
Serial.begin(9600);
Wire.begin();
// give the reader time to reset:
delay(2000);
Serial.println("asking for firmware");
// open the I2C connection,
// the I2C address for the reader is 0x42:
Wire.beginTransmission(0x42);
Wire.write(0x01); // length
Wire.write(0x81); // command
Wire.write(0x82); // checksum
Wire.endTransmission();
// reader needs 50ms in between responses:
delay(50);
Serial.print("getting reply: ");
// wait for ten bytes back via I2C:
Wire.requestFrom(0x42,10);
// don't do anything until new bytes arrive:
while(!Wire.available()) {
delay(50);
}
// when new bytes arrive on the I2C bus, read them:
while(Wire.available()) {
Serial.write(Wire.read());
}
// add a newline:
Serial.println();
}
void loop() {
}
| true |
e8f06007e3d2f3b80be9adbc01b4b1ac50739970 | C++ | llwwlql/Dictionary | /代码库/Dev c++/Dividing.cpp | GB18030 | 1,082 | 2.71875 | 3 | [] | no_license | #include <stdio.h>
#include <string.h>
int dp[120005];
void ZeroOnePack(int v,int w,int V)
{
int j;
for(j=V;j>=w;j--)
{
if(dp[j-w]+v>dp[j])
dp[j]=dp[j-w]+v;
}
}
int main()
{
int n[10],N=6;
int V;
int i,j,k;
int index=0;
while(scanf("%d %d %d %d %d %d",&n[1],&n[2],&n[3],&n[4],&n[5],&n[6]),n[1]||n[2]||n[3]||n[4]||n[5]||n[6])
{
index++;
V=0;
for(i=1;i<=N;i++)
V+=n[i]*i;
if(V%2==0)
{
V/=2;
memset(dp,0,sizeof(dp));
for(i=1;i<=N;i++)
{
if(n[i]*i>=V) //ȫ
{
for(j=i;j<=V;j++) //iʼѭģ1ѭj-iҲ
{
if(dp[j-i]+i>dp[j])
dp[j]=dp[j-i]+i;
}
}
else
{
for(k=1;k<n[i];k*=2) //ֲ
{
ZeroOnePack(k*i,k*i,V);
n[i]=n[i]-k;
}
ZeroOnePack(n[i]*i,n[i]*i,V);
}
}
if(dp[V]==V)
printf("Collection #%d:\nCan be divided.\n\n",index);
else
printf("Collection #%d:\nCan't be divided.\n\n",index);
}
else
printf("Collection #%d:\nCan't be divided.\n\n",index);
}
return 0;
}
| true |
bf88eca22575c7a327b80de4940332e008297eb1 | C++ | ctkhanhly/C- | /homework/hw07/gameOfMedievalTIme/Lord.cpp | UTF-8 | 2,633 | 3.109375 | 3 | [] | no_license | #include "Lord.h"
#include "Protector.h"
using namespace std;
namespace WarriorCraft{
size_t Lord::lookForProtector(Protector& protector) const{
size_t pIndex = armyOfProtectors.size();
for(size_t i = 0; i < armyOfProtectors.size(); ++i){
if(armyOfProtectors[i] == &protector){
pIndex = i;
break;
}
}
if(pIndex == armyOfProtectors.size()){
cerr << "You didn't hire this warrior, cannot fire" << endl;
}
return pIndex;
}
Lord::Lord(const string& name): Noble(name){}
bool Lord::hires(Protector& protector){
if(Noble::getIsDead() || protector.getIsHired() || protector.getIsDead()){
return false;
}
else{
protector.setIsHired(true);
protector.setLord(this);
armyOfProtectors.push_back(&protector);
Noble::setStrength(Noble::getStrength()+ protector.getStrength());
return true;
}
}
bool Lord::fires(Protector& protector){
if(Noble::getIsDead()){
return false;
}
else{
if(!deleteProtector(protector)){
cerr << "Couldn't remove the Warrior" << endl;
return false;
}
return true;
}
}
bool Lord::deleteProtector(Protector& protector){
size_t pIndex = lookForProtector(protector);
if(pIndex == armyOfProtectors.size()){
return false;
}
for(size_t i = pIndex; i < armyOfProtectors.size(); ++i){
armyOfProtectors[i] = armyOfProtectors[i+1];
}
armyOfProtectors.pop_back();
Noble::setStrength(Noble::getStrength() - protector.getStrength());
protector.setIsHired(false);
protector.setLord(nullptr);
return true;
}
void Lord::setStrengthLoser(){
for(Protector* const protector : armyOfProtectors){
protector->setStrength(0);
protector->setIsDead(true);
}
Noble::setStrengthLoser();
}
void Lord::setStrengthWinner(Noble& loser){
double ratio = loser.getStrength() / Noble::getStrength();
for(Protector* const protector : armyOfProtectors){
double curr_strength = protector->getStrength();
protector->setStrength(curr_strength*(1-ratio));
}
Noble::setStrength(Noble::getStrength() * (1 - ratio));
}
void Lord::wayOfDefending() const{
for(Protector* protector: armyOfProtectors){
protector->wayOfDefending();
}
}
} | true |
c41d9dc7a5a25a7668963e8b1c6beb0c2c4b2a3d | C++ | sfofgalaxy/Summary-of-Software-Engineering-Coursework-in-Zhejiang-University | /2大二/面向对象程序设计/教师内部资料/Courseware/review/异质list/IntNode.h | WINDOWS-1252 | 144 | 2.765625 | 3 | [] | no_license | class IntNode : public Node
{
int i;
public:
IntNode(int ii=0): i(ii)
{}
void print() const
{
cout << "" << i << endl;
}
};
| true |
d30a8c5d863724f314d0688760c2e1cb916fca75 | C++ | conornewton/timetabling-bristol | /src/Data/Teachers.cpp | UTF-8 | 1,480 | 3.140625 | 3 | [] | no_license | #include "Teachers.hpp"
#include "../CSV/CSV.hpp"
#include "Data.hpp"
#include "Activities.hpp"
#include <sstream>
std::string Teacher::to_string() {
std::stringstream s;
s << ID << ", ";
for (int a : activities) {
s << a << " ";
}
s << pathway_one << ", ";
for (int t : bad_timeslots) {
s << t << " ";
}
return s.str();
}
std::string Teachers::to_string() {
std::stringstream s;
for (Teacher& t: data) {
s << t.to_string();
s << "\n";
}
return s.str();
}
Teachers::Teachers() {
CSV csv_staff(FILEPATH_TEACHERS);
while (csv_staff.next_line()) {
auto values = csv_staff.get_values();
Teacher t;
t.ID = values[0];
std::vector<std::string> activity_values = split(values[1], ',');
for (int i = 0; i < activity_values.size(); i++) {
t.activities.push_back(stoi(activity_values[i]));
}
if (values[2][0] == '1') {
t.pathway_one = true;
} else {
t.pathway_one = false;
}
std::vector<std::string> timeslot_values = split(values[3], ',');
for (int i = 0; i < timeslot_values.size(); i++) {
t.bad_timeslots.push_back(stoi(timeslot_values[i]));
}
data.push_back(t);
}
}
Teacher& Teachers::operator[](const int& a) {
return this->data[a];
}
int Teachers::size() {
return data.size();
}
bool Teachers::is_bad_timeslot(const int& t, const int& ts) {
Teacher& teach = data[t];
return std::find(teach.bad_timeslots.begin(), teach.bad_timeslots.end(), ts) != teach.bad_timeslots.end();
} | true |
d327c3cdd93bae5a8113f84fc7a5e0c4959ce7c5 | C++ | matanki-saito/BMFont | /source/acutil_path.cpp | UTF-8 | 6,135 | 2.671875 | 3 | [
"Zlib"
] | permissive | /*
AngelCode Tool Box Library
Copyright (c) 2012-2016 Andreas Jonsson
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you
must not claim that you wrote the original software. If you use
this software in a product, an acknowledgment in the product
documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
Andreas Jonsson
andreas@angelcode.com
*/
// 2016-02-21 Fixes for 64bit
// 2014-06-16 Updated to support build both for unicode and multibyte applications
// 2013-06-15 Fixed GetFullPath() to handle relative base paths
// 2013-06-15 Fixed crash in GetRelativePath() when both paths refer to same directory
#include "acutil_path.h"
#include <windows.h>
#include "acwin_window.h"
using namespace std;
namespace acUtility
{
string ReplacePathSlashes(const string &path)
{
string tmp(path);
// Replace all backslashes with forward slashes
size_t pos;
while( (pos = tmp.find("\\")) != string::npos )
tmp[pos] = '/';
return tmp;
}
string GetApplicationPath()
{
// Get the full path of the application
TCHAR buffer[300];
GetModuleFileName(0, buffer, 300);
string path;
acWindow::ConvertTCharToUtf8(buffer, path);
// Replace all backslashes with forward slashes
path = ReplacePathSlashes(path);
// Cut of the name of the application
size_t n = path.rfind("/");
path = path.substr(0, n+1);
return path;
}
string GetFullPath(const string &base, const string &relative)
{
string b = ReplacePathSlashes(base);
string r = ReplacePathSlashes(relative);
// Make sure the base path doesn't contain a filename
if( b[b.size()-1] != '/' )
{
size_t pos = b.rfind("/");
b = b.substr(0, pos+1);
}
// Get the drive letter from the base path
string drive, path;
size_t pos = b.find(":");
if( pos != string::npos )
{
drive = b.substr(0, pos);
path = b.substr(pos+1);
}
else
{
// The base itself is a relative path so get the current working directory
TCHAR buf[MAX_PATH];
GetCurrentDirectory(MAX_PATH, buf);
string cwd;
acWindow::ConvertTCharToUtf8(buf, cwd);
if( b.length() > 0 && b[0] == '/' )
{
// The base is an absolute path in current drive
path = cwd.substr(0, 2);
path += b;
}
else
path = ReplacePathSlashes(cwd) + '/' + b;
drive = path.substr(0, 1);
path = path.substr(2);
}
// Does the relative path contain a drive letter?
if( (pos = r.find(":")) != string::npos )
{
// The relative path is already a full path
drive = r.substr(0, pos);
path = r.substr(pos+1);
}
else if( r[0] == '/' )
{
// Relative path is a full path on the current drive
path = r;
}
else
{
// Add the relative path to the base path
path += r;
}
// Remove any ../ in the path
for(;;)
{
pos = path.find("../");
if( pos != string::npos && pos > 1 )
{
size_t p2 = path.rfind("/", pos-2);
path = path.substr(0, p2+1) + path.substr(pos+3);
}
else
break;
}
// Remove any ./ in the path
for(;;)
{
pos = path.find("./");
if( pos != string::npos && pos > 0 )
path = path.substr(0, pos-1) + path.substr(pos+2);
else
break;
}
return drive + ":" + path;
}
string GetRelativePath(const string &base, const string &relative)
{
string b = ReplacePathSlashes(base);
string r = ReplacePathSlashes(relative);
// Make sure the base path doesn't contain a filename and ends with /
if( b[b.size()-1] != '/' )
{
size_t pos = b.rfind("/");
b = b.substr(0, pos+1);
}
// Get the drive letter from the base path
string drive, path;
size_t pos = b.find(":");
if( pos != string::npos )
{
drive = b.substr(0, pos);
path = b.substr(pos+1);
}
else
path = b;
string driveRel, pathRel;
if( (pos = r.find(":")) != string::npos )
{
// The relative path is a full path
driveRel = r.substr(0, pos);
pathRel = r.substr(pos+1);
// Caseless comparison on Windows
// TODO: Linux uses case sensitive file names
if( _stricmp(driveRel.c_str(), drive.c_str()) != 0 )
{
// The drive is different, so the relative path must be taken as a whole
drive = "";
path = "";
}
else
{
// The drive letter won't be used anymore
drive = "";
driveRel = "";
}
}
else if( r[0] == '/' )
{
// The relative path doesn't specify drive, but is an absolute path.
// We'll assume it is the same drive as the base
// The drive letter won't be used anymore
drive = "";
pathRel = r;
}
else
{
// If the relative path is already a relative path
// then assume it is relative to the base path already
// The base path and drive won't be used anymore
drive = "";
path = "";
pathRel = r;
}
// TODO: Clean up the paths to remove unnecessary ../ and ./
if( path != "" )
{
// Remove the common path
// base = /a/b/c/d/
// rel = /a/b/e/f/
for(;;)
{
size_t pbase = path.find("/");
size_t prel = pathRel.find("/");
// Caseless comparison on Windows
// TODO: Linux uses case sensitive file names
if( pbase != string::npos && prel != string::npos &&
pbase == prel && _strnicmp(&path[0], &pathRel[0], pbase) == 0 )
{
path = path.substr(pbase+1);
pathRel = pathRel.substr(pbase+1);
}
else
break;
}
// Add the necessary ../
// base = c/d/
// rel = e/f/
int count = 0;
size_t pos = 0;
for(;;)
{
pos = path.find("/", pos);
if( pos++ != string::npos )
count++;
else
break;
}
path = "";
for( int n = 0; n < count; n++ )
path += "../";
pathRel = path + pathRel;
}
else if( driveRel != "" )
{
pathRel = driveRel + ":" + pathRel;
}
return pathRel;
}
}
| true |
65003774c8ea5694f9149bcd273b3866b666ce8a | C++ | mobi12/study | /cpp/move.cpp | UTF-8 | 217 | 3 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int *pt = new int [10];
pt[0] = 1;
pt[1] = 2;
pt[5] = 5;
cout << pt[0] << endl;
cout << pt[1] << endl;
cout << pt[5] << endl;
delete pt;
return 0;
}
| true |
52b73f93ab41e1a0743fd177800792b062667d3a | C++ | sebbekarlsson/cpluspong | /Game.h | UTF-8 | 3,965 | 3.109375 | 3 | [] | no_license | extern const int WIDTH;
extern const int HEIGHT;
extern const int SCALE;
SDL_Window* display = NULL;
class Game {
public:
bool quit;
std::list<Instance*> instances;
std::list<Instance*>::iterator iter;
SDL_GLContext context;
/**
* Constructor
*/
Game () {
this->quit = false;
}
/**
* This function is used to initialize the openGL.
* @return <bool>
*/
bool initGL () {
bool success = true;
GLenum error = GL_NO_ERROR;
glClearColor(0, 0, 0, 0);
glClearDepth(1.0f);
glViewport(0, 0, WIDTH * SCALE, HEIGHT * SCALE);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, WIDTH * SCALE, HEIGHT * SCALE, 0, 1, -1);
glMatrixMode(GL_MODELVIEW);
glEnable(GL_TEXTURE_2D);
glEnable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glLoadIdentity();
glClearColor(
(float)(255/255),
(float)(255/255),
(float)(255/255),
1.0f
);
return success;
}
/**
* This function is used to initialize the display/window with
* the OpenGL context.
* @return <bool>
*/
bool init () {
bool success = true;
if (!SDL_Init(SDL_INIT_VIDEO) < 0) {
printf("Could not initialize video", SDL_GetError());
success = false;
} else {
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
display = SDL_CreateWindow (
"Game Title",
0,
0,
WIDTH * SCALE,
HEIGHT * SCALE,
SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN
);
if (display == NULL) {
printf("Could not create display", SDL_GetError());
} else {
context = SDL_GL_CreateContext(display);
if (context == NULL) {
printf("Could not create context", SDL_GetError());
success = false;
} else {
if (!initGL()) {
printf("Could not initialize OpenGL", SDL_GetError());
success = false;
}
}
}
}
return success;
}
/**
* Tick/Update function.
*/
void update (float delta) {
Instance *instance;
for (iter = instances.begin() ; iter != instances.end(); iter++) {
instance = &**iter;
instance->tick(delta);
}
}
/**
* This function is used to draw a rotating green plane.
*/
void render (float delta) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
Instance *instance;
for (iter = instances.begin() ; iter != instances.end(); iter++) {
instance = &**iter;
instance->draw(delta);
}
}
/**
* This function is used to terminating and killing the program.
*/
void close () {
SDL_DestroyWindow(display);
display = NULL;
SDL_Quit();
}
};
| true |
9457c8855f4d858292a772845038bc2c676d614c | C++ | alisw/AliPhysics | /PWGCF/FEMTOSCOPY/AliFemto/AliFemtoTrio.cxx | UTF-8 | 5,127 | 2.71875 | 3 | [] | permissive | ///
/// \file AliFemtoTrio.h
/// \author Jeremi Niedziela
#include <TMath.h>
#include "AliFemtoTrio.h"
#include "AliFemtoLorentzVector.h"
AliFemtoTrio::AliFemtoTrio():
fTrack1(nullptr),
fTrack2(nullptr),
fTrack3(nullptr),
fTrack1type(kUnknown),
fTrack2type(kUnknown),
fTrack3type(kUnknown)
{
}
AliFemtoTrio::AliFemtoTrio(const AliFemtoTrio& trio):
fTrack1(trio.fTrack1),
fTrack2(trio.fTrack2),
fTrack3(trio.fTrack3),
fTrack1type(trio.fTrack1type),
fTrack2type(trio.fTrack2type),
fTrack3type(trio.fTrack3type)
{
}
AliFemtoTrio::~AliFemtoTrio()
{
}
AliFemtoTrio& AliFemtoTrio::operator=(const AliFemtoTrio& trio)
{
fTrack1 = trio.fTrack1;
fTrack2 = trio.fTrack2;
fTrack3 = trio.fTrack3;
fTrack1type = trio.fTrack1type;
fTrack2type = trio.fTrack2type;
fTrack3type = trio.fTrack3type;
return *this;
}
double AliFemtoTrio::MInv()
{
if(!fTrack1 || !fTrack2 || !fTrack3){
cout<<"W - AliFemtoTrio::MInv - track missing in a trio"<<endl;
cout<<"track1:"<<fTrack1<<endl;
cout<<"track2:"<<fTrack2<<endl;
cout<<"track3:"<<fTrack3<<endl;
return -1.0;
}
AliFemtoLorentzVector p1 = fTrack1->FourMomentum();
AliFemtoLorentzVector p2 = fTrack2->FourMomentum();
AliFemtoLorentzVector p3 = fTrack3->FourMomentum();
double E = p1.e() + p2.e() + p3.e();
double px = p1.px() + p2.px() + p3.px();
double py = p1.py() + p2.py() + p3.py();
double pz = p1.pz() + p2.pz() + p3.pz();
// double m_inv = abs(fTrack1->FourMomentum() + fTrack2->FourMomentum() + fTrack3->FourMomentum());
return sqrt(E*E-(px*px+py*py+pz*pz));
}
double AliFemtoTrio::MInv12()
{
if(!fTrack1 || !fTrack2 || !fTrack3){
cout<<"W - AliFemtoTrio::MInv - track missing in a trio"<<endl;
cout<<"track1:"<<fTrack1<<endl;
cout<<"track2:"<<fTrack2<<endl;
cout<<"track3:"<<fTrack3<<endl;
return -1.0;
}
AliFemtoLorentzVector p1 = fTrack1->FourMomentum();
AliFemtoLorentzVector p2 = fTrack2->FourMomentum();
double E = p1.e() + p2.e();
double px = p1.px() + p2.px();
double py = p1.py() + p2.py();
double pz = p1.pz() + p2.pz();
return sqrt(E*E-(px*px+py*py+pz*pz));
}
double AliFemtoTrio::MInv23()
{
if(!fTrack1 || !fTrack2 || !fTrack3){
cout<<"W - AliFemtoTrio::MInv - track missing in a trio"<<endl;
cout<<"track1:"<<fTrack1<<endl;
cout<<"track2:"<<fTrack2<<endl;
cout<<"track3:"<<fTrack3<<endl;
return -1.0;
}
AliFemtoLorentzVector p2 = fTrack2->FourMomentum();
AliFemtoLorentzVector p3 = fTrack3->FourMomentum();
double E = p2.e() + p3.e();
double px = p2.px() + p3.px();
double py = p2.py() + p3.py();
double pz = p2.pz() + p3.pz();
return sqrt(E*E-(px*px+py*py+pz*pz));
}
double AliFemtoTrio::MInv31()
{
if(!fTrack1 || !fTrack2 || !fTrack3){
cout<<"W - AliFemtoTrio::MInv - track missing in a trio"<<endl;
cout<<"track1:"<<fTrack1<<endl;
cout<<"track2:"<<fTrack2<<endl;
cout<<"track3:"<<fTrack3<<endl;
return -1.0;
}
AliFemtoLorentzVector p3 = fTrack3->FourMomentum();
AliFemtoLorentzVector p1 = fTrack1->FourMomentum();
double E = p3.e() + p1.e();
double px = p3.px() + p1.px();
double py = p3.py() + p1.py();
double pz = p3.pz() + p1.pz();
return sqrt(E*E-(px*px+py*py+pz*pz));
}
double AliFemtoTrio::GetTheta12()
{
AliFemtoLorentzVector a = fTrack1->FourMomentum();
AliFemtoLorentzVector b = fTrack2->FourMomentum();
AliFemtoLorentzVector c = fTrack3->FourMomentum();
AliFemtoLorentzVector r = a+b;
AliFemtoLorentzVector je = r+c;
je.boost(r);
return r.Theta()-je.Theta();
}
double AliFemtoTrio::GetTheta23()
{
AliFemtoLorentzVector a = fTrack2->FourMomentum();
AliFemtoLorentzVector b = fTrack3->FourMomentum();
AliFemtoLorentzVector c = fTrack1->FourMomentum();
AliFemtoLorentzVector r = a+b;
AliFemtoLorentzVector je = r+c;
je.boost(r);
return r.Theta()-je.Theta();
}
double AliFemtoTrio::GetTheta31()
{
AliFemtoLorentzVector a = fTrack3->FourMomentum();
AliFemtoLorentzVector b = fTrack1->FourMomentum();
AliFemtoLorentzVector c = fTrack2->FourMomentum();
AliFemtoLorentzVector r = a+b;
AliFemtoLorentzVector je = r+c;
je.boost(r);
return r.Theta()-je.Theta();
}
double AliFemtoTrio::GetTheta1()
{
AliFemtoLorentzVector a = fTrack2->FourMomentum();
AliFemtoLorentzVector b = fTrack3->FourMomentum();
AliFemtoLorentzVector c = fTrack1->FourMomentum();
AliFemtoLorentzVector r = a+b;
AliFemtoLorentzVector je = r+c;
je.boost(c);
return c.Theta()-je.Theta();
}
double AliFemtoTrio::GetTheta2()
{
AliFemtoLorentzVector a = fTrack3->FourMomentum();
AliFemtoLorentzVector b = fTrack1->FourMomentum();
AliFemtoLorentzVector c = fTrack2->FourMomentum();
AliFemtoLorentzVector r = a+b;
AliFemtoLorentzVector je = r+c;
je.boost(c);
return c.Theta()-je.Theta();
}
double AliFemtoTrio::GetTheta3()
{
AliFemtoLorentzVector a = fTrack1->FourMomentum();
AliFemtoLorentzVector b = fTrack2->FourMomentum();
AliFemtoLorentzVector c = fTrack3->FourMomentum();
AliFemtoLorentzVector r = a+b;
AliFemtoLorentzVector je = r+c;
je.boost(c);
return c.Theta()-je.Theta();
}
| true |
694bb7b4f86223a1a8f56fcee58502bb193f206c | C++ | firiexp/contest_log | /yukicoder/193.cpp | UTF-8 | 1,002 | 2.53125 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <iomanip>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <numeric>
#include <bitset>
static const int MOD = 1000000007;
using ll = int64_t;
using u32 = uint32_t;
using namespace std;
template<class T> constexpr T INF = ::numeric_limits<T>::max()/32*15+208;
int f(string &s){
if(s.front() == '+' || s.front() == '-') return -MOD;
if(s.back() == '+' || s.back() == '-') return -MOD;
int ret = 0, c = 0, f = 1;
for (auto &&i : s) {
if(i == '+') ret += c*f, c = 0, f = 1;
else if(i == '-') ret += c*f, c = 0, f = -1;
else {
c = c*10+(i-'0');
}
}
ret += c*f;
return ret;
}
int main() {
string s;
cin >> s;
int ans = -MOD;
s = s+s;
for (int i = 0; i < s.size()/2; ++i) {
string t = s.substr(i, s.size()/2);
ans = max(ans, f(t));
}
cout << ans << "\n";
return 0;
}
| true |
5a926376cf797866af128e9798f86e788285fbb3 | C++ | devang-m/DataStructure-Algo-Practice | /Dijkstra2.cpp | UTF-8 | 1,347 | 2.578125 | 3 | [] | no_license | //http://codeforces.com/problemset/problem/20/C
#include <vector>
#include <cmath>
#include <queue>
#include <stack>
#include <string>
#define loop(i,n) for(int i = 0; i < n; i++)
#define pb push_back
#define INF 1e15
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> ipair;
int main()
{
int m,n;
cin >> n >> m;
vector< ipair > A[n+1];
priority_queue< ipair, vector <ipair> , greater<ipair> > p;
while(m--)
{
int a,b,d;
cin >> a >> b >> d;
A[a].pb(make_pair(b,d));
A[b].pb(make_pair(a,d));
}
vector<ll> dist(n+1, INF);
vector<int> prev(n+1,-1);
dist[1]=0;
p.push(make_pair(0,1));
while(!p.empty())
{
int x = p.top().second;
p.pop();
for(int i = 0;i<A[x].size();i++)
{
int node = A[x][i].first;
int weight = A[x][i].second;
if(dist[node] > dist[x] + weight)
{
prev[node]=x;
dist[node]= dist[x]+weight;
p.push(make_pair(dist[x]+weight,node));
}
}
}
//cout << dist[n] << endl;
stack <int> s;
s.push(n);
int next = n,flag=0;
while(true)
{
if(next==1)
break;
if(prev[next] == -1)
{
flag=1;
break;
}
s.push(prev[next]);
next = prev[next];
}
if(flag==1)
{
cout << "-1\n";
}
else
{
int size = s.size();
for(int i=0;i<size;i++)
{
int ans = s.top();
s.pop();
cout << ans << " ";
}
cout << endl;
}
}
| true |
3f8a62139f015f426e1aca5f9da71778ea00d484 | C++ | xucaimao/netlesson | /pa3/cy08-02.cpp | UTF-8 | 1,401 | 3.484375 | 3 | [] | no_license | /*
程序设计实习MOOC /程序设计与算法(三)第八周测验(2018秋季)
2:按距离排序
write by xucaimao,2018-10-24
非常神奇的函数对象,
*/
#include <iostream>
#include <cmath>
#include <algorithm>
#include <string>
using namespace std;
template <class T1,class T2>
struct Closer {
// 在此处补充你的代码
private:
T1 n;
T2 op;
public:
Closer(T1 n_,T2 op_):n(n_),op(op_){}
bool operator()(T1 &a,T1 &b){
if( op(n,a)<op(n,b) )
return true;
else if( op(n,a)==op(n,b) && a<b )
return true;
else
return false;
}
};
int Distance1(int n1,int n2) {
return abs(n1-n2);
}
int Distance2(const string & s1, const string & s2)
{
return abs((int)s1.length()- (int) s2.length());
}
int a[10] = { 0,3,1,4,7,9,20,8,10,15};
string b[6] = {"American","Jack","To","Peking","abcdefghijklmnop","123456789"};
int main()
{
freopen("/Users/xcm/xcmprogram/netlesson/pa3/in.txt","r",stdin);
int n;string s;
while( cin >> n >> s ) {
sort(a,a+10,Closer<int ,int (*)(int ,int)> (n,Distance1));
for(int i = 0;i < 10; ++i)
cout << a[i] << "," ;
cout << endl;
sort(b,b+6,Closer<string,int (*)(const string &,const string & )> (s,Distance2));
for(int i = 0;i < 6; ++i)
cout << b[i] << "," ;
cout << endl;
}
return 0;
} | true |
91f2157ff06cd8692f0c70b0205c31d298e68506 | C++ | k-eck/DataStructures-List | /List.h | UTF-8 | 4,906 | 3.578125 | 4 | [] | no_license | #pragma once
template <typename T>
class List
{
struct ListNode
{
ListNode()
{
}
T mData;
ListNode* mPrev;
ListNode* mNext;
};
int mSize;
ListNode* mHead;
ListNode* mTail;
T mUndefined;
public:
List()
{
mHead = new ListNode;
mTail = new ListNode;
mHead->mNext = mTail;
mHead->mPrev = nullptr;
mTail->mPrev = mHead;
mTail->mNext = nullptr;
mSize = 0;
}
//Copy Constructor
List( const List& tOther ) : List()
{
*this = tOther;
}
List& operator = ( const List& tRHS )
{
if ( mSize > 0 ) Clear();
if ( tRHS.mHead->mNext == mTail ) return *this;
for ( List<T>::Iterator tIter = tRHS.Begin(); tIter != tRHS.End(); tIter++ ) {
PushBack( tIter.GetData() );
}
return *this;
}
//Destructor
~List()
{
Clear();
delete mHead;
delete mTail;
}
void PushFront(const T& tWhat)
{
ListNode* tTempNode = new ListNode();
tTempNode->mData = tWhat;
tTempNode->mPrev = mHead;
tTempNode->mNext = mHead->mNext;
mHead->mNext->mPrev = tTempNode;
mHead->mNext = tTempNode;
mSize++;
}
void PopFront()
{
if ( mHead->mNext == mTail )
{//Nothing to pop!
return;
}
ListNode* tTempPtr = mHead->mNext;
mHead->mNext = mHead->mNext->mNext;
mHead->mNext->mPrev = mHead;
delete tTempPtr;
mSize--;
}
T& Front()
{
if ( mHead->mNext == mTail )
{//No data
return mUndefined;
}
else return mHead->mNext->mData;
}
void PushBack( const T& tWhat )
{
ListNode* tTempNode = new ListNode();
tTempNode->mData = tWhat;
tTempNode->mNext = mTail;
tTempNode->mPrev = mTail->mPrev;
mTail->mPrev->mNext = tTempNode;
mTail->mPrev = tTempNode;
mSize++;
}
void PopBack()
{
if ( mTail->mPrev == mHead )
{//Nothing to pop!
return;
}
ListNode* tTempPtr = mTail->mPrev;
mTail->mPrev = mTail->mPrev->mPrev;
mTail->mPrev->mNext = mTail;
mSize--;
}
T& Back()
{
if ( mTail->mPrev == mHead )
{//No data
return mUndefined;
}
else return mTail->mPrev->mData;
}
int Size() const
{
return mSize;
}
void Clear()
{
if ( mHead->mNext == mTail )return;
for ( int i = 0; i < mSize; )
{
PopBack();
}
}
T& At( int tWhere )
{
if ( tWhere > mSize || tWhere < 0 ) return mUndefined;
ListNode* tTempPtr = mHead->mNext;
for ( int i = 0; i < tWhere; i++ )
{
tTempPtr = tTempPtr->mNext;
}
return tTempPtr->mData;
}
///////////////////////////////////////////////////////////////////
// Iterators
class Iterator
{
ListNode* mCurrent;
T mUndefined;
friend class List;
public:
Iterator()
{
mCurent = nullptr;
}
Iterator( ListNode* tStart )
{
mCurrent = tStart;
}
T& GetData()
{
if ( mCurrent->mPrev == nullptr || mCurrent->mNext == nullptr )
return mUndefined;
else
return mCurrent->mData;
}
void Next()// As in "Move to the next item please"
{
if ( mCurrent->mNext != nullptr )
{
mCurrent = mCurrent->mNext;
}
}
void Back() {
if ( mCurrent->mPrev != nullptr )
{
mCurrent = mCurrent->mPrev;
}
}
bool IsEqual( const Iterator& tRHS )
{
if ( mCurrent == tRHS.mCurrent )
return true;
else
return false;
}
bool operator == ( const Iterator& tRHS )
{
return IsEqual( tRHS );
}
bool operator != ( const Iterator& tRHS )
{
return !( IsEqual( tRHS ) );
}
Iterator operator ++ ()
{
Next();
return *this;
}
Iterator operator ++ ( int )
{
Next();
return *this;
}
Iterator operator -- ()
{
Back();
return *this;
}
Iterator operator -- ( int )
{
Back();
return *this;
}
};
Iterator Insert( Iterator& tWhere, const T& tWhat )
{
if ( tWhere.mCurrent->mPrev == nullptr
|| tWhere.mCurrent->mNext == nullptr
|| tWhere.mCurrent == nullptr ) return Iterator( nullptr );
ListNode* tTempPtr = new ListNode();
tTempPtr->mData = tWhat;
tTempPtr->mNext = tWhere.mCurrent;
tTempPtr->mPrev = tWhere.mCurrent->mPrev;
tWhere.mCurrent->mPrev->mNext = tTempPtr;
tWhere.mCurrent->mPrev = tTempPtr;
tWhere.mCurrent = tWhere.mCurrent->mPrev;
mSize++;
return tWhere;
}
Iterator Erase( Iterator& tWhere )
{
if ( tWhere.mCurrent->mPrev == nullptr
|| tWhere.mCurrent->mNext == nullptr
|| tWhere.mCurrent == nullptr) return Iterator( nullptr );
tWhere.mCurrent->mPrev->mNext = tWhere.mCurrent->mNext;
tWhere.mCurrent->mNext->mPrev = tWhere.mCurrent->mPrev;
ListNode* tTempPtr = tWhere.mCurrent;
tWhere.mCurrent = tWhere.mCurrent->mNext;
mSize--;
delete tTempPtr;
return tWhere;
}
Iterator Begin() const
{
return Iterator( mHead->mNext );
}
Iterator End() const
{
return Iterator( mTail );
}
}; | true |
303740e021735cbe4e62992c8e2d3a57f932bccd | C++ | Oureyelet/Chapter-9-Arrays--Strings--Pointers--and-References--vsCode- | /9.14 — Dynamically allocating arrays (vsCode)/Question2(anwser).cpp | UTF-8 | 1,396 | 3.734375 | 4 | [] | no_license | #include <iostream>
#include <algorithm>// std::sort
#include <cstddef>// std::size_t
#include <limits>// std::numeric_limits
#include <string>
using namespace std;
//forward functions declaration
size_t getNameCount();
void getNames(string*,size_t);
void printNames(string*,size_t);
int main()
{
std::size_t lenght{ getNameCount() };
auto* names{ new std::string[lenght]{} };
getNames(names, lenght);
std::sort(names, names + lenght);
printNames(names, lenght);
delete[] names;
return 0;
}
std::size_t getNameCount()
{
std::cout << "How many names would you like to enter? ";
std::size_t how_many{};
std::cin >> how_many;
return how_many;
}
// Asks user to enter all the names
void getNames(std::string* names, std::size_t how_many)
{
// Ignore the line feed that was left by std::cin.
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
for(std::size_t count{ 0 }; count < how_many; ++count)
{
std::cout << "Enter name #" << count+1 << ": ";
std::getline(std::cin, names[count]); // ????
}
}
// Prints the sorted names
void printNames(std::string* names, std::size_t how_many)
{
std::cout << "\nHere is your sorted list:\n";
for(std::size_t count{ 0 }; count < how_many; ++count)
{
std::cout << "Name #" << count+1 << ": " << names[count] << '\n';
}
} | true |
b5825c69b65a0cd85d642805a2451fa47f782a24 | C++ | 4eetah/AlgoLib | /clients/EdgeWeightedGraph_cli.cpp | UTF-8 | 778 | 3.0625 | 3 | [] | no_license | #include "EdgeWeightedGraph.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char** argv)
{
if (argc != 2) {
cerr << "Using: ./main EdgeWeightedInputFile\n";
exit(1);
}
fstream fin(argv[1]);
if (!fin.is_open()) {
cerr << "Can't open " << argv[1] << endl;
exit(1);
}
string vstr, wstr, weightstr;
fin >> vstr >> wstr;
int V = stoi(vstr);
int E = stoi(wstr);
EdgeWeightedGraph graph(V);
for (int i = 0; i < V; i++) {
fin >> vstr >> wstr >> weightstr;
int v = stoi(vstr);
int w = stoi(wstr);
double weight = stod(weightstr);
Edge e(v, w, weight);
graph.addEdge(e);
}
cout << graph.toString();
}
| true |
b166f22986d42844acca3f8232f671b6aa7a9039 | C++ | Argons/Cracking-the-Coding-Interview | /Bit_Manipulation-6.cpp | UTF-8 | 454 | 3.8125 | 4 | [] | no_license | # include <iostream>
using namespace std;
// Write a program to swap odd and even bits in an integer with as
// few instructions as possible.
// e.g., bit 0 and 1 are swapped, bit 2 and bit 3 are swapped, etc.
int iwapOddAndEvenBits(int num) {
// &0xA (= 1010), record the odd bits;
// &0x5 (= 0101), record the even bits;
// 'int' has 32 bits, i.e. 8 bits for hex.
return ( ((num & 0xAAAAAAAA) >> 1) | ((num & 0x55555555) << 1) );
}
| true |
574cc66015a1657439e98231437bb339d13c8d68 | C++ | zahidzhp/ALL-MY-ACM-CODES | /CodeForces/750C. New Year and Rating.cpp | UTF-8 | 1,214 | 2.734375 | 3 | [] | no_license | #include <iostream>
#include <stdio.h>
using namespace std;
int arr[200005];
int divis[200005];
int n;
int check(int k)
{
register int i,j;
for(i=n-1; i>=0; i--)
{
k-=arr[i];
if(divis[i]==1&&k<1900) return 1;
else if(divis[i]==2&&k>=1900) return -1;
}
return 0;
}
int main()
{
int flag1=0,flag2=1;
cin>>n;
register int i,j;
for(i=0; i<n; i++)
{
cin>>arr[i]>>divis[i];
if(i>0)
{
if((((arr[i-1]<0&&divis[i-1]==2)&&divis[i]==1)||(arr[i-1]>0&&divis[i-1]==1&&divis[i]==2))) flag1=1;
}
if(divis[i]==2) flag2=0;
}
if(flag1)
{
cout<<"Impossible"<<endl;
return 0;
}
if(flag2)
{
cout<<"Infinity"<<endl;
return 0;
}
int h=22000000,l=-22000000,mid,c,ans=-22000000;
while(h>=l)
{
mid=(l+h)/2;
c=check(mid);
if(c==1)
{
l=mid+1;
}
else if(c==-1)
{
h=mid-1;
}
else
{
l=mid+1;
ans=mid;
}
}
if(ans<=-22000000||ans>=22000000) printf("Impossible\n");
else
printf("%d\n",ans);
return 0;
}
| true |
a54bfd93888274a945a09aaa5f20867b82bf6e4e | C++ | pleasemarkdarkly/iomega_hipzip | /dev/player/util/registry/src/Registry.cpp | UTF-8 | 1,776 | 2.71875 | 3 | [] | no_license | // Registry.cpp: system wide class registry
// danc@iobjects.com 07/08/01
// (c) Interactive Objects
#include "RegistryImp.h"
#include <util/debug/debug.h>
//
// C style API
// note that these routines have C linkage
//
int registry_add_item( RegKey key, void* data, short flags, short length )
{
return CRegistry::GetInstance()->AddItem( key, data, flags, length );
}
void* registry_find_by_key( RegKey key )
{
return CRegistry::GetInstance()->FindByKey( key );
}
ERESULT registry_find_by_type( RegKey type, RegKey* table, int size )
{
return CRegistry::GetInstance()->FindByType( type, table, size );
}
void* registry_remove_item( RegKey key )
{
return CRegistry::GetInstance()->RemoveItem( key );
}
//
// CRegistry implementation
//
static CRegistry* s_pSingleton = 0;
CRegistry* CRegistry::GetInstance()
{
if( s_pSingleton == 0 ) {
s_pSingleton = new CRegistry;
}
return s_pSingleton;
}
CRegistry::CRegistry()
{
m_pImp = new CRegistryImp;
}
CRegistry::~CRegistry()
{
delete m_pImp;
}
int CRegistry::AddItem( RegKey key, void* data, short flags, short length )
{
return m_pImp->AddItem(key, data, flags, length);
}
void* CRegistry::FindByKey( RegKey key )
{
return m_pImp->FindByKey(key);
}
ERESULT CRegistry::FindByKey( RegKey key, void** ppData )
{
return m_pImp->FindByKey(key, ppData);
}
int CRegistry::FindByType( RegKey type, RegKey* pTable, int size )
{
return m_pImp->FindByType(type, pTable, size );
}
void* CRegistry::RemoveItem( RegKey key )
{
return m_pImp->RemoveItem(key);
}
ERESULT CRegistry::SaveState( IOutputStream* pOutput )
{
return m_pImp->SaveState(pOutput);
}
ERESULT CRegistry::RestoreState( IInputStream* pInput )
{
return m_pImp->RestoreState(pInput);
}
| true |
f3bf3313d670bc307d7bcd60791b3c115f8260b9 | C++ | SimoGecko/ctci | /src/17_hard/17_6_count_of_2s.cpp | UTF-8 | 1,055 | 3.234375 | 3 | [] | no_license | // (c) Simone Guggiari 2019 - CTCI
#include <iostream>
#include <cmath>
#include <algorithm>
#include <string>
using namespace std;
constexpr int d = 2;
int clamp(int v, int lo, int hi) {
return max(lo, min(hi, v));
}
int countNumDigitsD(const int N) {
int sum = 0;
int K = floor(log10(N) + 1);
for (int i = 0; i < K; ++i) {
int p10i = pow(10, i);
sum += p10i * (N / (p10i * 10)); // how many full groups
int base = d * p10i - 1; // the number d99...
sum += clamp(N % (p10i * 10) - base, 0, p10i);
}
return sum;
}
int countNumDigitsDBruteForce(const int N){ // used to check only
int sum=0;
for(int i=0; i<=N; ++i){
string s = to_string(i);
for(size_t j=0; j<s.size(); j++)
if(s[j]==('0'+d)) sum++;
}
return sum;
}
int main() {
cout << "Computes the number of digits " << d << " in range [0, n]." << endl;
while (true) {
cout << "Insert n: " << endl;
int n; cin >> n;
cout << "result = " << countNumDigitsD(n) << endl << endl;
//cout << "bruteforce = " << countNumDigitsDBruteForce(n) << endl << endl;
}
return 0;
} | true |
0b02b3f962a4f3dd450a84ba5a018316ca92bd33 | C++ | boleaczek/FileTransfer | /src/tools/StringToEnumNumber.cpp | UTF-8 | 1,454 | 2.890625 | 3 | [] | no_license | #include <algorithm>
#include "StringToEnumNumber.h"
#include "CommandPacket.h"
std::map<std::string, MessageType> StringToEnumNumber::message_type_map = {{"file", MessageType::file}, {"command", MessageType::command}};
std::map<std::string, CommandType> StringToEnumNumber::command_type_map =
{{"remove", CommandType::remove_file},
{"move", CommandType::move},
{"list", CommandType::list},
{"ping", CommandType::ping},
{"response", CommandType::response},
{"exit", CommandType::end_connection},
{"get", CommandType::get}};
MessageType StringToEnumNumber::StringToMessageType(const std::string& message_string)
{
return message_type_map[message_string];
}
CommandType StringToEnumNumber::StringToCommandType(const std::string& command_string)
{
return command_type_map[command_string];
}
std::string StringToEnumNumber::MessageTypeToString(MessageType messageType)
{
return enumVariantToString(messageType, message_type_map);
}
std::string StringToEnumNumber::CommandTypeToString(CommandType commandType)
{
return enumVariantToString(commandType, command_type_map);
}
template<typename T>
std::string StringToEnumNumber::enumVariantToString(T enumVariant, const std::map<std::string, T>& valuesMap)
{
auto valueEnumVariant = std::find_if(valuesMap.cbegin(), valuesMap.cend(), [&enumVariant] (auto keyval) {
return keyval.second == enumVariant;
});
return valueEnumVariant->first;
} | true |
9cbe5131207d2175a01cfd2fdc0c8192cc5433e9 | C++ | yoghourtzzy/DataStructs | /RNP/postfix.cpp | GB18030 | 1,790 | 3.734375 | 4 | [] | no_license | #include<iostream>
#include<string>
#include<cassert>
#include<cctype>
#include<stack>
using namespace std;
/*һʽתΪʽ
صıʽַÿͲ֮䶼һ
*/
string postfix(string exp)
{
char token,//char in exp
topToken;//top element in stack
stack<char>opStack;//the stack to storage operator in exp
string postfixExp;
for (int i = 0;i < exp.length();++i)
{
token = exp[i];
switch (token)
{
case '\0':
break;
case '(':
opStack.push(token);
break;
case')':
{
while (true)
{
assert(!opStack.empty());
topToken = opStack.top();
opStack.pop();
if (topToken == '(')
break;
postfixExp.append(1,topToken);
postfixExp.append(1, '\0');
}
break;
}
case'+':
case'-':
case'*':
case'/':
case'%':
while (true)
{
if (opStack.empty() ||
opStack.top() == '(' ||
(token == '*' || token == '/' || token == '%') &&
(opStack.top() == '+' || opStack.top() == '-'))
{
opStack.push(token);
break;
}
else
{
topToken = opStack.top();
opStack.pop();
postfixExp.append(1,topToken);
postfixExp.append(1, '\0');
}
}
break;
default://
postfixExp.append(1, token);
//Ǹλ
while (true)
{
if (!isalnum(exp[i + 1]))
break;
i++;
token = exp[i];
postfixExp.append(1,token);
}
postfixExp.append(1, '\0');
}
}
//ʣ
for (;;)
{
if (opStack.empty())
break;
topToken = opStack.top();
opStack.pop();
if (topToken != '(')
{
postfixExp.append(1,topToken);
postfixExp.append(1, '\0');
}
else
{
cerr << "***error expression***" << endl;
break;
}
}
return postfixExp;
} | true |
b8a04e4c5a74e046c0ec620b6429b1b02bdf9e58 | C++ | leethomason/OpenSaber | /src/st7735/Grinliz_Util.h | UTF-8 | 10,393 | 3.109375 | 3 | [] | no_license | #ifndef GRINLIZ_UTIL_INCLUDED
#define GRINLIZ_UTIL_INCLUDED
#include <string.h>
#include <stdint.h>
class Stream;
#include "grinliz_assert.h"
#include "fixed.h"
template<class T>
T clamp(T value, T lower, T upper) {
if (value < lower) return lower;
if (value > upper) return upper;
return value;
}
template<class T>
T lerp256(T a, T b, T t256) {
return (a * (256 - t256) + b * t256) / 256;
}
template<class T>
T lerp1024(T a, T b, T t1024) {
return (a * (1024 - t1024) + b * t1024) / 1024;
}
bool TestUtil();
/**
* Returns 'true' if 2 strings are equal.
* If one or both are null, they are never equal.
* (But two empty strings are equal.)
*/
inline bool strEqual(const char* a, const char* b) {
return a && b && strcmp(a, b) == 0;
}
inline bool strEqual(const char* a, const char* b, int n) {
return a && b && strncmp(a, b, n);
}
/**
* Returns 'true' if 'str' strarts with 'prefix'
*/
bool strStarts(const char* str, const char* prefix);
bool istrStarts(const char* str, const char* prefix);
void intToString(int value, char* str, int allocated, bool writeZero);
// Hash suitible for short (8 char or so) strings.
uint16_t hash8(const char* v, const char* end);
/**
* The CStr class is a "c string": a simple array of
* char and an int size bound in a class. It allocates
* no memory, and is very efficient.
*/
template< int ALLOCATE >
class CStr
{
public:
CStr() {
clear();
}
CStr(const char* src) {
clear();
append(src);
}
CStr(const CStr<ALLOCATE>& other) {
memcpy(buf, other.buf, ALLOCATE);
len = other.len;
}
~CStr() {}
const char* c_str() const {
return buf;
}
int size() const {
return len;
}
bool empty() const {
return buf[0] == 0;
}
int capacity() const {
return ALLOCATE - 1;
}
void clear() {
buf[0] = 0;
len = 0;
}
bool beginsWith(const char* prefix) const {
return strStarts(buf, prefix);
}
bool operator==(const char* str) const {
return strEqual(buf, str);
}
bool operator!=(const char* str) const {
return !strEqual(buf, str);
}
char operator[](int i) const {
return buf[i];
}
template < class T > bool operator==(const T& str) const {
return strEqual(this->c_str(), str.c_str());
}
template < class T > bool operator!=(const T& str) const {
return !strEqual(this->c_str(), str.c_str());
}
bool operator<(const CStr<ALLOCATE>& str) const {
return strcmp(buf, str.buf) < 0;
}
void operator=(const char* src) {
clear();
append(src);
}
void operator=(char* const src) {
clear();
append((const char*)src);
}
void operator=(const unsigned char* src) {
clear();
append((const char*) src);
}
template< class T > void operator=(const T& str) {
// T is presumably a CStr of a different size or a CStrBuf
// Possibly on c_str() method.
//*this = str.c_str();
this->clear();
for(int i=0; i<str.size(); ++i) {
this->append(str[i]);
}
}
void operator+=(const char* src) {
append(src);
}
void append(const char* src) {
for (const char* q = src; q && *q; ++q) {
append(*q);
}
}
void append(const char* start, const char* end) {
while(start < end && *start) {
append(*start);
++start;
}
}
void append(char c) {
if (len < ALLOCATE - 1) {
buf[len] = c;
++len;
buf[len] = 0;
}
}
void setFromNum(uint32_t value, bool writeZero) {
clear();
intToString(value, buf, ALLOCATE, writeZero);
len = (int) strlen(buf);
}
uint16_t hash8() const {
return ::hash8(buf, buf + len);
}
private:
int len;
char buf[ALLOCATE];
};
/**
* The CStrBuf. Wraps a buffer of characters, that doesn't have
to be null-terminated. Optimizes for space (the size of this structure
should just be ALLOCATE) vs. performance. Note also the abscence of the
c_str() method, since it can't be implemented without allocating memory.
*/
template< int ALLOCATE >
class CStrBuf
{
public:
CStrBuf() { clear(); }
CStrBuf(const char* src) {
set(src);
}
CStrBuf(const CStrBuf<ALLOCATE>& other) {
memcpy(buf, other.buf, ALLOCATE);
}
~CStrBuf() {}
int size() const {
for (int i = 0; i < ALLOCATE; i++) {
if (buf[i] == 0) return i;
}
return ALLOCATE;
}
bool empty() const {
return buf[0] == 0;
}
int capacity() const {
return ALLOCATE;
}
void clear() {
buf[0] = 0;
}
char operator[](int i) const {
return buf[i];
}
template < class T > bool operator==(const T& str) const {
const int s = this->size();
if (str.size() != s)
return false;
for (int i = 0; i < s; ++i) {
if ((*this)[i] != str[i])
return false;
}
return true;
}
template< class T > bool operator !=(const T& str) const {
// Somewhat forced syntax because I don't want to re-implement the operator==
return !(*this == str);
}
void set(const char* src) {
int i = 0;
for (; i < ALLOCATE && src[i]; ++i) {
buf[i] = src[i];
}
if (i < ALLOCATE)
buf[i] = 0;
}
uint16_t hash8() const {
return ::hash8(buf, buf + size());
}
private:
char buf[ALLOCATE];
};
bool TestCStr();
// --- Hex / Dec Utility --- //
/// Convert a char ('0'-'9', 'a'-'f', 'A'-'F') to the integer value.
int hexToDec(char h);
/// Convert an integer from 0-15 to the hex character. '0' - 'f'
char decToHex(int v);
bool TestHexDec();
/**
* Convert a string in the form: aabbcc to decimal.
*/
void parseHex(const CStr<7>& str, uint8_t* color3);
void parseHex(const CStr<4>& str, uint8_t* color3);
/**
* Convert a numbers to a CStr.
*/
void writeHex(const uint8_t* color3, CStr<6>* str);
bool TestHex();
template<int CAP>
class CQueue
{
public:
CQueue() {}
void push(int val) {
ASSERT(len < CAP);
int index = (head + len) % CAP;
data[index] = val;
++len;
}
int pop() {
ASSERT(len > 0);
int result = data[head];
head = (head + 1) % CAP;
--len;
return result;
}
bool hasCap() const { return len < CAP; }
int empty() const { return len == 0; }
private:
int len = 0;
int head = 0;
int data[CAP];
};
bool TestCQueue();
// --- Range / Min / Max --- //
template<class T>
bool inRange(const T& val, const T& a, const T& b) {
return val >= a && val <= b;
}
template<class T>
T glMin(T a, T b) { return (a < b) ? a : b; }
template<class T>
T glMax(T a, T b) { return (a > b) ? a : b; }
template<class T>
T glClamp(T x, T a, T b) {
if (x < a) return a;
if (x > b) return b;
return x;
}
template<class T>
T glAbs(T x) { return x >= 0 ? x : -x; }
// --- Algorithm --- //
template <class T> inline void Swap(T* a, T* b) {
T temp = *a;
*a = *b;
*b = temp;
};
template <class T>
inline void combSort(T* mem, int size)
{
int gap = size;
for (;;) {
gap = gap * 3 / 4;
if (gap == 0) gap = 1;
bool swapped = false;
const int end = size - gap;
for (int i = 0; i < end; i++) {
int j = i + gap;
if (mem[j] < mem[i]) {
Swap(mem + i, mem + j);
swapped = true;
}
}
if (gap == 1 && !swapped) {
break;
}
}
}
class Random
{
public:
Random() : s(1) {}
void setSeed(uint32_t seed) {
s = (seed > 0) ? seed : 1;
}
uint32_t rand() {
// Xorshift
// My new favorite P-RNG
s ^= s << 13;
s ^= s >> 17;
s ^= s << 5;
return s;
}
uint32_t rand(uint32_t limit) {
return rand() % limit;
}
static bool Test();
private:
uint32_t s;
};
class Timer2
{
public:
Timer2(uint32_t period = 1000, bool repeating = true, bool enable = true) {
m_period = period;
m_repeating = repeating;
m_enable = enable;
}
uint32_t remaining() const { return m_period - m_accum; }
uint32_t period() const { return m_period; }
void setPeriod(uint32_t period) { m_period = period; }
bool repeating() const { return m_repeating; }
void setRepeating(bool repeating) { m_repeating = repeating; }
bool enabled() const { return m_enable; }
void setEnabled(bool enable) {
if (!m_enable && enable) {
reset();
}
m_enable = enable;
}
void reset() { m_accum = 0; }
int tick(uint32_t delta);
static bool Test();
private:
uint32_t m_accum = 0;
uint32_t m_period;
bool m_repeating;
bool m_enable;
};
/* Generally try to keep Ardunino and Win332 code very separate.
But a log class is useful to generalize, both for utility
and testing. Therefore put up with some #define nonsense here.
*/
#ifdef _WIN32
class Stream;
static const int DEC = 1; // fixme: use correct values
static const int HEX = 2;
#endif
class SPLog
{
public:
void attachSerial(Stream* stream);
void attachLog(Stream* stream);
const SPLog& p(const char v[], int width=0) const;
const SPLog& p(char v) const;
const SPLog& p(unsigned char v, int p = DEC) const;
const SPLog& p(int v, int p = DEC) const;
const SPLog& p(unsigned int v, int p = DEC) const;
const SPLog& p(long v, int p = DEC) const;
const SPLog& p(unsigned long v, int p = DEC) const;
const SPLog& p(double v, int p = 2) const;
// Templated print, generally of alternate string class.
template<class T> const SPLog& pt(const T& str) const {
for(int i=0; i<str.size(); ++i) {
(*this).p(str[i]);
}
return *this;
}
// Templated print, with commas.
template<class T> const SPLog& ptc(const T& str) const {
(*this).p("[");
for(int i=0; i<str.size(); ++i) {
(*this).p(str[i]);
if (i != str.size() - 1) {
(*this).p(",");
}
}
(*this).p("]");
return *this;
}
void eol() const;
private:
Stream* serialStream = 0;
Stream* logStream = 0;
};
class EventQueue
{
public:
// Note that the event is stored *by pointer*, so the
// string needs to be in static memory.
void event(const char* event, int data = 0);
struct Event {
const char* name = 0;
int data = 0;
};
Event popEvent();
bool hasEvent() const { return m_nEvents > 0; }
int numEvents() const { return m_nEvents; }
const Event& peek(int i) const;
// For testing.
void setEventLogging(bool enable) { m_eventLogging = enable; }
private:
static const int NUM_EVENTS = 8;
int m_nEvents = 0;
int m_head = 0;
bool m_eventLogging = true;
Event m_events[NUM_EVENTS];
};
extern SPLog Log;
extern EventQueue EventQ;
bool TestEvent();
#endif // GRINLIZ_UTIL_INCLUDED
| true |
8428119b979a909ad57b0863e545ff0f10c81677 | C++ | KoTLiK/VUT-FIT | /2015-2016/IJC/du2/tail2.h | UTF-8 | 1,243 | 2.9375 | 3 | [
"MIT"
] | permissive | /**
* @file tail2.h
* @brief Riesenie IJC-DU2-1, 12.4.2016
* @author Milan Augustin, xaugus09, VUT-FIT
* @details Prelozene: g++ 4.8
* Ze zadaného vstupního souboru vytiskne posledních 10 řádků.
* Není-li zadán vstupní soubor, čte ze stdin. Je-li programu
* zadán parametr -n číslo, bude se tisknout tolik posledních
* řádků, kolik je zadáno parametrem 'číslo'.
*/
#ifndef TAIL2_H_INCLUDED
#define TAIL2_H_INCLUDED
#include <queue>
#include <string>
#include <iostream>
#include <fstream>
#include <climits>
/**
* @brief Checking if parameters are correct
*
* @param N (Number of lines) Will be changed if syntax is correct
* @param argv Arguments of program (parameters)
*
* @return Returns 0, if no problem occurs, else returns 1
*/
int set_num(int *N, char const *argv[]);
/**
* @brief Reads lines from stdin or FILE and only [num] last lines are printed
*
* @param[in] num Number of lines
* @param[in] f_status File status -> stdin or FILE
* @param filename Filename from argv e.g. argv[f_status]
*
* @return Indicates success (0) or not (1)
*/
int read_tail(int num, int f_status, char const *filename);
#endif
| true |
ef4a0e87c2268f5e3f5b0fa7ccba8b6cd78bd0a1 | C++ | amitnautiyalcsf/Ciphers | /Code for Alphabetic Substitution.cpp | UTF-8 | 1,171 | 3.59375 | 4 | [] | no_license | #include<iostream>
#include<cstring>
using namespace std;
void encrypt();
void decrypt();
char lookup(char a, int ch);
int main()
{
int choice;
cout<<"Enter the choice: 1 for Encryption and 0 for Decryption"<<endl;
cin>>choice;
if(choice==1)
encrypt();
else if(choice==0)
decrypt();
return 0;
}
void encrypt()
{
char input[40], output[40]={' '};
cout<<"Enter the string"<<endl;
cin>>input;
int len=strlen(input);
for(int i=0; i<len; i++)
{
output[i]= lookup(input[i], 1);
}
cout<<output;
}
void decrypt()
{
char input[40], output[40]={' '};
cout<<"Enter the string"<<endl;
cin>>input;
int len=strlen(input);
for(int i=0; i<len; i++)
{
output[i]=lookup(input[i],0);
}
cout<<output;
}
char lookup(char a,int ch)
{
char orig[]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
char rep[] ={'j','g','r','t','y','u','i','o','p','q','w','e','a','s','d','f','h','k','l','z','m','n','x','c','v','b'};
int b= a-97;
if(ch==1)
return rep[b];
else if(ch==0)
{
for(int i=0; i<26; i++)
{
if(a==rep[i])
{
return orig[i];
}
}
}
}
| true |
421fbf4b9fe5b7f20dc0490d70b9088d32dd22ea | C++ | NiwdEE/Sous-Marin-Autonome | /physic.hpp | UTF-8 | 8,327 | 2.59375 | 3 | [] | no_license | #ifdef WIN32
#include <GL/glew.h>
#endif
#include <glm/glm.hpp>
#include <glm/gtx/transform.hpp>
#include <glm/gtc/type_ptr.hpp>
using namespace glm;
/*
Conventions de codage :
La première lettre du nom d'un vec3 correspond à la nature du vec3. Avec V => Vecteur, P => Point, I => Indéfini(mais l'un des deux), Rien => Autre
P0, P1 sont des points VDir, et VVel sont des vecteurs
La numérotation des points de fait à partir de 0
Dans le doute, toujours normaliser les vecteurs directeurs qu'on utilise. À moins de savoir ce que l'on fait, c'est le meilleur moyen de faire de la D
*/
#ifndef DEF_Physic
#define DEF_Physic
//Objects
class Ray //Segment
{
public:
Ray();
Ray(vec3 p0, vec3 p1);
Ray(vec3 p0, vec3 dir, float len);
~Ray();
float getLength(void) const;
vec3 getDirection(void) const;
vec3 getCenter(void) const;
vec3 getPoint(int n) const;
void SetPoint(int n, vec3 NO);
void Redefine();
void Redefine(vec3 pp0, vec3 pp1);
void Redefine(vec3 pp0, vec3 dir, float len);
private:
vec3 mP0;
vec3 mP1;
vec3 mPCenter;
float mLength;
vec3 mVDirection;
void RefreshDatas(void);
};
namespace Plane
{
class Infinite
{
public:
Infinite();
Infinite(vec3 p0, vec3 normal);
Infinite(vec3 p0, vec3 dir1, vec3 dir2);
~Infinite();
vec3 getOrigin();
vec3 getNormal();
private:
vec3 mP0;
vec3 mVNormal;
vec3 mVDirector0;
vec3 mVDirector1;
void RefreshDirectors(void);
};
class Triangle
{
public:
Triangle();
Triangle(vec3 p0, vec3 p1, vec3 p2);
Triangle(vec3 p0, vec3 vdir0, float len0, vec3 vdir1, float len1);
~Triangle();
vec3 getNormal(void);
vec3 getGravityCenter(void);
vec3 getPoint(int n);
private:
vec3 mP0;
vec3 mP1;
vec3 mP2;
vec3 mPGravityCenter;
vec3 mVNormal;
void RefreshDatas(void);
};
class Disc
{
public:
Disc();
Disc(vec3 origin, vec3 normal, float radius);
Disc(vec3 origin, vec3 p1, vec3 p2);
Disc(vec3 origin, vec3 dir1, vec3 dir2, float radius);
~Disc();
vec3 getCenter(void);
vec3 getNormal(void);
float getRadius(void);
private:
vec3 mPCenter;
vec3 mVNormal;
float mRadius;
};
};
namespace Shape
{
class Cylinder
{
public:
Cylinder();
Cylinder(Plane::Disc basedisc, float height);
Cylinder(Plane::Disc basedisc, float height, bool reversenormal);
Cylinder(vec3 BaseOrigin, vec3 BaseNormal, float radius, float height);
~Cylinder();
private:
Plane::Disc mBaseDisc;
float height;
};
}
/*
namespace gte
{
template <typename Real>
class TIQuery<Real, Plane3<Real>, Cylinder3<Real>>
{
public:
struct Result
{
bool intersect;
};
// The cylinder must have finite height.
Result operator()(Plane3<Real> const& plane, Cylinder3<Real> const& cylinder)
{
LogAssert(cylinder.height != std::numeric_limits<Real>::max(),
"Cylinder height must be finite.");
Result result;
// Compute extremes of signed distance Dot(N,X)-d for points on
// the cylinder. These are
// min = (Dot(N,C)-d) - r*sqrt(1-Dot(N,W)^2) - (h/2)*|Dot(N,W)|
// max = (Dot(N,C)-d) + r*sqrt(1-Dot(N,W)^2) + (h/2)*|Dot(N,W)|
DCPQuery<Real, Vector3<Real>, Plane3<Real>> vpQuery;
Real distance = vpQuery(cylinder.axis.origin, plane).distance;
Real absNdW = std::fabs(Dot(plane.normal, cylinder.axis.direction));
Real root = std::sqrt(std::max((Real)1 - absNdW * absNdW, (Real)0));
Real term = cylinder.radius * root + (Real)0.5 * cylinder.height * absNdW;
// Intersection occurs if and only if 0 is in the interval
// [min,max].
result.intersect = (distance <= term);
return result;
}
};
template <typename Real>
class FIQuery<Real, Plane3<Real>, Cylinder3<Real>>
{
public:
struct Result
{
bool intersect;
// The type of intersection.
// 0: none
// 1: single line (cylinder is tangent to plane), line[0] valid
// 2: two parallel lines (plane cuts cylinder in two lines)
// 3: circle (cylinder axis perpendicular to plane)
// 4: ellipse (cylinder axis neither parallel nor perpendicular)
int type;
Line3<Real> line[2];
Circle3<Real> circle;
Ellipse3<Real> ellipse;
};
// The cylinder must have infinite height.
Result operator()(Plane3<Real> const& plane, Cylinder3<Real> const& cylinder)
{
LogAssert(cylinder.height != std::numeric_limits<Real>::max(),
"Cylinder height must be finite.");
Result result;
DCPQuery<Real, Vector3<Real>, Plane3<Real>> vpQuery;
Real sdistance = vpQuery(cylinder.axis.origin, plane).signedDistance;
Vector3<Real> center = cylinder.axis.origin - sdistance * plane.normal;
Real cosTheta = Dot(cylinder.axis.direction, plane.normal);
Real absCosTheta = std::fabs(cosTheta);
if (absCosTheta > (Real)0)
{
// The cylinder axis intersects the plane in a unique point.
result.intersect = true;
if (absCosTheta < (Real)1)
{
result.type = 4;
result.ellipse.normal = plane.normal;
result.ellipse.center = cylinder.axis.origin -
(sdistance / cosTheta) * cylinder.axis.direction;
result.ellipse.axis[0] = cylinder.axis.direction -
cosTheta * plane.normal;
Normalize(result.ellipse.axis[0]);
result.ellipse.axis[1] = UnitCross(plane.normal,
result.ellipse.axis[0]);
result.ellipse.extent[0] = cylinder.radius / absCosTheta;
result.ellipse.extent[1] = cylinder.radius;
}
else
{
result.type = 3;
result.circle.normal = plane.normal;
result.circle.center = center;
result.circle.radius = cylinder.radius;
}
}
else
{
// The cylinder is parallel to the plane.
Real distance = std::fabs(sdistance);
if (distance < cylinder.radius)
{
result.intersect = true;
result.type = 2;
Vector3<Real> offset = Cross(cylinder.axis.direction, plane.normal);
Real extent = std::sqrt(cylinder.radius * cylinder.radius - sdistance * sdistance);
result.line[0].origin = center - extent * offset;
result.line[0].direction = cylinder.axis.direction;
result.line[1].origin = center + extent * offset;
result.line[1].direction = cylinder.axis.direction;
}
else if (distance == cylinder.radius)
{
result.intersect = true;
result.type = 1;
result.line[0].origin = center;
result.line[0].direction = cylinder.axis.direction;
}
else
{
result.intersect = false;
result.type = 0;
}
}
return result;
}
};
}*/
//Functions
bool collide(Ray ray, Plane::Infinite plane);
bool collide(Plane::Infinite plane, Ray ray);
bool collide(Ray ray, Plane::Triangle plane);
bool collide(Plane::Triangle plane, Ray ray);
bool collide(Ray ray, Plane::Disc plane);
bool collide(Plane::Disc plane, Ray ray);
#endif | true |
54889e9367971f43d7ac76a6d6f89d84223b7fb5 | C++ | GradyLealand/C | /Searching/HashTable/FileHandler.cpp | UTF-8 | 1,601 | 3.265625 | 3 | [] | no_license | //
// Created by prog2100 on 10/04/18.
//
#include <fstream>
#include <iostream>
#include <cstring>
#include "FileHandler.h"
#include <locale>
using namespace std;
Hash FileHandler::sortDictionary(string readFile, Hash hash)
{
string line;
ifstream fileIn;
try{
fileIn.open(readFile);
}
catch(const ifstream::failure& e)
{
cout << "Error reading the file" << endl;
}
catch(std::exception const& e)
{
cout << "There was an error: " << e.what() << endl;
}
while (!fileIn.eof())
{
getline(fileIn, line);
hash.addEntry(line);
}
fileIn.close();
return hash;
}
/*
* split into individual words and exclude special characters
* http://www.cplusplus.com/reference/cstring/strtok/
*/
void FileHandler::parseToCheck(string readFile, Hash hash)
{
cout << endl;
cout << "Misspelled words:" << endl;
locale loc;
ifstream fileIn(readFile);
string content((istreambuf_iterator<char>(fileIn)),
(istreambuf_iterator<char>()));
char str[content.length()];
for(int i = 0; i < content.length(); i++)
{
str[i] = content[i];
}
char * pch;
pch = strtok (str, " .,()#&\"1234567890");
while (pch != NULL)
{
string checkStr = "";
checkStr += ("%s\n", pch);
pch = strtok (NULL, " .,()#&\"1234567890");
//convert string to lower case
for(int i = 0; i <checkStr.length(); i++)
{
checkStr[i] = tolower(checkStr[i], loc);
}
hash.spellCheck(checkStr, hash);
}
}
| true |
ae91d2dcf04964629f59933d53c6653af72e183c | C++ | KaelMa/leetcode | /C++/Palindrome Linked List.cpp | UTF-8 | 1,535 | 3.484375 | 3 | [
"MIT"
] | permissive | // Palindrome Linked List My Submissions Question
// Total Accepted: 25431 Total Submissions: 104985 Difficulty: Easy
// Given a singly linked list, determine if it is a palindrome.
// Follow up:
// Could you do it in O(n) time and O(1) space?
// Subscribe to see which companies asked this question
//My solution
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool isPalindrome(ListNode* head)
{
ListNode *slow = head;
ListNode* fast = head;
while(fast != nullptr)
{
if(fast->next != nullptr)
fast = fast->next->next;
else
fast = fast->next;
slow = slow->next;
}
ListNode* rHead = reverseLink(slow);
while(rHead != nullptr)
{
if(rHead->val != head->val)
return false;
else
{
rHead = rHead->next;
head = head->next;
}
}
return true;
}
ListNode* reverseLink(ListNode* head)
{
ListNode* pre = nullptr;
ListNode* lat = nullptr;
while(head != nullptr)
{
lat = head->next;
head->next = pre;
pre = head;
head = lat;
}
return pre;
}
}; | true |
e95ae331081dc5fbd8b51c69925c7f2d11edfd49 | C++ | jjoe64/babydevelop | /beispiele/Qt/mp3_player/gui.cpp | UTF-8 | 3,868 | 2.859375 | 3 | [] | no_license | /* gui.cpp */
#include "gui.h"
//Globale Variablen
extern QString aktuellerPfad;
/* Konstruktor */
GUI::GUI (QWidget *elternWidget) : QWidget (elternWidget)
{
this->setGeometry(0,0,480,383);
//Farbsteuerung ist leider etwas aufwaendig
QColor farbe_gelb; // Gelb soll es sein
farbe_gelb.setRgb(252,255,0); // yellow
QPalette palette_gelb; // Bestimmt die Behandlung z.B. Aufhellen beim Ueberfahren mit der Maus
palette_gelb.setColor(QPalette::Window, farbe_gelb);
this->setAutoFillBackground(true); // Hintergrund automatisch zeichnen, wenn notwendig
this->setPalette(palette_gelb);
copy = new QLabel("(c) by ufg, Jorgito Alvarado and Jonas",this);
copy->setGeometry(240, 360, 238, 20);
copy->setPalette(Qt::green); // Hintergrundfarbe
copy->setAutoFillBackground(true); // Hintergrundfarbe automatisch zeichnen, wenn notwendig
copy->setAlignment(Qt::AlignCenter); // Zentrierte Anordnung
copy->show();
zeile = new QLineEdit("", this);
zeile->setGeometry(10, 10, 230, 30);
zeile->show();
connect(zeile, SIGNAL( returnPressed() ), SLOT(nimmText() ) );
tasteFinde = new QPushButton("Finde",this);
tasteFinde->setGeometry(10, 50, 70, 30);
tasteFinde->show();
connect(tasteFinde, SIGNAL( clicked() ), SLOT(nimmText() ) );
tasteInfo = new QPushButton("Info",this);
tasteInfo->setGeometry(90, 50, 70, 30);
tasteInfo->show();
connect(tasteInfo, SIGNAL( clicked() ), SLOT(informieren() ) );
tastePlay = new QPushButton("Play",this);
tastePlay->setGeometry(170, 50, 70, 30);
tastePlay->show();
connect(tastePlay, SIGNAL( clicked() ), SLOT(spiele() ) );
tasteEnde = new QPushButton("Ende",this);
tasteEnde->setGeometry(10, 345, 70, 30);
tasteEnde->show();
connect(tasteEnde, SIGNAL( clicked() ), SLOT(ende() ) );
tabelle = new QListWidget(this);
tabelle->setGeometry(10, 95, 460, 240);
tabelle->show();
connect(tabelle, SIGNAL( itemDoubleClicked(QListWidgetItem*) ),SLOT(auswahlLied(QListWidgetItem*)));
}
/* Destruktor */
GUI::~GUI ()
{
}
void GUI::ladeListe()
{
tabelle->clear();
//Anmerkung: Mit QTextStream geht es nicht, da das Teil bei Zeilenende
// meint es sei das Dateiende - scheiß Qt
QFile liste( aktuellerPfad+"/liste.txt" );
liste.open(QIODevice::ReadOnly);
QString zeile;
int nZeile=0;
while( (zeile = liste.readLine()) != NULL)
{
qWarning("aktpfad=%s",aktuellerPfad.toLatin1().data());
zeile.chop(1); //Zeiche \n entfernen
pfad[nZeile] = zeile;
QString lied = zeile.remove(0,zeile.lastIndexOf("/")+1);
tabelle->insertItem(nZeile,lied);
nZeile++;
}
liste.close();
}
void GUI::auswahlLied(QListWidgetItem* lied)
{
//QListWidgetItem* lied wird nicht benoetigt, wird aber vom Signal geliefert
int liedNr = tabelle->currentRow();
emit ladeLied(pfad[liedNr]);
}
void GUI::spiele()
{
int liedNr = tabelle->currentRow();
emit ladeLied(pfad[liedNr]);
}
void GUI::nimmText()
{
QString begriff = zeile->text();
emit finde(begriff);
}
void GUI::informieren()
{
QMessageBox::information(this,"Information","Es muss der XMMS-Player installiert sein!\n"
"Geben Sie einen Teil des Suchbegriffs ein und druecken\n"
"Sie [Enter] oder klicken Sie auf die [Finde]-Taste.\n"
"Suchen Sie Ihr Lied aus der Liste aus und\n"
"doppelklicken Sie darauf.\n"
"Nun sollte das gewuenschte Lied abgespielt werden.\n"
"Beenden Sie das Programm mit der [Ende]-Taste.");
}
void GUI::ende()
{
emit sigEnde();
}
| true |
767c8e822a27eb73ad460ac53482a1ee27689c98 | C++ | zg2nets/windows-backend | /Dali/dali-core/dali/internal/event/common/demangler-unix.cpp | UTF-8 | 3,114 | 2.828125 | 3 | [] | no_license | /*
* Copyright (c) 2019 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
// FILE HEADER
#include <dali/internal/event/common/demangler.h>
// INTERNAL HEADERS
#include <dali/public-api/common/vector-wrapper.h>
namespace
{
// true if character represent a digit
inline bool IsDigit(char c)
{
return (c >= '0' && c <= '9');
}
// Gets the number of characters (number is in string)
// start The start position to look for a number
// result The number as an integer
// returns the number of characters used to define the number ie '12' is 2
size_t GetNumberOfCharacters(const std::string& s, const size_t& start, int& result)
{
size_t size = s.size();
size_t i = start;
int number = 0;
for( ; i < size; ++i )
{
char c = s.at(i);
if( !IsDigit( c ) )
{
break;
}
else
{
number = 10 * number + (c - '0');
}
}
if( i - start )
{
result = number;
}
return i - start;
}
/**
* @brief Demangle a nested typeid name into its component parts.
* A nested type name is one containing namespaces and class names only.
* eg DemangleNestedNames(typeid(Dali::Actor).name());
* @param[in] typeIdName The type id name string to demangle.
* @returns the demangled list of names ie ["Dali","Actor"] or an empty list
*/
std::vector<std::string> DemangleNestedNames(const char *typeIdName)
{
// Demangle class name mangled according to the Itanium C++ ABI
// Returns demangled names ie "N4Dali8Internal5ActorE" is ["Dali","Internal","Actor"]
std::vector<std::string> ret;
const std::string mangledName(typeIdName);
size_t size = mangledName.size();
if( size >= 2 )
{
int number = 0;
size_t start = 0;
// If the class isnt nested in a namespace then it just starts with the
// number of characters
if(mangledName[0] == 'N' && mangledName[size-1] == 'E')
{
start = 1;
}
while( size_t chars = GetNumberOfCharacters(mangledName, start, number) )
{
ret.push_back( mangledName.substr( start + chars, number ) );
start += chars + number;
}
}
return ret;
}
} // anon namespace
namespace Dali
{
namespace Internal
{
const std::string DemangleClassName(const char *typeIdName)
{
std::string name;
std::vector<std::string> names = DemangleNestedNames(typeIdName);
if( names.size() )
{
name = names[ names.size() - 1 ];
}
return name;
}
} // namespace Internal
} // namespace Dali
| true |
8e7ec7a2eb4e14e3646ef5534869f4e97a0ed755 | C++ | milanvujmilovic/OSI2019-Grupa-6 | /Dogadjaj.h | UTF-8 | 1,592 | 3.140625 | 3 | [] | no_license | #pragma once
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include<ctime>
#include <iterator>
class Dogadjaj
{
friend std::ostream& operator<<(std::ostream& stream, const Dogadjaj& other);
std::string naziv;
std::vector<std::string> komentari;
std::string opis;
std::tm datum = { 0,0,0,0,0,0,0,0,0 };
std::string vrsta; //kategorija
std::string lokacija;
public:
Dogadjaj() = default;
~Dogadjaj() = default;
Dogadjaj(std::string naziv,std::string vrsta,std::string opis, std::string lokacija,std::tm datum) : naziv(naziv), vrsta(vrsta), datum(datum),opis(opis), lokacija(lokacija)
{}
Dogadjaj(const Dogadjaj& dogadjaj);
Dogadjaj(Dogadjaj&& dogadjaj)noexcept;
void setNaziv(std::string naziv) {this->naziv = naziv; }
std::string getNaziv() { return this->naziv; }
void setVrsta(std::string vrsta) { this->vrsta = vrsta; }
std::string getVrsta() { return this->vrsta; }
void setDatum(std::tm datum) { this->datum = datum; }
std::tm getDatum() { return this->datum; }
void setLokacija(std::string lokacija) { this->lokacija = lokacija; }
std::string getLokacija() { return this->lokacija; }
void setOpis(std::string opis) { this->opis = opis; }
std::string getOpis() { return this->opis; }
void setKomentar(std::string komentar) { komentari.push_back(komentar); }
void izlistajKomentare() { for (auto x : komentari) { std::cout << x << std::endl; } }
void operator=(const Dogadjaj& dogadjaj);
void upisDogadjaja();
void izbrisiDogadjaj();
void print();
}; | true |
07c42d35e8a42dd421bed0bd3c974ce579aad085 | C++ | swallville/java-class | /lib/pop_dup_swap.cpp | UTF-8 | 2,747 | 2.96875 | 3 | [
"MIT"
] | permissive | #include "pop_dup_swap.hpp"
void i_pop(Frame* frame)
{
frame->operandStack.pop();
return;
}
void i_pop2(Frame* frame)
{
frame->operandStack.pop();
frame->operandStack.pop();
return;
}
void i_dup(Frame* frame)
{
frame->operandStack.push(frame->operandStack.top());
return;
}
void i_dup_x1(Frame* frame)
{
Data valueTop = frame->operandStack.top();
frame->operandStack.pop();
Data valor = frame->operandStack.top();
frame->operandStack.pop();
frame->operandStack.push(valor);
frame->operandStack.push(valueTop);
frame->operandStack.push(valor);
return;
}
void i_dup_x2(Frame* frame)
{
Data valueTop = frame->operandStack.top();
frame->operandStack.pop();
Data valor = frame->operandStack.top();
frame->operandStack.pop();
Data valuefloor = frame->operandStack.top();
frame->operandStack.pop();
frame->operandStack.push(valuefloor);
frame->operandStack.push(valor);
frame->operandStack.push(valueTop);
frame->operandStack.push(valuefloor);
return;
}
void i_dup2(Frame* frame)
{
Data valueTop = frame->operandStack.top();
frame->operandStack.pop();
Data valor = frame->operandStack.top();
frame->operandStack.pop();
frame->operandStack.push(valor);
frame->operandStack.push(valueTop);
frame->operandStack.push(valor);
frame->operandStack.push(valueTop);
return;
}
void i_dup2_x1(Frame* frame)
{
Data valueTop = frame->operandStack.top();
frame->operandStack.pop();
Data valor = frame->operandStack.top();
frame->operandStack.pop();
Data valuefloor = frame->operandStack.top();
frame->operandStack.pop();
frame->operandStack.push(valuefloor);
frame->operandStack.push(valor);
frame->operandStack.push(valueTop);
frame->operandStack.push(valuefloor);
frame->operandStack.push(valor);
return;
}
void i_dup2_x2(Frame* frame)
{
Data value1 = frame->operandStack.top();
frame->operandStack.pop();
Data value2 = frame->operandStack.top();
frame->operandStack.pop();
Data value3 = frame->operandStack.top();
frame->operandStack.pop();
Data value4 = frame->operandStack.top();
frame->operandStack.pop();
frame->operandStack.push(value4);
frame->operandStack.push(value3);
frame->operandStack.push(value2);
frame->operandStack.push(value1);
frame->operandStack.push(value4);
frame->operandStack.push(value3);
return;
}
void i_swap(Frame* frame)
{
Data value1 = frame->operandStack.top();
frame->operandStack.pop();
Data value2 = frame->operandStack.top();
frame->operandStack.pop();
frame->operandStack.push(value1);
frame->operandStack.push(value2);
return;
}
| true |
bf041c29ad76d23fa305ff5c8b2be76bee63665e | C++ | ankushgarg1998/Competitive_Coding | /contests/codechef-contests/OCT17/chefcoun.cpp | UTF-8 | 2,009 | 2.703125 | 3 | [] | no_license | #include<iostream>
#include<cstdlib>
#include<vector>
typedef long long int ll;
using namespace std;
int correctSolver(vector <int> a, int N) {
int min = a[0], i;
int ind = 0;
for(i=0; i<N; i++)
{
if(a[i]==1)
{
ind = i;
break;
}
if(a[i]<min)
{
min = a[i];
ind = i;
}
}
return ind+1;
}
int wrongSolver(vector <unsigned int> a) {
int n = a.size();
std::vector<unsigned int> prefSum(n), sufSum(n);
prefSum[0] = a[0];
for (int i = 1; i < n; i++) {
prefSum[i] = prefSum[i - 1] + a[i];
// cout<<prefSum[i]<<" ";
}
sufSum[n - 1] = a[n - 1];
for (int i = n - 2; i >= 0; i--) {
sufSum[i] = sufSum[i + 1] + a[i];
}
unsigned int mn = prefSum[0] + sufSum[0];
int where = 1;
for (int i = 1; i < n; i++) {
unsigned int val = prefSum[i] + sufSum[i];
if (val < mn) {
mn = val;
where = i + 1;
}
}
return where;
}
int main()
{
int t;
ll n, i, ans = 100000, x, a;
cin>>t;
while(t--)
{
cin>>n;
vector<int> v;
vector<unsigned int> v2;
// for(i=0; i<n; i++)
// {
// x = rand()%10;
// cout<<ans-x<<" ";
// v.push_back(ans);
// v2.push_back(ans);
// }
for(i=1; i<=42949; i++)
{
// cout<<ans<<" ";
v.push_back(ans);
v2.push_back(ans);
}
// cout<<67296<<" ";
v.push_back(67296);
v2.push_back(67296);
for(i=1; i<=42949; i++)
{
// cout<<ans<<" ";
v.push_back(ans);
v2.push_back(ans);
}
a = n - 85899;
while(a--)
{
// cout<<"0 ";
v.push_back(1);
v2.push_back(1);
}
cout<<"\n";
cout<<"Correct Ans: "<<correctSolver(v, n)<<"\n";
cout<<"Wrong Ans: "<<wrongSolver(v2);
}
return 0;
}
| true |