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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
9f14495a6d7ee781432b35cb8125f6a9512f3f26 | C++ | Manspear/CCGW_Reborn | /CCGW_Reborn/Input.cpp | UTF-8 | 4,803 | 2.78125 | 3 | [] | no_license | #include "Input.h"
#include "global_variables.h"
bool Input::update()
{
bool result = true;
mPressedKeys.clear();
// copy last frames current input to current frames previous input
for (int i = 0; i<MAX_KEYS; i++)
mPrevKeys[i] = mCurKeys[i];
for (int i = 0; i<MAX_BUTTONS; i++)
mPrevButtons[i] = mCurButtons[i];
// poll SDL for input
SDL_Event e;
while (SDL_PollEvent(&e))
{
if (e.type == SDL_QUIT) // user pressed the X button of the window
mQuit = true;
else if (e.type == SDL_KEYDOWN) // user pressed a key
{
int key = e.key.keysym.sym;
if (key >= 0 && key < MAX_KEYS)
{
mPressedKeys.push_back(key);
mCurKeys[key] = true;
}
}
else if (e.type == SDL_KEYUP) // user released a key
{
int key = e.key.keysym.sym;
if (key >= 0 && key < MAX_KEYS)
mCurKeys[key] = false;
}
else if (e.type == SDL_MOUSEBUTTONDOWN) // user pressed a mouse button
{
int button = e.button.button - 1; // SDL_BUTTON_LEFT is 1, we want it to be 0
if (button >= 0 && button < MAX_BUTTONS)
mCurButtons[button] = true;
}
else if (e.type == SDL_MOUSEBUTTONUP) // user released a mouse button
{
int button = e.button.button - 1;
if (button >= 0 && button < MAX_BUTTONS)
mCurButtons[button] = false;
}
else if (e.type == SDL_MOUSEMOTION)
{
this->mPrevMouse = mCurMouse;
this->mCurMouse = glm::vec2(e.motion.x, e.motion.y);
}
}
int tempx = 0; int tempy = 0;
SDL_GetWindowPosition( mpWindow, &tempx, &tempy );
this->mPrevMouse =glm::vec2(gWidth/2, gHeight/2);
if( mMouseLock )
{
SDL_WarpMouseInWindow( mpWindow, gWidth/2, gHeight/2 );
SDL_FlushEvent(SDL_MOUSEMOTION);
}
return result;
}
bool Input::keyDown(int key) const
{
if (key < 0 || key >= MAX_KEYS)
return false;
return mCurKeys[key];
}
bool Input::keyUp(int key)const
{
if (key < 0 || key >= MAX_KEYS)
return false;
return !mCurKeys[key];
}
bool Input::keyPressed(int key) const
{
if (key < 0 || key >= MAX_KEYS)
return false;
if (mPrevKeys[key])
return false;
return mCurKeys[key];
}
bool Input::keyReleased(int key)const
{
if (key < 0 || key >= MAX_KEYS)
return false;
if (mCurKeys[key])
return false;
return mPrevKeys[key];
}
bool Input::buttonDown(int button)const
{
if (button < 0 || button >= MAX_BUTTONS)
return false;
return mCurButtons[button];
}
bool Input::buttonUp(int button)const
{
if (button < 0 || button >= MAX_BUTTONS)
return false;
return !mCurButtons[button];
}
bool Input::buttonPressed(int button)const
{
if (button < 0 || button >= MAX_BUTTONS)
return false;
if (mPrevButtons[button])
return false;
return mCurButtons[button];
}
bool Input::buttonReleased(int button)const
{
if (button < 0 || button >= MAX_BUTTONS)
return false;
if (mCurButtons[button])
return false;
return mPrevButtons[button];
}
glm::vec2 Input::mousePosition()const
{
return mCurMouse;
}
glm::vec2 Input::mouseDelta()const
{
return (mPrevMouse - mCurMouse);
}
bool Input::toggleMouseLock()
{
return ( mMouseLock = !mMouseLock );
}
bool Input::toggleMouseVisibility()
{
setMouseVisible( !mMouseVisible );
return mMouseVisible;
}
void Input::setMouseLock( bool enabled )
{
mMouseLock = enabled;
}
void Input::setMouseVisible( bool visible )
{
mMouseVisible = visible;
SDL_ShowCursor( ( visible ? 1 : 0 ) );
}
bool Input::getMouseLock() const
{
return mMouseLock;
}
bool Input::getMouseVisible() const
{
return mMouseVisible;
}
bool Input::getQuit() const
{
return mQuit;
}
std::vector<int>* Input::getPressedKeys()
{
return &mPressedKeys;
}
Input& Input::operator=(const Input& ref)
{
// copy values from reference
for (int i = 0; i<MAX_KEYS; i++)
{
mCurKeys[i] = ref.mCurKeys[i];
mPrevKeys[i] = ref.mPrevKeys[i];
}
for (int i = 0; i<MAX_BUTTONS; i++)
{
mCurButtons[i] = ref.mCurButtons[i];
mPrevButtons[i] = ref.mPrevButtons[i];
}
mCurMouse = ref.mCurMouse;
mPrevMouse = ref.mPrevMouse;
mMouseLock = ref.mMouseLock;
mMouseVisible = ref.mMouseVisible;
return *this;
}
Input::Input(const Input& ref)
: mCurMouse(ref.mCurMouse), mPrevMouse(ref.mPrevMouse), mMouseLock( ref.mMouseLock ), mMouseVisible( ref.mMouseVisible )
{
// copy values from reference
for (int i = 0; i<MAX_KEYS; i++)
{
mCurKeys[i] = ref.mCurKeys[i];
mPrevKeys[i] = ref.mPrevKeys[i];
}
for (int i = 0; i<MAX_BUTTONS; i++)
{
mCurButtons[i] = ref.mCurButtons[i];
mPrevButtons[i] = ref.mPrevButtons[i];
}
}
Input::Input(SDL_Window* w)
: mCurMouse( 0.0f ), mPrevMouse( 0.0f ), mMouseLock( true ), mMouseVisible( true )
{
// initialize all values to false
for (int i = 0; i<MAX_KEYS; i++)
mCurKeys[i] = mPrevKeys[i] = false;
for (int i = 0; i<MAX_BUTTONS; i++)
mCurButtons[i] = mPrevButtons[i] = false;
this->mQuit = false;
this->mpWindow = w;
}
Input::~Input()
{
} | true |
226d60dfe8cfb3cf2f4c9e7d4776423400da2095 | C++ | gabriel-vsqz/P3Examen2_GabrielVasquez | /Relacion.hpp | UTF-8 | 826 | 3.265625 | 3 | [] | no_license | #pragma once
#include <vector>
#include <string>
#include "Tupla.hpp"
using namespace std;
class Relacion {
private:
vector<string> encabezados;
vector<Tupla> tuplas;
string nombre;
public:
Relacion();
Relacion(string, vector<string>);
string getNombre();
vector<string> getEncabezados();
void setTupla(Tupla t);
vector<Tupla> getTuplas();
};
Relacion :: Relacion() {
}
Relacion :: Relacion (string name, vector<string> headers) {
nombre = name;
encabezados = headers;
}
string Relacion :: getNombre() {
return nombre;
}
vector<string> Relacion :: getEncabezados() {
return encabezados;
}
void Relacion :: setTupla(Tupla nuevo) {
tuplas.push_back(nuevo);
}
vector<Tupla> Relacion :: getTuplas() {
return tuplas;
} | true |
db05dca15894fd24419eb389347303cef464d1ec | C++ | VarickQ/ACM | /HaveDone/PAT/1049.Counting Ones.cpp | GB18030 | 1,045 | 3 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <stdio.h>
#include <string.h>
#include <string>
#include <set>
using namespace std;
typedef long long LL;
const int N = 100005;
//http://blog.csdn.net/SJF0115/article/details/8600599
int getOnes(int n){
int tmp = 1, ret = 0;
while (n / tmp) {
int left = n / (tmp * 10);
int now = (n / tmp) % 10;
int right = n % tmp;
if (now == 0) {
//ǰλΪ0,ܳ1Ĵɸλ
//ڸλ * ǰλ
ret += left * tmp;
} else if (now == 1) {
//ǰλΪ1,ܳ1ĴܸλӰ컹ܵλӰ
//ڸλ * ǰλ + λ + 1
ret += left * tmp + right + 1;
} else {
//ǰλִ12~9,1ɸλ
//ڣλ + 1 * ǰλ
ret += (left + 1) * tmp;
}
tmp *= 10;
}
return ret;
}
int main(){
int n;
scanf("%d", &n);
int ans = getOnes(n);
printf("%d\n", ans);
return 0;
} | true |
6d49e9d6fca86e5c8fcd1135a1675428c5ed4d47 | C++ | thegamer1907/Code_Analysis | /CodesNew/4545.cpp | WINDOWS-1250 | 2,172 | 2.515625 | 3 | [] | no_license | #define fori(q, x) for(int q=0; q<x; q++)
#define forl(q, x) for(long q=0; q<x; q++)
#define forll(q, x) for(ll q=0; q<x; q++)
#define unsync ios::sync_with_stdio(0), cin.tie(0)
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> ii;
typedef vector<ii> vii;
typedef vector<int> vi;
#define INF 1000000000 // 1 billion, safer than 2B for Floyd Warshalls
#define MAX 100005
const double EPS = (1e-9);
// Common memset settings
//memset(memo, -1, sizeof memo); // initialize DP memoization table with -1
//memset(arr, 0, sizeof arr); // to clear array of integers
int vis[MAX];
vector<int> vec; int N;
ll ans = 0;
bool found = false;
int p, q, r, s, t, u;
bool f(int x){
int cnt = 1;
for(int i = N - x - 1; i >= 0; i--){
if(vec[i] * 2 > vec[N-cnt])
return false;
cnt++;
}
return true;
}
double BS_double(double start, double endd,double val) {
while(fabs(endd - start) > EPS) { // iterate 100-500 iteration
double mid = start + (endd-start)/2;
if(f(mid) > val) start= mid;
else endd = mid;
//cout << start << " " << endd << endl;
}
return start;
}
int BSfindFirst(int start, int endd) {
int lastmid = -1;
while(start < endd) {
int mid = start + (endd-start)/2;
if(mid == lastmid) break;
else lastmid = mid;
if(f(mid)) endd= mid;
else if(!f(mid)) start = mid+1;
//else endd = mid;
//cout << start << " " << endd << " " << mid << " " << f(mid) << endl;
}
return start;
}
void dfs(int u, vector<int> adj[]){
vis[u]++;
for(int v : adj[u])
if(!vis[v])
dfs(v, adj);
}
int main()
{
unsync;
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
#endif // ONLINE_JUDGE
cin >> N;
fori(i, N){
int x; cin >> x;
vec.push_back(x);
}
sort(vec.begin(), vec.end());
cout << BSfindFirst(ceil(N/2.0), N);
}
| true |
f0f4df204fc659d23feeb63880c935404b1b4619 | C++ | saikrishna17394/Code | /Codechef/ext_contests/cdcz2013/bhav.cpp | UTF-8 | 355 | 2.609375 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
int main() {
int t,s,n,c,val;
cin>>t;
while(t--) {
cin>>s;
cin>>n;
cin>>c;
if((n+2*c)<s)
printf("NO\n");
else {
if(s<n)
printf("YES 0\n");
else {
val=(s-n)/2;
if((s-n)&1)
val++;
printf("YES %d\n", val);
}
}
}
return 0;
} | true |
e487817d227c05c8a63bf9b8674888f1c3097d8b | C++ | makeblade/Graphing-Calculator | /RPN/token.cpp | UTF-8 | 209 | 2.609375 | 3 | [] | no_license | #include "token.h"
/**
* @brief Token::Token constructor
* @param tok_str
* @param type
*/
Token::Token(string tok_str, int type)
{
_str = tok_str;
_type = type;
}
void Token::print() const
{
}
| true |
a87d4f851c92496770f80545f53701e121c41d6e | C++ | leandroS08/SEMEAR_RR | /src/OpenCV/code.cpp | UTF-8 | 14,781 | 2.703125 | 3 | [] | no_license | #include <iostream>
#include <math.h>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
using namespace cv;
using namespace std;
#define PI 3.1415926
char* source_window = "Original Video";
char* result_window = "Result Video";
/*
Variável que armazena a identidade da linha analisada
0: nenhuma linha
1: linha continua esquerda
2: linha pontilhada central
3: linha continua direita
*/
int current_line_view = 2;
void bird_Eyes(Mat&, Mat&);
Mat transformationMat;
Mat trans_mat;
void bird_Eyes_2(Mat&, int, int, int, int, int, Mat&);
int iLowV = 0;
int iHighV = 255;
void select_Channel(Mat&, Mat&, int, int);
Point2i button;
int previous_x = -1;
void histogram_Line(Mat&);
/* Constantes da funções de sliding_Window */
int h_rectangle = 30;
int l_rectangle = 90;
int num_rectangle = 20; // Quando atualizar, lembrar de atualizar o tamanho dos vetores control_line[] e alpha[]
vector<Point2f> Central_Line;
vector<Point2i> iCentral_Line;
int control_line[20];
double alpha[20];
void sliding_Window_Line(Mat&, Mat&);
vector<Point2f> final_navegavel;
vector<Point2i> ifinal_navegavel;
void inverse_bird_Eyes(Mat&, Mat&, Mat&);
void inverse_bird_Eyes_2(Mat&, Mat&, Mat&);
float shift_Central(Mat&);
int main( int argc, char** argv )
{
Mat src; // Frame original lido da câmera
Mat tr1;
Mat bird_img; // Bird Eyes Transformation
Mat color_img; // Manipulação dos canais de cor
Mat sliding_img; //
Mat result_img;
/* Abertura do vídeo */
char* videoName = argv[1];
VideoCapture cap(videoName);
if ( !cap.isOpened() )
{
cout << "Erro ao abrir o video" << endl;
return -1;
}
/* Janelas */
namedWindow(source_window, CV_WINDOW_NORMAL);
namedWindow(result_window, CV_WINDOW_NORMAL);
for(int j = 0; j<num_rectangle; j++)
control_line[j] = -1;
while ( (waitKey(33) != 27) && (cap.isOpened()) )
{
cap.read(src);
bird_Eyes(src,bird_img);
//bird_Eyes_2(color_img, 40, 90, 90, 430, 600, bird_img);
select_Channel(bird_img, color_img, iLowV, iHighV);
histogram_Line(color_img);
sliding_img = bird_img.clone();
sliding_Window_Line(color_img, sliding_img);
inverse_bird_Eyes(src, bird_img, result_img);
//inverse_bird_Eyes_2(src, bird_img, result_img);
//result_img = sliding_img.clone();
shift_Central(result_img);
imshow(source_window, src);
imshow(result_window, result_img);
Central_Line.clear();
iCentral_Line.clear();
final_navegavel.clear();
ifinal_navegavel.clear();
waitKey(0);
}
waitKey(0);
}
void bird_Eyes(Mat& in, Mat& out)
{
Mat tr; // variável de manipulação interna da função
int Rows = in.rows;
int Cols = in.cols;
Point2f src_vertices[4];
src_vertices[0] = Point( 0, Rows); //
src_vertices[1] = Point(0.30*Cols, 0.30*Rows); //
src_vertices[2] = Point(0.70*Cols, 0.30*Rows); //
src_vertices[3] = Point( Cols, Rows); //
Point2f dst_vertices[4];
dst_vertices[0] = Point( 0, 480);
dst_vertices[1] = Point( 0, 0);
dst_vertices[2] = Point(640, 0);
dst_vertices[3] = Point(640, 480);
Mat M = getPerspectiveTransform(src_vertices, dst_vertices);
tr = Mat(480, 640, CV_8UC3);
warpPerspective(in, tr, M, tr.size(), INTER_LINEAR, BORDER_CONSTANT);
out = tr;
char* bird_window = "Bird Eyes Transformation";
namedWindow(bird_window, CV_WINDOW_NORMAL);
imshow(bird_window, out);
}
void select_Channel(Mat& in, Mat& out, int low, int high)
{
Mat tr;
Mat imgThresholded;
GaussianBlur(in,tr,Size(3,3),0,0,BORDER_DEFAULT);
cvtColor(tr,tr,CV_RGB2HSV); // conversão para HLS
inRange(tr, Scalar(0, 75, 135), Scalar(145, 255, 208), imgThresholded); //Threshold the image
//morphological opening (remove small objects from the foreground)
erode(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) );
dilate( imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) );
//morphological closing (fill small holes in the foreground)
dilate( imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) );
erode(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) );
/*namedWindow("H channel", CV_WINDOW_NORMAL);
namedWindow("S channel", CV_WINDOW_NORMAL);
namedWindow("L channel", CV_WINDOW_NORMAL);
imshow("H channel", hls_planes[0]);
imshow("S channel", hls_planes[1]);
imshow("L channel", hls_planes[2]);*/
//inRange(hls_planes[1], Scalar(low), Scalar(high), out); // selecão do canal H
//inRange(hls_planes[1], 30, 180, tr); // selecão do canal L
//bitwise_not ( imgThresholded, imgThresholded );
out = imgThresholded;
char* color_window = "Selecao do Canal e das Intensidades de Cor";
namedWindow(color_window, CV_WINDOW_NORMAL);
imshow(color_window, out);
}
void bird_Eyes_2(Mat& in, int alpha_, int beta_, int gamma_, int f_, int dist_, Mat& out)
{
//int frameWidth = ;
//int frameHeight = ;
int offsetx = 0;
int offsety = -175;
trans_mat = (Mat_<double>(2,3) << 1, 0, offsetx, 0, 1, offsety);
warpAffine(in,out,trans_mat,in.size());
double focalLength, dist, alpha, beta, gamma;
alpha =((double)alpha_ -90) * PI/180;
beta =((double)beta_ -90) * PI/180;
gamma =((double)gamma_ -90) * PI/180;
focalLength = (double)f_;
dist = (double)dist_;
Size image_size = in.size();
double w = (double)image_size.width, h = (double)image_size.height;
// Projecion matrix 2D -> 3D
Mat A1 = (Mat_<float>(4, 3)<<
1, 0, -w/2,
0, 1, -h/2,
0, 0, 0,
0, 0, 1 );
// Rotation matrices Rx, Ry, Rz
Mat RX = (Mat_<float>(4, 4) <<
1, 0, 0, 0,
0, cos(alpha), -sin(alpha), 0,
0, sin(alpha), cos(alpha), 0,
0, 0, 0, 1 );
Mat RY = (Mat_<float>(4, 4) <<
cos(beta), 0, -sin(beta), 0,
0, 1, 0, 0,
sin(beta), 0, cos(beta), 0,
0, 0, 0, 1 );
Mat RZ = (Mat_<float>(4, 4) <<
cos(gamma), -sin(gamma), 0, 0,
sin(gamma), cos(gamma), 0, 0,
0, 0, 1, 0,
0, 0, 0, 1 );
// R - rotation matrix
Mat R = RX * RY * RZ;
// T - translation matrix
Mat T = (Mat_<float>(4, 4) <<
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, dist,
0, 0, 0, 1);
// K - intrinsic matrix
Mat K = (Mat_<float>(3, 4) <<
focalLength, 0, w/2, 0,
0, focalLength, h/2, 0,
0, 0, 1, 0
);
transformationMat = K * (T * (R * A1));
warpPerspective(in, out, transformationMat, image_size, INTER_CUBIC | WARP_INVERSE_MAP);
Mat deslocamento = (Mat_<double>(2,3) << 1, 0, 0,
0, 1, (0.05*out.cols));
warpAffine(out,out,deslocamento,out.size());
char* bird_window = "Bird Eyes Transformation";
namedWindow(bird_window, CV_WINDOW_NORMAL);
imshow(bird_window, out);
}
void histogram_Line(Mat& in)
{
Mat histImage(in.rows, in.cols, CV_8UC3, Scalar(255,255,255) );
int count[in.cols];
long int count_Num = 0;
int count_Den = 0;
int i_best_col = -1;
int n_best_col = 0;
//int normalized_count[in.cols];
float inicial_Row = 0.5 * in.rows;
for (int col = 0; col < in.cols; ++col)
{
count[col]=0;
//for (int i=0; (i<10) && (count_Den < 10); i++)
//{
for (int row = inicial_Row ; row < in.rows; ++row)
{
if ( (int)(in.at<uchar>(row,col)) != 0)
{
++count[col];
count_Num+=(col*count[col]);
count_Den+=count[col];
}
}
//}
//if (count[col] != 0)
//cout << "Coluna " << col << " tem " << count[col] << " pixeis" << endl;
if (count[col] > n_best_col)
{
i_best_col = col;
n_best_col = count[col];
}
circle(histImage, Point(col, in.rows - count[col]),1,Scalar(0,0,255),3,8,0);
}
button.y = in.rows;
/*if ( ( (count_Den > 10) || (previous_x == -1)) && (count_Den != 0) )
{
//cout << "Count_num: " << count_Num << " Count_den: " << count_Den << endl;
button.x = count_Num / count_Den;
previous_x = button.x;
}*/
if ( ( (count_Den > 10) || (previous_x == -1) ) )
{
button.x = i_best_col;
previous_x = button.x;
}
else
button.x = previous_x;
//cout << "Ponto inicial (" << button.x << "," << button.y << " ) " << endl;
char* histogram_window = "Histogram 2";
namedWindow(histogram_window, CV_WINDOW_NORMAL);
imshow(histogram_window, histImage);
}
void sliding_Window_Line(Mat& in, Mat& out)
{
// Desenha o quadrado inicial resultante do histograma
Point2d initial_Center = Point(button.x, button.y);
Point2d final_Center;
Point P1, P2; // pontos auxiliares para desenho dos retângulos
P1.x = button.x - (l_rectangle/2);
P1.y = button.y - (h_rectangle/2);
P2.x = button.x + (l_rectangle/2);
P2.y = button.y;
rectangle(out, P1, P2, Scalar(255,255,0), 2, 8, 0);
Point2d previous_Center = initial_Center;
Point2d new_Center;
int count[l_rectangle];
int count_Num;
int count_Den;
for (int i=0; i<num_rectangle; i++)
{
count_Num = 0;
count_Den = 0;
new_Center.x = previous_Center.x;
new_Center.y = previous_Center.y - (h_rectangle/2);
P1.x = new_Center.x - (l_rectangle/2);
P1.y = new_Center.y - (h_rectangle/2);
P2.x = new_Center.x + (l_rectangle/2);
P2.y = new_Center.y;
for (int col = P1.x ; col <= (P1.x + l_rectangle); col++)
{
count[col-P1.x] = 0;
for (int row = P1.y ; row <= (P1.y + h_rectangle); row++)
{
if ( (int)(in.at<uchar>(row,col)) != 0)
{
++count[col-P1.x];
count_Num+=(col*count[col-P1.x]);
count_Den+=count[col-P1.x];
}
}
//cout << "A coluna " << col << "(indice " << col-P1.x << " ) tem " << count[col-P1.x] << endl;
}
//cout << " O quadrado " << i << " tem " << count_Den << " pontos " << endl;
if (count_Den > 20)
{
new_Center.x = count_Num / count_Den;
control_line[i] = new_Center.x;
}
else
{
control_line[i] = -1;
//cout << "Centro anterior [ " << i << " ]: ( " << previous_Central_Line[i].x << " , " << previous_Central_Line[i].y << " ) " << endl;
//cout << "Centro anterior [ " << i << " ]: " << previous_Central_Line[1].x << endl;
}
Central_Line.push_back(new_Center);
iCentral_Line.push_back(new_Center);
if (i>0)
{
double aux = ( Central_Line[i].y - iCentral_Line[i-1].y )/( Central_Line[i].x - iCentral_Line[i-1].x ) ;
alpha[i-1] = ( atan(aux) * 180 ) / (double) PI;
//cout << "Alpha [ " << i-1 << " ]: " << alpha[i-1] << endl;
}
P1.x = new_Center.x - (l_rectangle/2);
P1.y = new_Center.y - (h_rectangle/2);
P2.x = new_Center.x + (l_rectangle/2);
P2.y = new_Center.y;
rectangle(out, P1, P2, Scalar(0,100,255), 2, 8, 0);
previous_Center = new_Center;
}
int count_aux = 0;
for (int j=0; j<num_rectangle; j++)
{
if(control_line[j] == -1)
count_aux++;
}
/*cout << "Descontinuidades " << count_aux << endl;
cout << "10 pcento do n retangulos " << 0.1 * num_rectangle << endl;*/
if ( count_aux > (int) ( 0.1 * num_rectangle ) )
current_line_view = 2; // pontilhada central
else if ( button.x > (in.rows)/2 )
current_line_view = 3; // continua direita
else if ( button.x < (in.rows)/2 )
current_line_view = 1; // continua esquerda
//cout << "Linha analisada " << current_line_view << endl;
polylines(out,iCentral_Line,0,Scalar(255,0,0),3,8,0);
char* sliding_window = "Sliding Window";
namedWindow(sliding_window, CV_WINDOW_NORMAL);
imshow(sliding_window, out);
}
void inverse_bird_Eyes(Mat& src, Mat& in, Mat& out)
{
out = src.clone();
int Rows = src.rows;
int Cols = src.cols;
Point2f src_vertices[4];
src_vertices[0] = Point( 0, Rows); //
src_vertices[1] = Point(0.30*Cols, 0.30*Rows); //
src_vertices[2] = Point(0.70*Cols, 0.30*Rows); //
src_vertices[3] = Point( Cols, Rows); //
Point2f dst_vertices[4];
dst_vertices[0] = Point( 0, 480);
dst_vertices[1] = Point( 0, 0);
dst_vertices[2] = Point(640, 0);
dst_vertices[3] = Point(640, 480);
Mat M = getPerspectiveTransform(dst_vertices, src_vertices);
perspectiveTransform(Central_Line, final_navegavel, M);
for(int i=0 ; i<final_navegavel.size() ; i++)
{
ifinal_navegavel.push_back(Point(final_navegavel[i].x, final_navegavel[i].y));
/*cout << "Ponto inicial: ( " << right_Line[i].x << " ; " << right_Line[i].y << " ) " << endl;
cout << "Ponto navegavel: ( " << navegavel_int[i].x << " ; " << navegavel_int[i].y << " ) " << endl;*/
}
polylines(out,ifinal_navegavel,0,Scalar(255,0,0),3,8,0);
}
/*void inverse_bird_Eyes_2(Mat& src, Mat& in, Mat& out)
{
out = src.clone();
perspectiveTransform(navegavel, final_navegavel, transformationMat.inv());
for(int i=0 ; i<navegavel.size() ; i++)
{
final_navegavel_int.push_back(Point(final_navegavel[i].x, final_navegavel[i].y));
//cout << "Ponto inicial: ( " << right_Line[i].x << " ; " << right_Line[i].y << " ) " << endl;
//cout << "Ponto navegavel: ( " << navegavel_int[i].x << " ; " << navegavel_int[i].y << " ) " << endl;
}
warpAffine(in,out,trans_mat.inv(),in.size());
polylines(out,final_navegavel_int,1,Scalar(255,0,0),3,8,0);
}*/
float shift_Central(Mat& in)
{
float frame_center = in.cols / 2;
float shift;
float shift_num = 0;
float shift_den = 0;
line(in,Point(frame_center,0),Point(frame_center,in.rows),Scalar(0,255,0),3,8,0);
for(int i=0; i < Central_Line.size(); i++)
{
shift_num += frame_center - Central_Line[i].x;
shift_den++;
}
shift = shift_num/shift_den;
cout << "Deslocamento da linha central (em pixeis): " << shift << endl;
} | true |
dc1ba3320be94e7bb9809fa76b18bd4dbbba4fe0 | C++ | waterproofpatch/c_chat_app | /src/shared/list.hpp | UTF-8 | 2,562 | 3.40625 | 3 | [] | no_license | #ifndef _LIST_H_
#define _LIST_H_
#include <stddef.h>
typedef struct _list_node_t
{
struct _list_node_t *next;
void *element;
} list_node_t;
typedef struct _list_t
{
list_node_t *head;
list_node_t *tail;
void *(*list_malloc)(size_t);
void (*list_free)(void *);
size_t count;
} list_t;
/**
* @brief create a list object
* @param list_malloc: the allocator to use for creating list nodes
* @param list_free: the free function to use for desrtoying list nodes
* @return a ptr to a list_t object
*/
list_t *list_init(void *(*list_malloc)(size_t), void (*list_free)(void *));
/**
* @brief destroy a list. DOES free elements
* @param list: the list to destroy
* @return: void
*/
void list_destroy(list_t *list);
/**
* @brief add an element to the list (shallow copy)
* @param list: the list to add to
* @paramm element: the element to add to the list
* @return: void
*/
void list_add(list_t *list, void *element);
/**
* @brief removal based on linux torvold's linked list impl. Does NOT free elements
* @param list: the list from which removal should occur
* @param element: the element to remove from the list
*/
void list_remove(list_t *list, void *element);
/**
* @brief invoke a function on each element in the list
* @param list: the list to process
* @param process_func: the function to invoke on each element of the list
* @param context: an opaquie context object to pass to the list
* @return: void
*/
void list_foreach(list_t *list, void (*process_func)(void *, void *), void *context);
/**
* @brief get an element at index
* @param list: the list to search
* @param index: the index into the list to get
* @return ptr to element in list at index 'index', NULL if no data found at index
*/
void* list_get_at_index(list_t* list, unsigned int index);
/**
* @brief searches the supplied list for an element with a key matching a supplied key.
* key_comparators should return 1 on a match, 0 otherwise.
* This function returns the first element that caused key_comparator to return 1.
* @param list: the list to search
* @param key_comparator: the supplied comparator function
* @param key: the key to pass along with the element to the key_comparator function
* @return: a ptr to the matching element if any found, NULL otherwise
*/
void *list_search(list_t *list, char (*key_comparator)(void *, void *), void *key);
/**
* @brief get the count of the list
* @param] list: the list to get the count of
* @return: the size of the list
*/
size_t list_count(list_t *list);
#endif | true |
cece9e6c972747d32b36ab4095b57af3922cc203 | C++ | mitdart/2DEngine | /src/core/objects/gameobject.h | UTF-8 | 2,970 | 3.046875 | 3 | [] | no_license | #ifndef GAMEOBJECT_H
#define GAMEOBJECT_H
#include <string>
#include <vector>
#include <typeinfo>
#include "../object_components/renderer.h"
#include "../object_components/basicscript.h"
#include "../object_components/rectcollider.h"
#include "../object_components/physicalbody.h"
#include <iostream>
#include "../object_components/gameobjectcomponent.h"
#include <SFML/Graphics.hpp>
namespace engine
{
class GameObject
{
public:
~GameObject();
GameObject();
GameObject(std::string m_name);
std::string name;
sf::Vector2f position;
sf::Vector2f direction;
std::vector<GameObjectComponent*> components;
void setPosition(int x, int y);
template <typename ComponentType>
void addComponent();
template <typename ComponentType>
ComponentType* getComponent();
template <typename ComponentType>
bool hasComponent();
void registerObjectScript(GameObjectComponent* script);
void unregisterObjectScript(GameObjectComponent* script);
void registerObjectRenderer(GameObjectComponent* renderer);
void unregisterObjectRenderer(GameObjectComponent* renderer);
void registerObjectRectCollider(GameObjectComponent* collider);
void unregisterObjectRectCollider(GameObjectComponent* collider);
void registerObjectPhysicalBody(GameObjectComponent* physBody);
void unregisterObjectPhysicalBody(GameObjectComponent* physBody);
};
template <typename ComponentType>
void GameObject::addComponent()
{
ComponentType* component = new ComponentType;
component->name = typeid(ComponentType).name();
component->parentObject = this;
components.push_back(component);
if (std::is_base_of<BasicScript, ComponentType>())
{
registerObjectScript(component);
}
if (typeid(ComponentType).name() == typeid(Renderer).name())
{
registerObjectRenderer(component);
}
if (typeid(ComponentType).name() == typeid(RectCollider).name())
{
registerObjectRectCollider(component);
}
if (typeid(ComponentType).name() == typeid(PhysicalBody).name())
{
registerObjectPhysicalBody(component);
}
}
template <typename ComponentType>
ComponentType* GameObject::getComponent()
{
for (auto component : components)
if (component->name == typeid(ComponentType).name())
{
ComponentType* wired = static_cast<ComponentType*>(component);
return wired;
}
}
template <typename ComponentType>
bool GameObject::hasComponent()
{
for (auto component : components)
if (component->name == typeid(ComponentType).name())
{
return true;
}
return false;
}
}
#endif // GAMEOBJECT_H
| true |
c45c82bb99717a904da7bbe0a02402dd9ee217ff | C++ | RamalhoDev/Roteiros | /Projeto_2/src/SistemaImobiliaria.cpp | UTF-8 | 11,467 | 2.625 | 3 | [] | no_license | #include <iostream>
#include <string>
#include "/home/rcr/Documentos/Backup_Mint/GITS/Roteiros/Projeto_2/includes/SistemaImobiliaria.h" //"SistemaImobiliaria.h"
#include "/home/rcr/Documentos/Backup_Mint/GITS/Roteiros/Projeto_2/includes/GerenteDePersistencia.h" //"GerenteDePersistencia.h"
#include "/home/rcr/Documentos/Backup_Mint/GITS/Roteiros/Projeto_2/includes/Imovel.h" //"Imovel.h"
using namespace std;
SistemaImobiliaria::SistemaImobiliaria(){} //Construtor de Sistema Imobiliaria
SistemaImobiliaria::~SistemaImobiliaria(){}
list <Imovel> SistemaImobiliaria:: getImoveis(){ //Lendo as Listas referentes a Sistema Imobiliaria
GerenteDePersistencia recupera;
list<Imovel> imovel = recupera.recuperaListaImoveis();
return imovel;
}
list <Imovel> SistemaImobiliaria:: getImoveisPorTipo(int tipo){ //Lendo as Listas referentes a Imoveis por Tipo
GerenteDePersistencia recupera;
list <Imovel> imovel = recupera.recuperaListaImoveis();
list <Imovel> imoveis;
for(Imovel &i : imovel){
if(i.getTipoDeImovel() == tipo){
imoveis.push_back(i);
}
}
return imoveis;
}
list <Imovel> SistemaImobiliaria::getImoveisPorTipoParaAlugar(int tipo){ //Lendo as Listas referentes a Imovel para alugar
GerenteDePersistencia recupera;
list <Imovel> imovel = recupera.recuperaListaImoveis();
list <Imovel> imoveis;
for(Imovel &i : imovel){
if(i.getTipoDeImovel() == tipo && i.getTipoOferta() == 0){
imoveis.push_back(i);
}
}
return imoveis;
}
list <Imovel> SistemaImobiliaria:: getImoveisParaAlugarPorBairro(string bairro){ //Lendo as Listas referentes a Imovel para alugar por Bairro
GerenteDePersistencia recupera;
list <Imovel> imovel = recupera.recuperaListaImoveis();
list <Imovel> imoveis;
for(Imovel &i : imovel){
if( ToUpper(bairro,i.getEndereco().getBairro()) && i.getTipoOferta() == 0){
imoveis.push_back(i);
}
}
return imoveis;
}
list <Imovel> SistemaImobiliaria:: getImoveisParaVenderPorBairro(string bairro){ //Lendo as Listas referentes a Imovel para vender por Bairro
GerenteDePersistencia recupera;
list <Imovel> imovel = recupera.recuperaListaImoveis();
list <Imovel> imoveis;
for(Imovel &i : imovel){
if(ToUpper(bairro,i.getEndereco().getBairro()) && i.getTipoOferta() == 1){
imoveis.push_back(i);
}
}
return imoveis;
}
list<Imovel> SistemaImobiliaria:: getImoveisPorCidade(string cidade){ //Lendo as Listas referentes a Imovel por Cidades
GerenteDePersistencia recupera;
list <Imovel> imovel = recupera.recuperaListaImoveis();
list <Imovel> imoveis;
for(Imovel &i: imovel){
cout << i.getEndereco().getCidade()<< endl;
if(ToUpper(cidade,i.getEndereco().getCidade())){
imoveis.push_back(i);
}
}
return imoveis;
}
Endereco SistemaImobiliaria::cadastrarEndereco(){ //Cadastramento de endereços dos Imoveis em geral
string cidade, bairro, logradouro, cep;
int numero;
cout<< "-------------------------------------\n";
cout <<"\t\t\tEndereço\n";
cout<< "-------------------------------------\n\n";
cout<< "Digite seu Logradouro: ";
getline(cin,logradouro);
cout<< "\nDigite seu Bairro: ";
getline(cin, bairro);
cout<< "\nDigite sua Cidade: ";
getline(cin, cidade);
cout<< "\nDigite seu CEP: ";
getline(cin, cep);
cout<< "\nDigite o numero do imovel: ";
cin>>numero;
getchar();
Endereco *endereco = new Endereco(logradouro, bairro, cidade, cep, numero);
return *endereco;
}
Casa* SistemaImobiliaria::cadastrarCasa(Endereco endereco, int tipoDeImovel){ //Cadastramento das informações especificas de uma Casa
Casa *casa;
int numPavimentos, numQuartos, tipoOferta;
double areaTerreno, areaConstruida, valor;
cout << "-------------------------------------\n";
cout << "\t\tEspecificações\n";
cout << "-------------------------------------\n\n";
cout << "\n Digite a quantidade o número de pavimentos da casa: ";
cin >> numPavimentos;
cout << "\n Digite a quantidade o número quartos da casa: ";
cin >> numQuartos;
cout << "\n Digite a área total da casa: ";
cin >> areaTerreno;
cout << "\n Digite a área construida da casa: ";
cin >> areaConstruida;
cout<< "\n-------------------------------------\n"
<<"\t\tValor\n"
<<"-------------------------------------\n\n";
cout << "Deseja alugar ou vender seu imovel ?\n"
<< "\t1 - Vender,\n"
<< "\t0 - Alugar.\n";
cin >> tipoOferta;
cout<<"Qual o valor do seu imovel?\n";
cin >> valor;
casa = new Casa(numPavimentos,numQuartos, areaTerreno, areaConstruida,tipoOferta, tipoDeImovel, valor, endereco);
getchar();
cout<<"\n\nImovel Cadastrado Com Sucesso!\n";
return casa;
}
Apartamento* SistemaImobiliaria::cadastrarApartamento(Endereco endereco, int tipoDeImovel){ //Cadastramento das informações especificas de um Apartamento
int numQuartos, vagasGaragem, tipoOferta;
double area, valor, valorCondominio;
string posicao;
Apartamento *apartamento;
cout << "-------------------------------------\n";
cout << "\t\tEspecificações\n";
cout << "-------------------------------------\n\n";
cout<<"\nDigite a quantidade o número quartos do apartamento: ";
cin>> numQuartos;
cout<<"\nDigite a quantidade de vagas na garagem disponiveis para o seu apartamento: ";
cin>>vagasGaragem;
cout<<"\nDigite o valor do condomínio: ";
cin>>valorCondominio;
cout<<"\nDigite a area do apartamento: ";
cin>>area;
getchar();
cout << "\nDigite a posicao do seu apartamento: ";
getline(cin, posicao);
cout<< "\n-------------------------------------\n"
<<"\t\tValor\n"
<<"-------------------------------------\n\n";
cout << "Deseja vender ou alugar seu imovel ?\n"
<< "\t1 - Vender,\n"
<< "\t0 - Aluga.\n";
cin >> tipoOferta;
cout << "Qual o valor do seu imovel?\n";
cin >> valor;
getchar();
apartamento = new Apartamento(posicao, numQuartos, vagasGaragem, valorCondominio, area, tipoOferta, tipoDeImovel, valor, endereco);
cout <<"\n\nImovel Cadastrado Com Sucesso!\n";
return apartamento;
}
Terreno* SistemaImobiliaria::cadastrarTerreno(Endereco endereco, int tipoDeImovel){ //Cadastramento das informações especificas de um Terreno
double area, valor;
int tipoOferta;
Terreno *terreno;
cout << "-------------------------------------\n";
cout << "\t\tEspecificações\n";
cout << "-------------------------------------\n\n";
cout << "Deseja vender ou alugar seu imovel ?\n"
<< "\t1 - Vender,\n"
<< "\t0 - Aluga.\n";
cin >> tipoOferta;
cout<<"Digite a área do seu terreno: "<<endl;
cin >> area;
cout<< "\n-------------------------------------\n"
<<"\t\tValor\n"
<<"-------------------------------------\n\n"
<<"Qual o valor do seu imovel?\n";
cin >> valor;
cout<<"\n\nImovel Cadastrado Com Sucesso!\n";
terreno = new Terreno(area,tipoOferta, tipoDeImovel, valor,endereco);
getchar();
return terreno;
}
bool SistemaImobiliaria::ToUpper(string entrada, string atributo){
string saidaUsuario;
for(int i = 0; i < entrada.size(); i++){
if(toupper(entrada[i]) == toupper(atributo[i]))
continue;
return false;
}
return true;
}
Flat* SistemaImobiliaria::cadastrarFlat(Apartamento *apartamento){ //Cadastramento das informações especificas de um Flat
string ar, internet, tv, lavanderia, limpeza, recepcao;
cout << "-------------------------------------\n";
cout << "\t\tEspecificações\n";
cout << "-------------------------------------\n\n";
cout << "\n\tPossui ar-condicionado ?\n"
<< "Insira S para Sim ou N para Nao: ";
cin >> ar;
cout << "\n\tPossui lavanderia ?\n"
<< "Insira S para Sim ou N para Nao: ";
cin >> lavanderia;
cout << "\n\tPossui limpeza ?\n"
<< "Insira S para Sim ou N para Nao: ";
cin >> limpeza;
cout << "\n\tPossui TV a cabo ?\n"
<< "Insira S para Sim ou N para Nao: ";
cin >> tv;
cout << "\n\tPossui Internet ?\n"
<< "Insira S para Sim ou N para Nao: ";
cin >> internet;
cout << "\n\tPossui recepcao ?\n"
<< "Insira S para Sim ou N para Nao: ";
cin >> recepcao;
Flat* flat = new Flat(ar,
internet,
tv,
lavanderia,
limpeza,
recepcao,
apartamento->getPosicao(),
apartamento->getNumQuartos(),
apartamento->getVagasGaragem(),
apartamento->getValorCondominio(),
apartamento->getArea(),
apartamento->getTipoOferta(),
apartamento->getTipoDeImovel(),
apartamento->getValor(),
apartamento->getEndereco());
return flat;
}
Studio* SistemaImobiliaria::cadastrarStudio( Flat *flat){ //Cadastramento das informações especificas de um Studio
string piscina, sauna, ginastica;
cout << "-------------------------------------\n";
cout << "\t\tEspecificações\n";
cout << "-------------------------------------\n\n";
cout << "\n\tPossui Sauna ?\n"
<< "Insira S para Sim ou N para Nao: ";
cin >> sauna;
cout << "\n\tPossui Piscina ?\n"
<< "Insira S para Sim ou N para Nao: ";
cin >> piscina;
cout << "\n\tPossui salão de Ginastica ?\n"
<< "Insira S para Sim ou N para Nao: ";
cin >> ginastica;
Studio* studio = new Studio(piscina,
sauna,
ginastica,
flat->getAr(),
flat->getInternet(),
flat->getTv(),
flat->getLavanderia(),
flat->getLimpeza(),
flat->getRecepcao(),
flat->getPosicao(),
flat->getNumQuartos(),
flat->getVagasGaragem(),
flat->getValorCondominio(),
flat->getArea(),
flat->getTipoOferta(),
flat->getTipoDeImovel(),
flat->getValor(),
flat->getEndereco());
return studio;
}
| true |
9b5c89c2abcb480cacc0f716e31732dd8919d46c | C++ | lsst-ts/ts_sal_runtime | /tcs/tcs/tpk/TopoApptTarget.cpp | UTF-8 | 6,787 | 2.625 | 3 | [] | no_license | /// \file TopoApptTarget.cpp
/// \brief Implementation of the topocentric apparent target class.
// D L Terrett
// Copyright CCLRC. All rights reserved.
#include "TopoApptTarget.h"
#include <stdexcept>
#include <string>
#include "slalib.h"
#include "ApptRefSys.h"
#include "ApptTarget.h"
#include "Site.h"
#include "TcsMutex.h"
#include "TopoApptRefSys.h"
#include "TopoApptTarget.h"
namespace {
int starin ( char[], int*, double*, double*);
}
namespace tpk {
/// Constructor from a vector position.
TopoApptTarget::TopoApptTarget(
const Site& site, ///< telescope site
const vector& pos ///< topocentric apparent position
) :
TrackingTarget(site),
mPositionTopoAppt(pos),
mT0TopoAppt(site.tai()),
mVelocityTopoAppt(0.0, 0.0, 0.0) {
// Update tracking frame position and rates.
update(mT0TopoAppt);
}
/// Constructor from a vector positions and tracking rates.
TopoApptTarget::TopoApptTarget(
const Site& site, ///< telescope site
const double& t0, ///< reference time (MJD)
const vector& pos, ///< topocentric apparent position at t0
const deltav& rate ///< displacement per day
) :
TrackingTarget(site),
mPositionTopoAppt(pos),
mT0TopoAppt(t0),
mVelocityTopoAppt(rate) {
// Replace zero reference time with now.
if ( mT0TopoAppt <= 0.0 ) {
mT0TopoAppt = site.tai();
}
// Update tracking frame position and rates.
update(site.tai());
}
/// Constructor from a right ascension and declination
TopoApptTarget::TopoApptTarget(
const Site& site, ///< telescope site
const double& ra, ///< topocentric apparent right ascension (radians)
const double& dec ///< topocentric apparent declination (radians)
) :
TrackingTarget(site),
mPositionTopoAppt(ra, dec),
mT0TopoAppt(site.tai()),
mVelocityTopoAppt(0.0, 0.0, 0.0) {
// Update tracking frame position and rates.
update(mT0TopoAppt);
}
/// Constructor from a right ascension and declination and rates.
TopoApptTarget::TopoApptTarget(
const Site& site, ///< telescope site
const double& t0, ///< reference time (MJD)
const double& ra, ///< topocentric apparent right ascension (radians)
const double& dec, ///< topocentric apparent declination (radians)
const double& radot, ///< rate in right ascension (radians/day)
const double& decdot ///< rate in declination (radians/day)
) :
TrackingTarget(site),
mPositionTopoAppt(ra, dec),
mT0TopoAppt(t0) {
// Compute displacement.
mVelocityTopoAppt = vector(ra + radot, dec + decdot) - vector(ra, dec);
// Replace zero reference time with now.
if ( mT0TopoAppt <= 0.0 ) {
mT0TopoAppt = site.tai();
}
// Update tracking frame position and rates.
update(site.tai());
}
/// Constructor with target specified as a string
/**
The target is assumed to be a star position specified as a
free-format string.
*/
TopoApptTarget::TopoApptTarget(
const Site& site, ///< telescope site
const std::string& starget ///< new target
) :
TrackingTarget(site)
{
// Decode the string.
int inptr = 1;
double ra, dec;
if ( starin( const_cast<char*>(starget.c_str()), &inptr, &ra, &dec ) ) {
throw std::runtime_error("Unable to decode target");
}
// Current time.
double t = site.tai();
// Store position.
mPositionTopoAppt = vector(ra, dec);
mT0TopoAppt = t;
mVelocityTopoAppt = deltav(0.0, 0.0, 0.0);
// Update tracking frame position and rates.
update(t);
}
/// Target position in another frame.
/**
\returns target position in specified frame
*/
vector TopoApptTarget::position(
const double& t, ///< TAI (MJD)
const RefSys& frame ///< coordinate reference system.
) const {
// Position in apparent at time t.
mMutex.lock();
vector p = mPositionTopoAppt + mVelocityTopoAppt * (t - mT0TopoAppt);
mMutex.unlock();
return frame.fromTopoAppt(t, mSite, p);
}
void TopoApptTarget::adjust(
const double& t,
const vector& pos
) {
// Create a temporary tracking frame target.
Target* target = mTrackFrame->target( mSite, pos);
// Get the target's position in Appt.
vector p = target->position(t, TopoApptRefSys());
// Store the new position and reference time.
mMutex.lock();
mPositionTopoAppt = p;
mT0TopoAppt = t;
mMutex.unlock();
// Delete the temporary target.
delete target;
// Update tracking frame position and rates.
update(t);
}
}
/*----------------------------------------------------------------------*/
namespace {
int starin ( char string[], int* iptr, double* ra, double* dec)
/*
** - - - - - - -
** s t a r i n
** - - - - - - -
**
** Decode a string representing a star position.
**
** The string contains the following fields:
**
** RA Dec
**
** where
**
** RA = right ascension in hours, minutes, seconds
** Dec = declination in degrees, minutes, seconds
**
** Example strings:
**
** "12 34 56.789 -01 23 45.67"
**
** Given:
** string char* string to be decoded
** iptr int* where to start decode (1 = first character)
**
** Returned:
** iptr int* advanced past decoded portion of string
** ra double* right ascension (radians)
** dec double* declination (radians)
**
** Function value:
** int status: 0 = OK
** -1 = error
**
** Called: slaDafin, slaDfltin, slaDbjin, slaKbj
**
** Notes:
**
** 1) Decoding is free-format, using the SLALIB/C functions slaDafin
** and slaDfltin. Separators can be whitespace or commas.
** Only minimal validation is performed.
**
** 2) Both RA and Dec must be present.
**
** Last revised December 17, 2003.
** Copyright CLRC and P.T.Wallace; all rights reserved.
*/
{
double r, d;
int jr, jd;
/* Decode. */
slaDafin ( string, iptr, &r, &jr );
slaDafin ( string, iptr, &d, &jd );
/* Check for omissions and errors. */
if ( jr > 0 || jd > 0 ) return -1;
/* Results. */
*ra = r * 15.0;
*dec = d;
return 0;
}
}
| true |
932d917c838a27cf56b43598f774dbf5983447f0 | C++ | Artvell/pract_5 | /Binary matrix/Solver.h | UTF-8 | 622 | 2.828125 | 3 | [] | no_license | #pragma once
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
class Solver {
public:
vector<vector<int>> matrix;
int strings, rows;
vector<int> deleted;
ifstream in;
ofstream out;
string filename;
Solver(string name) {
filename = name;
}
int openWrite(); //done
int maxUnitString(); //done
int deleteCrossRows(); //done
bool isZerosExists(int ind);
int writeAnswer();
int solve();
int isExists(int n);
void print() {
for (int i = 0; i < matrix.size(); i++) {
for (int j = 0; j < matrix[i].size(); j++) {
cout << matrix[i][j] << " ";
}
cout << "\n";
}
}
}; | true |
9d4d65657c7200bcb68e165ddca3d2d3af238d6f | C++ | hunkarlule/Cpp_Studies | /Cpp_common_data_structures/ordering-system.cpp | UTF-8 | 1,776 | 3.953125 | 4 | [] | no_license | #include <iostream>
#include <queue>
using namespace std;
class MerchOrderSystem
{
private:
queue<int> regularOrders;
queue<int> priorityOrders;
public:
void place_order(int orderID, bool isPriority = false) {
if (isPriority) {
cout << "Placing the order " << orderID << " to priority orders queue." << endl;
priorityOrders.push(orderID);
}
else {
cout << "Placing the order " << orderID << " to regular orders queue." << endl;
regularOrders.push(orderID);
}
}
int fulfill_order() {
int processedOrderID = -1;
if (!priorityOrders.empty()) {
processedOrderID = priorityOrders.front();
cout << "Processing order: " << processedOrderID << endl;
priorityOrders.pop();
}
else {
if (!regularOrders.empty()) {
processedOrderID = regularOrders.front();
cout << "Processing order: " << processedOrderID << endl;
regularOrders.pop();
}
else {
cout << "There are no orders to process." << endl;
}
}
return processedOrderID;
}
};
int main()
{
MerchOrderSystem orderSystem; // Instantiate MerchOrderSystem object
// Placing some orders
orderSystem.place_order(201); // Regular order
orderSystem.place_order(202); // Regular order
orderSystem.place_order(101, true); // Priority order
orderSystem.place_order(203); // Regular order
// Fulfilling all orders
int orderID;
while ((orderID = orderSystem.fulfill_order()) != -1)
{
cout << "Order with ID " << orderID << " has been fulfilled.\n";
}
return 0;
} | true |
250349c3734fc17f26f24fb611613943d073478b | C++ | pconrad/old_pconrad_cs16 | /15W/lect/01.12/funcDemo.cpp | UTF-8 | 318 | 3.25 | 3 | [] | no_license | #include <iostream>
#include <cstdlib>
using namespace std;
int findSum(int num1, int num2);
int main(int argc, char *argv[]) {
int a = atoi(argv[1]);
int b = atoi(argv[2]);
int sum = findSum(a,b);
cout << "sum=" << sum << endl;
return 0;
}
int findSum(int num1, int num2) {
return num1 + num2;
}
| true |
a0bcc320250073a12b83f4f3eb32186e6c21489e | C++ | SelAD/cocos2dx-games | /MyLinker/Classes/LinkLogic.cpp | UTF-8 | 3,781 | 2.859375 | 3 | [] | no_license | //
// LinkLogic.cpp
// MyLinker
//
// Created by zhouf369 on 14-8-18.
//
//
#include "LinkLogic.h"
#include "Icon.h"
#include "GameMapLayer.h"
bool LinkLogic::canFadeAway(Icon *first, Icon *second)
{
if (checkLine(first, second)
|| checkOneCorner(first, second)
|| checkTwoCorner(first, second))
{
return true;
}
return false;
}
bool LinkLogic::checkLine(Icon *first, Icon *second)
{
int dy = first->getRow() - second->getRow();
int dx = first->getCol() - second->getCol();
int next = 0;
Icon *pNextIcon = NULL;
if (dx == 0)
{
for (int i = 0; i < abs(dy); i++)
{
if (dy < 0)
{
next++;
}
else
{
next--;
}
pNextIcon = GameMapLayer::getIconAtRowAndCol(first->getRow()+next, first->getCol());
if (pNextIcon == second)
{
return true;
}
else if (!pNextIcon->getDestroyed())
{
return false;
}
}
}
else if (dy == 0)
{
for (int i = 0; i < abs(dx); i++)
{
if (dx < 0)
{
next++;
}
else
{
next--;
}
pNextIcon = GameMapLayer::getIconAtRowAndCol(first->getRow(), first->getCol()+next);
if (pNextIcon == second)
{
return true;
}
else if (!pNextIcon->getDestroyed())
{
return false;
}
}
}
return false;
}
bool LinkLogic::checkOneCorner(Icon *first, Icon *second)
{
int iCornerRow1 = first->getRow();
int iCornerCol1 = second->getCol();
Icon *pCornerIcon1 = GameMapLayer::getIconAtRowAndCol(iCornerRow1, iCornerCol1);
if (pCornerIcon1->getDestroyed() && checkLine(first, pCornerIcon1) && checkLine(pCornerIcon1, second))
{
return true;
}
int iCornerRow2 = second->getRow();
int iCornerCol2 = first->getCol();
Icon *pCornerIcon2 = GameMapLayer::getIconAtRowAndCol(iCornerRow2, iCornerCol2);
if (pCornerIcon2->getDestroyed() && checkLine(first, pCornerIcon2) && checkLine(pCornerIcon2, second))
{
return true;
}
return false;
}
bool LinkLogic::checkTwoCorner(Icon *first, Icon *second)
{
for (int i = first->getRow()+1; i < GameMapLayer::m_iMapRow; i++)
{
Icon *pIcon = GameMapLayer::getIconAtRowAndCol(i, first->getCol());
if (!pIcon->getDestroyed())
{
break;
}
else if (checkOneCorner(pIcon, second))
{
return true;
}
}
for (int i = first->getRow()-1; i >= 0; i--)
{
Icon *pIcon = GameMapLayer::getIconAtRowAndCol(i, first->getCol());
if (!pIcon->getDestroyed())
{
break;
}
else if (checkOneCorner(pIcon, second))
{
return true;
}
}
for (int i = first->getCol()+1; i < GameMapLayer::m_iMapCol; i++)
{
Icon *pIcon = GameMapLayer::getIconAtRowAndCol(first->getRow(), i);
if (!pIcon->getDestroyed())
{
break;
}
else if (checkOneCorner(pIcon, second))
{
return true;
}
}
for (int i = first->getCol()-1; i >= 0; i++)
{
Icon *pIcon = GameMapLayer::getIconAtRowAndCol(first->getRow(), i);
if (!pIcon->getDestroyed())
{
break;
}
else if (checkOneCorner(pIcon, second))
{
return true;
}
}
return false;
} | true |
ab9272b531bd38253a18416bdd6736f819b123ee | C++ | sjb8100/FishEngine-Experiment | /Include/FishEngine/Application.hpp | UTF-8 | 822 | 2.75 | 3 | [
"MIT"
] | permissive | #pragma once
#include <string>
namespace FishEditor
{
class EditorApplication;
}
namespace FishEngine
{
class Application final
{
public:
static Application& GetInstance()
{
static Application instance;
return instance;
}
// The value depends on which platform you are running on:
// Unity Editor: <path to project folder>/Assets
// Mac player: <path to player app bundle>/Contents
// Win/Linux player: <path to executablename_Data folder> (note that most Linux installations will be case-sensitive!)
const std::string& GetDataPath() const
{
return m_DataPath;
}
private:
Application() = default;
Application(const Application&) = delete;
const Application& operator=(const Application&) = delete;
friend class FishEditor::EditorApplication;
std::string m_DataPath;
};
} | true |
b20c6e26b25b42fbe6799d16006d48f8734c41d4 | C++ | sgzwiz/xbox_leak_may_2020 | /xbox_leak_may_2020/xbox trunk/xbox/private/xdktools/dvdutil/xbpremaster/CXmlNode.h | UTF-8 | 3,062 | 2.703125 | 3 | [] | no_license | // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//
// File: CXmlNode.h
// Contents: Simple XML generation class
// Revisions: 4-Jun-2001: Created (jeffsim)
//
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// ++++ DEFINES +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// MAX_XML_ATTRIBUTES -- Maximum number of attributes in an XML node.
#define MAX_XML_ATTRIBUTES 10
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// ++++ CLASSES +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Forward Class declarations
class CFile;
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Class: CXmlNode
// Purpose: A single node in an XML tree. Can be root, middle, or leaf node.
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
class CXmlNode
{
public:
// ++++ CONSTRUCTION-RELATED FUNCTIONS ++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// CXmlNode -- CXmlNode Constructor
CXmlNode(char *szName);
// ~CXmlNode -- CXmlNode Destructor
~CXmlNode();
// ++++ MISCELLANEOUS FUNCTIONS +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// AddElement -- Creates a new CXmlNode and adds it to our list of child ndoes
CXmlNode *AddElement(char *szName);
// AddAttr -- Adds a new attribute to this node
void AddAttr(char *szName, char *szValue);
// WriteToFile -- Dumps this node's XML tree to the specified file in human-readable format.
HRESULT WriteToFile(CDlg *pdlg, CFile *poutfile, int nDepth);
private:
// m_rgpxnChildren -- The list this node's of child nodes.
CXmlNode **m_rgpxnChildren;
// m_cpxnAlloc -- The maximum size of the m_rgpxnChildren array
int m_cpxnAlloc;
// m_cChildren -- The number of child nodes.
int m_cChildren;
// m_rgszAttrName -- The list of attribute names.
char m_rgszAttrName[MAX_XML_ATTRIBUTES][100];
// m_rgszAttrValue -- The list of attribute values.
char m_rgszAttrValue[MAX_XML_ATTRIBUTES][100];
// m_cAttrs -- The number of attributes this node has
int m_cAttrs;
// m_szName -- This node's name
char m_szName[100];
};
| true |
3bcb5ff714f0761ceb38eebecb60937f3f4b69a6 | C++ | HrshWardhan/Competetive-Programming-Stuff | /ds/string.cpp | UTF-8 | 1,219 | 2.90625 | 3 | [] | no_license | /// Name: String processing
/// Description: CP algo mainly
/// Detail: Suffix Structures padh le bc :(
/// Guarantee: struct FU {
vector<int> prefix_function(string &s){
int n = (int)s.size();
vector<int> pi(n);
for (int i = 1; i < n; i++) {
int j = pi[i-1];
while (j > 0 && s[i] != s[j])
j = pi[j-1];
if (s[i] == s[j])
j++;
pi[i] = j;
}
return pi;
}
vector<int> z_function(string s) {
int n = (int) s.length();
vector<int> z(n);
for (int i = 1, l = 0, r = 0; i < n; ++i) {
if (i <= r)
z[i] = min (r - i + 1, z[i - l]);
while (i + z[i] < n && s[z[i]] == s[i + z[i]])
++z[i];
if (i + z[i] - 1 > r)
l = i, r = i + z[i] - 1;
}
return z;
}
void compute_automaton(string s, vector<vector<int>>& aut) {
s += '#';
int n = s.size();
vector<int> pi = prefix_function(s);
aut.assign(n, vector<int>(26));
for (int i = 0; i < n; i++) {
for (int c = 0; c < 26; c++) {
if (i > 0 && 'a' + c != s[i])
aut[i][c] = aut[pi[i-1]][c];
else
aut[i][c] = i + ('a' + c == s[i]);
}
}
} | true |
d236240a531b9350228bb55151b03601fd0bde70 | C++ | AlbertaSat/ex2_sdr | /include/pdu/pdu.hpp | UTF-8 | 1,598 | 2.890625 | 3 | [] | no_license | /*!
* @file pdu.h
* @author Steven Knudsen
* @date April 13, 2021
*
* @details The based Protocol Data Unit class. It encapsulates a payload
* vector that is either @p uint8_t, @p uint32_t, @p float, @p complex<float>,
* or @p complex<double>
*
* @copyright University of Alberta 2021
*
* @license
* This software may not be modified or distributed in any form, except as described in the LICENSE file.
*/
#ifndef EX2_SDR_PDU_PDU_H_
#define EX2_SDR_PDU_PDU_H_
#include <cstdint>
#include <vector>
namespace ex2 {
namespace sdr {
template <class T>
class PDU {
public:
/*!
* @brief Payload type
*/
typedef std::vector<T> payload_t;
/*!
* @brief Constructor
*/
PDU () {};
/*!
* @brief Constructor
*
* @param[in] payload The PDU payload, which is copied.
*/
PDU (payload_t payload) {
m_payload.reserve(payload.size());
for (uint32_t i = 0; i < payload.size(); i++)
m_payload.push_back(payload[i]);
};
virtual
~PDU () {};
/*!
* @brief Accessor - payload
*
* @return payload
*/
const payload_t& getPayload() const {
return m_payload;
}
/*!
* @brief The number of payload elements.
*
* @return The number of payload elements.
*/
unsigned long
payloadLength () const {
return m_payload.size();
}
protected:
payload_t m_payload;
};
} /* namespace sdr */
} /* namespace ex2 */
#endif /* EX2_SDR_PDU_PDU_H_ */
| true |
4c297198a19e06efce16fb466e5e16fe3a436a10 | C++ | derekrose/cpp-protobuf | /example/hello/persion.h | UTF-8 | 772 | 2.8125 | 3 | [
"Apache-2.0"
] | permissive | #ifndef _PERSON_H
#define _PERSON_H
#include <core.h>
#include <string>
#include <vector>
using std::string;
using std::vector;
Serializable
class Person
{
Field(required,1,3) //Field(repeated,seq=1,def=3)
int mId;
Field(optional,2,"shgli")
string mName;
Field(repeated,3)
vector<int> mFriends;
public:
Method(OnSerializing)
void OnSerialing();
Method(OnSerialized)
void OnSerialized();
Method(OnDeserializing)
void OnDeserializing();
Method(OnDeserialized)
void OnDeserialized();
int Id() const { return mId; }
void Id(int id) { mId = id; }
const string& Name()const { return mName;}
void Name(const string name) { mName = name;}
vector<int> Friends() { return mFriends; }
};
#endif
| true |
06b2e377887e8a71432446fed273ddc4e057dc13 | C++ | iYaphetS/CPP | /类简例/point.cpp | UTF-8 | 165 | 2.59375 | 3 | [] | no_license | #include "point.h"
void point::set_x(int x)
{
_x = x;
}
void point::set_y(int y)
{
_y = y;
}
int point::get_x()
{
return _y;
}
int point::get_y()
{
return _y;
} | true |
9db2dacedc2824a10236375a8e4eff622d5fabe8 | C++ | theanik/CompetitiveProgramming | /codeforces/Translation.cpp | UTF-8 | 290 | 2.859375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(){
string s;
string t;
string o;
cin>>s;
cin>>o;
for(int i = s.length() - 1; i >= 0 ; i--) {
t+=s[i];
}
if(o == t) {
cout<<"YES";
} else {
cout<<"NO";
}
return 0;
}
| true |
845212c3bba48138196786babfa7a178839fbeb0 | C++ | carvalhojldc/mlp | /mlp.h | UTF-8 | 3,845 | 3.140625 | 3 | [] | no_license | #ifndef MLP_H
#define MLP_H
#include "layer.h"
class MLP
{
private:
std::vector<Layer> network;
std::vector<double> insertThreshold(std::vector<double> input)
{
std::vector<double> newInput;
newInput.push_back(-1);
newInput.insert(newInput.end(), input.begin(), input.end());
return newInput;
}
double getError(std::vector<double> d, std::vector<double> y)
{
double error = 0.0;
for(int i=0; i<d.size(); i++)
error += pow(d[i]-y[i],2);
error *= (1./d.size());
return error;
}
double forward(std::vector<double> X)
{
std::vector<double> inputs;
std::vector<double> outputs;
Layer * layer;
Neuron * neuron;
inputs = insertThreshold(X);
// run of all layers of the network
for(int l=0; l<network.size(); l++)
{
layer = &(network[l]);
outputs.clear();
// run of all neurons of layer(l)
for(int n=0; n<layer->neurons.size(); n++)
{
neuron = &(layer->neurons[n]);
neuron->setWeightedInput(inputs);
outputs.push_back( neuron->getOutput() );
}
inputs = insertThreshold(outputs);
}
return outputs[0];
}
void backForward(int x, std::vector<double> d, double learningRate)
{
Layer * layer;
Neuron * neuron;
int lastLayer = network.size()-1;
for(int l=lastLayer; l>=0; l--)
{
layer = &(network[l]);
if(l == lastLayer) // last layer
{
std::vector<double> dataD;
dataD.push_back(d[x]);
for(int n=0; n<layer->neurons.size(); n++)
{
neuron = &(layer->neurons[n]);
neuron->sigma = (dataD[n]-neuron->getOutput())*neuron->getOutput_d();
neuron->updateWeights(learningRate);
}
}
else // others layers
{
Layer * nextLayer = &(network[l+1]);
Neuron * neuronNextLayer;
for(int n=0; n<layer->neurons.size(); n++)
{
neuron = &(layer->neurons[n]);
neuron->sigma = 0.0;
for(int nl=0; nl<nextLayer->neurons.size(); nl++)
{
neuronNextLayer = &(nextLayer->neurons[nl]);
neuron->sigma += (neuronNextLayer->sigma*neuronNextLayer->weights[n+1]);
}
neuron->sigma *= neuron->getOutput_d();
neuron->updateWeights(learningRate);
}
}
}
}
public:
MLP(std::vector<int> network)
{
for(int i=1; i<network.size(); i++)
this->network.push_back( Layer(network[i], network[i-1]) );
}
void fit(std::vector<std::vector<double>> X, std::vector<double> d, \
int epochs, double learningRate, double mse)
{
std::vector<double> y;
double error;
int contEpochs = 1;
for(int i=0; i<d.size(); i++)
y.push_back(0);
printf("Training [ learningRate: %lf, mse: %lf ] ... \n", learningRate, mse);
do
{
for(int x=0; x<X.size(); x++)
{
y[x] = forward(X[x]);
backForward(x, d, learningRate);
}
error = getError(d, y);
contEpochs++;
}
while((contEpochs <= epochs) && (error > mse));
printf("\nfinish: [ epochs: %d, error: %lf ]\n", contEpochs, error );
}
double process(std::vector<double> X)
{
return forward(X);
}
};
#endif // MLP_H
| true |
4fadbcb1d2d34ade417de20360c0396c2d5603c0 | C++ | dronDrew/home_work_week4 | /home_work_week4/string_check.cpp | UTF-8 | 1,884 | 3.25 | 3 | [] | no_license | #include "string_check.h"
string_check::element_check::element_check(char data) {
this->data = data;
this->next_adress = nullptr;
}
string_check:: string_check(const char* a) {
this->top = nullptr;
for (int i = 0; i < strlen(a); i++)
{
if (a[i] == 46 || a[i] == 59) {
std::cout << std::boolalpha << this->is_corect() <<std::endl;
}
if (a[i] == 40 || a[i] == 41 || a[i] == 91 || a[i] == 93 || a[i] == 123 || a[i] == 125) {
if ((last() == 40 && a[i] == 41) || (last() == 91 && a[i] == 93) || (last() == 123 && a[i] == 125)) {
Pop_elem();
//show();
}
else
{
Add_elem(a[i]);
//show();
//this->a += a[i];
}
}
}
}
void string_check::Add_elem(char a) {
if (this->top == nullptr) {
top = new element_check(a);
}
else
{
element_check* temp = this->top;
while (temp->next_adress!=nullptr)
{
temp = temp->next_adress;
}
temp->next_adress = new element_check(a);
}
}
void string_check::Pop_elem() {
if (this->top == nullptr) {
}
else
{
int i = 0;
element_check* temp = this->top;
while (temp->next_adress != nullptr)
{
temp = temp->next_adress;
i++;
}
if (i==0) {
temp = this->top;
delete temp;
temp = nullptr;
this->top = temp;
}
else
{
i--;
temp = this->top;
while (i > 0)
{
i--;
temp = temp->next_adress;
}
delete temp->next_adress;
temp->next_adress = nullptr;
}
}
}
void string_check::show() {
element_check* temp = this->top;
while (temp != nullptr)
{
std::cout << temp->data << std::endl;
temp = temp->next_adress;
}
}
char string_check::last() {
if (this->top == nullptr) {
return 0;
}
element_check* temp = this->top;
while (temp->next_adress != nullptr)
{
temp = temp->next_adress;
}
return temp->data;
}
bool string_check::is_corect() {
if (this->top==nullptr)
{
return true;
}
else {
return false;
}
}
| true |
44eacdf07c65f19a9e788022136eab6d9b2086fb | C++ | yingziyu-llt/OI | /c/2018noip/competition/2018.10.3/林乐天/prime/prime.cpp | UTF-8 | 591 | 2.828125 | 3 | [] | no_license | #include<stdio.h>
#include<string.h>
#include<math.h>
bool isprime[1000010];
void makep(int maxn)
{
float sqrtmax = sqrt(maxn);
for(int i = 2 ;i <= sqrtmax;i++)
{
if(!isprime[i]) continue;
for(int j = 2;i * j <= maxn;j++)
{
isprime[i * j] = false;
}
}
}
int main()
{
freopen("prime.in","r",stdin);
freopen("prime.out","w",stdout);
memset(isprime,1,sizeof(isprime));
int a,b;
scanf("%d%d",&a,&b);
isprime[0] = isprime[1] = false;
makep(b);
int ans = 0;
for(int i = a;i <= b;i++)
if(isprime[i])
ans++;
printf("%d",ans);
return 0;
} | true |
18f5613b2ac6ff6baea8f2515438d24c87c70517 | C++ | Raj-kar/C-programs- | /prac56.cpp | UTF-8 | 291 | 2.71875 | 3 | [] | no_license | #include<stdio.h>
int main()
{
int max,min,i,j,a[10],n;
printf("enter range::");
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
min=max=a[0];
for(i=0;i<n;i++)
{
if(a[i]>max)
max=a[i];
if(a[i]<min)
min=a[i];
}
printf("min=%d \n max=%d",min,max);
}
| true |
c9a430c655e8020c0a3d94189740b9c3adc10ea0 | C++ | upupming/algorithm | /acwing/算法基础课/第五讲 动态规划/背包问题/3. 完全背包问题.cpp | UTF-8 | 810 | 3.09375 | 3 | [
"MIT"
] | permissive | /*
f[i][j]:前i个物品,背包容量j下的最大价值
第 i 个物品选 k 个,k = 0, 1, ...
f[i-1][j-k*v[i]]+k*w[i]
朴素的做法时间复杂度为 O(NM*M) = O(NM^2)
观察:
f[i][j] = max(f[i-1][j], f[i-1][j-v]+w, f[i-1][j-2v]+2w, ...)
f[i][j-v] = max(f[i-1][j-v], f[i-1][j-2v]+w, f[i-1][j-3v]+2w, ...)
发现:
f[i][j] = max(f[i-1][j], f[i][j-v]+w)
*/
#include <iostream>
using namespace std;
const int N = 1010;
int n, m, v[N], w[N], g[N];
void loop_optimized() {
for (int i = 1; i <= n; i++) {
for (int j = v[i]; j <= m; j++) {
g[j] = max(g[j], g[j - v[i]] + w[i]);
}
}
cout << g[m] << endl;
}
int main() {
cin >> n >> m;
for (int i = 1; i <= n; i++) {
cin >> v[i] >> w[i];
}
loop_optimized();
return 0;
}
| true |
b1f56cc4b4cc9990da22eca741a5d10bdf1e5697 | C++ | NicolasVillalba/CS_exe | /00_Linux_Progreamming/02_Process/04_wait.cpp | UTF-8 | 421 | 2.78125 | 3 | [] | no_license | ///
/// @file 04_wait.cpp
/// @author AverageJoeWang(AverageJoeWang@gmail.com)
///
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
using std::cout;
using std::endl;
int main()
{
pid_t pid = fork();
if(pid == 0)
exit(10);
else
{
wait(NULL);//NULL表示等待所有进程
sleep(10);//将sleep放在wait后面,否则会出现僵尸进程
}
}
| true |
6e1c148decf7adbdc24f739b87534fec66096e5a | C++ | anveshh/cpp-book | /src/Leetcode/1394_find-lucky-integer-in-an-array.cpp | UTF-8 | 643 | 3.390625 | 3 | [] | no_license | // https://leetcode.com/problems/find-lucky-integer-in-an-array/
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int findLucky(vector<int> &arr)
{
int freq;
int res = -1;
for (int i = 0; i < arr.size(); i++)
{
freq = 0;
for (int j = 0; j < arr.size(); j++)
if (arr[i] == arr[j])
freq++;
if (freq == arr[i])
res = max(arr[i], res);
}
return res;
}
};
int main()
{
Solution a;
vector<int> in = {2, 2, 2, 3, 3};
cout << a.findLucky(in) << endl;
return 0;
} | true |
fb767ad06b9150c67e0fd9dde9c15c0a289d9d0f | C++ | tiqwab/atcoder | /abc160/c/main.cpp | UTF-8 | 738 | 2.71875 | 3 | [] | no_license | #include <algorithm>
#include <cassert>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <vector>
using namespace std;
typedef long long ll;
template<class T>
inline bool chmax(T &a, T b) {
if(a < b) {
a = b;
return true;
}
return false;
}
template<class T>
inline bool chmin(T &a, T b) {
if(a > b) {
a = b;
return true;
}
return false;
}
vector<ll> A;
int main(void) {
ll K, N;
cin >> K >> N;
A.resize(N + 1);
for (int i = 0; i < N; i++) {
cin >> A[i];
}
A[N] = K + A[0];
ll ans = K;
for (int i = 1; i <= N; i++) {
chmin(ans, K - (A[i] - A[i - 1]));
}
cout << ans << endl;
return 0;
}
| true |
062ccf38aebaf58885f93fdbeb9b122d75c42ca2 | C++ | rranjik/ideal-octo-barnacle | /1208-GetEqualSubstringsWithinBudget.cpp | UTF-8 | 875 | 2.84375 | 3 | [] | no_license | class Solution {
public:
int equalSubstring(string s, string t, const int maxCost) {
vector<int> d;
for(int i = 0; i<s.length(); i++){
d.push_back(abs(s[i]-t[i]));
}
// for(const auto& n : d){
// //cout<<n<<"\t";
// }
int res = 0;
for(int i = 0; i<d.size(); i++){
int mx = maxCost;
for(int j = i; j<d.size()&&mx>=0; j++){
mx-=d[j];
if(mx>=0){
res = max(res, j-i+1);
}
else
break;
}
}
for(int i = 0; i<d.size(); i++){
int c = 0;
for(int j = i; j<d.size(); j++){
c+=d[j];
if(c<=maxCost){
}
}
}
return res;
}
};
| true |
572f889875a452433165acd79b5ca8e0f335d6d8 | C++ | adi-075/C-HSC-Boards-2021 | /Introduction to C++/Practise Programs/time.cpp | UTF-8 | 764 | 3.484375 | 3 | [
"MIT"
] | permissive | #include <iostream>
using namespace std;
class Time{
int hrs, min;
public:
void read(int h, int m)
{
hrs=h;
min=m;
}
void display()
{
cout<<hrs<<":"<<min;
}
void add(Time t1, Time t2)
{
min = t1.min+t2.min;
hrs =t1.hrs+t2.hrs+ (min/60);
min = min%60;
}
};
int main()
{
Time T1,T2,T3;
cout<<"Read data for Time T1\n";
T1.read(4,34);
cout<<"Read data for Time T2\n";
T2.read(4,43);
cout<<"\nTime T1\n";
T1.display();
cout<<"\nTime T2\n";
T2.display();
cout<<"\n";
T3. add (T1,T2);
cout<<"\nTime T3\n";
T3.display();
return 0;
}
| true |
beb29615438f3062f54f9b42b95642154f182acd | C++ | PuppyRush/SDL2_Tetris_Client | /lib/SDL2EasyGUI/include/SEG_Event.h | WINDOWS-1252 | 3,699 | 2.640625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"Zlib"
] | permissive | //
// Created by chaed on 19. 2. 6.
//
#ifndef SDL2EASYGUI_EVENT_H
#define SDL2EASYGUI_EVENT_H
#include <cassert>
#include <type_traits>
#include <SDL2/SDL.h>
#include "SEG_Constant.h"
#include "SEG_Struct.h"
#include "SEG_TypeTraits.h"
#include "SEG_Resource.h"
namespace seg {
namespace event {
typedef struct SEG_Click
{
SEG_Point point = { INVALID_COORD, INVALID_COORD };
t_id resourceId = toUType(resource::NONE);
bool selected = false;
SEG_Click(const SEG_Point& point, const t_id& res, const bool sel)
: point(point), resourceId(res), selected(sel)
{}
} SEG_Click;
//must call by TimerAdder
Uint32 timerCallback(Uint32 interval, void* param);
typedef struct SEG_UserEventData
{
bool isDisplay = true; // display or control
t_id controlId = seg::NULL_WINDOW_ID;
t_timer timerId = seg::NULL_TIMER_ID;
}SEG_UserEventData;
class SEG_Timer final
{
public:
SEG_Timer(const t_id id, const Uint32 interval)
: m_interval(interval), m_id(id), m_userData(new SEG_UserEventData{})
{
m_userEvent.data1 = static_cast<void*>(m_userData);
m_userEvent.data2 = nullptr;
}
~SEG_Timer()
{
if(m_userData)
delete m_userData;
SDL_RemoveTimer(m_timerId);
}
inline SEG_Timer* timestamp(const Uint32 time)
{
this->m_userEvent.timestamp = time;
return this;
}
inline SEG_Timer* userEventData(SEG_UserEventData data)
{
*static_cast<SEG_UserEventData*>(this->m_userEvent.data1) = data;
return this;
}
template <typename T>
inline SEG_Timer* data(T* data)
{
this->m_userEvent.data2 = static_cast<void*>(data);
return this;
}
bool isStarted() const noexcept
{
return m_isStarted;
}
t_id getTimerId() const noexcept
{
return m_timerId;
}
t_timer start()
{
if (m_isStarted)
{
return NULL_TIMER_ID;
}
m_userEvent.timestamp = SDL_GetTicks();
m_userEvent.windowID = m_id;
m_timerId = SDL_AddTimer(m_interval, timerCallback, &m_userEvent);
m_userData->timerId = m_timerId;
if (m_timerId != 0)
{
m_isStarted = true;
}
return m_timerId;
}
void stop()
{
SDL_RemoveTimer(m_timerId);
m_isStarted = false;
m_timerId = NULL_TIMER_ID;
}
private:
const Uint32 m_interval;
SDL_UserEvent m_userEvent;
SEG_UserEventData* m_userData;
t_timer m_timerId;
t_id m_id = NULL_TIMER_ID;
bool m_isStarted = false;
};
class EventPusher
{
public:
EventPusher(const t_id winid, const t_eventType type, const t_eventType event)
:m_userData(new SEG_UserEventData{})
{
m_user.data1 = static_cast<void*>(m_userData);
m_user.type = type;
m_user.windowID = winid;
m_user.code = event;
m_event.type = type;
}
~EventPusher()
{
//data1 delete?
}
void setIsControl(bool b)
{
m_userData->isDisplay = b;
}
void setTargetId(t_eventType tid)
{
m_userData->controlId = tid;
}
template<class T>
void setUserData(T* data)
{
m_user.data2 = static_cast<void*>(data);
}
void pushEvent()
{
m_user.timestamp = SDL_GetTicks();
m_event.user = m_user;
SDL_PushEvent(&m_event);
}
private:
EventPusher()
{
m_user.data1 = nullptr;
m_user.data2 = nullptr;
}
SDL_Event m_event;
SDL_UserEvent m_user;
SEG_UserEventData* m_userData;
};
}
}
#endif //SDL2EASYGUI_EVENT_H
| true |
77e53a16d54d5ba64804f6a076296c014956408d | C++ | ayushchopra96/topologize | /rotation.cpp | UTF-8 | 3,156 | 3.03125 | 3 | [] | no_license | #include <bits/stdc++.h>
#include "header.h"
using namespace std;
float magnituide(struct vectr v)//magnituide of a vector
{
float mag = sqrt(v.x*v.x+v.y*v.y+v.z*v.z);
return mag;
}
struct vectr unitVector(struct vectr v)
{
struct vectr m;
float mag=magnituide(v);
m.x=v.x/mag;
m.y=v.y/mag;
m.z=v.z/mag;
return m;
}
float dotProduct(struct vectr a,struct vectr b)
{
return a.x*b.x + a.y*b.y + a.z*b.z;
}
struct vectr crossProduct(struct vectr a,struct vectr b)
{
struct vectr m;
m.x=a.y*b.z-b.y*a.z;
m.y=b.x*a.z-a.x*b.z;
m.z=a.x*b.y-b.x*a.y;
return m;
}
struct vectr multiplication(struct vectr v,float a)//scalar
{ //calculates a*v //vector multiplication with scalar quantity;
struct vectr m;
m.x=v.x*a;
m.y=v.y*a;
m.z=v.z*a;
return m;
}
struct vectr addition(struct vectr v,struct vectr v1)//scalar
{ //calculates v+v1
struct vectr m;
m.x=v.x+v1.x;
m.y=v.y+v1.y;
m.z=v.z+v1.z;
return m;
}
//editing the defition,errenously same as that for addition:- NOTE POINT..
struct vectr subtraction(struct vectr v,struct vectr v1)//scalar
{ //calculates v-v1
struct vectr m;
//m.x=v.x+v1.x;
//m.y=v.y+v1.y;
//m.z=v.z+v1.z;
m.x=v.x-v1.x;
m.y=v.y-v1.y;
m.z=v.z-v1.z;
return m;
}
struct vectr rotate(struct vectr v,struct vectr r,float theta)
{ //v vector to be rotated // vector along it is rotated // angle by which vector v is rotated
//using this link multiplication is adopted
//https://math.kennesaw.edu/~plaval/math4490/rotgen.pdf
const float pie=3.14159;
float angle=pie*theta/180;//converting into radian
//float angle=theta;
r=unitVector(r);
float temp=(1-cos(angle))*(dotProduct(v,r));
struct vectr a=multiplication(r,temp);
struct vectr b=multiplication(v,cos(angle));
struct vectr c=multiplication(crossProduct(r,v),sin(angle));
struct vectr d=addition(a,b);
d=addition(c,d);
return d;
}
/*void rotate_all_point(struct pdb pdbfile1[],int filelength1,struct vectr r)
{
r=unitVector(r);
struct vectr v;
for(int i=0;i<filelength1;i++)
{
v.x=pdbfile1[i].x2;
v.y=pdbfile1[i].y2;
v.z=pdbfile1[i].z2;
float angle=acos(dotProduct(v,r)/magnituide(v))*180/3.14159;
v=rotate(v,crossProduct(v,r),angle);
pdbfile1[i].x2=v.x;
pdbfile1[i].y2=v.y;
pdbfile1[i].z2=v.z;
}
}*/
void rotate_all_point(struct pdb pdbfile1[],int filelength1,struct vectr r)
{
struct vectr m;
struct vectr v;
for(int i=0;i<filelength1;i++)
{
m.x=pdbfile1[i].x2-r.x;
m.y=pdbfile1[i].y2-r.y;
m.z=pdbfile1[i].z2-r.z;
v.x=pdbfile1[i].x2;
v.y=pdbfile1[i].y2;
v.z=pdbfile1[i].z2;
m=unitVector(m);
float angle=acos(dotProduct(v,m)/magnituide(v))*180.0/3.14159;
v=rotate(v,crossProduct(v,m),angle);
pdbfile1[i].x2=v.x;
pdbfile1[i].y2=v.y;
pdbfile1[i].z2=v.z;
}
}
/*int main()
{
struct vectr v;v.x=1,v.y=0,v.z=0;
struct vectr r;r.x=0,r.y=1,r.z=0;
struct ans=rotate(v,r,90);
printf(" %f %f %f\n",ans.x,ans.y,ans.z);
}*/
| true |
2942064e77cc0c6950da8454b7cd80085231fca3 | C++ | YP-Yang-hub/Plane-Game | /src/car.cpp | UTF-8 | 2,662 | 3.359375 | 3 | [] | no_license |
#include "car.h"
#include <thread>
#include <iostream>
#include <string>
#include <mutex>
//copy constr
Car::Car(Car& src){
_xpos = src._xpos;
_ypos = src._ypos;
_delay = src._delay;
_active = src._active;
_speed = src._speed;
_limit = src._limit;
_axis = src._axis;
_succeeded = src._succeeded;
// mtx = src.mtx; // mtx is not assignable
};
void Car::move(){
// horizontal
// vertical
while(_active){
std::this_thread::sleep_for(std::chrono::milliseconds(_delay));
if (_axis == "horizontal"){
int x = get_xpos();
set_xpos( newPos(x));
//std::cout << "Car Thread #: " <<std::this_thread::get_id()<<" --- Pos ="<< _xpos<<std::endl;
}else{
int y = get_ypos();
set_ypos(newPos(y));
//std::cout << "Car Thread #: " <<std::this_thread::get_id()<<" --- Pos = " <<_ypos<<std::endl;
}
// reached to the correct place
if(get_xpos()< 15 && get_ypos() <15)
{
_active = false;
_succeeded = true;
}
}
// stopped in the correct place
if(get_xpos()< 15 && get_ypos() <15)
{
_succeeded = true;
}
//std::cout << std::this_thread::get_id()<< " thread is ending\n"<< std::endl;
};
int Car::newPos(int pos){
if (pos + _speed > _limit){
pos = _limit-5;// to make its edge visible
}else if(pos + _speed < 0){
pos = 0;
}else{
pos += _speed;
}
return pos;
};
void Car::setAxis(std::string axis){
// horizontal or vertical
_axis = axis;
}
void Car::setDirection(int d){
//+1 or -1
_speed = d * abs(_speed);
}
void Car::adjustDelay(int d){
_delay += d;
};
int Car::get_xpos(){
std::lock_guard lck(mtx);
return _xpos;
}
int Car::get_ypos(){
std::lock_guard lck(mtx);
return _ypos;
}
void Car::set_xpos(int x){
std::lock_guard lck(mtx);
_xpos = x;
}
void Car::set_ypos(int y){
std::lock_guard lck(mtx);
_ypos = y;
}
bool Car::get_success(){
std::lock_guard lck(mtx);
return _succeeded;
}
bool Car::isActive(){
std::lock_guard lck(mtx);
return _active;
}
void Car::set_active(bool a){
std::lock_guard lck(mtx);
_active = a;
}; | true |
37c67364f956674866dd7a01ea49ea6803457c9e | C++ | Franeiro/AyED | /Unidad 4/src/tickets.hpp | UTF-8 | 7,656 | 2.921875 | 3 | [] | no_license | #ifndef _MAINHPP
#define _MAINHPP
#include <iostream>
#include <iostream>
#include <sstream>
#include <string>
#include <string.h>
#include <stdlib.h>
#include "biblioteca/funciones/strings.hpp"
#include "biblioteca/funciones/tokens.hpp"
#include "biblioteca/tads/Coll.hpp"
using namespace std;
struct Producto
{
int idProd;
char descr[20];
double precio;
int idRub;
};
struct Rubro
{
int idRub;
char descr[20];
double promo;
};
struct Ventas
{
Producto productoComprado;
int cantidad;
};
struct Item
{
string descripcion;
double precio;
double precioConDescuento;
int cantidad;
};
struct RegistroProductos
{
Producto prod;
int contador;
};
struct RegistroRubro
{
Rubro rubro;
double ahorro;
};
string productoToString(Producto x)
{
char sep = 1;
string sIdProd = to_string(x.idProd);
string sDescr = x.descr;
string sPrecio = to_string(x.precio);
string sIdRub = to_string(x.idRub);
return sIdProd + sep + sDescr + sep + sPrecio + sep + sIdRub;
}
Producto productoFromString(string s)
{
char sep = 1;
Producto x;
string t0 = getTokenAt(s, sep, 0);
x.idProd = stoi(t0);
string t1 = getTokenAt(s, sep, 1);
strcpy(x.descr, t1.c_str());
string t2 = getTokenAt(s, sep, 2);
x.precio = stod(t2);
string t3 = getTokenAt(s, sep, 3);
x.idRub = stoi(t3);
return x;
}
string productoToDebug(Producto x)
{
stringstream sout;
sout << "[";
sout << x.idProd;
sout << ",";
sout << x.descr;
sout << ",";
sout << x.precio;
sout << ",";
sout << x.idRub;
sout << "]";
return sout.str();
}
Producto producto(int idProd, string descr, double precio, int idRub)
{
Producto a;
a.idProd = idProd;
strcpy(a.descr, descr.c_str());
a.precio = precio;
a.idRub = idRub;
return a;
}
bool productoEquals(Producto a, Producto b)
{
if (a.idProd != b.idProd)
return false;
if (a.precio != b.precio)
return false;
if (a.idRub != b.idRub)
return false;
return true;
}
string rubroToString(Rubro x)
{
char sep = 2;
string sIdRub = to_string(x.idRub);
string sDescr = x.descr;
string sPromo = to_string(x.promo);
return sIdRub + sep + sDescr + sep + sPromo;
}
Rubro rubroFromString(string s)
{
char sep = 2;
Rubro x;
string t0 = getTokenAt(s, sep, 0);
x.idRub = stoi(t0);
string t1 = getTokenAt(s, sep, 1);
strcpy(x.descr, t1.c_str());
string t2 = getTokenAt(s, sep, 2);
x.promo = stod(t2);
return x;
}
string rubroToDebug(Rubro x)
{
stringstream sout;
sout << "[";
sout << x.idRub;
sout << ",";
sout << x.descr;
sout << ",";
sout << x.promo;
sout << "]";
return sout.str();
}
Rubro rubro(int idRub, string descr, double promo)
{
Rubro a;
a.idRub = idRub;
strcpy(a.descr, descr.c_str());
a.promo = promo;
return a;
}
bool rubroEquals(Rubro a, Rubro b)
{
if (a.idRub != b.idRub)
return false;
if (a.promo != b.promo)
return false;
return true;
}
string ventasToString(Ventas x)
{
char sep = 3;
string sProductoComprado = productoToString(x.productoComprado);
string sCantidad = to_string(x.cantidad);
return sProductoComprado + sep + sCantidad;
}
Ventas ventasFromString(string s)
{
char sep = 3;
Ventas x;
string t0 = getTokenAt(s, sep, 0);
x.productoComprado = productoFromString(t0);
string t1 = getTokenAt(s, sep, 1);
x.cantidad = stoi(t1);
return x;
}
string ventasToDebug(Ventas x)
{
stringstream sout;
sout << "[";
sout << productoToDebug(x.productoComprado);
sout << ",";
sout << x.cantidad;
sout << "]";
return sout.str();
}
Ventas ventas(Producto productoComprado, int cantidad)
{
Ventas a;
a.productoComprado = productoComprado;
a.cantidad = cantidad;
return a;
}
bool ventasEquals(Ventas a, Ventas b)
{
if (!productoEquals(a.productoComprado, b.productoComprado))
return false;
if (a.cantidad != b.cantidad)
return false;
return true;
}
string itemToString(Item x)
{
char sep = 4;
string sDescripcion = x.descripcion;
string sPrecio = to_string(x.precio);
string sPrecioConDescuento = to_string(x.precioConDescuento);
string sCantidad = to_string(x.cantidad);
return sDescripcion + sep + sPrecio + sep + sPrecioConDescuento + sep + sCantidad;
}
Item itemFromString(string s)
{
char sep = 4;
Item x;
string t0 = getTokenAt(s, sep, 0);
x.descripcion = t0;
string t1 = getTokenAt(s, sep, 1);
x.precio = stod(t1);
string t2 = getTokenAt(s, sep, 2);
x.precioConDescuento = stod(t2);
string t3 = getTokenAt(s, sep, 3);
x.cantidad = stoi(t3);
return x;
}
string itemToDebug(Item x)
{
stringstream sout;
sout << "[";
sout << x.descripcion;
sout << ",";
sout << x.precio;
sout << ",";
sout << x.precioConDescuento;
sout << ",";
sout << x.cantidad;
sout << "]";
return sout.str();
}
Item item(string descripcion, double precio, double precioConDescuento, int cantidad)
{
Item a;
a.descripcion = descripcion;
a.precio = precio;
a.precioConDescuento = precioConDescuento;
a.cantidad = cantidad;
return a;
}
bool itemEquals(Item a, Item b)
{
if (a.descripcion != b.descripcion)
return false;
if (a.precio != b.precio)
return false;
if (a.precioConDescuento != b.precioConDescuento)
return false;
if (a.cantidad != b.cantidad)
return false;
return true;
}
string registroProductosToString(RegistroProductos x)
{
char sep = 5;
string sProd = productoToString(x.prod);
string sContador = to_string(x.contador);
return sProd + sep + sContador;
}
RegistroProductos registroProductosFromString(string s)
{
char sep = 5;
RegistroProductos x;
string t0 = getTokenAt(s, sep, 0);
x.prod = productoFromString(t0);
string t1 = getTokenAt(s, sep, 1);
x.contador = stoi(t1);
return x;
}
string registroProductosToDebug(RegistroProductos x)
{
stringstream sout;
sout << "[";
sout << productoToDebug(x.prod);
sout << ",";
sout << x.contador;
sout << "]";
return sout.str();
}
RegistroProductos registroProductos(Producto prod, int contador)
{
RegistroProductos a;
a.prod = prod;
a.contador = contador;
return a;
}
bool registroProductosEquals(RegistroProductos a, RegistroProductos b)
{
if (!productoEquals(a.prod, b.prod))
return false;
if (a.contador != b.contador)
return false;
return true;
}
string registroRubroToString(RegistroRubro x)
{
char sep = 6;
string sRubro = rubroToString(x.rubro);
string sAhorro = to_string(x.ahorro);
return sRubro + sep + sAhorro;
}
RegistroRubro registroRubroFromString(string s)
{
char sep = 6;
RegistroRubro x;
string t0 = getTokenAt(s, sep, 0);
x.rubro = rubroFromString(t0);
string t1 = getTokenAt(s, sep, 1);
x.ahorro = stod(t1);
return x;
}
string registroRubroToDebug(RegistroRubro x)
{
stringstream sout;
sout << "[";
sout << rubroToDebug(x.rubro);
sout << ",";
sout << x.ahorro;
sout << "]";
return sout.str();
}
RegistroRubro registroRubro(Rubro rubro, double ahorro)
{
RegistroRubro b;
b.rubro = rubro;
b.ahorro = ahorro;
return b;
}
bool registroRubroEquals(RegistroRubro a, RegistroRubro b)
{
if (!rubroEquals(a.rubro, b.rubro))
return false;
if (a.ahorro != b.ahorro)
return false;
return true;
}
#endif
| true |
3d7765e439c1e6c751c41855efd44a17a2f1b485 | C++ | Drew0824/Lab-25-Lab-25.1-dpatel4 | /main.cpp | UTF-8 | 736 | 3.859375 | 4 | [] | no_license | #include <iostream>
using namespace std;
/* _Compound Assignment_
Compound assignment operators modify the current value of a variable by performing an operation on it:
expression | equivalent to
y += x; y = y + x;
x -= 5; x = x - 5;
x /= y; x = x / y;
y *= x; y = y * x;
Instructions: Convert the math expressions in the code to use compound assignment operators when possible.
*/
int main() {
int a = 1;
int b = 3;
int c = 21;
// b = b + 4;
b += 4;
//a = a * 7;
a *= 7;
// b = b + a;
b += a;
//a = b + a;
a += b;
//c = c / 7;
c /= 7;
c = b - 7;
//c = c - 21;
c -= 21;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "c = " << c << endl;
} | true |
87bac1ce352675af86e31e015f10758228ee689f | C++ | dhahaj/LCD_HC_SR04 | /LCD_HC-SR04.ino | UTF-8 | 1,180 | 2.65625 | 3 | [] | no_license | #include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <ST_HW_HC_SR04.h>
LiquidCrystal_I2C lcd(0x3F, 16, 2); // set the LCD address to 0x27 for a 16 chars and 2 line display
ST_HW_HC_SR04 ultrasonicSensor(5, 6); // ST_HW_HC_SR04(TRIG, ECHO)
void setup()
{
lcd.init(); // initialize the lcd
lcd.backlight();
lcd.clear();
lcd.home();
lcd.print(F("Sketch Starting!"));
delay(2000);
}
// * hitTime / 29.10 = distance [centimeters]
// * hitTime / 74.75 = distance [inches]
void loop()
{
float hitTime = ultrasonicSensor.getHitTime(); // In microseconds
if( !hitTime && (ultrasonicSensor.getTimeout() == 5000) )
{
lcd.clear();
lcd.home();
lcd.print(F("Timeout!"));
delay(1500);
}
else
{
float in = hitTime / 74.75,
mm = hitTime / 29.10;
lcd.home();
lcd.print(F("Echo Time="));
lcd.print((uint8_t)hitTime);
lcd.print(F("us "));
lcd.setCursor(0, 1);
lcd.print(F("Dis="));
lcd.print(mm);
lcd.print(F("mm"));
lcd.print(F(","));
lcd.print(in);
lcd.println(F("\""));
delay(500);
}
}
| true |
15991d824c6697906f3237cc195b944d87c6fb47 | C++ | TinySmaug/TinyHeroes | /TinyHeroes/src/InputManager.cpp | UTF-8 | 1,991 | 2.859375 | 3 | [] | no_license | #include "InputManager.h"
#include <cassert>
#define DEBUG 0
InputManager::InputManager()
{
}
InputManager::~InputManager()
{
}
InputManager& InputManager::getInstance()
{
static InputManager instance;
return instance;
}
void InputManager::update(float deltaTime)
{
for (auto i = m_keyboardInputHandlers.begin(); i != m_keyboardInputHandlers.end(); i++)
{
if (sf::Keyboard::isKeyPressed((*i).first))
{
(*i).second.ActivationHandler(deltaTime);
(*i).second.wasActiveInPreviousFrame = true;
}
else if ((*i).second.wasActiveInPreviousFrame)
{
(*i).second.DeactivationHandler(deltaTime);
(*i).second.wasActiveInPreviousFrame = false;
}
}
for (auto i = m_mouseInputHandlers.begin(); i != m_mouseInputHandlers.end(); i++)
{
if (sf::Mouse::isButtonPressed((*i).first))
{
(*i).second.ActivationHandler(deltaTime);
(*i).second.wasActiveInPreviousFrame = true;
}
else if ((*i).second.wasActiveInPreviousFrame)
{
(*i).second.DeactivationHandler(deltaTime);
(*i).second.wasActiveInPreviousFrame = false;
}
}
}
bool InputManager::addKeyboardInputHandler(sf::Keyboard::Key key, InputHandlerData data)
{
bool result = m_keyboardInputHandlers.try_emplace(key, data).second;
if (DEBUG)
{
assert(result);
}
return result;
}
bool InputManager::addMouseInputHandler(sf::Mouse::Button button, InputHandlerData data)
{
bool result = m_mouseInputHandlers.try_emplace(button, data).second;
if (DEBUG)
{
assert(result);
}
return result;
}
bool InputManager::removeKeyboardInputHandler(sf::Keyboard::Key key)
{
auto position = m_keyboardInputHandlers.find(key);
if (position != m_keyboardInputHandlers.end())
{
m_keyboardInputHandlers.erase(position);
return true;
}
return false;
}
bool InputManager::removeMouseInputHandler(sf::Mouse::Button button)
{
auto position = m_mouseInputHandlers.find(button);
if (position != m_mouseInputHandlers.end())
{
m_mouseInputHandlers.erase(position);
return true;
}
return false;
}
| true |
a706f9ac1df401d8b5a871f1636b68e850023727 | C++ | OIC-Shinchaemin/RatchetNclank-PrivateCopy | /ClientProject/Mof/MofLibrary/Include/Common/KeyFrame.inl | SHIFT_JIS | 7,534 | 2.75 | 3 | [
"MIT"
] | permissive | /*************************************************************************//*!
@file KeyFrame.inl
@brief L[t[NXB
@author CDW
@date 2014.05.14
*//**************************************************************************/
/*************************************************************************//*!
@brief RXgN^
@param None
@return None
*//**************************************************************************/
template < typename T > FORCE_INLINE CKeyFrame< T >::CKeyFrame() :
m_Value(NULL) ,
m_Time(0.0f) ,
m_Flag(0) ,
m_InterpolationType(KEYINTERPOLATION_LINEAR) {
memset(m_InterpolationValue,0,sizeof(MofFloat) * MOF_KEYFRAMEINTERPOLATIONCOUNT);
}
/*************************************************************************//*!
@brief RXgN^
@param[in] v vf
@param[in] t
@param[in] f tO
@param[in] inter ԕ@
@param[in] pinterval ԃp[^[
@return None
*//**************************************************************************/
template < typename T > FORCE_INLINE CKeyFrame< T >::CKeyFrame(const T& v,MofFloat t,MofU32 f,KeyFrameInterpolationType inter,LPCMofFloat pinterval) :
m_Value(v) ,
m_Time(t) ,
m_Flag(f) ,
m_InterpolationType(inter) {
memset(m_InterpolationValue,0,sizeof(MofFloat) * MOF_KEYFRAMEINTERPOLATIONCOUNT);
switch(inter)
{
case KEYINTERPOLATION_EASE:
memcpy(m_InterpolationValue,pinterval,sizeof(MofFloat));
break;
case KEYINTERPOLATION_HERMITE:
memcpy(m_InterpolationValue, pinterval, sizeof(MofFloat) * 2);
break;
case KEYINTERPOLATION_BEZIER1:
memcpy(m_InterpolationValue, pinterval, sizeof(MofFloat) * 4);
break;
case KEYINTERPOLATION_BEZIER2:
memcpy(m_InterpolationValue,pinterval,sizeof(MofFloat) * 4);
break;
case KEYINTERPOLATION_BEZIER2_VECTOR3:
memcpy(m_InterpolationValue, pinterval, sizeof(MofFloat) * 12);
break;
case KEYINTERPOLATION_BEZIER2_VECTOR4:
memcpy(m_InterpolationValue, pinterval, sizeof(MofFloat) * 16);
break;
default:
memset(m_InterpolationValue,0,sizeof(MofFloat) * 16);
break;
}
}
/*************************************************************************//*!
@brief Rs[RXgN^
@param[in] pObj Rs[t[
@return None
*//**************************************************************************/
template < typename T > FORCE_INLINE CKeyFrame< T >::CKeyFrame(const CKeyFrame< T >& pObj) :
m_Value(pObj.m_Value) ,
m_Time(pObj.m_Time) ,
m_Flag(pObj.m_Flag) ,
m_InterpolationType(pObj.m_InterpolationType) {
memcpy(m_InterpolationValue,pObj.m_InterpolationValue,sizeof(MofFloat) * MOF_KEYFRAMEINTERPOLATIONCOUNT);
}
/*************************************************************************//*!
@brief Rs[L[t[̍쐬
@param None
@return 쐬ꂽRs[L[t[<br>
쐬ɎsꍇNULLԂ
*//**************************************************************************/
template < typename T > FORCE_INLINE CKeyFrame< T >* CKeyFrame< T >::CreateCopyObject(void) const{
return new CKeyFrame< T >(*this);
}
/*************************************************************************//*!
@brief fXgN^
@param None
@return None
*//**************************************************************************/
template < typename T > FORCE_INLINE CKeyFrame< T >::~CKeyFrame(){
}
/*************************************************************************//*!
@brief f[^ݒ
@param[in] v f[^
@return TRUE <br>
ȊO sAG[R[h߂lƂȂ
*//**************************************************************************/
template < typename T > FORCE_INLINE MofBool CKeyFrame< T >::SetValue(T& v){
m_Value = v;
return TRUE;
}
/*************************************************************************//*!
@brief Ԑݒ
@param[in] t f[^
@return TRUE <br>
ȊO sAG[R[h߂lƂȂ
*//**************************************************************************/
template < typename T > FORCE_INLINE MofBool CKeyFrame< T >::SetTime(MofFloat v){
m_Time = v;
return TRUE;
}
/*************************************************************************//*!
@brief Ԑݒ
@param[in] inter ԕ@
@param[in] pinterval ԃp[^[
@return None
*//**************************************************************************/
template < typename T > FORCE_INLINE MofBool CKeyFrame< T >::SetInterpolation(KeyFrameInterpolationType inter, LPCMofFloat pinterval) {
m_InterpolationType = inter;
switch (inter)
{
case KEYINTERPOLATION_EASE:
memcpy(m_InterpolationValue, pinterval, sizeof(MofFloat));
break;
case KEYINTERPOLATION_HERMITE:
memcpy(m_InterpolationValue, pinterval, sizeof(MofFloat) * 2);
break;
case KEYINTERPOLATION_BEZIER1:
memcpy(m_InterpolationValue, pinterval, sizeof(MofFloat) * 4);
break;
case KEYINTERPOLATION_BEZIER2:
memcpy(m_InterpolationValue, pinterval, sizeof(MofFloat) * 4);
break;
case KEYINTERPOLATION_BEZIER2_VECTOR3:
memcpy(m_InterpolationValue, pinterval, sizeof(MofFloat) * 12);
break;
case KEYINTERPOLATION_BEZIER2_VECTOR4:
memcpy(m_InterpolationValue, pinterval, sizeof(MofFloat) * 16);
break;
}
return TRUE;
}
/*************************************************************************//*!
@brief Ԏ擾
@param None
@return
*//**************************************************************************/
template < typename T > FORCE_INLINE MofFloat CKeyFrame< T >::GetTime(void) const{
return m_Time;
}
/*************************************************************************//*!
@brief tO擾
@param None
@return tO
*//**************************************************************************/
template < typename T > FORCE_INLINE MofU32 CKeyFrame< T >::GetFlag(void) const{
return m_Flag;
}
/*************************************************************************//*!
@brief ԕ@擾
@param None
@return ԕ@
*//**************************************************************************/
template < typename T > FORCE_INLINE KeyFrameInterpolationType CKeyFrame< T >::GetInterpolationType(void) const{
return m_InterpolationType;
}
/*************************************************************************//*!
@brief ԏ擾
@param None
@return ԏ
*//**************************************************************************/
template < typename T > FORCE_INLINE LPCMofFloat CKeyFrame< T >::GetInterpolationValue(void) const{
return m_InterpolationValue;
}
/*************************************************************************//*!
@brief f[^擾
@param None
@return f[^
*//**************************************************************************/
template < typename T > FORCE_INLINE T& CKeyFrame< T >::GetValue(void){
return m_Value;
}
/*************************************************************************//*!
@brief f[^擾
@param None
@return f[^
*//**************************************************************************/
template < typename T > FORCE_INLINE const T& CKeyFrame< T >::GetValue(void) const{
return m_Value;
}
//[EOF] | true |
e2e831a145b037b008fb40fee8e3bf6af2f92b9e | C++ | arabine/grenier | /qt/Multivac/CWaveFile.cpp | ISO-8859-1 | 8,083 | 2.765625 | 3 | [] | no_license | /*=============================================================================
* Multivac 1.0 - CWaveFile.cpp
*=============================================================================
* Classe C++ de validation/lecture de fichier Wave
*=============================================================================
* (c) Anthony RABINE - 2003
* arabine@programmationworld.com
* http://www.programmationworld.com
* Environment : VC++ 6.0
*
* Historique :
*
* 31/01/2003 : premire version
*
*=============================================================================
*/
// Classes internes
#include "CWaveFile.h"
/*****************************************************************************/
CWaveFile::CWaveFile()
{
fileName = new char[1];
strcpy(fileName,"");
data = new unsigned char[1];
data[0]='\0';
}
/*****************************************************************************/
CWaveFile::CWaveFile(const char *name)
{
int taille;
taille = strlen(name);
fileName = new char[taille];
strcpy(fileName,name);
}
/*****************************************************************************/
CWaveFile::~CWaveFile()
{
delete data;
delete fileName;
}
/*****************************************************************************/
void CWaveFile::setPath(const char *name)
{
int taille;
delete fileName;
taille = strlen(name);
fileName = new char[taille];
strcpy(fileName,name);
}
/*****************************************************************************/
/**
* Renvoie 0 en cas de succs, sinon un code d'erreur
*/
int CWaveFile::loadWaveFile()
{
unsigned char WavHeader[HEADER_SIZE];
FILE *fp;
unsigned long int ret;
fp = fopen(fileName,"rb");
if(fp==NULL)
{
return WAV_CANT_OPEN; // Impossible d'ouvrir le fichier
}
waveFileSize = fileSize(fp);
ret = fread(WavHeader, sizeof(unsigned char), HEADER_SIZE, fp); // retourne ret, le nombre d'octets lus
if(ret!=HEADER_SIZE)
{
fclose(fp);
return WAV_CANT_READ_HDR; // Probleme de lecture du fichier.
}
if((ret=verifWav(WavHeader))!=0)
{
fclose(fp);
return ret; // Fichier .wav non valide (voir les messages d'erreurs dans error.h)
}
// le fichier est maintenant valide, on va capturer les donnes
delete data;
data = new unsigned char[dataSize];
// position des donnes diffrente selon les formats wav
if(fact==0)
fseek(fp,44,0);
ret = fread(data, sizeof(unsigned char), dataSize, fp);
if(ret!=dataSize)
{
fclose(fp);
return WAV_CANT_READ_DATA; // Probleme de lecture du fichier.
}
fclose(fp);
return 0;
}
/*****************************************************************************/
/**
* retour :
* 0 : fichier wav valide
* sinon : fichier wav non valide : code de retour
* codes :
* 42 : la fonction mid s'est mal droule
*/
int CWaveFile::verifWav(unsigned char WavHeader[HEADER_SIZE])
{
char buff[HEADER_SIZE];
unsigned int val=0;
char chr[2];
chr[1]='\0';
// on teste le format
if(mid(WavHeader,HEADER_SIZE,0,3,buff))
return WAV_BAD_PARAMETERS;
if(strcmp(buff,"RIFF"))
return WAV_NO_RIFF;
// on teste la taille du fichier
val = WavHeader[4]+WavHeader[5]*256+WavHeader[6]*65536+WavHeader[7]*16777216;
if(val+8!=waveFileSize)
return WAV_BAD_FILESIZE;
// on teste le format
if(mid(WavHeader,HEADER_SIZE,8,15,buff))
return WAV_BAD_PARAMETERS;
if(strcmp(buff,"WAVEfmt "))
return WAV_NO_WAVE;
// nombre d'octets pour dcrire le format souvent 16 ou 18 !! (d'autres tailles existent ???)
val = WavHeader[16]+WavHeader[17]*256+WavHeader[18]*65536+WavHeader[19]*16777216;
if(val==16)
fact=0;
else if(val==18)
fact=1;
else
return WAV_NO_SUPPORT;
// on ne gre que le PCM non compress
val = WavHeader[20]+WavHeader[21]*256;
if(val!=1)
return WAV_NO_COMPRESSION;
// canaux : mono = 1, stereo = 2
val = WavHeader[22]+WavHeader[23]*256;
if(val==1)
channels = 1;
else if(val==2)
{
channels = 2;
return WAV_NO_STEREO; // ne gre pas encore le format stro, on quitte !
}
else
return WAV_BAD_CHANNELS;
// frquence d'chantillonnage
samplesPerSec = WavHeader[24]+WavHeader[25]*256+WavHeader[26]*65536+WavHeader[27]*16777216;
// nombre d'octets par seconde (== frquence d'chantillonnage si mono)
avgBytesPerSec = WavHeader[28]+WavHeader[29]*256+WavHeader[30]*65536+WavHeader[31]*16777216;
// octets par chantillon : 1=8 bit Mono, 2=8 bit Stereo or 16 bit Mono, 4=16 bit Stereo
val = WavHeader[32]+WavHeader[33]*256;
if(val==1)
BlockAlign = 1;
else if(val==2)
BlockAlign = 2;
else if(val==4)
BlockAlign = 4;
else
return WAV_NO_BLOCKALIGN;
// bits par chantillon : 8, 12 ou 16
val = WavHeader[34]+WavHeader[35]*256;
if(val==8)
bitsPerSample = 8;
else if(val==12)
bitsPerSample = 12;
else if(val==16)
bitsPerSample = 16;
else
return WAV_BAD_BITS;
// On commence la zone de donnes proprement dite
// on teste l'existance du label
if(fact==0)
{
if(mid(WavHeader,HEADER_SIZE,36,39,buff))
return WAV_BAD_PARAMETERS;
}
else
{
if(mid(WavHeader,HEADER_SIZE,50,53,buff))
return WAV_BAD_PARAMETERS;
}
if(strcmp(buff,"data"))
return WAV_NO_DATA;
// taille des donnes
if(fact==0)
dataSize = WavHeader[40]+WavHeader[41]*256+WavHeader[42]*65536+WavHeader[43]*16777216;
else
dataSize = WavHeader[54]+WavHeader[55]*256+WavHeader[56]*65536+WavHeader[57]*16777216;
return 0;
}
/*****************************************************************************/
/**
* Retourne : 0 si bien pass
* 1 en cas d'erreur
*/
int CWaveFile::mid(unsigned char *in, int taille, int debut, int fin, char *out)
{
int i, ecart;
ecart = fin-debut;
if(taille<=0 || ecart>=taille || ecart<=0)
return(1);
for(i=0;i<=ecart;i++)
out[i] = (char)in[debut+i];
out[ecart+1]='\0'; // on termine la chaine de caractres
return 0;
}
/*****************************************************************************/
/**
* Retourne la taille du fichier en octets
*/
unsigned int CWaveFile::fileSize(FILE *stream)
{
unsigned int curpos,length;
curpos = ftell(stream); /* garder la position courante */
fseek(stream, 0L, SEEK_END);
length = ftell(stream);
fseek (stream, curpos, SEEK_SET); /* restituer la position */
return length;
}
/*****************************************************************************/
/**
* Accesseurs
*/
char *CWaveFile::getFileName()
{
return fileName;
}
/*****************************************************************************/
unsigned int CWaveFile::getFileSize()
{
return waveFileSize;
}
/*****************************************************************************/
unsigned int CWaveFile::getChannels()
{
return channels;
}
/*****************************************************************************/
unsigned int CWaveFile::getSamplesPerSec()
{
return samplesPerSec;
}
/*****************************************************************************/
unsigned int CWaveFile::getAvgBytesPerSec()
{
return avgBytesPerSec;
}
/*****************************************************************************/
unsigned short int CWaveFile::getBlockAlign()
{
return BlockAlign;
}
/*****************************************************************************/
unsigned short int CWaveFile::getBitsPerSample()
{
return bitsPerSample;
}
/*****************************************************************************/
unsigned long int CWaveFile::getDataSize()
{
return dataSize;
}
/*****************************************************************************/
unsigned char *CWaveFile::getData()
{
return data;
}
//=============================================================================
// Fin du fichier CWaveFile.h
//============================================================================= | true |
65e832c022d4888ee7fd270ee9a90acf22edb371 | C++ | CST-Modelling-Tools/TonatiuhPP | /source/libraries/SunPathLib/math/geometry/vec2d.cpp | UTF-8 | 502 | 2.984375 | 3 | [] | no_license | #include "vec2d.h"
namespace sp {
const vec2d vec2d::Zero(0., 0.);
const vec2d vec2d::One(1., 1.);
const vec2d vec2d::UnitX(1., 0.);
const vec2d vec2d::UnitY(0., 1.);
bool vec2d::operator==(const vec2d& v) const
{
if (this == &v) return true;
return equals(x, v.x) && equals(y, v.y);
}
bool vec2d::operator!=(const vec2d& v) const
{
return !(*this == v);
}
std::ostream& operator<<(std::ostream& os, const vec2d& v)
{
os << v.x << ", " << v.y;
return os;
}
} // namespace sp
| true |
ee603fca46a0251865cd18a8d2a372e844480e87 | C++ | haward79/binary_search_tree | /src/Exception.h | UTF-8 | 309 | 2.65625 | 3 | [] | no_license | #ifndef Exception_h
#define Exception_h
#include <string>
using std::string;
class Exception
{
public:
// Constructor.
Exception();
// Method.
string toString() const;
private:
// Empty.
};
#endif
| true |
71763dc1a12a756ade0c6522231655516af5b811 | C++ | AIS-Bonn/stillleben | /contrib/v-hacd/src/vhacdRaycastMesh.h | UTF-8 | 1,764 | 2.71875 | 3 | [
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #ifndef RAYCAST_MESH_H
#define RAYCAST_MESH_H
#include <stdint.h>
namespace VHACD
{
// Very simple brute force raycast against a triangle mesh. Tests every triangle; no hierachy.
// Does a deep copy, always does calculations with full double float precision
class RaycastMesh
{
public:
static RaycastMesh * createRaycastMesh(uint32_t vcount, // The number of vertices in the source triangle mesh
const double *vertices, // The array of vertex positions in the format x1,y1,z1..x2,y2,z2.. etc.
uint32_t tcount, // The number of triangles in the source triangle mesh
const uint32_t *indices); // The triangle indices in the format of i1,i2,i3 ... i4,i5,i6, ...
static RaycastMesh * createRaycastMesh(uint32_t vcount, // The number of vertices in the source triangle mesh
const float *vertices, // The array of vertex positions in the format x1,y1,z1..x2,y2,z2.. etc.
uint32_t tcount, // The number of triangles in the source triangle mesh
const uint32_t *indices); // The triangle indices in the format of i1,i2,i3 ... i4,i5,i6, ...
// Uses high speed AABB raycasting
virtual bool raycast(const double *start,
const double * dir,
double& outT,
double& u,
double& v,
double& w,
double& faceSign,
uint32_t& faceIndex) const = 0;
virtual bool raycast(const double *start,
const double * to,
double &outT,
double &faceSign,
double *hitLocation) const = 0;
virtual bool getClosestPointWithinDistance(const double *point,double maxDistance,double *closestPoint) = 0;
virtual void release(void) = 0;
protected:
virtual ~RaycastMesh(void) { };
};
} // end of VHACD namespace
#endif
| true |
ea3c45409492ceb89a38e27992c9c52067c18fa3 | C++ | sibeelyildizz/OOP-Exercises-with-CPP- | /dateType/src/dateType.cpp | UTF-8 | 430 | 3.015625 | 3 | [] | no_license | #include "dateType.h"
#include <iostream>
using namespace std;
dateType::dateType()
{
//ctor
}
void dateType::setDate(int month,int day,int year){
dMonth=month;
dDay=day;
dYear=year;
}
void dateType::getDate(int& month,int day,int& year){
month = dMonth;
day = dDay;
year = dYear;
}
void dateType::printDate()const {
cout<<dMonth<<"."<<dDay<<"."<<dYear<<endl;
}
dateType::~dateType()
{
//dtor
}
| true |
f31344396c93a0fce09459e820fad0c30223858c | C++ | mshoe/Little_Tactics | /Checkers/CGameEngine.h | UTF-8 | 534 | 2.703125 | 3 | [] | no_license | #pragma once
#include "Classes.h"
#include "Structures.h"
#include "CGameState.h"
#include "Stack.h"
class CGameEngine
{
public:
CGameEngine();
~CGameEngine();
void Init();
void Cleanup();
void ChangeState(CGameState *state);
void pushState(CGameState *state);
CGameState* popState();
void KeyBoard(unsigned char key, int x, int y);
void IdleUpdate();
void Draw();
bool Running() { return m_running; }
void Quit() { m_running = false; }
private:
//the stack of states
Stack<CGameState> *states;
bool m_running;
}; | true |
12b3cff4c58a906e03cbf12ef96768da1e309369 | C++ | code-killerr/Algorithm | /数据结构/实验7/二叉树.cpp | UTF-8 | 425 | 2.875 | 3 | [] | no_license | #include<iostream>
using namespace std;
class Bigtree
{
private:
int data;
Bigtree *lchild;
Bigtree *rchild;
public:
int Initiate();
Bigtree Create(int x,Bigtree lbt,Bigtree Rbt);
};
int Bigtree::Initiate()
{
if(!this)
return 0;
this->lchild = NULL;
this->rchild = NULL;
return 1;
}
Bigtree Create(int x,Bigtree lbt,Bigtree Rbt)
{
}
int main()
{
Bigtree First;
First.Initiate();
return 0;
} | true |
ae8a7a1a393ce30319e968f27a7ade47cef6f08e | C++ | Swkings/thread_copy | /pthread_copy.cpp | UTF-8 | 8,494 | 3.09375 | 3 | [] | no_license | #include<unistd.h> //sleep() wite()
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<dirent.h>//输出文件信息
#include<sys/stat.h>//判断是否目录
#include<pthread.h>//使用线程
/*
linux中不带pthread库,所以编译时应如下在后加上 -lpthread
gcc thread.c -o thread -lpthread
*/
char *source_arr[512];//存放源文件路径的数组
char *destination_arr[512];//存放目标文件路径的数组
int source_arr_index=0;//存放源文件路径的数组的索引,就是for(int i=xx;..;..)那个i
int destination_arr_index=0;//存放目标文件路径的数组的索引
pthread_mutex_t mutex;//声明一个互斥锁mutex
int i=-1,j=-2,temp;//多个线程函数用到这个i,用于记录是否复制完毕,因此作为全局变量处理~
/*字符串处理函数*/
int endwith(char* s,char c) //用于判断字符串结尾是否为“/”与“.”
{
if(s[strlen(s)-1]==c)
{
return 1;
}
else
{
return 0;
}
}
char* str_contact(char* str1,char* str2) //字符串连接
{
char* result;
result=(char*)malloc(strlen(str1)+strlen(str2)+1);//str1的长度+str2的长度+\0;
if(!result) //如果内存动态分配失败
{
printf("字符串连接时,内存动态分配失败\n");
exit(1);
}
strcat(result,str1);
strcat(result,str2);//字符串拼接
return result;
}
/*遍历函数*/
int is_dir(char* path) //判断是否是目录
{
struct stat st;
stat(path,&st);
if(S_ISDIR(st.st_mode))
{
return 1;
}
else
{
return 0;
}
}
/*遍历source_path并且在destination_path中创建好对应的文件夹,并将需要复制的文件加到source_arr和destination_arr数组中,相当于生产多进程中的任务*/
void read_folder(char* source_path,char *destination_path) //复制文件夹
{
if(!opendir(destination_path))
{
if (mkdir(destination_path,0777))//如果不存在就用mkdir函数来创建,0777表示读写以及执行权限
{
printf("创建文件夹失败!");
}
}
char *path;
path=(char*)malloc(512);//相当于其它语言的String path="",纯C环境下的字符串必须自己管理大小,这里为path直接申请512的位置的空间,用于目录的拼接
path=str_contact(path,source_path);//这三句,相当于path=source_path
struct dirent* filename;
DIR* dp=opendir(path);//用DIR指针指向这个文件夹
while(filename=readdir(dp)) //遍历DIR指针指向的文件夹,也就是文件数组。
{
memset(path,0,sizeof(path));
path=str_contact(path,source_path);
//如果source_path,destination_path以路径分隔符结尾,那么source_path/,destination_path/直接作路径即可
//否则要在source_path,destination_path后面补个路径分隔符再加文件名,谁知道你传递过来的参数是f:/a还是f:/a/啊?
char *file_source_path;
file_source_path=(char*)malloc(512);
file_source_path=str_contact(file_source_path,source_path);
if(!endwith(source_path,'/'))
{
file_source_path=str_contact(source_path,"/");
}
char *file_destination_path;
file_destination_path=(char*)malloc(512);
file_destination_path=str_contact(file_destination_path,destination_path);
if(!endwith(destination_path,'/'))
{
file_destination_path=str_contact(destination_path,"/");
}
//取文件名与当前文件夹拼接成一个完整的路径
file_source_path=str_contact(file_source_path,filename->d_name);
if(is_dir(file_source_path)) //如果是目录
{
if(!endwith(file_source_path,'.')) //同时并不以.结尾,因为Linux在所有文件夹都有一个.文件夹用于连接上一级目录,必须剔除,否则进行递归的话,后果无法想象!
{
file_destination_path=str_contact(file_destination_path,filename->d_name);//对目标文件夹的处理,取文件名与当前文件夹拼接成一个完整的路径
read_folder(file_source_path,file_destination_path);//进行递归调用,相当于进入这个文件夹进行遍历~
}
}
else //否则,将源文件于目标文件的路径分别存入相关数组
{
//对目标文件夹的处理,取文件名与当前文件夹拼接成一个完整的路径
//file_destination_path=str_contact(file_destination_path,"pre_");//给目标文件重命名,这里示意如何加个前缀~^_^
file_destination_path=str_contact(file_destination_path,filename->d_name);
source_arr[source_arr_index]=file_source_path;
source_arr_index++;
destination_arr[destination_arr_index]=file_destination_path;
destination_arr_index++;
}
}
}
/*复制文件*/
void copy_file(char* source_path,char *destination_path) //复制文件
{
char buffer[1024]; //缓冲区,先将文件数据复制到缓冲区,再从缓冲区复制到目标位置
FILE *in,*out;//定义两个文件流,分别用于文件的读取和写入int len;
if((in=fopen(source_path,"r"))==NULL) //打开源文件的文件流
{
printf("源文件打开失败!\n");
exit(1);
}
if((out=fopen(destination_path,"w"))==NULL) //打开目标文件的文件流
{
printf("目标文件创建失败!\n");
exit(1);
}
int len;//len为fread读到的字节长
while((len=fread(buffer,1,1024,in))>0) //从源文件中读取数据并放到缓冲区中,第二个参数1也可以写成sizeof(char)
{
fwrite(buffer,1,len,out);//将缓冲区的数据写到目标文件中
}
fclose(out);
fclose(in);
}
/*
线程执行函数
在read_folder函数中已经生成任务数组,线程的目标就是完成任务数组中的任务
*/
void *thread_function(void *arg)
{
while(i<destination_arr_index&&j<destination_arr_index)
{
/* if(pthread_mutex_lock(&mutex)!=0) //对互斥锁上锁,临界区开始
* {
* printf("%s的互斥锁创建失败!\n",(char *)arg);
* pthread_exit(NULL);
* }
*/
temp = i>j?i:j;
if(temp<destination_arr_index)
{
copy_file(source_arr[temp],destination_arr[temp]);//复制单一文件
printf("%s复制%s到%s成功!\n",(char *)arg,source_arr[temp],destination_arr[temp]);
if(i>j){
j = i+1;
}else{
i = j+1;
}
sleep(1);//该线程挂起1秒
}
else //否则退出
{
pthread_exit(NULL);//退出线程
}
//pthread_mutex_unlock(&mutex);//解锁,临界区结束
sleep(1);//该线程挂起1秒
}
pthread_exit(NULL);//退出线程
}
/*主函数*/
int main(int argc,char *argv[])
{
if(argv[1]==NULL||argv[2]==NULL)
{
printf("请输入两个文件夹路径,第一个为源,第二个为目的!\n");
exit(1);
}
char* source_path=argv[1];//取用户输入的第一个参数
char* destination_path=argv[2];//取用户输入的第二个参数
DIR* source=opendir(source_path);
DIR* destination=opendir(destination_path);
if(!source||!destination)
{
printf("你输入的一个参数或者第二个参数不是文件夹!\n");
}
read_folder(source_path,destination_path);//进行文件夹的遍历
/*线程并发开始*/
pthread_mutex_init(&mutex,NULL);//初始化这个互斥锁
//声明并创建三个线程
pthread_t t1;
pthread_t t2;
//pthread_t t3;
if(pthread_create(&t1,NULL,thread_function,"线程1")!=0)
{
printf("创建线程失败!程序结束!\n");
exit(1);
}
if(pthread_create(&t2,NULL,thread_function,"线程2")!=0)
{
printf("创建线程失败!程序结束!\n");
exit(1);
}
/* if(pthread_create(&t3,NULL,thread_function,"线程3")!=0)
* {
* printf("创建线程失败!程序结束!\n");
* exit(1);
* }
*/
pthread_join(t1,NULL);
pthread_join(t2,NULL);
//pthread_join(t3,NULL);
//三个线程都完成才能执行以下的代码
pthread_mutex_destroy(&mutex);//销毁这个互斥锁
/*线程并发结束*/
return 0;
}
| true |
c9c73a0d1ae03221afbe90916caddf3fa3a4c44a | C++ | CJFulford/Modeling-Project | /Project/Shader.cpp | UTF-8 | 2,284 | 2.734375 | 3 | [] | no_license | #include "Shader.h"
#include <iostream>
#include <fstream>
unsigned long getFileLength(std::ifstream& file)
{
if (!file.good()) return 0;
file.seekg(0, std::ios::end);
unsigned long len = (unsigned long)file.tellg();
file.seekg(std::ios::beg);
return len;
}
GLchar* loadshader(std::string filename)
{
std::ifstream file;
file.open(filename.c_str(), std::ios::in);
if (!file)
{
std::cout << "FILE " << filename.c_str() << " NOT FOUND" << std::endl;
return NULL;
}
unsigned long len = getFileLength(file);
if (len == 0) return NULL;
GLchar* ShaderSource = 0;
ShaderSource = new char[len + 1];
if (ShaderSource == 0) return NULL;
ShaderSource[len] = 0;
unsigned int i = 0;
while (file.good())
{
ShaderSource[i] = file.get();
if (!file.eof())
i++;
}
ShaderSource[i] = 0;
file.close();
return ShaderSource;
}
void unloadshader(GLchar** ShaderSource)
{
if (*ShaderSource != 0) delete[] * ShaderSource;
*ShaderSource = 0;
}
void attachShader(GLuint &program, const char* fileName, GLuint shaderType)
{
GLuint shader;
const GLchar *shaderSource[] = { loadshader(fileName) };
shader = glCreateShader(shaderType);
glShaderSource(shader, 1, shaderSource, NULL);
glCompileShader(shader);
GLint status;
glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
if (status == GL_FALSE)
{
GLint infoLogLength;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLogLength);
GLchar* strInfoLog = new GLchar[infoLogLength + 1];
glGetShaderInfoLog(shader, infoLogLength, NULL, strInfoLog);
std::cout << "\n\n" << fileName << std::endl;
fprintf(stderr, "compilation error in shader vertex_shader: \n%s", strInfoLog);
delete[] strInfoLog;
}
glAttachShader(program, shader);
glDeleteShader(shader);
unloadshader((GLchar**)shaderSource);
}
GLuint generateProgram(const char* vertexFilename, const char* fragmentFilename)
{
GLuint program = glCreateProgram();
attachShader(program, vertexFilename, GL_VERTEX_SHADER);
attachShader(program, fragmentFilename, GL_FRAGMENT_SHADER);
glLinkProgram(program);
return program;
}
| true |
0f9f15a6009c635a4621ade540ccec89887e71ea | C++ | CarLoiD/CppAndroidEngine | /app/src/main/cpp/Engine/vertex_buffer.cpp | UTF-8 | 2,818 | 3 | 3 | [] | no_license | #include "vertex_buffer.h"
#include "utils.h"
inline void DefineVertexAttribPointer(const uint32_t program, const VertexElement& element,
const uint32_t stride, uint16_t& offset)
{
// Element attribute location
const uint32_t attribLocation = [&]() {
uint32_t tmpLocation;
switch (element) {
case VertexElement::Position:
tmpLocation = (uint32_t)glGetAttribLocation(program, "Position");
break;
case VertexElement::Color:
tmpLocation = (uint32_t)glGetAttribLocation(program, "Color");
break;
case VertexElement::TexCoord:
tmpLocation = (uint32_t)glGetAttribLocation(program, "TexCoord");
break;
case VertexElement::Normal:
tmpLocation = (uint32_t)glGetAttribLocation(program, "Normal");
break;
} return tmpLocation;
}();
LogDebug("AttribLocation -> %d", attribLocation);
// Element size
const uint32_t elementSize = [&]() {
uint32_t tmpSize;
switch (element) {
case VertexElement::Position:
tmpSize = 3; // XYZ
break;
case VertexElement::Color:
tmpSize = 4; // RGBA
break;
case VertexElement::TexCoord:
tmpSize = 2; // UV
break;
case VertexElement::Normal:
tmpSize = 3; // N (XYZ)
break;
} return tmpSize;
}();
glVertexAttribPointer(attribLocation, elementSize, GL_FLOAT, GL_FALSE, stride, (void*)offset);
offset += elementSize * sizeof(float);
}
void CreateVertexBuffer(const uint32_t program, const VertexElement* layout,
const uint32_t count, VertexBuffer& buffer, const bool dynamic)
{
const uint32_t usage = dynamic ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW;
glGenBuffers(1, &buffer.Id);
glBindBuffer(GL_ARRAY_BUFFER, buffer.Id);
glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)buffer.Size, buffer.Data, usage);
uint16_t offset = 0;
for (uint32_t index = 0; index < count; ++index) {
glEnableVertexAttribArray(index);
DefineVertexAttribPointer(program, layout[index], buffer.Stride, offset);
}
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
void DestroyVertexBuffer(const VertexBuffer& buffer)
{
glDeleteBuffers(1, &buffer.Id);
}
void BindVertexBuffer(const VertexBuffer& buffer)
{
glBindBuffer(GL_ARRAY_BUFFER, buffer.Id);
}
void UpdateVertexBuffer(const void* data, const uint32_t size, const VertexBuffer& buffer)
{
glBindBuffer(GL_ARRAY_BUFFER, buffer.Id);
glBufferSubData(GL_ARRAY_BUFFER, 0, size, data);
glBindBuffer(GL_ARRAY_BUFFER, 0);
} | true |
b0e4ca637b1d079d83832a59c9aab271acb636c4 | C++ | apple/swift-lldb | /tools/debugserver/source/TTYState.cpp | UTF-8 | 2,616 | 2.515625 | 3 | [
"NCSA",
"Apache-2.0",
"LLVM-exception"
] | permissive | //===-- TTYState.cpp --------------------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// Created by Greg Clayton on 3/26/07.
//
//===----------------------------------------------------------------------===//
#include "TTYState.h"
#include <fcntl.h>
#include <sys/signal.h>
#include <unistd.h>
TTYState::TTYState()
: m_fd(-1), m_tflags(-1), m_ttystateErr(-1), m_processGroup(-1) {}
TTYState::~TTYState() {}
bool TTYState::GetTTYState(int fd, bool saveProcessGroup) {
if (fd >= 0 && ::isatty(fd)) {
m_fd = fd;
m_tflags = fcntl(fd, F_GETFL, 0);
m_ttystateErr = tcgetattr(fd, &m_ttystate);
if (saveProcessGroup)
m_processGroup = tcgetpgrp(0);
else
m_processGroup = -1;
} else {
m_fd = -1;
m_tflags = -1;
m_ttystateErr = -1;
m_processGroup = -1;
}
return m_ttystateErr == 0;
}
bool TTYState::SetTTYState() const {
int result = 0;
if (IsValid()) {
if (TFlagsValid())
result = fcntl(m_fd, F_SETFL, m_tflags);
if (TTYStateValid())
result = tcsetattr(m_fd, TCSANOW, &m_ttystate);
if (ProcessGroupValid()) {
// Save the original signal handler.
void (*saved_sigttou_callback)(int) = NULL;
saved_sigttou_callback = (void (*)(int))signal(SIGTTOU, SIG_IGN);
// Set the process group
result = tcsetpgrp(m_fd, m_processGroup);
// Restore the original signal handler.
signal(SIGTTOU, saved_sigttou_callback);
}
return true;
}
return false;
}
TTYStateSwitcher::TTYStateSwitcher() : m_currentState(~0) {}
TTYStateSwitcher::~TTYStateSwitcher() {}
bool TTYStateSwitcher::GetState(uint32_t idx, int fd, bool saveProcessGroup) {
if (ValidStateIndex(idx))
return m_ttystates[idx].GetTTYState(fd, saveProcessGroup);
return false;
}
bool TTYStateSwitcher::SetState(uint32_t idx) const {
if (!ValidStateIndex(idx))
return false;
// See if we already are in this state?
if (ValidStateIndex(m_currentState) && (idx == m_currentState) &&
m_ttystates[idx].IsValid())
return true;
// Set the state to match the index passed in and only update the
// current state if there are no errors.
if (m_ttystates[idx].SetTTYState()) {
m_currentState = idx;
return true;
}
// We failed to set the state. The tty state was invalid or not
// initialized.
return false;
}
| true |
2ffa85023e6badea9c0b3a759241c4514bfd7324 | C++ | Ckins/Compiler-for-AQL-subset | /src/tokenizer.h | UTF-8 | 1,805 | 3.5 | 4 | [] | no_license | #ifndef TOKENIZER_H
#define TOKENIZER_H
#include <string>
#include <vector>
#include <cstring>
using namespace std;
/*
DocToken:
records the info of every token in an article:
# int start_pos_ : the token's start position in the article
# int end_pos_ : the token's start position in the article
# string content_ :the content of the token
# int word_num_ : the NO. of the token (the first token int the article is 1)
*/
class DocToken {
public:
int start_pos_;
int end_pos_;
std::string content_;
int word_num_;
DocToken(int s = 0, int e = 0, std::string c = "", int w = 0) :
start_pos_(s), end_pos_(e), content_(c), word_num_(w) { }
};
/*
Tokenizer:
records an article and cut it into DocTokens:
# int word_num_ : the quantity of tokens in the article
# vector<DocToken> doc_vector_ : a vector recording all tokens of the article
# string file_name_ : the name of the article
# whole_string_ : the whole article in string
* void make_token() : handle the article from the beginning
* void display() const : show all tokens and its No.
* vector<DocToken> get_doc_token_list() const : get all tokens in vector
* bool is_num_or_letter(char&) : judge whether a char is a num or letter
* string get_all_as_string() const : returns the whole article in string
*/
class Tokenizer {
public:
int word_num_;
vector<DocToken> doc_vector_;
string file_name_;
string whole_string_;
Tokenizer(std::string file);
void make_token();
void display() const;
bool is_num_or_letter(char& c);
vector<DocToken> get_doc_token_list() const;
string get_all_as_string() const;
};
#endif | true |
cac48fc284edafe40ccafe85639f75cbf3414469 | C++ | ngtruongphat/Introduction-to-Programming-in-C | /Bai328.cpp | UTF-8 | 497 | 3.15625 | 3 | [] | no_license | #include "stdafx.h"
#include<iostream>
using namespace std;
void input(float A[100][100], int m, int n)
{
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
cin >> A[i][j];
cout << endl;
}
}
float Result(float A[100][100], int m, int n)
{
float t = 1;
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
t *= A[i][j];
t /= n*m;
return t;
}
int main()
{
float A[100][100];
int m, n;
cin >> m >> n;
input(A, m, n);
cout << Result(A, m, n) << endl;
return 0;
}
| true |
a39fda4bc194e03c315c6d15336b59ae76deaf11 | C++ | aumiaik7/Compiler | /Final/plc.cc | UTF-8 | 2,220 | 2.75 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <cstring>
#include "symbol.h"
#include "scanner.h"
#include "administration.h"
#include "parser.h"
#include "symboltable.h"
#include "blocktable.h"
#include "Assembler.h"
#include "interp.h"
int main(int argc, char *argv[]) {
//source file object
ifstream srcFile;
//output file object
ofstream outFile;
//print symbol table upon user input
bool printSymTab = false;
//must give at list 2 arguments while executing program .
if(argc < 2)
{
cerr<<"Please specify the file name as argument"<<endl;
return 1;
}
//symbol table object
Symboltable st;
//Scanner object
Scanner scanner(srcFile,st);
srcFile.open(argv[1]);
if (!srcFile)
{
cerr << "Input file " << argv[1] << " could not be opened" << endl;
return 1;
}
//outFile.open("Code");
char intermediate[1024];
strcpy(intermediate,"PLFile_");
strcat(intermediate, argv[1]);
strcat(intermediate, ".asm");
ofstream assemblyOutfile;
assemblyOutfile.open(intermediate, ios::out);
if (!assemblyOutfile)
{
cerr << "Intermediate file " << intermediate<< " could not be written"
<< endl;
return 1;
}
BlockTable bTable;
//Parser calss object
Parser parser(srcFile, assemblyOutfile, scanner, bTable);
//Strat Parsing
int errorCount = parser.parse();
srcFile.close();
assemblyOutfile.close();
//no errors so perfor first and second pass in Assembler and execute machine
//code in interpreter
if (errorCount == 0)
{
ifstream assemblyInfile;
assemblyInfile.open(intermediate, ios::in);
if (!assemblyInfile)
{
cerr << "Intermediate file " << intermediate<< " could not be read"<< endl;
return 1;
}
//machine code with resolved forward references are always stored in this file
ofstream outputfile("machineCode");
if (!outputfile)
{
cerr << "Output file " << argv[3] << " could not be opened"<< endl;
return 1;
}
Assembler assembler(assemblyInfile, outputfile);
assembler.firstPass();
assemblyInfile.seekg(0);
assembler.secondPass();
assemblyInfile.close();
outputfile.close();
Interpreter interpreter("machineCode", false);
}
//srcFile.close();
}
| true |
ffcac555a7c0e2e3dd4ea2210151c80d298693c9 | C++ | pearan2/cpp_modules | /cpp04/ex00/Peon.cpp | UTF-8 | 1,410 | 2.828125 | 3 | [] | no_license | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Peon.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: honlee <honlee@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/04/12 12:12:09 by honlee #+# #+# */
/* Updated: 2021/04/14 04:26:16 by honlee ### ########.fr */
/* */
/* ************************************************************************** */
#include "Peon.hpp"
Peon::Peon()
{
this->name = "default";
}
Peon::Peon(const std::string &name) : Victim(name)
{
std::cout << "Zog Zog." << std::endl;
}
Peon::Peon(const Peon &origin) : Victim(origin)
{
}
Peon& Peon::operator=(const Peon &origin)
{
this->name = origin.name;
return (*this);
}
Peon::~Peon()
{
std::cout << "Bleuark..." << std::endl;
}
//overridding with virtual keyword
void Peon::getPolymorphed(void) const
{
std::cout << getName() << " was just polymorphed into a pink Peon!" << std::endl;
}
| true |
694bf98c8dcffb3ae88be383717ce1857e6089d0 | C++ | imthearchitjain/Data-Structures | /Trees/Binary Search Trees/Construct BST From Level Order.CPP | UTF-8 | 1,335 | 3.734375 | 4 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
class Node
{
public:
int data;
bool Ltag, Rtag;
Node *left;
Node *right;
Node(int data = 0)
{
left = right = nullptr;
this->data = data;
}
};
void insert(Node **root, int data)
{
if (!*root)
*root = new Node(data);
else if (data < (*root)->data)
insert(&(*root)->left, data);
else
insert(&(*root)->right, data);
}
void inorder(Node *root)
{
if(!root)
return;
inorder(root->left);
cout << root->data << " ";
inorder(root->right);
}
Node *LevelOrder(Node *root, int data)
{
if(!root)
{
root = new Node(data);
return root;
}
if (data <= root->data)
root->left = LevelOrder(root->left, data);
else
root->right = LevelOrder(root->right, data);
return root;
}
Node *constructBst(int arr[], int n)
{
if (n == 0)
return NULL;
Node *root = NULL;
for (int i = 0; i < n; i++)
root = LevelOrder(root, arr[i]);
return root;
}
int main()
{
int arr[] = {7, 4, 12, 3, 6, 8, 1, 5, 10};
int n = sizeof(arr) / sizeof(arr[0]);
Node *root = constructBst(arr, n);
cout << "Inorder Traversal: ";
inorder(root);
return 0;
} | true |
76623e7974be603f9db3944b3f67e65a972e23b6 | C++ | Krandelbord/file-fleet-admiral | /src/gui/Rectangle.h | UTF-8 | 268 | 2.609375 | 3 | [] | no_license | #ifndef RECTANGLE_H
#define RECTANGLE_H
class Rectangle {
public :
Rectangle(int width, int height);
int getWidth() const;
int getHeight() const;
~Rectangle();
private:
int width, height;
};
#endif /** RECTANGLE_H */
| true |
13f7a1fb8c89ad2fecc41d369de88d89e76d9eeb | C++ | jmgregory/cap-simulation | /CharacteristicMatrix.h | UTF-8 | 1,189 | 2.859375 | 3 | [] | no_license | #ifndef JMG_CHARACTERISTIC_MATRIX_H
#define JMG_CHARACTERISTIC_MATRIX_H
#include <complex>
#include <vector>
#include "Matrix.h"
using std::complex;
const complex <double> air_index = complex <double> (1.0, 0.0);
class CharacteristicMatrix
{
public:
double thickness() const;
double wavelength() const;
Matrix GetMatrix() const;
CharacteristicMatrix & operator *= (const CharacteristicMatrix & rhs);
double ReflectivityInEnvironment(const complex <double> & index_before = air_index, const complex <double> & index_after = air_index) const;
double TransmissionInEnvironment(const complex <double> & index_before = air_index, const complex <double> & index_after = air_index) const;
private:
static double MagnitudeSquared(const complex <double> & number);
Matrix CalculateFullMatrixInEnvironment(const complex <double> & index_before, const complex <double> & index_after) const;
complex <double> Wavenumber(const complex <double> & index) const;
protected:
CharacteristicMatrix();
double _thickness;
double _wavelength;
Matrix _matrix;
};
CharacteristicMatrix operator * (const CharacteristicMatrix & lhs, const CharacteristicMatrix & rhs);
#endif
| true |
f0586d1ddf18e137e6d4ddb44129a1e85e5495fc | C++ | JulesIMF/MIPT_1 | /Onegin/Main.cpp | UTF-8 | 5,735 | 2.578125 | 3 | [] | no_license | /*
Copyright (c) 2020 MIPT
Name:
Сортировка Онегина
Abstract:
Сортирует строки входного файла и выводит в другой файл
Author:
JulesIMF
Last Edit:
12.09.2020 22:02
Edit Notes:
1) Структура string_view добавлена
2) translateFileIntoRam теперь честно считает количество строк
3) Функция getFileSize
*/
//#define JULESIMF_DEBUG
//#define JULESIMF_NO_OUTPUT
///Из-за специфики VS необходимо объявить следующий макрос
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
#include <ctype.h>
#include <string.h>
#include "string_view.h"
#include "Comparasion.h"
#include "Files.h"
//*************************************************************************************************
//*************************************************************************************************
//******************************************MAIN
//*************************************************************************************************
//*************************************************************************************************
int main(int argc, char const** argv)
{
#ifdef JULESIMF_DEBUG
//Для извращенского дебага все можно
argc = 3;
argv[1] = "Tests.txt";
argv[2] = "out.txt";
#endif //!JULESIMF_DEBUG
if (argc && !argv)
{
printf("Error occured while passing parameters!\n");
return 0;
}
if (argc != 3)
{
printf("Invalid parameters!\n");
return 0;
}
//Получим размер файла и транслируем его в память
int fileSize = 0; //Размер файла запишется сюда
int nStrings = 0; //Количество строк запишется сюда
//*************************************************************************************************
//******************************************ТРАНСЛЯЦИЯ ДАННЫХ
//*************************************************************************************************
#ifndef JULESIMF_NO_OUTPUT
printf("Translating file into RAM...\n");
#endif //!JULESIMF_NO_OUTPUT
void* translatedFile = translateFileIntoRam(argv[1], &fileSize, &nStrings);
if (!translatedFile)
{
printf("Error occured while translating file into RAM\n");
return 0;
}
string_view* strings = (string_view*)calloc(nStrings, sizeof(string_view)); //А здесь сам массив
if (!strings)
{
printf("Error occured while calling calloc\n");
return 0;
}
//*************************************************************************************************
//******************************************РАЗДЕЛЕНИЕ НА СТРОКИ
//*************************************************************************************************
#ifndef JULESIMF_NO_OUTPUT
printf("Separating strings...\n");
#endif //!JULESIMF_NO_OUTPUT
int RETURN_readStrings = separateStrings(translatedFile, fileSize, strings,
nStrings);
if (RETURN_readStrings == 1)
{
printf("Error occured while separating file into strings\n");
return 0;
}
string_view* originalStrings = (string_view*)calloc(nStrings, sizeof(string_view)); //А здесь сам массив
#ifndef JULESIMF_DEBUG
assert(originalStrings);
#endif //!JULESIMF_DEBUG
memcpy(originalStrings, strings, nStrings * sizeof(string_view));
//*************************************************************************************************
//******************************************СОРТИРОВКА СТРОК В ПРЯМОМ ПОРЯДКЕ
//*************************************************************************************************
#ifndef JULESIMF_NO_OUTPUT
printf("Sorting the poem in direct...\n");
#endif //!JULESIMF_NO_OUTPUT
qsort((void*)strings, nStrings, sizeof(string_view), stringComparator);
if (write(argv[2], strings, nStrings, "w"))
{
printf("Failed to open file \"%s\"", argv[2]);
return 0;
}
//*************************************************************************************************
//******************************************СОРТИРОВКА СТРОК В ОБРАТНОМ ПОРЯДКЕ
//*************************************************************************************************
#ifndef JULESIMF_NO_OUTPUT
printf("Sorting the poem in reverse...\n");
#endif //!JULESIMF_NO_OUTPUT
#ifdef JULESIMF_DEBUG
FILE* file = fopen(argv[2], "a");
fprintf(file, "\n\n\n");
fclose(file);
#endif //!JULESIMF_DEBUG
qsort((void*)strings, nStrings, sizeof(string_view), reverseStringComparator);
if (write(argv[2], strings, nStrings, "a"))
{
printf("Failed to open file \"%s\"", argv[2]);
return 0;
}
//*************************************************************************************************
//******************************************ВЫВОД В ОРИГИНАЛЬНОМ ПОРЯДКЕ
//*************************************************************************************************
#ifdef JULESIMF_DEBUG
FILE* file_ = fopen(argv[2], "a");
fprintf(file_, "\n\n\n");
fclose(file_);
#endif //!JULESIMF_DEBUG
if (write(argv[2], originalStrings, nStrings, "a"))
{
printf("Failed to open file \"%s\"", argv[2]);
return 0;
}
free(strings);
free(originalStrings);
free(translatedFile);
#ifndef JULESIMF_NO_OUTPUT
printf("\n\n");
#endif // !JULESIMF_NO_OUTPUT
printf("Executed correctly\n");
return 0;
} | true |
38f61ea58b031af7a07adcb642c85099e31c3b16 | C++ | aryner/fall2013 | /fall2013/csc340/finalPrep/lec8/thingy.h | UTF-8 | 477 | 3.546875 | 4 | [] | no_license | #include <iostream>
#include <string>
using namespace::std;
template <typename T>
class thingy
{
public:
thingy():size(0)
{
}
void push(T thing)
{
list[size] = thing;
size++;
}
T pop()
{
size--;
return list[size];
}
friend ostream & operator<<(ostream & os , const thingy<T> & x)
{
os << "<";
for(int i=0; i<x.size; i++)
{
os << x.list[i];
if(i<x.size-1)
os << ",";
}
os << ">";
return os;
}
private:
T list[10];
int size;
};
| true |
52c49fa945d12684de5b71c6c618e2d17910446d | C++ | chris3will/algorithmStudy | /acwings/算法基础课/3图论搜索/861二分最大匹配问题.cpp | UTF-8 | 1,549 | 3.109375 | 3 | [] | no_license | //二分匹配问题
//找到能够满足左右一对一匹配的最大匹配对数
//思路就是固定让一遍发起匹配行为,然后找右边
//每次右边只能迭代一次,要满足不会重复迭代右边的对象,我们初始化的时候也只需要有向边即可
//有一个特殊的match数组即可
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int N = 510, M = 1e5+10;
int n1,n2,m;
bool st[N];
int match[N]; //用来匹匹配n2的匹配对象
//经典的定义邻接表
int h[N],e[M],ne[M],idx;
void add(int a,int b)
{//在a后接上新的节点,值为b
e[idx]=b,ne[idx]=h[a],h[a]=idx++;
}
bool find(int u)
{
//用来观察这个节点能否找到一个可进行匹配的对象
//如果可以则总匹配数目就应该增加
for(int i=h[u];~i;i=ne[i])
{
int j = e[i];
if(!st[j])
{
st[j] = true;
if(match[j]==0 || find(match[j]))
{
match[j] = u;
return true;
}
}
}
return false;
}
int main()
{
scanf("%d%d%d",&n1,&n2,&m);
memset(h,-1,sizeof h); //邻接表的必要初始化
for(int i=0;i<m;i++)
{
int a,b;
scanf("%d%d",&a,&b);
add(a,b);
}
int res = 0;
for(int i=1;i<=n1;i++)
{
memset(st,0,sizeof st); //保证对每个点进行查询的时候,右边的查询记录都是空白的
if(find(i))res++;
}
cout<<res<<endl;
return 0;
} | true |
7682bfef1f635140b4317920e134c468c051d986 | C++ | marromlam/lhcb-software | /LHCb/Kernel/LHCbKernel/Kernel/STDataFunctor.h | UTF-8 | 6,079 | 2.671875 | 3 | [] | no_license | #ifndef _STDataFunctor_H_
#define _STDataFunctor_H_
#include <cmath>
#include <functional>
#include <numeric>
#include "Kernel/STChannelID.h"
//
// This File contains the declaration of STDataFunctor namespace
// - dumping ground for things that don't fit.
//
// C++ code for 'LHCb Tracking package(s)'
//
// Author: M. Needham
// Created:
namespace STDataFunctor {
// functors
template <class TYPE1, class TYPE2 = TYPE1 >
class Less_by_Channel
: public std::binary_function<TYPE1,TYPE2,bool>
{
public:
/** compare the channel of one object with the
* channel of another object
* @param obj1 first object
* @param obj2 second object
* @return result of the comparision
*/
inline bool operator() ( TYPE1 obj1 , TYPE2 obj2 ) const
{
return
( !obj1 ) ? true :
( !obj2 ) ? false : obj1->channelID() < obj2->channelID() ;
}
///
};
// for the detector element the channelID is called the elemented ID
template <class TYPE1, class TYPE2 = TYPE1 >
class Less_by_ElementID
: public std::binary_function<TYPE1,TYPE2,bool>
{
public:
/** compare the element of one channel of one object with the
* channel of another object
* @param obj1 first object
* @param obj2 second object
* @return result of the comparision
*/
inline bool operator() ( TYPE1 obj1 , TYPE2 obj2 ) const
{
return
( !obj1 ) ? true :
( !obj2 ) ? false : obj1->elementID() < obj2->elementID() ;
}
///
};
template <class TYPE1, class TYPE2 = TYPE1 >
class Less_by_Key
: public std::binary_function<TYPE1,TYPE2,bool>
{
public:
/** compare the channel of one object with the
* channel of another object
* @param obj1 first object
* @param obj2 second object
* @return result of the comparision
*/
inline bool operator() ( TYPE1 obj1 , TYPE2 obj2 ) const
{
return
( !obj1 ) ? true :
( !obj2 ) ? false : obj1->key() < obj2->key() ;
}
///
};
template <class TYPE1, class TYPE2 = TYPE1 >
class Less_by_depositedCharge
: public std::binary_function<TYPE1,TYPE2,bool>
{
public:
/** compare the dep charge of one object with the
* dep Charge of another object
* @param obj1 first object
* @param obj2 second object
* @return result of the comparision
*/
inline bool operator() ( TYPE1 obj1 , TYPE2 obj2 ) const
{
return
( !obj1 ) ? true :
( !obj2 ) ? false : obj1->depositedCharge() < obj2->depositedCharge() ;
}
///
};
/// class for accumulating energy
template <class TYPE>
class Accumulate_Charge
: public std::binary_function<double,TYPE, double>{
public:
inline double operator() ( double& charge , TYPE obj ) const {
return ( !obj ) ? charge : charge+= obj->depositedCharge() ; };
///
};
// class for accumulating charge2
template <class TYPE>
class Accumulate_Charge2
: public std::binary_function<double,TYPE, double>{
public:
inline double operator() ( double& charge2 , TYPE obj ) const {
return ( !obj ) ? charge2 : charge2+= std::pow(obj->depositedCharge(),2) ; };
///
};
template <class TYPE>
class station_eq: public std::unary_function<TYPE,bool>{
LHCb::STChannelID aChan;
public:
explicit station_eq(const LHCb::STChannelID& testChan) : aChan(testChan){}
inline bool operator() (TYPE obj) const{
return obj->channelID().station()==aChan.station();}
};
template <class TYPE>
class layer_eq: public std::unary_function<TYPE,bool>{
LHCb::STChannelID aChan;
public:
explicit layer_eq(const LHCb::STChannelID& testChan) : aChan(testChan){}
inline bool operator() (TYPE obj) const{
return obj->channelID().uniqueLayer()==aChan.uniqueLayer();}
};
template <class TYPE>
class sector_eq: public std::unary_function<TYPE,bool>{
LHCb::STChannelID aChan;
public:
explicit sector_eq(const LHCb::STChannelID& testChan) : aChan(testChan){}
inline bool operator() (TYPE obj) const{
return obj->channelID().uniqueSector()==aChan.uniqueSector();}
};
template <class TYPE>
class compByStation_LB: public std::binary_function<const TYPE, const LHCb::STChannelID, bool>{
public:
inline bool operator() (const TYPE& obj, const LHCb::STChannelID& testID) const{
return ((!obj) ? false : testID.station() >obj->channelID().station());
}
};
template <class TYPE>
class compByStation_UB: public std::binary_function<const LHCb::STChannelID,const TYPE ,bool>{
public:
inline bool operator() (const LHCb::STChannelID& testID, const TYPE& obj) const{
return ((!obj) ? false : testID.station() >obj->channelID().station());
}
};
template <class TYPE>
class compByLayer_LB: public std::binary_function<const TYPE, const LHCb::STChannelID, bool>{
LHCb::STChannelID testID;
public:
inline bool operator() (const TYPE& obj,const LHCb::STChannelID& testID) const{
return ((!obj) ? false : testID.uniqueLayer() >obj->channelID().uniqueLayer());
}
};
template <class TYPE>
class compByLayer_UB: public std::binary_function<const LHCb::STChannelID,const TYPE ,bool>{
LHCb::STChannelID testID;
public:
inline bool operator()(const LHCb::STChannelID& testID, const TYPE& obj) const{
return ((!obj) ? false : testID.uniqueLayer() >obj->channelID().uniqueLayer());
}
};
template <class TYPE>
class compBySector_LB: public std::binary_function<const TYPE, const LHCb::STChannelID, bool>{
LHCb::STChannelID testID;
public:
inline bool operator() (const TYPE& obj,const LHCb::STChannelID& testID) const{
return ((!obj) ? false : testID.uniqueSector() >obj->channelID().uniqueSector());
}
};
template <class TYPE>
class compBySector_UB: public std::binary_function<const LHCb::STChannelID, const TYPE ,bool>{
LHCb::STChannelID testID;
public:
inline bool operator() (const LHCb::STChannelID& testID, const TYPE& obj) const{
return ((!obj) ? false : testID.uniqueSector() >obj->channelID().uniqueSector());
}
};
}
#endif // _STDataFunctor_H_
| true |
9d7c4a9ed9d9c8db519cb430d2b3fde489be0094 | C++ | beduty/QtTrain | /101_QtGame_Custom2DGraphicsViewDemo/main.cpp | UTF-8 | 2,869 | 2.90625 | 3 | [] | no_license | #include <QApplication>
#include <QGraphicsRectItem>
#include <QGraphicsScene>
#include <QGraphicsView>
QGraphicsRectItem *createComplexItem(qreal width, qreal height, qreal radius);
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
// 1. Test
// QGraphicsScene scene;
// //scene.setSceneRect(0,20,100,100);
// QGraphicsRectItem *rectItem = new QGraphicsRectItem(QRect(0,0,100,50));
// scene.addItem(rectItem);
// QGraphicsEllipseItem *circleItem = new QGraphicsEllipseItem(QRect(0,50,25,25));
// scene.addItem(circleItem);
// QGraphicsSimpleTextItem *textItem = new QGraphicsSimpleTextItem(QObject::tr("Demo"));
// scene.addItem(textItem);
// QGraphicsView view(&scene);
// //view.setAlignment(Qt::AlignTop | Qt::AlignLeft);
//// view.scale(5,5);
//// view.rotate(20);
// view.show();
// 2. Test
// QGraphicsScene scene;
// scene.addLine(-100,0,100,0);
// scene.addLine(0,-100,0,100);
// QGraphicsItem* rectItem = scene.addRect(-25,-25,50,50);
// rectItem->setPos(75,75);
// rectItem->setRotation(45);
// QGraphicsView view(&scene);
// view.show();
// 3. Test
// QGraphicsScene scene;
// scene.addLine(-100,0,100,0);
// scene.addLine(0,-100,0,100);
// QGraphicsItem* rectItem = scene.addRect(50,50,50,50);
// rectItem->setTransformOriginPoint(75,75);
// rectItem->setRotation(45);
// QGraphicsView view(&scene);
// view.show();
// 4. Make Group!
// QObject의 Parent를 하나 만들고, 하위에 Child들을 넣을 수 있다.
// Children은 기존 Screne에 독립되고,
// Parent 좌표에 상대적인 위치와 Parent의 Transform에 상대적인 Transform을 가진다.
QGraphicsScene scene;
QGraphicsRectItem *item1 = createComplexItem(100,60,8);
scene.addItem(item1);
QGraphicsRectItem *item2 = createComplexItem(100,60,8);
scene.addItem(item2);
item2->setPos(200,0);
item2->setRotation(20);
QGraphicsView view(&scene);
view.show();
return a.exec();
}
QGraphicsRectItem *createComplexItem(qreal width, qreal height, qreal radius)
{
QRectF rect(-width/2, -height/2, width, height);
QGraphicsRectItem *parent = new QGraphicsRectItem(rect);
QRectF circleBoundary(-radius, -radius, 2*radius, 2*radius);
for(int i = 0; i < 4; i ++)
{
QGraphicsEllipseItem *child = new QGraphicsEllipseItem(circleBoundary, parent);
child->setBrush(Qt::black);
QPointF pos;
switch (i)
{
case 0:
pos = rect.topLeft();
break;
case 1:
pos = rect.bottomLeft();
break;
case 2:
pos = rect.topRight();
break;
case 3:
pos = rect.bottomRight();
break;
}
child->setPos(pos);
}
return parent;
}
| true |
95c325485f940cb765c6f71b1c7299b94a5889de | C++ | dhanendraverma/Daily-Coding-Problem | /Day74.cpp | UTF-8 | 1,163 | 3.6875 | 4 | [] | no_license | /*****************************************************************************************************************************************
This problem was asked by Apple.
Suppose you have a multiplication table that is N by N. That is, a 2D array where the value at the i-th row and j-th column is
(i + 1) * (j + 1) (if 0-indexed) or i * j (if 1-indexed).
Given integers N and X, write a function that returns the number of times X appears as a value in an N by N multiplication table.
For example, given N = 6 and X = 12, you should return 4, since the multiplication table looks like this:
| 1 | 2 | 3 | 4 | 5 | 6 |
| 2 | 4 | 6 | 8 | 10 | 12 |
| 3 | 6 | 9 | 12 | 15 | 18 |
| 4 | 8 | 12 | 16 | 20 | 24 |
| 5 | 10 | 15 | 20 | 25 | 30 |
| 6 | 12 | 18 | 24 | 30 | 36 |
And there are 4 12's in the table
******************************************************************************************************************************************/
#include <iostream>
using namespace std;
int main() {
int n=6,x=4;
int ans = x<=n?2:0;
for(int i=2;i<n/2+1;i++){
if(x%i==0){
if(i*i==x)
ans += 1;
else
ans += 2;
}
}
cout<<ans<<endl;
return 0;
}
| true |
74ba4854552c994c2224c14ff300551ac8e44e6d | C++ | igy234/SFMLSampleGame | /SFMLSampleGame/IOpponent.h | UTF-8 | 341 | 2.515625 | 3 | [] | no_license | #pragma once
#include "stdafx.h"
///Interface for managing AI
class IOpponent
{
public:
///@brief method responsible for Ai's decision and move making
virtual void MakeMove() = 0;
///@brief method responsible for calculating number of cards in AI's hand
///@returns number of cards in AI's hand
virtual int GetNumberOfCards() = 0;
};
| true |
c366ae5e7b60aff7c9c247dc31bffed30a51db7c | C++ | hpdipto/ROB302-Artificial-Intelligence-Lab | /allPossiblePathBFS.cpp | UTF-8 | 1,261 | 3.171875 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#include <vector>
#include <queue>
using namespace std;
vector<int>edges[50];
queue< vector<int> >paths;
bool inPath(vector<int>path, int node)
{
int len = path.size();
for(int i = 0; i < len; i++) {
if(path[i] == node)
return false;
}
return true;
}
void bfs(vector<int>graph[], int source, int goal)
{
vector<int>p;
p.push_back(source);
int len = graph[source].size();
for(int i = 0; i < len; i++) {
p.push_back(graph[source][i]);
paths.push(p);
p.pop_back();
}
while(!paths.empty()) {
p = paths.front();
len = p.size();
int lastNode = p.back();
if(lastNode == goal) {
len = p.size();
for(int j = 0; j < len; j++)
cout << p[j] << " ";
cout << endl;
paths.pop();
continue;
}
len = graph[lastNode].size();
for(int i = 0; i < len; i++) {
int node = graph[lastNode][i];
if(inPath(p, node)) {
p.push_back(node);
paths.push(p);
p.pop_back();
}
}
paths.pop();
}
}
int main()
{
int N, E, i;
scanf("%d%d", &N, &E);
for(i = 1; i <= E; i++) {
int x, y;
scanf("%d%d", &x, &y);
edges[x].push_back(y);
edges[y].push_back(x);
}
bfs(edges, 1, 8);
return 0;
}
| true |
a33c8aea71fec8ae88046b28bae88b7e871ad794 | C++ | zjsxzy/algo | /Poj/P3686.cpp | UTF-8 | 2,170 | 2.578125 | 3 | [] | no_license | #include <map>
#include <set>
#include <list>
#include <cmath>
#include <queue>
#include <stack>
#include <bitset>
#include <vector>
#include <cstdio>
#include <string>
#include <sstream>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int MAXN = 55 * 55;
const int inf = 0x3f3f3f3f;
struct KM
{
int E[MAXN][MAXN], n, m, slack;
bool map[MAXN][MAXN];
bool visx[MAXN], visy[MAXN];
int mate[MAXN], lx[MAXN], ly[MAXN];
void init(int n, int m)
{
this->n = n;
this->m = m;
memset(E, 0, sizeof(E));
}
void addEdge(int i, int j, int k)
{
E[i][j] = k;
}
bool path(int x)
{
visx[x] = true;
for (int y = 0; y < m; y++)
{
if (visy[y]) continue;
int t = lx[x] + ly[y] - E[x][y];
if (t == 0)
{
visy[y] = true;
if (mate[y] == -1 || path(mate[y]))
{
mate[y] = x;
return true;
}
}
else if (slack > t) slack = t;
}
return false;
}
int solve()
{
memset(mate, -1, sizeof(mate));
memset(lx, 0, sizeof(lx));
memset(ly, 0, sizeof(ly));
for (int x = 0; x < n; x++)
for (int y = 0; y < m; y++)
if (E[x][y] > lx[x]) lx[x] = E[x][y];
for (int x = 0; x < n; x++)
{
while (1)
{
memset(visx, 0, sizeof(visx));
memset(visy, 0, sizeof(visy));
slack = inf;
if (path(x)) break;
for (int i = 0; i < n; i++)
if (visx[i]) lx[i] -= slack;
for (int i = 0; i < m; i++)
if (visy[i]) ly[i] += slack;
}
}
int ans = 0;
for (int y = 0; y < m; y++)
if (mate[y] != -1)
ans += E[mate[y]][y];
return ans;
}
};
KM km;
int main()
{
freopen("a", "r", stdin);
int T;
scanf("%d", &T);
while (T--)
{
int N, M;
scanf("%d%d", &N, &M);
km.init(N, N * M);
for (int i = 0; i < N; i++)
{
for (int j = 0; j < M; j++)
{
int tmp;
scanf("%d", &tmp);
for (int k = 0; k < N; k++)
{
km.addEdge(i, j * N + k, -tmp * (k + 1));
//cout << i << " " << j << " " << k << " " << tmp * (k + 1) << endl;
}
}
}
int ans = -km.solve();
printf("%.6lf\n", (double)ans / N);
}
return 0;
}
| true |
614d1528d9a7d11ad81648b44ffbbfaf038eb7d4 | C++ | ysyisyourbrother/My-Leetcode | /数据结构与算法/链表/ArrayList, version 2 .cpp | GB18030 | 4,063 | 3.953125 | 4 | [] | no_license | #include <iostream>
using namespace std;
typedef int T;
class ArrayList2 {
public:
ArrayList2()//Ա
{
elems=NULL;
count=0;
arraySize=0;
}
ArrayList2(int n)//쳤ȣsizeΪnԱ
{
elems = new T[n];
count=n;
arraySize=n;
}
~ArrayList2()
{
delete []elems;
count=0;
arraySize=0;
}
ArrayList2(const ArrayList2 & c)
{
elems = new T[c.arraySize];
for(int i=0;i<c.count;i++)
{
elems[i]=c.elems[i];
}
count=c.count;
arraySize=c.arraySize;
}
const ArrayList2& operator = (ArrayList2 & c)
{
if(elems!=NULL)
{
delete []elems;
}
elems = new T[c.arraySize];
for(int i=0;i<c.count;i++)
{
elems[i]=c.elems[i];
}
count=c.count;
arraySize=c.arraySize;
return *this;
}
int size() const //ԱԪظ
{
return count;
}
int capacity()const//
{
return arraySize;
}
bool full() const //true, false.
{
return count==arraySize;
}
bool empty() const //գtrue, false.
{
return count==0;
}
void clear() //Ϊձ
{
count=0;
}
void traverse(void (*visit)(T &))// (*visit)ӦõÿԪϡ
{
for(int i=0;i<count;i++)
{
visit(elems[i]);
}
}
void retrieve(int position, T &x) const
{
if(0<=position&&position<=size()-1)
{
x=elems[position];
}
else
return;
}
//0=<position<=size()-1, xλpositionԪ
//Ϊ.
void replace(int position, const T &x)
{
if(0<=position&&position<=size()-1)
{
elems[position]=x;
}
else
return;
}
//0=<position<=size()-1, λpositionԪijx.
//Ϊ.
void erase(int position, T &x)
{
if(0<=position&&position<=size()-1)
{
x=elems[position];
for(int i=position;i<count-1;i++)
{
elems[i]=elems[i+1];
}
count--;
}
else
return;
}
//0=<position<=size()-1, λpositionԪɾ
//ɾԪxأΪ.
void erase(int position)
{
if(0<=position&&position<=size()-1)
{
for(int i=position;i<count-1;i++)
{
elems[i]=elems[i+1];
}
count--;
}
else
return;
}
T & operator [] (int position)
{
return elems[position];
}
//0=<position<=size()-1, λpositionԪ
//Ϊ.
int find( T &x) const //return the position of the first occurrence of x if it exists, return -1 otherwise.
{
for(int i=0;i<count;i++)
{
if(elems[i]==x)
{
return i;
}
}
return -1;
}
void push_back(const T &x)//put x after the last item
{
insert(count,x);
}
void insert(int position, const T &x)
{
if(0<=position&&position<=size())
{
if(full())
{
T* newlist = new T[arraySize+1];//չС,ÿչ5С
for(int i=0;i<position;i++)
{
newlist[i]=elems[i];
}
newlist[position]=x;
for(int i=position+1;i<=count;i++)
{
newlist[i]=elems[i-1];
}
count++;
arraySize++;
delete []elems;
elems=newlist;
return;
}
for(int i=count-1;i>=position;i--)
{
elems[i+1]=elems[i];
}
elems[position]=x;
count++;
}
else
return;
}
//0=<position<=size(), x뵽λposition.
//Ϊ.
private:
T *elems;
int count; //¼elemsд洢Ԫظ
int arraySize;//鳤
};
int main()
{
ArrayList2 lst1(5);
lst1.push_back(1);
lst1.push_back(2);
lst1.push_back(3);
lst1.push_back(4);
lst1.push_back(5);
lst1.push_back(6);
ArrayList2 lst2(lst1);
lst2.erase(0);
lst1=lst2;
cout<<lst1[0];
}
| true |
85481b5804ae40cddccc878806f44af5c337cac3 | C++ | rhzx3519/leetcode | /c++/211. Add and Search Word - Data structure design.cpp | UTF-8 | 3,071 | 3.609375 | 4 | [] | no_license | static const int DICT_SIZE = 26;
struct TrieNode {
public:
TrieNode(char ch = '\0', struct TrieNode *parent = NULL) {
this->is_word = false;
this->ch = ch;
this->parent = parent;
this->children.resize(DICT_SIZE, NULL);
}
~TrieNode() {
int len = this->children.size();
int i;
for (i = 0; i < len; i++) {
if (this->children[i] != NULL) {
delete this->children[i];
this->children[i] = NULL;
}
}
this->children.clear();
}
public:
char ch;
bool is_word;
vector<TrieNode*> children;
TrieNode* parent;
};
class Trie {
public:
/** Initialize your data structure here. */
Trie() {
root = new TrieNode();
}
/** Inserts a word into the trie. */
void insert(string word) {
int lw = word.size();
int i, idx;
TrieNode *p = root;
for (i = 0; i < lw; i++) {
idx = word[i] - 'a';
if (p->children[idx] == NULL)
p->children[idx] = new TrieNode(word[i], p);
p = p->children[idx];
}
p->is_word = true;
}
/** Returns if the word is in the trie. */
bool search(TrieNode *root, string word, int idx) {
int lw = word.size();
int t;
while (idx < lw && word[idx] != '.') {
t = word[idx] - 'a';
root = root->children[t];
if (root == NULL)
return false;
idx++;
}
if (idx == lw)
return root->is_word;
for (int i = 0; i < root->children.size(); i++) {
if (root->children[i] != NULL && search(root->children[i], word, idx + 1))
return true;
}
return false;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
int lw = prefix.size();
int i, idx;
TrieNode *p = root;
for (i = 0; i < lw; i++) {
idx = prefix[i] - 'a';
p = p->children[idx];
if (p == NULL)
return false;
}
return(p != NULL);
}
public:
TrieNode *root;
};
class WordDictionary {
public:
/** Initialize your data structure here. */
WordDictionary() {
trie = new Trie();
}
~WordDictionary() {
delete trie;
trie = NULL;
}
/** Adds a word into the data structure. */
void addWord(string word) {
trie->insert(word);
}
/** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
bool search(string word) {
return trie->search(trie->root, word, 0);
}
private:
Trie *trie;
};
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary obj = new WordDictionary();
* obj.addWord(word);
* bool param_2 = obj.search(word);
*/ | true |
12dad57b7df81af870512077bc6329efe6d0bea6 | C++ | yoshizakikohei/Cgengo_kadai | /kadai/kadai2/kadai2/kadai2.cpp | SHIFT_JIS | 1,771 | 3.015625 | 3 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
#include <malloc.h>
#include<string.h>
#define NINZU 500
typedef char namae[10];
//\̂̐錾
typedef struct date{
int *english;
int *math;
int *science;
}score;
int main(void){
FILE *fp;
char *fname = "data.csv";
char maxname[10];
int maxenglish, maxmath, maxscience;
char buf[4][5];
namae *name;
score seiseki;
name = (namae *)malloc(sizeof(namae) * 500);
if(name == NULL) exit(0);
seiseki.english = (int *)malloc(sizeof(int) * 500);
if(seiseki.english == NULL) exit(0);
seiseki.math = (int *)malloc(sizeof(int) * 500);
if(seiseki.math == NULL) exit(0);
seiseki.science = (int *)malloc(sizeof(int) * 500);
if(seiseki.science == NULL) exit(0);
fp = fopen(fname, "r");
if(fp == NULL){
printf("%st@CJ܂\n", fname);
return -1;
}
printf("\n");
//1sړǂݍ
fscanf(fp, "%[^,], %[^,], %[^,], %s", buf[0], buf[1], buf[2], buf[3]);
printf("%s %s %s %s\n", buf[0], buf[1], buf[2], buf[3]);
//2sڈȍ~ǂݍ
for(int i = 0; i < NINZU; i++){
fscanf(fp, "%[^,], %d, %d, %d", name[i], &seiseki.english[i], &seiseki.math[i], &seiseki.science[i]);
printf("%s %d %d %d\n", name[i], seiseki.english[i], seiseki.math[i], seiseki.science[i]);
}
//_ւ
/*maxenglish = 0;
for(i = 0; i <= NINZU; i++){
if(seiseki.english[i] < seiseki.english[i +1]){
strcpy(maxname, name[i + 1]);
maxenglish = seiseki.english[i + 1];
maxmath = seiseki.math[i + 1];
maxscience = seiseki.science[i + 1];
}
}
//ō_̕\
printf("%s %d %d %d", maxname, maxenglish, maxmath, maxscience);
*/
fclose(fp);
free(name);
free(seiseki.english);
free(seiseki.math);
free(seiseki.science);
return 0;
} | true |
af5fbdaaeaf2f88c77691bce17a1f14782604ee6 | C++ | sp3arm4n/CPP-Programming | /practice/2020/1.cpp | UTF-8 | 405 | 3.125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
int num1, num2, i;
int sum1 = 0, sum2 = 0;
print("두 정수를 입력하시오: ");
scanf_s("%d %d", &num1, &num2);
for (i = 1; i <= num1; i++) {
if ((num1 % i) == 0)
sum1++;
}
for (i = 1; i <= num2; i++) {
if ((num2 % i) == 0)
sum2++;
}
printf("\n약수들의 갯수: %d %d\n", sum1, sum2);
return 0;
} | true |
5c7da025f8e881e7034da0463f75d29ffaea7dd2 | C++ | MChang1984/GSP420EngineDemo | /Main/ProjectileManager.cpp | UTF-8 | 824 | 2.6875 | 3 | [] | no_license | //Projectile Manager, Bullet, and Missile classes created by Darrell Smith and Brent Spector
#include "ProjectileManager.h"
#include "Game.h"
void ProjectileManager::update(const float dt)
{
std::list<Bullet>::iterator it1 = Bullets.begin();
while (it1 != Bullets.end())
{
if (!it1->isEnabled())
it1 = Bullets.erase(it1);
else
++it1;
}
std::list<Missile>::iterator it2 = Missiles.begin();
while (it2 != Missiles.end())
{
if (!it2->isEnabled())
it2 = Missiles.erase(it2);
else
++it2;
}
}
void ProjectileManager::removeTarget(Enemy* targ)
{
for (std::list<Missile>::iterator it = Missiles.begin(), end = Missiles.end();
it != end; ++it)
{
//if it is a player missile and has a matching target, set the target to NULL instead
if (it->getEnemyTarget() == targ)
{
it->setEnemyTarget(NULL);
}
}
}
| true |
69b206f597736388114d0dba74fac7a64e336375 | C++ | liming-vie/LeetCode | /BinaryTreeMaximumPathSum.cpp | UTF-8 | 660 | 2.84375 | 3 | [] | no_license | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#define MAX(a,b) (a>b?a:b)
class Solution {
public:
int res=1<<31;
int func(TreeNode* root) {
if(!root) return 0;
int a=func(root->left), b=func(root->right);
int max=a+b+root->val;
int tmp=MAX(a,b)+root->val;
tmp=MAX(tmp, root->val);
max=MAX(max, tmp);
res=MAX(max, res);
return tmp;
}
int maxPathSum(TreeNode* root) {
func(root);
return res;
}
}; | true |
f6be3620758af3b83af3ddb4c73ed8371a314ded | C++ | mcarrier1851/lcd_ili9341 | /lib/gfx/src/gfx_drawing.hpp | UTF-8 | 74,590 | 2.546875 | 3 | [] | no_license | #ifndef HTCW_GFX_DRAWING_HPP
#define HTCW_GFX_DRAWING_HPP
#include "bits.hpp"
#include "gfx_core.hpp"
#include "gfx_pixel.hpp"
#include "gfx_positioning.hpp"
#include "gfx_font.hpp"
namespace gfx {
enum struct bitmap_flags {
crop = 0,
resize = 1
};
// provides drawing primitives over a bitmap or compatible type
struct draw {
private:
template<typename Destination,typename Source,bool BltDst,bool BltSrc,bool Async>
struct draw_bmp_caps_helper {
};
template<typename Destination,typename Source>
struct draw_bmp_caps_helper<Destination,Source,true,true,false> {
static gfx::gfx_result do_draw(Destination& destination, Source& source, const gfx::rect16& src_rect,gfx::point16 location) {
return source.blt_to(src_rect,destination,location);
}
};
template<typename Destination,typename Source>
struct draw_bmp_caps_helper<Destination,Source,false,true,false> {
static gfx::gfx_result do_draw(Destination& destination, Source& source, const gfx::rect16& src_rect,gfx::point16 location) {
return destination.copy_from(src_rect,source,location);
}
};
template<typename Destination,typename Source>
struct draw_bmp_caps_helper<Destination,Source,true,true,true> {
static gfx::gfx_result do_draw(Destination& destination, Source& source, const gfx::rect16& src_rect,gfx::point16 location) {
return source.blt_to_async(src_rect,destination,location);
}
};
template<typename Destination,typename Source>
struct draw_bmp_caps_helper<Destination,Source,false,true,true> {
static gfx::gfx_result do_draw(Destination& destination, Source& source, const gfx::rect16& src_rect,gfx::point16 location) {
return destination.copy_from_async(src_rect,source,location);
}
};
template<typename Destination,typename Source,bool Batch,bool Async>
struct draw_bmp_batch_caps_helper {
};
template<typename Destination,typename Source>
struct draw_bmp_batch_caps_helper<Destination,Source,false,false> {
static gfx_result do_draw(Destination& destination, const gfx::rect16& dstr, Source& source,const gfx::rect16& srcr,int o) {
// do cropping
bool flipX = (int)rect_orientation::flipped_horizontal==(o&(int)rect_orientation::flipped_horizontal);
bool flipY= (int)rect_orientation::flipped_vertical==(o&(int)rect_orientation::flipped_vertical);
uint16_t x2=srcr.x1;
uint16_t y2=srcr.y1;
for(typename rect16::value_type y=dstr.y1;y<=dstr.y2;++y) {
for(typename rect16::value_type x=dstr.x1;x<=dstr.x2;++x) {
typename Source::pixel_type px;
uint16_t ssx=x2;
uint16_t ssy=y2;
if(flipX) {
ssx= srcr.x2-x2;
}
if(flipY) {
ssy=srcr.y2-y2;
}
gfx_result r = source.point(point16(ssx,ssy),&px);
if(gfx_result::success!=r)
return r;
typename Destination::pixel_type px2=px.template convert<typename Destination::pixel_type>();
r=destination.point(point16(x,y),px2);
if(gfx_result::success!=r)
return r;
++x2;
if(x2>srcr.x2)
break;
}
x2=srcr.x1;
++y2;
if(y2>srcr.y2)
break;
}
return gfx_result::success;
}
};
template<typename Destination,typename Source>
struct draw_bmp_batch_caps_helper<Destination,Source,true,false> {
static gfx_result do_draw(Destination& destination, const gfx::rect16& dstr, Source& source,const gfx::rect16& srcr,int o) {
// do cropping
bool flipX = (int)rect_orientation::flipped_horizontal==(o&(int)rect_orientation::flipped_horizontal);
bool flipY= (int)rect_orientation::flipped_vertical==(o&(int)rect_orientation::flipped_vertical);
//gfx::rect16 sr = source_rect.crop(source.bounds()).normalize();
uint16_t x2=0;
uint16_t y2=0;
gfx_result r = destination.begin_batch(dstr);
if(gfx_result::success!=r)
return r;
for(typename rect16::value_type y=dstr.y1;y<=dstr.y2;++y) {
for(typename rect16::value_type x=dstr.x1;x<=dstr.x2;++x) {
typename Source::pixel_type px;
uint16_t ssx=x2+srcr.x1;
uint16_t ssy=y2+srcr.y1;
if(flipX) {
ssx= srcr.x2-x2;
}
if(flipY) {
ssy=srcr.y2-y2;
}
r = source.point(point16(ssx,ssy),&px);
if(gfx_result::success!=r)
return r;
typename Destination::pixel_type px2=px.template convert<typename Destination::pixel_type>();
r=destination.write_batch(px2);
if(gfx_result::success!=r)
return r;
++x2;
}
x2=0;
++y2;
}
r=destination.commit_batch();
if(gfx_result::success!=r) {
return r;
}
return gfx_result::success;
}
};
template<typename Destination,typename Source>
struct draw_bmp_batch_caps_helper<Destination,Source,false,true> {
static gfx_result do_draw(Destination& destination, const gfx::rect16& dstr, Source& source,const gfx::rect16& srcr,int o) {
// do cropping
bool flipX = (int)rect_orientation::flipped_horizontal==(o&(int)rect_orientation::flipped_horizontal);
bool flipY= (int)rect_orientation::flipped_vertical==(o&(int)rect_orientation::flipped_vertical);
uint16_t x2=srcr.x1;
uint16_t y2=srcr.y1;
for(typename rect16::value_type y=dstr.y1;y<=dstr.y2;++y) {
for(typename rect16::value_type x=dstr.x1;x<=dstr.x2;++x) {
typename Source::pixel_type px;
uint16_t ssx=x2;
uint16_t ssy=y2;
if(flipX) {
ssx= srcr.x2-x2;
}
if(flipY) {
ssy=srcr.y2-y2;
}
gfx_result r = source.point(point16(ssx,ssy),&px);
if(gfx_result::success!=r)
return r;
typename Destination::pixel_type px2=px.template convert<typename Destination::pixel_type>();
r=destination.point_async(point16(x,y),px2);
if(gfx_result::success!=r)
return r;
++x2;
if(x2>srcr.x2)
break;
}
x2=srcr.x1;
++y2;
if(y2>srcr.y2)
break;
}
return gfx_result::success;
}
};
template<typename Destination,typename Source>
struct draw_bmp_batch_caps_helper<Destination,Source,true,true> {
static gfx_result do_draw(Destination& destination, const gfx::rect16& dstr, Source& source,const gfx::rect16& srcr,int o) {
// do cropping
bool flipX = (int)rect_orientation::flipped_horizontal==(o&(int)rect_orientation::flipped_horizontal);
bool flipY= (int)rect_orientation::flipped_vertical==(o&(int)rect_orientation::flipped_vertical);
//gfx::rect16 sr = source_rect.crop(source.bounds()).normalize();
uint16_t x2=0;
uint16_t y2=0;
gfx_result r = destination.begin_batch_async(dstr);
if(gfx_result::success!=r)
return r;
for(typename rect16::value_type y=dstr.y1;y<=dstr.y2;++y) {
for(typename rect16::value_type x=dstr.x1;x<=dstr.x2;++x) {
typename Source::pixel_type px;
uint16_t ssx=x2+srcr.x1;
uint16_t ssy=y2+srcr.y1;
if(flipX) {
ssx= srcr.x2-x2;
}
if(flipY) {
ssy=srcr.y2-y2;
}
r = source.point(point16(ssx,ssy),&px);
if(gfx_result::success!=r)
return r;
typename Destination::pixel_type px2=px.template convert<typename Destination::pixel_type>();
r=destination.write_batch_async(px2);
if(gfx_result::success!=r)
return r;
++x2;
}
x2=0;
++y2;
}
r=destination.commit_batch_async();
if(gfx_result::success!=r) {
return r;
}
return gfx_result::success;
}
};
template<typename Destination,typename Source>
static gfx_result draw_bitmap_impl(Destination& destination, const srect16& dest_rect, Source& source, const rect16& source_rect,bitmap_flags options,srect16* clip,bool async) {
gfx_result r;
rect16 dr;
if(!translate_adjust(dest_rect,&dr))
return gfx_result::success; // whole thing is offscreen
// get the scale
float sx = dest_rect.width()/(float)source_rect.width();
float sy = dest_rect.height()/(float)source_rect.height();
int o = (int)dest_rect.orientation();
point16 loc(0,0);
rect16 ccr;
if(nullptr!=clip) {
if(!translate_adjust(*clip,&ccr))
return gfx_result::success; // clip rect is off screen
dr = dr.crop(ccr);
}
dr = dr.normalize();
size16 dim(dr.width(),dr.height());
if(dim.width>source_rect.width())
dim.width = source_rect.width();
if(dim.height>source_rect.height())
dim.height = source_rect.height();
auto x2=dest_rect.left();
auto y2=dest_rect.top();
if(0>x2) {
loc.x = -x2;
if(nullptr==clip)
dim.width+=dest_rect.x1;
}
if(0>y2) {
loc.y = -y2;
if(nullptr==clip)
dim.height+=y2;
}
loc.x+=source_rect.top();
loc.y+=source_rect.left();
rect16 srcr = rect16(loc,dim);
rect16 dstr(dr.x1,dr.y1,srcr.width()*sx+.5+dr.x1,srcr.height()*sy+.5+dr.y1);
if(dstr.x2>dr.x2) dstr.x2=dr.x2;
if(dstr.y2>dr.y2) dstr.y2=dr.y2;
if((int)bitmap_flags::resize!=((int)options&(int)bitmap_flags::resize)) {
gfx_result r;
if(async)
r=draw_bmp_batch_caps_helper<Destination,Source,Destination::caps::batch_write,Destination::caps::async>::do_draw(destination,dstr,source,srcr,o);
else
r=draw_bmp_batch_caps_helper<Destination,Source,Destination::caps::batch_write,false>::do_draw(destination,dstr,source,srcr,o);
if(gfx_result::success!=r)
return r;
} else {
if((int)rect_orientation::flipped_horizontal==(o&(int)rect_orientation::flipped_horizontal)) {
dstr=dstr.flip_horizontal();
}
if((int)rect_orientation::flipped_vertical==(o&(int)rect_orientation::flipped_vertical)) {
dstr=dstr.flip_vertical();
}
// TODO: Modify this to write the destination left to right top to bottom
// and then use batching to speed up writes
// do resizing
int o = (int)dest_rect.orientation();
uint32_t x_ratio = (uint32_t)((dest_rect.width()<<16)/source_rect.width()) +1;
uint32_t y_ratio = (uint32_t)((dest_rect.height()<<16)/source_rect.height()) +1;
bool growX = dest_rect.width()>source_rect.width(),
growY = dest_rect.height()>source_rect.height();
point16 p(-1,-1);
point16 ps;
srcr = source_rect.normalize();
for(ps.y=srcr.y1;ps.y<srcr.y2;++ps.y) {
for(ps.x=srcr.x1;ps.x<srcr.x2;++ps.x) {
uint16_t px = ps.x;
uint16_t py = ps.y;
if((int)rect_orientation::flipped_horizontal==((int)rect_orientation::flipped_horizontal&o)) {
px=source_rect.width()-px-1;
}
if((int)rect_orientation::flipped_vertical==((int)rect_orientation::flipped_vertical&o)) {
py=source_rect.height()-py-1;
}
uint16_t ux(((px*x_ratio)>>16));
uint16_t uy(((py*y_ratio)>>16));
ux+=dstr.left();
uy+=dstr.top();
if(ux!=p.x || uy!=p.y) {
typename Source::pixel_type px;
r= source.point(ps,&px);
if(gfx_result::success!=r)
return r;
p=point16(ux,uy);
typename Destination::pixel_type px2=px.template convert<typename Destination::pixel_type>();
if(!(growX || growY)) {
r=destination.point(p,px2);
if(gfx_result::success!=r)
return r;
} else {
uint16_t w = x_ratio>>16,h=y_ratio>>16;
r=destination.fill(rect16(p,size16(w,h)),px2);
if(gfx_result::success!=r)
return r;
}
}
}
}
}
return gfx_result::success;
}
template<typename Destination,typename Source,typename DestinationPixelType,typename SourcePixelType>
struct bmp_helper {
inline static gfx_result draw_bitmap(Destination& destination, const srect16& dest_rect, Source& source, const rect16& source_rect,bitmap_flags options,srect16* clip,bool async) {
return draw_bitmap_impl(destination,dest_rect,source,source_rect,options,clip,async);
}
};
template<typename Destination,typename Source,typename PixelType>
struct bmp_helper<Destination,Source,PixelType,PixelType> {
static gfx_result draw_bitmap(Destination& destination, const srect16& dest_rect, Source& source, const rect16& source_rect,bitmap_flags options,srect16* clip,bool async) {
const bool optimized = (Destination::caps::blt || Destination::caps::frame_write_partial) && (Source::caps::blt);
// disqualify fast blting
if(!optimized || dest_rect.x1>dest_rect.x2 ||
dest_rect.y1>dest_rect.y2 ||
((int)bitmap_flags::resize==((int)options&(int)bitmap_flags::resize)&&
(dest_rect.width()!=source_rect.width()||
dest_rect.height()!=source_rect.height())
)
) {
return draw_bitmap_impl(destination,dest_rect,source,source_rect,options,clip,async);
}
rect16 dr;
if(!translate_adjust(dest_rect,&dr))
return gfx_result::success; // whole thing is offscreen
point16 loc(0,0);
rect16 ccr;
if(nullptr!=clip) {
if(!translate_adjust(*clip,&ccr))
return gfx_result::success; // clip rect is off screen
dr = dr.crop(ccr);
}
size16 dim(dr.width(),dr.height());
if(dim.width>source_rect.width())
dim.width = source_rect.width();
if(dim.height>source_rect.height())
dim.height = source_rect.height();
if(0>dest_rect.x1) {
loc.x = -dest_rect.x1;
if(nullptr==clip)
dim.width+=dest_rect.x1;
}
if(0>dest_rect.y1) {
loc.y = -dest_rect.y1;
if(nullptr==clip)
dim.height+=dest_rect.y1;
}
loc.x+=source_rect.top();
loc.y+=source_rect.left();
rect16 r = rect16(loc,dim);
if(async)
return draw_bmp_caps_helper<Destination,Source,Destination::caps::blt,Source::caps::blt,Destination::caps::async>::do_draw(destination,source, r,dr.top_left());
else
return draw_bmp_caps_helper<Destination,Source,Destination::caps::blt,Source::caps::blt,false>::do_draw(destination,source, r,dr.top_left());
}
};
// Defining region codes
constexpr static const int region_inside = 0; // 0000
constexpr static const int region_left = 1; // 0001
constexpr static const int region_right = 2; // 0010
constexpr static const int region_bottom = 4; // 0100
constexpr static const int region_top = 8; // 1000
// Function to compute region code for a point(x, y)
static int region_code(const srect16& rect,float x, float y)
{
// inside
int code = region_inside;
if (x < rect.x1) // to the left of rectangle
code |= region_left;
else if (x > rect.x2) // to the right of rectangle
code |= region_right;
if (y < rect.y1) // above the rectangle
code |= region_top;
else if (y > rect.y2) // below the rectangle
code |= region_bottom;
return code;
}
static bool line_clip(srect16* rect,const srect16* clip) {
float x1=rect->x1,
y1=rect->y1,
x2=rect->x2,
y2=rect->y2;
// Compute region codes for P1, P2
int code1 = region_code(*clip,x1, y1);
int code2 = region_code(*clip,x2, y2);
// Initialize line as outside the rectangular window
bool accept = false;
while (true) {
if ((code1 == region_inside) && (code2 == region_inside)) {
// If both endpoints lie within rectangle
accept = true;
break;
}
else if (code1 & code2) {
// If both endpoints are outside rectangle,
// in same region
break;
}
else {
// Some segment of line lies within the
// rectangle
int code_out;
double x=0, y=0;
// At least one endpoint is outside the
// rectangle, pick it.
if (code1 != 0)
code_out = code1;
else
code_out = code2;
// Find intersection point;
// using formulas y = y1 + slope * (x - x1),
// x = x1 + (1 / slope) * (y - y1)
if (code_out & region_top) {
// point is above the rectangle
x = x1 + (x2 - x1) * (clip->y1 - y1) / (y2 - y1);
y = clip->y1;
} else if (code_out & region_bottom) {
// point is below the clip rectangle
x = x1 + (x2 - x1) * (clip->y2 - y1) / (y2 - y1);
y = clip->y2;
}
else if (code_out & region_right) {
// point is to the right of rectangle
y = y1 + (y2 - y1) * (clip->x2 - x1) / (x2 - x1);
x = clip->x2;
}
else if (code_out & region_left) {
// point is to the left of rectangle
y = y1 + (y2 - y1) * (clip->x1 - x1) / (x2 - x1);
x = clip->x1;
}
// Now intersection point x, y is found
// We replace point outside rectangle
// by intersection point
if (code_out == code1) {
x1 = x;
y1 = y;
code1 = region_code(*clip,x1, y1);
}
else {
x2 = x;
y2 = y;
code2 = region_code(*clip,x2, y2);
}
}
}
if (accept) {
rect->x1=x1+.5;
rect->y1=y1+.5;
rect->x2=x2+.5;
rect->y2=y2+.5;
return true;
}
return false;
}
// TODO: This translate code isn't necessary anymore
// because rects and points such can be converted
// between their signed and unsigned counterparts
static bool translate(spoint16 in,point16* out) {
if(0>in.x||0>in.y||nullptr==out)
return false;
out->x=typename point16::value_type(in.x);
out->y=typename point16::value_type(in.y);
return true;
}
static bool translate(size16 in,ssize16* out) {
if(nullptr==out)
return false;
out->width=typename ssize16::value_type(in.width);
out->height=typename ssize16::value_type(in.height);
return true;
}
static bool translate(const srect16& in,rect16* out) {
if(0>in.x1||0>in.y1||0>in.x2||0>in.y2||nullptr==out)
return false;
out->x1 = typename point16::value_type(in.x1);
out->y1 = typename point16::value_type(in.y1);
out->x2 = typename point16::value_type(in.x2);
out->y2 = typename point16::value_type(in.y2);
return true;
}
static bool translate_adjust(const srect16& in,rect16* out) {
if(nullptr==out || (0>in.x1&&0>in.x2)||(0>in.y1&&0>in.y2))
return false;
srect16 gfx_result = in.crop(srect16(0,0,in.right(),in.bottom()));
out->x1=gfx_result.x1;
out->y1=gfx_result.y1;
out->x2=gfx_result.x2;
out->y2=gfx_result.y2;
return true;
}
template<typename Destination>
static gfx_result ellipse_impl(Destination& destination, const srect16& rect,typename Destination::pixel_type color,srect16* clip,bool filled,bool async) {
gfx_result r;
using int_type = typename srect16::value_type;
int_type x_adj =(1-(rect.width()&1));
int_type y_adj =(1-(rect.height()&1));
int_type rx = rect.width()/2-x_adj;
int_type ry = rect.height()/2-y_adj;
if(0==rx)
rx=1;
if(0==ry)
ry=1;
int_type xc = rect.width()/2+rect.left()-x_adj;
int_type yc = rect.height()/2+rect.top()-y_adj;
float dx, dy, d1, d2, x, y;
x = 0;
y = ry;
// Initial decision parameter of region 1
d1 = (ry * ry)
- (rx * rx * ry)
+ (0.25 * rx * rx);
dx = 2 * ry * ry * x;
dy = 2 * rx * rx * y;
// For region 1
while (dx < dy+y_adj) {
if(filled) {
r=line_impl(destination,srect16(-x + xc, y + yc+y_adj,x + xc+x_adj, y + yc+y_adj),color,clip,async);
if(r!=gfx_result::success)
return r;
r=line_impl(destination,srect16(-x + xc, -y + yc,x + xc+x_adj, -y + yc),color,clip,async);
if(r!=gfx_result::success)
return r;
} else {
// Print points based on 4-way symmetry
r=point_impl(destination,spoint16(x + xc+x_adj, y + yc+y_adj),color,clip,async);
if(r!=gfx_result::success)
return r;
r=point_impl(destination,spoint16(-x + xc, y + yc+y_adj),color,clip,async);
if(r!=gfx_result::success)
return r;
r=point_impl(destination,spoint16(x + xc+x_adj, -y + yc),color,clip,async);
if(r!=gfx_result::success)
return r;
r=point_impl(destination,spoint16(-x + xc, -y + yc),color,clip,async);
if(r!=gfx_result::success)
return r;
}
// Checking and updating value of
// decision parameter based on algorithm
if (d1 < 0) {
++x;
dx = dx + (2 * ry * ry);
d1 = d1 + dx + (ry * ry);
}
else {
++x;
--y;
dx = dx + (2 * ry * ry);
dy = dy - (2 * rx * rx);
d1 = d1 + dx - dy + (ry * ry);
}
}
// Decision parameter of region 2
d2 = ((ry * ry) * ((x + 0.5) * (x + 0.5)))
+ ((rx * rx) * ((y - 1) * (y - 1)))
- (rx * rx * ry * ry);
// Plotting points of region 2
while (y >= 0) {
// printing points based on 4-way symmetry
if(filled) {
r=line_impl(destination,srect16(-x + xc, y + yc+y_adj,x + xc+x_adj, y + yc+y_adj),color,clip,async);
if(r!=gfx_result::success)
return r;
r=line_impl(destination,srect16(-x + xc, -y + yc,x + xc+x_adj, -y + yc),color,clip,async);
if(r!=gfx_result::success)
return r;
} else {
r=point_impl(destination,spoint16(x + xc+x_adj, y + yc+y_adj),color,clip,async);
if(r!=gfx_result::success)
return r;
r=point_impl(destination,spoint16(-x + xc, y + yc+y_adj),color,clip,async);
if(r!=gfx_result::success)
return r;
r=point_impl(destination,spoint16(x + xc+x_adj, -y + yc),color,clip,async);
if(r!=gfx_result::success)
return r;
r=point_impl(destination,spoint16(-x + xc, -y + yc),color,clip,async);
if(r!=gfx_result::success)
return r;
}
// Checking and updating parameter
// value based on algorithm
if (d2 > 0) {
--y;
dy = dy - (2 * rx * rx);
d2 = d2 + (rx * rx) - dy;
}
else {
--y;
++x;
dx = dx + (2 * ry * ry);
dy = dy - (2 * rx * rx);
d2 = d2 + dx - dy + (rx * rx);
}
}
return gfx_result::success;
}
template<typename Destination>
static gfx_result arc_impl(Destination& destination, const srect16& rect,typename Destination::pixel_type color,srect16* clip,bool filled,bool async) {
using int_type = typename srect16::value_type;
gfx_result r;
int_type x_adj =(1-(rect.width()&1));
int_type y_adj =(1-(rect.height()&1));
int orient;
if(rect.y1<=rect.y2) {
if(rect.x1<=rect.x2) {
orient=0;
} else {
orient=2;
}
} else {
if(rect.x1<=rect.x2) {
orient=1;
} else {
orient=3;
}
}
int_type rx = rect.width()-x_adj-1;
int_type ry = rect.height()-1;
int_type xc = rect.width()+rect.left()-x_adj-1;
int_type yc = rect.height()+rect.top()-1;
if(0==rx)
rx=1;
if(0==ry)
ry=1;
float dx, dy, d1, d2, x, y;
x = 0;
y = ry;
// Initial decision parameter of region 1
d1 = (ry * ry)
- (rx * rx * ry)
+ (0.25 * rx * rx);
dx = 2 * ry * ry * x;
dy = 2 * rx * rx * y;
// For region 1
while (dx < dy+y_adj) {
if(filled) {
switch(orient) {
case 0: //x1<=x2,y1<=y2
r=line_impl(destination,srect16(-x + xc, -y + yc, xc+x_adj, -y + yc),color,clip,async);
if(r!=gfx_result::success)
return r;
break;
case 1: //x1<=x2,y1>y2
r=line_impl(destination,srect16(-x + xc, y + yc-ry, xc+x_adj, y + yc-ry),color,clip,async);
if(r!=gfx_result::success)
return r;
break;
case 2: //x1>x2,y1<=y2
r=line_impl(destination,srect16( xc-rx, -y + yc,x + xc+x_adj-rx, -y + yc),color,clip,async);
if(r!=gfx_result::success)
return r;
break;
case 3: //x1>x2,y1>y2
r=line_impl(destination,srect16( xc-rx, y + yc-ry,x + xc-rx, y + yc-ry),color,clip,async);
if(r!=gfx_result::success)
return r;
break;
}
} else {
switch(orient) {
case 0: //x1<=x2,y1<=y2
r=point_impl(destination,spoint16(-x + xc, -y + yc),color,clip,async);
if(r!=gfx_result::success)
return r;
if(x_adj && -y+yc==rect.y1) {
r=point_impl(destination,rect.top_right(),color,clip,async);
if(r!=gfx_result::success)
return r;
}
break;
case 1: //x1<=x2,y1>y2
r=point_impl(destination,spoint16(-x + xc, y + yc-ry),color,clip,async);
if(r!=gfx_result::success)
return r;
if(x_adj && y+yc-ry==rect.y1) {
r=point_impl(destination,rect.bottom_right(),color,clip,async);
if(r!=gfx_result::success)
return r;
}
break;
case 2: //x1>x2,y1<=y2
r=point_impl(destination,spoint16(x + xc+x_adj-rx, -y + yc),color,clip,async);
if(r!=gfx_result::success)
return r;
if(x_adj && -y+yc==rect.y1) {
r=point_impl(destination,rect.top_left(),color,clip,async);
if(r!=gfx_result::success)
return r;
}
break;
case 3: //x1>x2,y1>y2
r=point_impl(destination,spoint16(x + xc+x_adj-rx, y + yc-ry),color,clip,async);
if(r!=gfx_result::success)
return r;
break;
}
}
// Checking and updating value of
// decision parameter based on algorithm
if (d1 < 0) {
++x;
dx = dx + (2 * ry * ry);
d1 = d1 + dx + (ry * ry);
}
else {
++x;
--y;
dx = dx + (2 * ry * ry);
dy = dy - (2 * rx * rx);
d1 = d1 + dx - dy + (ry * ry);
}
}
// Decision parameter of region 2
d2 = ((ry * ry) * ((x + 0.5) * (x + 0.5)))
+ ((rx * rx) * ((y - 1) * (y - 1)))
- (rx * rx * ry * ry);
// Plotting points of region 2
while (y >= 0) {
// printing points based on 4-way symmetry
if(filled) {
switch(orient) {
case 0: //x1<=x2,y1<=y2
r=line_impl(destination,srect16(-x + xc, -y + yc,xc+x_adj, -y + yc),color,clip,async);
if(r!=gfx_result::success)
return r;
break;
case 1: //x1<=x2,y1>y2
r=line_impl(destination,srect16(-x + xc, y + yc-ry,xc+x_adj, y + yc-ry),color,clip,async);
if(r!=gfx_result::success)
return r;
break;
case 2: //x1>x2,y1<=y2
r=line_impl(destination,srect16( xc-rx, -y + yc,x + xc+x_adj-rx, -y + yc),color,clip,async);
if(r!=gfx_result::success)
return r;
break;
case 3: //x1>x2,y1>y2
r=line_impl(destination,srect16(xc-rx, y + yc-ry,x + xc+x_adj-rx, y + yc-ry),color,clip,async);
if(r!=gfx_result::success)
return r;
break;
}
} else {
switch(orient) {
case 0: //x1<=x2,y1<=y2
r=point_impl(destination,spoint16(-x + xc, -y + yc),color,clip,async);
if(r!=gfx_result::success)
return r;
break;
case 1: //x1<=x2,y1>y2
r=point_impl(destination,spoint16(-x + xc, y + yc-ry),color,clip,async);
if(r!=gfx_result::success)
return r;
break;
case 2: //x1>x2,y1<=y2
r=point_impl(destination,spoint16(x + xc+x_adj-rx, -y + yc),color,clip,async);
if(r!=gfx_result::success)
return r;
break;
case 3: //x1>x2,y1>y2
r=point_impl(destination,spoint16(x + xc+x_adj-rx, y + yc-ry),color,clip,async);
if(r!=gfx_result::success)
return r;
break;
}
}
// Checking and updating parameter
// value based on algorithm
if (d2 > 0) {
--y;
dy = dy - (2 * rx * rx);
d2 = d2 + (rx * rx) - dy;
}
else {
--y;
++x;
dx = dx + (2 * ry * ry);
dy = dy - (2 * rx * rx);
d2 = d2 + dx - dy + (rx * rx);
}
}
return gfx_result::success;
}
template<typename Destination,bool Async>
struct draw_point_helper {
};
template<typename Destination>
struct draw_point_helper<Destination,true> {
static gfx_result do_draw(Destination& destination,point16 location,typename Destination::pixel_type color,bool async) {
if(!async) return draw_point_helper<Destination,false>::do_draw(destination,location,color,false);
return destination.point_async(location,color);
}
};
template<typename Destination>
struct draw_point_helper<Destination,false> {
static gfx_result do_draw(Destination& destination,point16 location,typename Destination::pixel_type color,bool async) {
return destination.point(location,color);
}
};
template<typename Destination>
static gfx_result point_impl(Destination& destination, spoint16 location,typename Destination::pixel_type color,srect16* clip,bool async) {
if(clip!=nullptr && !clip->intersects(location))
return gfx_result::success;
if(!((srect16)destination.bounds()).intersects(location))
return gfx_result::success;
point16 p;
if(translate(location,&p)) {
if(async)
return draw_point_helper<Destination,Destination::caps::async>::do_draw(destination,p,color,async);
return draw_point_helper<Destination,false>::do_draw(destination,p,color,async);
}
return gfx_result::success;
}
template<typename Destination,bool Async>
struct draw_filled_rect_helper {
};
template<typename Destination>
struct draw_filled_rect_helper<Destination,true> {
static gfx_result do_draw(Destination& destination,const rect16& rect,typename Destination::pixel_type color,bool async) {
if(!async) return draw_filled_rect_helper<Destination,false>::do_draw(destination,rect,color,false);
return destination.fill_async(rect,color);
}
};
template<typename Destination>
struct draw_filled_rect_helper<Destination,false> {
static gfx_result do_draw(Destination& destination,const rect16& rect,typename Destination::pixel_type color,bool async) {
return destination.fill(rect,color);
}
};
template<typename Destination,bool Async>
struct async_wait_helper {
inline static gfx_result wait_all(Destination& destination) {return gfx_result::success;}
};
template<typename Destination>
struct async_wait_helper<Destination,true> {
inline static gfx_result wait_all(Destination& destination) {return destination.wait_all_async();}
};
template<typename Destination>
static gfx_result filled_rectangle_impl(Destination& destination, const srect16& rect,typename Destination::pixel_type color,srect16* clip,bool async) {
srect16 sr=rect;
if(nullptr!=clip)
sr=sr.crop(*clip);
rect16 r;
if(!translate_adjust(sr,&r))
return gfx_result::success;
r=r.crop(destination.bounds());
if(async)
return draw_filled_rect_helper<Destination,Destination::caps::async>::do_draw(destination,r,color,true);
return draw_filled_rect_helper<Destination,false>::do_draw(destination,r,color,false);
}
template<typename Destination,bool Batch,bool Async>
struct draw_font_batch_helper {
};
template<typename Destination>
struct draw_font_batch_helper<Destination,true,false> {
static gfx_result do_draw(Destination& destination,const font& font,const font_char& fc,const srect16& chr,typename Destination::pixel_type color,typename Destination::pixel_type backcolor,bool transparent_background,srect16* clip,bool async) {
// transparent_background is ignored for this routine
srect16 sr = srect16(chr);
if(nullptr!=clip)
sr=sr.crop(*clip);
if(!sr.intersects((srect16)destination.bounds()))
return gfx_result::success;
rect16 dr = (rect16)sr.crop((srect16)destination.bounds());
gfx_result r = destination.begin_batch(dr);
if(gfx_result::success!=r)
return r;
// draw the character
size_t wb = (fc.width()+7)/8;
const uint8_t* p = fc.data();
for(size_t j=0;j<font.height();++j) {
bits::int_max m = 1 << (fc.width()-1);
bits::int_max accum=0;
memcpy(&accum,p,wb);
p+=wb;
for(size_t n=0;n<=fc.width();++n) {
if(dr.intersects(point16(n+chr.left(),j+chr.top()))) {
if(accum&m) {
r=destination.write_batch(color);
if(gfx_result::success!=r)
return r;
} else {
r=destination.write_batch(backcolor);
if(gfx_result::success!=r)
return r;
}
}
accum<<=1;
}
}
r=destination.commit_batch();
return r;
}
};
template<typename Destination>
struct draw_font_batch_helper<Destination,false,false> {
static gfx_result do_draw(Destination& destination,const font& font,const font_char& fc,const srect16& chr,typename Destination::pixel_type color,typename Destination::pixel_type backcolor,bool transparent_background,srect16* clip,bool async) {
gfx_result r = gfx_result::success;
// draw the character
size_t wb = (fc.width()+7)/8;
const uint8_t* p = fc.data();
for(size_t j=0;j<font.height();++j) {
bits::int_max m = 1 << (fc.width()-1);
bits::int_max accum=0;
memcpy(&accum,p,wb);
p+=wb;
int run_start_fg = -1;
int run_start_bg = -1;
for(size_t n=0;n<fc.width();++n) {
if(accum&m) {
if(!transparent_background&&-1!=run_start_bg) {
r=line(destination,srect16(run_start_bg+chr.left(),chr.top()+j,n-1+chr.left(),chr.top()+j),backcolor,clip);
run_start_bg=-1;
}
if(-1==run_start_fg)
run_start_fg=n;
} else {
if(-1!=run_start_fg) {
r=line(destination,srect16(run_start_fg+chr.left(),chr.top()+j,n-1+chr.left(),chr.top()+j),color,clip);
run_start_fg=-1;
}
if(!transparent_background) {
if(-1==run_start_bg)
run_start_bg=n;
}
}
accum<<=1;
}
if(-1!=run_start_fg) {
r=line(destination,srect16(run_start_fg+chr.left(),chr.top()+j,fc.width()-1+chr.left(),chr.top()+j),color,clip);
}
if(!transparent_background&&-1!=run_start_bg) {
r=line(destination,srect16(run_start_bg+chr.left(),chr.top()+j,fc.width()-1+chr.left(),chr.top()+j),backcolor,clip);
}
}
return r;
}
};
template<typename Destination>
struct draw_font_batch_helper<Destination,true,true> {
static gfx_result do_draw(Destination& destination,const font& font,const font_char& fc,const srect16& chr,typename Destination::pixel_type color,typename Destination::pixel_type backcolor,bool transparent_background,srect16* clip,bool async) {
// transparent_background is ignored for this routine
srect16 sr = srect16(chr);
if(nullptr!=clip)
sr=sr.crop(*clip);
if(!sr.intersects((srect16)destination.bounds()))
return gfx_result::success;
rect16 dr = (rect16)sr.crop((srect16)destination.bounds());
gfx_result r = (async)?destination.begin_batch_async(dr):destination.begin_batch(dr);
if(gfx_result::success!=r)
return r;
// draw the character
size_t wb = (fc.width()+7)/8;
const uint8_t* p = fc.data();
for(size_t j=0;j<font.height();++j) {
bits::int_max m = 1 << (fc.width()-1);
bits::int_max accum=0;
memcpy(&accum,p,wb);
p+=wb;
for(size_t n=0;n<=fc.width();++n) {
if(dr.intersects(point16(n+chr.left(),j+chr.top()))) {
if(accum&m) {
r=(async)?destination.write_batch_async(color):destination.write_batch(color);
if(gfx_result::success!=r)
return r;
} else {
r=(async)?destination.write_batch_async(backcolor):destination.write_batch(backcolor);
if(gfx_result::success!=r)
return r;
}
}
accum<<=1;
}
}
r=(async)?destination.commit_batch_async():destination.commit_batch();
return r;
}
};
template<typename Destination>
struct draw_font_batch_helper<Destination,false,true> {
static gfx_result do_draw(Destination& destination,const font& font,const font_char& fc,const srect16& chr,typename Destination::pixel_type color,typename Destination::pixel_type backcolor,bool transparent_background,srect16* clip,bool async) {
gfx_result r = gfx_result::success;
// draw the character
size_t wb = (fc.width()+7)/8;
const uint8_t* p = fc.data();
for(size_t j=0;j<font.height();++j) {
bits::int_max m = 1 << (fc.width()-1);
bits::int_max accum=0;
memcpy(&accum,p,wb);
p+=wb;
int run_start_fg = -1;
int run_start_bg = -1;
for(size_t n=0;n<fc.width();++n) {
if(accum&m) {
if(!transparent_background&&-1!=run_start_bg) {
r=(async)?line_async(destination,srect16(run_start_bg+chr.left(),chr.top()+j,n-1+chr.left(),chr.top()+j),backcolor,clip):line(destination,srect16(run_start_bg+chr.left(),chr.top()+j,n-1+chr.left(),chr.top()+j),backcolor,clip);
run_start_bg=-1;
}
if(-1==run_start_fg)
run_start_fg=n;
} else {
if(-1!=run_start_fg) {
r=(async)?line(destination,srect16(run_start_fg+chr.left(),chr.top()+j,n-1+chr.left(),chr.top()+j),color,clip):line(destination,srect16(run_start_fg+chr.left(),chr.top()+j,n-1+chr.left(),chr.top()+j),color,clip);
run_start_fg=-1;
}
if(!transparent_background) {
if(-1==run_start_bg)
run_start_bg=n;
}
}
accum<<=1;
}
if(-1!=run_start_fg) {
r=(async)?line_async(destination,srect16(run_start_fg+chr.left(),chr.top()+j,fc.width()-1+chr.left(),chr.top()+j),color,clip):line(destination,srect16(run_start_fg+chr.left(),chr.top()+j,fc.width()-1+chr.left(),chr.top()+j),color,clip);
}
if(!transparent_background&&-1!=run_start_bg) {
r=(async)?line_async(destination,srect16(run_start_bg+chr.left(),chr.top()+j,fc.width()-1+chr.left(),chr.top()+j),backcolor,clip):line(destination,srect16(run_start_bg+chr.left(),chr.top()+j,fc.width()-1+chr.left(),chr.top()+j),backcolor,clip);
}
}
return r;
}
};
template<typename Destination>
static gfx_result line_impl(Destination& destination, const srect16& rect,typename Destination::pixel_type color,srect16* clip,bool async) {
if(rect.x1==rect.x2||rect.y1==rect.y2) {
return filled_rectangle_impl(destination,rect,color,clip,async);
}
srect16 c = (nullptr!=clip)?*clip:rect;
ssize16 ss;
translate(destination.dimensions(),&ss);
c = c.crop(srect16(spoint16(0,0),ss));
srect16 r = rect;
if(!c.contains(r))
line_clip(&r,&c);
float xinc,yinc,x,y,ox,oy;
float dx,dy,e;
dx=std::abs(r.x2-r.x1);
dy=std::abs(r.y2-r.y1);
if(r.x1<r.x2)
xinc=1;
else
xinc=-1;
if(r.y1<r.y2)
yinc=1;
else
yinc=-1;
x=ox=r.x1;
y=oy=r.y1;
if(dx>=dy)
{
e=(2*dy)-dx;
while(x!=r.x2)
{
if(e<0)
{
e+=(2*dy);
}
else
{
e+=(2*(dy-dx));
oy=y;
y+=yinc;
}
x+=xinc;
if(oy!=y || y==r.y1) {
line_impl(destination,srect16(ox,oy,x,oy),color,nullptr,async);
ox=x;
}
}
}
else
{
e=(2*dx)-dy;
while(y!=r.y2)
{
if(e<0)
{
e+=(2*dx);
}
else
{
e+=(2*(dx-dy));
ox=x;
x+=xinc;
}
y+=yinc;
if(ox!=x || x==r.x1) {
line_impl(destination,srect16(ox,oy,ox,y),color,nullptr,async);
oy=y;
}
}
}
return gfx_result::success;
}
template<typename Destination>
static gfx_result rectangle_impl(Destination& destination, const srect16& rect,typename Destination::pixel_type color,srect16* clip,bool async) {
gfx_result r;
// top or bottom
r=line_async(destination,srect16(rect.x1,rect.y1,rect.x2,rect.y1),color,clip,async);
if(r!=gfx_result::success)
return r;
// left or right
r=line_async(destination,srect16(rect.x1,rect.y1,rect.x1,rect.y2),color,clip,async);
if(r!=gfx_result::success)
return r;
// right or left
r=line_async(destination,srect16(rect.x2,rect.y1,rect.x2,rect.y2),color,clip,async);
if(r!=gfx_result::success)
return r;
// bottom or top
return line_async(destination,srect16(rect.x1,rect.y2,rect.x2,rect.y2),color,clip,async);
}
template<typename Destination>
static gfx_result rounded_rectangle_impl(Destination& destination,const srect16& rect,float ratio, typename Destination::pixel_type color,srect16* clip,bool async) {
// TODO: This can be sped up by copying the ellipse algorithm and modifying it slightly.
gfx_result r;
srect16 sr=rect.normalize();
float fx = .025>ratio?.025:ratio>.5?.5:ratio;
float fy = .025>ratio?.025:ratio>.5?.5:ratio;
int rw = (sr.width()*fx+.5);
int rh = (sr.height()*fy+.5);
// top
r=line_impl(destination,srect16(sr.x1+rw,sr.y1,sr.x2-rw,sr.y1),color,clip,async);
if(gfx_result::success!=r)
return r;
// left
r=line_impl(destination,srect16(sr.x1,sr.y1+rh,sr.x1,sr.y2-rh),color,clip,async);
if(gfx_result::success!=r)
return r;
// right
r=line_impl(destination,srect16(sr.x2,sr.y1+rh,sr.x2,sr.y2-rh),color,clip,async);
if(gfx_result::success!=r)
return r;
// bottom
r=line_impl(destination,srect16(sr.x1+rw,sr.y2,sr.x2-rw,sr.y2),color,clip,async);
if(gfx_result::success!=r)
return r;
r=arc_impl(destination,srect16(sr.top_left(),ssize16(rw+1,rh+1)),color,clip,false,async);
if(gfx_result::success!=r)
return r;
r=arc_impl(destination,srect16(spoint16(sr.x2-rw,sr.y1),ssize16(rw+1,rh+1)).flip_horizontal(),color,clip,false,async);
if(gfx_result::success!=r)
return r;
r=arc_impl(destination,srect16(spoint16(sr.x1,sr.y2-rh),ssize16(rw,rh)).flip_vertical(),color,clip,false,async);
if(gfx_result::success!=r)
return r;
return arc_impl(destination,srect16(spoint16(sr.x2-rw,sr.y2-rh),ssize16(rw+1,rh)).flip_all(),color,clip,false,async);
}
template<typename Destination>
static gfx_result filled_rounded_rectangle_impl(Destination& destination,const srect16& rect,float ratio, typename Destination::pixel_type color,srect16* clip,bool async) {
gfx_result r;
srect16 sr=rect.normalize();
float fx = .025>ratio?.025:ratio>.5?.5:ratio;
float fy = .025>ratio?.025:ratio>.5?.5:ratio;
int rw = (sr.width()*fx+.5);
int rh = (sr.height()*fy+.5);
// top
r=filled_rectangle_impl(destination,srect16(sr.x1+rw,sr.y1,sr.x2-rw,sr.y1+rh-1),color,clip,async);
if(gfx_result::success!=r)
return r;
// middle
r=filled_rectangle_impl(destination,srect16(sr.x1,sr.y1+rh,sr.x2,sr.y2-rh-1),color,clip,async);
if(gfx_result::success!=r)
return r;
// bottom
r=filled_rectangle_impl(destination,srect16(sr.x1+rw,sr.y2-rh,sr.x2-rw,sr.y2),color,clip,async);
if(gfx_result::success!=r)
return r;
r=arc_impl(destination,srect16(sr.top_left(),ssize16(rw+1,rh+1)),color,clip,true,async);
if(gfx_result::success!=r)
return r;
r=arc_impl(destination,srect16(spoint16(sr.x2-rw,sr.y1),ssize16(rw+1,rh+1)).flip_horizontal(),color,clip,true,async);
if(gfx_result::success!=r)
return r;
r=arc_impl(destination,srect16(spoint16(sr.x1,sr.y2-rh),ssize16(rw,rh)).flip_vertical(),color,clip,true,async);
if(gfx_result::success!=r)
return r;
return arc_impl(destination,srect16(spoint16(sr.x2-rw,sr.y2-rh),ssize16(rw+1,rh)).flip_all(),color,clip,true,async);
}
// draws text to the specified destination rectangle with the specified font and colors and optional clipping rectangle
template<typename Destination>
static gfx_result text_impl(
Destination& destination,
const srect16& dest_rect,
const char* text,
const font& font,
typename Destination::pixel_type color,
typename Destination::pixel_type backcolor,
bool transparent_background,
unsigned int tab_width,
srect16* clip,
bool async) {
gfx_result r=gfx_result::success;
if(nullptr==text)
return gfx_result::invalid_argument;
const char*sz=text;
int cw;
uint16_t rw;
srect16 chr(dest_rect.top_left(),ssize16(font.width(*sz),font.height()));
if(0==*sz) return gfx_result::success;
font_char fc = font[*sz];
while(*sz) {
switch(*sz) {
case '\r':
chr.x1=dest_rect.x1;
++sz;
if(*sz) {
font_char nfc = font[*sz];
chr.x2=chr.x1+nfc.width()-1;
fc=nfc;
}
break;
case '\n':
chr.x1=dest_rect.x1;
++sz;
if(*sz) {
font_char nfc = font[*sz];
chr.x2=chr.x1+nfc.width()-1;
fc=nfc;
}
chr=chr.offset(0,font.height());
if(chr.y2>dest_rect.bottom())
return gfx_result::success;
break;
case '\t':
++sz;
if(*sz) {
font_char nfc = font[*sz];
rw=chr.x1+nfc.width()-1;
fc=nfc;
} else
rw=chr.width();
cw = font.average_width()*4;
chr.x1=((chr.x1/cw)+1)*cw;
chr.x2=chr.x1+rw-1;
if(chr.right()>dest_rect.right()) {
chr.x1=dest_rect.x1;
chr=chr.offset(0,font.height());
}
if(chr.y2>dest_rect.bottom())
return gfx_result::success;
break;
default:
if(nullptr==clip || clip->intersects(chr)) {
if(chr.intersects(dest_rect)) {
if(transparent_background)
r=draw_font_batch_helper<Destination,false,Destination::caps::async>::do_draw(destination,font,fc,chr,color,backcolor,transparent_background,clip,async);
else
r=draw_font_batch_helper<Destination,Destination::caps::batch_write,Destination::caps::async>::do_draw(destination,font,fc,chr,color,backcolor,transparent_background,clip,async);
if(gfx_result::success!=r)
return r;
chr=chr.offset(fc.width(),0);
++sz;
if(*sz) {
font_char nfc = font[*sz];
chr.x2=chr.x1+nfc.width()-1;
if(chr.right()>dest_rect.right()) {
chr.x1=dest_rect.x1;
chr=chr.offset(0,font.height());
}
if(chr.y2>dest_rect.bottom())
return gfx_result::success;
fc=nfc;
}
}
}
break;
}
}
return gfx_result::success;
}
public:
// draws a point at the specified location and of the specified color, with an optional clipping rectangle
template<typename Destination>
inline static gfx_result point(Destination& destination, spoint16 location,typename Destination::pixel_type color,srect16* clip=nullptr) {
return point_impl(destination,location,color,clip,false);
}
// asynchronously draws a point at the specified location and of the specified color, with an optional clipping rectangle
template<typename Destination>
inline static gfx_result point_async(Destination& destination, spoint16 location,typename Destination::pixel_type color,srect16* clip=nullptr) {
return point_impl(destination,location,color,clip,true);
}
// draws a filled rectangle with the specified dimensions and of the specified color, with an optional clipping rectangle
template<typename Destination>
inline static gfx_result filled_rectangle(Destination& destination, const srect16& rect,typename Destination::pixel_type color,srect16* clip=nullptr) {
return filled_rectangle_impl(destination,rect,color,clip,false);
}
// asynchronously draws a filled rectangle with the specified dimensions and of the specified color, with an optional clipping rectangle
template<typename Destination>
inline static gfx_result filled_rectangle_async(Destination& destination, const srect16& rect,typename Destination::pixel_type color,srect16* clip=nullptr) {
return filled_rectangle_impl(destination,rect,color,clip,true);
}
// draws a rectangle with the specified dimensions and of the specified color, with an optional clipping rectangle
template<typename Destination>
inline static gfx_result rectangle(Destination& destination, const srect16& rect,typename Destination::pixel_type color,srect16* clip=nullptr) {
return rectangle_impl(destination,rect,color,clip,false);
}
// asynchronously draws a rectangle with the specified dimensions and of the specified color, with an optional clipping rectangle
template<typename Destination>
inline static gfx_result rectangle_async(Destination& destination, const srect16& rect,typename Destination::pixel_type color,srect16* clip=nullptr) {
return rectangle_impl(destination,rect,color,clip,true);
}
// draws a line with the specified start and end point and of the specified color, with an optional clipping rectangle
template<typename Destination>
inline static gfx_result line(Destination& destination, const srect16& rect,typename Destination::pixel_type color,srect16* clip=nullptr) {
return line_impl(destination,rect,color,clip,false);
}
// asynchronously draws a line with the specified start and end point and of the specified color, with an optional clipping rectangle
template<typename Destination>
inline static gfx_result line_async(Destination& destination, const srect16& rect,typename Destination::pixel_type color,srect16* clip=nullptr) {
return line_impl(destination,rect,color,clip,true);
}
// draws an ellipse with the specified dimensions and of the specified color, with an optional clipping rectangle
template<typename Destination>
inline static gfx_result ellipse(Destination& destination,const srect16& rect,typename Destination::pixel_type color,srect16* clip=nullptr) {
return ellipse_impl(destination,rect,color,clip,false,false);
}
// asynchronously draws an ellipse with the specified dimensions and of the specified color, with an optional clipping rectangle
template<typename Destination>
inline static gfx_result ellipse_async(Destination& destination,const srect16& rect,typename Destination::pixel_type color,srect16* clip=nullptr) {
return ellipse_impl(destination,rect,color,clip,false,true);
}
// draws a filled ellipse with the specified dimensions and of the specified color, with an optional clipping rectangle
template<typename Destination>
inline static gfx_result filled_ellipse(Destination& destination,const srect16& rect,typename Destination::pixel_type color,srect16* clip=nullptr) {
return ellipse_impl(destination,rect,color,clip,true,false);
}
// asynchronously draws a filled ellipse with the specified dimensions and of the specified color, with an optional clipping rectangle
template<typename Destination>
inline static gfx_result filled_ellipse_async(Destination& destination,const srect16& rect,typename Destination::pixel_type color,srect16* clip=nullptr) {
return ellipse_impl(destination,rect,color,clip,true,true);
}
// draws an arc with the specified dimensions and of the specified color, with an optional clipping rectangle
template<typename Destination>
inline static gfx_result arc(Destination& destination,const srect16& rect,typename Destination::pixel_type color,srect16* clip=nullptr) {
return arc_impl(destination,rect,color,clip,false,false);
}
// asynchronously draws an arc with the specified dimensions and of the specified color, with an optional clipping rectangle
template<typename Destination>
inline static gfx_result arc_async(Destination& destination,const srect16& rect,typename Destination::pixel_type color,srect16* clip=nullptr) {
return arc_impl(destination,rect,color,clip,false,true);
}
// draws a arc with the specified dimensions and of the specified color, with an optional clipping rectangle
template<typename Destination>
inline static gfx_result filled_arc(Destination& destination,const srect16& rect,typename Destination::pixel_type color,srect16* clip=nullptr) {
return arc_impl(destination,rect,color,clip,true,false);
}
// draws a arc with the specified dimensions and of the specified color, with an optional clipping rectangle
template<typename Destination>
inline static gfx_result filled_arc_async(Destination& destination,const srect16& rect,typename Destination::pixel_type color,srect16* clip=nullptr) {
return arc_impl(destination,rect,color,clip,true,true);
}
// draws a rounded rectangle with the specified dimensions and of the specified color, with an optional clipping rectangle
template<typename Destination>
inline static gfx_result rounded_rectangle(Destination& destination,const srect16& rect,float ratio, typename Destination::pixel_type color,srect16* clip=nullptr) {
return rounded_rectangle_impl(destination,rect,ratio,color,clip,false);
}
// asynchronously draws a rounded rectangle with the specified dimensions and of the specified color, with an optional clipping rectangle
template<typename Destination>
inline static gfx_result rounded_rectangle_async(Destination& destination,const srect16& rect,float ratio, typename Destination::pixel_type color,srect16* clip=nullptr) {
return rounded_rectangle_impl(destination,rect,ratio,color,clip,true);
}
// draws a filled rounded rectangle with the specified dimensions and of the specified color, with an optional clipping rectangle
template<typename Destination>
inline static gfx_result filled_rounded_rectangle(Destination& destination,const srect16& rect,const float ratio, typename Destination::pixel_type color,srect16* clip=nullptr) {
return filled_rounded_rectangle_impl(destination,rect,ratio,color,clip,false);
}
// asynchronously draws a filled rounded rectangle with the specified dimensions and of the specified color, with an optional clipping rectangle
template<typename Destination>
inline static gfx_result filled_rounded_rectangle_async(Destination& destination,const srect16& rect,const float ratio, typename Destination::pixel_type color,srect16* clip=nullptr) {
return filled_rounded_rectangle_impl(destination,rect,ratio,color,clip,true);
}
// draws a portion of a bitmap or display buffer to the specified rectangle with an optional clipping rentangle
template<typename Destination,typename Source>
static inline gfx_result bitmap(Destination& destination,const srect16& dest_rect,Source& source,const rect16& source_rect,bitmap_flags options=bitmap_flags::crop,srect16* clip=nullptr) {
return bmp_helper<Destination,Source,typename Destination::pixel_type,typename Source::pixel_type>
::draw_bitmap(destination,dest_rect,source,source_rect,options,clip,false);
}
// asynchronously draws a portion of a bitmap or display buffer to the specified rectangle with an optional clipping rentangle
template<typename Destination,typename Source>
static inline gfx_result bitmap_async(Destination& destination,const srect16& dest_rect,Source& source,const rect16& source_rect,bitmap_flags options=bitmap_flags::crop,srect16* clip=nullptr) {
return bmp_helper<Destination,Source,typename Destination::pixel_type,typename Source::pixel_type>
::draw_bitmap(destination,dest_rect,source,source_rect,options,clip,true);
}
// draws text to the specified destination rectangle with the specified font and colors and optional clipping rectangle
template<typename Destination>
inline static gfx_result text(
Destination& destination,
const srect16& dest_rect,
const char* text,
const font& font,
typename Destination::pixel_type color,
typename Destination::pixel_type backcolor=::gfx::rgb_pixel<3>(0,0,0).convert<typename Destination::pixel_type>(),
bool transparent_background = true,
unsigned int tab_width=4,
srect16* clip=nullptr) {
return text_impl(destination,dest_rect,text,font,color,backcolor,transparent_background,tab_width,clip,false);
}
// asynchronously draws text to the specified destination rectangle with the specified font and colors and optional clipping rectangle
template<typename Destination>
inline static gfx_result text_async(
Destination& destination,
const srect16& dest_rect,
const char* text,
const font& font,
typename Destination::pixel_type color,
typename Destination::pixel_type backcolor=::gfx::rgb_pixel<3>(0,0,0).convert<typename Destination::pixel_type>(),
bool transparent_background = true,
unsigned int tab_width=4,
srect16* clip=nullptr) {
return text_impl(destination,dest_rect,text,font,color,backcolor,transparent_background,tab_width,clip,true);
}
// waits for all asynchronous operations on the destination to complete
template<typename Destination>
static gfx_result wait_all_async(Destination& destination) {
return async_wait_helper<Destination,Destination::caps::async>::wait_all(destination);
}
};
}
#endif | true |
4d4a8ec15b22c46aff9a35366cfcd049e6f47062 | C++ | Frederico-lp/Prog | /Proj1/game.hpp | UTF-8 | 1,133 | 2.609375 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
struct Robot {
int x;
int y;
int id;
};
struct Element {
int x;
int y;
};
void robot_collision(vector<Robot> &robots, vector<bool> &status, vector<Element> &fences);
void robot_movement(Element &player, vector<Robot> &robots, vector<bool> &robotStatus);
bool is_fence_or_post(Element &mapSize, int x, int y, vector< Element > &fences);
int is_robot(int x, int y, vector< Robot> &robots, vector<bool> &robotStatus);
bool is_player(int x, int y, Element player);
bool is_alive(Element &mapSize, vector<Robot> &robots, vector< Element> &fences, Element player);
void input_map(Element &mapSize, Element &player, vector< Robot> &robots, vector< Element> &fences, int mapNumber);
void export_results(int mapNumber, time_t gameTime);
void draw(Element &mapSize, vector< Element> &fences, vector< Robot> &robots, vector< bool> &robotStatus, Element player);
void moveTurn(vector< Robot> &robots, vector<bool> &robotStatus, Element &player);
int play_game(int mapNumber);
| true |
024cfaec9604c6dd7bd2b6dd93f3d2c9888b9bc1 | C++ | justinmoor/FTP-Server | /client.cpp | UTF-8 | 5,896 | 2.515625 | 3 | [] | no_license | #include "client.h"
Client::Client(QObject *parent) : QObject(parent)
{
QThreadPool::globalInstance()->setMaxThreadCount(5);
}
void Client::setSocket(qintptr descriptor){
this->descriptor = descriptor;
socket = new QTcpSocket();
connect(socket, SIGNAL(connected()), this, SLOT(connected()));
connect(socket, SIGNAL(disconnected()), this, SLOT(disconnected()));
connect(socket, SIGNAL(readyRead()), this, SLOT(readyRead()));
connect(socket, SIGNAL(disconnected()), socket, SLOT(deleteLater()));
socket->setSocketDescriptor(descriptor);
currentDir = settings.value("rootPath").toString();
emit message( "Client connected at " + QString::number(descriptor));
sendResponse(settings.value("welcomeMessage").toString().toLocal8Bit());
socket->flush();
}
void Client::readyRead(){
QString c = socket->readLine();
if (c.startsWith("LOGIN")){
doLogin(c);
} else if(c.startsWith("LIST")){
emit clientMessage(this->username, c);
doList(c);
} else if(c.startsWith("PUT")){
emit clientMessage(this->username, c);
doPut(c);
} else if(c.startsWith("MKD")){
emit clientMessage(this->username, c);
doMkDir(c);
} else if(c.startsWith("GET")){
emit clientMessage(this->username, c);
doGet(c);
}
// Task *task = new Task();
// task->setCommand(c);
// QThreadPool::globalInstance()->start(task);
}
void Client::doPut(QString &fileName){
fileName = currentDir + "/" + fileName.trimmed().split('"').at(1);
qDebug() << "Do put" << fileName;
fileSocket.receiveFile(fileName);
}
void Client::doGet(QString &fileName){
fileName = currentDir + "/" + fileName.split('"').at(1);
fileSocket.sendFile(fileName);
sendResponse("250 File sent");
}
//TODO HIER FIXEN
void Client::doLogin(QString &creds){
QMap<QString, QString> users = getUsers();
creds = creds.trimmed();
QString name = creds.split(' ').at(1);
QString password = creds.split(' ').at(2);
name = name.trimmed();
password = password.trimmed();
qDebug() << creds;
qDebug() << name << " " << password;
qDebug() << users;
QSettings settings;
if(!settings.value("allowAnonUsers").toBool()){
if(!users.contains(name)){
sendResponse("430 Invalid username or password");
socket->disconnectFromHost();
return;
} else if(users[name] != password){
sendResponse("430 Invalid username or password");
qDebug() << "hier";
socket->disconnectFromHost();
return;
} else {
login(name);
}
} else {
login(name);
}
}
void Client::login(QString& username){
openFileSocket();
sendResponse(("230 Login OK! " + QString::number(filePort)).toLocal8Bit());
this->username = username;
emit clientMessage(this->username, "LOGGED IN");
emit info(QString::number(descriptor), socket->peerAddress().toString(), this->username);
authorized = true;
}
QMap<QString, QString> Client::getUsers(){
QFile file("users.us");
QMap <QString, QString> users;
if(file.exists()){
if(!file.open(QIODevice::ReadOnly)){
qDebug() << "Error";
} else {
QDataStream in(&file);
users.clear();
in.setVersion(QDataStream::Qt_5_9);
in >> users;
}
}
file.flush();
file.close();
return users;
}
void Client::doMkDir(QString &dirName){
QDir dir(currentDir);
dirName = dirName.split('"').at(1);
if(!dir.mkdir(dirName)){
sendResponse("Couldn't create directory...");
}else {
sendResponse("257 Directory created!");
}
}
void Client::doList(QString & path){
sendResponse("Listing directory");
QDir dir(currentDir);
qDebug() << "Command: " << path;
QString dirPath = (path.trimmed().split(" ").at(1) != "/") ? currentDir+"/"+path.trimmed().split('"').at(1) : settings.value("rootPath").toString();
if(!dir.cd(dirPath)){
sendResponse("Directory does not exist...");
return;
}
currentDir = dir.absolutePath();
QFileInfo info(currentDir);
if(info.isDir()){
QFileInfoList entryList = dir.entryInfoList();
QStringList outlines;
foreach(QFileInfo entry, entryList){
if(entry.isHidden()) qDebug() << "Hidden";
outlines.append(generateList(entry));
}
fileSocket.sendList(outlines.join(QString()).toLocal8Bit());
} else {
qDebug() << "1file";
fileSocket.sendList(generateList(info).toLocal8Bit());
}
}
void Client::sendResponse(const QByteArray &bytes){
socket->write(bytes +"\r\n");
}
QString Client::generateList(const QFileInfo &entry) const {
QString line;
line += QLocale(QLocale::English).toString(entry.lastModified(), QLatin1String("MM-dd-yy hh:mmAP"));
if (entry.isDir()){
line += QLatin1String(" <DIR> ");
} else {
line += QString("%1").arg(entry.size(), 20);
// qDebug() << entry.fileName() << " " << QString::number(entry.size());
}
line += QLatin1Char(' ');
line += entry.fileName();
line += QLatin1String("\r\n");
qDebug () << line;
return line;
}
void Client::connected(){
emit message("Client " + QString::number(socket->socketDescriptor()) + " connected");
}
void Client::disconnected(){
emit message("Client " + QString::number(this->descriptor) +" disconnected");
emit removeFromTable(this->descriptor);
delete this;
}
void Client::kickAll(){
socket->disconnectFromHost();
}
void Client::kickClient(int descriptor){
if(this->descriptor == descriptor){
socket->disconnectFromHost();
}
}
void Client::openFileSocket(){
fileSocket.listenFor();
filePort = fileSocket.serverPort();
}
| true |
1a2b815a7d6ebe6b69a79c594d2ac300f43937de | C++ | aredev/simulation-2 | /ParticleToy/particles/Particle.cpp | UTF-8 | 1,305 | 2.890625 | 3 | [] | no_license | #include "Particle.h"
#include <GL/glut.h>
Particle::Particle(const Vec2f &ConstructPos, float m) :
m_ConstructPos(ConstructPos), m_Position(ConstructPos), m_Velocity(Vec2f(0.0, 0.0)) {
m_Mass = m;
m_Colour = 1.0f;
}
void Particle::reset() {
m_Position = m_ConstructPos;
m_Force = Vec2f(0.0, 0.0);
m_Velocity = Vec2f(0.0, 0.0);
}
void Particle::setColour(float c) {
m_Colour = c;
}
void Particle::draw() {
const float h = 0.01;
glColor3f(1.f, 1.f, 1.f);
glBegin(GL_QUADS);
glVertex2f(m_Position[0] - h / 2.0f, m_Position[1] - h / 2.0f);
glVertex2f(m_Position[0] + h / 2.0f, m_Position[1] - h / 2.0f);
glVertex2f(m_Position[0] + h / 2.0f, m_Position[1] + h / 2.0f);
glVertex2f(m_Position[0] - h / 2.0f, m_Position[1] + h / 2.0f);
glEnd();
}
void Particle::drawForce() {
glColor3f(0.000, 0.000, 1.000);
glBegin(GL_LINES);
glVertex2f(m_Position[0], m_Position[1]);
glVertex2f(m_Position[0] + m_Force[0] * 10, m_Position[1] + m_Force[1] * 10);
glEnd();
}
void Particle::drawVelocity() {
glColor3f(0.000, 1.000, 0.000);
glBegin(GL_LINES);
glVertex2f(m_Position[0], m_Position[1]);
glVertex2f(m_Position[0] + m_Velocity[0], m_Position[1] + m_Velocity[1]);
glEnd();
}
Particle::~Particle() = default;
| true |
c2cba48c3b862f8825be988cdbc9a70615208713 | C++ | jakexks/Streamberry | /networking.cpp | UTF-8 | 2,916 | 2.53125 | 3 | [] | no_license | #include "networking.h"
#include <QCryptographicHash>
#include <QStringList>
#include <QUdpSocket>
#include <iostream>
// Constructor, needs no arguments
networking::networking()
{
}
// Returns a string containing the unique ID of the current machine
QString networking::getuniqid()
{
QList<QNetworkInterface> interfaces = QNetworkInterface::allInterfaces();
QString s = "";
for (int i = 0; i < interfaces.length(); i++)
{
s.append(interfaces[i].hardwareAddress());
//break;
}
QCryptographicHash hash(QCryptographicHash::Sha1);
hash.addData(s.toUtf8());
return hash.result().toHex();
}
// Returns a string containing the ip address of the current machine
QString networking::getmyip()
{
QList<QNetworkInterface> interfaces = QNetworkInterface::allInterfaces();
QString s = "";
for (int i = 0; i < interfaces.length(); i++)
{
for (int j = 0; j < interfaces[i].allAddresses().length(); j++)
{
QString ip = interfaces[i].allAddresses()[j].toString();
if (!ip.startsWith("fe80:", Qt::CaseInsensitive) && !ip.startsWith("127.") && !ip.startsWith("0:"))
{
return ip;
}
}
}
return NULL;
}
// Generic receive function. Waits until there is something to receive from the network, then returns a byte array containing all the data received
QByteArray networking::receive(int port)
{
QTcpServer tcpServer;
if(!tcpServer.listen(QHostAddress::Any,port))
{
qDebug() << "Could not Listen";
}
QByteArray buf;
if(!tcpServer.waitForNewConnection(3000))
{
qDebug() << "Could not receive";
}
while(tcpServer.hasPendingConnections())
{
QTcpSocket* tcpServerConnection = tcpServer.nextPendingConnection();
buf.resize(buf.size() + tcpServerConnection->bytesAvailable());
buf.append(tcpServerConnection->readAll());
tcpServerConnection->close();
delete tcpServerConnection;
}
tcpServer.close();
return buf;
}
// Generic send function
void networking::send(QHostAddress host, quint16 port, QByteArray data)
{
const int timeout = 5000;
QTcpSocket tcpClient;
tcpClient.connectToHost(host, port);
if(tcpClient.waitForConnected(timeout))
{
tcpClient.write(data);
tcpClient.close();
}
else
{
std::cerr << tcpClient.errorString().toStdString() << std::endl;
}
}
void networking::udpSend(QHostAddress ip, quint16 port, QByteArray data)
{
QUdpSocket udpsocket;
udpsocket.bind(QHostAddress::Broadcast, 45454, QUdpSocket::ShareAddress);
udpsocket.writeDatagram(data.data(), data.size(), ip, port);
}
// Unique ID parser
QString networking::parsebeacon(QString bc, int field)
{
QStringList split = bc.split('|', QString::KeepEmptyParts, Qt::CaseInsensitive);
return split.takeAt(field);
}
| true |
0e9c377ebdba7d2ab859651430154f5221135be0 | C++ | wlz971750/wanglingzhi | /projectWlz/projectWlz/projectWlz/GameMenu.cpp | GB18030 | 1,835 | 2.65625 | 3 | [] | no_license | #include "stdafx.h"
#include "GameMenu.h"
CGameMenu::CGameMenu()
{
m_iMenuState = MENU_START;
}
CGameMenu::~CGameMenu()
{
}
void CGameMenu::upDate()
{
if (KEYDOWN(VK_UP))
{
m_iMenuState--;
if (m_iMenuState < MENU_START)
m_iMenuState = MENU_EXIT;
}
else if (KEYDOWN(VK_DOWN))
{
m_iMenuState++;
if (m_iMenuState > MENU_EXIT)
m_iMenuState = MENU_START;
}
else if (KEYDOWN(VK_RETURN))
{
if (m_iMenuState == MENU_EXIT)
g_iGameState = GAME_EXIT;
else
g_iGameState = GAME_START;
}
}
void CGameMenu::onRender()
{
cout << "" << endl;
cout << " " << endl;
cout << " ʧ " << endl;
cout << " " << endl;
cout << " " << endl;
cout << " " << endl;
if (m_iMenuState == MENU_START)
{
cout << " -> ʼϷ " << endl;
cout << " " << endl;
cout << " ˳Ϸ " << endl;
}
else
{
cout << " ʼϷ " << endl;
cout << " " << endl;
cout << " -> ˳Ϸ " << endl;
}
cout << " " << endl;
cout << " " << endl;
cout << " " << endl;
cout << " ɽ˹ " << endl;
cout << " " << endl;
cout << "" << endl;
}
| true |
5f99c662bd75d7fcf511eda8877e7d81e9bb3a4c | C++ | johnw188/me405 | /tests/triangulate_test.cc | UTF-8 | 3,752 | 3.390625 | 3 | [] | no_license | //======================================================================================
/** \file triangulate_test.cc
* This file contains a test program which checks that the A/D converter on the
* AVR processor is working correctly.
*
* Revisions:
* \li 4-14-08 JB, BC added keyboard interface to print a reading whenever
* spacebar is pressed.
* \li 4-16-08 BMC added ability to print only one port at a time
*
* License:
* This file released under the Lesser GNU Public License. The program is intended
* for educational use only, but its use is not restricted thereto.
*/
//======================================================================================
// System headers included with < >
#include <stdlib.h> // Standard C library
// User written headers included with " "
#include "rs232.h" // Include header for serial port class
//#include "avr_adc.h" // Include header for the A/D class
//#include "motor_drv.h" // Include header for the motor class
#include "triangle.h" // trianglulation class
/** This is the baud rate divisor for the serial port. It should give 9600 baud for the
* CPU crystal speed in use, for example 26 works for a 4MHz crystal on an ATmega8
*/
#define BAUD_DIV 52 // For testing an ATmega128
//--------------------------------------------------------------------------------------
/** The main function is the "entry point" of every C program, the one which runs first
* (after standard setup code has finished). For mechatronics programs, main() runs an
* infinite loop and never exits.
*/
char input_char;
int main ()
{
int obj_x = 2;
int obj_y = 2;
signed int obj_ang = 45;
signed int obj_dis = 3;
// Create an RS232 serial port object. Diagnostic information can be printed out
// using this port
rs232 the_serial_port (BAUD_DIV, 1);
// Create an ADC (Analog to Digital Converter) object. This object must be given a
// pointer to the serial port object so that it can print debugging information
// avr_adc my_adc (&the_serial_port);
// motor_drv my_motor (&the_serial_port);
triangle my_triangle (&the_serial_port);
// Say hello
the_serial_port << "triangulation test program" << endl;
the_serial_port << "press spacebar for reading" << endl;
my_triangle.set_position(4,1,0);
// Run the main scheduling loop, in which the action to run is done repeatedly.
// In the future, we'll run tasks here; for now, just do things in a simple loop
while (true)
{
// The dummy counter is used to slow down the rate at which stuff is printed
// on the terminal
if (the_serial_port.check_for_char ())
{
input_char = the_serial_port.getchar ();
if (input_char == ' ')
{
// read ports 0-3 and print
the_serial_port << "camera angle is: " << (my_triangle.global_to_angle(obj_x,obj_y)) << endl << endl;
the_serial_port << "From angle 45 and distance 3: x_global: " << (my_triangle.angle_to_global(1,obj_ang,obj_dis)) <<
" y_global: " << (my_triangle.angle_to_global(0,obj_ang,obj_dis)) << endl << endl;
}
else //if any other key is pressed, print error and do nothing
{
the_serial_port << "invalid key\r";
}
}
}
return (0);
}
| true |
ae04d0dfecbd7d7663f1bdb96b6dee3969b7e72c | C++ | docofab/mechanumWheelRobot | /Arduino/OtaFabMechanum/src/functionsApi/watchSurrounding.cpp | UTF-8 | 2,735 | 2.859375 | 3 | [
"Apache-2.0"
] | permissive | /**
* @file watchSurrounding.cpp
* @brief
*
* @date 2020/12/24 まずcでファイル分割をかく
*/
#include <Arduino.h>
#include "./../lib/debugPrint.h"
#include "./../lib/pinAssignment.h"
#include "./../hardWareDriver/ultraSonicSensor.h"
#include "./../hardWareDriver/servoDriver.h"
#include "functionsApi.h"
const int distancelimit = 30; //distance limit for obstacles in front
const int sidedistancelimit = 30; //minimum distance in cm to obstacles at both sides (the car will allow a shorter distance sideways)
int leftscanval, centerscanval, rightscanval, ldiagonalscanval, rdiagonalscanval;
//Meassures distances to the right, left, front, left diagonal, right diagonal and asign them in cm to the variables rightscanval,
//leftscanval, centerscanval, ldiagonalscanval and rdiagonalscanval (there are 5 points for distance testing)
String watchSurrounding(){
/* obstacle_status is a binary integer, its last 5 digits stands for if there is any obstacles in 5 directions,
* for example B101000 last 5 digits is 01000, which stands for Left front has obstacle, B100111 means front, right front and right ha
*/
int obstacle_status =B100000;
centerscanval = ultraSonicSensorWatch();
if(centerscanval<distancelimit){
moveStop();
obstacle_status =obstacle_status | B100;
}
servoWrite(120);
delay(100);
ldiagonalscanval = ultraSonicSensorWatch();
if(ldiagonalscanval<distancelimit){
moveStop();
obstacle_status =obstacle_status | B1000;
}
servoWrite(170); //Didn't use 180 degrees because my servo is not able to take this angle
delay(300);
leftscanval = ultraSonicSensorWatch();
if(leftscanval<sidedistancelimit){
moveStop();
obstacle_status =obstacle_status | B10000;
}
servoWrite(90); //use 90 degrees if you are moving your servo through the whole 180 degrees
delay(100);
centerscanval = ultraSonicSensorWatch();
if(centerscanval<distancelimit){
moveStop();
obstacle_status =obstacle_status | B100;
}
servoWrite(40);
delay(100);
rdiagonalscanval = ultraSonicSensorWatch();
if(rdiagonalscanval<distancelimit){
moveStop();
obstacle_status =obstacle_status | B10;
}
servoWrite(0);
delay(100);
rightscanval = ultraSonicSensorWatch();
if(rightscanval<sidedistancelimit){
moveStop();
obstacle_status =obstacle_status | 1;
}
servoWrite(90); //Finish looking around (look forward again)
delay(300);
String obstacle_str= String(obstacle_status,BIN);
obstacle_str= obstacle_str.substring(1,6);
return obstacle_str; //return 5-character string standing for 5 direction obstacle status
}
int watchDistance(){
ultraSonicSensorWatch();
} | true |
37e6bc546d87c60d54a65567b1853bf7c7a89c6f | C++ | brainmelts/h-da_PAD1_Praktikum1 | /Aufgabe3/main.cpp | UTF-8 | 2,380 | 4.375 | 4 | [
"MIT"
] | permissive | // Summe, Mittelwert, Produkt, kleinster und größter Wert von 3 Integern ausgeben
// Autor: Suayb Yurdakul
// Datum: 2018-10-15
#include <iostream>
using namespace std;
int main()
{
int num1, num2, num3, small, big;
cout << "Bitte drei unterschiedliche ganze Zahlen eingeben: "; // user prompt
cin >> num1 >> num2 >> num3;
// nested if-statements cause apparently we're not allowed to use ternary operators lol
// SMALL
if (num1 < num2) { // num1 < num2 = true
if (num1 < num3) { // num1 < num3 = true
small = num1; // num1 is small
}
else { // num1 < num2 = true
small = num3; // num1 < num3 = false
} // num3 is small
}
else { // num1 < num2 = false
if (num2 < num3) { // num2 < num3 = true
small = num2; // num2 is small
}
else { // num1 < num2 = false
small = num3; // num2 < num3 = false
} // num3 is small
}
// BIG
if (num1 > num2) { // num1 > num2 = true
if (num1 > num3) { // num1 > num3 = true
big = num1; // num1 is big
}
else { // num1 > num2 = true
big = num3; // num1 > num3 = false
} // num3 is big
}
else { // num1 > num2 = false
if (num2 > num3) { // num2 > num3 = true
big = num2; // num2 is big
}
else { // num1 > num2 = false
big = num3; // num2 > num3 = false
} // num3 is big
}
// output
cout << "Die Summe ist \t\t" << (num1 + num2 + num3) << endl;
cout << "Der Mittelwert ist \t" << ((num1 + num2 + num3) / 3) << endl;
cout << "Das Produkt ist \t" << (num1 * num2 * num3) << endl;
cout << "Der kleinste Wert ist \t" << small << endl;
cout << "Der groesste Wert ist \t" << big << endl;
// cout << "Der kleinste Wert ist \t" << (num1 < num2 ? (num1 < num3 ? num1 : num3) : (num2 < num3 ? num2 : num3)) << endl; // easy way to avoid nested if-statements - ternary operator
// cout << "Der groesste Wert ist \t" << (num1 > num2 ? (num1 > num3 ? num1 : num3) : (num2 > num3 ? num2 : num3)) << endl; // is num1 < num2 ? (true) : (false)
return 0;
}
| true |
82f926399db54a14655d4b4a1b1bcbf9a723e1e9 | C++ | mrundle/nd_undergrad | /cse20212/lab2/C4Board.cpp | UTF-8 | 7,070 | 3.5625 | 4 | [] | no_license | /*
Matt Rundle
cse20212.01
C4Board.cpp
Implementation file for the C4Board class type; also contains the play() function
that drives the game of Connect Four in the compiled program, either with two
human players or with one human player against a simple human AI.
*/
#include <iostream>
#include <cstdio>
#include "C4Col.h"
#include "C4Board.h"
using namespace std;
/*
Default constructor for class C4Board; creates an array of C4Col objects
*/
C4Board::C4Board(){
numCols=7;
}
/*
Deconstructor for class C4Board; releases the allocated array of C4Col objects
*/
C4Board::~C4Board(){
//delete [] board;
}
/*
Prints/displays the board
*/
ostream &operator<< (ostream & print, const C4Board & B){
print << "Connect Four\n\n";
for(int i=B.board[0].getMaxDiscs()-1;i>=0;i--){
print << "|_";
for(int j=0;j<B.numCols;j++){
if(j<(B.numCols-1)) print << B.board[j].getDisc(i) << "_|_";
if(j==(B.numCols-1)) print << B.board[j].getDisc(i) << "_|";
}
print << "\n";
}
print << " 0 1 2 3 4 5 6\n\n"; // Number the columns for user input reference
return print;
}
/*
Searches the board for winners; helper function for checkWinner(). This function consists of
6 main searches, including one for a horizontal search, one for a vertical search, and four for
the diagonal searching. Multiple functions were used in the diagonal searching because of
convenience and to maintain implementation functionality for boards of differenct sizes.
*/
int C4Board::boardSearch(char c){
int matches;
// VERTICAL SEARCH
for(int i=0;i<numCols;i++){
matches=0;
for(int j=0;j<board[0].getMaxDiscs();j++){
if(board[i].getDisc(j)==c) matches++;
if(board[i].getDisc(j)!=c) matches=0;
if(matches==4) return 1;
}
}
// HORIZONTAL SEARCH
for(int i=0;i<board[0].getMaxDiscs();i++){
matches=0;
for(int j=0;j<numCols;j++){
if(board[j].getDisc(i)==c) matches++;
if(board[j].getDisc(i)!=c) matches=0;
if(matches==4) return 1;
}
}
// DIAGONAL SEARCHES
// Northwest->Southeast
for(int i=3;i<board[0].getMaxDiscs();i++){
matches=0;
for(int j=0;j<(i+1);j++){
if(board[j].getDisc(i-j)==c) matches++;
if(board[j].getDisc(i-j)!=c) matches=0;
if(matches==4) return 1;
}
}
// Southeast->Northwest
for(int i=0;i<3;i++){
matches=0;
for(int j=numCols-1;j>i;j--){
if(board[j].getDisc((numCols-1)-j+i)==c) matches++;
if(board[j].getDisc((numCols-1)-j+i)!=c) matches=0;
if(matches==4) return 1;
}
}
// Southwest->Northeast
for(int i=0;i<3;i++){
matches=0;
for(int j=0;j<(numCols-1)-i;j++){
if(board[j].getDisc(j+i)==c) matches++;
if(board[j].getDisc(j+i)!=c) matches=0;
if(matches==4) return 1;
}
}
// Northeast->Southwest
for(int i=3;i<board[0].getMaxDiscs();i++){
matches=0;
for(int j=(numCols-1);j>=(numCols-1)-i;j--){
if(board[j].getDisc(j-((numCols-1)-i))==c) matches++;
if(board[j].getDisc(j-((numCols-1)-i))!=c) matches=0;
if(matches==4) return 1;
}
}
// If it makes it through these checks, there is no winner
return 0;
}
/*
utilizes the boardSearch() function to check for winners of piece 'O' or 'X'. If winner is found, returns 1.
*/
int C4Board::checkWinner(){
if(boardSearch('O')==1) return 1;
if(boardSearch('X')==1) return 1;
}
/*
Helper function for the computerMove() function, sees if another similar piece is around
-finds the location of the next disc placed
-j is the column, i is the row
-checks 'O' character for matches because that is the computer's piece
-if no adjacency found, return 0
*/
int C4Board::checkAdjacent(int i){
int j=board[i].getNumDiscs();
if(board[j].getDisc(i-1)=='O') return 1; // South adjacency
if(board[j-1].getDisc(i)=='O') return 1; // West adjacency
if(board[j-1].getDisc(i+1)=='O') return 1; // Northwest adjacency
if(board[j-1].getDisc(i-1)=='O') return 1; // Southwest adjacency
if(board[j+1].getDisc(i)=='O') return 1; // East adjacency
if(board[j+1].getDisc(i+1)=='O') return 1; // Northeast adjacency
if(board[j+1].getDisc(i-1)=='O') return 1; // Southeast adjacency
return 0;
}
/*
Picks a column for the computer player to play; helper function of play(int).
-First, loops through columns in ascending order and checks to see if it can find
an empty spot adjacent to one of its own pieces
-If it can't find such position, it again loops through the columns in ascending
order and drops the piece into the first open space
-If no move is possible for the computer, return 0 and end game
*/
int C4Board::computerMove(){
int computerChoice;
for(int computerChoice=0;computerChoice<numCols;computerChoice++){
if(checkAdjacent(computerChoice)==1 && board[computerChoice].isFull()==0){
board[computerChoice].addDisc('O');
return 1;
}
}
for(int computerChoice=0;computerChoice<numCols;computerChoice++){
if(board[computerChoice].isFull()==0){
board[computerChoice].addDisc('O');
return 1;
}
}
return 0;
}
/*
Acquires and validates user move choice; helper function for play(int)
*/
int C4Board::playerMove(int player){
int playerChoice;
while(1){
// ask user where the player wants to go
cout << "Player " << player << ", which column would you like to drop your piece into?\n";
cout << "To end the game, enter '-1'.\n";
cin >> playerChoice;
// end the game if player chooses -1
if(playerChoice==-1){
cout << "Game ended by Player " << player << "." << endl;
return -1;
}
// handle bad input
if(playerChoice<0 || playerChoice>(numCols-1)){
cout << "Error: Column does not exist. Please choose again.\n";
cin >> playerChoice;
if(playerChoice==-1){
cout << "Game ended by Player " << player << "." << endl;
return -1;
}
continue;
}
if(board[playerChoice].isFull()==1){
cout << "Error: Invalid move, column is full. Choose another column.\n";
cin >> playerChoice;
continue;
}
// if valid move, place disc and return
if(board[playerChoice].isFull()==0){
//if(player==1) board[playerChoice].addDisc('X'); // OLD
if(player==1) board[playerChoice]+=('X');
//if(player==2) board[playerChoice].addDisc('O'); // OLD
if(player==2) board[playerChoice]+=('O');
return 1;
}
}
}
/*
Play the game
-If computerPlayer==1, play against AI
*/
void C4Board::play(int computerPlayer){
int gameOver=0;
int turn=1;
int player;
int playerChoice;
while(gameOver==0){
//clear screen between each player's turn
printf("\033[2J\033[H");
// display board
cout << *this;
// Check for winner
if(checkWinner()==1){
cout << "Player " << player << " wins the game!" << endl;
return;
}
// determine player
turn++;
player=(turn%2)+1;
// Ask for input from player - if computer is player 2, skip this.
// Add Disc in user selected column once move is validated
if(player==1 || (player==2 && computerPlayer!=1)){
if(playerMove(player)==-1) return;
}
// if player 2 is the computer player, run AI to choose a move
if(player==2 && computerPlayer==1){
if(computerMove()==0) return;
}
}
}
| true |
7eae5a3bb23e4eba65802f28e6c5155b57372900 | C++ | CaffeineViking/nqsok | /src/nqsok/texture.hh | UTF-8 | 1,450 | 2.609375 | 3 | [
"MIT",
"Libpng",
"BSD-3-Clause",
"Zlib"
] | permissive | #ifndef NQSOK_TEXTURE_HH
#define NQSOK_TEXTURE_HH
#include <vector>
#include <string>
#include <GL/glew.h>
#include "shader.hh"
#include "image.hh"
namespace nq {
class Texture_error final : public std::runtime_error {
public: using std::runtime_error::runtime_error; };
class Texture final {
public:
struct Parameters {
GLenum minifying_filter {GL_NEAREST};
GLenum magnifying_filter {GL_NEAREST};
};
Texture(Image&, const Parameters&);
~Texture() { glDeleteTextures(1, &handle); }
Texture(std::vector<GLfloat>&, GLsizei, GLsizei, const Parameters&);
void active(Shader&, GLenum, const std::string&); // What texture unit and name?
GLsizei get_width() const { return width; } GLsizei get_height() const { return height; }
bool is_current() const;
Texture(Texture&& other) noexcept {
this->width = other.width;
this->height = other.height;
this->handle = other.handle;
other.handle = 0;
}
Texture& operator=(Texture&& other) noexcept {
this->width = other.width;
this->height = other.height;
this->handle = other.handle;
other.handle = 0;
return *this;
}
private:
friend class Model;
static Texture* current;
GLsizei width, height;
GLuint handle;
};
}
#endif
| true |
ef6a0965a19c5ad69255b3caf92e1b71cbfcc4ce | C++ | ths-rwth/smtrat | /src/smtrat-mcsat/explanations/FullParallelExplanation.h | UTF-8 | 5,425 | 2.609375 | 3 | [
"MIT"
] | permissive | #pragma once
#include <thread>
#include <unistd.h>
#include "../utils/Bookkeeping.h"
#include <smtrat-common/smtrat-common.h>
namespace smtrat {
namespace mcsat {
/**
* This explanation executes all given explanation parallel in multiple threads and waits until every single one has finished,
* returning the result of the first listed explanation
*/
// TODO currently trying to be FastParallelExplanation, change behavior to description
template<typename... Backends>
struct FullParallelExplanation {
private:
using B = std::tuple<Backends...>;
B mBackends;
template<std::size_t N = 0, carl::EnableIfBool<N == std::tuple_size<B>::value> = carl::dummy>
std::optional<Explanation> explain(const mcsat::Bookkeeping&, carl::Variable, const FormulasT&,
const std::size_t NUM_THREADS, std::mutex& mtx,
std::vector<std::thread>& threads, std::vector<pthread_t>& nativeHandles,
size_t& counter, std::vector<std::optional<Explanation>>& explanations) const {
SMTRAT_LOG_DEBUG("smtrat.mcsat.explanation", "All explanations started.");
mtx.unlock();
void *res;
int s;
std::optional<Explanation> explanation;
while(true) {
if(counter == NUM_THREADS){ SMTRAT_LOG_ERROR("smtrat.mcsat.explanation", "No explanation left."); }
SMTRAT_LOG_DEBUG("smtrat.mcsat.explanation", "Look for resulting explanation");
for (size_t i = 0; i < NUM_THREADS; i++) {
explanation = explanations[i];
if (explanation != std::nullopt) {
mtx.lock();
SMTRAT_LOG_DEBUG("smtrat.mcsat.explanation", "Found explanation: " << *explanation);
for(size_t j = 0; j < NUM_THREADS; j++){
pthread_cancel(nativeHandles[j]);
s = pthread_join(nativeHandles[j], &res);
if(s != 0){ SMTRAT_LOG_ERROR("smtrat.mcsat.explanation", "Join failed"); }
if (res != PTHREAD_CANCELED){
SMTRAT_LOG_ERROR("smtrat.mcsat.explanation", "Thread not cancelled");
} else {
SMTRAT_LOG_DEBUG("smtrat.mcsat.explanation", "Thread cancelled successfully");
}
}
nativeHandles.clear();
mtx.unlock();
SMTRAT_LOG_DEBUG("smtrat.mcsat.explanation", "Return reachable");
return explanation;
}
}
}
}
template<std::size_t N = 0, carl::EnableIfBool<N < std::tuple_size<B>::value> = carl::dummy>
std::optional<Explanation> explain(const mcsat::Bookkeeping& data, carl::Variable var, const FormulasT& reason,
const std::size_t NUM_THREADS, std::mutex& mtx,
std::vector<std::thread>& threads, std::vector<pthread_t>& nativeHandles,
size_t& counter, std::vector<std::optional<Explanation>>& explanations) const {
auto F = [&](){
if(pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL)){
SMTRAT_LOG_ERROR("smtrat.mcsat.explanation", "Pthread set cancel type error");
assert(false);
}
SMTRAT_LOG_DEBUG("smtrat.mcsat.explanation", "Concurrent strategy " << N+1 << " started");
explanations[N] = std::get<N>(mBackends)(data, var, reason);
SMTRAT_LOG_DEBUG("smtrat.mcsat.explanation", "Concurrent strategy " << N+1 << " done");
mtx.lock();
counter++;
mtx.unlock();
SMTRAT_LOG_DEBUG("smtrat.mcsat.explanation", "Concurrent strategy " << N+1 << " waiting");
//TODO make this a wait()
while(true){
//no-op
(void)0;
};
};
SMTRAT_LOG_TRACE("smtrat.mcsat.explanation", "Create Thread");
threads.push_back(std::thread(F));
SMTRAT_LOG_TRACE("smtrat.mcsat.explanation", "Created Thread");
nativeHandles.push_back(threads[N].native_handle());
SMTRAT_LOG_TRACE("smtrat.mcsat.explanation", "Store Thread");
explain<N+1>(data, var, reason, NUM_THREADS, mtx, threads, nativeHandles, counter, explanations);
}
public:
std::optional<Explanation> operator()(const mcsat::Bookkeeping& data, carl::Variable var, const FormulasT& reason) const {
const std::size_t NUM_THREADS = std::tuple_size<B>::value;
if(NUM_THREADS <= 0){
SMTRAT_LOG_ERROR("smtrat.mcsat.explanation", "No explanation given.");
return std::nullopt;
}
std::mutex mtx;
std::vector<std::thread> threads;
std::vector<pthread_t> nativeHandles;
size_t counter = 0;
std::vector<std::optional<Explanation>> explanations(NUM_THREADS, std::nullopt);
mtx.lock();
// same workarround as in sequential explanation
std::optional<Explanation> explanation = explain<0>(data, var, reason, NUM_THREADS, mtx, threads, nativeHandles, counter, explanations);
SMTRAT_LOG_DEBUG("smtrat.mcsat.explanation", "Explanation returned");
return explanation;
}
};
} // namespace mcsat
} // namespace smtrat
| true |
090b8f794bcc04c19f3f054b5c8f3f2aa2d6d1fa | C++ | yumcyaWiz/Luminox | /src/vec3.h | UTF-8 | 3,167 | 3.703125 | 4 | [
"MIT"
] | permissive | #ifndef VEC3_H
#define VEC3_H
#include <cmath>
#include <iostream>
class Vec3 {
public:
float x;
float y;
float z;
Vec3() { x = y = z = 0; };
Vec3(float _x) { x = y = z = _x; };
Vec3(float _x, float _y, float _z) : x(_x), y(_y), z(_z) {};
Vec3 operator-() const {
return Vec3(-x, -y, -z);
};
Vec3& operator+=(const Vec3& v) {
x += v.x;
y += v.y;
z += v.z;
return *this;
};
Vec3& operator-=(const Vec3& v) {
x -= v.x;
y -= v.y;
z -= v.z;
return *this;
};
Vec3& operator*=(const Vec3& v) {
x *= v.x;
y *= v.y;
z *= v.z;
return *this;
};
Vec3& operator/=(const Vec3& v) {
x /= v.x;
y /= v.y;
z /= v.z;
return *this;
};
float length() const {
return std::sqrt(x*x + y*y + z*z);
};
float length2() const {
return x*x + y*y + z*z;
};
};
inline Vec3 operator+(const Vec3& v1, const Vec3& v2) {
return Vec3(v1.x + v2.x, v1.y + v2.y, v1.z + v2.z);
}
inline Vec3 operator+(const Vec3& v1, float k) {
return Vec3(v1.x + k, v1.y + k, v1.z + k);
}
inline Vec3 operator+(float k, const Vec3& v2) {
return v2 + k;
}
inline Vec3 operator-(const Vec3& v1, const Vec3& v2) {
return Vec3(v1.x - v2.x, v1.y - v2.y, v1.z - v2.z);
}
inline Vec3 operator-(const Vec3& v1, float k) {
return Vec3(v1.x - k, v1.y - k, v1.z - k);
}
inline Vec3 operator-(float k, const Vec3& v2) {
return Vec3(k - v2.x, k - v2.y, k - v2.z);
}
inline Vec3 operator*(const Vec3& v1, const Vec3& v2) {
return Vec3(v1.x * v2.x, v1.y * v2.y, v1.z * v2.z);
}
inline Vec3 operator*(const Vec3& v1, float k) {
return Vec3(v1.x * k, v1.y * k, v1.z * k);
}
inline Vec3 operator*(float k, const Vec3& v2) {
return v2 * k;
}
inline Vec3 operator/(const Vec3& v1, const Vec3& v2) {
return Vec3(v1.x / v2.x, v1.y / v2.y, v1.z / v2.z);
}
inline Vec3 operator/(const Vec3& v1, float k) {
return Vec3(v1.x / k, v1.y / k, v1.z / k);
}
inline Vec3 operator/(float k, const Vec3& v2) {
return Vec3(k / v2.x, k / v2.y, k / v2.z);
}
inline std::ostream& operator<<(std::ostream& stream, const Vec3& v) {
stream << "(" << v.x << ", " << v.y << ", " << v.z << ")";
return stream;
}
inline float dot(const Vec3& v1, const Vec3& v2) {
return v1.x * v2.x + v1.y * v2.y + v1.z * v2.z;
}
inline Vec3 cross(const Vec3& v1, const Vec3& v2) {
return Vec3(v1.y*v2.z - v1.z*v2.y, v1.z*v2.x - v1.x*v2.z, v1.x*v2.y - v1.y*v2.x);
}
inline Vec3 normalize(const Vec3& v) {
return v/v.length();
}
inline void orthonormalBasis(const Vec3& v1, Vec3& v2, Vec3& v3) {
v2 = Vec3(1, 0, 0);
if(std::abs(v1.x) > 0.9) v2 = Vec3(0, 1, 0);
v2 = normalize(v2 - dot(v1, v2)*v1);
v3 = normalize(cross(v1, v2));
}
inline Vec3 world2local(const Vec3& p, const Vec3& v1, const Vec3& v2, const Vec3& v3) {
return Vec3(dot(p, v1), dot(p, v2), dot(p, v3));
}
inline Vec3 local2world(const Vec3& p, const Vec3& v1, const Vec3& v2, const Vec3& v3) {
Vec3 a = Vec3(v1.x, v2.x, v3.x);
Vec3 b = Vec3(v1.y, v2.y, v3.y);
Vec3 c = Vec3(v1.z, v2.z, v3.z);
return Vec3(dot(p, a), dot(p, b), dot(p, c));
}
#endif
| true |
1fe76ab7f1b40189b9126cea7d10f68176befcb1 | C++ | Ishay1997/number-with-units-b | /NumberWithUnits.hpp | UTF-8 | 1,854 | 2.796875 | 3 | [
"MIT"
] | permissive | #pragma once
#include <iostream>
#include <unordered_map>
#include <string>
using namespace std;
namespace ariel{
class NumberWithUnits{
private:
string unit;
double num;
public :
NumberWithUnits(double num, const string &unit);
static void read_units(ifstream& units_file);
static double conversion(const string &src, const string &dest);
friend NumberWithUnits operator+(const NumberWithUnits &a,const NumberWithUnits &b);
friend NumberWithUnits operator-(const NumberWithUnits &a,const NumberWithUnits &b);
friend NumberWithUnits& operator++(NumberWithUnits &a);
friend NumberWithUnits& operator--(NumberWithUnits &a);
NumberWithUnits operator++(int );
NumberWithUnits operator--(int );
NumberWithUnits operator+();
NumberWithUnits operator-();
NumberWithUnits& operator+=(const NumberWithUnits &b);
NumberWithUnits& operator-=(const NumberWithUnits &b);
friend NumberWithUnits operator*(const NumberWithUnits &a,const double num);
friend NumberWithUnits operator*(const double num,const NumberWithUnits &a);
friend bool operator==(const NumberWithUnits &a,const NumberWithUnits &b);
friend bool operator!=(const NumberWithUnits &a,const NumberWithUnits &b);
friend bool operator<(const NumberWithUnits &a,const NumberWithUnits &b);
friend bool operator>(const NumberWithUnits &a,const NumberWithUnits &b);
friend bool operator>=(const NumberWithUnits &a,const NumberWithUnits &b);
friend bool operator<=(const NumberWithUnits &a,const NumberWithUnits &b);
friend ostream &operator<<(ostream &os,const NumberWithUnits &a);
friend istream &operator>>(istream &is, NumberWithUnits &a);
};
}
| true |
2f1dd5da84f6a2f1ea5e9c2476bbb491e635c028 | C++ | katarina-gres/fit-projects | /IMS/state.cpp | UTF-8 | 2,164 | 2.640625 | 3 | [] | no_license |
/*
* Soubor: state.cpp
* Autor: Vojtech Havlena (xhavle03), Karel Brezina (xbrezi13)
*
* Zdrojovy soubor k implementaci tridy reprezentujici stat.
*/
#include "state.h"
/*
* Metoda, ktera provede hodinu chodu statu (spotrebuje se urcite
* mnozstvi plynu a urcite mnozstvi se vyprodukuje).
*/
void State::ProcessHour()
{
long cons = consumption * ((100 - CONSUMPTION ) + rand() % (CONSUMPTION * 2)) / 100.0;
if(summerConsumption)
{
cons = consumption * summerRatio;
}
else
{
cons = consumption * (2 - summerRatio);
}
stored += importOther + production * ((100 - PRODUCTION ) + rand() % (PRODUCTION * 2)) / 100.0;
stored -= cons;
}
/*
* Metoda, ktera exportuje plyn ze statu.
* @param strategy Pouzita strategie.
* @param time Aktualni cas.
*/
void State::SendGas(STRATEGY strategy, long time)
{
long im = 0;
if(strategy == STRATEGY::GREEDY)
{
/* Mnozstvi odesilaneho plynu. */
im = importLast - consumption + production + importOther;
if(im < 0)
return;
if(sendStates == NULL)
return;
for (auto &val : *sendStates)
{
/* Mnozstvi plynu je rozdeleno podle pomeru kapacit. */
val.second->AddSendGas(im * (val.second->GetCapacity() / (double)sumOutput));
val.second->SendGas(time);
}
}
else
{
if(sendStates == NULL)
return;
for (auto &val : *sendStates)
{
val.second->AddSendGas(val.first);
val.second->SendGas(time);
}
}
}
/*
* Metoda, ktera aktualizuje mnozstvi plynu (po kazde hodine).
*/
void State::CheckStatus()
{
stored += importGas;
importLast = importGas;
importGas = 0;
if(stored < 0)
{
stored = 0;
}
if(stored > capacity)
stored = capacity;
n++;
average = (average * (n-1) + stored) / (double)n;
}
/*
* Nastaveni statu, kam se ma posilat plyn.
* @param send Staty, kam se ma posilat plyn.
*/
void State::SetSendStates(map<long, GasPipeline*> * send)
{
sendStates = send;
sumOutput = 0;
for (auto &val : *sendStates)
{
sumOutput += val.second->GetCapacity();
}
}
| true |
72149c30a2427bc8508a18e4a788485b5cc81963 | C++ | RasedulRussell/uva_problem_solve | /422 - Word-Search Wonder.cpp | UTF-8 | 2,983 | 2.609375 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std ;
char grid[101][101] ;
int row, colam, n ;
vector< pair<int,int> >huha ;
bool boundary_check( int i, int j )
{
if( i >= 1 && i <= n && j >= 1 && j <= n )
{
return true ;
}
return false ;
}
bool finding( string word, int i, int j, pair<int,int>pi )
{
int sz = 0 ;
int sx = i;
int sy = j ;
char ch = word[sz] ;
char gChar = grid[i][j] ;
while( gChar == ch )
{
sz++ ;
ch = word[sz] ;
if( sz == word.size( ) )
{
/*if( sx >= i && sy >= j )
{
cout << "Not found" ;
return true ;
}*/
cout << sx << "," << sy << " " << i << "," << j ;
return true ;
}
i += pi.first ;
j += pi.second ;
gChar = grid[i][j] ;
///cout << gChar << " " << ch << "sz = " << sz << endl ;
if( boundary_check( i, j )==false )
{
break ;
}
}
return false ;
}
void check( string word )
{
int sz = 0 ;
char ch = word[0] ;
for( int i = 1 ; i <= n ; i++ )
{
for( int j = 1 ; j <= n ; j++ )
{
char gch = grid[i][j] ;
if( gch == ch )
{
for( int k = 0 ; k < 8 ; k++ )
{
if( finding( word, i, j, huha[k] ) )
{
return ;
}
}
}
}
}
cout << "Not found" ;
}
int main()
{
huha.push_back( make_pair( 0, 1 ) ) ;
huha.push_back( make_pair( 0, -1 ) ) ;
huha.push_back( make_pair( -1, 0 ) ) ;
huha.push_back( make_pair( 1, 0 ) ) ;
huha.push_back( make_pair( 1, 1 ) ) ;
huha.push_back( make_pair( 1, -1 ) ) ;
huha.push_back( make_pair( -1, 1 ) ) ;
///huha.push_back( make_pair( -1, -1 ) ) ;
int t = 0 ;
while( cin >> n )
{
if( n == 0 )return 0 ;
/// if( t != 0 )cout << endl ; t++ ;
for( int i = 1 ; i <= n ; i++ )
{
for( int j = 1 ; j <= n ; j++ )
{
cin >> grid[i][j] ;
}
}
vector<string>word ;
string bal ;
getchar( ) ;
while( getline( cin, bal ) )
{
if( bal.size( ) == 0 )break ;
word.push_back( bal ) ;
}
/// cout << "sajdfh" << endl ;
///int cnt = 0 ;
for( int i = 0 ; i < word.size() ; i++ )
{
///cnt++ ;
string srch = word[i] ;
if( i != word.size() - 1 )
{
check( srch ) ;
}
if( i != word.size() )
{
cout << endl ;
}
}
///cout << "sdf " << cnt << endl ;
}
return 0 ;
}
| true |
0bb2570f04b80e5ee329c269aebfc4d1e97916b4 | C++ | RedBoxer/tp-lab-7 | /src/Predator.cpp | UTF-8 | 2,178 | 2.828125 | 3 | [] | no_license | #include "Predator.h"
Predator::Predator()
{
this->objType = 2;
this->preysInside = 0;
this->age = 0;
}
Cell* Predator::findPreyNear(){
std::vector<std::vector<Cell*>*> oceanMap = place->getOcean()->getMap();
std::vector<Cell*> preys;
if(row + 1 <= oceanMap.size()-1 && oceanMap.at(row + 1)->at(col) != nullptr && (oceanMap.at(row + 1)->at(col))->getObjType() == 1){
preys.push_back(oceanMap.at(row + 1)->at(col));
}
if(col + 1 <= oceanMap.size()-1 &&oceanMap.at(row)->at(col + 1) != nullptr && (oceanMap.at(row)->at(col + 1))->getObjType() == 1){
preys.push_back(oceanMap.at(row)->at(col + 1));
}
if(row - 1 >= 0 && oceanMap.at(row - 1)->at(col) != nullptr && (oceanMap.at(row - 1)->at(col))->getObjType() == 1){
preys.push_back(oceanMap.at(row - 1)->at(col));
}
if(col - 1 >= 0 && oceanMap.at(row)->at(col - 1) != nullptr && (oceanMap.at(row)->at(col - 1))->getObjType() == 1){
preys.push_back(oceanMap.at(row)->at(col - 1));
}
if(preys.size() == 0)
return nullptr;
if(preys.size() == 1)
return preys.back();
int randIndex = rand()%preys.size();
return preys.at(randIndex);
}
void Predator::live(){
std::vector<std::vector<Cell*>*> oceanMap = place->getOcean()->getMap();
Cell* spot = findPreyNear();
if(spot != nullptr){
(spot->getObject())->kill();
preysInside++;
(oceanMap.at(row)->at(col))->setObject(nullptr);
spot->setObject(this);
if(preysInside >= 2){
spot = getFreeNearSpot();
if(spot != nullptr){
preysInside--;
Predator* child = new Predator();
spot->setObject(child);
place->getOcean()->addObject(child);
}
}
}else{
preysInside--;
spot = getFreeNearSpot();
if(spot != nullptr){
(oceanMap.at(row)->at(col))->setObject(nullptr);
spot->setObject(this);
}
}
age++;
if(age == 15 || preysInside == -3){
std::cout << "Pk ";
(oceanMap.at(row)->at(col))->setObject(nullptr);
this->kill();
}
}
| true |
fde76b26fc8983424ba6f305d9a030decb6cc550 | C++ | DmitryDreytser/TFS4OpenConf | /gcomp/NameTable.h | UTF-8 | 1,131 | 2.5625 | 3 | [] | no_license |
#ifndef NAME_TABLE_H
#define NAME_TABLE_H
#include "Declarations.h"
#include "Strings.h"
class CNameTableRecord
{
public:
MMSObjectType Type;
GCString Type1C;
GCString sID;
GCString StorageName;
bool HasSuffix;
GCString Dir;
GCString FileName;
GCString Ext;
public:
GCString PrepareFileName(GCString& Dir, CMMSObject* object = NULL);
GCString PrepareDirName(GCString& Dir, CMMSObject* object = NULL);
GCString PrepareStorageName(int suffix = 0);
};
class CNameTable
{
private:
CArray<CNameTableRecord*, CNameTableRecord*&> NameTable;
int nRecords;
public:
CNameTable() {};
void RusConstructor();
void EngConstructor();
~CNameTable();
void AddRecord(MMSObjectType Type, LPCSTR Type1C, LPCSTR sID,
LPCSTR StorageName, bool HasSuffix,
LPCSTR Dir, LPCSTR FileName = NULL, LPCSTR Ext = NULL);
CNameTableRecord* Find(MMSObjectType Type);
CNameTableRecord* Find(GCString& sID);
CNameTableRecord* FindByType1C(GCString& Type1C);
inline int GetNRecords() {return nRecords;};
inline CNameTableRecord* operator[](int i) {return NameTable[i];};
};
#endif | true |
ee4096c755b6bcb1410cd27fe9d09a8e41d383d6 | C++ | Fancy7Fully/Library | /p1t/test10.cc | UTF-8 | 7,435 | 2.84375 | 3 | [] | no_license | /***************************************
* test10 - Deli modified for test *
***************************************/
#include <iostream>
#include <vector>
#include <queue>
#include <fstream>
#include <list>
#include <map>
#include <sstream>
#include <cstdlib>
#include "thread.h"
#define ARRAYSIZE(array) (sizeof((array))/sizeof((array[0])))
typedef struct _order_t {
int cashier_id;
int sandwich_id;
} order_t;
typedef struct _cashier_arg_t {
int cashier_id;
std::queue<int> order_list;
} cashier_arg_t;
std::vector<order_t> board;
int max_board;
int num_cashiers;
int num_makers;
// Locks
unsigned int lock_board;
// Condition Variables;
unsigned int CV_can_add =10;
unsigned int CV_can_take =15;
void maker(void* vp);
void cashier(void* cashier_arg);
std::queue<int>* cashiers;
void deli(void* vp){
//std::cout << "We are in deli\n";
//start_preemptions(bool async, bool sync, int random_seed)
/*std::cout << "Starting async preemptions" << std::endl;
start_preemptions(true, false, 10);*/
thread_create(maker, (void*) "maker");
for (int i = 0; i < num_cashiers; ++i) {
cashier_arg_t* cashier_arg = new cashier_arg_t;
cashier_arg->cashier_id = i;
cashier_arg->order_list = cashiers[i];
thread_create(cashier,(void *) cashier_arg);
}
}
void maker(void* vp){
int last_sandwich_made = -1;
// until sandwiches are finished
do {
//std::cout << "We are in maker\n";
// Acquire lock
thread_lock(lock_board);
// Check conditions
while(!(board.size() >= max_board || board.size() >= num_cashiers)) {
// std::cerr << "[maker sleeps]" << std::endl;
/*if(!thread_wait(lock_board, CV_can_take)){
std::cerr << "Maker is not waiting" << std::endl;
}*/
thread_wait(lock_board, CV_can_take);
// std::cerr << "[maker awake]" << std::endl;
}
while(board.size() >= max_board || board.size() >= num_cashiers) {
int min_difference = 1000;
int min_diff_index = 0;
int diff;
for (int i = 0; i < board.size(); ++i) {
diff = abs(board[i].sandwich_id - last_sandwich_made);
if (min_difference > diff) {
min_diff_index = i;
min_difference = diff;
}
}
last_sandwich_made = board[min_diff_index].sandwich_id;
std::cout << "READY: cashier " << board[min_diff_index].cashier_id << " sandwich " << board[min_diff_index].sandwich_id << std::endl;
board.erase(board.begin() + min_diff_index);
}
// Release lock
thread_unlock(lock_board);
// Broadcast
thread_broadcast(lock_board, CV_can_add);
} while(num_cashiers > 0);
//initialization to -1
// lock board
// while (board not full){
// wait(board full)
// }
// while board full {
// use algorithm, make sandwich
// remove from board
// cout
// }
// broadcast;
// } unlock;
}
//assume the board lock is had here
// 3 conditions to check:
// 1. >= max board
// 2. >= num cashiers
// 3. cashier_id on board already
bool cashier_cant_add(int cashier_id){
if (board.size() >= max_board) {
return true;
} else if (board.size() >= num_cashiers) {
return true;
}
for (int i = 0; i < board.size(); ++i) {
if (board[i].cashier_id == cashier_id) {
return true;
}
}
return false;
}
void cashier(void* cashier_arg){
int cashier_id = ((cashier_arg_t*) cashier_arg)->cashier_id;
std::queue<int> order_list = ((cashier_arg_t*)cashier_arg)->order_list;
while(true) {
//std::cout << "We are in cashier1\n";
// Acquire Lock
thread_lock(lock_board);
// Check the board conditions
while(cashier_cant_add(cashier_id)) {
// std::cerr << "[cashier waiting (" << cashier_id << ")]" << std::endl;
thread_wait(lock_board, CV_can_add);
//std::cerr << "[cashier awake (" << cashier_id << ")]" << std::endl;
}
//std::cout << "We are in cashier2\n";
// If no more sandwiches left, exit.
if (order_list.empty()) {
num_cashiers--;
if (num_cashiers == 0) {
//std::cerr << "[cashier quits (" << cashier_id << ")]" << std::endl;
return;
}
thread_unlock(lock_board);
thread_broadcast(lock_board, CV_can_add);
// std::cerr << "numcashiers = " << num_cashiers << std::endl;
return;
}
// Create Structure to add to board
order_t order;
order.cashier_id = cashier_id;
order.sandwich_id = order_list.front();
order_list.pop();
// Add to board
board.push_back(order);
std::cout << "POSTED: cashier " << order.cashier_id << " sandwich " << order.sandwich_id << std::endl;
// Release Lock
thread_unlock(lock_board);
// Signal the maker if the board is full or its equal to num_cashiers
if (board.size() >= max_board || board.size() >= num_cashiers) {
//board.size() != 0 removed from the if statement
//std::cerr << "Board size is: " << board.size() << std::endl;
//std::cerr << "** signal to maker **" << std::endl;
thread_broadcast(lock_board, CV_can_take);
} else {
// std::cerr << "Board size is: " << board.size() << std::endl;
//std::cerr << "** signal to cashiers **" << std::endl;
thread_broadcast(lock_board, CV_can_add);
}
}
}
int main(int argc, char *argv[])
{
/******************* Argument parsing ******************/
std::map<int, std::list<int> > matrix;
num_makers = 1;
num_cashiers = 10;
max_board = 4;
cashiers = new std::queue<int> [num_cashiers];
int zero[] = {250, 490, 510};
int one[] = {150, 480, 520};
int two[] = {50, 47, 530};
int three[] = {25, 470, 540};
int four[] = {20, 460, 590};
int five[] = {950, 440, 580};
int six[] = {850, 920, 570};
int seven[] = {750, 875, 560};
int eight[] = {650, 45, 551};
int nine[] = {350, 35, 55};
for(int i =0; i < 10; i++) matrix[i].push_back(0);
matrix[0].insert(matrix[0].begin(), zero, zero+ARRAYSIZE(zero)+1);
matrix[1].insert(matrix[1].begin(), one, one+ARRAYSIZE(one)+1);
matrix[2].insert(matrix[2].begin(), two, two+ARRAYSIZE(two)+1);
matrix[3].insert(matrix[3].begin(), three, three+ARRAYSIZE(three)+1);
matrix[4].insert(matrix[4].begin(), four, four+ARRAYSIZE(four)+1);
matrix[5].insert(matrix[5].begin(), five, five+ARRAYSIZE(five)+1);
matrix[6].insert(matrix[6].begin(), six, six+ARRAYSIZE(six)+1);
matrix[7].insert(matrix[7].begin(), seven, seven+ARRAYSIZE(seven)+1);
matrix[8].insert(matrix[8].begin(), eight, eight+ARRAYSIZE(eight)+1);
matrix[9].insert(matrix[9].begin(), nine, nine+ARRAYSIZE(nine)+1);
for(int i = 0; i < num_cashiers; i++){
std::queue<int> sandwich_list;
for(int j = 0; j < matrix[i].size(); j++){
sandwich_list.push(matrix[i].front());
matrix[i].pop_front();
}
cashiers[i] = sandwich_list;
}
/*************** Threaded Program *********************/
thread_libinit(deli, (void*) "Deli Program");
return 0;
}
| true |
9a85abc74bb0458fdfbd604d5a680ed5a1fb0504 | C++ | yesterdail/deformable-mesh | /mesh/mesh/common/TriMesh.cpp | UTF-8 | 4,013 | 2.5625 | 3 | [] | no_license | #include "TriMesh.h"
namespace hj
{
TriMesh::TriMesh(void)
{
}
TriMesh::~TriMesh(void)
{
}
void TriMesh::needBoundingBox()
{
TriMesh::ConstVertexIter vIt = vertices_begin();
TriMesh::ConstVertexIter vEnd = vertices_end();
bbox_min = bbox_max = point(vIt);
for (; vIt != vEnd; ++vIt) {
const Point& p = point(vIt);
bbox_min.minimize(p);
bbox_max.maximize(p);
}
}
void TriMesh::request_curvature()
{
OpenMesh::VPropHandleT<TriMesh::Point> curvature;
get_property_handle(curvature, "curvature");
TriMesh::VertexIter v_it, v_end(vertices_end());
TriMesh::VertexVertexIter vv_it, vv_it2;
TriMesh::Scalar voronoiArea;
for (v_it = vertices_begin(); v_it != v_end; ++v_it)
{
property(curvature, v_it)[0] = 0;
property(curvature, v_it)[1] = 0;
property(curvature, v_it)[2] = 0;
voronoiArea = 0;
for (vv_it = vv_iter(v_it); vv_it.is_valid(); ++vv_it)
{
// (p) - p3
// / \ /
// p1 - p2
// p is v_it; p2 is vv_it;
Point p = point(v_it);
Point p2 = point(vv_it);
vv_it--;
Point p3 = point(vv_it);
vv_it++;
vv_it++;
Point p1 = point(vv_it);
vv_it--;
TriMesh::Scalar wij = ((p - p1) | (p2 - p1)) / ((p - p1) % (p2 - p1)).length() +
((p - p3) | (p2 - p3)) / ((p - p3) % (p2 - p3)).length();
property(curvature, v_it) += wij * (p2 - p);
voronoiArea += wij * (p2 - p).length() * (p2 - p).length() / 8;
}
property(curvature, v_it) /= 2 * voronoiArea;
}
}
void TriMesh::request_curvature_color()
{
OpenMesh::VPropHandleT<TriMesh::Point> curvature;
get_property_handle(curvature, "curvature");
OpenMesh::VPropHandleT<TriMesh::Point> curvature_color;
get_property_handle(curvature_color, "curvature_color");
TriMesh::VertexIter v_it, v_end(vertices_end());
std::vector<float> lens;
TriMesh::Scalar len;
for (v_it = vertices_begin(); v_it != v_end; ++v_it)
{
len = property(curvature, v_it).length();
lens.push_back(len);
}
std::sort(lens.begin(), lens.end());
TriMesh::Scalar threshold = lens[(unsigned int)ceil(9 * n_vertices() / 10.0)];
for (v_it = vertices_begin(); v_it != v_end; ++v_it)
{
if (property(curvature, v_it).length() > threshold)
len = 1;
else
len = 0;
property(curvature_color, v_it)[0] = 1 - len;
property(curvature_color, v_it)[1] = 1 - len;
property(curvature_color, v_it)[2] = 1 - len;
}
lens.clear();
}
bool TriMesh::read(const char* filename, OpenMesh::IO::Options* opt)
{
OpenMesh::IO::Options default_opt;
default_opt += OpenMesh::IO::Options::VertexNormal;
default_opt += OpenMesh::IO::Options::VertexTexCoord;
default_opt += OpenMesh::IO::Options::FaceNormal;
default_opt += OpenMesh::IO::Options::FaceTexCoord;
if (!opt)
opt = &default_opt;
this->request_vertex_normals();
this->request_vertex_texcoords2D();
this->request_face_normals();
if (!OpenMesh::IO::read_mesh(*this, filename, *opt)) {
return false;
}
// update face and vertex normals
if (!opt->check(OpenMesh::IO::Options::FaceNormal))
this->update_face_normals();
else
std::cout << "File provides face normals\n";
if (!opt->check(OpenMesh::IO::Options::VertexNormal))
this->update_vertex_normals();
else
std::cout << "File provides vertex normals\n";
// check for texcoord.
if (opt->check(OpenMesh::IO::Options::VertexTexCoord))
std::cout << "File provides texture coordinates\n";
option = *opt;
return true;
}
bool TriMesh::save(const char* filename, OpenMesh::IO::Options* opt)
{
OpenMesh::IO::Options default_opt;
if (!opt)
opt = &default_opt;
if (!OpenMesh::IO::write_mesh(*this, filename, *opt))
return false;
return true;
}
} | true |
1f4dcd5247e39ca81d9ca58ff0f020cdeeba7b7a | C++ | vicobill/simpleai | /src/ai/zone/Zone.h | UTF-8 | 12,502 | 3 | 3 | [
"Zlib"
] | permissive | /**
* @file
*
* @defgroup Zone
* @{
* A zone is a logical unit that groups AI instances.
*
* Zones should have unique names - this is for the debug server to print the zone names to
* debug them properly.
*
* Each zone has a dedicated ai::GroupMgr instance. For more detailed information, just check out
* the [sourcecode](src/ai/zone/Zone.h).
*/
#pragma once
#include "ICharacter.h"
#include "group/GroupMgr.h"
#include "common/Thread.h"
#include "common/ThreadPool.h"
#include "common/Types.h"
#include "common/ExecutionTime.h"
#include <unordered_map>
#include <vector>
#include <memory>
namespace ai {
class AI;
typedef std::shared_ptr<AI> AIPtr;
/**
* @brief A zone represents one logical zone that groups AI instances.
*
* You have to update the AI instances in this zone in your tick by calling
* @c Zone::update.
*
* Zones should have unique names - otherwise the @c Server won't be able to
* select a particular @c Zone to debug it.
*/
class Zone {
public:
typedef std::unordered_map<CharacterId, AIPtr> AIMap;
typedef std::vector<AIPtr> AIScheduleList;
typedef std::vector<CharacterId> CharacterIdList;
typedef AIMap::const_iterator AIMapConstIter;
typedef AIMap::iterator AIMapIter;
protected:
const std::string _name;
AIMap _ais;
AIScheduleList _scheduledAdd;
AIScheduleList _scheduledRemove;
CharacterIdList _scheduledDestroy;
bool _debug;
ReadWriteLock _lock {"zone"};
ReadWriteLock _scheduleLock {"zone-schedulelock"};
ai::GroupMgr _groupManager;
mutable ThreadPool _threadPool;
/**
* @brief called in the zone update to add new @c AI instances.
*
* @note Make sure to also call @c removeAI whenever you despawn the given @c AI instance
* @note This doesn't lock the zone - but because @c Zone::update already does it
*/
bool doAddAI(const AIPtr& ai);
/**
* @note This doesn't lock the zone - but because @c Zone::update already does it
*/
bool doRemoveAI(const AIPtr& ai);
/**
* @brief @c removeAI will access the character and the @c AI object, this method does not need access to the data anymore.
*
* @note That means, that this can be called in case the attached @c ICharacter instances or the @c AI instance itself is
* already invalid.
* @note This doesn't lock the zone - but because @c Zone::update already does it
*/
bool doDestroyAI(const CharacterId& id);
public:
Zone(const std::string& name, int threadCount = std::min(1u, std::thread::hardware_concurrency())) :
_name(name), _debug(false), _threadPool(threadCount) {
}
virtual ~Zone() {}
/**
* @brief Update all the @c ICharacter and @c AI instances in this zone.
* @param dt Delta time in millis since the last update call happened
* @note You have to call this on your own.
*/
void update(int64_t dt);
/**
* @brief If you need to add new @code AI entities to a zone from within the @code AI tick (e.g. spawning via behaviour
* tree) - then you need to schedule the spawn. Otherwise you will end up in a deadlock
*
* @note This does not lock the zone for writing but a dedicated schedule lock
*/
bool addAI(const AIPtr& ai);
/**
* @brief Add multiple AIPtr instances but only lock once.
* @sa addAI()
*/
template<class Collection>
bool addAIs(const Collection& ais) {
if (ais.empty()) {
return false;
}
ScopedWriteLock scopedLock(_scheduleLock);
_scheduledAdd.insert(_scheduledAdd.end(), ais.begin(), ais.end());
return true;
}
/**
* @brief Will trigger a removal of the specified @c AI instance in the next @c Zone::update call
*
* @note This does not lock the zone for writing but a dedicated schedule lock
*/
bool removeAI(const AIPtr& ai);
/**
* @brief Remove multiple AIPtr instances but only lock once.
* @sa removeAI()
*/
template<class Collection>
bool removeAIs(const Collection& ais) {
if (ais.empty()) {
return false;
}
ScopedWriteLock scopedLock(_scheduleLock);
_scheduledRemove.insert(_scheduledRemove.end(), ais.begin(), ais.end());
return true;
}
/**
* @brief Will trigger a destroy of the specified @c AI instance in the next @c Zone::update call
* @sa destroyAI
* @note @c removeAI will access the character and the @c AI object, this method does not need access to the data anymore.
* That means, that this can be called in case the attached @c ICharacter instances or the @c AI instance itself is
* already invalid.
*/
bool destroyAI(const CharacterId& id);
/**
* @brief Every zone has its own name that identifies it
*/
const std::string& getName() const;
/**
* @brief Activate the debugging for this particular server instance
* @param[in] debug @c true if you want to activate the debugging and send
* the npc states of this server to all connected clients, or @c false if
* none of the managed entities is broadcasted.
*/
void setDebug(bool debug);
bool isDebug () const;
GroupMgr& getGroupMgr();
const GroupMgr& getGroupMgr() const;
/**
* @brief Lookup for a particular @c AI in the zone.
*
* @return empty @c AIPtr() in the case the given @c CharacterId wasn't found in this zone.
*
* @note This locks the zone for reading to perform the CharacterId lookup
*/
inline AIPtr getAI(CharacterId id) const {
ScopedReadLock scopedLock(_lock);
auto i = _ais.find(id);
if (i == _ais.end()) {
return AIPtr();
}
const AIPtr& ai = i->second;
return ai;
}
/**
* @brief Executes a lambda or functor for the given character
*
* @return @c true if the func is going to get called for the character, @c false if not
* e.g. in the case the given @c CharacterId wasn't found in this zone.
* @note This is executed in a thread pool - so make sure to synchronize your lambda or functor.
* We also don't wait for the functor or lambda here, we are scheduling it in a worker in the
* thread pool.
*
* @note This locks the zone for reading to perform the CharacterId lookup
*/
template<typename Func>
inline bool executeAsync(CharacterId id, const Func& func) const {
const AIPtr& ai = getAI(id);
if (!ai) {
return false;
}
executeAsync(ai, func);
return true;
}
/**
* @brief Executes a lambda or functor for the given character
*
* @returns @c std::future with the result of @c func.
* @note This is executed in a thread pool - so make sure to synchronize your lambda or functor.
* We also don't wait for the functor or lambda here, we are scheduling it in a worker in the
* thread pool. If you want to wait - you have to use the returned future.
*/
template<typename Func>
inline auto executeAsync(const AIPtr& ai, const Func& func) const
-> std::future<typename std::result_of<Func(const AIPtr&)>::type> {
return _threadPool.enqueue(func, ai);
}
template<typename Func>
inline auto execute(const AIPtr& ai, const Func& func) const
-> typename std::result_of<Func(const AIPtr&)>::type {
return func(ai);
}
template<typename Func>
inline auto execute(const AIPtr& ai, Func& func)
-> typename std::result_of<Func(const AIPtr&)>::type {
return func(ai);
}
/**
* @brief The given functor or lambda must be able to deal with invalid @c AIPtr instances
* @note It's possible that the given @c CharacterId can't be found in the @c Zone.
* @return the return value of your functor or lambda
*/
template<typename Func>
inline auto execute(CharacterId id, const Func& func) const
-> typename std::result_of<Func(const AIPtr&)>::type {
return execute(getAI(id), func);
}
/**
* @brief The given functor or lambda must be able to deal with invalid @c AIPtr instances
* @note It's possible that the given @c CharacterId can't be found in the @c Zone.
* @return the return value of your functor or lambda
*/
template<typename Func>
inline auto execute(CharacterId id, Func& func)
-> typename std::result_of<Func(const AIPtr&)>::type {
return execute(getAI(id), func);
}
/**
* @brief Executes a lambda or functor for all the @c AI instances in this zone
* @note This is executed in a thread pool - so make sure to synchronize your lambda or functor.
* We are waiting for the execution of this.
*
* @note This locks the zone for reading
*/
template<typename Func>
void executeParallel(Func& func) {
std::vector<std::future<void> > results;
_lock.lockRead();
AIMap copy(_ais);
_lock.unlockRead();
for (auto i = copy.begin(); i != copy.end(); ++i) {
const AIPtr& ai = i->second;
results.emplace_back(executeAsync(ai, func));
}
for (auto & result: results) {
result.wait();
}
}
/**
* @brief Executes a lambda or functor for all the @c AI instances in this zone.
* @note This is executed in a thread pool - so make sure to synchronize your lambda or functor.
* We are waiting for the execution of this.
*
* @note This locks the zone for reading
*/
template<typename Func>
void executeParallel(const Func& func) const {
std::vector<std::future<void> > results;
_lock.lockRead();
AIMap copy(_ais);
_lock.unlockRead();
for (auto i = copy.begin(); i != copy.end(); ++i) {
const AIPtr& ai = i->second;
results.emplace_back(executeAsync(ai, func));
}
for (auto & result: results) {
result.wait();
}
}
/**
* @brief Executes a lambda or functor for all the @c AI instances in this zone
* We are waiting for the execution of this.
*
* @note This locks the zone for reading
*/
template<typename Func>
void execute(const Func& func) const {
_lock.lockRead();
AIMap copy(_ais);
_lock.unlockRead();
for (auto i = copy.begin(); i != copy.end(); ++i) {
const AIPtr& ai = i->second;
func(ai);
}
}
/**
* @brief Executes a lambda or functor for all the @c AI instances in this zone
* We are waiting for the execution of this.
*
* @note This locks the zone for reading
*/
template<typename Func>
void execute(Func& func) {
_lock.lockRead();
AIMap copy(_ais);
_lock.unlockRead();
for (auto i = copy.begin(); i != copy.end(); ++i) {
const AIPtr& ai = i->second;
func(ai);
}
}
inline std::size_t size() const {
ScopedReadLock scopedLock(_lock);
return _ais.size();
}
};
inline void Zone::setDebug (bool debug) {
_debug = debug;
}
inline bool Zone::isDebug () const {
return _debug;
}
inline const std::string& Zone::getName() const {
return _name;
}
inline GroupMgr& Zone::getGroupMgr() {
return _groupManager;
}
inline const GroupMgr& Zone::getGroupMgr() const {
return _groupManager;
}
inline bool Zone::doAddAI(const AIPtr& ai) {
if (ai == nullptr) {
return false;
}
const CharacterId& id = ai->getCharacter()->getId();
if (_ais.find(id) != _ais.end()) {
return false;
}
_ais.insert(std::make_pair(id, ai));
ai->setZone(this);
return true;
}
inline bool Zone::doRemoveAI(const AIPtr& ai) {
if (!ai) {
return false;
}
const CharacterId& id = ai->getCharacter()->getId();
AIMapIter i = _ais.find(id);
if (i == _ais.end()) {
return false;
}
i->second->setZone(nullptr);
_groupManager.removeFromAllGroups(i->second);
_ais.erase(i);
return true;
}
inline bool Zone::doDestroyAI(const CharacterId& id) {
AIMapIter i = _ais.find(id);
if (i == _ais.end()) {
return false;
}
_ais.erase(i);
return true;
}
inline bool Zone::addAI(const AIPtr& ai) {
if (!ai) {
return false;
}
ScopedWriteLock scopedLock(_scheduleLock);
_scheduledAdd.push_back(ai);
return true;
}
inline bool Zone::destroyAI(const CharacterId& id) {
ScopedWriteLock scopedLock(_scheduleLock);
_scheduledDestroy.push_back(id);
return true;
}
inline bool Zone::removeAI(const AIPtr& ai) {
if (!ai) {
return false;
}
ScopedWriteLock scopedLock(_scheduleLock);
_scheduledRemove.push_back(ai);
return true;
}
inline void Zone::update(int64_t dt) {
{
AIScheduleList scheduledRemove;
AIScheduleList scheduledAdd;
CharacterIdList scheduledDestroy;
{
ScopedWriteLock scopedLock(_scheduleLock);
scheduledAdd.swap(_scheduledAdd);
scheduledRemove.swap(_scheduledRemove);
scheduledDestroy.swap(_scheduledDestroy);
}
ScopedWriteLock scopedLock(_lock);
for (const AIPtr& ai : scheduledAdd) {
doAddAI(ai);
}
scheduledAdd.clear();
for (const AIPtr& ai : scheduledRemove) {
doRemoveAI(ai);
}
scheduledRemove.clear();
for (auto id : scheduledDestroy) {
doDestroyAI(id);
}
scheduledDestroy.clear();
}
auto func = [&] (const AIPtr& ai) {
if (ai->isPause()) {
return;
}
ai->update(dt, _debug);
ai->getBehaviour()->execute(ai, dt);
};
executeParallel(func);
_groupManager.update(dt);
}
}
| true |
7bec85f30a7e714569e261697ee0db52b761ecae | C++ | manojkiraneda/phosphor-networkd | /dhcp_configuration.hpp | UTF-8 | 3,660 | 2.59375 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
#include "config_parser.hpp"
#include <sdbusplus/bus.hpp>
#include <sdbusplus/server/object.hpp>
#include <string>
#include <xyz/openbmc_project/Network/DHCPConfiguration/server.hpp>
namespace phosphor
{
namespace network
{
class Manager; // forward declaration of network manager.
namespace dhcp
{
using ConfigIntf =
sdbusplus::xyz::openbmc_project::Network::server::DHCPConfiguration;
using Iface = sdbusplus::server::object::object<ConfigIntf>;
/** @class Configuration
* @brief DHCP configuration.
* @details A concrete implementation for the
* xyz.openbmc_project.Network.DHCP DBus interface.
*/
class Configuration : public Iface
{
public:
Configuration() = default;
Configuration(const Configuration&) = delete;
Configuration& operator=(const Configuration&) = delete;
Configuration(Configuration&&) = delete;
Configuration& operator=(Configuration&&) = delete;
virtual ~Configuration() = default;
/** @brief Constructor to put object onto bus at a dbus path.
* @param[in] bus - Bus to attach to.
* @param[in] objPath - Path to attach at.
* @param[in] parent - Parent object.
*/
Configuration(sdbusplus::bus::bus& bus, const std::string& objPath,
Manager& parent) :
Iface(bus, objPath.c_str(), true),
bus(bus), manager(parent)
{
ConfigIntf::dNSEnabled(getDHCPPropFromConf("UseDNS"));
ConfigIntf::nTPEnabled(getDHCPPropFromConf("UseNTP"));
ConfigIntf::hostNameEnabled(getDHCPPropFromConf("UseHostname"));
ConfigIntf::sendHostNameEnabled(getDHCPPropFromConf("SendHostname"));
emit_object_added();
}
/** @brief If true then DNS servers received from the DHCP server
* will be used and take precedence over any statically
* configured ones.
* @param[in] value - true if DNS server needed from DHCP server
* else false.
*/
bool dNSEnabled(bool value) override;
/** @brief If true then NTP servers received from the DHCP server
will be used by systemd-timesyncd.
* @param[in] value - true if NTP server needed from DHCP server
* else false.
*/
bool nTPEnabled(bool value) override;
/** @brief If true then Hostname received from the DHCP server will
* be set as the hostname of the system
* @param[in] value - true if hostname needed from the DHCP server
* else false.
*
*/
bool hostNameEnabled(bool value) override;
/** @brief if true then it will cause an Option 12 field, i.e machine's
* hostname, will be included in the DHCP packet.
* @param[in] value - true if machine's host name needs to be included
* in the DHCP packet.
*/
bool sendHostNameEnabled(bool value) override;
/** @brief read the DHCP Prop value from the configuration file
* @param[in] prop - DHCP Prop name.
*/
bool getDHCPPropFromConf(const std::string& prop);
/* @brief Network Manager needed the below function to know the
* value of the properties (ntpEnabled,dnsEnabled,hostnameEnabled
sendHostNameEnabled).
*
*/
using ConfigIntf::dNSEnabled;
using ConfigIntf::hostNameEnabled;
using ConfigIntf::nTPEnabled;
using ConfigIntf::sendHostNameEnabled;
private:
/** @brief sdbusplus DBus bus connection. */
sdbusplus::bus::bus& bus;
/** @brief Network Manager object. */
phosphor::network::Manager& manager;
};
} // namespace dhcp
} // namespace network
} // namespace phosphor
| true |
52afffae7f19c68af75135386ed9c2d6c09aaaa2 | C++ | GirlsCrush/Stepik-MultiThread | /StepikTask14/main.cpp | UTF-8 | 2,014 | 2.578125 | 3 | [] | no_license | #include <sys/types.h>
//
#include <sys/stat.h>
//
#include <unistd.h>
//
#include <stdio.h>
//
#include <stdlib.h>
//
#include <fcntl.h>
//
#include <string>
int main() {
int fd_fifo_in;
int fd_fifo_out;
char buffer[1024];
if((mkfifo("/home/box/in.fifo", 0666)) == -1) {
fprintf(stderr, "Невозможно создать infifo\n");
exit(0);
}
printf("mkfifo in\n");
if((fd_fifo_in = open("/home/box/in.fifo", O_RDONLY | O_NONBLOCK)) == -1) {
fprintf(stderr, "Невозможно открыть infifo\n");
exit(0);
}
printf("opened in\n");
if((mkfifo("/home/box/out.fifo", 0666)) == -1) {
fprintf(stderr, "Невозможно создать outfifo\n");
exit(0);
}
if((fd_fifo_out = open("/home/box/out.fifo", O_WRONLY )) == - 1) {
fprintf(stderr, "Невозможно открыть outfifo\n");
exit(0);
}
printf("opened out\n");
size_t len = 0;
std::string buf;
while (!len) {
//printf("trying to read\n");
if ((len = read(fd_fifo_in, &buffer, sizeof(buffer))) == -1) {
fprintf(stderr, "Невозможно прочесть из FIFO\n");
close(fd_fifo_in);
close(fd_fifo_out);
exit(0);
}
}
while (len) {
buf += buffer;
if ((len = read(fd_fifo_in, &buffer, sizeof(buffer))) == -1) {
fprintf(stderr, "Невозможно прочесть из FIFO\n");
close(fd_fifo_in);
close(fd_fifo_out);
exit(0);
}
}
printf(buf.c_str());
write(fd_fifo_out, buf.c_str(), buf.size());
close(fd_fifo_in);
close(fd_fifo_out);
} | true |
ba77f06c6b1ad236ed5ec6ef731acd0b1253a752 | C++ | wwambolt/schoolwork | /comp3773/assignments/a5/A5Driver.cpp | UTF-8 | 3,729 | 3.453125 | 3 | [] | no_license | /*
* File: A5Driver.cpp
* Author: William Wambolt 100097716
* Version: 1.0
* Date: March 27, 2019
* Purpose: Driver class to test modules.
*
* Notes:
*
*/
#include <iostream>
using namespace std;
#include "Registrar.h"
int
main()
{
// The main program follows the following steps:
// 1. create a Registrar object
Registrar * reg = new Registrar();
// 2. create and add at least three courses to the Registrar
Course * cour_1 = new Course("COMP 0666");
Course * cour_2 = new Course("MATH 1337");
Course * cour_3 = new Course("BUSI 8008");
Course * cour_4 = new Course("CHEM 8584");
Course * cour_5 = new Course("PSYC 1123");
Course * cour_6 = new Course("WGST 3343");
reg->addCourse(cour_1);
reg->addCourse(cour_2);
reg->addCourse(cour_3);
reg->addCourse(cour_4);
reg->addCourse(cour_5);
reg->addCourse(cour_6);
// 3. create and add at least five students to the Registrar
Student * stud_1 = new Student("Chief Masters");
Student * stud_2 = new Student("Artyom Metro");
Student * stud_3 = new Student("J.C. Jensen");
Student * stud_4 = new Student("Cmdr. Sheepherder");
Student * stud_5 = new Student("Link Zelda");
reg->addStudent(stud_1);
reg->addStudent(stud_2);
reg->addStudent(stud_3);
reg->addStudent(stud_4);
reg->addStudent(stud_5);
// 4. enroll one student in three courses
reg->enroll(1, "COMP 0666");
reg->enroll(1, "MATH 1337");
reg->enroll(1, "BUSI 8008");
// 5. enroll one student in two courses
reg->enroll(2, "CHEM 8584");
reg->enroll(2, "PSYC 1123");
// 6. enroll three students in one course each
reg->enroll(3, "COMP 0666");
reg->enroll(4, "WGST 3343");
reg->enroll(5, "WGST 3343");
/* 7. for each student a.print their name and number and the list of
courses they're enrolled in */
cout << "Students and their courses:" << endl
<< "***************************" << endl;
stud_1->printStudentInfo();
stud_1->printCourseList();
cout << endl;
stud_2->printStudentInfo();
stud_2->printCourseList();
cout << endl;
stud_3->printStudentInfo();
stud_3->printCourseList();
cout << endl;
stud_4->printStudentInfo();
stud_4->printCourseList();
cout << endl;
stud_5->printStudentInfo();
stud_5->printCourseList();
cout << endl << endl;
/* 8. for each course a.print its code and the list of students enrolled
in it */
cout << "Courses and their students:" << endl
<< "***************************" << endl;
cour_1->printCode();
cour_1->printStudentList();
cout << endl;
cour_2->printCode();
cour_2->printStudentList();
cout << endl;
cour_3->printCode();
cour_3->printStudentList();
cout << endl;
cour_4->printCode();
cour_4->printStudentList();
cout << endl;
cour_5->printCode();
cour_5->printStudentList();
cout << endl;
cour_6->printCode();
cour_6->printStudentList();
cout << endl << endl;
// 9. drop (any) one student from (any) one course
cout << "Student #1 dropped COMP 0666" << endl
<< "****************************" << endl;
reg->drop(1, "COMP 0666");
/* 10. print the name and number of that student and the list of courses
they're enrolled in */
stud_1->printStudentInfo();
stud_1->printCourseList();
cout << endl << endl;
/*11. print the code and list of students for the course that student
dropped */
cout << "COMP 0666 not enrolling Student #1" << endl
<< "**********************************" << endl;
cour_1->printCode();
cour_1->printStudentList();
return 0;
} | true |
1f3adc8bcc4173d580a71661527c47e7fc349c58 | C++ | yangmingzi/MyLeetcode | /3-Longest Substring Without Repeating Characters.cpp | UTF-8 | 6,317 | 3.828125 | 4 | [] | no_license | /*
Given a string, find the length of the longest substring without repeating characters.
For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3.
For "bbbbb" the longest substring is "b", with the length of 1.
*/
/*
最长不重复子串
参考博客:http://www.ahathinking.com/archives/123.html
*/
/*
基本算法 使用Hash
要求子串中的字符不能重复,判重问题首先想到的就是hash,
寻找满足要求的子串,最直接的方法就是遍历每个字符起始的子串,辅助hash,
寻求最长的不重复子串,由于要遍历每个子串故复杂度为O(n^2),n为字符串的长度,辅助的空间为常数hash[256]。
DP方案
前面刚刚讨论过最长递增子序列的问题,咋一想就觉得二者有点类似,何不向DP方面想一下,为什么说二者类似,
在LIS问题中,对于当前的元素,要么是与前面的LIS构成新的最长递增子序列,要么就是与前面稍短的子序列构成新的子序列或单独构成新子序列;
同理,对于最长不重复子串,某个当前的字符,如果它与前面的最长不重复子串中的字符没有重复,那么就可以以它为结尾构成新的最长子串;
如果有重复,且重复位置在上一个最长子串起始位置之后,那么就与该起始位置之后的稍短的子串构成新的子串或者单独成一个新子串。
举个例子:例如字符串“abcdeab”,第二个字符a之前的最长不重复子串是“abcde”,a与最长子串中的字符有重复,
但是它与稍短的“bcde”串没有重复,于是它可以与其构成一个新的子串,之前的最长重复子串“abcde”结束;
再看一个例子:字符串“abcb”,跟前面类似,最长串“abc”结束,第二个字符b与稍短的串“c”构成新的串;
这两个例子,可以看出些眉目:当一个最长子串结束时(即遇到重复的字符),
新的子串的长度是与第一个重复的字符的下标有关的,如果该下标在上一个最长子串起始位置之前,则dp[i] = dp[i-1] + 1,
即上一个最长子串的起始位置也是当前最长子串的起始位置;
如果该下标在上一个最长子串起始位置之后,则新的子串是从该下标之后开始的。
于是类似LIS,对于每个当前的元素,我们“回头”去查询是否有与之重复的,
如没有,则最长不重复子串长度+1,
如有,则考察上一个子串起始位置与重复字符下标的关系,
当然,如果DP使用O(n^2)的方案,则我们只需在内层循环遍历到上一个最长子串的起始位置即可,
O(N^2)的DP方案,我们可以与LIS的DP方案进行对比,是一个道理的。
DP + Hash 方案
上面的DP方案是O(n^2)的,之所以是n^2,是因为“回头”去寻找重复元素的位置了,受启发于最初的Hash思路,
我们可以用hash记录元素是否出现过,我们当然也可以用hash记录元素出现过的下标,
既然这样,在DP方案中,我们何不hash记录重复元素的位置,这样就不必“回头”了,
而时间复杂度必然降为O(N),只不过需要一个辅助的常数空间visit[256],典型的空间换时间。
这样遍历一遍便可以找到最长不重复子串
DP + Hash 优化方案
写到这里,还是有些别扭,因为辅助的空间多了,是不是还能优化,仔细看DP最优子问题解的更新方程:
1
dp[i] = dp[i-1] + 1;
dp[i-1]不就是更新dp[i]当前的最优解么?这与最大子数组和问题的优化几乎同出一辙,
我们不需要O(n)的辅助空间去存储子问题的最优解,而只需O(1)的空间就可以了,
至此,我们找到了时间复杂度O(N),辅助空间为O(1)(一个额外变量与256大小的散列表)的算法,
注意:当前最长子串的构成是与上一次最长子串相关的,故要记录上一次最长子串的起始位置!
*/
/*
图中的start是一个标志位,表示当前不重复子串的起始位置,
图中的数字表示记录字符出现位置的数组hashtable,
比如字符b出现在第1位,那么hashtable[‘b’]=1。
顺序扫描字符串,第4个位置时,在hashtable中发现b已经出现过(记出现的位置为k,此时k=1),
那么当前的不重复子串长度 = 当前位置-start;
下一个不重复子串就应该从第k+1个字符(2号位的c)开始,即令start = 2,
并且把[start, k)位置的字符对应的hashtable清空,重新设置b在hashtable的位置为4。
继续扫描直到再次发现相同的字符,和前面一样处理。
注意全部处理完字符串,还要判断一下末尾的不重复子串是否是最长的。
时间复杂度分析:最坏情况下,相当于遍历了两遍字符串,因此时间复杂度是O(n)
*/
//16ms
class Solution {
public:
int lengthOfLongestSubstring(string s) {
vector<int> bitmap(128, -1);
int res = 0;
int start = 0, lastStart = 0;
for(int i = 0; i < s.size(); i++)
{
if(bitmap[s[i]] != -1)
{
res = max(res, i-start);
lastStart = start;
start = bitmap[s[i]] + 1;
for(int j = lastStart; j < bitmap[s[i]]; j++)
bitmap[s[j]] = -1;
}
bitmap[s[i]] = i;
}
res = max(res, (int)s.size()-start);//不要忘了最后的判断
return res;
}
};
//很巧妙地解法 16ms
class Solution {
public:
int lengthOfLongestSubstring(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int locs[256];//保存字符上一次出现的位置
memset(locs, -1, sizeof(locs));
int idx = -1, max = 0;//idx为当前子串的开始位置-1
for (int i = 0; i < s.size(); i++)
{
if (locs[s[i]] > idx)//如果当前字符出现过,那么当前子串的起始位置为这个字符上一次出现的位置+1
{
idx = locs[s[i]];
}
if (i - idx > max)
{
max = i - idx;
}
locs[s[i]] = i;
}
return max;
}
}; | true |
4842c06e1ce810b2e00aa54764eec0c2fee23392 | C++ | ReddyArunreddy/RummyGame | /Main.cpp | UTF-8 | 3,155 | 3.28125 | 3 | [] | no_license | #include <iostream>
#include "cards.h"
#include "player.h"
#include "table.h"
#define CARDS_DEALT 13
#define EVEN_ODD 2
bool is_genuine_show;
void PlayGame();
void DealDeck(Player &, Player &, Cards &);
int main(int argc, char *argv[])
{
std::cout << "Welcome to RummyGame:\n";
PlayGame();
return 0;
}
void PlayGame()
{
std::string name;
std::cout << "Enter player1 name: ";
std::getline(std::cin, name);
Player player1(name);
std::cout << "Enter player2 name: ";
std::getline(std::cin, name);
Player player2(name);
Cards deck;
// Initialize the deck and shuffle...
deck.InitTheDeck();
deck.ShuffleDeck();
// Clear the player hand and melded cards...
player1.ClearHandandMeldedCards();
player2.ClearHandandMeldedCards();
DealDeck(player1, player2, deck);
deck.SetJokerCard();
player1.InitialHandSort();
player2.InitialHandSort();
unsigned int turn = 0;
int show_hand = 0;
while (1)
{
if (turn % EVEN_ODD == 0)
{
player1.play(deck);
std::cout << "Want to show your hand? press 1.\n";
std::cin >> show_hand;
if (show_hand == YES)
{
player1.SetShowValue(true);
break;
}
}
else
{
player2.play(deck);
std::cout << "Want to show your hand? press 1.\n";
std::cin >> show_hand;
if (show_hand == YES)
{
player2.SetShowValue(true);
break;
}
}
//std::cin.get();
++turn;
}
if (player1.GetShowValue())
{
player1.Show(deck);
if (is_genuine_show)
{
std::cout << player2.GetName() << " Hand:\n";
player2.CalculateHandScore(deck);
std::cout << player2.GetName() << "'s score: " << player2.GetScore() << "\n";
}
else
{
std::cout << "\n\n\n" << player2.GetName() << " You won the game:\n\n\n";
}
player1.SetShowValue(false);
}
if (player2.GetShowValue())
{
player2.Show(deck);
if (is_genuine_show)
{
std::cout << player1.GetName() << " Hand:\n";
player1.CalculateHandScore(deck);
std::cout << player1.GetName() << "'s score: " << player1.GetScore() << "\n";
}
else
{
std::cout << "\n\n\n" << player1.GetName() << " Won the game:\n";
}
player2.SetShowValue(false);
}
}
void DealDeck(Player &player1, Player &player2, Cards &deck)
{
int i = 0;
while (i < EVEN_ODD * CARDS_DEALT)
{
player1.InsertCardIntoHand(deck.TopCardOfClosedDeck());
deck.PopCardFromClosedDeck();
i++;
player2.InsertCardIntoHand(deck.TopCardOfClosedDeck());
deck.PopCardFromClosedDeck();
i++;
}
deck.AddCardToOpenDeck();
deck.SetJokerCard();
} | true |
68d3b37bd77e8feb79a7f1510ec4791b6e031bef | C++ | xiaoqiangkx/cpp_primer | /exercise/chapter15/ex15_35.cpp | UTF-8 | 4,188 | 3.421875 | 3 | [] | no_license | #include <iostream>
#include <stdexcept>
#include <set>
using namespace std;
class Item_base {
public:
Item_base(const string& _isbn="", double _price=0.0)
: isbn(_isbn), price(_price) {}
const string& book() const {
return isbn;
}
virtual double net_price(size_t n) const {
return price * n;
}
virtual void debug(ostream &os = cout) const {
cout << "Item_base: isbn=" << isbn << ",price=" << price << endl;
}
virtual Item_base* clone() const {
return new Item_base(*this);
}
private:
string isbn;
protected:
double price;
};
class Bulk_item: public Item_base {
public:
Bulk_item(const string& _isbn="", double _price=0.0, double _discount=0.0, size_t _max_qty=1)
: Item_base(_isbn, _price), discount(_discount), max_qty(_max_qty) {}
virtual double net_price(size_t n) const {
if (n <= max_qty) {
return (1 - discount) * n * price;
} else {
return (n-max_qty) * price + max_qty * price * (1 - discount);
}
}
Bulk_item* clone() const {
return new Bulk_item(*this);
}
virtual void debug(ostream& os = cout) const {
cout << "Bulk_item: isbn=" << book() << ",price=" << price << endl;
cout << "dicont=" << discount << ", max_qty" << max_qty << endl;
}
virtual Bulk_item* clone() {
return new Bulk_item(*this);
}
private:
double discount;
size_t max_qty;
};
// 句柄类, 管理Item_base继承簇
class Sales_item {
public:
Sales_item(): ptr(NULL), use(new size_t(1)) {} // NULL considered as source
// use clone function to avoid pointer in user space
Sales_item(const Item_base& base)
: ptr(base.clone()), use(new size_t(1)) {
}
Sales_item& operator=(const Sales_item& rhs) {
++*use;
decr_use();
ptr = rhs.ptr;
use = rhs.use;
return *this;
}
Sales_item(const Sales_item& item): ptr(item.ptr), use(item.use) {
++*use;
}
~Sales_item() { decr_use(); }
const Item_base& operator*() const {
if (ptr)
return *ptr;
else
throw new logic_error("unbound Sales_item");
}
const Item_base* operator->() const {
if (ptr)
return ptr;
else
throw new logic_error("unbound Sales_item");
}
private:
Item_base* ptr;
size_t* use;
void decr_use() {
if (--*use == 0) {
delete ptr;
delete use;
}
}
};
inline bool compare(const Sales_item &lhs, const Sales_item &rhs) {
return lhs->book() < rhs->book();
}
class Basket {
typedef bool (*Comp)(const Sales_item &lhr, const Sales_item &rhs);
public:
typedef multiset<Sales_item, Comp> set_type;
typedef set_type::size_type size_type;
typedef set_type::const_iterator const_iter;
Basket(): items(compare) {}
size_type size(const Sales_item &i) const {
return items.count(i);
}
void add_item(const Sales_item &item) {
items.insert(item);
}
double total();
private:
multiset<Sales_item, Comp> items;
};
double Basket::total() {
double sum = 0.0;
for (const_iter iter = items.begin(); iter != items.end(); iter = items.upper_bound(*iter)) {
size_t n = size(*iter);
Sales_item sale_item = *iter;
sum += sale_item->net_price(n);
}
return sum;
}
int main() {
Bulk_item bulk_item("Dream", 2.2, 0.5, 5);
Item_base base_item("Hello", 1.0);
Basket basket;
for (int i=0; i<12; i++) {
basket.add_item(bulk_item);
}
for (int i=0; i<5; i++) {
basket.add_item(base_item);
}
double sum = basket.total();
cout << "sum=" << sum << endl;
return 0;
}
| true |