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 |
---|---|---|---|---|---|---|---|---|---|---|---|
f0f340f2dcbf14a30688d3d2558b072047cff143
|
C++
|
h005/vptools
|
/amtclassify/svm2k/feaExtra.cpp
|
UTF-8
| 999 | 2.796875 | 3 |
[] |
no_license
|
#include <iostream>
#include <fstream>
#include <string>
#include <string.h>
// input 2D fea file name and 3D fea file name
// remove the case name only remains the fea vector
int main(int argc,char *argv[])
{
if(argc < 3)
{
std::cout << "parameter not enough "<< std::endl;
}
else
{
// deal 2D fea file
std::ifstream fin(argv[1]);
int len = strlen(argv[1]);
char *path;
path = new char[len + 1];
strcpy(path,argv[1]);
path[len] = 'c';
path[len+1] = '\0';
std::ofstream fout(path);
std::string ss;
while(std::getline(fin,ss))
{
std::getline(fin,ss);
fout << ss << std::endl;
}
fin.close();
fout.close();
fin.open(argv[2]);
delete []path;
len = strlen(argv[2]);
path = new char[len+1];
strcpy(path,argv[2]);
path[len] = 'c';
path[len+1] = '\0';
fout.open(path);
while(std::getline(fin,ss))
{
std::getline(fin,ss);
fout << ss << std::endl;
}
fin.close();
fout.close();
}
}
| true |
9df038f72cc23f934ce16488cf2adecd0c6cc6d7
|
C++
|
lmoz25/NES_Emulator
|
/src/cpu/CPU_Timer.cpp
|
UTF-8
| 722 | 3.109375 | 3 |
[] |
no_license
|
#include "CPU_Timer.h"
#include "ThreadUtils.h"
volatile uint8_t CPU_Timer::extra_cycles = 0;
CPU_Timer::CPU_Timer(const uint8_t& cycles) {
runner = std::make_unique<std::thread>(time, cycles);
}
CPU_Timer::~CPU_Timer() {
runner->join();
}
void CPU_Timer::time(const uint8_t& cycles) {
auto instruction_execution_time =
static_cast<float>(cycles) * cpu_cycle_length_useconds;
usleep(instruction_execution_time);
// Sleep for extra cycles, e.g if an operation has caused memory to cross a
// page boundary
if(extra_cycles) {
usleep(static_cast<float>(extra_cycles) * cpu_cycle_length_useconds);
}
// Wake the CPU execution thread
thread_waker.notify_all();
}
| true |
556b506d0cfaddc56b7d8129abf730416a49504c
|
C++
|
jeafleohj/GameOfLife
|
/src/world.cpp
|
UTF-8
| 1,540 | 2.625 | 3 |
[] |
no_license
|
#include "world.h"
#include <random>
#include <chrono>
#include <thread>
World::World(int n)
:n(n)
{
std::default_random_engine generator;
std::bernoulli_distribution dist(0.06);
//std::binomial_distribution<int> dist(20,.00001);
//std::poisson_distribution<int> dist(.0004);
p=new Cell***[n];
const GLfloat l=3./n;
for(int i=0;i<n;i++){
p[i]=new Cell**[n];
for(int j=0;j<n;j++){
p[i][j]=new Cell*[n];
for(int k=0;k<n;k++){
p[i][j][k]=new Cell(- n*l/2 + i*l , - n*l/2 + j*l , - n*l/2 + k*l, l, dist(generator) ? true:false );
}
}
}
}
void World::drawWorld(){
int px[]={
1, 1, 0,-1,-1,-1, 0, 1, 0, //abajo
1, 1, 0,-1,-1,-1, 0, 1, //medio
1, 1, 0,-1,-1,-1, 0, 1, 0 //arriba
};
int py[]={
0,-1,-1,-1, 0, 1, 1, 1, 0,
0,-1,-1,-1, 0, 1, 1, 1,
0,-1,-1,-1, 0, 1, 1, 1, 0
};
int pz[]={
-1,-1,-1,-1,-1,-1,-1,-1,-1,
0, 0, 0, 0, 0, 0, 0, 0,
1, 1, 1, 1, 1, 1, 1, 1, 1
};
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
for(int z=0;z<n;z++){
p[i][j][z]->drawCell();
}
}
}
// std::this_thread::sleep_for(std::chrono::milliseconds(200));
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
for(int z=0;z<n;z++){
int vecinos=0;
for(int k=0;k<26;k++){
if( (0<=i+py[k] && i+py[k]<n) && (0<=j+px[k] && j+px[k]<n )&& (0<=z+pz[k] && z+pz[k]<n )&& p[i+py[k]][j+px[k]][z+pz[k]]->getLife() ){
vecinos++;
}
}
p[i][j][z]->setNeighbours(vecinos);
}
}
}
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
for(int z=0;z<n;z++)
p[i][j][z]->updateState();
}
| true |
583663b5f95927923cb6ffa321d9503fff12a407
|
C++
|
AskuSU/GB_P2_HW_L7
|
/Task2.cpp
|
UTF-8
| 787 | 3.296875 | 3 |
[] |
no_license
|
#include"Task2.h"
std::shared_ptr<Date> maxDate(const std::shared_ptr<Date>& date1, const std::shared_ptr<Date>& date2)
{
if (date1.get()->getYear() > date2.get()->getYear()) return std::shared_ptr<Date>(date1);
else if(date1.get()->getYear() < date2.get()->getYear()) return std::shared_ptr<Date>(date2);
else if(date1.get()->getMonth() > date2.get()->getMonth()) return std::shared_ptr<Date>(date1);
else if(date1.get()->getMonth() < date2.get()->getMonth()) return std::shared_ptr<Date>(date2);
else if(date1.get()->getDay() > date2.get()->getDay()) return std::shared_ptr<Date>(date1);
else return std::shared_ptr<Date>(date2);
}
void swapDate(std::shared_ptr<Date>& date1, std::shared_ptr<Date>& date2)
{
auto tmp = move(date1);
date1 = move(date2);
date2 = move(tmp);
}
| true |
fd87721db6a0c390cc9b3c890d8843f7fd1bffc0
|
C++
|
martin-favre/asciigraphicsv2
|
/textgraphics.hpp
|
UTF-8
| 1,721 | 2.59375 | 3 |
[] |
no_license
|
#ifndef TEXTGRAPHICS_HPP
#define TEXTGRAPHICS_HPP
#include <vector>
#include <string>
#include <chrono>
#include <climits>
#include <map>
#include "pixel.hpp"
#include "gameobject.hpp"
#include "imgcontainer.hpp"
class Textgrafs{
public:
Textgrafs();
void add_border(const Pixel & p, int px, int py, int sizex, int sizey);
void add_pixel(const Pixel & p, int px, int py);
//void add_image(std::vector<std::vector<std::string>> & , int px, int py);
void add_image(const std::vector<std::vector<Pixel>> &, int px, int py);
void add_image(const Img_container & img, int px, int py);
void add_rect(const Pixel & p, int px, int py, int sizex, int sizey);
void add_fill(const Pixel & p, int px, int py, int sizex, int sizey);
void add_fill(int px, int py, int sizex, int sizey);
//WIP Should textgrafs hold gameobjects?
void add_gameobject(const Gameobject & g);
void add_gameobjects(const std::vector<Gameobject> & g);
//void remove_gameobject; How should I
void print(); //Prints one grid
bool next_tick(); //Should be private
void paint(); //For continuous animation
void clear_screen(); //Empty screen
void hide_cursor();
void show_cursor();
void cursorpos(int px, int py); //Set cursorpos on screen
std::string cursorpos_str(int px, int py);
void fill_grid(const Pixel & p);
void clear_grid();
void clear_grid_specific(int px, int py, int sizex, int sizey);
int rows_;
int cols_;
private:
void save_old_grid();
std::chrono::system_clock::time_point timer_;
bool debug = false;
double time_between_frames_ = 0.005;
std::vector<std::vector<std::string>> grid;
std::vector<std::vector<std::string>> old_grid;
std::map<int, Gameobject> objects;
};
#endif
| true |
5c4dbbab476451232e76dfb356d728269dea215b
|
C++
|
slollo/basachky
|
/List.hpp
|
UTF-8
| 1,402 | 2.875 | 3 |
[
"MIT"
] |
permissive
|
/*
* List.hpp
*
*
* Copyright (C) 2019 Max V. Stotsky <maxstotsky@gmail.com>
*
*/
#ifndef LIST_HPP
#define LIST_HPP
#include <iostream>
#include "HeadTail.hpp"
#include "IsEmpty.hpp"
template <class EType>
struct ListNull
{
typedef EType Type;
typedef size_t KeyT;
};
template <class EType, EType elem, class T>
struct List
{
typedef EType Type;
typedef size_t KeyT;
typedef ListNull<EType> Empty;
static const Type value = elem;
typedef T tail;
};
template <class EType, EType e, EType ...lst>
struct ToList
{
typedef List<EType, e, typename ToList<EType, lst...>::Result> Result;
};
template <class EType, EType e>
struct ToList<EType, e>
{
typedef List<EType, e, ListNull<EType>> Result;
};
template <class EType>
struct IsEmpty<ListNull<EType>>
{
static const bool result = true;
};
template <class EType, EType e, class T>
struct Head<List<EType, e, T>>
{
static const EType result = e;
};
template <class EType, EType e, class T>
struct Tail<List<EType, e, T>>
{
typedef T Result;
};
template <class EType>
struct Tail<ListNull<EType>>
{
typedef ListNull<EType> Result;
};
template <class EType, EType e, class T, EType ie>
struct PushFront<List<EType, e, T>, ie>
{
typedef List<EType, ie, List<EType, e, T>> Result;
};
template <class EType, EType ie>
struct PushFront<ListNull<EType>, ie>
{
typedef List<EType, ie, ListNull<EType>> Result;
};
#endif /* LIST_HPP */
| true |
7a555f9dcbfd4cab2a640f245171985fddeb143e
|
C++
|
Bpara001/CS_UCR
|
/cs12/cs12old/assignment5/clickable.cpp
|
UTF-8
| 3,314 | 3.390625 | 3 |
[] |
no_license
|
// Course: CS 12 quarter 2 , 2010
//
// First Name: Christopher
// Last Name: Wong
// Login id: wongc
// email address: cwong030@student.ucr.edu
// Student id: 860 923 521
//
// Lecture Section: 001
// Lab Section: 021
// TA: Denise Duma
//
// Assignment: Programming Assignment 5
//
// I hereby certify that the code in this file
// is ENTIRELY my own original work.
// clickable.cpp
#include "clickable.h"
// \brief Default constructor for the Clickable class.
Clickable::Clickable()
: shown(),border()
{
}
// \brief Constructor for the Clickable class.
// \param ul_corner The position of the upper left corner of the object.
// \param height The height of the object.
// \param width The width of the object.
Clickable::Clickable(const Point & ll_corner,double height,double width)
: shown(false),border(ll_corner,height,width)
{
}
// \brief Draw the object in the drawing area.
// \return void.
void Clickable::draw() const
{
win << border;
}
// \brief Test to see if the object has been clicked.
//
// Only visible objects can be clicked.
// \param click The point corresponding to the mouse click to test.
// \return Whether the object has been clicked.
bool Clickable::is_clicked(const Point & click) const
{
double xclick = click.get_x();
double yclick = click.get_y();
Point lowerleft = border.get_lower_left();
double x_ll = lowerleft.get_x();
double y_ll = lowerleft.get_y();
double height = border.get_height();
double width = border.get_width();
if(yclick > y_ll && yclick < y_ll + height && xclick > x_ll
&& xclick < x_ll + width)
{
return true;
}
else return false;
}
// \brief Test to see if the object is currently shown.
// \return Whether the object is currently shown.
bool Clickable::is_shown() const
{
if (shown == true)
{
return true;
}
else
{
return false;
}
}
// \brief Make the object visible in the drawing window when drawn.
// \return void.
void Clickable::show()
{
shown = true;
}
// \brief Make the object invisible in the drawing area when drawn.
// \return void.
void Clickable::hide()
{
shown = false;
}
// \brief Move the object by a displacement.
// \param x_displace The distance to move the object in the x-direction.
// \param y_displace The distance to move the object in the y-direction.
// \return void.
void Clickable::move(double x_displace, double y_displace)
{
border.move(x_displace,y_displace);
}
// \brief Move the upper left corner of the object to a position.
// \param loc The location to move the object to.
// \return void.
void Clickable::move_to(const Point & loc)
{
Point ll_corner = border.get_lower_left();
double xpoint = ll_corner.get_x();
double ypoint = ll_corner.get_y();
move(loc.get_x()-xpoint,loc.get_y()-ypoint);
}
// \brief Center the object about a point.
// \param loc The location about which to center the object.
// \return void.
void Clickable::center(const Point & loc)
{
Point ll_corner = border.get_lower_left();
double xpoint = ll_corner.get_x();
double ypoint = ll_corner.get_y();
move(loc.get_x()-xpoint-border.get_width()/2,
loc.get_y()-ypoint-border.get_height()/2);
}
// \brief Destructor for the Clickable class.
Clickable::~Clickable()
{
}
| true |
9296f21ba2544fcc7faa6fd9aea7c360773568e6
|
C++
|
huangzhemin/LeetCode
|
/9 Palindrome Number.cpp
|
GB18030
| 1,146 | 3.578125 | 4 |
[] |
no_license
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <stack>
#include <sstream>
#include <map>
#include <set>
using namespace std;
typedef struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
} TreeNode;
typedef struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
}ListNode;
class Solution {
public:
//˼·
//жһǷΪҲҪռ䣬δȡӦ
//ҪжǷΪҪ
bool isPalindrome(int x) {
if (x < 0) return false;
if (reverseInt(x) == x) return true;
return false;
}
int reverseInt(int x) {
int result = 0;
while (x) {
result *= 10;
result += x % 10;
x /= 10;
}
return result;
}
};
int main() {
Solution s;
cout << s.isPalindrome(-1) << endl;
return 0;
}
| true |
aa61a92ea12c4d28217529165bab3020d5546985
|
C++
|
aqlan-hussin/USCS20
|
/payRoll.cpp
|
UTF-8
| 1,060 | 3.1875 | 3 |
[] |
no_license
|
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <iomanip>
using namespace std;
int main()
{
int id, hours;
double gross, tax, kwsp, deduct, netPay;
double const empUnion = 10;
ofstream pay("payRoll.dat");
if (pay.fail())
{
cout << "The file was not successfully opened";
exit(1);
}
while (id != -1)
{
cout << "Please enter your employee's id: ";
cin >> id;
if (id == -1)
{
break;
}
else
{
cout << "Please enter your hours worked per week: ";
cin >> hours;
cout << endl;
if (hours <= 40)
{
gross = 4.0 * hours;
}
else if (hours > 40 && hours <= 50)
{
gross = 1.5 * 4.0 * hours;
}
else
{
gross = 2.0 * 4.0 * hours;
}
tax = 8.0 / 100 * gross;
kwsp = 10.0 / 100 * gross;
deduct = tax + kwsp + empUnion;
netPay = gross - deduct;
pay << fixed << setprecision(2)
<< id << "\tRM" << gross << "\tRM" << deduct << "\t\tRM" << netPay << endl;
}
}
pay.close();
cout << "The file has been successfully written";
return 0;
}
| true |
7d538c6f552adedb87f65d49ede89f0ca181ee1e
|
C++
|
brucexia1/DesignPattern
|
/src/algorithm/xsSearch.cpp
|
GB18030
| 1,305 | 3.453125 | 3 |
[
"MIT"
] |
permissive
|
#include "xsSearch.h"
//ֲ㷨
template<typename T>
int BinSearch(std::vector<T> &vec, int key)
{
if (vec.empty()) return -1;
int low(0), high(vec.size() - 1), mid(0);
while (low <= high){
mid = low + (high - low) / 2;
if (vec[mid] == key) return mid;
if (vec[mid]>key)
high = mid - 1;
else
low = mid + 1;
}
return -1;
}
/************************************************************************\
(BST)ֶ()
ʣ
1ǿգм¼ֵСڸ¼ֵ
2ǿգм¼ֵڸ¼ֵ
3ҸʽһBST
ע⣺¼ֵͬԪ
\************************************************************************/
int InsertBST(BSTNode *&p, KeyType k)
{
if (!p){
p = new BSTNode;
p->key = k;
p->lchild = p->rchild = NULL;
return 1;
}
else if (k == p->key)
return 0;
else if (k<p->key)
return InsertBST(p->lchild, k);
else
return InsertBST(p->rchild, k);
}
BSTNode *CreateBST(std::vector<KeyType> &vec)
{
BSTNode * bt = NULL;
int i(0);
while (i<vec.size()){
InsertBST(bt, vec[i++]);
}
return bt;
}
void Del(BSTNode *p, BSTNode *&r)
{
return;
}
| true |
3a34a173fdd91ed4daa5361c63db7c932ac3e0a2
|
C++
|
lyubolp/OOP-SI-2021
|
/week10/code/main.cpp
|
UTF-8
| 720 | 3.5 | 4 |
[] |
no_license
|
#include <iostream>
#include <fstream>
class Foo{
public:
Foo() = default;
friend std::istream& operator>>(std::istream& in, Foo& object);
friend std::ostream& operator<<(std::ostream& out, const Foo& object);
private:
int first;
int second;
int third;
};
std::istream& operator>>(std::istream& in, Foo& object) {
in >> object.first >> object.second >> object.third;
return in;
}
std::ostream& operator<<(std::ostream& out, const Foo& object) {
out << object.first << " " << object.second << " " << object.third;
return out;
}
int main() {
std::ifstream reader("random_text.txt");
Foo instance;
reader >> instance;
std::cout << instance;
return 0;
}
| true |
ca0baecb0c7035855cd86181e0c52e40a2cfdd48
|
C++
|
havocykp/Project-Development
|
/密码本/密码本/密码本.cpp
|
GB18030
| 5,998 | 2.75 | 3 |
[] |
no_license
|
// 뱾.cpp : ̨Ӧóڵ㡣
//
#include "stdafx.h"
#include "data.h"
#include <stdlib.h>
#include "ctrl.h"
#include <string.h>
#include <windows.h>
#include <conio.h>
#pragma comment(lib, "winmm.lib")
//void setColor(int color);
//void setCurson(int x, int y);
//ҪʾIJ˵
char *menu[] =
{
"\t\t\t\t 1. 鿴\t \n\n",
"\t\t\t\t 2. \t\t \n\n",
"\t\t\t\t 3. ɾ\t\t \n\n",
"\t\t\t\t 4. \t\t \n\n",
"\t\t\t\t 5. ѯ\t\t \n\n",
"\t\t\t\t 6. ļ\t\t \n\n",
"\t\t\t\t 7. ˳\t\t \n",
};
//
CONSOLE_CURSOR_INFO cci;
//Ĭϵλ
COORD pos = { 0,0 };
//ʾ˵
void showmenu(HANDLE hOut, char **menu, int size, int index);
//ȡû
int get_userinput(int *index, int size);
int main()
{
int ret;
int index = 0;
PPASSWORD pPwd = nullptr; //
int nCount = 0; //ǰ
g_nNum = 0; //ǰ뱾
readInfo(&pPwd, &nCount); //ӱļжȡ룬ڳʼ뱾
HANDLE hOut;
//ȡǰľ---Ϊ
hOut = GetStdHandle(STD_OUTPUT_HANDLE);
//ȡϢ
GetConsoleCursorInfo(hOut, &cci);
//ùС
cci.dwSize = 1;
//ù겻ɼ FALSE
cci.bVisible = 0;
//(Ӧ)Ϣ
SetConsoleCursorInfo(hOut, &cci);
PlaySoundA("sound\\xiao.wav", NULL, SND_ASYNC | SND_NODEFAULT); //ű
while (1)
{
showmenu(hOut, menu, _countof(menu),index);
ret = get_userinput(&index, _countof(menu));
if (ret == ESC)
break;
if (ret == ENTER)
{
switch (index)
{
case 鿴:
searchAllInfo(pPwd, nCount);
break;
case :
insertInfo(pPwd, &nCount);
break;
case ɾ:
deleteInfo(pPwd, &nCount);
break;
case :
alterInfo(pPwd, nCount);
break;
case ѯ:
searchInfo(pPwd, nCount);
break;
case ı:
saveInfoA(pPwd, nCount);
break;
case ˳:
exit(0);
break;
default:
break;
}
system("cls");
}
}
return 0;
}
void showmenu(HANDLE hOut, char **menu, int size, int index)
{
int i;
system("cls");
//ʾıɫ
SetConsoleTextAttribute(hOut, FOREGROUND_GREEN | 0x8);
//ʼ̨ʾX,Y
pos.X = 30;
pos.Y = 0;
//ʾ̨ն˵ľλ
SetConsoleCursorPosition(hOut, pos);
for (i = 0; i < size; i++)
{
//i==indexʾڵǰѡλãĬϳʼʾǵһʾΪɫ
//°ѡʱƶҲͿбѡ
if (i == index)
{
//ɫ
SetConsoleTextAttribute(hOut, FOREGROUND_RED | 0x8);
pos.X = 25;
pos.Y = 5 + i;
//ù
SetConsoleCursorPosition(hOut, pos);
printf("%s", menu[i]);
}
//ʾΪɫ
else
{
//ɫ
SetConsoleTextAttribute(hOut, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
pos.X = 30;
pos.Y = 5 + i;
//ù
SetConsoleCursorPosition(hOut, pos); //ù
printf("%s", menu[i]);
}
}
//ˢ±
fflush(stdout);
}
//ȡûĽӿ
int get_userinput(int *index, int size)
{
int ch;
ch = _getch();
switch (ch)
{
//
//ѡϣôƶ
case UP: if (*index > 0) *index -= 1; break;
//
//ѡ£ôƶ
case DOWN:if (*index < size - 1) *index += 1; break;
//س
case ENTER: return ENTER;
//ESC
case ESC: return ESC;
}
return 0;
}
int main11()
{
PPASSWORD pPwd= nullptr; //
int nCount = 0; //ǰ
g_nNum = 0; //ǰ뱾
//ӱļжȡ룬ڳʼ뱾
readInfo(&pPwd, &nCount);
/*
while (true)
{
PlaySoundA("sound\\xiao.wav", NULL, SND_ASYNC | SND_NODEFAULT); //ű
setColor(12);
system("title ӭʹ뱾"); //ı
printf("\n\n\n\n");
printf("\t\t+--------------------뱾-------------------+\n");
printf("\t\t|\t\t\t\t\t |\n");
setColor(5);
printf("\t\t|\t\t 1. 鿴\t |\n\n");
setColor(1);
printf("\t\t|\t\t 2. \t\t |\n\n");
setColor(3);
printf("\t\t|\t\t 3. ɾ\t\t |\n\n");
setColor(7);
printf("\t\t|\t\t 4. \t\t |\n\n");
setColor(11);
printf("\t\t|\t\t 5. ѯ\t\t |\n\n");
setColor(6);
printf("\t\t|\t\t 6. ļ\t\t |\n\n");
setColor(10);
printf("\t\t|\t\t 0. ˳\t\t |\n");
printf("\t\t|\t\t\t\t\t |\n");
printf("\t\t+---------------------------------------------+\n\n");
setColor(4);
printf("\t\t\tѡ[06][ ]\b\b");
int op;
scanf_s("%d", &op);
switch (op)
{
case 鿴:
searchAllInfo(pPwd, nCount);
break;
case :
insertInfo(pPwd, &nCount);
break;
case ɾ:
deleteInfo(pPwd, &nCount);
break;
case :
alterInfo(pPwd, nCount);
break;
case ѯ:
searchInfo(pPwd, nCount);
break;
case ı:
saveInfoA(pPwd, nCount);
break;
case ˳:
exit(0);
break;
default:
break;
}
system("cls");
}
*/
return 0;
}
//ɫ
void setColor(int color)
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color);
}
/*
//ù
void setCurson(int x, int y)
{
COORD coord;
coord.X = x;
coord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
*/
| true |
43ac969d2427162cda39ac8633994d224cb63c82
|
C++
|
Starterware/MyCraft
|
/Playground/Languages/c++/DataStructures/Stack.cpp
|
UTF-8
| 1,032 | 3.640625 | 4 |
[] |
no_license
|
#include "gmock/gmock.h"
#include <stack>
using namespace ::testing;
/*
Stacks are a type of container adaptor, specifically designed to operate in a LIFO context (last-in first-out).
The standard container classes vector, deque and list fulfill these requirements.
*/
class Stack : public Test {
protected:
std::stack<int> s;
};
TEST_F(Stack, test_empty)
{
ASSERT_THAT(s.empty(), Eq(true));
}
TEST_F(Stack, test_size)
{
ASSERT_THAT(s.size(), Eq(0));
}
TEST_F(Stack, test_add_element) // O(1)
{
s.push(1);
ASSERT_THAT(s.size(), Eq(1));
}
TEST_F(Stack, test_see_next_element) // O(1)
{
s.push(1);
s.push(2);
ASSERT_THAT(s.top(), Eq(2));
}
TEST_F(Stack, test_remove_element) // O(1)
{
s.push(1);
s.push(2);
s.pop();
ASSERT_THAT(s.top(), Eq(1));
}
TEST(StackBasedOnDifferentContainer, test_creation)
{
std::stack<int, std::vector<int>> s;
s.push(3);
ASSERT_THAT(s.top(), Eq(3));
}
TEST(StackInitFromContainer, test_creation)
{
std::stack<int> s(std::deque<int> {1, 2, 3});
ASSERT_THAT(s.top(), Eq(3));
}
| true |
aceca5920e5a0b93381a15f67d796ba871f142e8
|
C++
|
mz-zajaczkowski/boost_serialize
|
/main.cpp
|
UTF-8
| 3,030 | 3.234375 | 3 |
[] |
no_license
|
#include <bitset>
#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/ptree.hpp>
#include <iostream>
#include <list>
#include <memory>
#include <vector>
using namespace std;
class Attribute {
public:
Attribute() { m_flags.set(static_cast<size_t>(Flags::isSerializable)); }
enum class Flags : uint8_t {
isSerializable = 0,
isWeird,
isSthElse,
is3,
is4,
is5,
is6,
is7,
is8,
SIZE
};
typedef std::bitset<static_cast<size_t>(Flags::SIZE)> Type;
void setFlags(const Type &flags) { m_flags = flags; }
inline bool isSerializable() {
return m_flags.test(static_cast<size_t>(Flags::isSerializable));
}
inline bool isWeird() {
return m_flags.test(static_cast<size_t>(Flags::isWeird));
}
inline bool isSthElse() {
return m_flags.test(static_cast<size_t>(Flags::isSthElse));
}
inline void setWeird() { m_flags.set(static_cast<size_t>(Flags::isWeird)); }
private:
Type m_flags;
};
class A {
public:
A() {
Attribute sth;
m_attrs.push_back(sth);
m_attrs.push_back(sth);
}
std::vector<Attribute> &getAttrs() { return m_attrs; }
private:
std::vector<Attribute> m_attrs;
};
class B {
public:
B(const A &base) : attribs(base) {}
inline bool isSer() {
for (auto &attr : attribs.getAttrs()) {
if (attr.isSerializable())
return true;
}
return false;
}
inline bool isWeird() {
for (auto &attr : attribs.getAttrs()) {
if (attr.isWeird())
return true;
}
return false;
}
inline bool isSthElse() {
for (auto &attr : attribs.getAttrs()) {
if (attr.isSthElse())
return true;
}
return false;
}
inline std::vector<Attribute> &getA() { return attribs.getAttrs(); }
private:
B() {}
A attribs;
};
using namespace boost::property_tree;
template <typename T> void serialize(T &object, ptree &root);
template <typename T> T &deserialize(ptree &root);
template <template <class...> class Container, class T>
void serialize(Container<T> &cont, ptree &root) {
for (auto &item : cont) {
cout << "serializing container item" << std::endl;
serialize(item, root);
}
}
// template <typename T> void serialize(std::vector<T> &vec, ptree &root) {
// for (auto &item : vec) {
// cout << "serializing vector item" << std::endl;
// serialize(item, root);
// }
//}
template <> void serialize(Attribute &object, ptree &root) {
ptree attrTree;
attrTree.put("isSerializable", object.isSerializable());
attrTree.put("isWeird", object.isWeird());
attrTree.put("isSthElse", object.isSthElse());
root.add_child("Attribute", attrTree);
}
template <> void serialize(B &object, ptree &root) {
ptree bTree;
ptree aTree;
serialize(object.getA(), aTree);
bTree.add_child("ATYPE", aTree);
root.add_child("BTYPE", bTree);
}
int main() {
A aObj;
aObj.getAttrs()[0].setWeird();
B bObj(aObj);
ptree root;
serialize(bObj, root);
write_json(std::cout, root);
cout << "Hello World!" << endl;
return 0;
}
| true |
0954358fb2e41d4ea88cc2026892f85042e53ecc
|
C++
|
averbukh/omniscidb
|
/Shared/json.h
|
UTF-8
| 11,474 | 2.75 | 3 |
[
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] |
permissive
|
// Copyright (c) 2021 OmniSci, Inc.
//
// 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.
// OmniSci JSON
// EXAMPLE #1
//
// #include "Shared/json.h"
// using JSON = omnisci::JSON;
// JSON json;
// json["item1"] = "abc";
// json["item2"] = 123;
// std::cout << json.stringify() << std::endl;
// std::cout << static_cast<int>(json["item2"]) << std::endl;
//
// OUTPUT: {"item1":"abc","item2":123}
// OUTPUT: 123
// EXAMPLE #2
//
// #include "Shared/json.h"
// using JSON = omnisci::JSON;
// std::string text = R"json(
// {
// "item1": "abc",
// "item2": 123
// }
// )json";
// JSON json(text);
// json["item3"] = false;
// json["item4"].parse("[0, 1, 2, 3, 4]");
// std::cout << json.stringify() << std::endl;
// std::cout << static_cast<size_t>(json["item4"][2]) << std::endl;
//
// OUTPUT: {"item1":"abc","item2":123,"item3":false,"item4":[0,1,2,3,4]}
// OUTPUT: 2
#pragma once
#include <rapidjson/document.h>
#include <rapidjson/stringbuffer.h>
#include <rapidjson/writer.h>
#include <limits>
#include <memory>
#include <stdexcept>
#include <string>
#include <type_traits>
// Calling any public JSON constructor except the move constructor creates a new document.
// Calling JSON's operator[] creates a reference into an existing document.
namespace omnisci {
class JSON final {
std::shared_ptr<rapidjson::Document> doc_;
rapidjson::Value* vptr_;
rapidjson::Document::AllocatorType& allo_;
const std::string name_; // only used in error messages
public:
// Default constructor makes a new empty document.
JSON()
: doc_(std::make_shared<rapidjson::Document>())
, vptr_(&*doc_)
, allo_(doc_->GetAllocator())
, name_("JSON") {}
// Copy constructor to make a new document as a deep copy of the peer document.
JSON(const JSON& peer) : JSON() { vptr_->CopyFrom(*peer.vptr_, allo_); }
// Move constructor to keep the existing document. Class members are moved efficiently.
JSON(JSON&&) = default;
// Constructor from std::string to make a new document.
JSON(const std::string& json) : JSON() { parse(json); }
// Constructor from C-style string to make a new document.
JSON(const char* json) : JSON() { parse(json); }
// Constructor from C-style string plus a length to make a new document without having
// to scan the string for the null terminator.
JSON(const char* json, size_t len) : JSON() { parse(json, len); }
void parse(const std::string& json) {
if (doc_->Parse(json).HasParseError()) {
throw std::runtime_error("failed to parse json");
}
}
void parse(const char* json) {
if (doc_->Parse(json).HasParseError()) {
throw std::runtime_error("failed to parse json");
}
}
void parse(const char* json, size_t len) {
if (doc_->Parse(json, len).HasParseError()) {
throw std::runtime_error("failed to parse json");
}
}
std::string stringify() const {
rapidjson::StringBuffer buf;
rapidjson::Writer<rapidjson::StringBuffer> wr(buf);
vptr_->Accept(wr);
return buf.GetString();
}
[[deprecated]] std::string getType() const { return kTypeNames[vptr_->GetType()]; }
bool isString() const { return vptr_->IsString(); }
bool isNumber() const { return vptr_->IsNumber(); }
bool isBoolean() const { return vptr_->IsBool(); }
bool isObject() const { return vptr_->IsObject(); }
bool isArray() const { return vptr_->IsArray(); }
bool isNull() const { return vptr_->IsNull(); }
bool hasMember(const std::string& name) const { return vptr_->HasMember(name); }
operator std::string() const {
if (!vptr_->IsString()) {
throw std::runtime_error("expected JSON field '" + name_ +
"' to be String but got [" + kTypeNames[vptr_->GetType()] +
"]");
}
return std::string{vptr_->GetString(), vptr_->GetStringLength()};
}
operator bool() const {
if (!vptr_->IsBool()) {
throw std::runtime_error("expected JSON field '" + name_ +
"' to be Boolean but got [" +
kTypeNames[vptr_->GetType()] + "]");
}
return vptr_->GetBool();
}
template <typename T>
operator T() const {
static_assert((std::is_integral_v<T> && !std::is_same_v<bool, std::remove_cv_t<T>>) ||
(std::is_floating_point_v<T>));
if constexpr (std::is_integral_v<T>) {
if constexpr (std::numeric_limits<T>::is_signed) {
if constexpr (sizeof(T) < 8) {
if (!vptr_->IsInt()) {
throw std::runtime_error("can't convert JSON field '" + name_ +
"' to be signed integer from [" +
kTypeNames[vptr_->GetType()] + "]");
}
return vptr_->GetInt();
} else {
if (!vptr_->IsInt64()) {
throw std::runtime_error("can't convert JSON field '" + name_ +
"' to be signed 64-bit integer from [" +
kTypeNames[vptr_->GetType()] + "]");
}
return vptr_->GetInt64();
}
} else {
if constexpr (sizeof(T) < 8) {
if (!vptr_->IsUint()) {
throw std::runtime_error("can't convert JSON field '" + name_ +
"' to be unsigned integer from [" +
kTypeNames[vptr_->GetType()] + "]");
}
return vptr_->GetUint();
} else {
if (!vptr_->IsUint64()) {
throw std::runtime_error("can't convert JSON field '" + name_ +
"' to be unsigned 64-bit integer from [" +
kTypeNames[vptr_->GetType()] + "]");
}
return vptr_->GetUint64();
}
}
} else if constexpr (std::is_floating_point_v<T>) {
if (!vptr_->IsDouble()) {
throw std::runtime_error("can't convert JSON field '" + name_ +
"' to be floating point number from [" +
kTypeNames[vptr_->GetType()] + "]");
}
return vptr_->GetDouble();
}
}
JSON& operator=(const JSON& peer) {
vptr_->CopyFrom(*peer.vptr_, allo_);
return *this;
}
JSON& operator=(const std::string& item) {
*vptr_ = rapidjson::Value().SetString(item, allo_);
return *this;
}
JSON& operator=(const char* item) {
*vptr_ = rapidjson::Value().SetString(item, allo_);
return *this;
}
JSON& operator=(bool item) {
vptr_->SetBool(item);
return *this;
}
JSON& operator=(int32_t item) {
vptr_->SetInt(item);
return *this;
}
JSON& operator=(int64_t item) {
vptr_->SetInt64(item);
return *this;
}
JSON& operator=(uint32_t item) {
vptr_->SetUint(item);
return *this;
}
JSON& operator=(uint64_t item) {
vptr_->SetUint64(item);
return *this;
}
JSON operator[](const std::string& name) { return (*this)[name.c_str()]; }
JSON operator[](const char* name) {
if (!vptr_->IsObject()) {
vptr_->SetObject();
}
if (!vptr_->HasMember(name)) {
vptr_->AddMember(
rapidjson::Value(name, allo_).Move(), rapidjson::Value().Move(), allo_);
auto f = vptr_->FindMember(name);
// f necessary because AddMember inexplicably doesn't return the new member
// https://stackoverflow.com/questions/52113291/which-object-reference-does-genericvalueaddmember-return
return JSON(doc_, &f->value, allo_, name);
}
return JSON(doc_, &(*vptr_)[name], allo_, name);
}
JSON operator[](const std::string& name) const { return (*this)[name.c_str()]; }
JSON operator[](const char* name) const {
if (!vptr_->IsObject()) {
throw std::runtime_error("JSON " + kTypeNames[vptr_->GetType()] + " field '" +
name_ + "' can't use operator []");
}
if (!vptr_->HasMember(name)) {
throw std::runtime_error("JSON field '" + std::string(name) + "' not found");
}
return JSON(doc_, &(*vptr_)[name], allo_, name);
}
template <typename T>
JSON operator[](T index) {
return operator[](static_cast<size_t>(index));
}
JSON operator[](size_t index) {
if (!vptr_->IsArray()) {
vptr_->SetArray();
}
if (index >= vptr_->Size()) {
throw std::runtime_error("JSON array index " + std::to_string(index) +
" out of range " + std::to_string(vptr_->Size()));
}
return JSON(doc_, &(*vptr_)[index], allo_, std::to_string(index));
}
template <typename T>
JSON operator[](T index) const {
return operator[](static_cast<size_t>(index));
}
JSON operator[](size_t index) const {
if (!vptr_->IsArray()) {
throw std::runtime_error("JSON " + kTypeNames[vptr_->GetType()] + " field '" +
name_ + "' can't use operator []");
}
if (index >= vptr_->Size()) {
throw std::runtime_error("JSON array index " + std::to_string(index) +
" out of range " + std::to_string(vptr_->Size()));
}
return JSON(doc_, &(*vptr_)[index], allo_, std::to_string(index));
}
private:
inline static std::string kTypeNames[] =
{"Null", "False", "True", "Object", "Array", "String", "Number"};
// Constructor used by operator[] to produce a reference into an existing document.
JSON(std::shared_ptr<rapidjson::Document> doc,
rapidjson::Value* vptr,
rapidjson::Document::AllocatorType& allo,
const std::string& name)
: doc_(doc), vptr_(vptr), allo_(allo), name_(name) {}
friend bool operator==(const JSON& json1, const JSON& json2);
friend bool operator!=(const JSON& json1, const JSON& json2);
template <typename T>
friend bool operator==(const JSON& json, const T& value);
template <typename T>
friend bool operator==(const T& value, const JSON& json);
template <typename T>
friend bool operator!=(const JSON& json, const T& value);
template <typename T>
friend bool operator!=(const T& value, const JSON& json);
}; // class JSON
// Compare the values referred to by two JSON objects.
inline bool operator==(const JSON& json1, const JSON& json2) {
return (*json1.vptr_ == *json2.vptr_);
}
inline bool operator!=(const JSON& json1, const JSON& json2) {
return (*json1.vptr_ != *json2.vptr_);
}
// Compare a JSON object's value with a value of an arbitrary type.
template <typename T>
inline bool operator==(const JSON& json, const T& value) {
return (*json.vptr_ == value);
}
template <typename T>
inline bool operator==(const T& value, const JSON& json) {
return (json == value);
}
template <typename T>
inline bool operator!=(const JSON& json, const T& value) {
return (*json.vptr_ != value);
}
template <typename T>
inline bool operator!=(const T& value, const JSON& json) {
return (json != value);
}
} // namespace omnisci
| true |
9f6e905daf514ff5ec02bdbc1469328d72d6ce0f
|
C++
|
fullsaildevelopment/FSGDEngine
|
/EDRendererD3D/ViewPortManager.h
|
UTF-8
| 6,471 | 2.609375 | 3 |
[] |
no_license
|
#pragma once
#include "..\EDRendererD3D\RenderShapeTarget.h"
#include "..\EDMath\Float4x4.h"
namespace EDRendererD3D
{
class ViewPortManager
{
class ViewPort
{
public:
/// The concatenated view and projection matrices to be used with this view port
EDMath::Float4x4 viewProjection;
EDMath::Float4x4 view;
EDMath::Float4x4 projection;
EDMath::Float4x4 world;
float nearClip;
float farClip;
EDRendererD3D::RenderShapeTarget viewPortQuad;
};
public:
~ViewPortManager(void);
/// Gets the view projection matrix of the view port that is currently active.
/// \return Returns the currently active viewport's view projection
inline const EDMath::Float4x4 &GetActiveViewProjection() const
{
return GetViewProjection(activePort);
}
/// Gets the view projection matrix of the view port whose index is passed in.
/// \param port - the index to the view port to select
/// \return Returns the selected viewport's view projection
inline const EDMath::Float4x4 &GetViewProjection(UINT port) const
{
return viewPorts[port].viewProjection;
}
/// Gets the world matrix of the view port that is currently active.
/// \return Returns the currently active viewport's world projection
inline const EDMath::Float4x4 &GetActiveWorld() const
{
return GetWorld(activePort);
}
/// Gets the world matrix of the view port whose index is passed in.
/// \param port - the index to the view port to select
/// \return Returns the selected viewport's world projection
inline const EDMath::Float4x4 &GetWorld(UINT port) const
{
return viewPorts[port].world;
}
/// Gets the view matrix of the view port that is currently active.
/// \return Returns the currently active viewport's view projection
inline const EDMath::Float4x4 &GetActiveView() const
{
return GetView(activePort);
}
/// Gets the view matrix of the view port whose index is passed in.
/// \param port - the index to the view port to select
/// \return Returns the selected viewport's view projection
inline const EDMath::Float4x4 &GetView(UINT port) const
{
return viewPorts[port].view;
}
/// Gets the projection matrix of the view port that is currently active.
/// \return Returns the currently active viewport's view projection
inline const EDMath::Float4x4 &GetActiveProjection() const
{
return GetProjection(activePort);
}
/// Gets the projection matrix of the view port whose index is passed in.
/// \param port - the index to the view port to select
/// \return Returns the selected viewport's view projection
inline const EDMath::Float4x4 &GetProjection(UINT port) const
{
return viewPorts[port].projection;
}
/// Gets the position of the viewer for the active viewport
/// \return Returns the position of the viewer
inline const EDMath::Float3 &GetActiveViewPosition() { return GetPosition(activePort); }
/// Gets the position of the viewer for the selected viewport
/// \param port - the index to the view port to select
/// \return Returns the position of the viewer
inline const EDMath::Float3 &GetPosition(UINT port )
{
return viewPorts[port].world.WAxis;
}
/// Gets the facing direction of the viewer for the active viewport
/// \return Returns the facing direction of the viewer
inline const EDMath::Float3 &GetActiveViewForward() { return GetForward(activePort); }
/// Gets the facing direction of the viewer for the selected viewport
/// \param port - the index to the view port to select
/// \return Returns the facing direction of the viewer
inline const EDMath::Float3 &GetForward(UINT port ) { return viewPorts[port].world.ZAxis; }
/// Gets the near clip plane distance for the selected viewport
/// \param port - the index to the view port to select
/// \return Returns the near clip distance of the selected view port
inline float GetNearClip(UINT port) { return viewPorts[port].nearClip; }
/// Gets the near clip plane distance for the active viewport
/// \return Returns the near clip distance of the active view port
inline float GetActiveViewNearClip() { return GetNearClip(activePort); }
/// Gets the far clip plane distance for the selected viewport
/// \param port - the index to the view port to select
/// \return Returns the far clip distance of the selected view port
inline float GetFarClip(UINT port) { return viewPorts[port].farClip; }
/// Gets the far clip plane distance for the active viewport
/// \return Returns the far clip distance of the active view port
inline float GetActiveViewFarClip() { return GetFarClip(activePort); }
/// Gets the facing direction of the viewer for the active viewport
/// \param port - the index to the view port to select
/// \return Returns the facing direction of the viewer
inline const EDMath::Float3 &GetActiveViewForward(UINT port )
{ return viewPorts[port].world.ZAxis; }
void UpdateViewPort(int port, const EDMath::Float4x4 &_world,
const EDMath::Float4x4 &_view, const EDMath::Float4x4 &_projection,
float _nearClip, float _farClip);
void UpdateActiveViewPort(const EDMath::Float4x4 &_world, const EDMath::Float4x4 &_view,
const EDMath::Float4x4 &_projection, float _nearClip, float _farClip);
inline size_t GetNumViewPorts() { return viewPorts.size(); }
inline void SetActiveViewPort(UINT _activePort) { activePort = _activePort; }
/// \param _renderMeshPtr - The address of the mesh to be used while rendering this shape.
/// \param _renderContextPtr - The Address of the context to be used while rendering this shape.
/// \param _renderTargetPtr - The RenderTarget whose texture should be rendered
/// \param matrix - Defines where on the screen the view port should be
void AddViewPort(EDRendererD3D::RenderMesh *_renderMeshPtr,
EDRendererD3D::RenderContext *_renderContextPtr,
EDRendererD3D::RenderTarget *_renderTargetPtr, const EDMath::Float4x4 &matrix);
void RenderActiveViewPort();
static ViewPortManager &GetReference();
static void DeleteInstance();
private:
std::vector<ViewPort> viewPorts;
UINT activePort;
ViewPortManager(void);
ViewPortManager(const ViewPortManager&);
ViewPortManager &operator=(const ViewPortManager &);
static ViewPortManager *instancePtr;
void CalcViewProjection(UINT port)
{
EDMath::Multiply(viewPorts[port].viewProjection, viewPorts[port].view,
viewPorts[port].projection);
}
};
}
| true |
3902924b89ca7cedc6853f3061e45286b2f9b839
|
C++
|
PramodShenoy/Competitive-Coding
|
/Hackerrank/UniversityCodeSprint/volcano.cpp
|
UTF-8
| 1,388 | 2.828125 | 3 |
[] |
no_license
|
#include <bits/stdc++.h>
using namespace std;
void print_matrix(int area[][300],int n)
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cout<<area[i][j]<<" ";
}
cout<<endl;
}
}
void calc_effect(int area[][300],int n,int w,int x,int y)
{
int i,j,k;
area[x][y]=w;
for(k=1;k<=w;k++)
{
for(i=x-k;i<=x+k;i++)
{
if(i==x-k||i==x+k)
for(j=y-k;j<=y+k;j++)
{
if((i<n && i>=0) && (j<n && j>=0))
{
area[i][j]+=w-k;
}
}
else
for(j=y-k;j<=y+k;j=j+2*k)
{
if((i<n && i>=0) && (j<n && j>=0))
{
area[i][j]+=w-k;
}
}
}
}
}
int main() {
int n;
int i,j,k;
int max = -1;
cin >> n;
int m;
cin >> m;
int area[n][300]={0};
for(int a0 = 0; a0 <m; a0++)
{
int x;
int y;
int w;
cin >> x >> y >> w;
calc_effect(area,n,w,x,y);
//print_matrix(area,n);
}
//cout<<area[5][5];
for( i=0;i<n;i++)
{
for( j=0;j<n;j++)
if(area[i][j]>max)
max=area[i][j];
}
cout<<max<<endl;
return 0;
}
| true |
5ba674ee4ba4dd733f6ec8ad3383a22a28ae1f58
|
C++
|
gillesgold/ProcessNotification
|
/EventTracing/event_tracing/event_trace_error.h
|
UTF-8
| 430 | 2.6875 | 3 |
[] |
no_license
|
#pragma once
#include <cstdint>
#include <stdexcept>
#include <string>
namespace event_tracing
{
class event_trace_error : public std::runtime_error
{
public:
event_trace_error(const std::string& text, std::uint32_t error_code);
explicit event_trace_error(const std::string& text);
std::uint32_t get_error_code() const noexcept
{
return error_code_;
}
private:
std::uint32_t error_code_;
};
} //namespace event_tracing
| true |
f6e4505e87520295f0ef0aa203abbb6a8804a1d5
|
C++
|
1kzpro/international
|
/Kazybek/COMP 2710/Exam 2/node_example.cpp
|
UTF-8
| 472 | 2.921875 | 3 |
[] |
no_license
|
#include <iostream>
#include "single_node.h"
using namespace std;
int main() {
SinglyLinkedList *myListS = new SinglyLinkedList;
myListS->insertNode(0, 1);
myListS->insertNode(0, 2);
myListS->insertNode(0, 3);
myListS->insertNode(0, 4);
myListS->insertNode(0, 5);
myListS->display();
myListS->head = myListS->reverse(NULL, myListS->head);
// cout << myListS->getNode(0)->next->value << endl;
myListS->display();
return 0;
}
| true |
6111b3ee978afeb4eb5491d095b12871ea5f766f
|
C++
|
zorbathut/glop
|
/Glop/glop3d/Mesh.h
|
UTF-8
| 4,534 | 3.03125 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
// TODO: Add raw accessor for textures and add comments
// Add comments
// Allow removing points
// glBlend
//
// A simple triangle-based mesh that can be edited and rendered. All data is stored in flat arrays
// and rendering is done with vertex arrays.
#ifndef GLOP_GLOP3D_MESH_H__
#define GLOP_GLOP3D_MESH_H__
#ifndef GLOP_LEAN_AND_MEAN
// Includes
#include "../Base.h"
#include "../Color.h"
#include "Point3.h"
// Class declarations
class Texture;
// Mesh class definition
class Mesh {
public:
// Constructors
Mesh(int num_points_allocated, int num_triangles_allocated, bool has_normals, bool has_colors,
bool has_textures);
~Mesh();
// Point and triangle allocation
int GetNumPoints() const {return num_points_;}
int GetNumPointsAllocated() const {return num_points_allocated_;}
void AllocatePoints(int num_points);
int GetNumTriangles() const {return num_triangles_;}
int GetNumTrianglesAllocated() const {return num_triangles_allocated_;}
void AllocateTriangles(int num_triangles);
// Mutation
int AddPoint(const Point3 &position);
int AddPoint(const Point3 &position, const Vec3 &normal, const Color &color, float tu, float tv);
int AddTriangle(int v1, int v2, int v3, const Texture *texture = 0);
void SetPoint(int index, const Point3 &position);
void SetNormal(int index, const Vec3 &normal);
void SetColor(int index, const Color &color);
void SetTextureCoords(int index, float tu, float tv);
void SetVertexIndices(int triangle, int v1, int v2, int v3);
void SetTexture(int triangle, const Texture *texture);
// Raw data accessors
const float *points() const {return points_;}
float *points() {return points_;}
const float *normals() const {return normals_;}
float *normals() {return normals_;}
const float *colors() const {return colors_;}
float *colors() {return colors_;}
const float *texture_coords() const {return texture_coords_;}
float *texture_coords() {return texture_coords_;}
const Texture * const *textures() const {return textures_;}
const Texture **textures() {return textures_;}
const short *vertex_indices() const {return vertex_indices_;}
short *vertex_indices() {return vertex_indices_;}
// "Natural" accessors
Point3 GetPoint(int index) const {
const float *base = &points_[3*index];
return Point3(base[0], base[1], base[2]);
}
Point3 GetNormal(int index) const {
const float *base = &normals_[3*index];
return Vec3(base[0], base[1], base[2]);
}
Color GetColor(int index) const {
const float *base = &colors_[4*index];
return Color(base[0], base[1], base[2], base[3]);
}
float GetTextureU(int index) const {return texture_coords_[2*index];}
float GetTextureV(int index) const {return texture_coords_[2*index+1];}
const Texture *GetTexture(int triangle) const {return textures_[triangle];}
int GetVertexIndex(int triangle, int vertex) const {return vertex_indices_[3*triangle+vertex];}
// Utilities
float GetRadius() const;
void DirtyRadius() {radius_ = -1;}
void Render(const Viewpoint &viewpoint);
void Render() const;
void DirtyRendering() {num_groups_ = -1;}
private:
// Mesh definition
short num_points_allocated_, num_triangles_allocated_;
short num_points_, num_triangles_;
float *points_;
float *normals_;
float *colors_;
float *texture_coords_;
short *vertex_indices_;
const Texture **textures_;
// Rendering data
mutable short num_groups_allocated_, num_groups_;
mutable short *group_start_, *group_size_;
mutable bool *group_is_fixed_normal_, *group_is_fixed_color_;
// Other data
mutable float radius_;
DISALLOW_EVIL_CONSTRUCTORS(Mesh);
};
// StockMeshes class definition.
class StockMeshes {
public:
static Mesh *NewBoxMesh(float width, float height, float depth, const Color &color,
const Texture *texture = 0);
static Mesh *NewCubeMesh(float size, const Color &color, const Texture *texture = 0) {
return NewBoxMesh(size, size, size, color, texture);
}
static Mesh *NewSphereMesh(float width, float height, float depth, const Color &color,
int precision, const Texture *texture = 0);
static Mesh *NewSphereMesh(float radius, const Color &color, int precision,
const Texture *texture = 0) {
return NewSphereMesh(radius*2, radius*2, radius*2, color, precision, texture);
}
private:
DISALLOW_EVIL_CONSTRUCTORS(StockMeshes);
};
#endif // GLOP_LEAN_AND_MEAN
#endif // GLOP_GLOP3D_MESH_H__
| true |
a470b0f23eb27b654428547195c224881d3c1705
|
C++
|
LINxu233/Algorithm
|
/LintCode/407. 加一.cpp
|
UTF-8
| 438 | 2.859375 | 3 |
[] |
no_license
|
class Solution
{
public:
vector<int> plusOne(vector<int>& digits)
{
vector<int> result;
int jin_wei=1;
for(int i=digits.size()-1;i>=0;--i)
{
int temp=digits[i]+jin_wei;
result.push_back(temp);
jin_wei=temp/10;
}
if(jin_wei>0)
result.push_back(jin_wei);
reverse(result.begin(),result.end());
return result;
}
};
| true |
ce525fae62b004a5ce3fe47936d4cdcbc6cd1131
|
C++
|
tankiJong/morph-engine
|
/Engine/Math/Primitives/aabb3.hpp
|
UTF-8
| 945 | 2.546875 | 3 |
[] |
no_license
|
#pragma once
#include "Engine/Core/common.hpp"
#include "Engine/Math/Primitives/vec3.hpp"
#undef min
#undef max
struct aabb3 {
aabb3()
: min(INFINITY)
, max(-INFINITY) {}
aabb3(const vec3& center, float size);
aabb3(const vec3& center, const vec3& size);
/*
* 7 ----- 6
* / | / |
* 4 -+-- 5 |
* | 3 --|- 2
* | / | /
* 0 ---- 1
*
*/
void corners(span<vec3> out) const;
vec3 corner(uint index) const;
inline vec3 center() const { return (min + max) * .5f; }
inline vec3 size() const { return max - min; };
inline vec3 halfExtent() const { return (max - min) * .5f; }
inline void invalidate() {
min = vec3(INFINITY);
max = vec3(-INFINITY);
};
inline bool valid() const { return max.x >= min.x; }
bool contains(const vec3& pos) const;
bool grow(const vec3& pos);
bool grow(const aabb3& bound);
vec3 min;
vec3 max;
};
| true |
09bd0a4176ee3fe33a55eb470cc646fe6560a161
|
C++
|
ecfrantz/AlgoBowl
|
/verify.cpp
|
UTF-8
| 4,606 | 3.78125 | 4 |
[] |
no_license
|
#include <string>
#include <iostream>
#include <fstream>
#include <set>
#include <vector>
using namespace std;
// !!!!! TO VERIFY FILES SIMPLY RUN THIS PROGRAM WITH INPUT AND OUTPUT FILES IN THE SAME DIRECTORY !!!!! //
/// Structure that represents an addition action.
/// int:sum - summand1 + summand2 (result of action)
/// int:sumand1 - the first number in the sum
/// int:sumand2 - the second number in the sum
struct Action
{
int sum;
int sumand1;
int sumand2;
Action(int msum, int msumand1, int msumand2)
{
sum = msum;
sumand1 = msumand1;
sumand2 = msumand2;
}
};
/// Loads an input file by a specified path
/// string:path - path to file input
/// set<int> - the list of numbers loaded from the file
set<int> loadInput(string path)
{
// Create input file stream
ifstream inFile(path);
// Check for failure during file loading
if (inFile.fail())
{
cerr << "Error opening input file.";
exit(1);
}
// Initialize integers
set<int> numbers;
int number;
// Ignore first line because it only contains the number of numbers
inFile >> number;
// Read all numbers into storage
while (inFile.eof() == false)
{
inFile >> number;
numbers.insert(number);
}
inFile.close();
return numbers;
}
/// Loads an output file by a specified path
/// string:path - path to file input
/// vector<Action> - the list of actions loaded from the file
vector<Action> loadOutput(string path)
{
// Create input file stream
ifstream inFile(path);
// Check for failure during file loading
if (inFile.fail())
{
cerr << "Error opening output file.";
exit(1);
}
// Initialize actions
vector<Action> actions;
int numActions;
// Take the first line as the number of actions there should be
inFile >> numActions;
// Read the actions into storage
int sumand1;
int sumand2;
while (inFile.eof() == false)
{
inFile >> sumand1;
inFile >> sumand2;
actions.push_back(Action(sumand1 + sumand2, sumand1, sumand2));
}
// Verify that the number of actions matches the actions listed
if (numActions != actions.size())
{
cerr << "Incorrect number of actions. FAILED VERIFY!";
cin.ignore();
exit(1);
}
return actions;
}
/// Verify whether the output is a valid response to the input
/// set<int>:targetNumbers target numbers from input
/// vector<Action>:actions actions contained in output
void verify(set<int> targetNumbers, vector<Action> actions)
{
// Set up the basis numbers for the algorithm
set<int> basisNumbers;
basisNumbers.insert(1);
// Verify that all basis numbers are accounted for in the actions
int index = 0;
for (auto action = actions.begin(); action != actions.end(); action++)
{
// Increment debugging index
index++;
// Check that both numbers involved in the action are valid
if (basisNumbers.find(action->sumand1) == basisNumbers.end())
{
cerr << "Action #" << index << " is invalid. Tried using " << action->sumand1 << " which does not exist. FAILED VERIFY!";
cin.ignore();
exit(1);
}
if (basisNumbers.find(action->sumand2) == basisNumbers.end())
{
cerr << "Action #" << index << " is invalid. Tried using " << action->sumand2 << " which does not exist. FAILED VERIFY!";
cin.ignore();
exit(1);
}
// Add the new sum to the basis numbers
basisNumbers.insert(action->sum);
}
// Verify that all target numbers have been achieved
for (auto target = targetNumbers.begin(); target != targetNumbers.end(); target++)
{
if (basisNumbers.find(*target) == basisNumbers.end())
{
cerr << "Target number " << *target << " was missed. FAILED VERIFY!";
cin.ignore();
exit(1);
}
}
}
int main()
{
// Get input file name from user.
string inFileName;
cout << "Please enter an input file name: ";
cin >> inFileName;
// Get output file name from user.
string outFileName;
cout << "Please enter an output file name: ";
cin >> outFileName;
// Load inputs and outputs from file.
set<int> inputs = loadInput(inFileName);
vector<Action> actions = loadOutput(outFileName);
// Validate
verify(inputs, actions);
// Report success at verify
cout << "No problems occurred. SUCCESS VERIFY!";
cin.ignore();
}
| true |
374444563e58f69e5f6643e375ed16e35960039d
|
C++
|
ayushiborkar/Basic-cpp
|
/palindrom.cpp
|
UTF-8
| 380 | 3.109375 | 3 |
[] |
no_license
|
// while-loop
// updated 2021-08
#include<stdio.h>
#include<conio.h>
main() {
int a,b,c;
b = 0;
printf("enter any number:"); // enter 121
scanf("%d",&a);
c = a;
while(a>0) {
b = b*10+a%10;
a = a/10;
}
if(b==c) {
printf("%d is a palindrom number",b);
}
else {
printf("%d is not a palindrom number because result is: %d",c,b);
}
getch();
}
| true |
d6115db5dea7a8335af8d234debd2b7127bd7909
|
C++
|
Alpha-car/Baekjoon-Algorithm-Study
|
/Coding/Baekjoon/C:C++/17140.cpp
|
UTF-8
| 2,293 | 2.78125 | 3 |
[] |
no_license
|
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
#define MAX 102
int r, c, k;
int A[MAX][MAX];
int row, col;
void testprint(){
cout << endl;
for(int i = 0; i<row; ++i){
for(int j = 0; j<col; ++j){
cout << A[i][j] << " ";
}cout << endl;
}cout << endl;
}
void R_opr(){
for(int i = 0; i<row; ++i){
vector< pair<int,int> > freq; // first : 빈도 수, second : 숫자
bool visited[MAX] = {0, };
for(int j = 0; j<col; ++j){
if(A[i][j] > 0){
if(visited[A[i][j]]==false){
freq.push_back(make_pair(1,A[i][j]));
visited[A[i][j]] = true;
}
else{
int tmp = find_if(freq.begin(), freq.end(), [&](const pair<int,int>& element){return element.second == A[i][j];})-freq.begin();
freq[tmp].first++;
}
}
}
sort(freq.begin(), freq.end());
if(col < 2*freq.size()){
col = 2*freq.size();
}
for(int j = 0; j<col; ++j){
int tmp = j/2;
if(j<2*freq.size()){
if(j%2 == 0){
A[i][j] = freq[tmp].second;
}
else if(j%2 == 1){
A[i][j] = freq[tmp].first;
}
}
else{
A[i][j] = 0;
}
}
}
}
void C_opr(){
for(int i = 0; i<col; ++i){
vector< pair<int,int> > freq; // first : 빈도 수, second : 숫자
bool visited[MAX] = {0, };
for(int j = 0; j<row; ++j){
if(A[j][i] > 0){
if(visited[A[j][i]]==false){
freq.push_back(make_pair(1,A[j][i]));
visited[A[j][i]] = true;
}
else{
int tmp = find_if(freq.begin(), freq.end(), [&](const pair<int,int>& element){return element.second == A[j][i];})-freq.begin();
freq[tmp].first++;
}
}
}
sort(freq.begin(), freq.end());
if(row < 2*freq.size()){
row = 2*freq.size();
}
for(int j = 0; j<row; ++j){
int tmp = j/2;
if(j<2*freq.size()){
if(j%2 == 0){
A[j][i] = freq[tmp].second;
}
else if(j%2 == 1){
A[j][i] = freq[tmp].first;
}
}
else{
A[j][i] = 0;
}
}
}
}
int main(){
cin >> r >> c >> k;
r--; c--;
for(int i = 0; i<3; ++i){
for(int j = 0; j<3; ++j){
cin >> A[i][j];
}
}
row = 3;
col = 3;
int time_cnt = 0;
while(A[r][c]!=k){
if(time_cnt >= 100){
time_cnt = -1;
break;
}
time_cnt++;
if(row >= col){ R_opr(); }
else if(row < col){ C_opr(); }
}
cout << time_cnt << endl;
return 0;
}
| true |
6b727410fab7238c3acfc7b1e1e407ad70e2d834
|
C++
|
ailyanlu1/ACM-10
|
/Online Judge/uva online judge/uva11859.cpp
|
UTF-8
| 1,987 | 2.8125 | 3 |
[] |
no_license
|
/**************************************************************
AUTHOR: Hardy
TIME: 2016年 08月 05日 星期五 13:59:27 CST
ID: uva 11859
TYPE: Nim 博弈
DETAIL: 给出n*m的矩阵,每次选择一行,任选其中大于1的数,把其变成自己的真因
子,当所有的数都变成1的时候游戏结束,最后不能走的人输
TACTICS: 求出没一行的质因子数目的和(包括重复的),每一次操作相当于从一堆
石子中取出k个石子,转变成n堆石子的Nim游戏,求出没一行质因子数目的异或和,
为0则输,否则赢。
***************************************************************/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define MAX(a, b) (a > b ? a : b)
#define MIN(a, b) (a > b ? b : a)
#define CL(a) memset(a, 0, sizeof(a));
using namespace std;
typedef long long ll;
const int inf = 1e9+7;
const int mod = 1e9+7;
const int maxn = 10100, maxe = 1e6+7, maxv = 1e6+7;
int prime[maxn], isNotPrime[maxn], cnt, Count[maxn];
void init(){
CL(prime);
CL(isNotPrime);
cnt = 0;
for(int i = 2; i < maxn; i ++){
if(!isNotPrime[i])
prime[cnt++] = i;
for(int j = 0; j < cnt && prime[j] * i < maxn; j ++){
isNotPrime[prime[j] * i] = 1;
if(i % prime[j] == 0)
break;
}
}
for(int i = 2; i < maxn; i ++){
int res = 0, tmp = i;
for(int j = 0; j < cnt && prime[j] * prime[j] <= tmp; j ++){
if(tmp % prime[j] == 0){
while(tmp % prime[j] == 0){
tmp /= prime[j];
res ++;
}
}
}
if(tmp > 1){
res ++;
}
Count[i] = res;
}
}
int sto[55][55];
int main()
{
int T, n, m, cc = 1;
scanf("%d", &T);
init();
while(T --){
scanf("%d%d", &n, &m);
int ans = 0, ct;
for(int i = 0; i < n; i ++){
ct = 0;
for(int j = 0; j < m; j ++){
scanf("%d", &sto[i][j]);
ct += Count[sto[i][j]];
}
ans ^= ct;
}
printf("Case #%d: ", cc++);
if(ans == 0){
puts("NO");
}
else
puts("YES");
}
return 0;
}
| true |
0732bd2ee86654d601ee3df798138b9da8a8cbdd
|
C++
|
ngk123/algorithms
|
/spoj/ETF.cpp
|
UTF-8
| 1,077 | 2.75 | 3 |
[] |
no_license
|
#include<iostream>
#include<cmath>
#include<cstdio>
using namespace std;
typedef unsigned long long ull;
bool isPrime[1001]={0};
int ans[1001];
int idx=0;
void sieve(int n)
{
int i,temp,j;
isPrime[0]=isPrime[1]=1;
isPrime[2]=isPrime[3]=0;
temp=sqrt(n);
for(i=4;i<=n;i+=2)
{
isPrime[i]=1;
}
for(i=3;i<=temp;i+=2)
{
if(isPrime[i]==0)
{
for(j=i*i;j<=n;j+=2*i)
{
isPrime[j]=1;
}
}
}
for(i=0;i<=n;i++)
{
if(isPrime[i]==0)
{
ans[idx]=i;
//printf("%d\t",i);
idx++;
}
}
//printf("prim[%d]:%d\n",idx,ans[idx-1]);
}
int main()
{
int n,T,temp2,i;
ull temp;
sieve(1000);
cin>>T;
while(T--)
{
cin>>n;
temp=n;
temp2=sqrt(n);
for(i=0;i<idx;i++)
{
if(ans[i]>temp2)break;
//printf("%d\n",ans[i]);
if(n%ans[i]==0)
{
while(n%ans[i]==0)
{
n=n/ans[i];
//printf("n=%d\n",n);
}
temp=(temp*(ans[i]-1))/ans[i];
}
//printf("n=%d\n",n);
}
if(n>1){temp=(temp*(n-1))/n;}
//printf("flag\n");
printf("%llu\n",temp);
}
}
| true |
34733b0a3edf524d0456fbcde5441a19a8071ec6
|
C++
|
UNIVERSAL-IT-SYSTEMS/mathgraphica
|
/gui/functions_gui.cpp
|
UTF-8
| 2,554 | 2.53125 | 3 |
[] |
no_license
|
#include "functions_gui.h"
#include "ui_functions_gui.h"
#include "globalfunctions.h"
#include <QMessageBox>
Functions_gui::Functions_gui(QWidget *parent) :
QWidget(parent),
ui(new Ui::Functions_gui)
{
ui->setupUi(this);
valueReturn = -1;
m_functionsListPtr = NULL;
}
Functions_gui::~Functions_gui()
{
m_functionsListPtr = NULL;
delete ui;
}
void Functions_gui::showEvent(QShowEvent *event)
{
Q_UNUSED(event);
updateFunctions();
}
void Functions_gui::updateFunctions()
{
if (m_functionsListPtr == NULL)
return;
QStringList m_functions_List;
for (int i = 0; i < m_functionsListPtr->size(); i++)
{
m_functions_List.append(m_functionsListPtr->at(i).GetFunctionDefinition());
}
QStringListToTableWidget(m_functions_List, *ui->tableWidget);
}
void Functions_gui::on_pushButton_new_clicked()
{
ui->tableWidget->setRowCount(ui->tableWidget->rowCount()+1);
}
void Functions_gui::on_pushButton_delete_clicked()
{
int index = ui->tableWidget->currentRow();
//if (index < 0 || index >= m_functions_List.size())
// return;
if (index < 0 || index >= m_functionsListPtr->size())
return;
QString aux = tr("Delete function ?\n") + ui->tableWidget->item(index,0)->text();
int r = QMessageBox::warning(this, tr("Delete function"), aux, QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
if (r == QMessageBox::Yes)
{
m_functionsListPtr->removeAt(index);
//m_functions_List.removeAt(index);
updateFunctions();
}
}
void Functions_gui::on_pushButton_ok_clicked()
{
if (m_functionsListPtr == NULL)
return;
//-- to refactor, check wich functions have been changed and only update those
// for now wI'm felling lazy and will just delete all and then copy all from tablewidget
//(*m_functionsListPtr).clear();
m_functionsListPtr->clear();
//m_functions_List.clear();
for (int i = 0; i < ui->tableWidget->rowCount(); i++)
{
if (ui->tableWidget->item(i,0) != 0)
{
QString aux = ui->tableWidget->item(i,0)->text();
if (m_function->SetFunction(aux)) // only saves valid functions
m_functionsListPtr->append(*m_function);
}
}
//m_functionsListPtr
valueReturn = 1;
close();
}
void Functions_gui::on_pushButton_cancel_clicked()
{
valueReturn = 0;
close();
}
| true |
5969c126fa66a47a075fd532979b6144e7e257af
|
C++
|
langkamil/Application_Programming_Course_2021
|
/Bank_simulation/Client.cpp
|
UTF-8
| 791 | 3.53125 | 4 |
[] |
no_license
|
#pragma once
#include "Client.h"
Client::Client(): name("John"), surname("Doe")
{
cout << "Constructor of class Client without arg. is working.\n";
}
Client::Client(string _name, string _surname, Address _address):
name(_name), surname(_surname), address(_address)
{
cout << "Constructor of class Client with 3 arg. is working.\n";
}
string Client::getName()
{
return name;
}
string Client::getSurname()
{
return surname;
}
Address Client::getAddress()
{
return address;
}
void Client::setName(string _name)
{
name = _name;
}
void Client::setSurname(string _surname)
{
surname = _surname;
}
void Client::setAddress(Address _address)
{
address = _address;
}
void Client::displayClient()
{
cout << "Name: " << name << "\nSurname: " << surname;
address.displayAddress();
}
| true |
f40327153473076fb0fd37dcca0da4b812263739
|
C++
|
aeremin/Codeforces
|
/alexey/Solvers/6xx/676/Solver676E.cpp
|
UTF-8
| 2,306 | 3.015625 | 3 |
[] |
no_license
|
#include <Solvers/pch.h>
#include "algo/io/baseio.h"
#include "iter/range.h"
#include "algo/polynomial/polynomial.h"
using namespace std;
// Solution for Codeforces problem http://codeforces.com/contest/676/problem/E
class Solver676E {
public:
void run();
};
bool isRoot(const Polynomial<int>& p, int x) {
if (x == 0)
return p.get_coefficient(0) == 0;
int val = 0;
for (int i : range(p.formal_degree() + 1)) {
val += p.coefficient(i);
if (val % x != 0)
return false;
val /= x;
}
return val == 0;
}
void Solver676E::run() {
int n, k;
cin >> n >> k;
vector<bool> isKnown(n + 1);
vector<int> coeffs(n + 1);
string s;
bool divisibleByX = false;
int actionsMade = 0;
for (int i : range(n + 1)) {
cin >> s;
isKnown[i] = (s != "?");
actionsMade += isKnown[i];
if (isKnown[i]) {
stringstream ss(s);
ss >> coeffs[i];
}
if (i == 0)
divisibleByX = s == "0";
}
if (k == 0) {
if (divisibleByX) {
cout << "Yes";
}
else if (isKnown[0]) {
cout << "No";
}
else if (actionsMade % 2 == 0) {
cout << "No";
}
else cout << "Yes";
}
else {
if (actionsMade == n + 1) {
auto p = Polynomial<int>(move(coeffs));
if (isRoot(p, k))
cout << "Yes";
else
cout << "No";
}
else {
if ((n + 1) % 2 == 0)
cout << "Yes";
else
cout << "No";
}
}
}
class Solver676ETest : public ProblemTest {};
TEST_F(Solver676ETest, Example1) {
string input = R"(1 2
-1
?
)";
string output = R"(Yes
)";
setInput(input);
Solver676E().run();
EXPECT_EQ_FUZZY(getOutput(), output);
}
TEST_F(Solver676ETest, Example2) {
string input = R"(2 100
-10000
0
1
)";
string output = R"(Yes
)";
setInput(input);
Solver676E().run();
EXPECT_EQ_FUZZY(getOutput(), output);
}
TEST_F(Solver676ETest, Example3) {
string input = R"(4 5
?
1
?
1
?
)";
string output = R"(No
)";
setInput(input);
Solver676E().run();
EXPECT_EQ_FUZZY(getOutput(), output);
}
| true |
cd2703478d47b7560e8397f669c821b0976f09f9
|
C++
|
yingwang/Invaders
|
/Invaders/Bomb.hpp
|
UTF-8
| 639 | 2.515625 | 3 |
[] |
no_license
|
//
// Bomb.hpp
// Invaders
//
// Created by Ying Wang on 2017-03-26.
// Copyright © 2017 Ying. All rights reserved.
//
#ifndef Bomb_hpp
#define Bomb_hpp
#include "Bomb.hpp"
#include "Sprite.hpp"
class Bomb
{
private:
Sprite *sprite;
int x;
int y;
bool rowUpdated;
public:
Bomb(SDL_Renderer* r, const std::string& path, const std::string& name, const int x, const int y);
void Draw() const;
void Update();
void ResetRowUpdated() { rowUpdated = false; }
bool RowUpdated() const { return rowUpdated; }
bool OutOfScreen() const;
int Row() const;
int Col() const;
};
#endif /* Bomb_hpp */
| true |
6c72dfcd1b7697a3377fae35b69f22e74cdf64f8
|
C++
|
colvez2020/MQQTTESP32OTAV4
|
/RTC_user.cpp
|
UTF-8
| 4,508 | 2.8125 | 3 |
[] |
no_license
|
#include <MCP7940_ADO.h>
#include "RTC_user.h"
#define RTC_DEBUG
String daysOfTheWeek[7] = { "Domingo", "Lunes", "Martes", "Miercoles", "Jueves", "Viernes", "Sabado" };
String monthsNames[12] = { "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre" };
TIME_Assert Mes_Assert[13];
TIME_Assert Dia_Assert[32];
TIME_Assert Hora_Assert[25];
RTC_MCP7940 rtc;
DateTime now_DATE;
//Temporizador por segundos
bool time_validar_seg(long *time_ref,long seg_segmento)
{
if(*time_ref==0) //Empezado conteo (primera vez)
*time_ref = millis();
if ( millis() - *time_ref > (seg_segmento*1000))
{
*time_ref = millis();
return true;
}
return false;
}
void Setup_RTC(void)
{
int i;
if (!rtc.begin())
{
Serial.println(F("Couldn't find RTC"));
//while (1);
}
// Si se ha perdido la corriente, fijar fecha y hora
//if (!rtc.isrunning())
{
// Fijar a fecha y hora de compilacion
#ifdef RTC_DEBUG
Serial.println("Configuro RTC a fecha actual");
#endif
//Recordar reinicir el IDE, para tener la fecha actual de conpilacion.
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
// Fijar a fecha y hora específica. En el ejemplo, 21 de Enero de 2016 a las 03:00:00
// rtc.adjust(DateTime(2019,11, 14,10,21, 0));
}
for( i=0;i<13;i++)
Mes_Assert[i].result=false;
for( i=0;i<31;i++)
Dia_Assert[i].result=false;
for( i=0;i<24;i++)
Hora_Assert[i].result=false;
}
void printDate(void)
{
now_DATE = rtc.now();
Serial.print(now_DATE.year(), DEC);
Serial.print('/');
Serial.print(now_DATE.month(), DEC);
Serial.print('/');
Serial.println(now_DATE.day(), DEC);
//Serial.print(" (");
//Serial.print(daysOfTheWeek[now_DATE.dayOfTheWeek()]);
// Serial.print(") ");
Serial.print(now_DATE.hour(), DEC);
Serial.print(':');
Serial.print(now_DATE.minute(), DEC);
Serial.print(':');
Serial.print(now_DATE.second(), DEC);
Serial.println();
}
void FullDatetochar(char* Cadena)
{
char charBuf[50];
now_DATE = rtc.now();
String dia_Semana=daysOfTheWeek[now_DATE.DayOfWeek()];
dia_Semana.toCharArray(charBuf, 50);
snprintf(Cadena, 50,"%d/%d/%d (%s) %d:%d:%d",now_DATE.year()
,now_DATE.month()
,now_DATE.day()
,charBuf
,now_DATE.hour()
,now_DATE.minute()
,now_DATE.second());
}
void Datetochar(char* Cadena)
{
now_DATE = rtc.now();
snprintf(Cadena,16,"%d/%d/%d",now_DATE.day()
,now_DATE.month()
,now_DATE.year()-2000);
}
void Timetochar(char* Cadena)
{
char Hour_char[3];
char Min_char[3];
now_DATE = rtc.now();
if(now_DATE.hour()<9)
snprintf(Hour_char,3,"0%d",now_DATE.hour());
else
snprintf(Hour_char,3,"%d",now_DATE.hour());
Hour_char[2]='\0';
if(now_DATE.minute()<9)
snprintf(Min_char,3,"0%d",now_DATE.minute());
else
snprintf(Min_char,3,"%d",now_DATE.minute());
Min_char[2]='\0';
snprintf(Cadena, 16,"%s:%s",Hour_char
,Min_char);
}
bool time_equal(int ME, int DD, int HH)
{
now_DATE = rtc.now();
if(ME!=-1)
{
if(now_DATE.day()!= ME)
{
Mes_Assert[ME].result=false;;
return false;
}
else
{
if( Mes_Assert[ME].result==false)
{
Mes_Assert[ME].result=true;
return true;
}
}
}
if(DD!=-1)
{
if(now_DATE.minute()!= DD)
{
Dia_Assert[DD].result=false;
return false;
}
else
{
if(Dia_Assert[DD].result==false)
{
Dia_Assert[DD].result=true;
return true;
}
}
}
if(HH!=-1)
{
if(now_DATE.hour()!= HH)
{
Hora_Assert[HH].result=false;
return false;
}
else
{
//Serial.print("1.hora igual=>Hora_Assert[HH].result=");
//Serial.println(Hora_Assert[HH].result);
if(Hora_Assert[HH].result==false)
{
//Serial.print("2.hora igual=Hora_Assert[HH].result=");
Hora_Assert[HH].result=true;
//Serial.println(Hora_Assert[HH].result);
return true;
}
}
}
return false;
}
| true |
d3b4d9c5f149cd926558cadfb0b0035ed42ef1eb
|
C++
|
JohnSpirit/2048Ai_V4
|
/treenode.cpp
|
GB18030
| 7,240 | 2.515625 | 3 |
[] |
no_license
|
#include "treenode.h"
float TreeNode::_weight[4] = { 0.5F,0.0F,0.5F,0.0F };
TreeNode::TreeNode(const Board & origin) :Board(origin)
{
_eval();
}
TreeNode::TreeNode(const TreeNode & origin, int8 dir) : Board(origin)
{
this->_depth = origin._depth + 1;
_root = (TreeNode*)&origin;
if (Move(dir)) { AddNum(); _eval(); /*printf("New node created: depth=%d, ses=%.3f\n",this->_depth,this->_eval_score);*/ }
else _depth = -1;
}
void TreeNode::_qsort(COOR_DATA data[], int8 start, int8 end)
{
if (start >= end)return;
loop_control low = start, high = end;
int8 pivot = data[start].value;
COOR_DATA medium;
while (high > low)
{
while (data[high].value >= pivot)
{
high--;
if (high <= low)break;
}
while (data[low].value <= pivot)
{
low++;
if (high <= low)break;
}
if (high <= low)break;
medium = data[low];
data[low] = data[high];
data[high] = medium;
}
medium = data[high];
data[high] = data[start];
data[start] = medium;
_qsort(data, start, high);
_qsort(data, high < low ? low : low + 1, end);
}
inline int8 TreeNode::_abs(int8 x)
{
return x >= 0 ? x : -x;
}
inline float TreeNode::_abs(float x)
{
return x >= 0 ? x : -x;
}
int8 TreeNode::_adj(COOR * const coor1, COOR * const coor2)
{
int8 i, j;
if (coor1->X == coor2->X)
{
i = coor1->Y - coor2->Y;
if (_abs(i) == 1)return 1;
else
{
if (i > 0) {
for (j = coor2->Y + 1; j < coor1->Y; j++)
if (_board[coor1->X][j])return 0;
}
else {
for (j = coor1->Y + 1; j < coor2->Y; j++)
if (_board[coor1->X][j])return 0;
}
return 1;
}
}
else if (coor1->Y == coor2->Y)
{
i = coor1->X - coor2->X;
if (_abs(i) == 1)return 1;
else
{
if (i > 0) {
for (j = coor2->X + 1; j < coor1->X; j++)
if (_board[j][coor1->Y])return 0;
}
else {
for (j = coor1->X + 1; j < coor2->X; j++)
if (_board[j][coor1->Y])return 0;
}
return 1;
}
}
else return 0;
}
void TreeNode::_eval()
{
_parameter[0] = _emptycoornum / 16.0F;
loop_control i = 0, j = 0, k = 0;
int8 nonemptycoornum = 16 - _emptycoornum;
//int8
// nonemptycoornum = 16 - _emptycoornum,
// largenum = 0,
// smallnum = 0,
// largenum_pos = 0,//ǰϴеλ
// smallnum_pos = 1,//ǰСеλ
// nextnum_pos = 0,//ǰȽССеλ
// largenum_rank = 0,//ϴ
// smallnum_rank = 1;//С
//int16
// total_value = 0,//Ȩֵ
// total_weight = 0;//Ȩֵ
//COOR_DATA* _sorted_coor_data = new COOR_DATA[nonemptycoornum];
//for (i = 0; i < 4; i++)
// for (j = 0; j < 4; j++)
// if (_board[i][j])
// {
// _sorted_coor_data[k].value = _board[i][j];
// _sorted_coor_data[k].coor.X = i;
// _sorted_coor_data[k].coor.Y = j;
// k++;
// }
//_qsort(_sorted_coor_data, 0, nonemptycoornum - 1);
//while (smallnum_pos < nonemptycoornum)
//{
// while (smallnum_pos < nonemptycoornum && largenum == _sorted_coor_data[smallnum_pos].value)smallnum_pos++;
// largenum = _sorted_coor_data[largenum_pos].value;
// smallnum = smallnum_pos < nonemptycoornum ? _sorted_coor_data[smallnum_pos].value : 0;
// nextnum_pos = smallnum_pos + 1;
// while (nextnum_pos < nonemptycoornum && smallnum == _sorted_coor_data[nextnum_pos].value)nextnum_pos++;
// for (i = largenum_pos; i < smallnum_pos; i++)
// {
// for (j = largenum_pos + 1; j < smallnum_pos; j++)
// {
// total_value += _adj(&_sorted_coor_data[i].coor, &_sorted_coor_data[j].coor)*(largenum_rank << 1);
// total_weight += largenum_rank << 1;
// }
// if (smallnum)for (; j < nextnum_pos; j++)
// {
// total_value += _adj(&_sorted_coor_data[i].coor, &_sorted_coor_data[j].coor)*(largenum_rank + smallnum_rank);
// total_weight += largenum_rank + smallnum_rank;
// }
// }
// largenum_pos = smallnum_pos;
// smallnum_pos = nextnum_pos;
// largenum_rank++;
// smallnum_rank++;
//}
//_parameter[1] = total_value / (float)total_weight;
//delete[] _sorted_coor_data;
_parameter[1] = 0.0F;
int16
C1_total_value = 0,//left-right
C1_equal_value = 0,
C1_total_weight = 0,
C2_total_value = 0,//up-down
C2_equal_value = 0,
C2_total_weight = 0;
float C1 = 0, C2 = 0;
loop_control
next_j = 1;
//left-right
for (i = 0; i < 4; i++)
for (j = 0, next_j = 1; j < 3; j = next_j, next_j = j + 1)
{
while (!_board[i][next_j] && next_j < 3)next_j++;
if (_board[i][j] > _board[i][next_j])C1_total_value += _board[i][j] + _board[i][next_j];
else if (_board[i][j] < _board[i][next_j]) C1_total_value -= _board[i][j] + _board[i][next_j];
else C1_equal_value += _board[i][j] + _board[i][next_j];
C1_total_weight += _board[i][j] + _board[i][next_j];
}
C1 = (_abs((float)C1_total_value) + C1_equal_value) / (float)C1_total_weight;
//up-down
for (i = 0; i < 4; i++)
for (j = 0, next_j = 1; j < 3; j = next_j, next_j = j + 1)
{
while (!_board[next_j][i] && next_j < 3)next_j++;
if (_board[j][i] > _board[next_j][i])C2_total_value += _board[j][i] + _board[next_j][i];
else if (_board[j][i] < _board[next_j][i]) C2_total_value -= _board[j][i] + _board[next_j][i];
else C2_equal_value += _board[j][i] + _board[next_j][i];
C2_total_weight += _board[j][i] + _board[next_j][i];
}
C2 = (_abs((float)C2_total_value) + C2_equal_value) / (float)C2_total_weight;
_parameter[2] = (C1 + C2) / 2.0F;
_parameter[3] = 0.0F;
//int16
// D_total_value = 0,//left-right
// D_equal_value = 0,
// D_total_weight = 0;
//if (C1 >= C2)
//{
// _parameter[2] = C1;
// //up-down
// for (i = 0; i < 4; i++)
// for (j = 0, next_j = 1; j < 3; j = next_j, next_j = j + 1)
// {
// while (!_board[next_j][i] && next_j < 3)next_j++;
// if ((i % 2) && _board[j][i] > _board[next_j][i] ||
// (!(i % 2)) && _board[j][i] < _board[next_j][i])
// D_total_value += _board[j][i] + _board[next_j][i];
// else if (_board[j][i] == _board[next_j][i])D_equal_value += _board[j][i] + _board[next_j][i];
// else D_total_value -= _board[j][i] + _board[next_j][i];
// D_total_weight += _board[j][i] + _board[next_j][i];
// }
//}
//else
//{
// _parameter[2] = C2;
// //left-right
// for (i = 0; i < 4; i++)
// for (j = 0, next_j = 1; j < 3; j = next_j, next_j = j + 1)
// {
// while (!_board[i][next_j] && next_j < 3)next_j++;
// if ((i % 2) && _board[i][j] > _board[i][next_j] ||
// (!(i % 2)) && _board[i][j] < _board[i][next_j])
// D_total_value += _board[i][j] + _board[i][next_j];
// else if (_board[i][j] == _board[i][next_j])D_equal_value += _board[i][j] + _board[i][next_j];
// else D_total_value -= _board[i][j] + _board[i][next_j];
// D_total_weight += _board[i][j] + _board[i][next_j];
// }
//}
//_parameter[3] = (_abs((float)D_total_value) + D_equal_value) / (float)D_total_weight;
_eval_score =
_parameter[0] * _weight[0] +
// _parameter[1] * _weight[1] +
_parameter[2] * _weight[2];// +
// _parameter[3] * _weight[3];
}
| true |
46c28502ffe8d04856ea9a133524459972aec86f
|
C++
|
jsonpark/iplanner2
|
/src/iplanner/mesh/mesh.h
|
UTF-8
| 1,087 | 2.953125 | 3 |
[
"MIT"
] |
permissive
|
#ifndef IPLANNER_MESH_MESH_H_
#define IPLANNER_MESH_MESH_H_
#include <vector>
#include <string>
namespace iplanner
{
class Mesh
{
public:
Mesh();
~Mesh();
void AddVertex(float x, float y, float z);
void AddNormal(float x, float y, float z);
void AddTexCoord(float u, float v);
void AddIndex(int i);
void SetDiffuseTextureFilename(const std::string& filename);
const auto& GetVertices() const
{
return vertices_;
}
const auto& GetNormals() const
{
return normals_;
}
const auto& GetTexCoords() const
{
return tex_coords_;
}
const auto& GetIndices() const
{
return indices_;
}
bool HasDiffuseTexture() const noexcept
{
return has_diffuse_texture_;
}
const auto& GetDiffuseTextureFilename() const noexcept
{
return diffuse_texture_filename_;
}
private:
std::vector<float> vertices_;
std::vector<float> normals_;
std::vector<float> tex_coords_;
std::vector<unsigned int> indices_;
bool has_diffuse_texture_ = false;
std::string diffuse_texture_filename_;
};
}
#endif // IPLANNER_MESH_MESH_H_
| true |
bdbbddabd70fba320564d2af7bd13a99cbd91731
|
C++
|
boxerprogrammer/TestCode
|
/NjTest/NinjaSprit/Game/Enemy/Kunai.h
|
SHIFT_JIS
| 1,026 | 2.546875 | 3 |
[
"Unlicense"
] |
permissive
|
#pragma once
#include "../Projectile.h"
class EffectManager;
class Kunai :
public Projectile
{
private:
int frame_ = 0;
int bulletH_ = -1;
float speed_ = 1.0f;
float centripetalSpeed_ = 0.0f;
Vector2f initVel_;
std::shared_ptr<EffectManager> effectMgr_;
public:
/// <summary>
/// CeRXgN^
/// </summary>
/// <param name="pos">W</param>
/// <param name="vel">x</param>
/// <param name="camera">J</param>
Kunai(const Position2f& pos, const Vector2f& vel, std::shared_ptr<Camera> camera, std::shared_ptr<EffectManager> efk);
~Kunai();
/// <summary>
/// t[XV
/// </summary>
void Update()override;
/// <summary>
/// t[`
/// </summary>
void Draw()override;
/// <summary>
/// ՓˎCxg
/// </summary>
/// <param name="colInfo">Փˏ</param>
void OnHit(CollisionInfo& me, CollisionInfo& other)override;
};
| true |
4148907999b9040d6566692930a6822935c09a48
|
C++
|
green-fox-academy/mate0905
|
/CLionProjects/Week-4 /Day-1 /Practice 2/main.cpp
|
UTF-8
| 298 | 3.53125 | 4 |
[] |
no_license
|
#include <iostream>
using namespace std;
int main()
{
int a=5,b,c,amount;
cout << "Gave me a random number: ";
cin >> b;
cout << "Gave me another number: ";
cin >> c;
amount = a + b + c;
cout << "Value of the three variable: " << amount << endl;
return 0;
}
| true |
1c973b57b939a0d0a9a5ed3afd92e3e90eb8cee7
|
C++
|
saswatsk/Comprehensive-C
|
/STL And DS & Algo/Stack/Programs/Program to find redundant parenthesis/main.cpp
|
UTF-8
| 975 | 3.921875 | 4 |
[] |
no_license
|
// Duplication of balanced parenthesis
// https://www.youtube.com/watch?v=aMPXhEdpXFA
#include<iostream>
#include<cstring>
#include<stack>
using namespace std;
bool findRed(string str) {
stack<int> s;
for (char temp : str) {
// push if you get opening brackets or any other characters
if (temp != ')') {
s.push(temp);
} else {
if (s.top() == '(') {
return true;
} else {
while (s.top() != '(') {
s.pop();
}
s.pop();
}
}
}
return false;
}
int main() {
// for all the test cases
int testCases;
cin >> testCases;
while (testCases--) {
// input the string
string str;
cin >> str;
bool ans = findRed(str);
if (ans)
cout << "Duplicate" << endl;
else
cout << "Not Duplicates" << endl;
}
return 0;
}
| true |
3e0e94403eb3e905a04c55bd468df0504af6ec64
|
C++
|
manolo5535/MyInvicibleLibrary
|
/InvincibleServer/DataBase.h
|
UTF-8
| 1,610 | 2.8125 | 3 |
[] |
no_license
|
#ifndef INVINCIBLESERVER_DATABASE_H
#define INVINCIBLESERVER_DATABASE_H
#include <iostream>
#include <fstream>
#include <SFML/Network/Packet.hpp>
#include "Singleton.h"
#include "FaultTolerance.h"
class DataBase {
private:
/**
* @brief Almacena la tabla en los discos
* @param string content
* @param string action
*/
static void send(std::string content, std::string action);
public:
/**
* @brief Crea una tabla para gurdar los datos de las imagenes
*/
static void createTable();
/**
* @brief agrega un nuevo elemento a la tabla
* @param std::string content
*/
static void addToTable(std::string content);
/**
* @brief Obtiene las partes de la tabla almacenada en los discos y reconstruir la tabla
* @return std::string
*/
static std::string getTable();
/**
* @brief Divide un string en elementos segun un caracter especificado
* @param std::string
* @param splitCharacter
* @return LinkedList<std::string>
*/
static LinkedList<std::string> splitString(std::string string, char *splitCharacter);
/**
* @brief Obtiene la informacion de la imagen almacenada
* @param name Nombre de la imagen
* @return LinkedList<std::string>
*/
static LinkedList<std::string> getImageData(std::string name);
/**
* @brief Obtener una parte de la imagen almacenada en el disco
* @param disk Numero del disco que se esta consultando
* @return std::string
*/
static std::string getPart(int disk);
};
#endif //INVINCIBLESERVER_DATABASE_H
| true |
3f5ea29a25608443240c0d347839514340dd8b3f
|
C++
|
Chris--B/CSCI441-Zelda64
|
/include/Cameras/ArcBallCamera.hpp
|
UTF-8
| 597 | 2.515625 | 3 |
[] |
no_license
|
#pragma once
#include "Utils.hpp"
#include "Cameras/CameraBase.hpp"
/*
* Arc Ball Camera, the camera moves around a control point while mantaining
* a radius around the point.
*
* This camera class assumes an x,z plane and y with the up direction.
*
*/
/************************* DRAW ARC BALL CAMERA **************************/
class ArcBallCamera : public Camera {
public:
ArcBallCamera() : Camera() {}
ArcBallCamera(VecPolar arc) : Camera(Vec(), arc) {}
virtual void adjustGLU() const override;
protected:
virtual void internalDraw() const override;
private:
};
| true |
e3ce3abfc9ce266de99adcdb72c1fceda15ffdb5
|
C++
|
alex-Symbroson/Advent-of-Code
|
/2018/092_-2.cpp
|
UTF-8
| 1,310 | 2.765625 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
#include <vector>
const uint
players = 400,
marbles = 7186400;
uint score[players], cur = 0;
std::vector<uint> marble = {0};
#define D(...) //__VA_ARGS__
int main() {
uint i, n, max;
for(i = 0; i < players; i++) score[i] = 0;
for(i = 1; i <= marbles; i++) {
if(!(i % 23)) {
//printf("cur:%3i size:%3i ", cur, marble.size());
cur = (cur + marble.size() - 7) % marble.size();
score[i % players] += i + marble[cur];
//printf("erase:%3i\n", cur);
marble.erase(marble.begin() + cur);
} else {
cur = (cur + 2) % marble.size();
marble.insert(marble.begin() + cur, i);
}
D(
printf("%i: ",i);
for(n = 0; n < marble.size(); n++) printf("%i,",marble[n]);
printf("\n");
)
if((100 * i) % marbles == 0) printf("%i%%\n",100 * i / marbles);
/*
if(!(i%23)) {
var max = 0;
for(var n = 0; n <= score.length; n++) if(max < score[n]) max = score[n];
console.log(i + ": " + max);
}*/
//if(i%71864==0)console.log(i/71864);
}
max = 0;
for(i = 0; i < players; i++) if(max < score[i]) max = score[i];
printf("%i\n",max);
}
| true |
8a5f62fd0aa3b0d3d5d581f0f4719c03dcb1cd13
|
C++
|
cemysf/itu-blg
|
/blg252e/objehw1_yedek/SystemManager.h
|
UTF-8
| 7,572 | 3.453125 | 3 |
[] |
no_license
|
#ifndef SYSTEMMANAGER_H_INCLUDED
#define SYSTEMMANAGER_H_INCLUDED
#include <string>
#include <iostream>
using namespace std;
class Seat
{
unsigned short int rowNumber;
char column;
bool booked;
Seat *next;
public:
};
class FlightSection
{
int seatClass;
Seat *head;
FlightSection *next;
public:
};
class Airport
{
string name;
Airport *next;
friend class SystemManager;
public:
Airport(const string &n){ name = n; next=NULL; }
};
class Flight
{
string id;
int yy, mm, dd; //year,month,day
Airport *origin_airport;
Airport *dest_airport;
FlightSection *head_section;
Flight *next;
friend class SystemManager;
public:
Flight(const string &flight_id,int year,int month,int day); //{ id = flight_id; head_section=NULL; next=NULL; }
};
Flight::Flight(const string &flight_id,int year,int month,int day )
{
id = flight_id;
yy = year; mm = month; dd = day;
origin_airport=NULL; dest_airport=NULL;
head_section=NULL; next=NULL;
}
class Airline
{
string name;
Flight *head_flight;
Airline *next;
friend class SystemManager;
public:
Airline(const string &n){ name = n; head_flight=NULL; next=NULL; }
};
class SystemManager
{
Airport *head_airport;
Airline *head_airline;
public:
SystemManager() { head_airline=NULL; head_airport=NULL; }
bool createAirport(const string &n);
bool createAirline(const string &n);
bool createFlight(const string &aname,const string &orig, const string &dest,int year,int month,int day, const string &id);
//(const string &aname, string orig, string dest,int year,int month,int day, string id);
void displaySystemDetails();
};
bool SystemManager::createAirport(const string &n)
{
if(n.size() != 3)
{
cerr << "ERROR:Airport name is wrong in size" << endl;
return false;
}
Airport *new_airport, *traverse;
if(head_airport) //if list not empty
{
traverse = head_airport;
while(traverse)
{
if(n.compare(traverse->name) == 0)
{
cerr << "ERROR:Airport '"<< n << "' already exists" << endl;
return false;
}
else if(traverse->next == NULL)
break;
else traverse=traverse->next;
}
new_airport = new Airport(n);
if(!new_airport)
{
cerr << "ERROR:Memory allocation failed" << endl;
return false;
}
traverse->next = new_airport;
new_airport->next = NULL;
}
else // if list empty
{
new_airport = new Airport(n);
if(!new_airport)
{
cerr << "ERROR:Memory allocation failed" << endl;
return false;
}
head_airport = new_airport;
head_airport->next = NULL;
}
return true;
}
bool SystemManager::createAirline(const string &n)
{
Airline *new_airline, *traverse;
if(head_airline) //if list not empty
{
traverse = head_airline;
while(traverse)
{
if( n.compare(traverse->name) == 0)
{
cerr << "ERROR:Airline '"<< n << "' already exists" << endl;
return false;
}
else if(traverse->next == NULL)
break;
else traverse=traverse->next;
}
new_airline = new Airline(n);
if(!new_airline)
{
cerr << "ERROR:Memory allocation failed" << endl;
return false;
}
traverse->next = new_airline;
new_airline->next = NULL;
}
else // if list empty
{
new_airline = new Airline(n);
if(!new_airline)
{
cerr << "ERROR:Memory allocation failed" << endl;
return false;
}
head_airline = new_airline;
head_airline->next = NULL;
}
return true;
}
bool SystemManager::createFlight(const string &aname,const string &orig, const string &dest,int year,int month,int day, const string &id)
{
Airline *airline = head_airline;
Airport *airport_orig = head_airport;
Airport *airport_dest = head_airport;
while(airline)
{
if(aname.compare(airline->name)==0)
break;
airline=airline->next;
}
if(airline==NULL)
{
cerr << "ERROR:(id="<< id <<")Airline not found" << endl;
return false;
}
while(airport_orig)
{
if(orig.compare(airport_orig->name)==0)
break;
airport_orig=airport_orig->next;
}
if(airport_orig==NULL)
{
cerr << "ERROR:(id="<< id <<")Origin airport not found" << endl;
return false;
}
while(airport_dest)
{
if(dest.compare(airport_dest->name)==0)
break;
airport_dest=airport_dest->next;
}
if(airport_dest==NULL)
{
cerr << "ERROR:(id="<< id <<")Destination airport not found" << endl;
return false;
}
if(airport_dest->name.compare(airport_orig->name) == 0)
{
cerr << "ERROR:(id="<< id <<")Origin and destination are same" << endl;
return false;
}
Flight *newFlight = new Flight(id,year,month,day);
newFlight->origin_airport = airport_orig;
newFlight->dest_airport = airport_dest;
Flight *traverse = airline->head_flight;
if(traverse) //not the first flight of airline
{
while(traverse->next != NULL)
{
traverse = traverse->next;
}
traverse->next = newFlight;
}
else
airline->head_flight = newFlight;
return true;
}
void SystemManager::displaySystemDetails()
{
cout << "---Airports---" << endl;
Airport *traverse_airports = head_airport;
while(traverse_airports != NULL)
{
cout << traverse_airports->name << endl;
traverse_airports=traverse_airports->next;
}
cout << endl;
cout << "---Airlines---" << endl;
Airline *traverse_airlines = head_airline;
while(traverse_airlines != NULL)
{
cout << traverse_airlines->name << endl;
if(traverse_airlines->head_flight != NULL) //if this airline has flights
{
Flight *traverse_flights = traverse_airlines->head_flight;
cout << string(5,' ') <<"--Flights--" << endl;
cout << string(5,' ') <<"Orig" << "\t" << "Dest" << "\t" << "Year"<< "\t" << "Month" << "\t" << "Day"<< "\t" << "ID"<<endl;
while(traverse_flights != NULL)
{
cout << string(5,' ') << traverse_flights->origin_airport->name << "\t" << traverse_flights->dest_airport->name << "\t"
<< traverse_flights->yy << "\t" << traverse_flights->mm << "\t" << traverse_flights->dd
<< "\t" << traverse_flights->id << endl;
traverse_flights=traverse_flights->next;
}
}
traverse_airlines=traverse_airlines->next;
cout << endl;
}
cout << endl;
// cout << "--- Airlines ---" << endl;
// traverse_airlines = head_airline;
// Flight *traverse_flights = traverse_airlines->head_flight;
// while(traverse_flights != NULL && traverse_airlines !=NULL)
// {
// cout << traverse_airlines->name << endl;
// traverse_airlines=traverse_airlines->next;
// }
// cout << endl;
}
#endif // SYSTEMMANAGER_H_INCLUDED
| true |
867e3b48e10c796d58cf1c8a1d75a9c0c68b0bb4
|
C++
|
ParamDeshpande/micromouse
|
/mbed/src/path_planner.cpp
|
UTF-8
| 13,935 | 2.53125 | 3 |
[] |
no_license
|
#include "../include/commons.h"
#include "../include/path_planner.h"
#include "../include/sensor_commons.h"
#include "../include/motor_commons.h"
#include "../include/maze_commons.h"
bool check_left_wall(void) {
if ((side_left_IR > hasLeftWall)){
return TRUE;
}
return FALSE;
}
bool check_right_wall(void) {
if ((side_right_IR > hasRightWall)){//need to adjust value
return TRUE;
}
return FALSE;
}
bool check_front_wall(void) {
if ((front_right_IR > hasFrontWall && front_left_IR > hasFrontWall) ){
return TRUE;
}
return FALSE;
}
static bool leftWall = 0;
static bool rightWall = 0;
static float current_yaw_checkpoint;
static float prev_yaw_checkpoint;
static void turn_around(void){
current_yaw_checkpoint = current_yaw;
prev_yaw_checkpoint = current_yaw_checkpoint;
float diff;
diff = current_yaw_checkpoint - prev_yaw_checkpoint;
while( diff <= D_2_RAD(180)){
main_controller(0,MAX_W_ACLKWISE);
}
}
float current_cell_position;
float previous_cell_checkpoint;
void move_single_cell(void) {
//initialize encoder values to 0
frontwallflag = 0;
previous_cell_checkpoint = current_cell_position;
//while the left encoder has not moved 1 "full" cell yet
while(current_cell_position - previous_cell_checkpoint <= ONECELL && !frontwallflag)
{
current_cell_position = current_x;
//IR_module.fire_and_get(); //read in sensors to update sensor readings
//maintain_pos_and_orient(); //call pid to make sure it is going straight based on sensor readings
}
previous_cell_checkpoint = current_cell_position;
//stop fucntions after finished moving 1 cell
motorbreak();
//*/
}
void maintain_pos_and_orient(void){
leftWall = check_left_wall();
rightWall = check_right_wall();
if ((front_right_IR > PIDSTOP && front_left_IR > PIDSTOP)) //prevents mouse from crashing into wall due to errors.
{ //if this is called, its a BAD sign....
motorbreak();
//main_controller(0,0);//STOP EVERYTHING
frontwallflag = 1;
return;
}
if(leftWall && rightWall) {
// Serial.println("in the middle");
}
else if(leftWall){
// Serial.println("only left wall");
// change in error
}
// sensor only reads in right wall
else if(rightWall){
// Serial.println("only right wall");
// change in error
}
}//*/
double previous_x =0;
double previous_yaw = 0;
double previous_vel = 0 ;
double previous_w = 0 ;
void update_states(){
current_yaw = yawGyro_rads;
current_x = (left_enc_dist + right_enc_dist)/2;
current_vel = (current_x - previous_x)/delT ;//
current_w = (current_yaw - previous_yaw)/delT ;
//UPDATING PREVIOUS VALUES
previous_x = current_x ;
previous_yaw = current_yaw ;
}
/** Function: change_dir ****ONLY FUNCTION THAT TOUCHES THE MAIN PROGRAM*****
* Parameters: this_maze - the maze with flood values
* x,y - current mouse coordinates
* dir - current direction mouse is facing.
* Description: makes the mouse face new direction. updates the new coordinates of the mouse.
*/
void change_dir ( Maze * this_maze, short * x, short * y, short * dir){
Node * this_node; //initialize a node
short next_dir; //new direction to face after performing floodfill calculation
this_node = this_maze->map[(*x)][(*y)];
next_dir = get_smallest_neighbor_dir(this_node, *dir);
/* update the appropriate location value x or y */
if (next_dir == NORTH)
(*x) = (*x) - 1;
else if (next_dir == EAST)
(*y) = (*y) + 1;
else if (next_dir == SOUTH)
(*x) = (*x) + 1;
else if (next_dir == WEST)
(*y) = (*y) - 1;
// Turn the actual mouse in the optimal direction
if (*dir == NORTH) {
if (next_dir == WEST)
pivot_left();
else if (next_dir == EAST)
pivot_right();
else if (next_dir == SOUTH)
turn_around();
}
else if (*dir == EAST) {
if (next_dir == NORTH)
pivot_left();
else if (next_dir == SOUTH)
pivot_right();
else if (next_dir == WEST)
turn_around();
}
else if (*dir == SOUTH) {
if (next_dir == EAST)
pivot_left();
else if (next_dir == WEST)
pivot_right();
else if (next_dir == NORTH)
turn_around();
}
else if (*dir == WEST) {
if (next_dir == SOUTH)
pivot_left();
else if (next_dir == NORTH)
pivot_right();
else if (next_dir == EAST)
turn_around();
}
/* update the direction */
(*dir) = next_dir;
wait_ms(200);
}//end change_dir
/** Function: visit_node
* Parameters: this_maze - maze with flood values
* this_stack - stack for flood fill
* x,y - coordinates to be visited
* flag - whether to update goal cells or not
* Description: visits the cell, checks for walls, and updates flood values
*/
void visit_node(Maze * this_maze, Stack * this_stack, short x, short y, short flag) {
IR_module.fire_and_get();
Node * this_node; //initialize a node
short northwall, eastwall, southwall, westwall; //boolean values of wall on each side
this_node = this_maze->map[x][y]; //initialize node to the node we want to go to
northwall = eastwall = southwall = westwall = FALSE;
//correspondingly update the walls based on which direction we are facing
if (direction == NORTH) { //check if direction is currently facing NORTH
if (check_front_wall()) { //there is a front wall
set_wall(this_node, NORTH);
northwall = TRUE;
}
}
else if (direction == EAST){ //check if direction is currently facing EAST
if (check_front_wall()) {
set_wall(this_node, EAST);
eastwall = TRUE;
}
}
else if (direction == SOUTH) {
if (check_front_wall()) {
set_wall(this_node, SOUTH);
southwall = TRUE;
}
}
else {//direction we are facing is WEST
if (check_front_wall()) {
set_wall(this_node, WEST);
westwall = TRUE;
}
}
// Serial.print("Row");
// Serial.println(ROW);
// Serial.print("Col");
// Serial.println(COL);
/* If there is a wall -> do a series of checks and pushes onto the stack */
if (northwall) {
if (this_node->row != 0)
push (this_stack, MAP[ROW-1][COL]);
set_wall(this_node, NORTH);
}
if (eastwall) {
if (this_node->column != SIZE-1)
push (this_stack, MAP[ROW][COL+1]);
set_wall(this_node, EAST);
}
if (southwall) {
if (this_node->row != SIZE-1)
push (this_stack, MAP[ROW+1][COL]);
set_wall(this_node, SOUTH);
}
if (westwall) {
if (this_node->column != 0)
push (this_stack, MAP[ROW][COL-1]);
set_wall(this_node, WEST);
}
/* push this node itself, as it was updated */
push(this_stack, this_node);
/* pop until the stack is empty, and call flood_fill on that node */
while (!is_empty_Stack(this_stack)) {
pop(this_stack, &this_node);
/* NOTE: the flag parameter determines wheter to update goal cells or not */
flood_fill(this_node, this_stack, flag);
}
set_visited (this_node);
}//end visit_node
/** Function: visit_node
* Parameters: this_maze - maze with flood values
* this_stack - stack for flood fill
* x,y - coordinates to be visited
* flag - whether to update goal cells or not
* Description: visits the cell, checks for walls, and updates flood values
*/
void visit_next_node(Maze * this_maze, Stack * this_stack, short x, short y, short flag) {
IR_module.fire_and_get();
if(check_front_wall()) //return if there is a wall, meaning that we cannot determine wall info about the
return; //next node in front of this one.
Node * next_node = NULL;//node one cell ahead of direction faced.
short northwall, eastwall, southwall, westwall; //boolean values of wall on each side
northwall = eastwall = southwall = westwall = FALSE;
if( direction == NORTH && (y > 0) )
next_node = this_maze->map[x][y-1];
if( direction == EAST && (x < (SIZE - 1)) )
next_node = this_maze->map[x+1][y];
if( direction == SOUTH && (y < (SIZE-1)) )
next_node = this_maze->map[x][y+1];
if( direction == WEST && (x > 0) )
next_node = this_maze->map[x-1][y];
if( next_node == NULL ) //return if we are at the boundry of the maze.
return;
//correspondingly update the walls based on which direction we are facing
if (direction == NORTH) { //check if direction is currently facing NORTH
if (check_left_wall()) { //there is a left wall
set_wall(next_node, WEST); //set wall on the left
westwall = TRUE;
}
if (check_right_wall()) { //there is a right wall
set_wall(next_node, EAST);
eastwall = TRUE;
}
}
else if (direction == EAST){ //check if direction is currently facing EAST
if (check_left_wall()) {
set_wall(next_node, NORTH);
northwall = TRUE;
}
if (check_right_wall()) {
set_wall(next_node, SOUTH);
southwall = TRUE;
}
}
else if (direction == SOUTH) {
if (check_left_wall()) {
set_wall(next_node, EAST);
eastwall = TRUE;
}
if (check_right_wall()) {
set_wall(next_node, WEST);
westwall = TRUE;
}
}
else { //direction we are facing is WEST
if (check_left_wall()) {
set_wall(next_node, SOUTH);
southwall = TRUE;
}
if (check_right_wall()) {
set_wall(next_node, NORTH);
northwall = TRUE;
}
}
/* If there is a wall -> do a series of checks and pushes onto the stack */
if (northwall) {
if (next_node->row != 0)
push (this_stack, MAP[(next_node->row)-1][next_node->column]);
set_wall(next_node, NORTH);
}
if (eastwall) {
if (next_node->column != SIZE-1)
push (this_stack, MAP[next_node->row][(next_node->column)+1]);
set_wall(next_node, EAST);
}
if (southwall) {
if (next_node->row != SIZE-1)
push (this_stack, MAP[(next_node->row)+1][next_node->column]);
set_wall(next_node, SOUTH);
}
if (westwall) {
if (next_node->column != 0)
push (this_stack, MAP[next_node->row][(next_node->column)-1]);
set_wall(next_node, WEST);
}
/* push this node itself, as it was updated */
push(this_stack, next_node);
/* pop until the stack is empty, and call flood_fill on that node */
while (!is_empty_Stack(this_stack)) {
pop(this_stack, &next_node);
/* NOTE: the flag parameter determines wheter to update goal cells or not */
flood_fill(next_node, this_stack, flag);
}
//set_visited (this_node);
}//end visit_next_node
/** Function: check_goal_reached
* Parameters: x,y - coordinate to be checked
* found_goal - flag if goal cell was found or not
* Description: updates flag for whether goal cell was reached
*/
void check_goal_reached (short * x, short * y, short * found_goal) {
//if the mouse is in the center of the maze -> it found it's goal
if (*x == SIZE / 2 || *x == SIZE / 2 - 1) {
if (*y == SIZE / 2 || *y == SIZE / 2 - 1) {
*(found_goal) = TRUE;
}
}
}
///* update flag for whether goal cell was reached */
//void check_start_reached (short * x, short * y, short * found_start) {
//
// if (*x == START_X && *y == START_Y) {
// *(found_start) = TRUE;
// //printf("Start Coorinates Reached: %d, %d\n", *x, *y);
// }
//}
/**Function: set_center_walls
Description: fills in the wall values of the centers based on where
you discovered the goal from.
*/
void set_center_walls(short entered_x, short entered_y) {
// 8, 8 : NORTH or WEST
if (entered_x == SIZE/2 && entered_y == SIZE/2) {
set_wall(my_maze->map[SIZE/2 - 1][SIZE/2 - 1], NORTH);
set_wall(my_maze->map[SIZE/2 - 1][SIZE/2 - 1], WEST);
set_wall(my_maze->map[SIZE/2 - 1][SIZE/2], NORTH);
set_wall(my_maze->map[SIZE/2 - 1][SIZE/2], EAST);
set_wall(my_maze->map[SIZE/2][SIZE/2 - 1], SOUTH);
set_wall(my_maze->map[SIZE/2][SIZE/2 - 1], WEST);
}
// 8, 7 : NORTH or EAST
if (entered_x == SIZE/2 && entered_y == SIZE/2 - 1) {
set_wall(my_maze->map[SIZE/2 - 1][SIZE/2 - 1], NORTH);
set_wall(my_maze->map[SIZE/2 - 1][SIZE/2 - 1], WEST);
set_wall(my_maze->map[SIZE/2 - 1][SIZE/2], NORTH);
set_wall(my_maze->map[SIZE/2 - 1][SIZE/2], EAST);
set_wall(my_maze->map[SIZE/2][SIZE/2], SOUTH);
set_wall(my_maze->map[SIZE/2][SIZE/2], EAST);
}
// 7, 7 : SOUTH or EAST
if (entered_x == SIZE/2 - 1 && entered_y == SIZE/2 - 1) {
set_wall(my_maze->map[SIZE/2][SIZE/2 - 1], SOUTH);
set_wall(my_maze->map[SIZE/2][SIZE/2 - 1], WEST);
set_wall(my_maze->map[SIZE/2 - 1][SIZE/2], NORTH);
set_wall(my_maze->map[SIZE/2 - 1][SIZE/2], EAST);
set_wall(my_maze->map[SIZE/2][SIZE/2], SOUTH);
set_wall(my_maze->map[SIZE/2][SIZE/2], EAST);
}
// 7, 8 : SOUTH or WEST
if (entered_x == SIZE/2 - 1 && entered_y == SIZE/2) {
set_wall(my_maze->map[SIZE/2][SIZE/2 - 1], SOUTH);
set_wall(my_maze->map[SIZE/2][SIZE/2 - 1], WEST);
set_wall(my_maze->map[SIZE/2 - 1][SIZE/2 - 1], NORTH);
set_wall(my_maze->map[SIZE/2 - 1][SIZE/2 - 1], WEST);
set_wall(my_maze->map[SIZE/2][SIZE/2], SOUTH);
set_wall(my_maze->map[SIZE/2][SIZE/2], EAST);
}
}
/** Function: reflood_from_goal
Description: Resets all the flood values so that the goal is now the start without modifying wall values.
*/
void reflood_from_goal(void) {
for (int i = 0; i < SIZE; i++)
for (int j = 0; j < SIZE; j++)
my_maze->map[i][j]->floodval = LARGEVAL;
// set the start value to zero
set_value(my_maze->map[START_X][START_Y], 0);
/* push the neighbors of start cell to stack
then pop everything until all cells updated*/
push_open_neighbors(my_maze->map[START_X][START_Y], my_stack);
while(!is_empty_Stack(my_stack)) {
pop(my_stack, &temp);
if (!(temp->row == 15 && temp->column == 0))
flood_fill(temp, my_stack, TRUE);
}
}
| true |
76497947e33776f9cbfab5acef047c23d243b43c
|
C++
|
joakimvrangum/photon-rickroll-alarm-clock
|
/src/photon-AlarmClock/src/tft_screen.cpp
|
UTF-8
| 3,412 | 2.75 | 3 |
[] |
no_license
|
#ifndef TFT_SCREEN_CPP
#define TFT_SCREEN_CPP
/*
* Project VekkerklokkePhoton
* Description: --
* Author: Joakim Vrangum
* Date: 06.04.18
*/
#include "tft_screen.h"
String currDay;
int ukedagNum;
int mndNum;
int timeNum;
int minuttNum;
int sekundNum;
void Screen::initScreen() {
tft.initR( INITR_BLACKTAB );
tft.fillScreen(ST7735_BLACK); // Tegner skjermen sort
}
void Screen::printHeading() {
tft.setCursor(1, 0);
tft.setTextColor(ST7735_MAGENTA);
tft.setTextSize(3);
tft.setTextWrap(true);
tft.print("KLOKKEN");
tft.setTextSize(2);
tft.setCursor(37,30);
tft.print(":");
tft.setCursor(74,30);
tft.print(":");
}
void Screen::printDate() {
tft.setTextSize(2);
tft.setCursor(0,55);
tft.setTextColor(ST7735_BLACK);
tft.print(currDay);
tft.setCursor(0,55);
tft.setTextColor(ST7735_CYAN);
ukedagNum = Time.weekday();
mndNum = Time.month();
tft.print(weekdayNorwegian(ukedagNum));
tft.setCursor(0,75);
tft.print(Time.day());
tft.setCursor(30,75);
tft.setTextSize(1);
tft.print(monthNorwegian(mndNum));
}
void Screen::printAlarm(int& alarmHours, int& alarmMinutes) {
tft.setTextSize(2);
tft.setCursor(0,105);
tft.setTextColor(ST7735_RED);
tft.print("ALARM");
tft.setCursor(30,125);
tft.print(alarmHours);
tft.print(":");
tft.print(alarmMinutes);
}
void Screen::eraseAlarm(int& alarmHours, int& alarmMinutes) {
tft.setTextSize(2);
tft.setCursor(0,105);
tft.setTextColor(ST7735_BLACK);
tft.print("ALARM");
tft.setCursor(30,125);
tft.print(alarmHours);
tft.print(":");
tft.print(alarmMinutes);
}
void Screen::printTime() {
tft.setTextSize(2);
tft.setCursor(10,30);
if (timeNum != Time.hour()) {
tft.setCursor(10,30);
tft.setTextColor(ST7735_BLACK);
tft.print(timeNum);
timeNum = Time.hour();
tft.setCursor(10,30);
tft.setTextColor(ST7735_WHITE);
tft.print(timeNum);
}
tft.setCursor(50,30);
if (minuttNum != Time.minute()) {
tft.setCursor(50,30);
tft.setTextColor(ST7735_BLACK);
tft.print(minuttNum);
minuttNum = Time.minute();
tft.setCursor(50,30);
tft.setTextColor(ST7735_WHITE);
tft.print(minuttNum);
}
tft.setCursor(90,30);
tft.setTextColor(ST7735_BLACK);
tft.print(sekundNum);
tft.setCursor(90,30);
sekundNum = Time.second();
tft.setTextColor(ST7735_WHITE);
tft.print(sekundNum);
delay(900);
}
String Screen::weekdayNorwegian(int& weekdayNumber) {
switch (weekdayNumber) {
case 1:
return "Søndag";
case 2:
return "Mandag";
case 3:
return "Tirsdag";
case 4:
return "Onsdag";
case 5:
return "Torsdag";
case 6:
return "Fredag";
case 7:
return "Lørdag";
}
}
String Screen::monthNorwegian(int& monthNumber) {
switch (monthNumber) {
case 1:
return "JANUAR";
case 2:
return "FEBRUAR";
case 3:
return "MARS";
case 4:
return "APRIL";
case 5:
return "MAI";
case 6:
return "JUNI";
case 7:
return "JULI";
case 8:
return "AUGUST";
case 9:
return "SEPTEMBER";
case 10:
return "OKTOBER";
case 11:
return "NOVEMBER";
case 12:
return "DESEMBER";
}
}
#endif
| true |
298704390245c541f087f52851100023d486cc3d
|
C++
|
Mesywang/EPSILON_Noted
|
/EPSILON/core/vehicle_model/src/vehicle_model/vehicle_model.cc
|
UTF-8
| 2,292 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
#include "vehicle_model/vehicle_model.h"
#include "common/math/calculations.h"
#include "odeint-v2/boost/numeric/odeint.hpp"
namespace odeint = boost::numeric::odeint;
namespace simulator {
VehicleModel::VehicleModel() : wheelbase_len_(2.5) { UpdateInternalState(); }
VehicleModel::VehicleModel(double wheelbase_len, double max_steering_angle)
: wheelbase_len_(wheelbase_len), max_steering_angle_(max_steering_angle) {
UpdateInternalState();
}
VehicleModel::~VehicleModel() {}
void VehicleModel::Step(double dt) {
odeint::integrate(boost::ref(*this), internal_state_, 0.0, dt, dt);
state_.vec_position(0) = internal_state_[0];
state_.vec_position(1) = internal_state_[1];
state_.angle = normalize_angle(internal_state_[2]);
state_.steer = internal_state_[3];
if (fabs(state_.steer) >= fabs(max_steering_angle_)) {
if (state_.steer > 0)
state_.steer = max_steering_angle_;
else
state_.steer = -max_steering_angle_;
}
state_.velocity = internal_state_[4];
state_.curvature = tan(state_.steer) * 1.0 / wheelbase_len_;
state_.acceleration = control_.acc_long;
UpdateInternalState();
}
void VehicleModel::operator()(const InternalState &x, InternalState &dxdt,
const double /* t */) {
State cur_state;
cur_state.vec_position(0) = x[0];
cur_state.vec_position(1) = x[1];
cur_state.angle = x[2];
cur_state.steer = x[3];
cur_state.velocity = x[4];
dxdt[0] = cos(cur_state.angle) * cur_state.velocity;
dxdt[1] = sin(cur_state.angle) * cur_state.velocity;
dxdt[2] = tan(cur_state.steer) * cur_state.velocity / wheelbase_len_;
dxdt[3] = control_.steer_rate;
dxdt[4] = control_.acc_long;
}
void VehicleModel::set_control(const Control &control) {
control_ = control;
// TODO: (@denny.ding) add control limit here
}
const VehicleModel::State &VehicleModel::state(void) const { return state_; }
void VehicleModel::set_state(const VehicleModel::State &state) {
state_ = state;
UpdateInternalState();
}
void VehicleModel::UpdateInternalState(void) {
internal_state_[0] = state_.vec_position(0);
internal_state_[1] = state_.vec_position(1);
internal_state_[2] = state_.angle;
internal_state_[3] = state_.steer;
internal_state_[4] = state_.velocity;
}
} // namespace simulator
| true |
824b85dcdbff4bbffb470182acd3e19b7ea74ebc
|
C++
|
mscoccimarro/odd-sentiment-analysis
|
/Grupo3/src/ProcesadorSet.cpp
|
UTF-8
| 2,823 | 2.9375 | 3 |
[] |
no_license
|
#include "ProcesadorSet.h"
#include "ProcesadorReviews.h"
#include "UtilesTexto.h"
#include <iomanip>
#include <vector>
#include <iostream>
#include <fstream>
#include <time.h>
#define MAX_REVIEWS_PROC 5000
#define TOTAL_REVIEWS 25000
#define SEC_PER_MIN 60
#define OK 0
using namespace std;
ProcesadorSet::ProcesadorSet(){ this->archivoSet = "testData.tsv"; }
ProcesadorSet::ProcesadorSet(const char* fileName){ this->archivoSet = fileName; }
void ProcesadorSet::mensaje_inicial(){
cout << "\n---------------------------------------------------------------\n";
cout << "Procesando set de test...\n";
cout << "---------------------------------------------------------------\n";
}
void ProcesadorSet::mensaje_final(){ cout << "Set de test procesado: "; }
void ProcesadorSet::error_set(){ cout << "ERROR: No se pudo procesar correctamente el archivo de test.\n\n"; }
void ProcesadorSet::error_stopWords(){ cout << "ERROR: No se pudo procesar correctamente el archivo de stop words.\n\n"; }
void ProcesadorSet::obtenerReview(SetReviews *setR,std::string linea){
string delimitador = "\t";
int resultado;
ProcesadorReviews *pReviews = new ProcesadorReviews();
UtilesTexto *util = new UtilesTexto();
string id_review = linea.substr(0, linea.find(delimitador));
linea.erase(0, id_review.length() + delimitador.length());
vector<string> contenido_review = pReviews->obtenerPalabras(linea,&resultado);
if (resultado==OK) setR->agregarReview(id_review,contenido_review);
else setR->vaciar();
delete pReviews;
delete util;
}
/*
* procesarSet():
* Devuelve un SetReviews con los id's de cada review del set y sus respectivos contenidos (tambien los sentimientos si esta procesando
* el set de entrenamiento).
* En caso de que ocurra algun error al procesar el set (no se pudieron eliminar correctamente las stop words,
* no se pudo procesar el archivo de entrenamiento, etc) devuelve el SetReviews vacio.
* */
void ProcesadorSet::procesarSet(SetReviews *setR){
int cant_reviews_procesados = 0,cantidad_anterior = 0;
string linea;
clock_t t = clock();
ifstream data(this->archivoSet);
mensaje_inicial();
if (data.is_open()){
getline(data,linea); // Ignoro la linea de titulos
while (getline(data,linea)){
if (cant_reviews_procesados == cantidad_anterior + MAX_REVIEWS_PROC && !setR->vacio()) {
cout<< "Reviews procesados: " << cant_reviews_procesados << " de " << TOTAL_REVIEWS << endl << endl;
cantidad_anterior = cant_reviews_procesados;
}
obtenerReview(setR,linea);
cant_reviews_procesados ++;
}
data.close();
if (setR->vacio()) error_stopWords();
else {
mensaje_final();
t = clock() - t;
cout << fixed << setprecision(2) << ((float)t/CLOCKS_PER_SEC)/SEC_PER_MIN << " minutos transcurridos.\n\n";
}
}
else error_set();
}
| true |
b8d89e5389db28c505001d7877a7dce6a0bad7c5
|
C++
|
chrisdembia/pyne
|
/cpp/data.cpp
|
UTF-8
| 14,631 | 2.734375 | 3 |
[
"BSD-2-Clause"
] |
permissive
|
// Implements basic nuclear data functions.
#include "data.h"
/*****************************/
/*** atomic_mass Functions ***/
/*****************************/
std::map<int, double> pyne::atomic_mass_map = std::map<int, double>();
void pyne::_load_atomic_mass_map()
{
// Loads the important parts of atomic_wight table into atomic_mass_map
//Check to see if the file is in HDF5 format.
if (!pyne::file_exists(pyne::NUC_DATA_PATH))
throw pyne::FileNotFound(pyne::NUC_DATA_PATH);
bool isH5 = H5::H5File::isHdf5(pyne::NUC_DATA_PATH);
if (!isH5)
throw h5wrap::FileNotHDF5(pyne::NUC_DATA_PATH);
// Get the HDF5 compound type (table) description
H5::CompType atomic_weight_desc(sizeof(atomic_weight_struct));
atomic_weight_desc.insertMember("nuc_name", HOFFSET(atomic_weight_struct, nuc_name), H5::StrType(0, 6));
atomic_weight_desc.insertMember("nuc_zz", HOFFSET(atomic_weight_struct, nuc_zz), H5::PredType::NATIVE_INT);
atomic_weight_desc.insertMember("mass", HOFFSET(atomic_weight_struct, mass), H5::PredType::NATIVE_DOUBLE);
atomic_weight_desc.insertMember("error", HOFFSET(atomic_weight_struct, error), H5::PredType::NATIVE_DOUBLE);
atomic_weight_desc.insertMember("abund", HOFFSET(atomic_weight_struct, abund), H5::PredType::NATIVE_DOUBLE);
// Open the HDF5 file
H5::H5File nuc_data_h5 (pyne::NUC_DATA_PATH.c_str(), H5F_ACC_RDONLY);
// Open the data set
H5::DataSet atomic_weight_set = nuc_data_h5.openDataSet("/atomic_weight");
H5::DataSpace atomic_weight_space = atomic_weight_set.getSpace();
int atomic_weight_length = atomic_weight_space.getSimpleExtentNpoints();
// Read in the data
atomic_weight_struct * atomic_weight_array = new atomic_weight_struct[atomic_weight_length];
atomic_weight_set.read(atomic_weight_array, atomic_weight_desc);
// close the nuc_data library, before doing anythng stupid
nuc_data_h5.close();
// Ok now that we have the array of stucts, put it in the map
for(int n = 0; n < atomic_weight_length; n++)
atomic_mass_map[atomic_weight_array[n].nuc_zz] = atomic_weight_array[n].mass;
};
double pyne::atomic_mass(int nuc)
{
// Find the nuclide;s weight in AMU
std::map<int, double>::iterator nuc_iter, nuc_end;
nuc_iter = atomic_mass_map.find(nuc);
nuc_end = atomic_mass_map.end();
// First check if we already have the nuc weight in the map
if (nuc_iter != nuc_end)
return (*nuc_iter).second;
// Next, fill up the map with values from the
// nuc_data.h5, if the map is empty.
if (atomic_mass_map.empty())
{
// Don't fail if we can't load the library
try
{
_load_atomic_mass_map();
return atomic_mass(nuc);
}
catch(...){};
};
double aw;
int nuc_zz = nucname::zzaaam(nuc);
// If in an excited state, return the ground
// state weight...not strictly true, but good guess.
if (0 < nuc_zz%10)
{
aw = atomic_mass((nuc_zz/10)*10);
atomic_mass_map[nuc] = aw;
return aw;
};
// Finally, if none of these work,
// take a best guess based on the
// aaa number.
aw = (double) ((nuc_zz/10)%1000);
atomic_mass_map[nuc] = aw;
return aw;
};
double pyne::atomic_mass(char * nuc)
{
int nuc_zz = nucname::zzaaam(nuc);
return atomic_mass(nuc_zz);
};
double pyne::atomic_mass(std::string nuc)
{
int nuc_zz = nucname::zzaaam(nuc);
return atomic_mass(nuc_zz);
};
/***********************************/
/*** scattering length functions ***/
/***********************************/
std::map<int, extra_types::complex_t> pyne::b_coherent_map = std::map<int, extra_types::complex_t>();
std::map<int, extra_types::complex_t> pyne::b_incoherent_map = std::map<int, extra_types::complex_t>();
std::map<int, double> pyne::b_map = std::map<int, double>();
void pyne::_load_scattering_lengths()
{
// Loads the important parts of atomic_wight table into atomic_mass_map
//Check to see if the file is in HDF5 format.
if (!pyne::file_exists(pyne::NUC_DATA_PATH))
throw pyne::FileNotFound(pyne::NUC_DATA_PATH);
bool isH5 = H5::H5File::isHdf5(pyne::NUC_DATA_PATH);
if (!isH5)
throw h5wrap::FileNotHDF5(pyne::NUC_DATA_PATH);
// Get the HDF5 compound type (table) description
H5::CompType scat_len_desc(sizeof(scattering_lengths_struct));
scat_len_desc.insertMember("nuc_name", HOFFSET(scattering_lengths_struct, nuc_name), H5::StrType(0, 6));
scat_len_desc.insertMember("nuc_zz", HOFFSET(scattering_lengths_struct, nuc_zz), H5::PredType::NATIVE_INT);
scat_len_desc.insertMember("b_coherent", HOFFSET(scattering_lengths_struct, b_coherent), h5wrap::PYTABLES_COMPLEX128);
scat_len_desc.insertMember("b_incoherent", HOFFSET(scattering_lengths_struct, b_incoherent), h5wrap::PYTABLES_COMPLEX128);
scat_len_desc.insertMember("xs_coherent", HOFFSET(scattering_lengths_struct, xs_coherent), H5::PredType::NATIVE_DOUBLE);
scat_len_desc.insertMember("xs_incoherent", HOFFSET(scattering_lengths_struct, xs_incoherent), H5::PredType::NATIVE_DOUBLE);
scat_len_desc.insertMember("xs", HOFFSET(scattering_lengths_struct, xs), H5::PredType::NATIVE_DOUBLE);
// Open the HDF5 file
H5::H5File nuc_data_h5 (pyne::NUC_DATA_PATH.c_str(), H5F_ACC_RDONLY);
// Open the data set
H5::DataSet scat_len_set = nuc_data_h5.openDataSet("/neutron/scattering_lengths");
H5::DataSpace scat_len_space = scat_len_set.getSpace();
int scat_len_length = scat_len_space.getSimpleExtentNpoints();
// Read in the data
scattering_lengths_struct * scat_len_array = new scattering_lengths_struct[scat_len_length];
scat_len_set.read(scat_len_array, scat_len_desc);
// close the nuc_data library, before doing anythng stupid
nuc_data_h5.close();
// Ok now that we have the array of stucts, put it in the maps
for(int n = 0; n < scat_len_length; n++)
{
b_coherent_map[scat_len_array[n].nuc_zz] = scat_len_array[n].b_coherent;
b_incoherent_map[scat_len_array[n].nuc_zz] = scat_len_array[n].b_incoherent;
};
};
//
// Coherent functions
//
extra_types::complex_t pyne::b_coherent(int nuc)
{
// Find the nuclide's bound scattering length in cm
std::map<int, extra_types::complex_t>::iterator nuc_iter, nuc_end;
nuc_iter = b_coherent_map.find(nuc);
nuc_end = b_coherent_map.end();
// First check if we already have the nuc in the map
if (nuc_iter != nuc_end)
return (*nuc_iter).second;
// Next, fill up the map with values from the
// nuc_data.h5, if the map is empty.
if (b_coherent_map.empty())
{
_load_scattering_lengths();
return b_coherent(nuc);
};
extra_types::complex_t bc;
int nuc_zz = nucname::zzaaam(nuc);
int znum = nuc_zz/10000;
int anum = (nuc_zz/10)%1000;
// Try to find a nuclide with matching A-number
nuc_iter = b_coherent_map.begin();
while (nuc_iter != nuc_end)
{
if (anum == (((*nuc_iter).first)/10)%1000)
{
bc = (*nuc_iter).second;
b_coherent_map[nuc] = bc;
return bc;
};
nuc_iter++;
};
// Try to find a nuclide with matching Z-number
nuc_iter = b_coherent_map.begin();
while (nuc_iter != nuc_end)
{
if (znum == ((*nuc_iter).first)/10000)
{
bc = (*nuc_iter).second;
b_coherent_map[nuc] = bc;
return bc;
};
nuc_iter++;
};
// Finally, if none of these work,
// just return zero...
bc.re = 0.0;
bc.im = 0.0;
b_coherent_map[nuc] = bc;
return bc;
};
extra_types::complex_t pyne::b_coherent(char * nuc)
{
int nuc_zz = nucname::zzaaam(nuc);
return b_coherent(nuc_zz);
};
extra_types::complex_t pyne::b_coherent(std::string nuc)
{
int nuc_zz = nucname::zzaaam(nuc);
return b_coherent(nuc_zz);
};
//
// Incoherent functions
//
extra_types::complex_t pyne::b_incoherent(int nuc)
{
// Find the nuclide's bound inchoherent scattering length in cm
std::map<int, extra_types::complex_t>::iterator nuc_iter, nuc_end;
nuc_iter = b_incoherent_map.find(nuc);
nuc_end = b_incoherent_map.end();
// First check if we already have the nuc in the map
if (nuc_iter != nuc_end)
return (*nuc_iter).second;
// Next, fill up the map with values from the
// nuc_data.h5, if the map is empty.
if (b_incoherent_map.empty())
{
_load_scattering_lengths();
return b_incoherent(nuc);
};
extra_types::complex_t bi;
int nuc_zz = nucname::zzaaam(nuc);
int znum = nuc_zz/10000;
int anum = (nuc_zz/10)%1000;
// Try to find a nuclide with matching A-number
nuc_iter = b_incoherent_map.begin();
while (nuc_iter != nuc_end)
{
if (anum == (((*nuc_iter).first)/10)%1000)
{
bi = (*nuc_iter).second;
b_incoherent_map[nuc] = bi;
return bi;
};
nuc_iter++;
};
// Try to find a nuclide with matching Z-number
nuc_iter = b_incoherent_map.begin();
while (nuc_iter != nuc_end)
{
if (znum == ((*nuc_iter).first)/10000)
{
bi = (*nuc_iter).second;
b_incoherent_map[nuc] = bi;
return bi;
};
nuc_iter++;
};
// Finally, if none of these work,
// just return zero...
bi.re = 0.0;
bi.im = 0.0;
b_incoherent_map[nuc] = bi;
return bi;
};
extra_types::complex_t pyne::b_incoherent(char * nuc)
{
int nuc_zz = nucname::zzaaam(nuc);
return b_incoherent(nuc_zz);
};
extra_types::complex_t pyne::b_incoherent(std::string nuc)
{
int nuc_zz = nucname::zzaaam(nuc);
return b_incoherent(nuc_zz);
};
//
// b functions
//
double pyne::b(int nuc)
{
// Find the nuclide's bound scattering length in cm
std::map<int, double>::iterator nuc_iter, nuc_end;
nuc_iter = b_map.find(nuc);
nuc_end = b_map.end();
// First check if we already have the nuc in the map
if (nuc_iter != nuc_end)
return (*nuc_iter).second;
// Next, calculate the value from coherent and incoherent lengths
extra_types::complex_t bc = b_coherent(nuc);
extra_types::complex_t bi = b_incoherent(nuc);
double b_val = sqrt(bc.re*bc.re + bc.im*bc.im + bi.re*bi.re + bi.im*bi.im);
return b_val;
};
double pyne::b(char * nuc)
{
int nuc_zz = nucname::zzaaam(nuc);
return b(nuc_zz);
};
double pyne::b(std::string nuc)
{
int nuc_zz = nucname::zzaaam(nuc);
return b(nuc_zz);
};
/******************************/
/*** atomic decay functions ***/
/******************************/
std::map<int, double> pyne::half_life_map = std::map<int, double>();
std::map<int, double> pyne::decay_const_map = std::map<int, double>();
void pyne::_load_atomic_decay()
{
// Loads the important parts of atomic_decay table into memory
//Check to see if the file is in HDF5 format.
if (!pyne::file_exists(pyne::NUC_DATA_PATH))
throw pyne::FileNotFound(pyne::NUC_DATA_PATH);
bool isH5 = H5::H5File::isHdf5(pyne::NUC_DATA_PATH);
if (!isH5)
throw h5wrap::FileNotHDF5(pyne::NUC_DATA_PATH);
// Get the HDF5 compound type (table) description
H5::CompType atom_dec_desc(sizeof(atomic_decay_struct));
atom_dec_desc.insertMember("from_nuc_name", HOFFSET(atomic_decay_struct, from_nuc_name), H5::StrType(0, 6));
atom_dec_desc.insertMember("from_nuc_zz", HOFFSET(atomic_decay_struct, from_nuc_zz), H5::PredType::NATIVE_INT);
atom_dec_desc.insertMember("level", HOFFSET(atomic_decay_struct, level), H5::PredType::NATIVE_DOUBLE);
atom_dec_desc.insertMember("to_nuc_name", HOFFSET(atomic_decay_struct, to_nuc_name), H5::StrType(0, 6));
atom_dec_desc.insertMember("to_nuc_zz", HOFFSET(atomic_decay_struct, to_nuc_zz), H5::PredType::NATIVE_INT);
atom_dec_desc.insertMember("half_life", HOFFSET(atomic_decay_struct, half_life), H5::PredType::NATIVE_DOUBLE);
atom_dec_desc.insertMember("decay_const", HOFFSET(atomic_decay_struct, decay_const), H5::PredType::NATIVE_DOUBLE);
atom_dec_desc.insertMember("branch_ratio", HOFFSET(atomic_decay_struct, branch_ratio), H5::PredType::NATIVE_DOUBLE);
// Open the HDF5 file
H5::H5File nuc_data_h5 (pyne::NUC_DATA_PATH.c_str(), H5F_ACC_RDONLY);
// Open the data set
H5::DataSet atom_dec_set = nuc_data_h5.openDataSet("/atomic_decay");
H5::DataSpace atom_dec_space = atom_dec_set.getSpace();
int atom_dec_length = atom_dec_space.getSimpleExtentNpoints();
// Read in the data
atomic_decay_struct * atom_dec_array = new atomic_decay_struct[atom_dec_length];
atom_dec_set.read(atom_dec_array, atom_dec_desc);
// close the nuc_data library, before doing anythng stupid
nuc_data_h5.close();
// Ok now that we have the array of stucts, put it in the maps
// giving precednece to ground state values or those seen first.
int from_nuc;
double level;
for(int n = 0; n < atom_dec_length; n++)
{
from_nuc = atom_dec_array[n].from_nuc_zz;
level = atom_dec_array[n].level;
if (0 == half_life_map.count(from_nuc) || 0.0 == level)
half_life_map[from_nuc] = atom_dec_array[n].half_life;
if (0 == decay_const_map.count(from_nuc) || 0.0 == level)
decay_const_map[from_nuc] = atom_dec_array[n].decay_const;
};
};
//
// Half-life data
//
double pyne::half_life(int nuc)
{
// Find the nuclide's half life in s
std::map<int, double>::iterator nuc_iter, nuc_end;
nuc_iter = half_life_map.find(nuc);
nuc_end = half_life_map.end();
// First check if we already have the nuc in the map
if (nuc_iter != nuc_end)
return (*nuc_iter).second;
// Next, fill up the map with values from the
// nuc_data.h5, if the map is empty.
if (half_life_map.empty())
{
_load_atomic_decay();
return half_life(nuc);
};
// Finally, if none of these work,
// assume the value is stable
double hl = 1.0 / 0.0;
half_life_map[nuc] = hl;
return hl;
};
double pyne::half_life(char * nuc)
{
int nuc_zz = nucname::zzaaam(nuc);
return half_life(nuc_zz);
};
double pyne::half_life(std::string nuc)
{
int nuc_zz = nucname::zzaaam(nuc);
return half_life(nuc_zz);
};
//
// Decay constant data
//
double pyne::decay_const(int nuc)
{
// Find the nuclide's half life in s
std::map<int, double>::iterator nuc_iter, nuc_end;
nuc_iter = decay_const_map.find(nuc);
nuc_end = decay_const_map.end();
// First check if we already have the nuc in the map
if (nuc_iter != nuc_end)
return (*nuc_iter).second;
// Next, fill up the map with values from the
// nuc_data.h5, if the map is empty.
if (decay_const_map.empty())
{
_load_atomic_decay();
return decay_const(nuc);
};
// Finally, if none of these work,
// assume the value is stable
double dc = 0.0;
decay_const_map[nuc] = dc;
return dc;
};
double pyne::decay_const(char * nuc)
{
int nuc_zz = nucname::zzaaam(nuc);
return decay_const(nuc_zz);
};
double pyne::decay_const(std::string nuc)
{
int nuc_zz = nucname::zzaaam(nuc);
return decay_const(nuc_zz);
};
| true |
495b08f89a40dd4c13d80944ecc49382bdc66898
|
C++
|
FullscreenSauna/School-12th-grade
|
/First Semester/exam_task_AlexanderDzhekov/exam_task_AlexanderDzhekov/exam_task_AlexanderDzhekov.cpp
|
UTF-8
| 2,154 | 3.65625 | 4 |
[
"MIT"
] |
permissive
|
#include <iostream>
using namespace std;
//triangle area by points coordinates
double area(int x1, int y1, int x2, int y2, int x3, int y3)
{
return abs((x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0);
}
bool isInTriangle(int x1, int y1, int x2, int y2, int x3, int y3, int x, int y)
{
float A = area(x1, y1, x2, y2, x3, y3);
float A1 = area(x, y, x2, y2, x3, y3);
float A2 = area(x1, y1, x, y, x3, y3);
float A3 = area(x1, y1, x2, y2, x, y);
return (A == A1 + A2 + A3);
}
int main()
{
int x, y;
cout << "Please enter the coordinates of your point:" << endl;
cout << "X: ";
cin >> x;
cout << "Y: ";
cin >> y;
int outerSquareSide = 20;
int innerSquareSide = 8;
int innerSquareDiagonal = (pow(innerSquareSide, 2) * 2);
bool isInsideOuterSquare = x < outerSquareSide&& y < outerSquareSide;
bool isInsideInnerSquare = x < innerSquareSide&& y < innerSquareSide;
int outerCircleRadius = outerSquareSide / 2;
int innerCircleRadius = innerSquareDiagonal / 2;
// pow(abs(xCircleCenter - px), 2.0) + pow(abs(yCircleCenter - py), 2.0) <= outerCircleRadius
bool isInsideOuterCircle = pow(outerCircleRadius, 2) >= (pow(x, 2) + pow(y, 2));
bool isInsideInnerCircle = pow(innerCircleRadius, 2) >= (pow(x, 2) + pow(y, 2));
// for the triangle
int ax = outerSquareSide / 2;
int bx = 0;
int cx = 0;
int ay = 0;
int by = outerSquareSide / 2;
int cy = 0;
bool isInsideTriangle = isInTriangle(ax, ay, bx, by, cx, cy, x, y);
if (isInsideInnerSquare)
{
cout << "The point is in the Inner square" << endl;
}
else
{
cout << "The point is outside of the Inner square" << endl;
}
if (isInsideOuterSquare)
{
cout << "The point is in the Outer square" << endl;
}
else
{
cout << "The point is outside of the Outer square" << endl;
}
if (!isInsideInnerCircle && isInsideOuterCircle)
{
cout << "The point is in the ring formed by the 2 circles" << endl;
}
else
{
cout << "The point is outside of the ring formed by the 2 circles" << endl;
}
if (isInsideTriangle)
{
cout << "The point is in the triangle" << endl;
}
else
{
cout << "The point is outside of the triangle" << endl;
}
}
| true |
313b1062d2212422fc7435460f57e266010d36e3
|
C++
|
denis-shcherbinin/snake-game
|
/src/input.cpp
|
UTF-8
| 1,432 | 2.921875 | 3 |
[] |
no_license
|
#include "engine.hpp"
void Engine::input()
{
sf::Event event = {};
while(window_.pollEvent(event))
{
switch (event.type)
{
case(sf::Event::Closed):
{
window_.close();
break;
}
case(sf::Event::KeyPressed):
{
// Quit
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Escape))
{
window_.close();
}
// Pause
if (sf::Keyboard::isKeyPressed(sf::Keyboard::P))
{
pauseGame();
}
// GameOver
if (currentGameState_ == GameState::GAMEOVER)
{
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Enter))
{
startGame();
}
}
break;
}
}
}
// Directions
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
{
addDirection(Direction::UP);
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
{
addDirection(Direction::RIGHT);
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
{
addDirection(Direction::DOWN);
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
{
addDirection(Direction::LEFT);
}
}
void Engine::addDirection(int newDirection)
{
if (directionQueue_.empty())
{
directionQueue_.emplace_back(newDirection);
}
else
{
if (directionQueue_.back() != newDirection)
{
directionQueue_.emplace_back(newDirection);
}
}
}
| true |
178e8fd259c012b8a86f568ad3f810415780c783
|
C++
|
danielondon/algorithms
|
/cpp/include/common.h
|
UTF-8
| 6,633 | 3.25 | 3 |
[] |
no_license
|
#include <sstream>
#include <iostream>
#include <vector>
#include <unordered_set>
#include <iterator> // for ostream_iterator
#include <algorithm>
#include <memory>
#include <map>
#include <queue>
#include <climits>
#include <cmath>
using namespace std;
template<typename EnumType>
using UnderlyingType = typename std::underlying_type<EnumType>::type;
template<typename EnumType>
constexpr auto convertEnumToUnderlyingType(EnumType enumValue) -> UnderlyingType<EnumType>
{
return static_cast<UnderlyingType<EnumType>>(enumValue);
}
template <typename TCollection>
void printCollection(TCollection const& collection)
{
for (auto const& value : collection)
cout<< value <<" ";
cout<<endl;
}
template <class T>
void printVector(const vector<T> & numbers)
{
std::for_each(numbers.cbegin(), numbers.cend(), [] (const T c) {std::cout << c << " ";} );
cout<<endl;
}
template <class T>
void printAsBinaryTree(const vector<T> & numbers)
{
auto currentLevel = 1;
for ( auto i = 0; i < numbers.size(); ++i)
{
cout<<numbers[i]<< " ";
if ((i+1) >= pow(2, currentLevel) - 1)
{
cout<<endl;
++currentLevel;
}
}
}
template <class T>
void printMatrix(const vector<vector<T>> & matrix)
{
std::for_each(matrix.cbegin(), matrix.cend(), [] (const auto& v) { printVector(v); } );
cout<<endl;
}
enum class Color
{
Red,
Blue,
Green,
Invalid
};
std::ostream& operator<< (std::ostream& stream, const Color& color)
{
stream<<convertEnumToUnderlyingType(color);
}
struct Node
{
//int value;
void addChild(shared_ptr<Node> child)
{
children.push_back(child);
}
~Node()
{
cout<<"Destroying Node"<<endl;
}
private:
vector<shared_ptr<Node>> children;
};
struct Vertex
{
Vertex(int _id, int _data) : id(_id), data(_data), visited(false)
{
cout<<"Creating Vertex "<<id<<endl;
}
~Vertex()
{
cout<<"Destroying Vertex "<<id<<endl;
//adjacents.clear();
}
void addEdge(shared_ptr<Vertex> to, int weigth)
{
//edges.push_back(Edge(to, weigth));
}
void addAdjacent(weak_ptr<Vertex> to)
{
adjacents.push_back(to);
auto ptr = to.lock();
cout<<"Edge from Vertex "<<id<<" to "<<ptr->id<<" was added."<<endl;
}
int id;
bool visited;
int data;
//vector<Edge> edges;
vector<weak_ptr<Vertex>> adjacents;
};
struct Edge
{
Edge(shared_ptr<Vertex> _from, shared_ptr<Vertex> _to, int _weight) : from(_from), to(_to), weight(_weight) {}
shared_ptr<Vertex> from;
shared_ptr<Vertex> to;
int weight;
~Edge()
{
cout<<"Destroying Edge"<<endl;
}
};
struct Graph
{
~Graph()
{
cout<<"Destroying Graph"<<endl;
}
shared_ptr<Vertex> getVertex(int id)
{
auto it = find_if(nodes.begin(), nodes.end(), [&] (const shared_ptr<Vertex>& v) { return v->id == id; } );
if (it != nodes.end())
{
cout<<"Node found "<< (*it)->id <<endl;
return *it;
}
return nullptr;
}
shared_ptr<Vertex> addVertex(int id, int data)
{
auto vertex = make_shared<Vertex>(id, data);
nodes.push_back(vertex);
cout<<"Vertex was added"<<endl;
return vertex;
}
bool containsVertex(shared_ptr<Vertex> vertex)
{
auto it = find(nodes.begin(), nodes.end(), vertex);
return it != nodes.end();
}
void removeVertex(shared_ptr<Vertex> vertex)
{
cout<<"Removing vertex"<<endl;
auto it = find(nodes.begin(), nodes.end(), vertex);
if (it != nodes.end())
{
nodes.erase(it, it + 1);
cout<<"Vertex removed"<<endl;
}
}
void addEdge(shared_ptr<Vertex> from, shared_ptr<Vertex> to, int weigth)
{
cout<<"Adding edge"<<endl;
auto itFrom = find(nodes.begin(), nodes.end(), from);
if (itFrom != nodes.end())
{
auto itTo = find(nodes.begin(), nodes.end(), to);
if (itTo != nodes.end())
{
(*itFrom)->addAdjacent(*itTo);
}
else
cout<<"To Vertex not found"<<endl;
}
else
{
cout<<"From Vertex not found"<<endl;
}
}
const vector<shared_ptr<Vertex>>& getNodes() const
{
return nodes;
}
private:
vector<shared_ptr<Vertex>> nodes;
};
// ----------------- Matrix and Coordinates ----------------
struct Position
{
int i;
int j;
string toString() const { return std::to_string(i) + "-" + std::to_string(j); }
bool operator==(const Position& other) const
{
return i == other.i && j == other.j;
}
Position goUp() const
{
return { i - 1, j };
}
Position goDown() const
{
return { i + 1, j };
}
Position goLeft() const
{
return { i, j - 1};
}
Position goRight() const
{
return { i, j + 1 };
}
};
namespace std {
template <>
struct hash<Position>
{
size_t operator()(const Position & x) const
{
std::hash<std::string> h;
return h(x.toString());
}
};
}
template <class T>
using Matrix = vector<vector<T>>;
template <class T>
bool inBounds (Position coordinates, const Matrix<T> matrix)
{
if (matrix.empty())
return false;
return inBounds(coordinates, matrix.size(), matrix.front().size());
}
bool inBounds (Position coordinates, int rows, int cols)
{
if (coordinates.i >= 0 && coordinates.i < rows
&& coordinates.j >= 0 && coordinates.j < cols)
return true;
return false;
}
template <class T>
struct NodeTree
{
T value;
shared_ptr<NodeTree> left;
shared_ptr<NodeTree> right;
NodeTree(int _value) : value(_value) {}
};
template <class T>
void breadthSearch(shared_ptr<NodeTree<T>> root)
{
queue<shared_ptr<NodeTree<T>>> queue;
queue.push(root);
int currentCount = 0;
int currentLevel = 1;
while(!queue.empty())
{
auto currentSize = queue.size();
cout<<queue.front()->value<<" ";
++currentCount;
if (currentCount >= pow(2, currentLevel) - 1)
{
cout<<endl;
++currentLevel;
}
if (queue.front()->left)
queue.push(queue.front()->left);
if (queue.front()->right)
queue.push(queue.front()->right);
queue.pop();
}
}
| true |
dbfa7143c6d2e9e16b2fc41fa9f6e1e7af8a86d6
|
C++
|
LYHyoung/BaekJoon
|
/BOJ solve/10000~19999/10000~10999/10844/main.cpp
|
WINDOWS-1252
| 670 | 2.734375 | 3 |
[] |
no_license
|
#include <iostream>
#include <cstring>
#define MOD 1000000000
using namespace std;
int n, ans;
int dp[101][10];
int func(int l, int x) {
if (l == 1)
return x == 0 ? 0 : 1;
int& ref = dp[l][x]; // ۷
if (ref != -1)
return ref;
if (x == 0)
return ref = func(l - 1, 1) % MOD;
if (x == 9)
return ref = func(l - 1, 8) % MOD;
else
return ref = (func(l - 1, x - 1) + func(l - 1, x + 1)) % MOD;
}
int main() {
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
cin >> n;
memset(dp, -1, sizeof(dp));
for (int i = 0; i <= 9; i++)
ans = (ans + func(n, i)) % MOD;
cout << ans << '\n';
return 0;
}
| true |
34b148e80f803c6446abfc46044e7766fda2ac78
|
C++
|
xylifyx2/humitemp
|
/src/main.cpp
|
UTF-8
| 2,585 | 2.5625 | 3 |
[] |
no_license
|
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include "config.h"
#include "DHT.h"
extern void setup_dht();
extern void setup_wifi();
extern void setup_mqtt();
extern void read_dht_values();
extern void publish_data();
extern void reconnect();
WiFiClient espClient;
PubSubClient client(espClient);
DHT dht;
void setup()
{
Serial.begin(9600);
pinMode(2, INPUT);
setup_dht();
// setup_wifi();
// setup_mqtt();
}
void loop()
{
delay(5000);
read_dht_values();
publish_data();
client.loop();
}
// Initialize DHT sensor.
// Note that older versions of this library took an optional third parameter to
// tweak the timings for faster processors. This parameter is no longer needed
// as the current DHT reading algorithm adjusts itself to work on faster procs.
float humidity = NAN;
float temperature = NAN;
const char *status = "Initializing";
void read_dht_values()
{
humidity = dht.getHumidity();
temperature = dht.getTemperature();
status = dht.getStatusString();
}
char buffer[50];
void publish_data()
{
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.print(", Humidity: ");
Serial.print(humidity);
Serial.print(", Status: ");
Serial.print(status);
Serial.println();
reconnect();
sprintf(buffer, "{\"value\":%f}", humidity);
Serial.println(client.publish(HUMI_TOPIC, buffer));
sprintf(buffer, "{\"value\":%f}", temperature);
Serial.println(client.publish(TEMP_TOPIC, buffer));
}
void setup_dht()
{
dht.setup(2, DHT::DHT22);
}
void setup_wifi()
{
Serial.println();
Serial.print("Connecting to ");
Serial.println(WIFI_SSID);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
// Wait for connection
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void reconnect()
{
while (!client.connected())
{
Serial.print("Connecting to MQTT server ");
Serial.println(MQTT_HOST);
client.setServer(MQTT_HOST, 1883);
if (client.connect(MQTT_CLIENT_ID, MQTT_USERNAME, MQTT_PASSWORD))
{
Serial.println("Connected");
}
else
{
Serial.print("Failed with state ");
Serial.print(client.state());
delay(2000);
}
}
}
void setup_mqtt()
{
reconnect();
}
| true |
84b4b5dbfe09aa2396e14972da65bbbcd4f55052
|
C++
|
rdg/cao001
|
/cao001/src/system/Strand.h
|
UTF-8
| 456 | 2.609375 | 3 |
[] |
no_license
|
#pragma once
#include "ofMain.h"
// Line
class Line {
public:
ofPoint start;
ofPoint end;
};
// Group of Lines
class Strand {
public:
Strand();
void update(int maxLines);
void render();
void addLine();
void extendLine();
void reset();
void setInfluence(float value);
const float & getInfluence();
const ofPoint & getPoint(int offset);
vector <Line> lines;
vector <ofPoint> points;
private:
int stepSize = 15;
float influence = 40.0f;
};
| true |
291266707efaf59c7eea5d53ef40cb0525f3d56e
|
C++
|
SashaKryzh/CPP_Pool
|
/d05/ex05/CentralBureaucracy.hpp
|
UTF-8
| 673 | 2.546875 | 3 |
[] |
no_license
|
#if !defined(CENTRAL_BUREAUCRACY_HPP)
#define CENTRAL_BUREAUCRACY_HPP
#include <string>
#include "OfficeBlock.hpp"
class CentralBureaucracy
{
private:
struct s_queueTargets
{
std::string name;
s_queueTargets *next;
};
OfficeBlock blocks_[20];
s_queueTargets *queueTargets_;
std::string *dequeueTarget();
public:
CentralBureaucracy();
~CentralBureaucracy();
CentralBureaucracy(const CentralBureaucracy &);
CentralBureaucracy &operator=(const CentralBureaucracy &);
void feedBureaucrat(Bureaucrat &);
void queueUp(std::string target);
void doBureaucracy();
};
#endif // CENTRAL_BUREAUCRACY_HPP
| true |
4c54ff142e60b6ebc13f05d34c6c18e8851b9f7d
|
C++
|
sust18023/ACM
|
/KuangBin/专题四 最短路练习(AK)/Subway.cpp
|
UTF-8
| 1,664 | 2.96875 | 3 |
[] |
no_license
|
/*
Subway
POJ - 2502
https://cn.vjudge.net/problem/POJ-2502#author=0
题面: 从家到学校,可以选择坐(40km/s)地铁或(10km/s)步行,求最短时间
输入 第一行 起点坐标,终点坐标
下面是每个地铁经过的站 知道-1 -1结束
样例输入:
0 0 10000 1000
0 200 5000 200 7000 200 -1 -1
2000 600 5000 600 10000 600 -1 -1
样例输出:
21
解法:
建图,跑一遍Floyed-Warshall
*/
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <iostream>
#include <queue>
#include <cmath>
using namespace std;
#define maxn 1000
#define INF 0x3f3f3f
struct node{
double x,y;
int kid;
}poi[maxn];
double mp[maxn][maxn];
int cnt=0;
void build(double x,double y,int kid){
poi[cnt].x=x;
poi[cnt].y=y;
poi[cnt].kid=kid;
cnt++;
}
int main(){
double x,y;
int kid=0;
scanf("%lf %lf", &x, &y);
build(x,y,kid++);
scanf("%lf %lf", &x, &y);
build(x,y,kid++);
while(~scanf("%lf %lf", &x, &y)) {
if(x<0&&y<0){
kid++;
continue;
}
build(x,y,kid);
}
for(int i=0;i<cnt;i++){
for(int j=0;j<cnt;j++){
mp[i][j]=sqrt((poi[i].x-poi[j].x)*(poi[i].x-poi[j].x)+(poi[i].y-poi[j].y)*(poi[i].y-poi[j].y))/(10000.0/60);
}
}
for(int i=0;i<cnt-1;i++){
if(poi[i].kid==poi[i+1].kid){
mp[i][i+1]=mp[i+1][i]=sqrt((poi[i].x-poi[i+1].x)*(poi[i].x-poi[i+1].x)+(poi[i].y-poi[i+1].y)*(poi[i].y-poi[i+1].y))/(40000.0/60);
}
}
for(int k=0;k<cnt;k++){
for(int i=0;i<cnt;i++){
for(int j=0;j<cnt;j++){
mp[i][j]=min(mp[i][k]+mp[k][j],mp[i][j]);
}
}
}
printf("%d\n", (int)(mp[0][1]+0.5));
return 0;
}
| true |
ab119b1e787fd3475a2a1416f814409b764f894c
|
C++
|
satyaaditya/My_C
|
/placing 2n elements in array_backtracking.cpp
|
UTF-8
| 841 | 3.640625 | 4 |
[] |
no_license
|
//this program is placing arrray of 2*n elements in array with i th element in i distance to other ith element
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
bool make_array(int *, int , int );
int main(){
int n;
printf("enter size of array ::: ");
scanf("%d", &n);
int *arr = (int*)calloc(2 * n, sizeof(int));
if(make_array(arr,n, n))
{
for (int i = 0; i < 2*n; i++)
printf("%d ", arr[i]);
}
else
printf("not possible");
getch();
}
bool make_array(int *arr, int cur_element, int n){
if (cur_element == 0)
return true;
for (int i = 0; i < 2 * n - cur_element - 1; i++){
if (arr[i] == 0 && arr[i + cur_element + 1] == 0){
arr[i] = arr[i + cur_element + 1] = cur_element;
if (make_array(arr, cur_element - 1, n))
return true;
arr[i] = arr[i+cur_element + 1] = 0;
}
}
return false;
}
| true |
c5e9a0d2c7b0368e0c3e80b5e62fe6d46e2791ca
|
C++
|
huleiak47/leetcode
|
/1.两数之和.cpp
|
UTF-8
| 1,407 | 3.5625 | 4 |
[] |
no_license
|
/*
* @lc app=leetcode.cn id=1 lang=cpp
*
* [1] 两数之和
*
* https://leetcode-cn.com/problems/two-sum/description/
*
* algorithms
* Easy (46.48%)
* Likes: 5997
* Dislikes: 0
* Total Accepted: 506.3K
* Total Submissions: 1.1M
* Testcase Example: '[2,7,11,15]\n9'
*
* 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
*
* 你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
*
* 示例:
*
* 给定 nums = [2, 7, 11, 15], target = 9
*
* 因为 nums[0] + nums[1] = 2 + 7 = 9
* 所以返回 [0, 1]
*
*
*/
#include <vector>
#include <algorithm>
#include <unordered_map>
using namespace std;
bool Compare(const int*& a, const int*& b)
{
return *a < *b;
}
// @lc code=start
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target)
{
vector<int> ret;
unordered_map<int, int> map;
for (int i = 0; i < nums.size(); ++i) {
int other = target - nums[i];
auto found = map.find(other);
if (found != map.end()) {
ret.push_back(found->second);
ret.push_back(i);
break;
}
map[nums[i]] = i;
}
return ret;
}
};
// @lc code=end
| true |
8161c649a309adf0ff402600b6191f50fee4e817
|
C++
|
anupamkaul/robot_ball_chaser
|
/samples/simple_arm/workspace/catkin_ws/src/simple_arm/src/look_away.cpp
|
UTF-8
| 4,063 | 3.265625 | 3 |
[
"MIT"
] |
permissive
|
// A good example of clients of nodes that invoke services , and also how a node can subscribe to multiple topics
//To see a ROS subscriber and client in action, you'll write a node called look_away. The look_away node will subscribe to the /rgb_camera/image_raw topic, which has image data from the camera mounted on the end of the robotic arm. Whenever the camera is pointed towards an uninteresting image - in this case, an image with uniform color - the callback function will request a safe_move service to safely move the arm to something more interesting.
#include "ros/ros.h"
#include "simple_arm/GoToPosition.h"
#include <sensor_msgs/JointState.h> // to read the arms joints' positions
#include <sensor_msgs/Image.h>
// Define global vector of joints last position, moving state of the arm, and the client that can request services
std::vector<double> joints_last_position{ 0, 0 };
bool moving_state = false;
ros::ServiceClient client;
// This function calls the safe_move service to safely move the arm to the center position
void move_arm_center()
{
ROS_INFO_STREAM("Moving the arm to the center");
// Request centered joint angles [1.57, 1.57]
simple_arm::GoToPosition srv;
srv.request.joint_1 = 1.57;
srv.request.joint_2 = 1.57;
// Call the safe_move service and pass the requested joint angles
if (!client.call(srv))
ROS_ERROR("Failed to call service safe_move");
}
// This callback function continuously executes and reads the arm joint angles position
void joint_states_callback(const sensor_msgs::JointState js)
{
// Get joints current position
std::vector<double> joints_current_position = js.position;
// Define a tolerance threshold to compare double values
double tolerance = 0.0005;
// Check if the arm is moving by comparing its current joints position to its latest
if (fabs(joints_current_position[0] - joints_last_position[0]) < tolerance && fabs(joints_current_position[1] - joints_last_position[1]) < tolerance)
moving_state = false;
else {
moving_state = true;
joints_last_position = joints_current_position;
}
}
// This callback function continuously executes and reads the image data
void look_away_callback(const sensor_msgs::Image img)
{
bool uniform_image = true;
// Loop through each pixel in the image and check if its equal to the first one
for (int i = 0; i < img.height * img.step; i++) {
if (img.data[i] - img.data[0] != 0) {
uniform_image = false;
break;
}
}
// If the image is uniform and the arm is not moving, move the arm to the center
if (uniform_image == true && moving_state == false)
move_arm_center();
}
int main(int argc, char** argv)
{
// Initialize the look_away node and create a handle to it
ros::init(argc, argv, "look_away");
ros::NodeHandle n; // the node for lookaway
// Define a client service capable of requesting services from safe_move
client = n.serviceClient<simple_arm::GoToPosition>("/arm_mover/safe_move");
// Subscribe to /simple_arm/joint_states topic to read the arm joints position inside the joint_states_callback function
ros::Subscriber sub1 = n.subscribe("/simple_arm/joint_states", 10, joint_states_callback);
// note that when sub1 recieves a message on /simple/arm/joint_states topic, it calls joint_states_callback.
// This callback checks what is our tolerance, checks if the arms have stopped moving, and updates our state of the joints' last position.
// Subscribe to rgb_camera/image_raw topic to read the image data inside the look_away_callback function
ros::Subscriber sub2 = n.subscribe("rgb_camera/image_raw", 10, look_away_callback);
// note that sub2, whenever it gets a camera feed, it checks if we are looking a boring image, checks if we are moving (using sub1's data)
// and accordingly shifts the robot arms to where camera can get us meaningful feed ..
// Handle ROS communication events
ros::spin();
return 0;
}
| true |
8621610579eb052ea462a5b92f5a1d4206ee5164
|
C++
|
TotteKarlsson/atapi
|
/source/arraybot/process/atTrigger.h
|
UTF-8
| 3,989 | 2.78125 | 3 |
[
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
#ifndef atTriggerH
#define atTriggerH
#include "atABExporter.h"
#include "atATObject.h"
#include <string>
#include "dslTimer.h"
#include <vector>
#include "dslXMLUtils.h"
#include "atUtils.h"
//---------------------------------------------------------------------------
using std::string;
using std::vector;
namespace at
{
typedef double (__closure *triggerTestFunctionFPtr)();
class TriggerFunction;
class AT_AB Trigger : public ATObject
{
public:
Trigger(ATObject* s, LogicOperator lt = loLargerThan);
virtual ~Trigger(){}
void assignSubject(ATObject* s){mSubject = s;}
ATObject* getSubject(){return mSubject;}
string getSubjectName();
bool setTestOperator(LogicOperator lo){mTriggerConditionOperator = lo; return true;}
LogicOperator getTestOperator(){return mTriggerConditionOperator;}
//!Enable 'loads' the trigger.
virtual bool enable();
//!Disable disables the trigger.
virtual bool disable();
//!The test function is using the TriggerCondition
//operator in order to check if the trigger should trigger
virtual void setTestFunction(triggerTestFunctionFPtr f);
//!Assign function that will be executed when
//!the trigger triggers
virtual void assignTriggerFunction(TriggerFunction* f);
//!Check if the trigger been triggered
bool isTriggered(){return mIsTriggered;}
//!Any subclass need to implement
//an execute method
virtual void execute() = 0;
virtual void reset();
TriggerFunction* getTriggerFunction(){return mTriggerFunction;}
//!Ability to read/write trigger objects occurs using xml
virtual dsl::XMLElement* addToXMLDocumentAsChild(dsl::XMLDocument& doc, dsl::XMLNode* docRoot) = 0;
protected:
//!The subject name is the name of the device being monitored
string mSubjectName;
//!The subject being 'observed' is typically APTDevices, motors etc
ATObject* mSubject;
//!The mIsTriggered is set to true in case the trigger been fired
bool mIsTriggered;
//!The Trigger timer checks for a satisified trigger condition.
//!Todo: Add timeout logic..
dsl::Timer mTriggerTimer;
//!The test function is a function called
//!in the triggers timer function and used to test for the trigger condition
triggerTestFunctionFPtr mTestFunction;
virtual bool test(double){return false;}
virtual bool test(int) {return false;}
//!The triggerTest function is called by the timer
//!and is the point at where the trigger condition is checked /
virtual void triggerTest() = 0;
//!The triggering is tested using an Logic operator
LogicOperator mTriggerConditionOperator;
//!The Fire function is executed when the trigger is
//triggered
TriggerFunction* mTriggerFunction;
};
}
#endif
| true |
c26d350a43c2f1d8e00c8ee8e1ced86038c3733e
|
C++
|
BigDeviltjj/design-patterns
|
/builder_maze.cpp
|
UTF-8
| 2,814 | 3.515625 | 4 |
[] |
no_license
|
#include<algorithm>
#include<iostream>
#include<cstdio>
#include<vector>
#include<string>
using namespace std;
enum Direction {
EAST,
WEST,
NORTH,
SOUTH
};
class MapSite {
public:
virtual void Enter() = 0;
};
class Room : public MapSite {
public:
Room(int roomNo){
_roomNumber = roomNo;
}
MapSite* GetSite(Direction d) const {
return _sides[d];
}
void SetSide(Direction d, MapSite* m){
_sides[d] = m;
}
virtual void Enter() override {}
protected:
MapSite* _sides[4];
int _roomNumber;
};
class Door : public MapSite {
public:
Door(Room* r1 = 0, Room* r2 = 0){
_room1 = r1;
_room2 = r2;
}
virtual void Enter() override {}
Room* OtherSideFrom(Room* r){
if (r == _room2) return _room1;
else return _room2;
}
protected:
Room* _room1;
Room* _room2;
bool isOpen;
};
class Wall : public MapSite {
public:
Wall(){}
virtual void Enter() override {}
};
class Maze {
public:
Maze(){
_rooms.clear();
}
void AddRoom(Room* r){
_rooms.push_back(r);
}
Room* RoomNo(int idx) const{
if (idx >= _rooms.size()) return nullptr;
return _rooms[idx-1];
}
private:
vector<Room*> _rooms;
};
class MazeBuilder {
public:
virtual void BuildMaze() {}
virtual void BuildRoom(int room) {}
virtual void BuildDoor(int roomFrom, int roomTo) {}
virtual Maze* GetMaze() { return 0; }
protected:
MazeBuilder(){}
};
class StandardMazeBuilder : public MazeBuilder {
public:
StandardMazeBuilder(){ _currentMaze = 0; }
virtual void BuildMaze() override {
_currentMaze = new Maze;
}
virtual void BuildRoom(int n) override {
if (!_currentMaze->RoomNo(n)){
Room* room = new Room(n);
_currentMaze->AddRoom(room);
room->SetSide(NORTH, new Wall);
room->SetSide(EAST, new Wall);
room->SetSide(SOUTH, new Wall);
room->SetSide(WEST, new Wall);
}
}
virtual void BuildDoor(int n1, int n2) override {
Room* r1 = _currentMaze->RoomNo(n1);
Room* r2 = _currentMaze->RoomNo(n2);
Door* d = new Door(r1,r2);
r1->SetSide(CommonWall(r1, r2), d);
r2->SetSide(CommonWall(r2, r1), d);
}
private:
Direction CommonWall(Room* r1, Room* r2) {
return EAST;
}
Maze* _currentMaze;
};
class MazeGame {
public:
Maze* CreateMaze(MazeBuilder& builder) {
builder.BuildMaze();
builder.BuildRoom(1);
builder.BuildRoom(2);
builder.BuildDoor(1,2);
return builder.GetMaze();
}
};
int main() {
Maze* maze;
MazeGame game;
StandardMazeBuilder builder;
game.CreateMaze(builder);
maze = builder.GetMaze();
}
| true |
1ac38db6d3cca8dd9334d7da4ac74d83c881ba6c
|
C++
|
JISyed/LGE-Game-Engine
|
/LGE_GameEngine/LittleGameEngine/src/PCS/PCSTree.cpp
|
UTF-8
| 13,820 | 2.9375 | 3 |
[
"MIT"
] |
permissive
|
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include "PCSTree.h"
#include "PCSNode.h"
#include "PCSTreeForwardIterator.h"
#include "PCSTreeReverseIterator.h"
namespace lge
{
//
// C-Helper Functinos
//
// Used to unlink an entire local branch of the tree
void unlinkBranchesFrom(PCSNode* headNode)
{
if (headNode == nullptr)
{
assert(headNode != nullptr);
return;
}
PCSNode* currChild = headNode->getChild();
PCSNode* nextChild = nullptr;
while (currChild != nullptr)
{
nextChild = currChild->getNextSibling();
// Recursion!
unlinkBranchesFrom(currChild);
currChild = nextChild;
}
// Unlink local node after unlinking children
headNode->setParent(nullptr);
headNode->setChild(nullptr);
headNode->setNextSibling(nullptr);
headNode->setPrevSibling(nullptr);
// Delete node. Assuming that the tree was managing the node in the first place
delete headNode;
}
// Used in tree branch removal
int getNumberOfChildrenFrom(PCSNode* headNode)
{
if (headNode->getChild() == nullptr)
{
return 0;
}
PCSNode* const firstChild = headNode->getChild();
PCSNode* currSibling = firstChild;
int localTotal = 0;
while (currSibling != nullptr)
{
// Recursion!
int branchTotal = getNumberOfChildrenFrom(currSibling) + 1;
localTotal += branchTotal;
currSibling = currSibling->getNextSibling();
}
return localTotal;
}
// Used to determine if the new node will increment the level or not
int getDepthByCountingUpFrom(PCSNode* leafNode)
{
int depth = 0;
PCSNode* currNode = leafNode;
while (currNode != nullptr)
{
depth++;
currNode = currNode->getParent();
}
return depth;
}
// Recursively figure out the new current level of the tree
void getNewDepthRecursively(PCSNode* headNode, int& maxDepth)
{
// If leaf node
if (headNode->getChild() == nullptr)
{
// Iteratively inquire the depth from local leaf node
int newDepth = getDepthByCountingUpFrom(headNode);
if (newDepth > maxDepth)
{
maxDepth = newDepth;
}
// Then ask the next sibling
PCSNode* leafSibling = headNode->getNextSibling();
if (leafSibling != nullptr)
{
getNewDepthRecursively(leafSibling, maxDepth);
}
}
// If not leaf node
else
{
// Ask every sibling of the first child
PCSNode* currChild = headNode->getChild();
while (currChild != nullptr)
{
getNewDepthRecursively(currChild, maxDepth);
currChild = currChild->getNextSibling();
}
}
}
//
// PCSTree Methods
//
// constructor
PCSTree::PCSTree() :
mInfo(),
root(nullptr)
{
}
// destructor
PCSTree::~PCSTree()
{
if (this->root != nullptr)
{
this->remove(this->root);
}
}
// get Root
PCSNode* const PCSTree::getRoot() const
{
return this->root;
}
// Insert
void PCSTree::insert(PCSNode * const inNode, PCSNode * const base)
{
// "parent" parameter will be refered to as "base" node
// Check for bad value
if (inNode == nullptr)
{
// Leave
return;
}
// If the base is null, inNode is new root
if (base == nullptr)
{
// Root should be null!
assert(this->root == nullptr);
this->root = inNode;
this->IncrementNode();
this->IncrementLevel();
this->root->setChild(nullptr);
this->root->setParent(nullptr);
this->root->setNextSibling(nullptr);
this->root->setPrevSibling(nullptr);
this->root->setForward(nullptr);
this->root->setReverse(nullptr);
}
// For non-empty tree
else
{
// If base node has no children
if (base->getChild() == nullptr)
{
// Check if the inNode would start a new generation
int newDepth = getDepthByCountingUpFrom(base) + 1;
if (newDepth > this->mInfo.currNumLevels)
{
this->IncrementLevel();
}
// inNode is new only child
base->setChild(inNode);
inNode->setParent(base);
this->IncrementNode();
// Correct forward and reverse pointers...
// ... If the base is NOT the root
if (base != this->root)
{
// If base has a forward pointer
if (base->getForward() != nullptr)
{
PCSNode* oldForward = base->getForward();
oldForward->setReverse(inNode);
inNode->setForward(oldForward);
inNode->setReverse(base);
base->setForward(inNode);
}
// If base has no forward pointer
else
{
inNode->setForward(nullptr);
inNode->setReverse(base);
base->setForward(inNode);
this->root->setReverse(inNode);
}
}
// ... Or if the base is the root
else
{
inNode->setForward(nullptr);
inNode->setReverse(nullptr);
this->root->setForward(inNode);
this->root->setReverse(inNode);
}
}
// If base node has children
else
{
// inNode is new first sibling
PCSNode* oldFirstSibling = base->getChild();
assert(oldFirstSibling->getPrevSibling() == nullptr);
oldFirstSibling->setPrevSibling(inNode);
inNode->setNextSibling(oldFirstSibling);
base->setChild(inNode);
inNode->setParent(base);
this->IncrementNode();
// Correct forward and reverse pointers...
// ... If the base is NOT the root
if (base != this->root)
{
inNode->setReverse(base);
inNode->setForward(oldFirstSibling);
oldFirstSibling->setReverse(inNode);
base->setForward(inNode);
}
// ... Or if the base is the root
else
{
this->root->setForward(inNode);
inNode->setForward(oldFirstSibling);
oldFirstSibling->setReverse(inNode);
}
}
}
}
// Remove
void PCSTree::remove(PCSNode * const target)
{
// "inNode" was renamed to "target" node
// Check for bad value
if (target == nullptr)
{
// Leave
assert(target != nullptr);
return;
}
// If target node has no parent
if (target->getParent() == nullptr)
{
// Non-parent target can only be the root
assert(target == this->root);
assert(target->getNextSibling() == nullptr);
assert(target->getPrevSibling() == nullptr);
// Remove target
this->root = nullptr;
this->mInfo.currNumNodes = 0;
this->mInfo.currNumLevels = 0;
unlinkBranchesFrom(target);
}
// If target node has parent
else
{
// If target has no siblings
if (target->getNextSibling() == nullptr && target->getPrevSibling() == nullptr)
{
// Calculate number of nodes removed
int totalRemovedNodes = getNumberOfChildrenFrom(target) + 1;
this->mInfo.currNumNodes -= totalRemovedNodes;
assert(this->mInfo.currNumNodes >= 0);
// Correct iterator pointers before removing node
this->correctItrPointersNoNextSibling(target);
// Remove node and its branch
PCSNode* parentOfTarget = target->getParent();
parentOfTarget->setChild(nullptr);
unlinkBranchesFrom(target);
// Calculate the new level
int newDepth = 0;
getNewDepthRecursively(this->root, newDepth);
this->mInfo.currNumLevels = newDepth;
}
// If target is last sibling
else if (target->getNextSibling() == nullptr)
{
// Calculate number of nodes removed
int totalRemovedNodes = getNumberOfChildrenFrom(target) + 1;
this->mInfo.currNumNodes -= totalRemovedNodes;
assert(this->mInfo.currNumNodes >= 0);
// Correct iterator pointers before removing node
this->correctItrPointersNoNextSibling(target);
// Remove node and its branch
PCSNode* prevSibling = target->getPrevSibling();
prevSibling->setNextSibling(nullptr);
unlinkBranchesFrom(target);
// Calculate the new level
int newDepth = 0;
getNewDepthRecursively(this->root, newDepth);
this->mInfo.currNumLevels = newDepth;
}
// If target is first sibling
else if (target->getPrevSibling() == nullptr)
{
// Calculate number of nodes removed
int totalRemovedNodes = getNumberOfChildrenFrom(target) + 1;
this->mInfo.currNumNodes -= totalRemovedNodes;
assert(this->mInfo.currNumNodes >= 0);
// Correct iterator pointers before removing node
this->correctItrPointersWithNextSibling(target);
// Remove node and its local branch
PCSNode* nextSibling = target->getNextSibling();
nextSibling->setPrevSibling(nullptr);
nextSibling->getParent()->setChild(nextSibling);
unlinkBranchesFrom(target);
// Calculate the new level
int newDepth = 0;
getNewDepthRecursively(this->root, newDepth);
this->mInfo.currNumLevels = newDepth;
}
// If target is a middle sibling
else
{
// Calculate number of nodes removed
int totalRemovedNodes = getNumberOfChildrenFrom(target) + 1;
this->mInfo.currNumNodes -= totalRemovedNodes;
assert(this->mInfo.currNumNodes >= 0);
// Correct iterator pointers before removing node
this->correctItrPointersWithNextSibling(target);
// Remove node and its local branch
PCSNode* prevSibling = target->getPrevSibling();
PCSNode* nextSibling = target->getNextSibling();
prevSibling->setNextSibling(nextSibling);
nextSibling->setPrevSibling(prevSibling);
unlinkBranchesFrom(target);
// Calculate the new level
int newDepth = 0;
getNewDepthRecursively(this->root, newDepth);
this->mInfo.currNumLevels = newDepth;
}
}
}
// get tree info
void PCSTree::getInfo(PCSTreeInfo &infoContainer)
{
infoContainer.currNumNodes = this->mInfo.currNumNodes;
infoContainer.maxNumNodes = this->mInfo.maxNumNodes;
infoContainer.currNumLevels = this->mInfo.currNumLevels;
infoContainer.maxNumLevels = this->mInfo.maxNumLevels;
}
void PCSTree::printTree() const
{
// Iterate through every node and print it
//*
PCSTreeForwardIterator itr(*this);
PCSNode* currNode = itr.First();
while (!itr.IsDone())
{
currNode->printNode();
currNode = itr.Next();
}
//*/
// Reverse iteration
/*
PCSTreeReverseIterator ritr(this);
PCSNode* currNode = ritr.First();
while (!ritr.IsDone())
{
currNode->printNode();
currNode = ritr.Next();
}
//*/
}
const int PCSTree::getNumberOfNodes() const
{
return this->mInfo.currNumNodes;
}
void PCSTree::IncrementNode()
{
this->mInfo.currNumNodes++;
if (this->mInfo.currNumNodes > this->mInfo.maxNumNodes)
{
this->mInfo.maxNumNodes = this->mInfo.currNumNodes;
}
}
void PCSTree::DecrementNode()
{
this->mInfo.currNumNodes--;
}
void PCSTree::IncrementLevel()
{
this->mInfo.currNumLevels++;
if (this->mInfo.currNumLevels > this->mInfo.maxNumLevels)
{
this->mInfo.maxNumLevels = this->mInfo.currNumLevels;
}
}
void PCSTree::DecrementLevel()
{
this->mInfo.currNumLevels--;
}
// Itr pointer corrections for node removal
void PCSTree::correctItrPointersWithNextSibling(PCSNode* oldNode)
{
// Get the node's reverse and nextSibling (reverse can either be parent or prevSibling)
PCSNode* oldReverse = oldNode->getReverse();
PCSNode* oldNextSibling = oldNode->getNextSibling();
// Does the node have a reverse pointer (usually the case)
if (oldReverse != nullptr)
{
oldReverse->setForward(oldNextSibling);
oldNextSibling->setReverse(oldReverse);
}
// Or does the node have no reverse ptr (indicates first sibling under root)
else
{
// The node's parent must be the tree root if we're here
assert(oldNode->getParent() == this->root);
oldNextSibling->setReverse(nullptr);
this->root->setForward(oldNextSibling);
}
}
void PCSTree::correctItrPointersNoNextSibling(PCSNode* oldNode)
{
// Get the old reverse (can be either parent or previous sibling)
PCSNode* oldReverse = oldNode->getReverse();
PCSNode* oldForward = nullptr;
// Does the node have a reverse pointer (usually the case)
if (oldReverse != nullptr)
{
// Get the old forward pointer...
// ... if the node has children
if (oldNode->getChild() != nullptr)
{
oldForward = this->getForwardAfterChildrenOf(oldNode);
}
// ... or if the node has no children
else
{
oldForward = oldNode->getForward();
}
// If old pointer is null, that means that deleting oldNode
// would have been the end of forward iteration
if (oldForward == nullptr)
{
// oldReverse is the new last node in forward iteration
oldReverse->setForward(nullptr);
this->root->setReverse(nullptr);
}
// Here, oldForward is valid, and thus wouldn't end forward iteration
else
{
oldReverse->setForward(oldForward);
oldForward->setReverse(oldReverse);
}
}
// Or does the node have no reverse ptr (indicates only sibling under root)
else
{
// The node's parent must be the tree root if we're here
assert(oldNode->getParent() == this->root);
// Assuming that the node has no other sibling
assert(oldNode->getPrevSibling() == nullptr);
assert(oldNode->getNextSibling() == nullptr);
// Basically removing every child node under the node,
// so root doesn't point to anyone anymore
this->root->setForward(nullptr);
this->root->setReverse(nullptr);
}
}
PCSNode* PCSTree::getForwardAfterChildrenOf(PCSNode* target)
{
// Assumption: target has children! (at least 1)
assert(target->getChild() != nullptr);
// "currForward" can never be invalid because
// a target's first child is its foward
PCSNode* currForward = target->getForward();
PCSNode* nextForward = currForward->getForward();
// Traverse through all children until no more forward...
while (nextForward != nullptr)
{
// ... or until nextForward is not directly related to currForward
if (!(currForward->getChild() == nextForward || currForward->getNextSibling() == nextForward))
{
// Stop traversing
break;
}
// Next node
currForward = nextForward;
nextForward = nextForward->getForward();
}
// If nextForward was null, there would be no forward after target is deleted.
// But regardless, return the result, null or not
return nextForward;
}
}
| true |
31bd90741404840ede6a06c8a4bd2375bacd9945
|
C++
|
vmware/concord-bft
|
/utt/libutt/test/TestRootsOfUnity.cpp
|
UTF-8
| 5,589 | 2.6875 | 3 |
[
"Apache-2.0",
"MIT"
] |
permissive
|
#include <utt/Configuration.h>
#include <utt/PolyCrypto.h>
#include <utt/PolyOps.h>
#include <xassert/XAssert.h>
#include <xutils/Log.h>
#include <xutils/Utils.h>
#include <libfqfft/polynomial_arithmetic/basic_operations.hpp>
#include <set>
#include <iomanip>
#include <vector>
#include <queue>
using namespace libutt;
void print_all_accumulators(std::vector<Fr> roots, const std::vector<Fr>& allRoots);
void print_all_accumulators(std::vector<Fr> roots,
const std::vector<Fr>& allRoots,
const std::vector<Fr>& p,
std::string nodeName);
std::vector<Fr> even_or_odd(const std::vector<Fr>& p, bool even);
std::vector<Fr> poly_from_roots(std::vector<Fr>::const_iterator beg, std::vector<Fr>::const_iterator end);
int main(int argc, char* argv[]) {
(void)argc;
(void)argv;
libutt::initialize(nullptr, 0);
// test roots of unity
size_t n = 128;
// Fr w_n = libff::get_root_of_unity<Fr>(n);
std::vector<Fr> allRoots = get_all_roots_of_unity(n);
// for(size_t i = 0; i < n; i++) {
// Fr w_ni = w_n^i;
//
// if(std::find(allRoots.begin(), allRoots.end(), w_ni) != allRoots.end()) {
// logerror << i << "th" << n << "th root of unity is not unique" << endl;
// assertFail("Something's wrong with the roots of unity");
// }
// allRoots.push_back(w_ni);
//}
// testAssertEqual(w_n^n, Fr(1));
auto checkCoeffs = [&allRoots](const std::vector<Fr>& p, const std::string& poly) {
size_t d = p.size();
loginfo << poly << " of degree " << d - 1 << " coeffs: ";
poly_print_wnk(p, allRoots);
std::cout << endl;
};
// test \prod_{i=0}{n-1} (x-w_n^i) = x^n - 1
std::vector<Fr> xn_minus_1 = poly_from_roots(allRoots.begin(), allRoots.end());
testAssertEqual(xn_minus_1.size(), n + 1);
checkCoeffs(xn_minus_1, "x^n - 1");
testAssertEqual(xn_minus_1[0], Fr(-1));
testAssertEqual(xn_minus_1[n], Fr::one());
// test \prod_{i=0}{n/2-1} (x-(w_n^i)^2) = x^{n/2} - 1
// NOTE: (w_n^i)^2 will be the roots of unity at even indices in 'allRoots'
// Example: For n = 4, we have the principal 4th root of unity w_4 = i
// ...and w_4^0 = i^0 = 1, w_4^1 = i^1 = i, w_4^2 = i^2 = -1, w_4^3 = -i
// The 2nd roots of unity will be (w_4^0)^2 = 1 = w_4^0 and (w_4^1)^2 = -1 = w_4^2
auto even = even_or_odd(allRoots, true);
std::vector<Fr> xn2_minus_1 = poly_from_roots(even.begin(), even.end());
testAssertEqual(xn2_minus_1.size(), n / 2 + 1);
checkCoeffs(xn2_minus_1, "x^{n/2} - 1");
testAssertEqual(xn2_minus_1[0], Fr(-1));
testAssertEqual(xn2_minus_1[n / 2], Fr::one());
// test \prod_{i=n/2-1}{n-1} (x-w_n^i) = x^{n/2} + 1
auto odd = even_or_odd(allRoots, false);
std::vector<Fr> xn2_plus_1 = poly_from_roots(odd.begin(), odd.end());
testAssertEqual(xn2_plus_1.size(), n / 2 + 1);
checkCoeffs(xn2_plus_1, "x^{n/2} + 1");
testAssertEqual(xn2_plus_1[0], Fr::one());
testAssertEqual(xn2_plus_1[n / 2], Fr::one());
logdbg << "All accumulator polys for n = " << n << ": " << endl;
print_all_accumulators(allRoots, allRoots);
std::cout << "Test '" << argv[0] << "' finished successfully" << std::endl;
return 0;
}
void checkMiddleCoeffs(const std::vector<Fr>& p) {
size_t d = p.size();
for (size_t i = 1; i < d - 1; i++) {
testAssertEqual(p[(d - 1) - i], Fr::zero());
}
};
void print_all_accumulators(std::vector<Fr> roots, const std::vector<Fr>& allRoots) {
std::vector<Fr> p = poly_from_roots(roots.begin(), roots.end());
print_all_accumulators(roots, allRoots, p, "");
}
void print_all_accumulators(std::vector<Fr> roots,
const std::vector<Fr>& allRoots,
const std::vector<Fr>& p,
std::string nodeName) {
checkMiddleCoeffs(p);
std::cout << std::endl
<< std::left << std::setw(static_cast<int>(Utils::log2ceil(allRoots.size())))
<< (nodeName.empty() ? "root" : nodeName) << " -> ";
poly_print_wnk(p, allRoots);
std::cout << endl;
if (roots.size() == 1) return;
std::vector<Fr> even = even_or_odd(roots, true);
std::vector<Fr> odd = even_or_odd(roots, false);
// print children below parent (this is just because I'm curious what they look like)
std::cout << " \\-0->";
auto p_even = poly_from_roots(even.begin(), even.end());
poly_print_wnk(p_even, allRoots);
std::cout << endl;
std::cout << " \\-1->";
auto p_odd = poly_from_roots(odd.begin(), odd.end());
poly_print_wnk(p_odd, allRoots);
std::cout << endl;
// make sure left * right = parent
std::vector<Fr> p_exp;
libfqfft::_polynomial_multiplication(p_exp, p_even, p_odd);
testAssertEqual(p, p_exp);
print_all_accumulators(even, allRoots, p_even, nodeName + "0");
print_all_accumulators(odd, allRoots, p_odd, nodeName + "1");
}
std::vector<Fr> poly_from_roots(std::vector<Fr>::const_iterator beg, std::vector<Fr>::const_iterator end) {
std::queue<std::vector<Fr>> merge;
while (beg != end) {
auto r = *beg;
merge.push({-r, 1});
beg++;
}
while (merge.size() > 1) {
std::vector<Fr> res, left, right;
left = merge.front();
merge.pop();
right = merge.front();
merge.pop();
libfqfft::_polynomial_multiplication(res, left, right);
merge.push(res);
}
return merge.front();
}
std::vector<Fr> even_or_odd(const std::vector<Fr>& p, bool even) {
std::vector<Fr> v;
size_t rem = even ? 0 : 1;
for (size_t i = 0; i < p.size(); i++) {
if (i % 2 == rem) {
v.push_back(p[i]);
}
}
return v;
}
| true |
a15d625eacc8420d9239117b5cabb55f944971a8
|
C++
|
s1ddb/ClassesDone
|
/database.cpp
|
UTF-8
| 498 | 3.03125 | 3 |
[] |
no_license
|
#include <iostream>
#include "database.h"
using namespace std;
//funt header
database::database() {
title = new char[20];
}
//title header
char* database::getTitle() {
return title;
}
void database::setTitle(char* userinput) {
strcpy(title, userinput); //sets the title to userinput
}
int database::getYear() {
return year; //returning the integer year when called
}
void database::setYear(int userinput) {
year = userinput;
}
int database::getType() {
return 0;
}
| true |
9a262d887f7a208d58a4afb6ccc1545fc9f72407
|
C++
|
sirecho/Sheila
|
/src/piece.h
|
UTF-8
| 2,540 | 3.53125 | 4 |
[] |
no_license
|
/*
* piece.h
*
* Created on: Dec 21, 2015
* Author: Eirik Skogstad
*/
#ifndef PIECE_H_
#define PIECE_H_
#include <vector>
#include "side.h"
#include "board.h"
#include "position.h"
class Piece {
public:
Piece(Side side, Position position);
virtual ~Piece(){}
Side getSide() { return side_; }
short getValue() { return value_; }
Position position() { return position_; }
void placeAt(Position position) { this->position_ = position; }
// Functions returning positions for legal moves
std::vector<Position> manhattanMoves(Board& board);
std::vector<Position> diagonalMoves(Board& board);
virtual std::vector<Position> getLegalMoves(Board& board) = 0;
virtual void move(Board& board, Position to);
char toChar() { return character_representation_; }
bool operator<(const Piece &rhs) const { return value_ < rhs.value_; }
protected:
Side side_;
short value_;
Position position_;
char character_representation_;
};
class Pawn: public Piece {
private:
bool enPassant;
public:
Pawn(Side side, Position position) : Piece(side, position) { enPassant = false; character_representation_ = side == WHITE ? 'P' : 'p'; value_ = 10; }
std::vector<Position> getLegalMoves(Board& board);
void move(Board& board, Position to);
bool canEnPassant() { return enPassant; }
};
class Rook: public Piece {
public:
Rook(Side side, Position position) : Piece(side, position) { character_representation_ = side == WHITE ? 'R' : 'r'; value_ = 50; }
std::vector<Position> getLegalMoves(Board& board);
};
class Knight: public Piece {
public:
Knight(Side side, Position position) : Piece(side, position) { character_representation_ = side == WHITE ? 'N' : 'n'; value_ = 30; }
std::vector<Position> getLegalMoves(Board& board);
};
class Bishop: public Piece {
public:
Bishop(Side side, Position position) : Piece(side, position) { character_representation_ = side == WHITE ? 'B' : 'b'; value_ = 30; }
std::vector<Position> getLegalMoves(Board& board);
};
class Queen: public Piece {
public:
Queen(Side side, Position position) : Piece(side, position) { character_representation_ = side == WHITE ? 'Q' : 'q'; value_ = 90; }
std::vector<Position> getLegalMoves(Board& board);
};
class King: public Piece {
public:
King(Side side, Position position) : Piece(side, position) { character_representation_ = side == WHITE ? 'K' : 'k'; value_ = 1000; }
std::vector<Position> getLegalMoves(Board& board);
};
#endif /* PIECE_H_ */
| true |
be61ef40a2e0f4fcb3c4b8b2226f91255a8dd5ac
|
C++
|
PranakBarua/CodeForces
|
/1054a.cpp
|
UTF-8
| 383 | 2.78125 | 3 |
[] |
no_license
|
#include<iostream>
#include<cstdio>
using namespace std;
int main()
{
int a,b,c,d,e,f,x,y,z;
cin>>a>>b>>c>>d>>e>>f;
x=(a-b)*d;
if(x<0)
x=x*(-1);
y=((a-c)*e);
if(y<0)
y=y*(-1);
y=y+(2*f);
z=((a-b)*e);
if(z<0)
z=z*(-1);
z=z+y+f;
if(z<=x)
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
return 0;
}
| true |
0725e1a620d974e9e5a53b70b9cba9e315343dcd
|
C++
|
kolya-t/PillClicker
|
/mainwindow.cpp
|
UTF-8
| 4,450 | 2.5625 | 3 |
[] |
no_license
|
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QRect>
#include <QDesktopWidget>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
_timer(new QTimer(this)),
_pillsCount(0), _step(1)
{
connect (_timer, SIGNAL(timeout()), this, SLOT(nullMultiplier()));
/*----------------УСТАНОВКА ИНТЕРФЕЙСА-НАЧАЛО-------------------*/
ui->setupUi(this);
nullMultiplier();
setCentralWidget(ui->stackedWidget);
/* размеры приложения */
// на десктопе
QRect screenGeometry = geometry();
// на андроиде
// QRect screenGeometry = qApp->desktop()->availableGeometry(ui->pillButton);
// установка размеров кнопки
_pillSize = screenGeometry.width() / 2;
ui->pillButton->resize(_pillSize, _pillSize);
ui->pillButton->setIconSize(QSize(_pillSize, _pillSize));
// центрирование кнопки
QPoint center(centerXBetweenAB(_pillSize, 0, screenGeometry.width()),
centerXBetweenAB(_pillSize, 0, screenGeometry.height()));
ui->pillButton->move(center);
// центрирование счетчика
QRect widgetGeometry = ui->counterLabel->geometry();
center = QPoint(centerXBetweenAB(widgetGeometry.width(), 0, screenGeometry.width()),
centerXBetweenAB(widgetGeometry.height(), 0, ui->pillButton->y()));
ui->counterLabel->move(center);
// центрирование шага
widgetGeometry = ui->stepLabel->geometry();
center = QPoint(centerXBetweenAB(widgetGeometry.width(), 0, screenGeometry.width()),
centerXBetweenAB(widgetGeometry.height(), _pillSize + ui->pillButton->y(), screenGeometry.height()));
ui->stepLabel->move(center);
/*----------------УСТАНОВКА ИНТЕРФЕЙСА-КОНЕЦ--------------------*/
}
MainWindow::~MainWindow() {
delete ui;
}
/* Возвращает такую координату, чтобы отрезок,
* длиной x оказался ровно по центру между begin и end */
int MainWindow::centerXBetweenAB(int x, int begin, int end) {
return begin + (end - begin - x) / 2;
}
void MainWindow::on_pillButton_clicked() {
// получение таблеточек
_pillsCount += _step * _multiplier;
// вывод информации на экран
ui->counterLabel->setText(QString::number(_pillsCount));
ui->stepLabel->setText(tr("+") + QString::number(_step * _multiplier));
/* временный множитель, пропадающий через 2 секунды
* после прекращения кликания. увеличивает свое значение
* каждые 5 кликов на 10 процентов */
++_clicksCount; // был произведен клик
// если 2 секунды еще не прошло
if (_timer->isActive()) {
if (_clicksCount == CLICKS_TO_INC_MULTIPLIER) {
_multiplier += _step * MULTIPLIER_INCREMENT;
_clicksCount = 0;
}
}
// если прошло 2 секунды после последнего клика
else {
nullMultiplier();
}
_timer->start(TIME_TO_NULL_MULTIPLIER);
}
void MainWindow::on_pillButton_pressed() {
ui->pillButton->setIconSize(QSize(_pillSize / 2, _pillSize));
}
void MainWindow::on_pillButton_released() {
ui->pillButton->setIconSize(QSize(_pillSize, _pillSize));
}
// обнуление количества кликов подряд и установка множителя = 1
void MainWindow::nullMultiplier() {
_clicksCount = 0;
_multiplier = 1;
ui->stepLabel->setText("");
}
void MainWindow::on_openUpgradesButton_clicked() {
ui->stackedWidget->setCurrentIndex(1);
}
void MainWindow::on_fromUpgradesToGameButton_clicked() {
ui->stackedWidget->setCurrentIndex(0);
}
void MainWindow::on_fromUpgradesToGameButton_pressed() {
ui->fromUpgradesToGameButton->setIconSize(QSize(45, 50));
}
void MainWindow::on_fromUpgradesToGameButton_released() {
ui->fromUpgradesToGameButton->setIconSize(QSize(50, 50));
}
void MainWindow::on_openUpgradesButton_pressed() {
ui->openUpgradesButton->setIconSize(QSize(45, 50));
}
void MainWindow::on_openUpgradesButton_released() {
ui->openUpgradesButton->setIconSize(QSize(50, 50));
}
| true |
7de64958b1906e66b30f3845c8dfaff51dbc233f
|
C++
|
dumpinfo/CppConcurrency
|
/chap9/WorkStealingQueue.h
|
UTF-8
| 1,025 | 3.5 | 4 |
[] |
no_license
|
#pragma once
#include <deque>
#include <mutex>
#include "FunctionWrapper.h"
class WorkStealingQueue {
using DataType = FunctionWrapper;
public:
WorkStealingQueue() = default;
WorkStealingQueue(const WorkStealingQueue& other) = delete;
WorkStealingQueue& operator=(const WorkStealingQueue& other) = delete;
void push(DataType data) {
std::lock_guard<std::mutex> lock(mu_);
queue_.push_front(std::move(data));
}
bool empty() const {
std::lock_guard<std::mutex> lock(mu_);
return queue_.empty();
}
bool tryPop(DataType& res) {
std::lock_guard<std::mutex> lock(mu_);
if (queue_.empty()) {
return false;
}
res = std::move(queue_.front());
queue_.pop_front();
return true;
}
bool trySteal(DataType& res) {
std::lock_guard<std::mutex> lock(mu_);
if (queue_.empty()) {
return false;
}
res = std::move(queue_.back());
queue_.pop_back();
return true;
}
private:
std::deque<DataType> queue_;
mutable std::mutex mu_;
};
| true |
91d4da6140137c2d55cb8ff100dfbffc6f26ad16
|
C++
|
jrl-umi3218/tvm
|
/src/constraint/BasicLinearConstraint.cpp
|
UTF-8
| 6,810 | 2.5625 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
/** Copyright 2017-2020 CNRS-AIST JRL and CNRS-UM LIRMM */
#include <tvm/constraint/BasicLinearConstraint.h>
#include <tvm/Variable.h>
namespace tvm
{
namespace constraint
{
BasicLinearConstraint::BasicLinearConstraint(const MatrixConstRef & A, VariablePtr x, Type ct)
: BasicLinearConstraint(std::vector<MatrixConstRef>{A}, {x}, ct)
{}
BasicLinearConstraint::BasicLinearConstraint(const std::vector<MatrixConstRef> & A,
const std::vector<VariablePtr> & x,
Type ct)
: LinearConstraint(ct, RHS::ZERO, static_cast<int>(A.begin()->rows()))
{
if(ct == Type::DOUBLE_SIDED)
throw std::runtime_error("This constructor is only for single-sided constraints.");
if(A.size() != x.size())
throw std::runtime_error("The number of matrices and variables is incoherent.");
auto v = x.begin();
for(const Eigen::MatrixXd & a : A)
{
add(a, *v);
++v;
}
}
BasicLinearConstraint::BasicLinearConstraint(const MatrixConstRef & A,
VariablePtr x,
const VectorConstRef & b,
Type ct,
RHS cr)
: BasicLinearConstraint(std::vector<MatrixConstRef>{A}, {x}, b, ct, cr)
{}
BasicLinearConstraint::BasicLinearConstraint(const std::vector<MatrixConstRef> & A,
const std::vector<VariablePtr> & x,
const VectorConstRef & b,
Type ct,
RHS cr)
: LinearConstraint(ct, cr, static_cast<int>(A.begin()->rows()))
{
if(ct == Type::DOUBLE_SIDED)
throw std::runtime_error("This constructor is only for single-sided constraints.");
if(cr == RHS::ZERO)
throw std::runtime_error("RHS::ZERO is not a valid input for this constructor. Please use the constructor for "
"Ax=0, Ax<=0 and Ax>=0 instead.");
if(A.size() != x.size())
throw std::runtime_error("The number of matrices and variables is incoherent.");
if(b.size() != size())
throw std::runtime_error("Vector b doesn't have the good size.");
auto v = x.begin();
for(const Eigen::MatrixXd & a : A)
{
add(a, *v);
++v;
}
this->b(b);
}
BasicLinearConstraint::BasicLinearConstraint(const MatrixConstRef & A,
VariablePtr x,
const VectorConstRef & l,
const VectorConstRef & u,
RHS cr)
: BasicLinearConstraint(std::vector<MatrixConstRef>{A}, {x}, l, u, cr)
{}
BasicLinearConstraint::BasicLinearConstraint(const std::vector<MatrixConstRef> & A,
const std::vector<VariablePtr> & x,
const VectorConstRef & l,
const VectorConstRef & u,
RHS cr)
: LinearConstraint(Type::DOUBLE_SIDED, cr, static_cast<int>(A.begin()->rows()))
{
if(cr == RHS::ZERO)
throw std::runtime_error("RHS::ZERO is not a valid input for this constructor. Please use the constructor for "
"Ax=0, Ax<=0 and Ax>=0 instead.");
if(A.size() != x.size())
throw std::runtime_error("The number of matrices and variables is incoherent.");
if(l.size() != size())
throw std::runtime_error("Vector l doesn't have the good size.");
if(u.size() != size())
throw std::runtime_error("Vector u doesn't have the good size.");
auto v = x.begin();
for(const Eigen::MatrixXd & a : A)
{
add(a, *v);
++v;
}
this->l(l);
this->u(u);
}
BasicLinearConstraint::BasicLinearConstraint(int m, VariablePtr x, Type ct, RHS cr) : LinearConstraint(ct, cr, m)
{
addVariable(x, true);
}
BasicLinearConstraint::BasicLinearConstraint(int m, std::vector<VariablePtr> & x, Type ct, RHS cr)
: LinearConstraint(ct, cr, m)
{
for(const auto & v : x)
{
addVariable(v, true);
}
}
void BasicLinearConstraint::A(const MatrixConstRef & A, const Variable & x, const tvm::internal::MatrixProperties & p)
{
if(A.rows() == size() && A.cols() == x.size())
{
jacobian_.at(&x) = A;
jacobian_.at(&x).properties(p);
}
else
throw std::runtime_error("Matrix A doesn't have the good size.");
}
void BasicLinearConstraint::A(const MatrixConstRef & A, const tvm::internal::MatrixProperties & p)
{
if(variables().numberOfVariables() == 1)
{
this->A(A, *variables()[0].get(), p);
}
else
throw std::runtime_error("You can use this method only for constraints with one variable.");
}
void BasicLinearConstraint::b(const VectorConstRef & b)
{
if(type() != Type::DOUBLE_SIDED && rhs() != RHS::ZERO)
{
if(b.size() == size())
{
switch(type())
{
case Type::EQUAL:
eRef() = b;
break;
case Type::GREATER_THAN:
lRef() = b;
break;
case Type::LOWER_THAN:
uRef() = b;
break;
default:
break;
}
}
else
throw std::runtime_error("Vector b doesn't have the correct size.");
}
else
throw std::runtime_error("setb is not allowed for this constraint.");
}
void BasicLinearConstraint::l(const VectorConstRef & l)
{
if(type() == Type::DOUBLE_SIDED && rhs() != RHS::ZERO)
{
if(l.size() == size())
{
lRef() = l;
}
else
{
throw std::runtime_error("Vector l doesn't have the correct size.");
}
}
else
{
throw std::runtime_error("setl is not allowed for this constraint.");
}
}
void BasicLinearConstraint::u(const VectorConstRef & u)
{
if(type() == Type::DOUBLE_SIDED && rhs() != RHS::ZERO)
{
if(u.size() == size())
{
uRef() = u;
}
else
{
throw std::runtime_error("Vector u doesn't have the correct size.");
}
}
else
throw std::runtime_error("setu is not allowed for this constraint.");
}
void BasicLinearConstraint::add(const Eigen::MatrixXd & A, VariablePtr x)
{
if(!x->space().isEuclidean() && x->isBasePrimitive())
throw std::runtime_error("We allow linear constraint only on Euclidean variables.");
if(A.rows() != size())
throw std::runtime_error("Matrix A doesn't have coherent row size.");
if(A.cols() != x->size())
throw std::runtime_error("Matrix A doesn't have its column size coherent with its corresponding variable.");
addVariable(x, true);
jacobian_.at(x.get()) = A;
jacobian_.at(x.get()).properties({tvm::internal::MatrixProperties::Constness(true)});
}
} // namespace constraint
} // namespace tvm
| true |
6141a24d684af4259e6c82913afb1bfe251dc3c4
|
C++
|
chetanpatil5/Reference
|
/Reference.cpp
|
UTF-8
| 1,254 | 3.734375 | 4 |
[] |
no_license
|
#include<iostream>
#include<string>
using namespace std;
int main()
{
int Data = 5;
cout << "\nData : " << Data<<endl;
int &ref = Data;
cout << "Address of Data : " << &Data << endl;
cout << "Address of Reference : " << &*&ref << endl;
cout << "Ref : " << ref<<endl;
int x = 1;
ref = x;
cout << "Ref : " << ref<<endl;
cout << "Address of Reference : " << &*&ref << endl;
cout << "x ka address" << &x << endl;
cout << "Data : " << Data << endl;
cout << "--------------------------------------" << endl;
//reference to a pointer
int y = 10;
int *ptr = &y;
int* (&reff) = ptr;
cout <<"Y : "<< y<<endl;
cout << "Y address"<<&y<<endl;
cout <<"Ref value :" <<*reff<< endl;
cout << "Reff address :" << &reff << endl;
//Reference to an array
int arr[5] = {1,2,3,4,5};
int (&reffarr)[5] = arr ;
for (int i = 0; i < 5; i++)
{
cout << reffarr[i]<<" ";
}
cout << endl;
for (int i : reffarr)
{
cout << i << " ";
}
cout << endl;
//Pointer to a reference-Address of eference not available
//So we cannot create pointer to reference
//int *ptr=&reff
//array of reference
//Similar to above
//reference to a reference
//Similar to above
return 0;
}
| true |
34e3ea55236679c92644a5db19d62653c6e33d3d
|
C++
|
kronicler/cs2040_DSnA
|
/KattisPractices/James/judgingmoose.cpp
|
UTF-8
| 299 | 3.453125 | 3 |
[] |
no_license
|
#include <iostream>
using namespace std;
int main () {
int left, right;
cin >> left >> right;
if (left + right == 0) {
cout << "Not a moose" << endl;
} else if (left == right) {
cout << "Even " << 2*left << endl;
} else {
cout << "Odd " << 2*max(left,right) << endl;
}
return 0;
}
| true |
d6897c635b57eb7a76e83bdc3433779f41c55a4e
|
C++
|
pxhmeiyangyang/USC_SDK_PXH
|
/sourcecode(occode)/Common/WaveHeader.cpp
|
UTF-8
| 5,379 | 2.578125 | 3 |
[] |
no_license
|
//
// WaveHeader.cpp
// usc
//
// Created by hejinlai on 13-11-8.
// Copyright (c) 2013年 yunzhisheng. All rights reserved.
//
#include <stdlib.h>
#include "WaveHeader.h"
// wav头部结构体
struct wave_header {
char riff[4];
unsigned long fileLength;
char wavTag[4];
char fmt[4];
unsigned long size;
unsigned short formatTag;
unsigned short channel;
unsigned long sampleRate;
unsigned long bytePerSec;
unsigned short blockAlign;
unsigned short bitPerSample;
char data[4];
unsigned long dataSize;
};
#define UNIT 4
#define WORD short
#define DWORD int
// wav语音文件头部
struct RIFF_HEADER
{
char szRiffID[4]; // 'R','I','F','F'
DWORD dwRiffSize;
char szRiffFormat[4]; // 'W','A','V','E'
};
struct WAVE_FORMAT
{
WORD wFormatTag;
WORD wChannels;
DWORD dwSamplesPerSec;
DWORD dwAvgBytesPerSec;
WORD wBlockAlign;
WORD wBitsPerSample;
};
struct FMT_BLOCK
{
char szFmtID[4]; // 'f','m','t',' '
DWORD dwFmtSize;
WAVE_FORMAT wavFormat;
};
struct DATA_BLOCK
{
char szDataID[4]; // 'd','a','t','a'
DWORD dwDataSize;
};
union DWORD_CHAR
{
int nValue;
char charBuf[4];
};
bool writeFile2Int(FILE *fp,int nWhere,int nValue)
{
if(fp==NULL)
{
return false;
}
fseek(fp,nWhere,SEEK_SET);
DWORD_CHAR dc;
dc.nValue=nValue;
fwrite(dc.charBuf,1,4,fp);
return true;
}
int writeWaveHead(FILE *fp, const int dw_size, const int dw_samples_per_sec,
const int ui_bits_per_sample)
{
if (NULL == fp)
{
return -1;
}
if (0 > dw_size || 0 > dw_samples_per_sec || 0 > ui_bits_per_sample)
{
return -2;
}
//写WAV文件头
RIFF_HEADER rh;
memset(&rh,0,sizeof(rh));
strncpy(rh.szRiffFormat,"WAVE",4);
strncpy(rh.szRiffID,"RIFF",4);
fwrite(&rh,1,sizeof(rh),fp);
FMT_BLOCK fb;
strncpy(fb.szFmtID,"fmt ",4);
fb.dwFmtSize = dw_size;
fb.wavFormat.wFormatTag = 0x0001;
fb.wavFormat.wChannels = 1;
fb.wavFormat.wBitsPerSample = ui_bits_per_sample;
fb.wavFormat.dwSamplesPerSec = dw_samples_per_sec;
fb.wavFormat.wBlockAlign = fb.wavFormat.wChannels*fb.wavFormat.wBitsPerSample/8; //4;
fb.wavFormat.dwAvgBytesPerSec = fb.wavFormat.dwSamplesPerSec * fb.wavFormat.wBlockAlign;
fwrite(&fb,1,sizeof(fb),fp);
char buf[]={"data0000"};
fwrite(buf,1,sizeof(buf),fp);
return 1;
}
int writeWaveBody(FILE *fp, long filelength)
{
if (NULL == fp)
{
return -1;
}
if (0 > filelength)
{
return -2;
}
//更新WAV文件dwRiffSize字段中的值
int nWhere = 4;
writeFile2Int(fp,nWhere, filelength - 8);
//更新WAV文件DataChunk中Size字段的值
nWhere=sizeof(RIFF_HEADER)+sizeof(FMT_BLOCK)+4;
writeFile2Int(fp,nWhere,filelength - (sizeof(RIFF_HEADER)+sizeof(FMT_BLOCK)+8) );
return 1;
}
int pcm_to_wav(const char* pcm_name, const char* wav_name, const int dw_size = 16,
const int dw_samples_per_sec = 16000, const int ui_bits_per_sample = 16)
{
if (NULL == pcm_name || NULL == wav_name || 0 > dw_size ||
0 > dw_samples_per_sec || 0 > ui_bits_per_sample)
{
// 错误的参数
return -1;
}
FILE *fpS;
FILE *fpD;
fpS = fopen(pcm_name, "rb");
fpD = fopen(wav_name, "wb+");
if(fpS==NULL || fpD==NULL)
{
// 文件打开错误
return -2;
}
fseek(fpS, 0, SEEK_END);
long filelength = ftell(fpS);
int ret = 0;
ret = writeWaveHead(fpD, dw_size, dw_samples_per_sec, ui_bits_per_sample);
if (ret < 0)
{
// 文件头部写入错误
return -3;
}
ret = writeWaveBody(fpD,filelength);
if (ret < 0)
{
// 语音内容拼接错误
return -4;
}
fseek(fpS,44,SEEK_SET);
char buf[UNIT];
while(UNIT==fread(buf,1,UNIT,fpS))
{
fwrite(buf,1,UNIT,fpD);
}
fclose(fpS);
fclose(fpD);
return 1;
}
//void *createWaveHeader(unsigned long fileLength, short channel, int sampleRate, short bitPerSample)
//{
// struct wave_header *header = (wave_header *)malloc(sizeof(struct wave_header));
//
// if (header == NULL) {
// return NULL;
// }
//
// // RIFF
// header->riff[0] = 'R';
// header->riff[1] = 'I';
// header->riff[2] = 'F';
// header->riff[3] = 'F';
//
// // file length
// header->fileLength = fileLength + (44 - 8);
//
// // WAVE
// header->wavTag[0] = 'W';
// header->wavTag[1] = 'A';
// header->wavTag[2] = 'V';
// header->wavTag[3] = 'E';
//
// // fmt
// header->fmt[0] = 'f';
// header->fmt[1] = 'm';
// header->fmt[2] = 't';
// header->fmt[3] = ' ';
//
// header->size = 16;
// header->formatTag = 1;
// header->channel = channel;
// header->sampleRate = sampleRate;
// header->bitPerSample = bitPerSample;
// header->blockAlign = (short)(header->channel * header->bitPerSample / 8);
// header->bytePerSec = header->blockAlign * header->sampleRate;
//
// // data
// header->data[0] = 'd';
// header->data[1] = 'a';
// header->data[2] = 't';
// header->data[3] = 'a';
//
// // data size
// header->dataSize = fileLength;
//
// return header;
//}
| true |
0c29fdd896321a40a2888078c113001523bad456
|
C++
|
BigSirj1993/AP_Assignment2_2021_NickSirju-TextAdventure-
|
/AP_Assignment2_2021_NickSirju(TextAdventure)/Enemy.cpp
|
UTF-8
| 906 | 3.015625 | 3 |
[] |
no_license
|
#include "Enemy.h"
//Done
Enemy::Enemy(int level)
{
this->level = level;
this->healthMax = rand() % (level * 10) + (level * 2);
this->health = this->healthMax;
this->damageMax + this->level * 2;
this->damageMin + this->level * 1;
this->dropChance = rand() % 100 + 1;
this->defense = rand() % level * 5 + 1;
this->aim = rand() % level * 5 + 1;
}
Enemy::~Enemy()
{
}
string Enemy::getAsString()const
{
return "Level: " + to_string(this->level) + "\n" +
"Health: " + to_string(this->health) + " / " + to_string(this->healthMax) + "\n" +
"Damage: " + to_string(this->damageMin) + " - " + to_string(this->damageMax) + "\n" +
"Defense: " + to_string(this->defense) + "\n" +
"Aim" + to_string(this->aim) + "\n" +
"Drop chance: " + to_string(this->dropChance) + "\n";
}
void Enemy::takeDamage(int damage)
{
this->health -= damage;
if (this->health <= 0)
{
this->health = 0;
}
}
| true |
8e32f97005cd4b2349c1680b27a763f468fac6c0
|
C++
|
abhiga/WebServer
|
/myhttpd.cpp
|
UTF-8
| 9,334 | 2.625 | 3 |
[] |
no_license
|
const char * usage =
" \n"
"myhttpd <port> for iterative server \n" "myhttpd -f <port> for server with fork/processes \n" "myhttpd -t <port> for server with multiple threads \n" "myhttpd -p <port> for server with pool of threads \n";
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <time.h>
#include <signal.h>
#include <sys/wait.h>
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
pthread_mutex_t m1;
void zombieHandler(int sig);
int QueueLength = 5;
// Processes time request
void processRequestAndClose(int socket);
void processTimeRequest( int socket );
void nonConcurrent (int masterSocket);
void threadConcurrent (int masterSocket);
void processConcurrent (int masterSocket);
void threadPoolConcurrent (int masterSocket);
int
main( int argc, char ** argv )
{
char cMode;
int port;
// Print usage if not enough arguments
if (argc == 3) {
//fprintf(stderr, argv[1]);
if(strcmp (argv[1], "-f") == 0) {
cMode = 'f';
}
else if(strcmp (argv[1], "-t") == 0) {
cMode = 't';
}
else if(strcmp (argv[1], "-p") == 0) {
cMode = 'p';
}
else {
fprintf( stderr, "%s", usage );
exit( -1 );
}
// Get the port from the arguments
port = atoi (argv[2]);
}
else if (argc == 2) {
cMode = 'n';
// Get the port from the arguments
port = atoi (argv[1]);
}
else {
fprintf( stderr, "%s", usage );
exit( -1 );
}
signal(SIGCHLD, zombieHandler);
// Set the IP address and port for this server
struct sockaddr_in serverIPAddress;
memset( &serverIPAddress, 0, sizeof(serverIPAddress) );
serverIPAddress.sin_family = AF_INET;
serverIPAddress.sin_addr.s_addr = INADDR_ANY;
serverIPAddress.sin_port = htons((u_short) port);
// Allocate a socket
int masterSocket = socket(PF_INET, SOCK_STREAM, 0);
if ( masterSocket < 0) {
perror("socket");
exit( -1 );
}
// Set socket options to reuse port. Otherwise we will
// have to wait about 2 minutes before reusing the sae port number
int optval = 1;
int err = setsockopt(masterSocket, SOL_SOCKET, SO_REUSEADDR,
(char *) &optval, sizeof( int ) );
// Bind the socket to the IP address and port
int error = bind( masterSocket,
(struct sockaddr *)&serverIPAddress,
sizeof(serverIPAddress) );
if ( error ) {
perror("bind");
exit( -1 );
}
// Put socket in listening mode and set the
// size of the queue of unprocessed connections
error = listen( masterSocket, QueueLength);
if ( error ) {
perror("listen");
exit( -1 );
}
if (cMode == 'n')
nonConcurrent (masterSocket);
else if (cMode == 't') {
threadConcurrent (masterSocket);
}
else if (cMode == 'f') {
processConcurrent (masterSocket);
}
else if (cMode == 'p') {
threadPoolConcurrent (masterSocket);
}
}
void nonConcurrent (int masterSocket) {
fprintf(stderr, "launching server in iterative mode\n");
while ( 1 ) {
// Accept incoming connections
struct sockaddr_in clientIPAddress;
int alen = sizeof( clientIPAddress );
int slaveSocket = accept( masterSocket,
(struct sockaddr *)&clientIPAddress,
(socklen_t*)&alen);
if ( slaveSocket < 0 ) {
continue;
perror( "accept" );
exit( -1 );
}
// Process request.
processTimeRequest( slaveSocket );
// Close socket
close( slaveSocket );
}
}
void threadConcurrent (int masterSocket) {
fprintf(stderr, "launching server with Threads\n");
while ( 1 ) {
// Accept incoming connections
struct sockaddr_in clientIPAddress;
int alen = sizeof( clientIPAddress );
pthread_mutex_lock(&m1);
int slaveSocket = accept( masterSocket,
(struct sockaddr *)&clientIPAddress,
(socklen_t*)&alen);
pthread_mutex_unlock(&m1);
if ( slaveSocket < 0 ) {
continue;
perror( "accept" );
exit( -1 );
}
// Process request.
pthread_t t;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
pthread_create(&t, &attr, (void * (*)(void *)) processRequestAndClose,
(void *) slaveSocket);
}
}
void processConcurrent (int masterSocket) {
fprintf(stderr, "launching server with Processes\n");
while (1) {
// Accept incoming connections
struct sockaddr_in clientIPAddress;
int alen = sizeof( clientIPAddress );
int slaveSocket = accept( masterSocket,
(struct sockaddr *)&clientIPAddress,
(socklen_t*)&alen);
if ( slaveSocket < 0 ) {
continue;
perror( "accept" );
exit( -1 );
}
int ret = fork();
if (ret == 0) {
// Process request.
processTimeRequest(slaveSocket);
exit(1);
}
else if (ret < 0) {
perror("fork");
exit(-1);
}
// Close socket
close( slaveSocket );
}
}
void loopthread (int masterSocket) {
while (1) {
struct sockaddr_in clientIPAddress;
int alen = sizeof(clientIPAddress);
pthread_mutex_lock(&m1);
int slaveSocket = accept(masterSocket,
(struct sockaddr *)&clientIPAddress,
(socklen_t *)&alen);
pthread_mutex_unlock(&m1);
if (slaveSocket < 0) {
continue;
perror("accept");
exit(-1);
}
// Handles the request and closes the socket
processRequestAndClose(slaveSocket);
}
}
void threadPoolConcurrent (int masterSocket) {
fprintf(stderr, "launching server with Pool of Threads\n");
pthread_t t[4];
for (int i = 0; i < 4; i++) {
pthread_create(&t[i], NULL, (void * (*)(void *))loopthread,
(void *) masterSocket);
}
// Make use of main thread to also handle requests
loopthread(masterSocket);
}
void processRequestAndClose(int slaveSocket ) {
processTimeRequest( slaveSocket );
// Close socket
close( slaveSocket );
}
void
processTimeRequest( int fd )
{
int n;
unsigned char newChar, oldChar = 0;
int gotGet = 0;
const int MAXSIZE = 1024;
char *docpath = new char[MAXSIZE];
char *curr_string = new char[MAXSIZE];
int curr_string_len = 0;
int docpath_seen = 0;
memset(docpath, 0, MAXSIZE);
memset(curr_string, 0, MAXSIZE);
while (n = read(fd, &newChar, sizeof(newChar))) {
curr_string_len++;
if (newChar == ' ') {
if (gotGet == 0) {
gotGet = 1;
} else if (docpath_seen == 0) {
curr_string[curr_string_len - 1] = 0;
strcpy(docpath, curr_string + 4);
docpath_seen = 1;
}
} else if (oldChar == '\r' && newChar == '\n') {
break;
} else {
oldChar = newChar;
curr_string[curr_string_len - 1] = newChar;
}
}
//fprintf(stderr,"url hit\n");
delete curr_string;
int max = 1024;
char *buff = (char *)malloc(max * sizeof(char));
int numRead = 0;
while ((n = read(fd, &newChar, sizeof(newChar)))) {
buff[numRead++] = newChar;
// Resize buffer if needed
// Read until two consecutive <cr><lf> are read
if (numRead >= max) {
max = 2 * max;
buff = (char *) realloc (buff, max);
}
if (oldChar == '\r' && newChar == '\n') {
if (numRead > 3) {
if (buff[numRead - 3] == '\n' && buff[numRead - 4] == '\r') {
break;
}
}
}
}
free(buff);
//fprintf(stderr,"abhiga\n");
char *cwd = {0};
cwd = getcwd(cwd, 256);
if ((strncmp (docpath, "/icons", strlen("/icons")) == 0) || (strncmp(docpath, "/htdocs", strlen("/htdocs")) == 0) || (strncmp(docpath, "/cgi-bin", strlen("/cgi-bin")) == 0)) {
strcat(cwd, "/http-root-dir");
strcat(cwd, docpath);
}
else if (strcmp(docpath, "/") == 0) {
strcat(cwd, "/http-root-dir/htdocs/index.html");
}
else {
strcat(cwd, "/http-root-dir/htdocs");
strcat(cwd, docpath);
}
//fprintf(stderr,"%s\n", cwd);
char content_Type[1000];
memset(content_Type, 0, 1000);
int gif = 0;
if (strstr (cwd, ".html") != 0) {
strcpy (content_Type, "text/html");
}
else if (strstr (cwd, ".gif") != 0) {
strcpy (content_Type, "image/gif");
gif = 1;
}
else {
strcpy (content_Type, "text/plain");
}
//fprintf(stderr, "%s\n", content_Type);
FILE * file;
if (gif) {
file = fopen(cwd, "rb");
}
else {
file = fopen(cwd, "r");
}
if (file <= 0) {
const char *notFound = "File not found.";
write(fd, "HTTP/1.0", strlen("HTTP/1.0"));
write(fd, " ", 1);
write(fd, "404", 3);
write(fd, "File", 4);
write(fd, " ", 1);
write(fd, "Not", 3);
write(fd, " ", 1);
write(fd, "Found,", 6);
write(fd, "\r\n", 2);
write(fd, "Server:", 7);
write(fd, " ", 1);
write(fd, "CS 252 lab5", strlen("CS 252 lab5"));
write(fd, "\r\n", 2);
write(fd, "Content-type:", 13);
write(fd, " ", 1);
write(fd, "text/plain", strlen("text/plain"));
write(fd, "\r\n", 2);
write(fd, "\r\n", 2);
write(fd, notFound, strlen(notFound));
}
else {
write(fd, "HTTP/1.0", strlen("HTTP/1.0"));
write(fd, " ", 1);
write(fd, "200 ", 4);
write(fd, "Document", 8);
write(fd, " ", 1);
write(fd, "follows", 7);
write(fd, "\r\n", 2);
write(fd, "Server:", 7);
write(fd, " ", 1);
write(fd, "CS 252 lab5", strlen("CS 252 lab5"));
write(fd, "\r\n", 2);
write(fd, "Content-Type:", strlen("Content-Type:"));
write(fd, " ", 1);
write(fd, content_Type, strlen(content_Type));
write(fd, "\r\n", 2);
write(fd, "\r\n", 2);
int count = 0;
char ch;
int f = fileno(file);
while (count = read(f, &ch, sizeof(ch))) {
write(fd, &ch, sizeof(ch));
}
fclose (file);
}
}
void zombieHandler(int sig) {
while (waitpid((pid_t)(-1), 0, WNOHANG) > 0) {}
}
| true |
ed89f60b5fc7755b5c8444a32f2b5da7d7fedadb
|
C++
|
yotamra/AIProject
|
/include/image.h
|
UTF-8
| 12,459 | 2.8125 | 3 |
[] |
no_license
|
#ifndef H_IMAGEPP
#define H_IMAGEPP
#include <Windows.h>
#include <cv.hpp>
#include <cxcore.h>
#include <cvaux.h>
#include <boost/shared_ptr.hpp>
#include <vector>
#include <string>
#include "prims.h"
typedef unsigned char byte;
namespace CPP {
using cv::Mat;
typedef std::pair<int,int> int_pair;
inline void calculate_range(double* hist, int_pair& range, double edge)
{
double sum=0;
for(range.first=0;range.first<256;++range.first)
{
sum+=hist[range.first];
if (sum>=edge) break;
}
sum=0;
for(range.second=255;range.second>0;--range.second)
{
sum+=hist[range.second];
if (sum>=edge) break;
}
}
inline unsigned char* get_row(Mat* image, int row)
{
return (unsigned char*)(image->data + row*image->step);
}
class CPPImage
{
cv::Mat* m_Image;
bool m_Failed;
static CvSize size(unsigned w, unsigned h)
{
CvSize sz;
sz.width=w;
sz.height=h;
return sz;
}
public:
CPPImage(unsigned w, unsigned h, int channels,int depth = CV_8U)
: m_Image(new Mat(size(w,h),depth,channels)),
m_Failed(false)
{}
CPPImage(const char* filename)
: m_Image(new Mat(cv::imread(filename))),
m_Failed(false)
{
if (!m_Image) m_Failed=true;
}
CPPImage(const std::string& filename)
: m_Image(new Mat(cv::imread(filename.c_str()))),
m_Failed(false)
{
if (!m_Image) m_Failed=true;
}
CPPImage(Mat* img)
: m_Image(new Mat(img->clone())),
m_Failed(false)
{}
~CPPImage(){}
bool failed() const { return m_Failed; }
CPPImage* clone()
{
CPPImage* img=new CPPImage(m_Image);
return img;
}
Mat* get() { return m_Image; }
void save(const std::string& filename)
{
cv::imwrite(filename.c_str(),*m_Image);
}
void save(const char* filename)
{
cv::imwrite(filename,*m_Image);
}
unsigned get_pitch()
{
return m_Image->step;
}
inline unsigned char* get_row(int row, int x=0)
{
unsigned char* ptr=CPP::get_row(m_Image,row);
ptr+=x*get_channels();
return ptr;
}
inline const unsigned char* get_row(int row, int x=0) const
{
const unsigned char* ptr=CPP::get_row(m_Image,row);
ptr+=x*get_channels();
return ptr;
}
unsigned get_width() const { return m_Image->cols; }
unsigned get_height() const { return m_Image->rows; }
unsigned get_channels() const { return m_Image->channels(); }
Rect get_rect() const { return Rect(0,0, m_Image->cols, m_Image->rows); }
bool calculate_histogram(double* hist)
{
if (get_channels()!=1) return false;
std::fill_n(hist,256,0);
unsigned w=get_width(),h=get_height(),x,y;
for(y=0;y<h;++y)
{
const unsigned char* row=get_row(y);
for(x=0;x<w;++x)
hist[row[x]]+=1.0;
}
return true;
}
};
typedef boost::shared_ptr<CPPImage> Image;
inline Image load(const std::string& filename) { return Image(new CPPImage(filename)); }
inline Image load(const char* filename) { return Image(new CPPImage(filename)); }
inline Image attach(Mat* image) { return Image(new CPPImage(image)); }
template<class T>
class CPPMatrix
{
Mat* m_Matrix;
static int get_type(const char&) { return CV_8U; }
static int get_type(const int&) { return CV_32S; }
static int get_type(const float&) { return CV_32F; }
static int get_type(const double&) { return CV_64F; }
public:
CPPMatrix(int w, int h)
: m_Matrix(new Mat(h,w,get_type(T())))
{}
~CPPMatrix(){}
const Mat* get() const { return m_Matrix; }
Mat* get() { return m_Matrix; }
void fill(const T& value)
{
*m_Matrix = value;
}
void set(int x, int y, const T& value)
{
m_Matrix->at<T>(x, y) = value;
}
};
inline Image odd_rows(Image image)
{
unsigned w=image->get_width(),h=image->get_height(),ch=image->get_channels();
Image target(new CPPImage(w,h/2,ch));
for(unsigned y=1;y<h;y+=2)
{
const unsigned char* src=image->get_row(y);
unsigned char* dst=target->get_row(y/2);
std::copy(src,src+w*ch,dst);
}
return target;
}
inline void paste(Image target, Image source, int ox, int oy)
{
int w=target->get_width(),h=target->get_height(),channels=target->get_channels();
int sw=source->get_width(),sh=source->get_height(),schannels=source->get_channels();
if (schannels!=channels) throw std::string("Channels mismatch in paste");
if ((ox+sw)>w || (oy+sh)>h) throw std::string("Image doesn't fit in paste");
int pitch=w*channels;
for(int y=oy;y<(oy+sh);++y)
{
unsigned char* row=target->get_row(y,ox);
const unsigned char* src=source->get_row(y-oy);
std::copy(src,src+sw*channels,row);
}
}
inline void and(Image a, Image b)
{
unsigned w = a->get_width(), h = a->get_height(), ch = a->get_channels();
if (w != b->get_width() || h != b->get_height() || ch != b->get_channels())
throw std::string("and: Images mismatch");
Image c(new CPPImage(w, h, ch));
cv::bitwise_and(*a->get(), *b->get(), *a->get());
}
inline Image or(Image a, Image b)
{
unsigned w=a->get_width(),h=a->get_height(),ch=a->get_channels();
if (w!=b->get_width() || h!=b->get_height() || ch!=b->get_channels())
throw std::string("and: Images mismatch");
Image c(new CPPImage(w,h,ch));
cv::bitwise_or(*a->get(),*b->get(),*c->get());
return c;
}
inline Image xor(Image a, Image b)
{
unsigned w=a->get_width(),h=a->get_height(),ch=a->get_channels();
if (w!=b->get_width() || h!=b->get_height() || ch!=b->get_channels())
throw std::string("and: Images mismatch");
Image c(new CPPImage(w,h,ch));
cv::bitwise_xor(*a->get(), *b->get(), *c->get());
return c;
}
inline void fill(Image image, unsigned char value)
{
*image->get() = value;
}
inline Image flip_vertical(Image image)
{
int w=image->get_width(),h=image->get_height(),n=image->get_channels();
Image target(new CPPImage(w,h,n));
flip(*image->get(), *target->get(), 0);
return target;
}
inline Image rotate_90(Image image, bool clockwise)
{
int w = image->get_width(), h = image->get_height(), n = image->get_channels();
Image target(new CPPImage(h, w, n));
flip(*image->get(), *target->get(), 1);
return target;
}
inline Image median_filter(Image image)
{
Image target(image->clone());
cv::medianBlur(*image->get(),*target->get(),3);
return target;
}
inline Image invert(Image image)
{
Image target(image->clone());
fill(target,255);
return xor(target,image);
}
// Output is set to 255 is 3x3 sum is >= mass
inline Image mass_filter(Image image, int mass)
{
unsigned w=image->get_width(),h=image->get_height(),ch=image->get_channels();
if (ch!=1)
throw std::string("mass_filter works on single channel images");
Image target(new CPPImage(w,h,ch));
fill(target,0);
for(unsigned y=1;y<(h-1);++y)
{
const byte* rows[3];
rows[0]=image->get_row(y-1);
rows[1]=image->get_row(y);
rows[2]=image->get_row(y+1);
byte* dst=target->get_row(y);
for(unsigned x=1;x<(w-1);++x)
{
int sum=int(rows[0][x-1])+int(rows[0][x])+int(rows[0][x+1])+
int(rows[1][x-1])+int(rows[1][x])+int(rows[1][x+1])+
int(rows[2][x-1])+int(rows[2][x])+int(rows[2][x+1]);
dst[x]=(sum>mass?255:0);
}
}
return target;
}
inline Image sobel(Image image, int xorder, int yorder, int apperture=3)
{
Image target(image->clone());
cv::Sobel(*image->get(),*target->get(), CV_8U, xorder,yorder,apperture);
return target;
}
inline Image laplace(Image& image, int apperture=1)
{
CPPImage* img = ((CPPImage*)image.get());
Mat* im2 = new Mat(cvGetSize(img->get()),
CV_8U, 1);
cv::Laplacian(*img->get(),*im2,CV_8U,apperture);
return Image(new CPPImage(im2));
}
inline Image scale_to(Image image, int w, int h, int interpolation=1)
{
if (w<1) w=1;
if (h<1) h=1;
Image target(new CPPImage(w,h,image->get_channels()));
cv::resize(*image->get(),*target->get(),cv::Size(w,h),0,0,interpolation);
return target;
}
inline Image dilate(Image image, int iter=1)
{
Image target(image->clone());
Mat element = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(4, 4));
cv::dilate(*image->get(),*target->get(),element,cv::Point(-1,-1),iter);
return target;
}
inline Image CannyWithBiliteral(const Image& image, int channels)
{
Image target(image->clone());
cv::bilateralFilter(*image->get(), *target->get(), 5, 80, 80);
//cv::namedWindow("Image:", CV_WINDOW_AUTOSIZE);
if (channels == 1)
{
//CFrameManager::displayImage(target);
//cv::imshow("Image:", *target->get());
//cv::waitKey(0);
cv::Canny(*target->get(), *target->get(), 30, 90);
}
if (channels == 3) {
Mat bgr[3]; //destination array
cv::split(*target->get(), bgr); //split source
cv::Canny(bgr[0], bgr[0], int(255/3), 255);
cv::Canny(bgr[1], bgr[1], int(255/3), 255);
cv::Canny(bgr[2], bgr[2], int(255/3), 255);
Mat mergedImage;
bitwise_or(bgr[0], bgr[1], mergedImage);
bitwise_or(mergedImage, bgr[2], mergedImage);
*target->get() = mergedImage;
//CFrameManager::displayImage(target);
//cv::imshow("Image:", *target->get());
//cv::waitKey(0);
// Wait for the user to press a key in the GUI window.
}
return target;
}
template<class T>
inline Image filter(const Image& image, const CPPMatrix<T>& matrix)
{
Image target(image->clone());
cv::filter2D(*image->get(), *target->get(),image->get()->depth(),*matrix.get());
return target;
}
inline Image threshold(const Image& image, double thres)
{
Image target(image->clone());
cv::threshold(*image->get(),*target->get(),thres,255, cv::THRESH_BINARY);
return target;
}
inline Image convert_to_gray(const Image& image)
{
if (image->get_channels()==1) return image;
Image target(new CPPImage(image->get_width(),image->get_height(),1));
cv::cvtColor(*image->get(),*target->get(),CV_RGB2GRAY);
return target;
}
inline Image convert_to_rgb(const Image& image)
{
if (image->get_channels()==3) return image;
Image target(new CPPImage(image->get_width(),image->get_height(),3));
cv::cvtColor(*image->get(),*target->get(),CV_GRAY2RGB);
return target;
}
//written by Assaf and Hila
inline Image convert_bgr_to_hsi(const Image& image)
{
Image target(new CPPImage(image->get_width(),image->get_height(),3));
cv::cvtColor(*image->get(), *target->get(),CV_BGR2HSV);
return target;
}
inline void imageAdd(const Image& image1,const Image& image2,const Image& dst)
{
cvAdd(((CPPImage*)image1.get())->get(),
((CPPImage*)image2.get())->get(),
((CPPImage*)dst.get())->get());
}
inline void imagePow(const Image& image,const Image& dst,double power)
{
cvPow(((CPPImage*)image.get())->get(),((CPPImage*)dst.get())->get(),power);
}
inline double getVal(const Image& image,int i,int j)
{
cv::Scalar S(((CPPImage*)image.get())->get()->at<uchar>(j, i));
return S.val[0];
}
inline void setVal(const Image& image,int i,int j,double val)
{
((CPPImage*)image.get())->get()->at<uchar>(i, j) = val;
}
inline Image abs_diff(const Image& imga, const Image& imgb)
{
Image target(imga->clone());
cv::absdiff(*imga->get(),*imgb->get(),*target->get());
return target;
}
inline Rect bounding_rect(const Image& img, byte bg=0)
{
unsigned x,y,w=img->get_width(),h=img->get_height(),ch=img->get_channels();
Rect r(w,h,0,0);
for(y=0;y<h;++y)
{
const byte* row=img->get_row(y);
for(x=0;x<w;++x)
{
if (row[x]!=bg)
{
r.l=Min(r.l,x);
r.t=Min(r.t,y);
r.r=Max(r.r,x+1);
r.b=Max(r.b,y+1);
}
}
}
return r;
}
inline Image crop(const Image& img, const cv::Rect& r)
{
Mat src=*img->get();
Mat* dst = new Mat(src(r).clone());
return Image(new CPPImage(dst));
}
inline Image copy(const Image& img)
{
return crop(img,cv::Rect(0,0,img->get_width(),img->get_height()));
}
inline void scale_color_space(Image& image, int_pair& range)
{
unsigned w=image->get_width(),h=image->get_height(),x,y;
unsigned n=w*image->get_channels();
if (range.second==range.first) return;
double mult=256.0/(range.second-range.first);
for(y=0;y<h;++y)
{
unsigned char* row=image->get_row(y);
for(x=0;x<n;++x)
{
double v=row[x];
v-=range.first;
v*=mult;
row[x]=byte(Max(0.0,Min(v,255.0)));
}
}
}
inline void scale_color_space(Image& image, double tail=0.01)
{
Image gray=convert_to_gray(image);
double hist[256];
gray->calculate_histogram(hist);
int_pair range;
calculate_range(hist,range,(gray->get_width()*gray->get_height())*tail);
scale_color_space(image,range);
}
} // namespace CPP
#endif // H_IMAGEPP
| true |
5313a6663ba0b69ca1173cc984a3da08c9f1b0a4
|
C++
|
raf-iq/Uva-solved-problems
|
/Accepted C++ codes/uva12157.cpp
|
UTF-8
| 707 | 2.765625 | 3 |
[] |
no_license
|
#include<bits/stdc++.h>
#define ll long long int
using namespace std;
int main()
{
int T,test=1;
cin >> T;
while(T--){
int n;
cin >> n;
int mile=0,juice=0;
for(int i=0; i<n; ++i){
int nn;
cin >> nn;
mile+=(nn/30+1);
juice+=(nn/60+1);
}
mile*=10;
juice*=15;
cout << "Case " << test++ << ": ";
if(mile < juice){
cout << "Mile " << mile << endl;
}
else if(mile > juice){
cout << "Juice " << juice << endl;
}
else
cout << "Mile Juice " << mile << endl;
}
return 0;
}
| true |
4db4c84bd2cb97613e4921e79465590fa0088097
|
C++
|
Vegtam/Roguelike
|
/src/Random.cpp
|
UTF-8
| 426 | 3 | 3 |
[] |
no_license
|
#include <cstdlib>
#include <ctime>
#include "Random.hpp"
Random* Random::rnd = NULL;
bool Random::init = false;
Random::Random()
{
srand(time(NULL));
init = true;
}
Random* Random::get()
{
if(!init)
{
rnd = new Random();
}
return rnd;
}
int Random::randInt()
{
return rand();
}
float Random::randFloat(float max)
{
int r = randInt();
float s = (float)(r & 0x7fff)/(float)0x7fff;
return (s * max);
}
| true |
9770107752b571e5e700f363d6e471ef723f4de9
|
C++
|
sudo-logic/ballistica
|
/src/ballistica/scene_v1/node/locator_node.h
|
UTF-8
| 1,921 | 2.625 | 3 |
[
"MIT"
] |
permissive
|
// Released under the MIT License. See LICENSE for details.
#ifndef BALLISTICA_SCENE_V1_NODE_LOCATOR_NODE_H_
#define BALLISTICA_SCENE_V1_NODE_LOCATOR_NODE_H_
#include <string>
#include <vector>
#include "ballistica/scene_v1/node/node.h"
namespace ballistica::scene_v1 {
class LocatorNode : public Node {
public:
static auto InitType() -> NodeType*;
explicit LocatorNode(Scene* scene);
void Draw(base::FrameDef* frame_def) override;
auto position() const -> std::vector<float> { return position_; }
void SetPosition(const std::vector<float>& vals);
auto visibility() const -> bool { return visibility_; }
void set_visibility(bool val) { visibility_ = val; }
auto size() const -> std::vector<float> { return size_; }
void SetSize(const std::vector<float>& vals);
auto color() const -> std::vector<float> { return color_; }
void SetColor(const std::vector<float>& vals);
auto opacity() const -> float { return opacity_; }
void set_opacity(float val) { opacity_ = val; }
auto draw_beauty() const -> bool { return draw_beauty_; }
void set_draw_beauty(bool val) { draw_beauty_ = val; }
auto getDrawShadow() const -> bool { return draw_shadow_; }
void setDrawShadow(bool val) { draw_shadow_ = val; }
auto getShape() const -> std::string;
void SetShape(const std::string& val);
auto getAdditive() const -> bool { return additive_; }
void setAdditive(bool val) { additive_ = val; }
private:
enum class Shape { kLocator, kBox, kCircle, kCircleOutline };
Shape shape_ = Shape::kLocator;
bool additive_ = false;
std::vector<float> position_ = {0.0f, 0.0f, 0.0f};
std::vector<float> size_ = {1.0f, 1.0f, 1.0f};
std::vector<float> color_ = {1.0f, 1.0f, 1.0f};
bool visibility_ = true;
float opacity_ = 1.0f;
bool draw_beauty_ = true;
bool draw_shadow_ = true;
};
} // namespace ballistica::scene_v1
#endif // BALLISTICA_SCENE_V1_NODE_LOCATOR_NODE_H_
| true |
93ebe80feee8366c377662f19835990b0f5d6c44
|
C++
|
91khr/91khr.github.io
|
/dev/helpers.hpp
|
UTF-8
| 2,005 | 3.09375 | 3 |
[] |
no_license
|
#ifndef HELPERS_HPP_INCLUDED
#define HELPERS_HPP_INCLUDED
#include <cstdio>
#include <cstdarg>
#include <string>
#include <unordered_map>
#include <chrono>
namespace chrono = std::chrono;
struct FileIO
{
FILE *handle;
FileIO() : handle(nullptr) {}
FileIO(const FileIO &) = delete;
FileIO(FileIO &&) = delete;
FileIO &operator=(const FileIO &) = delete;
FileIO &operator=(FileIO &&) = delete;
FileIO(FILE *f) : handle(f) {}
FileIO(const std::string &fname, const char *type) : handle(fopen(fname.c_str(), type)) {}
~FileIO() { close(); }
void close()
{
if (handle)
fclose(handle);
handle = nullptr;
}
void reopen(const std::string &fname, const char *type)
{
if (handle)
fclose(handle);
handle = fopen(fname.c_str(), type);
}
int printf(const char *fmt, ...)
{
va_list arg;
va_start(arg, fmt);
return vfprintf(handle, fmt, arg);
}
int scanf(const char *fmt, ...)
{
va_list arg;
va_start(arg, fmt);
return vfscanf(handle, fmt, arg);
}
std::string getline()
{
thread_local struct LineBuf {
char *data = nullptr;
size_t len = 0;
~LineBuf() { free(data); }
} buf;
::getline(&buf.data, &buf.len, handle);
std::string res(buf.data);
res.pop_back(); // Trim the trailing '\n'
return res;
}
bool eof() const { return feof(handle); }
};
namespace helper
{
inline std::unordered_map<std::string, chrono::system_clock::time_point> read_dates()
{
std::unordered_map<std::string, chrono::system_clock::time_point> res;
auto f = FileIO("timestamp.txt", "r");
while (!f.eof())
{
long long time;
fscanf(f.handle, "%lld ", &time);
res[f.getline()] = chrono::system_clock::time_point(chrono::seconds(time));
}
return res;
}
} // End namespace helper
#endif // HELPERS_HPP_INCLUDED
| true |
72a38c7bfd777a23d8c5ac5b30274cd3c503a515
|
C++
|
zhichengzhang1995/16
|
/lab04/countEvens.cpp
|
UTF-8
| 299 | 2.84375 | 3 |
[] |
no_license
|
#include "arrayFuncs.h"
#include <cstdlib>
#include <iostream>
int countEvens(int a[], int size) {
int c = 0;
int x;
for (int i=0; i<size; i++)
{
x = a[i];
if (x < 0)
x = x * (-1);
if (x == 0)
c++;
else if (x % 2 == 0)
c++;
}
return c; // STUB! Replace with correct code.
}
| true |
a40fb3b5f3ee84c3bf6e95ead06fcd8685469f45
|
C++
|
ProjectViman/viman
|
/viman_control/src/utility/vm_sensor_data.cpp
|
UTF-8
| 1,670 | 2.515625 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
#include <ros/ros.h>
#include <geometry_msgs/PointStamped.h>
#include <sensor_msgs/Imu.h>
#include "imumath_brief.h"
// If set displays quaternion read by IMU
#define SHOW_QUAT 0
Quaternion q;
Cardan angles;
double height;
void HeightCallbck(const geometry_msgs::PointStamped& height_){
height = height_.point.z;
}
void ImuCallbck(const sensor_msgs::Imu& imu_){
q.w = imu_.orientation.w;
q.x = imu_.orientation.x;
q.y = imu_.orientation.y;
q.z = imu_.orientation.z;
angles = get_cardan_angles(q);
}
int main(int argc, char **argv){
ros::init(argc,argv,"vm_sensor_data");
ros::NodeHandle node;
ros::Subscriber height_subs_ = node.subscribe("/viman/height",500,HeightCallbck);
ros::Subscriber imu_subs_ = node.subscribe("/viman/imu",500,ImuCallbck);
if( height_subs_.getTopic() != "")
ROS_INFO("found altimeter height topic");
else
ROS_WARN("cannot find altimeter height topic!");
if( imu_subs_.getTopic() != "")
ROS_INFO("found imu topic");
else
ROS_WARN("cannot find imu topic!");
ros::Rate rate(20);
while(ros::ok()){
std::cout << "Time (in secs): " << ros::Time::now().toSec() << std::endl
<< "Height (in m): " << height << std::endl
<< "Yaw (deg): " << angles.yaw << std::endl
<< "Pitch (deg): " << angles.pitch << std::endl
<< "Roll (deg): " << angles.roll << std::endl;
#if SHOW_QUAT
std::cout << "qx: " << q.x << std::endl
<< "qy: " << q.y << std::endl
<< "qz: " << q.z << std::endl
<< "qw: " << q.w << std::endl;
#endif
std::cout << "---------" << std::endl << std::endl;
ros::spinOnce();
rate.sleep();
}
return 0;
}
| true |
df5d07451ba0e7fce2782a02a7488f15cb03997f
|
C++
|
leisheyoufu/study_exercise
|
/algorithm/leetcode/69_sqrt_x/main2.cpp
|
UTF-8
| 1,017 | 3.890625 | 4 |
[] |
no_license
|
/*
69. Sqrt(x)
Implement int sqrt(int x).
Compute and return the square root of x.
*/
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
class Solution
{
public:
int mySqrt(int x)
{
if(x <=0) {
return 0;
}
int left = 1;
int right = x;
while(left <= right) {
int mid = left + (right - left)/2;
unsigned long long val = (unsigned long long)mid *mid;
if( val == x) {
return mid;
}
if( val < x && (unsigned long long)(mid+1) * (mid+1) >x) {
return mid;
}
if(val < x) {
left = mid+1;
} else {
right = mid-1;
}
}
return 0;
}
};
int main()
{
Solution sln;
cout << sln.mySqrt(3) << endl; // 1
cout << sln.mySqrt(8) << endl; // 2
cout << sln.mySqrt(2147395599) << endl;
system("pause");
return 0;
}
| true |
df7b936873e6abde55b1f2fc99a8e90b59c0ac83
|
C++
|
DemjanGolubovski/Qt_Project
|
/C++/Vezbi_09_Site_Zadaci/Matrica.cpp
|
UTF-8
| 4,862 | 3.3125 | 3 |
[] |
no_license
|
#include <iostream>
#include <cassert>
#include "Matrica.h"
using namespace std;
// Constructor
Matrica::Matrica(int red, int kol){
redici=red;
koloni=kol;
matrica=new int[red*kol];
assert(matrica!=0);
for(int i=0; i<red*kol; i++){
matrica[i]=0;
}
}
// Constructor
Matrica::Matrica(int red, int kol, int *mat){
redici=red;
koloni=kol;
matrica=new int[red*kol];
assert(matrica!=0);
for(int i=0; i<red*kol; i++){
matrica[i]=mat[i];
}
}
// Copy construcotr
Matrica::Matrica(const Matrica &m): redici(m.redici), koloni(m.koloni){
matrica=new int[redici*koloni];
assert(matrica!=0);
for(int i=0; i<redici*koloni; i++){
matrica[i]=m.matrica[i];
}
}
// Destructor
Matrica::~Matrica(){
delete [] matrica;
}
const Matrica &Matrica::operator=(const Matrica &m){
if(&m!=this){
if(redici!=m.redici && koloni!=m.koloni){
delete [] matrica;
redici=m.redici;
koloni=m.koloni;
matrica=new int[redici*koloni];
assert(matrica!=0);
}
for(int i=0; i<redici*koloni; i++){
matrica[i]=m.matrica[i];
}
}
return *this;
}
ostream &operator<<(ostream &output, const Matrica &m){
output<<"["<<m.redici<<", "<<m.koloni<<"]"<<endl;
for(int i=0; i<m.redici*m.koloni; i++){
output<<m.matrica[i];
if((i+1)%m.koloni==0)
output<<endl;
else
output<<" ";
}
return output;
}
istream &operator>>(istream &input, Matrica &m){
for(int i=0; i<m.redici*m.koloni; i++)
input>>m.matrica[i];
return input;
}
int &Matrica::operator[](int index){ //left side
assert(index>=0 && index<(redici*koloni));
return matrica[index];
}
const int &Matrica::operator[](int index) const{ //right side
assert(index>=0 && index<(redici*koloni));
return matrica[index];
}
bool Matrica::operator==(const Matrica &m) const{
if(redici==m.redici && koloni==m.koloni)
{
for(int i=0; i<redici*koloni; i++){
if(matrica[i]!=m.matrica[i])
return false;
}
return true;
}
return false;
}
bool Matrica::operator!=(const Matrica &m) const{
return !(*this==m);
}
Matrica Matrica::operator+(const Matrica &m) const{
assert(redici==m.redici && koloni==m.koloni);
Matrica tmpObj(redici, koloni);
for(int i=0; i<redici*koloni; i++)
tmpObj.matrica[i]=matrica[i]+m.matrica[i];
return tmpObj;
}
Matrica Matrica::operator+(const int broj) const{
Matrica tmpObj(redici, koloni);
for(int i=0; i<redici*koloni; i++)
tmpObj.matrica[i]=matrica[i]+broj;
return tmpObj;
}
Matrica operator+(const int broj,const Matrica &m){
Matrica tmpObj(m.redici, m.koloni);
for(int i=0; i<m.redici*m.koloni; i++)
tmpObj.matrica[i]=m.matrica[i]+broj;
return tmpObj;
}
Matrica Matrica::operator-(const Matrica &m) const{
assert(redici==m.redici && koloni==m.koloni);
Matrica tmpObj(redici, koloni);
for(int i=0; i<redici*koloni; i++)
tmpObj.matrica[i]=matrica[i]-m.matrica[i];
return tmpObj;
}
Matrica Matrica::operator-(const int broj) const{
Matrica tmpObj(redici, koloni);
for(int i=0; i<redici*koloni; i++)
tmpObj.matrica[i]=matrica[i]-broj;
return tmpObj;
}
Matrica operator-(const int broj,const Matrica &m){
Matrica tmpObj(m.redici, m.koloni);
for(int i=0; i<m.redici*m.koloni; i++)
tmpObj.matrica[i]=-m.matrica[i]+broj;
return tmpObj;
}
Matrica Matrica::operator*(const Matrica &m) const{
assert(koloni==m.redici);
Matrica tmpObj(redici, m.koloni);
int index=0;
while(index<(redici*m.koloni)){
int mat_1=0, mat_2=0;
int tmpRed=index/m.koloni;
int tmpKol=index%m.koloni;
int suma=0;
while(mat_1<(redici*koloni) && mat_2<(m.koloni*m.redici)){
if(mat_1/koloni==tmpRed && mat_2%koloni==tmpKol){
suma=suma+matrica[mat_1]*m.matrica[mat_2];
mat_1++;
mat_2++;
}
else if(mat_1/koloni!=tmpRed && mat_2%koloni!=tmpKol){
mat_1++;
mat_2++;
}
else if(mat_1/koloni!=tmpRed && mat_2%koloni==tmpKol){
mat_1++;
}
else{
mat_2++;
}
}
tmpObj.matrica[index]=suma;
index++;
}
return tmpObj;
}
Matrica Matrica::operator*(const int broj) const{
Matrica tmpObj(redici, koloni);
for(int i=0; i<redici*koloni; i++)
tmpObj.matrica[i]=matrica[i]*broj;
return tmpObj;
}
Matrica operator*(const int broj,const Matrica &m){
Matrica tmpObj(m.redici, m.koloni);
for(int i=0; i<m.redici*m.koloni; i++)
tmpObj.matrica[i]=m.matrica[i]*broj;
return tmpObj;
}
| true |
9b42aa5ebb56fe9032f232baa99bbd402eb01712
|
C++
|
yclizhe/acm
|
/POJ/1953/1.cpp
|
UTF-8
| 318 | 2.953125 | 3 |
[] |
no_license
|
#include <iostream>
using namespace std;
int f(int n, int e) {
if(n==1)
return 1;
if(e==0)
return f(n-1,0)+f(n-1,1);
else
return f(n-1,0);
}
int main() {
int N;
cin >> N;
int count = 0;
while(N--) {
int n;
cin >> n;
cout << "Scenario #" << ++count << ":\n" << f(n,0)+f(n,1) << endl << endl;
}
}
| true |
caff4777c9da4fcf699bdeef0980c4cb1acc7723
|
C++
|
MHDante/CPS511_Assignment1
|
/Game.cpp
|
UTF-8
| 8,248 | 2.609375 | 3 |
[] |
no_license
|
#include "Game.h"
#include "Camera.h"
#include "GLUtils.h"
#include <iostream>
#include <thread>
#include "VarMesh.h"
Game* Game::instance = nullptr;
//=******************************************************************
//Scene Modelling Program
//=********************************************************************
Game::Game()
{
instance = this;
ScreenWidth = 1500;
ScreenHeight = 800;
windowName = "Scene Game";
centerX = ScreenWidth / 2;
centerY = ScreenHeight / 2;
}
void Game::setUpScene() {
rooms.push_back(new Room(Vector3(0,0,0), Vector3(32,4,32)));
rooms.push_back(rooms[0]->SpawnRoom(LEFT));
rooms.push_back(rooms[1]->SpawnRoom(FORWARD));
rooms.push_back(rooms[1]->SpawnRoom(BACK));
rooms.push_back(rooms[3]->SpawnRoom(BACK));
player = new Player(this);
player->setPosition(Vector3(0.0, 0, 0.0));
player->turnPlayer(0);
mainCamera->fovY = 60.0f;
mainCamera->nearZ = 1.0f;
mainCamera->farZ = 100;
mainCamera->Follow(player);
mesh = new VarMesh("megaman.obj");
mesh->setPosition(Vector3(0.0f, -1.3f, 0.0f));
mesh->setScale(Vector3(0.2f, 0.2f, 0.2f));
recenterMouse();
glutSetCursor(GLUT_CURSOR_NONE);
loadTextures();
for (int i = 0; i < initialEnemies; i++)
{
spawnEnemy();
}
}
void Game::display(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
// Set up the camera
mainCamera->display();
// Draw all cubes (see CubeMesh.h)
for (auto& c : cubes) c->draw();
for (auto& r : rooms) r->draw();
for (auto& l : lines) l.Draw();
for (auto& b : bullets)b->draw();
for (auto& r : robots)r->draw();
player->draw();
char buff[40];
snprintf(buff, sizeof(buff), "Kills: %d Remaining: %d Health: %d", kills, robots.size(), player->health);
drawText(buff, 40, 10, 10);
if (lostGame)
{
string s = "YOU LOST! Press F1 to restart.";
drawText(s.data(), s.length(), 130, 100);
}
else if (wonGame)
{
string s = "YOU WIN! Press F1 to restart.";
drawText(s.data(), s.length(), 130, 100);
}
glutSwapBuffers();
}
Vector3 pos = Vector3(0, 0, 0);
// Mouse button callback - use only if you want to
void Game::mouse(int button, int state, int xMouse, int yMouse)
{
currentButton = button;
switch (button)
{
case GLUT_LEFT_BUTTON:
if (state == GLUT_DOWN)
{
player->spawnBullet();
//if (currentAction == SELECT || currentAction == MULTIPLESELECT) {
Ray ray = mainCamera->ScreenToWorldRay(xMouse, yMouse);
lines.clear();
for (auto& c : cubes) {
Vector3 hit = c->Intersects(ray);
if (hit.isValid()) {
}
}
}
break;
case GLUT_RIGHT_BUTTON:
if (state == GLUT_DOWN)
{
;
}
break;
default:
break;
}
glutPostRedisplay();
}
// Mouse motion callback - use only if you want to
void Game::mouseMotionHandler(int xMouse, int yMouse)
{
//printf("%d :: %d\n", xMouse, yMouse);
int xdiff = centerX - xMouse;
if (xdiff != 0) {
player->turnPlayer(xdiff);
recenterMouse();
}
if (currentButton == GLUT_LEFT_BUTTON)
{
;
}
glutPostRedisplay();
}
void Game::UpdateConsole() {
while (true) {
std::this_thread::sleep_for(std::chrono::milliseconds(500));
system("cls");
std::cout << "Press f1 to spawn a block." << std::endl;
std::cout << "Scale : S | Translate : T | Rotate : R | Extrude : E | Raise : H |" << std::endl;
std::cout << "Select : C | MultiSelect : + | Deselect : - | Delete : Del | Quit : Esc |" << std::endl;
}
}
// Handles input from the keyboard, non-arrow keys
void Game::keyboard(unsigned char key, int x, int y)
{
switch (key)
{
case 'w': upDown.x = 1; break;
case 's': upDown.y = -1; break;
case 'd': rightLeft.x = 1; break;
case 'a': rightLeft.y = -1; break;
case 't':
break;
case 27: exit(0); break; // esc
case 127://del
break;
case ' ':break; //spacebar
}
glutPostRedisplay();
}
void Game::functionKeys(int key, int x, int y)
{
/*switch (key) {
case GLUT_KEY_F1: {
}
case GLUT_KEY_UP: upDown.x = 1; break;
case GLUT_KEY_DOWN: upDown.y = -1; break;
case GLUT_KEY_RIGHT: rightLeft.x = 1; break;
case GLUT_KEY_LEFT: rightLeft.y = -1; break;
}
glutPostRedisplay();
*/
}
void Game::restart()
{
for(auto& r : robots)
{
delete r;
}
robots.clear();
for (int i = 0; i < initialEnemies; i++)
{
spawnEnemy();
}
wonGame = false;
lostGame = false;
player->setPosition(Vector3(0.0, 0, 0.0));
player->setRotation(Vector3(0.0, 0, 0.0));
kills = 0;
player->health = player->maxHealth;
}
void Game::keyboardRelease(unsigned char key, int x, int y)
{
switch (key) {
case GLUT_KEY_F1: {
restart();
break;
}
case 'w': upDown.x = 0; break;
case 's': upDown.y = 0; break;
case 'd': rightLeft.x = 0; break;
case 'a': rightLeft.y = 0; break;
case ' ': if (wonGame || lostGame) restart(); break;
}
glutPostRedisplay();
}
void Game::idleFunc()
{
int newTime = glutGet(GLUT_ELAPSED_TIME);
int deltaTime = newTime - previousTime;
previousTime = newTime;
//printf("%f %f\n", rightLeft.x + rightLeft.y, upDown.x + upDown.y);
player->movePlayer(rightLeft.x + rightLeft.y, upDown.x + upDown.y, deltaTime);
player->update(deltaTime);
for(auto& b : bullets)
{
b->update(deltaTime);
}
for (auto& r : robots)
{
r->update(deltaTime);
}
bullets.erase(
std::remove_if(bullets.begin(), bullets.end(),
[](Bullet* element) -> bool {
//return true if element should be removed.
bool remove = element->flaggedForRemoval;
if (remove) free(element);
return remove;
} ), bullets.end() );
robots.erase(
std::remove_if(robots.begin(), robots.end(),
[](Robot* element) -> bool {
//return true if element should be removed.
bool remove = element->flaggedForRemoval;
if (remove) free(element);
return remove;
}), robots.end());
if (robots.size() == 0)
{
wonGame = true;
}
if (!wonGame) {
spawnTimer += deltaTime;
if (spawnTimer >= spawnTimerMaxRand)
{
spawnTimer = 0;
int fourthMax = (spawnTimerMax / 4);
int range = rand() % fourthMax - fourthMax / 2;
spawnTimerMaxRand = spawnTimerMax + range;
spawnEnemy();
}
}
glutPostRedisplay();
}
void Game::spawnEnemy()
{
Room * playerRoom = roomAt(player->getWorldPos());
int i = 0, pRoomIndex = -1;
for(auto& rr : rooms)
{
if (rr == playerRoom)
{
pRoomIndex = i;
break;
}
i++;
}
int roomIndex = rand() % rooms.size();
while (playerRoom != nullptr && roomIndex == pRoomIndex)
{
roomIndex = rand() % rooms.size();
}
Room * r = rooms[roomIndex];
Robot * robot = new Robot(this);
auto v = (r->bounds.max - r->bounds.min) * (randZeroToOne() * 0.6f + 0.2f) + r->bounds.min;
v.y = (r->bounds.min.y + r->bounds.max.y) / 2;
robot->translate(v);
robot->setRandDirection();
robots.push_back(robot);
}
void Game::recenterMouse()
{
glutWarpPointer(centerX, centerY);
}
void Game::loadTextures()
{
glEnable(GL_TEXTURE_2D);
loadTexture("tiles01.bmp", Textures::TILES01);
loadTexture("professor.bmp", Textures::PROFESSOR);
loadTexture("megaman.bmp", Textures::MEGAMAN);
loadTexture("plank01.bmp", Textures::PLANK);
loadTexture("clover01.bmp", Textures::CLOVER);
}
void Game::loadTexture(const char * filename, Textures tex)
{
GLuint textureId;
glGenTextures(1, &textureId);
pixmaps[tex] = RGBpixmap();
textureMap[tex] = textureId;
pixmaps[tex].readBMPFile(filename);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1); // store pixels by byte
glBindTexture(GL_TEXTURE_2D, textureId); // select current texture (0)
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D( // initialize texture
GL_TEXTURE_2D, // texture is 2-d
0, // resolution level 0
GL_RGB, // internal format
pixmaps[tex].nCols, // image width
pixmaps[tex].nRows, // image height
0, // no border
GL_RGB, // my format
GL_UNSIGNED_BYTE, // my type
pixmaps[tex].pixel); // the pixels
}
Room* Game::roomAt(Vector3 center) {
for (auto& r : rooms) {
if (r != nullptr && r->bounds.Contains(center)) return r;
}
return nullptr;
}
| true |
ded4dd15714c16eb625af758648e741e0b714588
|
C++
|
eduardo-mior/URI-Online-Judge-Solutions
|
/Iniciante/URI 1008.cpp
|
UTF-8
| 291 | 3.0625 | 3 |
[] |
no_license
|
#include <iostream>
int main() {
int funcionarios, horas;
float valorPorHora, salario;
scanf("%d %d %f", &funcionarios, &horas, &valorPorHora);
salario = horas * valorPorHora;
printf("NUMBER = %d\n", funcionarios);
printf("SALARY = U$ %.2f\n", salario);
return 0;
}
| true |
00ac4ec08e7d371715122726fcf67fefcda9a56d
|
C++
|
joaorabelo1121/Sistema-de-Operadora-de-Celular
|
/Date.h
|
UTF-8
| 444 | 2.609375 | 3 |
[] |
no_license
|
#ifndef _DATE_H
#define _DATE_H
#include <iostream>
using namespace std;
class Date{
private:
unsigned int dia;
unsigned int mes;
unsigned int ano;
unsigned int hora;
unsigned int minuts;
public:
Date();
Date(unsigned int _dia, unsigned int _mes, unsigned int _ano, unsigned int _hora, unsigned int _minuts);
~Date();
void diadomes(unsigned int _dia);
unsigned int get_diadomes();
};
#endif // _DATE_H
| true |
84a4c778c91d999e6893083957fac983ba766782
|
C++
|
sg-p4x347/ECS-Database-Test
|
/ConsoleApp/main.cpp
|
UTF-8
| 1,504 | 2.96875 | 3 |
[] |
no_license
|
#include <iostream>
#include "WorldEntityManager.h"
#include "WorldEntityCache.h"
#include "Position.h"
#include "ComponentA.h"
#include "ComponentB.h"
typedef WorldEntityManager<Position, ComponentA, ComponentB> WEM;
template < typename CacheType>
void Print(CacheType & cache) {
for (auto & entity : cache) {
cout << "ID: " << entity.GetID() << endl;
cout << "Signature: " << entity.GetSignature() << endl;
Vector3 & pos = entity.Get<Position>().Pos;
cout << "Position: x(" << pos.x << ") y(" << pos.y << ") z(" << pos.z << ")" << endl;
//cout << "A data: " << entity.Get<ComponentA>().data << endl;
//cout << "B data: " << entity.Get<ComponentB>().data << endl;
}
}
int main() {
WEM wem("C:\\Gage Omega\\Programming\\ConsoleApp\\Database",1024,256);
/*{
Position pos = Position(Vector3(42.f, 0.f, 42.f));
ComponentA a = ComponentA();
a.data = "I am the first";
ComponentB b = ComponentB();
b.data = 4.2;
wem.CreateEntity(pos, a, b);
}
{
Position pos = Position(Vector3(540.f, 0.f, 540.f));
ComponentA a = ComponentA();
a.data = "I am the second";
ComponentB b = ComponentB();
b.data = 4.2;
wem.CreateEntity(pos,b);
}*/
wem.Save();
auto wec = wem.NewEntityCache<Position>();
wem.ReCenter(64, 64, 32);
wem.UpdateCache(wec);
Print(wec);
cout << "moved" << endl;
wem.ReCenter(512, 512, 32);
wem.UpdateCache(wec);
Print(wec);
cout << "moved" << endl;
wem.ReCenter(64, 64, 32);
wem.UpdateCache(wec);
Print(wec);
keep_window_open();
return 0;
}
| true |
b7c2c06d279b022790f032cef2b1f2b19131a524
|
C++
|
ahmadalsajid/UVaCodes
|
/10935.cpp
|
UTF-8
| 508 | 2.6875 | 3 |
[] |
no_license
|
#include<iostream>
#include<queue>
using namespace std;
int main()
{
int n,i,t;
while((cin>>n)&&n){
queue<int>q;
for(i=1;i<=n;i++) q.push(i);
cout<<"Discarded cards:";
while(q.size()>1){
cout<<" "<<q.front(); q.pop();
if(q.size()>1) cout<<",";
t=q.front();q.pop();
q.push(t);
}
cout<<endl;
cout<<"Remaining card:"<<" "<<q.front();
cout<<endl;
}
return 0;
}
| true |
f73929b46f6b1a0ea4e64e57416d3e329f9a3001
|
C++
|
ordinary-developer/education
|
/cpp/std-11/a_williams-cpp_concurrency_in_action/code/ch_05-cpp_mem_model_and_operations_on_atomic/15-transitive_sync_using_acquire_release_ordering_01/main.cpp
|
UTF-8
| 979 | 3.203125 | 3 |
[
"MIT"
] |
permissive
|
#include <atomic>
#include <thread>
#include <assert.h>
std::atomic<int> data[5];
std::atomic<bool> sync1(false), sync2(false);
void thread_1() {
data[0].store(42, std::memory_order_relaxed);
data[1].store(97, std::memory_order_relaxed);
data[2].store(17, std::memory_order_relaxed);
data[3].store(-141, std::memory_order_relaxed);
data[4].store(2003, std::memory_order_relaxed);
sync1.store(true, std::memory_order_release);
}
void thread_2() {
while (!sync1.load(std::memory_order_acquire));
sync2.store(true, std::memory_order_release);
}
void thread_3() {
while (!sync2.load(std::memory_order_acquire));
assert(42 == data[0].load(std::memory_order_relaxed));
assert(97 == data[1].load(std::memory_order_relaxed));
assert(17 == data[2].load(std::memory_order_relaxed));
assert(-141 == data[3].load(std::memory_order_relaxed));
assert(2003 == data[4].load(std::memory_order_relaxed));
}
int main() {
return 0;
}
| true |
dd8e9d92ffb33e3435594f4ec31fd2fcc14be65a
|
C++
|
wxkkk/edge-computing-practices
|
/ncnn_mobilenet_yolo/mobilenet.cpp
|
UTF-8
| 6,809 | 2.546875 | 3 |
[] |
no_license
|
#include <iostream>
#include <vector>
#include <string>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/videoio.hpp>
#include "net.h"
//#include "mat.h"
#include "platform.h"
#include "timer_counter.h"
struct Object
{
cv::Rect_<float> rect;
int label;
float prob;
};
static int detect_yolov3(const ncnn::Net& net, const cv::Mat& image, std::vector<Object>& objects)
{
const float probThreshold {0.5};
const int input_size = 352;
int img_width = image.cols;
int img_height = image.rows;
ncnn::Mat ncnnImage = ncnn::Mat::from_pixels_resize(image.data, ncnn::Mat::PIXEL_BGR, img_width, img_height, input_size, input_size);
//subtract range mean value, norm to (-1, 1)
const float mean_vals[3] = {127.5f, 127.5f, 127.5f};
const float norm_vals[3] = {0.007843f, 0.007843f, 0.007843f};
ncnnImage.substract_mean_normalize(mean_vals, norm_vals);
ncnn::Extractor ex = net.create_extractor();
ex.set_num_threads(4);
ex.input("data", ncnnImage);
ncnn::Mat detectRes;
ex.extract("detection_out", detectRes);
std::cout << detectRes.h << std::endl;
objects.clear();
for(int i = 0; i < detectRes.h; i++)
{
const float* values = detectRes.row(i);
if(values[1] >= probThreshold)
{
Object object;
object.label = values[0];
object.prob = values[1];
object.rect.x = values[2] * img_width;
object.rect.y = values[3] * img_height;
object.rect.width = values[4] * img_width - object.rect.x;
object.rect.height = values[5] * img_height - object.rect.y;
objects.push_back(object);
}
}
return 0;
}
static void draw_objects(const cv::Mat& inputImage, const std::vector<Object>& objects)
{
static const char* class_name[] = {"background",
"aeroplane", "bicycle", "bird", "boat",
"bottle", "bus", "car", "cat", "chair",
"cow", "diningtable", "dog", "horse",
"motorbike", "person", "pottedplant",
"sheep", "sofa", "train", "tvmonitor"};
cv::Mat image = inputImage.clone();
for(size_t i = 0; i < objects.size(); i++)
{
const Object& obj = objects[i];
cv::rectangle(image, obj.rect, cv::Scalar(50,205,50));
std::string text {""};
text += class_name[obj.label];
text += std::to_string(obj.prob * 100);
text += "%";
int baseline = 0;
cv::Size textSize = cv::getTextSize(text, cv::FONT_HERSHEY_DUPLEX, 0.5, 1, &baseline);
int x = obj.rect.x;
int y = obj.rect.y;
if(y < 0)
y = 0;
if(x + textSize.width > image.cols)
x = image.cols - textSize.width;
//y + textSize.height for bottom left corner
cv::rectangle(image, cv::Rect(x, y, textSize.width, textSize.height + 5), cv::Scalar(50,205,50), -1);
cv::putText(image, text, cv::Point(x, y + textSize.height), cv::FONT_HERSHEY_DUPLEX, 0.5, cv::Scalar(255,255,255));
//cv::imshow("image", image);
//cv::waitKey(0);
}
cv::imshow("image", image);
//image only
//cv::waitKey(0);
}
static int detect_from_image(const ncnn::Net& net, const std::string image_path)
{
cv::Mat image = cv::imread(image_path, cv::IMREAD_COLOR);
//cv::imshow("image", image);
//cv::waitKey(0);
if (image.empty())
{
std::cerr << "no image has been read!" << std::endl;
return -1;
}
TimerCounter tc;
tc.Start();
std::vector<Object> objects;
//detection
detect_yolov3(net, image, objects);
tc.Stop();
std::cout << "Time: " << tc.dbTime * 1000 << "ms" << std::endl;
//draw box
draw_objects(image, objects);
return 0;
}
static int detect_from_video(const ncnn::Net& net, const std::string video_path)
{
// Create a VideoCapture object and open the input file
// If the input is the web camera, pass 0 instead of the video file name
cv::Mat frame;
cv::VideoCapture cap(video_path);
// Check if camera opened successfully
if (!cap.isOpened())
{
std::cout << "Error opening video stream or file" << std::endl;
return -1;
}
while (true)
{
// Capture frame-by-frame
cap.read(frame);
// If the frame is empty, break immediately
if (frame.empty())
{
std::cout << "Error, blank frame.";
break;
}
std::vector<Object> objects;
// Display the resulting frame
//imshow("Frame", frame);
TimerCounter tc;
tc.Start();
detect_yolov3(net, frame, objects);
tc.Stop();
std::cout << "Time: " << tc.dbTime * 1000 << "ms" << std::endl;
draw_objects(frame, objects);
// Press ESC on keyboard to exit
char c = (char)cv::waitKey(2);
if (c == 27)
break;
}
// When everything done, release the video capture object
cap.release();
// Closes all the frames
cv::destroyAllWindows();
return 0;
}
static int detect_from_camera(const ncnn::Net& net)
{
cv::Mat frame;
cv::VideoCapture cap;
// 0 = open default camera
int deviceID = 0;
// 0 = autodetect default API
int apiID = cv::CAP_ANY;
//open camera
cap.open(deviceID + apiID);
if(!cap.isOpened())
{
std::cerr<<"ERROR! Unable to open camera\n";
return -1;
}
//--- grab and write loop
while(true)
{
cap.read(frame);
if(frame.empty())
{
std::cerr<<"ERROR! blank frame grabbed\n";
return -1;
}
std::vector<Object> objects;
TimerCounter tc;
tc.Start();
detect_yolov3(net, frame, objects);
tc.Stop();
std::cout << "Time: " << tc.dbTime * 1000 << "ms" << std::endl;
draw_objects(frame, objects);
//cv::imshow("image", frame);
//char c = (char)cv::waitKey(20);
//if (c == 27)
//break;
if(cv::waitKey(10) >= 0)
break;
}
return 0;
}
int main(int argc, char** argv)
{
std::string image_path = "./images/test3.jpg";
std::string video_path = "./videos/test2.mp4";
//load model and pretrained weights
ncnn::Net net;
net.load_param("./models/yolov3_m2-opt.param");
net.load_model("./models/yolov3_m2-opt.bin");
//net.load_param("./models/yolov3-opt.param");
//net.load_model("./models/yolov3-opt.bin");
//read image and recognize
//detect_from_image(net, image_path);
//detect_from_camera(net);
detect_from_video(net, video_path);
return 0;
}
| true |
f3491ae7da49169e74bbd360eea86402082577d1
|
C++
|
kohyatoh/contests
|
/pku/2504/2504.cpp
|
UTF-8
| 1,367 | 2.734375 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <math.h>
#include <complex>
#include <algorithm>
using namespace std;
#define rep(i, n) for(int i=0; i<(int)(n); i++)
const double pi = atan2(0, -1);
#define EPS (1e-08)
typedef complex<double> P;
double cross(const P& a, const P& b) { return imag(conj(a)*b); }
P rot90(const P& p) { return P(imag(p), -real(p)); }
P crosspoint(const P& l0, const P& l1, const P& m0, const P& m1) {
double A=cross(l1-l0, m1-m0), B=cross(l1-l0, l1-m0);
if(abs(A)<EPS && abs(B)<EPS) return m0;
return m0 + B/A*(m1-m0);
}
int main() {
for(int q=0;; q++) {
int n;
scanf("%d", &n);
if(n==0) return 0;
double ax, ay, bx, by, cx, cy;
scanf("%lf%lf%lf%lf%lf%lf", &ax, &ay, &bx, &by, &cx, &cy);
P a(ax, ay), b(bx, by), c(cx, cy);
P g(crosspoint(0.5*(a+b), 0.5*(a+b)+rot90(b-a),
0.5*(c+b), 0.5*(c+b)+rot90(b-c)));
double r=abs(a-g), alpha=arg(a-g);
double xmax=-1e100, xmin=1e100, ymax=-1e100, ymin=1e100;
rep(i, n) {
double x = real(g)+r*cos(alpha+2*pi*i/n);
double y = imag(g)+r*sin(alpha+2*pi*i/n);
xmax = max(xmax, x);
xmin = min(xmin, x);
ymax = max(ymax, y);
ymin = min(ymin, y);
}
printf("Polygon %d: %.3f\n", q+1, (xmax-xmin)*(ymax-ymin));
}
}
| true |
bd32a1baf017e389942eb9b4fd3b3f494c52284a
|
C++
|
Vidyadhar-Mudkavi/gitApplications
|
/Calendar/calIso.h
|
UTF-8
| 1,967 | 2.546875 | 3 |
[
"MIT"
] |
permissive
|
#ifndef _CALISO_
#define _CALISO_
/**
*File: calIso.h
*Description:
this file declares class calIso
*Version: 1.2 "@(#) calIso. header. ver. 1.2. Premalatha, Vidyadhar Mudkavi, CTFD, NAL."
*Dependencies:
*Authors: Premalatha, Vidyadhar Mudkavi, CTFD, NAL.
*Date:
*/
// system includes
#include <iostream>
// standard template
// local includes
#include "calDate.h"
#include "calBase.h"
// const declarations
// function prototypes
// forward declarations
class calRataDie;
// begin class declaration
class calIso : public calBase
{
friend class calRataDie;
inline friend std::ostream& operator<<(std::ostream& os, const calIso& iso_date);
public:
// constructors
calIso(const calYear& year=1, const calWeek& week=1, const calDay& day=1); // default
calIso(const calIso& iso);
// assignment operator
calIso& operator=(const calIso& iso);
calIso& operator=(const calIsoDate& date);
// destructor
~calIso();
// other functionality
protected:
private:
void _ComputeFixed();
private:
long int pv_year;
int pv_week;
int pv_day;
};
// include any inline code here
inline calIso& calIso::operator=(const calIsoDate& date)
{
pv_year = date.Year();
pv_week = date.Week();
pv_day = date.Day();
_ComputeFixed();
return *this;
}
inline std::ostream& operator<<(std::ostream& os, const calIso& iso_date)
{
os << iso_date.pv_year << "-" << iso_date.pv_week << "-" << iso_date.pv_day; return os;
}
/**
declare any typedef statements here (e.g.: typedef aVortex areVortices;)
*/
//
// \\^//
// o(!_!)o
// __m__ o __m__
//
#endif // _CALISO_
| true |
190f23455fcf96ffe86a60d9221a632accbed5c1
|
C++
|
vgerber/projectdraw
|
/src/Core/Renderer/FlatRenderer/Interface/flat_drawable.h
|
UTF-8
| 866 | 2.859375 | 3 |
[] |
no_license
|
#pragma once
#include "Core/Scene/drawable.h"
#include "Core/Renderer/FlatRenderer/Interface/flat_sceneobject.h"
/**
* @brief Interface for drawables in FlatRenderer
*
*/
class FlatDrawable : public FlatSceneObject {
public:
/**
* @brief Construct a new Flat Drawable from @ref Drawable
* Calls setup function
* @param drawable
*/
FlatDrawable(Drawable * drawable);
/**
* @brief Updates internal data
* Will be called by mapped class when @see Drawable::isModified is true
*/
virtual void update() override;
/**
* @brief Draws data to screen
*
*/
virtual void draw() override;
/**
* @brief Frees allocated memeory
*
*/
virtual void dispose() override;
protected:
/**
* @brief Initialize varibales
*
*/
virtual void setup() override;
};
| true |
3c3dd4e0d9b8a15f936a7f1a5cd1bd57515e1c83
|
C++
|
rodins/gtk-online-life
|
/ResultsNet.hpp
|
UTF-8
| 1,558 | 2.515625 | 3 |
[] |
no_license
|
// ResultsNet.hpp
class ResultsNet {
CURL *curl_handle;
ResultsParser *parser;
string url;
public:
ResultsNet(ResultsParser *parser) {
this->parser = parser;
/* init the curl session */
curl_handle = curl_easy_init();
if(curl_handle) {
/* remove crash bug */
curl_easy_setopt(curl_handle, CURLOPT_NOSIGNAL, 1);
/* send all data to this function */
curl_easy_setopt(curl_handle,
CURLOPT_WRITEFUNCTION,
ResultsNet::results_writer);
curl_easy_setopt(curl_handle, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl_handle,
CURLOPT_WRITEDATA,
parser);
}
}
~ResultsNet() {
/* cleanup curl stuff */
curl_easy_cleanup(curl_handle);
}
void resetFirstItem() {
parser->resetFirstItem();
}
gboolean isEmpty() {
return parser->isEmpty();
}
void setMode(gboolean isPage) {
if(isPage) {
url = parser->getNextLink();
}else {
url = parser->getLink();
}
}
CURLcode getResultsFromNet() {
CURLcode res;
if(curl_handle) {
/* set url to get here */
curl_easy_setopt(curl_handle,
CURLOPT_URL,
url.c_str());
/* get it */
res = curl_easy_perform(curl_handle);
}
return res;
}
private:
static int results_writer(char *data, size_t size, size_t nmemb,
ResultsParser *parser)
{
if(parser == NULL) {
return 0;
}
parser->divs_parser(data);
return size*nmemb;
}
};
| true |
41ef392a72396853b96f822d3234e10d40e093d4
|
C++
|
zhr1201/Algorithms
|
/MedianMaintenance/MedianMaintenance/MedianMaintenance/heap.cpp
|
UTF-8
| 1,481 | 3.59375 | 4 |
[] |
no_license
|
#include "heap.h"
int BinaryHeap::find_top()
{
if(current_size == 0)
return -1;
else
return num_array[1];
}
void BinaryHeap::insert(int new_element)
{
int hole = ++current_size;
num_array[0] = new_element;
if(max_heap)
{
num_array.push_back(new_element);
for(; new_element > num_array[hole / 2]; hole /= 2)
num_array[hole] = num_array[hole / 2];
num_array[hole] = new_element;
}
else
{
num_array.push_back(new_element);
for(; new_element < num_array[hole / 2]; hole /= 2)
num_array[hole] = num_array[hole / 2];
num_array[hole] = new_element;
}
return;
}
void BinaryHeap::delete_top()
{
int hole = 1;
int last_element = num_array[current_size];
int child;
if(max_heap)
{
for(; hole * 2 <= current_size; hole = child)
{
child = hole * 2;
if(child != current_size && num_array[child] < num_array[child + 1])
{
child++;
}
if(num_array[child] > last_element)
num_array[hole] = num_array[child];
else
break;
}
num_array[hole] = last_element;
}
else
{
for(; hole * 2 <= current_size; hole = child)
{
child = hole * 2;
if(child != current_size && num_array[child] > num_array[child + 1])
{
child++;
}
if(num_array[child] < last_element)
num_array[hole] = num_array[child];
else
break;
}
num_array[hole] = last_element;
}
num_array.erase(num_array.end() - 1);
current_size--;
return;
}
| true |
74b0a808674dab62434325c4d14123db569ecbd2
|
C++
|
JayJ72/OSU2016
|
/Cpp Stuff/Linear Geometry Stuff/Line.cpp
|
UTF-8
| 674 | 3.140625 | 3 |
[] |
no_license
|
//Jay Banerji
//Assignment 2 CS162 2016
#include "Line.hpp"
#include "Point.hpp"
#include <cmath>
using namespace std;
Line::Line (Point point1, Point point2) {
this->point1 = point1;
this->point2 = point2;
}
Point Line::getPoint1() {
return point1;
}
Point Line::getPoint2() {
return point2;
}
double Line::slope() {
return (point2.getYCoord()-point1.getYCoord() / point2.getXCoord()-point1.getXCoord());
}
double Line::distanceTo(Point P2) {
return sqrt((pow(point1.getXCoord()-point2.getXCoord(),2)) + (pow(point1.getYCoord()-point2.getYCoord(),2)));
}
Point Line::intersectWith(Point intersectP) {
return point1;//intersection formula
}
| true |
1a76a65ec7991237a0559b1d9fcf127837e98aa9
|
C++
|
yananliu000/Projects
|
/GlarekEngineProject/Engine/Engine/Source/Application/Texture/SFMLSprite.h
|
UTF-8
| 1,924 | 2.90625 | 3 |
[] |
no_license
|
#pragma once
/** \file SFMLSprite.h */
/** TODO: File Purpose */
// Created by Billy Graban
#ifdef _SFML
#include <SFML/Graphics/Sprite.hpp>
#include <SFML/Graphics/Texture.hpp>
#include ".\ISprite.h"
namespace Engine
{
/** \class SFMLSprite */
/** TODO: Class Purpose */
class SFMLSprite
: public ISprite
{
public:
// --------------------------------------------------------------------- //
// Public Member Variables
// --------------------------------------------------------------------- //
// --------------------------------------------------------------------- //
// Public Member Functions
// --------------------------------------------------------------------- //
/** Default Constructor */
SFMLSprite() {};
/** Default Destructor */
~SFMLSprite() { delete m_pSprite; m_pSprite = nullptr; };
//create sprite from texture
bool Init(ITexture* pTexture) override;
//create sprite from filepath
bool Init(const char* filepath) override;
void SetTint(Color tintColor) override { m_pSprite->setColor(sf::Color{ tintColor.red, tintColor.blue, tintColor.green });}
void SetAlpha(u8 alpha) override { m_pSprite->setColor(sf::Color{ 255, 255, 255, alpha }); };
private:
// --------------------------------------------------------------------- //
// Private Member Variables
// --------------------------------------------------------------------- //
//the sprite
sf::Sprite* m_pSprite;
// --------------------------------------------------------------------- //
// Private Member Functions
// --------------------------------------------------------------------- //
public:
// --------------------------------------------------------------------- //
// Accessors & Mutators
// --------------------------------------------------------------------- //
//get the sprite pointer
virtual void* GetNativeSprite() override { return m_pSprite; };
};
}
#endif
| true |
05370fe21002c0d150b321eed818c06ce7bcefab
|
C++
|
mbcolson/Academic-Programming-Projects
|
/Heap/HeapMain.cpp
|
UTF-8
| 492 | 3.265625 | 3 |
[] |
no_license
|
#include "Heap.h"
using namespace std;
int main()
{
Itemtype i1;
Heap h;
h.Insert(4);
h.Insert(1);
h.Insert(7);
h.Insert(3);
h.Insert(9);
h.Insert(2);
h.Insert(8);
h.Insert(5);
cout << "Heap is full: " << (h.IsFull() ? "true" : "false") << endl;
cout << "Heap is empty: " << (h.IsEmpty() ? "true" : "false") << endl;
i1 = h.Retrieve();
cout << "h.Retrieve: " << i1 << endl;
return 0;
}
| true |
0a06c0ad54fe636165f8e45eae47616c7ac63b3a
|
C++
|
Alpha-0010/Company-Wise-Problems-Leetcode
|
/Top Interview Questions/Rotate_Image.cpp
|
UTF-8
| 663 | 3.5625 | 4 |
[] |
no_license
|
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int rows=matrix.size();
if(rows==0){
return;
}
int cols=matrix[0].size();
// Transpose of the matrix.
for(int i=0;i<rows;i++){
for(int j=i+1;j<cols;j++){
swap(matrix[i][j],matrix[j][i]);
}
}
// Horizontal revrsal of the matrix.
for(int i=0;i<rows;i++){
int left=0,right=cols-1;
while(left<right){
swap(matrix[i][left],matrix[i][right]);
left++;
right--;
}
}
}
};
| true |
d038ac1d3838cec9263dce37dda3b1cc86036f12
|
C++
|
aurialLoop/kimchiandchips
|
/oF/addons/ofxCVgui/src/scrBaseMarkers.cpp
|
UTF-8
| 858 | 2.5625 | 3 |
[] |
no_license
|
/*
* scrBaseMarkers.cpp
* pixel correlation
*
* Created by Elliot Woods on 20/03/2010.
* Copyright 2010 Kimchi and Chips. All rights reserved.
*
*/
#include "scrBaseMarkers.h"
scrBaseMarkers::scrBaseMarkers()
{
_hasMarkers=false;
}
void scrBaseMarkers::setMarkers(std::vector<ofPoint> *x)
{
_markers=x;
_nMarkers=x->size();
_hasMarkers=true;
}
void scrBaseMarkers::clearMarkers()
{
_hasMarkers=false;
}
void scrBaseMarkers::drawMarkers(float x, float y, float width, float height)
{
float xMarker, yMarker;
if (_hasMarkers)
{
ofPushStyle();
ofNoFill();
ofSetColor(0,0,255);
glBegin(GL_POINTS);
for (int iMarker=0; iMarker < _nMarkers; iMarker++)
{
xMarker = (*_markers)[iMarker].x * width + x;
yMarker = (*_markers)[iMarker].y * height + y;
glVertex2f(xMarker, yMarker);
}
glEnd();
ofPopStyle();
}
}
| true |
b0a33c700ad87a7c93dfe19f2914303b64b1c7cd
|
C++
|
bibaev/arkanoid
|
/arkanoid/main.cpp
|
UTF-8
| 2,668 | 2.59375 | 3 |
[] |
no_license
|
#include <chrono>
#include <string>
#include <gl/freeglut.h>
#include <algorithm>
#include "gl_helpers.h"
#include "game.h"
#include "config.h"
game* game_ptr;
static const GLint GAME_FIELD_WIDTH = DEFAULT_GAME_WIDTH;
static const GLint GAME_FIELD_HEIGHT = DEFAULT_GAME_HEIGHT;
using time_point = std::chrono::high_resolution_clock::time_point;
static GLint screen_width = 1024;
static GLint screen_height = 768;
// Shared variabled, indicate some state of game
bool right_key_pressed = false;
bool left_key_pressed = false;
static void reshape_callback(GLint width, GLint height) {
screen_width = std::max(GAME_FIELD_WIDTH, width);
screen_height = std::max(GAME_FIELD_HEIGHT, height);
glutReshapeWindow(screen_width, screen_height);
glViewport(0, 0, screen_width, screen_height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, screen_width, screen_height, 0, 0, 1.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void on_key_down_callback(unsigned char ch, int a, int b) {
switch (ch) {
case 'd': case 226:
right_key_pressed = true;
break;
case 'a': case 244:
left_key_pressed = true;
break;
case ' ':
game_ptr->release_ball();
break;
}
}
void on_key_up_callback(unsigned char ch, int a, int b) {
switch (ch) {
case 'd': case 226:
right_key_pressed = false;
break;
case 'a': case 244:
left_key_pressed = false;
break;
}
}
void fps_counter(time_point now) {
static auto start_time = std::chrono::high_resolution_clock::now();
static size_t frames;
static size_t fps = 0;
++frames;
draw_string(std::to_string(fps).c_str(), { 5, 20 }, { 1., 1., 0. }, GLUT_BITMAP_HELVETICA_18);
auto diff = now - start_time;
if (now - start_time >= std::chrono::milliseconds(50)) {
fps = static_cast<size_t>(frames / (std::chrono::duration_cast<std::chrono::milliseconds>(diff).count() / 1000.));
frames = 0;
start_time = now;
}
}
void display() {
static time_point old_time = std::chrono::high_resolution_clock::now();
auto now = std::chrono::high_resolution_clock::now();
auto elapsed_time = std::chrono::duration_cast<std::chrono::milliseconds>(now - old_time).count() / 1000.f;
game_ptr->process(elapsed_time);
fps_counter(now);
game_ptr->render();
old_time = now;
}
int main(int argc, char* argv[]) {
gl_config config{ on_key_down_callback, on_key_up_callback, display, reshape_callback, screen_width, screen_height };
game_ptr = new game{};
init_gl(argc, argv, config);
delete game_ptr;
return 0;
}
| true |