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
0040bad4163d1fbb4dfbacf0c1368a398cafa02a
C++
TheGregTanaka/csc160FinalSpaceDefense
/Program/Character.h
UTF-8
2,396
3.1875
3
[]
no_license
#pragma once #include <string> #include <iostream> #include <iomanip> #include <typeinfo> #include "CombatStats.h" #include "Weapon.h" #include "Armor.h" #include "PowerUp.h" #include "EmptySlot.h" using std::string; // define constants to avoid "magic numbers" const int STARTING_HP = 10; const double STARTING_MONEY = 15; const int STARTING_INV_SIZE = 6; enum CharacterType { BigGun, Engineer, Sniper, Creature }; class Character { private: string name; CharacterType role; CombatStats stats; int level; Equipment **inventory; double money; int equipedWeapon; // represents index of equiped weapon in inventory int equipedArmor; // represents index of equiped armor in inventory //methods int accurateAttack(); int strongAttack(); int cleverAttack(); int specialAttack(); bool takeDamage(int); void increaseStats(int); public: Character(CharacterType, string, int, CombatStats, double, int, int); Character(CharacterType, string, int, CombatStats, double, int, int, int, Equipment**); ~Character(); // getters string getName() { return name; }; CharacterType getRole() { return role; }; int getHealth() { return stats.health; }; int getStrength() { return stats.strength; }; int getDefense() { return stats.defense; }; int getSpeed() { return stats.speed; }; int getIntellect() { return stats.intellect; }; int getAccuracy() { return stats.accuracy; }; int getIsTrained() { return stats.isTrained; }; bool getAlive() { return stats.isAlive; }; CombatStats getStats() { return stats; }; int getLevel() { return level; }; double getMoney() { return money; }; int getEquipedWeapon() { return equipedWeapon; }; int getEquipedArmor() { return equipedArmor; }; string getInventoryString(); // setters void setName(string s) { name = s; }; void setHealth(int h) { stats.health = h; }; void setStrength(int s) { stats.strength = s; }; void setDefense(int d) { stats.defense = d; }; void setSpeed(int s) { stats.speed = s; }; void setIntellect(int i) { stats.intellect = i; }; void setAccuracy(int a) { stats.accuracy = a; }; //methods int attack(); bool defend(); void purchase(Equipment*); void useItem(Equipment*, int); void useItem(PowerUp*, int); void receiveMoney(double m); void removeWeapon(); void removeArmor(); void levelUp(); void displayStats(); void displayCharSheet(); Character& operator++(); Character operator++(int); };
true
db8707f72cdb5896f821dfa7f1cb28ef7e560ba2
C++
HPDRC/RasterTile
/src/TileImagerySystem/Common/global_functions.h
UTF-8
268
2.59375
3
[]
no_license
#pragma once #include <string> using namespace std; void Log(char *format, ...); void LogThrow(char *format, ...); // for now, only log assert fail events inline void Assert(bool assert, char *msg) { if (assert == false) Log("Assert failed: %s", msg); }
true
a2dfe3136fbfb669cb75ccac6368c774835ef28a
C++
qq77457051/crpAlynasis
/MV200/UI/Login/userLogin.cpp
UTF-8
5,204
2.5625
3
[]
no_license
#include "userLogin.h" UserLogin::UserLogin(QDialog *parent) : QDialog(parent) { initForm(); //初始化 initStyle(); //界面风格 initConnect(); //连接信号与槽 initData(); //初始化数据 } //初始化 void UserLogin::initForm() { fraImage = new QFrame; labTitle = new QLabel("用户登录"); labUser = new QLabel("用 户:"); editUser = new QLineEdit; labPwd = new QLabel("密 码:"); editPwd = new QLineEdit; chkSelfCheck = new QCheckBox("是否开机自检"); //是否要开机自检 btnLogin = new QPushButton("登 录"); btnCancel = new QPushButton("取 消"); layout = new QGridLayout; layout->setMargin(10); layout->setSpacing(10); layout->addWidget(fraImage, 1, 0, 3, 5, Qt::AlignRight); layout->addWidget(labTitle, 1, 5, 3, 15, Qt::AlignLeft); layout->addWidget(labUser, 4, 0, 1, 5, Qt::AlignRight); layout->addWidget(editUser, 4, 5, 1, 15, Qt::AlignLeft); layout->addWidget(labPwd, 6, 0, 1, 5, Qt::AlignRight); layout->addWidget(editPwd, 6, 5, 1, 15, Qt::AlignLeft); layout->addWidget(chkSelfCheck,10, 5, 1, 15, Qt::AlignLeft); layout->addWidget(btnCancel, 12, 0, 1, 10, Qt::AlignCenter); layout->addWidget(btnLogin, 12, 10, 1, 10, Qt::AlignCenter); this->setLayout(layout); } //界面风格 void UserLogin::initStyle() { this->setFixedSize(360, 300); this->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint); //去掉标题栏 //图标设置 QIcon icon; icon.addPixmap(QPixmap(QString::fromUtf8("icon/WinIcon.png")), QIcon::Normal, QIcon::Off); this->setWindowIcon(icon); QFile qss(":/QSS/QSS/LoginWidget.qss"); qss.open(QFile::ReadOnly); this->setStyleSheet(qss.readAll()); qss.close(); this->setObjectName("loginDlg"); fraImage->setFixedSize(64, 64); fraImage->setObjectName("userLoginFrame"); labTitle->setObjectName("lab30"); chkSelfCheck->setChecked(true); editPwd->setEchoMode(QLineEdit::Password); } //连接信号与槽 void UserLogin::initConnect() { connect(btnCancel, SIGNAL(clicked()), this, SLOT(slt_btnCancel_Clicked())); connect(btnLogin, SIGNAL(clicked()), this, SLOT(slt_btnLogin_Clicked())); } //初始化数据 void UserLogin::initData() { editUser->setPlaceholderText("UserName"); editPwd->setPlaceholderText("PassWord"); //读取MVLogin.ini文件获取最后一次登录的的用户名及密码 gSetting = new QSettings("MV200Login.ini", QSettings::IniFormat); gSetting->beginGroup("Login"); editUser->setText(gSetting->value("name").toString()); editPwd->setText(AppHelper::getXorEncryptDecrypt(gSetting->value("pwd").toString(), KEY)); gSetting->endGroup(); } //槽:登陆 void UserLogin::slt_btnLogin_Clicked() { //(0:用户不存在,1:允许登录,2:密码错误) QString user = editUser->text(); QString psd = editPwd->text(); int login = SQLite::getInstance()->Login(user, psd); if( login == 1 ) { int selfCheck = chkSelfCheck->isChecked(); //是否开机自检 gParameter->set_isSelfCheck(selfCheck); //保存最后登录的用户信息 gSetting->beginGroup("Login"); gSetting->setValue("name", editUser->text().trimmed()); //Build类型(发布版、研发版) if( !gParameter->get_isRelease()) //0:研发版 gSetting->setValue("pwd", AppHelper::getXorEncryptDecrypt(editPwd->text().trimmed(), KEY)); else gSetting->setValue("pwd", AppHelper::getXorEncryptDecrypt("", KEY)); gSetting->endGroup(); this->accept(); delete gSetting; } else if( login == 2) { gMessageBox->setInfo(QString("提示"), QString("密码错误!"), QPixmap("://resource/resource/MessageBox/information.png"), true, true); gMessageBox->setButtonText(Cancel, "返回"); if(gMessageBox->exec() == MVMessageBox::Rejected) { editPwd->clear(); return; } } else { gMessageBox->setInfo(QString("提示"), QString("用户不存在!"), QPixmap("://resource/resource/MessageBox/information.png"), true, true); gMessageBox->setButtonText(Cancel, "返回"); if(gMessageBox->exec() == MVMessageBox::Rejected) { editUser->clear(); editPwd->clear(); return; } } } //槽:取消 void UserLogin::slt_btnCancel_Clicked() { this->reject(); } //按下鼠标事件 void UserLogin::mousePressEvent( QMouseEvent * event ) { //窗口移动距离 move_point = event->globalPos() - pos(); } //移动鼠标事件 void UserLogin::mouseMoveEvent(QMouseEvent *event) { //移动窗口 QPoint move_pos = event->globalPos(); move(move_pos - move_point); } //键盘事件 void UserLogin::keyPressEvent(QKeyEvent *event) { //回车键 & 确定(数字键) if(event->key()== Qt::Key_Return || event->key()== Qt::Key_Enter) { slt_btnLogin_Clicked(); } }
true
c0ffcb45a9dcdfae941c613c73954a0907bbbcc1
C++
jackson123zz/LeetCode
/code/0137.cpp
UTF-8
586
3.4375
3
[]
no_license
#include <iostream> #include <vector> #include <unordered_map> using namespace std; class Solution { public: int singleNumber(vector<int>& nums) { unordered_map<int, int> map; for (int i = 0; i < nums.size(); i++) { map[nums[i]]++; } for (auto x : map) { if (x.second == 1) { return x.first; } } return 0; } }; int main() { vector<int> num = { 0,1,0,1,0,1,99 }; Solution A; int result = A.singleNumber(num); std::cout << "result = " << result << endl;; }
true
91021a7644fd963e4a43f2b497c2e46b0c716e3a
C++
saulopz/rtsim
/src/TimeLine.cpp
UTF-8
7,571
2.765625
3
[ "BSD-4-Clause-UC" ]
permissive
#include "config.h" #include "TimeLine.h" #include "Task.h" #include "Budget.h" #include <allegro.h> #include <stdio.h> #include <string.h> #include <math.h> TimeLine::TimeLine(char *fName) { imageSize = 1; image = NULL; time = 0.0; strcpy(fileName, fName); posX = 50; posY = 50; type = RATE_MONOTONIC; loadFile(); orderTasks(); if (computeSchaduling()) { printf("Accepted scheduling...\n"); } else { printf("Not accepted scheduling...\n"); } computeTimeSize(); makeTasks(); } void TimeLine::loadFile() { FILE *file; char n[50]; char taskType[70]; float period; float execution; int r, g, b; Task *t = NULL; strcpy(n, fileName); strcat(n, ".in"); if ((file = fopen(n, "r")) == NULL) { fprintf(stderr, "Cannot open %s\n", n); exit(1); } while (!feof(file)) { fscanf(file, "%s %f %f %d %d %d\n", taskType, &period, &execution, &r, &g, &b); printf("<%s : %.1f : %.1f : %d , %d , %d>\n", taskType, period, execution, r, g, b); if (strcmp("periodic", taskType) == 0) { t = addTask(PERIODIC, (int)period, execution, makecol(r, g, b)); } else if (strcmp("simple_sporadic_server", taskType) == 0) { t = addTask(SIMPLE_SPORADIC_SERVER, (int)period, execution, makecol(r, g, b)); } else if (strcmp("deferrable_server", taskType) == 0) { t = addTask(DEFERRABLE_SERVER, (int)period, execution, makecol(r, g, b)); } else if (strcmp("pooling_server", taskType) == 0) { t = addTask(POOLING_SERVER, (int)period, execution, makecol(r, g, b)); } else if (strcmp("aperiodic", taskType) == 0) { if (t != NULL) { t->addAperiodic((int)period, execution, makecol(r, g, b)); } } } fclose(file); } Task *TimeLine::addTask(int type, int period, float execution, int color) { Task *t = new Task(this, type, period, execution, color); task.push_back(t); return t; } Budget *TimeLine::addBudget(float size) { printf("new budget %d\n", (int)budget.size()); char *name = (char *)malloc(50 * sizeof(char)); strcpy(name, "Budget"); Budget *b = new Budget(this, name, size); budget.push_back(b); return b; } void TimeLine::makeTasks() { for (unsigned int i = 0; i < task.size(); i++) { task[i]->priority = i + 1; task[i]->make(); } for (unsigned int i = 0; i < budget.size(); i++) { budget[i]->make(); } } void TimeLine::executeTasks() { while (time < timeSize) { for (unsigned int i = 0; i < task.size(); i++) { task[i]->run(); } for (unsigned int i = 0; i < budget.size(); i++) { budget[i]->run(); } time += 0.1; } for (unsigned int i = 0; i < task.size(); i++) { task[i]->showAperiodicResponseTime(); } printf("Execution finished...\n"); } int TimeLine::computeSchaduling() { float a = 0; for (unsigned int i = 0; i < task.size(); i++) { a += task[i]->execution / task[i]->period; } float b = task.size() * (pow(2, ((float)1 / task.size())) - 1); printf("Computing %.3f < %.3f\n", a, b); if (a < b) return true; else return false; } void TimeLine::computeTimeSize() { int found = false; timeSize = 0; while (!found) { timeSize++; float total = 0; for (unsigned int i = 0; i < task.size(); i++) { total += (float)(((int)(timeSize)) % ((int)(task[i]->period))); } found = (total == 0); } printf("timeSize %d\n", timeSize); } void TimeLine::orderTasks() { for (unsigned int a = 0; a < task.size(); a++) { int lowerValue = task[a]->period; unsigned int lowerIndex = a; for (unsigned int b = a + 1; b < task.size(); b++) { if (task[b]->period < lowerValue) { lowerValue = task[b]->period; lowerIndex = b; } } if (a != lowerIndex) { Task *aux = task[a]; task[a] = task[lowerIndex]; task[lowerIndex] = aux; } } for (unsigned int i = 0; i < task.size(); i++) { if (task[i] != NULL) { task[i]->orderAperiodic(); printf("%s%d (%d, %.1f)\n", task[i]->name, i, task[i]->period, task[i]->execution); } } printf("Finish order...\n"); } void TimeLine::run() { executeTasks(); draw(); } void TimeLine::draw() { makeTimeLine(); int position = image->h - 30; for (int i = budget.size() - 1; i >= 0; i--) { position -= budget[i]->image->h; draw_sprite(image, budget[i]->image, 0, position); } for (int i = task.size() - 1; i >= 0; i--) { position -= task[i]->image->h; draw_sprite(image, task[i]->image, 0, position); } } void TimeLine::makeTimeLine() { int h = 0; for (unsigned int i = 0; i < budget.size(); i++) { h += budget[i]->image->h; } for (unsigned int i = 0; i < task.size(); i++) { h += task[i]->image->h; } if (image == NULL) { image = create_bitmap((int)(timeSize * 10), h + 30); } clear_to_color(image, TRANSPARENT); line(image, 0, 0, 0, image->h - 20, COLOR_TIME_LINE); line(image, 0, image->h - 20, image->w, image->h - 20, COLOR_TIME_LINE); int aux = 0; for (int i = 0; i < timeSize; i++) { if (aux == 5) { line(image, i * 10, 0, i * 10, image->h - 21, makecol(200, 200, 200)); char number[10]; sprintf(number, "%d", i); textout_centre_ex(image, font, number, i * 10, image->h - 15, COLOR_TIME_LINE, TRANSPARENT); aux = 0; } else { if (i > 0) { line(image, i * 10, 0, i * 10, image->h - 21, makecol(240, 240, 240)); } } aux++; } } void TimeLine::saveTimeLine() { PALLETE pal; char n[50]; get_palette(pal); BITMAP *temp = create_bitmap(image->w, image->h); clear_to_color(temp, makecol(255, 255, 255)); draw_sprite(temp, image, 0, 0); sprintf(n, "%s.bmp", fileName); save_bitmap(n, temp, pal); printf("Writting %s...\n", n); } void TimeLine::saveResponseTime() { FILE *file; char n[50]; sprintf(n, "%s.out", fileName); if ((file = fopen(n, "w")) == NULL) { fprintf(stderr, "Cannot open %s\n", n); exit(1); } for (unsigned int i = 0; i < task.size(); i++) { fprintf(file, "%s%d (%d, %.1f)\n", task[i]->name, task[i]->priority, task[i]->period, task[i]->execution); for (unsigned int j = 0; j < task[i]->aperiodic.size(); j++) { fprintf(file, "\t(A: r=%.1f, e=%.1f) - RT:%.1f\n", task[i]->aperiodic[j]->r, task[i]->aperiodic[j]->e, task[i]->aperiodic[j]->getResponseTime()); } } fclose(file); printf("Writting %s...\n", n); } TimeLine::~TimeLine() { saveTimeLine(); saveResponseTime(); for (unsigned int i = 0; i < task.size(); i++) { delete task[i]; } for (unsigned int i = 0; i < budget.size(); i++) { delete budget[i]; } }
true
b70d8716b425dc3e6b6b3e67d51e75ca258571e6
C++
ana-carolina-nunes/smartpillboxic
/arduino-rtc-bluetooth-reedswitch.ino
UTF-8
4,146
2.828125
3
[]
no_license
#include <Wire.h> #include <RTClib.h> //inclusão das bibliotecas //#include <SoftwareSerial.h> #define RX 8 #define TX 9 //SoftwareSerial bluetooth(RX, TX); // RX, TX RTC_DS3231 rtc; //OBJETO DO TIPO RTC_DS3231 //DECLARAÇÃO DOS DIAS DA SEMANA char daysOfTheWeek[7][12] = {"Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado"}; const int pinoLed = 12; //pino digital utilizado pelo LED const int pinoSensor=8; //pino digital utilizado pelo sensor void setup() { // put your setup code here, to run once: //RTC Serial.begin(9600); //INICIALIZA A SERIAL if(! rtc.begin()) { // SE O RTC NÃO FOR INICIALIZADO, FAZ Serial.println("DS3231 não encontrado"); //imprime o texto while(1); //SEMPRE ENTRE NO LOOP } if(rtc.lostPower()){ //SE RTC FOI LIGADO PELA PRIMEIRA VEZ / FICOU SEM ENERGIA / ESGOTOU A BATERIA, FAZ Serial.println("DS3231 OK!"); //imprime o texto //INSERINDO AS INFORMAÇÕES ATUALIZADAS EM SEU RTC (apenas para a primeira vez que for usar o RTC) //depois disso, a linha a seguir é opcional rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); //CAPTURA A DATA E HORA EM QUE O SKETCH É COMPILADO } delay(100); //INTERVALO DE 100 MILISSEGUNDOS //PREED SWITCH pinMode(pinoSensor, INPUT); //define o pino como entrada pinMode(pinoLed, OUTPUT); //define o pino como saída digitalWrite(pinoLed, LOW); //LED inicia desligado } /*void verificaBluetooth(){ // Verifica se existe algum dado a ser lido da serial if (bluetooth.available()){ // verifica se existem bytes a serem lidos da porta serial virtual char dados = bluetooth.read(); // Lê 1 byte da porta serial Serial.print(dados); // Mostra esse dado lido na porta serial if (dados=='0'){ // Se o byte lido for igual a 0 Serial.print(" Não há dados disponíveis (primeiro if) "); } else{ if (dados=='1'){ // Se o byte lido for igual a 1 Serial.print(" Não há dados disponíveis (segundo if)"); } } } }*/ void loop() { // put your main code here, to run repeatedly: //RTC DateTime now = rtc.now(); //CHAMADA DE FUNÇÃO /* Serial.print("Data: "); //IMPRIME O TEXTO NO MONITOR SERIAL Serial.print(now.day(), DEC); //IMPRIME NO MONITOR SERIAL O DIA Serial.print('/'); //IMPRIME O CARACTERE NO MONITOR SERIAL Serial.print(now.month(), DEC); //IMPRIME NO MONITOR SERIAL O MÊS Serial.print('/'); //IMPRIME O CARACTERE NO MONITOR SERIAL Serial.print(now.year(), DEC); //IMPRIME NO MONITOR SERIAL O ANO Serial.print(" / Dia: "); //IMPRIME O TEXTO NA SERIAL Serial.print(daysOfTheWeek[now.dayOfTheWeek()]); //IMPRIME NO MONITOR SERIAL O DIA Serial.print(" / Horas: "); //IMPRIME O TEXTO NA SERIAL Serial.print(now.hour(), DEC); //IMPRIME NO MONITOR SERIAL A HORA Serial.print(':'); //IMPRIME O CARACTERE NO MONITOR SERIAL Serial.print(now.minute(), DEC); //IMPRIME NO MONITOR SERIAL OS MINUTOS Serial.print(':'); //IMPRIME O CARACTERE NO MONITOR SERIAL Serial.print(now.second(), DEC); //IMPRIME NO MONITOR SERIAL OS SEGUNDOS */ //REED SWITCH if(digitalRead (pinoSensor) == LOW){ //se a leitura do pino for igual a LOW digitalWrite(pinoLed,LOW); //ascende o LED String variavel; variavel = (String)now.year()+"-"+(String)now.month()+"-"+(String)now.day()+"-"+(String)now.hour()+"-"+(String)now.minute()+"-"+(String)now.second(); Serial.print(variavel); Serial.print("-0-*"); //Serial.print(" LED DESLIGADO => caixinha FECHADA ");//0 }else{//se não digitalWrite (pinoLed, HIGH); //apaga o LED String variavel2; variavel2 = (String)now.year()+"-"+(String)now.month()+"-"+(String)now.day()+"-"+(String)now.hour()+"-"+(String)now.minute()+"-"+(String)now.second(); Serial.print(variavel2); Serial.print("-1-*"); // Serial.print(" LED LIGADO => caixinha ABERTA "); //1 } // Serial.println(); //QUEBRA DE LINHA NA SERIAL delay(10000); //INTERVALO DE 10 SEGUNDOS }
true
305cdfda738bc2fe27fe6dff97ce4759b157a7eb
C++
modrake/cpp-book-problems
/pointer-practice.cpp
UTF-8
371
3.40625
3
[]
no_license
#include <iostream> using namespace std; void dostuff (int a, int *b, int *c) { a = 3; *b = 3; cout << a << " " << *b << " " << *c << endl; } int main() { int a = 0; int *b = new int; int *c = new int; *b = 1; *c = 2; cout << a << " " << *b << " " << *c << endl; dostuff (a, b, c); cout << a << " " << *b << " " << *c << endl; return 0; }
true
837634764997c0f90ec99d7de91eba7ce8843d26
C++
teetotal/library
/ui/ui_ext.cpp
UTF-8
16,200
2.53125
3
[]
no_license
#include "ui_ext.h" #define _OPACITY 0.05f /* drawCircleForPhysics */ DrawNode * guiExt::drawCircleForPhysics(Node * p, Vec2 pos, float radius, COLOR_RGB color){ auto draw = DrawNode::create(); draw->drawDot(Vec2(radius, radius), radius, color.getColor4F()); // Color4F centerCircleColor = color.getColor4F(); // float opacity = (_OPACITY * 8) / ((radius - .1f) * 10); // centerCircleColor.a = 1; // for(float n = radius - .1f; n > .1f; n = n - 0.1f) { // centerCircleColor.r = std::fmin(1.f, centerCircleColor.r + opacity); // centerCircleColor.g = std::fmin(1.f, centerCircleColor.g + opacity); // centerCircleColor.b = std::fmin(1.f, centerCircleColor.b + opacity); // draw->drawDot(Vec2(radius, radius), n, centerCircleColor); // } draw->setContentSize(Size(radius * 2.f, radius * 2.f)); draw->setPosition(Vec2(pos.x - radius, pos.y - radius)); if(p) p->addChild(draw); return draw; } /* drawRectForPhysics */ DrawNode * guiExt::drawRectForPhysics(Node * p, Vec2 pos, Size size, COLOR_RGB color, bool isSolid, float thick){ auto draw = DrawNode::create(); if(isSolid) { draw->drawSolidRect(Vec2::ZERO, size, color.getColor4F()); Color4F line = color.getColorDark().getColor4F(); for(float n=0; n < thick; n = n + 0.1f) { draw->drawLine(Vec2(size.width, size.height - n), Vec2(0, size.height - n), line); draw->drawLine(Vec2(n, size.height), Vec2(n, 0.f), line); draw->drawLine(Vec2(size.width - n, size.height), Vec2(size.width - n, 0.f), line); draw->drawLine(Vec2(size.width, n), Vec2(0.f, n), line); } } else draw->drawRect(Vec2::ZERO, size, color.getColor4F()); draw->setContentSize(size); //physics를 적용하면 anchorpoint가 0,0 이되는 현상이 있다. draw->setPosition(Vec2(pos.x - size.width / 2.f, pos.y - size.height / 2.f)); if(p) p->addChild(draw); return draw; } /* drawRectRoundShadow */ DrawNode * guiExt::drawRectRoundShadow (Node * p, Vec2 pos, Size size, COLOR_RGB& color) { Color4F colorShadow = color.getColorLight().getColor4F(); Color4F colorMain = color.getColor4F(); gui::inst()->drawRectRound(p, Vec2(pos.x, pos.y), size, colorShadow); return gui::inst()->drawRectRound(p, pos, Size(size.width - 2.f, size.height - 2.f), colorMain); } /* addRoulette */ ui_roulette * guiExt::addRoulette(Node * p, Size size, Vec2 center, COLOR_RGB& color, COLOR_RGB& bg, const string sz) { auto roulette = ui_roulette::create(size, center, color, bg, sz); if(p) p->addChild(roulette); return roulette; } /* addIconCircle */ //Layout * guiExt::addIconCircle (Node * p, Vec2 pos, ALIGNMENT align, float radius, const string sz, COLOR_RGB color, const string szText, COLOR_RGB colorText) { // // Size sizeCircle = Size(radius * 2.f, radius * 2.f); // Size size = sizeCircle; // // Color4F colorOut, colorInner, colorOutline; // Color3B colorSymbol; // colorOut = color.getColorDark().getColor4F(); // colorInner = color.getColor4F(); // colorOutline = color.getColorDark().getColorDark().getColor4F(); // colorSymbol = color.getColorDark().getColorDark().getColor3B(); // // auto draw = DrawNode::create(); // Vec2 centerInner = Vec2(radius, radius); // // //outline //// draw->drawDot(centerInner, radius, colorOutline); // // //outcircle // draw->drawDot(centerInner, radius - .1, colorOut); // // //inner circle // draw->drawDot(centerInner, radius * 0.8f, colorInner); // // //circle text // float fontSize = gui::inst()->getFontSizeDefine(sizeCircle, -1); // auto label = Label::createWithSystemFont(sz, SYSTEM_FONT_NAME, fontSize); // label->setColor(colorSymbol); // gui::inst()->setAnchorPoint(label, ALIGNMENT_CENTER); // label->setPosition(centerInner); // // Label * labelText = NULL; // //text // if(szText.size() > 0) { // float fontSizeText = gui::inst()->getFontSizeDefine(sizeCircle, 0); // labelText = Label::createWithTTF(szText, gui::inst()->mDefaultFont, fontSizeText); // labelText->setColor(colorText.getColor3B()); // gui::inst()->setAnchorPoint(labelText, ALIGNMENT_LEFT_BOTTOM); // labelText->setPosition(Vec2(sizeCircle.width, 0)); // // size.width += labelText->getContentSize().width; // } // // auto layer = Layout::create(); //// layer->setBackGroundColor(Color3B::MAGENTA); //// layer->setBackGroundColorType(Layout::BackGroundColorType::SOLID); // layer->setContentSize(size); // // layer->addChild(draw); // layer->addChild(label); // // if(labelText) // layer->addChild(labelText); // // layer->setPosition(pos); // gui::inst()->setAnchorPoint(layer, align); // // // p->addChild(layer); // return layer; //} /* addIconHeart */ //Layout * guiExt::addIconHeart (Node * p, Vec2 pos, ALIGNMENT align, float fontSize, COLOR_RGB color, const string sz) { // auto layer = Layout::create(); // auto labelHeart = Label::createWithSystemFont("♥", SYSTEM_FONT_NAME, fontSize); // gui::inst()->setAnchorPoint(labelHeart, ALIGNMENT_LEFT_BOTTOM); // labelHeart->setPosition(Vec2::ZERO); // Size size = labelHeart->getContentSize(); // // if(sz.size() > 0) { // auto label = Label::createWithTTF(sz, gui::inst()->mDefaultFont, fontSize); // label->setColor(color.getColor3B()); // gui::inst()->setAnchorPoint(label, ALIGNMENT_LEFT_BOTTOM); // label->setPosition(Vec2(size.width, 0)); // // size.width += label->getContentSize().width; // layer->setContentSize(size); // // // layer->addChild(labelHeart); // layer->addChild(label); // } else { // layer->setContentSize(size); // layer->addChild(labelHeart); // } // // layer->setPosition(pos); // gui::inst()->setAnchorPoint(layer, align); // //// label->enableGlow(color.getColorDark().getColor4B()); // // p->addChild(layer); // return layer; //} Node * guiExt::addMovingEffect(Node * p , COLOR_RGB bgColor , const string img , const string text , COLOR_RGB fontColor , bool toRight , float speed , CallFunc * pCallFunc , CallFunc * pCallFuncInter) { auto layer = gui::inst()->createLayout(Size(p->getContentSize().width, p->getContentSize().height / 3), "", true, bgColor.getColor3B()); gui::inst()->setAnchorPoint(layer, ALIGNMENT_LEFT); layer->setPosition( Vec2(p->getContentSize().width * ((toRight) ? -1.f : 1.f), p->getContentSize().height / 2.f) ); layer->setOpacity(bgColor.getA()); auto center = EaseBackIn::create(MoveTo::create(.4f * speed, Vec2(0, p->getContentSize().height / 2.f))); auto left = EaseBackOut::create(MoveTo::create(.4f * speed, Vec2(p->getContentSize().width * -1.f, p->getContentSize().height / 2.f))); auto right = EaseBackOut::create(MoveTo::create(.4f * speed, Vec2(p->getContentSize().width * 1.f, p->getContentSize().height / 2.f))); Vector<FiniteTimeAction*> arr; arr.pushBack(center); arr.pushBack(DelayTime::create(.4f * speed)); if(pCallFuncInter) arr.pushBack(pCallFuncInter); arr.pushBack(toRight ? right : left); arr.pushBack(RemoveSelf::create()); if(pCallFunc) arr.pushBack(pCallFunc); layer->runAction(Sequence::create( arr )); Vec2 gridText = Vec2(1,1); int posText = 0; int fontSize = -2; if(img.length() > 0) { auto sprite = gui::inst()->getSprite(img); gui::inst()->setScaleByHeight(sprite, layer->getContentSize().height / 2.f); sprite->setPosition(gui::inst()->getCenter(layer)); sprite->runAction(Sequence::create(DelayTime::create(0.4f * speed) , ScaleBy::create(.2f * speed, 1.5) , ScaleBy::create(.2f * speed, 1 / 1.5) , NULL)); layer->addChild(sprite); gridText = Vec2(1,2); posText = 1; fontSize = -2; } if(text.length() > 0) { auto txt = gui::inst()->addLabelAutoDimension(0, posText, text, layer, fontSize, ALIGNMENT_CENTER, fontColor.getColor3B(), gridText, Vec2::ZERO, Vec2::ZERO, Vec2::ZERO); txt->enableGlow(Color4B::BLACK); if(img.length() == 0) { txt->runAction(Sequence::create(DelayTime::create(.4f * speed) ,ScaleBy::create(.2f * speed, 1.5) , ScaleBy::create(.2f * speed, 1 / 1.5) , NULL)); } else { txt->setOpacity(fontColor.getA()); } } p->addChild(layer); return layer; } void guiExt::addVibrateEffect(Node * p, CallFunc * pCallFunc, float duration, float width) { Vec2 pos = p->getPosition(); p->runAction(Sequence::create( MoveTo::create(duration, Vec2(pos.x - width, pos.y - width)) , MoveTo::create(duration, Vec2(pos.x + width, pos.y + width)) , MoveTo::create(duration, Vec2(pos.x - width, pos.y)) , MoveTo::create(duration, Vec2(pos.x + width, pos.y)) , MoveTo::create(duration, pos) , pCallFunc , NULL)); } void guiExt::addScaleEffect(Node * p , const string img , const string text , COLOR_RGB fontColor , CallFunc * pCallFunc , float duration , float sizeRatio , Vec2 specificPosition , bool isFadeout ) { Size size = p->getContentSize(); size.width *= sizeRatio; size.height *= sizeRatio; float min = fmin(size.width, size.height); auto layer = gui::inst()->createLayout(size); gui::inst()->setAnchorPoint(layer, ALIGNMENT_CENTER); Vec2 pos; if(specificPosition.x == -1 && specificPosition.y == -1) pos = gui::inst()->getCenter(p); else pos = specificPosition; layer->setPosition(pos); Vec2 grid = Vec2(1, 1); Vec2 position = Vec2::ZERO; float fontSize = -1; Sprite * pImg = NULL; Label * label = NULL; if(img.size() > 0) { pImg = gui::inst()->getSprite(img); gui::inst()->setScale(pImg, min); pImg->setPosition(gui::inst()->getCenter(layer)); layer->addChild(pImg); grid.y++; position.y++; fontSize--; } if(text.size() > 0) { label = gui::inst()->addLabelAutoDimension(position.x, position.y, text, layer, fontSize, ALIGNMENT_CENTER, fontColor.getColor3B(), grid, Vec2::ZERO, Vec2::ZERO, Vec2::ZERO); label->enableGlow(Color4B::BLACK); label->setOpacity(fontColor.getA()); } if(isFadeout) { if(pImg) { pImg->runAction(FadeOut::create(duration * 2)); } if(label) { label->runAction(FadeOut::create(duration * 2)); } } runScaleEffect(layer, pCallFunc, duration, true); p->addChild(layer); } void guiExt::runScaleEffect(Node * p, CallFunc * pCallFunc, float duration, bool isRemoveSelf) { Vector<FiniteTimeAction *> actions; float origin = p->getScale(); actions.pushBack(EaseBackIn::create(ScaleBy::create(duration, 1.2f))); actions.pushBack(EaseBackOut::create(ScaleTo::create(duration, origin))); if(isRemoveSelf) actions.pushBack(RemoveSelf::create()); if(pCallFunc) actions.pushBack(pCallFunc); Sequence * seq = Sequence::create(actions); p->runAction(seq); // p->runAction(Sequence::create( // EaseBackIn::create(ScaleTo::create(duration, 1.5f)) // , EaseBackOut::create(ScaleTo::create(duration, 1.f)) // , RemoveSelf::create() // , pCallFunc // , NULL)); } void guiExt::runFlyEffect(Node * p, CallFunc * pCallFunc, float duration, bool isDown, bool isRemoveSelf) { Vec2 direction = Vec2(p->getContentSize().width / 2.f, p->getContentSize().height * 1.5f); if(isDown) { direction.x *= -1.f; direction.y *= -1.f; } Spawn * spawn = Spawn::create(MoveBy::create(duration, direction) , FadeOut::create(duration) , NULL ); Vector<FiniteTimeAction *> actions; actions.pushBack(spawn); if(isRemoveSelf) actions.pushBack(RemoveSelf::create()); if(pCallFunc) actions.pushBack(pCallFunc); Sequence * seq = Sequence::create(actions); p->runAction(seq); } DrawNode * guiExt::drawRectCircleButton(Node * p, Vec2 pos, Size size, COLOR_RGB colorFront, COLOR_RGB colorBack) { DrawNode * draw; Size innerSize; if(colorBack.isValidColor) { draw = gui::inst()->drawRectCircle(p, pos, size, colorBack.getColor4F()); float innerMargin = size.height * 0.1f; innerSize = Size(size.width - innerMargin, size.height - innerMargin); draw = gui::inst()->drawRectCircle(NULL, Vec2(pos.x, pos.y), innerSize, colorFront.getColorDark().getColor4F(), draw); } else { draw = gui::inst()->drawRectCircle(p, pos, size, colorFront.getColorDark().getColor4F()); innerSize = size; } float shadowMargin = innerSize.height * 0.1f; draw = gui::inst()->drawRectCircle(NULL, Vec2(pos.x, pos.y + (shadowMargin / 2.f)), Size(innerSize.width, innerSize.height - shadowMargin), colorFront.getColor4F(), draw); return draw; } void guiExt::addBlinkStar(Node * p, CallFunc * pCallFunc, float d, Color3B color) { float duration = d; Vec2 grid = Vec2(3, 3); auto s1 = gui::inst()->createLabel(0, 1, "+", -1, ALIGNMENT_CENTER, color, p->getContentSize(), grid, Vec2::ZERO, Vec2::ZERO); auto s2 = gui::inst()->createLabel(2, 0, "+", 0, ALIGNMENT_CENTER, color, p->getContentSize(), grid, Vec2::ZERO, Vec2::ZERO); auto s3 = gui::inst()->createLabel(2, 2, "+", -2, ALIGNMENT_CENTER, color, p->getContentSize(), grid, Vec2::ZERO, Vec2::ZERO); const float scale = 1.8f; s1->runAction( Sequence::create(Spawn::create(RotateBy::create(duration, 270), ScaleBy::create(duration, scale), FadeOut::create(duration), NULL) , pCallFunc, NULL) ); duration = d * 0.75f; s2->runAction(Sequence::create( Hide::create() , DelayTime::create(d * 0.25f) , Show::create() , Spawn::create(RotateBy::create(duration, 270), ScaleBy::create(duration, scale), FadeOut::create(duration), NULL) , NULL) ); duration = d * 0.5f; s3->runAction(Sequence::create( Hide::create() , DelayTime::create(d * 0.5f) , Show::create() , Spawn::create(RotateBy::create(duration, 360), ScaleBy::create(duration, scale), FadeOut::create(duration), NULL) , NULL )); p->addChild(s1); p->addChild(s2); p->addChild(s3); }
true
6b3f1a3cd5861f1a23fc85a08c2e80ef82808291
C++
CMilly/DeviantTools-Math_Engine-Libray
/vd1m/vd1m/ext/Mat2_rotclock.hpp
UTF-8
593
2.59375
3
[]
no_license
/** * Created by: Cameron Mims * vDefiant1 Math Engine - Personal Project * File - Mat2_rotclock.hpp * Date (Started) - 05/13/19 */ #ifndef VDEFIANT1_MATH_ENGINE_MAT2_ROTCLOCK_HPP #define VDEFIANT1_MATH_ENGINE_MAT2_ROTCLOCK_HPP #include <vd1m/Vec2.hpp> namespace vd1m{ /** * Class that represents a 2-D clockwise rotation matrix */ class Mat2_rotclock{ private: float matrix2_rotclock[4]; public: Mat2_rotclock(); Mat2_rotclock(float theta); Vec2 operator*(const Vec2 &v); }; } #endif //VDEFIANT1_MATH_ENGINE_MAT2_ROTCLOCK_HPP
true
f92a67e72a24c339ef6301e07e1d68bcc80ef5b7
C++
ppawel11/True-Life
/src/TrueLife/Controller/Controller.cpp
UTF-8
600
2.59375
3
[]
no_license
/** * @author Paweł Lech */ #include "Controller.h" Controller::Controller(){} void Controller::attachEnv(boost::shared_ptr<Observer> obs){ env_observer = obs; } void Controller::attachSimu(boost::shared_ptr<Observer> obs){ simu_observer = obs; } void Controller::notifyEnv(boost::shared_ptr<EnvDataModel> data){ //boost::shared_ptr<InitDataModel> mod(data); env_observer->update(data); } SpecificAnimalModel* Controller::request(int id){ return env_observer->update(id); } void Controller::notifySimu(boost::shared_ptr<EnvDataModel> data){ simu_observer->update(data); }
true
e7d1f5dc15bb6cf084465c7bbe9e9ff76c019d26
C++
talkami/OOP
/Project1/Project1/Board.cpp
UTF-8
10,138
3.21875
3
[]
no_license
#include "Board.h" #include <string> #include <fstream> #include <iostream> //empty constructor Board::Board() { for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { this->matrix[i][j] = new Point; this->matrix[i][j]->setX(i); this->matrix[i][j]->setY(j); } } this->playerABoard = new char *[10]; this->playerBBoard = new char *[10]; for (int i = 0; i < 10; i++) { this->playerABoard[i] = new char[10]; this->playerBBoard[i] = new char[10]; } } Board::~Board() { for (int i = 0; i<10; i++) { delete[]this->playerABoard[i]; delete[]this->playerBBoard[i]; } delete[]playerABoard; delete[]playerBBoard; } //unused constructor //Board(const string& boardFile){ //matrix(NULL); //getBoard(boardFile); //} //load board function bool Board::loadBoard(const std::string& boardFile, Player* A, Player* B) { bool result = true; /// there is so much shit need to be chekced here!! std::string board[10]; std::ifstream fin(boardFile); if (!fin) { //error return false; } for (int i = 0; i < 10; i++) { if (!std::getline(fin, board[i])) { board[i] = " "; } while (board[i].length() < 10) { board[i].append(" "); } } // putting up the points- checking if the left/ up to the current point have a boat in it, and by that updating the "NEAR" variable for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { char currentChar = board[i].at(j); if (i>0) { this->matrix[i][j]->setUp(this->matrix[i - 1][j]); this->matrix[i - 1][j]->setDown(this->matrix[i][j]); if (this->matrix[i - 1][j]->getBoat() != nullptr) { this->matrix[i][j]->setNear(true); } } if (j>0) { this->matrix[i][j]->setLeft(this->matrix[i][j - 1]); this->matrix[i][j - 1]->setRight(this->matrix[i][j]); if (this->matrix[i][j - 1]->getBoat() != nullptr) { this->matrix[i][j]->setNear(true); } } addToPlayerBoard(currentChar, i, j, A, B); } } checkBoatValidity(); result = checkBoard(); result = (checkNumOfPlayersBoats(A,B) && result); if (this->errorArray[8]) { result = false; std::cout << "Adjacent Ships on Board" << std::endl; } return result; } //checking the charecter read from the file and putting the boats on the board void Board::addToPlayerBoard(char currentChar, int row, int col, Player* A, Player* B) { if (currentChar == 'B') { addBoatToBoard(this->matrix[row][col], row, col, 1, 0, A, B); this->playerABoard[row][col] = 'B'; this->playerBBoard[row][col] = ' '; } if (currentChar == 'b') { addBoatToBoard(this->matrix[row][col], row, col, 1, 1, B, A); this->playerABoard[row][col] = ' '; this->playerBBoard[row][col] = 'b'; } if (currentChar == 'P') { addBoatToBoard(this->matrix[row][col], row, col, 2, 0, A, B); this->playerABoard[row][col] = 'P'; this->playerBBoard[row][col] = ' '; } if (currentChar == 'p') { addBoatToBoard(this->matrix[row][col], row, col, 2, 1, B, A); this->playerABoard[row][col] = ' '; this->playerBBoard[row][col] = 'p'; } if (currentChar == 'M') { addBoatToBoard(this->matrix[row][col], row, col, 3, 0, A, B); this->playerABoard[row][col] = 'M'; this->playerBBoard[row][col] = ' '; } if (currentChar == 'm') { addBoatToBoard(this->matrix[row][col], row, col, 3, 1, B, A); this->playerABoard[row][col] = ' '; this->playerBBoard[row][col] = 'm'; } if (currentChar == 'D') { addBoatToBoard(this->matrix[row][col], row, col, 4, 0, A, B); this->playerABoard[row][col] = 'D'; this->playerBBoard[row][col] = ' '; } if (currentChar == 'd') { addBoatToBoard(this->matrix[row][col], row, col, 4, 1, B, A); this->playerABoard[row][col] = ' '; this->playerBBoard[row][col] = 'd'; } else { this->playerABoard[row][col] = ' '; this->playerBBoard[row][col] = ' '; } } //checking that all boats are of correct size and shape void Board::checkBoatValidity() { for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { Boat* boat = this->matrix[i][j]->getBoat(); if (boat != nullptr) { if ((boat->getBoatSize() != boat->getAcctualSize()) || !boat->isValid()) { int errorNum = (boat->getBoatSize() - 1) + (4 * boat->getPlayer()); errorArray[errorNum] = true; boat->getOwner()->removeBoat(); delete boat; } } } } } bool Board::checkBoard() { bool result = true; if (errorArray[0]){ std::cout << "Wrong size or shape for ship B for player A" << std::endl; result = false; } if (errorArray[1]) { std::cout << "Wrong size or shape for ship P for player A" << std::endl; result = false; } if (errorArray[2]) { std::cout << "Wrong size or shape for ship M for player A" << std::endl; result = false; } if (errorArray[3]) { std::cout << "Wrong size or shape for ship D for player A" << std::endl; result = false; } if (errorArray[4]) { std::cout << "Wrong size or shape for ship b for player B" << std::endl; result = false; } if (errorArray[5]) { std::cout << "Wrong size or shape for ship p for player B" << std::endl; result = false; } if (errorArray[6]) { std::cout << "Wrong size or shape for ship m for player B" << std::endl; result = false; } if (errorArray[7]) { std::cout << "Wrong size or shape for ship d for player B" << std::endl; result = false; } return result; } //checking each player have the right amount of boats bool Board::checkNumOfPlayersBoats(Player* A, Player* B) { bool result = true; int numOfBoatsA = A->getNumOfBoats(); if (numOfBoatsA < 5) { result = false; std::cout << "Too few ships for player A" << std::endl; } if (numOfBoatsA > 5) { result = false; std::cout << "Too many ships for player A" << std::endl; } int numOfBoatsB = B->getNumOfBoats(); if (numOfBoatsB < 5) { result = false; std::cout << "Too few ships for player B" << std::endl; } if (numOfBoatsB > 5) { result = false; std::cout << "Too many ships for player B" << std::endl; } return result; } // attack function - get pair and attack at the <x,y> point in the "matrix" variable. // maybe will print out the attack- ask Tal- remember remember!!!!!!!!!!!!!!! AttackResult Board::play_attack(std::pair<int, int> attack, int attacker, bool* selfHit) { int x = attack.first; int y = attack.second; AttackResult result = matrix[x][y]->attack(attacker, selfHit); return result; // print the attack result? } char** Board::getPlayerABoard() { return this->playerABoard; } char** Board::getPlayerBBoard() { return this->playerBBoard; } //inner function helping the loadBoard. pretty much useless outside. void Board::addBoatToBoard(Point* point, int i, int j, int size, int player, Player* owner, Player* rival) { //if no boat near the current point if (!point->getNear()) { Boat* boat =new Boat(size, player, owner, rival, point); point->setBoat(boat); if (i > 0) { point->getUp()->setNear(true); } if (j > 0) { point->getLeft()->setNear(true); } } //if there is boat near the current point else { if (i > 0) { Boat* boat = point->getUp()->getBoat(); if (boat != nullptr) { //if there is a boat left to the current point if (boat->getBoatSize() == size && boat->getHorizontal() < 2 && boat->getAcctualSize() < size && boat->getPlayer() == player) { //if the left boat match to the current boat variables (size, player, horizontal and it is no bigger then its max size) boat->addPoint(point); boat->setHorizontal(1); point->setBoat(boat); point->getUp()->setNear(true); if (j > 0) { point->getLeft()->setNear(true); } } else { //if boat is next to another boat - create new boat. do not set the boats unvalid- will be count at the total boat count if (boat->getBoatSize() != size || boat->getPlayer() != player) { Boat* newBoat = new Boat(size, player, owner, rival, point); point->setBoat(newBoat); if (j > 0) { point->getLeft()->setNear(true); } this->errorArray[8] = true; } //if the boat is at wrong shape or too big set the boat unvalid- won't be count at the total boat count else { boat->addPoint(point); boat->setValid(false); point->setBoat(boat); point->getUp()->setNear(true); if (j > 0) { point->getLeft()->setNear(true); } } } } } if (j > 0) { Boat* boat = point->getLeft()->getBoat(); if (boat != nullptr) { //if there is a boat next to the current point if (boat->getBoatSize() == size && boat->getHorizontal() != 1 && boat->getAcctualSize() < size && boat->getPlayer() == player) { //if the boat above match to the current boat variables (size, player, horizontal and it is no bigger then its max size) boat->addPoint(point); boat->setHorizontal(2); if (point->getBoat() != nullptr) { if (!point->getBoat()->isValid()) { boat->setValid(false); } else { delete point->getBoat(); } owner->removeBoat(); } point->setBoat(boat); if (i > 0) { point->getUp()->setNear(true); } } else { if (boat->getBoatSize() != size || boat->getPlayer() != player) { //if boat is next to another boat - create new boat. do not set the boats unvalid- will be count at the total boat count if (point->getBoat() != nullptr) { this->errorArray[8] = true; return; } Boat* newBoat = new Boat(size, player, owner, rival, point); point->setBoat(newBoat); point->getLeft()->setNear(true); if (i > 0) { point->getUp()->setNear(true); } this->errorArray[8] = true; return; } else { //if the boat is at wrong shape or too big set the boat invalid- won't be count at the total boat count if ((point->getBoat() != nullptr) && (point->getBoat() != boat)) { delete point->getBoat(); owner->removeBoat(); } boat->setValid(false); boat->addPoint(point); point->setBoat(boat); if (i > 0) { point->getUp()->setNear(true); } point->getLeft()->setNear(true); return; } } } } } }
true
aae0c5d852fd2b7244b563899c52e493c80006e3
C++
darkjedi9922/listpad
/core/TableRows.cpp
UTF-8
958
2.671875
3
[]
no_license
#include "core/TableRows.h" #include <QXmlStreamReader> using namespace Core; TableRows::TableRows(const QString &datafile) { setDatafile(datafile); } void TableRows::setDatafile(const QString &datafile) { this->datafile = datafile; loadRows(); } QString TableRows::getDatafile() const { return this->datafile; } const QList<QList<QString>>& TableRows::getRows() const { return rows; } void TableRows::loadRows() { rows.clear(); if (!QFile::exists(datafile)) return; QFile file(datafile); file.open(QIODevice::ReadWrite | QFile::Text); QXmlStreamReader reader(&file); do { reader.readNext(); if (reader.isStartElement() && reader.name() == "row") { QList<QString> newRow; for (auto attr : reader.attributes()) { newRow.append(attr.value().toString()); } rows.append(newRow); } } while (!reader.atEnd()); }
true
ee33e5723308ad6b97e9c2b3559054ff7eb98fcd
C++
mzry1992/workspace
/contest/2012summer/UESTC Summer Training #25/I.cpp
UTF-8
2,246
2.78125
3
[]
no_license
#include <iostream> #include <algorithm> #include <cstdio> #include <cstring> #include <queue> using namespace std; struct Edge { int to,next; char val; }edge[2][30000]; int L[2],head[2][2000],nxt[2000][26]; int n[2],s[2],m[2]; void addedge(int id,int u,int v,char val) { edge[id][L[id]].to = v; edge[id][L[id]].val = val; edge[id][L[id]].next = head[id][u]; head[id][u] = L[id]++; } bool visit[2000][2000]; bool BFS() { queue<pair<int,int> > Q; memset(visit,false,sizeof(visit)); visit[s[0]][s[1]] = true; Q.push(make_pair(s[0],s[1])); while (!Q.empty()) { pair<int,int> now = Q.front(); Q.pop(); if (now.second == n[1]-1) return false; for (int i = head[0][now.first];i != -1;i = edge[0][i].next) { pair<int,int> nn = make_pair(edge[0][i].to,nxt[now.second][edge[0][i].val-'a']); if (visit[nn.first][nn.second] == false) { visit[nn.first][nn.second] = true; Q.push(nn); } } } return true; } int main() { int totcas; scanf("%d",&totcas); while (totcas--) { for (int i = 0;i < 2;i++) { scanf("%d%d%d",&n[i],&m[i],&s[i]); s[i]--; if (i == 1) n[i]++; for (int j = 0;j < n[i];j++) head[i][j] = -1; L[i] = 0; for (int j = 0;j < m[i];j++) { int u,v; char val; scanf("%d %c%d",&u,&val,&v); while (u < 1 || u > n[i] || (v != -1 && (v < 1 || v > n[i]))) puts("fuck"); u--,v--; if (v == -2) v = n[i]-1; addedge(i,u,v,val); } } for (int i = 0;i < n[1];i++) { for (int j = 0;j < 26;j++) nxt[i][j] = i; for (int j = head[1][i];j != -1;j = edge[1][j].next) nxt[i][edge[1][j].val-'a'] = edge[1][j].to; } if (BFS()) puts("satisfied"); else puts("violated"); } return 0; }
true
c85f32d0b776e23034830a4903789409b2caf538
C++
Sometrik/sqldb
/src/CSV.cpp
UTF-8
10,013
2.515625
3
[ "MIT" ]
permissive
#include "CSV.h" #include <Cursor.h> #include "TextFile.h" #include "utils.h" #include <vector> #include <cassert> #include <charconv> using namespace sqldb; using namespace std; static inline vector<string> split(string_view line, char delimiter) { vector<string> r; if (!line.empty()) { size_t i = 0; bool in_quote = false; string current; size_t n = line.size(); for ( ; i < n; i++) { auto c = line[i]; if (c == '\r') { // ignore carriage returns } else if (!in_quote && c == '"') { in_quote = true; } else if (in_quote) { if (c == '\\') current += line[++i]; else if (c == '"') in_quote = false; else current += c; } else if (c == delimiter) { r.push_back(std::move(current)); current.clear(); } else { current += c; } } r.push_back(std::move(current)); } return r; } class sqldb::CSVFile : public sqldb::TextFile { public: CSVFile(std::string filename, bool has_records) : TextFile(move(filename)) { open(has_records); } void open(bool has_records) { in_ = fopen(filename_.c_str(), "rb"); if (in_) { if (has_records) { auto [ s, error ] = get_record(); // autodetect delimiter if (!delimiter_) { size_t best_n = 0; char best_delimiter = 0; for (int i = 0; i < 3; i++) { char d; if (i == 0) d = ','; else if (i == 1) d = ';'; else d = '\t'; auto tmp = split(s, d); auto n = tmp.size(); if (n > best_n) { best_n = n; best_delimiter = d; } } // if there are no delimiters in header, use no delimiter if (best_n) { delimiter_ = best_delimiter; } } header_row_ = split(s, delimiter_); } else { header_row_.push_back("Content"); } } else { throw std::runtime_error("Failed to open CSV"); } } CSVFile(const CSVFile & other) : TextFile(other), delimiter_(other.delimiter_), next_row_idx_(other.next_row_idx_), header_row_(other.header_row_), current_row_(other.current_row_), // input_buffer_(other.input_buffer_), row_offsets_(other.row_offsets_) { in_ = fopen(filename_.c_str(), "rb"); if (in_) fseek(in_, ftell(other.in_), SEEK_SET); } std::string_view getText(int column_index) const { auto idx = static_cast<size_t>(column_index); return idx < current_row_.size() ? current_row_[idx] : null_string; } bool isNull(int column_index) const { auto idx = static_cast<size_t>(column_index); return idx < current_row_.size() ? current_row_[idx].empty() : true; } int getNumFields() const { return static_cast<int>(header_row_.size()); } const std::string & getColumnName(int column_index) const { auto idx = static_cast<size_t>(column_index); return idx < header_row_.size() ? header_row_[idx] : null_string; } int getNextRowIdx() const { return next_row_idx_; } bool seek(int row) { if (!in_) { return false; } if (row + 1 == next_row_idx_) { return true; } if (row < static_cast<int>(row_offsets_.size())) { input_buffer_.clear(); next_row_idx_ = row; fseek(in_, row_offsets_[next_row_idx_], SEEK_SET); return next(); } if (!row_offsets_.empty()) { input_buffer_.clear(); next_row_idx_ = static_cast<int>(row_offsets_.size()) - 1; fseek(in_, row_offsets_.back(), SEEK_SET); row -= static_cast<int>(row_offsets_.size()) - 1; } while (row > 0) { auto r = next(); if (!r) return false; row--; } return next(); } bool next() { size_t row_offset = ftell(in_) - input_buffer_.size(); auto [ s, ec ] = get_record(); switch (ec) { case Error::OK: break; case Error::Eof: return false; case Error::InvalidUtf8: throw std::runtime_error("Invalid UTF8 in CSV"); } current_row_ = split(s, delimiter_); if (next_row_idx_ == static_cast<int>(row_offsets_.size())) { row_offsets_.push_back(row_offset); } next_row_idx_++; return true; } private: std::pair<std::string, Error> get_record() { while ( 1 ) { bool quoted = false; for (size_t i = 0; i < input_buffer_.size(); i++) { if (!quoted && input_buffer_[i] == '"') { quoted = true; } else if (input_buffer_[i] == '\\') { i++; } else if (quoted && input_buffer_[i] == '"') { quoted = false; } else if (!quoted && input_buffer_[i] == '\n') { auto record0 = string_view(input_buffer_).substr(0, i); if (record0.back() == '\r') record0.remove_suffix(1); auto [ r, ec ] = normalize_nfc(record0); input_buffer_ = input_buffer_.substr(i + 1); if (ec) return std::pair(std::move(r), Error::InvalidUtf8); else return std::pair(std::move(r), Error::OK); } } if (in_) { char buffer[4096]; auto r = fread(buffer, 1, 4096, in_); if (r > 0) { input_buffer_ += std::string(buffer, r); continue; } } // If the last row is not \n terminated, return it anyway if (!input_buffer_.empty()) { auto [ r, ec ] = normalize_nfc(input_buffer_); input_buffer_.clear(); if (ec) return std::pair(r, Error::InvalidUtf8); else return std::pair(r, Error::OK); } else { return std::pair(std::string(), Error::Eof); } } } char delimiter_ = 0; int next_row_idx_ = 0; std::vector<std::string> header_row_; std::vector<std::string> current_row_; std::vector<size_t> row_offsets_; static inline std::string null_string; }; class CSVCursor : public Cursor { public: CSVCursor(const std::shared_ptr<sqldb::CSVFile> & csv, int row, int sheet) : csv_(csv), sheet_(sheet) { csv_->seek(row); updateRowKey(); } bool next() override { if (csv_->next()) { updateRowKey(); return true; } else { return false; } } std::string_view getText(int column_index) override { return csv_->getText(column_index); } double getDouble(int column_index, double default_value = 0.0) override { auto s = getText(column_index); if (!s.empty()) { double d; auto [ ptr, ec ] = std::from_chars(s.data(), s.data() + s.size(), d); if (ec == std::errc()) return d; } return default_value; } float getFloat(int column_index, float default_value = 0.0f) override { auto s = getText(column_index); if (!s.empty()) { float f; auto [ ptr, ec ] = std::from_chars(s.data(), s.data() + s.size(), f); if (ec == std::errc()) return f; } return default_value; } int getInt(int column_index, int default_value = 0) override { auto s = getText(column_index); if (!s.empty()) { int i; auto [ ptr, ec ] = std::from_chars(s.data(), s.data() + s.size(), i); if (ec == std::errc()) return i; } return default_value; } long long getLongLong(int column_index, long long default_value = 0) override { auto s = getText(column_index); if (!s.empty()) { long long ll; auto [ ptr, ec ] = std::from_chars(s.data(), s.data() + s.size(), ll); if (ec == std::errc()) return ll; } return default_value; } Key getKey(int column_index) override { return Key(getText(column_index)); } int getNumFields() const override { return csv_->getNumFields(); } vector<uint8_t> getBlob(int column_index) override { auto v = csv_->getText(column_index); std::vector<uint8_t> r; for (size_t i = 0; i < v.size(); i++) r.push_back(static_cast<uint8_t>(v[i])); return r; } bool isNull(int column_index) const override { return csv_->isNull(column_index); } const std::string & getColumnName(int column_index) override { return csv_->getColumnName(column_index); } void set(int column_idx, std::string_view value, bool is_defined = true) override { throw std::runtime_error("CSV is read-only"); } void set(int column_idx, int value, bool is_defined = true) override { throw std::runtime_error("CSV is read-only"); } void set(int column_idx, long long value, bool is_defined = true) override { throw std::runtime_error("CSV is read-only"); } void set(int column_idx, double value, bool is_defined = true) override { throw std::runtime_error("CSV is read-only"); } void set(int column_idx, const void * data, size_t len, bool is_defined = true) override { throw std::runtime_error("CSV is read-only"); } size_t execute() override { throw std::runtime_error("CSV is read-only"); } size_t update(const Key & key) override { throw std::runtime_error("CSV is read-only"); } long long getLastInsertId() const override { return 0; } protected: void updateRowKey() { Key key; key.addComponent(sheet_); if (csv_->getNextRowIdx() >= 1) key.addComponent(csv_->getNextRowIdx() - 1); setRowKey(std::move(key)); } private: std::shared_ptr<CSVFile> csv_; int sheet_; }; CSV::CSV(std::string csv_file, bool has_records) { csv_.push_back(make_shared<CSVFile>(move(csv_file), has_records)); std::vector<ColumnType> key_type = { ColumnType::INT, ColumnType::INT }; setKeyType(std::move(key_type)); } CSV::CSV(const CSV & other): Table(other) { for (auto & csv : other.csv_) { csv_.push_back(make_shared<CSVFile>(*csv)); } } CSV::CSV(CSV && other) : Table(other), csv_(move(other.csv_)) { } int CSV::getNumFields(int sheet) const { if (sheet >= 0 && sheet < static_cast<int>(csv_.size())) { return csv_[sheet]->getNumFields(); } else { return 0; } } const std::string & CSV::getColumnName(int column_index, int sheet) const { if (sheet >= 0 && sheet < static_cast<int>(csv_.size())) { return csv_[sheet]->getColumnName(column_index); } else { return empty_string; } } unique_ptr<Cursor> CSV::seek(const Key & key) { return seek(key.getInt(1), key.getInt(0)); } unique_ptr<Cursor> CSV::seek(int row, int sheet) { return make_unique<CSVCursor>(csv_[sheet], row, sheet); }
true
035cb7dea79478748ec6412e5f396f02aa4feed6
C++
BBenNguyenn/Emergency-Room-Queue-Simulation
/Queue.cpp
UTF-8
1,734
3.84375
4
[]
no_license
// CLASS: Queue // REMARKS: What is the purpose of this class? // Linked list queue data structure. //----------------------------------------- #include <iostream> // for definition of NULL #include "Queue.hpp" #include "Node.hpp" //we DO NOT need to #include ListItem.h here because we're not //using any of its methods or defining any instance. //we DO need to include Node because we're using one of //its methods (top's print!) and we are creating a new node using namespace std; class ListItem; //constructor Queue::Queue() : front(NULL), end(NULL) {} //destructor Queue::~Queue() {} void Queue::print() { cout << "[ "; if (!isEmpty()) front->print(); cout << "]" << endl; } void Queue::enqueue(ListItem *newItem) { Node *newNode = new Node(newItem, NULL); if (front == NULL && end == NULL) { front = newNode; end = newNode; } else { end->setLink(newNode); end = newNode; } // front = new Node(newItem, front); } // end enqueue ListItem *Queue::dequeue() { ListItem *returnItem = NULL; Node *newFront = NULL; if (!isEmpty()) { returnItem = front->getItem(); if (front != end) //normal case newFront = front->getLink(); else { //last node edge case newFront = NULL; end = NULL; } delete front; front = newFront; } // if (front) // { // if (Event *e = dynamic_cast<Event *>(front->getItem())) // { // // old was safely casted to NewType // // e->doSomething(); // cout<<"REM "; // print(); // } // } // else // cout << "NULL FRONT" << endl; return returnItem; } // end dequeue ListItem *Queue::peek() { ListItem *theItem = NULL; if (front) theItem = front->getItem(); return theItem; } bool Queue::isEmpty() { return front == NULL; }
true
63707326e9dcd4866cf6851e1d1b2eb233f4d19f
C++
brayangomez22/resources-and-practices-with-c
/matrices/hallar si la matriz es simetrica.cpp
UTF-8
711
3.046875
3
[]
no_license
#include<iostream> #include<conio.h> #include<math.h> using namespace std; int main (){ int numeros[100][100], filas, columnas; char bandera = 'f'; cout<<"digie el numero de filas: "; cin>>filas; cout<<"digite el numero de columnas: "; cin>>columnas; for( int i=0; i<filas; i++ ){ for( int j=0; j<columnas; j++ ){ cout<<"digite un numero ["<<i<<"]["<<j<<"]: "; cin>>numeros[i][j]; } } if(filas == columnas ){ for( int i=0; i<filas; i++ ){ for( int j=0; j<columnas; j++ ){ if(numeros[i][j] == numeros[j][i] ){ bandera = 'v'; } } } } if(bandera == 'v' ){ cout<<"\nla matriz es simetrica"; }else{ cout<<"\nla matriz no es simetrica"; } getch(); return 0; }
true
c0e525fdfe63666cb627a37ff1223a470cc4965b
C++
yuyuOWO/source-code
/CPP/string其他方法.cpp
UTF-8
673
3.40625
3
[]
no_license
#include <iostream> #include <string> using namespace std; int main(int argc, char const *argv[]) { const char * a = "abcdefghijklmnopqrstuvwxyz"; cout << a << endl; string s1(a); cout << "s1(a), s1 = " << s1 << endl; string s2(a + 23, 2); cout << "s2(a + 23, 2), s2 = " << s2 << endl; string s3(a + 4, 5); cout << "s3(a + 4, 5), s3 = " << s3 << endl; string s4(a, 4, 5); cout << "s4(a, 4, 5), s4 = " << s4 << endl; string s5(a, 4); cout << "s5(a, 4), s5 = " << s5 << endl; string s6(a, 4, 100); cout << "a6(a, 4, 100), s6 = " << s6 << endl; /* string s7(a, 100);抛出out_of_range异常 cout << "s7(a, 100), s7 = " << s7 << endl; */ return 0; }
true
abf6f3c048f38ec6a579ecfb6a3be48150b780fd
C++
lucaimperiale/Algo3-tps
/algo3-tp1/funciones.cpp
UTF-8
3,575
3.203125
3
[]
no_license
// // Created by Luca on 9/11/2018. // #include "funciones.h" int min(int x,int y){ return (x) < (y) ? x : y; } int sumarUno(int x){return x==INT32_MAX ? INT32_MAX : x+1;} int optimo(int x, int y){ if(x == -1){ return y; } if( y == -1){ return x; } return min(x,y); } int solveFuerzaBruta(vector<int>& elementos, int objetivo){ int suma,aux; int cantidad = -1; int lim = pow(2.0,(float)elementos.size())-1; for (int i=1; i < lim ;i++){ suma = 0; aux = 0; bitset<32> bin(i); for (int j = 0; j<32;j++){ if(bin[j]){ suma = suma + elementos[j]; aux++; } } if(suma == objetivo){ if(aux < cantidad or cantidad == -1){ cantidad = aux; } } } return cantidad; } bool factibilidad(vector<int> elem,int obj){ int res=0; for(int i=0;i<elem.size();i++){ res += elem[i]; if(res>= obj){ return true; } } return false; } int solveBacktracking(vector<int> &elementos, int objetivo){ int min = elementos.size()+1; vector<bool> usados (elementos.size(),true); int suma = 0; for (int i = 0; i < elementos.size(); i++) { suma += elementos[i]; } fBacktracking(elementos,usados,objetivo,min,suma); return min; } int cantUsados(vector<bool> s){ int res =0; for(auto it=s.begin();it!=s.end();it++){ if(*it){ res++; } } return res; } void fBacktracking(vector<int> &elementos, vector<bool> &usados,int objetivo,int& min, int suma){ int res = cantUsados(usados); if(min>res){ if(suma == objetivo){ min = res; } } for(int i=0;i<elementos.size() ;i++){ if(usados[i]) { if (suma - elementos[i] >= objetivo) { usados[i] = false; fBacktracking(elementos, usados, objetivo, min, suma - elementos[i]); usados[i] = true; } } } } int solveDinamica(vector<int> &elementos, int objetivo){ vector<vector<int> > yaCalculados(objetivo+1,vector<int>(elementos.size()+1,-1)); int res = fDinamica(elementos,yaCalculados,objetivo,elementos.size()); return res != INT32_MAX ? res : -1; } int fDinamica(vector<int>& elem, vector<vector<int> > &yaCalculados, int obj, int i){ if (yaCalculados[obj][i] == -1){ if(i==0 and obj==0) { yaCalculados[obj][i] = 0;} if(i==0 and obj!=0) { yaCalculados[obj][i] = INT32_MAX;} if(i>0 and elem[i-1]>obj) { yaCalculados[obj][i] = fDinamica(elem,yaCalculados,obj,i-1);} if(i>0 and elem[i-1]<= obj) { yaCalculados [obj][i]= min(fDinamica(elem,yaCalculados,obj,i-1),sumarUno(fDinamica(elem,yaCalculados,obj-elem[i-1],i-1)));} } return yaCalculados[obj][i]; } int solveBacktrackingIterativo(vector<int> &elementos, int objetivo){ int suma,aux; int cantidad = -1; for (int i=1; i < pow(2.0,(float)elementos.size()) ;i++){ suma = 0; aux = 0; bitset<32> bin(i); for (int j = 0; j<32 and suma<objetivo and (aux < cantidad or cantidad == -1);j++){ if(bin[j]==1){ suma = suma + elementos[j]; aux++; } } if(suma == objetivo){ if(aux < cantidad or cantidad == -1){ cantidad = aux; } } } return cantidad; }
true
fe00f34a322a95641eb59cf0164cf3ef68aac55b
C++
fallow24/starsensor
/src/img/Roi.cpp
UTF-8
2,037
3.484375
3
[]
no_license
#include "Roi.h" //find a focuspoint from a star Pointf* Roi::focus(int* grayscaledImage, int width, std::vector<Point*> star) { //use a ROI with size nxn Point* brightest = brightestPixel(grayscaledImage, width, star); int n = determineSize(brightest, grayscaledImage, width); //with advanced dynamic roi double sumx = 0, sumy = 0, sumh = 0, h; //sum of all x, y and h for(int x = brightest->x - n/2; x < brightest->x + n/2; x++) { for(int y = brightest->y - n/2; y < brightest->y + n/2; y++) { h = grayscaledImage[y * width + x]; //function h(x,y) is brightnes sumx += x * h; sumy += y * h; sumh += h; } } //calc focuspoint (x, y) in double double x = sumx/sumh; double y = sumy/sumh; Pointf* focuspoint = new Pointf(x, y); return focuspoint; } //advanced dynamic ROI int Roi::determineSize(Point* brightest, int* grayscaledImage, int width) { int brightness = grayscaledImage[brightest->y * width + brightest->x]; return brightness / 34 + 3; //mindestesgroesse für ein ROI ist 3x3, maximalgroesse ist 10x10 } Point* Roi::brightestPixel(int* grayscaledImage, int width, std::vector<Point*> star) { Point *result, *brightest; //find the pixel with the maximum magnitude int max_magnitude = 0, magnitude; for(int i = 0; i < star.size(); i++) { magnitude = grayscaledImage[star[i]->y * width + star[i]->x]; if(magnitude > max_magnitude) { max_magnitude = magnitude; brightest = star[i]; } } result = new Point(brightest->x, brightest->y); return result; } Pointf** Roi::focuspoints(int* grayscaledImage, int width, std::vector<Point*> *stars, int numberofstars) { Pointf** focuspoints = new Pointf*[numberofstars]; //calculate focus points for(int i = 0; i < numberofstars; i++) { focuspoints[i] = Roi::focus(grayscaledImage, width, stars[i]); } return focuspoints; }
true
be1f0527d1d0fd5818a97f5522935ae6ec335340
C++
ssilverman/libCBOR
/src_tests/tests/floating_point.inc
UTF-8
9,368
2.65625
3
[ "BSD-3-Clause" ]
permissive
// floating_point.inc is part of libCBOR. // (c) 2017 Shawn Silverman // *************************************************************************** // Floating-point tests // *************************************************************************** test(half_zero) { uint8_t b[] = { (7 << 5) + 25, 0x00, 0x00 }; cbor::BytesStream bs{b, sizeof(b)}; cbor::Reader r{bs}; assertTrue(r.isWellFormed()); assertEqual(r.getReadSize(), size_t{3}); bs.reset(); assertEqual(static_cast<int>(r.readDataType()), static_cast<int>(cbor::DataType::kFloat)); assertEqual(r.getFloat(), 0.0f); assertFalse(std::signbit(r.getFloat())); assertEqual(r.getReadSize(), size_t{6}); } test(half_negative_zero) { uint8_t b[] = { (7 << 5) + 25, 0x80, 0x00 }; cbor::BytesStream bs{b, sizeof(b)}; cbor::Reader r{bs}; assertTrue(r.isWellFormed()); assertEqual(r.getReadSize(), size_t{3}); bs.reset(); assertEqual(static_cast<int>(r.readDataType()), static_cast<int>(cbor::DataType::kFloat)); assertEqual(r.getFloat(), 0.0f); assertTrue(std::signbit(r.getFloat())); assertEqual(r.getReadSize(), size_t{6}); } test(half_one) { uint8_t b[] = { (7 << 5) + 25, 0x3c, 0x00 }; cbor::BytesStream bs{b, sizeof(b)}; cbor::Reader r{bs}; assertTrue(r.isWellFormed()); assertEqual(r.getReadSize(), size_t{3}); bs.reset(); assertEqual(static_cast<int>(r.readDataType()), static_cast<int>(cbor::DataType::kFloat)); assertEqual(r.getFloat(), 1.0f); assertEqual(r.getReadSize(), size_t{6}); } test(half_1p5) { uint8_t b[] = { (7 << 5) + 25, 0x3e, 0x00 }; cbor::BytesStream bs{b, sizeof(b)}; cbor::Reader r{bs}; assertTrue(r.isWellFormed()); assertEqual(r.getReadSize(), size_t{3}); bs.reset(); assertEqual(static_cast<int>(r.readDataType()), static_cast<int>(cbor::DataType::kFloat)); assertEqual(r.getFloat(), 1.5f); assertEqual(r.getReadSize(), size_t{6}); } test(half_65504) { uint8_t b[] = { (7 << 5) + 25, 0x7b, 0xff }; cbor::BytesStream bs{b, sizeof(b)}; cbor::Reader r{bs}; assertTrue(r.isWellFormed()); assertEqual(r.getReadSize(), size_t{3}); bs.reset(); assertEqual(static_cast<int>(r.readDataType()), static_cast<int>(cbor::DataType::kFloat)); assertEqual(r.getFloat(), 65504.0f); assertEqual(r.getReadSize(), size_t{6}); } test(half_small) { uint8_t b[] = { (7 << 5) + 25, 0x00, 0x01 }; cbor::BytesStream bs{b, sizeof(b)}; cbor::Reader r{bs}; assertTrue(r.isWellFormed()); assertEqual(r.getReadSize(), size_t{3}); bs.reset(); assertEqual(static_cast<int>(r.readDataType()), static_cast<int>(cbor::DataType::kFloat)); assertEqual(r.getFloat(), 5.960464477539063e-8f); assertEqual(r.getReadSize(), size_t{6}); } test(half_medium_small) { uint8_t b[] = { (7 << 5) + 25, 0x04, 0x00 }; cbor::BytesStream bs{b, sizeof(b)}; cbor::Reader r{bs}; assertTrue(r.isWellFormed()); assertEqual(r.getReadSize(), size_t{3}); bs.reset(); assertEqual(static_cast<int>(r.readDataType()), static_cast<int>(cbor::DataType::kFloat)); assertEqual(r.getFloat(), 0.00006103515625f); assertEqual(r.getReadSize(), size_t{6}); } test(half_negative_4) { uint8_t b[] = { (7 << 5) + 25, 0xc4, 0x00 }; cbor::BytesStream bs{b, sizeof(b)}; cbor::Reader r{bs}; assertTrue(r.isWellFormed()); assertEqual(r.getReadSize(), size_t{3}); bs.reset(); assertEqual(static_cast<int>(r.readDataType()), static_cast<int>(cbor::DataType::kFloat)); assertEqual(r.getFloat(), -4.0f); assertEqual(r.getReadSize(), size_t{6}); } test(half_infinity) { uint8_t b[] = { (7 << 5) + 25, 0x7c, 0x00 }; cbor::BytesStream bs{b, sizeof(b)}; cbor::Reader r{bs}; assertTrue(r.isWellFormed()); assertEqual(r.getReadSize(), size_t{3}); bs.reset(); assertEqual(static_cast<int>(r.readDataType()), static_cast<int>(cbor::DataType::kFloat)); assertEqual(r.getFloat(), INFINITY); assertEqual(r.getReadSize(), size_t{6}); } test(half_negative_infinity) { uint8_t b[] = { (7 << 5) + 25, 0xfc, 0x00 }; cbor::BytesStream bs{b, sizeof(b)}; cbor::Reader r{bs}; assertTrue(r.isWellFormed()); assertEqual(r.getReadSize(), size_t{3}); bs.reset(); assertEqual(static_cast<int>(r.readDataType()), static_cast<int>(cbor::DataType::kFloat)); assertEqual(r.getFloat(), -INFINITY); assertEqual(r.getReadSize(), size_t{6}); } test(half_nan) { uint8_t b[] = { (7 << 5) + 25, 0x7e, 0x00 }; cbor::BytesStream bs{b, sizeof(b)}; cbor::Reader r{bs}; assertTrue(r.isWellFormed()); assertEqual(r.getReadSize(), size_t{3}); bs.reset(); assertEqual(static_cast<int>(r.readDataType()), static_cast<int>(cbor::DataType::kFloat)); assertTrue(std::isnan(r.getFloat())); assertEqual(r.getReadSize(), size_t{6}); } test(float_100000) { uint8_t b[] = { (7 << 5) + 26, 0x47, 0xc3, 0x50, 0x00 }; cbor::BytesStream bs{b, sizeof(b)}; cbor::Reader r{bs}; assertTrue(r.isWellFormed()); assertEqual(r.getReadSize(), size_t{5}); bs.reset(); assertEqual(static_cast<int>(r.readDataType()), static_cast<int>(cbor::DataType::kFloat)); assertEqual(r.getFloat(), 100000.0f); assertEqual(r.getReadSize(), size_t{10}); } test(float_large) { uint8_t b[] = { (7 << 5) + 26, 0x7f, 0x7f, 0xff, 0xff }; cbor::BytesStream bs{b, sizeof(b)}; cbor::Reader r{bs}; assertTrue(r.isWellFormed()); assertEqual(r.getReadSize(), size_t{5}); bs.reset(); assertEqual(static_cast<int>(r.readDataType()), static_cast<int>(cbor::DataType::kFloat)); assertEqual(r.getFloat(), 3.4028234663852886e+38f); assertEqual(r.getReadSize(), size_t{10}); } test(float_infinity) { uint8_t b[] = { (7 << 5) + 26, 0x7f, 0x80, 0x00, 0x00 }; cbor::BytesStream bs{b, sizeof(b)}; cbor::Reader r{bs}; assertTrue(r.isWellFormed()); assertEqual(r.getReadSize(), size_t{5}); bs.reset(); assertEqual(static_cast<int>(r.readDataType()), static_cast<int>(cbor::DataType::kFloat)); assertEqual(r.getFloat(), INFINITY); assertEqual(r.getReadSize(), size_t{10}); } test(float_negative_infinity) { uint8_t b[] = { (7 << 5) + 26, 0xff, 0x80, 0x00, 0x00 }; cbor::BytesStream bs{b, sizeof(b)}; cbor::Reader r{bs}; assertTrue(r.isWellFormed()); assertEqual(r.getReadSize(), size_t{5}); bs.reset(); assertEqual(static_cast<int>(r.readDataType()), static_cast<int>(cbor::DataType::kFloat)); assertEqual(r.getFloat(), -INFINITY); assertEqual(r.getReadSize(), size_t{10}); } test(float_nan) { uint8_t b[] = { (7 << 5) + 26, 0x7f, 0xc0, 0x00, 0x00 }; cbor::BytesStream bs{b, sizeof(b)}; cbor::Reader r{bs}; assertTrue(r.isWellFormed()); assertEqual(r.getReadSize(), size_t{5}); bs.reset(); assertEqual(static_cast<int>(r.readDataType()), static_cast<int>(cbor::DataType::kFloat)); assertTrue(std::isnan(r.getFloat())); assertEqual(r.getReadSize(), size_t{10}); } test(double_1p1) { uint8_t b[] = { (7 << 5) + 27, 0x3f, 0xf1, 0x99, 0x99, 0x99, 0x99, 0x99, 0x9a }; cbor::BytesStream bs{b, sizeof(b)}; cbor::Reader r{bs}; assertTrue(r.isWellFormed()); assertEqual(r.getReadSize(), size_t{9}); bs.reset(); assertEqual(static_cast<int>(r.readDataType()), static_cast<int>(cbor::DataType::kDouble)); assertEqual(r.getDouble(), 1.1); assertEqual(r.getReadSize(), size_t{18}); } test(double_negative_4p1) { uint8_t b[] = { (7 << 5) + 27, 0xc0, 0x10, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66 }; cbor::BytesStream bs{b, sizeof(b)}; cbor::Reader r{bs}; assertTrue(r.isWellFormed()); assertEqual(r.getReadSize(), size_t{9}); bs.reset(); assertEqual(static_cast<int>(r.readDataType()), static_cast<int>(cbor::DataType::kDouble)); assertEqual(r.getDouble(), -4.1); assertEqual(r.getReadSize(), size_t{18}); } test(double_large) { uint8_t b[] = { (7 << 5) + 27, 0x7e, 0x37, 0xe4, 0x3c, 0x88, 0x00, 0x75, 0x9c }; cbor::BytesStream bs{b, sizeof(b)}; cbor::Reader r{bs}; assertTrue(r.isWellFormed()); assertEqual(r.getReadSize(), size_t{9}); bs.reset(); assertEqual(static_cast<int>(r.readDataType()), static_cast<int>(cbor::DataType::kDouble)); assertEqual(r.getDouble(), 1.0e+300); assertEqual(r.getReadSize(), size_t{18}); } test(double_infinity) { uint8_t b[] = { (7 << 5) + 27, 0x7f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; cbor::BytesStream bs{b, sizeof(b)}; cbor::Reader r{bs}; assertTrue(r.isWellFormed()); assertEqual(r.getReadSize(), size_t{9}); bs.reset(); assertEqual(static_cast<int>(r.readDataType()), static_cast<int>(cbor::DataType::kDouble)); assertEqual(r.getDouble(), INFINITY); assertEqual(r.getReadSize(), size_t{18}); } test(double_negative_infinity) { uint8_t b[] = { (7 << 5) + 27, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; cbor::BytesStream bs{b, sizeof(b)}; cbor::Reader r{bs}; assertTrue(r.isWellFormed()); assertEqual(r.getReadSize(), size_t{9}); bs.reset(); assertEqual(static_cast<int>(r.readDataType()), static_cast<int>(cbor::DataType::kDouble)); assertEqual(r.getDouble(), -INFINITY); assertEqual(r.getReadSize(), size_t{18}); } test(double_nan) { uint8_t b[] = { (7 << 5) + 27, 0x7f, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; cbor::BytesStream bs{b, sizeof(b)}; cbor::Reader r{bs}; assertTrue(r.isWellFormed()); assertEqual(r.getReadSize(), size_t{9}); bs.reset(); assertEqual(static_cast<int>(r.readDataType()), static_cast<int>(cbor::DataType::kDouble)); assertTrue(std::isnan(r.getDouble())); assertEqual(r.getReadSize(), size_t{18}); }
true
762e793c8f3d2529658810c84fd63b4d29e272be
C++
JFengWu/Cpp-homework
/cpp-homework3/Q118/Source.cpp
UTF-8
2,215
3.65625
4
[]
no_license
#include <iostream> #include <string> #include <vector> using namespace std; class Hero { public: int id; string name; int hp; int atk; int atked; Hero() : id(0), name(NULL), hp(0), atk(0), atked(0) {} Hero(int _id, string _name, int _hp, int _atk, int _atked) : id(_id), name(_name), hp(_hp), atk(_atk), atked(_atked) {} virtual void power() {} bool isAlive() { return hp > 0; } void attacked(int del) { hp -= del; atked = del; } friend ostream &operator << (ostream &os, Hero &hero) { return os << hero.name << " " << hero.atk << " " << hero.hp << endl; } }; class Warrior : public Hero { public: Warrior() : Hero(1, "Warrior", 12, 2, 0) {} void power() { if (isAlive()) { hp++; } } }; class Magician : public Hero { public: bool usedPower; Magician() : Hero(2, "Magician", 2, 6, 0) { usedPower = false; } void power() { if (!usedPower) { hp += atked; usedPower = true; } } }; class Leader : public Hero { public: Leader() : Hero(3, "Leader", 6, 6, 0) {} void power() { if (isAlive()) { atk++; } } }; class HeroPool { public: Hero* CreateHero(const int &id) { Hero* ret; switch(id) { case 1: ret = new Warrior(); break; case 2: ret = new Magician(); break; case 3: ret = new Leader(); break; default: ret = NULL; break; } return ret; } }; int main(int argc, char* argv[]) { int n; cin >> n; HeroPool heroPool; vector<Hero*> h1; for (int i = 0; i < n; i++) { int id; cin >> id; h1.emplace_back(heroPool.CreateHero(id)); } vector<Hero*> h2; for (int i = 0; i < n; i++) { int id; cin >> id; h2.emplace_back(heroPool.CreateHero(id)); } int i = 0; int j = 0; while (i < n && j < n) { h1[i]->attacked(h2[j]->atk); h2[j]->attacked(h1[i]->atk); if (h1[i]->id == 2) { h1[i]->power(); } if (h2[j]->id == 2) { h2[j]->power(); } if (h1[i]->isAlive()) { h1[i]->power(); } else { i++; } if (h2[j]->isAlive()) { h2[j]->power(); } else { j++; } } if (i == n && j == n) { cout << "All Dead" << endl; return 0; } else { for (int k = i; k < n; k++) { cout << *h1[k]; } for (int k = j; k < n; k++) { cout << *h2[k]; } } return 0; }
true
7f1967ed41b2b07f80c73ed3a4a834770a7f4afe
C++
Nismirno/SDLSnake
/SDLSnake/Game.cpp
UTF-8
1,950
2.90625
3
[ "MIT" ]
permissive
#include "Game.h" #include <Windows.h> Game::Game() {} Game::~Game() { m_gameWindow.free(); } bool Game::init() { // Initialize SDL if (SDL_Init(SDL_INIT_VIDEO) < 0) { printf("SDL could not initialize! SDL Error: %s\n", SDL_GetError()); return false; } // Initialize PNG loading int imgFlags = IMG_INIT_PNG; if (!(IMG_Init(imgFlags)) & imgFlags) { printf("SDL_image could not initialize! SDL Error: %s\n", IMG_GetError()); return false; } // Set texture filtering if (!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "1")) { printf("Warning: Linear texture filtering not enabled!\n"); return false; } if (!m_gameWindow.init()) { printf("Window could not be created! SDL Error: %s\n", SDL_GetError()); return false; } m_gameWindow.createRenderer(); if (m_gameWindow.renderer() == NULL) { printf("Renderer could not be created! SDL Error: %s\n", SDL_GetError()); return false; } return true; } bool Game::execute() { SDL_Renderer *renderer = m_gameWindow.renderer(); bool quit = false; bool gameOver = false; SDL_Event e; Texture gameOverTexture; gameOverTexture.loadFromFile("media/gameOver.png", renderer); Grid grid; grid.create(renderer); while (!quit) { while (SDL_PollEvent(&e)) { uint32_t eventType = e.type; SDL_Keycode keyCode = e.key.keysym.sym; // Exit the game if (eventType == SDL_QUIT) { quit = true; } m_gameWindow.handleEvent(e); grid.handleEvent(e); } clearScreen(); if (!gameOver) { gameOver = grid.updateGrid(); grid.render(renderer); } else { gameOverTexture.render(renderer, 0, 0); } SDL_RenderPresent(renderer); } return true; } bool Game::finalize() { m_gameWindow.free(); return true; } void Game::clearScreen() { SDL_Renderer *renderer = m_gameWindow.renderer(); SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF); SDL_RenderClear(renderer); } void Game::resize(int width, int height) { return; }
true
5ec6032c7f887143f004355f0a17742033d2ee92
C++
v-kyle/university-labs-and-courseworks-c-cpp
/second-course/lab2_2/Laba2/Laba2.cpp
UTF-8
693
2.671875
3
[]
no_license
#include <iostream> #include "Shannon.h" void showInfoAboutString(Shannon& obj, string str) { obj.Convertion_input_string(str); obj.show_on_display(); } int main() { setlocale(0, "Rus"); Shannon example; showInfoAboutString(example, "Классика – то, что каждый считает нужным прочесть и никто не читает."); showInfoAboutString(example, "Плох тот классик, которому ничего не приписывают."); showInfoAboutString(example, "Классика — это то, что каждый хотел бы прочесть, по возможности — не читая."); system("pause"); }
true
67702fa483a9049dd62c83456ab4df18e08481cc
C++
ShamimiWidat/Embedded-System
/Week_10/Example-12,13/Example-12.ino
UTF-8
1,018
2.78125
3
[]
no_license
void setup() { Serial.begin(9600); } void loop() { char* ddrb = (char*)0x24; //Points to DDRB register char* portb = (char*)0x25;//Points to PORB register *ddrb = 0b00001111;//Set the 4 pins as output char DriveSteps[] = {1,2,4,8};//Activation pattern of wave drive char position = 0; unsigned long now = millis(); unsigned long last;//Stores last time the motor moved if(now - last >= 5)//If the motor has not moved for 5 ms { *portb = DriveSteps[position]; position++; if(position >= 4) { position = 0; } last = now; Serial.println((unsigned char)*portb,BIN);//Serial printing is just for trouble shooting } /*if(now-last>=2)//If the motor has not moved for 2 ms { *portb = DriveSteps[position]; position--; if(position < 0) { position = 3; } last = now; Serial.println((unsigned char)*portb,BIN);//Serial printing is just for trouble shooting }*/ }
true
4470d89ee1afd0cf73b0ea398d900cf78826ee8c
C++
tuowenhao/algorithm022
/Week_07/surrounded.cpp
UTF-8
2,461
3.03125
3
[]
no_license
class UnionFind { public: UnionFind(int n) { parent = new int[n]; count = n; for (int i = 0; i < n; ++i) { parent[i] = i; } } int findRoot(int p) { while (p != parent[p]) { parent[p] = parent[parent[p]]; p = parent[p]; } return p; } void unite(int x, int y) { int rootX = findRoot(x); int rootY = findRoot(y); if (rootX != rootY) { parent[rootX] = rootY; count--; } } int getCount() { return count; } bool isConnected(int x, int y) { int rootX = findRoot(x); int rootY = findRoot(y); return rootX == rootY; } private: int* parent; int count; }; class Solution { public: int rows; int cols; void solve(vector<vector<char>>& board) { if (board.size() == 0) return; rows = board.size(), cols = board[0].size(); int virtualNode = rows * cols; UnionFind* un = new UnionFind(rows * cols + 1); for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { if (board[i][j] == 'O') { if (i == 0 || i == rows - 1 || j == 0 || j == cols - 1) { un->unite(mapNode(i, j), virtualNode); } else { if (i > 0 && board[i - 1][j] == 'O') { un->unite(mapNode(i, j), mapNode(i - 1, j)); } if (i < rows - 1 && board[i + 1][j] == 'O') { un->unite(mapNode(i, j), mapNode(i + 1,j)); } if (j > 0 && board[i][j - 1] == 'O') { un->unite(mapNode(i, j), mapNode(i, j - 1)); } if (j < cols - 1 && board[i][j + 1] == 'O') { un->unite(mapNode(i, j), mapNode(i, j + 1)); } } } } } for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { if (un->isConnected(mapNode(i, j), virtualNode)) { board[i][j] = 'O'; } else { board[i][j] = 'X'; } } } } int mapNode(int i, int j) { return i * cols + j; } };
true
f4aa4d2681cfcc22e2b30ef1e24048bc10e6fc1c
C++
albertlis/Photovoltaic-platform-visualization---WDS
/Projekt/Software/Qt + OpenGL/platform/my/globals.cpp
UTF-8
523
2.640625
3
[]
no_license
#include "globals.h" /** * @brief Value of the vertical rotation angle in degrees * */ volatile int32_t V = 0; /** * @brief Value of the horizontal rotation angle in degrees * */ volatile int32_t H = 0; /** * @brief Value of the light intensivity in lx * */ volatile int32_t L = 0; /** * @brief Value of the current flow in mA * */ volatile int32_t I = 0; /** * @brief Value of the voltage in mV * */ volatile int32_t U = 0; /** * @brief Value of the recived power in mW * */ volatile int32_t P = 0;
true
2383257abb6ae708c51f00101b9150364d504949
C++
johansaji/ThunderNanoServices
/examples/TestUtility/CommandCore/TestCommandBase.h
UTF-8
3,159
2.65625
3
[ "Apache-2.0" ]
permissive
#include <interfaces/json/JsonData_TestUtility.h> #include "interfaces/ITestUtility.h" #include "../Module.h" namespace WPEFramework { class TestCommandBase : public Exchange::ITestUtility::ICommand { public: TestCommandBase() = delete; TestCommandBase(const TestCommandBase&) = delete; TestCommandBase& operator=(const TestCommandBase&) = delete; public: class SignatureBuilder { public: SignatureBuilder() = delete; SignatureBuilder(const SignatureBuilder&) = delete; SignatureBuilder& operator=(const SignatureBuilder&) = delete; public: explicit SignatureBuilder(string const& name, JsonData::TestUtility::TypeType type, string const& comment) : _jsonSignature() { JsonData::TestUtility::InputInfo inputParam; inputParam.Name = name; inputParam.Type = type; inputParam.Comment = comment; _jsonSignature.Output = inputParam; } explicit SignatureBuilder(const JsonData::TestUtility::InputInfo& inputParam) : _jsonSignature() { _jsonSignature.Output = inputParam; } SignatureBuilder& InputParameter(const string& name, JsonData::TestUtility::TypeType type, const string& comment) { JsonData::TestUtility::InputInfo inputParam; inputParam.Name = name; inputParam.Type = type; inputParam.Comment = comment; _jsonSignature.Input.Add(inputParam); return (*this); } virtual ~SignatureBuilder() = default; private: friend class TestCommandBase; string ToString() const { string outString; _jsonSignature.ToString(outString); return outString; } JsonData::TestUtility::ParametersData _jsonSignature; }; class DescriptionBuilder { public: DescriptionBuilder() = delete; DescriptionBuilder(const DescriptionBuilder&) = delete; DescriptionBuilder& operator=(const DescriptionBuilder&) = delete; public: explicit DescriptionBuilder(const string& description) : _jsonDescription() { _jsonDescription.Description = description; } virtual ~DescriptionBuilder() = default; private: friend class TestCommandBase; string ToString() const { string outString; _jsonDescription.ToString(outString); return outString; } JsonData::TestUtility::DescriptionData _jsonDescription; }; public: explicit TestCommandBase(const DescriptionBuilder& description, const SignatureBuilder& signature) : Exchange::ITestUtility::ICommand() , _description(description.ToString()) , _signature(signature.ToString()) { } virtual ~TestCommandBase() = default; public: // ICommand methods string Description() const final { return _description; } string Signature() const final { return _signature; } private: string _description; string _signature; }; } // namespace WPEFramework
true
023085e466cc3b8b3d0f9e0a62693c48943e7f65
C++
proscrumdev/battleship-embedded
/lib/Battleship.GameController/Position.cpp
UTF-8
465
3.3125
3
[]
no_license
#include <Position.h> #include <sstream> namespace std { template<typename T> std::string to_string(const T &n) { std::ostringstream s; s << n; return s.str(); } } enum Letters Column; int Row; Position::Position() { } Position::Position(Letters column, int row) { Column = column; Row = row; } string Position::toString() { char letter = Column + 'A'; return letter + std::to_string(Row); }
true
dd27c52653bf775ce6548b36f3843e2a9bd51990
C++
uselessgoddess/Collections
/cpp/Platform.Collections.Tests/ListTests.cpp
UTF-8
789
2.765625
3
[ "MIT" ]
permissive
namespace Platform::Collections::Tests { TEST_CLASS(ListTests) { public: TEST_METHOD(GetElementTest) { auto nullList = (IList<std::int32_t>){}; Assert::AreEqual(0, nullList.GetElementOrDefault(1)); Assert::IsFalse(nullList.TryGetElement(1, out std::int32_t element)); Assert::AreEqual(0, element); auto list = List<std::int32_t>() { 1, 2, 3 }; Assert::AreEqual(3, list.GetElementOrDefault(2)); Assert::IsTrue(list.TryGetElement(2, out element)); Assert::AreEqual(3, element); Assert::AreEqual(0, list.GetElementOrDefault(10)); Assert::IsFalse(list.TryGetElement(10, out element)); Assert::AreEqual(0, element); } }; }
true
08124336db95f4651c965031d321dc50c240e79f
C++
Sysreqx/Cpp
/itstep/HW/06.06.2018 VehicleStore/Plane.cpp
UTF-8
837
3.140625
3
[]
no_license
#include "Plane.h" Plane::Plane(std::string color, std::string model, int max_speed, int number_of_seats, int price, int altitude, std::string arrivalGate) : AirVehicle(color, model, max_speed, number_of_seats, price, altitude) { this->setArrivalGate(arrivalGate); } void Plane::setArrivalGate(std::string arrivalGate) { this->arrivalGate = arrivalGate; } std::string Plane::getArrivalGate() const { return this->arrivalGate; } void Plane::info() const { AirVehicle::info(); std::cout << "Arrival gate: " << arrivalGate << std::endl; } std::string Plane::codeInfo() const { std::string str = "Plane;"; str += AirVehicle::codeInfo(); str += arrivalGate + ';'; return str; } void Plane::start() { std::cout << "Plane started to move" << std::endl; } void Plane::stop() { std::cout << "Plane stopped" << std::endl; }
true
76a1a1f923e93b69a656237b89e7156a213f1ba8
C++
imharsh94/ALGO-DS
/linkedlist2.cpp
UTF-8
1,142
4
4
[]
no_license
//! remove duplicate elements from a linked list ITERATION //! INPUT 1->1->2->3 //! OUTPUT 1->2->3 #include<bits/stdc++.h> using namespace std; struct Node { int data; struct Node* next; }; Node* newNode(int data) { Node* temp = new Node; temp->data = data; temp->next = NULL; } void printList(struct Node* start) { while(start != NULL) { printf("%d ",start->data); start = start->next; } } void removeDuplicates(struct Node** head) { struct Node* current = *head,*next_element; if(current == NULL) return ; while(current->next != NULL) { if(current->data == current->next->data) { next_element = current->next->next; free(current->next); current->next = next_element; } else current = current->next; } } int main() { Node* start = newNode(3); start->next = newNode(7); start->next->next = newNode(7); start->next->next->next = newNode(9); cout<<start->data<<" "<<start->next->data<<'\n'; removeDuplicates(&start); printList(start); return 0; }
true
e0e58bfc175d33689a79820fbd2236959f5d5c8d
C++
LuisBarcenas14/Programacion-Competitiva
/Otros/gauss.cpp
UTF-8
1,551
3.03125
3
[]
no_license
#include<bits/stdc++.h> using namespace std; #define endl '\n' #define MAX_N 100 // adjust this value as needed struct AugmentedMatrix { double mat[MAX_N][MAX_N + 1]; }; struct ColumnVector { double vec[MAX_N]; }; ColumnVector GaussianElimination(int N, AugmentedMatrix Aug) { // O(N^3) // input: N, Augmented Matrix Aug, output: Column vector X, the answer int i, j, k, l; double t; ColumnVector X; for (j = 0; j < N - 1; j++) { // the forward elimination phase l = j; for (i = j + 1; i < N; i++) // which row has largest column value if (fabs(Aug.mat[i][j]) > fabs(Aug.mat[l][j])) l = i; // remember this row l // swap this pivot row, reason: to minimize floating point error for (k = j; k <= N; k++) // t is a temporary double variable t = Aug.mat[j][k], Aug.mat[j][k] = Aug.mat[l][k], Aug.mat[l][k] = t; for (i = j + 1; i < N; i++) // the actual forward elimination phase for (k = N; k >= j; k--) Aug.mat[i][k] -= Aug.mat[j][k] * Aug.mat[i][j] / Aug.mat[j][j]; } for (j = N - 1; j >= 0; j--) { // the back substitution phase for (t = 0.0, k = j + 1; k < N; k++) t += Aug.mat[j][k] * X.vec[k]; X.vec[j] = (Aug.mat[j][N] - t) / Aug.mat[j][j]; // the answer is here } return X; } int main(){ freopen("in-gauss","r",stdin); int n; double db; cin>>n; AugmentedMatrix Aug1; for(int i=0;i<n;i++){ for(int j=0;j<n+1;j++){ cin>>Aug1.mat[i][j]; } } ColumnVector res = GaussianElimination(n, Aug1); for(int j=0;j<n;j++){ cout<<res.vec[j]<<" "; } cout<<endl; return 0; }
true
5f8579eb6a1eb4e2662763049c0ee51f5b8ad8b6
C++
MakSim345/cpp
/exceptions_edu_vs/my_exceptions.cpp
UTF-8
1,170
2.875
3
[]
no_license
//============================================================ // // Description: // <purpose of this file> //============================================================ #include "my_exceptions.h" #include "div_error.h" int throw_error::Run() { std::cout << "Hello World!\n"; throw std::runtime_error("Something really bad happens!\n"); return 0; } throw_error::throw_error() { int i = 0; // _ASSERT(i > 0); std::cout << "a=" << a << "\n"; } my_exceptions::my_exceptions(): num1(0), num2(0) { std::cout << "my_exceptions - init\n"; } void my_exceptions::run() { cout << "BBeguTe 4epe3 npo6eL gBa 4ucLa gLq geLeHuq:\n"; cin >> num1 >> num2; quotient(); } float my_exceptions::quotient(/*int num1, int num2*/) { if (num2==0) { // throw DivideByZeroError (); throw std::runtime_error("ERROR: Divizion to zer0!\n"); } return (float) num1 / num2; } float my_exceptions::quotient2(/*int num1, int num2*/) { if (num2==0) { throw DivideByZeroError(); } return (float) num1 / num2; } void my_exceptions::init_alphabet(vector<string>& alphabet) { }
true
cbdf51b17a8b1427eb99fb099d0d4f5077ade9b5
C++
kpadmost/UNIX-Linda
/src/server/model/implementation/CommunicationManagerFIFO.cpp
UTF-8
998
2.828125
3
[]
no_license
// // Created by konstantin on 10.06.17. // #include "CommunicationManagerFIFO.h" TupleMessage CommunicationManagerFIFO::receiveMessage() { TupleMessage m; fifo->readFromFIFO(m); if(m.clientPid != m.INVALID_PID) std::cout << "\nmessage received " << m << std::endl; return m; } void CommunicationManagerFIFO::sendMessage(const int clientId, const Tuple &tuple, const RequestType type) { sendMessage(TupleMessage(clientId, tuple, type)); } void CommunicationManagerFIFO::sendMessage(const TupleMessage &message) { FifoManager clientFifo(message.clientPid,false , O_WRONLY); clientFifo.openFifo(); std::cout << "message sent: " << message << std::endl; clientFifo.writeToFifo(message); } CommunicationManagerFIFO::CommunicationManagerFIFO() : fifo(std::unique_ptr<FifoManager>(new FifoManager(FifoManager::SERVER_FIFO, true, O_RDONLY))){ fifo->openFifo(); } CommunicationManagerFIFO::~CommunicationManagerFIFO() { fifo->closeFifo(); }
true
61c0ecd4a664665ce7d969366fc0324e91ea8c5a
C++
dropofwill/multi-tone-arduino
/multi_tone.ino
UTF-8
3,664
2.8125
3
[]
no_license
/* Multiple tone player Plays multiple tones on multiple pins to play basic power chords circuit: * 3 8-ohm speaker on digital pins set by the constants LEFT_S, MID_S, RIGHT_S * Capacative touch setup on the default I2C base on code from Tom Igoe based on a snippet from Greg Borenstein This example code is in the public domain. http://arduino.cc/en/Tutorial/Tone4 */ #include <Tone.h> #include <Wire.h> #include "Adafruit_MPR121.h" #include "pitches.h" // You can have up to 4 on one i2c bus but one is enough for testing! Adafruit_MPR121 cap = Adafruit_MPR121(); // Keeps track of the last pins touched // so we know when buttons are 'released' uint16_t lasttouched = 0; uint16_t currtouched = 0; // Pins for the speakers const int LEFT_S = 11; const int MID_S = 5; const int RIGHT_S = 3; // Pins for the touch const int LEFT_T = 6; const int MID_T = 8; const int RIGHT_T = 10; boolean is_left = false; boolean is_mid = false; boolean is_right = false; Tone freq1; Tone freq2; void setup() { Serial.begin(9600); freq1.begin(LEFT_S); freq2.begin(RIGHT_S); // Default address is 0x5A, if tied to 3.3V its 0x5B // If tied to SDA its 0x5C and if SCL then 0x5D if (!cap.begin(0x5A)) { while (1); } } void loop() { // Get the currently touched pads currtouched = cap.touched(); for (uint8_t i=0; i<12; i++) { // it if *is* touched and *wasnt* touched before, alert! if ((currtouched & _BV(i)) && !(lasttouched & _BV(i)) ) { if (i == LEFT_T) { is_left = true; } if (i == MID_T) { is_mid = true; } if (i == RIGHT_T) { is_right = true; } } // if it *was* touched and now *isnt*, alert! if (!(currtouched & _BV(i)) && (lasttouched & _BV(i)) ) { if (i == LEFT_T) { is_left = false; } if (i == MID_T) { is_mid = false; } if (i == RIGHT_T) { is_right = false; } } } // // G5 - Bb5 - F5 // // G5: G2 and D2 // // Bb5: Bb2/As2 and F3 // // F5: F2 and C2 // if (!is_left && !is_mid && !is_right) { // freq1.stop(); // freq2.stop(); // } // // G // else if (is_left && !is_mid && !is_right) { // freq2.stop(); // freq1.play(NOTE_G3); // } // // Bb // else if (is_mid && !is_left && !is_right) { // freq1.play(NOTE_AS3); // freq2.stop(); // } // // F // else if (is_right && !is_left && !is_mid) { // freq1.play(NOTE_F3); // freq2.stop(); // } // // G5 // else if (is_left && is_mid && !is_right) { // freq1.play(NOTE_G3); // freq2.play(NOTE_D3); // } // // Bb5 // else if (is_mid && is_right && !is_left) { // freq1.play(NOTE_AS3); // freq2.play(NOTE_F4); // } // // F5 // else if (is_right && is_left && !is_mid) { // freq1.play(NOTE_F3); // freq2.play(NOTE_C3); // } // A5 - D5 - E5 // A5: G2 and D2 // D5: Bb2/As2 and F3 // E5: F2 and C2 // off if (!is_left && !is_mid && !is_right) { freq1.stop(); freq2.stop(); } // A else if (is_left && !is_mid && !is_right) { freq2.stop(); freq1.play(NOTE_A3); } // D else if (is_mid && !is_left && !is_right) { freq1.play(NOTE_D3); freq2.stop(); } // E else if (is_right && !is_left && !is_mid) { freq1.play(NOTE_E3); freq2.stop(); } // A5 else if (is_left && is_mid && !is_right) { freq1.play(NOTE_A3); freq2.play(NOTE_E4); } // D5 else if (is_mid && is_right && !is_left) { freq1.play(NOTE_D3); freq2.play(NOTE_A4); } // E5 else if (is_right && is_left && !is_mid) { freq1.play(NOTE_E3); freq2.play(NOTE_B3); } // reset our state lasttouched = currtouched; }
true
e41d6b691d8009c6cd29ef08e4bc02bc6e0ce9f2
C++
LuisBarcenas14/Programacion-Competitiva
/COJ - AC/LuisBarcenas14-p2661-Accepted-s966187.cpp
UTF-8
512
2.671875
3
[]
no_license
#include <iostream> #include <string> using namespace std; #define endl '\n' #define ios ios_base::sync_with_stdio(0); cin.tie(0); string s; int i; int t, mod; int main() { ios; while(cin>>s){ t=0; for(i=0;s[i]!='\0';i++){ t+=s[i]-48; } mod = t%3; if(mod==1){ cout<<'7'<<endl; }else if (mod==2){ cout<<'4'<<endl; }else{ cout<<'1'<<endl; } } return 0; }
true
3fc0f0065044c06609bb6b746b9a8e8362bed949
C++
elmspace/Charged_AB_C_System_Ion_Solubility
/HEADERFILES/Tools.hh
UTF-8
472
3.078125
3
[]
no_license
double FindIntersect (double x1f, double y1f, double x2f, double y2f, double x1g, double y1g, double x2g, double y2g){ // This function will find the point of intersection between two lines, given from the 4 points above // The two functions are called f(x) and g(x) double af, ag, bf, bg; double X_point; af=(y2f - y1f)/(x2f - x1f); bf=y1f-af*x1f; ag=(y2g - y1g)/(x2g - x1g); bg=y1g-ag*x1g; X_point=(bg - bf)/(af - ag); return X_point; };
true
45e77f61dec4fdc2345c10c5355ba2211d565bc5
C++
ufjf-barbara/manipulacao-de-arquivos-JoaoPedroSilvaFreitas
/files.cpp
UTF-8
7,337
3.328125
3
[]
no_license
/* * Codigo C++ com exemplos para criaçao e manipulaçao de arquivos em C++. * * Criado por: Prof. Jose J. Camata * */ #include <iostream> #include <fstream> #include <string> #include <cstdlib> #include <chrono> using namespace std; using namespace std::chrono; int tamanhoArquivo(fstream& arq) { //int pos = arq.tellg(); arq.seekg(0, arq.end); int tam = arq.tellg(); arq.seekg(0); return tam; } void escreveArquivoTexto() { ofstream arq("arqTexto.txt"); arq << "Dados:" << endl; arq << 4.2; arq << 2 << 3; cout << "Tamanho em bytes apos escrita: " << arq.tellp() << endl; //arq.close(); } void leArquivoTextoString() { ifstream arq("arqTexto.txt"); if(arq.is_open()) { cout << "Informacoes armazenadas no arquivo:\n\n***" << endl; string str; int count = 1; while(getline(arq, str)) { cout << count << " - EOF: " << ((arq.eof()) ? "true" : "false") << endl; cout << str << endl; count++; } cout << "***" << endl; } else cerr << "ERRO: O arquivo nao pode ser aberto!" << endl; } void leArquivoTextoGeral() { ifstream arq("arqTexto.txt"); if(arq.is_open()) { cout << "Informacoes armazenadas no arquivo:\n\n***" << endl; string str; float val; getline(arq, str); arq >> val; cout << str << '\n' << val << endl; // ERRO: irá gerar lixo de memória, pois val irá armazenar todos os dígitos na sequência //int intval; //arq >> intval; // cout << str << '\n' << val << '\n' << intval << endl; cout << "\n***" << endl; } else cerr << "ERRO: O arquivo nao pode ser aberto!" << endl; } void escreveArquivoBinario() { fstream arq("arq.bin", ios::out | ios::binary); if(arq.is_open()) { float val = 4.2; string str = "Dados"; int intval = 2; // ERRO: verifique como o arquivo fica corrompido! //arq.write(reinterpret_cast<const char*>(&str), str.length()); arq.write(reinterpret_cast<const char*>(str.c_str()), str.length()); arq.write(reinterpret_cast<const char*>(&val), sizeof(float)); arq.write(reinterpret_cast<const char*>(&intval), sizeof(int)); intval = 3; arq.write(reinterpret_cast<char*>(&intval), sizeof(int)); cout << "Tamanho em bytes apos escrita: " << arq.tellp() << endl; } else cerr << "ERRO: O arquivo nao pode ser aberto!" << endl; } void adicionaInfoArquivo(fstream& arq) { if(arq.is_open()) { string app = "app"; arq.write(reinterpret_cast<const char*>(app.c_str()), app.length()); //arq << app; cout << "Tamanho em bytes apos escrita: " << arq.tellp() << endl; } else cerr << "ERRO: O arquivo nao pode ser aberto!" << endl; } void leArquivoBinario() { fstream arq("arq.bin", ios::in | ios::binary); if(arq.is_open()) { float val; char str[10]; int intval; arq.read(str, 5); str[5] = '\0'; arq.read(reinterpret_cast<char*>(&val), sizeof(float)); arq.read(reinterpret_cast<char*>(&intval), sizeof(int)); cout << str << '\n' << val << " " << intval << " "; arq.read(reinterpret_cast<char*>(&intval), sizeof(int)); cout << intval << endl; // ERRO: tentar ler após o fim do arquivo irá retornar 0 bytes e str ficará inalterado // arq.read(str, 3); // str[3] = '\0'; // cout << str << endl; } else cerr << "ERRO: O arquivo nao pode ser aberto!" << endl; } void geraCSV() { ofstream arq("dados.csv"); for(int i = 1; i <= 1000000; i++) { arq << i << "," << i*2 << "," << rand()%i << endl; } arq.close(); } void carregaArquivoPorBlocos(int tamBloco) { char *dados = new char[tamBloco]; ifstream arq("dados.csv"); if(arq.is_open()) { high_resolution_clock::time_point inicio = high_resolution_clock::now(); while(!arq.eof()) { arq.read(dados, tamBloco); cout << arq.gcount() << " bytes lidos" << endl; } high_resolution_clock::time_point fim = high_resolution_clock::now(); cout << duration_cast<duration<double> >(fim - inicio).count() << " segundos" << endl; } arq.close(); delete [] dados; } void geraArquivoBinario() { ofstream arq("dados.dat", ios::binary); for(int i = 1; i <= 1000000; i++) { int x = i; arq.write(reinterpret_cast<const char*>(&x), sizeof(int)); x = i * 2; arq.write(reinterpret_cast<const char*>(&x), sizeof(int)); x = rand() % i; arq.write(reinterpret_cast<const char*>(&x), sizeof(int)); } arq.close(); } void carregaRegistro(int indice) { ifstream arq("dados.dat", ios::binary); if(arq.is_open()) { high_resolution_clock::time_point inicio = high_resolution_clock::now(); int x; arq.seekg((indice-1)*12); arq.read(reinterpret_cast<char*>(&x), sizeof(int)); cout << x << ", "; arq.read(reinterpret_cast<char*>(&x), sizeof(int)); cout << x << ", "; arq.read(reinterpret_cast<char*>(&x), sizeof(int)); cout << x << endl; high_resolution_clock::time_point fim = high_resolution_clock::now(); cout << duration_cast<duration<double> >(fim - inicio).count() << " segundos" << endl; } arq.close(); } int main() { // EXEMPLO 1: Criação de um arquivo texto // Não há distinção entre o inteiro e o float, são todos transformados em caracteres escreveArquivoTexto(); fstream arq("arqTexto.txt"); cout << "Tamanho do arquivo texto: " << tamanhoArquivo(arq) << endl; // arq.close(); // EXEMPLO 2: Leitura de um arquivo texto utilizando getline // A cada linha, imprimimos o índice da linha e o valor de EOF. //leArquivoTextoString(); // EXEMPLO 3: Tentativa de leitura de um arquivo texto utilizando os tipos de dados originais // leArquivoTextoGeral(); // EXEMPLO 4: Criação de um arquivo binário //escreveArquivoBinario(); // EXEMPLO 5: Adição de novas informações a um arquivo previamente criado // ERRO: apenas abrir o arquivo já apaga o seu conteúdo //fstream arq("arqTexto.txt", ios::out); //arq.seekp(2); //fstream arq("arqTexto.txt", ios::app); // fstream arq("arq.bin", ios::app); //adicionaInfoArquivo(arq); //cout << "Tamanho do arquivo texto: " << tamanhoArquivo(arq) << endl; //arq.close(); // EXEMPLO 6: Leitura de um arquivo binário //leArquivoBinario(); // EXEMPLO 7: Acesso direto a um arquivo binário usando seekg //geraArquivoBinario(); //carregaRegistro(100000); // EXEMPLO 8: Leitura de um arquivo grande usando um buffer na memória principal //geraCSV(); //carregaArquivoPorBlocos(5000000); return 0; }
true
eee6bbbb6f2e50ae686df072a392f4c8509fbeba
C++
vicmars5/EDA
/enclase/5-abril/LSLLSE/include/node.h
UTF-8
907
3.546875
4
[]
no_license
#ifndef NODE_H #define NODE_H template <class T> class Node { public: Node(); Node(const T&); T& getData(); Node <T>* getPrev(); Node<T>* getNext(); void setData(const T&); void setPrev(Node<T>*); void setNext(Node<T>*); private: T data; Node<T>* prev; Node<T>* next; }; template <class T> Node<T>::Node() { prev = nullptr; next = nullptr; } template <class T> Node<T>::Node(const T& e) : Node(){ data = e; } template <class T> T& Node<T>::getData() { return data; } template <class T> Node<T>* Node<T>::getPrev() { return prev; } template <class T> Node<T>* Node<T>::getNext() { return next; } template <class T> void Node<T>::setData(const T& e) { data = e; } template <class T> void Node<T>::setPrev(Node<T>* p) { prev = p; } template <class T> void Node<T>::setNext(Node<T>* p) { next = p; } #endif // NODE_H
true
d379883cbe737158b676402d4dbc864bf33351ff
C++
lj2759531/JaimeLuis_CIS5_Fall2017
/Class/Budget_FED_DOD_NASA/main.cpp
UTF-8
816
2.765625
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: main.cpp * Author: Luis Jaime * * Created on September 6, 2017, 9:49 AM * Purpose: What is known? and What is reality? */ #include<iostream> #include <cstdlib> using namespace std; int main(int argc, char** argv) { short fedBudg; short dodBudg; short nasaBudg; float pctDOD; float pctNASA; fedBudg= 3650; //3650 billion dodBudg= 639; //639 Billion nasaBudg= 19;// 19.1 Billion pctDOD=100.0f*dodBudg/fedBudg; pctNASA=100.0f*nasaBudg/fedBudg; cout<<"DOD Budget= "<<pctDOD<<"%"<<endl; cout<<"NASA Budget= "<<pctNASA<<"%"<<endl; return 0; }
true
98182ee7887dd116eeefedf5fa7bb111858e1350
C++
ccdxc/logSurvey
/data/crawl/make/old_hunk_1599.cpp
UTF-8
139
2.65625
3
[]
no_license
{ case cs_running: c->next = children; children = c; /* One more job slot is in use. */ ++job_slots_used;
true
059748c27780897abf16fe6202afdf102f526348
C++
alusan/patscan_project
/patscan/include/m_unit.h
UTF-8
368
2.75
3
[]
no_license
#ifndef M_UNIT_H #define M_UNIT_H #include <Rule.h> class m_unit : public Rule //if this, then expect pattern of type: 4...8 { public: m_unit(std::string s); int getStart(); int getEnd(); protected: int ind_s; // start of the matching range int ind_e; // end of the matching range private: }; #endif // M_UNIT_H
true
054c31eeed34925b91ba274cc2513a3bd570a157
C++
sguazt/dcsxx-commons
/inc/dcs/math/curvefit/interpolation/nearest.hpp
UTF-8
2,354
2.703125
3
[ "Apache-2.0" ]
permissive
/** * \file dcs/math/curvefit/interpolation/nearest_neighbor.hpp * * \brief In nearest neighbor interpolation, the value of an interpolated point * is set to the value of the nearest data point. * * \author Marco Guazzone (marco.guazzone@gmail.com) * * <hr/> * * Copyright 2013 Marco Guazzone (marco.guazzone@gmail.com) * * 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. */ #ifndef DCS_MATH_CURVEFIT_INTERPOLATION_NEAREST_NEIGHBOR_HPP #define DCS_MATH_CURVEFIT_INTERPOLATION_NEAREST_NEIGHBOR_HPP #include <dcs/assert.hpp> #include <dcs/exception.hpp> #include <dcs/math/curvefit/interpolation/base1d.hpp> #include <cmath> #include <cstddef> #include <stdexcept> namespace dcs { namespace math { namespace curvefit { template <typename RealT> class nearest_neighbor_interpolator: public base_1d_interpolator<RealT> { public: typedef RealT real_type; private: typedef base_1d_interpolator<real_type> base_type; public: template <typename XIterT, typename YIterT> nearest_neighbor_interpolator(XIterT first_x, XIterT last_x, YIterT first_y, YIterT last_y) : base_type(first_x, last_x, first_y, last_y) { // pre: n >= 1 DCS_ASSERT(this->num_nodes() > 0, DCS_EXCEPTION_THROW(::std::invalid_argument, "Insufficient number of nodes. Required at least 1 node")); } private: real_type do_interpolate(real_type x) const { // Find the neighbor j that minimizes the distance: // j = \arg\min_i |x_i-x| // and return the corresponding y_j value ::std::size_t j = 0; real_type diff = ::std::abs(this->node(j)-x); for (::std::size_t i = 1; i < this->num_nodes(); ++i) { real_type d = ::std::abs(this->node(i)-x); if (d < diff) { diff = d; j = i; } } return this->value(j); } }; // nearest_neighbor_interpolator }}} // Namespace dcs::math::curvefit #endif // DCS_MATH_CURVEFIT_INTERPOLATION_NEAREST_NEIGHBOR_HPP
true
3e024fa1eb8a6c7975dae5e3189366d5f1006c55
C++
bawjensen/COMP-215-Algorithms
/Jensen_A1/Jensen_A1.cpp
UTF-8
5,851
3.9375
4
[]
no_license
#include "Jensen_A1.h" using namespace std; String::String() { // Default constructor - sets contents of String object to the empty character array of length 1. // Precondition: No String object created. // Postcondition: String object created with contents of an empty character array // of length 1. contents = new char[1]; // Not set to null becuase cout'ing a character array // implicitly attempts dereferencing - bad news for the 0 // memory location. } String::String(const char c[]) { // Copy constructor - sets contents of String object to the contents of the passed // character array. // Precondition: No String object created. // Postcondition: String object created with the contents set to the passed char array. short lenC = strlen(c); contents = new char[lenC]; strcpy(contents, c); } long String::length() { // Method to return the length of the String. // Precondition: String has contents initialized. // Postcondition: Returned long with length of String object. return strlen(contents); } String String::operator+(String other) { // Concatenation operator - concatenates two strings together and returns a new // String object with the new contents. // Precondition: Two separate string objects with contents arrays. // Postcondition: A new string created with the copy constructor, returned to caller. short lenThis = strlen(contents); short lenOther = strlen(other.contents); char* buffContents = new char[lenThis + lenOther]; // char array buffer to store result strcpy(buffContents, contents); strcpy(buffContents+lenThis, other.contents); String buff(buffContents); // String buffer variable delete[] buffContents; // preventing (some) memory leaks return buff; } String String::operator+=(String other) { // Append operator - appends the contents of other onto the first String. // Precondition: Two separate string objects with distinct contents. // Postcondition: First String object contents are expanded and include the contents // of the "other" String appended at the end. short lenThis = strlen(contents); short lenOther = strlen(other.contents); char* newContents = new char[lenThis + lenOther]; strcpy(newContents, contents); strcpy(newContents+lenThis, other.contents); delete[] contents; // preventing (some) memory leaks contents = newContents; return (*this); } char String::operator[](short i) { // Index access - accepts a short, i, and returns the value of the 'i'th + 1 element. // Precondition: String has contents array. Does error checking. // Postcondition: Returns a character to the caller. if (i >= strlen(contents)) { cout << "Error: Bad index" << endl; // Note: Doesn't raise an exception return contents[strlen(contents)-1]; } return contents[i]; } void String::operator=(const char c[]) { // Assignment operator - assigns the right operand of type char array to // the contents of the String object. // Precondition: A String object with or without a filled contents array. // Postcondition: Old contents memory freed up, with new char array stored in contents. short lenC = strlen(c); delete[] contents; // preventing (some) memory leaks contents = new char[lenC]; strcpy(contents, c); } bool String::operator==(String other) { // Boolean equality operator - evaluates whether or not the two strings have // identical contents in terms of chars. // Precondition: Two String objects with contents arrays. // Postcondition: A returned value with the evaluation of the equality of the two Strings. if (strlen(contents) == strlen(other.contents)) { // If length isn't the same, fails right away for (short i = 1; contents[i] != '\0'; i++) { // loops until termination character '\0' if (contents[i] != other.contents[i]) { // Once two elements aren't the same, fails return false; } } return true; // Made it through all elements } else { return false; } } ostream& operator<<(ostream& co, const String& s) { // Overloading ostream operator output - prints out the contents of the String // object to stdout. // Precondition: String object with contents array, full or empty. // Postcondition: Std output to user of contents's characters. for (short i = 0; s.contents[i] != '\0'; i++) { // Iterates through till termination character co << s.contents[i]; } return co; } istream& operator>>(istream& ci, String& s) { // Overloading istream operator input - takes in user input from stdin // and stores it in the String's contents. // Precondition: String object with contents array, full or empty. // Postcondition: String object with filled contents array, and the istream object // returned to the caller. short guess_length = 5; // guessed length of input - adjusted later if wrong short count = 0; // counter variable for index char* buffContents; // character array buffer variable char* temp; // temp character array storage for creating new (larger) arrays if needed char c[2]; // small array to take input from cin - Note: length is 2 due to quirks of cin buffContents = new char[guess_length]; // Create initial guessed array for (int i = 0; ci; i++) { // Iterate until ci evaluates as false (aka out-of-input) if (ci.get(c, 2)) { // checks to see that the get operation works - Note: length 2 // actually grabs the first character off of the array buffContents[i] = *c; // Store the contents } if (i > guess_length) { guess_length *= 2; // Step-up the guessed size of input temp = new char[guess_length]; // Create new guess buffer strcpy(temp, buffContents); delete[] buffContents; // delete old - preventing (some) memory leaks buffContents = temp; // Store old into new and continue } } delete[] s.contents; // preventing (some) memory leaks s.contents = buffContents; return ci; }
true
3b7af0cb53d7566c38a06eb20267698d05fd9bdb
C++
eightnoteight/compro
/syncp/nproc-cs.cc
UTF-8
631
2.859375
3
[]
no_license
/* n processes, critical section problem. */ bool waiting[n], lock = false, key; std::fill(waiting, waiting + n, false); do { waiting[i] = true; key = true; while (waiting[i] && key) key = test_and_set(&lock); waiting[i] = false; /* critical section */ j = (i + 1) % n; while ((j != i) && !waiting[j]) j = (j + 1) % n; if (j == i) /* no one is waiting */ lock = false; /* revoke ownership of lock, so that someone will claim it. */ else waiting[j] = false; /* transfer the ownership of lock to the jth process */ /* remainder section */ } while (true);
true
525db31dd202bd6057951f136cf282f7dcc6d378
C++
vincentwutst/LeetCode
/Sqrt(x).cpp
UTF-8
320
3.203125
3
[]
no_license
class Solution { public: int sqrt(int x) { int left = 0, right = x, mid; while (left < right) { mid = left + (right - left) / 2 + 1; if (x / mid == mid) return mid; else if (x / mid < mid) //// 不要用x > mid * mid,会溢出 right = mid - 1; else left = mid; } return right; } };
true
1f9c6d6c5f9ae25610e194009d29f5851167d4f1
C++
105599004/posd_project
/src/number.cpp
UTF-8
539
3.0625
3
[ "MIT" ]
permissive
#include "../include/number.h" #include <string> using namespace std; Number::Number(int i){ _value = i; _symbol = to_string(i); } string Number::value(){ return to_string(_value); } string Number::symbol(){ return _symbol; } bool Number::match(Number n){ return _value == n._value; } bool Number::match(Variable &var){ if(var.isAssignable()){ var.match(*this); var.setNonAssignable(); return true; }else{ return to_string(_value) == var.value(); } } bool Number::match(Atom a){ return false; }
true
56d9014b593aeaa4456ad280b7196943dad15c80
C++
jcbages/notebook
/notebook/Strings/Hashing.cpp
UTF-8
783
3
3
[ "MIT" ]
permissive
#include <bits/stdc++.h> using namespace std; typedef long long ll; #define X 137 #define MOD ((ll)1e9+7) #define mod(n) (((n)%(MOD)+(MOD))%(MOD)) // given a string A and a target B, print the occurrences of B in A void hashing(const string &a, const string &b) { // build the hash function string s = b + "$" + a; int n = s.size(); vector<ll> h(n+1), r(n+1); r[0] = 1; for (int i = 1; i <= n; ++i) { h[i] = mod(h[i-1]*X+s[i-1]); r[i] = mod(r[i-1]*X); } // print occurrences int m = b.size(); for (int i = m+1; i <= n; ++i) { if (mod(h[i]-mod(h[i-m]*r[m])) == h[m]) cout << i-2*m-1 << '\n'; } } int main() { string a = "alabalalabala"; string b = "bala"; // 3, 9 (0-based index) hashing(a, b); }
true
58ac262e9678b70ed171c1100547de6e5aa27d62
C++
CitlaliRem/Ejercicios_Clase
/Práctica05/main_prac5.cpp
ISO-8859-1
10,635
2.609375
3
[]
no_license
//Semestre 2019 - II //************************************************************// //************************************************************// //******** Alumno: BADILLO REMIGIO DULCE CITLALI ************// //****** PRCTICA 5 ******// //******** Visual Studio 2017 ******// //**** Para mover el teclado: *************************// //**** Derecha: teclas 'A' 'a' *************************// //**** Izquierda: teclas 'D' 'd' *************************// //**** Arriba: teclas 'Q' 'q' *************************// //**** Abajo: teclas 'E' 'e' ************************// //**** Acercar: teclas 'W' 'w' *************************// //**** Alejar: teclas 'S' 's' *************************// //**** Brazo positivo: tecla 'h' ************************// //**** Brazo negativo: tecla 'H' ************************// //**** Codo positivo: tecla 'c' ************************// //**** Codo negativo: tecla 'C' ************************// //**** Palma positivo: tecla 'P' ************************// //**** Palma negativo: tecla 'p' ************************// //**** Palma positivo: tecla 'm' ************************// //**** Palma negativo: tecla 'M' ************************// //************************************************************// #include "Main.h" float transZ = -5.0f; float transX = 0.0f; float transY = 0.0f; float angleX = 0.0f; float angleY = 0.0f; int screenW = 0.0; int screenH = 0.0; float angHombro = 0.0f; float angCodo = 0.0f; float angMueca = 0.0f; float angMano = 0.0f; GLfloat Position[]= { 0.0f, 3.0f, 0.0f, 1.0f }; // Light Position GLfloat Position2[]= { 0.0f, 0.0f, -5.0f, 1.0f }; // Light Position void InitGL ( void ) // Inicializamos parametros { glShadeModel(GL_SMOOTH); // Habilitamos Smooth Shading glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // Negro de fondo glClearDepth(1.0f); // Configuramos Depth Buffer glEnable(GL_DEPTH_TEST); // Habilitamos Depth Testing //Configuracion luz glLightfv(GL_LIGHT0, GL_POSITION, Position); glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, Position2); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glDepthFunc(GL_LEQUAL); // Tipo de Depth Testing a realizar glEnable ( GL_COLOR_MATERIAL ); glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); } void prisma(void) { GLfloat vertice [8][3] = { {0.5 ,-0.5, 0.5}, //Coordenadas Vrtice 0 V0 {-0.5 ,-0.5, 0.5}, //Coordenadas Vrtice 1 V1 {-0.5 ,-0.5, -0.5}, //Coordenadas Vrtice 2 V2 {0.5 ,-0.5, -0.5}, //Coordenadas Vrtice 3 V3 {0.5 ,0.5, 0.5}, //Coordenadas Vrtice 4 V4 {0.5 ,0.5, -0.5}, //Coordenadas Vrtice 5 V5 {-0.5 ,0.5, -0.5}, //Coordenadas Vrtice 6 V6 {-0.5 ,0.5, 0.5}, //Coordenadas Vrtice 7 V7 }; glBegin(GL_POLYGON); //Front glNormal3f( 0.0f, 0.0f, 1.0f); glVertex3fv(vertice[0]); glVertex3fv(vertice[4]); glVertex3fv(vertice[7]); glVertex3fv(vertice[1]); glEnd(); glBegin(GL_POLYGON); //Right glNormal3f( 1.0f, 0.0f, 0.0f); glVertex3fv(vertice[0]); glVertex3fv(vertice[3]); glVertex3fv(vertice[5]); glVertex3fv(vertice[4]); glEnd(); glBegin(GL_POLYGON); //Back glNormal3f( 0.0f, 0.0f, -1.0f); glVertex3fv(vertice[6]); glVertex3fv(vertice[5]); glVertex3fv(vertice[3]); glVertex3fv(vertice[2]); glEnd(); glBegin(GL_POLYGON); //Left glNormal3f( -1.0f, 0.0f, 0.0f); glVertex3fv(vertice[1]); glVertex3fv(vertice[7]); glVertex3fv(vertice[6]); glVertex3fv(vertice[2]); glEnd(); glBegin(GL_POLYGON); //Bottom glNormal3f( 0.0f, -1.0f, 0.0f); glVertex3fv(vertice[0]); glVertex3fv(vertice[1]); glVertex3fv(vertice[2]); glVertex3fv(vertice[3]); glEnd(); glBegin(GL_POLYGON); //Top glNormal3f( 0.0f, 1.0f, 0.0f); glVertex3fv(vertice[4]); glVertex3fv(vertice[5]); glVertex3fv(vertice[6]); glVertex3fv(vertice[7]); glEnd(); } void display ( void ) // Creamos la funcion donde se dibuja { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Limiamos pantalla y Depth Buffer //glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(transX, transY, transZ); glRotatef(angleY, 0.0, 1.0, 0.0); glRotatef(angleX, 1.0, 0.0, 0.0); //Poner Cdigo Aqu. (0,0,0) glPushMatrix(); //dibuja brazo 1 glTranslatef(-2.5, 1.25, 0.0); // (-2.5,1.25,0.0) glRotatef(angHombro, 0, 0, 1); //rotate para el hombro glPushMatrix(); //dibuja hombro 2 glTranslatef(2.5, -1.25, 0.0); //(0,0,0) glScalef(5.0, 2.5, 5.0); prisma(); glPopMatrix(); //2 glPushMatrix();//dibuja antebrazo 3 glRotatef(angCodo, 0, 0, 1); //rotate para el codo glPushMatrix(); //4 glTranslatef(8.0,-1.25,0.0); glScalef(6.0, 2.5, 3.0); prisma(); glPopMatrix();//4 glPushMatrix(); //5 glRotatef(angMueca, 0, 1, 0); // rotate para la mueca glPushMatrix();//6 dibuja palma glTranslatef(12.0, -1.25, 0.0); glScalef(2.0, 2.5, 2.0); prisma(); glPopMatrix(); //6 glPushMatrix(); //21 glRotatef(angMano, 0, 1, 0); glPushMatrix();//dedo pulgar 1 7 glTranslatef(12.25, 0.25, 0.0); glScalef(0.5, 0.5, 1.0); prisma(); glPopMatrix(); //7 glPushMatrix();//dedo pulgar 2 8 glTranslatef(12.25, 0.75, 0.0); glScalef(0.5, 0.5, 1.0); prisma(); glPopMatrix(); //8 glPushMatrix();//dedo ndice 1 9 glTranslatef(13.25, -0.25, 0.0); glScalef(0.5, 0.5, 1.0); prisma(); glPopMatrix(); //9 glPushMatrix();//dedo ndice 2 10 glTranslatef(13.75, -0.25, 0.0); glScalef(0.5, 0.5, 1.0); prisma(); glPopMatrix(); //10 glPushMatrix();//dedo ndice 3 11 glTranslatef(14.25, -0.25, 0.0); glScalef(0.5, 0.5, 1.0); prisma(); glPopMatrix(); //11 glPushMatrix();//dedo medio 1 12 glTranslatef(13.375, -0.825, 0.0); glScalef(0.75, 0.5, 1.0); prisma(); glPopMatrix(); //12 glPushMatrix();//dedo medio 2 13 glTranslatef(14.125, -0.825, 0.0); glScalef(0.75, 0.5, 1.0); prisma(); glPopMatrix(); //13 glPushMatrix();//dedo medio 3 14 glTranslatef(14.875, -0.825, 0.0); glScalef(0.75, 0.5, 1.0); prisma(); glPopMatrix(); //14 glPushMatrix();//dedo anular 1 15 glTranslatef(13.25, -1.5, 0.0); glScalef(0.5, 0.5, 1.0); prisma(); glPopMatrix(); //15 glPushMatrix();//dedo anular 2 16 glTranslatef(13.75, -1.5, 0.0); glScalef(0.5, 0.5, 1.0); prisma(); glPopMatrix(); //16 glPushMatrix();//dedo anular 3 17 glTranslatef(14.25, -1.5, 0.0); glScalef(0.5, 0.5, 1.0); prisma(); glPopMatrix(); //17 glPushMatrix();//dedo meique 1 18 glTranslatef(13.2, -2.25, 0.0); glScalef(0.4, 0.5, 1.0); prisma(); glPopMatrix(); //18 glPushMatrix();//dedo meique 2 19 glTranslatef(13.6, -2.25, 0.0); glScalef(0.4, 0.5, 1.0); prisma(); glPopMatrix(); //19 glPushMatrix();//dedo meique 3 20 glTranslatef(14.0, -2.25, 0.0); glScalef(0.4, 0.5, 1.0); prisma(); glPopMatrix(); //20 glPopMatrix(); glPopMatrix();//5 glPopMatrix(); //3 glPopMatrix();//1 glutSwapBuffers ( ); // Swap The Buffers } void reshape ( int width , int height ) // Creamos funcion Reshape { if (height==0) // Prevenir division entre cero { height=1; } glViewport(0,0,width,height); glMatrixMode(GL_PROJECTION); // Seleccionamos Projection Matrix glLoadIdentity(); // Tipo de Vista //glOrtho(-5,5,-5,5,0.2,20); glFrustum (-0.3, 0.3,-0.3, 0.3, 0.1, 50.0); glMatrixMode(GL_MODELVIEW); // Seleccionamos Modelview Matrix //glLoadIdentity(); } void keyboard ( unsigned char key, int x, int y ) // Create Keyboard Function { switch ( key ) { case 'w': case 'W': transZ +=0.2f; break; case 's': case 'S': transZ -=0.2f; break; case 'a': case 'A': transX +=0.2f; break; case 'd': case 'D': transX -=0.2f; break; case 'e': case 'E': transY += 0.2f; break; case 'q': case 'Q': transY -= 0.2f; break; case 'h': if (angHombro < 90) { angHombro += 0.5f; printf("%f ", angHombro); } break; case 'H': if (angHombro > -90) { angHombro -= 0.5f; printf("%f ", angHombro); } break; case 'c': if (angCodo < 10) { angCodo += 0.5f; printf("%f ", angCodo); } break; case 'C': if (angCodo > -15) { angCodo -= 0.5f; printf("%f ", angCodo); } break; case 'p': if (angMueca < 10) { angMueca += 0.5f; printf("%f ", angCodo); } break; case 'P': if (angMueca > -15) { angMueca -= 0.5f; printf("%f ", angCodo); } break; case 'm': if (angMano < 7) { angMano += 0.5f; printf("%f ", angMano); } break; case 'M': if (angMano > -5) { angMano -= 0.5f; printf("%f ", angMano); } break; case 27: // Cuando Esc es presionado... exit ( 0 ); // Salimos del programa break; default: // Cualquier otra break; } glutPostRedisplay(); } void arrow_keys ( int a_keys, int x, int y ) // Funcion para manejo de teclas especiales (arrow keys) { switch ( a_keys ) { case GLUT_KEY_UP: // Presionamos tecla ARRIBA... angleX +=2.0f; break; case GLUT_KEY_DOWN: // Presionamos tecla ABAJO... angleX -=2.0f; break; case GLUT_KEY_LEFT: angleY +=2.0f; break; case GLUT_KEY_RIGHT: angleY -=2.0f; break; default: break; } glutPostRedisplay(); } int main ( int argc, char** argv ) // Main Function { glutInit (&argc, argv); // Inicializamos OpenGL glutInitDisplayMode (GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH); // Display Mode (Clores RGB y alpha | Buffer Doble ) screenW = glutGet(GLUT_SCREEN_WIDTH); screenH = glutGet(GLUT_SCREEN_HEIGHT); glutInitWindowSize (500, 500); // Tamao de la Ventana glutInitWindowPosition (0, 0); //Posicion de la Ventana glutCreateWindow ("Practica 5"); // Nombre de la Ventana printf("Resolution H: %i \n", screenW); printf("Resolution V: %i \n", screenH); InitGL (); // Parametros iniciales de la aplicacion glutDisplayFunc ( display ); //Indicamos a Glut funcin de dibujo glutReshapeFunc ( reshape ); //Indicamos a Glut funcin en caso de cambio de tamano glutKeyboardFunc ( keyboard ); //Indicamos a Glut funcin de manejo de teclado glutSpecialFunc ( arrow_keys ); //Otras glutMainLoop ( ); // return 0; }
true
074d3bd9fb9f70daae26eb481f3f83ba97669375
C++
flseaui/Tiler
/src/Button.cpp
UTF-8
2,249
2.828125
3
[ "MIT" ]
permissive
#include "Button.h" Button::Button(Window* window, Camera* camera, const char* pPressed, const char* pUnpressed, const char* pHover, float x, float y, float width, float height, bool check) : TexRect(camera, pPressed, x, y, 0, width, height, true) { stateSkek = 0; this->check = check; this->window = window; this->hitbox = new AABB(x, y, width, height); unpressed = new Texture(pUnpressed); pressed = new Texture(pPressed); unpressed = new Texture(pUnpressed); hover = new Texture(pHover); } void Button::update() { if (check) { if (hitbox->contains(window->getMouseUX(camera), window->getMouseUY(camera))) { if (state != PRESSED) state = HOVERED; if (window->getMouseLeft()) { if (state == HOVERED && stateSkek == 2) { stateSkek = 0; state = PRESSED; } if (stateSkek == 1) { state = HOVERED; stateSkek = 3; } } } else { if (state == HOVERED) state = NEUTRAL; } if (!window->getMouseLeft()) { if (stateSkek == 0) ++stateSkek; if (stateSkek == 3) --stateSkek; } } else { if (hitbox->contains(window->getMouseUX(camera), window->getMouseUY(camera))) { if (window->getMouseLeft()) state = PRESSED; else state = HOVERED; } else state = NEUTRAL; } switch (state) { case NEUTRAL: setTexture(unpressed); break; case PRESSED: setTexture(pressed); break; case RELEASED: setTexture(unpressed); break; case HOVERED: setTexture(hover); break; default: setTexture(unpressed); break; } } AABB* Button::getHitbox() { return hitbox; } int Button::getState() { return state; } void Button::setState(int state) { this->state = State(state); } TexButton::TexButton(Window* window, Camera* camera, const char* texture, float x, float y, float width, float height, int id, bool check) : Button(window, camera, "res/textures/button_pressed.png", "res/textures/button_unpressed.png", "res/textures/button_hover.png", x, y, width, height, check) { this->texture = new TexRect(camera, texture, x + (width / 6), y + (height / 6), 0, width - (width / 3), height - (height / 3), true); this->id = id; } void TexButton::renderTexture() { texture->render(); } int TexButton::getID() { return id; }
true
ee4da4241c5338ab533657408257357bcdf579c0
C++
rangzee/notepad2
/scintilla/lexlib/PropSetSimple.h
UTF-8
704
2.5625
3
[ "LicenseRef-scancode-scintilla", "BSD-3-Clause", "MIT", "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// Scintilla source code edit control /** @file PropSetSimple.h ** A basic string to string map. **/ // Copyright 1998-2009 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #pragma once namespace Lexilla { class PropSetSimple final { std::map<std::string, std::string, std::less<>> props; public: bool Set(std::string_view key, std::string_view val); const char *Get(std::string_view key) const; int GetInt(const char *key, size_t keyLen, int defaultValue = 0) const; template <size_t N> int GetInt(const char (&key)[N], int defaultValue = 0) const { return GetInt(key, N - 1, defaultValue); } }; }
true
48c775a88c2d81d3fc0f442df781145d21cb444a
C++
caioguedesam/message_network_posix
/common.cpp
UTF-8
1,282
3.09375
3
[]
no_license
#include "common.h" // Transforma endereço IPv4 string void AddrToStr(const sockaddr *addr, char *str, size_t size) { char addrstr[INET_ADDRSTRLEN + 1] = ""; uint16_t port; if(addr->sa_family == AF_INET) { sockaddr_in *addr4 = (sockaddr_in *)addr; if(!inet_ntop(AF_INET, &(addr4->sin_addr), addrstr, INET_ADDRSTRLEN + 1)) LogExit("Error converting network address to presentation in AddrToStr"); port = ntohs(addr4->sin_port); } else { LogExit("Unsupported protocol family"); } if(str) snprintf(str, size, "IPv4 %s %hu", addrstr, port); } // Inicializa um socket com o protocolo em storage int CreateSocket(const sockaddr_storage storage) { int s; s = socket(storage.ss_family, SOCK_STREAM, 0); if(s == -1) LogExit("Error on socket init"); return s; } // Transforma a string de uma porta em representação do dispositivo para da rede uint16_t ParsePortFromDevice(const char *portStr) { // Analisando a porta uint16_t port = (uint16_t)atoi(portStr); if(port == 0) return 0; // Convertendo a representação do porto do dispositivo para a da rede return htons(port); } void LogExit(const char* msg) { perror(msg); exit(EXIT_FAILURE); }
true
c3d2f15d615d9f103bd1facf61d0436afa3abb78
C++
BCSJH/Arduino
/project_school/2019.11.11/Stream/Stream.ino
UTF-8
3,240
2.671875
3
[]
no_license
#include <SoftwareSerial.h>//와이파이 통신 #include "FirebaseESP8266.h" //파이어베이스 사용 #include <ESP8266WiFi.h> //와이파이 사용 //와이파이와 파이어베이스 연동 #define FIREBASE_HOST "arduinowebserver2.firebaseio.com" #define FIREBASE_AUTH "cg" #define WIFI_SSID "KBU" #define WIFI_PASSWORD "" //Define FirebaseESP8266 data object FirebaseData firebaseData; FirebaseJson json; SoftwareSerial s(D6,D5); // (Rx, Tx) //와이파이 통신 void printResult(FirebaseData &data); void setup() { Serial.begin(9600); s.begin(9600); //와이파이 연결 WiFi.begin(WIFI_SSID, WIFI_PASSWORD); Serial.print("Connecting to Wi-Fi"); while (WiFi.status() != WL_CONNECTED) { Serial.print("."); delay(300); } Serial.println(); Serial.print("Connected with IP: "); Serial.println(WiFi.localIP()); Serial.println(); //파이어베이스 연결 Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH); Firebase.reconnectWiFi(true); //와이파이와 아두이노 연결 : https://www.youtube.com/watch?v=SiU-QZwik8w /* This option allows get and delete functions (PUT and DELETE HTTP requests) works for device connected behind the Firewall that allows only GET and POST requests. Firebase.enableClassicRequest(firebaseData, true); */ String path = "/testBucket/WIFIControl"; Serial.println("------------------------------------"); Serial.println("Get double test..."); //Also can use Firebase.get instead of Firebase.setInt if (Firebase.getString(firebaseData, path)) { Serial.print("WIFIControl VALUE: "); printResult(firebaseData); Serial.println("------------------------------------"); Serial.println(); } else { Serial.println("FAILED"); Serial.println("REASON: " + firebaseData.errorReason()); Serial.println("------------------------------------"); Serial.println(); } } void printResult(FirebaseData &data) { if (data.dataType() == "int") Serial.println(data.intData()); else if (data.dataType() == "float") Serial.println(data.floatData(), 5); else if (data.dataType() == "double") printf("%.9lf\n", data.doubleData()); else if (data.dataType() == "boolean") Serial.println(data.boolData() == 1 ? "true" : "false"); else if (data.dataType() == "string") { int a; a = data.stringData().toInt(); s.write(a);//a.toInt() Serial.print("a int:"); Serial.println(a); Serial.println(data.stringData()); } } void loop() { String path = "/testBucket/WIFIControl";//경로 delay(5000); if (Firebase.getString(firebaseData, path)) { Serial.print("WIFIControl VALUE: "); printResult(firebaseData); Serial.println("------------------------------------"); Serial.println(); } else { Serial.println("FAILED"); Serial.println("REASON: " + firebaseData.errorReason()); Serial.println("------------------------------------"); Serial.println(); } }
true
2466f73bfec02af207bd99e45217e03cac8c148c
C++
Coolchirutha/CP
/Step3/131.palindrome-partitioning.cpp
UTF-8
1,007
3.140625
3
[]
no_license
/* * @lc app=leetcode id=131 lang=cpp * * [131] Palindrome Partitioning */ #include <bits/stdc++.h> using namespace std; // @lc code=start class Solution { public: vector<vector<string>> partition(string s) { ios_base::sync_with_stdio(false); cin.tie(NULL); vector<vector<string>> result; vector<string> curPart; dfs(0, s, curPart, result); return result; } void dfs(int curIndex, string &s, vector<string> &curPart, vector<vector<string>> &result) { if (curIndex == s.size()) { result.push_back(curPart); return; } for (int i = curIndex; i < s.size(); i++) { if (isPal(s, curIndex, i)) { curPart.push_back(s.substr(curIndex, i - curIndex + 1)); dfs(i + 1, s, curPart, result); curPart.pop_back(); } } } bool isPal(const string &s, int start, int end) { while (start <= end) { if (s[start++] != s[end--]) { return false; } } return true; } }; // @lc code=end
true
155a6684c996b404ee31790f3a799ec20b11a616
C++
Manit1/Linear-Search
/main.cpp
UTF-8
639
3.890625
4
[]
no_license
#include <iostream> using namespace std; int Linear_search(int arr[],int x); int main() { int arr[10],x,flag; cout<<"Enter the elements of the array\n"; for(int i=0;i<10;i++) cin>>arr[i]; cout<<"Enter the element you want to search :"; cin>>x; flag= Linear_search(arr,x); if(flag==0) cout<<"\nElement does not exist in the array"; else cout<<"\nElement exists at index "<<flag; return 0; } int Linear_search(int arr[],int x){ int flag=-1; for(int i=0;i<10;i++) { if(arr[i]==x) flag=i; } return flag; }
true
c67e445cab2eebb300d3910dce01afac7ea72664
C++
SourDumplings/CodeSolutions
/OJ practices/LeetCode题目集/242. Valid Anagram(easy)-红黑树(map)法.cpp
UTF-8
459
3.015625
3
[]
no_license
/* * @Author: SourDumplings * @Date: 2019-08-29 12:51:45 * @Link: https://github.com/SourDumplings/ * @Email: changzheng300@foxmail.com * @Description: https://leetcode.com/problems/valid-anagram/ */ class Solution { public: bool isAnagram(string s, string t) { map<char, int> m1, m2; for (auto &&c : s) { ++m1[c]; } for (auto &&c : t) { ++m2[c]; } return m1 == m2; } };
true
f184c1ade0121c52693dca925466c28551b24c64
C++
BraderLh/AED
/Lista Enlazada Genérica/Nodo.h
UTF-8
1,597
3.4375
3
[]
no_license
#ifndef NODO_H_INCLUDED #define NODO_H_INCLUDED #include <iostream> using namespace std; template <class nodoType> class Nodo //definiendo la clase nodo { private: nodoType dato;//es el contenido que estara dentro de cada nodo el cual será de tipo entero Nodo *sig;//puntero al siguiente nodo public: template<typename listType> friend class ListaEn;//se declara como amiga la clase ListaEn para que esta pueda acceder al los datos miembros de la clase Nodo Nodo();//Constructor predeterminado de la clase nodo Nodo(const nodoType&);//Constructor por parametros de la clase nodo Nodo<nodoType>(const Nodo<nodoType> &n) : dato(n.dato),sig(n.prox){}; ~Nodo();//Destructor de la clase nodo void getDato() const;//funcion devuele el valor que contiene el nodo void deleteDato();//funcion que elimina el valor que contiene el nodo }; template<class nodoType> Nodo<nodoType>::Nodo()/*Inicializamos el dato y el siguiente nodo como NULL de forma predeterminada*/ { dato=NULL; sig=NULL; } template<class nodoType> Nodo<nodoType>::Nodo(const nodoType& dato)/*Inicializamos mediante un dato de tipo entero el dato y como NULL el siguente nodo*/ { this->dato=dato; this->sig=NULL; } template<class nodoType> void Nodo<nodoType>::getDato() const /*Imprime el dato que contiene el nodo"*/ { cout<<dato<<" -> "; } template<class nodoType> void Nodo<nodoType>::deleteDato()/*Borra el dato que contiene el nodo*/ { if(sig!=NULL) { sig->deleteDato(); } delete this; } template<class nodoType> Nodo<nodoType>::~Nodo() {} #endif // NODO_H_INCLUDED
true
9419dfa3bc42c60a4cd8570a164f82414f62406c
C++
ravi-dafauti/Algoritms
/DynamicProgramming/MinimumPartition.cpp
WINDOWS-1252
1,343
3.65625
4
[]
no_license
/*Given a set of integers, the task is to divide it into two sets S1 and S2 such that the absolute difference between their sums is minimum. If there is a set S with n elements, then if we assume Subset1 has m elements, Subset2 must have n - m elements and the value of abs(sum(Subset1) sum(Subset2)) should be minimum */ #include<iostream> using namespace std; #define MAX 99999 // solution is extension of subset sum problem int findMin(int arr[], int n) { int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; int **dp = (int **)malloc(sizeof(int)*(n + 1)); for (int i = 0; i <= n; i++) { dp[i] = (int *)malloc(sizeof(int)*((sum / 2) + 1)); } for (int i = 0; i < ((sum / 2) + 1); i++) dp[0][i] = 0; for (int i = 0; i <= n; i++) dp[i][0] = 1; for (int i = 1; i <= n; i++) { for (int j = 1; j <= (sum / 2); j++) { if (dp[i - 1][j] == 1) dp[i][j] = 1; else { if (arr[i - 1] <= j &&dp[i][j - arr[i - 1]] == 1) dp[i][j] = 1; else dp[i][j] = 0; } } } int i; int min_diff = MAX; for (i = sum / 2; i >= 0; i--) { if (dp[n][i] == 1) { min_diff = sum - 2 * i; break; } } return min_diff; } int main() { int arr[] = { 3, 1, 4, 2, 2, 1 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "The minimum difference between 2 sets is : " << findMin(arr, n); return 0; }
true
9a3e4c7eb5ea8843c97c28739268d4dd466c0851
C++
vinodkanchi/Audio-Player-System
/CAudioPlayerController.cpp
UTF-8
13,961
2.640625
3
[]
no_license
/* * CAudioPlayerController.cpp * * Created on: 09.01.2020 * Author: Wirth */ //////////////////////////////////////////////////////////////////////////////// // Header #define USE_MATH_DEFINES #include <cmath> #include <iostream> #include <string> #include <stdlib.h> #include <stdio.h> #include <dirent.h> // functions to scan files in folders (used in Lab04prep_DBAdminInsert) using namespace std; #include "CASDDException.h" #include "CFile.h" #include "CAudiofiltersDb.h" #include "CFilter.h" #include "CUserInterface.h" #include "CAudioPlayerController.h" CAudioPlayerController::CAudioPlayerController() { m_pSFile=NULL; // association with 1 or 0 CSoundFile-objects m_pFilter=NULL; // association with 1 or 0 CFilter-objects m_ui=NULL; // association with 1 or 0 CUserInterface-objects } CAudioPlayerController::~CAudioPlayerController() { if(m_pSFile)delete m_pSFile; if(m_pFilter)delete m_pFilter; } void CAudioPlayerController::run(CUserInterface* pui) { // if an exception has been thrown by init, the user is not able to use the player // therefore the program is terminated (unrecoverable error) try { m_ui=pui; // set the current user interface (given by the parameter) init(); // initialize the components of the controller, if possible and necessary } catch(CASDDException& e) { string eMsg="Error from: "; m_ui->showMessage(eMsg+e.getSrcAsString()+""+e.getErrorText()); return; } ////////////////////////////////////////////////// // main menue of the player // todo: Add further menu items, the corresponding cases and method calls to the following code // note: the last item of the menu must be empty (see CUserInterfaceCmdIOW code) string mainMenue[]={"select sound","select filter","select amplitude meter scaling mode","play sound","administrate sound collection", "administrate filter collection", "terminate player", ""}; while(1) { // if an exception will be thrown by one of the methods, the main menu will be shown // after an error message has been displayed. The user may decide, what to do (recoverable error) // For instance, if the user selects a filter without having selected a sound file before, an error // message tells the user to select a sound file. He/She may decide to do this and then select a filter // once more. In this case, the error condition is eliminated and the program may continue regularly. try { // display the menu and get the user's choice int selitem=m_ui->getListSelection(mainMenue); // process the user's choice by calling the appropriate CAudioPlayerControllerMethod switch(selitem) { case 0: chooseSound();break; case 1: chooseFilter();break; case 2: chooseAmplitudeScale();break; case 3: play();break; case 4: manageSoundCollection();break; case 5: manageFilterCollection();break; default: return; } } catch(CASDDException& e) { string eMsg="Error from: "; m_ui->showMessage(eMsg+e.getSrcAsString()+""+e.getErrorText()); } } } void CAudioPlayerController::init() { // no printing - the controller is the only object which may initiate // printing via the view object (MVC design) try { m_ui->init(); m_filterColl.open("localhost","ASDDuser","ASDDuser"); m_filterColl.allowPrint(false); m_soundColl.open("localhost","ASDDuser","ASDDuser"); m_soundColl.allowPrint(false); } catch(CASDDException& e) { e.print(); } } void CAudioPlayerController::chooseFilter() { if(!m_pSFile) // a sound file must have been created by the chooseSoundFile method before { m_ui->showMessage("Error from selectFilter: No sound file. Select sound file before filter!"); return; } // get the sampling rate from the current sound file int fs=m_pSFile->getSampleRate(); ///////////////////////////////////// // list the appropriate filters for the sound // select the appropriate filters int numflt=m_filterColl.selectFilters(fs); // get the number of appropriate filters if(numflt) // if there are filters that fit { // prepare a string array for the user interface, that will contain a menu with the selection of filters // there is place for an additional entry for an unfiltered sound and an empty string string* pFlt=new string[numflt+2]; // prepare an integer array for the corresponding filter IDs to pass them to the user interface as well // there is place for -1 (unfiltered sound) int* pFIDs=new int[numflt+1]; for(int i=0; i < numflt; i++) { m_filterColl.fetch(); // get a record of filter data // instead to print the filter data, the will be inserted into the string array and the filter ID array pFIDs[i]= m_filterColl.getFilterID(); pFlt[i]= m_filterColl.getFilterType() + "/" + m_filterColl.getFilterSubType() + ", order=" + to_string(m_filterColl.getOrder()) + "/delay=" + to_string(m_filterColl.getDelay()) + "s]: "+ m_filterColl.getFilterInfo(); } m_filterColl.closeQuery(); // add the last menu entry for the choice of an unfiltered sound pFIDs[numflt]=-1; pFlt[numflt]="-1 [unfiltered sound]"; // pass the arrays to the user interface and wait for the user's input // if the user provides a filterID which is not in pFIDs, the method returns // CUI_UNKNOWN int fid=m_ui->getListSelection(pFlt,pFIDs); // destroy the arrays delete[]pFlt; delete[]pFIDs; ///////////////////////////////////// // create a filter according to the user's choice if(fid != CUI_UNKNOWN) { if(fid>=0) // the user has chosen a filter from the filter collection { // get the filter's data if(true == m_filterColl.selectFilter(fid)) { // if there was a filter object from a preceding choice of the user, delete this if(m_pFilter)delete m_pFilter; // create filter // Lab05 changed: get filter data int order=m_filterColl.getOrder(); int delay=m_filterColl.getDelay(); string type=m_filterColl.getFilterType(); m_filterColl.closeQuery(); // int numAC=0, numBC=0; float* ac=m_filterColl.getACoeffs(fid, numAC); float* bc=m_filterColl.getBCoeffs(fid, numBC); if(type != "delay") m_pFilter=new CFilter(ac,bc,order,m_pSFile->getNumChannels()); else m_pFilter=new CDelayFilter(bc[1]-ac[1], -ac[1], delay, m_pSFile->getSampleRate(), m_pSFile->getNumChannels()); } else { // wrong ID (may only accidently happen - logical error in the program?) m_ui->showMessage("Error from selectFilter: No filter data available! Did not change filter. "); } } else // the user has chosen not to filter the sound { if(m_pFilter) // if there was a filter object from a preceding choice of the user { delete m_pFilter; // ... delete this m_pFilter=NULL; // currently we have no filter m_ui->showMessage("Message from selectFilter: Filter removed. "); } } } else m_ui->showMessage("Error from selectFilter: Invalid filter selection! Play unfiltered sound. "); } else m_ui->showMessage("Error from selectFilter: No filter available! Play unfiltered sound. "); } void CAudioPlayerController::manageFilterCollection() { // user input for filter file path string fltfolder; m_ui->showMessage("Enter filter file path: "); fltfolder=m_ui->getUserInputPath(); ////////////////////////////////////////// // Code from Lab04prep_DBAdminInsert and Lab04prep_insertFilterTest // iterates through the folder that the user entered and inserts all // the filters it finds in the folder (reading txt files) dirent* entry; DIR* dp; string fltfile; dp = opendir(fltfolder.c_str()); if (dp == NULL) { m_ui->showMessage("Could not open filter file folder."); return; } while((entry = readdir(dp))) { fltfile=entry->d_name; m_ui->showMessage("Filter file to insert into the database: " + fltfolder+fltfile+":"); if(fltfile.rfind(".txt")!=string::npos)// txt file? { const int rbufsize=100; // assume not more than 100 different sampling frequencies char readbuf[rbufsize]; // get all sampling frequencies contained in the file int numFs=rbufsize; int fsbuf[rbufsize]; CFilterFile::getFs((fltfolder+fltfile).c_str(),fsbuf,numFs); for(int i=0; i < numFs;i++) // iterate through all found fs { CFilterFile ff(fsbuf[i], (fltfolder+fltfile).c_str(), FILE_READ); // create a file object for a certain fs ff.open(); if(ff.read(readbuf,rbufsize)) // read information about the filter with the fs { // send information to the user interface to display it string fileinfo = "Inserting filter file: " + ff.getFilterType() + "/" + ff.getFilterSubType() + " filter [order=" + to_string(ff.getOrder()) + ", delay=" + to_string(ff.getDelay()) + "s, fs=" + to_string(fsbuf[i]) + "Hz] " + ff.getFilterInfo(); m_ui->showMessage(fileinfo); // insert the filter into the filter collection database if( false == m_filterColl.insertFilter(ff.getFilterType(),ff.getFilterSubType(), fsbuf[i],ff.getOrder(),1000.*ff.getDelay(),ff.getFilterInfo(), ff.getBCoeffs(),ff.getNumBCoeffs(),ff.getACoeffs(),ff.getNumACoeffs())) m_ui->showMessage("insert error"/*m_filterColl.getSQLErrorMsg()*/); // if error, let the user interface show the error message } else m_ui->showMessage("No coefficients available for fs=" + to_string(fsbuf[i]) + "Hz"); ff.close(); } } else m_ui->showMessage(" irrelevant file of other type or directory"); } closedir(dp); } void CAudioPlayerController::play() { if(!m_pSFile) { m_ui->showMessage("Error from play: No sound file. Select sound file before playing!"); return; } // configure sample buffer int framesPerBlock; // 1s/8=125ms per block if(m_pFilter) framesPerBlock= m_pSFile->getSampleRate()/8 > m_pFilter->getOrder() ? m_pSFile->getSampleRate()/8 : m_pFilter->getOrder() * 2; else framesPerBlock= m_pSFile->getSampleRate()/8; // 1s/8=125ms per block int sblockSize=m_pSFile->getNumChannels()*framesPerBlock; // total number of samples per block float* sbuf=new float[sblockSize]; float* sfbuf=new float[sblockSize]; float* playbuf; if(m_pFilter==NULL)playbuf=sbuf; else playbuf=sfbuf; // open and start the audio stream m_audiostream.open(m_pSFile->getNumChannels(), m_pSFile->getSampleRate(), framesPerBlock,false); m_audiostream.start(); bool bPlay=true; m_ui->showMessage("Press ENTER to start!"); m_ui->wait4Key(); // play the file // reads the number of frames passed (1 frame == 1 for mono, 2 for stereo, channel number in general) int readSize=m_pSFile->read((char*)sbuf, sblockSize*sizeof(float)); while(readSize) { if(m_ui->wait4Key(false)==true)bPlay=!bPlay; if(bPlay) { if(m_pFilter) { if(false==m_pFilter->filter(sbuf,sfbuf,framesPerBlock)) { delete[]sbuf; delete[]sfbuf; throw CASDDException(SRC_Filter,-1,"Filter order exceeds buffer size!"); } } m_audiostream.play(playbuf,framesPerBlock); m_ui->showAmplitude(playbuf,sblockSize); readSize=m_pSFile->read((char*)sbuf, sblockSize*sizeof(float)); } } // prepare next playing m_audiostream.close(); m_pSFile->rewind(); // release resources // audio data buffers if(sbuf)delete[]sbuf; if(sfbuf)delete[]sfbuf; } void CAudioPlayerController::chooseSound() { int numsnd=m_soundColl.selectNumSounds(); if(numsnd > 0) { string* pSounds=new string[numsnd+1]; int* pIDs=new int[numsnd]; m_soundColl.selectAllSounds(); for(int i=0; i < numsnd; i++) { m_soundColl.fetch(); pIDs[i]= m_soundColl.getID(); pSounds[i]=m_soundColl.getPath() + m_soundColl.getName() + "[" + to_string(m_soundColl.getFs()) + "Hz, " + to_string(m_soundColl.getNumChan()) + " Channels]"; } m_soundColl.closeQuery(); int sID=m_ui->getListSelection(pSounds,pIDs); delete[]pSounds; delete[]pIDs; if(sID!=CUI_UNKNOWN) { if(m_soundColl.selectSoundData(sID)) { CSoundFile* psf=new CSoundFile((m_soundColl.getPath()+m_soundColl.getName()).c_str(),FILE_READ); m_soundColl.closeQuery(); try{ psf->open(); if(m_pSFile)delete m_pSFile; m_pSFile=psf; } catch(CASDDException& e){ m_ui->showMessage("Error from " + e.getSrcAsString() + ": " + e.getErrorText()); } } else m_ui->showMessage("Error from selectSound: No sound data available!"); } else m_ui->showMessage("Error from selectSound: Invalid sound selection!"); } else throw CASDDException(SRC_Database,-1,"No sounds available!"); } void CAudioPlayerController::chooseAmplitudeScale() { string pscale_menue[]={"linear","logarithmic",""}; int sel=m_ui->getListSelection(pscale_menue); switch(sel) { case 0: m_ui->setAmplitudeScaling(SCALING_MODE_LIN);;break; case 1: m_ui->setAmplitudeScaling(SCALING_MODE_LOG);;break; default: m_ui->setAmplitudeScaling(SCALING_MODE_LIN);break; } } // Lab05 task c) void CAudioPlayerController::manageSoundCollection() { string sndfolder; m_ui->showMessage("Enter sound file path: "); sndfolder=m_ui->getUserInputPath(); dirent* entry; DIR* dp=NULL; string sndfile; dp = opendir(sndfolder.c_str()); if (dp == NULL) { m_ui->showMessage("Could not open sound file folder."); return; } while((entry = readdir(dp))) { sndfile=entry->d_name; m_ui->showMessage(sndfile+":"); if(sndfile.rfind(".wav")!=string::npos) { CSoundFile mysf((sndfolder+sndfile).c_str(),FILE_READ); mysf.open(); string fileinfo = "Inserting sound file: channels(" + to_string(mysf.getNumChannels()) + ") fs(" + to_string(mysf.getSampleRate()) + "Hz)"; m_ui->showMessage(fileinfo); if(false == m_soundColl.insertSound(sndfolder,sndfile,mysf.getSampleRate(),mysf.getNumChannels())) m_ui->showMessage(m_soundColl.getSQLErrorMessage("Error from manage sound collection: ")); } else m_ui->showMessage(" irrelevant file of other type or directory"); } if(dp)closedir(dp); }
true
628eab47d61493facf7ad0b9cf3608b4838fcf95
C++
zhsrl/PP1
/week14/G2/2.cpp
UTF-8
306
2.71875
3
[]
no_license
#include <iostream> #include <algorithm> #include <vector> using namespace std; int main(){ int a = 2; int *p = &a; // char *c; // double *d; // cout << &a << "\n" << p << endl; cout << a << "\n" << *p << endl; *p = 10; // int c = a; // c = 12; cout << a << endl; return 0; }
true
c5d379ca064497ac67814da415b868923a487b8a
C++
yalavrinenko/dscs
/src/ships/component.hpp
UTF-8
1,680
2.65625
3
[]
no_license
// // Created by yalavrinenko on 07.04.19. // #ifndef DSCS_COMPONENT_HPP #define DSCS_COMPONENT_HPP #include "../../utils/logger_factory.hpp" #include <memory> #include "utils/math_function.hpp" enum class component_type{ engine, reactor, hull, fuel_tank, battery, radar, radio, monitor_unit, warhead, none }; class icomponent: public gui::igui_object{ public: icomponent(double mass, std::string name, plogger logger, component_type type = component_type::none) : gui::igui_object(std::move(logger.gui_window)), mass_(mass), logger_(std::move(logger.text_logger)), name_(std::move(name)), type_(type), loggers_{logger_, window_} {} virtual void action() = 0; virtual void log_action() const = 0; //void draw() override {} [[nodiscard]] virtual double mass() const { return mass_; } auto const& name() const {return name_;}; component_type type() const { return type_; } protected: double mass_{}; ptext_logger& logger() const { return logger_; } plogger& slogger() { return loggers_; } private: mutable ptext_logger logger_ = nullptr; std::string name_; component_type type_; plogger loggers_; }; using pcomponent = std::unique_ptr<icomponent>; using pscomponent = std::shared_ptr<icomponent>; template <unsigned num, unsigned den> struct size_scale { static double constexpr scale = static_cast<double>(num) / static_cast<double>(den); }; struct component_size{ using tiny = size_scale<1, 4>; using small = size_scale<1, 2>; using medium = size_scale<1, 1>; using large = size_scale<2, 1>; using huge = size_scale<4, 1>; }; #endif // DSCS_COMPONENT_HPP
true
18ed44fba9da87f19cf90441c4319b63b6efeb6b
C++
MohamedShanaz/xforcerepo
/Calculator/logfunctionelement.cpp
UTF-8
784
2.984375
3
[]
no_license
#include "logfunctionelement.h" LogFunctionElement::LogFunctionElement() { } LogFunctionElement::~LogFunctionElement() { } double LogFunctionElement::evaluate(string input){ double answer; input += " "; istringstream iss( input ); string word; int cntr = 0,x; while (getline( iss, word, '(' )) { // cout << "word " << ++cntr << ": " << FunctionElement::trim( word ) << '\n'; ++cntr; if(cntr==2){ string y=FunctionElement::trim(word); y.substr(0, y.size()-1); istringstream buffer(y); // convert string to int buffer >> x; } } answer = log10 (x); // cout<<result; return answer; }
true
298921cbf85581d2a65c710d61ebd867ce5af5a3
C++
youZhuang/qco-editor
/plugin/coc/coc_animation/coc_color_transform.cpp
UTF-8
1,449
3
3
[]
no_license
/** * Project coc-animation * @author zhoubao */ #include "coc_color_transform.h" /** * ColorTransform implementation */ NS_COC_BEGIN /*static*/ColorTransform ColorTransform::Identity(1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f); void ColorTransform::contact(const ColorTransform& other) { rm *= other.rm; gm *= other.gm; bm *= other.bm; am *= other.am; ro = ro * other.rm + other.ro; go = go * other.gm + other.go; bo = bo * other.bm + other.bo; ao = ao * other.am + other.ao; } /** * 在a和b之间,按照比例ratio进行插值。 * 公式:this = a * ratio + b * (1 - ratio) */ void ColorTransform::interpolate(const ColorTransform &a, const ColorTransform &b, float ratio) { for(int i = 0; i < 16; ++i) { values[i] = a.values[i] * ratio + b.values[i] * (1.0f - ratio); } } void ColorTransform::transform(cocos2d::Color4F& color) const { color.r = color.r * rm + ro; color.g = color.g * gm + go; color.b = color.b * bm + bo; color.a = color.a * am + ao; } void ColorTransform::transform(cocos2d::Color4B& color) const { color.r = (GLubyte)cocos2d::clampf(color.r * rm + ro * 255, 0.0f, 255.0f); color.g = (GLubyte)cocos2d::clampf(color.g * gm + go * 255, 0.0f, 255.0f); color.b = (GLubyte)cocos2d::clampf(color.b * bm + bo * 255, 0.0f, 255.0f); color.a = (GLubyte)cocos2d::clampf(color.a * am + ao * 255, 0.0f, 255.0f); } NS_COC_END
true
62be367f106f0c34f04f12b144c8a440812bb88a
C++
RenatoBrittoAraujo/Competitive-Programming
/URI-Online-Judge/2311.cpp
UTF-8
436
2.578125
3
[]
no_license
#include <iostream> using namespace std; int main() { int c; cin>>c; string n; float d,s,ma,me,x; for(int i=0;i<c;i++){ s=0; cin >> n >> d; for(int i=0;i<7;i++){ cin >> x; if(i==0){ma=x;me=x;} s+=x; if(x>ma)ma=x; if(x<me)me=x; } s-=me+ma; s*=d; cout << n;printf(" %.2f\n",s); } return 0; }
true
e816cd442343f6db06a4ca29fd23277d1f705011
C++
osanseviero/C-training
/Foundations/Preparation/17.count_say.cpp
UTF-8
798
3.515625
4
[]
no_license
#include <iostream> #include <string> using namespace std; string cas(string str){ string str1; char ch=str[0]; int chn=1; for(int i = 1; i<=str.size();i++){ if (str[i]==ch){chn++;} else { char chr = chn+'0'; str1 = str1+ chr; str1 = str1+ch; ch = str[i]; chn=1; } } return str1; } string count_say(int n){ if (n==1) {return "1";} string str1 = "1"; string strn; for (int i=1; i<n;i++){ strn = cas(str1); str1 = strn; } return strn; } int main(){ int n1; cout << "Enter a number: "; cin >> n1; cout << count_say(n1) << endl; return 0; }
true
a0ca255ffa985fa9acf09404158728ddf8027427
C++
jo80923/SysCallSocketDemo
/src/server.cpp
UTF-8
5,341
2.875
3
[]
no_license
#include "server.h" void server::setMaxConnections(int connectionsAllowed){ this->connectionsAllowed = connectionsAllowed; } server::~server(){ if(this->sockfd != -1){ close(this->sockfd); } } server_tcp::server_tcp(){ this->port = -1; this->host = NULL; } server_tcp::server_tcp(char* host, int port){ this->port = port; this->host = host; } void server_tcp::runSysCallServer(){ struct addrinfo hints, *serv_info; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; std::string temp = std::to_string(this->port); getaddrinfo(this->host, temp.c_str(), &hints, &serv_info); this->sockfd = socket(serv_info->ai_family, serv_info->ai_socktype, serv_info->ai_protocol); if(bind(this->sockfd, serv_info->ai_addr, serv_info->ai_addrlen) == -1){ perror("ERROR binding"); exit(-1); } std::cout<<"Server accepting connections"<<std::endl; //plan on allowing more connections here with forks or a loop that has a timeout if(listen(this->sockfd, 1) == -1){ perror("ERROR listening"); exit(-1); } struct sockaddr_storage client_addr; socklen_t addr_size = sizeof(client_addr); int fd = accept(this->sockfd, (struct sockaddr* )&client_addr, &addr_size); if(fd == -1){ perror("ERROR accepting connection"); exit(-1); } if(fd != -1){ char hoststr[NI_MAXHOST]; char portstr[NI_MAXHOST]; getnameinfo((struct sockaddr *)&client_addr, addr_size, hoststr, sizeof(hoststr), portstr, sizeof(portstr), NI_NUMERICHOST | NI_NUMERICSERV); std::cout<<"Server has connected with "<<hoststr<<":"<<portstr<<std::endl; this->processCommands(fd); } else{ perror("ERROR in accepting client connection"); exit(-1); } close(fd); close(this->sockfd); std::cout<<"Server is no longer accepting connections"<<std::endl; } void server_tcp::processCommands(int fd){ std::string output; bool keepConnection = true; std::string command_str; char command[4096]; int counter = 0; int bytes = 0; while(keepConnection && fd != -1){ memset(&command[0], 0, 4096); bytes = recv(fd, command, 4096, 0); if(bytes == -1){ perror("Error recieving message from client"); break; } else if(counter > 10){ std::cout<<"ERROR in connection - 10+ blank messages"<<std::endl; break; } else if(bytes == 0){ counter++; continue; } else{ output.clear(); counter = 0; command_str = std::string(command); std::cout<<"-> "<<command_str<<std::endl; if(command_str == "q"){ output = "...Goodbye..."; keepConnection = false; } else{ output = exec(command); std::cout<<output<<std::endl; } if(send(fd, output.c_str(), output.length(), 0) == -1){ perror("ERROR sending message to client"); exit(-1); } } } } server_udp::server_udp(){ this->port = -1; this->host = NULL; } server_udp::server_udp(char* host, int port){ this->port = port; this->host = host; } void server_udp::runSysCallServer(){ struct addrinfo hints, *serv_info; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; hints.ai_flags = AI_PASSIVE; std::string temp = std::to_string(this->port); getaddrinfo(this->host, temp.c_str(), &hints, &serv_info); this->sockfd = socket(serv_info->ai_family, serv_info->ai_socktype, serv_info->ai_protocol); if(bind(this->sockfd, serv_info->ai_addr, serv_info->ai_addrlen) == -1){ perror("ERROR binding"); exit(-1); } std::cout<<"Server started"<<std::endl; this->processCommands(); close(this->sockfd); std::cout<<"Server is no longer active"<<std::endl; } void server_udp::processCommands(){ struct sockaddr_storage client_addr; socklen_t addr_size = sizeof(client_addr); std::string output; bool keepAlive = true; std::string command_str; char command[4096]; int counter = 0; int bytes = -1; while(keepAlive){ memset(&command[0], 0, 4096); bytes = recvfrom(this->sockfd, command, 4096, 0, (struct sockaddr*)&client_addr, &addr_size); if(bytes == -1){ continue; } else if(counter > 10){ std::cout<<"ERROR - 10+ blank messages"<<std::endl; break; } else if(bytes == 0){ counter++; continue; } else{ char hoststr[NI_MAXHOST]; char portstr[NI_MAXHOST]; counter = 0; getnameinfo((struct sockaddr *)&client_addr, addr_size, hoststr, sizeof(hoststr), portstr, sizeof(portstr), NI_NUMERICHOST | NI_NUMERICSERV); //std::string ip = inet_ntop(client_addr.ss_family, get_in_addr((struct sockaddr*)&client_addr),hoststr,sizeof(hoststr)); std::cout<<"Command recieved from "<<hoststr<<std::endl; command_str = std::string(command); std::cout<<"-> "<<command_str<<std::endl; if(command_str == "q"){ output = "...Goodbye..."; keepAlive = false; } else{ output.clear(); output = exec(command); std::cout<<output<<std::endl; } if(sendto(this->sockfd, output.c_str(), output.length(), 0, (struct sockaddr*)&client_addr, addr_size) == -1){ perror("ERROR sending message to client"); exit(-1); } } } }
true
b8dbb81dfafaede226339e47c5778117f5572196
C++
babakpst/Learning
/C++/112_beautiful_C++_STL_Algorithm/partial_sort.cpp
UTF-8
2,384
3.671875
4
[]
no_license
/* Babak Poursartip 11/19/2020 Reference: Beautiful C++: STL Algorithm PluralSight partial sort, partial_sort - if you have a large set and you do not want to sort the entire set, you can use partial sort. - ex: {1,5,4,2,9,7}, sort the first 3 elements: {1,2,4,9,5,7}, now the first three are ordered, and the rest are not necessarily in order, but they are all greater that the 3rd element. - partial sort takes three parameters: first and last are the iterators to the container, the middle indicate where the non-sortedness begins. - is_sorted_until: returns the iterator/pointer, in which the vector is sorted up to. - partial_sort_copy: copies from a first vector, indicated by its iterators, to a second copy, indicated by its iterators. The size of the vector that is being copied is determined by the size of the second vector. */ #include <iostream> #include <vector> #include <algorithm> #include <random> int main(){ std::cout << " starts here ...\n"; std::vector<int> myV{4,1,0,1,-2,3,7,-6,2,0,0,-9,9 }; // this is partial sort to all of the myV. Here the first 4 elements would be sorted, and the rest of the elements are larger, in no particular order. partial_sort(begin(myV), find(begin(myV), end(myV),-2), end(myV)); std::cout << " here is my vec: \n"; for (auto c:myV) std::cout << c << " "; std::cout << "\n\n"; //std::vector<int>::iterator breakpoint = is_sorted_until(begin(myV), end(myV)); auto breakpoint = is_sorted_until(begin(myV), end(myV)); std::cout << " sorted until: " << *breakpoint << "\n"; // ========================================== // shuffle for partial copy std::random_device randomdevice; // creating a random device std::mt19937 generator(randomdevice()); // creating a generator from the random device. // Here, it is a Mersenne Twister to use as a generator //The Mersenne Twister is a pseudorandom number generator. // 19937 is how many bits exist in the Mersenne prime. shuffle(begin(myV),end(myV), generator); std::cout << " here is after shuffle: \n"; for (auto c:myV) std::cout << c << " "; std::cout << "\n\n"; std::vector<int> nV(5); partial_sort_copy(begin(myV), end(myV), begin(nV), end(nV)); std::cout << " here is the new vec: \n"; for (auto c:nV) std::cout << c << " "; std::cout << "\n\n"; std::cout << " finished.\n"; return 0; }
true
0eacb0559096e63a4167d4a1426c55bc58a03b7a
C++
jeevan1133/CPP-2017
/main/fibonacci.cc
UTF-8
792
3.609375
4
[]
no_license
#include <iostream> class fib { private: size_t i {0}; size_t a {0}; size_t b {1}; public: fib() = default; explicit fib(size_t i_) : i{i_} {} size_t operator*() const { return b; } fib& operator++() { const size_t old_b {b}; b += a; a = old_b; ++i; return *this; } bool operator!=(const fib& o) const {return i != o.i; } bool operator==(const fib& o) const {return (!(operator!=(o)));} }; class fib_range { size_t end_n; public: fib_range(size_t end_n_) : end_n{end_n_} {} fib begin() const { return fib(); } fib end() const { return fib{end_n}; } }; int main() { for (size_t i : fib_range(10)) { std::cout << i << ", "; } std::cout << '\n'; }
true
a4aa4b1e6b0041666b063e7ec2d9bd25506af9c8
C++
shehabosama/ArrayList-implementation
/main.cpp
UTF-8
3,757
4.125
4
[]
no_license
#include <iostream> #include <cassert> using namespace std; class arrayListType { public: arrayListType(int size = 100); arrayListType(arrayListType& otherList); //copy constructor ~arrayListType(); // destructor bool isEmpty(); bool isFull(); int listSize(); int maxListSize(); void print(); bool isItemAtEqual(int loc, int item); void insertAt(int loc, int item); void insertEnd(int item); void removeAt(int loc); void retrieveAt(int loc, int& item); void replaceAt(int loc, int item); void clearList(); int seqSearch(int item); void insertNoDuplicate(int item); void remove(int item); private: int *list; //array to hold the list elements int length; //to store the length of the list int maxSize; //to store the maximum size of the list }; arrayListType::arrayListType(int size) { /* initilize the private members */ if(size <= 0) { cout << " Wrong Size " << endl; maxSize = 100; } else maxSize = size; length = 0; list = new int [maxSize]; assert(list != NULL); //terminate if unable to allocate memory space } arrayListType::arrayListType(arrayListType& otherList) { maxSize = otherList.maxSize; length = otherList.length; list = new int [maxSize]; //create the array assert(list != NULL); //terminate if unable to allocate memory space for(int j = 0; j < length; j++) //copy otherList list [j] = otherList.list[j]; } arrayListType::~arrayListType() { delete [] list; } bool arrayListType::isEmpty() { return (length == 0); } bool arrayListType::isFull() { return (length == maxSize); } int arrayListType::listSize() { return length; } int arrayListType::maxListSize() { return maxSize; } void arrayListType::print() { for(int i = 0; i < length; i++) cout<<list[i]<<" "; cout<<endl; } bool arrayListType::isItemAtEqual(int loc, int item) { if(loc < 0 || loc >= length) return false; else return (list[loc] == item); } void arrayListType::insertAt(int loc, int item) { if(isFull()) cout<<" The List is Full " << endl; else if(loc < 0 || loc > length) cout << "Out of Range " << endl; else { for(int i = length; i > loc; i--) list[i] = list[i - 1]; //shift right list[loc] = item; //insert the item at the specified position length++; //increment the length } } void arrayListType::insertEnd(int item) { if(isFull()) cout<<" The List is Full " << endl; else list[length++] = item; } void arrayListType::retrieveAt(int loc, int& item) { if(loc < 0 || loc >= length) cout << "Out of Range " << endl; else item = list[loc]; } void arrayListType::replaceAt(int loc, int item) { if(loc < 0 || loc >= length) cout << "Out of Range " << endl; else list[loc] = item; } void arrayListType::clearList() { length = 0; } int arrayListType::seqSearch(int item) { for(int loc = 0; loc < length; loc++) if(list[loc] == item) return loc; return -1; } void arrayListType::insertNoDuplicate(int item) { if(isFull()) cout<<" The List is Full " << endl; else { int flag = seqSearch(item); if(flag == -1) list[length++] = item; else cout<<"No duplicates are allowed."<<endl; } } void arrayListType::remove(int item) { int loc = seqSearch(item); if(loc == -1) cout<<"The item to be deleted is not in the list" << endl; else removeAt(loc); } void arrayListType::removeAt(int loc) { if(loc < 0 || loc >= length) cout<<"The location of the item to be removed is out of range."<<endl; else { for(int i = loc; i < length - 1; i++) list[i] = list[i+1]; length--; } } int main() { arrayListType lst1; for(int i = 0; i < 20; i++) lst1.insertAt(i, i * i); lst1.print(); int x; lst1.retrieveAt(10, x); cout<< x << endl; arrayListType lst2(lst1); lst2.print(); return 0; }
true
85f0563a1d5eca08f1564dda57e7d62be503d991
C++
Yobretaw/AlgorithmProblems
/Leetcode/DetailImplementation/palindromeNumber.cpp
UTF-8
1,069
3.734375
4
[]
no_license
#include <iostream> #include <vector> #include <string> #include <string.h> #include <sstream> #include <stack> #include <queue> #include <utility> #include <unordered_map> using namespace std; /* * Determine whether an integer is a palindrome. Do this without extra space. * * Some hints: * Could negative integers be palindromes? (ie, -1) * * If you are thinking of converting the integer to string, note the restriction of using extra space. * * You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", * you know that the reversed integer might overflow. How would you handle such case? * * There is a more generic way of solving this problem. */ bool isPalindrom(int x) { if(x < 0) return false; if(x < 10) return true; int d = 1; while(x / d >= 10) d *= 10; while(x > 0) { int q = x / d; int r = x % 10; if(q != r) return false; x = (x % d) / 10; d /= 100; } return true; } int main() { int x = 1234321; cout << isPalindrom(x) << endl; return 0; }
true
2a098353f6014f77908025e21ebacd9aedffd209
C++
crimsonskylark/win32experiments
/win32um/pe.cpp
UTF-8
687
2.53125
3
[]
no_license
#include "Introspect.hh" int introspect() { auto h = GetModuleHandle(NULL); if (!h) { std::cout << "unable to get module handle" << "\n"; return -1; } auto dosHdr = reinterpret_cast<IMAGE_DOS_HEADER*>(h); auto ntHdr = reinterpret_cast<IMAGE_NT_HEADERS*>( reinterpret_cast<uint8_t*>(dosHdr) + dosHdr->e_lfanew); auto sctHdr = reinterpret_cast<IMAGE_SECTION_HEADER*>(ntHdr + 1); std::cout << "ntHdr ptr: " << std::hex << ntHdr << "\n"; std::cout << "ntHdr+1 ptr: " << std::hex << ntHdr + 1 << "\n"; for (auto idx = 0; idx < ntHdr->FileHeader.NumberOfSections; idx++) { std::cout << sctHdr[idx].Name << "\n"; } std::cout << dosHdr->e_lfanew << "\n"; return 1; }
true
78e7becca1ab5743f9b77d5d16c9994c4eb67534
C++
peichangliang123/UE4
/Runtime/RenderCore/Public/RenderGraphBlackboard.h
UTF-8
4,494
2.890625
3
[]
no_license
// Copyright Epic Games, Inc. All Rights Reserved. #pragma once #include "RenderGraphDefinitions.h" #include "Misc/GeneratedTypeName.h" /** Declares a struct for use by the RDG blackboard. */ #define RDG_REGISTER_BLACKBOARD_STRUCT(StructType) \ template <> \ inline FString FRDGBlackboard::GetTypeName<StructType>() \ { \ return GetTypeName(TEXT(#StructType), TEXT(__FILE__), __LINE__); \ } /** The blackboard is a map of struct instances with a lifetime tied to a render graph allocator. It is designed * to solve cases where explicit marshaling of immutable data is undesirable. Structures are created once and the mutable * reference is returned. Only the immutable version is accessible from the blackboard. This constraint on mutability * is to discourage relying entirely on the blackboard. The mutable version should be marshaled around if needed. * Good candidates for the blackboard would be data that is created once and immutably fetched across the entire * renderer pipeline, where marshaling would create more maintenance burden than benefit. More constrained data * structures should be marshaled through function calls instead. * * Example of Usage: * * class FMyStruct * { * public: * FRDGTextureRef TextureA = nullptr; * FRDGTextureRef TextureB = nullptr; * FRDGTextureRef TextureC = nullptr; * }; * * RDG_REGISTER_BLACKBOARD_STRUCT(FMyStruct); * * static void InitStruct(FRDGBlackboard& GraphBlackboard) * { * auto& MyStruct = GraphBlackboard.Create<FMyStruct>(); * * //... * } * * static void UseStruct(const FRDGBlackboard& GraphBlackboard) * { * const auto& MyStruct = GraphBlackboard.GetChecked<FMyStruct>(); * * //... * } */ class FRDGBlackboard { public: /** Creates a new instance of a struct. Asserts if one already existed. */ template <typename StructType, typename... ArgsType> StructType& Create(ArgsType&&... Args) { using HelperStructType = TStruct<StructType>; const int32 StructIndex = GetStructIndex<StructType>(); if (StructIndex >= Blackboard.Num()) { Blackboard.SetNum(StructIndex + 1); } FStruct*& Result = Blackboard[StructIndex]; checkf(!Result, TEXT("RDGBlackboard duplicate Create called on struct '%s'. Only one Create call per struct is allowed."), GetGeneratedTypeName<StructType>()); Result = Allocator.Alloc<HelperStructType>(Forward<ArgsType&&>(Args)...); check(Result); return static_cast<HelperStructType*>(Result)->Struct; } /** Gets an immutable instance of the struct. Returns null if not present in the blackboard. */ template <typename StructType> const StructType* Get() const { using HelperStructType = TStruct<StructType>; const int32 StructIndex = GetStructIndex<StructType>(); if (StructIndex < Blackboard.Num()) { return &static_cast<const HelperStructType*>(Blackboard[StructIndex])->Struct; } return nullptr; } /** Gets an immutable instance of the struct. Asserts if not present in the blackboard. */ template <typename StructType> const StructType& GetChecked() const { const StructType* Struct = Get<StructType>(); checkf(Struct, TEXT("RDGBlackboard Get failed to find instance of struct '%s' in the blackboard."), GetGeneratedTypeName<StructType>()); return *Struct; } private: FRDGBlackboard(FRDGAllocator& InAllocator) : Allocator(InAllocator) {} void Clear() { Blackboard.Empty(); } struct FStruct { virtual ~FStruct() = default; }; template <typename StructType> struct TStruct final : public FStruct { template <typename... TArgs> FORCEINLINE TStruct(TArgs&&... Args) : Struct(Forward<TArgs&&>(Args)...) {} StructType Struct; }; template <typename StructType> static FString GetTypeName() { // Forces the compiler to only evaluate the assert on a concrete type. static_assert(sizeof(StructType) == 0, "Struct has not been registered with the RDG blackboard. Use RDG_REGISTER_BLACKBOARD_STRUCT to do this."); } static RENDERCORE_API FString GetTypeName(const TCHAR* ClassName, const TCHAR* FileName, uint32 LineNumber); static RENDERCORE_API uint32 AllocateIndex(FString&& TypeName); template <typename StructType> static uint32 GetStructIndex() { static uint32 Index = UINT_MAX; if (Index == UINT_MAX) { Index = AllocateIndex(GetTypeName<StructType>()); } return Index; } FRDGAllocator& Allocator; TArray<FStruct*, FRDGArrayAllocator> Blackboard; friend class FRDGBuilder; };
true
945e26cdd8bde6dfdf142aceef005d0bb97e7fe5
C++
ak566g/Data-Structures-and-Algorithms
/Searching/12_searchInRowAndColumnSortedMatrix.cpp
UTF-8
745
2.953125
3
[]
no_license
//by Ankita Gupta #include<bits/stdc++.h> using namespace std; bool findInMatrix(int **mat, int m, int n, int key) { int i=0,j=n-1; while((i<=m-1)&&(j>=0)) { if(mat[i][j]==key) return true; else if(mat[i][j]>key) { j--; } else { i++; } } return false; } int main() { //code int t; cin>>t; while(t--) { int m,n; cin>>m>>n; int **mat = new int*[m]; for(int i=0;i<m;i++) { mat[i]=new int[n]; for(int j=0;j<n;j++){ cin>>mat[i][j]; } } int key; cin>>key; cout<<findInMatrix(mat,m,n,key)<<"\n"; } return 0; }
true
8e5a635b1cb489cf73f1902164d315bb161aa6b8
C++
abhishek1711/COdeforces
/codeforces/claswtch.cpp
UTF-8
364
2.6875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main() { int n;cin>>n; int k = n - 100; int arr[200]; int cnt = 0; for(int i = k;i<n;i++){ int temp = i; int su = 0; while(temp!=0){ su = su +temp%10; temp = temp/10; } if(su + i ==n){ arr[cnt] = i; cnt++; } } cout<<cnt<<endl; for(int i=0;i<cnt;i++){ cout<<arr[i]<<" "; } }
true
d348cde628248f0ca298a90d9b4a22b599110b01
C++
dritchie/GraphicsEngine
/GraphicsEngine/Viewing/Camera.cpp
UTF-8
3,734
3.046875
3
[]
no_license
#include "Viewing/Camera.h" #include "Common/GL.h" #include "Math/Transform.h" #include "Eigen/Geometry" #include <iostream> using namespace Eigen; using namespace std; namespace GraphicsEngine { Camera::Camera() : eyePos(0.0f,0.0f,0.0f), lookAtPoint(0.0f,0.0f,-1.0f), lookVec(0.0f,0.0f,-1.0f), upVec(0.0f,1.0f,0.0f), leftVec(-1.0f,0.0f,0.0f), absUp(0.0f,1.0f,0.0f) { } Camera::Camera(const Vector3f& eye, const Vector3f& lookAt, const Vector3f& up, const Vector3f& worldUp) { Reset(eye, lookAt, up, worldUp); } Camera::Camera(float phi, float theta, float r) { // Polar to rectangular float rsintheta = r*sin(theta); Vector3f eye; eye.x() = rsintheta*cos(phi); eye.y() = rsintheta*sin(phi); eye.z() = r*cos(theta); Reset(eye, Vector3f::Zero(), Vector3f::UnitZ(), Vector3f::UnitZ()); } void Camera::Deserialize(istream& stream) { Vector3f eye, lookAt, up, worldUp; stream >> eye.x() >> eye.y() >> eye.z(); stream >> lookAt.x() >> lookAt.y() >> lookAt.z(); stream >> up.x() >> up.y() >> up.z(); stream >> worldUp.x() >> worldUp.y() >> worldUp.z(); Reset(eye, lookAt, up, worldUp); } void Camera::Serialize(ostream& stream) { stream << eyePos.x() << " " << eyePos.y() << " " << eyePos.z() << " " << lookAtPoint.x() << " " << lookAtPoint.y() << " " << lookAtPoint.z() << " " << upVec.x() << " " << upVec.y() << " " << upVec.z() << " " << absUp.x() << " " << absUp.y() << " " << absUp.z(); } void Camera::Reset(const Vector3f& eye, const Vector3f& lookAt, const Vector3f& up, const Vector3f& worldUp) { absUp = worldUp; eyePos = eye; lookAtPoint = lookAt; upVec = up.normalized(); lookVec = (lookAtPoint - eyePos).normalized(); leftVec = upVec.cross(lookVec); upVec = lookVec.cross(leftVec); } Transform Camera::GetLookAtTransform() const { return Transform::LookAt(eyePos, lookAtPoint, upVec); } void Camera::DollyLeft(float dist) { Vector3f offset = dist*leftVec; eyePos += offset; lookAtPoint += offset; } void Camera::DollyForward(float dist) { Vector3f offset = dist*lookVec; eyePos += offset; lookAtPoint += offset; } void Camera::DollyUp(float dist) { Vector3f offset = dist*upVec; eyePos += offset; lookAtPoint += offset; } void Camera::Zoom(float dist) { Vector3f offset = dist*lookVec; eyePos += offset; } void Camera::PanLeft(float theta) { Transform t = Transform::Rotation(absUp, theta, eyePos); Vector3f lookdir = lookAtPoint - eyePos; lookdir = t.TransformVector(lookdir); lookAtPoint = eyePos + lookdir; lookVec = lookdir.normalized(); upVec = t.TransformVector(upVec); leftVec = t.TransformVector(leftVec); } void Camera::PanUp(float theta) { Transform t = Transform::Rotation(leftVec, theta, eyePos); Vector3f lookdir = lookAtPoint - eyePos; lookdir = t.TransformVector(lookdir); lookAtPoint = eyePos + lookdir; lookVec = lookdir.normalized(); upVec = t.TransformVector(upVec); } void Camera::OrbitLeft(float theta) { Transform t = Transform::Rotation(absUp, theta, lookAtPoint); Vector3f invLookdir = eyePos - lookAtPoint; invLookdir = t.TransformVector(invLookdir); eyePos = lookAtPoint + invLookdir; lookVec = -invLookdir.normalized(); upVec = t.TransformVector(upVec); leftVec = t.TransformVector(leftVec); } void Camera::OrbitUp(float theta) { Transform t = Transform::Rotation(leftVec, theta, lookAtPoint); Vector3f invLookdir = eyePos - lookAtPoint; invLookdir = t.TransformVector(invLookdir); eyePos = lookAtPoint + invLookdir; lookVec = -invLookdir.normalized(); upVec = t.TransformVector(upVec); } void Camera::TrackTo(const Eigen::Vector3f& newPos) { Reset(newPos, lookAtPoint, upVec, absUp); } }
true
ebc3d58409b9c4c3802b0250fec2d96b623c26a1
C++
andars/advent-of-code
/2016/day13/task.cpp
UTF-8
1,352
2.859375
3
[]
no_license
#include <cstdio> #include <bitset> #include <queue> #include <map> int goal_x = 31; int goal_y = 39; int input = 1352; bool is_wall(int x, int y) { int t = x*x + 3*x + 2*x*y + y + y*y + input; std::bitset<64> b(t); return b.count() % 2 == 1; } void solve(int ix, int iy) { std::queue<std::tuple<int, int, int>> q; std::map<std::pair<int, int>, bool> seen; int delta[][2] = { { 1, 0}, {-1, 0}, { 0,-1}, { 0, 1}, }; int pt1 = -1; int pt2 = 0; int limit = 50; int d, x, y; q.emplace(0, ix, iy); seen.emplace(std::make_pair(ix,iy), true); while (!q.empty()) { std::tie(d,x,y) = q.front(); q.pop(); pt1 = std::max(pt1, d); if (d <= limit) pt2++; if (x == goal_x && y == goal_y) { break; } for (int i = 0; i < 4; i++) { int nx = x + delta[i][0]; int ny = y + delta[i][1]; auto p = std::make_pair(nx,ny); if (nx < 0 || ny < 0 || is_wall(nx,ny) || seen.count(p)) { continue; } seen.emplace(p, true); q.emplace(d+1, nx, ny); } } printf("Part 1: %d\n", pt1); printf("Part 2: %d\n", pt2); printf("Examined %lu total nodes\n", seen.size()); } int main() { solve(1,1); }
true
d1d516b7197903aa32b7577c153f7e64b90d5eb7
C++
SirichandanaSambatur/RCP
/Test-Packages/HtmlDocument.h
UTF-8
5,216
2.859375
3
[]
no_license
#pragma once ///////////////////////////////////////////////////////////////////////////////////////// // HtmlDocument.h - Used for creating HTML pages and all the required tags // // ver 1.0 // // Language: Visual C++ 2015 // // Platform: Macbook Pro, Windows 10 // // Application: Used to convert existing files into html pages that are published // // Author: Siri Chandana Sambatur, ssambatu@syr.edu // ///////////////////////////////////////////////////////////////////////////////////////// /* Package Operations: ================== This package is used to create HTML pages, that can be viewed on browser. It consists of all the methods that help in creating the required tags of HTML. It will also include the required CSS and JS for the HTML files. Public Interface: ================= Build Process: ============== Required files Build commands devenv CodeAnalyzer.sln /rebuild debug Maintenance History: ==================== ver 1.0 : 02 Apr 2017 - first release */ #include<iostream> #include<string> #include<vector> namespace CodePublisher { ///////////////////////////////////////////////////////////////////////////////////////// // HtmlDocument class helps creating Html pages that follow the Html syntax and semantics // - this class is used to create various Html tags (start and end) // - it factilates in creating the html file structure // class HtmlDocument { public: std::string createHtmlStartTag(); std::string createHeadSection(std::vector<std::string> cssList, std::vector<std::string> jsList); std::string createBodyStartTag(); std::string createBodyEndTag(); std::string createAnchorTag(std::string className, std::string name, std::string link); std::string createHtmlEndTag(); std::string createPreTag(std::string content); std::string createScriptTag(std::string name); std::string createDivision(std::string id, std::string className, std::string bodyDiv); std::string createLiTag(std::string t); std::string createOLTag(std::string t, std::string className, std::string n); std::string createButton(std::string var); std::string createDivIdStart(std::string v); std::string createDivIdEnd(); }; std::string HtmlDocument::createDivIdStart(std::string v) { return "<div id = \"collapsible" + v + "\">"; } std::string HtmlDocument::createDivIdEnd() { return "</div>"; } //creating Html button std::string HtmlDocument::createButton(std::string var) { std::string content="<br><button id=\"collapseInfo\" onclick =\"myFunction('collapsible"+var+"')\">show</button>"; return content; } //creating html start tag std::string HtmlDocument::createHtmlStartTag() { return "<!DOCTYPE html><br><html>"; } //html end tag std::string HtmlDocument::createHtmlEndTag() { return "</html>"; } //head section and include all necessary links to external files std::string HtmlDocument::createHeadSection(std::vector<std::string> cssList, std::vector<std::string> jsList) { std::string headContent = "<head>"; for (int i = 0; i < cssList.size(); i++) { headContent += "<link rel='stylesheet' type='text/css' href='" + cssList[i] + "'>\n"; } for (int j = 0; j < jsList.size(); j++) { headContent += createScriptTag(jsList[j]); } headContent += "</head>"; return headContent; } //body tag and necessary feature if any std::string HtmlDocument::createBodyStartTag() { return "<body>"; } //end the body section of html file std::string HtmlDocument::createBodyEndTag() { return "</body>"; } //create the necessary links std::string HtmlDocument::createAnchorTag(std::string className, std::string name, std::string link) { std::string tag = ""; tag = "<a "; if (className != "") tag += "class='" + className + "'"; tag += "href='" + link + "'>" + name; tag = tag + "</a>"; return tag; } //creating pre tag of html files std::string HtmlDocument::createPreTag(std::string content) { std::string tag = "<pre>" + content + "</pre>"; return tag; } //creating script tag to add any js functions or external js files std::string HtmlDocument::createScriptTag(std::string name) { std::string tag = "<script src='" + name + "'></script>"; return tag; } std::string HtmlDocument::createDivision(std::string id, std::string className, std::string bodyDiv) { std::string tag = "<div "; if (id != "") { tag = tag + "id='" + id + "'"; } if (className != "") { tag = tag + "class='" + className + "'"; } tag = tag + ">" + bodyDiv + "</div>"; return tag; } std::string HtmlDocument::createLiTag(std::string t) { std::string ol = "<li>" + t + "</li>"; return ol; } std::string HtmlDocument::createOLTag(std::string t, std::string className, std::string n) { std::string ol = "<ol class='" + className; ol += "' type='" + t + "'>" + n + "</ol>"; return ol; } }
true
f51d07ab3a73c84d3378cf9c30ed398accacb4df
C++
Cirnoo/game-server
/Packdef.h
GB18030
5,412
2.546875
3
[]
no_license
#pragma once #include <string> #include <iostream> #include <QString> #include <array> #define PRINT(a) std::cout<<a<<"\n"; #define _DEF_PORT 1234 #define _SERVER_IP "127.0.0.1" #define _DEF_CLIENTPORT 2000 #define _DEF_SERVERPORT 10086 #define _DEF_SIZE 64 #define _DEF_ROOMBUFFERSIZE 550*1000 #define _DEF_NUM 10 #define _DEF_SQLLEN 100 #define USER_LENGTH 10 using std::wstring; enum class MS_TYPE :unsigned char { REGISTER_RQ, REGISTER_RE_T, REGISTER_RE_F, LOGIN_RQ, LOGIN_RE_T, LOGIN_RE_F, ADD_ROOM, GET_ROOM_LIST, CREATE_ROOM, CREATE_ROOM_RE_T, CREATE_ROOM_RE_F, ENTER_ROOM, ENTER_ROOM_RE_T, ENTER_ROOM_RE_F, MATE_INFO_UPDATE, LEAVE_ROOM, UPDATE_ROOM, GAME_START, ALLOC_POKER, // SELECT_LANDLORD_CALL, //ѯǷе SELECT_LANDLORD_ROB, //ѯǷ WANT_LANDLORD, //е/ NOT_WANT_LANDLORD, /// SET_LANDLORD, //е׶ PLAY_CARD, PASS, GAME_WIN_RQ, GAME_OFFLINE, GAME_RESTRT, HEARTBEAT,// }; using std::string; struct USER_BUF { wchar_t buf[USER_LENGTH]; USER_BUF() { Clear(); } USER_BUF(wstring str) { for(int i=0;i<USER_LENGTH;i++) { buf[i]=0; } str.copy(buf, str.size(), 0); } USER_BUF & operator=(const USER_BUF & u ) { memcpy(buf,u.buf,USER_LENGTH); return *this; } USER_BUF & operator=(const wstring & str) { str.copy(buf, str.size(), 0); return *this; } wstring GetStr() const { wstring str=wstring(buf); return str; } void Clear() { memset(buf,0,sizeof(buf)); } }; enum class CardType : unsigned char { Heart , Spade , Diamond , Club , Joker , }; enum class PokerPoints : unsigned char { Three=3,Four,Five,Six,Seven,Eight,Nine,Ten,jack,Queen,King,Ace,Two,Black_Joker,Red_Joker }; struct Poker //˿ { CardType c_type; PokerPoints point; bool hide; //Ƿ bool check; //Ƿѡ bool select; //Ƿ񱻿ѡ Poker(){InitVar();} Poker(char num) { InitVar(); Q_ASSERT(num>=0&&num<54); if (num<52) { c_type=CardType(num/13); point=PokerPoints(num%13); } else { c_type=CardType::Joker; point=PokerPoints(num-52+13); } } Poker(CardType t,PokerPoints p) { InitVar(); c_type=t; point=p; } int operator-(const Poker & p) const { return p.GetPointVal()-this->GetPointVal(); } bool operator==(const Poker & p) const { return point==p.point; } char toNum() const { return c_type==CardType::Joker?52-13+(char)point:13*(char)c_type+(char)point; } char GetPointVal() const { return static_cast<char> (point); } private: void InitVar() { hide=false;check=false;select=false; } }; enum ArrayType : unsigned char { // ,,,,һ,,˳,˫˳,˳,ɻ,Ĵ,ը,ը //Ӣ, }; struct CardArray //Ҫ { char cards[20]; //һ20 ArrayType type; // unsigned char point; //ĴС unsigned char num; //Ƹ CardArray(const std::vector<Poker> & vec, ArrayType _type,unsigned char _point ) { memset(cards,0,sizeof(cards)); num=vec.size(); type=_type;point=_point; for (int i=0;i<num;i++) { cards[i]=vec[i].toNum(); } } }; enum PlayerText { CALL_LANDLORD,NOT_CALL,ROB_LANDLORD,NOT_ROB,CARD_PASS }; struct GAME_PROCESS { char player_pos; PlayerText text; CardArray card_arr; }; struct USER_INFO { USER_BUF name; USER_BUF password; USER_INFO() { name.Clear(); password.Clear(); } USER_INFO(USER_BUF n,USER_BUF p) { name=n;password=p; } void operator=(const USER_INFO & u ) { name=u.name;password=u.password; } }; enum class ClientState //ͻ״̬ { Other, GameRoom, //Ϸ Gaming //Ϸ }; struct ROOM_LIST_INFO { USER_BUF name; unsigned char num; }; struct MATE_INFO { USER_BUF name; char pos; }; struct PLAYER_INFO { USER_BUF name,room_name; char pos; }; struct ENTER_ROOM_RE { USER_BUF mate_name[3]; char player_pos; }; class QTcpSocket; struct CLIENT_INFO { wstring username,room_name; string ip; char room_pos; unsigned short port; ClientState state=ClientState::Other; void UpdateClientInfo(const USER_BUF & name,const char player_nums) // { room_name=name.GetStr(); room_pos=player_nums-1; } }; const uint MAX_BUF_SIZE=sizeof(ROOM_LIST_INFO)*3; struct DATA_PACKAGE { struct DATA_BUF { char buf[MAX_BUF_SIZE]; DATA_BUF() { memset(buf,0,MAX_BUF_SIZE); } template <class T> DATA_BUF(const T & u) { int i=0; for(i=0;i<sizeof(u);i++) { buf[i]=(*((char *)&u+i)); } memset(buf+i,0,MAX_BUF_SIZE-i); } void Clear() { memset(buf,0,sizeof(buf)); } }; MS_TYPE ms_type; DATA_BUF buf; template <class T> DATA_PACKAGE(MS_TYPE type,T & u) { ms_type=type; buf=u; } DATA_PACKAGE() { ms_type=MS_TYPE::HEARTBEAT; buf.Clear(); } };
true
69be63c2ff1b60ee925ffc1e722cc7f449d05340
C++
rdfostrich/ostrich
/src/test/cpp/controller/controller.cc
UTF-8
78,252
2.546875
3
[ "MIT" ]
permissive
#include <gtest/gtest.h> #include "../../../main/cpp/controller/controller.h" #include "../../../main/cpp/snapshot/vector_triple_iterator.h" #include "../../../main/cpp/dictionary/dictionary_manager.h" #define BASEURI "<http://example.org>" #define TESTPATH "./" // The fixture for testing class controller-> class ControllerTest : public ::testing::Test { protected: Controller* controller; ControllerTest() : controller(new Controller(TESTPATH)) {} virtual void SetUp() { } virtual void TearDown() { Controller::cleanup(TESTPATH, controller); } }; TEST_F(ControllerTest, GetEdge) { Triple t; // Build a snapshot std::vector<TripleString> triples; triples.push_back(TripleString("<a>", "<a>", "<a>")); triples.push_back(TripleString("<a>", "<a>", "<b>")); triples.push_back(TripleString("<a>", "<a>", "<c>")); VectorTripleIterator* it = new VectorTripleIterator(triples); controller->get_snapshot_manager()->create_snapshot(0, it, BASEURI); PatchTreeManager* patchTreeManager = controller->get_patch_tree_manager(); DictionaryManager *dict = controller->get_snapshot_manager()->get_dictionary_manager(0); // Request version 1 (after snapshot before a patch id added) TripleIterator* it1 = controller->get_version_materialized(Triple("", "", "", dict), 0, 1); ASSERT_EQ(true, it1->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <a>.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, it1->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <b>.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, it1->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <c>.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(false, it1->next(&t)) << "Iterator should be finished"; // Apply a simple patch PatchSorted patch1(dict); patch1.add(PatchElement(Triple("<a>", "<a>", "<b>", dict), false)); patchTreeManager->append(patch1, 1, dict); // Request version -1 (before first snapshot) TripleIterator* it0 = controller->get_version_materialized(Triple("", "", "", dict), 0, -1); ASSERT_EQ(false, it0->next(&t)) << "Iterator should be empty"; // Request version 2 (after last patch) TripleIterator* it2 = controller->get_version_materialized(Triple("", "", "", dict), 0, 2); ASSERT_EQ(true, it2->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <a>.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, it2->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <c>.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(false, it2->next(&t)) << "Iterator should be finished"; } TEST_F(ControllerTest, PatchBuilder) { controller->new_patch_bulk() ->addition(TripleString("a", "a", "a")) ->addition(TripleString("b", "b", "b")) ->addition(TripleString("c", "c", "c")) ->commit(); controller->new_patch_bulk() ->deletion(TripleString("a", "a", "a")) ->addition(TripleString("d", "d", "d")) ->deletion(TripleString("c", "c", "c")) ->commit(); DictionaryManager *dict = controller->get_snapshot_manager()->get_dictionary_manager(0); ASSERT_EQ(3, controller->get_version_materialized_count(Triple("", "", "", dict), 0).first) << "Count is incorrect"; ASSERT_EQ(2, controller->get_version_materialized_count(Triple("", "", "", dict), 1).first) << "Count is incorrect"; } TEST_F(ControllerTest, PatchBuilderStreaming) { controller->new_patch_stream() ->addition(TripleString("a", "a", "a")) ->addition(TripleString("b", "b", "b")) ->addition(TripleString("c", "c", "c")) ->close(); controller->new_patch_stream() ->deletion(TripleString("a", "a", "a")) ->addition(TripleString("d", "d", "d")) ->deletion(TripleString("c", "c", "c")) ->close(); DictionaryManager *dict = controller->get_snapshot_manager()->get_dictionary_manager(0); ASSERT_EQ(3, controller->get_version_materialized_count(Triple("", "", "", dict), 0).first) << "Count is incorrect"; ASSERT_EQ(2, controller->get_version_materialized_count(Triple("", "", "", dict), 1).first) << "Count is incorrect"; } TEST_F(ControllerTest, GetVersionMaterializedSimple) { // Build a snapshot std::vector<TripleString> triples; triples.push_back(TripleString("<a>", "<a>", "<a>")); triples.push_back(TripleString("<a>", "<a>", "<b>")); triples.push_back(TripleString("<a>", "<a>", "<c>")); VectorTripleIterator* it = new VectorTripleIterator(triples); controller->get_snapshot_manager()->create_snapshot(0, it, BASEURI); PatchTreeManager* patchTreeManager = controller->get_patch_tree_manager(); DictionaryManager *dict = controller->get_snapshot_manager()->get_dictionary_manager(0); // Apply a simple patch PatchSorted patch1(dict); patch1.add(PatchElement(Triple("<a>", "<a>", "<b>", dict), false)); patchTreeManager->append(patch1, 1, dict); // Expected version 0: // <a> <a> <a> // <a> <a> <b> // <a> <a> <c> // Expected version 1: // <a> <a> <a> // <a> <a> <c> Triple t; // Request version 0 (snapshot) ASSERT_EQ(3, controller->get_version_materialized_count(Triple("", "", "", dict), 0).first) << "Count is incorrect"; TripleIterator* it0 = controller->get_version_materialized(Triple("", "", "", dict), 0, 0); ASSERT_EQ(true, it0->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <a>.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, it0->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <b>.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, it0->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <c>.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(false, it0->next(&t)) << "Iterator should be finished"; // Request version 1 (patch) ASSERT_EQ(2, controller->get_version_materialized_count(Triple("", "", "", dict), 1).first) << "Count is incorrect"; TripleIterator* it1 = controller->get_version_materialized(Triple("", "", "", dict), 0, 1); ASSERT_EQ(true, it1->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <a>.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, it1->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <c>.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(false, it1->next(&t)) << "Iterator should be finished"; // Request version 1 (patch) at offset 1 ASSERT_EQ(2, controller->get_version_materialized_count(Triple("", "", "", dict), 1).first) << "Count is incorrect"; TripleIterator* it2 = controller->get_version_materialized(Triple("", "", "", dict), 1, 1); ASSERT_EQ(true, it2->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <c>.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(false, it2->next(&t)) << "Iterator should be finished"; // Request version 0 (snapshot) for ? ? <c> ASSERT_EQ(1, controller->get_version_materialized_count(Triple("", "", "<c>", dict), 0).first) << "Count is incorrect"; TripleIterator* it3 = controller->get_version_materialized(Triple("", "", "<c>", dict), 0, 0); ASSERT_EQ(true, it3->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <c>.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(false, it3->next(&t)) << "Iterator should be finished"; // Request version 1 (patch) for ? ? <c> ASSERT_EQ(1, controller->get_version_materialized_count(Triple("", "", "<c>", dict), 1).first) << "Count is incorrect"; TripleIterator* it4 = controller->get_version_materialized(Triple("", "", "<c>", dict), 0, 1); ASSERT_EQ(true, it4->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <c>.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(false, it4->next(&t)) << "Iterator should be finished"; } TEST_F(ControllerTest, GetVersionMaterializedComplex1) { // Build a snapshot std::vector<TripleString> triples; triples.push_back(TripleString("g", "p", "o")); triples.push_back(TripleString("s", "z", "o")); triples.push_back(TripleString("h", "z", "o")); triples.push_back(TripleString("h", "p", "o")); VectorTripleIterator* it = new VectorTripleIterator(triples); controller->get_snapshot_manager()->create_snapshot(0, it, BASEURI); PatchTreeManager* patchTreeManager = controller->get_patch_tree_manager(); DictionaryManager *dict = controller->get_snapshot_manager()->get_dictionary_manager(0); PatchSorted patch1(dict); patch1.add(PatchElement(Triple("g", "p", "o", dict), false)); patch1.add(PatchElement(Triple("a", "p", "o", dict), true)); patchTreeManager->append(patch1, 1, dict); PatchSorted patch2(dict); patch2.add(PatchElement(Triple("s", "z", "o", dict), false)); patch2.add(PatchElement(Triple("s", "a", "o", dict), true)); patchTreeManager->append(patch2, 1, dict); PatchSorted patch3(dict); patch3.add(PatchElement(Triple("g", "p", "o", dict), false)); patch3.add(PatchElement(Triple("a", "p", "o", dict), false)); patch3.add(PatchElement(Triple("h", "z", "o", dict), false)); patch3.add(PatchElement(Triple("l", "a", "o", dict), true)); patchTreeManager->append(patch3, 2, dict); PatchSorted patch4(dict); patch4.add(PatchElement(Triple("h", "p", "o", dict), false)); patch4.add(PatchElement(Triple("s", "z", "o", dict), false)); patchTreeManager->append(patch4, 4, dict); PatchSorted patch5(dict); patch5.add(PatchElement(Triple("h", "p", "o", dict), true)); patchTreeManager->append(patch5, 5, dict); PatchSorted patch6(dict); patch6.add(PatchElement(Triple("a", "p", "o", dict), true)); patchTreeManager->append(patch6, 6, dict); // Expected version 0: // g p o // h p o // h z o // s z o // Expected version 1: // h p o // h z o // a p o (+) // s a o (+) // Expected version 2: // h p o // l a o (+) // s a o (+) Triple t; // Request version 0 (snapshot) ASSERT_EQ(4, controller->get_version_materialized_count(Triple("", "", "", dict), 0).first) << "Count is incorrect"; TripleIterator* it0 = controller->get_version_materialized(Triple("", "", "", dict), 0, 0); ASSERT_EQ(true, it0->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("g p o.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, it0->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("h p o.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, it0->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("h z o.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, it0->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("s z o.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(false, it0->next(&t)) << "Iterator should be finished"; // Request version 1 (patch) ASSERT_EQ(4, controller->get_version_materialized_count(Triple("", "", "", dict), 1).first) << "Count is incorrect"; TripleIterator* it1 = controller->get_version_materialized(Triple("", "", "", dict), 0, 1); ASSERT_EQ(true, it1->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("h p o.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, it1->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("h z o.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, it1->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("a p o.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, it1->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("s a o.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(false, it1->next(&t)) << "Iterator should be finished"; // Request version 1 (patch), offset 1 TripleIterator* it2 = controller->get_version_materialized(Triple("", "", "", dict), 1, 1); ASSERT_EQ(true, it2->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("h z o.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, it2->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("a p o.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, it2->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("s a o.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(false, it2->next(&t)) << "Iterator should be finished"; // Request version 1 (patch), offset 2 TripleIterator* it3 = controller->get_version_materialized(Triple("", "", "", dict), 2, 1); ASSERT_EQ(true, it3->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("a p o.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, it3->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("s a o.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(false, it3->next(&t)) << "Iterator should be finished"; // Request version 1 (patch), offset 3 TripleIterator* it4 = controller->get_version_materialized(Triple("", "", "", dict), 3, 1); ASSERT_EQ(true, it4->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("s a o.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(false, it4->next(&t)) << "Iterator should be finished"; // Request version 1 (patch), offset 4 TripleIterator* it5 = controller->get_version_materialized(Triple("", "", "", dict), 4, 1); ASSERT_EQ(false, it5->next(&t)) << "Iterator should be finished"; // Request version 2 (patch) ASSERT_EQ(3, controller->get_version_materialized_count(Triple("", "", "", dict), 2).first) << "Count is incorrect"; TripleIterator* it6 = controller->get_version_materialized(Triple("", "", "", dict), 0, 2); ASSERT_EQ(true, it6->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("h p o.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, it6->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("l a o.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, it6->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("s a o.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(false, it6->next(&t)) << "Iterator should be finished"; // Request version 2 (patch), offset 1 TripleIterator* it7 = controller->get_version_materialized(Triple("", "", "", dict), 1, 2); ASSERT_EQ(true, it7->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("l a o.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, it7->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("s a o.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(false, it7->next(&t)) << "Iterator should be finished"; // Request version 2 (patch), offset 2 TripleIterator* it8 = controller->get_version_materialized(Triple("", "", "", dict), 2, 2); ASSERT_EQ(true, it8->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("s a o.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(false, it8->next(&t)) << "Iterator should be finished"; // Request version 2 (patch), offset 3 TripleIterator* it9 = controller->get_version_materialized(Triple("", "", "", dict), 3, 2); ASSERT_EQ(false, it9->next(&t)) << "Iterator should be finished"; } TEST_F(ControllerTest, GetVersionMaterializedComplex2) { // Build a snapshot std::vector<TripleString> triples; triples.push_back(TripleString("g", "p", "o")); triples.push_back(TripleString("s", "z", "o")); triples.push_back(TripleString("h", "z", "o")); triples.push_back(TripleString("h", "p", "o")); VectorTripleIterator* it = new VectorTripleIterator(triples); controller->get_snapshot_manager()->create_snapshot(0, it, BASEURI); PatchTreeManager* patchTreeManager = controller->get_patch_tree_manager(); DictionaryManager *dict = controller->get_snapshot_manager()->get_dictionary_manager(0); PatchSorted patch1(dict); patch1.add(PatchElement(Triple("g", "p", "o", dict), false)); patch1.add(PatchElement(Triple("a", "p", "o", dict), true)); patchTreeManager->append(patch1, 1, dict); PatchSorted patch2(dict); patch2.add(PatchElement(Triple("s", "z", "o", dict), false)); patch2.add(PatchElement(Triple("s", "a", "o", dict), true)); patchTreeManager->append(patch2, 1, dict); PatchSorted patch3(dict); patch3.add(PatchElement(Triple("g", "p", "o", dict), false)); patch3.add(PatchElement(Triple("a", "p", "o", dict), false)); patch3.add(PatchElement(Triple("h", "z", "o", dict), false)); patch3.add(PatchElement(Triple("l", "a", "o", dict), true)); patchTreeManager->append(patch3, 2, dict); PatchSorted patch4(dict); patch4.add(PatchElement(Triple("h", "p", "o", dict), false)); patch4.add(PatchElement(Triple("s", "z", "o", dict), false)); patchTreeManager->append(patch4, 4, dict); PatchSorted patch5(dict); patch5.add(PatchElement(Triple("h", "p", "o", dict), true)); patchTreeManager->append(patch5, 5, dict); PatchSorted patch6(dict); patch6.add(PatchElement(Triple("a", "p", "o", dict), true)); patchTreeManager->append(patch6, 6, dict); // Expected version 0: // g p o // h p o // h z o // s z o // Expected version 1: // h p o // h z o // a p o (+) // s a o (+) // Expected version 2: // h p o // l a o (+) // s a o (+) Triple t; // Request version 0 (snapshot) ASSERT_EQ(4, controller->get_version_materialized_count(Triple("", "", "o", dict), 0).first) << "Count is incorrect"; TripleIterator* it0 = controller->get_version_materialized(Triple("", "", "o", dict), 0, 0); ASSERT_EQ(true, it0->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("g p o.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, it0->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("h p o.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, it0->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("h z o.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, it0->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("s z o.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(false, it0->next(&t)) << "Iterator should be finished"; // Request version 1 (patch) ASSERT_EQ(4, controller->get_version_materialized_count(Triple("", "", "o", dict), 1).first) << "Count is incorrect"; TripleIterator* it1 = controller->get_version_materialized(Triple("", "", "o", dict), 0, 1); ASSERT_EQ(true, it1->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("h p o.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, it1->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("h z o.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, it1->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("a p o.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, it1->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("s a o.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(false, it1->next(&t)) << "Iterator should be finished"; // Request version 1 (patch), offset 1 TripleIterator* it2 = controller->get_version_materialized(Triple("", "", "o", dict), 1, 1); ASSERT_EQ(true, it2->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("h z o.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, it2->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("a p o.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, it2->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("s a o.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(false, it2->next(&t)) << "Iterator should be finished"; // Request version 1 (patch), offset 2 TripleIterator* it3 = controller->get_version_materialized(Triple("", "", "o", dict), 2, 1); ASSERT_EQ(true, it3->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("a p o.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, it3->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("s a o.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(false, it3->next(&t)) << "Iterator should be finished"; // Request version 1 (patch), offset 3 TripleIterator* it4 = controller->get_version_materialized(Triple("", "", "o", dict), 3, 1); ASSERT_EQ(true, it4->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("s a o.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(false, it4->next(&t)) << "Iterator should be finished"; // Request version 1 (patch), offset 4 TripleIterator* it5 = controller->get_version_materialized(Triple("", "", "o", dict), 4, 1); ASSERT_EQ(false, it5->next(&t)) << "Iterator should be finished"; // Request version 2 (patch) ASSERT_EQ(3, controller->get_version_materialized_count(Triple("", "", "o", dict), 2).first) << "Count is incorrect"; TripleIterator* it6 = controller->get_version_materialized(Triple("", "", "o", dict), 0, 2); ASSERT_EQ(true, it6->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("h p o.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, it6->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("l a o.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, it6->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("s a o.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(false, it6->next(&t)) << "Iterator should be finished"; // Request version 2 (patch), offset 1 TripleIterator* it7 = controller->get_version_materialized(Triple("", "", "o", dict), 1, 2); ASSERT_EQ(true, it7->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("l a o.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, it7->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("s a o.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(false, it7->next(&t)) << "Iterator should be finished"; // Request version 2 (patch), offset 2 TripleIterator* it8 = controller->get_version_materialized(Triple("", "", "o", dict), 2, 2); ASSERT_EQ(true, it8->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("s a o.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(false, it8->next(&t)) << "Iterator should be finished"; // Request version 2 (patch), offset 3 TripleIterator* it9 = controller->get_version_materialized(Triple("", "", "o", dict), 3, 2); ASSERT_EQ(false, it9->next(&t)) << "Iterator should be finished"; } TEST_F(ControllerTest, GetVersionMaterializedComplex3) { // Build a snapshot std::vector<TripleString> triples; triples.push_back(TripleString("g", "p", "o")); triples.push_back(TripleString("s", "z", "o")); triples.push_back(TripleString("h", "z", "o")); triples.push_back(TripleString("h", "p", "o")); VectorTripleIterator* it = new VectorTripleIterator(triples); controller->get_snapshot_manager()->create_snapshot(0, it, BASEURI); PatchTreeManager* patchTreeManager = controller->get_patch_tree_manager(); DictionaryManager *dict = controller->get_snapshot_manager()->get_dictionary_manager(0); PatchSorted patch1(dict); patch1.add(PatchElement(Triple("g", "p", "o", dict), false)); patch1.add(PatchElement(Triple("a", "p", "o", dict), true)); patchTreeManager->append(patch1, 1, dict); PatchSorted patch2(dict); patch2.add(PatchElement(Triple("s", "z", "o", dict), false)); patch2.add(PatchElement(Triple("s", "a", "o", dict), true)); patchTreeManager->append(patch2, 1, dict); PatchSorted patch3(dict); patch3.add(PatchElement(Triple("g", "p", "o", dict), false)); patch3.add(PatchElement(Triple("a", "p", "o", dict), false)); patch3.add(PatchElement(Triple("h", "z", "o", dict), false)); patch3.add(PatchElement(Triple("l", "a", "o", dict), true)); patchTreeManager->append(patch3, 2, dict); PatchSorted patch4(dict); patch4.add(PatchElement(Triple("h", "p", "o", dict), false)); patch4.add(PatchElement(Triple("s", "z", "o", dict), false)); patchTreeManager->append(patch4, 4, dict); PatchSorted patch5(dict); patch5.add(PatchElement(Triple("h", "p", "o", dict), true)); patchTreeManager->append(patch5, 5, dict); PatchSorted patch6(dict); patch6.add(PatchElement(Triple("a", "p", "o", dict), true)); patchTreeManager->append(patch6, 6, dict); // --- filtered by s ? ? // Expected version 0: // s z o // Expected version 1: // s a o (+) // Expected version 2: // s a o (+) Triple t; // Request version 0 (snapshot) ASSERT_EQ(1, controller->get_version_materialized_count(Triple("s", "", "", dict), 0).first) << "Count is incorrect"; TripleIterator* it0 = controller->get_version_materialized(Triple("s", "", "", dict), 0, 0); ASSERT_EQ(true, it0->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("s z o.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(false, it0->next(&t)) << "Iterator should be finished"; // Request version 1 (patch) ASSERT_EQ(1, controller->get_version_materialized_count(Triple("s", "", "", dict), 1).first) << "Count is incorrect"; TripleIterator* it1 = controller->get_version_materialized(Triple("s", "", "", dict), 0, 1); ASSERT_EQ(true, it1->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("s a o.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(false, it1->next(&t)) << "Iterator should be finished"; // Request version 1 (patch), offset 1 TripleIterator* it2 = controller->get_version_materialized(Triple("s", "", "", dict), 1, 1); ASSERT_EQ(false, it2->next(&t)) << "Iterator should be finished"; // Request version 2 (patch) ASSERT_EQ(1, controller->get_version_materialized_count(Triple("s", "", "", dict), 2).first) << "Count is incorrect"; TripleIterator* it6 = controller->get_version_materialized(Triple("s", "", "", dict), 0, 2); ASSERT_EQ(true, it6->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("s a o.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(false, it6->next(&t)) << "Iterator should be finished"; // Request version 2 (patch), offset 1 TripleIterator* it7 = controller->get_version_materialized(Triple("s", "", "", dict), 1, 2); ASSERT_EQ(false, it7->next(&t)) << "Iterator should be finished"; } TEST_F(ControllerTest, EdgeCaseVersionMaterialized1) { /* * This tests the special case where there are extra deletions that * need to be taken into account when the first deletion count is applied * as offset to the snapshot iterator. * * In this case, for offset = 3 we will find in the snapshot element "3". * The number of deletions before this element is 3, so the new snapshot offset becomes 6 (= 3 + 3). * The first element in this new snapshot iterator is "6", which is wrong because we expect "8". * This is because deletion elements "4" and "5" weren't taken into account when applying this new offset. * This is why we have to _loop_ when applying offsets until we apply one that contains no new deletions relative * to the previous offset. */ // Build a snapshot std::vector<TripleString> triples; triples.push_back(TripleString("0", "0", "0")); triples.push_back(TripleString("1", "1", "1")); triples.push_back(TripleString("2", "2", "2")); triples.push_back(TripleString("3", "3", "3")); triples.push_back(TripleString("4", "4", "4")); triples.push_back(TripleString("5", "5", "5")); triples.push_back(TripleString("6", "6", "6")); triples.push_back(TripleString("7", "7", "7")); triples.push_back(TripleString("8", "8", "8")); triples.push_back(TripleString("9", "9", "9")); VectorTripleIterator *it = new VectorTripleIterator(triples); controller->get_snapshot_manager()->create_snapshot(0, it, BASEURI); PatchTreeManager* patchTreeManager = controller->get_patch_tree_manager(); DictionaryManager *dict = controller->get_snapshot_manager()->get_dictionary_manager(0); PatchSorted patch1(dict); patch1.add(PatchElement(Triple("0", "0", "0", dict), false)); patch1.add(PatchElement(Triple("1", "1", "1", dict), false)); patch1.add(PatchElement(Triple("2", "2", "2", dict), false)); // No 3! patch1.add(PatchElement(Triple("4", "4", "4", dict), false)); patch1.add(PatchElement(Triple("5", "5", "5", dict), false)); patchTreeManager->append(patch1, 1, dict); Triple t; // Request version 1, offset 0 TripleIterator* it0 = controller->get_version_materialized(Triple("", "", "", dict), 0, 1); ASSERT_EQ(true, it0->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("3 3 3.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, it0->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("6 6 6.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, it0->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("7 7 7.", t.to_string(*dict)) << "Element is incorrect"; // Request version 1, offset 3 (The actual edge case!) TripleIterator* it1 = controller->get_version_materialized(Triple("", "", "", dict), 3, 1); ASSERT_EQ(true, it1->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("8 8 8.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, it1->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("9 9 9.", t.to_string(*dict)) << "Element is incorrect"; } TEST_F(ControllerTest, EdgeCaseVersionMaterialized2) { /* * This tests the case in which a deletion that does not match the queried triple pattern * exists *before* all applicable deletions, and the first matching triple is just a snapshot triple. */ // Build a snapshot std::vector<TripleString> triples; triples.push_back(TripleString("a", "a", "a")); triples.push_back(TripleString("b", "b", "b")); triples.push_back(TripleString("y", "a", "a")); triples.push_back(TripleString("z", "a", "a")); VectorTripleIterator* it = new VectorTripleIterator(triples); controller->get_snapshot_manager()->create_snapshot(0, it, BASEURI); PatchTreeManager* patchTreeManager = controller->get_patch_tree_manager(); DictionaryManager *dict = controller->get_snapshot_manager()->get_dictionary_manager(0); PatchSorted patch1(dict); patch1.add(PatchElement(Triple("b", "b", "b", dict), false)); patch1.add(PatchElement(Triple("y", "a", "a", dict), false)); patch1.add(PatchElement(Triple("z", "a", "a", dict), false)); patchTreeManager->append(patch1, 1, dict); // --- filtered by a ? a // Expected version 0: // a a a // y a a // z a a // Expected version 1: // a a a Triple t; // Request version 0 (snapshot) ASSERT_EQ(3, controller->get_version_materialized_count(Triple("", "a", "a", dict), 0).first) << "Count is incorrect"; TripleIterator* it0 = controller->get_version_materialized(Triple("", "a", "a", dict), 0, 0); ASSERT_EQ(true, it0->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("a a a.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, it0->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("y a a.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, it0->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("z a a.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(false, it0->next(&t)) << "Iterator has a no next value"; // Request version 1 (patch) ASSERT_EQ(1, controller->get_version_materialized_count(Triple("", "a", "a", dict), 1).first) << "Count is incorrect"; TripleIterator* it1 = controller->get_version_materialized(Triple("", "a", "a", dict), 0, 1); ASSERT_EQ(true, it1->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("a a a.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(false, it1->next(&t)) << "Iterator has a no next value"; } TEST_F(ControllerTest, EdgeCaseVersionMaterialized3) { /* * Same as the previous case, but we start from an offset. */ // Build a snapshot std::vector<TripleString> triples; triples.push_back(TripleString("a", "a", "a")); triples.push_back(TripleString("b", "a", "a")); triples.push_back(TripleString("c", "c", "c")); triples.push_back(TripleString("d", "a", "a")); triples.push_back(TripleString("y", "a", "a")); triples.push_back(TripleString("z", "a", "a")); VectorTripleIterator* it = new VectorTripleIterator(triples); controller->get_snapshot_manager()->create_snapshot(0, it, BASEURI); PatchTreeManager* patchTreeManager = controller->get_patch_tree_manager(); DictionaryManager *dict = controller->get_snapshot_manager()->get_dictionary_manager(0); PatchSorted patch1(dict); patch1.add(PatchElement(Triple("b", "a", "a", dict), false)); patch1.add(PatchElement(Triple("c", "c", "c", dict), false)); patch1.add(PatchElement(Triple("y", "a", "a", dict), false)); patch1.add(PatchElement(Triple("z", "a", "a", dict), false)); patchTreeManager->append(patch1, 1, dict); // --- filtered by a ? a // Expected version 0: // a a a // b a a // d a a // y a a // z a a // Expected version 1: // a a a Triple t; // Request version 0 (snapshot) ASSERT_EQ(5, controller->get_version_materialized_count(Triple("", "a", "a", dict), 0).first) << "Count is incorrect"; TripleIterator* it0 = controller->get_version_materialized(Triple("", "a", "a", dict), 0, 0); ASSERT_EQ(true, it0->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("a a a.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, it0->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("b a a.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, it0->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("d a a.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, it0->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("y a a.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, it0->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("z a a.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(false, it0->next(&t)) << "Iterator has a no next value"; // Request version 1 (patch) ASSERT_EQ(2, controller->get_version_materialized_count(Triple("", "a", "a", dict), 1).first) << "Count is incorrect"; TripleIterator* it1 = controller->get_version_materialized(Triple("", "a", "a", dict), 0, 1); ASSERT_EQ(true, it1->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("a a a.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, it1->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("d a a.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(false, it1->next(&t)) << "Iterator has a no next value"; // Request version 1 (patch), offset 1 TripleIterator* it2 = controller->get_version_materialized(Triple("", "a", "a", dict), 1, 1); ASSERT_EQ(true, it2->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("d a a.", t.to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(false, it2->next(&t)) << "Iterator has a no next value"; // Request version 1 (patch), offset 2 TripleIterator* it3 = controller->get_version_materialized(Triple("", "a", "a", dict), 2, 1); ASSERT_EQ(false, it3->next(&t)) << "Iterator has a no next value"; } TEST_F(ControllerTest, GetDeltaMaterializedSnapshotPatch) { controller->new_patch_bulk() ->addition(TripleString("<a>", "<a>", "<a>")) ->addition(TripleString("<a>", "<a>", "<b>")) ->addition(TripleString("<a>", "<a>", "<c>")) ->commit(); controller->new_patch_bulk() ->deletion(TripleString("<a>", "<a>", "<b>")) ->commit(); controller->new_patch_bulk() ->addition(TripleString("<a>", "<a>", "<d>")) ->commit(); DictionaryManager *dict = controller->get_snapshot_manager()->get_dictionary_manager(0); // Expected version 0: // <a> <a> <a> // <a> <a> <b> // <a> <a> <c> // Expected version 1: // <a> <a> <a> // <a> <a> <c> // Expected version 2: // <a> <a> <a> // <a> <a> <c> // <a> <a> <d> TripleDelta t; // Request between versions 0 and 1 for ? ? ? ASSERT_EQ(1, controller->get_delta_materialized_count(Triple("", "", "", dict), 0, 1).first) << "Count is incorrect"; TripleDeltaIterator* it0 = controller->get_delta_materialized(Triple("", "", "", dict), 0, 0, 1); ASSERT_EQ(true, it0->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <b>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(false, t.is_addition()) << "Element is incorrect"; ASSERT_EQ(false, it0->next(&t)) << "Iterator should be finished"; // Request between versions 0 and 1 for <a> ? ? ASSERT_EQ(1, controller->get_delta_materialized_count(Triple("<a>", "", "", dict), 0, 1).first) << "Count is incorrect"; TripleDeltaIterator* it1 = controller->get_delta_materialized(Triple("<a>", "", "", dict), 0, 0, 1); ASSERT_EQ(true, it1->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <b>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(false, t.is_addition()) << "Element is incorrect"; ASSERT_EQ(false, it1->next(&t)) << "Iterator should be finished"; // Request between versions 0 and 1 for ? ? <d> ASSERT_EQ(0, controller->get_delta_materialized_count(Triple("", "", "<d>", dict), 0, 1).first) << "Count is incorrect"; TripleDeltaIterator* it2 = controller->get_delta_materialized(Triple("", "", "<d>", dict), 0, 0, 1); ASSERT_EQ(false, it2->next(&t)) << "Iterator should be finished"; // Request between versions 0 and 2 for <a> ? ? ASSERT_EQ(2, controller->get_delta_materialized_count(Triple("<a>", "", "", dict), 0, 2).first) << "Count is incorrect"; TripleDeltaIterator* it3 = controller->get_delta_materialized(Triple("<a>", "", "", dict), 0, 0, 2); ASSERT_EQ(true, it3->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <b>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(false, t.is_addition()) << "Element is incorrect"; ASSERT_EQ(true, it3->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <d>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, t.is_addition()) << "Element is incorrect"; ASSERT_EQ(false, it3->next(&t)) << "Iterator should be finished"; // Request between versions 0 and 2 for <a> ? ? with offset 1 TripleDeltaIterator* it4 = controller->get_delta_materialized(Triple("<a>", "", "", dict), 1, 0, 2); ASSERT_EQ(true, it4->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <d>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, t.is_addition()) << "Element is incorrect"; ASSERT_EQ(false, it4->next(&t)) << "Iterator should be finished"; // Request between versions 0 and 2 for <a> ? ? with offset 2 TripleDeltaIterator* it5 = controller->get_delta_materialized(Triple("<a>", "", "", dict), 2, 0, 2); ASSERT_EQ(false, it5->next(&t)) << "Iterator should be finished"; } TEST_F(ControllerTest, GetDeltaMaterializedPatchPatch) { controller->new_patch_bulk() ->addition(TripleString("<a>", "<a>", "<a>")) ->addition(TripleString("<a>", "<a>", "<b>")) ->addition(TripleString("<a>", "<a>", "<c>")) ->commit(); controller->new_patch_bulk() ->deletion(TripleString("<a>", "<a>", "<b>")) ->commit(); controller->new_patch_bulk() ->addition(TripleString("<a>", "<a>", "<d>")) ->commit(); controller->new_patch_bulk() ->addition(TripleString("<a>", "<a>", "<e>")) ->deletion(TripleString("<a>", "<a>", "<a>")) ->commit(); DictionaryManager *dict = controller->get_snapshot_manager()->get_dictionary_manager(0); // Expected version 0: // <a> <a> <a> // <a> <a> <b> // <a> <a> <c> // Expected version 1: // <a> <a> <a> // <a> <a> <c> // Expected version 2: // <a> <a> <a> // <a> <a> <c> // <a> <a> <d> // Expected version 3: // <a> <a> <c> // <a> <a> <d> // <a> <a> <e> TripleDelta t; // Request between versions 1 and 2 for ? ? ? ASSERT_EQ(3, controller->get_delta_materialized_count(Triple("", "", "", dict), 1, 2, true).first) << "Count is incorrect"; ASSERT_EQ(1, controller->get_delta_materialized_count(Triple("", "", "", dict), 1, 2, false).first) << "Count is incorrect"; TripleDeltaIterator* it0 = controller->get_delta_materialized(Triple("", "", "", dict), 0, 1, 2); ASSERT_EQ(true, it0->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <d>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, t.is_addition()) << "Element is incorrect"; ASSERT_EQ(false, it0->next(&t)) << "Iterator should be finished"; // Request between versions 2 and 3 for ? ? ? ASSERT_EQ(2, controller->get_delta_materialized_count(Triple("", "", "", dict), 2, 3).first) << "Count is incorrect"; TripleDeltaIterator* it1 = controller->get_delta_materialized(Triple("", "", "", dict), 0, 2, 3); ASSERT_EQ(true, it1->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <a>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(false, t.is_addition()) << "Element is incorrect"; ASSERT_EQ(true, it1->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <e>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, t.is_addition()) << "Element is incorrect"; ASSERT_EQ(false, it1->next(&t)) << "Iterator should be finished"; // Request between versions 2 and 3 for ? ? ? with offset 1 TripleDeltaIterator* it1_b = controller->get_delta_materialized(Triple("", "", "", dict), 1, 2, 3); ASSERT_EQ(true, it1_b->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <e>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, t.is_addition()) << "Element is incorrect"; ASSERT_EQ(false, it1_b->next(&t)) << "Iterator should be finished"; // Request between versions 2 and 3 for ? ? ? with offset 2 TripleDeltaIterator* it1_c = controller->get_delta_materialized(Triple("", "", "", dict), 2, 2, 3); ASSERT_EQ(false, it1_c->next(&t)) << "Iterator should be finished"; // Request between versions 1 and 3 for ? ? ? ASSERT_EQ(3, controller->get_delta_materialized_count(Triple("", "", "", dict), 1, 3).first) << "Count is incorrect"; TripleDeltaIterator* it2 = controller->get_delta_materialized(Triple("", "", "", dict), 0, 1, 3); ASSERT_EQ(true, it2->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <a>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(false, t.is_addition()) << "Element is incorrect"; ASSERT_EQ(true, it2->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <d>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, t.is_addition()) << "Element is incorrect"; ASSERT_EQ(true, it2->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <e>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, t.is_addition()) << "Element is incorrect"; ASSERT_EQ(false, it2->next(&t)) << "Iterator should be finished"; // Request between versions 1 and 3 for ? ? ? with offset 1 TripleDeltaIterator* it2_b = controller->get_delta_materialized(Triple("", "", "", dict), 1, 1, 3); ASSERT_EQ(true, it2_b->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <d>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, t.is_addition()) << "Element is incorrect"; ASSERT_EQ(true, it2_b->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <e>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, t.is_addition()) << "Element is incorrect"; ASSERT_EQ(false, it2_b->next(&t)) << "Iterator should be finished"; // Request between versions 1 and 3 for ? ? ? with offset 2 TripleDeltaIterator* it2_c = controller->get_delta_materialized(Triple("", "", "", dict), 2, 1, 3); ASSERT_EQ(true, it2_c->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <e>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, t.is_addition()) << "Element is incorrect"; ASSERT_EQ(false, it2_c->next(&t)) << "Iterator should be finished"; // Request between versions 1 and 3 for ? ? ? with offset 3 TripleDeltaIterator* it2_d = controller->get_delta_materialized(Triple("", "", "", dict), 3, 1, 3); ASSERT_EQ(false, it2_d->next(&t)) << "Iterator should be finished"; } TEST_F(ControllerTest, EdgeCaseGetDeltaMaterialized1) { /* * Test if DM between two patches is correct. * We specifically test the case for a triple that is added in 1, and removed again in 3. * We check if DM 1-2 correctly emits the addition, and if DM 3-4 correctly emits the deletion. */ controller->new_patch_bulk() ->addition(TripleString("<a>", "<a>", "<a>")) ->commit(); controller->new_patch_bulk() ->addition(TripleString("<z>", "<z>", "<z>")) ->commit(); controller->new_patch_bulk() ->addition(TripleString("<a>", "<a>", "<b>")) ->commit(); controller->new_patch_bulk() ->deletion(TripleString("<a>", "<a>", "<a>")) ->commit(); controller->new_patch_bulk() ->deletion(TripleString("<a>", "<a>", "<b>")) ->commit(); controller->new_patch_bulk() ->addition(TripleString("<y>", "<y>", "<y>")) ->commit(); DictionaryManager *dict = controller->get_snapshot_manager()->get_dictionary_manager(0); // Expected version 0: // <a> <a> <a> // Expected version 1: // <a> <a> <a> // <z> <z> <z> // Expected version 2: // <a> <a> <a> // <a> <a> <b> // <z> <z> <z> // Expected version 3: // <a> <a> <b> // <z> <z> <z> // Expected version 4: // <z> <z> <z> // Expected version 5: // <y> <y> <y> // <z> <z> <z> TripleDelta t; // Request between versions 1 and 2 for ? ? ? TripleDeltaIterator* it0 = controller->get_delta_materialized(Triple("", "", "", dict), 0, 1, 2); ASSERT_EQ(true, it0->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <b>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, t.is_addition()) << "Element is incorrect"; ASSERT_EQ(false, it0->next(&t)) << "Iterator should be finished"; // Request between versions 3 and 4 for ? ? ? TripleDeltaIterator* it1 = controller->get_delta_materialized(Triple("", "", "", dict), 0, 3, 4); ASSERT_EQ(true, it1->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <b>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(false, t.is_addition()) << "Element is incorrect"; ASSERT_EQ(false, it1->next(&t)) << "Iterator should be finished"; } TEST_F(ControllerTest, EdgeCaseGetDeltaMaterialized2) { /* * Test if DM is correct if we repeatedly add and remove the same triple. */ controller->new_patch_bulk() ->addition(TripleString("<a>", "<a>", "<a>")) ->commit(); controller->new_patch_bulk() ->deletion(TripleString("<a>", "<a>", "<a>")) ->commit(); controller->new_patch_bulk() ->addition(TripleString("<a>", "<a>", "<a>")) ->commit(); controller->new_patch_bulk() ->deletion(TripleString("<a>", "<a>", "<a>")) ->commit(); controller->new_patch_bulk() ->addition(TripleString("<a>", "<a>", "<a>")) ->commit(); DictionaryManager *dict = controller->get_snapshot_manager()->get_dictionary_manager(0); // Expected version 0: // <a> <a> <a> // Expected version 1: // Expected version 2: // <a> <a> <a> // Expected version 3: // Expected version 4: // <a> <a> <a> TripleDelta t; // Request between versions 0 and 1 for ? ? ? TripleDeltaIterator* it0 = controller->get_delta_materialized(Triple("", "", "", dict), 0, 0, 1); ASSERT_EQ(true, it0->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <a>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(false, t.is_addition()) << "Element is incorrect"; ASSERT_EQ(false, it0->next(&t)) << "Iterator should be finished"; // Request between versions 1 and 2 for ? ? ? TripleDeltaIterator* it1 = controller->get_delta_materialized(Triple("", "", "", dict), 0, 1, 2); ASSERT_EQ(true, it1->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <a>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, t.is_addition()) << "Element is incorrect"; ASSERT_EQ(false, it1->next(&t)) << "Iterator should be finished"; // Request between versions 2 and 3 for ? ? ? TripleDeltaIterator* it2 = controller->get_delta_materialized(Triple("", "", "", dict), 0, 2, 3); ASSERT_EQ(true, it2->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <a>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(false, t.is_addition()) << "Element is incorrect"; ASSERT_EQ(false, it2->next(&t)) << "Iterator should be finished"; // Request between versions 3 and 4 for ? ? ? TripleDeltaIterator* it3 = controller->get_delta_materialized(Triple("", "", "", dict), 0, 3, 4); ASSERT_EQ(true, it3->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <a>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, t.is_addition()) << "Element is incorrect"; ASSERT_EQ(false, it3->next(&t)) << "Iterator should be finished"; } TEST_F(ControllerTest, EdgeCaseGetDeltaMaterialized3) { /* * Test if DM is correct when the range does not match the changeset bounds, * and the triple *is not* present in the snapshot. */ controller->new_patch_bulk() ->addition(TripleString("<dummy>", "<dummy>", "<dummy>")) ->commit(); controller->new_patch_bulk() ->addition(TripleString("<dummy2>", "<dummy2>", "<dummy2>")) ->commit(); controller->new_patch_bulk() ->addition(TripleString("<a>", "<a>", "<a>")) ->commit(); controller->new_patch_bulk() ->addition(TripleString("<dummy3>", "<dummy3>", "<dummy3>")) ->commit(); controller->new_patch_bulk() ->deletion(TripleString("<a>", "<a>", "<a>")) ->commit(); DictionaryManager *dict = controller->get_snapshot_manager()->get_dictionary_manager(0); // Expected version 0: // Expected version 1: // Expected version 2: // <a> <a> <a> // Expected version 3: // <a> <a> <a> // Expected version 4: TripleDelta t; // Request between versions 1 and 4 for <a> ? ? TripleDeltaIterator* it0 = controller->get_delta_materialized(Triple("<a>", "", "", dict), 0, 1, 4); ASSERT_EQ(false, it0->next(&t)) << "Iterator should be finished"; // Request between versions 2 and 4 for <a> ? ? TripleDeltaIterator* it1 = controller->get_delta_materialized(Triple("<a>", "", "", dict), 0, 2, 4); ASSERT_EQ(true, it1->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <a>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(false, t.is_addition()) << "Element is incorrect"; ASSERT_EQ(false, it1->next(&t)) << "Iterator should be finished"; // Request between versions 1 and 3 for <a> ? ? TripleDeltaIterator* it2 = controller->get_delta_materialized(Triple("<a>", "", "", dict), 0, 1, 3); ASSERT_EQ(true, it2->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <a>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, t.is_addition()) << "Element is incorrect"; ASSERT_EQ(false, it2->next(&t)) << "Iterator should be finished"; } TEST_F(ControllerTest, EdgeCaseGetDeltaMaterialized4) { /* * Test if DM is correct when the range does not match the changeset bounds, * and the triple *is* present in the snapshot. */ controller->new_patch_bulk() ->addition(TripleString("<a>", "<a>", "<a>")) ->commit(); controller->new_patch_bulk() ->addition(TripleString("<dummy>", "<dummy>", "<dummy>")) ->commit(); controller->new_patch_bulk() ->deletion(TripleString("<a>", "<a>", "<a>")) ->commit(); controller->new_patch_bulk() ->addition(TripleString("<dummy2>", "<dummy2>", "<dummy2>")) ->commit(); controller->new_patch_bulk() ->addition(TripleString("<a>", "<a>", "<a>")) ->commit(); DictionaryManager *dict = controller->get_snapshot_manager()->get_dictionary_manager(0); // Expected version 0: // <a> <a> <a> // Expected version 1: // <a> <a> <a> // Expected version 2: // Expected version 3: // Expected version 4: // <a> <a> <a> TripleDelta t; // Request between versions 1 and 4 for <a> ? ? TripleDeltaIterator* it0 = controller->get_delta_materialized(Triple("<a>", "", "", dict), 0, 1, 4); ASSERT_EQ(false, it0->next(&t)) << "Iterator should be finished"; // Request between versions 2 and 4 for <a> ? ? TripleDeltaIterator* it1 = controller->get_delta_materialized(Triple("<a>", "", "", dict), 0, 2, 4); ASSERT_EQ(true, it1->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <a>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, t.is_addition()) << "Element is incorrect"; ASSERT_EQ(false, it1->next(&t)) << "Iterator should be finished"; // Request between versions 1 and 3 for <a> ? ? TripleDeltaIterator* it2 = controller->get_delta_materialized(Triple("<a>", "", "", dict), 0, 1, 3); ASSERT_EQ(true, it2->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <a>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(false, t.is_addition()) << "Element is incorrect"; ASSERT_EQ(false, it2->next(&t)) << "Iterator should be finished"; } TEST_F(ControllerTest, EdgeCaseGetDeltaMaterialized5) { /* * Test if DM relative to snapshot is correct when the range does not match the changeset bounds, * and the triple *is not* present in the snapshot. */ controller->new_patch_bulk() ->addition(TripleString("<dummy>", "<dummy>", "<dummy>")) ->commit(); controller->new_patch_bulk() ->addition(TripleString("<a>", "<a>", "<a>")) ->commit(); controller->new_patch_bulk() ->deletion(TripleString("<a>", "<a>", "<a>")) ->commit(); DictionaryManager *dict = controller->get_snapshot_manager()->get_dictionary_manager(0); // Expected version 0: // Expected version 1: // <a> <a> <a> // Expected version 2: TripleDelta t; // Request between versions 0 and 2 for <a> ? ? TripleDeltaIterator* it0 = controller->get_delta_materialized(Triple("<a>", "", "", dict), 0, 0, 2); ASSERT_EQ(false, it0->next(&t)) << "Iterator should be finished"; // Request between versions 0 and 1 for <a> ? ? TripleDeltaIterator* it1 = controller->get_delta_materialized(Triple("<a>", "", "", dict), 0, 0, 1); ASSERT_EQ(true, it1->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <a>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, t.is_addition()) << "Element is incorrect"; ASSERT_EQ(false, it1->next(&t)) << "Iterator should be finished"; // Request between versions 1 and 2 for <a> ? ? TripleDeltaIterator* it2 = controller->get_delta_materialized(Triple("<a>", "", "", dict), 0, 1, 2); ASSERT_EQ(true, it2->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <a>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(false, t.is_addition()) << "Element is incorrect"; ASSERT_EQ(false, it2->next(&t)) << "Iterator should be finished"; } TEST_F(ControllerTest, EdgeCaseGetDeltaMaterialized6) { /* * Test if DM relative to snapshot is correct when the range does not match the changeset bounds, * and the triple *is* present in the snapshot. */ controller->new_patch_bulk() ->addition(TripleString("<a>", "<a>", "<a>")) ->commit(); controller->new_patch_bulk() ->deletion(TripleString("<a>", "<a>", "<a>")) ->commit(); controller->new_patch_bulk() ->addition(TripleString("<a>", "<a>", "<a>")) ->commit(); DictionaryManager *dict = controller->get_snapshot_manager()->get_dictionary_manager(0); // Expected version 0: // <a> <a> <a> // Expected version 1: // Expected version 2: // <a> <a> <a> TripleDelta t; // Request between versions 0 and 2 for <a> ? ? TripleDeltaIterator* it0 = controller->get_delta_materialized(Triple("<a>", "", "", dict), 0, 0, 2); ASSERT_EQ(false, it0->next(&t)) << "Iterator should be finished"; // Request between versions 0 and 1 for <a> ? ? TripleDeltaIterator* it1 = controller->get_delta_materialized(Triple("<a>", "", "", dict), 0, 0, 1); ASSERT_EQ(true, it1->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <a>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(false, t.is_addition()) << "Element is incorrect"; ASSERT_EQ(false, it1->next(&t)) << "Iterator should be finished"; // Request between versions 1 and 2 for <a> ? ? TripleDeltaIterator* it2 = controller->get_delta_materialized(Triple("<a>", "", "", dict), 0, 1, 2); ASSERT_EQ(true, it2->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <a>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(true, t.is_addition()) << "Element is incorrect"; ASSERT_EQ(false, it2->next(&t)) << "Iterator should be finished"; } TEST_F(ControllerTest, GetVersionSnapshot) { controller->new_patch_bulk() ->addition(TripleString("<a>", "<a>", "<a>")) ->addition(TripleString("<a>", "<a>", "<b>")) ->addition(TripleString("<a>", "<a>", "<c>")) ->commit(); DictionaryManager *dict = controller->get_snapshot_manager()->get_dictionary_manager(0); // Expected version 0: // <a> <a> <a> // <a> <a> <b> // <a> <a> <c> TripleVersions t; std::vector<int> v_0(0); v_0.push_back(0); // Request versions for ? ? ? ASSERT_EQ(3, controller->get_version_count(Triple("", "", "", dict)).first) << "Count is incorrect"; TripleVersionsIterator* it0 = controller->get_version(Triple("", "", "", dict), 0); ASSERT_EQ(true, it0->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <a>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(v_0, *(t.get_versions())) << "Element is incorrect"; ASSERT_EQ(true, it0->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <b>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(v_0, *(t.get_versions())) << "Element is incorrect"; ASSERT_EQ(true, it0->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <c>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(v_0, *(t.get_versions())) << "Element is incorrect"; ASSERT_EQ(false, it0->next(&t)) << "Iterator should be finished"; // Request versions for ? ? ? with offset 1 TripleVersionsIterator* it1 = controller->get_version(Triple("", "", "", dict), 1); ASSERT_EQ(true, it1->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <b>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(v_0, *(t.get_versions())) << "Element is incorrect"; ASSERT_EQ(true, it1->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <c>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(v_0, *(t.get_versions())) << "Element is incorrect"; ASSERT_EQ(false, it1->next(&t)) << "Iterator should be finished"; // Request versions for ? ? ? with offset 2 TripleVersionsIterator* it2 = controller->get_version(Triple("", "", "", dict), 2); ASSERT_EQ(true, it2->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <c>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(v_0, *(t.get_versions())) << "Element is incorrect"; ASSERT_EQ(false, it2->next(&t)) << "Iterator should be finished"; // Request versions for ? ? ? with offset 3 TripleVersionsIterator* it3 = controller->get_version(Triple("", "", "", dict), 3); ASSERT_EQ(false, it3->next(&t)) << "Iterator should be finished"; // Request versions for <a> ? ? ASSERT_EQ(3, controller->get_version_count(Triple("<a>", "", "", dict)).first) << "Count is incorrect"; TripleVersionsIterator* it5 = controller->get_version(Triple("", "", "", dict), 0); ASSERT_EQ(true, it5->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <a>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(v_0, *(t.get_versions())) << "Element is incorrect"; ASSERT_EQ(true, it5->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <b>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(v_0, *(t.get_versions())) << "Element is incorrect"; ASSERT_EQ(true, it5->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <c>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(v_0, *(t.get_versions())) << "Element is incorrect"; ASSERT_EQ(false, it5->next(&t)) << "Iterator should be finished"; // Request versions for <a> ? ? with offset 1 TripleVersionsIterator* it6 = controller->get_version(Triple("<a>", "", "", dict), 1); ASSERT_EQ(true, it6->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <b>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(v_0, *(t.get_versions())) << "Element is incorrect"; ASSERT_EQ(true, it6->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <c>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(v_0, *(t.get_versions())) << "Element is incorrect"; ASSERT_EQ(false, it6->next(&t)) << "Iterator should be finished"; // Request versions for <a> ? ? with offset 2 TripleVersionsIterator* it7 = controller->get_version(Triple("<a>", "", "", dict), 2); ASSERT_EQ(true, it7->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <c>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(v_0, *(t.get_versions())) << "Element is incorrect"; ASSERT_EQ(false, it7->next(&t)) << "Iterator should be finished"; // Request versions for <a> ? ? with offset 3 TripleVersionsIterator* it8 = controller->get_version(Triple("<a>", "", "", dict), 3); ASSERT_EQ(false, it8->next(&t)) << "Iterator should be finished"; // Request versions for ? ? <a> ASSERT_EQ(1, controller->get_version_count(Triple("", "", "<a>", dict)).first) << "Count is incorrect"; TripleVersionsIterator* it10 = controller->get_version(Triple("", "", "<a>", dict), 0); ASSERT_EQ(true, it10->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <a>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(v_0, *(t.get_versions())) << "Element is incorrect"; ASSERT_EQ(false, it10->next(&t)) << "Iterator should be finished"; // Request versions for ? ? <a> with offset 1 TripleVersionsIterator* it11 = controller->get_version(Triple("", "", "<a>", dict), 1); ASSERT_EQ(false, it11->next(&t)) << "Iterator should be finished"; // Request versions for ? ? <b> ASSERT_EQ(1, controller->get_version_count(Triple("", "", "<b>", dict)).first) << "Count is incorrect"; TripleVersionsIterator* it12 = controller->get_version(Triple("", "", "<b>", dict), 0); ASSERT_EQ(true, it12->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <b>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(v_0, *(t.get_versions())) << "Element is incorrect"; ASSERT_EQ(false, it12->next(&t)) << "Iterator should be finished"; // Request versions for ? ? <b> with offset 1 TripleVersionsIterator* it13 = controller->get_version(Triple("", "", "<b>", dict), 1); ASSERT_EQ(false, it13->next(&t)) << "Iterator should be finished"; // Request versions for ? ? <c> ASSERT_EQ(1, controller->get_version_count(Triple("", "", "<c>", dict)).first) << "Count is incorrect"; TripleVersionsIterator* it14 = controller->get_version(Triple("", "", "<c>", dict), 0); ASSERT_EQ(true, it14->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <c>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(v_0, *(t.get_versions())) << "Element is incorrect"; ASSERT_EQ(false, it14->next(&t)) << "Iterator should be finished"; // Request versions for ? ? <c> with offset 1 TripleVersionsIterator* it15 = controller->get_version(Triple("", "", "<c>", dict), 1); ASSERT_EQ(false, it15->next(&t)) << "Iterator should be finished"; // Request versions for ? ? <d> ASSERT_EQ(0, controller->get_version_count(Triple("", "", "<d>", dict)).first) << "Count is incorrect"; TripleVersionsIterator* it16 = controller->get_version(Triple("", "", "<d>", dict), 0); ASSERT_EQ(false, it16->next(&t)) << "Iterator should be finished"; } TEST_F(ControllerTest, GetVersion) { controller->new_patch_bulk() ->addition(TripleString("<a>", "<a>", "<a>")) ->addition(TripleString("<a>", "<a>", "<b>")) ->addition(TripleString("<a>", "<a>", "<c>")) ->commit(); controller->new_patch_bulk() ->deletion(TripleString("<a>", "<a>", "<b>")) ->commit(); controller->new_patch_bulk() ->addition(TripleString("<a>", "<a>", "<d>")) ->commit(); DictionaryManager *dict = controller->get_snapshot_manager()->get_dictionary_manager(0); // Expected version 0: // <a> <a> <a> // <a> <a> <b> // <a> <a> <c> // Expected version 1: // <a> <a> <a> // <a> <a> <c> // Expected version 2: // <a> <a> <a> // <a> <a> <c> // <a> <a> <d> TripleVersions t; std::vector<int> v_012(0); v_012.push_back(0); v_012.push_back(1); v_012.push_back(2); std::vector<int> v_0(0); v_0.push_back(0); std::vector<int> v_2(0); v_2.push_back(2); // Request versions for ? ? ? ASSERT_EQ(4, controller->get_version_count(Triple("", "", "", dict)).first) << "Count is incorrect"; TripleVersionsIterator* it0 = controller->get_version(Triple("", "", "", dict), 0); ASSERT_EQ(true, it0->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <a>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(v_012, *(t.get_versions())) << "Element is incorrect"; ASSERT_EQ(true, it0->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <b>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(v_0, *(t.get_versions())) << "Element is incorrect"; ASSERT_EQ(true, it0->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <c>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(v_012, *(t.get_versions())) << "Element is incorrect"; ASSERT_EQ(true, it0->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <d>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(v_2, *(t.get_versions())) << "Element is incorrect"; ASSERT_EQ(false, it0->next(&t)) << "Iterator should be finished"; // Request versions for ? ? ? with offset 1 TripleVersionsIterator* it1 = controller->get_version(Triple("", "", "", dict), 1); ASSERT_EQ(true, it1->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <b>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(v_0, *(t.get_versions())) << "Element is incorrect"; ASSERT_EQ(true, it1->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <c>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(v_012, *(t.get_versions())) << "Element is incorrect"; ASSERT_EQ(true, it1->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <d>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(v_2, *(t.get_versions())) << "Element is incorrect"; ASSERT_EQ(false, it1->next(&t)) << "Iterator should be finished"; // Request versions for ? ? ? with offset 2 TripleVersionsIterator* it2 = controller->get_version(Triple("", "", "", dict), 2); ASSERT_EQ(true, it2->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <c>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(v_012, *(t.get_versions())) << "Element is incorrect"; ASSERT_EQ(true, it2->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <d>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(v_2, *(t.get_versions())) << "Element is incorrect"; ASSERT_EQ(false, it2->next(&t)) << "Iterator should be finished"; // Request versions for ? ? ? with offset 3 TripleVersionsIterator* it3 = controller->get_version(Triple("", "", "", dict), 3); ASSERT_EQ(true, it3->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <d>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(v_2, *(t.get_versions())) << "Element is incorrect"; ASSERT_EQ(false, it3->next(&t)) << "Iterator should be finished"; // Request versions for ? ? ? with offset 4 TripleVersionsIterator* it4 = controller->get_version(Triple("", "", "", dict), 4); ASSERT_EQ(false, it4->next(&t)) << "Iterator should be finished"; // Request versions for <a> ? ? ASSERT_EQ(4, controller->get_version_count(Triple("<a>", "", "", dict)).first) << "Count is incorrect"; TripleVersionsIterator* it5 = controller->get_version(Triple("", "", "", dict), 0); ASSERT_EQ(true, it5->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <a>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(v_012, *(t.get_versions())) << "Element is incorrect"; ASSERT_EQ(true, it5->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <b>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(v_0, *(t.get_versions())) << "Element is incorrect"; ASSERT_EQ(true, it5->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <c>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(v_012, *(t.get_versions())) << "Element is incorrect"; ASSERT_EQ(true, it5->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <d>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(v_2, *(t.get_versions())) << "Element is incorrect"; ASSERT_EQ(false, it5->next(&t)) << "Iterator should be finished"; // Request versions for <a> ? ? with offset 1 TripleVersionsIterator* it6 = controller->get_version(Triple("<a>", "", "", dict), 1); ASSERT_EQ(true, it6->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <b>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(v_0, *(t.get_versions())) << "Element is incorrect"; ASSERT_EQ(true, it6->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <c>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(v_012, *(t.get_versions())) << "Element is incorrect"; ASSERT_EQ(true, it6->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <d>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(v_2, *(t.get_versions())) << "Element is incorrect"; ASSERT_EQ(false, it6->next(&t)) << "Iterator should be finished"; // Request versions for <a> ? ? with offset 2 TripleVersionsIterator* it7 = controller->get_version(Triple("<a>", "", "", dict), 2); ASSERT_EQ(true, it7->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <c>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(v_012, *(t.get_versions())) << "Element is incorrect"; ASSERT_EQ(true, it7->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <d>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(v_2, *(t.get_versions())) << "Element is incorrect"; ASSERT_EQ(false, it7->next(&t)) << "Iterator should be finished"; // Request versions for <a> ? ? with offset 3 TripleVersionsIterator* it8 = controller->get_version(Triple("<a>", "", "", dict), 3); ASSERT_EQ(true, it8->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <d>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(v_2, *(t.get_versions())) << "Element is incorrect"; ASSERT_EQ(false, it8->next(&t)) << "Iterator should be finished"; // Request versions for <a> ? ? with offset 4 TripleVersionsIterator* it9 = controller->get_version(Triple("<a>", "", "", dict), 4); ASSERT_EQ(false, it9->next(&t)) << "Iterator should be finished"; // Request versions for ? ? <a> ASSERT_EQ(1, controller->get_version_count(Triple("", "", "<a>", dict)).first) << "Count is incorrect"; TripleVersionsIterator* it10 = controller->get_version(Triple("", "", "<a>", dict), 0); ASSERT_EQ(true, it10->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <a>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(v_012, *(t.get_versions())) << "Element is incorrect"; ASSERT_EQ(false, it10->next(&t)) << "Iterator should be finished"; // Request versions for ? ? <a> with offset 1 TripleVersionsIterator* it11 = controller->get_version(Triple("", "", "<a>", dict), 1); ASSERT_EQ(false, it11->next(&t)) << "Iterator should be finished"; // Request versions for ? ? <b> ASSERT_EQ(1, controller->get_version_count(Triple("", "", "<b>", dict)).first) << "Count is incorrect"; TripleVersionsIterator* it12 = controller->get_version(Triple("", "", "<b>", dict), 0); ASSERT_EQ(true, it12->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <b>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(v_0, *(t.get_versions())) << "Element is incorrect"; ASSERT_EQ(false, it12->next(&t)) << "Iterator should be finished"; // Request versions for ? ? <b> with offset 1 TripleVersionsIterator* it13 = controller->get_version(Triple("", "", "<b>", dict), 1); ASSERT_EQ(false, it13->next(&t)) << "Iterator should be finished"; // Request versions for ? ? <c> ASSERT_EQ(1, controller->get_version_count(Triple("", "", "<c>", dict)).first) << "Count is incorrect"; TripleVersionsIterator* it14 = controller->get_version(Triple("", "", "<c>", dict), 0); ASSERT_EQ(true, it14->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <c>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(v_012, *(t.get_versions())) << "Element is incorrect"; ASSERT_EQ(false, it14->next(&t)) << "Iterator should be finished"; // Request versions for ? ? <c> with offset 1 TripleVersionsIterator* it15 = controller->get_version(Triple("", "", "<c>", dict), 1); ASSERT_EQ(false, it15->next(&t)) << "Iterator should be finished"; // Request versions for ? ? <d> ASSERT_EQ(1, controller->get_version_count(Triple("", "", "<d>", dict)).first) << "Count is incorrect"; TripleVersionsIterator* it16 = controller->get_version(Triple("", "", "<d>", dict), 0); ASSERT_EQ(true, it16->next(&t)) << "Iterator has a no next value"; ASSERT_EQ("<a> <a> <d>.", t.get_triple()->to_string(*dict)) << "Element is incorrect"; ASSERT_EQ(v_2, *(t.get_versions())) << "Element is incorrect"; ASSERT_EQ(false, it16->next(&t)) << "Iterator should be finished"; // Request versions for ? ? <d> with offset 1 TripleVersionsIterator* it17 = controller->get_version(Triple("", "", "<d>", dict), 1); ASSERT_EQ(false, it17->next(&t)) << "Iterator should be finished"; }
true
9af6326a797d1aa38b70cb5bbb779d5abeca45ce
C++
m-paniagua/printer-queue
/paniaguamPrinterQueue/pqtype.h
UTF-8
338
2.6875
3
[]
no_license
#include "heap.h" #ifndef PQTYPE_H #define PQTYPE_H template<class ItemType> class PQType { public: PQType(int); //~PQType(); void MakeEmpty(); bool IsEmpty(); bool IsFull(); void Enqueue(ItemType newItem); void Dequeue(ItemType&); private: int length; HeapType<ItemType> items; int maxItems; }; #include "pqtype.cpp" #endif
true
6ed239e4753dafc0e3cb841b9d65e31eaad97651
C++
ArneStenkrona/prototype2
/src/game/game.cpp
UTF-8
2,398
2.515625
3
[]
no_license
#include "game.h" #include "src/container/vector.h" #include "src/config/prototype2Config.h" #include <chrono> #include <thread> #include <iostream> Game::Game() : m_input(), m_gameRenderer(DEFAULT_WIDTH, DEFAULT_HEIGHT), m_assetManager(RESOURCE_PATH), m_physicsSystem(), m_scene(m_gameRenderer, m_assetManager, m_physicsSystem, m_input), m_editor(m_scene, m_input, m_gameRenderer.getWindow(), DEFAULT_WIDTH, DEFAULT_HEIGHT), m_frameRate(FRAME_RATE), m_microsecondsPerFrame(1000000 / m_frameRate), m_currentFrame(0), m_time(0.0f) { m_input.init(m_gameRenderer.getWindow()); loadScene(); } void Game::loadScene() { m_scene.bindToRenderer(); } Game::~Game() { } void Game::run() { using clock = std::chrono::high_resolution_clock; auto lastTime = clock::now(); clock::time_point deadLine = clock::now(); uint32_t framesMeasured = 0; clock::time_point nextSecond = lastTime + std::chrono::seconds(1); while (m_gameRenderer.isWindowOpen()) { auto currentTime = clock::now(); deadLine = currentTime + std::chrono::microseconds(m_microsecondsPerFrame); float deltaTime = std::chrono::duration<float, std::chrono::seconds::period>(currentTime - lastTime).count(); lastTime = currentTime; update(deltaTime); m_gameRenderer.render(deltaTime, m_renderMask); std::this_thread::sleep_until(deadLine); framesMeasured++; if (nextSecond <= clock::now()) { nextSecond += std::chrono::seconds(1); std::cout << "Frame rate: " << framesMeasured << "FPS" << std::endl; framesMeasured = 0; } m_currentFrame++; glfwPollEvents(); } } void Game::update(float deltaTime) { m_time += deltaTime; m_input.update(m_mode == Mode::GAME); updateMode(); switch (m_mode) { case Mode::GAME: m_renderMask = GameRenderer::GAME_RENDER_MASK; m_scene.update(deltaTime); break; case Mode::EDITOR: int w,h; m_gameRenderer.getWindowSize(w,h); m_renderMask = GameRenderer::EDITOR_RENDER_MASK; m_editor.update(deltaTime,w,h); break; } } void Game::updateMode() { if (m_input.getKeyDown(INPUT_KEY::KEY_TAB)) { m_mode = m_mode == Mode::GAME ? Mode::EDITOR : Mode::GAME; } }
true
fc21c68ad641af45c15fe0e7f0908249b7575b18
C++
SKARPG/MEWA_GUITAR_PROCESSOR
/Drivers/Pin/Pin.hpp
UTF-8
609
3.15625
3
[]
no_license
#pragma once #include <stm32h7xx_hal.h> #include <cstdint> namespace board{ class Pin { private: GPIO_TypeDef *port; std::uint8_t pin; public: Pin() = delete; Pin(GPIO_TypeDef *_port, std::uint8_t _pin) : port(_port), pin(_pin) { } auto getPin() const noexcept -> std::uint8_t { return pin; } auto getPort() const noexcept -> GPIO_TypeDef* { return port; } void writePin(bool value){ HAL_GPIO_WritePin(port, pin, value ? GPIO_PIN_SET : GPIO_PIN_RESET); } auto readPin() -> bool{ return HAL_GPIO_ReadPin(port, pin); } void togglePin(){ HAL_GPIO_TogglePin(port, pin); } }; }
true
b1cbf4ea92948e59282e9addc579970cd4f30e06
C++
kingnak/GameGenerator
/GGEditor_src/command/ggabstractcommand.h
UTF-8
1,220
2.78125
3
[]
no_license
#ifndef GGABSTRACTCOMMAND_H #define GGABSTRACTCOMMAND_H #include <QString> class GGAbstractCommand { public: GGAbstractCommand() : m_state(NotExecuted) {} virtual ~GGAbstractCommand() {} enum CommandState { NotExecuted, Executed, Undone }; CommandState state() const { return m_state; } bool execute(); bool undo(); bool redo(); QString error() const { return m_error; } virtual QString description() const = 0; protected: bool setError(QString error); virtual bool doExecute() = 0; virtual bool doUndo() = 0; virtual bool doRedo() = 0; protected: CommandState m_state; QString m_error; }; ////////////////////////// class GGAbstractCommandFactory { Q_DISABLE_COPY(GGAbstractCommandFactory) protected: GGAbstractCommandFactory() {} public: virtual ~GGAbstractCommandFactory() {} static inline bool oneShotCommand(GGAbstractCommand *cmd, QString *error = NULL); }; bool GGAbstractCommandFactory::oneShotCommand(GGAbstractCommand *cmd, QString *error) { bool ret = cmd->execute(); if (!ret && error) *error = cmd->error(); delete cmd; return ret; } #endif // GGABSTRACTCOMMAND_H
true
0677edec0bb74a5953cec1dad11f752f4d4bd4fa
C++
thirtiseven/CF
/AIM tech round3/A.cc
UTF-8
411
2.609375
3
[]
no_license
#include <iostream> #include <algorithm> int main(int argc, char *argv[]) { int n, b, d; int a[100005]; std::cin >> n >> b >> d; for(int i = 0; i < n; i++) { std::cin >> a[i]; } int ans=0, sum=0; for(int i = 0; i < n; i++) { if(a[i] > b) { continue; } else { sum+=a[i]; } if(sum>d) { ans++; sum=0; } } std::cout << ans << std::endl; return 0; }
true
f3cc3e4495272480b22c1f65b53508aa83e02534
C++
ailyanlu1/Programming-Challenges
/hdoj/hdoj1711.cpp
UTF-8
1,113
2.96875
3
[]
no_license
/* Problem: HDOJ 1711 Author: 靖难 Tag: KMP, string match, DFA Difficulty: 1 (from 1 to 5) */ # include <stdio.h> # include <string.h> const int NMAX = 1000000; const int MMAX = 10000; int Pattern[MMAX]; int Next[MMAX]; int Target[NMAX]; int kmp(int n, int m) { Next[0] = -1; int p = -1; for(int i = 1; i < m; ++i){ while(p != -1 && Pattern[p+1] != Pattern[i]){ p = Next[p]; } if(Pattern[p+1] == Pattern[i]){ p = p + 1; } Next[i] = p; } p = -1; for(int i = 0; i < n; ++i){ while(p != -1 && Pattern[p+1] != Target[i]){ p = Next[p]; } if(Pattern[p+1] == Target[i]){ p = p + 1; } if(p == m-1) return i - m + 2; } return -1; } int main() { int T = 0, N = 0, M = 0; scanf("%d", &T); while(T--){ scanf("%d%d", &N, &M); for(int i = 0; i < N; ++i){ scanf("%d", &Target[i]); } for(int i = 0; i < M; ++i){ scanf("%d", &Pattern[i]); } printf("%d\n", kmp(N, M)); } }
true
8023905219d7cdc5a0cdef52e3bcc842d2e69f4b
C++
ResonanceGroup/GMSH304
/Post/shapeFunctions.h
UTF-8
33,243
2.59375
3
[ "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.0-or-later", "LicenseRef-scancode-generic-exception", "GPL-1.0-or-later", "LicenseRef-scancode-proprietary-license", "GPL-2.0-only", "GPL-2.0-or-later", "LicenseRef-scancode-other-copyleft", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// Gmsh - Copyright (C) 1997-2017 C. Geuzaine, J.-F. Remacle // // See the LICENSE.txt file for license information. Please report all // bugs and problems to the public mailing list <gmsh@onelab.info>. #ifndef _SHAPE_FUNCTIONS_H_ #define _SHAPE_FUNCTIONS_H_ #include "Numeric.h" #include "GmshMessage.h" class element{ protected: bool _ownData; double *_x, *_y, *_z; static double TOL; public: element(double *x, double *y, double *z, int numNodes=0) { if(!numNodes){ _ownData = false; _x = x; _y = y; _z = z; } else{ _ownData = true; _x = new double[numNodes]; _y = new double[numNodes]; _z = new double[numNodes]; for(int i = 0; i < numNodes; i++){ _x[i] = x[i]; _y[i] = y[i]; _z[i] = z[i]; } } } virtual ~element() { if(_ownData){ delete [] _x; delete [] _y; delete [] _z; } } virtual void getXYZ(int num, double &x, double &y, double &z) { if(num < 0 || num >= getNumNodes()) return; x = _x[num]; y = _y[num]; z = _z[num]; } static void setTolerance (const double tol){ TOL = tol; } static double getTolerance () { return TOL; } virtual int getDimension() = 0; virtual int getNumNodes() = 0; virtual void getNode(int num, double &u, double &v, double &w) = 0; virtual int getNumEdges() = 0; virtual void getEdge(int num, int &start, int &end) = 0; virtual int getNumGaussPoints() = 0; virtual void getGaussPoint(int num, double &u, double &v, double &w, double &weight) = 0; virtual void getShapeFunction(int num, double u, double v, double w, double &s) = 0; virtual void getGradShapeFunction(int num, double u, double v, double w, double s[3]) = 0; double getJacobian(double u, double v, double w, double jac[3][3]) { jac[0][0] = jac[0][1] = jac[0][2] = 0.; jac[1][0] = jac[1][1] = jac[1][2] = 0.; jac[2][0] = jac[2][1] = jac[2][2] = 0.; double s[3]; switch(getDimension()){ case 3 : for(int i = 0; i < getNumNodes(); i++) { getGradShapeFunction(i, u, v, w, s); jac[0][0] += _x[i] * s[0]; jac[0][1] += _y[i] * s[0]; jac[0][2] += _z[i] * s[0]; jac[1][0] += _x[i] * s[1]; jac[1][1] += _y[i] * s[1]; jac[1][2] += _z[i] * s[1]; jac[2][0] += _x[i] * s[2]; jac[2][1] += _y[i] * s[2]; jac[2][2] += _z[i] * s[2]; } return fabs( jac[0][0] * jac[1][1] * jac[2][2] + jac[0][2] * jac[1][0] * jac[2][1] + jac[0][1] * jac[1][2] * jac[2][0] - jac[0][2] * jac[1][1] * jac[2][0] - jac[0][0] * jac[1][2] * jac[2][1] - jac[0][1] * jac[1][0] * jac[2][2]); case 2 : for(int i = 0; i < getNumNodes(); i++) { getGradShapeFunction(i, u, v, w, s); jac[0][0] += _x[i] * s[0]; jac[0][1] += _y[i] * s[0]; jac[0][2] += _z[i] * s[0]; jac[1][0] += _x[i] * s[1]; jac[1][1] += _y[i] * s[1]; jac[1][2] += _z[i] * s[1]; } { double a[3], b[3], c[3]; a[0]= _x[1] - _x[0]; a[1]= _y[1] - _y[0]; a[2]= _z[1] - _z[0]; b[0]= _x[2] - _x[0]; b[1]= _y[2] - _y[0]; b[2]= _z[2] - _z[0]; prodve(a, b, c); jac[2][0] = c[0]; jac[2][1] = c[1]; jac[2][2] = c[2]; } return sqrt(gmsh_SQU(jac[0][0] * jac[1][1] - jac[0][1] * jac[1][0]) + gmsh_SQU(jac[0][2] * jac[1][0] - jac[0][0] * jac[1][2]) + gmsh_SQU(jac[0][1] * jac[1][2] - jac[0][2] * jac[1][1])); case 1: for(int i = 0; i < getNumNodes(); i++) { getGradShapeFunction(i, u, v, w, s); jac[0][0] += _x[i] * s[0]; jac[0][1] += _y[i] * s[0]; jac[0][2] += _z[i] * s[0]; } { double a[3], b[3], c[3]; a[0]= _x[1] - _x[0]; a[1]= _y[1] - _y[0]; a[2]= _z[1] - _z[0]; if((fabs(a[0]) >= fabs(a[1]) && fabs(a[0]) >= fabs(a[2])) || (fabs(a[1]) >= fabs(a[0]) && fabs(a[1]) >= fabs(a[2]))) { b[0] = a[1]; b[1] = -a[0]; b[2] = 0.; } else { b[0] = 0.; b[1] = a[2]; b[2] = -a[1]; } prodve(a, b, c); jac[1][0] = b[0]; jac[1][1] = b[1]; jac[1][2] = b[2]; jac[2][0] = c[0]; jac[2][1] = c[1]; jac[2][2] = c[2]; } return sqrt(gmsh_SQU(jac[0][0])+gmsh_SQU(jac[0][1])+gmsh_SQU(jac[0][2])); default: jac[0][0] = jac[1][1] = jac[2][2] = 1.; return 1.; } } double interpolate(double val[], double u, double v, double w, int stride=1) { double sum = 0; int j = 0; for(int i = 0; i < getNumNodes(); i++){ double s; getShapeFunction(i, u, v, w, s); sum += val[j] * s; j += stride; } return sum; } void interpolateGrad(double val[], double u, double v, double w, double f[3], int stride=1, double invjac[3][3]=NULL) { double dfdu[3] = {0., 0., 0.}; int j = 0; for(int i = 0; i < getNumNodes(); i++){ double s[3]; getGradShapeFunction(i, u, v, w, s); dfdu[0] += val[j] * s[0]; dfdu[1] += val[j] * s[1]; dfdu[2] += val[j] * s[2]; j += stride; } if(invjac){ matvec(invjac, dfdu, f); } else{ double jac[3][3], inv[3][3]; getJacobian(u, v, w, jac); inv3x3(jac, inv); matvec(inv, dfdu, f); } } void interpolateCurl(double val[], double u, double v, double w, double f[3], int stride=3) { double fx[3], fy[3], fz[3], jac[3][3], inv[3][3]; getJacobian(u, v, w, jac); inv3x3(jac, inv); interpolateGrad(&val[0], u, v, w, fx, stride, inv); interpolateGrad(&val[1], u, v, w, fy, stride, inv); interpolateGrad(&val[2], u, v, w, fz, stride, inv); f[0] = fz[1] - fy[2]; f[1] = -(fz[0] - fx[2]); f[2] = fy[0] - fx[1]; } double interpolateDiv(double val[], double u, double v, double w, int stride=3) { double fx[3], fy[3], fz[3], jac[3][3], inv[3][3]; getJacobian(u, v, w, jac); inv3x3(jac, inv); interpolateGrad(&val[0], u, v, w, fx, stride, inv); interpolateGrad(&val[1], u, v, w, fy, stride, inv); interpolateGrad(&val[2], u, v, w, fz, stride, inv); return fx[0] + fy[1] + fz[2]; } double integrate(double val[], int stride=1) { double sum = 0; for(int i = 0; i < getNumGaussPoints(); i++){ double u, v, w, weight, jac[3][3]; getGaussPoint(i, u, v, w, weight); double det = getJacobian(u, v, w, jac); double d = interpolate(val, u, v, w, stride); sum += d * weight * det; } return sum; } double integrateLevelsetPositive(double val[]) { // FIXME: explain + generalize this double ones[8] = {1., 1., 1., 1., 1., 1., 1., 1.}; double area = integrate(ones); double sum = 0, sumabs = 0.; for(int i = 0; i < getNumNodes(); i++){ sum += val[i]; sumabs += fabs(val[i]); } double res = 0.; if(sumabs) res = area * (1 + sum/sumabs) * 0.5 ; return res; } virtual double integrateCirculation(double val[]) { Msg::Error("integrateCirculation not available for this element"); return 0.; } virtual double integrateFlux(double val[]) { Msg::Error("integrateFlux not available for this element"); return 0.; } virtual void xyz2uvw(double xyz[3], double uvw[3]) { // general newton routine for the nonlinear case (more efficient // routines are implemented for simplices, where the basis // functions are linear) uvw[0] = uvw[1] = uvw[2] = 0.0; int iter = 1, maxiter = 20; double error = 1., tol = 1.e-6; while (error > tol && iter < maxiter){ double jac[3][3]; if(!getJacobian(uvw[0], uvw[1], uvw[2], jac)) break; double xn = 0., yn = 0., zn = 0.; for (int i = 0; i < getNumNodes(); i++) { double s; getShapeFunction(i, uvw[0], uvw[1], uvw[2], s); xn += _x[i] * s; yn += _y[i] * s; zn += _z[i] * s; } double inv[3][3]; inv3x3(jac, inv); double un = uvw[0] + inv[0][0] * (xyz[0] - xn) + inv[1][0] * (xyz[1] - yn) + inv[2][0] * (xyz[2] - zn); double vn = uvw[1] + inv[0][1] * (xyz[0] - xn) + inv[1][1] * (xyz[1] - yn) + inv[2][1] * (xyz[2] - zn) ; double wn = uvw[2] + inv[0][2] * (xyz[0] - xn) + inv[1][2] * (xyz[1] - yn) + inv[2][2] * (xyz[2] - zn) ; error = sqrt(gmsh_SQU(un - uvw[0]) + gmsh_SQU(vn - uvw[1]) + gmsh_SQU(wn - uvw[2])); uvw[0] = un; uvw[1] = vn; uvw[2] = wn; iter++ ; } //if(error > tol) Msg::Warning("Newton did not converge in xyz2uvw") ; } virtual int isInside(double u, double v, double w) = 0; double maxEdgeLength() { double max = 0.; for(int i = 0; i < getNumEdges(); i++){ int n1, n2; getEdge(i, n1, n2); double d = sqrt(gmsh_SQU(_x[n1]-_x[n2]) + gmsh_SQU(_y[n1]-_y[n2]) + gmsh_SQU(_z[n1]-_z[n2])); if(d > max) max = d; } return max; } }; class point : public element{ public: point(double *x, double *y, double *z, int numNodes=0) : element(x, y, z, numNodes) {} inline int getDimension(){ return 0; } inline int getNumNodes(){ return 1; } void getNode(int num, double &u, double &v, double &w) { u = v = w = 0.; } inline int getNumEdges(){ return 0; } void getEdge(int num, int &start, int &end) { start = end = 0; } inline int getNumGaussPoints(){ return 1; } void getGaussPoint(int num, double &u, double &v, double &w, double &weight) { u = v = w = 0.; weight = 1.; } void getShapeFunction(int num, double u, double v, double w, double &s) { switch(num) { case 0 : s = 1.; break; default : s = 0.; break; } } void getGradShapeFunction(int num, double u, double v, double w, double s[3]) { s[0] = s[1] = s[2] = 0.; } void xyz2uvw(double xyz[3], double uvw[3]) { uvw[0] = uvw[1] = uvw[2] = 0.; } int isInside(double u, double v, double w) { if(fabs(u) > TOL || fabs(v) > TOL || fabs(w) > TOL) return 0; return 1; } }; class line : public element{ public: line(double *x, double *y, double *z, int numNodes=0) : element(x, y, z, numNodes) {} inline int getDimension(){ return 1; } inline int getNumNodes(){ return 2; } void getNode(int num, double &u, double &v, double &w) { v = w = 0.; switch(num) { case 0 : u = -1.; break; case 1 : u = 1.; break; default: u = 0.; break; } } inline int getNumEdges(){ return 1; } void getEdge(int num, int &start, int &end) { start = 0; end = 1; } inline int getNumGaussPoints(){ return 1; } void getGaussPoint(int num, double &u, double &v, double &w, double &weight) { if(num < 0 || num > 0) return; u = v = w = 0.; weight = 2.; } void getShapeFunction(int num, double u, double v, double w, double &s) { switch(num) { case 0 : s = 0.5 * (1.-u); break; case 1 : s = 0.5 * (1.+u); break; default : s = 0.; break; } } void getGradShapeFunction(int num, double u, double v, double w, double s[3]) { switch(num) { case 0 : s[0] = -0.5; s[1] = 0.; s[2] = 0.; break; case 1 : s[0] = 0.5; s[1] = 0.; s[2] = 0.; break; default : s[0] = s[1] = s[2] = 0.; break; } } double integrateCirculation(double val[]) { double t[3] = {_x[1]-_x[0], _y[1]-_y[0], _z[1]-_z[0]}; norme(t); double v[3]; for(int i = 0; i < 3; i++) v[i] = integrate(&val[i], 3); double d; prosca(t, v, &d); return d; } int isInside(double u, double v, double w) { if(u < -(1. + TOL) || u > (1. + TOL) || fabs(v) > TOL || fabs(w) > TOL) return 0; return 1; } }; class triangle : public element{ public: triangle(double *x, double *y, double *z, int numNodes=0) : element(x, y, z, numNodes) {} inline int getDimension(){ return 2; } inline int getNumNodes(){ return 3; } void getNode(int num, double &u, double &v, double &w) { w = 0.; switch(num) { case 0 : u = 0.; v = 0.; break; case 1 : u = 1.; v = 0.; break; case 2 : u = 0.; v = 1.; break; default: u = 0.; v = 0.; break; } } inline int getNumEdges(){ return 3; } void getEdge(int num, int &start, int &end) { switch(num) { case 0 : start = 0; end = 1; break; case 1 : start = 1; end = 2; break; case 2 : start = 2; end = 0; break; default: start = end = 0; break; } } inline int getNumGaussPoints(){ return /* 3 */ 1; } void getGaussPoint(int num, double &u, double &v, double &w, double &weight) { /* static double u3[3] = {0.16666666666666,0.66666666666666,0.16666666666666}; static double v3[3] = {0.16666666666666,0.16666666666666,0.66666666666666}; static double p3[3] = {0.16666666666666,0.16666666666666,0.16666666666666}; if(num < 0 || num > 2) return; u = u3[num]; v = v3[num]; w = 0.; weight = p3[num]; */ if(num < 0 || num > 0) return; u = v = 0.333333333333333; w = 0.; weight = 0.5; } void getShapeFunction(int num, double u, double v, double w, double &s) { switch(num){ case 0 : s = 1.-u-v; break; case 1 : s = u ; break; case 2 : s = v; break; default : s = 0.; break; } } void getGradShapeFunction(int num, double u, double v, double w, double s[3]) { switch(num) { case 0 : s[0] = -1.; s[1] = -1.; s[2] = 0.; break; case 1 : s[0] = 1.; s[1] = 0.; s[2] = 0.; break; case 2 : s[0] = 0.; s[1] = 1.; s[2] = 0.; break; default : s[0] = s[1] = s[2] = 0.; break; } } double integrateFlux(double val[]) { double t1[3] = {_x[1]-_x[0], _y[1]-_y[0], _z[1]-_z[0]}; double t2[3] = {_x[2]-_x[0], _y[2]-_y[0], _z[2]-_z[0]}; double n[3]; prodve(t1, t2, n); norme(n); double v[3]; for(int i = 0; i < 3; i++) v[i] = integrate(&val[i], 3); double d; prosca(n, v, &d); return d; } #if 0 // faster, but only valid for triangles in the z=0 plane void xyz2uvw(double xyz[3], double uvw[3]) { double mat[2][2], b[2]; mat[0][0] = _x[1] - _x[0]; mat[0][1] = _x[2] - _x[0]; mat[1][0] = _y[1] - _y[0]; mat[1][1] = _y[2] - _y[0]; b[0] = xyz[0] - _x[0]; b[1] = xyz[1] - _y[0]; sys2x2(mat, b, uvw); uvw[2] = 0.; } #endif int isInside(double u, double v, double w) { if(u < -TOL || v < -TOL || u > ((1. + TOL) - v) || fabs(w) > TOL) return 0; return 1; } }; class quadrangle : public element{ public: quadrangle(double *x, double *y, double *z, int numNodes=0) : element(x, y, z, numNodes) {} inline int getDimension(){ return 2; } inline int getNumNodes(){ return 4; } void getNode(int num, double &u, double &v, double &w) { w = 0.; switch(num) { case 0 : u = -1.; v = -1.; break; case 1 : u = 1.; v = -1.; break; case 2 : u = 1.; v = 1.; break; case 3 : u = -1.; v = 1.; break; default: u = 0.; v = 0.; break; } } inline int getNumEdges(){ return 4; } void getEdge(int num, int &start, int &end) { switch(num) { case 0 : start = 0; end = 1; break; case 1 : start = 1; end = 2; break; case 2 : start = 2; end = 3; break; case 3 : start = 3; end = 0; break; default: start = end = 0; break; } } inline int getNumGaussPoints(){ return 4; } void getGaussPoint(int num, double &u, double &v, double &w, double &weight) { static double u4[4] = {0.577350269189,-0.577350269189,0.577350269189,-0.577350269189}; static double v4[4] = {0.577350269189,0.577350269189,-0.577350269189,-0.577350269189}; static double p4[4] = {1.,1.,1.,1.}; if(num < 0 || num > 3) return; u = u4[num]; v = v4[num]; w = 0.; weight = p4[num]; } void getShapeFunction(int num, double u, double v, double w, double &s) { switch(num) { case 0 : s = 0.25 * (1.-u) * (1.-v); break; case 1 : s = 0.25 * (1.+u) * (1.-v); break; case 2 : s = 0.25 * (1.+u) * (1.+v); break; case 3 : s = 0.25 * (1.-u) * (1.+v); break; default : s = 0.; break; } } void getGradShapeFunction(int num, double u, double v, double w, double s[3]) { switch(num) { case 0 : s[0] = -0.25 * (1.-v); s[1] = -0.25 * (1.-u); s[2] = 0.; break; case 1 : s[0] = 0.25 * (1.-v); s[1] = -0.25 * (1.+u); s[2] = 0.; break; case 2 : s[0] = 0.25 * (1.+v); s[1] = 0.25 * (1.+u); s[2] = 0.; break; case 3 : s[0] = -0.25 * (1.+v); s[1] = 0.25 * (1.-u); s[2] = 0.; break; default : s[0] = s[1] = s[2] = 0.; break; } } double integrateFlux(double val[]) { double t1[3] = {_x[1]-_x[0], _y[1]-_y[0], _z[1]-_z[0]}; double t2[3] = {_x[2]-_x[0], _y[2]-_y[0], _z[2]-_z[0]}; double n[3]; prodve(t1, t2, n); norme(n); double v[3]; for(int i = 0; i < 3; i++) v[i] = integrate(&val[i], 3); double d; prosca(n, v, &d); return d; } int isInside(double u, double v, double w) { if(u < -(1. + TOL) || v < -(1. + TOL) || u > (1. + TOL) || v > (1. + TOL) || fabs(w) > TOL) return 0; return 1; } }; class tetrahedron : public element{ public: tetrahedron(double *x, double *y, double *z, int numNodes=0) : element(x, y, z, numNodes) {} inline int getDimension(){ return 3; } inline int getNumNodes(){ return 4; } void getNode(int num, double &u, double &v, double &w) { switch(num) { case 0 : u = 0.; v = 0.; w = 0.; break; case 1 : u = 1.; v = 0.; w = 0.; break; case 2 : u = 0.; v = 1.; w = 0.; break; case 3 : u = 0.; v = 0.; w = 1.; break; default: u = 0.; v = 0.; w = 0.; break; } } inline int getNumEdges(){ return 6; } void getEdge(int num, int &start, int &end) { switch(num) { case 0 : start = 0; end = 1; break; case 1 : start = 1; end = 2; break; case 2 : start = 2; end = 0; break; case 3 : start = 3; end = 0; break; case 4 : start = 3; end = 2; break; case 5 : start = 3; end = 1; break; default: start = end = 0; break; } } inline int getNumGaussPoints(){ return 4; } void getGaussPoint(int num, double &u, double &v, double &w, double &weight) { static double u4[4] = {0.138196601125,0.138196601125,0.138196601125,0.585410196625}; static double v4[4] = {0.138196601125,0.138196601125,0.585410196625,0.138196601125}; static double w4[4] = {0.138196601125,0.585410196625,0.138196601125,0.138196601125}; static double p4[4] = {0.0416666666667,0.0416666666667,0.0416666666667,0.0416666666667}; if(num < 0 || num > 3) return; u = u4[num]; v = v4[num]; w = w4[num]; weight = p4[num]; } void getShapeFunction(int num, double u, double v, double w, double &s) { switch(num) { case 0 : s = 1.-u-v-w; break; case 1 : s = u ; break; case 2 : s = v ; break; case 3 : s = w; break; default : s = 0.; break; } } void getGradShapeFunction(int num, double u, double v, double w, double s[3]) { switch(num) { case 0 : s[0] = -1.; s[1] = -1.; s[2] = -1.; break; case 1 : s[0] = 1.; s[1] = 0.; s[2] = 0.; break; case 2 : s[0] = 0.; s[1] = 1.; s[2] = 0.; break; case 3 : s[0] = 0.; s[1] = 0.; s[2] = 1.; break; default : s[0] = s[1] = s[2] = 0.; break; } } void xyz2uvw(double xyz[3], double uvw[3]) { double mat[3][3], b[3]; mat[0][0] = _x[1] - _x[0]; mat[0][1] = _x[2] - _x[0]; mat[0][2] = _x[3] - _x[0]; mat[1][0] = _y[1] - _y[0]; mat[1][1] = _y[2] - _y[0]; mat[1][2] = _y[3] - _y[0]; mat[2][0] = _z[1] - _z[0]; mat[2][1] = _z[2] - _z[0]; mat[2][2] = _z[3] - _z[0]; b[0] = xyz[0] - _x[0]; b[1] = xyz[1] - _y[0]; b[2] = xyz[2] - _z[0]; double det; sys3x3(mat, b, uvw, &det); } int isInside(double u, double v, double w) { if(u < (-TOL) || v < (-TOL) || w < (-TOL) || u > ((1. + TOL) - v - w)) return 0; return 1; } }; class hexahedron : public element{ public: hexahedron(double *x, double *y, double *z, int numNodes=0) : element(x, y, z, numNodes) {} inline int getDimension(){ return 3; } inline int getNumNodes(){ return 8; } void getNode(int num, double &u, double &v, double &w) { switch(num) { case 0 : u = -1.; v = -1.; w = -1.; break; case 1 : u = 1.; v = -1.; w = -1.; break; case 2 : u = 1.; v = 1.; w = -1.; break; case 3 : u = -1.; v = 1.; w = -1.; break; case 4 : u = -1.; v = -1.; w = 1.; break; case 5 : u = 1.; v = -1.; w = 1.; break; case 6 : u = 1.; v = 1.; w = 1.; break; case 7 : u = -1.; v = 1.; w = 1.; break; default: u = 0.; v = 0.; w = 0.; break; } } inline int getNumEdges(){ return 12; } void getEdge(int num, int &start, int &end) { switch(num) { case 0 : start = 0; end = 1; break; case 1 : start = 0; end = 3; break; case 2 : start = 0; end = 4; break; case 3 : start = 1; end = 2; break; case 4 : start = 1; end = 5; break; case 5 : start = 2; end = 3; break; case 6 : start = 2; end = 6; break; case 7 : start = 3; end = 7; break; case 8 : start = 4; end = 5; break; case 9 : start = 4; end = 7; break; case 10: start = 5; end = 6; break; case 11: start = 6; end = 7; break; default: start = end = 0; break; } } inline int getNumGaussPoints(){ return 6; } void getGaussPoint(int num, double &u, double &v, double &w, double &weight) { static double u6[6] = { 0.40824826, 0.40824826, -0.40824826, -0.40824826, -0.81649658, 0.81649658}; static double v6[6] = { 0.70710678, -0.70710678, 0.70710678, -0.70710678, 0., 0.}; static double w6[6] = {-0.57735027, -0.57735027, 0.57735027, 0.57735027, -0.57735027, 0.57735027}; static double p6[6] = { 1.3333333333, 1.3333333333, 1.3333333333, 1.3333333333, 1.3333333333, 1.3333333333}; if(num < 0 || num > 5) return; u = u6[num]; v = v6[num]; w = w6[num]; weight = p6[num]; } void getShapeFunction(int num, double u, double v, double w, double &s) { switch(num) { case 0 : s = (1.-u) * (1.-v) * (1.-w) * 0.125; break; case 1 : s = (1.+u) * (1.-v) * (1.-w) * 0.125; break; case 2 : s = (1.+u) * (1.+v) * (1.-w) * 0.125; break; case 3 : s = (1.-u) * (1.+v) * (1.-w) * 0.125; break; case 4 : s = (1.-u) * (1.-v) * (1.+w) * 0.125; break; case 5 : s = (1.+u) * (1.-v) * (1.+w) * 0.125; break; case 6 : s = (1.+u) * (1.+v) * (1.+w) * 0.125; break; case 7 : s = (1.-u) * (1.+v) * (1.+w) * 0.125; break; default : s = 0.; break; } } void getGradShapeFunction(int num, double u, double v, double w, double s[3]) { switch(num) { case 0 : s[0] = -0.125 * (1.-v) * (1.-w); s[1] = -0.125 * (1.-u) * (1.-w); s[2] = -0.125 * (1.-u) * (1.-v); break; case 1 : s[0] = 0.125 * (1.-v) * (1.-w); s[1] = -0.125 * (1.+u) * (1.-w); s[2] = -0.125 * (1.+u) * (1.-v); break; case 2 : s[0] = 0.125 * (1.+v) * (1.-w); s[1] = 0.125 * (1.+u) * (1.-w); s[2] = -0.125 * (1.+u) * (1.+v); break; case 3 : s[0] = -0.125 * (1.+v) * (1.-w); s[1] = 0.125 * (1.-u) * (1.-w); s[2] = -0.125 * (1.-u) * (1.+v); break; case 4 : s[0] = -0.125 * (1.-v) * (1.+w); s[1] = -0.125 * (1.-u) * (1.+w); s[2] = 0.125 * (1.-u) * (1.-v); break; case 5 : s[0] = 0.125 * (1.-v) * (1.+w); s[1] = -0.125 * (1.+u) * (1.+w); s[2] = 0.125 * (1.+u) * (1.-v); break; case 6 : s[0] = 0.125 * (1.+v) * (1.+w); s[1] = 0.125 * (1.+u) * (1.+w); s[2] = 0.125 * (1.+u) * (1.+v); break; case 7 : s[0] = -0.125 * (1.+v) * (1.+w); s[1] = 0.125 * (1.-u) * (1.+w); s[2] = 0.125 * (1.-u) * (1.+v); break; default : s[0] = s[1] = s[2] = 0.; break; } } int isInside(double u, double v, double w) { if(u < -(1. + TOL) || v < -(1. + TOL) || w < -(1. + TOL) || u > (1. + TOL) || v > (1. + TOL) || w > (1. + TOL)) return 0; return 1; } }; class prism : public element{ public: prism(double *x, double *y, double *z, int numNodes=0) : element(x, y, z, numNodes) {} inline int getDimension(){ return 3; } inline int getNumNodes(){ return 6; } void getNode(int num, double &u, double &v, double &w) { switch(num) { case 0 : u = 0.; v = 0.; w = -1.; break; case 1 : u = 1.; v = 0.; w = -1.; break; case 2 : u = 0.; v = 1.; w = -1.; break; case 3 : u = 0.; v = 0.; w = 1.; break; case 4 : u = 1.; v = 0.; w = 1.; break; case 5 : u = 0.; v = 1.; w = 1.; break; default: u = 0.; v = 0.; w = 0.; break; } } inline int getNumEdges(){ return 9; } void getEdge(int num, int &start, int &end) { switch(num) { case 0 : start = 0; end = 1; break; case 1 : start = 0; end = 2; break; case 2 : start = 0; end = 3; break; case 3 : start = 1; end = 2; break; case 4 : start = 1; end = 4; break; case 5 : start = 2; end = 5; break; case 6 : start = 3; end = 4; break; case 7 : start = 3; end = 5; break; case 8 : start = 4; end = 5; break; default: start = end = 0; break; } } inline int getNumGaussPoints(){ return 6; } void getGaussPoint(int num, double &u, double &v, double &w, double &weight) { static double u6[6] = {0.166666666666666, 0.333333333333333, 0.166666666666666, 0.166666666666666, 0.333333333333333, 0.166666666666666}; static double v6[6] = {0.166666666666666, 0.166666666666666, 0.333333333333333, 0.166666666666666, 0.166666666666666, 0.333333333333333}; static double w6[6] = {-0.577350269189, -0.577350269189, -0.577350269189, 0.577350269189, 0.577350269189, 0.577350269189}; static double p6[6] = {0.166666666666666,0.166666666666666,0.166666666666666, 0.166666666666666,0.166666666666666,0.166666666666666,}; if(num < 0 || num > 5) return; u = u6[num]; v = v6[num]; w = w6[num]; weight = p6[num]; } void getShapeFunction(int num, double u, double v, double w, double &s) { switch(num) { case 0 : s = (1.-u-v) * (1.-w) * 0.5; break; case 1 : s = u * (1.-w) * 0.5; break; case 2 : s = v * (1.-w) * 0.5; break; case 3 : s = (1.-u-v) * (1.+w) * 0.5; break; case 4 : s = u * (1.+w) * 0.5; break; case 5 : s = v * (1.+w) * 0.5; break; default : s = 0.; break; } } void getGradShapeFunction(int num, double u, double v, double w, double s[3]) { switch(num) { case 0 : s[0] = -0.5 * (1.-w) ; s[1] = -0.5 * (1.-w) ; s[2] = -0.5 * (1.-u-v) ; break ; case 1 : s[0] = 0.5 * (1.-w) ; s[1] = 0. ; s[2] = -0.5 * u ; break ; case 2 : s[0] = 0. ; s[1] = 0.5 * (1.-w) ; s[2] = -0.5 * v ; break ; case 3 : s[0] = -0.5 * (1.+w) ; s[1] = -0.5 * (1.+w) ; s[2] = 0.5 * (1.-u-v) ; break ; case 4 : s[0] = 0.5 * (1.+w) ; s[1] = 0. ; s[2] = 0.5 * u ; break ; case 5 : s[0] = 0. ; s[1] = 0.5 * (1.+w) ; s[2] = 0.5 * v ; break ; default : s[0] = s[1] = s[2] = 0.; break; } } int isInside(double u, double v, double w) { if(w > (1. + TOL) || w < -(1. + TOL) || u < (-TOL) || v < (-TOL) || u > ((1. + TOL) - v)) return 0; return 1; } }; class pyramid : public element{ public: pyramid(double *x, double *y, double *z, int numNodes=0) : element(x, y, z, numNodes) {} inline int getDimension(){ return 3; } inline int getNumNodes(){ return 5; } void getNode(int num, double &u, double &v, double &w) { switch(num) { case 0 : u = -1.; v = -1.; w = 0.; break; case 1 : u = 1.; v = -1.; w = 0.; break; case 2 : u = 1.; v = 1.; w = 0.; break; case 3 : u = -1.; v = 1.; w = 0.; break; case 4 : u = 0.; v = 0.; w = 1.; break; default: u = 0.; v = 0.; w = 0.; break; } } inline int getNumEdges(){ return 8; } void getEdge(int num, int &start, int &end) { switch(num) { case 0 : start = 0; end = 1; break; case 1 : start = 0; end = 3; break; case 2 : start = 0; end = 4; break; case 3 : start = 1; end = 2; break; case 4 : start = 1; end = 4; break; case 5 : start = 2; end = 3; break; case 6 : start = 2; end = 4; break; case 7 : start = 3; end = 4; break; default: start = end = 0; break; } } inline int getNumGaussPoints(){ return 8; } void getGaussPoint(int num, double &u, double &v, double &w, double &weight) { static double u8[8] = {0.2631840555694285,-0.2631840555694285, 0.2631840555694285,-0.2631840555694285, 0.5066163033492386,-0.5066163033492386, 0.5066163033492386,-0.5066163033492386}; static double v8[8] = {0.2631840555694285,0.2631840555694285, -0.2631840555694285,-0.2631840555694285, 0.5066163033492386,0.5066163033492386, -0.5066163033492386,-0.5066163033492386}; static double w8[8] = {0.544151844011225,0.544151844011225, 0.544151844011225,0.544151844011225, 0.122514822655441,0.122514822655441, 0.122514822655441,0.122514822655441}; static double p8[8] = {0.100785882079825,0.100785882079825, 0.100785882079825,0.100785882079825, 0.232547451253508,0.232547451253508, 0.232547451253508,0.232547451253508}; if(num < 0 || num > 7) return; u = u8[num]; v = v8[num]; w = w8[num]; weight = p8[num]; } void getShapeFunction(int num, double u, double v, double w, double &s) { double r; if(w != 1. && num != 4) r = u*v*w / (1.-w); else r = 0.; switch(num) { case 0 : s = 0.25 * ((1.-u) * (1.-v) - w + r); break; case 1 : s = 0.25 * ((1.+u) * (1.-v) - w - r); break; case 2 : s = 0.25 * ((1.+u) * (1.+v) - w + r); break; case 3 : s = 0.25 * ((1.-u) * (1.+v) - w - r); break; case 4 : s = w ; break; default : s = 0. ; break; } } void getGradShapeFunction(int num, double u, double v, double w, double s[3]) { if(w == 1.) { switch(num) { case 0 : s[0] = -0.25 ; s[1] = -0.25 ; s[2] = -0.25 ; break ; case 1 : s[0] = 0.25 ; s[1] = -0.25 ; s[2] = -0.25 ; break ; case 2 : s[0] = 0.25 ; s[1] = 0.25 ; s[2] = -0.25 ; break ; case 3 : s[0] = -0.25 ; s[1] = 0.25 ; s[2] = -0.25 ; break ; case 4 : s[0] = 0. ; s[1] = 0. ; s[2] = 1. ; break ; default : s[0] = s[1] = s[2] = 0.; break; } } else{ switch(num) { case 0 : s[0] = 0.25 * ( -(1.-v) + v*w/(1.-w) ) ; s[1] = 0.25 * ( -(1.-u) + u*w/(1.-w) ) ; s[2] = 0.25 * ( -1. + u*v/(1.-w) + u*v*w/gmsh_SQU(1.-w) ) ; break ; case 1 : s[0] = 0.25 * ( (1.-v) - v*w/(1.-w) ) ; s[1] = 0.25 * ( -(1.+u) - u*w/(1.-w) ) ; s[2] = 0.25 * ( -1. - u*v/(1.-w) - u*v*w/gmsh_SQU(1.-w) ) ; break ; case 2 : s[0] = 0.25 * ( (1.+v) + v*w/(1.-w) ) ; s[1] = 0.25 * ( (1.+u) + u*w/(1.-w) ) ; s[2] = 0.25 * ( -1. + u*v/(1.-w) + u*v*w/gmsh_SQU(1.-w) ) ; break ; case 3 : s[0] = 0.25 * ( -(1.+v) - v*w/(1.-w) ) ; s[1] = 0.25 * ( (1.-u) - u*w/(1.-w) ) ; s[2] = 0.25 * ( -1. - u*v/(1.-w) - u*v*w/gmsh_SQU(1.-w) ) ; break ; case 4 : s[0] = 0. ; s[1] = 0. ; s[2] = 1. ; break ; default : s[0] = s[1] = s[2] = 0.; break; } } } int isInside(double u, double v, double w) { if(u < (w - (1. + TOL)) || u > ((1. + TOL) - w) || v < (w - (1. + TOL)) || v > ((1. + TOL) - w) || w < (-TOL) || w > (1. + TOL)) return 0; return 1; } }; class elementFactory{ public: element* create(int numNodes, int dimension, double *x, double *y, double *z, bool copy=false) { switch(dimension){ case 0: return new point(x, y, z, copy ? numNodes : 0); case 1: return new line(x, y, z, copy ? numNodes : 0); case 2: if(numNodes == 4) return new quadrangle(x, y, z, copy ? numNodes : 0); else return new triangle(x, y, z, copy ? numNodes : 0); case 3: if(numNodes == 8) return new hexahedron(x, y, z, copy ? numNodes : 0); else if(numNodes == 6) return new prism(x, y, z, copy ? numNodes : 0); else if(numNodes == 5) return new pyramid(x, y, z, copy ? numNodes : 0); else return new tetrahedron(x, y, z, copy ? numNodes : 0); default: Msg::Error("Unknown type of element in factory"); return NULL; } } }; #undef SQU #endif
true
0ebc71f94136d3df74a8daa6253288e9bdcc212e
C++
ayundina/cpp_piscine
/day01/ex07/src/ClassInput.cpp
UTF-8
402
2.8125
3
[]
no_license
#include "ClassInput.hpp" Input::Input(const std::string &input_file_name) { _input_file.open(input_file_name); if (!_input_file.is_open()) { _error.showAndExit("Unable to open " + input_file_name + " file"); } } Input::~Input() { _input_file.close(); return; } bool Input::getLine(std::string &line) { bool ret = false; ret = static_cast<bool>(getline(_input_file, line)); return ret; }
true
8cb1d746dd7d0d935f1b20d6b1e444fdc191082c
C++
Fissuras/snow-leopard
/Snow Leopard/Snow Leopard/XercesString.h
UTF-8
5,941
3
3
[]
no_license
/* ========== Beginning of file XercesString.h ========== */ /*! \file XercesString.h \brief Definition of class XercesString. */ #ifndef _XMLDB_XERCES_STRING_H_ # define _XMLDB_XERCES_STRING_H_ // ========== Includes ========== // ----- standard header ----- #include <ostream> // operator<<() #include <string> // std::string // ----- xerces header ----- #include <xercesc/util/XMLString.hpp> // XMLCh* XERCES_CPP_NAMESPACE_USE // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // ========== Classes ========== // ###################################################################### //! Wrapper class for string conversion. // ---------------------------------------------------------------------- /*! */ // ###################################################################### class XercesString { public: // --- public methods --- // ******************************************************************** //! Constructor for STL string. // -------------------------------------------------------------------- /*! \param pStr STL string to be used as content. Can be omitted, if epmty. */ // ******************************************************************** XercesString( const std::string& str_ = std::string() ) : m_pXercesCh( 0 ), m_Str( str_ ), m_StrIsValid( true ) {} // ******************************************************************** //! Constructor for xerces-c string. // -------------------------------------------------------------------- /*! \param pXmlCh xerces-c char array to be used as content \param pOwner flag, if the XercesString should take ownership of array */ // ******************************************************************** XercesString( const XMLCh* pXmlCh_, bool owner_ = false ) : m_pXercesCh( const_cast<XMLCh*>( pXmlCh_ ) ), m_HaveOwnership( owner_ ), m_StrIsValid( false ) {} // ******************************************************************** //! Desctructor. // ******************************************************************** ~XercesString() { if ( m_pXercesCh && m_HaveOwnership ) { XMLString::release( &m_pXercesCh ); } } // ******************************************************************** //! Conversion to STL string. // -------------------------------------------------------------------- /*! \return STL string */ // ******************************************************************** const std::string& stdStr() const { /* ------------------------------------------------------------ - if the string need to be converted yet - create a char array via transcode - copy the char array to the string - set validity flag - release the memory for the temporary char array - return the string ------------------------------------------------------------ */ if ( ! m_StrIsValid ) { char* chStr = XMLString::transcode( m_pXercesCh ); m_Str = chStr; m_StrIsValid = true; XMLString::release( &chStr ); } return m_Str; } // ******************************************************************** //! Conversion to xerces-c char array. // -------------------------------------------------------------------- /*! \return xerces-c char array (ownership stays in XercesString object) */ // ******************************************************************** const XMLCh* xmlCh() const { if ( ! m_pXercesCh ) { m_pXercesCh = XMLString::transcode( m_Str.c_str() ); m_HaveOwnership = true; } return m_pXercesCh; } operator std::string () const { return this->stdStr(); } private: // --- private methods --- //! Disable copy constructor. XercesString( const XercesString& ); //! Disable assignment operator. const XercesString& operator=( const XercesString& ); private: // --- private attributes --- mutable XMLCh* m_pXercesCh; //!< xerces-c representation of the string mutable bool m_HaveOwnership; //!< flag to know, if the instance has the ownership of the xerces string mutable std::string m_Str; //!< STL representation of the string mutable bool m_StrIsValid; //!< flag if STL string is initialized yet }; // ### class XercesString ### // ********************************************************************** //! Output stream operator. // ---------------------------------------------------------------------- /*! \param pStream floating stream (input) \param pString string to be output \return floating stream (output) */ // ********************************************************************** inline std::ostream& operator<<( std::ostream& stream_, const XercesString& string_ ) { return stream_ << string_.stdStr(); } // *** operator<<() *** // ********************************************************************** //! Output stream operator for XMLCh*. // ---------------------------------------------------------------------- /*! \param pStream floating stream (input) \param pCh xml string to be output \return floating stream (output) */ // ********************************************************************** inline std::ostream& operator<<( std::ostream& stream_, const XMLCh* pCh_ ) { /* ------------------------------------------------------------ - return, if the xerces string pointer is invalid - create a char array from the xerces string via transcode - append the char array to the stream - release memory for the char array - return the stream ------------------------------------------------------------ */ if ( NULL == pCh_ ) { return stream_; } char* pCh = XMLString::transcode( pCh_ ); stream_ << pCh; XMLString::release( &pCh ); return stream_; } // *** operator<<() *** #endif // --- #ifndef _XMLDB_XERCES_STRING_H_ --- /* ========== End of file XercesString.h ========== */
true
029d05cc86e56fe376bfa6a77561fc8b4e2ce1bd
C++
esean/codingground
/linklistCPP/main.cpp
UTF-8
1,742
3.734375
4
[]
no_license
#include <iostream> #include <stdbool.h> using namespace std; template<class T> class node { public: node() { pNext=NULL; } node(T v) { value=v; pNext=NULL; } ~node() {} void dump() { dumper(this); } void set_value(T val) { this->value = val; } void add_node(node* pNode) { this->pNext = pNode; } bool is_circular(); private: node* pNext; T value; void dumper(node* start); }; template<class T> void node<T>::dumper(node<T>* start) { int i = 0; cout << i << ":" << start->value << endl; while (start->pNext) { ++i; start = start->pNext; cout << i << ":" << start->value << endl; } } template<class T> bool node<T>::is_circular() { node<T>* n1 = this; node<T>* n2 = this; if (!n1) return false; n2 = n2->pNext; while (n1) { printf(" is_circ: %d == %d ?\n",n1->value,n2->value); if (n1==n2) return true; if (!n1 || !n2 || !n1->pNext || !n2->pNext->pNext) return false; n1 = n1->pNext; n2 = n2->pNext->pNext; } // can't get here return false; } int main() { // INT //----------------- node<int> first(1); node<int> second(2); node<int> third(3); node<int> four(4); first.add_node(&second); second.add_node(&third); third.add_node(&four); printf("Before making circular:\n"); first.dump(); // make circular four.add_node(&first); // NO! - don't call //first.dump(); printf("INT Buffer is %s circular\n", first.is_circular() ? "YES" : "NOT"); // CHAR //----------------- node<char> c1('a'); node<char> c2('b'); node<char> c3('c'); c1.add_node(&c2); c2.add_node(&c3); c1.dump(); printf("CHAR Buffer is %s circular\n", c1.is_circular() ? "YES" : "NOT"); return 0; }
true
2f747f2739d21d8e5958137fed46e64325a916e2
C++
nik3212/challenges
/LeetCode/189. Rotate Array/solution_2.cpp
UTF-8
1,250
3.84375
4
[ "MIT" ]
permissive
/* 189. Rotate Array Given an array, rotate the array to the right by k steps, where k is non-negative. Follow up: * Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. * Could you do it in-place with O(1) extra space? Example 1: Input: nums = [1,2,3,4,5,6,7], k = 3 Output: [5,6,7,1,2,3,4] Explanation: rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps to the right: [6,7,1,2,3,4,5] rotate 3 steps to the right: [5,6,7,1,2,3,4] Example 2: Input: nums = [-1,-100,3,99], k = 2 Output: [3,99,-1,-100] Explanation: rotate 1 steps to the right: [99,-1,-100,3] rotate 2 steps to the right: [3,99,-1,-100] */ class Solution { void reverse(vector<int>&nums, int start, int end) { while (start < end) { swap(nums[start++], nums[end--]); } } void swapArray(vector<int>& nums, int l, int r) { while (l < r) { swap(nums[l++], nums[r--]); } } public: void rotate(vector<int>& nums, int k) { if (k == 0) { return; } k = k % nums.size(); int n = nums.size(); reverse(nums, 0, n - 1); reverse(nums, 0, k - 1); reverse(nums, k, n - 1); } };
true
e879f90b7c30d94c5ac2bf1618353fe5b2cd0a04
C++
Girl-Code-It/Beginner-CPP-Submissions
/Harsha Gupta/Milestone 11/Code For Win Q10.cpp
UTF-8
699
4.0625
4
[]
no_license
//Deletion from Array #include<iostream> #include<conio.h> using namespace std; void del(int a[], int size, int x) { int flag=0,pos; for(int i=0;i<size;i++) { if(a[i]==x) { flag=1; pos=i; } } if(flag==0) { cout<<"\nElement not found to delete."; } else if(flag==1) { for(int i=pos;i<size;i++) { a[i]=a[i+1]; } } } int main() { int size,val; cout<<"Enter the size of array: "; cin>>size; int a[size]; cout<<"\nEnter the elements of Array: "; for(int i=0;i<size;i++) { cin>>a[i]; } cout<<"\nEnter the element to delete: "; cin>>val; del(a,size,val); cout<<"\nElements of Array are: "; for(int i=0;i<size-1;i++) { cout<<a[i]<<" "; } return 0; }
true
80bcc18b5248d8f657bc3587624b5710039280c2
C++
david-xue/chess-x11
/pawn.cc
UTF-8
2,678
2.6875
3
[]
no_license
#include "pawn.h" #include "posn.h" #include "move.h" #include <cstdlib> #include <vector> #include "chessboard.h" using namespace std; Pawn::Pawn(ChessBoard* b, char c, bool player) : Piece(b, c, player), prom(0) {} Pawn::~Pawn() { delete prom; } int Pawn::val() { return prom ? prom->val() : 1; } char Pawn::getName() { return prom ? prom->getName() : name; } void Pawn::promote(Piece* p) { prom = p; owner ? p->update(pos, covers, threats) : p->update(pos, covers, threats); } int Pawn::canReach(const Posn posn) { if (prom) return prom->canReach(posn); int o = board->isOccupied(posn, owner); if (owner) { if (posn.col == pos.col) { if (posn.row == pos.row - 2) { if (!moved) { if (board->isOccupied(Posn(pos.row-1,posn.col), owner) == 0) { return o ? 0 : 1; } else { return 0; } } else return 0; } else if (posn.row == pos.row - 1) return o ? 0 : (posn.row == 0 && prom == 0 ? 3 : 1); } if (abs(posn.col - pos.col) == 1) { if (posn.row == pos.row - 1) { return o ? (posn.row == 0 && prom == 0 ? 3 : 1) : isenPassant(posn); } else return 0; } } else { if (posn.col == pos.col) { if (posn.row == pos.row + 2) { if (board->isOccupied(Posn(pos.row+1, posn.col), owner)) return 0; if (!moved) return o ? 0 : (posn.row == 7 && prom == 0 ? 3 : 1); else return 0; } else if (posn.row == pos.row + 1) return o ? 0 : (posn.row == 7 && prom == 0 ? 3 : 1); } if (abs(posn.col - pos.col) == 1) { if (posn.row == pos.row + 1) { return o ? (posn.row == 7 ? 3 : 1) : isenPassant(posn); } else return 0; } } return 0; } int Pawn::isenPassant(const Posn posn) { if (prom) return 0; Posn p (pos.row, posn.col); if (board->getRecord()->size() == 0) return 0; Move m = (board->getRecord())->back(); Posn o (owner ? 1 : 6, posn.col); if (m.orig == o && m.dest == p && m.name == (owner ? 'p' : 'P')) { return 4; } else return 0; } void Pawn::unpromote() { delete prom; prom = 0; } void Pawn::update(const Posn p, vector<Piece*> white, vector<Piece*> black) { if (!(pos == Posn(-1, -1)) && !(pos == p)) moved = true; else { vector<Move>* record = board->getRecord(); bool res = false; if (record->size()) { for (vector<Move>::reverse_iterator i = record->rbegin(); i != record->rend(); i++) { if (i->mover == this) { res = true; break; } } } moved = res; } pos = p; threats = owner ? black : white; covers = owner ? white : black; Threatened = threats.empty() ? false : true; Covered = covers.empty() ? false : true; }
true
1f8e3a27a1ba6408d2cd89b74a47c30194e31aa3
C++
songxinjianqwe/CppPrimerCode
/TextQuery/header/QueryBase.h
GB18030
2,558
3.09375
3
[]
no_license
/* * QueryBase.h * * Created on: 2016926 * Author: songx */ #ifndef QUERYBASE_H_ #define QUERYBASE_H_ #include "TextQuery.h" //ԭıѯϽչ //һʣʲѯ // ~(word1) õвƥѯ // (word1|word2) һ // (word1&word2) ƥȫ //ʹ word1 & word2 | word3 //Dzѯ䣬ʹԲʾѯͺִеĴ //((fiery & bird)|wind) //ṹ //QueryBase вѯij //WordQuery ѯij //NotQuery //BinaryQuery ࣬ʾIJѯ //AndQuery ̳BinaryQuery //OrQuery ̳BinaryQuery //Щ඼eval һTextQuery󣬷һQueryResult //rep ػѯstringʽ //QueryBaseevalrepΪ麯 //ΪAndQueryOrQuery಻ͬԶһBinaryQueryλǵij //ιϵڽӿ //Query q = Query("word1") & Query("word2") | Query("word3") //û뽫ֱʹЩ̳е //ǽһQueryĶӿڵ࣬ûֻӴQuery //Queryฺ̳ϵ //QueryཫһQueryBaseָ룬ָ󶨵QueryBaseС //QueryĶӿںQueryBaseһ£evalѯrepûɲѯstringʽ //Queryṩһص<<ʾѯ //ûͨQueryIJӵشQueryBase //QueryԼһstringQuery캯 //Щ̬һµQueryBase //& һ󶨵µAndQueryϵQuery //| һ󶨵µOrQueryϵQuery //~ һ󶨵µNotQueryϵQuery class QueryBase{ friend class Query; protected: virtual ~QueryBase() = default; private: virtual QueryResult eval(TextQuery &) const = 0; virtual string rep() const = 0; }; //DzϣûֱʹQueryBaseûpublicԱ //жQueryBaseʹöҪͨQuery //ΪQueryQueryBase˽гԱԶΪԪ #endif /* QUERYBASE_H_ */
true
658f8ca7a43561c950ac3ba181191d56508ce0e0
C++
Jereq/PongOut
/client/src/Input/InputLinux.cpp
UTF-8
8,700
2.609375
3
[]
no_license
#include "InputLinux.h" #include <GLFW/glfw3.h> std::map<int, IInput::KeyCode> InputLinux::keyMapFromNative; std::map<IInput::KeyCode, int> InputLinux::keyMapToNative; std::map<GLFWwindow*, std::weak_ptr<InputLinux>> InputLinux::windowMap; bool InputLinux::staticInitialized = initKeyMaps(); void InputLinux::insertKey(int _nativeKey, IInput::KeyCode _iKey) { keyMapFromNative[_nativeKey] = _iKey; keyMapToNative[_iKey] = _nativeKey; } bool InputLinux::initKeyMaps() { insertKey(GLFW_KEY_0, IInput::KeyCode::K0); insertKey(GLFW_KEY_1, IInput::KeyCode::K1); insertKey(GLFW_KEY_2, IInput::KeyCode::K2); insertKey(GLFW_KEY_3, IInput::KeyCode::K3); insertKey(GLFW_KEY_4, IInput::KeyCode::K4); insertKey(GLFW_KEY_5, IInput::KeyCode::K5); insertKey(GLFW_KEY_6, IInput::KeyCode::K6); insertKey(GLFW_KEY_7, IInput::KeyCode::K7); insertKey(GLFW_KEY_8, IInput::KeyCode::K8); insertKey(GLFW_KEY_9, IInput::KeyCode::K9); insertKey(GLFW_KEY_A, IInput::KeyCode::A); insertKey(GLFW_KEY_B, IInput::KeyCode::B); insertKey(GLFW_KEY_C, IInput::KeyCode::C); insertKey(GLFW_KEY_D, IInput::KeyCode::D); insertKey(GLFW_KEY_E, IInput::KeyCode::E); insertKey(GLFW_KEY_F, IInput::KeyCode::F); insertKey(GLFW_KEY_G, IInput::KeyCode::G); insertKey(GLFW_KEY_H, IInput::KeyCode::H); insertKey(GLFW_KEY_I, IInput::KeyCode::I); insertKey(GLFW_KEY_J, IInput::KeyCode::J); insertKey(GLFW_KEY_K, IInput::KeyCode::K); insertKey(GLFW_KEY_L, IInput::KeyCode::L); insertKey(GLFW_KEY_M, IInput::KeyCode::M); insertKey(GLFW_KEY_N, IInput::KeyCode::N); insertKey(GLFW_KEY_O, IInput::KeyCode::O); insertKey(GLFW_KEY_P, IInput::KeyCode::P); insertKey(GLFW_KEY_Q, IInput::KeyCode::Q); insertKey(GLFW_KEY_R, IInput::KeyCode::R); insertKey(GLFW_KEY_S, IInput::KeyCode::S); insertKey(GLFW_KEY_T, IInput::KeyCode::T); insertKey(GLFW_KEY_U, IInput::KeyCode::U); insertKey(GLFW_KEY_V, IInput::KeyCode::V); insertKey(GLFW_KEY_W, IInput::KeyCode::W); insertKey(GLFW_KEY_X, IInput::KeyCode::X); insertKey(GLFW_KEY_Y, IInput::KeyCode::Y); insertKey(GLFW_KEY_Z, IInput::KeyCode::Z); insertKey(GLFW_KEY_APOSTROPHE, IInput::KeyCode::SINGLE_QUOTE); insertKey(GLFW_KEY_BACKSLASH, IInput::KeyCode::BACK_SLASH); insertKey(GLFW_KEY_BACKSPACE, IInput::KeyCode::BACKSPACE); insertKey(GLFW_KEY_CAPS_LOCK, IInput::KeyCode::CAPS_LOCK); insertKey(GLFW_KEY_COMMA, IInput::KeyCode::COMMA); insertKey(GLFW_KEY_DELETE, IInput::KeyCode::DEL); insertKey(GLFW_KEY_DOWN, IInput::KeyCode::DOWN_ARROW); insertKey(GLFW_KEY_END, IInput::KeyCode::END); insertKey(GLFW_KEY_ENTER, IInput::KeyCode::RETURN); insertKey(GLFW_KEY_EQUAL, IInput::KeyCode::EQUAL); insertKey(GLFW_KEY_ESCAPE, IInput::KeyCode::ESCAPE); insertKey(GLFW_KEY_F1, IInput::KeyCode::F1); insertKey(GLFW_KEY_F2, IInput::KeyCode::F2); insertKey(GLFW_KEY_F3, IInput::KeyCode::F3); insertKey(GLFW_KEY_F4, IInput::KeyCode::F4); insertKey(GLFW_KEY_F5, IInput::KeyCode::F5); insertKey(GLFW_KEY_F6, IInput::KeyCode::F6); insertKey(GLFW_KEY_F7, IInput::KeyCode::F7); insertKey(GLFW_KEY_F8, IInput::KeyCode::F8); insertKey(GLFW_KEY_F9, IInput::KeyCode::F9); insertKey(GLFW_KEY_F10, IInput::KeyCode::F10); insertKey(GLFW_KEY_F11, IInput::KeyCode::F11); insertKey(GLFW_KEY_F12, IInput::KeyCode::F12); insertKey(GLFW_KEY_GRAVE_ACCENT, IInput::KeyCode::BACK_QUOTE); insertKey(GLFW_KEY_HOME, IInput::KeyCode::HOME); insertKey(GLFW_KEY_INSERT, IInput::KeyCode::INSERT); insertKey(GLFW_KEY_KP_0, IInput::KeyCode::NP0); insertKey(GLFW_KEY_KP_1, IInput::KeyCode::NP1); insertKey(GLFW_KEY_KP_2, IInput::KeyCode::NP2); insertKey(GLFW_KEY_KP_3, IInput::KeyCode::NP3); insertKey(GLFW_KEY_KP_4, IInput::KeyCode::NP4); insertKey(GLFW_KEY_KP_5, IInput::KeyCode::NP5); insertKey(GLFW_KEY_KP_6, IInput::KeyCode::NP6); insertKey(GLFW_KEY_KP_7, IInput::KeyCode::NP7); insertKey(GLFW_KEY_KP_8, IInput::KeyCode::NP8); insertKey(GLFW_KEY_KP_9, IInput::KeyCode::NP9); insertKey(GLFW_KEY_KP_ADD, IInput::KeyCode::NP_PLUS); insertKey(GLFW_KEY_KP_DECIMAL, IInput::KeyCode::NP_PERIOD); insertKey(GLFW_KEY_KP_DIVIDE, IInput::KeyCode::NP_DIVIDE); insertKey(GLFW_KEY_KP_ENTER, IInput::KeyCode::NP_RETURN); insertKey(GLFW_KEY_KP_MULTIPLY, IInput::KeyCode::NP_MULTIPLY); insertKey(GLFW_KEY_KP_SUBTRACT, IInput::KeyCode::NP_MINUS); insertKey(GLFW_KEY_LEFT, IInput::KeyCode::LEFT_ARROW); insertKey(GLFW_KEY_LEFT_ALT, IInput::KeyCode::LEFT_ALT); insertKey(GLFW_KEY_LEFT_BRACKET, IInput::KeyCode::LEFT_SQUARE_BRACKET); insertKey(GLFW_KEY_LEFT_CONTROL, IInput::KeyCode::LEFT_CTRL); insertKey(GLFW_KEY_LEFT_SHIFT, IInput::KeyCode::LEFT_SHIFT); insertKey(GLFW_KEY_LEFT_SUPER, IInput::KeyCode::LEFT_SUPER); insertKey(GLFW_KEY_MENU, IInput::KeyCode::MENU); insertKey(GLFW_KEY_MINUS, IInput::KeyCode::DASH); insertKey(GLFW_KEY_NUM_LOCK, IInput::KeyCode::NUM_LOCK); insertKey(GLFW_KEY_PAGE_DOWN, IInput::KeyCode::PAGE_DOWN); insertKey(GLFW_KEY_PAGE_UP, IInput::KeyCode::PAGE_UP); insertKey(GLFW_KEY_PAUSE, IInput::KeyCode::BREAK); insertKey(GLFW_KEY_PERIOD, IInput::KeyCode::PERIOD); insertKey(GLFW_KEY_PRINT_SCREEN, IInput::KeyCode::SYS_RQ); insertKey(GLFW_KEY_RIGHT, IInput::KeyCode::RIGHT_ARROW); insertKey(GLFW_KEY_RIGHT_ALT, IInput::KeyCode::RIGHT_ALT); insertKey(GLFW_KEY_RIGHT_BRACKET, IInput::KeyCode::RIGHT_SQUARE_BRACKET); insertKey(GLFW_KEY_RIGHT_CONTROL, IInput::KeyCode::RIGHT_CTRL); insertKey(GLFW_KEY_RIGHT_SHIFT, IInput::KeyCode::RIGHT_SHIFT); insertKey(GLFW_KEY_RIGHT_SUPER, IInput::KeyCode::RIGHT_SUPER); insertKey(GLFW_KEY_SCROLL_LOCK, IInput::KeyCode::SCROLL_LOCK); insertKey(GLFW_KEY_SEMICOLON, IInput::KeyCode::SEMICOLON); insertKey(GLFW_KEY_SLASH, IInput::KeyCode::SLASH); insertKey(GLFW_KEY_SPACE, IInput::KeyCode::SPACE); insertKey(GLFW_KEY_TAB, IInput::KeyCode::TAB); insertKey(GLFW_KEY_UP, IInput::KeyCode::UP_ARROW); insertKey(GLFW_KEY_WORLD_1, IInput::KeyCode::WORLD_1); insertKey(GLFW_KEY_WORLD_2, IInput::KeyCode::WORLD_2); return true; } IInput::KeyCode InputLinux::translateKey(int _nativeKey) { if (keyMapFromNative.count(_nativeKey) == 0) { return IInput::KeyCode::UNKNOWN; } return keyMapFromNative.at(_nativeKey); } int InputLinux::translateKey(IInput::KeyCode _iKey) { if (keyMapToNative.count(_iKey) == 0) { return GLFW_KEY_UNKNOWN; } return keyMapToNative.at(_iKey); } InputLinux::InputLinux() { } void InputLinux::keyCallback(GLFWwindow* _window, int _key, int _scancode, int _action, int _mods) { if (_key == GLFW_KEY_BACKSPACE && _action != GLFW_RELEASE) { Event ev; ev.type = Event::Type::CHARACTER; ev.charEvent.character = (char32_t)'\b'; ptr input = windowMap[_window].lock(); if (input) { input->events.push_back(ev); } } if (_action == GLFW_REPEAT) { return; } Event ev; ev.type = Event::Type::KEY; ev.keyEvent.key = translateKey(_key); ev.keyEvent.pressed = (_action == GLFW_PRESS); ptr input = windowMap[_window].lock(); if (input) { input->events.push_back(ev); } } void InputLinux::mouseButtonCallback(GLFWwindow* _window, int _button, int _action, int _mods) { MouseButtonEvent::Button button; switch (_button) { case GLFW_MOUSE_BUTTON_LEFT: button = MouseButtonEvent::Button::LEFT; break; case GLFW_MOUSE_BUTTON_RIGHT: button = MouseButtonEvent::Button::RIGHT; break; case GLFW_MOUSE_BUTTON_MIDDLE: button = MouseButtonEvent::Button::MIDDLE; break; default: button = MouseButtonEvent::Button::UNKNOWN; break; } Event ev; ev.type = Event::Type::MOUSE_BUTTON; ev.mouseButtonEvent.button = button; ev.mouseButtonEvent.pressed = (_action == GLFW_PRESS); ptr input = windowMap[_window].lock(); if (input) { input->events.push_back(ev); } } void InputLinux::mouseCursorPosCallback(GLFWwindow* _window, double _xpos, double _ypos) { int windowWidth, windowHeight; glfwGetWindowSize(_window, &windowWidth, &windowHeight); Event ev; ev.type = Event::Type::MOUSE_MOVE; ev.mouseMoveEvent.posX = _xpos / windowWidth * 2.0 - 1.0; ev.mouseMoveEvent.posY = -(_ypos / windowHeight * 2.0 - 1.0); ptr input = windowMap[_window].lock(); if (input) { input->events.push_back(ev); } } void InputLinux::characterCallback(GLFWwindow* _window, unsigned int _character) { Event ev; ev.type = Event::Type::CHARACTER; ev.charEvent.character = _character; ptr input = windowMap[_window].lock(); if (input) { input->events.push_back(ev); } } bool InputLinux::registerWindowForInput(GLFWwindow* _window) { if (!_window) { return false; } windowMap[_window] = shared_from_this(); glfwSetKeyCallback(_window, &keyCallback); glfwSetCursorPosCallback(_window, &mouseCursorPosCallback); glfwSetMouseButtonCallback(_window, &mouseButtonCallback); glfwSetCharCallback(_window, &characterCallback); return true; }
true
5f7e062819c1f5038ea80c74022df7c3fae0e6fb
C++
TeoPaius/Projects
/c++/Diverse problems and algorithms/Algorithms/arbori/disjoint/main.cpp
UTF-8
1,117
3
3
[]
no_license
#include <fstream> using namespace std; ifstream is ("disjoint.in"); ofstream os ("disjoint.out"); int n, m; int t[100000], h[100000]; int op; int a, b; int Find(int x); void Union(int x, int y); int main() { is >> n >> m; for(int i = 1; i <= n; ++i) { t[i] = i; h[i] = 1; } for(int i = 1; i <= m; ++i) { is >> op >> a >> b; if(op == 2) { if (Find(a) == Find(b)) os << "DA" <<'\n'; else os << "NU" << '\n'; } if(op == 1) { int aux1 = Find(a); int aux2 = Find(b); Union(aux1, aux2); } } is.close(); os.close(); return 0; } int Find(int x) { if (x == t[x]) return x; return t[x] = Find(t[x]); } void Union(int x, int y) { if(h[x] > h[y]) { h[y] = 0; t[y] = x; return; } if(h[x] < h[y]) { h[x] = 0; t[x] = y; return; } if(h[x] == h[y]) { h[y] = 0; t[y] = x; h[x]++; return; } }
true
dafd8faa67d055d360e899ba4fc702c7ea7ac2f8
C++
SeongmanPark/Algorithm
/SWEA/SWE 홈 방범 서비스.cpp
UTF-8
2,112
3
3
[]
no_license
#include <iostream> //#include <fstream> #include <queue> #define MAX(A,B) (A>B ? A:B) using namespace std; int map[21][21]; bool visit[21][21]; int N, M, testCase, K, answer, temp_answer; int a = 1; int dx[] = { -1,1,0,0 }; int dy[] = { 0,0,-1,1 }; void init() { a++; answer = 0; temp_answer = 0; } bool isWall(int x, int y) { if (x < 1 || y < 1 || x > N || y > N) return true; else return false; } void bfs(int x, int y) { int home = 0; int K = 1; int cur_x, cur_y, new_x, new_y, cur_dist; memset(visit, 0, sizeof(visit)); queue<pair<int, int>> q; q.push(make_pair(x, y)); visit[x][y] = true; if (map[x][y] == 1) home++; // 시작점 큐에 푸쉬, 거리는 0 while (!q.empty()) { if (K > N + 1) break; // service가 배열의 크기 + 1이 넘으면 ?? 더이상 해볼 필요 없음 !! if ((K * K + (K - 1)*(K - 1)) <= home * M) { answer = MAX(answer, home); } // 비용계산, 정답 초기화 부분 !! int s = q.size(); // 현재 큐의 사이즈를 저장 // 현재 큐의 사이즈만큼 for문 돈다 -> 기준점으로부터 똑같이 떨어진 노드의 개수만큼 돈다. !!!! // 매우 중요함 .. !!! for (int Qs = 0; Qs < s; Qs++) { cur_x = q.front().first; cur_y = q.front().second; q.pop(); for (int i = 0; i < 4; i++) { new_x = cur_x + dx[i]; new_y = cur_y + dy[i]; if (visit[new_x][new_y] || isWall(new_x, new_y)) continue; visit[new_x][new_y] = true; if (map[new_x][new_y] == 1) { home++; } q.push(make_pair(new_x, new_y)); } } K++; } } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); //ifstream cin("input.txt"); cin >> testCase; while (testCase-- > 0) { cin >> N >> M; for (int i = 1; i <= N; i++) { for (int j = 1; j <= N; j++) { cin >> map[i][j]; } } // 입력 완료 for (int i = 1;i <= N; i++) { for (int j = 1; j <= N; j++) { bfs(i, j); // 모든 정점에 대해서 완전탐색 해야함 } } cout << "#" << a << " " << answer << '\n'; init(); } } // 완전탐색 + 시뮬레이션 문제 !!!!
true
6a9402a36fad94f669d03b38dcd257e092a9083d
C++
inoobkk/c-PrimerExcise
/chapter3/3.2.3/test6.cpp
GB18030
445
3.1875
3
[]
no_license
#include<iostream> #include<string> using namespace std; int main() { const string s = "Keep"; for(auto &c: s) { //c = 'a'; // , cdz, const char& c˵ // cõĶһڵײconstauto // autoԵײconst const char& c = 'c'; const char& b = 'b'; // ðɾ޷󶨵ط const char a = 'a'; } return 0; }
true
58dd3ccd4200de9e2751c4ea66d524373c964d8f
C++
codecsp/Competitive-Programming
/online judges/Codechef/Long Challenge/APRIL 20/strno.cpp
UTF-8
790
3.21875
3
[]
no_license
#include <iostream> #include <cmath> using namespace std; int primeFactors(int n) { int count = 0; while(n%2 == 0) { count++; // 2 n = n/2; } for(int i=3;i<= sqrt(n); i = i+2) { while(n%i == 0) { count++; n = n/i; // i } } if(n>2) { count++; // n } return count; } int main() { int t; cin>>t; while(t--) { int x,k; cin>>x>>k; int size = primeFactors(x); if(k <= size) { cout<<1<<endl; } else { cout<<0<<endl; } } return 0; } // lack of facility shouldn't depress us & presence and luxury and facility shouldn't distract us.
true
19de6eaff818b0fd5096067187d9610494b818de
C++
harshagowda/NixDOS
/EDITOR.CPP
UTF-8
1,923
2.625
3
[ "MIT" ]
permissive
typedef unsigned char usc; #define ESC 27 #define BKSPACE 8 #define ENTER 13 #define TAB 9 #define UP 72 #define DOWN 80 #define LEFT 75 #define RIGHT 77 #define DEL 83 #define INSERT 128 #define F1 59 #define F2 60 #define F3 61 #define F4 64 void ndedithelp() { } void open() { } void save() { } void eprint() { } int ndedit() { int x=0,y=2,maxx=79,maxy=22,minx=0,miny=2,exit=0; scrollpgup(0,0,0,24,79); print("A mini EDITOR for MINI O.S",20,0); print("ESC ->Quit F1 ->Help F2 ->Save F3 ->Open F4 ->Print",2,24); setcurpos(0,y); usc c[1760]; for(int i=1;i<=1760;) { c[i]=getch(); switch(c[i]) { case ESC: exit=1; //esc scrollpgup(0,0,0,24,79); break; case BKSPACE: //if(x==0&&y==1) if(x==0) {print(" ",maxx,--y);x=maxx;c[--i]='\0';setcurpos(x,y);} if(x==1) {print(" ",--x,y);c[--i]='\0';setcurpos(x,y);} if(x>0&&y>1&&y<=23) {c[--i]='\0';print(" ",--x,y);} setcurpos(x,y); break; case ENTER: if(y==24) y--; y++; c[i++]='\n'; x=0; setcurpos(x,y); break; case UP: if(y==2) y=3; setcurpos(x,--y); break; case DOWN: if(y==23) y=22; setcurpos(x,++y); break; case LEFT: if(x==0) x=1; setcurpos(--x,y); break; case RIGHT: if(x==79) x=78; setcurpos(x++,y); break; case DEL: print(" ",x,y); break; case TAB: x=x+5; setcurpos(x,y); break; case INSERT: break; case F1: ndedithelp(); break; case F2: save(); break; case F3: open(); break; case F4: eprint(); break; default : if(x==79) {y++;x=0;} printa(c[i++],x++,y); setcurpos(x,y); break; } if(exit==1) break; } return(0); }
true
847a491afb758b4837de2cc664d5d28a039f912c
C++
HarithFernando/Airline-Ticket-Reservation
/TakeHome.cpp
UTF-8
496
3.234375
3
[]
no_license
// A simple C++ program to show working of getline #include <iostream> #include <cstring> #include <string> #include <fstream> using namespace std; int main() { std::ifstream inFile("./Flights.txt"); if(!inFile) { cout<<"Couldn't open the file"<<endl; exit(1); } string line; int i=0; string arr[5]; while( getline(inFile, line) ) { arr[i]= line; i=+1; } for(int x=0; x<5 ; x++){ cout << arr[x]; } }
true