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 |
---|---|---|---|---|---|---|---|---|---|---|---|
ebcf1636c0931043f35eb7dfc3e04fa22e213ea8
|
C++
|
Saqib-Sizan-Khan/Data_Structure
|
/Stack/Postfix Expression.cpp
|
UTF-8
| 2,091 | 3.625 | 4 |
[] |
no_license
|
#include<bits/stdc++.h>
using namespace std;
string ConvertPostfix(string exp);
bool IsOperator(char c);
bool IsOperand(char c);
int Priority(char op1,char op2);
int GetWeight(char op);
int IsRightAssociative(char op);
int main()
{
string exp;
cout<<"Enter an Infix Expression:"<<endl;
getline(cin,exp);
string postfix = ConvertPostfix(exp);
cout<<postfix<<endl;
}
string ConvertPostfix(string exp)
{
stack<char> s;
string postfix = "";
for(int i=0;i<exp.size();i++)
{
if(exp[i]==' ' || exp[i]==',')continue;
else if(IsOperator(exp[i]))
{
while(!s.empty() && exp[i]!='(' && Priority(s.top(),exp[i]))
{
postfix += s.top();
s.pop();
}
s.push(exp[i]);
}
else if(IsOperand(exp[i]))
{
postfix += exp[i];
}
else if(exp[i]==')')
{
while(!s.empty() && s.top()=='(')
{
postfix += s.top();
s.pop();
}
s.pop();
}
else if(exp[i]=='(')
{
s.push(exp[i]);
}
}
while(!s.empty())
{
postfix += s.top();
s.pop();
}
return postfix;
}
bool IsOperator(char c)
{
if(c=='+' || c=='-' || c=='*' || c=='/' || c=='$')return true;
return false;
}
bool IsOperand(char c)
{
if(c>='0' && c<='9')return true;
if(c>='A' && c<='Z')return true;
if(c>='a' && c<='z')return true;
return false;
}
int Priority(char op1,char op2)
{
int op1weight = GetWeight(op1);
int op2weight = GetWeight(op2);
if(op1weight==op2weight)
{
if(IsRightAssociative(op1))return false;
else return true;
}
return op1weight > op2weight ? true:false;
}
int GetWeight(char op)
{
int weight = 0;
if(op=='+' || op=='-')return weight=1;
else if(op=='/' || op=='*')return weight=2;
else if(op=='$')return weight=3;
}
int IsRightAssociative(char op)
{
if(op == '$') return true;
return false;
}
| true |
403ebb359177a62a9e903ed3e5ff91715b643b94
|
C++
|
TobyNartowski/AllegroEngine
|
/src/Drawer.cpp
|
UTF-8
| 6,879 | 2.953125 | 3 |
[] |
no_license
|
#include "Drawer.hpp"
#include "Logger.hpp"
#include <allegro5/allegro_primitives.h>
#include <cmath>
Drawer::Drawer(ALLEGRO_DISPLAY *display, int width, int height) {
this->width = width;
this->height = height;
this->display = display;
background = al_load_bitmap(BACKGROUND_PATH);
if (!background) {
Logger::getLogger().logError("Failed to load background image");
}
font = al_load_ttf_font(FONT_PATH, 32, 0);
}
void Drawer::fillBackground(Color *color) {
al_clear_to_color(color->getAllegroColor());
}
void Drawer::drawBackground() {
al_draw_scaled_bitmap(background, 0, 0, 1800, 1200, 0, 0, width, height, 0);
}
void Drawer::drawPoint(Point *point, Color *color) {
al_draw_pixel(point->getX(), point->getY(), color->getAllegroColor());
}
void Drawer::drawPoints(std::vector<Point*> points, Color *color) {
for (auto point : points) {
al_draw_pixel(point->getX(), point->getY(), color->getAllegroColor());
}
}
void Drawer::drawRectangle(Point *upperLeftPoint, Point *lowerRightPoint, Color *color, float thickness) {
if (thickness != 0.0) {
al_draw_rectangle(upperLeftPoint->getX(), upperLeftPoint->getY(), lowerRightPoint->getX(),
lowerRightPoint->getY(), color->getAllegroColor(), thickness);
} else {
al_draw_filled_rectangle(upperLeftPoint->getX(), upperLeftPoint->getY(), lowerRightPoint->getX(),
lowerRightPoint->getY(), color->getAllegroColor());
}
}
void Drawer::drawTriangle(Point *upperPoint, Point *leftPoint, Point *rightPoint, Color *color, float thickness) {
if (thickness != 0.0) {
al_draw_triangle(upperPoint->getX(), upperPoint->getY(), leftPoint->getX(), leftPoint->getY(),
rightPoint->getX(), rightPoint->getY(), color->getAllegroColor(), thickness);
} else {
al_draw_filled_triangle(upperPoint->getX(), upperPoint->getY(), leftPoint->getX(), leftPoint->getY(),
rightPoint->getX(), rightPoint->getY(), color->getAllegroColor());
}
}
void Drawer::drawEllipse(Point *center, int radiusX, int radiusY, Color *color, float thickness) {
if (thickness != 0.0) {
al_draw_ellipse(center->getX(), center->getY(), radiusX, radiusY, color->getAllegroColor(), thickness);
} else {
al_draw_filled_ellipse(center->getX(), center->getY(), radiusX, radiusY, color->getAllegroColor());
}
}
void Drawer::drawCircle(Circle *circle, Color *color, float thickness) {
if (thickness != 0.0) {
al_draw_circle(circle->getX(), circle->getY(), circle->getRadius(), color->getAllegroColor(), thickness);
} else {
al_draw_filled_circle(circle->getX(), circle->getY(), circle->getRadius(), color->getAllegroColor());
}
}
void Drawer::drawMultipleLines(std::vector<LineSegment*> lines, Color *color) {
for (auto line : lines) {
drawLine(line, color);
}
}
void Drawer::helpDrawLine(int x, int x2, int x3, int xi, int y, int y3, int yi, int flag, Color *color) {
int t1 = (y3 - x3) * 2;
int t2 = y3 * 2;
int t3 = t2 - x3;
while (x != x2) {
if (t3 >= 0) {
x += xi;
y += yi;
t3 += t1;
} else {
t3 += t2;
x += xi;
}
if (flag == 0) {
al_draw_pixel(x, y, color->getAllegroColor());
} else {
al_draw_pixel(y, x, color->getAllegroColor());
}
}
}
void Drawer::drawLine(LineSegment *line, Color *color) {
int x1 = line->getFirstPoint()->getX();
int y1 = line->getFirstPoint()->getY();
int x2 = line->getSecondPoint()->getX();
int y2 = line->getSecondPoint()->getY();
int x3, y3, xi, yi;
int x = x1, y = y1;
xi = (x1 < x2) ? 1 : -1;
x3 = (x1 < x2) ? (x2 - x1) : (x1 - x2);
yi = (y1 < y2) ? 1 : -1;
y3 = (y1 < y2) ? (y2 - y1) : (y1 - y2);
al_draw_pixel(x,y, color->getAllegroColor());
if (x3 > y3) {
helpDrawLine(x, x2, x3, xi, y, y3, yi, 0, color);
} else {
helpDrawLine(y, y2, y3, yi, x, x3, xi, 1, color);
}
}
void Drawer::drawViewport(Viewport *viewport, Color *color) {
drawRectangle(viewport->getUpperLeft(), viewport->getLowerRight(), color, 1.0);
}
void Drawer::drawPlayer(Player *player) {
int x = player->getPosition()->getX();
int y = player->getPosition()->getY();
int r = player->getSize() / 2;
al_draw_filled_circle(x, y, r, al_map_rgb(255, 255, 255));
}
void Drawer::drawEnemy(Enemy *enemy) {
int r = enemy->getSize();
int x = enemy->getPosition()->getX() - (r / 2);
int y = enemy->getPosition()->getY() - (r / 2);
al_draw_scaled_bitmap(enemy->getBitmap(), 0, 0, 420, 420, x, y, r, r, 0);
}
void Drawer::drawCrosshair(Player *player) {
al_draw_circle(player->getCrosshairPosition()->getX(), player->getCrosshairPosition()->getY(), 3, al_map_rgb(255, 0, 0), 1.2);
}
void Drawer::drawBoundingBox(BoundingBox *boundingBox) {
Point *center = boundingBox->getCenterPoint();
float width = boundingBox->getWidth();
float height = boundingBox->getHeight();
Point *upperLeft = new Point(center->getX() - (width / 2.0), center->getY() - (height / 2.0));
Point *lowerRight = new Point(center->getX() + (width / 2.0), center->getY() + (height / 2.0));
drawRectangle(upperLeft, lowerRight, boundingBox->getColor(), 1.0);
}
void Drawer::drawBullet(Bullet *bullet, Color *color) {
// drawPoint(bullet->getPosition(), color);
drawRectangle(new Point(bullet->getPosition()->getX() - 1, bullet->getPosition()->getY() - 1),
new Point(bullet->getPosition()->getX() + 1, bullet->getPosition()->getY() + 1), color, 0.0);
}
void Drawer::drawRectangle(Rectangle *rectangle) {
Point *center = rectangle->getCenterPoint();
float width = rectangle->getWidth();
float height = rectangle->getHeight();
Point *upperLeft = new Point(center->getX() - (width / 2.0), center->getY() - (height / 2.0));
Point *lowerRight = new Point(center->getX() + (width / 2.0), center->getY() + (height / 2.0));
drawRectangle(upperLeft, lowerRight, rectangle->getColor(), 0.0);
}
void Drawer::drawRectangle(std::vector<Rectangle*> rectangles) {
for (auto rect : rectangles) {
drawRectangle(rect);
}
}
void Drawer::drawScore(int score) {
al_draw_text(font, al_map_rgb(255, 255, 255), 32, 32, ALLEGRO_ALIGN_LEFT, ("Score: " + std::to_string(score)).c_str());
}
void Drawer::drawHp(int hp, int fullHp) {
Color *color;
if (hp <= 25) {
color = new Color(255, 0, 0);
} else if (hp <= 50) {
color = new Color(255, 192, 0);
} else if (hp <= 75) {
color = new Color(192, 255, 0);
} else {
color = new Color(0, 255, 0);
}
drawRectangle(new Point(width - 148, 32), new Point(width - 48, 64), new Color(255, 255, 255), 1.0);
drawRectangle(new Point(width - 148, 33), new Point((width - 48) - (fullHp - hp), 62), color, 0.0);
}
void Drawer::drawGameOver(int score) {
std::string first = "Game Over";
std::string second = "Your score: " + std::to_string(score);
al_draw_text(font, al_map_rgb(255, 255, 255), width / 2 - (first.length() / 2), height / 2 - 64, ALLEGRO_ALIGN_CENTER, first.c_str());
al_draw_text(font, al_map_rgb(255, 255, 255), width / 2 - (second.length() / 2), height / 2 - 24, ALLEGRO_ALIGN_CENTER, second.c_str());
}
| true |
8140b7662cf0ebc148063fb35d712f1d4c8dffc3
|
C++
|
cibercitizen1/zmqHelper
|
/examples/01-REQ-REP/clientREQ.cpp
|
UTF-8
| 1,197 | 2.671875 | 3 |
[
"MIT"
] |
permissive
|
// -----------------------------------------------------------------
// clientREQ.cpp
// -----------------------------------------------------------------
#include <zmq.hpp>
#include <string>
#include <iostream>
#include "../../zmqHelper.hpp"
// -----------------------------------------------------------------
// -----------------------------------------------------------------
int main ()
{
using namespace zmqHelper;
std::vector<std::string> lines;
const int N = 10;
std::cerr << "client starts ... \n" << std::flush;
SocketAdaptor< ZMQ_REQ > sa;
sa.connect ("tcp://localhost:5555");
// Do 10 requests, waiting each time for a response
int i;
for (i = 1; i <= N; i++) {
std::cout << " i = " << i << "\n";
// Send the request
std::vector<std::string> multi = { "Hallo Hallo", "Hello Hello" };
sa.sendText ( multi );
// Get the reply.
sa.receiveText (lines); // ignoring bool returned. Guess it's true
std::cout << " received -------- \n";
for ( auto s : lines ) {
std::cout << s << "\n";
}
std::cout << " ----------------- \n";
} // for
assert (i = N+1);
std::cout << " OK \n" << std::flush;
sa.close ();
return 0;
} // main ()
| true |
ae8c8b73b4496f0d7606ef8e75aedee1d7f44f33
|
C++
|
patsko-loo/Snake
|
/Header Files/cell.h
|
UTF-8
| 302 | 2.640625 | 3 |
[] |
no_license
|
#ifndef _CELL_H_
#define _CELL_H_
#include "info.h" //info.h contains Row and Col of a cell, pluss the enum statetype: {Snake,empty,food}
class Cell {
private:
Info info;
public:
Cell(Info temp);
Info getInfo();
void setInfo(Info s);
};
#endif
| true |
2b6bbd6810852581dcb1af6cba3f0e28118b397c
|
C++
|
jlubea/propelize
|
/src/propelize/algorithms/gpu/dilation.cpp
|
UTF-8
| 3,366 | 2.5625 | 3 |
[] |
no_license
|
#include "propelize/algorithms/gpu/dilation.h"
#include "propelize/algorithms/color_channels.h"
#include "substasics/platform/exceptions.h"
namespace cn = concurrency;
namespace sp = substasics::platform;
namespace propelize { namespace algorithms { namespace gpu {
void Dilation::operator()(concurrency::array<uint32_t, 2> &image, concurrency::array<uint32_t, 2> &output)
{
static const char *func = "Dilation::()";
int filterXMid = _kernel.extent[0] / 2;
int filterYMid = _kernel.extent[1] / 2;
int maxX = image.extent[1] - filterXMid;
int maxY = image.extent[0] - filterYMid;
// these can be negative for very small images.
if (maxX < 0 || maxY < 0)
{
throw sp::exception(func, "Image is too small for dilation with kernel dimensions: (%d, %d)", _kernel.extent[0], _kernel.extent[1]);
}
else
{
cn::parallel_for_each(
image.accelerator_view,
image.extent,
[=, &image, &output](cn::index<2> idx) restrict(amp)
{
int r = static_cast<int>(idx[0]);
int c = static_cast<int>(idx[1]);
// if the dilation kernel doesn't fit in the image at the current position
if ((r - filterYMid) < 0
|| (c - filterXMid) < 0
|| (r + filterYMid) >= image.extent[0]
|| (c + filterXMid) >= image.extent[1])
{
output[idx] = 0;
}
// apply the dilation kernel
else
{
uint32_t maxRed = 0, maxGrn = 0, maxBlu = 0, maxAlpha = 0;
// apply the filter to a local region
for (int y = 0; y < _kernel.extent[0]; ++y)
for (int x = 0; x < _kernel.extent[1]; ++x)
{
if (_kernel(y, x) == 0) continue;
int dx = -filterXMid + x;
int dy = -filterYMid + y;
uint32_t sourceP = image(r + dy, c + dx);
uint32_t red = GET_RED(sourceP);
uint32_t grn = GET_GRN(sourceP);
uint32_t blu = GET_BLU(sourceP);
uint32_t alpha = GET_ALPHA(sourceP);
maxRed = max(red, maxRed);
maxGrn = max(grn, maxGrn);
maxBlu = max(blu, maxBlu);
maxAlpha = max(alpha, maxAlpha);
}
output[idx] = BUILD_RGBA(maxRed, maxGrn, maxBlu, maxAlpha);
}
}
);
// Extend border. We don't want to fill with black in case we do something like edge detection in a later algorithm.
// In the future this fill policy will be configurable.
// replace the left and right borders
cn::extent<2> lrExt(image.extent[0], filterXMid);
cn::parallel_for_each(
image.accelerator_view,
lrExt,
[=, &image, &output](cn::index<2> idx) restrict(amp)
{
uint32_t leftSourceP = output(idx[0], filterXMid);
uint32_t rightSourceP = output(idx[0], image.extent[1]-1 - filterXMid);
output(idx[0], filterXMid - (idx[1] + 1)) = leftSourceP;
output(idx[0], (image.extent[1]-1 - filterXMid) + (idx[1] + 1)) = rightSourceP;
}
);
// replace the top and bottom borders
cn::extent<2> tbExt(image.extent[1], filterYMid);
cn::parallel_for_each(
image.accelerator_view,
tbExt,
[=, &image, &output](cn::index<2> idx) restrict(amp)
{
uint32_t topSourceP = output(filterYMid, idx[0]);
uint32_t bottomSourceP = output(image.extent[0]-1 - filterYMid, idx[0]);
output(filterYMid - (idx[1] + 1), idx[0]) = topSourceP;
output((image.extent[0]-1 - filterYMid) + (idx[1] + 1), idx[0]) = bottomSourceP;
}
);
}
}
}
}
}
| true |
540e2197bf6013ebeb3058e347c709927da88bfc
|
C++
|
JanneRemes/janityengine
|
/JanneRemesEngine/Libraries/JanityMath/Source/Point.cpp
|
UTF-8
| 2,090 | 3.4375 | 3 |
[] |
no_license
|
#include <JanityMath\Point.h>
#include <JanityMath\MathUtils.h>
using namespace JanityMath;
Point::Point() : x(0), y(0){}
Point::Point(float X, float Y) : x(X), y(Y){}
Point::~Point(){}
Point::Point(const Point& other) : x(other.x), y(other.y){}
// Public
Point Point::maximum(const Point& point) const
{
const int _x = JanityMath::maximum(x, point.x);
const int _y = JanityMath::maximum(y, point.y);
return Point(_x, _y);
}
Point Point::minimum(const Point& point) const
{
const int _x = JanityMath::minimum(x, point.x);
const int _y = JanityMath::minimum(y, point.y);
return Point(_x, _y);
}
// Static
Point Point::zero()
{
return Point(0, 0);
}
// Operators
Point& Point::operator= (const Point& rhs)
{
this->x = rhs.x;
this->y = rhs.y;
}
Point& Point::operator+= (const Point& rhs)
{
this->x = this->x + rhs.x;
this->y = this->y + rhs.y;
}
Point& Point::operator+ (const Point& rhs)
{
return operator+=(rhs);
}
Point& Point::operator+= (int value)
{
this->x = this->x + value;
this->y = this->y + value;
}
Point& Point::operator+ (int value)
{
return operator+(value);
}
Point& Point::operator-= (int value)
{
this->x = this->x- value;
this->y = this->y - value;
}
Point& Point::operator- (int value)
{
return operator-=(value);
}
Point& Point::operator*= (int scalar)
{
this->x = this->x * scalar;
this->y = this->y * scalar;
}
Point& Point::operator* (int scalar)
{
return operator*=(scalar);
}
Point& Point::operator/= (int divisor)
{
if(divisor!=0)
{
this->x = this->x / divisor;
this->y = this->y / divisor;
}
else
{
std::printf("Error: Point/= 0");
}
}
Point& Point::operator/ (int divisor)
{
return operator/=(divisor);
}
bool operator== (const Point& lhs, const Point& rhs)
{
float x = lhs.x;
if(lhs.x == rhs.x && lhs.y == rhs.y)
return true;
else
return false;
}
bool operator!= (const Point& lhs, const Point& rhs)
{
if(lhs.x == rhs.x && lhs.y == rhs.y)
return false;
else
return true;
}
std::ostream& operator<< (std::ostream& output, const Point& point)
{
return output << "[" << point.x << "," << point.y << "]";
}
| true |
4282542728bed57d6ceae8d55f198ead243581ac
|
C++
|
Sayaten/StudyCPP
|
/DesignPattern/CommandPattern/CPStereo.cpp
|
UTF-8
| 587 | 2.9375 | 3 |
[] |
no_license
|
#include "CPStereo.hpp"
#include <iostream>
#include <string>
using namespace std;
Stereo::Stereo(string place)
{
vol = 0;
this -> place = place;
}
void Stereo::on()
{
cout << place << " Stereo On" << endl;
}
void Stereo::off()
{
cout << place << " Stereo Off" << endl;
}
void Stereo::setCD()
{
cout << place << " Stereo Set CD" << endl;
}
void Stereo::removeCD()
{
cout << place << " Stereo Remove CD" << endl;
}
void Stereo::setVolume(float vol)
{
this -> vol = vol;
cout << place << " Stereo Set Volume " << vol << endl;
}
string Stereo::toString()
{
return place;
}
| true |
81895a3d2639b285bc628b4e9bc11a92c8e60c15
|
C++
|
TrevorNewell/RayTracer
|
/MyVectorClass/Vector/Point/Point.h
|
UTF-8
| 806 | 2.875 | 3 |
[] |
no_license
|
// Point.h
// Author: Trevor Newell
// 11/6/2016
#pragma once
#ifndef stdio_h_Included
#define stdio_h_Included
#include <stdio.h>
#endif // !stdio.h_Included
#ifndef tchar_h_Included
#define tchar_h_Included
#include <tchar.h>
#endif // !tchar.h_Included
#ifndef iostream_Included
#define iostream_Included
#include <iostream>
#endif // !iostream_Included
#ifndef ostream_Included
#define ostream_Included
#include <ostream>
#endif // !ostream_Included
class Point
{
public:
Point(); // constructor
Point(float x, float y, float z); // constructor
Point(const Point& copyFrom); //copy constructor
Point operator=(const Point copy_from); //copy assignment
~Point(); // destructor
float x;
float y;
float z;
void PrintPoint(char* prefixWith) const;
private:
};
| true |
1ef7639d7e06d3216fd53cf5da231f4ea9e0f063
|
C++
|
mady4ever/Preparation
|
/revision/questions/huffman-coding.cpp
|
UTF-8
| 2,914 | 3.515625 | 4 |
[] |
no_license
|
/*
https://www.geeksforgeeks.org/huffman-coding-greedy-algo-3/
use max heap to get the elements with there frquency.
create max heap with frequency and elements.
while heap is not empty insert root/top node to the binary tree.
now travers the tree and create huffman code.
*/
#include<bits/stdc++.h>
using namespace std;
typedef struct Node{
char d;
int f;
Node *l;
Node *r;
}Node;
Node *makeNode(char d,int f)
{
Node *t = (Node *)malloc(sizeof(Node));
t->l = t->r = NULL;
t->d = d;
t->f = f;
return t;
}
void LogData(Node *t)
{
cout<<endl;
cout<<t->d<<"\t"<<t->f<<"\t";
}
Node *buildHuffman(char a[],int f[],int s)
{
auto comp=[](Node *a,Node *b){return a->f < b->f;};
priority_queue<Node*,vector<Node*>,decltype(comp)> pq(comp); // min heap.
for(int i=0;i<s;i++)
{
Node *t = makeNode(a[i],f[i]);
//LogData(t);
pq.push(t);
}
//while(!pq.empty())
//{
// Node *t = pq.top();
// pq.pop();
// LogData(t);
//}
while(pq.size()>1)
{
// int d=0;
// Node *l = pq.top();
// pq.pop();
// Node *r=NULL;
// d+=l->f;
// if(pq.size()>=1)
// {
// r = pq.top();
// pq.pop();
// d+=r->f;
// }
// Node *m = makeNode('$',d);
// m->l=l;
// m->r=r;
// pq.push(m);
//LogData(m);
Node *l = pq.top();
pq.pop();
Node *r = pq.top();
pq.pop();
Node *m = makeNode('$',l->f + r->f);
m->l = l;
m->r = r;
pq.push(m);
}
Node *result = pq.top();
pq.pop();
return pq.size()==0 ? result:NULL;
}
void InOrder(Node *r)
{
if(r)
{
InOrder(r->l);
LogData(r);
InOrder(r->r);
}
}
void LevelOrderTraversal(Node *r)
{
if(r==NULL) return;
list<Node *> q;
q.push_back(r);
int size=q.size();
while(!q.empty())
{
size = q.size();
while(size)
{
Node *t = q.front();
q.pop_front();
cout<<t->d<<"\t";
if(t->l)
q.push_back(t->l);
if(t->r)
q.push_back(t->r);
size--;
}
cout<<endl;
}
}
void huffmanCodes(Node *r, string output)
{
if(r==NULL)
{
//cout<<output<<endl;
return;
}
huffmanCodes(r->l,"0"+output);
huffmanCodes(r->r,"1"+output);
if(r->l == NULL && r->r == NULL)
{
//LogData(r);
cout<<output<<endl;
return;
}
}
void codes(Node *r,int arr[],int index)
{
if(r->l)
{
arr[index] = 0;
codes(r->l,arr,index+1);
}
if(r->r)
{
arr[index] = 1;
codes(r->r,arr,index+1);
}
if(r->l==NULL && r->r==NULL)
{
for(int i=0;i<5;i++)
{
cout<<arr[i];
}
cout<<endl;
}
}
int main()
{
char arr[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
int freq[] = { 5, 9, 12, 13, 16, 45 };
int size = sizeof(arr) / sizeof(arr[0]);
Node *m = buildHuffman(arr,freq,size);
//InOrder(m);
//LevelOrderTraversal(m);
//huffmanCodes(m,"");
int arrr[]={0,0,0,0,0};
codes(m,arrr,0);
return 0;
}
| true |
d00b474c04033c82c285bdc074de56067312f35d
|
C++
|
USArmyResearchLab/Fusion3D
|
/include/Fusion3D/osus_image_store_class.h
|
UTF-8
| 917 | 2.640625 | 3 |
[
"Apache-2.0"
] |
permissive
|
#ifndef _osus_image_store_class_h_
#define _osus_image_store_class_h_
#ifdef __cplusplus
/**
Provides storage for images that are defined in screen coordinates (always staying same size regardless of zoom).
Images are created and stored internally. They can then be retrieved by image index.
*/
class osus_image_store_class{
private:
int n_images; ///< No. of images currently stored
int n_images_max; ///< Max no. of images that can be stored -- hardwired to 100
SoSeparator** cameraImagesBase; ///< Per image stored, base of tree
public:
osus_image_store_class();
~osus_image_store_class();
int make_sensor_image_screen(float scaleFactor, int image_nx, int image_ny, int image_np, unsigned char *image_data);
SoSeparator* get_image_subtree(int index);
};
#endif /* __cplusplus */
#endif /* _osus_image_store_class_h_ */
| true |
72136c8c9c91a2ce7995c92ef781d1be1b04306d
|
C++
|
kanha95/SPOJ-solutions
|
/IITKWPCB.cpp
|
UTF-8
| 322 | 2.609375 | 3 |
[] |
no_license
|
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstdio>
using namespace std;
int main()
{
long long t;
cin>>t;
while(t--)
{
long long n;
cin>>n;
if(n==1)
cout<<"0"<<endl;
else
{
long long i;
for(i=n/2;i>=1;i--)
{
if(__gcd(n,i)==1)
break;
}
cout<<i<<endl;
}
}
}
| true |
520e679005511cf1fa32fdde3244a8f0f375ad92
|
C++
|
cshung/Competition
|
/Competition/LEET_GOAT_LATIN.cpp
|
UTF-8
| 2,100 | 3.203125 | 3 |
[] |
no_license
|
#include "stdafx.h"
// https://leetcode.com/problems/goat-latin/
#include "LEET_GOAT_LATIN.h"
#include <map>
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
using namespace std;
namespace _LEET_GOAT_LATIN
{
class Solution
{
public:
string toGoatLatin(string S)
{
string vowels = "aeiouAEIOU";
vector<char> w;
int i = 0;
int count = 0;
ostringstream oss;
for (int i = 0; i <= S.length(); i++)
{
char c = i == S.length() ? ' ' : S[i];
if (c == ' ')
{
if (count != 0)
{
oss << " ";
}
bool move = vowels.find(w[0]) == string::npos;
bool first = true;
for (auto wc : w)
{
if (first)
{
first = false;
if (!move)
{
oss << wc;
}
}
else
{
oss << wc;
}
}
if (move)
{
oss << w[0];
}
oss << "ma";
count++;
for (int j = 0; j < count; j++)
{
oss << "a";
}
w.clear();
}
else
{
w.push_back(c);
}
}
return oss.str();
}
};
};
using namespace _LEET_GOAT_LATIN;
int LEET_GOAT_LATIN()
{
Solution solution;
cout << solution.toGoatLatin("I speak Goat Latin") << endl;
cout << solution.toGoatLatin("The quick brown fox jumped over the lazy dog") << endl;
return 0;
}
| true |
a2f9231eca46053338c2d9aad302bdb8b7dfe08c
|
C++
|
KORYUOH/koryuohproject-svn-server
|
/2013TGS07班/TGS_Team7_Projects_Ver1.17/TGS_Team7_Projects/Souse/Managers/Food.h
|
SHIFT_JIS
| 2,672 | 2.9375 | 3 |
[] |
no_license
|
/******************************************************************************
* File Name : FoodManager.h Ver : 1.00 Date : 2013-05-13
*
* Description :
*
* HǗ҃NXD
*
******************************************************************************/
#ifndef _FOOD_MANAGER_H_
#define _FOOD_MANAGER_H_
/*---- wb_t@C̓ǂݍ ---------------------------------------------*/
#include<map>
/*---- s錾 -------------------------------------------------------------*/
class Unit;
class UnitParameter;
class UnitHierarchy;
typedef std::map<Unit*, float> FoodContainer;
/// <summary>
/// lފǗ.
/// </summary>
class FoodManager
{
public:
/// <summary>
/// RXgN^.
/// </summary>
/// <param name="parameter">p[^</param>
FoodManager();
/// <summary>
/// .
/// </summary>
void Initialize();
/// <summary>
/// lނ̍őlXV.
/// </summary>
/// <param name="unit">jbg</param>
void HumanUpdate( Unit* unit );
/// <summary>
/// lނ̍őlXV.
/// </summary>
/// <param name="unit">jbg</param>
/// <param name="hierarchy">Kw</param>
void HumanUpdate( Unit* unit, UnitHierarchy& hierarchy );
/// <summary>
/// H̒lj.
/// </summary>
/// <param name="unit">jbg</param>
void Add( Unit* unit );
/// <summary>
/// łƂ肷.
/// </summary>
/// <param name="unit">jbg</param>
/// <param name="food"></param>
/// <returns>ł鎞^AłȂUԂ.</returns>
bool IsAccess( Unit* unit, float food ) const;
/// <summary>
/// lނ.
/// </summary>
/// <param name="my">jbg</param>
/// <param food="food"></param>
/// <returns>ړłΐ^AłȂUԂ.</returns>
bool Fluctuation( Unit* my, float food );
/// <summary>
/// lނړ.
/// </summary>
/// <param name="my">ړjbg</param>
/// <param name="target">ړ惆jbg</param>
/// <param name="food"></param>
/// <returns>ړłΐ^AłȂUԂ.</returns>
bool Fluctuation( Unit* my, Unit* target, float food );
/// <summary>
/// .
/// </summary>
void Clear();
private:
/// <summary>
/// HRei.
/// </summary>
FoodContainer mFoodContainer;
};
#endif // !_HUMAN_MANAGER_H_
/********** End of File ******************************************************/
| true |
10605862ed0404f14c89039f031734a27b9b39ee
|
C++
|
nvladimus/ArduinoRotaryEncoderPCB
|
/examples/RotaryEncoder_PushButton/RotaryEncoder_PushButton.ino
|
UTF-8
| 1,001 | 2.78125 | 3 |
[
"MIT"
] |
permissive
|
#include <Encoder.h> //encoder library https://www.pjrc.com/teensy/td_libs_Encoder.html
// Change these two numbers to the pins connected to your encoder.
// Best Performance: both pins have interrupt capability
// Good Performance: only the first pin has interrupt capability
// Low Performance: neither pin has interrupt capability
Encoder myEnc(2,3);
// avoid using pins with LEDs attached
// set up the button action of the rotary encoder shaft
int buttonState = LOW;
int pinButton = 4;
void setup() {
Serial.begin(115200);
Serial.println("Basic Encoder Test:");
pinMode(pinButton, INPUT);
}
long oldPosition = -999;
void loop() {
long newPosition = myEnc.read();
if (newPosition != oldPosition) {
oldPosition = newPosition;
Serial.println(newPosition);
}
//read the button state
int reading = digitalRead(pinButton);
if(reading != buttonState){
buttonState = reading;
if(buttonState == HIGH){
Serial.println("button pressed");
}
}
}
| true |
335df224eccecb15dc007d82bc21c63c395e3996
|
C++
|
wbpcode/simplecache
|
/scache/cache-base.h
|
UTF-8
| 1,061 | 2.953125 | 3 |
[] |
no_license
|
#pragma once
#include <string>
enum CacheType { DictType, ListType, LongType, StringType };
using int64 = long long;
class CacheBase {
private:
const CacheType m_type;
protected:
CacheBase(CacheType t) :m_type(t) { ; }
virtual ~CacheBase() = default;
public:
CacheType getType();
friend void delInstance(CacheBase* base);
};
class CacheValue : public CacheBase {
private:
void *m_value = nullptr;
public:
CacheValue(CacheType valueType)
: CacheBase(valueType) { ; }
virtual ~CacheValue();
std::string getValue();
void setValue(std::string value);
};
template<class T> T* getInstance(CacheType type) {
switch (type) {
case StringType:
return (T*)(new CacheValue(StringType));
case LongType:
return (T*)(new CacheValue(LongType));
case ListType:
return (T*)(new CacheList<CacheValue*>());
case DictType:
return (T*)(new CacheDict<std::string,
CacheValue*>());
default:
return nullptr;
}
}
void delInstance(CacheBase* base);
| true |
bd4355e6f2327c72149efd7d19fb867fb35681ab
|
C++
|
greenfox-zerda-sparta/nagyzsuska
|
/week6/Day-1/09/MyStack.h
|
UTF-8
| 366 | 3 | 3 |
[] |
no_license
|
#ifndef MYSTACK_H_
#define MYSTACK_H_
#include <string>
const int m_index = 5;
class MyStack {
private:
int m_top = -1;
int m_stack[m_index];
public:
MyStack();
~MyStack();
enum MyErrorMessages {
STACK_IS_FULL,
STACK_IS_EMPTY
};
void Push(int x);
void Pop();
std::string interpretException(MyErrorMessages x);
};
#endif /* MYSTACK_H_ */
| true |
e24e495a0a4b13fa44b4a387f4bf8c4d0e10747b
|
C++
|
ljordan51/odysseus
|
/ZeroingTest/ZeroingTest.ino
|
UTF-8
| 3,747 | 2.546875 | 3 |
[] |
no_license
|
#include <EEPROM.h>
#include "FlexyStepper.h"
//
// pin assignments
//
const int LED_PIN = 13;
const int MOTOR_X_STEP = 2;
const int MOTOR_Y_STEP = 3;
const int MOTOR_Z_STEP = 4;
const int MOTOR_X_DIR = 5;
const int MOTOR_Y_DIR = 6;
const int MOTOR_Z_DIR = 7;
const int STEPPERS_ENABLE = 8;
const int LIMIT_SWITCH_X = 9;
const int LIMIT_SWITCH_Y = 10;
const int LIMIT_SWITCH_Z = 11;
const int SPINDLE_ENABLE = 12;
const int SPINDLE_DIRECTION = 13;
const int microX = 1;
const int microY = 1;
const int microZ = 1;
const int standardStepsPerRev = 200;
int defRevsPerSecond = 50;
int zeroingAccel = 100;
// create the stepper motor object
//
FlexyStepper stepperX;
FlexyStepper stepperY;
FlexyStepper stepperZ;
//Initialize pins
int xPin = A1;
int zPin = A0;
int buttonPin = A2;
//Initialize variables for pins
int xRevsPerSecond = 0;
int xRead = 0;
int zRevsPerSecond = 0;
int zRead = 0;
int buttonRead = 0;
//Initialize other varaibles
boolean buttonState = 0;
int prevButtonRead = 0;
String axisState = "Roaming";
String axisState2 = "Fixed";
boolean settingOrigin = 1;
void setup() {
//Joystick 1
pinMode(xPin, INPUT);
pinMode(zPin, INPUT);
pinMode(buttonPin, INPUT_PULLUP);
byte contrastValue;
//
// configure IO pins
//
pinMode(LED_PIN, OUTPUT);
pinMode(STEPPERS_ENABLE, OUTPUT);
//
// create the stepper object & enable them
//
stepperY.connectToPins(MOTOR_Y_STEP, MOTOR_Y_DIR);
stepperX.connectToPins(MOTOR_X_STEP, MOTOR_X_DIR);
stepperZ.connectToPins(MOTOR_Z_STEP, MOTOR_Z_DIR);
digitalWrite(STEPPERS_ENABLE, LOW);
stepperX.setStepsPerRevolution(standardStepsPerRev*microX);
stepperY.setStepsPerRevolution(standardStepsPerRev*microY);
stepperZ.setStepsPerRevolution(standardStepsPerRev*microZ);
Serial.begin(9600);
}
void loop() {
if (settingOrigin){
setOrigin();
}
else {
Serial.println();
Serial.println("Hit a key and press enter to start"); // signal initalization done
while(Serial.available() == 0){}
Serial.println("Cutting Mode Goes Here");
}
}
void setOrigin(){
//Read pin inputs
xRead = analogRead(xPin);
zRead = analogRead(zPin);
buttonRead = digitalRead(buttonPin);
//Toggles button states for button 1 and 2
if (buttonRead == 1 && prevButtonRead == 0) {
buttonState = !buttonState;
if (buttonState == 0) {
axisState = "Fixed";
}
else {
axisState = "Roaming";
}
}
//Make velocities 0. Accounts for different origins of joystick
if (xRead > 450){
xRevsPerSecond = defRevsPerSecond;
} else if (xRead < 400){
xRevsPerSecond = -defRevsPerSecond;
} else {
xRevsPerSecond = 0;
}
if (zRead > 480){
zRevsPerSecond = defRevsPerSecond;
} else if (zRead < 430){
zRevsPerSecond = -defRevsPerSecond;
} else {
zRevsPerSecond = 0;
}
//Remove Velocity inputs if axis is fixed
if (axisState.equals("Fixed")){
xRevsPerSecond = 0;
zRevsPerSecond = 0;
}
//Set previous button read
prevButtonRead = buttonRead;
if (axisState.equals("Fixed")){
settingOrigin = !settingOrigin;
}
Serial.print("X: ");
Serial.print(xRevsPerSecond);
Serial.print(" | Y: ");
Serial.print(zRevsPerSecond);
Serial.print(" | Button: ");
Serial.println(axisState);
stepperX.setSpeedInRevolutionsPerSecond(xRevsPerSecond);
stepperZ.setSpeedInRevolutionsPerSecond(zRevsPerSecond);
stepperX.setAccelerationInRevolutionsPerSecondPerSecond(zeroingAccel);
stepperZ.setAccelerationInRevolutionsPerSecondPerSecond(zeroingAccel);
stepperX.setTargetPositionRelativeInRevolutions(xRevsPerSecond);
stepperZ.setTargetPositionRelativeInRevolutions(zRevsPerSecond);
stepperX.processMovement();
stepperZ.processMovement();
}
| true |
c45dad018a52e7755bc72fe08a2f5d3ce6d0a64c
|
C++
|
EliseyDev/CPP-Primer-Plus-Exercises
|
/stephen_prata/chapter_05/programming_exercises/hw2.cpp
|
UTF-8
| 402 | 3.3125 | 3 |
[] |
no_license
|
#include <iostream>
#include <array>
const int ARRAY_SIZE = 101;
int main() {
std::array<long double, ARRAY_SIZE> factorials{};
factorials[0] = factorials[1] = 1;
for (int i = 2; i < ARRAY_SIZE; i++) {
factorials[i] = factorials[i - 1] * i;
}
for (int j = 0; j < ARRAY_SIZE; j++) {
std::cout << j << "! = " << factorials[j] << std::endl;
}
return 0;
}
| true |
20cda8df159f42ea19f2cc085096598bf2952de2
|
C++
|
omarzandona/omar_code
|
/2.3.12.0b/src/imgserver.cpp
|
IBM852
| 77,980 | 2.671875 | 3 |
[] |
no_license
|
/*!
\file imgserver.cpp
\brief Sorgente principale dell'imgserver: contiene le inizializzazioni di variabili,
la creazione dei thread ed, infine, il ciclo in cui il server resta in ascolto del client.
Si tratta del file principale del progetto dove risiede il main all'interno del quale viene fatto quanto segue:
- parsing degli eventuali argomenti (--dir o -version, il primo permette di
specificare una cartella diversa da quella di default in cui andare a
leggere e scrivere i vari file mentre il secondo visualizza a video
la versione dello image server);
- inizializzazione di alcune delle innumerevoli variabili
globali (vedi var_init());
- inizializzazione dei device di input e
output (vedi init_io());
- caricamento dei parametri di default per i device ed altre variabili
globali (vedi load_parms() e calib_load_parms());
- caricamento della mappa di disparita' del background da file;
- inizializzazione strutture dati per il tracking (vedi initpeople());
- aggiunta al file di log del messaggio di avvio dello imgserver
con verifica di riempimento del file: se i file di log hanno un numero
di righe che supera le MAX_LOG_LINES allora viene creato un nuovo
file di log numerato ciclicamente da 0 a 9.
- vengono attivati i vari thread corrispondenti alle seguenti
funzioni implementate in loops.cpp: main_loop(), watchdog_loop(),
record_loop(), ser_loopttyS0(), ser_loopttyS1(), input_loop0() e
input_loop1();
- inizializza la comunicazione via socket tramite un canale TCP di
comunicazione listener usato per rimanere in ascolto degli eventuali
messaggi del client.
Inoltre, viene creato un ulteriore canale UDP di comunicazione datagram
utilizzato in ping_loop() ma per il quale non viene lanciato il comando
listen() e non vengono specificate opzioni particolari con setsockopt().
- crea il thread corrispondente al ping_loop();
- infine, il main() e' concluso da un ciclo infinito con il quale lo
image server resta in ascolto di eventuali comandi inviati dal
win_client tramite la RecvString() e se li riceve li passa alla
Communication() affinche' ne venga fatto il parsing e venga presa
l'opportuna azione.
Per ulteriori dettagli vedere la funzione main().
\author Alessio Negri, Andrea Colombari (eVS - embedded Vision Systems s.r.l. - http://www.evsys.net)
\mainpage
Il passenger counter è un sistema di visione embedded utilizzato per contare le persone
che attraversano un varco (ad esempio i passeggeri di un autobus che salgono e scendono).
Il sistema è suddiviso in tre parti fondamentali: hardware, firmware e software.
Con hardware si intende l'insieme dei dispositivi che costituiscono il passenger
counter ad eccezione dell'FPGA che insieme all'imgserver formano il firmware.
Quindi, in questa categoria ricadono il processore, la memoria, i bus, le memorie
flash, i sensori CMOS, ecc...
In FPGA sono implementati vari algoritmi di image processing come calcolo della mappa
di disparità, il calcolo dei parametri di motion detection e il valor medio
delle due immagini acquisite.
La parte software si suddivide in parte client (<b>win_client/rs485_gui</b>) e parte
server (<b>imgserver</b>). Dal momento che il software del lato server fa comunque parte del
sensore PCN, sarà considerato parte del firmware.
Questo documento ipertestuale descrive il codice del software del lato server (imgserver) che
incorpora la logica di alto livello necessaria per il conteggio
delle persone, ovvero sottrazione dello sfondo dalla mappa di disparità e
successivo filtraggio, detection e tracking delle teste. Il software del lato client
consta di due applicazioni <b>win_client</b> e <b>rs485_gui</b>. Riassumendo, win_client è
un'interfaccia utente che permette di interagire con un sensore PCN
mediante connessione USB al fine di aggiornare il software del server, di
visualizzare le immagini sorgenti, quelle rettificate, la mappa di disparità
originale, quella filtrata e il risultato del tracking delle teste. Il software
rs485_gui è sempre una interfaccia grafica che permette di interagire col sensore
PCN ma per via seriale. Dati i limiti intrinseci di questo tipo di collegamento,
questo client ha funzionalità più limitate.
Esiste anche una versione di <b>win_client di debug</b> con cui è possibile acquisire delle sequenze
al fine di acquisire un data set da usare come test-bed durante lo sviluppo di modifiche
e/o evoluzioni del software. Per questa versione esistono due comandi specifici "recimg"
e "recimgdsp" (vedi commands.cpp) che permettono al client di chiedere al server i valori attuali dei contatori
in e out ed inoltre o le immagini+mappa di disparità ("recimg") o solo la mappa di
disparità ("recimgdsp"). Affinchè i contatori siano perfettamente allineati con le
immagini passate, anche gli algoritmi di detezione e tracking sono eseguiti dal server
solo in concomitanza delle richieste del client.
Per quanto riguarda il lato server qui descritto, possiamo riassumerne
le caratteristiche andando ad illustrare brevemente il contenuto dei vari
file:
- imgserver.cpp: contiene il main() dell'applicazione dove vengono effettuate
tutte le inizializzazioni delle variabili globali, dei device e dei necessari
canali di comunicazione per poter interagire con il client o con il software
concentratore (molti dei valori di default usati per le varie inizializzazioni
sono definiti in default_parms.h); quindi vengono creati i vari thread corrispondenti alle funzioni
di tipo loop in loops.cpp; infine vi è un ciclo infinito (a meno di
errori che provocano la terminazione dell'applicazione) che gestisce la
comunicazione con il client via socket per mezzo delle funzioni contenute
in socket.cpp e in commands.cpp. I parametri sono memorizzati in due strutture dati
descritte rispettivamente in \ref tabella_parms e in \ref tabella_calib.
- loops.cpp: contiene il codice relativo ai vari thread lanciati nel main()
tra i quali vi è il main_loop() che si occupa di acquisire i dati
dall'FPGA (vedi images_fpga.cpp) e di elaborarli per il detection (vedi peopledetection.cpp) e il
tracking (vedi peopletrack.cpp) delle persone.
- socket.cpp: insieme di funzioni per la gestione della comunicazione via socket.
- commands.cpp: contiene un'unica monolitica funzione che gestisce lo scambio
di messaggi tra client (<b>win_client</b>) e server via socket: interpreta il pacchetto arrivato dal client, esegue
quanto richiesto e risponde con un opportuno feedback.
- serial_port.cpp: insieme di funzioni per la gestione della comunicazione tra client (<b>rs485_gui</b>) e
imgserver via seriale nonche' tra i vari sensori nel caso di configurazione "widegate"
usata per monitorare varchi piu' larghi di 120cm (60cm in piu' per ogni ulteriore sensore
fino a un massimo di 5).
- io.cpp: insieme di funzioni per la gestione dei device e per la lettura e scrittura
dei parametri su file.
- calib_io.cpp: insieme di funzioni per la lettura e scrittura su file dei
parametri di calibrazione che possono essere cambiati via client sciegliendo
una delle due configurazioni 25/30 o 31/40.
- pcn1001.h: contiene tutta una serie di define tra cui i valori
da usare per settare il registro FPGA che specifica cosa l'FPGA restituisce nel
buffer prelevato poi nel main_loop() e alcuni settaggi per configurare l'acquisizione
dei sensori CMOS.
- makefile: direttive per il compilatore.
<b>Note per la consultazione</b><br>
Per meglio consultare questa documentazione si tenga presente che:
- Si puo' sfruttare il motore di ricerca in alto a destra.
- I commenti dei singoli sottoprogrammi sono completati da due voci "Riferimenti/References" e "Referenziato
da/Referenced by": la prima corrisponde a un elenco di tutte le variabili, funzioni e costanti usate
all'interno della funzione in esame; la seconda corrisponde a un elenco di altri sottoprogrammi
che richiamano al loro interno il sottoprogramma in esame. Data la grande quantita' di
variabili globali e la scarsa modularita' del codice, questi due elenchi risultano
molto comodi per poter, per esempio, "ricostruire la storia" di una variabile o capire l'uso di
un particolare sottoprogramma in base a dove viene chiamato.
- Alle volte i commenti contengono tre punti interrogativi "???" per indicare
quei punti ancora poco chiari.
- Si noti, inoltre, che la struttura del progetto software non segue le direttive
standard che prevedono coppie di file .c e .h al fine di modulare il codice
bensi' imgserver.cpp include tutti gli altri file cpp ottenendo qualcosa di equivalente
ad un unico file cpp.
- Se ci sono dubbi si consiglia di consultare anche le technotes che completano la
documentazione al codice.
\author Alessio Negri, Andrea Colombari (eVS - embedded Vision Systems s.r.l. - http://www.evsys.net)
\note Per info e dettagli contattare Andrea Colombari (andrea.colombari@evsys.net)
*/
#include "imgserver.h"
extern int num_pers;
unsigned char Frame[NN << 2]; //!< Blocco dati trasferito mediante quick capture technology (#NN*4=#NX*#NY*4=160*120*4=320*240 bytes).
unsigned char Frame_DX[NN]; //!< Immagine destra a 256 livelli di grigio (#NX*#NY=160*120).
unsigned char Frame_SX[NN]; //!< Immagine sinistra a 256 livelli di grigio (#NX*#NY=160*120).
unsigned char Frame_DSP[NN]; //!< Mappa di disparità #NX*#NY=160*120 (16 livelli di disparità distribuiti su 256 livelli di grigio).
//unsigned char minuti_log=0; //!< ???
char FPN_DX[NN]; //!< Buffer contenente il Fixed Pattern Noise del sensore destro (#NN=#NX*#NY=160*120).
char FPN_SX[NN]; //!< Buffer contenente il Fixed Pattern Noise del sensore sinistro (#NN=#NX*#NY=160*120).
unsigned short Frame10_DX[NN]; //!< Immagine destra a toni di grigio a 10 bit di dimensione #NX*#NY=160*120.
unsigned short Frame10_SX[NN]; //!< Immagine sinistra a toni di grigio a 10 bit di dimensione #NX*#NY=160*120.
short ODCbuf[NN*8]; //!< Buffer contenente le informazioni (look-up-table) per la correzione della distorsione causata dalle ottiche (dimensione totale del buffer = #NX*#NY*8=160*120*8 bytes).
//char records[MAX_RECORDS][64]; //!< Buffer storing log messages (reporting counting results) periodically written on file.
char records[MAX_RECORDS][128]; //!< Buffer storing log messages (reporting counting results) periodically written on file.
/*!<
Records (log lines reporting counting results) are not immediately written on a file but they are first stored in a
buffer of strings (one for each line of at most 64 characters) named #records which is periodically (every
#RECORD_INTERVAL seconds) got empty and saved on a file with name #rd_filename.
Therefore, this buffer has to be big enough to contain all the records. Supposing that people run at 5m/sec and
that the detection area is 100cm*120cm the upper bound #MAX_PEOPLE_PER_SEC can be fixed at 10 persons per second.
This number is multiplied by the #RECORD_INTERVAL to obtain the maximum dimension for the buffer #MAX_RECORDS.
If (but it should not be) the buffer get full then the last element is re-written.
A file of records can be at maximum of #MAX_REC_LINES lines of logs. When a file get greater than that
another file is created with a new suffix. This suffix starts from 0 and goes to #MAX_REC_FILES-1 and
then starts from 0 again and the old file is rewritten.
*/
char working_dir[128] = WORK_DIR; //!< Cartella di lavoro (#WORK_DIR).
char bg_filename[128]; //!< Percorso del file che contiene lo sfondo (#WORK_DIR + #BG_FILENAME).
char rd_filename[128]; //!< Percorso del file che contiene i messaggi di log (#WORK_DIR + #RD_FILENAME).
char pm_filename[128]; //!< Percorso del file che contiene i parametri della porta seriale, no tracking zone e motion detection (#WORK_DIR + #PM_FILENAME).
char ca_filename[128]; //!< Percorso del file che contiene i parametri di calibrazione (#WORK_DIR + #CA_FILENAME).
char cr_filename[128]; //!< Percorso dei file che contiene i contatori delle persone entrate/uscite (#WORK_DIR + #CR_FILENAME).
int pxa_qcp; //!< File descriptor della porta di tipo quick capture della intel.
/*!<
Viene utilizzata mediante la chiamata ioctl() per l'interfacciamento con l'FPGA,
ad esempio settaggio strutture dati video_picture e video_window,
inizializzazione cattura video e settaggio della modalità di acquisizione (ioctl(pxa_qcp,VIDIOCSI2C,&i2cstruct)).
*/
int imagesize; //!< Size of the Quick Capture Interface buffer which is cpoied in #Frame (#NN*4=#NX*#NY*4).
struct video_picture vid_pict; //!< Questa variabile è una struttura dati di tipo "video_picture" (Video4Linux).
struct video_window vid_win; //!< Questa variabile è una struttura dati di tipo "video_window" (Video4Linux).
pxa_i2c_t i2cstruct; //!< Variabile usata per la comunicazione via I2C.
char addresses[MAX_CONN][16]; //!< Lista degli indirizzi relativi alle connessioni accettate dal server mediante la funzione accept().
struct sockaddr_in myaddr; //!< Indirizzo lato server associato alla socket di tipo TCP per la comunicazione client/server (mediante connessione usb).
// 20111014 eVS, myaddr_data declaration moved in the ping_pong loop code
//struct sockaddr_in myaddr_data; //!< Indirizzo lato server associato alla socket di tipo UDP per la comunicazione client/server (mediante connessione usb).
struct sockaddr_in remoteaddr; //!< Indirizzo lato client associato alla socket di tipo TCP per la comunicazione client/server (mediante connessione usb).
struct sockaddr_in remoteaddr_data; //!< Indirizzo lato client associato alla socket di tipo UDP per la comunicazione client/server (mediante connessione usb).
int fdmax; //!< Numero massimo di file descriptor da associare alla socket TCP per la comunicazione client/server.
int listener; //!< Nuovo file descriptor restituito dalla funzione accept (listener=socket(AF_INET,SOCK_STREAM,0)) quando il server accetta la nuova connessione da parte di un client (mediante socket di tipo TCP).
int sockfd; //!< File descriptor associato alla socket di tipo TCP per la comunicazione tra win_client ed imgserver. Viene restituito dalla funzione accept: newfd = accept(listener, (struct sockaddr *)&remoteaddr,&addrlen)).
bool connected; //!< Flag che indica se un client è connesso oppure no al server.
// 20111014 eVS, datagram declaration moved in the ping_pong loop code
//int datagram; //!< File descriptor associato alla socket di tipo UDP (datagram = socket(AF_INET, SOCK_DGRAM, 0)).
/*
In questo caso i pacchetti di dati (datagram o datagramma) hanno una lunghezza massima prefissata,
indirizzati singolarmente. Non esiste una connessione e la trasmissione è effettuata
in maniera non affidabile.
*/
//int level; //??? DEFINITA MA NON USATA ???
//unsigned short door; // ??? DEFINITA MA NON USATA ???
int record_enabled; //!< Salvataggio messaggi di log abilitato.
int thread_status; //!< Stato del thread associato al ciclo principale di esecuzione.
int count_enabled; //!< Person counting enabled (via I/O).
int images_enabled; //!< Abilitazione dell'invio delle immagini dall'imgserver al win_client.
bool autoled; //!< Modalita' automatica di funzionamento dei LED.
bool led_status; //!< Stato degli illuminatori.
char sys_ver[256]; //!< Versione del sistema operativo.
float fw_ver; //!< Versione del bitstream (FPGA).
bool autogain; //!< Modalit automatica gain 20130927 eVS added to manage gain Vref
unsigned char fpn_counter; //!< Relative to the FPN calibration application (to obtain FPN win_client_calib needs more than one image and this counter helps).
unsigned long records_idx; //!< Indice del buffer dei messaggi di log #records.
// 20111012 eVS, added records_saving_in_progress
bool records_saving_in_progress = false; //!< A true se il salvataggio dei records in corso (in tal caso la "rdsv" e "rdsave" aspetteranno la fine del salvataggio prima di procedere al trasferimento del log
unsigned long counter_in; //!< Contatore delle persone entrate INDIPENDENTE dalla direzione di marcia (ovvero come se la direzione fosse 0).
unsigned long counter_out; //!< Contatore delle persone uscite INDIPENDENTE dalla direzione di marcia (ovvero come se la direzione fosse 0).
unsigned char people_dir; //!< Vale zero se la direzione di ingresso è dall'alto verso il basso, uno viceversa.
unsigned long out0; //!< optocoupled out0 queue for incoming people.
/*!<
The default value 0 (given at startup by #var_init) but during counting this
value is related to the number of the counted persons and is used to
communicate counting data to the collector via digital
output (see #write_output).
\see record_counters()
*/
unsigned long out1; //!< optocoupled out1 queue for outgoing people.
/*!<
\see out0
*/
unsigned short acq_mode; //!< Specifica se l'acquisizione è o meno abilitata e, nel caso in cui sia abilitata, dice in quale modalità avviene l'acquisizione.
/*!<
Inizializzata in init_io().
Le due informazioni, su accensione/spegnimento dell'acquisizione e su quale modalità
è in uso, sono inserite rispettivamente nella parte alta e bassa dei sedici bit
della variabile. Quindi per vedere se l'acquisizione è attiva basta fare
il seguente and bit a bit
\code
(acq_mode & 0x0100)
\endcode
se la parte alta è a 1 questo and restituirà 1
altrimento darà 0.
Per estrarre la parte bassa, invece, basterà fare il seguente and bit a bit
\code
(acq_mode & 0x00FF)
\endcode
Le modalità di acquisizione specificata dalla parte
bassa può assumere i valori specificati dalle seguenti define: <BR>
#MUX_MODE_10_NOFPN_DX <BR>
#MUX_MODE_10_NOFPN_SX <BR>
#MUX_MODE_8_NOFPN <BR>
#MUX_MODE_8_FPN <BR>
#MUX_MODE_8_FPN_ODC <BR>
#MUX_MODE_8_FPN_ODC_SOBEL <BR>
#MUX_MODE_8_FPN_ODC_DISP <BR>
#MUX_MODE_8_FPN_ODC_DISP_SOBEL <BR>
#MUX_MODE_8_FPN_ODC_MEDIAN_DISP <BR>
#MUX_MODE_8_FPN_ODC_MEDIAN_DISP_SOBEL <BR>
#MUX_MODE_8_FPN_ODC_DISP_SOBEL_SX <BR>
#MUX_MODE_8_FPN_ODC_MEDIAN_DISP_SOBEL_SX
Altro modo per capire la modalità a partire dalla variabile acq_mode e dalle define
appena elencate è data dall'uso di un confronto del tipo
\code
(acq_mode != (MUX_MODE_8_FPN_ODC_MEDIAN_DISP | 0x0100))
\endcode
*/
unsigned short start_stop; //!< Modified in the command "disconnect" in commands.cpp but not used in other places.
unsigned short dac_sensor; //!< Initialized in var_init() but not used in other places.
unsigned char *input_test; //!< see "testin" command in both commands.cpp and serial_port.cpp
unsigned char input_test0; //!< used by "testin" command in commands.cpp and updated by input_loop0() in loops.cpp
//!< \warning Usage of this variable seems to be deprecated instead use the proper register in #regs
unsigned char input_test1; //!< used by "testin" command in commands.cpp and updated by input_loop1() in loops.cpp
//!< \warning Usage of this variable seems to be deprecated instead use the proper register in #regs
bool wd_check; //!< watchdog flag.
unsigned char slave_id=0; //!< Used in widegate mode by each sensor in the chain to replay (SNP_reply()) a message (coming from the previous in the chain) to the next sensor (this value is always 0 and should correspond to the 24th element of the params vector).
//unsigned char count_debug=0; //!< ??? 20100520 commented
extern unsigned char total_sys_number;
extern unsigned char current_sys_number;
// 20100521 eVS aggiornati commenti
unsigned char current_sys_number_tmp=0; //!< Used together #total_sys_number_tmp for the wideconfiguration initialization (after receiving wideconfiguration activation till end_chain command arrives).
/*!<
Vedi commands.cpp ("wideconfiguration") e serial.cpp ("wideconfiguration" e "end_chain").
*/
unsigned char total_sys_number_tmp=0; //!< Used together #current_sys_number_tmp for the wideconfiguration initialization (after receiving wideconfiguration activation till end_chain command arrives).
/*!<
Vedi commands.cpp ("wideconfiguration") e serial.cpp ("wideconfiguration" e "end_chain").
*/
extern unsigned char count_sincro; //!< Per la sincronizzazione di piu' PCN in wide-gate.
extern unsigned char *data_wide_gate;
unsigned char send_enable=0; //!< Se sono in widegate e sono il master uso send_enable per regolare l'accesso alla seriale (send_enable deve essere zero per gli slave).
int pcin0; //!< File descriptor associato alla prima porta seriale di input.
int pcin1; //!< File descriptor associato alla seconda porta seriale di input.
int pcout0; //!< File descriptor associato alla prima porta seriale di output.
int pcout1; //!< File descriptor associato alla seconda porta seriale di output.
int watchdog; //!< File descriptor associato al dispositivo "/dev/watchdog".
//FILE *in,*out; // sostituite variabili globali con variabili locali dove serviva
//FILE *platelist; //??? DICHIARATA MA NON UTILIZZATA ???.
struct timeval start0; //!< Per controllare timeout0
struct timeval stop0; //!< Per controllare timeout0
struct timeval start1; //!< Per controllare timeout1
struct timeval stop1; //!< Per controllare timeout1
//int debug; //??? DICHIARATA MA NON UTILIZZATA ???.
/********************* wide-gate variables **************************/
#define time_bkg //!< Per abilitare la compilazione del codice relativo all'aggiornamento automatico del background.
unsigned long people_rec[2]; //!< Vettore contenente i due contatori delle persone entrare/uscite che devono essere inseriti nel messaggio di log.
extern unsigned long people[2];
extern unsigned char det_area;
extern int inst_height; ///< Altezza d'installazione ( in cm)
extern int inst_dist; ///< Distanza tra due dispositivi in modalita widegate ( in cm)
unsigned char flag_serial; //!< Flag associato alla comunicazione seriale di tipo master-slave.
unsigned char flag_wg=1; //!< Flag che indica se è presente la configurazione wide-gate, cioè se è presente almeno uno slave.
unsigned char flag_wg_count=0;//!< Slave presence flag.
unsigned char wg_check; //!< Abilita/disabilita il controllo della presenza della configurazione wide-gate (DA VERIFICARE) ???
unsigned char * SNPimg;
extern unsigned char frame_cnt_door;
extern unsigned char frame_fermo;
/********************* record.txt variables **************************/
int recordfd; //!< File descriptor del file contenente i messaggi di log.
char record_fn[256]; //!< Nome del file contenente i messaggi di log.
unsigned long record_id;//!< Indice del file contenente i messaggi di log.
/************************** threads **********************************/
pthread_t serloopttyS0; //!< Posix thread associato alla funzione ser_loopttyS0() per la gestione della porta seriale numero 0.
pthread_t serloopttyS1; //!< Posix thread associato alla funzione ser_loopttyS1() per la gestione della porta seriale numero 1.
pthread_mutex_t rdlock; //!< Semaforo di tipo posix utilizzato per poter accedere in modo esclusivo alla risorsa #records[].
pthread_mutex_t mainlock; //!< Semaforo di tipo posix utilizzato per poter accedere in modo esclusivo ad una variabile globale da thread concorrenti.
pthread_mutex_t acq_mode_lock; // 20100517 eVS
// (reset_counters function and "serial" command)
pthread_t ploop;
pthread_t mloop; //!< Posix thread associato alla funzione main_loop() che contiene il ciclo principale di esecuzione.
pthread_t tloop;
pthread_t rdloop;
pthread_t inloop0;
pthread_t inloop1;
pthread_t wdloop; //!< Posix thread associato al ciclo di controllo "watchdog".
/**************** serial port variables **********************************/
// 20100520 eVS comments added for both ttyS0 and ttyS1
int ttyS0; //!< File descriptor corresponding to the serial port 0 (set to -1 if inactive).
/*!<
This port is used by a PCN to communicate with its master (which can be the
rs485_gui or another PCN in wideconfiguration that precedes this one in
the chain or the collector)
*/
int ttyS1; //!< File descriptor corresponding to the serial port 1 (set to -1 if inactive).
/*!<
This port is used by a PCN to communicate with its slave (which can only be
another PCN in wideconfiguration that follows this one in the chain)
*/
//struct termios newtio; 20100521 eVS commented because not used
// 20100521 eVS added comments for framecounter and test_serial
extern unsigned long int framecounter; //!< Used to count acquired frames.
/*!<
Initialized to zero and then incremented by one at each new acquisition.
It is used to start some processing every N frame just using the %
operator, e.g., if (framecounter % N == 0).
*/
unsigned char test_serial; //!< Used from the win_client (via socket) to test the serial port at the slave side (via #ttyS1)
/******************* parameters *****************************************/
/*!
\var parm_names
\brief Nome dei parametri relativi alle porte seriali, no tracking zone e motion detection (\ref tabella_parms).
*/
char parm_names[256][PARM_STR_LEN] = {
"outtime0",
"outtime1",
"input0",
"input1",
"sled",
"dir",
"threshold",
"serial_id",
"serial_br",
"serial_db",
"serial_pr",
"serial_sb",
"detect_area",
"autoled",
"inst_height",
"serial_ms",
"serial_sid",
"serial_sbr",
"serial_sdb",
"serial_spr",
"serial_ssb",
"timebkg",
"staticth",
"slave_id",
"sx_dx",
"inst_dist",
"wg_check",
"sys_number",
"sys_number_index",
"sxlimit",
"dxlimit",
"sxlimit_riga_start",
"dxlimit_riga_start",
"sxlimit_riga_end",
"dxlimit_riga_end" ,
"cond_diff_1p",
"diagnostic_en",
"move_det_col0",
"move_det_col1",
"move_det_row0",
"move_det_row1",
"move_det_alfareg",
"move_det_thr",
"move_det_en",
"door_stairs_en",
"up_line_limit",
"down_line_limit",
"dis_autobkg", // 20090506 Lisbona
"door_size", // 20130411 eVS, door_size instead of door_kind (for 2.3.10.7)
"handle_oor", // 20130715 eVS added to manage OOR situation after reboot
"auto_gain" // 20130927 eVS added to manage gain Vref
};
/*!
\var calib_parm_names
\brief Nomi dei parametri di calibrazione (\ref tabella_calib).
*/
char calib_parm_names[256][PARM_STR_LEN] = {
"map_minth",
"map_thuni",
"map_disp",
"dac_vref1",
"dac_vprec1",
"dac_vgap1",
"dac_vref2",
"dac_vprec2",
"dac_vgap2",
"threshBkg",
"step225_0",
"step225_1",
"step225_2",
"step225_3",
"step225_4",
"step225_5",
"step225_6",
"step225_7",
"step225_8",
"step225_9",
"step225_A",
"step225_B",
"step225_C",
"step225_D",
"step225_E",
"step225_F",
"winsz",
"step240_0",
"step240_1",
"step240_2",
"step240_3",
"step240_4",
"step240_5",
"step240_6",
"step240_7",
"step240_8",
"step240_9",
"step240_A",
"step240_B",
"step240_C",
"step240_D",
"step240_E",
"step240_F"
};
/*!
\var parm_values
\brief Valori dei parametri relativi alle porte seriali, no tracking zone e motion detection (vedi \ref tabella_parms).
*/
unsigned short parm_values[256];
//! Valori di default dei parametri relativi alle porte seriali, no tracking zone e motion detection (vedi \ref tabella_parms)
unsigned short default_values[256] = {
OUTTIME0,
OUTTIME1,
INPUT0,
INPUT1,
SLED,
DIR,
THRESHOLD,
SERIAL_ID,
SERIAL_BR,
SERIAL_DB,
SERIAL_PR,
SERIAL_SB,
DETECT_AREA,
OFF,
INST_HEIGHT,
SERIAL_MS,
SERIAL_SID,
SERIAL_SBR,
SERIAL_SDB,
SERIAL_SPR,
SERIAL_SSB,
TIMEBKG,
STATIC_TH,
SLAVE_ID,
SX_DX,
INST_DIST,
WG_CHECK,
SYS_NUMBER,
SYS_NUMBER_INDEX,
SXLIMIT,
DXLIMIT,
SXLIMIT_RIGA_START,
DXLIMIT_RIGA_START,
SXLIMIT_RIGA_END,
DXLIMIT_RIGA_END,
OFF,
DIAGNOSTIC_EN,
MOVE_DET_COL0,
MOVE_DET_COL1,
MOVE_DET_ROW0,
MOVE_DET_ROW1,
MOVE_DET_ALFAREG,
MOVE_DET_THR,
MOVE_DET_EN,
DOOR_STAIRS_EN,
UP_LINE_LIMIT,
DOWN_LINE_LIMIT,
DIS_AUTOBKG, //20090506 Lisbona
DOOR_SIZE, //20130411 eVS, DOOR_SIZE instead of DOOR_KIND (for 2.3.10.7)
HANDLE_OOR, // 20130715 eVS, in order to manage OOR correctly after reboot
AUTO_GAIN // 20130927 eVS added to manage gain Vref
};
/*!
\var calib_parm_values
\brief Valori dei parametri di calibrazione (\ref tabella_calib).
*/
unsigned short calib_parm_values[256];
/*!
\var calib_default_values
\brief Valori di default dei parametri di calibrazione (\ref tabella_calib).
*/
unsigned short calib_default_values[256] = {
MAP_MINTH,
MAP_THUNI,
MAP_DISP,
DAC_VREF,
DAC_VPREC,
DAC_VGAP,
DAC_VREF,
DAC_VPREC,
DAC_VGAP,
THBKG,
STEPS_225[0],
STEPS_225[1],
STEPS_225[2],
STEPS_225[3],
STEPS_225[4],
STEPS_225[5],
STEPS_225[6],
STEPS_225[7],
STEPS_225[8],
STEPS_225[9],
STEPS_225[10],
STEPS_225[11],
STEPS_225[12],
STEPS_225[13],
STEPS_225[14],
STEPS_225[15],
WIN_SIZE,
STEPS_240[0],
STEPS_240[1],
STEPS_240[2],
STEPS_240[3],
STEPS_240[4],
STEPS_240[5],
STEPS_240[6],
STEPS_240[7],
STEPS_240[8],
STEPS_240[9],
STEPS_240[10],
STEPS_240[11],
STEPS_240[12],
STEPS_240[13],
STEPS_240[14],
STEPS_240[15]
};
/**************************** gpios strucures ************************/
/*!
\struct reg_info
\brief Struttura dati contenente informazioni relative alle porte di input/output di tipo geneal purpose.
*/
struct reg_info {
char *name; //!< nome registro di memoria
unsigned int addr; //!< indirizzo registro di memoria
int shift; //!< traslazione espressa in bits
unsigned int mask; //!< maschera
char type; //!< tipo
char *desc; //!< descrizione
};
/*!
\var static struct reg_info regs[]
\brief Informazioni dei registri di tipo general purpose.
Dopo Lisbona sono stati aggiunti gli ultimi due record "GPLR2_095" e "GPLR3_096" che sono
stati utilizzati al posto delle variabili globali #input_test0 e #input_test1
per verificare lo stato dei digital input.
\date February 2009 (after Lisbon)
*/
static struct reg_info regs[] = {
//GPIO_100 RS485 RTS pin
{ "GPLR3_100", 0x40E00100, 4, 0x00000001, 'd', "GPIO 100 level" },
{ "GPSR3_100", 0x40E00118, 4, 0x00000001, 'd', "GPIO 100 set" },
{ "GPCR3_100", 0x40E00124, 4, 0x00000001, 'd', "GPIO 100 clear" },
{ "GPDR3_100", 0x40E0010C, 4, 0x00000001, 'd', "GPIO 100 i/o direction (1=output)" },
{ "FFLSR_TEMT", 0x40100014, 6, 0x00000001, 'd', "FFUART LSR transmitter empty" },
{ "BTLSR_TEMT", 0x40200014, 6, 0x00000001, 'd', "BTUART LSR transmitter empty" },
{ "STLSR_TEMT", 0x40700014, 6, 0x00000001, 'd', "STUART LSR transmitter empty" },
{ "IER_RTOIE", 0x40700004, 7, 0x00000001, 'd', "IER Receiver Timeout Interrupt Enable" },
{ "IIR_TOD", 0x40700008, 3, 0x00000001, 'd', "IER Receiver Timeout Interrupt Enable" },
{ "FOR_BC", 0x40700024, 0, 0x0000003F, 'd', "IER Receiver Timeout Interrupt Enable" },
{ "GPLR3_091", 0x40E00008, 27, 0x00000001, 'd', "GPOUT0 level" },
{ "GPSR3_091", 0x40E00020, 27, 0x00000001, 'd', "GPOUT0 set" },
{ "GPCR3_091", 0x40E0002C, 27, 0x00000001, 'd', "GPOUT0 clear" },
{ "GPLR3_090", 0x40E00008, 26, 0x00000001, 'd', "GPOUT1 level" },
{ "GPSR3_090", 0x40E00020, 26, 0x00000001, 'd', "GPOUT1 set" },
{ "GPCR3_090", 0x40E0002C, 26, 0x00000001, 'd', "GPOUT1 clear" },
{ "GPLR2_095", 0x40E00008, 31, 0x00000001, 'd', "GPIN1 level" }, //20090506 Lisbona
{ "GPLR3_096", 0x40E00100, 0, 0x00000001, 'd', "GPIN0 level" } //20090506 Lisbona
};
/****************** tracking extern variables ************************/
extern unsigned char Bkgvec[NN];
//extern unsigned char Pasvec[NN];
extern int svec[NN];
extern unsigned char Bkgvectmp[NN];
extern bool ev_door_open;
extern bool ev_door_close;
extern bool ev_door_open_rec;
extern bool ev_door_close_rec;
extern bool mem_door;
//extern unsigned long door_in; // 20100702 eVS moved in io.cpp where used
//extern unsigned long door_out; // 20100702 eVS moved in io.cpp where used
extern unsigned char vm_img;
extern unsigned char vm_bkg;
extern unsigned char soglia_bkg;
extern unsigned char persdata[54];
extern int static_th;
extern unsigned char minuti_th;
extern unsigned char limitSx;
extern unsigned char limitDx;
extern unsigned char limitSx_riga_start;
extern unsigned char limitDx_riga_start;
extern unsigned char limitSx_riga_end;
extern unsigned char limitDx_riga_end;
extern unsigned char draw_detected;
extern unsigned char limit_line_Up;
extern unsigned char limit_line_Down;
extern int diff_cond_1p;
unsigned char auto_gain; // 20130927 eVS, manage gainn vref
//20090506 Lisbona
extern unsigned char autobkg_disable;
//20100419 eVS
extern unsigned char door_size; // 20130411 eVS, door_size instead of door_kind (for 2.3.10.7)
extern unsigned char handle_oor; // 20130715 eVS, manage OOR after system reboot
int count_check_counter;
extern unsigned char mov_dect_0_7l;
extern unsigned char mov_dect_8_15l;
extern unsigned char mov_dect_15_23l;
extern unsigned char mov_dect_0_7r;
extern unsigned char mov_dect_8_15r;
extern unsigned char mov_dect_15_23r;
extern bool count_true_false;
int mov_det_left; //!< Parametro di motion detection relativo al frame sinistro.
/*!<
Viene calcolato nel main_loop() concatenando i tre byte estratti da get_images()
e dividendo per 100:<BR>
((((#mov_dect_15_23l & 0xff) << 16) | ((#mov_dect_8_15l & 0xff) << 8) | (#mov_dect_0_7l & 0xff))/100)
*/
int mov_det_right; //!< Parametro di motion detection relativo al frame destro.
/*!<
Viene calcolato nel main_loop() concatenando i tre byte estratti da get_images()
e dividendo per 100:<BR>
((((#mov_dect_15_23r & 0xff) << 16) | ((#mov_dect_8_15r & 0xff) << 8) | (#mov_dect_0_7r & 0xff))/100)
*/
int default_vref_left; //!< Valore di default della vref di sinistra letta da #calib_parm_values mediante la calib_get_parms().
int default_vref_right;//!< Valore di default della vref di destra letta da #calib_parm_values mediante la calib_get_parms().
int current_vref_left; //!< Valore di corrente della vref di sinistra modificata dalla funzione main_loop() (in loops.cpp).
int current_vref_right;//!< Valore di corrente della vref di destra modificata dalla funzione main_loop() (in loops.cpp).
//extern unsigned char move_det_en;
unsigned char move_det_en;
// 20111207 eVS, changed data type avoiding redundancy (now error_pcn_status_code is useless because it is encoded inside the pcn_status itself)
//bool pcn_status; //!< Stato corrente del PCN: 1->ok, 0->riscontrati problemi di diagnostica.
//bool old_pcn_status; //!< Used by record_counter() to understand a diagnostic error message has to be written in the log.
unsigned char pcn_status; //!< Stato corrente del PCN: 0->ok, N->riscontrati problemi di diagnostica.
unsigned char old_pcn_status; //!< Used by record_counter() to understand which diagnostic error message has to be written in the log.
//unsigned char error_pcn_status_code; //!< Contain the diagnosis error code to be written in the log file (see record_counter() and main_loop() code).
/*!<
From the least significant bit to the most significant one, the meaning of each bit is:
- average gray level of the right image too dark (obscured right camera)
- average gray level of the left image too dark (obscured left camera)
- average gray levels of the two camera are contrasting (high difference)
- the vref of the two cameras are contrasting (high difference): this can happen when auto-vref is running
The other bits have no meaning.
If an error occurs it is written in the log file (see record_counters() and main_loop() code).
*/
unsigned char diagnostic_en; //!< Global variable corresponding to the parameter "diagnostic_en" in #parm_values
int move_det_thr; //!< Soglia di motion detection per capire se c'è stato del movimento nella scena confrontando questo parametro con i valori di #mov_det_left e #mov_det_right.
extern unsigned char door_stairs_en;
/*!
\brief Funzione pricipale dell'imgserver.
Dopo una serie di settaggi iniziali (var_init() per le variabili e init_io() per i dispositivi e
canali di comunicazione I/O) e dopo aver caricato dei parametri da file mediante la load_parms() e la calib_load_parms(),
la funzione main contiene un ciclo in cui l'imgserver resta in ascolto di eventuali comandi inviati
dal win_client (mediante socket TCP).
Inoltre viene attivato il ciclo principale di elaborazione main_loop() mediante
la chiamata a mainloop_enable() (in loops.cpp): Per ogni mappa di disparità (calcolata
direttamente dall'FPGA) viene eseguita una serie di pre-filtraggi (sottrazione dello sfondo
ed operazioni morfologiche), dopo di che viene chiamato l'algoritmo di people
detection, che raffina ulteriormente la mappa di disparità senza sfondo (vedi la
funzione detectAndTrack() in peopledetection.cpp), e successivamente l'algoritmo di
tracking (vedi la funzione track() in peopletrack.cpp) che esegue il blob matching, a
partire dal risultato dell'algoritmo precedente, disegnando le croci sulle teste delle
persone che si muovono all'interno della zona monitorata al fine di contare i passeggeri
che entrano e che ed escono.
Segue, quindi, il ciclo principale di esecuzione in cui l'imgserver resta in ascolto
di eventuali comandi inviati dal win_client.
All'uscita del ciclo viene eseguita la deallocazione delle risorse (deinitpeople()), la cancellazione dei thread
e la chiusura dei dispositivi (deinit_io()).
*/
int main(int argc, char ** argv)
{
fd_set master; //master file descriptor list
fd_set read_fds; //temp file descriptor list
int newfd;
char buf[MAX_STR_LENGTH];
int nbytes;
int yes=1;
socklen_t addrlen;
int i;
int c;
static struct option long_options[] =
{
{"version",no_argument,0,'v'},
{"dir",required_argument,0,'d'},
{0, 0, 0, 0}
};
int option_index = 0;
/*! \code
// Esegue il parsing della stringa di comando (per esempio: imgserver --version oppure imgserver -v)
c = getopt_long(argc, argv, "v:d",long_options, &option_index);
\endcode */
c = getopt_long(argc, argv, "v:d",long_options, &option_index);
switch (c)
{
case 'v' :
printf("System: %s. Daemon version: %s\n",SYSTEM,VERSION);
return 0;
case 'd' :
if(optarg)
{
sprintf(working_dir,"%s/",optarg);
}
break;
}
// check if ip was changed
{
char filename[255];
sprintf(filename, "%sip.txt", working_dir);
FILE *ip = fopen(filename,"r");
if (ip)
{
// change ip
char command[255];
fgets(command, 255, ip);
fclose(ip);
system(command);
print_log("%s\n", command);
// remove ip file
sprintf(command, "rm -f %s", filename);
system(command);
}
}
/*!
<b>Inizializzazioni variabili e dispositivi</b>
\code
// settaggio variabili globali
var_init();
input_function0 = do_nothing;
input_function1 = do_nothing;
// inizializzazione dispositivi
if(init_io() < 0) exit(0);
\endcode
<b>Caricamento parametri</b>
\code
// caricamento dei parametri della porta seriale, no tracking zone e motion detection
load_parms();
// caricamento dei parametri di calibrazione
calib_load_parms();
\endcode
*/
var_init(); // setting global variables
input_function0 = do_nothing;
input_function1 = do_nothing;
if(init_io() < 0) exit(0); // initializing devices
load_parms(); // loading saved parameters
calib_load_parms(); // loading saved calibration parameters
gettimeofday(&start0,NULL);
gettimeofday(&start1,NULL);
memset(ODCbuf,0,sizeof(ODCbuf));
/*! \code
// get calibration vref value
default_vref_left = calib_get_parms("dac_vref2");
default_vref_right = calib_get_parms("dac_vref1");
current_vref_left = default_vref_left;
current_vref_right = default_vref_right;
\endcode */
// get calibration vref value
default_vref_left = calib_get_parms("dac_vref2");
default_vref_right = calib_get_parms("dac_vref1");
current_vref_left = default_vref_left;
current_vref_right = default_vref_right;
/*!
<b>Caricamento dello sfondo della scena da file ascii</b>
\code
if((in = fopen(bg_filename,"rb")))
{
// Bkgvec contiene lo sfondo (o meglio una media di n immagini di sfondo)
fread(Bkgvec,sizeof(Bkgvec),1,in);
// svec contiene la deviazione standard di ciascun pixel dal valor medio dello sfondo
fread(svec,sizeof(svec),1,in);
// vm_bkg rappresenta il valor medio dello sfondo
fread(&vm_bkg,sizeof(vm_bkg),1,in);
...
\endcode
*/
// loading scene background image
FILE *in;
if((in = fopen(bg_filename,"rb")))
{
fread(Bkgvec,sizeof(Bkgvec),1,in);
fread(svec,sizeof(svec),1,in);
fread(&vm_bkg,sizeof(vm_bkg),1,in);
fclose(in);
}
// copio il background caricato nella variabile usata per l'auto background
memcpy(Bkgvectmp,Bkgvec,NN);
//---------------people tracking init------------------//
unsigned long people[2];
imagesize = NN << 2;
people[people_dir] = counter_in; // la load_counters carica i valori in counter_in e counter_out
people[1-people_dir] = counter_out; // la load_counters carica i valori in counter_in e counter_out
//initpeople(people[0],people[1]);
initpeople(people[0],people[1], total_sys_number, num_pers);
//------------salvataggio log riavvio-------------------//
time_t curtime_reb;
struct tm *loctime_reb;
char reb_str[255];
char comando[200];
FILE *record_reb;
unsigned long lines;
curtime_reb = time (NULL);
loctime_reb = localtime (&curtime_reb);
sprintf(reb_str,"Boot\t%02d/%02d/%04d\t%02d:%02d:%02d\t%06ld\t%06ld\n",
loctime_reb->tm_mday,loctime_reb->tm_mon+1,1900+loctime_reb->tm_year,
loctime_reb->tm_hour,loctime_reb->tm_min,loctime_reb->tm_sec,
counter_in, counter_out);
record_reb = fopen("/var/neuricam/syslog.txt","a+");
fseek(record_reb,0L,SEEK_END);
lines = ftell(record_reb)/MED_LINE_LEN;
if(lines >= MAX_LOG_LINES)
{
fclose(record_reb); // the records file is full.
sprintf(comando,"rm /var/neuricam/syslog.txt");
system(comando); // removing the oldest file
record_reb = fopen("/var/neuricam/syslog.txt","a+");
}
fprintf(record_reb,"%s",reb_str);
fclose(record_reb);
// 20110914 eVS - Add boot string in records<N>.txt
{
FILE* recordfd = fopen(record_fn,"a+");
if (recordfd)
{
fseek(recordfd,0L,SEEK_END);
fprintf(recordfd, "%s", reb_str);
/*sprintf(reb_str,"Diagnostic enabled: %d\t%02d/%02d/%04d\t%02d:%02d:%02d\t%06ld\t%06ld\n", diagnostic_en,
loctime_reb->tm_mday,loctime_reb->tm_mon+1,1900+loctime_reb->tm_year,
loctime_reb->tm_hour,loctime_reb->tm_min,loctime_reb->tm_sec,
counter_in, counter_out);
fprintf(recordfd, "%s", reb_str);*/
fclose(recordfd);
}
}
////////////////////
// 20091120 eVS
//{
/* int r0 = get_parms("move_det_row0");
int r1 = get_parms("move_det_row1");
int c0 = get_parms("move_det_col0");
int c1 = get_parms("move_det_col1");
int thr = get_parms("move_det_thr");
//sprintf(reb_str, "Init: md_row0=%d\t md_row1=%d\t md_col0=%d\t md_col1=%d\t md_thr=%d\n", r0, r1, c0, c1, thr);
*/
//}
//fprintf(record_reb,"%s",reb_str);
// 20091120 eVS
////////////////////
//print_log("Init:\n\t md_r0=%d\t md_r1=%d\t md_c0=%d\t md_c1=%d\t md_thr=%d\n", r0, r1, c0, c1, thr);
//20090506 Lisbona 20111010 eVS moved after widegate initialization
//if((input_function0 == enable_counting && get_gpio("GPLR3_096")==0) || (input_function1 == enable_counting && get_gpio("GPLR2_095")==0))
// count_enabled=0; //stopping the counting
sockfd = 0;
FD_ZERO(&master); //// This function initializes the file descriptor set to contain no file descriptors.
FD_ZERO(&read_fds);
/*!
<B>Funzione SOCKET (di tipo TCP)</B>
\code
// funzione che permette di creare una socket per la comunicazione client/server
// Provvede un canale di trasmissione dati bidirezionale, sequenziale e affidabile.
// Opera su una connessione con un altro socket. I dati vengono ricevuti e trasmessi
// come un flusso continuo di byte (da cui il nome stream).
listener = socket(AF_INET, SOCK_STREAM, 0);
\endcode */
if ((listener = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
perror("socket");
print_log("Exit (socket)\n"); // 20111013 eVS, added to verify if exit
exit(1);
}
/*!
<B>Funzione SETSOCKOPT</B>
\code
// funzione che permette di settare le opzioni di una socket
setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &yes,sizeof(int));
\endcode */
if (setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &yes,sizeof(int)) == -1)
{
perror("setsockopt");
print_log("Exit (setsockopt)\n"); // 20111013 eVS, added to verify if exit
exit(1);
}
myaddr.sin_family = AF_INET;
myaddr.sin_addr.s_addr = INADDR_ANY;
myaddr.sin_port = htons(PORT);
memset(&(myaddr.sin_zero), '\0', 8);
/*!
<B>Funzione BIND</B>
\code
// Con bind si puo' assegnare un indirizzo IP specifico ad un socket,
// purche' questo appartenga ad una interfaccia della macchina.
// Per un client TCP questo diventera' l'indirizzo sorgente usato
// per i tutti i pacchetti inviati sul socket, mentre per un server TCP
// questo restringera' l'accesso al socket solo alle connessioni
// che arrivano verso tale indirizzo.
// Normalmente un client non specifica mai l'indirizzo di un socket,
// ed il kernel sceglie l'indirizzo di origine quando viene effettuata
// la connessione, sulla base dell'interfaccia usata per trasmettere i pacchetti,
// (che dipendera' dalle regole di instradamento usate per raggiungere il server).
// Se un server non specifica il suo indirizzo locale il kernel usera'
// come indirizzo di origine l'indirizzo di destinazione specificato dal SYN del client.
bind(listener, (struct sockaddr *)&myaddr, sizeof(myaddr));
\endcode */
if (bind(listener, (struct sockaddr *)&myaddr, sizeof(myaddr)) == -1)
{
perror("bind");
print_log("Exit (bind)\n"); // 20111013 eVS, added to verify if exit
exit(1);
}
/*!
<B>Funzione LISTEN</B>
\code
// La funzione listen serve ad usare un socket in modalita' passiva, cioe', come dice il nome,
// per metterlo in ascolto di eventuali connessioni; in sostanza l'effetto della funzione e' di
// portare il socket dallo stato CLOSED a quello LISTEN. In genere si chiama la funzione in un
// server dopo le chiamate a socket e bind e prima della chiamata ad accept.
listen(listener, MAX_CONN);
\endcode */
if (listen(listener, MAX_CONN) == -1)
{
perror("listen");
print_log("Exit (listen)\n"); // 20111013 eVS, added to verify if exit
exit(1);
}
FD_SET(listener, &master); //// This function adds a file descriptor to a file descriptor set.
fdmax = listener;
/*!
<b>Socket di tipo UDP</b>
\code
// Viene usato per trasmettere pacchetti di dati (datagram) di lunghezza massima prefissata,
// indirizzati singolarmente. Non esiste una connessione e la trasmissione e' effettuata
// in maniera non affidabile.
datagram = socket(AF_INET, SOCK_DGRAM, 0);
\endcode */
// 20111014 eVS, datagram creation moved in the ping_pong loop code
// datagram socket
/*if ((datagram = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
{
perror("socket");
exit(1);
}
myaddr_data.sin_family = AF_INET;
myaddr_data.sin_addr.s_addr = INADDR_ANY;
myaddr_data.sin_port = htons(PORT);
memset(&(myaddr_data.sin_zero), '\0', 8);*/
/*! \code
bind(datagram, (struct sockaddr *)&myaddr_data, sizeof(myaddr_data);
\endcode */
// 20111014 eVS, datagram bind moved in the ping_pong loop code
/*if (bind(datagram, (struct sockaddr *)&myaddr_data, sizeof(myaddr_data)) == -1)
{
perror("bind");
exit(1);
}*/
/*!
<B>Lancio dei threads e inizializzazione semafori</B>
\code
mainloop_enable(1); //starting the acquisition thread
pthread_mutex_init(&mainlock,NULL);
pthread_create (&wdloop, NULL, watchdog_loop, NULL);
pthread_create(&rdloop, NULL, record_loop, NULL);
pthread_mutex_init(&rdlock,NULL);
pthread_create (&inloop0, NULL, input_loop0, NULL);
pthread_create (&inloop1, NULL, input_loop1, NULL);
\endcode */
pthread_mutex_init(&acq_mode_lock,NULL); // 20100518 eVS
pthread_mutex_init(&mainlock,NULL);
pthread_mutex_init(&rdlock,NULL);
// 20100603 eVS moved here
if (total_sys_number > 1) {
count_sincro=0; // initialize the clock-syncro
current_sys_number_tmp = current_sys_number;
total_sys_number_tmp = total_sys_number;
if(current_sys_number_tmp!=total_sys_number_tmp)
{
save_parms("serial_sbr",B230400); //B921600
write_parms("serial_sbr",B230400);
save_parms("serial_sdb",CS8);
write_parms("serial_sdb",CS8);
save_parms("serial_spr",0);
write_parms("serial_spr",0);
save_parms("serial_ssb",0);
write_parms("serial_ssb",0);
}
// 20111010 eVS bugfix, at boot the saved configuration about input0 has already been rightly loaded
// we just commented the following part
/*if(current_sys_number_tmp!=1)
{
write_parms("input0",3);
save_parms("input0",3);
}
else if (current_sys_number_tmp==1)
{
if (get_parms("input0") != 0 && get_parms("input0") != 2)
{
write_parms("input0",0);
save_parms("input0",0);
}
}
write_parms("input1",3);
save_parms("input1",3);*/
write_parms("outtime0",4); //disable FPGA in optoO
save_parms("outtime0",4);
write_parms("outtime1",4); //disable FPGA in optoO
save_parms("outtime1",4);
// 20111010 eVS by default in widegate the system starts counting
count_enabled=1;
set_gpio("GPSR3_090",1); //enable slave people counting
if(current_sys_number_tmp>1)
{
write_parms("serial_br",B230400);
save_parms("serial_br",B230400);
write_parms("serial_db",CS8);
save_parms("serial_db",CS8);
write_parms("serial_pr",0);
save_parms("serial_pr",0);
write_parms("serial_sb",0);
save_parms("serial_sb",0);
}
if(current_sys_number_tmp==total_sys_number_tmp)
{
write_parms("outtime1",200);
save_parms("outtime1",200);
// 20111010 eVS bugfix, at boot the saved configuration about input0 has already been rightly loaded
// we just commented the following part
/*write_parms("input0",3);
save_parms("input0",3);
//initpeople(0,0);
//initpeople(people[0],people[1]);*/
}
if(current_sys_number_tmp==1)
{
write_parms("outtime0",200);
save_parms("outtime0",200);
// 20111010 eVS bugfix, at boot the saved configuration about input0 has already been rightly loaded
// we just commented the following part
/*write_parms("input1",3);
save_parms("input1",3);
usleep(500000);
unsigned char value=get_parms("autoled");
SNP_Send(slave_id,"autoled",(char *)&value,sizeof(value),ttyS1);
usleep(50000);
value=get_parms("threshold");
SNP_Send(slave_id,"threshold",(char *)&value,sizeof(value),ttyS1);
usleep(50000);
value=get_parms("dir");
SNP_Send(slave_id,"dir",(char *)&value,sizeof(value),ttyS1);
usleep(50000);
value=get_parms("detect_area");
SNP_Send(slave_id,"detect_area",(char *)&value,sizeof(value),ttyS1);
*/
}
// 20111010 eVS added conters syncronization between master and the last slave (the one actually counting)
if(current_sys_number_tmp==1)
{
unsigned long counters[2];
counters[0] = counter_in;
counters[1] = counter_out;
SNP_Send(get_parms("slave_id"), "gcounters", (char *)counters,sizeof(counters),ttyS0);
usleep(TIMEOUT_485); //wait answer
}
if(current_sys_number_tmp==1)
send_enable=1; // boot: se sono il master uso send_enable per evitare conflitti su seriale
else
send_enable=0; // boot: tutti gli slave non usano send_enable e quindi la pongono a zero
framecounter=0;
}
//20090506 Lisbona 20111010 eVS moved here from above because this code has to be placed after widegate initialization
if((input_function0 == enable_counting && get_gpio("GPLR3_096")==0) || (input_function1 == enable_counting && get_gpio("GPLR2_095")==0))
{
//count_enabled=0; //stopping the counting // 20101010 eVS commented because now there enable_counting(0)
// 20101010 eVS added check for widegate as done in the input_loop
if(total_sys_number>0 && current_sys_number!=total_sys_number) //se non sono l'ultimo
{
//faccio il ponte del segnale porta
set_gpio("GPCR3_090",1);
}
enable_counting(0); // 20101010 eVS added this emulation of the enable_counting input_function
} else {
/*if(total_sys_number>0 && current_sys_number!=total_sys_number) //se non sono l'ultimo
{//faccio il ponte del segnale porta
if((input_function0 == enable_counting && get_gpio("GPLR3_096")!=0) ||
(input_function1 == enable_counting && get_gpio("GPLR2_095")!=0) ||
(input_function0 != enable_counting && input_function1 != enable_counting)
set_gpio("GPSR3_090",1);
else
set_gpio("GPCR3_090",1);
}*/
// 20101010 eVS added check for widegate as done in the input_loop
if(total_sys_number>0 && current_sys_number!=total_sys_number) //se non sono l'ultimo
{//faccio il ponte del segnale porta
set_gpio("GPSR3_090",1);
}
enable_counting(1); // 20101010 eVS added this emulation of the enable_counting input_function
ev_door_open_rec = true; // 20101104 eVS added to properly start counting
}
mainloop_enable(1); //starting the acquisition and processing thread
pthread_create (&wdloop, NULL, watchdog_loop, NULL); //watchdog loop
pthread_create (&rdloop, NULL, record_loop, NULL);
pthread_create (&inloop0, NULL, input_loop0, NULL);
pthread_create (&inloop1, NULL, input_loop1, NULL);
//-----------------------------------------------------//
/*! \code
pthread_create (&ploop, NULL, ping_loop, NULL);
\endcode */
pthread_create (&ploop, NULL, ping_loop, NULL);
// 20100623 eVS moved above before threads creation
// 20100603 eVS moved here
/*if (total_sys_number > 1) {
count_sincro=0; // initialize the clock-syncro
current_sys_number_tmp = current_sys_number;
total_sys_number_tmp = total_sys_number;
wide_gate_serial_parms_set();
}*/
// ciclo principale di esecuzione in cui l'imgserver resta in ascolto di eventuali comandi inviati dal win_client
for(;;)
{
read_fds = master;
if (select(fdmax+1, &read_fds, NULL, NULL,NULL) == -1)
{
perror("select");
print_log("Exit (select)\n"); // 20120119 eVS, added to verify if exit
exit(1);
}
for(i = 0; i <= fdmax; i++)
{
if (FD_ISSET(i, &read_fds))
// This function returns a value for the file descriptor in the file descriptor set.
// Returns a non-zero value if the file descriptor is set in the file descriptor
// set pointed to by fdset; otherwise returns 0.
{
/*!
<b>Funzione ACCEPT</b>
\code
//new connection
if (i == listener && !connected)
{
addrlen = sizeof(remoteaddr);
// La funzione accept e' chiamata da un server per gestire la connessione una volta
// che sia stato completato il three way handshake, la funzione restituisce un nuovo
// socket descriptor su cui si potra' operare per effettuare la comunicazione.
// Se non ci sono connessioni completate il processo viene messo in attesa.
if ((newfd = accept(listener, (struct sockaddr *)&remoteaddr,&addrlen)) == -1)
{
...
\endcode */
if (i == listener && !connected) //new connection
{
addrlen = sizeof(remoteaddr);
if ((newfd = accept(listener, (struct sockaddr *)&remoteaddr,&addrlen)) == -1)
{
perror("accept");
}
else
{
FD_SET(newfd, &master); // add to master set
if (newfd > fdmax)
{
fdmax = newfd;
}
strcpy(addresses[newfd],inet_ntoa(remoteaddr.sin_addr));
printf("selectserver: new connection from %s on "
"socket %d\n", addresses[newfd], newfd);
sockfd = newfd;
/*! \code
// imgserver will send images to remoteaddr_data (see main_loop)
remoteaddr_data.sin_family = AF_INET;
remoteaddr_data.sin_addr.s_addr = remoteaddr.sin_addr.s_addr;
remoteaddr_data.sin_port = htons(UDP_PORT);
memset(&(remoteaddr_data.sin_zero), '\0', 8);
connected = true;
\endcode */
// imgserver will send images to remoteaddr_data (see main_loop)
remoteaddr_data.sin_family = AF_INET;
remoteaddr_data.sin_addr.s_addr = remoteaddr.sin_addr.s_addr;
remoteaddr_data.sin_port = htons(UDP_PORT);
memset(&(remoteaddr_data.sin_zero), '\0', 8);
connected = true;
}
}
else if(i != listener && connected)
{
/*!
<b>Configurazione della modalità di acquisizione</b>
\code
//old connection
else if(i != listener && connected)
{
if((nbytes = RecvString(i, buf,sizeof(buf))) <= 0)
{
...
// questa funzione rimuove un file descriptor dal set di fd
FD_CLR(i, &master);
// configurazione della modalita' di acquisizione
if(acq_mode != (MUX_MODE_8_FPN_ODC_MEDIAN_DISP | 0x0100))
{
acq_mode = MUX_MODE_8_FPN_ODC_MEDIAN_DISP | 0x0100;
i2cstruct.reg_addr = MUX_MODE;
i2cstruct.reg_value = acq_mode & 0x00FF;
ioctl(pxa_qcp,VIDIOCSI2C,&i2cstruct);
}
...
//starting the acquisition thread (if stopped)
mainloop_enable(1);
connected = false;
...
\endcode */
if((nbytes = RecvString(i, buf,sizeof(buf))) <= 0)
{
printf("imgserver: host %s has closed the connection\n", addresses[i]);
if (nbytes < 0) perror("recv");
images_enabled = 0;
sockfd = 0;
close(i);
// This function removes a file descriptor from the file descriptor set.
FD_CLR(i, &master);
//configuring the tracking process
if(acq_mode != (MUX_MODE_8_FPN_ODC_MEDIAN_DISP | 0x0100))
{
acq_mode = MUX_MODE_8_FPN_ODC_MEDIAN_DISP | 0x0100;
i2cstruct.reg_addr = MUX_MODE;
i2cstruct.reg_value = acq_mode & 0x00FF;
ioctl(pxa_qcp,VIDIOCSI2C,&i2cstruct);
}
if(total_sys_number>1 && current_sys_number==1)
{
send_enable=1;
}
//starting the acquisition thread (if stopped)
mainloop_enable(1);
connected = false;
}
else
/* \code
// Se la connessione valida e se stato ricevuto un comando valido dal win_client
// allora l'imgserver esegue il comando ricevuto mediante la funzione Communication
// definita nel sorgente commands.cpp
Communication(i,buf)
\endcode */
// Se la connessione valida e se stato ricevuto un comando valido dal win_client
// allora l'imgserver esegue il comando ricevuto mediante la funzione Communication
// definita nel sorgente commands.cpp
{
if(Communication(i,buf) < 0)
printf("imgserver: error executing %s command!\n",buf);
}
}
}
} // end internal for
} // end of for(;;)
/*!
<b>Cancellazione thread e chiusura dispositivi</b>
\code
deinitpeople(num_pers);
pthread_mutex_destroy(&rdlock);
pthread_mutex_destroy(&mainlock);
pthread_cancel(ploop);
pthread_cancel(rdloop);
pthread_cancel(inloop0);
pthread_cancel(mloop);
deinit_io();
\endcode */
//deinitpeople();
//pthread_mutex_destroy(&rdlock); 20100518 eVS moved after cancelling threads!!!
//pthread_mutex_destroy(&mainlock);
pthread_cancel(ploop);
pthread_cancel(rdloop);
pthread_cancel(inloop0);
pthread_cancel(inloop1); // 20100518 eVS added
pthread_cancel(mloop);
deinitpeople(num_pers); // 20100518 eVS added
deinit_io();
pthread_mutex_destroy(&rdlock);
pthread_mutex_destroy(&mainlock);
pthread_mutex_destroy(&acq_mode_lock);
return 0;
}
/*!
\brief Inizializzazione variabili.
Creazione del percorso del file contenente lo sfondo (#bg_filename),
creazione del percorso del file contenente i messaggi di log (#rd_filename),
creazione del percorso del file contenente i parametri di calibrazione (#ca_filename),
creazione del percorso del file contenente i parametri della porta seriale, no tracking zone e motion detection (#pm_filename),
creazione del percorso del file contenente i contatori (#cr_filename),
resetta i contatori delle persone entrate/uscite (#counter_in/#counter_out),
abilita il conteggio delle persone (#count_enabled),
settaggio stato porte seriali (#ttyS0=-1 e #ttyS1=-1),
inizializzazione thread (#thread_status=#MAINLOOP_STOP),
inizializzazione numero totale di sistemi connessi in serie (#total_sys_number=0),
inizializzazione indice PCN corrente (#current_sys_number=0),
disabilita l'invio delle immagini al win_client (#images_enabled=0),
illuminatori settati in modalità manuale (#autoled=false),
settaggio dello stato iniziale del people counter (#pcn_status=true),
inizializzazione altri parametri.
*/
void var_init()
{
sprintf(bg_filename,"%s%s",working_dir,BG_FILENAME); // create background file path
sprintf(rd_filename,"%s%s",working_dir,RD_FILENAME); // create records file path
sprintf(pm_filename,"%s%s",working_dir,PM_FILENAME); // create parameters file path
sprintf(ca_filename,"%s%s",working_dir,CA_FILENAME); // create calibration parameters file path
sprintf(cr_filename,"%s%s",working_dir,CR_FILENAME); // create counters file path
connected = false; //client connected
counter_in = 0; //in counter
counter_out = 0; //out counter
people_dir = 0; //incoming people go down, outgoing go up
out0 = 0; //optocoupled out0 queue
out1 = 0; //optocoupled out1 queue
records_idx = 0; //"records" buffer index
records_saving_in_progress = false;
record_enabled = 1; //enabling in/out counters recording
count_enabled = 1; //enabling counting process (via opto I/O and RS485)
ttyS0 = -1; //serial port loop status = not active
ttyS1 = -1; //serial port loop status = not active
serloopttyS0 = 0; //serial port thread init
serloopttyS1 = 0; //serial port thread init
dac_sensor = DAC_SENS; //enabling changes on both CMOS sensors
images_enabled = 0; //not sending images
/*! \code
//mainloop is not running also mainloop is running for peopledetection and peopletracking
thread_status = MAINLOOP_STOP;
\endcode */
//mainloop is not running also mainloop is running for peopledetection and peopletracking
thread_status = MAINLOOP_STOP;
wd_check = 0; // watchdog check
autoled = false;
autogain = true; //eVS added 20130927
led_status = false;
total_sys_number = 0; // total systems number connected for each door
current_sys_number = 0; // selected system index (0 none system selected???)
data_wide_gate=NULL;
pcn_status = 0; //true; // current pcn status 1->ok, 0->diagnostic found problem
old_pcn_status = 0; //true;
}
/*!
\brief Inizializzazione periferiche.
Inizializzazione dell'interfaccia quick capture (#pxa_qcp),
settaggio struttura dati video_picture (#vid_pict),
settaggio struttura dati video_window (#vid_win),
settaggio struttura dati i2cstruct,
configurazione modalità di acquisizione mediante la chiamata ioctl(),
apertura canali di comunicazione di input/output (#pcin0, #pcin1, #pcout0 e #pcout1).
<B>Le porte di input di tipo general purpose (GPI1/GPI2)</B> possono essere usate in quattro modi differenti: <BR>
Do nothing: il sistema ignora ogni segnale ricevuto sulla linea di input.<BR>
Test: permette all'operatore di testare le due linee di ingresso.<BR>
Reset counters: setta a zero i contatori degli ingressi/uscite quando viene rilevato un fronte di salita.
In configurazione wide-gate solo la porta GPI2 può essere settata come reset.<BR>
Enable/Disable counting: quando la porta GPI1/GPI2 riceve un fronte di salita il PCN inizia il processo di conteggio.
Quando la porta GPI1/GPI2 riceve un fronte di discesa il PCN blocca il processo di conteggio.
Nella configurazione wide-gate solo il GPI1 può essere settato come abilitato/disabilitato.
Per default il processo di conteggio è attivo.
<B>Le porte di output di tipo general purpose (GPO1/GPO2)</B>: le due porte di output hanno lo scopo di reagire
quando una persona viene contata. Per default la porta GPO1 è associata alle persone entranti, mentre la porta
GPO2 è associata alle persone uscenti. Quando un PCN trova una persona, uno dei due output (in base alla direzione
della persona) modifica il suo stato in aperto per un periodo di "GPO-Open-Time" millisecondi.
*/
/*
If two people walk in the same direction under the PCN-1001, the first signal will be immediately
sent to the appropriate output, the second will be queued for GPOOT for 2 milliseconds.
In the Wide-Gate configuration the GPO1 used will be the one of the first PCN-1001.
The GPO2 will be the one of the last PCN-1001. In any case, both the GPO-Open-Time have to be set
connecting the first PCN-1001.
*/
int init_io()
{
int arg;
/*! \code
// inizializzazione dell'interfaccia quick capture
pxa_qcp = open("/dev/video",O_RDWR);
\endcode */
pxa_qcp = 0;
pxa_qcp = open("/dev/video",O_RDWR);
if (pxa_qcp < 0)
{
printf("Error: cannot open /dev/video.\n");
return -1;
}
vid_pict.palette = CAMERA_IMAGE_FORMAT_RAW8;
/*! \code
// settaggio della struttura dati video_picture
ioctl(pxa_qcp,VIDIOCSPICT,&vid_pict);
\endcode */
ioctl(pxa_qcp,VIDIOCSPICT,&vid_pict);
vid_win.width = NX << 1;
vid_win.height = NY << 1;
/*! \code
// settaggio della struttura dati video_window
ioctl(pxa_qcp,VIDIOCSWIN,&vid_win);
\endcode */
ioctl(pxa_qcp,VIDIOCSWIN,&vid_win);
/*! \code
// inizializzazione cattura video
arg = VIDEO_START;
ioctl(pxa_qcp, VIDIOCCAPTURE, arg);
\endcode */
arg = VIDEO_START;
ioctl(pxa_qcp, VIDIOCCAPTURE, arg);
// -------------- fpga i2c address --------------------------
i2cstruct.adapter_nr = 0;
i2cstruct.slave_addr = 0x20;
/*! \code
// configurazione modalita' di acquisizione
acq_mode = MUX_MODE_8_FPN_ODC_MEDIAN_DISP | 0x0100;
i2cstruct.reg_addr = MUX_MODE;
i2cstruct.reg_value = acq_mode & 0x00FF;
ioctl(pxa_qcp,VIDIOCSI2C,&i2cstruct);
\endcode */
if(acq_mode != (MUX_MODE_8_FPN_ODC_MEDIAN_DISP | 0x0100))
{
acq_mode = MUX_MODE_8_FPN_ODC_MEDIAN_DISP | 0x0100;
i2cstruct.reg_addr = MUX_MODE;
i2cstruct.reg_value = acq_mode & 0x00FF;
ioctl(pxa_qcp,VIDIOCSI2C,&i2cstruct);
}
/*! \code
// viene aperto il primo dispositivo di input seriale
pcin0 = open("/dev/pcin0",O_RDWR);
// il primo dispositivo viene triggerato sul fronte di salita
ioctl(pcin0,PCIOCSIN,RISING);
\endcode */
// ------------- optocoupled I/Os ---------------------------
// viene aperto il primo dispositivo di input seriale
pcin0 = open("/dev/pcin0",O_RDWR);
if (pcin0 < 0)
{
printf("Error: cannot open /dev/pcin0.\n");
return -1;
}
// il primo dispositivo viene triggerato sul fronte di salita
ioctl(pcin0,PCIOCSIN,RISING); // triggered on rising edges
// the second input device is opened
pcin1 = open("/dev/pcin1",O_RDWR);
if (pcin1 < 0)
{
printf("Error: cannot open /dev/pcin1.\n");
return -1;
}
// the second input device is triggered onto signal rise
ioctl(pcin1,PCIOCSIN,RISING); // triggered on rising edges
// the first output device is opened
pcout0 = open("/dev/pcout0",O_RDWR);
if (pcout0 < 0)
{
printf("Error: cannot open /dev/pcout0.\n");
return -1;
}
// the second output device is opened
pcout1 = open("/dev/pcout1",O_RDWR);
if (pcout1 < 0)
{
printf("Error: cannot open /dev/pcout1.\n");
return -1;
}
/*! \code
// viene aperto il dispositivo wathdog
watchdog = open("/dev/watchdog",O_WRONLY);
if (watchdog < 0)
{
//...
}
else
{
int timeout = 30; // 30 seconds
ioctl(watchdog, WDIOC_SETTIMEOUT, &timeout);
write(watchdog, "\0", 1);
}
\endcode */
// open the wathdog device
watchdog = open("/dev/watchdog",O_WRONLY);
if (watchdog < 0)
{
printf("Warning: cannot open /dev/watchdog.\n");
printf("Warning: watchdog disabled.\n");
}
else
{
int timeout = 30; // 30 seconds
ioctl(watchdog, WDIOC_SETTIMEOUT, &timeout);
write(watchdog, "\0", 1);
}
// ----------- loading the newest records file ------------------
record_id = 0;
sprintf(record_fn,"%s%ld.txt",rd_filename,record_id);
while(file_exists(record_fn))
{
sprintf(record_fn,"%s%ld.txt",rd_filename,++record_id);
}
if(record_id > 0) sprintf(record_fn,"%s%ld.txt",rd_filename,--record_id);
return 0;
}
/*!
\brief Blocco della cattura video e chiusura delle porte di input/output, del pxa_qcp e watchdog.
*/
void deinit_io()
{
int arg;
arg = VIDEO_STOP;
// stop video capture
ioctl(pxa_qcp, VIDIOCCAPTURE, arg);
/*! \code
ioctl(pxa_qcp, VIDIOCCAPTURE, arg);
\endcode */
close(pcout0);
close(pcout1);
close(pcin0);
close(pcin1);
close(pxa_qcp);
close(watchdog);
return;
}
/*!
\brief Lettura della versione del sistema operativo dal file "/etc/system.info".
\param version versione del sistema operativo
*/
int sys_version(char *version)
{
int ret = -1;
char string[256];
FILE *fd;
if((fd = fopen(OS_FILENAME,"r")) == NULL) return -1;
else
{
do
{
ret = fscanf(fd,"%s",string);
if(!strcmp(string,"Software:"))
{
ret = fscanf(fd,"%s",string);
sprintf(version,"%s",string);
fclose(fd);
return 0;
}
}
while(ret != EOF);
fclose(fd);
}
return -1;
}
/*!
\brief Lettura della versione del kernel dal file "/proc/version".
\param version versione del kernel
*/
int ker_version(char *version)
{
float ret = -1;
char string[256];
unsigned char i,j;
FILE *fd;
if((fd = fopen(KL_FILENAME,"r")) == NULL) return -1;
else
{
do
{
ret = fscanf(fd,"%s",string);
i = 0;
while(string[i])
{
if(!strncasecmp(&string[i],"pcn1001-",8))
{
j=0;
while(string[i+8+j] && (string[i+8+j] != '-'))
{
version[j] = string[i+8+j];
j++;
}
version[j] = 0;
fclose(fd);
return 0;
}
i++;
}
}
while(ret != EOF);
fclose(fd);
}
return -1;
}
/*!
\brief Lettura della versione del bitstream nell'FPGA.
\return Numero della versione del bitstream nell'FPGA.
*/
float fw_version()
{
/*!
\code
i2cstruct.reg_value = 0;
i2cstruct.reg_addr = FW_VERSION;
ioctl(pxa_qcp,VIDIOCGI2C,&i2cstruct);
\endcode
*/
i2cstruct.reg_value = 0;
i2cstruct.reg_addr = FW_VERSION;
ioctl(pxa_qcp,VIDIOCGI2C,&i2cstruct);
return ((i2cstruct.reg_value & 0xF0) >> 4) + ((float)(i2cstruct.reg_value & 0x0F)/10);
}
/*!
\brief Checking file existence.
\param path
\return fopen result
*/
int file_exists(char *path)
{
int ret = 0;
FILE *fd;
if((fd = fopen(path,"r")) != NULL)
{
fclose(fd);
ret = 1;
}
return ret;
}
// 20100521 eVS created a common function
void prepare_for_wideconfiguration()
{
write_parms("sxlimit",SXLIMIT);
write_parms("dxlimit",DXLIMIT);
write_parms("sxlimit_riga_start",SXLIMIT_RIGA_START);
write_parms("dxlimit_riga_start",DXLIMIT_RIGA_START);
write_parms("sxlimit_riga_end",SXLIMIT_RIGA_END);
write_parms("dxlimit_riga_end",DXLIMIT_RIGA_END);
write_parms("up_line_limit",UP_LINE_LIMIT);
write_parms("down_line_limit",DOWN_LINE_LIMIT);
save_parms("sxlimit",SXLIMIT);
save_parms("dxlimit",DXLIMIT);
save_parms("sxlimit_riga_start",SXLIMIT_RIGA_START);
save_parms("dxlimit_riga_start",DXLIMIT_RIGA_START);
save_parms("sxlimit_riga_end",SXLIMIT_RIGA_END);
save_parms("dxlimit_riga_end",DXLIMIT_RIGA_END);
save_parms("up_line_limit",UP_LINE_LIMIT);
save_parms("down_line_limit",DOWN_LINE_LIMIT);
write_parms("cond_diff_1p",OFF);
save_parms("cond_diff_1p",OFF);
write_parms("move_det_en",OFF);
save_parms("move_det_en",OFF);
///////////////////
// 20091120 eVS
check_mov_det_parms();
// 20091120 eVS
////////////////////
}
/*!
\page tabella_calib Tabella riassuntiva parametri di calibrazione
Tabella che permette di capire l'associazione esistente tra indice del vettore dei
parametri di calibrazione, stringa con il nome del parametro e il valore di default.
\htmlinclude tab_cal.htm
*/
/////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////
/*!
\page tabella_parms Tabella riassuntiva parametri
Tabella che permette di capire l'associazione esistente tra indice del vettore dei parametri,
stringa con il nome del parametro e il valore di default.
\htmlinclude tab_par.htm
*/
#include "loops.cpp"
#include "commands.cpp"
#include "socket.cpp"
#include "images_fpga.cpp"
#include "io.cpp"
#include "calib_io.cpp"
#include "serial_port.cpp"
| true |
e1d9d617bdf8b18a51842aef4a865490c349ea47
|
C++
|
mitchellharvey/cryptopals
|
/challenge3.cpp
|
UTF-8
| 907 | 2.96875 | 3 |
[] |
no_license
|
#include "Utils.h"
#include <iostream>
int main(int argc, char** argv) {
std::string encoded_string = "1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736";
std::string bytes = hex::decode(encoded_string);
std::cout << "Attempt to decode: " << encoded_string << std::endl;
std::string result = encoded_string;
float best = 0.0f;
char encode_byte = '\0';
for(unsigned char i = 0; i < 255; ++i) {
std::string decoded = cipher::byte_xor(bytes, i);
float score = ascii::frequency_score(decoded);
if (score > best) {
best = score;
encode_byte = i;
result = decoded;
}
}
std::cout << std::endl;
std::cout << "Score: " << best << std::endl;
std::cout << "Byte: 0x" << hex::encode(encode_byte) << std::endl;
std::cout << "Result: " << result << std::endl;
return 0;
}
| true |
a31caa98db648d934c5268659e62ea1d77cb490b
|
C++
|
lordnynex/CLEANUP
|
/FORKS/C/L.A.S.E.R.-TAG-GRL/tree/libs/ofAddons/computerVision/ofCvColorImage.h
|
UTF-8
| 1,122 | 2.6875 | 3 |
[
"WTFPL",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
#ifndef _CV_COLOR_IMAGE_H
#define _CV_COLOR_IMAGE_H
//----------------
#include "ofMain.h"
#include "ofCvConstants.h"
//------------------------------------
class ofCvColorImage {
public:
ofCvColorImage();
void allocate(int _w, int _h);
void clear();
void setFromPixels(unsigned char * _pixels, int w, int h);
void warpIntoMe(ofCvColorImage &mom, ofPoint2f src[4], ofPoint2f dst[4]);
unsigned char * getPixels();
IplImage * getCvImage(){ return cvImage;};
void rgbToHsv();
void hsvToRgb();
void draw(float x, float y);
void draw(float x, float y, float w, float h);
int width, height;
private:
//----------------------------
// internal functionality
// we will use two iplImages internally, since many of the
// operations expect a "src" and a "swap"
//----------------------------
IplImage * cvImage;
IplImage * cvImageTemp;
void swapTemp(); // make the "dst" image the current "src" image
unsigned char * pixels; // not width stepped
ofTexture tex; // internal tex
};
#endif
| true |
3ec62cc59a356ba205917b5a75a171ed22a985e4
|
C++
|
ANetCode/Netcode
|
/ext/netcode/network/message.cpp
|
UTF-8
| 1,353 | 2.828125 | 3 |
[] |
no_license
|
#include "message.h"
message::message(lua_State* L) {
this->L = L;
m_udata = nullptr;
reset();
}
bool message::parse(buffer& buffer) {
if (m_ready == true)
return true;
if(m_message_start == false) {
m_message_start = true;
const uint8_t* raw_data = buffer.r_data();
m_length = *((int32_t*)raw_data);
if (m_length > 16 * 1024 * 1024) {
return false;
}
buffer.pop_front(4);
}
if (buffer.size() == 0) return true;
// 完成此消息还需要的长度
size_t nbyte_left = m_length - m_buffer.size();
if(nbyte_left >= buffer.size()) { // buffer 数据不够, 全部吃完
m_buffer.copy(buffer);
buffer.reset();
} else {
// 吃掉一部分buffer, 余下部分是数据其他消息
m_buffer.copy(buffer.r_data(), nbyte_left);
buffer.pop_front(nbyte_left);
}
// is is ready
if (m_length == m_buffer.size()) {
m_content = std::string((char*) m_buffer.r_data());
m_ready = true;
m_message_start = false;
m_buffer.reset();
}
return true;
}
bool message::is_ready() {
return m_ready;
}
std::string message::content() {
return m_content;
}
void message::reset() {
m_message_start = false;
m_ready = false;
m_content = "";
}
| true |
bc1cf6d3b93f06401cf1cb7a67f5e855a893194c
|
C++
|
Jazzcharles/ACM-ICPC-Code
|
/shuoj/1664/main.cpp
|
UTF-8
| 248 | 2.53125 | 3 |
[] |
no_license
|
#include<stdio.h>
int main()
{
int n,i,j,a[100];
char ch;
while(scanf("%d",&n)!=EOF)
{
ch=getchar();
for(i=0;n!=0;i++)
{
a[i]=n%3;
n=n/3;
}
for(j=i-1;j>=0;j--)
putchar(a[j]+'0');
printf("\n");
}
return 0;
}
| true |
ecd17869a82cb29b841b942d1d823e64c5932b74
|
C++
|
ksychla/DiscreteKnapsackProblem
|
/DiscreteKnapsackProblem/main.cpp
|
UTF-8
| 2,039 | 2.875 | 3 |
[] |
no_license
|
//
// main.cpp
// DiscreteKnapsackProblem
//
// Created by Krzysztof Sychla on 17.05.2018.
// Copyright © 2018 Krzysztof Sychla. All rights reserved.
//
#include <iostream>
#include "BackPack.hpp"
#include <fstream>
#include "Timer.hpp"
int main(int argc, const char * argv[]) {
int C;
int n;
std::fstream dane1;
std::fstream dane2;
std::fstream wynik1;
std::fstream wynik2;
dane1.open("dane_1.txt",std::ios_base::in);
dane2.open("dane_2.txt",std::ios_base::in);
wynik1.open("wynik_1.txt",std::ios_base::app);
wynik2.open("wynik_2.txt",std::ios_base::app);
Timer time;
while(!dane1.eof()){
dane1 >> C;
dane1 >> n;
int *weight = new int[n];
int *price = new int [n];
for (int j=0;j<n;j++){
dane1 >> weight[j];
dane1 >> price[j];
}
BackPack *plecak = new BackPack(C,n,price,weight);
std::cout<<"Executing n: "<<n;
time.StartTimer();
plecak->BruteForce();
time.EndTimer();
wynik1<<time.GetDelta()<<"\t";
time.StartTimer();
plecak->DynamicProgramming();
time.EndTimer();
wynik1<<time.GetDelta()<<"\n";
std::cout<<" DONE"<<"\n";
delete [] weight;
delete [] price;
delete plecak;
}
while(!dane2.eof()){
dane2 >> C;
dane2 >> n;
int *weight = new int[n];
int *price = new int [n];
for (int j=0;j<n;j++){
dane2 >> weight[j];
dane2 >> price[j];
}
BackPack *plecak = new BackPack(C,n,price,weight);
std::cout<<"Executing C: "<<C;
time.StartTimer();
plecak->BruteForce();
time.EndTimer();
wynik2<<time.GetDelta()<<"\t";
time.StartTimer();
plecak->DynamicProgramming();
time.EndTimer();
wynik2<<time.GetDelta()<<"\n";
std::cout<<" DONE"<<"\n";
delete [] weight;
delete [] price;
delete plecak;
}
return 0;
}
| true |
e566ab24a15e9d9b910213ffcd99a884147137c2
|
C++
|
kusan-thana/PLT
|
/src/common/engine.cpp
|
UTF-8
| 2,980 | 2.625 | 3 |
[] |
no_license
|
#include "engine.hpp"
#include <iostream>
using namespace engine;
Engine::Engine(state::LevelState& levelState) : levelState(levelState), actions(levelState), engineMode(PLAY) {
commandSet = new engine::CommandSet();
commandSet2 = new engine::CommandSet();
}
Engine::~Engine() {
free(commandSet);
free(commandSet2);
}
void Engine::addCommand(Command *cmd) {
commandSet2->set(cmd);
}
void Engine::setMode(EngineMode mode) {
engineMode = mode;
}
state::LevelState& Engine::getLevelState() const{
return this->levelState;
}
EngineMode Engine::getMode() {
return engineMode;
}
void Engine::update() {
swapCommands();
Ruler ruler(this->actions, *commandSet, this->levelState);
if (commandSet->size()) {
if (commandSet->get(MODE)) {
setMode(((ModeCommand*)commandSet->get(MODE))->getMode());
}
if (engineMode == PLAY){
//MODIFICATION ETAT
update_mutex.lock();
ruler.apply();
update_mutex.unlock();
//FIN MODIFICATION ETAT
turnGestion();
//MODIFICATION ETAT
update_mutex.lock();
actions.apply();
update_mutex.unlock();
//FIN MODIFICATION ETAT
actions.clear();
}
else if (engineMode == SAVE){
levelStateSave =levelState.clone();
engineMode = PLAY;
}
else if (engineMode == LOADSAVE) {
levelState.copy(*levelStateSave);
levelState.getElementList().notifyObservers(-1);
levelState.getElementGrid().notifyObservers(-1,-1);
engineMode = PLAY;
}
else if (engineMode == ROLLBACK) {
engineMode = PLAY;
}
commandSet->clear();
}
}
void Engine::turnGestion() {
//Gestion des tours
state::ElementList& elementList = levelState.getElementList();
if (levelState.getTurnToPlay() == state::PLAYER) {
for(int i = 0, count = 0; i < levelState.getElementList().size();i++){
state::MobileElement* curr_mobileElement = (state::MobileElement*)elementList.getElement(i);
if(curr_mobileElement->isPlayerCharacter()){ //Si c'est un personnage
if (curr_mobileElement->getTurnPlayed()){ //Si ce personnage a joué
count++;
if (count == elementList.numberOfPlayer()){ //Si l'ensemble des personnage a joué - Opponent turn
actions.add(new EndTeamTurn(state::PLAYER));
}
}
}
}
}
else if (levelState.getTurnToPlay() == state::OPPONENT) {
for(int i = 0, count = 0; i < levelState.getElementList().size();i++){
state::MobileElement* curr_mobileElement = (state::MobileElement*)elementList.getElement(i);
if(!curr_mobileElement->isPlayerCharacter()){ //Si c'est un personnage
if (curr_mobileElement->getTurnPlayed()){ //Si ce personnage a joué
count++;
if (count == elementList.numberOfMonster()){ //Si l'ensemble des personnage a joué - Player turn
actions.add(new EndTeamTurn(state::OPPONENT));
}
}
}
}
}
}
std::mutex& Engine::getUpdateMutex() const{
return update_mutex;
}
void Engine::swapCommands(){
CommandSet* tmp;
tmp = commandSet;
commandSet = commandSet2;
commandSet2 = tmp;
}
| true |
bafd593d296ecac582bce9f7975d2101f1d50eff
|
C++
|
avaz1301/schoolProjects
|
/Advanced OOP in C++/InvertedIndex/Invertedindex.cpp
|
UTF-8
| 2,239 | 3.28125 | 3 |
[] |
no_license
|
//Angelo Zamudio CS381 Summer 16'
#include <iostream>
#include <fstream>
#include <sstream>
#include <map>
#include <vector>
using namespace std;
class InvertedIndex {
private:
map<string, pair<int, vector<int>>> wordIndex;
public:
InvertedIndex() { };
~InvertedIndex(){};
bool alreadyIndexed(string x, int line_num, int line_pos) {
map<std::string, std::pair<int, vector<int>>>::iterator i = wordIndex.find(x);
if (i != wordIndex.end()) {
i->second.first += 1;
i->second.second.push_back(line_num);
i->second.second.push_back(line_pos);
return true;
}//if
return false;
}//alreadyIndexed
void addToindex(string x, int line_num, int line_pos) {
if (alreadyIndexed(x, line_num, line_pos)) {
return;
} else {
wordIndex[x] = {1, {line_num, line_pos}};
return;
}//else
}//addToIndex
void printIndex() {
int count = 0;
for (auto i: wordIndex) {
cout << i.first << " " << i.second.first<<" [ ";
for (auto j:i.second.second) {
if (count % 2 == 0) {
cout << "(" << j << ",";
count++;
} else if (count % 2 == 1) {
cout << j << ") ";
count++;
}//if
}//forj
cout << "]\n\n";
count = 0;
}//for i
return;
}//printIndex
};
int main(int argc, char *argv[]) {
InvertedIndex a;
int count = 1;
size_t line_pos;
string word;
ifstream in(argv[1]);
string line;
if (in) {
while (getline(in, line)) {
stringstream ss(line);
while (ss >> word) {
line_pos = line.find(word);
for (int i = 0; i < word.length(); i++) {
if (word[i] == ',' || word[i] == '.') {
word.erase(word.begin() + i);
}//if
}//for
a.addToindex(word, count, int(line_pos));
}//while word
count += 1;
}//while line
}//open
in.close();
a.printIndex();
return 0;
};
| true |
fc00aa7e5cfba0e04ab3a1c8f69ab24de7bb8116
|
C++
|
Yiwen-Gao/final-project
|
/src/network/resps.cpp
|
UTF-8
| 1,800 | 2.734375 | 3 |
[] |
no_license
|
#include "conn.h"
using namespace std;
const string CONTENT_OP = "Content-Length:";
string BaseResp::get_header() {
return "HTTP/1.0 200 OK";
}
string BaseResp::get_body() {
return "";
}
// recv own cert resp
CertResp::CertResp(string cert) {
this->cert = cert;
}
string CertResp::get_body() {
string data = cert + "\n";
return CONTENT_OP + " " + to_string(data.length()) + "\n" + data;
}
// recv recipient certs resp
MailCertResp::MailCertResp(vector<string> certs) {
this->certs = certs;
}
MailCertResp::MailCertResp(string content) {
vector<string> lines = str_to_vec(content);
string curr = "";
for (string line : lines)
{
curr += line + "\n";
if (line.find("END CERTIFICATE") != string::npos)
{
this->certs.push_back(curr);
curr = "";
}
}
}
string MailCertResp::get_body() {
string data = vec_to_str(certs);
return CONTENT_OP + " " + to_string(data.length()) + "\n" + data;
}
// recvmsg resp
MailResp::MailResp(string content) {
int one = content.find("\n");
if (one == string::npos)
{
return;
}
int two = content.substr(0, one + 1).find("\n");
if (two == string::npos)
{
return;
}
address = content.substr(0, one + two + 1);
msg = content.substr(one + two + 2);
cout << endl << endl << "address: " << address << endl;
cout << endl << "msg: " << msg << endl;
}
string MailResp::get_body() {
string data = address + "\n\n" + msg + "\n";
return CONTENT_OP + " " + to_string(data.length()) + "\n" + data;
}
string remove_headers(string &http_content) {
int i1 = http_content.find("\n");
int i2 = http_content.substr(i1 + 1).find("\n");
return http_content.substr(i1 + 1).substr(i2 + 1);
}
| true |
96b515fb2cfeae3a81652cbd0c37e3f7123dac62
|
C++
|
rouille/Toolkit
|
/simuevents.h
|
UTF-8
| 3,783 | 2.875 | 3 |
[] |
no_license
|
#ifndef _SIMUEVENTS_H
#define _SIMUEVENTS_H
#include <vector>
#include "events.h"
#include "healpixmap.h"
#include "TRandom2.h"
using namespace std;
/*! \file simuevents.h
This file contains the codes we developped for simulating events. The procedure is described in GAP2005-083.
We simulate the events according to a underlying anisotropic map provided by the user in input, this map can
contain large scale anisotropies, points sources or any sky pattern. It accounts for the zenith angle acceptance
and optionnaly a time variable acceptance of the array. The events are returned as a vector<TEvent> that can be
directly used in our analysis tools.
*/
/*!
Event simulator: map is the input anisotropic map (the map one would get with an infinite number of events).
nEvents is the number of events to be simulated. thetaLaw and pThetaLaw are the shape of the zenith angle
acceptance. thetaLaw is in degrees and has to go up to \f$ 180^\circ \f$ (obviously it is zero between
\f$ 90^\circ \f$ and \f$ 180^\circ \f$). The optional arguments utcFile, jdFile and globalFile are files where
the relative acceptance is described as a function of time. The files have to be in ASCII format with two
columns : time (utcFile : hour, jdFile : julian day and global file: UTC seconds) and relative accetpance.
utcFile and jdFile may be used as the same time if your acceptance model depends separately on the time of the
day (utcFile) and date of the year (jdFile). The globalFile case is when your model is more general and depend
on the time in a complex way, you then specify the acceptance as a function of the time in general (in UTC
seconds - from January 1st, 1970). A detailed description of the algorithms used here can be found in
GAP2005-083.
*/
vector<TEvent> SimulateEvents(const THealpixMap & map, unsigned int nEvents, const vector<double> & thetaLaw, const vector<double> & pThetaLaw, double latSite, double lonSite, string utcFile = "", string jdFile = "", string globalFile = "");
//! Simple case of an isotropic distribution
vector<TEvent> SimulateIsoEvents(unsigned int nEvents, const vector<double> & thetaLaw, const vector<double> & pThetaLaw, double latSite, double lonSite);
//! It generates the UTC distribution. Uniform if utcFile is not supplied.
void UtcGenerator(string utcFile, vector<double> & utc, vector<double> & pUtc);
//! It generates the JD distribution. Uniform if jdFile is not supplied.
void JdGenerator(string jdFile, vector<double> & jd, vector<double> & pJd);
//! It generates the temporal distribution enclosed in globalFile.
void GlobalTimeGenerator(string globalFile, vector<double> & jd, vector<double> & pJd);
/*!
This function returns nb values distributed randomly following the distribution specified by x and y vectors.
The algorithm used here is the inverse transform method.
*/
vector<double> distri(const vector<double> & x, const vector<double> & y, unsigned int nb);
/*!
This function returns one value distributed randomly following the distribution specified by x and y vectors.
The algorithm used here is the inverse transform method.
*/
double distri(const vector<double> & x, const vector<double> & y);
/*!
This function returns nb integer values distributed randomly following the distribution specified by x and y
vectors. The algorithm used here is the inverse transform method.
*/
vector<long> distriDiscrete(const vector<long> & x, const vector<double> & y, unsigned int nb);
/*!
This function returns one integer value distributed randomly following the distribution specified by x and y
vectors. The algorithm used here is the inverse transform method.
*/
long distriDiscrete(const vector<long> & x, const vector<double> & y);
#endif
| true |
619da65c7a0afdf6131df09dbc9b805312840ce8
|
C++
|
HyunHub/Learning-Algorithm
|
/practice60/practice65.cpp
|
UHC
| 705 | 2.84375 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <vector>
#include <algorithm>
using namespace std;
// ̷ Ž(DFS)
int map[8][8];
int ch[8][8];
// ð
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, 1, 0, -1};
int n, i, j, cnt;
void DFS(int x, int y) {
int i, xx, yy; // ǥ
if(x==7&& y==7){
cnt++;
}
else {
for(i=0; i<4; i++) {
xx=x+dx[i];
yy=y+dy[i];
if(xx<1 || xx>7 || yy<1 || yy>7) continue;
if(map[xx][yy] == 0 && ch[xx][yy]==0) {
ch[xx][yy] =1;
DFS(xx, yy);
ch[xx][yy] =0;
}
}
}
}
int main() {
for(i=1; i<=7; i++) {
for(j=1; j<=7; j++) {
scanf("%d", &map[i][j]);
}
}
ch[1][1] =1;
DFS(1,1);
printf("%d ", cnt);
}
| true |
98245df0758a0867ca2cef7ff9b3d36ae9c74b50
|
C++
|
Chigric/Mag_2_course_1_Lab
|
/lab3/lab3.cpp
|
UTF-8
| 2,743 | 2.796875 | 3 |
[] |
no_license
|
#include <cassert>
#include <map>
#include <functional>
#include <numeric>
#include "lab3.h"
#include "Output.hpp"
namespace SundayWork {
// Solving coefficients for solution Volterra integral equation
Vector coefsForVolterraIntegralEquation(ECubatureRules cubatureRule, std::size_t amountPoints)
{
Vector coefs(0.L, amountPoints);
switch (cubatureRule) {
case ECubatureRules::Trapezoidal:
for (std::size_t i = 0; i < amountPoints-1; i++) {
coefs[i+0] += 0.5L;
coefs[i+1] += 0.5L;
}
break;
case ECubatureRules::Simpson:
coefs[0] = (1.L/3);
coefs[amountPoints-1] = (1.L/3);
for (size_t m = 1; m <= amountPoints/2 - 1; m++) {
if (m*2 < amountPoints)
coefs[m*2] = (4.L/8);
}
for (size_t m = 1; m <= amountPoints/2; m++) {
if (m*2 < amountPoints) {
coefs[m*2 - 1] = (6.L/4);
}
}
break;
case ECubatureRules::Simpson_3by8:
coefs[0] = (3.L/8);
coefs[amountPoints-1] = (3.L/8);
for (size_t m = 1; m <= amountPoints/3 - 1; m++) {
if (m*3 < amountPoints)
coefs[m*3] = (6.L/8);
}
for (size_t m = 1; m <= amountPoints/3; m++) {
if (m*3 < amountPoints) {
coefs[m*3 - 2] = (9.L/8);
coefs[m*3 - 1] = (9.L/8);
}
}
break;
default:
assert(false && "I cann't to work with this method");
break;
}
return std::move(coefs);
}
// Successive approximation method (solve Volterra integral equation of the second kind)
Vector successiveApproximationMethodVolterra(MaxDouble startIntegral
, MaxDouble endIntegral
, SpecFunc2Arg kernelFunc
, SpecFunc rightFunc
, ECubatureRules cubatureRule
, std::size_t amountPoints
)
{
using namespace std;
Vector nodes(amountPoints);
MaxDouble step = (endIntegral - startIntegral) / (amountPoints-1);
auto nodeI = [&startIntegral, &step](size_t i) -> MaxDouble {
return startIntegral+step*i;
};
Vector coefs = SundayWork::coefsForVolterraIntegralEquation(cubatureRule, amountPoints);
nodes[0] = rightFunc(startIntegral);
for (size_t i = 1; i < amountPoints; i++) {
MaxDouble curNode = nodeI(i);
MaxDouble sunEquation = 0.L;
for (size_t j = 0; j < i; j++) {
MaxDouble curSubNode = nodeI(j);
sunEquation += coefs[j] * kernelFunc(curNode, curSubNode) * nodes[j];
}
nodes[i] += 1/(1 - step*coefs[0]*kernelFunc(curNode, curNode))
* (rightFunc(curNode) + step*sunEquation);
}
return nodes;
}
};
| true |
609e574f66cd855cf7cfb3e62bfa13935a8ec8ca
|
C++
|
xavierfebrer/sample1_fire_shaders
|
/sample1_fire_shaders/sample1_fire_shaders/core/include/Animation.h
|
UTF-8
| 734 | 2.78125 | 3 |
[] |
no_license
|
#pragma once
#include "Util.h"
#include "AnimationStep.h"
class Animation {
private:
double deltaTimeLeft;
int initialLoopsLeft;
int loopsLeft;
int currentStepIndex;
std::vector<std::unique_ptr<AnimationStep>> steps;
public:
Animation(std::vector<std::unique_ptr<AnimationStep>> steps, int loopTimes = -1);
virtual ~Animation();
void setLoopTimes(int loopTimes);
const bool isInfinite() const;
const int getLoopsLeft();
void decreaseLoopsLeft();
const bool hasEnded() ;
void update(double deltaTime, double scale = 1.0);
const bool nextCurrentStepIndex();
void setSteps(std::vector<std::unique_ptr<AnimationStep>> steps);
void restart();
AnimationStep& getCurrentStep();
const double getDuration() const;
};
| true |
60c0369f93e8c6a1a50eee30d6d8c395ad29c883
|
C++
|
cumtmiao/Algrithm
|
/leecode/Tree/Flatten_Binary_Tree_to_Linked_List.cpp
|
UTF-8
| 1,695 | 3.75 | 4 |
[] |
no_license
|
/*
Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
*/
#include<bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
/*
定义了额外的存储空间。不符合题意,
题目要求在原始树的基础上直接转换。
*/
// vector<int> res;
// void preordertraverse(TreeNode* root)
// {
// if(root==nullptr)
// return ;
// res.push_back(root->val);
// preordertraverse(root->left);
// preordertraverse(root->right);
// }
// TreeNode* reconstruct(vector<int> res,int &index)
// {
// if(index==res.size())
// return nullptr;
// TreeNode* root=new TreeNode(0);
// root->val=res[index];
// index=index+1;
// root->right=reconstruct(res,index);
// return root;
// }
// void flatten(TreeNode* root) {
// preordertraverse(root);
// int index=0;
// root=reconstruct(res,index);
// }
/*
使用先序遍历。先访问到最左子节点,递归将左子树移动到当前节点的右子树,同时将左子树赋值为nullptr;
之后再将原来右子树接到现右子树的末端。
*/
void flatten(TreeNode* root) {
if(root==nullptr)
return ;
if(root->left)
flatten(root->left);
if(root->right)
flatten(root->right);
TreeNode *temp=root->right;
root->right=root->left;
root->left=nullptr;
while(root->right)
root=root->right;
root->right=temp;
return ;
}
| true |
f6ceb2cc671997bf69ed4c463b4861a938e58c52
|
C++
|
danakreimer/ProblemSolver
|
/FileCacheManager.h
|
UTF-8
| 3,278 | 3.3125 | 3 |
[] |
no_license
|
//
// Created by duni on 12/01/2020.
//
#ifndef PROBLEMSOLVER_FILECHACHEMANAGER_H
#define PROBLEMSOLVER_FILECHACHEMANAGER_H
#include <fstream>
#include <mutex>
#include "CacheManager.h"
using namespace std;
template<class Problem>
class FileCacheManager : public CacheManager<Problem, string> {
private:
std::mutex fileLock;
public:
// This function checks the cache if a current solution exists and returns the result
bool doesSolutionExist(Problem p, string algorithmName) {
fileLock.lock();
ifstream file;
string strFileName = "";
char currentChar;
int i;
// Preform hash function on the problem to save the file in a unique way
std::size_t fileName = std::hash<std::string>{}(p);
strFileName = std::to_string(fileName);
// Concatenate the algorithm name which solved the problem to the result of the hash function
strFileName += algorithmName;
// Concatenate the ending of the file name
strFileName.append(".txt");
file.open(strFileName);
// Check if the wanted file exists in the cache
bool doesExist = file.good();
file.close();
fileLock.unlock();
return doesExist;
}
// This function saves the solution in the cache
void saveSolution(Problem p, string s, string algorithmName) {
fileLock.lock();
ofstream file;
string strFileName = "";
char currentChar;
int i;
// Preform hash function on the problem to save the file in a unique way
std::size_t fileName = std::hash<std::string>{}(p);
strFileName = std::to_string(fileName);
// Concatenate the algorithm name which solved the problem to the result of the hash function
strFileName += algorithmName;
// Concatenate the ending of the file name
strFileName.append(".txt");
// Open the file
file.open(strFileName, ios::app);
if (file.is_open()) {
// Write the solution into the file
file << s << endl;
//file.write((char *) &s, sizeof(s));
} else {
throw "could not open file";
}
file.close();
fileLock.unlock();
}
// This function returns the solution from the cache
string getSolution(Problem p, string algorithmName) {
fileLock.lock();
ifstream file;
string strFileName;
char currentChar;
int i;
string s;
// Preform hash function on the problem to save the file in a unique way
std::size_t fileName = std::hash<std::string>{}(p);
strFileName = std::to_string(fileName);
// Concatenate the algorithm name which solved the problem to the result of the hash function
strFileName += algorithmName;
// Concatenate the ending of the file name
strFileName.append(".txt");
// Open the file that contains the solution
file.open(strFileName, ios::in);
if (file.is_open()) {
getline(file, s);
} else {
throw "object doesnt exist in cache or files";
}
file.close();
fileLock.unlock();
return s;
}
};
#endif //PROBLEMSOLVER_FILECHACHEMANAGER_H
| true |
83931e7b08074ffce774613f673ae392dcf411e4
|
C++
|
theomission/layerlab
|
/src/fourier.cpp
|
UTF-8
| 17,027 | 2.6875 | 3 |
[
"BSD-2-Clause"
] |
permissive
|
/*
fourier.cpp -- Functions for sampling and evaluating Fourier series
Copyright (c) 2015 Wenzel Jakob <wenzel@inf.ethz.ch>
All rights reserved. Use of this source code is governed by a
BSD-style license that can be found in the LICENSE file.
*/
#include <layer/fourier.h>
#include <layer/simd.h>
NAMESPACE_BEGIN(layer)
#if defined(__AVX__)
static void initializeRecurrence(double c, __m256d &factor_prev, __m256d &factor_cur) {
/* How to generate:
c[0] = 1;
c[1] = c;
c[n_] := Expand[2 c c[n - 1] - c[n - 2]]
last = 2 c;
For[i = 3, i <= 9, ++i,
last = Expand[(c[i] + last)/c];
Print[last]
]
*/
double c2 = c*c,
temp1 = 2.0*c,
temp2 = -1.0+4.0*c2,
temp3 = c*(-4.0+8.0*c2),
temp4 = 1.0+c2*(-12.0+16.0*c2);
factor_prev = _mm256_set_pd(-temp3, -temp2, -temp1, -1.0f);
factor_cur = _mm256_set_pd( temp4, temp3, temp2, temp1);
}
#endif
Float evalFourier(const float *coeffs, size_t nCoeffs, Float phi) {
#if FOURIER_SCALAR == 1
double cosPhi = std::cos((double) phi),
cosPhi_prev = cosPhi,
cosPhi_cur = 1.0,
value = 0.0;
for (size_t i=0; i<nCoeffs; ++i) {
value += coeffs[i] * cosPhi_cur;
double cosPhi_next = 2.0*cosPhi*cosPhi_cur - cosPhi_prev;
cosPhi_prev = cosPhi_cur; cosPhi_cur = cosPhi_next;
}
return (Float) value;
#else
double cosPhi = std::cos((double) phi);
__m256d
cosPhi_prev = _mm256_set1_pd(cosPhi),
cosPhi_cur = _mm256_set1_pd(1.0),
value = _mm256_set_sd((double) coeffs[0]),
factorPhi_prev, factorPhi_cur;
initializeRecurrence(cosPhi, factorPhi_prev, factorPhi_cur);
for (size_t i=1; i<nCoeffs; i+=4) {
__m256d coeff = _mm256_cvtps_pd(_mm_load_ps(coeffs+i));
__m256d cosPhi_next = _mm256_add_pd(_mm256_mul_pd(factorPhi_prev, cosPhi_prev),
_mm256_mul_pd(factorPhi_cur, cosPhi_cur));
value = _mm256_add_pd(value, _mm256_mul_pd(cosPhi_next, coeff));
cosPhi_prev = _mm256_splat2_pd(cosPhi_next);
cosPhi_cur = _mm256_splat3_pd(cosPhi_next);
}
return (Float) simd::hadd(value);
#endif
}
Color3 evalFourier3(float * const coeffs[3], size_t nCoeffs, Float phi) {
#if FOURIER_SCALAR == 1
double cosPhi = std::cos((double) phi),
cosPhi_prev = cosPhi,
cosPhi_cur = 1.0f;
double Y = 0, R = 0, B = 0;
for (size_t i=0; i<nCoeffs; ++i) {
Y += coeffs[0][i] * cosPhi_cur;
R += coeffs[1][i] * cosPhi_cur;
B += coeffs[2][i] * cosPhi_cur;
double cosPhi_next = 2*cosPhi*cosPhi_cur - cosPhi_prev;
cosPhi_prev = cosPhi_cur; cosPhi_cur = cosPhi_next;
}
double G = 1.39829f*Y -0.100913f*B - 0.297375f*R;
return Color3((Float) R, (Float) G, (Float) B);
#else
double cosPhi = std::cos((double) phi);
__m256d
cosPhi_prev = _mm256_set1_pd(cosPhi),
cosPhi_cur = _mm256_set1_pd(1.0),
Y = _mm256_set_sd((double) coeffs[0][0]),
R = _mm256_set_sd((double) coeffs[1][0]),
B = _mm256_set_sd((double) coeffs[2][0]),
factorPhi_prev, factorPhi_cur;
initializeRecurrence(cosPhi, factorPhi_prev, factorPhi_cur);
for (size_t i=1; i<nCoeffs; i+=4) {
__m256d cosPhi_next = _mm256_add_pd(_mm256_mul_pd(factorPhi_prev, cosPhi_prev),
_mm256_mul_pd(factorPhi_cur, cosPhi_cur));
Y = _mm256_add_pd(Y, _mm256_mul_pd(cosPhi_next, _mm256_cvtps_pd(_mm_load_ps(coeffs[0]+i))));
R = _mm256_add_pd(R, _mm256_mul_pd(cosPhi_next, _mm256_cvtps_pd(_mm_load_ps(coeffs[1]+i))));
B = _mm256_add_pd(B, _mm256_mul_pd(cosPhi_next, _mm256_cvtps_pd(_mm_load_ps(coeffs[2]+i))));
cosPhi_prev = _mm256_splat2_pd(cosPhi_next);
cosPhi_cur = _mm256_splat3_pd(cosPhi_next);
}
MM_ALIGN32 struct {
double Y;
double R;
double B;
double unused;
} tmp;
simd::hadd(Y, R, B, _mm256_setzero_pd(), (double *) &tmp);
double G = 1.39829*tmp.Y -0.100913*tmp.B - 0.297375*tmp.R;
return Color3((Float) tmp.R, (Float) G, (Float) tmp.B);
#endif
}
Float sampleFourier(const float *coeffs, const double *recip, size_t nCoeffs,
Float sample, Float &pdf, Float &phi) {
bool flip = false;
if (sample < 0.5f) {
sample *= 2.0f;
} else {
sample = 1.0f - 2.0f * (sample - 0.5f);
flip = true;
}
int iterations = 0;
double a = 0.0,
c = math::Pi_d,
coeff0 = coeffs[0],
y = coeff0*math::Pi_d*sample,
deriv = 0.0,
b = 0.5 * math::Pi_d,
sinB = 1,
cosB = 0;
if (nCoeffs > 10 && sample != 0 && sample != 1) {
float stddev = std::sqrt(2.0f/3.0f * std::log(coeffs[1]/coeffs[2]));
if (std::isfinite(stddev)) {
b = std::min(c, (double) math::normal_quantile(0.5f + sample/2) * stddev);
cosB = std::cos(b);
sinB = std::sqrt(1-cosB*cosB);
}
}
while (true) {
#if FOURIER_SCALAR == 1
double cosB_prev = cosB,
sinB_prev = -sinB,
sinB_cur = 0.0,
cosB_cur = 1.0,
value = coeff0 * b;
deriv = coeff0;
for (size_t j=1; j<nCoeffs; ++j) {
double sinB_next = 2.0*cosB*sinB_cur - sinB_prev,
cosB_next = 2.0*cosB*cosB_cur - cosB_prev,
coeff = (double) coeffs[j];
value += coeff * recip[j] * sinB_next;
deriv += coeff * cosB_next;
sinB_prev = sinB_cur; sinB_cur = sinB_next;
cosB_prev = cosB_cur; cosB_cur = cosB_next;
}
#else
__m256d factorB_prev, factorB_cur;
initializeRecurrence(cosB, factorB_prev, factorB_cur);
__m256d
sinB_prev = _mm256_set1_pd(-sinB),
sinB_cur = _mm256_set1_pd(0.0),
cosB_prev = _mm256_set1_pd(cosB),
cosB_cur = _mm256_set1_pd(1.0),
value_vec = _mm256_set_sd(coeff0 * b),
deriv_vec = _mm256_set_sd(coeff0);
for (size_t j=1; j<nCoeffs; j+=4) {
__m128 coeff_vec_f = _mm_load_ps(coeffs+j);
__m256d recip_vec = _mm256_load_pd(recip+j);
__m256d coeff_vec = _mm256_cvtps_pd(coeff_vec_f);
__m256d sinB_next = _mm256_add_pd(
_mm256_mul_pd(factorB_prev, sinB_prev),
_mm256_mul_pd(factorB_cur, sinB_cur));
__m256d cosB_next = _mm256_add_pd(
_mm256_mul_pd(factorB_prev, cosB_prev),
_mm256_mul_pd(factorB_cur, cosB_cur));
value_vec = _mm256_add_pd(value_vec, _mm256_mul_pd(
_mm256_mul_pd(recip_vec, coeff_vec), sinB_next));
deriv_vec = _mm256_add_pd(deriv_vec, _mm256_mul_pd(coeff_vec, cosB_next));
sinB_prev = _mm256_splat2_pd(sinB_next);
cosB_prev = _mm256_splat2_pd(cosB_next);
sinB_cur = _mm256_splat3_pd(sinB_next);
cosB_cur = _mm256_splat3_pd(cosB_next);
}
double value = simd::hadd(value_vec);
deriv = simd::hadd(deriv_vec);
#endif
value -= y;
if (std::abs(value) <= 1e-5 * coeff0 || ++iterations > 20)
break;
else if (value > 0.0)
c = b;
else
a = b;
b -= value / deriv;
if (!(b >= a && b <= c))
b = 0.5f * (a + c);
cosB = std::cos(b);
sinB = std::sqrt(1-cosB*cosB);
}
if (flip)
b = 2.0*math::Pi_d - b;
pdf = (Float) (math::InvTwoPi_d * deriv / coeff0);
phi = (Float) b;
return (Float) (coeff0*(2*math::Pi_d));
}
Color3 sampleFourier3(float * const coeffs[3], const double *recip, size_t nCoeffs,
Float sample, Float &pdf, Float &phi) {
bool flip = false;
if (sample < 0.5f) {
sample *= 2.0f;
} else {
sample = 1.0f - 2.0f * (sample - 0.5f);
flip = true;
}
int iterations = 0;
double a = 0.0,
c = math::Pi_d,
coeff0 = coeffs[0][0],
y = coeff0*math::Pi_d*sample,
deriv = 0.0,
b = 0.5 * math::Pi_d,
cosB = 0,
sinB = 1;
if (nCoeffs > 10 && sample != 0 && sample != 1) {
float stddev = std::sqrt(2.0f / 3.0f * std::log(coeffs[0][1] / coeffs[0][2]));
if (std::isfinite(stddev)) {
b = std::min(c, (double) math::normal_quantile(0.5f + sample / 2) * stddev);
cosB = std::cos(b);
sinB = std::sqrt(1 - cosB * cosB);
}
}
#if FOURIER_SCALAR != 1
__m256d factorB_prev, factorB_cur;
#endif
while (true) {
#if FOURIER_SCALAR == 1
double cosB_prev = cosB,
sinB_prev = -sinB,
sinB_cur = 0.0,
cosB_cur = 1.0,
value = coeff0 * b;
deriv = coeff0;
for (size_t j=1; j<nCoeffs; ++j) {
double sinB_next = 2.0*cosB*sinB_cur - sinB_prev,
cosB_next = 2.0*cosB*cosB_cur - cosB_prev,
coeff = (double) coeffs[0][j];
value += coeff * recip[j] * sinB_next;
deriv += coeff * cosB_next;
sinB_prev = sinB_cur; sinB_cur = sinB_next;
cosB_prev = cosB_cur; cosB_cur = cosB_next;
}
#else
initializeRecurrence(cosB, factorB_prev, factorB_cur);
__m256d
sinB_prev = _mm256_set1_pd(-sinB),
sinB_cur = _mm256_set1_pd(0.0),
cosB_prev = _mm256_set1_pd(cosB),
cosB_cur = _mm256_set1_pd(1.0),
value_vec = _mm256_set_sd(coeff0 * b),
deriv_vec = _mm256_set_sd(coeff0);
for (size_t j=1; j<nCoeffs; j+=4) {
__m128 coeff_vec_f = _mm_load_ps(coeffs[0]+j);
__m256d recip_vec = _mm256_load_pd(recip+j);
__m256d coeff_vec = _mm256_cvtps_pd(coeff_vec_f);
__m256d sinB_next = _mm256_add_pd(
_mm256_mul_pd(factorB_prev, sinB_prev),
_mm256_mul_pd(factorB_cur, sinB_cur));
__m256d cosB_next = _mm256_add_pd(
_mm256_mul_pd(factorB_prev, cosB_prev),
_mm256_mul_pd(factorB_cur, cosB_cur));
value_vec = _mm256_add_pd(value_vec, _mm256_mul_pd(
_mm256_mul_pd(recip_vec, coeff_vec), sinB_next));
deriv_vec = _mm256_add_pd(deriv_vec, _mm256_mul_pd(coeff_vec, cosB_next));
sinB_prev = _mm256_splat2_pd(sinB_next);
cosB_prev = _mm256_splat2_pd(cosB_next);
sinB_cur = _mm256_splat3_pd(sinB_next);
cosB_cur = _mm256_splat3_pd(cosB_next);
}
double value = simd::hadd(value_vec);
deriv = simd::hadd(deriv_vec);
#endif
value -= y;
if (std::abs(value) <= 1e-5 * coeff0 || ++iterations > 20)
break;
else if (value > 0.0)
c = b;
else
a = b;
b -= value / deriv;
if (!(b >= a && b <= c))
b = 0.5f * (a + c);
cosB = std::cos(b);
sinB = std::sqrt(1-cosB*cosB);
}
double Y = deriv;
if (flip)
b = 2.0*math::Pi_d - b;
pdf = (Float) (math::InvTwoPi_d * Y / coeff0);
phi = (Float) b;
#if FOURIER_SCALAR == 1
double cosB_prev = cosB,
cosB_cur = 1.0;
double R = coeffs[1][0];
double B = coeffs[2][0];
for (size_t j=1; j<nCoeffs; ++j) {
double cosB_next = 2.0*cosB*cosB_cur - cosB_prev,
coeffR = (double) coeffs[1][j],
coeffB = (double) coeffs[2][j];
R += coeffR * cosB_next;
B += coeffB * cosB_next;
cosB_prev = cosB_cur; cosB_cur = cosB_next;
}
#else
__m256d
cosB_prev = _mm256_set1_pd(cosB),
cosB_cur = _mm256_set1_pd(1.0),
R_vec = _mm256_set_sd(coeffs[1][0]),
B_vec = _mm256_set_sd(coeffs[2][0]);
for (size_t j=1; j<nCoeffs; j+=4) {
__m128 coeff_R_vec_f = _mm_load_ps(coeffs[1]+j);
__m128 coeff_B_vec_f = _mm_load_ps(coeffs[2]+j);
__m256d coeff_R_vec = _mm256_cvtps_pd(coeff_R_vec_f);
__m256d coeff_B_vec = _mm256_cvtps_pd(coeff_B_vec_f);
__m256d cosB_next = _mm256_add_pd(
_mm256_mul_pd(factorB_prev, cosB_prev),
_mm256_mul_pd(factorB_cur, cosB_cur));
R_vec = _mm256_add_pd(R_vec, _mm256_mul_pd(coeff_R_vec, cosB_next));
B_vec = _mm256_add_pd(B_vec, _mm256_mul_pd(coeff_B_vec, cosB_next));
cosB_prev = _mm256_splat2_pd(cosB_next);
cosB_cur = _mm256_splat3_pd(cosB_next);
}
double R = simd::hadd(R_vec);
double B = simd::hadd(B_vec);
#endif
double G = 1.39829 * Y - 0.100913 * B - 0.297375 * R;
return Color3((Float) R, (Float) G, (Float) B)
* (2 * math::Pi) * (Float) (coeff0 / Y);
}
namespace {
/// Filon integration over a single spline segment (used by filonIntegrate)
inline void filon(Float phi[2], Float f[3], size_t lmax, Float *output) {
Float h = phi[1] - phi[0], invH = 1/h;
output[0] += (math::InvPi / 6.0) * h * (f[0]+4*f[1]+f[2]);
Float cosPhi0Prev = std::cos(phi[0]), cosPhi0Cur = 1.0f,
cosPhi1Prev = std::cos(phi[1]), cosPhi1Cur = 1.0f,
sinPhi0Prev = -std::sin(phi[0]), sinPhi0Cur = 0.0f,
sinPhi1Prev = -std::sin(phi[1]), sinPhi1Cur = 0.0f,
twoCosPhi0 = 2.0f * cosPhi0Prev,
twoCosPhi1 = 2.0f * cosPhi1Prev;
const Float term0 = 3*f[0]-4*f[1]+f[2],
term1 = f[0]-4*f[1]+3*f[2],
term2 = 4*(f[0]-2*f[1]+f[2]);
for (size_t l=1; l<lmax; ++l) {
Float cosPhi0Next = twoCosPhi0*cosPhi0Cur - cosPhi0Prev,
cosPhi1Next = twoCosPhi1*cosPhi1Cur - cosPhi1Prev,
sinPhi0Next = twoCosPhi0*sinPhi0Cur - sinPhi0Prev,
sinPhi1Next = twoCosPhi1*sinPhi1Cur - sinPhi1Prev;
Float invL = 1 / (Float) l,
invL2H = invH*invL*invL,
invL3H2 = invL2H*invL*invH;
output[l] += (2 * math::InvPi) *
((invL2H * (term0 * cosPhi0Next + term1 * cosPhi1Next) +
invL3H2 * term2 * (sinPhi0Next - sinPhi1Next) +
invL * (f[2] * sinPhi1Next - f[0] * sinPhi0Next)));
cosPhi0Prev = cosPhi0Cur; cosPhi0Cur = cosPhi0Next;
cosPhi1Prev = cosPhi1Cur; cosPhi1Cur = cosPhi1Next;
sinPhi0Prev = sinPhi0Cur; sinPhi0Cur = sinPhi0Next;
sinPhi1Prev = sinPhi1Cur; sinPhi1Cur = sinPhi1Next;
}
}
};
void filonIntegrate(const std::function<Float(Float)> &f, Float *coeffs,
size_t nCoeffs, int nEvals, Float a, Float b) {
/* Avoid numerical overflow issues for extremely small intervals */
if (sizeof(Float) == sizeof(float)) {
if (std::abs(b-a) < 1e-6)
return;
} else {
if (std::abs(b-a) < 1e-15)
return;
}
if (nEvals % 2 == 0)
++nEvals;
Float value[3], phi[2], delta = (b-a) / (nEvals - 1);
phi[0] = a; value[0] = f(a);
for (int i=0; i<(nEvals-1)/2; ++i) {
phi[1] = phi[0] + 2*delta;
value[1] = f(phi[0] + delta);
value[2] = f(phi[1]);
filon(phi, value, nCoeffs, coeffs);
value[0] = value[2];
phi[0] = phi[1];
}
}
void convolveFourier(const Float *a, size_t ka_, const Float *b, size_t kb_, Float *c) {
ssize_t ka = (ssize_t) ka_, kb = (ssize_t) kb_;
for (ssize_t i=0; i<ka+kb-1; ++i) {
Float sum = 0;
for (ssize_t j=0; j<std::min(kb, ka - i); ++j)
sum += b[j]*a[i+j];
for (ssize_t j=std::max((ssize_t) 0, i-ka+1); j<std::min(kb, i+ka); ++j)
sum += b[j]*a[std::abs(i - j)];
if (i < kb)
sum += b[i]*a[0];
if (i == 0)
sum = .5f * (sum + a[0]*b[0]);
c[i] = .5f * sum;
}
}
NAMESPACE_END(layer)
| true |
74472dd3e694bdf0b795a243abfa917c9eedc0ba
|
C++
|
WZH-moyu/wuzhihu
|
/10-20/10-20/test.cpp
|
UTF-8
| 2,147 | 3.078125 | 3 |
[] |
no_license
|
#include<iostream>
#include<stdlib.h>
using namespace std;
//int Add(int a, int b)
//{
// return a + b;
//}
//double Add(double a, int b)
//{
// return a + b;
//}
//int main()
//{
// Add(1, 2);
// Add(1.0, 2);
// Add(2.0, 3.0);
// system("pause");
// return 0;
//}
//class Base
//{
//public:
// virtual void Funtest1(int i)
// {
// cout << "Base::Funtest1()" << endl;
// }
// void Funtest2(int i)
// {
// cout << "Base::Funtest2()" << endl;
// }
//};
//class Drived :public Base
//{
// virtual void Funtest1(int i)
// {
// cout << "Drived::Fubtest1()" << endl;
// }
// virtual void Funtest2(int i)
// {
// cout << "Drived::Fubtest2()" << endl;
// }
// //void Funtest2(int i)
// //{
// // cout << "Drived::Fubtest2()" << endl;
// //}
//};
//void TestVirtual(Base& b)
//{
// b.Funtest1(1);
// b.Funtest2(2);
//}
//int main()
//{
// Base b;
// Drived d;
// Base *p = &b;
// p->Funtest1(1);
// TestVirtual(b);
// TestVirtual(d);
// system("pause");
// return 0;
//}
//int partion(int arr[], int left, int right)
//{
// int key = left;
// int first = left;
// int end = right;
// while (first < end)
// {
// while (first < end && arr[end] >= arr[key])
// end--;
// while (first < end && arr[first] < arr[key])
// first++;
// if (first < end)
// swap(arr[first], arr[end]);
// }
// swap(arr[key], arr[first]);
// return first;
//}
//void QuickSort(int arr[], int left, int right)
//{
// if (left > right)
// return;
// else
// {
// int div = partion(arr, left, right);
// QuickSort(arr, left, div - 1);
// QuickSort(arr, div + 1, right);
// }
//}
//int main()
//{
// int arr[]{ 2,4,1,4,6,32,765,32,654,32,43,765 };
// int sz = sizeof(arr) / sizeof(int);
// QuickSort(arr, 0, sz - 1);
// for (int i = 0; i < sz; i++)
// {
// cout << arr[i] << " ";
// }
// cout << endl;
// system("pause");
// return 0;
//}
//class Base
//{
//public:
// virtual void Funtest1(int i)
// {
// cout << "Base::Funtest1()" << endl;
// }
// virtual void Funtest2(int i)
// {
// cout << "Base::Funtest2()" << endl;
// }
// int _data;
//};
//
//int main()
//{
// cout << sizeof(Base) << endl;
// Base b;
// //b._data = 10;
// system("pause");
// return 0;
//}
| true |
2d4a768816047b64ae4ab615222fbe424e1df4a9
|
C++
|
karunvarma/Pakfood-Internationals---OOP-Case-Study
|
/TransportT4.h
|
UTF-8
| 1,509 | 3.296875 | 3 |
[] |
no_license
|
/** Transport class
*
* #include "TransportT4.h" <BR>
* -llib
*
*/
#ifndef TRANSPORT_H
#define TRANSPORT_H
// SYSTEM INCLUDES
#include<iostream>
using std::string;
// Transport class definition
class Transport {
public:
// LIFECYCLE
/** Default + Overloaded constructor.
*/
Transport(float = 0.0, const string& = "", float = 0.0);
// Use compiler-generated copy constructor, assignment, and destructor.
// Transport(const Transport&);
// Transport& operator=(const Transport&);
// ~Transport();
// OPERATIONS
/** function that loads goods.
*
* @param void
*
* @return void
*/
void Load();
/** function that unloads goods.
*
* @param void
*
* @return void
*/
void Unload();
/** Pure virtual function that ships goods.
* This makes Transport as an Abstract class
*
* @param void
*
* @return void
*/
virtual void Ship() = 0;
// ACCESS
// setters
void SetWeight(float = 0.0);
void SetCapacity(const string& = "");
void SetSpeed(float = 0.0);
void SetTransport(float = 0.0, const string& = "", float = 0.0);
/**
# @overload void SetTransport(const Transport& aTransport);
*/
void SetTransport(const Transport& aTransport);
// getters
float GetWeight()const;
const string& GetCapacity()const;
float GetSpeed()const;
const Transport& GetTransport()const;
private:
// DATA MEMBERS
float mWeight;
string mCapacity;
float mSpeed;
};
// end class Transport
#endif
// _TRANSPORT_H_
| true |
5a687f1d6abfda6cc2599fb5f262af13927ef7b1
|
C++
|
OKriw/Seminar3
|
/Task.h
|
UTF-8
| 980 | 2.734375 | 3 |
[] |
no_license
|
//
// Created by Olga on 16/09/2020.
//
#ifndef TTIMER_TASK_H
#define TTIMER_TASK_H
#include "Timer.h"
enum states {
stopped, //initial state
running,
deleted //when we want to delete from the storage
};
class Task {
private:
class Timer *timer;
bool isValid(states new_state);
/*states for state machine*/
states state;
public:
string name;
string time_spent;
Task(string tname);
/*вернуть true если задача исполняется*/
bool isRunning();
/*вернуть true если задачу остановили*/
bool isStopped();
/*вернуть true если задачу удалили*/
bool isDeleted();
/* вернуть состояние текущей задачи*/
states getState();
// states setState();
void start();
void stop();
void clear();
void delete_t();
void statistics();
int time_spend();
};
#endif //TTIMER_TASK_H
| true |
93eea6ebcf922c09869d7dc5feef5864d905a70e
|
C++
|
fedepiz/osdev
|
/src/heap.cpp
|
UTF-8
| 4,136 | 3.109375 | 3 |
[] |
no_license
|
#include <heap.h>
#include <system.h>
void Heap::insert_block(unsigned char* ptr,unsigned long total_size) {
unsigned long payload_size = total_size - sizeof(heap_block_tag) - sizeof(heap_block_footer);
heap_block_tag head = { payload_size, 0xacab, false };
heap_block_footer footer = { (heap_block_tag*)ptr };
memcpy(ptr,&head,sizeof(heap_block_tag));
memset(ptr + sizeof(heap_block_tag),0,payload_size);
memcpy(ptr + sizeof(heap_block_tag) + payload_size, &footer, sizeof(heap_block_footer));
}
unsigned long total_to_palyoad(unsigned long size) {
return size - sizeof(heap_block_tag) - sizeof(heap_block_footer);
}
unsigned long payload_to_total(unsigned long size) {
return size + sizeof(heap_block_tag) + sizeof(heap_block_footer);
}
bool Heap::split_blocks(unsigned char* ptr, unsigned long split_size) {
heap_block_tag* header = (heap_block_tag*)ptr;
unsigned long original_total_size = payload_to_total(header->size);
unsigned long remaining_size = original_total_size - split_size;
if(remaining_size <= payload_to_total(0)) {
return false;
}
unsigned char* second_target = ptr + split_size;
insert_block(ptr,split_size);
insert_block(second_target, remaining_size);
return true;
}
void Heap::merge_blocks(unsigned char* ptr1, unsigned char* ptr2) {
heap_block_tag* second_tag = (heap_block_tag*)ptr2;
unsigned long total_second_size = payload_to_total(second_tag->size);
unsigned long in_between_pointers = abs_diff((unsigned long)ptr1,(unsigned long)ptr2);
unsigned long total_size = in_between_pointers + total_second_size;
insert_block(ptr1,total_size);
}
bool Heap::in_bounds(unsigned char* addr) {
return addr >= memory && addr < memory + memory_size;
}
unsigned char* Heap::next_block(unsigned char* ptr) {
heap_block_tag* tag = (heap_block_tag*)ptr;
unsigned char* next = ptr + payload_to_total(tag->size);
if(in_bounds(next)) {
return next;
} else {
return 0;
}
}
unsigned char* Heap::previous_block(unsigned char* ptr) {
heap_block_footer* footer = (heap_block_footer*)(ptr - sizeof(heap_block_footer));
unsigned char* prev = (unsigned char*)(footer->header);
if(in_bounds(prev)) {
return prev;
} else {
return 0;
}
}
unsigned char* Heap::first_free_block(unsigned long min_payload_size) {
unsigned char* ptr = this->memory;
while(this->in_bounds(ptr)) {
heap_block_tag* tag = (heap_block_tag*)ptr;
if(tag->size >= min_payload_size && !tag->taken) {
return ptr;
} else {
ptr = next_block(ptr);
}
}
return 0;
}
unsigned char* Heap::allocate(unsigned long payload_size) {
unsigned char* ptr = this->first_free_block(payload_size);
heap_block_tag* tag = (heap_block_tag*)ptr;
//If bigger, try to split
if(tag->size > payload_size) {
this->split_blocks(ptr,payload_to_total(payload_size));
}
tag->taken = true;
return ptr + sizeof(heap_block_tag);
}
void Heap::free(void* p) {
unsigned char* ptr = (unsigned char*)p;
ptr = ptr - sizeof(heap_block_tag);
heap_block_tag* tag = (heap_block_tag*)ptr;
tag->taken = false;
unsigned char* next = this->next_block(ptr);
if(next != 0) {
heap_block_tag* next_tag = (heap_block_tag*)next;
if(!next_tag->taken) {
this->merge_blocks(ptr,next);
}
}
unsigned char* prev = this->previous_block(ptr);
if(prev != 0) {
heap_block_tag* prev_tag = (heap_block_tag*)prev;
if(!prev_tag->taken) {
this->merge_blocks(prev,ptr);
}
}
}
Heap::Heap(unsigned char* memory,unsigned long memory_size) {
this->memory = memory;
this->memory_size = memory_size;
this->insert_block(memory,memory_size);
}
unsigned char* Heap::getMemoryPtr() {
return this->memory;
}
unsigned long Heap::getMemorySize() {
return this->memory_size;
}
//Debug stuff
void print_heap_block_tag(heap_block_tag* header) {
unsigned long addr = (unsigned long)header;
void* arr[] = {&addr, &header->size, &header->magic, &header->taken };
putf("Structure of header at %h: size = %d, magic = %i, taken = %b\n",arr);
}
void Heap::printHeap() {
unsigned char* ptr = this->memory;
while(in_bounds(ptr)) {
heap_block_tag* tag = (heap_block_tag*)ptr;
print_heap_block_tag(tag);
ptr = next_block(ptr);
}
}
| true |
11f5ed65a7241aa623e24b10ad3c9ec020e720f9
|
C++
|
chrisdyck/COMP1045
|
/Lab007L3/Lab007L3.ino
|
UTF-8
| 743 | 3.234375 | 3 |
[] |
no_license
|
/*
Name: Lab007L3.ino
Created: 6/6/2018 5:12:06 PM
Author: chris
*/
int RGBGreenPin = 10; //The green RGB LED is connected pin 10 of the Arduino.
int rotationPin = A0;
int data = 0;
void setup() {
Serial.begin(9600); //This will enable the Arduino to send data to the Serial monitor.
}
// the loop function runs over and over again until power down or reset
void loop() {
data = Read();
analogWrite(RGBGreenPin, data);
delay(500);
}
int Read() {
int rawdata = analogRead(rotationPin);// / 4; //Read the value from the light sensor and store it in the lightData variable.
int value = map(rawdata, 0, 1023, 0, 255);
Serial.print("Volume Level is = ");
Serial.println(value); //Print the data to the serial port.
return(value);
}
| true |
5802703df4b33d775cc981d43a2d4c98f6d1f6ec
|
C++
|
Diusrex/UVA-Solutions
|
/11900 Boiled Eggs.cpp
|
UTF-8
| 664 | 2.96875 | 3 |
[
"Apache-2.0"
] |
permissive
|
#include <iostream>
using namespace std;
// [egg][weightAfter] -> best number to be added
// Includes this egg
int main()
{
int T;
cin >> T;
for (int t = 1; t <= T; ++t)
{
int N, P, Q;
cin >> N >> P >> Q;
int sum = 0, numUsed = 0;
int i, weight;
for (i = 0; i < N && sum <= Q; ++i, ++numUsed)
{
cin >> weight;
sum += weight;
}
if (sum > Q)
{
--numUsed;
for (; i < N; ++i)
cin >> weight;
}
cout << "Case " << t << ": " << min(numUsed, P) << '\n';
}
}
| true |
671733e4d6975b7bc401429f9d51a1b6f80a3eaa
|
C++
|
phenixcxz/CppLearning
|
/practice/day2/递归阶乘.cpp
|
UTF-8
| 448 | 2.875 | 3 |
[] |
no_license
|
/*************************************************************************
> File Name: 递归阶乘.cpp
> Author: cxz
> Mail: phenixcxz@163.com
> Created Time: 三 6/17 19:33:29 2020
************************************************************************/
#include<iostream>
using namespace std;
int f(int x){
if(x == 0)
return 1;
else{
return x*f(x-1);
}
}
int main(){
int n;
while(cin >> n){
cout << f(n) << endl;
}
cout << endl;
}
| true |
0e1f126916e3174ec371a18720f48a6154bfd5b9
|
C++
|
Mia-Cross/modules_cpp
|
/cpp06/ex02/main.cpp
|
UTF-8
| 1,668 | 2.90625 | 3 |
[] |
no_license
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lemarabe <lemarabe@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/01/18 04:39:33 by lemarabe #+# #+# */
/* Updated: 2021/01/18 05:02:50 by lemarabe ### ########.fr */
/* */
/* ************************************************************************** */
#include "identify.hpp"
int main()
{
A *a = new A;
B *b = new B;
C *c = new C;
srand(time(NULL));
std::cout << "Identifying A, B & C from pointers :\n";
identify_from_pointer(a);
identify_from_pointer(b);
identify_from_pointer(c);
std::cout << "Identifying A, B & C from references :\n";
identify_from_reference(*a);
identify_from_reference(*b);
identify_from_reference(*c);
std::cout << "Identifying an object returned by generate() :\n";
Base *random_ptr = generate();
Base &random_ref = *random_ptr;
std::cout << "By pointer\t";
identify_from_pointer(random_ptr);
std::cout << "By reference\t";
identify_from_reference(random_ref);
delete random_ptr;
delete a;
delete b;
delete c;
}
| true |
b9dfcb7cc4242af1662e4a57e8a69f76dc004b4a
|
C++
|
lzbxh/CPP_GOF
|
/设计模式/设计模式/装饰模式.cpp
|
UTF-8
| 1,321 | 3.5 | 4 |
[] |
no_license
|
//
// 装饰模式.cpp
// 设计模式
//
// Created by 刘智滨 on 16/7/6.
// Copyright © 2016年 刘智滨. All rights reserved.
//
#include <iostream>
//动态的给一个对象添加一些额外的职责。就增加功能来说,此模式比生成子类更为灵活。
using namespace std;
class Car
{
public:
virtual void show() = 0;
};
class RunCar : public Car
{
public:
virtual void show()
{
cout << "run" << endl;
}
};
//对传入的Car进行修饰,依赖关系
class SwimCarDirector : public Car
{
public:
SwimCarDirector(Car *car)
{
_car = car;
}
void swim()
{
cout << "swim" << endl;
}
virtual void show()
{
_car->show();
swim();
}
private:
Car *_car;
};
class FlyCarDirector : public Car
{
public:
FlyCarDirector(Car *car)
{
_car = car;
}
void fly()
{
cout << "fly" << endl;
}
virtual void show()
{
_car->show();
fly();
}
private:
Car *_car;
};
int main()
{
RunCar rc;
rc.show();
cout << "==========" << endl;
//装饰
SwimCarDirector sc(&rc);
sc.show();
cout << "==========" << endl;
FlyCarDirector fc(&rc);
fc.show();
return 0;
}
| true |
4dc55412a479551ba26ad4bfb552d231b68c3e7d
|
C++
|
vmswift/CS372-Data-Structures
|
/Overload Throttle/Overload Throttle/throttle.h
|
UTF-8
| 2,258 | 3.5 | 4 |
[] |
no_license
|
//Throttle Overload Class Header
//throttle.h
//CS372 Fall 2014
//By John Knowles jknowle2@my.athens.edu
//Date 9/8/2014
//
//This is a partial clone of the file in the textbook
//I combined the cpp and header file into the header
#include <cassert>
#include <iostream>
class throttle
{
public:
throttle( );
throttle(int size);
throttle(int size, int pos);
throttle(throttle & one);
void shut_off( ) { position = 0; };
void shift(int amount);
bool operator==(throttle& t1); //overload ==
bool operator!=(throttle& t1); //overload !=
double flow( ) const { return position / double(top_position); } ;
bool is_on( ) const { return (position > 0); };
int getPos();
int getTop();
friend std::ostream& operator<<(std::ostream& outs,throttle& t1); //overload cout
private:
int top_position;
int position;
};
throttle::throttle( )
{ // A simple on-off throttle
top_position = 6;
position = 0;
}
throttle::throttle(int size)
// Library facilities used: cassert
{
assert(size > 0);
top_position = size;
position = 0;
}
throttle::throttle(int size,int pos)
// Library facilities used: cassert
{
assert(size > 0);
top_position = size;
position = pos;
}
throttle::throttle(throttle &one)
{
top_position=one.top_position;
position=one.position;
}
void throttle::shift(int amount)
{
position += amount;
if (position < 0)
position = 0;
else if (position > top_position)
position = top_position;
}
int throttle::getPos()
{
return position;
}
int throttle::getTop()
{
return top_position;
}
bool throttle::operator==(throttle& t1)
{
if (position==t1.getPos())
if (top_position==t1.getTop())
return true;
else
return false;
else
return false;
}
bool throttle::operator!=(throttle& t1)
{
if (!(position==t1.getPos()))
if (!(top_position==t1.getTop()))
return true;
else
return false;
else
return false;
}
std::ostream& operator<<(std::ostream& outs,throttle& t1)
{
outs << "Top position: " << t1.top_position << " ";
outs << "Current Position: " << t1.position;
return outs;
}
| true |
05d340b8692ecfb86e4934014a3ac324fe543be5
|
C++
|
Guillaume227/app_utils
|
/src/string_utils.cpp
|
UTF-8
| 10,569 | 2.8125 | 3 |
[] |
no_license
|
#include <cstring>
#include <regex>
#include <sstream>
#include <vector>
#include <app_utils/string_utils.hpp>
#include <app_utils/cond_check.hpp>
#include <app_utils/container_utils.hpp>
namespace app_utils {
namespace strutils {
namespace {
std::string const openSymbols = "<({[";
std::string const closeSymbols = ">)}]";
} // namespace
bool isCloseSymbol(char c) { return closeSymbols.find(c) != std::string::npos; }
bool isOpenSymbol(char c) { return openSymbols.find(c) != std::string::npos; }
char getCloseSymbol(char openSymbol) {
auto pos = openSymbols.find(openSymbol);
if (pos == std::string::npos) {
throwExc("no close symbol found for", openSymbol);
}
return closeSymbols[pos];
}
std::string toUpper(std::string str) {
for (auto& c : str) c = static_cast<char>(::toupper(c));
return str;
}
std::string toLower(std::string str) {
for (auto& c : str) c = static_cast<char>(::tolower(c));
return str;
}
bool contains(std::string_view src, std::string_view substr) { return src.find(substr) != std::string::npos; }
bool contains(std::string_view src, char const c) { return src.find(c) != std::string::npos; }
bool startswith(std::string_view src, std::string_view suffix) {
auto pos = src.find(suffix);
return pos == 0;
}
bool startswith(std::string_view src, char const prefix) { return not src.empty() and src.front() == prefix; }
bool endswith(std::string_view src, char const suffix) { return not src.empty() and src.back() == suffix; }
bool endswith(std::string_view src, std::string_view suffix) {
auto pos = src.rfind(suffix);
if (pos != std::string::npos) {
return src.length() == pos + suffix.length();
}
return false;
}
std::string_view& strip_in_place(std::string_view& str, std::string_view const whitespace) {
auto const strBegin = str.find_first_not_of(whitespace);
if (strBegin == std::string::npos) {
str = "";
} else {
auto const strEnd = str.find_last_not_of(whitespace);
str.remove_suffix(str.size() - strEnd - 1);
str.remove_prefix(strBegin);
}
return str;
}
std::string_view strip(std::string_view const str, std::string_view const whitespace) {
std::string_view res = str;
strip_in_place(res, whitespace);
return res;
}
size_t split(std::string_view const str,
char const delim,
std::string_view& outBuffer,
size_t maxNumTokens) {
size_t leftIndexPos = 0;
std::string_view* outputPointer = &outBuffer;
size_t parsedTokens = 0;
for (size_t i = 0; i < str.size(); i++) {
if (str.at(i) == delim) {
*outputPointer = str.substr(leftIndexPos, i - leftIndexPos);
leftIndexPos = i+1;
if (++parsedTokens >= maxNumTokens) {
return parsedTokens;
}
outputPointer++;
}
}
if (leftIndexPos + 1 < str.size()) {
*outputPointer = str.substr(leftIndexPos);
++parsedTokens;
}
return parsedTokens;
}
std::vector<std::string_view> split(char const delim,
std::string_view const str,
bool const stripWhiteSpace,
int const nSplits) {
if (str.empty()) return {str};
if (nSplits == 0) return {stripWhiteSpace ? strip(str) : str};
std::vector<std::string_view> res;
size_t token_start_index = 0;
size_t i = 0;
for (; i < str.size(); i++) {
char c = str[i];
if(c == delim) {
if(i > token_start_index) {
res.push_back(str.substr(token_start_index, i-token_start_index));
if (stripWhiteSpace) {
strip_in_place(res.back());
}
}
token_start_index = i + 1;
}
if(nSplits > 0 and (int)res.size() >= nSplits) {
break;
}
}
if (token_start_index < str.size()) {
res.push_back(str.substr(token_start_index));
if (stripWhiteSpace) {
strip_in_place(res.back());
}
}
return res;
}
std::vector<std::string_view> splitNoEmpty(char const delim, std::string_view str) {
return split(delim, str, /*strip whitespace*/true, -1);
}
// that version takes a multi-char delimiter
std::vector<std::string_view> splitM(std::string_view const delim, std::string_view const str) {
std::vector<std::string_view> res;
auto const pos = str.find(delim);
if (pos == std::string::npos) {
res.push_back(str);
} else {
res.push_back(str.substr(0, pos));
res.push_back(str.substr(pos + delim.size()));
}
return res;
}
std::vector<std::string> splitByRegex(std::string const& s, char const* delim) {
std::vector<std::string> result;
std::regex rgx(delim);
std::sregex_token_iterator iter(s.begin(), s.end(), rgx, -1);
std::sregex_token_iterator end;
for (; iter != end; ++iter) {
result.push_back(*iter);
}
return result;
}
std::string_view lastLine(std::string_view const src) {
auto pos = src.find_last_of('\n');
if (pos == std::string::npos) {
return src;
}
return src.substr(pos + 1);
}
namespace {
class SplitIter {
public:
explicit SplitIter(std::string_view data, char separator = ',', int maxSplits = 1)
: m_data(data)
, m_separator(separator)
, m_maxSplits(maxSplits) {}
std::string_view next() {
std::vector<char> expectedBrackets;
m_start_i = ++m_end_i;
if (m_end_i >= (int)m_data.size()) {
return "";
}
if (m_maxSplits >= 0 and m_splitCounter >= m_maxSplits) {
m_end_i = (int) m_data.size();
return m_data.substr(size_t(m_start_i));
}
for (; m_end_i < int(m_data.size()); m_end_i++) {
auto const character = m_data[m_end_i];
if (isOpenSymbol(character)) {
expectedBrackets.push_back(getCloseSymbol(character));
} else if (isCloseSymbol(character)) {
if (character != '>') {
// only if we found a match we pop the bracket off and continue
// otherwise no error will be triggered
if (not expectedBrackets.empty() and expectedBrackets.back() == character) {
expectedBrackets.pop_back();
}
} else {
// Here if we meet > as expected we just pop them all off
// instead of triggering an error
while (not expectedBrackets.empty()) {
if (expectedBrackets.back() != '>') {
break;
}
expectedBrackets.pop_back();
}
checkCond(not expectedBrackets.empty(), "Inbalanced brackets in string \"", m_data, "\".",
"Found closing bracket", character, "without any matching opening bracket.");
auto const expectedBracket = expectedBrackets.back();
expectedBrackets.pop_back();
checkCond(character == expectedBracket, "Imbalanced brackets in string \"", m_data, "\".",
"Expected closing bracket", expectedBracket, ", but found", character);
}
} else if (character == m_separator) {
if (expectedBrackets.empty()) {
break;
}
}
}
checkCond(expectedBrackets.empty() or app_utils::all_of(expectedBrackets, [](auto const& x) { return x == '>'; }),
"Imbalanced brackets in string \"", m_data, "\"." /*,
"Expected to see the following brackets:", expectedBrackets*/);
m_splitCounter++;
return m_data.substr(size_t(m_start_i), size_t(m_end_i - m_start_i));
}
[[nodiscard]]
bool hasNext() const { return not m_data.empty() and m_end_i < int(m_data.size()); }
private:
std::string_view const m_data;
char const m_separator;
int const m_maxSplits;
int m_start_i = -1, m_end_i = -1;
int m_splitCounter = 0;
};
} // namespace
std::vector<std::string_view> splitParse(std::string_view const valStr,
char delimiter,
bool doStrip,
int maxSplits) {
SplitIter splitIter(valStr, delimiter, maxSplits);
std::vector<std::string_view> res;
while (splitIter.hasNext()) {
res.emplace_back(splitIter.next());
if (doStrip) {
res.back() = strip(res.back());
}
}
if (res.empty()) {
res.push_back(valStr);
}
return res;
}
std::vector<std::string_view> splitParse(std::string_view const valStr, char delimiter, bool doStrip) {
return splitParse(valStr, delimiter, doStrip, -1);
}
std::string_view stripVectorBraces(std::string_view const valStr) { return stripBraces(valStr); }
std::string_view stripBraces(std::string_view const valStr, std::string_view const braces) {
std::string_view out = strip(valStr);
if (enclosedInBraces(out, braces)) {
return out.substr(1, out.size() - 2);
}
return out;
}
std::size_t findMatchingClose(std::string_view const valStr, size_t const startFrom) {
checkCond(valStr.size() > startFrom, "inconsistent inputs");
char openSymbol = valStr[startFrom];
checkCond(isOpenSymbol(openSymbol), openSymbol, "is not a supported open symbol in", valStr);
char closeSymbol = getCloseSymbol(openSymbol);
int numOpen = 1;
for (size_t pos = startFrom + 1; pos < valStr.size(); pos++){
if (valStr[pos] == closeSymbol) {
numOpen--;
} else if (valStr[pos] == openSymbol) {
numOpen++;
}
if (numOpen == 0) {
return pos;
}
}
return std::string::npos;
}
bool enclosedInBraces(std::string_view const valStr, std::string_view const braces) {
checkCond(braces.size() == 2, "invalid braces specification:", braces);
// Vector braces only exist as the first and last character.
if (not startswith(valStr, braces[0])) {
return false;
}
for (size_t unmatched_braces = 1, index = 1; index < valStr.size(); ++index) {
if (valStr[index] == braces[0]) {
++unmatched_braces;
} else if (valStr[index] == braces[1] and --unmatched_braces == 0) {
return index == valStr.size() - 1;
}
}
return false;
}
void replaceAll(std::string& str, std::string_view const from, std::string_view const to) {
if (from.empty()) return;
size_t start_pos = 0;
while ((start_pos = str.find(from, start_pos)) != std::string::npos) {
str.replace(start_pos, from.length(), to);
start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
}
}
std::string to_string(double val) {
std::ostringstream oss;
oss << std::setprecision(8) << std::noshowpoint << val;
return oss.str();
}
std::string to_string(float val) {
std::ostringstream oss;
oss << std::setprecision(8) << std::noshowpoint << val;
return oss.str();
}
} // namespace strutils
} // namespace app_utils
| true |
38bdb739d34b8c75cdcdf497461bd068ec51d406
|
C++
|
Leprasa/Stroustrup_homeworks
|
/5/5.9.7.cpp
|
UTF-8
| 797 | 4.09375 | 4 |
[] |
no_license
|
//7.Определите таблицу, содержащую название месяцев и кол-во дней в каждом из них.
//Выведите содержимое таблицы.Воспользуйтесб массивом структур,каждая из которых
//хранит назв. месяца и кол-во дней в нем.
//
#include <iostream>
struct month {
const char *name;
int days;
};
int main()
{
month year[5];
year[0].name = "Jan";
year[0].days = 31;
year[1].name = "Feb";
year[1].days = 30;
year[2].name = "Mar";
year[2].days = 31;
year[3].name = "Apr";
year[3].days = 30;
year[4].name = "May";
year[4].days = 31;
for (int i = 0; i < 5; i++) {
std::cout << year[i].name << " " << year[i].days << std::endl;
}
}
| true |
53fdaeaad3e05f554a10a28b78977f5a3a748916
|
C++
|
MelulekiDube/md_allocator
|
/include/freelist.h
|
UTF-8
| 3,310 | 3.234375 | 3 |
[] |
no_license
|
#pragma once
#include "memory_blk.h"
#include <stdlib.h>
#include <algorithm> // std::max
#define WORD_SIZE 4
template <class A, size_t s> class FreeList {
A parent_;
struct Node {
Node *next;
} root_;
public:
FreeList(A allocator) : parent_(allocator) { root_ = nullptr; }
static constexpr unsigned align();
static constexpr size_t goodsize(size_t n) {
return std::max(n, s);
}
Block allocate(size_t n) {
if (n == s && root_) {
Block b = {root_, n};
root_ = root_.next;
return b;
}
return parent_.allocate(n);
}
void deallocate(Block &b) {
if (b._size != s)
return parent_.deallocate(b);
auto p = (Node *)b._ptr;
p.next = root_;
root_ = p;
}
bool expand(Block &block, size_t n) {
Block temp;
if(n <= block._size) return false; // we cant expand to same size or less size
if (block._size == s) { // if it originally belonged here we deallocate and
// then use parent to allocate more space
temp = parent_.allocate(n);
if(!temp._ptr) return false;
memcpy(temp._ptr, block._ptr, std::min(s, n));
deallocate(block);
return true;
}
if (n == s) {
if(root_) {
temp = {root_, n};
root_ = root_.next;
memcpy(temp._ptr, block._ptr, std::min(block._size, s));
parent_.deallocate(block);
return true;
}
}
temp = parent_.expand(block, n); // otherwise we just call the expand from the parent_
if(!temp._ptr) return false;
memcpy(temp._ptr, block._ptr, std::min(block._size, n));
return true;
}
void reallocate(Block &block, size_t n) {
Block temp;
if(n == block._size) return ; // we cant expand to same size
if (block._size == s) { // if it originally belonged here we deallocate and
// then use parent to allocate more space
temp = parent_.allocate(n);
if(!temp._ptr) return ;
memcpy(temp._ptr, block._ptr, std::min(s, n));
deallocate(block);
return;
}
if (n == s) {
if(root_) {
temp = {root_, n};
root_ = root_.next;
memcpy(temp._ptr, block._ptr, std::min(block._size, s));
parent_.deallocate(block);
return ;
}
}
temp = parent_.expand(block, n); // otherwise we just call the expand from the parent_
if(!temp._ptr) return;
memcpy(temp._ptr, block._ptr, std::min(block._size, n));
}
void deallocateAll() {
// since we get all the blocks from parent allocator we can just call it
// here
parent_.deallocateAll();
root_ = nullptr;
;
}
Block alignedAllocate(size_t n) {
if (n == s && root_) {
Node* current = root_, *prev = nullptr;
while(current){
if(!(current%WORD_SIZE)) break;
prev = current;
current = current->next;
}
if(current){
prev->next = current+n;
return {current, n};
}
}
return parent_.alignedAllocate(n);
}
Block alignedReAllocate(Block &block, size_t new_size) {
}
bool owns(const Block &block) const {
return block._size == s || parent_.owns(block);
}
};
/*
we can add max_size of list
we also allocate more than we need (bigger chunks and store the rest in memory)
Also have a an upper bound of default size of chunk
*/
| true |
6fc800b4780f5da68beee122ef0dceae284cc466
|
C++
|
kaseLunt/CalendarApp
|
/lunt_reminder.cpp
|
UTF-8
| 599 | 2.96875 | 3 |
[] |
no_license
|
#include "lunt_reminder.h"
// Reminder's method implementations
/************************************************************************/
Reminder::Reminder()
{
}
void Reminder::setText()
{
//prompt for reminder text and save
std::cout << "Enter reminder text: ";
//call getline once to clear the buffer of the \n character, again to get input from user
std::getline(std::cin, this->text); std::getline(std::cin, this->text);
}
std::string Reminder::getText()
{
//return the reminder text
return this->text;
}
std::string Reminder::toString()
{
return "Reminder: " + this->text;
}
| true |
dff217e83db38f87bd4ab6edae5b543ecf66c1af
|
C++
|
SpintroniK/libeXaDrums
|
/DrumKit/Triggers/Curves/CurveType.h
|
UTF-8
| 1,511 | 2.984375 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
/*
* Curves.h
*
* Created on: 2 Jun 2015
* Author: jeremy
*/
#ifndef LIBEXADRUMS_SOURCE_DRUMKIT_CURVES_CURVE_H_
#define LIBEXADRUMS_SOURCE_DRUMKIT_CURVES_CURVE_H_
#include "../../../Util/Enums.h"
#include <sstream>
#include <string>
#include <type_traits>
namespace DrumKit
{
enum class CurveType
{
Linear,
Exponential1,
Exponential2,
Log1,
Log2,
Loud1,
Loud2,
Spline,
First = Linear,
Last = Spline
};
inline std::ostream& operator<<(std::ostream& o, const CurveType& x)
{
std::string os;
switch (x)
{
case CurveType::Exponential1: os = "Exponential1";break;
case CurveType::Linear: os = "Linear"; break;
case CurveType::Exponential2: os = "Exponential2";break;
case CurveType::Log1: os = "Log1"; break;
case CurveType::Log2: os = "Log2"; break;
case CurveType::Loud1: os = "Loud1"; break;
case CurveType::Loud2: os = "Loud2"; break;
case CurveType::Spline: os = "Spline"; break;
default: break;
}
return o << os;
}
inline CurveType operator++(CurveType& x) { return x = (CurveType)(std::underlying_type_t<CurveType>(x) + 1); };
inline CurveType operator*(CurveType x) { return x; };
inline CurveType begin(CurveType x) { return CurveType::First; };
inline CurveType end(CurveType x) { CurveType l = CurveType::Last; return ++l; };
inline std::istream& operator>>(std::istream& is, CurveType& x)
{
return Util::StreamToEnum(is, x);
}
}
#endif /* LIBEXADRUMS_SOURCE_DRUMKIT_CURVES_CURVE_H_ */
| true |
d3b98e52073b4286c1e23ba25a9960b5c85dad7f
|
C++
|
Mosaic0412/CPlusPlus
|
/day02/day02_encapsulationPrivate/day02_encapsulationPrivate/main.cpp
|
UTF-8
| 1,148 | 3.453125 | 3 |
[] |
no_license
|
//
// main.cpp
// day02_encapsulationPrivate
//
// Created by 陈庆华 on 2020/3/15.
// Copyright © 2020 陈庆华. All rights reserved.
//
/*
建议将成员变量设置为private
*/
#include <iostream>
#include <string>
using namespace std;
class Person{
private:
string pName; //可读可写
int pAge = 23; //只读
string pLover; //只写
public:
// void setpAge(int age){
// pAge = age;
// }
int getpAge(){
return pAge;
}
string getpName(){
return pName;
}
void setpName(string name){
pName = name;
}
void setpLover(string lover){
pLover = lover;
}
void showLover(){
cout<<"Lover:"<<pLover<<endl;
}
};
void test01(){
cout<<"------test 01------"<<endl;
Person person1;
// person1.pAge = 10; //error: 'pAge' is a private member of 'Person'
person1.setpName("Mosaic");
person1.setpLover("wintersweet");
cout<<"姓名:"<<person1.getpName()<<endl<<"年龄:"<<person1.getpAge()<<endl;
person1.showLover();
}
int main(int argc, const char * argv[]) {
test01();
return 0;
}
| true |
55ea62f5c6a655e727758be25b308f0f74550ede
|
C++
|
HemanDas/cpp_project
|
/Lab_works/Lab_object/Operatoroverloading/complex_op.cpp
|
UTF-8
| 679 | 3.640625 | 4 |
[] |
no_license
|
#include<iostream>
using namespace std;
class complex{
float real=0,imag=0;
public:
void getdata(){
float r,i;
cout<<"enter the real and imaginary part"<<endl;
cin>>r>>i;
real=r;
imag=i;
}
complex operator +(complex a)
{
complex temp;
temp.real=real+a.real;
temp.imag=imag+a.imag;
return temp;
}
void display()
{
cout<<"Sum of complex numbers = "<<real<<"+"<<imag<<"j"<<endl;
}
};
int main()
{
complex c1,c2,c3;
c1.getdata();
c2.getdata();
c3=c1+c2;
c3.display();
}
| true |
3cfd74231cc3cfb83cc9711e253ab7e8949dcc1c
|
C++
|
ImanolGo/VideoPixels
|
/Arduino/SD_VideoPlayer/SD_VideoPlayer.ino
|
UTF-8
| 4,723 | 2.625 | 3 |
[] |
no_license
|
/*
SD Video Player
Description:
* Led video player reading content from SD Card
Hardware:
* Teensy 3.5
* WS2811 5V LED strips
The circuit:
* SD card attached to SPI bus as follows:
** MOSI - pin 11 on Arduino Uno/Duemilanove/Diecimila, pin 7 on Teensy with audio board
** MISO - pin 12 on Arduino Uno/Duemilanove/Diecimila
** CLK - pin 13 on Arduino Uno/Duemilanove/Diecimila, pin 14 on Teensy with audio board
** CS - depends on your SD card shield or module - pin 10 on Teensy with audio board
Pin 4 used here for consistency with other Arduino examples
* LED Ground: Connected to GND
* LED +5V:: Connected to VSUB
* LED Data: Connected to pin 2
created 30 March 2017
by Imanol Gómez
*/
// include the SD library:
#include <SD.h>
#include <SPI.h>
#define FILENAME "10.BMP"
#define serialDebug 0 //whether or not to output whats read
// include Fast LED Library
#include "FastLED.h"
// set up variables using the FastLED utility library functions:
#define FRAMES_PER_SECOND 24
#define DATA_PIN 2
//#define CLK_PIN 4
#define LED_TYPE WS2811
#define COLOR_ORDER GRB
#define NUM_LEDS 596
CRGB leds[NUM_LEDS];
uint8_t gHue = 0; // rotating "base color" used by many of the patterns
//set up files variables
File myFile;
long height = 1;
long bitmapOffset = 0x36;
long filePosition = 0;
int currentFrame = 0;
// Teensy 3.5 & 3.6 on-board: BUILTIN_SDCARD
const int chipSelect = BUILTIN_SDCARD;
void setup()
{
setupSerial();
setupSD();
setupLeds();
}
void setupSerial() {
//Initialize serial
Serial.begin(9600);
delay(2000);
}
void setupSD() {
Serial.print("Initializing SD card...");
if (!SD.begin(chipSelect)) {
Serial.println("initialization failed!");
return;
}
Serial.println("initialization done.");
loadBMPinfo(FILENAME);
}
void setupLeds() {
// tell FastLED about the LED strip configuration
FastLED.addLeds<LED_TYPE,DATA_PIN,COLOR_ORDER>(leds, NUM_LEDS).setCorrection(TypicalLEDStrip);
FastLED.setMaxPowerInVoltsAndMilliamps (5, 2400);
}
void loop(void) {
updateLeds();
}
void updateLeds()
{
nextFrame();
//rainbow();
// send the 'leds' array out to the actual LED strip
FastLED.show();
// insert a delay to keep the framerate modest
FastLED.delay(1000/FRAMES_PER_SECOND);
// do some periodic updates
EVERY_N_MILLISECONDS( 1 ) { gHue++; } // slowly cycle the "base color" through the rainbow
}
void nextFrame() {
currentFrame = (currentFrame + 1) % height;
int index = height - currentFrame - 1;
setFrame(index);
}
void setFrame(int frameIndex) {
if(frameIndex < 0 || frameIndex >= height){
return;
}
filePosition = bitmapOffset+ (frameIndex *(NUM_LEDS * 3) );
myFile.seek(filePosition);//get to data
memset(leds, 0, NUM_LEDS * 3);//blank the array
//something went wrong, myFile should not return -1 here.
if (!myFile){
Serial.println("the card broke");
return;
}
//read an entire line to leds[]
for(int i=0; i < NUM_LEDS; i++) {
leds[i].b=myFile.read();
leds[i].g=myFile.read();
leds[i].r=myFile.read();
if (serialDebug) {
Serial.print(leds[i].r,HEX);
Serial.print(":");
Serial.print(leds[i].g,HEX);
Serial.print(":");
Serial.print(leds[i].b,HEX);
Serial.print(",");
}
}
FastLED.show(); //fastspi output
}
void rainbow()
{
// FastLED's built-in rainbow generator
fill_rainbow( leds, NUM_LEDS, gHue, 7);
}
void loadBMPinfo(String fileName) {
byte heightByte[4];
height = 0; //start with a zero'd signed long, 4 bytes.
if (SD.exists(FILENAME)) {
Serial.print(FILENAME);
Serial.println(" exists.");
}
else {
Serial.print(FILENAME);
Serial.println(" doesn't exist.");
}
myFile.close();
myFile = SD.open(FILENAME, FILE_READ);
myFile.seek(0x16); //goto start byte of bitmap height
for (int i = 0; i < 4; i++){ //height is a 4 byte integer stored in reverse byte order
heightByte[i] = myFile.read();
} //end for grab
for (int i = 3; i > 0; i--){ //3 2 1 not zero
height = height | heightByte[i]; //add the i'th byte
height = height << 8; //bitshift everything 1 byte left
}
height = height | heightByte[0];
myFile.seek(0xA);
bitmapOffset = myFile.read();
Serial.print("BitmapOffset:"); //debug if the bitmap data offset is correct
Serial.println(bitmapOffset,HEX);
Serial.print("Height:");
Serial.println(height);
}
| true |
b83c08fac337f7658a42853b26d065a278667b89
|
C++
|
BitBlitObviMormon/Minecraft-Server
|
/src/data/datatypes.cpp
|
UTF-8
| 21,369 | 3.3125 | 3 |
[] |
no_license
|
#include "debug.h"
#include "data/datatypes.h"
#include "client/client.h"
#include <stdexcept>
#include <iostream>
/******************************************
* CountNumVarLength *
* Reads a variable and counts its length *
******************************************/
Byte CountNumVarLength(const Byte* data, const Byte maxlength)
{
// Check for null data
if (data == NULL)
return 0;
// Parse the data byte by byte
Int numRead = 0;
Byte read;
do
{
// Read a byte of data
read = data[numRead];
numRead++;
// If we read too much data then throw an exception
if (numRead > maxlength)
throw new std::overflow_error("VarNum is too big");
} while ((read & 0x80) != 0); // Stop when we hit a certain number
return numRead;
}
/*******************************************
* ParseNumVar *
* Reads a variable of length x and throws *
* an exception when that length is passed *
*******************************************/
Long parseNumVar(const Byte* data, const Byte maxlength)
{
// Check for null data
if (data == NULL)
return 0;
// Parse the data byte by byte
Int numRead = 0;
Long result = 0;
Byte read;
do
{
// Read a byte of data
read = data[numRead];
result |= ((read & 0x7f) << (7 * numRead));
numRead++;
// If we read too much data then throw an exception
if (numRead > maxlength)
throw new std::overflow_error("VarNum is too big");
} while ((read & 0x80) != 0); // Stop when we hit a certain number
return result;
}
/*******************************************************
* MakeNumVar *
* Takes a long and creates a variable of length x *
* It throws an exception if the new value is too long *
*******************************************************/
void makeNumVar(Long value, const Byte maxlength, VarNum& num)
{
// Allocate some memory for the value
Byte* data = new Byte[maxlength];
Byte numWrote = 0;
do
{
// Calculate a byte
Byte temp = (Byte)(value & 0x7f);
value = (Long)(((ULong)value) >> 7); // Logical right-shift
if (value != 0)
temp |= 0x80;
// Write the calculated byte
data[numWrote++] = temp;
// Check if we exceeded the array
if (numWrote >= maxlength)
throw new std::overflow_error("VarNum is too big");
// Write the null byte at the end
// data[numWrote] = 0;
} while (value != 0);
// Assemble and return the VarNum
num.data = data;
num.length = CountNumVarLength(data, maxlength);
}
/*******************************************************
* MakeNumVar *
* Takes an int and creates a variable of length x *
* It throws an exception if the new value is too long *
*******************************************************/
void makeNumVar(Int value, const Byte maxlength, VarNum& num)
{
// Allocate some memory for the value
Byte* data = new Byte[maxlength];
Byte numWrote = 0;
do
{
// Calculate a byte
Byte temp = (Byte)(value & 0x7f);
value = (Int)(((UInt)value) >> 7); // Logical right-shift
if (value != 0)
temp |= 0x80;
// Write the calculated byte
data[numWrote++] = temp;
// Check if we exceeded the array
if (numWrote >= maxlength)
throw new std::overflow_error("VarInt is too big");
// Write the null byte at the end
data[numWrote] = 0;
} while (value != 0);
// Assemble and return the VarNum
num.data = data;
num.length = CountNumVarLength(data, maxlength);
}
/***********************
* VarNum :: VarNum *
* Default Constructor *
***********************/
VarNum::VarNum(Byte* data) : data(NULL)
{
length = CountNumVarLength(data, VARNUM_MAX_SIZE);
// Copy the array given
Byte* newData = new Byte[length];
for (int i = 0; i < length; i++)
newData[i] = data[i];
this->data = newData;
}
/*********************
* VarNum :: VarNum *
* Copy Constructor *
*********************/
VarNum::VarNum(const VarNum& value)
{
// If the other value has no data then forget about copying
if (value.data == NULL)
{
length = 0;
data = NULL;
return;
}
// Copy the data from the value to the new long
length = value.length;
data = new Byte[length];
for (int i = 0; i < length; i++)
data[i] = value.data[i];
}
/*********************
* VarNum :: VarNum *
* Move Constructor *
*********************/
VarNum::VarNum(VarNum&& value) : data(value.data), length(value.length)
{
value.data = NULL;
value.length = 0;
}
/**************************
* VarNum :: VarNum *
* Constructor from a Num *
**************************/
VarNum::VarNum(const Long value) { makeNumVar(value, VARNUM_MAX_SIZE, *this); }
/**************************
* VarNum :: VarNum *
* Constructor from a Num *
**************************/
VarNum::VarNum(const Int value) { makeNumVar(value, VARNUM_MAX_SIZE, *this); }
/*********************
* VarNum :: ~VarNum *
* Destructor *
*********************/
VarNum::~VarNum() { if (data != NULL) { delete[] data; data = NULL; } }
/**************************
* VarNum :: toNum *
* Converts VarNum to Num *
**************************/
Long VarNum::toNum() const { return parseNumVar(data, length); }
/*****************************
* VarNum :: getSize *
* Returns the size in bytes *
*****************************/
const Byte VarNum::getSize() const { return length; }
/**************************
* VarNum :: getData *
* Returns the data array *
**************************/
const Byte* VarNum::getData() const { return data; }
/***********************
* VarInt :: VarInt *
* Default Constructor *
***********************/
VarInt::VarInt(Byte* data) : VarNum(data)
{
if (length > VARINT_MAX_SIZE)
throw new std::overflow_error("VarInt is too big");
}
/*********************
* VarInt :: VarInt *
* Copy Constructor *
*********************/
VarInt::VarInt(const VarInt& value) : VarNum(value)
{
if (length > VARINT_MAX_SIZE)
throw new std::overflow_error("VarInt is too big");
}
/************************
* VarInt :: VarInt *
* Constructor from Int *
************************/
VarInt::VarInt(const Int value) : VarNum((const Int)value)
{
if (length > VARINT_MAX_SIZE)
throw new std::overflow_error("VarInt is too big");
}
/****************************
* VarInt :: VarInt *
* Constructor from VarLong *
****************************/
VarInt::VarInt(const VarLong& value) : VarNum(value)
{
if (length > VARINT_MAX_SIZE)
throw new std::overflow_error("VarInt is too big");
}
/****************************
* VarInt :: operator= *
* Copy Assignment Operator *
****************************/
VarInt& VarInt::operator=(const VarInt& right)
{
// If the other value has no data then forget about copying
if (right.data == NULL)
{
length = 0;
data = NULL;
return *this;
}
// Copy the data from the value to the new long
length = right.length;
data = new Byte[length];
for (int i = 0; i < length; i++)
data[i] = right.data[i];
return *this;
}
/*********************
* VarInt :: ~VarInt *
* Destructor *
*********************/
VarInt::~VarInt() {}
/**************************
* VarInt :: toInt *
* Converts VarInt to Int *
**************************/
Int VarInt::toInt() const { return (Int)toNum(); }
/***********************
* VarLong :: VarLong *
* Default Constructor *
***********************/
VarLong::VarLong(Byte* data) : VarNum(data)
{
if (length > VARLONG_MAX_SIZE)
throw new std::overflow_error("VarLong is too big");
}
/***********************
* VarLong :: VarLong *
* Copy Constructor *
***********************/
VarLong::VarLong(const VarLong& value) : VarNum(value)
{
if (length > VARLONG_MAX_SIZE)
throw new std::overflow_error("VarLong is too big");
}
/*************************
* VarLong :: VarLong *
* Constructor from Long *
*************************/
VarLong::VarLong(const Long value) : VarNum((const Long)value)
{
if (length > VARLONG_MAX_SIZE)
throw new std::overflow_error("VarLong is too big");
}
/***************************
* VarLong :: VarLong *
* Constructor from VarInt *
***************************/
VarLong::VarLong(const VarInt& value) : VarNum(value)
{
if (length > VARLONG_MAX_SIZE)
throw new std::overflow_error("VarLong is too big");
}
/***********************
* VarLong :: ~VarLong *
* Destructor *
***********************/
VarLong::~VarLong() {}
/****************************
* VarLong :: operator= *
* Copy Assignment Operator *
****************************/
VarLong& VarLong::operator=(const VarLong& right)
{
// If the other value has no data then forget about copying
if (right.data == NULL)
{
length = 0;
data = NULL;
return *this;
}
// Copy the data from the value to the new long
length = right.length;
data = new Byte[length];
for (int i = 0; i < length; i++)
data[i] = right.data[i];
return *this;
}
/****************************
* VarLong :: toLong *
* Converts VarLong to Long *
****************************/
Long VarLong::toLong() const { return toNum(); }
/*********************************
* SerialString :: SerialString *
* Default Constructor *
*********************************/
SerialString::SerialString(Byte* data) : length(0), data(NULL)
{
if (data != NULL)
{
// Get the length of the string
VarInt data1 = VarInt(data);
length = data1;
data += length.getSize();
// Copy the string to a new buffer
Int len = length.toInt();
this->data = new Byte[len];
for (int i = 0; i < len; i++)
this->data[i] = data[i];
}
}
/*********************************
* SerialString :: SerialString *
* Constructor from UTF-8 String *
*********************************/
SerialString::SerialString(const String& text)
{
length = VarInt(text.length());
data = new Byte[text.length()];
// Copy the data from the string to this one
for (UInt i = 0; i < text.length(); i++)
data[i] = text[i];
}
/*********************************
* SerialString :: SerialString *
* Constructor from SerialString *
*********************************/
SerialString::SerialString(const SerialString& str)
{
// Allocate the data
int len = str.getLength();
data = new Byte[len];
length = VarInt(len);
// Copy the data
for (int i = 0; i < len; ++i)
data[i] = str.data[i];
}
/**********************************
* SerialString :: equal operator *
* Copy SerialString *
**********************************/
SerialString& SerialString::operator=(const SerialString& rhs)
{
// Allocate the data
int len = rhs.getLength();
data = new Byte[len];
length = VarInt(len);
// Copy the data
for (int i = 0; i < len; ++i)
data[i] = rhs.data[i];
return *this;
}
/*********************************
* SerialString :: ~SerialString *
* Destructor *
*********************************/
SerialString::~SerialString() { if (data != NULL) { delete[] data; data = NULL; } }
/*********************************
* SerialString :: getLength *
* Returns the size of the array *
*********************************/
const Int SerialString::getLength() const { return length.toInt(); }
/********************************
* SerialString :: getSize *
* Returns the size of the data *
********************************/
const Int SerialString::getSize() const { return length.toInt() + length.getSize(); }
/*******************************
* SerialString :: getData *
* Creates an array of data *
* Has to be deleted after use *
*******************************/
char* SerialString::makeData() const
{
// Get the dimensions of the data and create an array to store it
Int end1 = length.getSize();
Int end2 = getSize();
const Byte* lengthData = length.getData();
char* moreData = new char[end2];
// Copy the contents of the length to the new array
int i;
for (i = 0; i < end1; i++)
moreData[i] = lengthData[i];
// Copy the contents of the data to the new array
for (int y = 0; i < end2; y++, i++)
moreData[i] = data[y];
return moreData;
}
/***********************
* SerialString :: str *
* Returns a string *
***********************/
const String SerialString::str() const
{
return String((const char*)data, length.toInt());
}
/***********************
* Chat :: Chat *
* Default Constructor *
***********************/
Chat::Chat(Byte* data) : SerialString(data) {}
/*********************************
* Chat :: Chat *
* Constructor from UTF-8 String *
*********************************/
Chat::Chat(const String& text) : SerialString(text) {}
/*****************
* Chat :: ~Chat *
* Destructor *
*****************/
Chat::~Chat() { if (data != NULL) { delete[] data; data = NULL; } }
/**************************************
* Serial Position :: Serial Position *
* Default Constructor *
**************************************/
SerialPosition::SerialPosition(Long data) : data(data) {}
/**************************************
* Serial Position :: Serial Position *
* Constructor from 3 Ints *
**************************************/
SerialPosition::SerialPosition(Int x, Int y, Int z)
{
data = ((Long)(x & 0x3FFFFFF) << 38) | ((Long)(y & 0xFFF) << 26) | (Long)(z & 0x3FFFFFF);
}
/**************************************
* Serial Position :: Serial Position *
* Constructor from Position *
**************************************/
SerialPosition::SerialPosition(Position pos) { SerialPosition(pos.x, pos.y, pos.z); }
/*************************************
* SerialPosition :: ~SerialPosition *
* Destructor *
*************************************/
SerialPosition::~SerialPosition() {}
/**************************
* SerialPosition :: getX *
* Get the X coordinate *
**************************/
const Int SerialPosition::getX() const { return data >> 38; }
/**************************
* SerialPosition :: getY *
* Get the Y coordinate *
**************************/
const Int SerialPosition::getY() const { return (data >> 26) & 0xFFF; }
/**************************
* SerialPosition :: getZ *
* Get the Z coordinate *
**************************/
const Int SerialPosition::getZ() const { return data << 38 >> 38; }
/*****************************
* SerialPosition :: getdata *
* Returns the raw data *
*****************************/
const Long SerialPosition::getData() const { return data; }
/********************************
* SerialPosition :: toPosition *
* Returns the position *
********************************/
const Position SerialPosition::toPosition() const { return Position(getX(), getY(), getZ()); }
/************************
* Position :: Position *
* Default Constructor *
************************/
Position::Position(Int x, Int y, Int z) : x(x), y(y), z(z) {}
/**************************
* PositionF :: PositionF *
* Default Constructor *
**************************/
PositionF::PositionF(Double x, Double y, Double z) : x(x), y(y), z(z) {}
/***********************
* UUID :: UUID *
* Default Constructor *
***********************/
UUID::UUID(Long value1, Long value2) : v1(value1), v2(value2) {}
/**************************
* UUID :: UUID *
* Generate from a client *
**************************/
UUID::UUID(Client* client) { recalculate(client); }
/*******************
* UUID :: ~UUID *
* Destructor *
*******************/
UUID::~UUID() {}
/**************************
* UUID :: recalculate *
* Generate from a client *
**************************/
void UUID::recalculate(Client* client)
{
// TODO: Generate a UUID
v1 = 0;
v2 = 0;
}
/*************************
* UUID :: str *
* Returns a UUID String *
*************************/
const String UUID::str() const
{
// TODO: Generate UUID Strings
return "00000000-0000-3000-0000-000000000000";
}
/**************************
* UUID :: getFirst *
* Returns the first long *
**************************/
const Long UUID::getFirst() const { return v1; }
/***************************
* UUID :: getSecond *
* Returns the second long *
***************************/
const Long UUID::getSecond() const { return v2; }
/*****************************************************************
* ChunkSection :: setBlock *
* Sets the block at the specified index to the specified id *
* Any block id that is < 0 or > 4095 causes undefined behavior! *
*****************************************************************/
void ChunkSection::setBlock(int index, BlockID blockid)
{
// Create a new array when necessary
if (!blocks)
fillBlocks();
// Set the block to the new block and the current block state
blocks[index] = (blocks[index] & 0xF) | ((Short)blockid << 4);
}
/*****************************************************************************
* ChunkSection :: setBlock *
* Sets the block at the specified index to the specified id and block state *
* Any block id that is < 0 or > 4095 causes undefined behavior! *
* Any block state that is < 0 or > 15 causes undefined behavior! *
*****************************************************************************/
void ChunkSection::setBlock(int index, BlockID blockid, Byte blockstate)
{
// Create a new array when necessary
if (!blocks)
fillBlocks();
// Set the block to the new block and the current block state
blocks[index] = ((Short)blockid << 4) | blockstate;
}
/*******************************************************************
* ChunkSection :: setBlockState *
* Sets the block state at the specified index to the specified id *
* Any block state that is < 0 or > 15 causes undefined behavior! *
*******************************************************************/
void ChunkSection::setBlockState(int index, Byte blockstate)
{
// Create a new array when necessary
if (!blocks)
fillBlocks();
// Set the block to the current block with the new block state
blocks[index] = (blocks[index] & 0xFFF0) | blockstate;
}
/*********************************************************************
* ChunkSection :: setBlockLighting *
* Sets the block lighting at the specified index to the given value *
* Any value that is < 0 or > 15 causes undefined behavior! *
*********************************************************************/
void ChunkSection::setBlockLighting(int index, Byte value)
{
// Create a new array when necessary
if (!lights)
fillLighting();
// Set the lighting to the new block lighting and the current sky lighting
lights[index] &= 0xF0;
lights[index] |= value << 4;
}
/*******************************************************************
* ChunkSection :: setSkyLighting *
* Sets the sky lighting at the specified index to the given value *
* Any value that is < 0 or > 15 causes undefined behavior! *
*******************************************************************/
void ChunkSection::setSkyLighting(int index, Byte value)
{
// Create a new array when necessary
if (!lights)
fillLighting();
// Set the lighting to the current block lighting and the new sky lighting
lights[index] &= 0xF;
lights[index] |= value;
}
/****************************************************************
* ChunkSection :: setLighting *
* Sets the lighting at the specified index to the given values *
* Any value that is < 0 or > 15 causes undefined behavior! *
****************************************************************/
void ChunkSection::setLighting(int index, Byte blockLightValue, Byte skyLightValue)
{
// Create a new array when necessary
if (!lights)
fillLighting();
// Set the lighting to the current block lighting and the new sky lighting
lights[index] = (blockLightValue << 4) | skyLightValue;
}
/******************************************************************
* ChunkSection :: fillBlocks *
* Fills the chunk with the given block and block state *
* Any block id that is < 0 or > 4095 causes undefined behavior! *
* Any block state that is < 0 or > 15 causes undefined behavior! *
******************************************************************/
void ChunkSection::fillBlocks(BlockID blockid, Byte blockstate)
{
// Create a new array when necessary
if (!blocks)
blocks = new Short[4096];
Short value = ((Short)blockid << 4) | blockstate;
// Set every block to the given block state and id
for (int i = 0; i < 4096; i++)
blocks[i] = value;
}
/************************************************************
* ChunkSection :: fillLighting *
* Sets all of the lighting to the given values *
* Any value that is < 0 or > 15 causes undefined behavior! *
************************************************************/
void ChunkSection::fillLighting(Byte blockLightValue, Byte skyLightValue)
{
// Create a new array when necessary
if (!lights)
lights = new Byte[4096];
Byte value = (blockLightValue << 4) | skyLightValue;
// Set all of the lighting to the given block and sky lighting values
for (int i = 0; i < 4096; i++)
lights[i] = value;
}
| true |
7a405c7e5f30e33b8e92d489dd6c014a3ea60907
|
C++
|
Ixox/NeoPixel-Projects
|
/NeoLampe/src/LedSpot.h
|
UTF-8
| 1,198 | 2.828125 | 3 |
[] |
no_license
|
/*
Copyright © 2018, Xavier Hosxe
Free license, do what you want with these files
*/
#ifndef LEDSPOT_H
#define LEDSPOT_H
#include <Adafruit_NeoPixel.h>
enum LedAnimation
{
ANIM_0 = 0,
ANIM_1,
ANIM_2,
ANIM_3,
ANIM_4,
ANIM_FINISHED
};
class LedSpot
{
public:
LedSpot(uint16_t numberOfPixels, uint8_t pin);
void setAllColor(uint32_t c);
uint32_t getColorFrom8bitsValue(uint8_t value, bool stopAtwhite = true);
void setBrightness(uint8_t brightness);
uint8_t getBrightness() { return m_brightness; }
void show();
void incLastUpdatedLed();
uint8_t getLastUpdatedOpositeLed();
void animationStart(LedAnimation anim);
void animationNextStep();
void setAnimationSpeed(uint8_t animationSpeed);
void nextAnimation();
uint32_t getRandomColor();
void loadStateFromEEPROM(int index);
void saveStateToEEPROM(int index);
void acknowledge(uint32_t color);
private:
Adafruit_NeoPixel *m_leds;
uint8_t m_numberOfPixels;
uint8_t m_brightness;
LedAnimation m_animationType;
int16_t m_animationStep;
int16_t m_animationSubStep;
uint8_t m_animationSpeed;
uint8_t m_lastUpdatedLed;
};
#endif
| true |
933f6e18af6237f2293e937e411a96c2d4def9ea
|
C++
|
tks3210/Atcoder
|
/abc109/abc109_d.cpp
|
UTF-8
| 1,790 | 3.265625 | 3 |
[] |
no_license
|
#include <iostream>
#include <vector>
using namespace std;
//pair<int int> 二つの異なる型の値を保持する。
//メンバ変数としてfirst, secondを持つ。XX.firstみたいな感じでアクセスする。
//https://cpprefjp.github.io/reference/utility/pair.html
#define pir pair<int, int>
//vector<T> 動的配列。
//不定個数の要素を格納できる。push_back()で要素を追加する。
vector<pair<pir,pir>> ans;
int main(){
int H, W;
int tmp;
int Num[500][500] = {0};
cin >> H >> W;
for (int i= 0; i < H; i++){
for (int j=0; j < W; j++){
if (i == H - 1 && j == W - 1) break;
cin >> tmp;
Num[i][j] += tmp;
if (Num[i][j] % 2 != 0){
if (j != W - 1){
//make_pair(T1, T2) によりpairクラスのオブジェクトを生成できる。
ans.push_back(make_pair(make_pair(i+1, j+1), make_pair(i+1, j+2)));
Num[i][j+1]++;
}else {
//なんやかんやこれでも、push_backできるらしい。波括弧の初期化
//https://dev.activebasic.com/egtra/2015/12/02/845/
ans.push_back({{i+1, j+1}, {i+2, j+1}});
Num[i+1][j]++;
}
}
}
}
cout << ans.size() << endl;
//範囲for文 コンテナ内の全要素に関してループを行う。
//(下の例だとansのクラスの)メンバ関数にbegin(),end()を持つクラスであれば使用可能
//https://cpprefjp.github.io/lang/cpp11/range_based_for.html
for (auto p:ans){
cout << p.first.first << " " << p.first.second << " " << p.second.first << " " << p.second.second << endl;
}
}
| true |
fdb9b8b3f571b7bed87d8bc067a3b368177b737a
|
C++
|
dongyanchaoTJ/LNMHacks-3.0-Submission
|
/manvendra19_f0ec/Code1_OneTXintdatatoServer/code01_tx/code01_tx.ino
|
UTF-8
| 2,961 | 2.84375 | 3 |
[] |
no_license
|
#include<SPI.h> // Library used to connect arduino with other devices
#include<nRF24L01.h> // Library made by TMRH Group for nRF24L01
#include<RF24.h> // Library made by TMRH Group for nRF24L01
#include "printf.h" // To display the attributes of the nRF
const int pinCE=9; // Chip enable is to enable or disable the connected device
const int pinCSN=10; // This pin is to tell the device that the sent information is a command or data
int counter=0; // Since, i am sending counter and it is a small int, i am defining it as byte
bool done=false; // done is updated to "True" when all the required bytes are sent
RF24 radio(pinCE, pinCSN); // Creating an object from the RF24 class
const uint64_t pAddress= 0xB00B1E5000LL; // Creating the pipe address
void setup()
{
Serial.begin(57600); // Using begin function of Serial library to display info on Monitor
printf_begin; // Printing details of nrf module
radio.begin(); // To start the nrf module
radio.setAutoAck(1); // To ensure auto acknowledgement is ON
radio.enableAckPayload(); //
radio.setRetries(5,15);
radio.openWritingPipe(pAddress);
radio.stopListening();
radio.printDetails();
}
void loop()
{
if(!done) // Last counter has not been sent yet
{
Serial.print(" Now send packet number : ");
Serial.println(counter); // To print the packet number
unsigned long time1 = micros(); // Starting time, before sending
if(!radio.write(&counter,2)) // If sending was not possible
{
Serial.println(" Packet delivery failed "); // Display,delivery was failed
}
else
{
unsigned long time2 = micros(); // Otherwise, note the time when the acknowledgement has come
time2 = time2 - time1; // This is trip time
Serial.print(" Time from message sent to receive acknowledgement : ");
Serial.print(time2);
Serial.println("microseconds");
counter++; // Increase counter for next iteration
if(counter==200)
counter=0;
}
delay(5);
while(radio.available()) // If there is anything in the radio
{
char gotChars[5];
radio.read (gotChars,5); // Store it in gotchar
Serial.print(gotChars[0]); // Print gotchar
Serial.print(gotChars[1]);
Serial.print(gotChars[2]);
Serial.print(gotChars[3]);
done=true;
}
}
delay(10);
}
| true |
512f6d7a2a7affb8a585809ede46331a8e8db2a0
|
C++
|
xxORVARxx/SDL-Book
|
/src/data/Parser.cpp
|
UTF-8
| 11,806 | 3.109375 | 3 |
[] |
no_license
|
#include "Parser.h"
namespace data
{
void Throw_invalid_argument( std::string the_corrupted_input );
void Throw_file_corrupted( std::string _str = "" );
bool Is_template( std::string& _function );
void Comment( std::ifstream& _file, std::string& _comment );
std::string Check_for_comments( std::ifstream& _file, std::string& _str );
}//data
namespace data
{
void
Parser::Set_this( State* _state )
{
m_this_state = _state;
}
void
Parser::Set_this( State* _state,
Base_SDL_game_obj* _object )
{
m_this_state = _state;
m_this_object = _object;
}
}//data
namespace data
{
template< typename T >
T
Parser::Parse_file( std::ifstream& _file )
{
this->Parse_file( _file, "Return" );
std::string function = data::Next_line_from_file( _file );
return this->Next_get_functions< T >( _file, function );
}
void
Parser::Parse_file( std::ifstream& _file, std::string _end )
{
std::string function;
while( ! _file.eof())
{
_file >> function;
if( _file.fail())
data::Throw_file_corrupted();
if( (*function.rbegin()) == ')' ) // Do-Function.
{
this->Next_do_functions( _file, function );
}
else if( function[0] == '#' ) // Comment.
{
data::Comment( _file, function );
}
else if( function == "Done" ) // Done.
{
if( _end == "Done" )
return;
else if( _end == "Local" )
throw std::logic_error( "(xx) Parsing ERROR! Unexpected: 'Done'. Expected: 'Local' and a Local-function! " );
else
throw std::logic_error( "(xx) Parsing ERROR! Unexpected: 'Done'. Expected: 'Return' and a value to be returned! " );
}
else if( function == "Return" ) // Return.
{
if( _end == "Return" )
return;
else if( _end == "Local" )
throw std::logic_error( "(xx) Parsing ERROR! Unexpected: 'Return'. Expected: 'Local' and a Local-function! " );
else
throw std::logic_error( "(xx) Parsing ERROR! Unexpected: 'Return'. Expected: 'Done' and no return value! " );
}
else if( function == "Local" ) // Local-Function
{
if( _end == "Local" )
return;
else
throw std::logic_error( "(xx) Parsing ERROR! Unexpected: 'Local'. Not expecting Local-function! " );
}
else
data::Throw_invalid_argument( function );
}//while
if( function == "Done" )
throw std::logic_error( "(xx) Parsing ERROR! Expected: 'Done' to end the parsing! " );
else
throw std::logic_error( "(xx) Parsing ERROR! Expected: 'Return' and a value to be returned! " );
}
}//data
namespace data
{
void
Parser::Next_do_functions( std::ifstream& _file,
std::string& _function )
{
if( (*_function.rbegin()) != ')' )
throw std::logic_error( "(xx) Parsing ERROR! Expected: 'Return Value' from the function: '" + _function + "'. Missing return value! " );
if( data::Is_template( _function ))
this->Select_type_for_do( _file, _function );
else
this->List_of_do_functions( _file, _function );
}
template< typename T >
T
Parser::Next_get_functions( std::ifstream& _file,
std::string& _function )
{
if( (*_function.rbegin()) == ')' )
throw std::logic_error( "(xx) Parsing ERROR! Unexpected: 'Return Value' from the function: '" + _function + "'. Did not expect return value! " );
if( data::Is_template( _function ))
return this->Select_type_for_get< T >( _file, _function );
else
return this->List_of_get_functions< T >( _file, _function );
}
}//data
namespace data
{
void
Parser::Select_type_for_do( std::ifstream& _file,
std::string& _function )
{
std::string template_type = data::Next_line_from_file( _file );
if( template_type == "Byte" )
this->List_of_template_do_functions< byte_t >( _file, _function );
else if( template_type == "Integer" )
this->List_of_template_do_functions< integer_t >( _file, _function );
else if( template_type == "Real" )
this->List_of_template_do_functions< real_t >( _file, _function );
else if( template_type == "String" )
this->List_of_template_do_functions< string_t >( _file, _function );
else
throw std::invalid_argument( "(xx) Parsing ERROR! '" + template_type + "' is not a valid type! " );
}
template< typename T >
T
Parser::Select_type_for_get( std::ifstream& _file,
std::string& _function )
{
T value;
std::string template_type = data::Next_line_from_file( _file );
if( template_type == "Byte" )
value = this->List_of_template_get_functions< byte_t >( _file, _function );
else if( template_type == "Integer" )
value = this->List_of_template_get_functions< integer_t >( _file, _function );
else if( template_type == "Real" )
value = this->List_of_template_get_functions< real_t >( _file, _function );
else if( template_type == "String" )
value = this->List_of_template_get_functions< string_t >( _file, _function );
else
throw std::invalid_argument( "(xx) Parsing ERROR! '" + template_type + "' is not a valid type! " );
return value;
}
}//data
namespace data
{
void
Parser::List_of_do_functions( std::ifstream& _file,
std::string& _function )
{
switch( _function[0] )
{
case 'l': // logic Functions:
if( _function == "l_If(PP)" )
m_do_functions.l_If( _file, this );
else if( _function == "l_If_not(PP)" )
m_do_functions.l_If_not( _file, this );
else
Throw_invalid_argument( _function );
break;
case 'c': // Container:
if( _function == "c_Container_erase(P)" )
m_do_functions.c_Container_erase( _file, this );
else
Throw_invalid_argument( _function );
break;
case 's': // State:
if( _function == "s_Make_camera(P)" )
m_do_functions.s_Make_camera( _file, this );
else
Throw_invalid_argument( _function );
break;
case 'o': // Object:
if( _function == "o_Make_SDL_gobj(PP)" )
m_do_functions.o_Make_SDL_gobj( _file, this );
else
Throw_invalid_argument( _function );
break;
case 't': // Texture:
if( _function == "t_Swap_texture_maps()" )
m_do_functions.t_Swap_texture_maps();
else if( _function == "t_Move_or_load_texture(PP)" )
m_do_functions.t_Move_or_load_texture( _file, this );
else if( _function == "t_Clear_texture_map()" )
m_do_functions.t_Clear_texture_map();
else if( _function == "t_Clear_current_texture_map()" )
m_do_functions.t_Clear_current_texture_map();
else
Throw_invalid_argument( _function );
break;
case 'i': // Images:
if( _function == "i_Load_image_data(PP)" )
m_do_functions.i_Load_image_data( _file, this );
else if( _function == "i_Erase_image_data(P)" )
m_do_functions.i_Erase_image_data( _file, this );
else if( _function == "i_Make_frame_printer(PPRRRR)" )
m_do_functions.i_Make_frame_printer( _file, this );
else if( _function == "i_Make_action(PPPPRRRR)" )
m_do_functions.i_Make_action( _file, this );
else
Throw_invalid_argument( _function );
break;
case 'e': // Events:
if( _function == "e_Make_event()" )
m_do_functions.e_Make_event( _file, this );
else
Throw_invalid_argument( _function );
break;
default:
Throw_invalid_argument( _function );
}//switch
}
template< typename T >
void
Parser::List_of_template_do_functions( std::ifstream& _file,
std::string& _function )
{
switch( _function[0] )
{
case 'c': // Container:
if( _function == "c_Container_add(PT)" )
m_do_functions.c_Container_add< T >( _file, this );
else if( _function == "c_Container_set(PT)" )
m_do_functions.c_Container_set< T >( _file, this );
else
Throw_invalid_argument( _function );
break;
case 'p': // Parser:
if( _function == "p_Print(T)" )
m_do_functions.p_Print< T >( _file, this );
else
Throw_invalid_argument( _function );
break;
default:
Throw_invalid_argument( _function );
}//switch
}
}//data
namespace data
{
template< typename T >
T
Parser::List_of_get_functions( std::ifstream& _file,
std::string& _function )
{
T value;
switch( _function[0] )
{
case 'b': // Built In Types:
if( _function == "b_Byte()R" )
value = m_get_functions.b_Byte( _file );
else if( _function == "b_Integer()R" )
value = m_get_functions.b_Integer( _file );
else if( _function == "b_Real()R" )
value = m_get_functions.b_Real( _file );
else if( _function == "b_String()R" )
value = m_get_functions.b_String( _file );
else
Throw_invalid_argument( _function );
break;
case 'c': // Container:
if( _function == "c_Container_has(P)R" )
value = m_get_functions.c_Container_has( _file, this );
else
Throw_invalid_argument( _function );
break;
case 'o': // Object:
if( _function == "o_This_object()R" )
value = m_get_functions.o_This_object( this );
else
Throw_invalid_argument( _function );
break;
case 'i': // Images:
if( _function == "i_Has_image_data(P)R" )
value = m_get_functions.i_Has_image_data( _file, this );
else
Throw_invalid_argument( _function );
break;
case 's': // State:
if( _function == "s_This_state()R" )
value = m_get_functions.s_This_state( this );
else if( _function == "s_Has_state(P)R" )
value = m_get_functions.s_Has_state( _file, this );
else
Throw_invalid_argument( _function );
break;
case 't': // Texture:
if( _function == "t_Texture_width(P)R" )
value = m_get_functions.t_Texture_width( _file, this );
else if( _function == "t_Texture_height(P)R" )
value = m_get_functions.t_Texture_height( _file, this );
else
Throw_invalid_argument( _function );
break;
case 'w': // World:
if( _function == "w_Display_width()R" )
value = m_get_functions.w_Display_width();
else if( _function == "w_Display_height()R" )
value = m_get_functions.w_Display_height();
else
Throw_invalid_argument( _function );
break;
default:
Throw_invalid_argument( _function );
}//switch
return value;
}
template< typename T >
T
Parser::List_of_template_get_functions( std::ifstream& _file,
std::string& _function )
{
T value;
switch( _function[0] )
{
case 'm': // Mathematical Operations:
if( _function == "m_Add(TT)T" )
value = m_get_functions.m_Add< T >( _file, this );
else if( _function == "m_Subtract(TT)T" )
value = m_get_functions.m_Subtract< T >( _file, this );
else if( _function == "m_Multiply(TT)T" )
value = m_get_functions.m_Multiply< T >( _file, this );
else if( _function == "m_Divide(TT)T" )
value = m_get_functions.m_Divide< T >( _file, this );
else
Throw_invalid_argument( _function );
break;
case 'c': // Container:
if( _function == "c_Container_get(P)T" )
value = m_get_functions.c_Container_get< T >( _file, this );
else if( _function == "c_Container_take(P)T" )
value = m_get_functions.c_Container_take< T >( _file, this );
else
Throw_invalid_argument( _function );
break;
/*
case 'r': // Random:
if( _function == "r_Random_discrete_num(PP)T" )
value = data::r_Random_discrete_num< T >( _file );
else if( _function == "r_Random_real_num(PP)T" )
value = data::r_Random_real_num< T >( _file );
else
Throw_invalid_argument( _function );
break;
*/
default:
Throw_invalid_argument( _function );
}//switch
return value;
}
}//data
namespace data
{
template byte_t Parser::Parse_file< byte_t >( std::ifstream& _file );
template integer_t Parser::Parse_file< integer_t >( std::ifstream& _file );
template real_t Parser::Parse_file< real_t >( std::ifstream& _file );
template string_t Parser::Parse_file< string_t >( std::ifstream& _file );
}//data
#include "Data_do_functions.tpp"
#include "Data_get_functions.tpp"
| true |
f5c9fc92be5777b8c315491fecb4bd615bcec3f6
|
C++
|
mugur9/cpptruths
|
/cpp0x/curry_class_template.cpp
|
UTF-8
| 1,197 | 3.1875 | 3 |
[] |
no_license
|
#include <type_traits>
#include <functional>
#include <map>
#include <iostream>
template <template <template <class> class> class T>
struct TTT {};
template <template <class...> class C, class... T, class D = C<T...>>
std::true_type valid(std::nullptr_t);
template <template <class...> class C, class... T>
std::false_type valid(...);
template <class TrueFalse, template <class...> class C, class... ActualArgs>
struct curry_impl;
template <template <class...> class C, class... ActualArgs>
struct curry_impl<std::true_type, C, ActualArgs...> {
using type = C<ActualArgs...>;
};
template <template <class...> class C, class... ActualArgs>
struct curry_impl<std::false_type, C, ActualArgs...> {
template <class U>
using apply = curry_impl<decltype(valid<C, ActualArgs..., U>(nullptr)), C, ActualArgs..., U>;
};
template <template <class...> class C>
struct curry {
template <class U>
using apply = curry_impl<decltype(valid<C, U>(nullptr)), C, U>;
};
int main(void) {
//int i = curry<std::is_same>::apply<int>::apply<int>::type::value;
curry<std::less>::apply<int>::type j;
curry<std::map>::apply<int>::apply<long>::type k;
std::cout << std::boolalpha << j(5000, 4000);
}
| true |
fe0f80353a7efd55e07809ca0e1197f2a35b2fc3
|
C++
|
qqsskk/Connection
|
/demo/echo/epoll_server/epoll_server.cpp
|
UTF-8
| 1,922 | 2.515625 | 3 |
[] |
no_license
|
#include <EPollServer.h>
#include "../Protocal.h"
#include <vector>
#include <iostream>
#include <stdio.h>
using namespace std;
#define LISTEN_PORT 8000
#define LISTEN_QUEUE 5
#define MAX_MSG_SIZE 1024
#define MAX_FDS 1024
#define MAX_EVENTS 10
int main()
{
ConcurrentServer *pServer = new EPollServer(MAX_FDS, MAX_EVENTS);
ConcurrentServer::ClientVector waitClientVec;
char msgStr[MAX_MSG_SIZE];
struct ProtocalHead head;
bool bNewClient;
ConcurrentServer::ClientVectorIter iter;
try{
cout << "Server Starting Service...\n";
pServer->StartService(NULL, LISTEN_PORT, LISTEN_QUEUE);
while(true){
bNewClient = pServer->WaitForClient(waitClientVec);
//process new client
iter = waitClientVec.begin();
if(bNewClient){
cout << "Client " << iter->GetIP() << ":" << iter->GetPort() << " connected in\n";
++iter;
}
//process requests
for(; iter != waitClientVec.end(); ++iter){
if(iter->RecvData(&head,sizeof(head)) == false){
cout << iter->GetLastError() << endl;
cout << "Remove Client " << iter->GetIP() << ":" << iter->GetPort() << endl;
pServer->RemoveClient(*iter);
continue;
}
if(iter->RecvData(msgStr, head.dataLen) == false){
cout << iter->GetLastError() << endl;
cout << "Remove Client " << iter->GetIP() << ":" << iter->GetPort() << endl;
pServer->RemoveClient(*iter);
continue;
}
if(iter->SendData(msgStr, head.dataLen) == false){
cout << iter->GetLastError() << endl;
cout << "Remove Client " << iter->GetIP() << ":" << iter->GetPort() << endl;
pServer->RemoveClient(*iter);
continue;
}
msgStr[head.dataLen]=0;
cout << "Received "<< msgStr << "\nEcho back ...\n";
}
}//while(true)
pServer->EndService();
}catch(ConnectionException &e){
cout << e.what() << endl;
}
delete pServer;
return 0;
}
| true |
20f93421ade81099f10daff37605910956cf696a
|
C++
|
moevm/oop
|
/6383/KaramyshevAO/lab1.2/Arc.cpp
|
UTF-8
| 1,194 | 3.109375 | 3 |
[] |
no_license
|
#include "Arc.h"
Arc::Arc(Point p1, Point p2, double input_radius, Point &cntr, Color &clr) : P1(p1), P2(p2), Circle(input_radius, cntr, clr) {}
void Arc::Calibr(double calibr) {
Circle::Calibr(calibr);
P1.x = (P1.x - cntr.x)*calibr + cntr.x;
P1.y = (P1.y - cntr.y)*calibr + cntr.y;
P2.x = (P2.x - cntr.x)*calibr + cntr.x;
P2.y = (P2.y - cntr.y)*calibr + cntr.y;
}
void Arc::Grad(double grad) {
P1.x = cos(acos((P1.x - cntr.x) / radius) + (grad/180)*PI) + cntr.x;
P1.y = sin(acos((P1.x - cntr.x) / radius) + (grad / 180)*PI) + cntr.y;
P2.x = cos(acos((P2.x - cntr.x) / radius) + (grad / 180)*PI) + cntr.x;
P2.y = sin(acos((P2.x - cntr.x) / radius) + (grad / 180)*PI) + cntr.y;
}
const Point& Arc::Get_P1() const { return P1; }
const Point& Arc::Get_P2() const { return P2; }
void Arc::Move(double x, double y) {
P1.x = P1.x - cntr.x + x;
P1.y = P1.y - cntr.y + y;
P2.x = P2.x - cntr.x + x;
P2.y = P2.y - cntr.y + y;
Circle::Move(x, y);
}
ostream& operator <<(ostream &os, const Arc &c) {
Point p1 = c.Get_P1();
Point p2 = c.Get_P2();
os << "P1(" << p1.x << "," << p1.y << ")";
os << " P2(" << p2.x << "," << p2.y << ")" << endl;
os << (const Circle &)c;
return os;
}
| true |
a209a669b585fdfcf2d8dd1b86ab0df62e043b28
|
C++
|
sh4062/Leetcode
|
/278.cpp
|
UTF-8
| 601 | 3.1875 | 3 |
[] |
no_license
|
// The API isBadVersion is defined for you.
// bool isBadVersion(int version);
class Solution {
public:
int firstBadVersion(int n) {
long l = 1;
long r = n;
int mid = 0;
while(l!=r){
mid=(l+r)/2;
//cout<<mid;
if(isBadVersion(mid)&&!isBadVersion(mid-1)){
//cout<<mid;
return mid;
}else if(isBadVersion(mid)){
r=mid-1;
}
else{
l=mid+1;
}
if(l==r)return l;
}
return mid==0?1:mid;
}
};
| true |
30ae98500300dc04af86f7ed1c81294a0e808eff
|
C++
|
niuxu18/logTracker-old
|
/second/download/squid/gumtree/squid_repos_function_5683_last_repos.cpp
|
UTF-8
| 478 | 2.546875 | 3 |
[] |
no_license
|
std::vector<Auth::User::Pointer>
CredentialsCache::sortedUsersList() const
{
std::vector<Auth::User::Pointer> rv(size(), nullptr);
std::transform(store_.begin(), store_.end(), rv.begin(),
[](StoreType::value_type v) { return v.second; }
);
std::sort(rv.begin(), rv.end(),
[](const Auth::User::Pointer &lhs, const Auth::User::Pointer &rhs) {
return strcmp(lhs->username(), rhs->username()) < 0;
}
);
return rv;
}
| true |
2ee7a3e9727e64b117375139373728d725c63703
|
C++
|
Krixium/KindaFastMatrixLibrary
|
/KindaFastMatrixLibrary/Matrix.h
|
UTF-8
| 2,194 | 2.984375 | 3 |
[] |
no_license
|
#pragma once
#include <assert.h>
#include <cmath>
#include <fstream>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
namespace kfml
{
class Matrix
{
public:
// Row
const size_t M;
// Column
const size_t N;
private:
// Was the determinant already calculated?
bool mbDetCalculated;
// Matrix data
std::unique_ptr<std::vector<double>> mData;
// Determinant
double mDet;
// Inverse Matrix
std::unique_ptr<Matrix> mInverse;
public:
Matrix(const size_t m);
Matrix(const size_t m, const size_t n);
Matrix(double *data, const size_t m, const size_t n);
Matrix *CrossMultiply(const Matrix& b);
inline Matrix *CrossMultiply(const std::unique_ptr<Matrix>& b) { return CrossMultiply(*b); }
inline Matrix *CrossMultiply(const Matrix *b) { return CrossMultiply(*b); }
void Scale(const double scalar);
Matrix *GetInverse();
const double GetDeterminant();
inline void Transpose()
{
for (size_t i = 0; i < M; i++)
{
for (size_t j = i + 1; j < N; j++)
{
double tmp = GetVal(i, j);
SetVal(GetVal(j, i), i, j);
SetVal(tmp, j, i);
}
}
}
inline double GetVal(const size_t m, const size_t n) const { return mData->at(m * N + n); }
inline void SetVal(const double val, const size_t m, const size_t n)
{
mData->at(m * N + n) = val;
mbDetCalculated = false;
mInverse.reset();
}
inline void Print()
{
for (size_t i = 0; i < M; i++)
{
for (size_t j = 0; j < N; j++)
{
std::cout << std::to_string(GetVal(i, j)) << "\t";
}
std::cout << std::endl << std::endl;
}
std::cout << std::endl;
}
inline void PrintLine()
{
std::cout << "[";
for (size_t i = 0; i < M * N - 1; i++)
{
std::cout << std::round(mData->at(i)) << ",";
}
std::cout << std::round(mData->at(M * N - 1)) << "]";
std::cout << std::endl;
}
inline void ZeroOut() { for (size_t i = 0; i < M * N; i++) mData->at(i) = 0; }
private:
void calculateInverse();
static double calculateDet(const Matrix &matrix, const size_t size);
static void extractMinor(const Matrix& matrix, Matrix& tmp, const size_t x, const size_t y, const size_t n);
};
}
| true |
6c31c2746f38c6b0e22ffd7eba1b77a91d209442
|
C++
|
figopratama/pemrograman-dasar
|
/Praktikum1.c+.cpp
|
UTF-8
| 433 | 2.921875 | 3 |
[] |
no_license
|
/*Program Menghitung Billing Warnet*/
#include <iostream>
#include <conio.h>
using namespace std;
int main ()
{
int A,B,C,X,Y,Z,T;
cout<<"HITUNG BIAYA WARNET KAMU DISINI\n";
cout<<endl;
cout<<"Masukkan Total Durasi Kamu Bermain Dibawah Ini\n";
cout<<"Jam = ";cin>>A;
cout<<"Menit = ";cin>>B;
cout<<"Detik = ";cin>>C;
X=A*5000;
Y=B*83;
Z=C*2;
T=X+Y+Z;
cout<<"\nTOTAL BIAYA = Rp."<<T;
getch ();
}
| true |
787a2887a3272542244ab72bda82327ef7e3f34a
|
C++
|
allenARM/Cpp-Piscine
|
/Day02/ex02/Fixed.class.hpp
|
UTF-8
| 1,311 | 2.8125 | 3 |
[] |
no_license
|
#ifndef FIXED_CLASS_HPP
# define FIXED_CLASS_HPP
#include <iostream>
#include <string>
#include <cmath>
class Fixed
{
public:
Fixed(void);
Fixed(Fixed const & src);
Fixed(int const val);
Fixed(float const valf);
~Fixed(void);
Fixed& operator=(Fixed const & rhs);
bool operator>(Fixed const & rhs) const;
bool operator<(Fixed const & rhs) const;
bool operator>=(Fixed const & rhs) const;
bool operator<=(Fixed const & rhs) const;
bool operator==(Fixed const & rhs) const;
bool operator!=(Fixed const & rhs) const;
Fixed operator+(Fixed const & rhs) const;
Fixed operator-(Fixed const & rhs) const;
Fixed operator*(Fixed const & rhs) const;
Fixed operator/(Fixed const & rhs) const;
Fixed& operator++(void);
Fixed operator++(int);
Fixed& operator--(void);
Fixed operator--(int);
float toFloat(void) const;
int toInt(void) const;
int getRawBits(void) const;
void setRawBits(int const raw);
static const Fixed& min(Fixed const &one, Fixed const &two);
static Fixed& min(Fixed &one, Fixed &two);
static const Fixed& max(Fixed const &one, Fixed const &two);
static Fixed& max(Fixed &one, Fixed &two);
private:
int _nbfixed;
static const int _fractbits;
};
std::ostream &operator<<(std::ostream &out, Fixed const &in);
#endif
| true |
c325313b846ef8de058f57e1f2b47f7b7b9290dd
|
C++
|
Dynmi/HW_CODE20
|
/4_2/main.cpp
|
UTF-8
| 2,589 | 2.578125 | 3 |
[] |
no_license
|
#include <bits/stdc++.h>
#define MAXN 560010
using namespace std;
set<int, less<int>> adj[MAXN]; // adj[i]是一个有序集合,包含了节点i的所有流出节点
int START;
vector<int> path; // 存储路径的栈
int deg[MAXN]; // 节点的出度
int max_all,cur_all;
int cnt,n; // 总共几条回路
vector<int>::iterator w_iter;
char PATH_IN[100] = "/home/dynmi/Documents/HW_CODE20/4_2/test_data.txt",
PATH_OUT[100] = "/home/dynmi/Documents/HW_CODE20/4_2/result.txt";
// 将path写入到文件中
void write_circuit(FILE *out)
{
w_iter = path.begin();
fprintf(out,"%d",*w_iter);
while( (++w_iter)!=path.end() ){
fprintf(out,",%d",*w_iter);
}
fprintf(out,"\n");
cnt++;
}
void travel(FILE *out,int cur)
{
path.push_back(cur); cur_all++;
if(cur_all==max_all)
{
if(adj[cur].find(START)!=adj[cur].end())
{
write_circuit(out);
}
path.pop_back(); cur_all--;
return;
}
auto v = adj[cur].begin();
while(*v<START && v!=adj[cur].end()){ v++; }
while( v!=adj[cur].end() ){
int next = *v;
if(deg[next]!=0 && find(path.begin(),path.end(),next)==path.end())
{
travel(out,next);
}
v++;
}
path.pop_back(); cur_all--;
}
int main()
{
clock_t start_t,end_t;
start_t = clock();
int a,b,tp;
FILE *in = fopen(PATH_IN,"r"),
*tmp= fopen("/home/dynmi/Documents/HW_CODE20/4_2/tmp.txt","w+");
//读入数据
while(fscanf(in,"%d,%d,%d",&a,&b,&tp)!=EOF)
{
n = max(n,max(a,b));
adj[a].insert(b);
deg[a]++;
}
fclose(in);
fprintf(tmp," \n");
/*
max_all=3;
thread fir(func,tmp);
max_all++;
thread sec(func,tmp);
max_all++;
thread thr(func,tmp);
max_all++;
thread fort(func,tmp);
max_all++;
thread fif(func,tmp);
fir.detach();
sec.detach();
thr.detach();
fort.detach();
fif.detach();
*/
for(max_all=3;max_all<=7;max_all++){
for(START=1;START<=n;START++){
cur_all=0; path.clear();
travel(tmp,START);
}
}
rewind(tmp);
FILE *OUT = fopen(PATH_OUT,"w");
fprintf(OUT,"%d\n",cnt);
char line[100];
while( fscanf(tmp,"%s",line)!=EOF ){
fprintf(OUT,"%s\n",line);
}
fclose(tmp); fclose(OUT);
end_t=clock();
double total_t = (double)(end_t - start_t) / CLOCKS_PER_SEC;
printf("%f seconds\n",total_t);
return 0;
}
| true |
4727fdee2e9a2ef865a6a85976551d11b48bf349
|
C++
|
hay2202/CPP-Ex5
|
/sources/BinaryTree.hpp
|
UTF-8
| 8,500 | 3.734375 | 4 |
[] |
no_license
|
#pragma once
#include <iostream>
#include <queue>
#include <stack>
using namespace std;
namespace ariel{
template<typename T>
class BinaryTree{
private:
typedef struct Node {
T data;
Node* left = nullptr;
Node* right = nullptr;
Node(const T& val ) : data(val) {}
bool operator==(const Node& other) const{
return (other.data == data) && (other.left == left) && (other.right == right);
}
bool operator!=(const Node& other) const{
return !(other == this);
}
}Node;
Node* root = nullptr;
void copyTree(Node& thisRoot,const Node& sourceRoot)
{
if (sourceRoot.left != nullptr)
{
thisRoot.left = new Node(sourceRoot.left->data);
copyTree(*thisRoot.left, *sourceRoot.left);
}
if (sourceRoot.right != nullptr)
{
thisRoot.right = new Node(sourceRoot.right->data);
copyTree(*thisRoot.right, *sourceRoot.right);
}
}
public:
BinaryTree() {}
BinaryTree(BinaryTree& other){
root = new Node(other.root->data);
copyTree(*this->root, *other.root);
}
~BinaryTree() {
if (root != nullptr) {
delete root;
}
}
BinaryTree &operator=(BinaryTree other) {
if (this != &other) {
delete root;
root = new Node(other.root->data);
copyTree(*root, *other.root);
}
return *this;
}
// Move constructor and operator=:
BinaryTree(BinaryTree&& other) noexcept{
root = other.root;
other.root = nullptr;
}
BinaryTree& operator=(BinaryTree&& other) noexcept{
if (root){
delete root;
}
root = other.root;
other.root = nullptr;
return *this;
}
BinaryTree& add_root(T r){
if(root == nullptr){
root = new Node(r);
}
else{
root->data = r;
}
return *this;
}
Node* find_node(const T& key,Node* curr){
Node* temp = curr;
if (curr == nullptr){
return curr;
}
if (curr->data == key){
return curr;
}
/* then recur on left sutree */
temp = find_node(key,curr->left);
if (temp != nullptr){
return temp;
}
/* node is not found in left,
so recur on right subtree */
temp = find_node(key, curr->right);
return temp;
}
BinaryTree& add_left(T parent, T child){
Node* temp = find_node(parent,root);
if (temp)
{
if (temp->left == nullptr){
temp->left = new Node(child);
}
else{
temp->left->data = child;
}
return *this;
}
throw out_of_range("parent doesn't exist!\n");
}
BinaryTree& add_right(const T& parent, const T& child){
Node* temp = find_node(parent,root);
if (temp)
{
if (temp->right == nullptr){
temp->right = new Node(child);
}
else{
temp->right->data = child;
}
return *this;
}
throw out_of_range("parent doesn't exist!\n");
}
friend ostream& operator<< (std::ostream& os, const BinaryTree& tree){
if (tree.root == NULL){
return os;
}
stack<Node*> s;
s.push(tree.root);
while (!s.empty()) {
Node* node = s.top();
os<<node->data<<" ";
s.pop();
if (node->right){
s.push(node->right);
}
if (node->left){
s.push(node->left);
}
}
os<<"\n__________________\n";
return os;
}
//-------------------------------------------------------------------
// inner class and methods that return instances of it
//-------------------------------------------------------------------
class iterator {
private:
Node* pointer_to_current_node = nullptr;
int type; // preorder = 0, inorder = 1, postorder = 2
queue<Node*> itr_queue;
void preorder(Node* curr)
{
// if the current node is empty
if (curr == nullptr) {
return;
}
itr_queue.push(curr);
// Traverse the left subtree
preorder(curr->left);
// Traverse the right subtree
preorder(curr->right);
}
void inorder(Node* curr)
{
// if the current node is empty
if (curr == nullptr) {
return;
}
// Traverse the left subtree
inorder(curr->left);
itr_queue.push(curr);
// Traverse the right subtree
inorder(curr->right);
}
void postorder(Node* curr)
{
// if the current node is empty
if (curr == nullptr) {
return;
}
// Traverse the left subtree
postorder(curr->left);
// Traverse the right subtree
postorder(curr->right);
itr_queue.push(curr);
}
public:
iterator(int n,Node* root) : type(n){
switch (n)
{
case 0:
preorder(root);
break;
case 1:
inorder(root);
break;
case 2:
postorder(root);
break;
default:
break;
}
if (!itr_queue.empty())
{
pointer_to_current_node = itr_queue.front();
itr_queue.pop();
}
}
T& operator*() const {
return pointer_to_current_node->data;
}
T* operator->() const {
return &(pointer_to_current_node->data);
}
// ++i;
iterator& operator++() {
if (itr_queue.empty()){
pointer_to_current_node = nullptr;
}
else{
pointer_to_current_node = itr_queue.front();
itr_queue.pop();
}
return *this;
}
// i++;
iterator operator++(int) {
iterator tmp= *this;
if (itr_queue.empty()){
pointer_to_current_node = nullptr;
}
else{
pointer_to_current_node = itr_queue.front();
itr_queue.pop();
}
return tmp;
}
bool operator==(const iterator& rhs) const {
return pointer_to_current_node == rhs.pointer_to_current_node;
}
bool operator!=(const iterator& rhs) const {
return pointer_to_current_node != rhs.pointer_to_current_node;
}
}; // END OF CLASS ITERATOR
iterator begin(){return begin_inorder();}
iterator end(){return end_inorder();}
iterator begin_preorder(){return iterator(0,root);}
iterator end_preorder(){return iterator(0,nullptr);}
iterator begin_inorder(){return iterator(1,root);}
iterator end_inorder(){return iterator(1,nullptr);}
iterator begin_postorder(){return iterator(2,root);}
iterator end_postorder(){return iterator(2,nullptr);}
};
}
| true |
b2ce8509dc58925c337d02b57a87964a44d992dd
|
C++
|
coronalabs/corona
|
/platform/windows/Corona.Native.Library.Win32/Interop/Input/InputDeviceDriverType.cpp
|
UTF-8
| 2,905 | 2.75 | 3 |
[
"MIT",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-free-unknown"
] |
permissive
|
//////////////////////////////////////////////////////////////////////////////
//
// This file is part of the Corona game engine.
// For overview and more information on licensing please refer to README.md
// Home page: https://github.com/coronalabs/corona
// Contact: support@coronalabs.com
//
//////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "InputDeviceDriverType.h"
#include <exception>
#include <list>
namespace Interop { namespace Input {
#pragma region Static Variables
/// <summary>
/// <para>Stores a collection of pointers to this class' driver type constants.</para>
/// <para>Used by this class' static From*() methods to fetch driver types by their integer or string IDs.</para>
/// </summary>
static std::list<InputDeviceDriverType*> sDriveTypeCollection;
#pragma endregion
#pragma region Static Constants
const InputDeviceDriverType InputDeviceDriverType::kDirectInput("directInput", 0);
const InputDeviceDriverType InputDeviceDriverType::kRawInput("rawInput", 1);
const InputDeviceDriverType InputDeviceDriverType::kXInput("xInput", 2);
#pragma endregion
#pragma region Constructors/Destructors
InputDeviceDriverType::InputDeviceDriverType(const char* stringId, int integerId)
: fStringId(stringId),
fIntegerId(integerId)
{
// Validate.
if (!fStringId || ('\0' == fStringId[0]))
{
throw std::exception();
}
// Add the driver type to the global collection.
sDriveTypeCollection.push_back(this);
}
InputDeviceDriverType::~InputDeviceDriverType()
{
}
#pragma endregion
#pragma region Public Methods
int InputDeviceDriverType::GetIntegerId() const
{
return fIntegerId;
}
const char* InputDeviceDriverType::GetStringId() const
{
return fStringId;
}
bool InputDeviceDriverType::Equals(const InputDeviceDriverType& value) const
{
return (fStringId == value.fStringId);
}
bool InputDeviceDriverType::NotEquals(const InputDeviceDriverType& value) const
{
return !Equals(value);
}
bool InputDeviceDriverType::operator==(const InputDeviceDriverType& value) const
{
return Equals(value);
}
bool InputDeviceDriverType::operator!=(const InputDeviceDriverType& value) const
{
return !Equals(value);
}
#pragma endregion
#pragma region Public Static Functions
const InputDeviceDriverType* InputDeviceDriverType::FromIntegerId(int integerId)
{
for (auto driverTypePointer : sDriveTypeCollection)
{
if (integerId == driverTypePointer->fIntegerId)
{
return driverTypePointer;
}
}
return nullptr;
}
const InputDeviceDriverType* InputDeviceDriverType::FromStringId(const char* stringId)
{
if (stringId && (stringId[0] != '\0'))
{
for (auto driverTypePointer : sDriveTypeCollection)
{
if ((stringId == driverTypePointer->fStringId) || !strcmp(stringId, driverTypePointer->fStringId))
{
return driverTypePointer;
}
}
}
return nullptr;
}
#pragma endregion
} } // namespace Interop::Input
| true |
988a3b2bb7c72e0a9fff47967e5850b4a70a4fe3
|
C++
|
helenyueyu/GFG-Exercise-Practice
|
/swapChanges.cpp
|
UTF-8
| 407 | 3.078125 | 3 |
[] |
no_license
|
#include <bits/stdc++.h>
using namespace std;
int minOperations(string s, string t, int n)
{
int ct0 = 0, ct1 = 0;
for (int i = 0; i < n; i++) {
if (s[i] == t[i])
continue;
if (s[i] == '0')
ct0++;
else
ct1++;
}
return max(ct0, ct1);
}
int main()
{
string s = "010", t = "101";
int n = s.length();
cout << minOperations(s, t, n);
return 0;
}
| true |
3981e085cf1f7d5e354da6442793ad6c8bac8f9d
|
C++
|
DFaouaz/RVR_UCM_2019-20
|
/proyecto/Server.cc
|
UTF-8
| 6,008 | 2.984375 | 3 |
[] |
no_license
|
#include "Server.h"
#include "MessageServer.h"
#include "MessageClient.h"
#include <chrono>
Server::Server(const char *host, const char *port) : socket(host, port), terminated(false)
{
players = std::vector<Player *>(4, nullptr);
}
Server::~Server()
{
}
// Public methods
void Server::init()
{
// Socket bind
socket.bind();
// Init world
world = new World(nullptr);
// Net thread
createNetThread();
inputThread = std::thread(&Server::manageInput, std::ref(*this));
inputThread.detach();
}
void Server::run()
{
sf::Clock timer;
float deltaTime = 0;
while (!terminated)
{
// Procesar partida
worldMutex.lock();
world->update(deltaTime);
worldMutex.unlock();
sendWorld();
if (1000.0 / 60.0 - timer.getElapsedTime().asMilliseconds() > 0)
std::this_thread::sleep_for(std::chrono::milliseconds(int64_t(1000.0 / 60.0 - timer.getElapsedTime().asMilliseconds())));
deltaTime = timer.getElapsedTime().asSeconds();
timer.restart();
}
}
void Server::close()
{
terminated = true;
MessageServer message;
message.type = MessageServer::LOGOUT;
for (int i = 0; i < clients.size(); i++)
{
socket.send(message, *clients[i]);
}
MessageClient cMessage;
cMessage.type = MessageClient::NONE;
for (int i = 0; i < netThreads.size(); i++)
socket.send(cMessage, socket);
for (int i = 0; i < netThreads.size(); i++)
netThreads[i].join();
for (auto client : clients)
delete client;
clients.clear();
delete world;
}
// Private methods
void Server::manageMessages()
{
// Mientras en hilo principal no este terminando
while (!terminated)
{
// Recibir conexiones
MessageClient message;
Socket *client = &socket;
if (socket.recv(message, client) < 0)
{
printf("Error al recibir mensaje\n");
return; //continue;
}
switch (message.type)
{
case MessageClient::LOGIN:
processLogin(client, message);
break;
case MessageClient::MESSAGE:
processMessage(client, message);
break;
case MessageClient::LOGOUT:
processLogout(client, message);
break;
default:
break;
}
}
}
void Server::manageInput()
{
std::string str = "";
while (str != "q")
std::cin >> str;
terminated = true;
}
void Server::processLogin(Socket *client, const MessageClient &message)
{
std::lock_guard<std::mutex> lock(clientMutex);
// Comprobar si ya esta logeado
for (auto c : clients)
{
if (*c == *client)
{
std::cout << "LOGGING ERROR: " << *client << "\n";
delete client;
client == nullptr;
}
}
if (client == nullptr)
return;
// Si hay hueco en la partida
int index = getFreeSlot();
if (index == -1)
{
MessageServer messageServer;
messageServer.type = MessageServer::LOGIN;
messageServer.index = -1;
socket.send(messageServer, *client);
return;
};
// Si no, meterlo en un vector
clients.push_back(client);
std::cout << "CLIENT LOGGED: " << *client << "\n";
//ECHO
MessageServer messageServer;
messageServer.type = MessageServer::LOGIN;
messageServer.index = index;
socket.send(messageServer, *client);
addPlayer(index);
// Crear otro hilo
createNetThread();
}
void Server::processMessage(Socket *client, const MessageClient &message)
{
std::lock_guard<std::mutex> lock(clientMutex);
// Comprobar que existe el client en el pool
int index = clientExists(client);
if (index < 0)
return;
if (players[message.playerState.index] != nullptr)
players[message.playerState.index]->processState(message.playerState);
}
void Server::processLogout(Socket *client, const MessageClient &message)
{
std::lock_guard<std::mutex> lock(clientMutex);
int index = clientExists(client);
// No encontrado en clientes
if (index < 0)
{
delete client;
return;
}
std::cout << "CLIENT LOGGED OUT: " << *clients[index] << "\n";
// Mensaje para que el cliente sepa que se ha podido desconectar
MessageServer messageServer;
messageServer.type = MessageServer::LOGOUT;
socket.send(messageServer, *client);
auto it = std::find(clients.begin(), clients.end(), clients[index]);
delete clients[index];
delete client;
clients.erase(it);
//Remove player
removePlayer(message.playerState.index);
}
int Server::clientExists(Socket *client)
{
int i = 0;
while (i < clients.size())
{
if (*clients[i] == *client)
break;
i++;
}
return i < clients.size() ? i : -1;
}
void Server::addPlayer(int index)
{
std::lock_guard<std::mutex> lock(worldMutex);
Player *player = new Player(index);
world->addGameObject(player);
players[index] = player;
}
void Server::removePlayer(int index)
{
std::lock_guard<std::mutex> lock(worldMutex);
Player *player = players[index];
world->removeGameObject(player);
players[index] = nullptr;
}
void Server::sendWorld()
{
std::lock_guard<std::mutex> lock(clientMutex);
// Estado del mundo
MessageServer messageServer;
messageServer.type = MessageServer::MESSAGE;
messageServer.world.copy(*world);
for (int i = 0; i < clients.size(); i++)
{
messageServer.index = i;
socket.send(messageServer, *clients[i]);
}
}
int Server::getFreeSlot()
{
int i = 0;
while (i < 4)
{
if (players[i] == nullptr)
return i;
i++;
}
return -1;
}
void Server::createNetThread()
{
if (netThreads.size() < clients.size() + 1)
{
netThreads.push_back(std::thread(&Server::manageMessages, std::ref(*this)));
}
}
| true |
df63f89e5dd00b8d1477a19ed2cc8c0359619414
|
C++
|
Jorgitou98/Acepta-el-Reto
|
/Soluciones/AceptaElReto258CogeElSobreYCorre.cpp
|
UTF-8
| 1,600 | 3.015625 | 3 |
[] |
no_license
|
#include <iostream>
#include <deque>
using namespace std;
struct tElem{
int elem, pos;
};
bool resuelveCaso() {
int n, k;
cin >> n >> k;
if (n == 0 && k == 0)
return false;
deque <tElem> colaK, candidatosMax;
tElem max = { 0, -1 };
int valor;
for (int i = 0; i < k; ++i){ //Cojo el maximo
cin >> valor;
if (valor > max.elem){
max = { valor, i };
}
colaK.push_back({ valor, i });
}
deque <tElem> aux = colaK;
int maxCand = 0;
while (!aux.empty()){
if (aux.back().elem > maxCand && aux.back().pos != max.pos){
maxCand = aux.back().elem;
candidatosMax.push_back(aux.back());
}
aux.pop_back();
}
cout << max.elem;
if (k < n) cout << " ";
for (int i = k; i < n; ++i){
cin >> valor;
if (!candidatosMax.empty() && candidatosMax.back().pos == colaK.front().pos) candidatosMax.pop_back();
if (colaK.front().elem == max.elem){
if (!candidatosMax.empty()) {
max = candidatosMax.back();
candidatosMax.pop_back();
}
else {
max = { valor, i };
}
}
colaK.pop_front();
if (valor > max.elem){
max = { valor, i };
if (!candidatosMax.empty()) candidatosMax.clear();
}
else {
if (candidatosMax.empty()) candidatosMax.push_back({ valor, i });
else{
if (valor >= candidatosMax.front().elem){
while (!candidatosMax.empty() && valor >= candidatosMax.front().elem) candidatosMax.pop_front();
}
candidatosMax.push_front({ valor, i });
}
}
colaK.push_back({ valor, i });
cout << max.elem;
if(i < n - 1) cout << " ";
}
cout << '\n';
return true;
}
int main() {
while (resuelveCaso());
return 0;
}
| true |
2881d29e7290e910fd4c08919c71d92c73f6bb89
|
C++
|
bonly/exercise
|
/2010/201005/20100528_io_pool.cpp
|
UTF-8
| 4,038 | 3.03125 | 3 |
[] |
no_license
|
/**
* @file 20100528_io_pool.cpp
* @brief
*
* @author bonly
* @date 2012-7-11 bonly created
*/
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include <iostream>
class thread_pool_checker: private boost::noncopyable
{
public:
thread_pool_checker(boost::asio::io_service& io_service,
boost::thread_group& threads, unsigned int max_threads,
long threshold_seconds, long periodic_seconds) :
io_service_(io_service), timer_(io_service), threads_(
threads), max_threads_(max_threads), threshold_seconds_(
threshold_seconds), periodic_seconds_(
periodic_seconds)
{
schedule_check();
}
private:
void schedule_check();
void on_check(const boost::system::error_code& error);
private:
boost::asio::io_service& io_service_;
boost::asio::deadline_timer timer_;
boost::thread_group& threads_;
unsigned int max_threads_;
long threshold_seconds_;
long periodic_seconds_;
};
void thread_pool_checker::schedule_check()
{
// Thread pool is already at max size.
if (max_threads_ <= threads_.size())
{
std::cout << "Thread pool has reached its max. Example will shutdown."
<< std::endl;
io_service_.stop();
return;
}
// Schedule check to see if pool needs to increase.
std::cout << "Will check if pool needs to increase in " << periodic_seconds_
<< " seconds." << std::endl;
timer_.expires_from_now(boost::posix_time::seconds(periodic_seconds_));
timer_.async_wait(
boost::bind(&thread_pool_checker::on_check, this,
boost::asio::placeholders::error));
}
void thread_pool_checker::on_check(const boost::system::error_code& error)
{
// On error, return early.
if (error)
return;
// Check how long this job was waiting in the service queue. This
// returns the expiration time relative to now. Thus, if it expired
// 7 seconds ago, then the delta time is -7 seconds.
boost::posix_time::time_duration delta = timer_.expires_from_now();
long wait_in_seconds = -delta.seconds();
// If the time delta is greater than the threshold, then the job
// remained in the service queue for too long, so increase the
// thread pool.
std::cout << "Job job sat in queue for " << wait_in_seconds << " seconds."
<< std::endl;
if (threshold_seconds_ < wait_in_seconds)
{
std::cout << "Increasing thread pool." << std::endl;
threads_.create_thread(
boost::bind(&boost::asio::io_service::run, &io_service_));
}
// Otherwise, schedule another pool check.
run();
}
// Busy work functions.
void busy_work(boost::asio::io_service&, unsigned int);
void add_busy_work(boost::asio::io_service& io_service, unsigned int count)
{
io_service.post(boost::bind(busy_work, boost::ref(io_service), count));
}
void busy_work(boost::asio::io_service& io_service, unsigned int count)
{
boost::this_thread::sleep(boost::posix_time::seconds(5));
count += 1;
// When the count is 3, spawn additional busy work.
if (3 == count)
{
add_busy_work(io_service, 0);
}
add_busy_work(io_service, count);
}
int main()
{
using boost::asio::ip::tcp;
// Create io service.
boost::asio::io_service io_service;
// Add some busy work to the service.
add_busy_work(io_service, 0);
// Create thread group and thread_pool_checker.
boost::thread_group threads;
thread_pool_checker checker(io_service, threads, 3, // Max pool size.
2, // Create thread if job waits for 2 sec.
3); // Check if pool needs to grow every 3 sec.
// Start running the io service.
io_service.run();
threads.join_all();
return 0;
}
| true |
6d2e8634fdb2046fa2b5994dba8e57be89747959
|
C++
|
Gabelonio/UD-Computer-Science
|
/8. Double Queue/main.cpp
|
WINDOWS-1250
| 539 | 2.90625 | 3 |
[] |
no_license
|
/*
Proyecto Manejo de colas dobles.
Nombres:
Gabriel Esteban Castillo Ramrez - 20171020021
Esteban Quintero Amaya -20171020022
*/
#include <iostream>
#include "Doblecola.h"
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char** argv) {
ColaDoble<int> lista;
cout << " " << endl;
lista.insertar(3,'I');
lista.insertar(8,'D');
lista.insertar(10,'I');
lista.atender('D');
lista.insertar(12,'D');
lista.atender('I');
lista.imprimir('I');
return 0;
}
| true |
685bcc04c6e4103e1d31c16a7fc85b6ddea4ef71
|
C++
|
hackerlank/renyang-learn
|
/socket/c++/tcp/five/simple_server_main.cpp
|
UTF-8
| 2,319 | 3.0625 | 3 |
[] |
no_license
|
#include "ServerSocket.h"
#include "SocketException.h"
#include <iostream>
#include <string>
#include "imagedata.h"
using namespace std;
void SDFile(ServerSocket *server,char *filename);
void SDStruct(ServerSocket *server,char *pixel);
int main(int argc,char **argv) {
cout << "running...." << endl;
ServerSocket *server;
try
{
server = new ServerSocket(30000);
}
catch ( SocketException& e )
{
cout << "Exception was caught:" << e.description() << "\nExiting.\n";
return -1;
}
while(true)
{
try
{
struct imagedata image;
// 把第一個資料填入
image.pixel[0][0]=77;
char data[MAXRECV];
while(true)
{
memset(data,0,MAXRECV);
*server >> data;
//::SDFile(server,"realalt180.exe");
::SDStruct(server,(char*)&image);
printf("%s\n",data);
}
}
catch (SocketException &)
{
server->close_connfd();
server->accept();
}
}
return 0;
}
//==========================function implement====================
void SDFile(ServerSocket *server,char *filename)
{
char sdbuffer[MAXRECV];
char end[7]="#over#";
int ReadByte=0;
FILE *sdfile = fopen(filename,"rb");
if (sdfile==NULL)
{
printf("open %s file error!!\n",filename);
*server << end;
return ;
}
printf("Client: sending file <%s>",filename);
while((ReadByte=fread(sdbuffer,sizeof(char),MAXRECV,sdfile))>0)
{
printf("fread:%d\n",ReadByte);
//printf(".");
server->Sendbyte(sdbuffer,ReadByte);
memset(sdbuffer,0,MAXRECV);
}
fclose(sdfile);
// 若這邊不sleep一下的話,上面的最後一個片段會與下面的結束片斷一起傳送,就會造成傳送過去的資料判斷錯誤
// 透過non-blocking就可以避免使用sleep啦
// sleep(1);
*server<<end;
printf("\nClient:<%s> Finish!!\n",filename);
}
void SDStruct(ServerSocket *server,char *pixel)
{
char sdbuffer[MAXRECV];
char end[7]="#over#";
int ReadByte=0;
int begin=0;
int structsize=sizeof(struct imagedata);
do
{
if (structsize>=begin+MAXRECV)
{
ReadByte=MAXRECV;
}
else
{
ReadByte=structsize-begin;
}
if (ReadByte>0)
{
memset(sdbuffer,0,MAXRECV);
strncpy(sdbuffer,pixel+begin,ReadByte);
server->Sendbyte(sdbuffer,ReadByte);
begin+=ReadByte;
}
else
{
break;
}
}while(true);
//sleep(1);
*server<<end;
printf("\nClient imagedata Finish!!\n");
}
| true |
db74c5a7c88021f21894ebcd8a48568e343d73ba
|
C++
|
alesandraisla/curso-linguagem-c
|
/tipos_variaveis.cpp
|
ISO-8859-1
| 1,123 | 3.40625 | 3 |
[] |
no_license
|
#include <stdio.h>
int main (){
//Armazena caracterer
/*
char variavelChar = 'a';
printf("%c\n", variavelChar);
scanf("%c", &variavelChar);
printf("%c\n", variavelChar);
*/
/*
bool variavelBool = true; // pode ser true 1 ou false que 0 usado em programa de sim ou nao
printf("%i\n", variavelBool);
*/
/*
int variavelInt = 10; // long int (variavel inteira longa espao dobrado em memria) // const int (fixando o valor da variavel) // pode aplicar unsigned int
printf("%i\n", variavelInt);
scanf("%i", &variavelInt);
printf("%i\n", variavelInt);
*/
/*
float variavelFloat = 10.10; // pode aplicar o unsigned float
printf("%0.2f\n", variavelFloat); //0.2 exibiara a quantidade de casas decimais aps a virgula
scanf("%0.2f", &variavelFloat);
printf("%0.2f\n", variavelFloat);
*/
double variavelDouble = 10.10; // preciso maior que a float // unsigned double (limita a variavel a assumir apenas valores positivos)
printf("%f\n", variavelDouble);
scanf("%lf\n", &variavelDouble); // scanf usa o %lf
printf("%f\n", variavelDouble);
return 0;
}
| true |
857bcd1cde08f3d2751db018d3181bcc44130c87
|
C++
|
lastvirgo266/AlgorithmProblem
|
/Baekjoon/14502_write.cpp
|
UTF-8
| 2,471 | 2.8125 | 3 |
[] |
no_license
|
#include<stdio.h>
#include<queue>
using namespace std;
int decayed[8][8] = {0,};
int board[8][8] = {0,};
int weight[4][2] = { {0,1}, {0,-1}, {1,0}, {-1,0}};
int N,M;
typedef struct _point{
int y, x;
}Point;
int BFS(){
queue<Point> que;
for(int i=0; i<N; i++)
for(int j=0; j<M; j++){
if(decayed[i][j] == 2){
Point point;
point.y = i;
point.x = j;
que.push(point);
}
}
while(!que.empty()){
Point temp = que.front();
que.pop();
for(int i=0; i<4; i++){
int nextY = temp.y + weight[i][0];
int nextX = temp.x + weight[i][1];
if(nextY < N &&
nextX < M &&
nextX >= 0 &&
nextY >= 0 &&
decayed[nextY][nextX] == 0){
decayed[nextY][nextX] = 2;
Point point;
point.x = nextX;
point.y = nextY;
que.push(point);
}
}
}
int count =0;
for(int i=0; i<N; i++)
for(int j=0; j<M; j++){
if(decayed[i][j] == 0){
count++;
}
}
return count;
}
void Experiment(){
for(int i=0; i<N; i++)
for(int j=0; j<M; j++)
decayed[i][j] = board[i][j];
}
int MakeWall(int current){
if(current == 3){
Experiment();
return BFS();
}
int result = 0;
int max = -99;
for(int i=0; i<N; i++)
for(int j=0; j<M; j++){
if(board[i][j] == 0){
board[i][j] = 1;
result = MakeWall(current + 1);
board[i][j] = 0;
max = max > result ? max : result;
}
}
return max;
}
int main(){
queue<Point> que;
scanf("%d %d",&N, &M);
for(int i = 0; i<N; i++)
for(int j =0; j<M; j++){
int temp = 0;
scanf("%d",&temp);
board[i][j] = temp;
}
//초기화 완료
int max = -99;
for(int i=0; i<N; i++)
for(int j=0; j<M; j++){
int result = 0;
if(board[i][j] == 0){
board[i][j] =1;
result = MakeWall(1);
board[i][j] = 0;
max = max > result ? max : result;
}
}
printf("%d",max);
return 0;
}
| true |
4ded4bab26057d33113bc2fa34ec0cead699c4b1
|
C++
|
tziccardi/pHController
|
/main.cpp
|
UTF-8
| 3,268 | 2.921875 | 3 |
[] |
no_license
|
//
// main.cpp
// phController
//
// Created by Thomas Ziccardi on 5/3/14.
// Copyright (c) 2014 Thomas Ziccardi. All rights reserved.
//
#include <iostream>
#include <fstream>
#include <string>
#include <ctime>
#include <stdlib.h>
#include <unistd.h>
#include <wiringPi.h>
using namespace std;
const char wday_name[] [4]= {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
const int pin = 0;
//struct setup
struct databaseInfo {
string dayOfWeek;
double amount;
int status;
};
void resetCursor(fstream &file);
void acidPump(double amount, int pin);
int main(int argc, const char * argv[])
{
fstream dbFile;
fstream logFile("pHCtr.log", ios::out | ios::app);
databaseInfo acidCtr;
string day, col1, col2;
int wP = 0;
// wiringPi setup
wiringPiSetup();
pinMode(pin, OUTPUT);
// for time
time_t rawtime;
struct tm * timeinfo;
if( dbFile.fail()) {
// the file doesnt exist -> create it and populate the database
dbFile.open("pHCtr.db", ios::out);
// table heading: DAY | TIME | ON/OFF
for (int i = 0; i < 7; i++) {
dbFile << wday_name[i] <<"$" << "0.0" << "$" << "0" << "$\n";
}
cout << "The initial values are stored\n";
dbFile.close();
}
else {
dbFile.close() ;
cout << "The Database Exists\n";
}
// get current day
time ( &rawtime );
timeinfo = localtime ( &rawtime );
//printf ( "The current date/time is: %s", asctime (timeinfo) );
// store the day to struct
acidCtr.dayOfWeek = wday_name[timeinfo->tm_wday];
cout << "The Current Day is: " << acidCtr.dayOfWeek << endl;
// open database and populate struct with data based on current day
dbFile.open("pHCtr.db", ios::in);
resetCursor(dbFile);
// load values into struct
while(!dbFile.eof()) {
getline(dbFile, day, '$');
if (day == acidCtr.dayOfWeek) {
getline(dbFile, col1, '$');
getline(dbFile, col2, '$');
break;
}
dbFile.ignore(256, '\n');
}
dbFile.close();
// convert strings to double and int
acidCtr.amount = atof(col1.c_str());
acidCtr.status = atof(col2.c_str());
cout << "The Values for today are: Amount: " << acidCtr.amount <<" Status: " << acidCtr.status << endl;
// write log file
//open log
logFile << asctime (timeinfo);
logFile << "amount:" << acidCtr.amount << " Status:" << acidCtr.status << endl;
logFile.close();
cout << "Log Written\n";
if (acidCtr.status == 0) {
cout << "Pump off for Today, exiting.....\n";
return 1;
}
acidPump(acidCtr.amount, pin);
cout << "Acid Pumped\n";
return 0;
}
void resetCursor(fstream &dataFile) {
dataFile.clear();
dataFile.seekg(0, ios::beg);
}
void acidPump(double amount, int pin) {
digitalWrite(pin, 0);
sleep(amount);
digitalWrite(pin, 1);
}
| true |
2b9a9a69eebdd7d2767df77f5808c88d5fb6268c
|
C++
|
seohojinn/algorithm
|
/소수2/소수2/main.cpp
|
UTF-8
| 981 | 2.96875 | 3 |
[] |
no_license
|
#include <iostream>
#include <deque>
using namespace std;
int arr[10001];
int solve(int data){
deque<int> value;
int size = 0;
while(data != 0){
value.push_front(data % 10);
data /= 10;
}
size = int(value.size());
for(int i=0;i<size;i++){
data = 0;
for(int j=i;j<size;j++){
data += value[j];
data *= 10;
}
data /= 10;
if(arr[data] == 0){
return 0;
}
}
return 1;
}
int main() {
int idx = 0;
for(int i=2;i<=10000;i++){
arr[i] = i;
}
for(int i=2;i<=10000;i++){
idx = i * 2;
if(arr[i] != 0){
while(idx <= 10000){
arr[idx] = 0;
idx += i;
}
}
}
for(int i=1;i<=10000;i++){
if(solve(i) == 1){
cout << i << "\n";
}
}
return 0;
}
| true |
f775bf9a9c937e7efc4a7471a5d2da2da7184907
|
C++
|
nawaf331/fractal
|
/fractal.cpp
|
UTF-8
| 19,949 | 2.671875 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <GL/glut.h>
//#if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
//#define OS_WIN
//#endif
int width=600, height=600; // window size
int windowID;
int color=0,flag=0;
GLfloat minX = -2.2f, maxX = 0.8f, minY = -1.5f, maxY = 1.5; // complex plane boundaries
GLfloat stepX = (maxX - minX)/(GLfloat)width;
GLfloat stepY = (maxY - minY)/(GLfloat)height;
char titleSet[10][25]={"Mandelbrot fractal","Mandelbrot^3 fractal","Flower fractal","Star fractal","Julia Fractal","Sierpanski Gasket"};
GLfloat black[] = {0.0f, 0.0f, 0.0f}; // black color
const int paletteSize = 128;
GLfloat palette[paletteSize][3];
const GLfloat radius = 5.0f;
bool fullScreen=false;
int fracCount=0;
GLfloat juliaFactor=0.0;
GLfloat juliaSpecial=0.5;
GLfloat zoomFactor=0.1;
GLfloat theta=0.0;
int randm=0;
typedef float point[3];
point v[]={{-0.5,0.0,1.0},{-0.5,1.0,0.0},
{-1.5,-0.5,0.0}, {0.5,-0.5,0.0}};
//#ifdef OS_WIN
//flag=0;
//#else
//#endif
//****************************************
void output(float x,float y,float z,void *font,char *string)
{
char *c;
glRasterPos3f(x,y,z);
for (c=string; *c != '\0'; c++)
{
glutBitmapCharacter(font, *c);
}
}
//***************************************
GLfloat* greenJulia(GLfloat u, GLfloat v){ //front page. though it is not green :P
GLfloat re = u;
GLfloat im = v;
GLfloat frontFrac1=-0.1;
GLfloat frontFrac2=0.651;
GLfloat tempRe=0.0;
for(int i=0; i < paletteSize; i++){
tempRe = re*re - im*im + frontFrac1+juliaFactor; //z=z^2+(-0.1+0.651i)
im = re * im * 2 + frontFrac2+juliaFactor;
re = tempRe;
if( (re*re + im*im) > radius ){
return palette[i+35];
}
}
return black;
}
//****************************************
GLfloat *mandelbrot(GLdouble u, GLdouble v) //z=z^2+c
{
GLdouble re = u;
GLdouble im = v;
GLdouble tempRe=0.0;
for(int i=0; i < paletteSize; i++)
{
tempRe = re*re - im*im + u;
im = re * im * 2 + v;
re = tempRe;
if( (re*re + im*im) > radius )
{
return palette[i];
}
}
return black;
}
//*****************************************
GLfloat *mandelbrot3(GLdouble u, GLdouble v) //z=z^3+c
{
GLdouble re = u;
GLdouble im = v;
GLdouble tempRe=0.0;
for(int i=0; i < paletteSize; i++)
{
tempRe = re*re*re - re*im*im - 2*re*im*im + u;
im = re*re*im -im*im*im+ 2*re*re*im+ v;
re = tempRe;
if( (re*re + im*im) > radius )
{
return palette[i];
}
}
return black;
}
//******************************************
GLfloat *starFractal(GLdouble u, GLdouble v) //shape resembles to be that of a star
{
GLdouble re = u;
GLdouble im = v;
GLdouble tempRe=0.0;
GLfloat starFrac1=-0.1;
GLfloat starFrac2=0.651;
for(int i=0; i < paletteSize; i++) //z=z^3+(-0.1+0.651i)
{
tempRe = re*re*re - re*im*im - 2*re*im*im -( re*re - im*im)+starFrac1+ juliaFactor*10;
im = re*re*im -im*im*im+ 2*re*re*im -(re * im * 2) +starFrac2+juliaFactor*10;
re = tempRe;
if( (re*re + im*im) > radius )
{
return palette[(i+100)]; ///for color variation add 100 to color index
}
}
return black;
}
//***********************************
GLfloat *julia(GLdouble u, GLdouble v) //julia set z=z^2+k where k is 0.36
{
GLdouble re = u;
GLdouble im = v;
GLdouble tempRe=0.0;
GLdouble juliaFrac=0.36;
for(int i=0; i < paletteSize; i++)
{
tempRe = re*re - im*im + juliaFrac+juliaFactor;
im = re * im * 2 + juliaFrac+juliaFactor;
re = tempRe;
if( (re*re + im*im) > radius )
{
return palette[i];
}
}
return black;
}
//*************************************
GLfloat *flower(GLdouble u, GLdouble v) //z=z^2+C where C varies for each iteration of each point
{
GLdouble re = u;
GLdouble im = v;
GLdouble tempRe=0.0;
for(int i=0; i < paletteSize; i++)
{
tempRe = re*re - im*im + re;
im = re * im * 2 + im;
re = tempRe;
if( (re*re + im*im) > radius )
{
return palette[i+31];
}
}
return black;
}
//***********************************
void drawFrontPage(){
glPushMatrix();
char name[10]="About Us";
char desc[20]="Description";
char help[10]="Help";
char title[25]="Fractals are awesome!!";
char isntit[25]="isn't it? :D";
glColor3f(0.0,0.0,0.0);
glTranslatef(-1.8,-0.5,0.0);
glBegin(GL_POLYGON);
glVertex3f(0.02,0.08,0.0);
glVertex3f(0.02,-0.11,0.0);
glVertex3f(0.65,-0.11,0.0);
glVertex3f(0.65,0.08,0.0);
glEnd();
glColor3f(1.0,1.0,1.0);
output(0.05,-0.05,0,GLUT_BITMAP_TIMES_ROMAN_24,desc);
//help
glTranslatef(0.0,-0.3,0.0);
glColor3f(0.0,0.0,0.0);
glBegin(GL_POLYGON);
glVertex3f(0.0,0.08,0.0);
glVertex3f(0.0,-0.11,0.0);
glVertex3f(0.65,-0.11,0.0);
glVertex3f(0.65,0.08,0.0);
glEnd();
glColor3f(1.0,1.0,1.0);
output(0.20,-0.05,0,GLUT_BITMAP_TIMES_ROMAN_24,help);
//printf("about us\n");
glColor3f(0.0,0.0,0.0);
glTranslatef(0.0,-0.3,0.0);
glBegin(GL_POLYGON);
glVertex3f(0.02,0.08,0.0);
glVertex3f(0.02,-0.11,0.0);
glVertex3f(0.65,-0.11,0.0);
glVertex3f(0.65,0.08,0.0);
glEnd();
glColor3f(1.0,1.0,1.0);
output(0.10,-0.05,0,GLUT_BITMAP_TIMES_ROMAN_24,name);
glTranslatef(1.8,1.2,0.0);
glColor3f(0.0,0.0,0.0);
output(-1.2,1.2,0,GLUT_BITMAP_TIMES_ROMAN_24,title);
output(-0.95,1.05,0,GLUT_BITMAP_TIMES_ROMAN_24,isntit);
glPopMatrix();
}
void mymenu(int value) {
if(value == 1)
switch(fracCount)
{
case 0:
printf("============= front page ================ \n");
printf("A fractal is a mathematical set that has a fractal dimension that usually exceeds its topological dimension and may fall between the integers. Fractals are typically self-similar patterns, where self-similar means they are \"the same from near as from far\". Fractals may be exactly the same at every scale, or, they may be nearly the same at different scales. The definition of fractal goes beyond self-similarity per se to exclude trivial self-similarity and include the idea of a detailed pattern repeating itself.\n\n");
break;
case 1:
printf("====== Mandelbrot fractal ======\n");
printf("The equation for this fractal is z=z^2+c\n\n");
break;
case 2:
printf("====== Mandelbrot^3 ====== \n");
printf("The equation for this fractal is z=z^3+c\n");
break;
case 3:
printf("====== flower fractal ====== \n");
printf("The equation for this fractal is z=z^3+c\n");
break;
case 4:
printf("star fractal\n");
break;
case 5:
printf("Julia factor\n");
break;
}
else if(value == 2 )
{
fracCount=1;
glutPostRedisplay();
}
else if(value == 3)
{
fracCount=2;
glutPostRedisplay();
}
else if(value == 4)
{
fracCount=5;
glutPostRedisplay();
}
else if(value == 10 )
{
system("gedit help");
}
else if(value==99)
{
system("gedit about");
}
}
GLfloat* calculateColor(GLfloat u, GLfloat v){
switch(fracCount)
{
case 0:
juliaSpecial=0.5;
return greenJulia(u,v);
break;
case 1:
juliaSpecial=0.0;
return mandelbrot(u,v);
break;
case 2:
//color=0;
juliaSpecial=0.5;
return mandelbrot3(u,v);
break;
case 3:
// printf("Flower\n");
juliaSpecial=0.0;
//color=0.0;
return flower(u,v);
break;
case 4:
//printf("Star\n");
juliaSpecial=0.9;
//color=45;
return starFractal(u,v);
break;
case 5:
//printf("Julia\n");
//color=0;
juliaSpecial=0.5;
return julia(u,v);
break;
default:
//printf("default\n");
//juliaSpecial=0.0;
fracCount=0;
glutPostRedisplay();
//return mandelbrot(u,v);
break;
}
}
//****************************************
void triangle(point a,point b,point c)
{
glBegin(GL_POLYGON);
glVertex3fv(a);
glVertex3fv(b);
glVertex3fv(c);
glEnd();
}
void divide_triangle(point a,point b,point c,int m)
{
point v1,v2,v3;
int j;
if(m>0)
{
for(j=0;j<3;j++)
v1[j]=(a[j]+b[j])/2;
for(j=0;j<3;j++)
v2[j]=(a[j]+c[j])/2;
for(j=0;j<3;j++)
v3[j]=(c[j]+b[j])/2;
divide_triangle(a,v1,v2,m-1);
divide_triangle(c,v2,v3,m-1);
divide_triangle(b,v3,v1,m-1);
}
else(triangle(a,b,c));
}
void tetrahedron(int m)
{
glColor3fv(palette[color]);
divide_triangle(v[0],v[1],v[2],m);
glColor3fv(palette[color+6]);
divide_triangle(v[3],v[2],v[1],m);
glColor3fv(palette[color+12]);
divide_triangle(v[0],v[3],v[1],m);
glColor3fv(palette[color+18]);
divide_triangle(v[0],v[2],v[3],m);
}
//****************************************
void repaint() {// function called to repaint the window
GLfloat* pixelColor;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // clear the screen buffer
if(fracCount<6){
glBegin(GL_POINTS); // start drawing in single pixel mode
for(GLfloat y = maxY; y >= minY; y -= stepY){
for(GLfloat x = minX+juliaSpecial; x <= maxX+juliaSpecial; x += stepX){
pixelColor=calculateColor(x,y);
glColor3fv(pixelColor+color); // set color
glVertex3f(x-juliaSpecial, y, 0.0f); // put pixel on screen (buffer) - [ 1 ]
//printf("%d\t%d\n",stepX,stepY);
}
}
glEnd(); // end drawing
}
else {
switch(fracCount)
{
case 6:
//glPushMatrix();
tetrahedron(5);
//glPopMatrix();
break;
}
}
if(fracCount==0){
drawFrontPage();
}
else
{
glPushMatrix();
char title[25]="";
strcpy(title,titleSet[fracCount-1]);
glColor3f(0.2,0.2,0.2);
output(-1.1,1.2,0,GLUT_BITMAP_TIMES_ROMAN_24,title);
printf("%s\n",title);
glPopMatrix();
}
glutSwapBuffers(); // swap the buffers - [ 2 ]
}
//****************************************
void reshape (int w, int h){ // function called when window size is changed
width=w;
height=h;
stepX = (maxX-minX)/(GLfloat)width; // calculate new value of step along X axis
stepY = (maxY-minY)/(GLfloat)height; // calculate new value of step along Y axis
glViewport (0, 0, (GLsizei)w, (GLsizei)h); // set new dimension of viewable screen
glutPostRedisplay(); // repaint the window
}
//****************************************
void keyFunction(unsigned char key, int x, int y){ // function to handle key pressing
switch(key){
case 'F': // pressing F is turning on/off fullscreen mode
case 'f':
if(fullScreen){
glutReshapeWindow(width,height); // sets default window size
GLsizei windowX = (glutGet(GLUT_SCREEN_WIDTH)-width)/2;
GLsizei windowY = (glutGet(GLUT_SCREEN_HEIGHT)-height)/2;
glutPositionWindow(windowX, windowY); // centers window on the screen
fullScreen = false;
}
else{
fullScreen = true;
glutFullScreen(); // go to fullscreen mode
}
glutPostRedisplay();
break;
case 'k':
juliaFactor+=0.0001;
//juliaFactor+=0.01;
glLoadIdentity();
glOrtho(minX, maxX, minY, maxY, ((GLdouble)-1), (GLdouble)1);
glutPostRedisplay();
break;
case 'l': juliaFactor-=0.0001;
glutPostRedisplay();
break;
case 'c': color++;
glutPostRedisplay();
break;
case 'C':color--;
glutPostRedisplay();
break;
case 'm':
minX = -2.2f, maxX = 0.8f, minY = -1.5f, maxY = 1.5;
stepX = (maxX - minX)/(GLfloat)width;
stepY = (maxY - minY)/(GLfloat)height;
glLoadIdentity();
glOrtho(minX, maxX, minY, maxY, ((GLdouble)-1), (GLdouble)1);
fracCount++;
glutPostRedisplay();
break;
case 'n':
minX = -2.2f, maxX = 0.8f, minY = -1.5f, maxY = 1.5; // complex plane boundaries
stepX = (maxX - minX)/(GLfloat)width;
stepY = (maxY - minY)/(GLfloat)height;
fracCount--;
glLoadIdentity();
glOrtho(minX, maxX, minY, maxY, ((GLdouble)-1), (GLdouble)1);
glutPostRedisplay();
break;
case 'z':
case '+':
printf("Zooming in\n");
minX+=zoomFactor;
maxX-=zoomFactor;
minY+=zoomFactor;
maxY-=zoomFactor;
stepX = (maxX-minX)/(GLfloat)width; // calculate new value of step along X axis
stepY = (maxY-minY)/(GLfloat)height; // calculate new value of step along Y axis
//glViewport (0, 0, (GLsizei)width, (GLsizei)height); // set new dimension of viewable screen
glLoadIdentity();
glOrtho(minX, maxX, minY, maxY, ((GLfloat)-1), (GLfloat)1);
glutPostRedisplay(); // repaint the window
break;
case 'Z':
case '-':
printf("Zooming out\n");
minX-=zoomFactor;
maxX+=zoomFactor;
minY-=zoomFactor;
maxY+=zoomFactor;
stepX = (maxX-minX)/(GLfloat)width; // calculate new value of step along X axis
stepY = (maxY-minY)/(GLfloat)height; // calculate new value of step along Y axis
//glViewport (0, 0, (GLsizei)width, (GLsizei)height); // set new dimension of viewable screen
glLoadIdentity();
glOrtho(minX, maxX, minY, maxY, ((GLfloat)-1), (GLfloat)1);
glutPostRedisplay(); // repaint the window
break;
case '<' :
theta+=0.2;
srand(time(NULL));
randm=rand()%3;
glClearColor(1.0,1.0,1.0,1.0);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
if(randm==0)
glRotatef(theta,1.0,0.0,0.0);
else if(randm==1)
glRotatef(theta,0.0,1.0,0.0);
else
glRotatef(theta,0.0,0.0,1.0);
glutPostRedisplay();
break;
case 27 : // escape key - close the program
glutDestroyWindow(windowID);
exit(0);
break;
}
}
//***************************************************
void mouseFunction(int button,int state,int x, int y)
{
if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
{
if(fracCount==0 && flag==0)
{
printf("x = %d,y = %d\n",x,y);
//**************** check if the user clicks on any button
if((x>85 && x<210) && y>385 && y<420)
{
system("gedit description");
}
else if((x>85 && x<210) && y>445 && y<480)
{
system("gedit help");
}
else if((x>85 && x<210) && y>500 && y<555)
{
system("gedit about");
}
}
else { //if(fracCount%100!=99){
printf("Zooooooooming area \n");
GLdouble centreX=minX+stepX*x;
GLdouble centreY=minY+stepY*y;
minX=centreX - (maxX-minX)/2.0f;
maxX=centreX + (maxX-minX)/2.0f;
minY=centreY - (maxY-minY)/2.0f;
maxY=centreY + (maxY-minY)/2.0f;
stepX = (maxX-minX)/(GLfloat)width; // calculate new value of step along X axis
stepY = (maxY-minY)/(GLfloat)height; // calculate new value of step along Y axis
glLoadIdentity();
glOrtho(minX, maxX, minY, maxY, ((GLdouble)-1), (GLdouble)1);
glutPostRedisplay();
}
}
else
if (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN)
{
glutCreateMenu(mymenu); // single menu, no need for id
glutAddMenuEntry("What is this", 1);
glutAddMenuEntry("Mandelbrot Fractal",2);
glutAddMenuEntry("Mandelbrot^3 fractal",3);
glutAddMenuEntry("Julia Fractal",4);
glutAddMenuEntry("How do i use this",10);
glutAddMenuEntry("About Us", 99);
glutAttachMenu(GLUT_RIGHT_BUTTON);
}
else
if(button == GLUT_MIDDLE_BUTTON && state==GLUT_DOWN)
{
printf("\nPan");
GLdouble centreX=minX+stepX*x;
GLdouble centreY=minY+stepY*y;
minX=centreX - (maxX-minX)/2.0f;
maxX=centreX + (maxX-minX)/2.0f;
minY=centreY - (maxY-minY)/2.0f;
maxY=centreY + (maxY-minY)/2.0f;
stepX = (maxX-minX)/(GLfloat)width; // calculate new value of step along X axis
stepY = (maxY-minY)/(GLfloat)height; // calculate new value of step along Y axis
glLoadIdentity();
glOrtho(minX, maxX, minY, maxY, ((GLdouble)-1), (GLdouble)1);
glutPostRedisplay();
}
}
//****************************************
void specialKeyFunction(int key, int x, int y){ // function to handle key pressing
switch(key)
{
case GLUT_KEY_RIGHT:
color=0;
minX = -2.2f, maxX = 0.8f, minY = -1.5f, maxY = 1.5;
stepX = (maxX - minX)/(GLfloat)width;
stepY = (maxY - minY)/(GLfloat)height;
glLoadIdentity();
glOrtho(minX, maxX, minY, maxY, ((GLdouble)-1), (GLdouble)1);
fracCount++;
glutPostRedisplay();
break;
case GLUT_KEY_LEFT:
color=0;
minX = -2.2f, maxX = 0.8f, minY = -1.5f, maxY = 1.5;
stepX = (maxX - minX)/(GLfloat)width;
stepY = (maxY - minY)/(GLfloat)height;
glLoadIdentity();
glOrtho(minX, maxX, minY, maxY, ((GLdouble)-1), (GLdouble)1);
fracCount--;
glutPostRedisplay();
break;
case GLUT_KEY_UP:
if(fracCount<6) {
printf("Zooming in\n");
minX+=zoomFactor;
maxX-=zoomFactor;
minY+=zoomFactor;
maxY-=zoomFactor;
stepX = (maxX-minX)/(GLfloat)width; // calculate new value of step along X axis
stepY = (maxY-minY)/(GLfloat)height; // calculate new value of step along Y axis
//glViewport (0, 0, (GLsizei)width, (GLsizei)height); // set new dimension of viewable screen
glLoadIdentity();
glOrtho(minX, maxX, minY, maxY, ((GLfloat)-1), (GLfloat)1);
glutPostRedisplay(); // repaint the window
}
else {
theta+=0.2;
glutPostRedisplay();
}
break;
case GLUT_KEY_DOWN:
printf("Zooming out\n");
minX-=zoomFactor;
maxX+=zoomFactor;
minY-=zoomFactor;
maxY+=zoomFactor;
stepX = (maxX-minX)/(GLfloat)width; // calculate new value of step along X axis
stepY = (maxY-minY)/(GLfloat)height; // calculate new value of step along Y axis
//glViewport (0, 0, (GLsizei)width, (GLsizei)height); // set new dimension of viewable screen
glLoadIdentity();
glOrtho(minX, maxX, minY, maxY, ((GLfloat)-1), (GLfloat)1);
glutPostRedisplay(); // repaint the window
break;
case GLUT_KEY_HOME:
minX = -2.2f, maxX = 0.8f, minY = -1.5f, maxY = 1.5;
stepX = (maxX - minX)/(GLfloat)width;
stepY = (maxY - minY)/(GLfloat)height;
glLoadIdentity();
glOrtho(minX, maxX, minY, maxY, ((GLdouble)-1), (GLdouble)1);
fracCount=0;
color=0;
glutPostRedisplay();
break;
case GLUT_KEY_F1:
system("gedit help");
break;
case GLUT_KEY_F10:
if(fullScreen){
glutReshapeWindow(width,height); // sets default window size
GLsizei windowX = (glutGet(GLUT_SCREEN_WIDTH)-width)/2;
GLsizei windowY = (glutGet(GLUT_SCREEN_HEIGHT)-height)/2;
glutPositionWindow(windowX, windowY); // centers window on the screen
fullScreen = false;
}
else{
fullScreen = true;
glutFullScreen(); // go to fullscreen mode
}
glutPostRedisplay();
break;
}
}
//****************************************
void createPalette(){
for(int i=0; i < 32; i++){
palette[i][0] = (8*i)/(GLfloat)255;
palette[i][1] = (128-4*i)/(GLfloat)255;
palette[i][2] = (255-8*i)/(GLfloat)255;
}
for(int i=0; i < 32; i++){
palette[32+i][0] = (GLfloat)1;
palette[32+i][1] = (8*i)/(GLfloat)255;
palette[32+i][2] = (GLfloat)0;
}
for(int i=0; i < 32; i++){
palette[64+i][0] = (128-4*i)/(GLfloat)255;
palette[64+i][1] = (GLfloat)1;
palette[64+i][2] = (8*i)/(GLfloat)255;
}
for(int i=0; i < 32; i++){
palette[96+i][0] = (GLfloat)0;
palette[96+i][1] = (255-8*i)/(GLfloat)255;
palette[96+i][2] = (8*i)/(GLfloat)255;
}
}
//****************************************
int main(int argc, char** argv){
glutInit(&argc, argv);
createPalette();
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
GLsizei windowX = (glutGet(GLUT_SCREEN_WIDTH)-width)/2;
GLsizei windowY = (glutGet(GLUT_SCREEN_HEIGHT)-height)/2;
glutInitWindowPosition(windowX, windowY);
glutInitWindowSize(width, height);
windowID = glutCreateWindow("Matrix Fractal Zoomer");
glViewport (0, 0, (GLsizei) width, (GLsizei) height);
glMatrixMode (GL_PROJECTION);
glLoadIdentity();
glOrtho(minX, maxX, minY, maxY, ((GLfloat)-1), (GLfloat)1);
// set the event handling methods
glutDisplayFunc(repaint);
glutReshapeFunc(reshape);
glutKeyboardFunc(keyFunction);
glutSpecialFunc(specialKeyFunction);
glutMouseFunc(mouseFunction);
glutMainLoop();
return 0;
}
//#endif
| true |
593bcf79fd1b156ef73f4e8318661e20da551b77
|
C++
|
albertomila/continous-formation
|
/MoreIdioms/MoreIdioms/samples/MI05_AttorneyClient.h
|
UTF-8
| 1,255 | 3.265625 | 3 |
[] |
no_license
|
#pragma once
#include "stdafx.h"
#include <cstdio>
class CClient
{
private:
void A(int data) {}
void B(float data) {}
void C(double data) {}
friend class Attorney;
};
class Attorney
{
private:
static void CallA(CClient& client, int data)
{
client.A(data);
}
static void CallB(CClient& client, float data)
{
client.B(data);
}
friend class CCaller;
};
class CCaller
{
public:
void DoProcess(CClient& c)
{
// Bar now has access to only Client::A and Client::B through the Attorney.
Attorney::CallA(c, 99);
Attorney::CallB(c, 99.9f);
}
};
////////////////////////////////////////////////////////////////////////
class Base
{
private:
virtual void Func(int x) = 0;
friend class Attorney2;
public:
virtual ~Base() {}
};
class Derived : public Base
{
private:
virtual void Func(int x)
{
printf("Derived::Func\n"); // This is called even though main is not a friend of Derived.
}
public:
~Derived() {}
};
class Attorney2
{
public:
static void callFunc(Base & b, int x)
{
return b.Func(x);
}
};
BEGIN_TEST(AttorneyClient)
CClient client;
CCaller caller;
caller.DoProcess(client);
Derived d;
Attorney2::callFunc(d, 10);
END_TEST()
| true |
40182dc99cb2bf35bb013396b8a66013c76c90cc
|
C++
|
Takiwa-i/Atcoder
|
/ABC/118/B.cpp
|
UTF-8
| 420 | 2.796875 | 3 |
[] |
no_license
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
int main(void)
{
int n, m;
std::cin >> n >> m;
std::vector<int> M(m, 0);
for (int i = 0; i < n; i++)
{
int k;
std::cin >> k;
for (int i = 0; i < k; i++)
{
int a;
std::cin >> a;
--a;
M[a]++;
}
}
int ans = 0;
for (int i = 0; i < m; i++)
{
if (M[i] == n)
++ans;
}
std::cout << ans << std::endl;
return (0);
}
| true |
697ed0c6ab814dfd5d7d53c057f6037cfe5aa958
|
C++
|
mz299/HuffmanCoding
|
/henc3608.cpp
|
UTF-8
| 4,612 | 2.6875 | 3 |
[] |
no_license
|
// Min Zeng cs610 3608 prp
#include <iostream>
#include <fstream>
#include <vector>
#include "Huffman3608.h"
#include "MinHeap3608.h"
using namespace std;
bool readOriginFile3608(const char* filePath, vector<unsigned char> &filedata) {
ifstream fin(filePath, ios::binary);
if (fin.fail()) {
return false;
}
streampos fsize = fin.tellg();
fin.seekg(0, ios::end);
fsize = fin.tellg() - fsize;
fin.clear();
fin.seekg(0, ios::beg);
filedata.resize(fsize);
fin.read(reinterpret_cast<char*>(&filedata[0]), fsize);
fin.close();
return true;
}
void writeEncodedFile3608(const char* filePath, vector<Node3608*> minHeap, vector<unsigned char> encodedData, char lastByteBitCount, size_t originFileSize) {
string encodedFilePath = string(filePath);
encodedFilePath += ".huf";
size_t size = minHeap.size();
ofstream fout(encodedFilePath.c_str(), ios::out | ios::binary);
fout.write(reinterpret_cast<char*>(&size), sizeof(size));
unsigned char bytes[256];
int counts[256];
for (int i = 0; i < size; i++) {
bytes[i] = minHeap[i]->byte;
counts[i] = minHeap[i]->count;
}
fout.write(reinterpret_cast<char*>(&bytes[0]), size * sizeof(unsigned char));
fout.write(reinterpret_cast<char*>(&counts[0]), size * sizeof(int));
fout.write(reinterpret_cast<char*>(&originFileSize), sizeof(originFileSize));
fout.write(reinterpret_cast<char*>(&lastByteBitCount), sizeof(lastByteBitCount));
fout.write(reinterpret_cast<char*>(&encodedData[0]), encodedData.size() * sizeof(unsigned char));
fout.close();
printf("Output file: %s\n", encodedFilePath.c_str());
}
vector<Node3608*> filedataToNodes3608(vector<unsigned char> filedata) {
vector<Node3608*> nodes = vector<Node3608*>();
int table[256] = {0};
for (int i = 0; i < filedata.size(); i++) {
table[filedata[i]]++;
}
for (int i = 0; i < 256; i++) {
if (table[i] == 0)
continue;
Node3608* node = new Node3608(i, table[i]);
nodes.push_back(node);
}
return nodes;
}
vector<unsigned char> encode3608(vector<unsigned char> filedata, const string codebook[], char &lastByteBitCount) {
vector<unsigned char> encodedData = vector<unsigned char>();
encodedData.resize(filedata.size());
unsigned char nextByte = 0;
char bitCounter = 0;
size_t size = 0;
for (int i = 0; i < filedata.size(); i++) {
unsigned char nextChar = filedata[i];
for (int i = 0; i < codebook[nextChar].size(); i++, bitCounter++) {
if (bitCounter == 8) {
if (encodedData.size() > size) {
encodedData[size] = nextByte;
} else {
encodedData.push_back(nextByte);
}
size++;
nextByte = 0;
bitCounter = 0;
}
if (codebook[nextChar][i] == '1') {
nextByte = nextByte | (0x01 << bitCounter);
}
}
}
if (bitCounter) {
if (encodedData.size() > size) {
encodedData[size] = nextByte;
}
else {
encodedData.push_back(nextByte);
}
size++;
}
encodedData.resize(size);
lastByteBitCount = bitCounter;
return encodedData;
}
void encode3608(const char* filePath) {
vector<unsigned char> filedata = vector<unsigned char>();
printf("Loading file.\n");
if (!readOriginFile3608(filePath, filedata)) {
printf("Read file error.\n");
return;
}
printf("Genarating Huffman code.\n");
vector<Node3608*> nodes = filedataToNodes3608(filedata);
MinHeap3608 minHeap = MinHeap3608();
minHeap.buildMinHeap3608(nodes);
Huffman3608 huffman = Huffman3608();
huffman.genarateHuffman3608(minHeap);
huffman.genarateCodebook3608();
printf("Encoding.\n");
char lastByteBitCount;
vector<unsigned char> encodedData = encode3608(filedata, huffman.codebook, lastByteBitCount);
printf("Original size: %ld\nEncoded size: %ld\nWriting file.\n", filedata.size(), encodedData.size());
writeEncodedFile3608(filePath, minHeap.minHeap, encodedData, lastByteBitCount, filedata.size());
}
int main(int argc, const char *argv[]) {
printf("\n\tHuffman Coding.\n\tby Min Zeng\n\tEncode\n\n");
string filePath;
if (argc == 2) {
filePath = argv[1];
} else {
printf("Input file path: ");
cin >> filePath;
}
encode3608(filePath.c_str());
return 0;
}
| true |
16ba399e7cb5fdf5e1c04274bb7f33a08e65abdd
|
C++
|
sky4walk/Raycaster
|
/Vector3D.cpp
|
UTF-8
| 2,453 | 3.28125 | 3 |
[] |
no_license
|
#include <math.h>
#include "Vector3D.h"
Vector3D::Vector3D(void)
{
for(int i=0;i<3;i++)
{
m_vector[i] = 0.0;
}
}
Vector3D::Vector3D(const Vector3D &vec)
{
for(int i=0;i<3;i++)
{
m_vector[i] = vec.m_vector[i];
}
}
Vector3D::Vector3D(double x,double y,double z)
{
m_vector[0] = x;
m_vector[1] = y;
m_vector[2] = z;
}
const double &Vector3D::operator[](int i) const
{
return m_vector[i];
}
double &Vector3D::operator[](int i)
{
return m_vector[i];
}
Vector3D &Vector3D::operator=(const Vector3D &vec)
{
for(int i=0;i<3;i++)
{
m_vector[i] = vec.m_vector[i];
}
return (*this);
}
Vector3D Vector3D::operator+(const Vector3D &vec) const
{
Vector3D ret;
for(int i=0;i<3; i++)
{
ret[i] = m_vector[i] + vec.m_vector[i];
}
return ret;
}
Vector3D Vector3D::operator-(const Vector3D &vec) const
{
Vector3D ret;
for(int i=0;i<3; i++)
{
ret[i] = m_vector[i] - vec.m_vector[i];
}
return ret;
}
Vector3D &Vector3D::operator+=(const Vector3D &vec)
{
for(int i=0;i<3; i++)
{
m_vector[i] += vec.m_vector[i];
}
return (*this);
}
Vector3D &Vector3D::operator-=(const Vector3D &vec)
{
for(int i=0;i<3; i++)
{
m_vector[i] -= vec.m_vector[i];
}
return (*this);
}
Vector3D Vector3D::operator*(double x) const
{
Vector3D ret;
for(int i=0;i<3;i++)
{
ret[i] = m_vector[i]*x;
}
return ret;
}
Vector3D Vector3D::operator/(double x) const
{
Vector3D ret;
for( int i=0; i<3; i++ )
{
ret[i] = m_vector[i]/x;
}
return ret;
}
double Vector3D::length(void) const
{
double l = 0.0;
for(int i=0;i<3;i++)
{
l += m_vector[i] * m_vector[i];
}
return sqrt(l);
}
Vector3D Vector3D::norm(void) const
{
return (*this) / length();
}
Vector3D Vector3D::cross(const Vector3D &vec ) const
{
Vector3D ret;
ret = Vector3D( m_vector[1]*vec.m_vector[2] - m_vector[2]*vec.m_vector[1],
m_vector[2]*vec.m_vector[0] - m_vector[0]*vec.m_vector[2],
m_vector[0]*vec.m_vector[1] - m_vector[1]*vec.m_vector[0] );
return ret;
}
double Vector3D::dot(const Vector3D &vec) const
{
double ret = 0.0;
for(int i=0;i<3;i++)
{
ret += m_vector[i] * vec.m_vector[i];
}
return ret;
}
double Vector3D::getX()
{
return m_vector[0];
}
double Vector3D::getY()
{
return m_vector[1];
}
double Vector3D::getZ()
{
return m_vector[2];
}
Vector3D::~Vector3D(void)
{
}
| true |
fa487844caa2c31b54cc8c8327b347acf40f32c7
|
C++
|
SydneySchiller/Comsc-200
|
/GeometryHomework7/GeometryHomework.cpp
|
UTF-8
| 4,583 | 3.109375 | 3 |
[] |
no_license
|
// Lab 12, The "Geometry Homework 7" Program
// Programmer: Sydney Schiller
// Editor(s) used: Notepad
// Compiler(s) used: MinGW TDM GCC
#include "GeometryHomework.h"
#include <iostream>
using std::endl;
using std::ios;
using std::ostream;
#include <iomanip>
using std::setprecision;
#include <cstdlib>
#include <cmath>
// global variables
const double PI = 3.14159;
// base class Shape
Shape::Shape(const char* const token[])
:dimension1(token[1] ? atof(token[1]) : 0),
dimension2(token[2] ? atof(token[2]) : 0),
dimension3(token[3] ? atof(token[3]) : 0){}
//Square
Square::Square(const char* const token[])
:Shape(token){}
void Square::output(ostream &out) const
{
out << "SQUARE side=" << dimension1;// output to screen
out << set << " area=" << dimension1 * dimension1;
out << " perimeter= " << dimension1 * 4 << reset << endl;
}
void Square::xls(ostream &out) const
{
out << "SQUARE" << "\t" << dimension1 << "\t\t\t\t\t"// output to .xls file
<< set << dimension1 * dimension1 << "\t"
<< reset << dimension1 * 4 << "\t\t\n";
}
//Rectangle
Rectangle::Rectangle(const char* const token[])
:Shape(token){}
void Rectangle::output(ostream &out) const
{
out << "RECTANGLE length=" << dimension1 << " width=" << dimension2;
out << set << " area=" << dimension1 * dimension2;
out << " perimeter=" << (dimension1 * 2) + (dimension2 * 2) << reset << endl;
}
void Rectangle::xls(ostream &out) const
{
out << "RECTANGLE\t\t\t" << dimension1 << "\t" << dimension2 << "\t\t"
<< set << dimension1 * dimension2 << "\t"
<< reset << (dimension1 * 2) + (dimension2 * 2) << "\t\t\n";
}
//Circle
Circle::Circle(const char* const token[])
:Shape(token){}
void Circle::output(ostream &out) const
{
out << "CIRCLE radius=" << dimension1;
out << set << " area=" << PI * ((dimension1) * (dimension1));
out << " perimeter=" << 2 * PI * (dimension1) << reset << endl;
}
void Circle::xls(ostream &out) const
{
out << "CIRCLE" << "\t\t" << dimension1 << "\t\t\t\t"
<< set << PI * ((dimension1) * (dimension1)) << "\t"
<< 2 * PI * (dimension1) << "\t\t\n" << reset;
}
//Cube
Cube::Cube(const char* const token [])
:Square(token){}
void Cube::output(ostream &out) const
{
out << "CUBE" << " side=" << dimension1;
out << set << " surface area=" << 6 * (dimension1 * dimension1);
out << " volume=" << pow(dimension1, 3.0) << reset << endl;
}
void Cube::xls(ostream &out) const
{
out << "CUBE" << "\t" << dimension1 << "\t\t\t\t\t\t\t"
<< 6 * (dimension1 * dimension1) << "\t"
<< pow(dimension1, 3.0) << "\n";
}
//Prism
Prism::Prism(const char* const token[])
:Rectangle(token){}
void Prism::output(ostream &out) const
{
out << "PRISM" << " length=" << dimension1 << " width=" << dimension2 << " height=" << dimension3;
out << set << " surface area=" << (2 * (dimension1) * (dimension2)) + (2 * ((dimension1) + (dimension2)) * (dimension3));
out << " volume=" << (dimension1) * (dimension2) * (dimension3) << reset << endl;
}
void Prism::xls(ostream &out) const
{
out << "PRISM" << "\t\t\t" << dimension1 << "\t" << dimension2 << "\t" << dimension3 << "\t\t\t"
<< (2 * (dimension1) * (dimension2)) + (2 * ((dimension1) + (dimension2)) * (dimension3)) << "\t"
<< (dimension1) * (dimension2) * (dimension3) << "\n";
}
//Cylinder
Cylinder::Cylinder(const char* const token[])
:Circle(token){}
void Cylinder::output(ostream &out) const
{
out << "CYLINDER" << " radius=" << dimension1 << " height=" << dimension2;
out << set << " surface area=" << 2 * (PI * (dimension1 * dimension1)) + 2 * (PI * dimension1 * dimension2);
out << " volume=" << PI * dimension1 * dimension1 * dimension2 << reset << endl;
}
void Cylinder::xls(ostream &out) const
{
out << reset << "CYLINDER" << "\t\t" << dimension1 << "\t\t\t" << dimension2 << "\t\t\t"
<< set << 2 * (PI * (dimension1 * dimension1)) + 2 * (PI * dimension1 * dimension2) << "\t"
<< reset << PI * dimension1 * dimension1 * dimension2 << "\n";
}
//overloaded operator <<
ostream& operator<<(ostream& out, const Shape* s)
{
s->output(out);
return out;
}
// newly defined output stream manipulators
ostream& reset(ostream& out) // requires iostream, using ostream
{
out.unsetf(ios::fixed|ios::showpoint); // requires iostream, using ios
out << setprecision(6); // requires iostream and iomanip, using setprecision
return out;
}
ostream& set(ostream& out) // requires iostream, using ostream
{
out.setf(ios::fixed|ios::showpoint); // requires iostream, using ios
out << setprecision(2); // requires iostream and iomanip, using setprecision
return out;
}
| true |
858e96e5575c5c020375235aa9d85758dc3e8bcb
|
C++
|
Prithviraj8/DS-Codes
|
/TBT_Practise.cpp
|
UTF-8
| 2,661 | 3.5625 | 4 |
[] |
no_license
|
#include <iostream>
using namespace std;
class node
{
public:
int data,lbit,rbit;
node *left,*right;
};
class TBT {
public:
node *root;
public:
TBT(){
root = NULL;
}
public:
void create(node*);
void inorder(node*);
void preorder(node*);
};
node *curr,*temp,*head;
void TBT :: create(node *head){
root = new (node);
std::cout << "Enter root data " << '\n';
std::cin >> root->data;
head->left = root;
head->lbit = 1;
root->left = head;
root->right = head;
root->lbit = root->rbit = 0;
char ch,ch2;
do {
curr = new(node);
std::cout << "Enter new data " << '\n';
std::cin >> curr->data;
curr->lbit = 0;
curr->rbit = 0;
temp = root;
while (1) {
std::cout << "Add this to the left of "<<temp->data<<" or the right ??" << '\n';
std::cin >> ch;
if(ch == 'l'||ch=='L'){
if(temp->lbit == 1){
temp = temp->left;
}else{
curr->left = temp->left;
temp->left = curr;
curr->right = temp;
temp->lbit = 1;
break;
}
}else{
if(temp->rbit == 1){
temp = temp->right;
}else{
curr->right = temp->right;
temp->right = curr;
curr->left = temp;
temp->rbit = 1;
break;
}
}
}
std::cout << "Want to add more ??" << '\n';
std::cin >> ch2;
}while(ch2=='Y'||ch2=='y');
}
void TBT :: inorder(node *head){
std::cout << "------------INORDER-----------" << '\n';
temp=head->left;
while(temp!=head)
{
while(temp->lbit!=0)
temp=temp->left;
// cout<<temp->data<<" ";
while(temp->rbit!=1)
{
cout<<temp->data<<" ";
temp=temp->right;
}
// if(temp==head)
// break;
cout<<temp->data;
temp=temp->right;
}
}
void TBT :: preorder(node *head){
std::cout << "\n---------PREORDER -----"<<head->data << '\n';
temp = head->left;
while (temp!=head) {
/* code */
while (1) {
std::cout << temp->data;
if(temp->lbit == 1){
temp=temp->left;
}else{break;}
while (temp->rbit!=1) {
temp = temp->right;
}
temp = temp->right;
}
}
}
int main() {
/* code */
TBT func;
head = new(node);
// std::cout << "Enter head data" << '\n';
head->data = 999;
head->left = head->right = head;
head->lbit = 0;
head->rbit = 1;
func.create(head);
func.inorder(head);
func.preorder(head);
return 0;
}
| true |
829afff730af17e38365baeb60a15615971ffc1b
|
C++
|
linux-cc/minihttpd
|
/mysql/mysql.h
|
UTF-8
| 2,451 | 2.640625 | 3 |
[] |
no_license
|
#ifndef __MYSQL_MYSQL_IMPL_H__
#define __MYSQL_MYSQL_IMPL_H__
#include "config.h"
#include <mysql.h>
#include <vector>
#include <string>
BEGIN_NS(mysql)
using std::string;
using std::vector;
class Mysql {
public:
struct Row {
Row(MYSQL_ROW row, int num);
const string &operator[](int index) const {
return _fields[index];
}
int size() const {
return _fields.size();
}
typedef vector<string>::const_iterator Iterator;
Iterator begin() const {
return _fields.begin();
}
Iterator end() const {
return _fields.end();
}
string dump() const;
vector<string> _fields;
};
public:
Mysql() {
mysql_init(&_mysql);
}
bool connect(const char *user, const char *passwd, const char *host, int port) {
return mysql_real_connect(&_mysql, host, user, passwd, NULL, port, NULL, 0) != NULL;
}
uint64_t lastInsertId() {
return mysql_insert_id(&_mysql);
}
bool selectDb(const char *dbname) {
return mysql_select_db(&_mysql, dbname) == 0;
}
void close() {
mysql_close(&_mysql);
}
void connectTimeout(int seconds) {
option(MYSQL_OPT_CONNECT_TIMEOUT, &seconds);
}
void readTimeout(int seconds) {
option(MYSQL_OPT_READ_TIMEOUT, &seconds);
}
void writeTimeout(int seconds) {
option(MYSQL_OPT_WRITE_TIMEOUT, &seconds);
}
int option(mysql_option option, const void *arg) {
return mysql_options(&_mysql, option, arg);
}
int errcode() {
return mysql_errno(&_mysql);
}
const char *errinfo() {
return mysql_error(&_mysql);
}
int size() const {
return _rows.size();
}
const Row &operator[](int index) const {
return _rows[index];
}
typedef vector<Row>::const_iterator Iterator;
Iterator begin() const {
return _rows.begin();
}
Iterator end() const {
return _rows.end();
}
int execute(const char *sql);
string dump() const;
private:
struct Field {
Field(const string &name, const string &orgName, int index):
_name(name), _orgName(orgName), _index(index) {}
string _name;
string _orgName;
int _index;
};
MYSQL _mysql;
vector<Field> _fields;
vector<Row> _rows;
};
END_NS
#endif /* ifndef __MYSQL_MYSQL_IMPL_H__ */
| true |
d01c23ebfb09b9c6ba996196cbc448945e81b6ed
|
C++
|
Lujie1996/Leetcode
|
/39. Combination Sum/39. Combination Sum/main.cpp
|
UTF-8
| 1,493 | 3.34375 | 3 |
[] |
no_license
|
//
// main.cpp
// 39. Combination Sum
//
// Created by Jie Lu on 05/03/2018.
// Copyright © 2018 Jie Lu. All rights reserved.
//
// 回溯的思路,递归实现
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void getCombination(vector<int>& candidates, vector<vector<int>>& res, vector<int>& com, int target, int start) {
if(target==0){
res.push_back(com);
return;
}
for(int i=start;i<candidates.size();i++){
if(candidates[i]>target)
break;
com.push_back(candidates[i]);
getCombination(candidates, res, com, target-candidates[i], i);
com.pop_back();
//剪枝 : 当函数从getCombination()退出的时候,要么上一步是target==0,要么是candidats[i]>target。第二种情况的推出后程序执行到上一行,这里需要把之前pushback进来的数字删除。
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
sort(candidates.begin(),candidates.end());
vector<vector<int>> res;
vector<int> com;
getCombination(candidates, res, com, target, 0);
return res;
}
int main(int argc, const char * argv[]) {
int nums[]={2,3,6,7};
vector<int> candidates(nums, nums+4);
vector<vector<int>> res = combinationSum(candidates, 7);
for(int i=0;i<res.size();i++)
{
for (int j=0;j<res[i].size(); j++) {
cout<<res[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
| true |
422b61253643514b58e903af6ec8a7248274dd31
|
C++
|
nave7693/leetcode
|
/165-compare-version-numbers.cpp
|
UTF-8
| 1,217 | 3.65625 | 4 |
[
"MIT"
] |
permissive
|
// https://leetcode.com/problems/compare-version-numbers/
class Solution {
public:
int getNumber(string s, int *index) {
int result = 0;
while (*index < s.size() && s[*index] != '.') {
result = result * 10 + s[*index] - '0';
(*index)++;
}
if (s[*index] == '.') {
(*index)++;
}
return result;
}
int compareVersion(string version1, string version2) {
int index1 = 0;
int index2 = 0;
int result = 0;
while (index1 < version1.size() || index2 < version2.size()) {
int v1 = getNumber(version1, &index1);
int v2 = getNumber(version2, &index2);
if (v1 == v2) {
continue;
} else if (v1 < v2) {
return -1;
} else {
return 1;
}
}
int tail1 = version1.size() - index1;
int tail2 = version2.size() - index2;
if (tail1 == tail2) {
return 0;
} else if (tail1 < tail2) {
return -1;
} else if (tail1 > tail2) {
return 1;
}
return 0;
}
};
| true |
22a950e5b227bb5961ae2ad77a2116ddfc04a64d
|
C++
|
mrdishant/Python
|
/AddTwoNumbers.cpp
|
UTF-8
| 178 | 2.984375 | 3 |
[] |
no_license
|
#include<iostream>
using namespace std;
int a,b;
int main(){
cout<<"Enter A : ";
cin>>a;
cout<<"Enter B : ";
cin>>b;
cout<<"Sum is ";
cout<<(a+b);
return 0;
}
| true |
17b19366c233dbff6d67444c4b26aef328e81d8d
|
C++
|
SETHJI01/DSA
|
/String/caseSort.cpp
|
UTF-8
| 771 | 2.578125 | 3 |
[] |
no_license
|
#include<bits/stdc++.h>
using namespace std;
int main(){
string s;
cin>>s;
int n=s.length();
int hash_sm[26]={0},hash_cap[26]={0};
for(int i=0;i<n;i++){
if(s[i]>='A'&&s[i]<='Z')
hash_cap[s[i]-'A']++;
else
hash_sm[s[i]-'a']++;
}
int sm=0,cap=0;
string str="";
for(int i=0;i<n;i++){
if(s[i]>='A'&&s[i]<='Z'){
while(hash_cap[cap]==0&&cap<26){
cap++;
}
char temp='A'+cap;
str+=temp;
hash_cap[cap]--;
}
else{
while(hash_sm[sm]==0&&sm<26){
sm++;
}
char temp='A'+sm;
str+=temp;
hash_sm[sm]--;
}
}
cout<<str;
}
| true |
bf074f679592a538fc47590b566c275e53c5c356
|
C++
|
NubGhost/Snake-Game-CPP
|
/SnakeFiles/Point.h
|
UTF-8
| 1,422 | 3.09375 | 3 |
[] |
no_license
|
#ifndef _POINT_H_
#define _POINT_H_
#include <iostream>
#include "Gotoxy.h"
#include "Direction.h"
#include "Color.h"
#define LINES 20
#define ROWS 80
using namespace std;
class Point
{
int x;
int y;
int dir_x = 1;
int dir_y = 0;
void moveImpl() {
x = (x + dir_x + ROWS) % ROWS;
y = (y + dir_y + LINES) % LINES;
}
public:
int getDir_x()const { return dir_x; }
int getDir_y()const { return dir_y; }
void setDir_X(int new_X) { dir_x = new_X; }
void setDir_Y(int new_Y) { dir_y = new_Y; }
int getXCoord()const { return x; }
int getYCoord() const { return y; }
Point(int x1 = 1, int y1 = 1) {
x = x1;
y = y1;
}
void set(int x1 = 1, int y1 = 1) {
x = x1;
y = y1;
}
void draw(char c,ColorOptions clr = WHITE) {
gotoxy(x, y + 4);
if (c == '#') {
cout << Color(RED) << c << endl;
}
else if (c == '$') {
cout << Color(GREEN) << c << endl;
}
else if (c == ' ')
cout << Color(BLACK) << c << endl;
else
cout << Color(clr) << c<< endl;
setTextColor(WHITE);
}
void changeDirWithoutTermsOfStuckSituation(Direction dir);
void changeDir(Direction dir);
void move() {
int sameDir = rand() % 10;
if (!sameDir) {
int dir = rand() % 4;
changeDir((Direction)dir);
}
moveImpl();
}
void move(Direction dir, bool stuckR, bool stuckL, bool stuckU, bool stuckD);
bool isStuckequaldirection(Direction dir, bool stuckR, bool stuckL, bool stuckU, bool stuckD);
};
#endif
| true |
742c031c275df207b93b4629b20a6e71eb1c43a3
|
C++
|
weixu000/pixel-factory
|
/include/PixelFactory/Application.h
|
UTF-8
| 308 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
#pragma once
#include <list>
class Window;
class Application {
public:
Application();
~Application();
static Application &Instance() { return *application_; }
int Run();
private:
static inline Application *application_ = nullptr;
friend class Window;
std::list<Window *> windows_;
};
| true |
39581ec026f2cc5adc8de8712d5643f0bf7232c6
|
C++
|
baileyweible/Project_5
|
/spyro.cpp
|
UTF-8
| 1,170 | 2.9375 | 3 |
[] |
no_license
|
#include "spyro.hpp"
Spyro::Spyro(JsonEntityBuilder &builder, JsonItemBuilder & inventory, uint32_t uid) :
Entity(builder, inventory, uid)
{
std::cout << Name() << " the spyro has entered the battle" << std::endl;
}
void Spyro::Flameshoot(Entity *target)
{
Attack(target, 4.5, "Flameshoot");
}
void Spyro::Headbutt(Entity *target)
{
Attack(target, GetStrength() * 1.5, "Headbutt");
}
void Spyro::OutputStatus() const
{
std::cout << Class() << ": " << this->Name()
<< "\n\tCurrent HP: " << this->CurrentHP()
<< "\n\tStrength: " << this->GetStrength()
<< std::endl;
PrintInventory();
}
void Spyro::WeaponAttack(Entity * target)
{
Attack(target, GetStrength() * 0.5, "Scratch");
}
void Spyro::UseAction(Entity * target, const std::string& spellName, const std::string & args)
{
if(spellName == "weapon_attack")
{
WeaponAttack(target);
return;
}
if(spellName == "flameshoot")
{
Flameshoot(target);
return;
}
if(spellName == "Headbutt")
{
Headbutt(target);
return;
}
errorFindingAbility(spellName);
}
| true |
eee715b527f590e3cb7bf5c9d797965478c93a03
|
C++
|
YourNerdyJoe/transconsciousness
|
/transconsciousness/rect.cpp
|
UTF-8
| 423 | 3.015625 | 3 |
[] |
no_license
|
#include "rect.h"
Rect::Rect() : pos(0, 0), w(16), h(16)
{
calculateVertices();
}
Rect::Rect(float x, float y, float w, float h) : pos(x, y), w(w), h(h)
{
calculateVertices();
}
Rect::~Rect()
{
}
void Rect::calculateVertices()
{
float hw = w/2,
hh = h/2;
v[0].setElements(pos.x-hw, pos.y-hh);
v[1].setElements(pos.x+hw, pos.y-hh);
v[2].setElements(pos.x+hw, pos.y+hh);
v[3].setElements(pos.x-hw, pos.y+hh);
}
| true |
554fe9e6f9aa5deccdf91cee09e70e4434842f81
|
C++
|
ssauermann/AutoPas
|
/src/autopas/selectors/ContainerSelector.h
|
UTF-8
| 7,480 | 2.71875 | 3 |
[
"BSD-2-Clause"
] |
permissive
|
/**
* @file ContainerSelector.h
* @author F. Gratl
* @date 11.06.18
*/
#pragma once
#include <array>
#include <vector>
#include "autopas/containers/ParticleContainer.h"
#include "autopas/containers/directSum/DirectSum.h"
#include "autopas/containers/linkedCells/LinkedCells.h"
#include "autopas/containers/verletClusterLists/VerletClusterCells.h"
#include "autopas/containers/verletClusterLists/VerletClusterLists.h"
#include "autopas/containers/verletListsCellBased/verletLists/VarVerletLists.h"
#include "autopas/containers/verletListsCellBased/verletLists/VerletLists.h"
#include "autopas/containers/verletListsCellBased/verletLists/neighborLists/asBuild/VerletNeighborListAsBuild.h"
#include "autopas/containers/verletListsCellBased/verletListsCells/VerletListsCells.h"
#include "autopas/options/ContainerOption.h"
#include "autopas/selectors/ContainerSelectorInfo.h"
#include "autopas/utils/StringUtils.h"
namespace autopas {
/**
* Selector for a particle container.
*
* The class is given a list of allowed container and traversal options to choose from.
* This class selects the optimal container and delegates the choice of the optimal traversal down to this container.
*
* @tparam Particle
* @tparam ParticleCell
*/
template <class Particle, class ParticleCell>
class ContainerSelector {
public:
/**
* Constructor for the ContainerSelecor class.
* @param boxMin Lower corner of the container.
* @param boxMax Upper corner of the container.
* @param cutoff Cutoff radius to be used in this container.
*/
ContainerSelector(const std::array<double, 3> &boxMin, const std::array<double, 3> &boxMax, double cutoff)
: _boxMin(boxMin), _boxMax(boxMax), _cutoff(cutoff), _currentContainer(nullptr), _currentInfo() {}
/**
* Sets the container to the given option.
* @param containerOption container to generate
* @param containerInfo additional parameter for the container
*/
void selectContainer(ContainerOption containerOption, ContainerSelectorInfo containerInfo);
/**
* Getter for the optimal container. If no container is chosen yet the first allowed is selected.
* @return Smartpointer to the optimal container.
*/
std::shared_ptr<autopas::ParticleContainerInterface<ParticleCell>> getCurrentContainer();
/**
* Getter for the optimal container. If no container is chosen yet the first allowed is selected.
* @return Smartpointer to the optimal container.
*/
std::shared_ptr<const autopas::ParticleContainerInterface<ParticleCell>> getCurrentContainer() const;
private:
/**
* Container factory that also copies all particles to the new container
* @param containerChoice container to generate
* @param containerInfo additional parameter for the container
* @return smartpointer to new container
*/
std::unique_ptr<autopas::ParticleContainerInterface<ParticleCell>> generateContainer(
ContainerOption containerChoice, ContainerSelectorInfo containerInfo);
const std::array<double, 3> _boxMin, _boxMax;
const double _cutoff;
std::shared_ptr<autopas::ParticleContainerInterface<ParticleCell>> _currentContainer;
ContainerSelectorInfo _currentInfo;
};
template <class Particle, class ParticleCell>
std::unique_ptr<autopas::ParticleContainerInterface<ParticleCell>>
ContainerSelector<Particle, ParticleCell>::generateContainer(ContainerOption containerChoice,
ContainerSelectorInfo containerInfo) {
std::unique_ptr<autopas::ParticleContainerInterface<ParticleCell>> container;
switch (containerChoice) {
case ContainerOption::directSum: {
container = std::make_unique<DirectSum<ParticleCell>>(_boxMin, _boxMax, _cutoff, containerInfo.verletSkin);
break;
}
case ContainerOption::linkedCells: {
container = std::make_unique<LinkedCells<ParticleCell>>(_boxMin, _boxMax, _cutoff, containerInfo.verletSkin,
containerInfo.cellSizeFactor);
break;
}
case ContainerOption::verletLists: {
container = std::make_unique<VerletLists<Particle>>(_boxMin, _boxMax, _cutoff, containerInfo.verletSkin,
VerletLists<Particle>::BuildVerletListType::VerletSoA,
containerInfo.cellSizeFactor);
break;
}
case ContainerOption::verletListsCells: {
container = std::make_unique<VerletListsCells<Particle>>(_boxMin, _boxMax, _cutoff, TraversalOption::c08,
containerInfo.verletSkin, containerInfo.cellSizeFactor);
break;
}
case ContainerOption::verletClusterLists: {
container = std::make_unique<VerletClusterLists<Particle>>(_boxMin, _boxMax, _cutoff, containerInfo.verletSkin);
break;
}
case ContainerOption::verletClusterCells: {
container = std::make_unique<VerletClusterCells<Particle>>(_boxMin, _boxMax, _cutoff, containerInfo.verletSkin,
containerInfo.verletClusterSize);
break;
}
case ContainerOption::varVerletListsAsBuild: {
container = std::make_unique<VarVerletLists<Particle, VerletNeighborListAsBuild<Particle>>>(
_boxMin, _boxMax, _cutoff, containerInfo.verletSkin);
break;
}
default: {
utils::ExceptionHandler::exception("ContainerSelector: Container type {} is not a known type!",
containerChoice.to_string());
}
}
// copy particles so they do not get lost when container is switched
if (_currentContainer != nullptr) {
for (auto particleIter = _currentContainer->begin(IteratorBehavior::haloAndOwned); particleIter.isValid();
++particleIter) {
// add particle as inner if it is owned
if (particleIter->isOwned()) {
container->addParticle(*particleIter);
} else {
container->addHaloParticle(*particleIter);
}
}
}
return container;
}
template <class Particle, class ParticleCell>
std::shared_ptr<autopas::ParticleContainerInterface<ParticleCell>>
ContainerSelector<Particle, ParticleCell>::getCurrentContainer() {
if (_currentContainer == nullptr) {
autopas::utils::ExceptionHandler::exception(
"ContainerSelector: getCurrentContainer() called before any container was selected!");
}
return _currentContainer;
}
template <class Particle, class ParticleCell>
std::shared_ptr<const autopas::ParticleContainerInterface<ParticleCell>>
ContainerSelector<Particle, ParticleCell>::getCurrentContainer() const {
if (_currentContainer == nullptr) {
autopas::utils::ExceptionHandler::exception(
"ContainerSelector: getCurrentContainer() called before any container was selected!");
}
return _currentContainer;
}
template <class Particle, class ParticleCell>
void ContainerSelector<Particle, ParticleCell>::selectContainer(ContainerOption containerOption,
ContainerSelectorInfo containerInfo) {
// if we already have this container do nothing.
if (_currentContainer == nullptr or _currentContainer->getContainerType() != containerOption or
_currentInfo != containerInfo) {
_currentContainer = std::move(generateContainer(containerOption, containerInfo));
_currentInfo = containerInfo;
}
}
} // namespace autopas
| true |
773fbfa0a0b9cd66cfef5278f072e757b9ea5bfe
|
C++
|
mrdepth/libdgmpp
|
/c-wrapper/area.cpp
|
UTF-8
| 448 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
//
// area.cpp
// dgmpp
//
// Created by Artem Shimanski on 14.12.2017.
//
#include "area.h"
#include "internal.h"
dgmpp_type dgmpp_area_create (dgmpp_type_id type_id) {
try {
return new_handle(std::make_shared<Area>(static_cast<TypeID>(type_id)));
}
catch (...) {
return nullptr;
}
}
dgmpp_type dgmpp_area_copy (dgmpp_type area) {
try {
return new_handle(std::make_shared<Area>(*get<Area>(area)));
}
catch (...) {
return nullptr;
}
}
| true |
e63dcf9f50c416c81563b1ea9e2e6f6c9154d3dd
|
C++
|
antoni-heredia/ED-COMPARTIDO
|
/Practica3/include/Pila_max_Cola.h
|
UTF-8
| 2,546 | 3.625 | 4 |
[
"MIT"
] |
permissive
|
/**
* @file Pila_max_Cola.h
* @brief Fichero cabecera del TDA Pila Máximo Implementado con Cola
*
*/
#ifndef __PILA_COLA_H__
#define __PILA_COLA_H__
#include <iostream>
#include <cassert>
#include <string>
#include "cola.h"
/**
* @brief T.D.A. Pila_max_Cola
*
* El T.D.A. Pila_max_Cola permite crear un contenedor de tipo Pila pero con
* una modificación, ofrece al usuario un método para obtener el valor máximo
* que hay almacenado en la pila.
*
* <tt>\#include Pila_max_Cola.h</tt>
*
* La clase Pila será implementada con una cola.
* También será implementada como un template.
*
* @author Heredia Castillo, Antonio Jesus
* @author Hinojosa Castro, Miguel Angel
* @author Perez Lendinez, Jose Manuel
*
* @date Noviembre 2017
*/
template <class T>
class Pila{
private:
struct elemento {
T dato; ///< Elemento almacenado en la pila
T maximo; ///< Elemento maximo almacenado en la pila
};
Cola<elemento> datos; ///< Cola que controla el funcionamiento de la pila
int nelem;///< Numero de lementos almacenados en la pila
public:
// --------------- Constructores ----------------
/**
* @brief Constructor por defecto
*/
Pila();
/**
* @brief Constructor de copia
* @param p La pila de la que se hara la copia.
*/
Pila(const Pila<T> & p);
// --------------- Otras funciones ---------------
/**
* @brief Devuelve el numero de elementos de la pila
*/
int getNumeroElementos() const;
/**
* @brief Devuelve el elemento maximo de la pila
*/
T getElementoMaximo() const;
/**
* @brief Comprueba si la Pila esta vacia.
*/
bool vacia() const;
/**
* @brief Añade un elemento al principio de la pila
* @param c Elemento que se va a añadir.
*/
void poner(const T& c);
/**
* @brief Quita el elemento del tope de la pila.
*/
void quitar();
/**
* @brief Devuelve el elemento del tope de la pila.
*/
T tope() const;
/**
* @brief Devuelve un string con informacion sobre la pila.
*/
std::string to_s() const;
/**
* @brief Operador de asignacion
* @param p La Pila que se va a asignar.
*/
Pila<T>& operator=(const Pila<T> &p);
private:
// --------------- Funciones auxiliares ---------------
/**
* @brief Copia la pila pasada como argumento
* @param p La pila que se va a copiar.
*/
void copiar(const Pila<T> & p);
// elemento elementoTope() const;
};
#include "Pila_max_Cola.cpp"
#endif /* Pila_max_VD.h */
| true |
6c86f57d65686199e9aef37faa0d6d41eaa86755
|
C++
|
SineObama/Calculator
|
/Calculator/CalculationStack.h
|
GB18030
| 2,269 | 3.4375 | 3 |
[] |
no_license
|
#pragma once
#include <stack>
#include <stdexcept>
#include "BasicCalculationStack.h"
#include "BasicCalculationTree.h"
#include "BasicCalculation.h"
#include "CalculationException.h"
namespace sine {
namespace calculator {
/**
* ܴС()㡣
* ջΪʵֵġ
*/
template<class T>
class CalculationStack : public BasicCalculation<T> {
public:
CalculationStack(const CalculationSetting<T> &);
virtual ~CalculationStack();
InsertType nextInsertType();
virtual void insertValue(const T &);
virtual void insertOp(int);
virtual T calculate();
virtual void clear();
private:
typedef BasicCalculationStack<T> Basic;
std::stack<BasicCalculation<T>*> stack;
const CalculationSetting<T> &_setting;
};
template<class T>
CalculationStack<T>::CalculationStack(
const CalculationSetting<T> &setting)
: BasicCalculation<T>(setting), _setting(getSetting()) {
// keep the size >= 1
stack.push(new Basic(_setting));
}
template<class T>
CalculationStack<T>::~CalculationStack() {
clear();
}
template<class Value>
InsertType CalculationStack<Value>::nextInsertType() {
return stack.top()->nextInsertType();
}
template<class T>
void CalculationStack<T>::insertValue(const T &v) {
stack.top()->insertValue(v);
}
template<class T>
void CalculationStack<T>::insertOp(int hash) {
BasicCalculation *bc = stack.top();
switch (hash) {
case '(':
if (bc->nextInsertType() == BinaryOperator)
throw MissingOperator("miss operator before '('.");
stack.push(new Basic(_setting));
break;
case ')':
if (stack.size() <= 1)
throw BrackerMismatch("more ')' than '('.");
stack.pop();
stack.top()->insertValue(bc->calculate());
delete bc;
break;
default:
bc->insertOp(hash);
}
}
template<class T>
T CalculationStack<T>::calculate() {
if (stack.size() != 1)
throw BrackerMismatch("miss ')'.");
T result = stack.top()->calculate();
stack.top()->clear();
return result;
}
template<class T>
void CalculationStack<T>::clear() {
while (stack.size() != 1) {
delete stack.top();
stack.pop();
}
stack.top()->clear();
}
}
}
| true |
9115d7621f020d870141acdb98860024be3b3edc
|
C++
|
BackupTheBerlios/windstille-svn
|
/trunk/collisiontest/colltest.cxx
|
UTF-8
| 1,468 | 2.640625 | 3 |
[] |
no_license
|
#include "colltest.hxx"
#include "collision.hxx"
#include <assert.h>
SweepResult simple_sweep_1d(float a, float aw, float av,
float b, float bw, float bv)
{
SweepResult res;
// Normalize the calculation so that only A moves and B stands still
float v = av - bv;
if (v > 0)
{
res.t0 = (b - (a + aw)) / v;
res.t1 = (b + bw - a) / v;
res.state = SweepResult::COL_AT;
assert(res.t0 <= res.t1);
}
else if (v < 0)
{
res.t0 = (b + bw - a) / v;
res.t1 = (b - (a + aw)) / v;
res.state = SweepResult::COL_AT;
assert(res.t0 <= res.t1);
}
else // (v == 0)
{
if ((a + aw) < b || (a > b + bw))
res.state = SweepResult::COL_NEVER;
else
res.state = SweepResult::COL_ALWAYS;
}
return res;
}
bool overlap(float a,float aw,float b,float bw)
{
float a2=a+aw;
float b2=b+bw;
return ((a>=b && a<b2) || (a2>=b && a2<b2) || (b>=a && b<a2) || (b2>=a && b2<=a2));
}
void collideRectRect(InstantCollisionResult &result,const CollRect &a,const CollRect &b)
{
result.collision=overlap(a.x_pos(),a.width(),b.x_pos(),b.width()) && overlap(a.x_pos(),a.width(),b.x_pos(),b.width());
if(result.collision)
{
// FIXME: calculate unstuck direction and depth
}
}
void collideRectTri(InstantCollisionResult &result,const CollRect &a,const CollTri &b)
{
}
void collideTriTri(InstantCollisionResult &result,const CollTri &a,const CollTri &b)
{
}
| true |
0d30fb4261f766b6d751e462ab6f495075412175
|
C++
|
hskramer/CPlus
|
/ProgramPP/Chapter06/Problem06/Problem06/grammar.cpp
|
UTF-8
| 2,573 | 3.484375 | 3 |
[] |
no_license
|
#include "../../std_lib_facilities.h"
/* program implements a parses simple english sentence given the following definitions:
* Sentence:
Article Noun Verb
Noun Verb
Sentence Conjunction Sentence
* Noun:
birds, fish, C++
* Verb:
rules, fly, swim
* Conjunction:
and, or, but
* Article:
The, the
* Having a upper case and lower case 'the' allows for sentences like: "The fish swim but the birds fly";
this also works with: "The birds fly but the fish swim and C++ rules" . Started working with the full
class definition but soon realized the bulk of it wasn't neccessary so I kept what worked and deleted
the rest. This turned to be a simple program that can handle any correct use of the grammar.
*/
//----------------------------------------------------------------------------
// taken from the calculator problem only difference is it handles words instead of tokens
class String_stream {
public:
String_stream();
string get();
private:
bool full{ false };
string buffer;
};
//-------------------------------------------------------------------------------
// The constructor just sets buffer full to false to indicate buffer is empty
String_stream::String_stream()
:full(false), buffer("") {}
string String_stream::get()
{
string str;
cin >> str;
if (str == "The" || str == "the") {
string word{ "" };
cin >> word;
return word;
}
else
return str;
}
String_stream sstrm;
bool verb(string str)
{
vector<string>verbs{ "rules", "fly", "swim" };
for (string v : verbs)
if (v != str)
continue;
else
return true;
return false;
}
bool noun(string str)
{
vector<string>nouns{ "birds", "fish", "C++" };
for (string n: nouns)
if (n != str)
continue;
else
return true;
return false;
}
bool conjunctions(string str)
{
vector<string>conj{ "and", "but", "or" };
for (string c : conj)
if (c != str)
continue;
else
return true;
return false;
}
bool sentence()
{
bool ok = false;
string str{ "" };
ok = noun(sstrm.get());
ok = verb(sstrm.get());
str = sstrm.get();
if (ok && str == ".") {
return true;
}
else if (ok) {
ok = conjunctions(str);
if (ok)
sentence();
}
else if (!ok)
return false;
if (!ok && str == ".")
return false;
}
int main()
try {
bool good = true;
while (good) {
good = sentence();
if (good) {
cout << "OK\n";
return 0;
}
else {
cout << "Not OK\n";
return 0;
}
}
}
catch (exception& e)
{
cerr << "error: " << e.what() << "\n";
return 1;
}
catch (...)
{
cerr<<"unkown exception!\n";
return 2;
}
| true |