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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
404407f164fb8061092981ac6941c79f9b59818a | C++ | MrWater/myspark | /src/container/SafeVector.h | UTF-8 | 2,256 | 3.046875 | 3 | [] | no_license | #ifndef __SAFE_VECTOR_H__
#define __SAFE_VECTOR_H__
#include <vector>
#include "thread/Lock.h"
#include "thread/AutoLock.h"
#include "common/Iterator.h"
#include "common/Iterateable.h"
namespace ns_container
{
template<typename TEle>
class SafeVectorIterator;
template<typename TEle>
class SafeVector : public Iterateable<TEle, SafeVectorIterator<TEle>>
{
public:
SafeVector() {}
~SafeVector() {}
void add(TEle ele)
{
ns_thread::AutoLock(&_rwlock, ns_thread::RWLock::WRITE);
_vector.push_back(ele);
}
void extend(SafeVector<TEle> lst)
{
}
void erase(const TEle& ele)
{
ns_thread::AutoLock(&_rwlock, ns_thread::RWLock::WRITE);
typename std::vector<TEle>::iterator iter = _vector.begin();
for (; iter != _vector.end(); ++iter)
{
if (*iter == ele)
{
_vector.erase(iter);
return;
}
}
}
bool find(const TEle& ele, TEle* ret)
{
// if (ret == NULL)
ns_thread::AutoLock(&_rwlock, ns_thread::RWLock::READ);
typename std::vector<TEle>::iterator iter = _vector.begin();
for (; iter != _vector.end(); ++iter)
{
if (*iter == ele)
{
*ret = *iter;
return true;
}
}
return false;
}
bool empty()
{
ns_thread::AutoLock(&_rwlock, ns_thread::RWLock::READ);
return _vector.empty();
}
size_t size()
{
ns_thread::AutoLock(&_rwlock, ns_thread::RWLock::READ);
return _vector.size();
}
virtual SafeVectorIterator<TEle> begin()
{
SafeVectorIterator<TEle> iter;
iter._current = &(*_vector.begin());
return iter;
}
virtual SafeVectorIterator<TEle> end()
{
SafeVectorIterator<TEle> iter;
iter._current = &(*_vector.end());
return iter;
}
private:
std::vector<TEle> _vector;
ns_thread::RWLock _rwlock;
};
template<typename TEle>
class SafeVectorIterator : public Iterator<TEle>
{
public:
~SafeVectorIterator() {}
private:
SafeVectorIterator() {}
friend class SafeVector<TEle>;
};
}
#endif
| true |
4a00ea575dd160d82fb0858b9679bd07c44ab697 | C++ | yaozhihan1994/ca | /test/test.cpp | UTF-8 | 1,813 | 2.75 | 3 | [] | no_license | #include <sys/ioctl.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <errno.h>
#include <unistd.h>
#include <pthread.h>
#include <fstream>
#include <sstream>
#include <ctime>
#include <thread>
#include <mutex>
#include <list>
#include <map>
#include <array>
using namespace std;
/*
class test{
public:
template<class T> static string ToString(const T& t){
ostringstream oss;
oss<<t;
return oss.str();
}
};
void test(unsigned char* a, int b){
for(int i = 0; i< b; i++){
printf("0x%02x ",*(a+i));
}
cout<<endl;
}
*/
mutex m;
void test2(char a[], int b, int c){
lock_guard<mutex> lck(m);
printf("0x%02x\n",a[0]);
printf("0x%02x\n",a[1]);
sleep(2);
}
unsigned char* IntToUnsignedChar(unsigned int num){
unsigned char *ret = (unsigned char* )malloc(4);
if (!ret) {
printf("IntToUnsignedChar malloc fail\n");
return NULL;
}
ret[0] = num >> 24;
ret[1] = num >> 16;
ret[2] = num >> 8;
ret[3] = num;
return ret;
}
int main(){
/*
list<string> l;
l.push_back("a");
l.push_back("b");
l.push_back("c");
for (std::list<string>::iterator i = l.begin(); i != l.end(); i++) {
cout<<*i<<endl;
}
cout<<test::ToString(6)<<endl;
string s("aa");
s= "sda" + s;
cout<<s<<endl;
unsigned char a[5] = {};
test(a, 5);
mutex m;
lock_guard<mutex> lock(m);
err:{
}
*/
array<unsigned char, 11> arr {};
memset(arr.data(), 0x31, 10);
map<string, array<unsigned char, 11>> m;
m.insert(pair<string, array<unsigned char, 11>>("haha",arr));
cout<<(m.find("haha")->second).data()<<endl;
cout<<arr.data()<<endl;
for (map<string, array<unsigned char, 11>>::iterator i = m.begin(); i != m.end(); ){
m.erase(i++);
}
getchar();
return 0;
}
| true |
a088a31c1f2563a4453173ac51107a9d9cfd7984 | C++ | Benten559/avlLab | /tnode.h | UTF-8 | 1,714 | 3.53125 | 4 | [] | no_license | #ifndef _TNODE
#define _TNODE
#include<iostream>
using namespace std;
template<class type> class tnode {
private:
int height; //for duplicates
type data;
tnode<type>* leftPtr;
tnode<type>* rightPtr;
public:
tnode();
tnode(type item);
tnode(type item,tnode<type>* left, tnode<type>* right);
tnode<type>* getLeft();
tnode<type>* getRight();
type getItem();
void setRight(tnode<type>* right);
void setLeft(tnode<type>* left);
void setHeight(int value);
int getHeight();
};
//constructors begin
template<class type>
tnode<type>::tnode(){
height = 0;
leftPtr = NULL;
rightPtr = NULL;
}
template<class type>
tnode<type>::tnode(type item){
data = item;
}
template<class type>
tnode<type>::tnode(type item,tnode<type>* left, tnode<type>* right){
data = item;
leftPtr = left;
rightPtr = right;
}
//constructors end
//setters && getters begin
template<class type>
tnode<type>* tnode<type>::getLeft(){
return leftPtr;
}
template<class type>
tnode<type>* tnode<type>::getRight(){
return rightPtr;
}
template<class type>
void tnode<type>::setLeft(tnode<type>* left){
leftPtr = left;
}
template <class type>
void tnode<type>::setRight(tnode<type>* right){
rightPtr = right;
}
template <class type>
type tnode<type>::getItem(){
return data;
}
template<class type>
void tnode<type>::setHeight(int value){
height = value;
}
template <class type>
int tnode<type>::getHeight(){
return height;
}
//setters && getters end
#endif
| true |
983dfe3c24385bd7c653de04137fc36f50df0499 | C++ | xfile6912/Baekjoon | /Stack, Queue, Deque, List/boj1021.cpp | UTF-8 | 1,359 | 3.390625 | 3 | [] | no_license | #define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include<iostream>
#include<string>
#include<algorithm>
#include <queue>
using namespace std;
int main(void)
{
deque<int> q;
int n, m;
int flag = 1;//flag가 0이면 왼쪽으로 이동시켜 뽑고, 1이면 오른쪽으로 이동시켜 뽑는다.
int i,j;
int result = 0;
scanf("%d %d", &n, &m);
for (i = 1; i <= n; i++)
{
q.push_back(i);//덱에 1부터 n까지 집어넣음.
}
vector<int> v(m, 0);//뽑으려고 하는 수의 배열
for (i = 0; i < m; i++)
{
scanf("%d", &v[i]);
}
for (i = 0; i < m; i++)
{
flag = 1;
for (j = 0; j < (q.size()+1)/2; j++)//절반까지 찾아보고 만약에 절반내에 있으면 왼쪽으로 이동시키면 된다.//없으면 오른쪽으로 이동시킴
{
if (q[j] == v[i])
{
flag = 0;
break;
}
}
if (flag == 0)
{
while (q.front() != v[i])//해당 원소가 나올때까지 왼쪽으로 이동시켜줌
{
int temp=q.front();
q.pop_front();
q.push_back(temp);
result++;
}
q.pop_front();//해당원소 팝해줌;
}
else
{
while (q.front() != v[i])//해당 원소가 나올때까지 오른쪽으로 이동시켜줌
{
int temp = q.back();
q.pop_back();
q.push_front(temp);
result++;
}
q.pop_front();//해당원소 팝해줌;
}
}
printf("%d", result);
}
| true |
f97038ba192fd16d3a3651042985601d0a4d8a49 | C++ | pj520/samples | /framework/net-tcpserver/include/CJob.h | UTF-8 | 724 | 2.765625 | 3 | [
"MIT"
] | permissive | /* Copyright(C)
* For free
* All right reserved
*
*/
/**
* @file CJob.h
* @brief 任务父类
* @author highway-9, 787280310@qq.com
* @version 1.1.0
* @date 2016-02-20
*/
#ifndef _CJOB_H
#define _CJOB_H
#include <string>
#include <memory>
/**
* @brief 任务类
*/
class CJob
{
public:
virtual ~CJob() = default;
/**
* @brief run 执行任务
*/
virtual void run() = 0;
public:
int jobNo() const { return m_jobNo; }
void setJobNo(int jobNo) { m_jobNo = jobNo; }
std::string jobName() const { return m_jobName; }
void setJobName(const std::string& jobName) { m_jobName = jobName; }
private:
int m_jobNo = 0;
std::string m_jobName;
};
using CJobPtr = std::shared_ptr<CJob>;
#endif
| true |
a8648a3fa509467a10d676c2ba0b29a950678839 | C++ | iakshatgandhi/DSAImportantQuestionScratch | /Amazon_Interview_Questions/Easy/Reverse_Integer.cpp | UTF-8 | 525 | 3.078125 | 3 | [] | no_license | /*
Problem Link: https://leetcode.com/problems/reverse-integer/
*/
class Solution {
public:
int reverse(int x) {
int flag=0;
if(x<0)
flag=1;
int num = abs(x);
long int revNum = 0;
while(num>0){
int rem = num%10;
if(revNum*10 > INT_MAX)
return 0;
revNum = revNum * 10 + rem;
num /= 10;
}
if(flag==0)
return revNum;
else
return revNum * (-1);
}
};
| true |
7cad89d46b1e71c6b1e042e3758020d753f0bcdb | C++ | RAJNDR/src | /src/testWindow.cpp | UTF-8 | 2,283 | 2.984375 | 3 | [] | no_license | #include "testWindow.hpp"
testWindow::testWindow()
{
gwindow = NULL;
gsurface = NULL;
ghelloWorld = NULL;
createdWindow = true;
SCREEN_WIDTH = 640;
SCREEN_HEIGHT = 480;
}
testWindow::~testWindow()
{
close();
}
bool testWindow::initWindow()
{
//Initialization flag
bool success = true;
//Initialize SDL
if( SDL_Init( SDL_INIT_VIDEO ) < 0 )
{
printf( "SDL could not initialize! SDL_Error: %s\n", SDL_GetError() );
success = false;
}
else
{
//Create window
gwindow = SDL_CreateWindow( "SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN );
if( gwindow == NULL )
{
printf( "Window could not be created! SDL_Error: %s\n", SDL_GetError() );
success = false;
}
else
{
//Get window surface
gsurface = SDL_GetWindowSurface( gwindow );
}
}
return success;
}
bool testWindow::loadMedia()
{
//Loading success flag
bool success = true;
//Load splash image
ghelloWorld = SDL_LoadBMP( "flower.bmp" );
if( ghelloWorld == NULL )
{
printf( "Unable to load image %s! SDL Error: %s\n", "flower.bmp", SDL_GetError() );
success = false;
}
return success;
}
void testWindow::close()
{
//Deallocate surface
SDL_FreeSurface( ghelloWorld );
ghelloWorld = NULL;
//Destroy window
SDL_DestroyWindow( gwindow );
gwindow = NULL;
//Quit SDL subsystems
SDL_Quit();
}
void testWindow::start()
{
if( !initWindow() )
{
printf( "Failed to initialize!\n" );
}
else
{
//Load media
if( !loadMedia() )
{
printf( "Failed to load media!\n" );
}
else
{
bool quit = false;
while(!quit){
while( SDL_PollEvent( &e ) != 0 ){
//User requests quit
if( e.type == SDL_QUIT ){
quit = true;
}
}
//Apply the image
SDL_BlitSurface( ghelloWorld, NULL, gsurface, NULL );
//Update the surface
SDL_UpdateWindowSurface( gwindow );
}
}
}
} | true |
78882b734e16986a099b746ae560e05bb8ef5b8f | C++ | tsnowak/rob550-botlab | /src/apps/utils/drawing_functions.hpp | UTF-8 | 5,057 | 2.875 | 3 | [
"MIT"
] | permissive | #ifndef APPS_UTILS_DRAWING_FUNCTIONS_HPP
#define APPS_UTILS_DRAWING_FUNCTIONS_HPP
#include <vx/vx_types.h>
#include <vector>
class ObstacleDistanceGrid;
class OccupancyGrid;
class PoseTrace;
class particles_t;
class pose_xyt_t;
class rplidar_laser_t;
class robot_path_t;
struct frontier_t;
/**
* draw_robot draws the robot as an isoceles triangle. The center of the triangle is located at the robot's current
* position and the triangle points in the orientation of the robot's heading.
*
* \param pose Pose at which to draw the robot
* \param color Color to draw the robot
* \param buffer Buffer to add the robot object to
*/
void draw_robot(const pose_xyt_t& pose, const float color[4], vx_buffer_t* buffer);
/**
* draw_pose_trace draws the trace of robot poses as a sequence of connected line segments. A line is drawn between
* each consecutive pair of poses.
*
* \param poses Sequence of poses to be drawn
* \param color Color to draw the line segments
* \param buffer Buffer to add the line segments to
*/
void draw_pose_trace(const PoseTrace& poses, const float color[4], vx_buffer_t* buffer);
/**
* draw_laser_scan draws a laser scan as a set of rays starting at the pose at which the scan was taken and terminating
* at the measured endpoint of the ray. The laser scan is assumed to be measured from the provided robot pose and that
* the x-axis of the laser rangefinder is aligned with the x-axis of the robot coordinate frame.
*
* \param laser Laser scan to be drawn
* \param pose Pose of the robot when the scan was taken
* \param color Color to draw the laser scan
* \param buffer Buffer to add the laser scan to
*/
void draw_laser_scan(const rplidar_laser_t& laser, const pose_xyt_t& pose, const float color[4], vx_buffer_t* buffer);
/**
* draw_occupancy_grid draws an OccupancyGrid as a collection of square cells. Each cell corresponds to the log-odds of
* that particular location being occupied. White indicated the lowest odds of occupancy, i.e. it's free space. Black
* indicates the highest odds of occupancy, i.e. there's definitely an obstacle. Gray means the occupancy is unknown.
*
* The occupancy grid is rendered as a grayscale image, where each pixel in the image corresponds to one cell in the
* occupancy grid. The bottom left corner of the image corresponds to the origin of the occupancy grid.
*
* \param grid OccupancyGrid to be drawn
* \param buffer Buffer to add the occupancy grid image to
*/
void draw_occupancy_grid(const OccupancyGrid& grid, vx_buffer_t* buffer);
/**
* draw_particles draws a set of particles being maintaining by the SLAM particle filter. Each particle has a pose and
* a weight. The easiest approach for drawing particles is as points. This approach allows for seeing where the particles
* are. Additionally, you can adjust the color of the particles based on their weight. Finally, you can draw each
* particle as an arrow rather than a point so you can see the estimated robot heading.
*
* \param particles Weighted particles to be drawn
* \param buffer Buffer to add the particles to
*/
void draw_particles(const particles_t& particles, vx_buffer_t* buffer);
/**
* draw_path draws the robot path as a sequence of lines and waypoints. Lines connect consecutive waypoints. A box
* is drawn for each waypoint in the path.
*
* \param path Path to be drawn
* \param color Color to draw the path
* \param buffer Buffer to add the path objects to
*/
void draw_path(const robot_path_t& path, const float color[4], vx_buffer_t* buffer);
/**
* draw_distance_grid draws an ObstacleDistanceGrid in similar fashion to an OccupancyGrid. The distance grid is
* drawn as an RGB image with the following properties:
*
* - Obstacles are drawn black
* - Free space in the configuration space is white
* - Cells too close to a wall are drawn red
*
* The configuration space radius is specified using the cspaceDistance parameter.
*
* \param grid ObstacleDistanceGrid to draw
* \param cspaceDistance Minimum safe distance from walls (meters)
* \param buffer Buffer to add the grid image to
*/
void draw_distance_grid(const ObstacleDistanceGrid& grid, float cspaceDistance, vx_buffer_t* buffer);
/**
* draw_frontiers draws the frontiers in the map with one box located at each of the cells that sits along a frontier
* boundary in the occupancy grid.
*
* \param frontiers Frontiers to draw
* \param metersPerCell Scale to draw the frontiers -- each box should be this size
* \param color Color to draw the frontiers
* \param buffer Buffer to add the frontiers to
*/
void draw_frontiers(const std::vector<frontier_t>& frontiers,
double metersPerCell,
const float* color,
vx_buffer_t* buffer);
#endif // APPS_UTILS_DRAWING_FUNCTIONS_HPP
| true |
4ff17687eba23472f8ec51fd9f6e6ecbd5a64bf1 | C++ | nikitablack/cpp-tests | /functional/hybrid_functional/Math.h | UTF-8 | 1,790 | 3.34375 | 3 | [] | no_license | #pragma once
#include <random>
namespace math
{
const float pi{ 3.14159265359f };
const float two_pi{ 2 * pi };
inline int randRange(int const from, int const to)
{
static std::mt19937 gen;
std::uniform_int_distribution<> const distr(from, to);
return distr(gen);
}
inline float randRange(float const from, float const to)
{
static std::mt19937 gen;
std::uniform_real_distribution<float> const distr(from, to);
return distr(gen);
}
struct Vec2
{
float x;
float y;
Vec2(float const x = 0.0f, float const y = 0.0f) : x{ x }, y{ y }
{}
Vec2 normalize() const
{
float const len{ std::sqrt(x * x + y * y) };
float const oneOverLen{ 1 / len };
return{ x * oneOverLen , y * oneOverLen };
}
Vec2 getNormal() const
{
Vec2 const n{ normalize() };
return{ n.y, -n.x };
}
Vec2 operator+(Vec2 const other) const
{
return{ x + other.x, y + other.y };
}
Vec2 operator-(Vec2 const other) const
{
return{ x - other.x, y - other.y };
}
Vec2 operator-() const
{
return{ -x, -y };
}
Vec2 operator*(float const s) const
{
return{ x * s, y * s };
}
float dot(Vec2 const other) const
{
return x * other.x + y * other.y;
}
};
struct Bounds
{
Bounds(Vec2 const tl = {}, Vec2 const br = {}) : topLeft{ tl }, bottomRight{ br }
{}
Vec2 topLeft;
Vec2 bottomRight;
};
struct Color
{
Color(float const r = 0.0f, float const g = 0.0f, float const b = 0.0f) : r{ r }, g{ g }, b{ b } {}
float r;
float g;
float b;
};
struct CellsRange
{
CellsRange(int const cStart = 0, int const rStart = 0, int const cEnd = 0, int const rEnd = 0) : colStart{ cStart }, rowStart{ rStart }, colEnd{ cEnd }, rowEnd{ rEnd }
{}
int colStart;
int rowStart;
int colEnd;
int rowEnd;
};
} | true |
fc7af66f72670b21dea10369379a6ebbe7a0688e | C++ | noobtechie/2015HackadayPrize | /Main_Project/Arduino_code/door/door.ino | UTF-8 | 1,582 | 2.78125 | 3 | [] | no_license | //Header files
#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
#include "printf.h"
#include "LowPower.h"
//Node ID definitions
#define DOOR 4
#define NET_ID 1
#define NODE_ID 3
int doorval;
//Structure to store the radio packets
typedef struct{
uint8_t from;
uint8_t to;
uint8_t type;
boolean data1;
boolean data2;
}payload;
payload door;
RF24 radio(9,10); //Radio initialization with CS and CE pins at arduino 9 and 10
const uint64_t pipe = 0xDEADBEEF03; //Pipe address of this node
void setup() {
// Serial Initialization
Serial.begin(57600);
printf_begin();
//Radio Initialization
radio.begin();
radio.setRetries(15,15);
radio.setDataRate(RF24_250KBPS);
radio.setPALevel(RF24_PA_MAX);
radio.setChannel(92);
radio.enableDynamicPayloads();
radio.setCRCLength(RF24_CRC_16);
//Open Pipe for Writing
radio.openWritingPipe(pipe);
//radio.startListening();
radio.printDetails();
pinMode(DOOR,INPUT);
pinMode(3,OUTPUT);
}
void loop() {
//Power Up radio from sleep mode
radio.powerUp();
// Read Sensor Data
doorval = digitalRead(DOOR);
//Store data in structure
door.from = NODE_ID;
door.to = 0;
door.type = 3;
door.data1 = doorval;
digitalWrite(3,doorval);
bool ok = false;
//Wait untill the data is sent
while(!ok)
ok = radio.write(&door,sizeof(payload));
//if(ok)
printf("ok\n");
//Power Down the node for 1 second
radio.powerDown();
LowPower.powerDown(SLEEP_1S, ADC_OFF, BOD_OFF);
LowPower.powerDown(SLEEP_1S, ADC_OFF, BOD_OFF);
}
| true |
993fe3ae88a79810b7e7314800108fc856ab2ffe | C++ | Alina-Stscherbakowa/laboratornie | /Лабораторная 1/ConsoleApplication1/ConsoleApplication1.cpp | WINDOWS-1251 | 1,086 | 3.171875 | 3 | [] | no_license | // ConsoleApplication1.cpp: .
//
#include "stdafx.h"
#include "vremia.h"
#include <iostream>
Time::Time() //
{
hour = 10;
point = new int;
*point = 20;
}
Time::~Time() //
{
hour = 0;
delete point;
}
void Time::settime(int h, int m, int s)
{
hour = h;
min = m;
sec = s;
}
void Time::showtime()
{
std::cout << hour << " " << min << " "
<< sec << " " << std::endl;
}
void Time::showtime2()
{
if (hour > 12)
hour -= 12;
std::cout << hour << " (-) P.M " << min << " "
<< sec << " " << std::endl;
}
void Time::showDay()
{
std::cout << "C 00:00 05.00 " << std::endl;
}
void Time::showDay2()
{
std::cout << "C 05:00 09.00 " << std::endl;
}
void Time::showDay3()
{
std::cout << "C 09:00 17.00 " << std::endl;
}
void Time::showDay4()
{
std::cout << "C 00:00 05.00 " << std::endl;
} | true |
dc73466f810cbb71dbf552db5449220761876eef | C++ | ChristianNHill/FIFO-Practice-Hospital-Queue- | /PriorityQueue.cpp | UTF-8 | 2,855 | 3.34375 | 3 | [] | no_license | //
//Christian Hill
//HW7 _ 11/8/16
//CSCi 2270 - Boese
//
#include <iostream>
#include <fstream>
#include <sstream>
#include <cstdlib>
#include <string>
#include "PatientQueue.hpp"
using namespace std;
//Constructor
PatientQueue::PatientQueue()
{
lastIndex = 0;
}
//Destructor
PatientQueue::~PatientQueue()
{
cout<<"We're CLOSING! Deleting patient queue!" <<endl;
for(int i=1;i<=lastIndex;i++)
{
cout<<"Removing "<<waitlist[i]->name<<" from the queue."<<endl;
delete waitlist[i];
}
}
bool PatientQueue::isEmpty(){
if (lastIndex == 0){
return true;
}
else{
return false;
}
}
//Returns Total amount of patients left
int PatientQueue::size(){
return lastIndex;
}
//Enqueue function that adds people to the queue and sorts them by priority.
void PatientQueue::enqueue(int priority, std::string name){
int parent;
cout << "Adding " << priority << " " << name << endl;
if(isEmpty() == true)
{
lastIndex++;
waitlist[lastIndex]= new Patient(priority, name);
}
else{
++lastIndex;
waitlist[lastIndex]= new Patient(priority, name);
int child=lastIndex;
parent = child/2;
while(waitlist[child]->priority < waitlist[parent]->priority && parent!=1){
swap(parent,child);
child = parent;
parent = child/2;
}
if(parent==1 && waitlist[parent]->priority>waitlist[child]->priority)
swap(parent,child);
}
printList();
}
//Swap function that swaps two array names/priority
void PatientQueue::swap(int index1, int index2){
string temp = waitlist[index1]->name;
int temp1 = waitlist[index1]->priority;
waitlist[index1]->priority = waitlist[index2]->priority;
waitlist[index1]->name = waitlist[index2]->name;
waitlist[index2]->priority = temp1;
waitlist[index2]->name = temp;
}
//Removes top priority from the array and re-heaps
Patient* PatientQueue::dequeue()
{
cout<<"Processing "<<waitlist[1]->priority<<" "<<waitlist[1]->name<<endl; // returns pointer to patient record and removes from array
if(isEmpty()==true){
cout<<"No patients"<<endl;
return waitlist[1];
}
else if (lastIndex == 1) {
lastIndex--;
return waitlist[1];
}
else{
int parent=1;
int child=2;
swap(1,lastIndex);
while(waitlist[parent]->priority > waitlist[child]->priority && child!=lastIndex)
{
if(waitlist[child+1]->priority>waitlist[child]->priority)
swap(parent,child);
else
swap(parent,child+1);
parent=child;
child=child*2;
}
lastIndex--;
return waitlist[lastIndex+1];
}
}
// prints the array using indexes
void PatientQueue::printList(){
int i=1;
cout<<"==="<<endl;
if(isEmpty()==true){
cout<<"Patients Waiting"<<endl;
cout<<"No one waiting!"<<endl;
cout<<"==="<<endl;
}
else{
cout<<"Patients Waiting"<<endl;
while(i!=lastIndex+1){
cout<<"["<<waitlist[i]->priority<<"] "<<waitlist[i]->name<<endl;
i++;
}
cout<<"==="<<endl;
}
}
| true |
b2bfaeed307b4d156528e33f4dbaa0ed11bbdf53 | C++ | itaniyagupta/Famous_Programming_Problems | /Searching & Sorting/Quicksort on an array.cpp | UTF-8 | 1,019 | 3.59375 | 4 | [
"MIT"
] | permissive | // Runtime: O(n log( n)) in best/average, O(n^2) in worst case; Space: 0(log(n))
// Sorting In Place: Yes
// Stable: No
class solution{
public:
void quicksort(vector<int>& arr){
int start =0;
int end = arr.size()-1;
int index = partition(arr, start, end);
if (start< index - 1)
{
quicksort(arr, start, index - 1);
}
if (index< end)
{
quicksort(arr, index, end);
}
}
int partition (vector<int>& arr, int start, int end){
int pivot = arr[(start + end)/2];
// Picking the pivot point
while (start <= end)
{
// Finding element on left side which should be on right side
while (arr[start] < pivot)
{
start++;
}
// Finding element on left side which should be on right side
while (arr[end] > pivot)
{
end--;
}
if (start<= end)
{ // swapping elements and moving start & end indexes
swap(arr, start, end);
start++;
end--;
}
}
return start;
}
}; | true |
20142054baf3ce90e556c8ecae2520f15b1bbd8c | C++ | rgb-empire/IM_A_MIDI_LITTLE_BITCH | /IM_A_MIDI_LITTLE_BITCH/Tweener.h | UTF-8 | 522 | 2.78125 | 3 | [
"MIT"
] | permissive | #pragma once
#include "Global_Definitions.h"
class Tweener
{
public:
static void tween(int* target, const int& new_val, const int duration = 2000, const Ease ease = LINEAR, const Ease_Type type = INOUT, Callback callback = NULL);
static void update();
protected:
struct Tween {
int* target;
int old_val;
int new_val;
int delta_val;
int duration;
long start_time;
long end_time;
Ease ease;
Ease_Type type;
Easing_Function ease_func;
Callback cb;
};
static std::vector<Tween*> tweens;
}; | true |
63a8b6fcbc0b9f6ef454c000753c3198b3eb5e92 | C++ | Himanshu54/practice-cpp | /dsa/array/minimum_stack.h | UTF-8 | 482 | 3.453125 | 3 | [] | no_license | #include <iostream>
#include <stack>
#include <utility> // <pair>
/*
A Template for Minimum stack.
*/
template <class T>
class MinStack{
std::stack<std::pair<T,T>> st;
public:
MinStack(){
}
void push(T element){
T min_ele = st.empty() ? element : std::min(element,st.top().second);
st.push({element, min_ele});
}
void pop(){
st.pop();
}
T top(){
return st.top().first;
}
T minimum(){
return st.top().second;
}
bool empty(){
return st.empty();
}
};
| true |
61839e9b5f2f98fd6f723412710740a657d88352 | C++ | pappyros/algorithm | /백준 KMP/백준 KMP/소스.cpp | UTF-8 | 297 | 2.984375 | 3 | [] | no_license | #include<iostream>
#include<string>
using namespace std;
int main() {
char arr[100];
cin >> arr;
string result = "";
for (int i = 0; i < 100; i++) {
if (i == 0) {
result += arr[0];
continue;
}
if (arr[i] == '-') {
result += arr[i + 1];
}
}
cout << result;
} | true |
a7f29f8418707ae27cf94e8af008868fc4f4f89a | C++ | CodeTest-StudyGroup/Code-Test-Study | /kuyhochung/3. 카카오/2020 KAKAO Blind Recruitment/외벽 점검.cpp | UTF-8 | 1,043 | 3.015625 | 3 | [] | no_license | #include <string>
#include <vector>
#include <algorithm>
using namespace std;
int solution(int n, vector<int> weak, vector<int> dist) {
int length = weak.size();
int dist_size = dist.size();
int answer = dist_size + 1; //최대 9의 값을 가진다.
for (int i = 0; i < length; i++)
weak.push_back(weak[i] + n);
for (int start = 0; start < length; start++) {
do {
int num_friend = 1;
int position = weak[start] + dist[num_friend-1];
for (int index = start; index < start + length; index++) {
if (position < weak[index]) {
num_friend++;
if (num_friend > dist_size)
break;
position = weak[index] + dist[num_friend - 1];
}
}
answer = min (answer, num_friend);
} while (next_permutation(dist.begin(), dist.end()));
}
if (answer > dist_size) return -1;
return answer;
} | true |
d0065977db333e356825fd569bb5bb4103cc40f1 | C++ | utkarsh914/LeetCode | /Design/211. design-add-and-search-words-data-structure.cpp | UTF-8 | 2,716 | 3.546875 | 4 | [] | no_license |
class WordDictionary {
class Trie {
// custom node class (each node will contain a single character of word)
class Node {
char data;
bool complete;
int children;
public:
vector<Node*> next;
// constructor
Node(char c='*', bool comp=false) {
data=c, complete=comp, children=0;
next.resize(26, NULL);
}
// adds a character to the node as child
void addChild(char c) {
if (!next[c-'a']) {
next[c-'a'] = new Node(c);
children++;
}
}
// returns the pointer of the given children (else NULL)
Node* address(char c) { return next[c-'a']; }
// below functions are self explanatory
void markComplete() { complete = true; }
bool isComplete() { return complete; }
int childCount() { return children; }
};
public:
// root node of our trie
Node* root;
/** Initialize your data structure here. */
Trie() {
root = new Node('*', false);
}
/** Inserts a word into the trie. */
void insert(string word) {
Node* curr = root;
for (auto c:word) {
curr->addChild(c);
curr = curr->address(c);
}
curr->markComplete();
}
/** Returns the pointer to node containing last character of word */
Node* getTailNode(string word) {
Node* curr = root;
for (auto c:word) {
if (!curr->address(c)) return NULL;
curr = curr->address(c);
}
return curr;
}
/** Returns if the word is in the trie. */
bool search(string word, int start=0, Node* curr=NULL) {
if (!curr) curr=root;
for (int i=start; i<word.length(); i++) {
char c = word[i];
if (c == '.') {
for (auto j:curr->next)
if (j!=NULL and search(word, i+1, j))
return true;
return false;
}
if (!curr->address(c))
return false;
curr = curr->address(c);
}
return (curr and curr->isComplete());
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
Node* curr = getTailNode(prefix);
if (!curr) return false;
return curr->isComplete() or curr->childCount()>0;
}
};
/**
* Your Trie object will be instantiated and called as such:
* Trie* obj = new Trie();
* obj->insert(word);
* bool param_2 = obj->search(word);
* bool param_3 = obj->startsWith(prefix);
*/
Trie* t;
public:
/** Initialize your data structure here. */
WordDictionary() {
this->t = new Trie();
}
void addWord(string word) {
t->insert(word);
}
bool search(string word) {
return t->search(word);
}
};
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary* obj = new WordDictionary();
* obj->addWord(word);
* bool param_2 = obj->search(word);
*/ | true |
c7f5440458cd96367a9a6336186d25a5d08e4844 | C++ | cwlseu/Algorithm | /leetcode/book/array/search_rotated_sortary.cpp | UTF-8 | 1,371 | 3.765625 | 4 | [] | no_license | /**
* @FILE: /array/search_rotated_sortary.cpp
* @DESCRIPTION:
* Suppose a sorted array is rotated at some pivot unknown to you beforehand.
* You are given a target value to search. If found in the array return its index, otherwise return -1.
* You may assume no duplicate exists in the array.
* @AUTHOR: wenlong.cao
* @CREATE: 2016-11-23
**/
#include <iostream>
#include <vector>
using namespace std;
#include <cassert>
// every iteration, delete the part of sorted
int search(int A[], int n, int target)
{
int first = 0, last = n;
while (first != last)
{
const int mid = (first + last) / 2;
if (A[mid] == target)
return mid;
if (A[first] <= A[mid])
{
if (A[first] <= target && target < A[mid])
last = mid;
else // if target cannot meeting previous condition, means the target may occur in another part
first = mid + 1;
} else
{
if (A[mid] < target && target <= A[last-1])
first = mid + 1;
else
last = mid;
}
}
return -1;
}
void test_search_rotated_sortary()
{
int A[] = {4,5,6,7,8,9,0,1,2};
assert( -1 == search(A,9,3));
assert( 8 == search(A,9,2));
}
int main(int argc, char const *argv[])
{
test_search_rotated_sortary();
return 0;
} | true |
81485905c600f4fb59bd3ab71a6854e414d70fd1 | C++ | lythesia/pat | /a/1029/1029.cc | UTF-8 | 1,071 | 2.53125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
#define inject(x) { cerr << "Function: " << __FUNCTION__ << ", Line: " << __LINE__ << ", " << #x << ": " << (x) << endl; }
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<string> vs;
typedef vector<vs> vvs;
int N, M;
long s[1000005 * 2];
int main(int argc, const char *argv[])
{
int tot = 0;
scanf("%d", &N);
for(; tot<N; tot++) scanf("%ld", &s[tot]);
scanf("%d", &M);
for(; tot<N+M; tot++) scanf("%ld", &s[tot]);
int k = (N + M - 1) / 2;
nth_element(s, s + k, s + M + N);
printf("%ld\n", s[k]);
return 0;
}
#if 0
// or bin-search
long find_kth(long a[], int m, long b[], int n, int k)
{
if(m > n) return find_kth(b, n, a, m, k);
if(m == 0) return b[k - 1];
if(k == 1) return min(a[0], b[0]);
int pa = min(k / 2, m), pb = k - pa;
if(a[pa - 1] == b[pb - 1]) return a[pa - 1];
else if(a[pa - 1] < b[pb - 1]) return find_kth(a + pa, m - pa, b, n, k - pa);
else return find_kth(a, m, b + pb, n - pb, k - pb);
}
find_kth(S1, N1, S2, N2, (N1 + N2 + 1) / 2);
#endif
| true |
e00e39a58f427d7d0f162a729f2b7c720dea61ee | C++ | dlgldgldgld/3D_VIEWER | /MY_VIEWER/MY_VIEWER/Source/CLogTrace.cpp | UTF-8 | 1,941 | 2.78125 | 3 | [] | no_license | #include "CLogTrace.h"
#include <windows.h>
#include <io.h>
#include <time.h>
void logTrace::CLogTrace::Clear()
{
if ( m_outLog != nullptr )
{
fclose( m_outLog );
}
}
logTrace::CLogTrace::CLogTrace( )
: m_outLog ( nullptr )
, m_Init ( false )
{
}
logTrace::CLogTrace::~CLogTrace()
{
Clear( );
}
logTrace::CLogTrace * logTrace::CLogTrace::GetInstance()
{
if (m_pInst == nullptr)
{
m_pInst = new CLogTrace;
}
return m_pInst;
}
void logTrace::CLogTrace::DestroyInstance()
{
if (m_pInst == nullptr)
{
return;
}
delete m_pInst;
m_pInst = nullptr;
}
bool logTrace::CLogTrace::Init( const char * filePath , const char * appName)
{
std::string logFilePath ;
logFilePath.append ( filePath ) ;
logFilePath.append ( "/" ) ;
logFilePath.append ( appName ) ;
logFilePath.append ( "_" ) ;
logFilePath.append ( LOG_FILE_NAME ) ;
if ( 0 == _access( logFilePath.c_str( ), 0 )
&& -1 == _unlink( logFilePath.c_str( ) ) )
{
printf("%s logFile Delete Fail!!\n", logFilePath.c_str( ) ) ;
return false;
}
fopen_s(&m_outLog, logFilePath.c_str(), "w+" ) ;
if ( m_outLog == nullptr )
{
printf("file_open fail.. \n");
return false;
}
return true;
}
void logTrace::CLogTrace::WriteLog( const logType & logType, char const * format , ... )
{
// Get Current Time
time_t now = time(0);
struct tm tstruct;
char buf[80];
localtime_s(&tstruct, &now);
strftime( buf, sizeof (buf), "%Y-%m-%d %X", & tstruct );
// Set LogColor
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute( hConsole, LOG_COLOR [ logType ] ) ;
va_list argptr;
va_start ( argptr, format );
printf ( "[ %s ] - ", buf ) ;
vprintf( format, argptr ) ;
printf ( "\n" ) ;
fprintf( m_outLog, "[ %s ] - ", buf ) ;
vfprintf_s( m_outLog, format , argptr);
fprintf( m_outLog, "\n" ) ;
va_end( argptr );
return;
}
//****************************
logTrace::CLogTrace * logTrace::CLogTrace::m_pInst = nullptr; | true |
265d759bfe0c108e76d94cf836cfa0fe66a6dd6d | C++ | ZitingShen/World-Simulation | /boid.cc | UTF-8 | 8,602 | 2.65625 | 3 | [] | no_license | #include "boid.h"
using namespace std;
BOID::BOID(){
pos = SPAWN_POSITION;
velocity = SPAWN_VELOCITY;
partner_radius = PARTNER_RADIUS;
}
bool is_partner(BOID& source, BOID& target){
return source.partner_radius >= glm::distance(source.pos,
target.pos);
}
void update_velocity(vector<BOID>& a_flock, GOAL& a_goal){
if (a_flock.size() < 2) return;
glm::vec3 s_modifier, a_modifier, c_modifier, f_modifier;
glm::vec3 flock_center;
int num_of_partners;
bool close_to_goal = false;
float dis_to_partner;
for (auto source = a_flock.begin(); source != a_flock.end(); source++){
num_of_partners = 0; //reset for the next boid
close_to_goal = glm::length(a_goal.pos - source->pos) < APPROACHING_GOAL;
for (auto target = a_flock.begin(); target != a_flock.end(); target++){
if (target == source) continue;
if (is_partner(*source, *target)){
num_of_partners++;
dis_to_partner = glm::distance(source->pos, target->pos);
if (dis_to_partner > SCATTERING){
s_modifier += (source->pos - target->pos) * 0.95f;
a_modifier += target->velocity;
c_modifier += target->pos * 1.05f;
} else if (dis_to_partner < COLLIDING){
s_modifier += (source->pos - target->pos) * 1.05f;
a_modifier += target->velocity;
c_modifier += target->pos * 0.95f;
} else {
s_modifier += source->pos - target->pos;
a_modifier += target->velocity;
c_modifier += target->pos;
}
if(close_to_goal){// if close to goal, scatter
//cout << "now near goal" << endl;
s_modifier = s_modifier * 1.1f;;
a_modifier = a_modifier * 0.9f;
}
}
}
if (num_of_partners != 0){
//cout << "num_of_partners = " << num_of_partners << endl;
s_modifier = s_modifier*(SEPARATION_WEIGHT/(float)num_of_partners)*1.8f;
a_modifier = (a_modifier*(1.0f/num_of_partners)
- source->velocity)*ALIGNMENT_WEIGHT*0.8f;
c_modifier = (c_modifier*(1.0f/num_of_partners)
- source->pos)*COHESION_WEIGHT;
//if (source->pos == a_flock[0].pos) // clear view for the first person view
// s_modifier = 10.0f * s_modifier;
source->velocity += s_modifier + a_modifier + c_modifier;
}
flock_center = flock_centroid(a_flock);
if (glm::distance(source->pos, flock_center) > FLOCK_RAIUS_CAP){
source->velocity += (flock_center - source->pos) * STAY_IN_FLOCK_WEIGHT;
}
/* Cap Z-axis Speed */
source->velocity[2] = max(-Z_SPEED_CAP, min(source->velocity[2], Z_SPEED_CAP));
/* Cap Boid Speed */
if(glm::length(source->velocity) > BOID_SPEED_CAP)
source->velocity = glm::normalize(source->velocity) * BOID_SPEED_CAP;
}
}
void update_pos(vector<BOID>& a_flock){
if (a_flock.size() == 0) return;
for (auto a_boid = a_flock.begin(); a_boid != a_flock.end(); a_boid++) {
a_boid->pos += a_boid->velocity;
}
}
glm::vec3 flock_centroid(vector<BOID>& a_flock){
glm::vec3 centroid = glm::vec3(0, 0, 0);
if (a_flock.size() == 0)
return centroid;
int counter = 0;
for (auto current = a_flock.begin(); current != a_flock.end(); current++) {
centroid += current->pos;
counter++;
}
return centroid*(1.0f/counter);
}
glm::vec3 mid_point(vector<BOID>& a_flock, GOAL& a_goal){
if (a_flock.size() == 0)
return glm::vec3(0, 0, 0);
return (flock_centroid(a_flock)+(a_goal.pos))*(0.5f);
}
glm::vec3 get_u(vector<BOID>& a_flock, GOAL& a_goal){
if (a_flock.size() == 0)
return glm::vec3(0, 0, 0);
return (a_goal.pos - flock_centroid(a_flock));
}
float get_d(vector<BOID>& a_flock, GOAL& a_goal){
if (a_flock.size() == 0)
return 0;
return glm::distance(flock_centroid(a_flock), a_goal.pos);
}
glm::vec3 get_average_v(vector<BOID>& a_flock){
glm::vec3 average_v = glm::vec3(0, 0, 0);
for (auto a_boid = a_flock.begin(); a_boid != a_flock.end(); a_boid++)
average_v += a_boid->velocity;
average_v = average_v * (1.0f / a_flock.size());
return average_v;
}
float flock_radius(vector<BOID>& a_flock){
if (a_flock.size() == 0) return 0;
float max_r = 0;
float dis = 0;
glm::vec3 centroid = flock_centroid(a_flock);
for (auto current = a_flock.begin(); current != a_flock.end(); current++) {
dis = glm::distance(current->pos, centroid);
max_r = max_r < dis ? dis : max_r;
}
return max_r;
}
void init_a_flock(vector<BOID>& a_flock){
int default_cube_length = SPAWN_CUBE_LENGTH*SQRT_2;
int half_cube_length = default_cube_length*0.5f;
for (int i = 0; i < DEFAULT_FLOCK_SIZE; i++){
BOID a_boid;
a_boid.pos[0] += (rand() % default_cube_length) - half_cube_length;
a_boid.pos[1] += (rand() % default_cube_length) - half_cube_length;
a_boid.pos[2] += (rand() % default_cube_length) - half_cube_length;
a_flock.push_back(a_boid);
}
}
void teleport_flock(vector<BOID>& a_flock, GOAL& goal, const glm::vec3& pos) {
int default_cube_length = SPAWN_CUBE_LENGTH*SQRT_2;
int half_cube_length = default_cube_length*0.5f;
srand(SEED);
for (int i = 0; i < DEFAULT_FLOCK_SIZE; i++){
a_flock[i].pos[0] = pos[0] + (rand() % default_cube_length) - half_cube_length;
a_flock[i].pos[1] = pos[1] + (rand() % default_cube_length) - half_cube_length;
a_flock[i].pos[2] = pos[2] + (rand() % default_cube_length) - half_cube_length;
a_flock[i].velocity = SPAWN_VELOCITY;
}
goal.pos = pos;
goal.velocity = DEFAULT_GOAL_SPAWN_VELOCITY;
goal.MOVE_ALONG_X_NEGATIVE = false;
goal.MOVE_ALONG_X_POSITIVE = false;
goal.MOVE_ALONG_Y_NEGATIVE = false;
goal.MOVE_ALONG_Y_POSITIVE = false;
goal.ACCELERATE = false;
goal.DECELERATE = false;
srand(time(NULL));
}
void apply_goal_attraction(vector<BOID>& a_flock, GOAL& a_goal){
glm::vec3 v_modifier(0, 0, 0);
float dis_to_goal;
float boid_speed, goal_speed = glm::length(a_goal.velocity);
for (auto a_boid = a_flock.begin(); a_boid != a_flock.end(); a_boid++) {
v_modifier = a_goal.pos - a_boid->pos;
dis_to_goal = glm::length(v_modifier);
boid_speed = glm::length(a_boid->velocity);
v_modifier = v_modifier*ATTRACTION_WEIGHT;
if (APPROACHING_GOAL < dis_to_goal) { // not near the goal
a_boid->velocity += v_modifier;
} else if (boid_speed > 3*goal_speed
&& boid_speed > BOID_SPEED_FLOOR){ // near goal scenario
a_boid->velocity = a_boid->velocity * 0.95f;
a_boid->velocity += v_modifier;
}
if (boid_speed > 4.0*goal_speed){ //applying absolute cap;
a_boid->velocity += v_modifier;
if(glm::length(a_boid->velocity) > BOID_SPEED_FLOOR){
a_boid->velocity = glm::normalize(a_boid->velocity)
*(9*glm::length(a_boid->velocity)+goal_speed)*0.1f;
}
}
}
}
void print_flock(vector<BOID>& a_flock) {
glm::vec3 centroid = flock_centroid(a_flock);
cout << "Flock's centroid: " << centroid[0] << ", "
<< centroid[1] << ", " << centroid[2] << endl;
float radius = flock_radius(a_flock);
cout << "Flock's radius: " << radius << endl;
cout << endl;
}
void init_flock_mesh(MESH& mesh, GLuint shader, glm::mat4& PROJ_MAT, int &TEXTURE_COUNTER) {
mesh.num_v = 6;
mesh.num_f = 4;
mesh.vertices.resize(6);
for (int i = 0; i< 6; i++) {
mesh.vertices[i].pos = glm::vec3(A_BOID[i][0], A_BOID[i][1],
A_BOID[i][2]);
mesh.vertices[i].tex_coords = glm::vec2(A_BOID_TEX[i][0],
A_BOID_TEX[i][1]);
}
for (int i = 0; i < 12; i++)
mesh.faces.draw_indices.push_back(BOID_INDEX[i]);
mesh.texels.resize(1);
if (!read_ppm(BOID_TEXTURE, &mesh.texels[0])) {
cerr << "BOID_MESH: FAILED TO LOAD TEXTURE" << endl;
}
mesh.texture_counter = TEXTURE_COUNTER;
TEXTURE_COUNTER++;
mesh.compute_face_normal();
mesh.compute_vertex_normal();
mesh.setup(shader, PROJ_MAT);
}
void draw_a_flock(vector<BOID>& a_flock, MESH& mesh, GLuint shader, glm::mat4& MV_MAT,
LIGHT THE_LIGHT, spotlight SPOT_LIGHT, bool if_fp){
THE_LIGHT.light0 = THE_LIGHT.light0*MV_MAT;
for (unsigned int i = 0; i < a_flock.size(); i++){
if (if_fp && i == 0)
continue; // dont draw the boid with headlight when in FP mode
glm::vec3 rotate_normal = glm::normalize(glm::cross(a_flock[i].velocity,
SPAWN_VELOCITY));
float angle = glm::orientedAngle(SPAWN_VELOCITY, a_flock[i].velocity,
rotate_normal);
glm::mat4 transformation = glm::translate(a_flock[i].pos);
transformation = glm::rotate(transformation, angle, rotate_normal);
mesh.draw(shader, MV_MAT, transformation, THE_LIGHT, SPOT_LIGHT);
}
}
| true |
d2ffdf764213b9f9fa7982ffc6de80615d44c89e | C++ | nameisshenlei/NewMemPool | /NewMemPool/ObjectBase.cpp | UTF-8 | 1,099 | 2.84375 | 3 | [] | no_license | #include "ObjectBase.h"
ObjectBase::ObjectBase(uint8_t* pData, uint32_t iBuffSize, MemPool<ObjectBase>* pPool /* = nullptr */)
: m_pData(pData)
, m_iBuffSize(iBuffSize)
, m_pPool(pPool)
{
}
ObjectBase::~ObjectBase()
{
m_pData = nullptr;
}
uint8_t* ObjectBase::GetData() const
{
if (m_iRefCount == 0)
return nullptr;
return m_pData;
}
void ObjectBase::RefPacket()
{
std::lock_guard<std::mutex> lock(m_mutexLock);
m_iRefCount++;
}
void ObjectBase::UnrefPacket()
{
std::lock_guard<std::mutex> lock(m_mutexLock);
--m_iRefCount;
}
bool ObjectBase::PacketValid()
{
return !!m_iRefCount;
}
bool ObjectBase::AppendData(const uint8_t* pData, const int iSize)
{
std::lock_guard<std::mutex> lock(m_mutexLock);
if (m_iRefCount != 0)
return false;
++m_iRefCount;
memcpy(m_pData, pData, iSize);
return true;
}
ObjectBase* ObjectBase::Ref()
{
if (m_iRefCount == 0)
return nullptr;
RefPacket();
return this;
}
void ObjectBase::Unref()
{
if (m_pPool)
{
m_pPool->Push(this);
}
else
{
DeleteThis(this);
}
}
void ObjectBase::DeleteThis(ObjectBase* pThis)
{
delete pThis;
} | true |
f4d57dd9a627c3d9974b57ff25b9be1032f64f6a | C++ | hwoodiwiss/HolidayHelper | /HolidayHelperLib/ISerializable.h | UTF-8 | 1,277 | 2.84375 | 3 | [] | no_license | #pragma once
#include <iostream>
#include "Common.h"
namespace HolidayHelper::Persistence
{
//Abstract interface for serializing objects to disk
class DllExport ISerializable
{
public:
//Pure virtual functions that have to be overloaded in derived classes
virtual std::ostream& Serialize(std::ostream& os) = 0;
virtual std::istream& Deserialize(std::istream& is) = 0;
//virtual std::ostream& Serialize(map<string, string>& om) = 0;
//virtual std::istream& Deserialize(map<string, string>& im) = 0;
//Out stream operator, allows operator based stream interaction for ISerializabe objects
friend std::ostream& operator <<(std::ostream& os, ISerializable& outObj)
{
//This will call the ISerializable::Serialize as defined in a derived object
return outObj.Serialize(os);
}
//In stream operator, allows operator based stream interaction for ISerializabe objects
friend std::istream& operator >>(std::istream& is, ISerializable& inObj)
{
//This will call the ISerializable::Deserialize as defined in a derived object
return inObj.Deserialize(is);
}
protected:
//Helper function for properly reading in a string from istream
inline std::string InStreamToString(std::istream& in);
};
} | true |
9de3f07b71c4ae519e0c337f8f43b5581cc6924c | C++ | mcduenash/herramientasclase | /agosto16/serieconverg.cpp | UTF-8 | 562 | 3.640625 | 4 | [] | no_license | //Este programa saca una tabla de datos que graficados muestran para que N converge la expansion de Taylor de la funcion exponencial
#include<iostream>
#include<cmath>
int factorial(int m){
if (m==0){
return 1;
}
else{
int f=1;
for (int i=1; i<=m; i++){
f*=i;
}
return f;
}
}
double suma(double x,int N){
double S=0;
for (int i=0; i<=N ;i++){
S+=std::pow(-1.0,i)*std::pow(x,i)/factorial(i);
}
return S;
}
int main (void){
for (int i; i<=100;i++){
std::cout<<i<<"\t"<<suma(100.0,i)<<"\n";
}
return 0;
}
| true |
1a0449cdc5b1a94b8a607a1324b6f3de842b8767 | C++ | klarmann2018/sams_teach_c-_in_one_hour_a_day | /sams_teach_c++_in_one_hour_a_day/04/listing04_04.cpp | UTF-8 | 1,181 | 3.640625 | 4 | [] | no_license | /*
* =====================================================================================
*
* Filename: LISTing04_04.cpp
*
* Description: Creating a Dynamic Array of Integers and Adding Values
* Dynamically
*
* Version: 1.0
* Created: 2018年09月04日 17时33分00秒
* Revision: none
* Compiler: gcc
*
* Author: bo lee
* Organization:
*
* =====================================================================================
*/
#include <iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> DynArrNums(3);
DynArrNums[0]=365;
DynArrNums[1]=-421;
DynArrNums[2]=789;
cout<<"Number of integers in Array: " << DynArrNums.size()<<endl;
cout<<"the array elements: " << DynArrNums[0] << "," << DynArrNums[1]<<","<<DynArrNums[2]<<endl;
cout << "Enter another number for the array" << endl;
int AnotherNum = 0;
cin >> AnotherNum;
DynArrNums.push_back(AnotherNum);
cout << "Number of integers in array: " << DynArrNums.size()<< endl;
cout << "Last element in array: ";
cout << DynArrNums[DynArrNums.size()-1] << endl;
return 0;
}
| true |
1579cac521f15244da7e9d0c59ee7419afc93e90 | C++ | Juli199696/AntSimCPlusPlusLearning | /main.cpp | UTF-8 | 25,310 | 2.703125 | 3 | [
"Unlicense"
] | permissive | /* 02.04.2014 Ant Simulation version : 0.5 Dev Autor: Julian Märtin
==============================================================================================================================
Allgemeine Programm Infos wie Changelog und vorhandene Funktionen.
==============================================================================================================================
New functions | +
Changed functions | #
Deleted functions | -
Vorhandene Funktionen:
-------------------------------------------------------------------------------------------------------------------------------
Ameisensterben : Ameisen können sterben wenn Sie zu wenig Nahrung/ Wasser haben.
BewegeAmeise : Ameisen werden zufällig bewegt.
Lebensmittel : Ist für den verbrauch und das hinzufügen von Lebensmitteln wie Nahrung und Wasser zuständig.
Main : Startet das Grundprogramm.
Nachrichten : News System informiert über aktuelle geschehnisse.
SetMyCurser : Ist für das Setzten des Cursers in der Console verantwortlich und kann jederzeit verändert werden.
Simulation : Lässt die Zeit laufen und ist mit für die Bewegung der Ameisen zuständig.
Spielfeld : Baut / setzt den Spielfeld Rand und Objekte.
Start : Ist für das Hauptmenu zuständig.
Highscore : Es ist nun möglich den Highscore vom letzten Spiel in einer Text Datei zu speichern und nachträglich wieder aufzurufen.
Changelog 15.10.2017:
*Inital Commit on Github.
+ Bugfixes for crashs and the ability to restart the simulation.
+ Ant Shop (You can now buy Food and Water for your ants to stay alive and rise your highscore!
+ Money money money! I have implemented a simple economy system but its not ready to use yet. You can use that money to buy new stuff from the shop or expand your current ant colony.
+ You can have highscores saved in text file!
+ I have added a game.cfg file which does not contain any usefull commands at the moment but will be handy to have later on.
# Changes to simulation itself (Add shop, add new variables for shop).
# Highscore now can be watched every round without the game to be restarted.
# General code cleanup.
- New Born Ants, for now i have remove the feature to create new ants when you got enough of food and water. This will be added later on again!
- Removed some unused variables and old code
==============================================================================================================================*/
#include <iostream>
#include <conio.h> // für getch()
#include <windows.h>
#include <fstream>
#include <string>
#include "rlutil.h"
//#include "global.h"
int wasser;
int nahrung;
int glasses;
int anz; //Anzahl der Ameisen Random
int happy;
int tot;
int bornant;
int regen;
int sonne;
int sturm;
int blaetter;
int angreifer;
int ende;
int ameisenmax;
int gamerunning;
int geld;
using namespace std;
//Generell nutzbare Variablen
/*
==============================================================================================================================
Setzt die Position des Cursers um Zeichen zu setzen.
==============================================================================================================================
*/
void SetMyCursor(short x, short y)
{
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
COORD pos;
pos.X = x;
pos.Y = y;
SetConsoleCursorPosition(hStdOut,pos);
}
/*
==============================================================================================================================
Spielfeld wird erstellt.
==============================================================================================================================
*/
void spielfeld()
{
SetMyCursor(1,23); // Setzt die Untermenü Linie
{
for (int i=0; i<79; i++)
{
cout << (char)205 ;
}
SetMyCursor(1,0); // Setzt die obere Spielfeldlinie
for (int i=0; i<79; i++)
{
cout << (char)205 ;
}
for (int i=0; i<23; i++) // Setzt die linke Spielfeldlinie
{
SetMyCursor(0,i);
cout << (char)186 ;
SetMyCursor(79,i); // Setzt die rechte Spielfeldlinie
cout << (char)186 ;
}
SetMyCursor(0,0); //Setzt die linke obere Ecke ╔
cout << (char)201 ;
SetMyCursor(79,0); //Setzt obere rechte Ecke ╗
cout << (char)187 ;
SetMyCursor(0,23); //Setzt untere linke Ecke ╚
cout << (char)200 ;
SetMyCursor(79,23); //Setzt untere rechte Ecke ╝
cout << (char)188 ;
}
}
/*
==============================================================================================================================
Ameisen Position wird übergeben und neu "geschrieben".
==============================================================================================================================
*/
void BewegeAmeise(int& altPosX, int& altPosY,int neuPosX, int neuPosY) //Bei & wird findet eine übergabe statt
{
SetMyCursor (altPosX, altPosY); //altePos löschen
cout << " ";
SetMyCursor (neuPosX, neuPosY); //Cursor neu plazieren...
cout << "*"; // ...und neu schreiben
altPosX = neuPosX;
altPosY = neuPosY;
}
/*
==============================================================================================================================
Ameisen sterben
==============================================================================================================================
*/
void Ameisensterben()
{
if (nahrung > 90)
{
/* bornant = rand() %10;
if (bornant == 1)
{
}
bornant = 0; */
}
if (nahrung < 10)
{
tot = rand() %10 +1;
if (tot == 1)
{
if (anz > 0)
{
anz--;
}
}
}
if (wasser < 10)
{
tot = rand() %10 +1;
if (tot == 1)
{
if (anz > 0)
{
anz--;
}
}
}
}
/*
==============================================================================================================================
Lebensmittel verbrauch
==============================================================================================================================
*/
void Lebensmittel()
{
int verbrauch ;
Ameisensterben();
SetMyCursor(2,24);
{
cout << "Wasser:" << wasser << "%";
cout << " ";
}
/* Ich hab keine Ahnung mehr wofür ich die kacke gebraucht habe.. Meh
int x[anz];
int y[anz];
char ameisen[anz];
SetMyCursor(15,24);
*/
{
cout << "Nahrung:" << nahrung << "%";
cout << " ";
}
verbrauch = rand() %55 +1;
if (verbrauch == 1)
{
if (nahrung > 0)
{
nahrung--;
}
}
if (verbrauch == 2)
{
if (wasser > 0)
{
wasser--;
}
}
}
/*
==============================================================================================================================
Nachrichten / Ameisen Informationen
==============================================================================================================================
*/
void Nachrichten()
{
if (nahrung > 75)
{
happy = 3;
}
if (nahrung > 50)
{
happy = 2;
}
if (nahrung > 25)
{
happy = 1;
}
if (nahrung < 15)
{
happy = 0;
}
SetMyCursor(1,25);
{
cout << "1 Ants 2 Shop 3 Environment";
}
SetMyCursor(1,26);
{
cout << "Nachrichten: ";
}
if (nahrung < 10)
{
SetMyCursor(1,27);
cout << "Es fehlt an Nahrung! ";
if (nahrung > 10)
cout << " ";
}
if (wasser < 10)
{
SetMyCursor(1,28);
cout << "Es fehlt an Wasser! ";
if (wasser > 10)
cout << " ";
}
if (sturm == 1)
{
SetMyCursor(1,29);
cout << "Ein Sturm wuetet in deiner Kolonie.";
}
if (sturm == 0)
{
SetMyCursor(1,29);
cout << " ";
}
}
//Befehle
void shop()
{
string yesorno;
int amounttobuy = 0;
int leavesinstock = rand()%(25-1 + 1) + 1;
int waterinstock = rand()%(25-1+ 1) + 1;
int glassesinstock = rand()%(3-1 + 1) + 1;
int sales = rand()%(3-1 + 1) + 1;
system("cls");
int shopping = 1;
int checkout = 10;
while (shopping == 1)
{
SetMyCursor(0,1);
{
cout << "Welcome to the ant shop" << endl << endl << "Here you can buy some good stuff for your ant colony" << endl << endl << "Todays sales are:" << endl;;
if (sales == 1)
{
cout << "Leaves (5) " << leavesinstock << " x";
}
if (sales == 2)
{
cout << "Water (6) " << leavesinstock << " x";
}
if (sales == 3)
{
cout << "Glasses (7) " << leavesinstock << " x";
}
SetMyCursor(1,18);
{
cout << "Buy stuff with the shown key.";
}
SetMyCursor(1,20);
{
cout << "Press 0 to go back";
}
if(GetKeyState('5') & 0x8000/*check if high-order bit is set (1 << 15)*/)
{
if (geld > 0)
{
SetMyCursor(1,12);
checkout = 0;
{
while (checkout == 0)
{
cout << "How much you wanna buy?" << endl;
cin >> amounttobuy;
if (amounttobuy > leavesinstock)
{
cout << "You cant buy more than " << leavesinstock << "!";
getch();
checkout = 10;
}
if (amounttobuy <= 0)
{
cout << "You cant buy less than one!";
getch();
checkout = 10;
}
else
{
if (sales == 1)
{
cout << "Are you sure you want to buy " << amounttobuy << " of leaves?" << endl;
}
cin >> yesorno;
if (yesorno == "Y" || yesorno == "y" || yesorno == "yes" || yesorno == "Yes")
{
nahrung = nahrung + amounttobuy;
cout << "You bought " << amounttobuy << " of " << sales << endl;
checkout = 10;
}
}
}
}
}
else
{
cout << "You dont got enough money!";
}
}
if(GetKeyState('6') & 0x8000/*check if high-order bit is set (1 << 15)*/)
{
if (geld > 0)
{
SetMyCursor(1,12);
checkout = 1;
{
while (checkout == 1)
{
cout << "How much you wanna buy?" << endl;
cin >> amounttobuy;
if (amounttobuy > waterinstock)
{
cout << "You cant buy more than " << waterinstock << "!";
getch();
checkout = 10;
}
if (amounttobuy <= 0)
{
cout << "You cant buy less than one!";
getch();
checkout = 10;
}
else
{
if (sales == 2)
{
cout << "Are you sure you want to buy " << amounttobuy << " of water?" << endl;
}
cin >> yesorno;
if (yesorno == "Y" || yesorno == "y" || yesorno == "yes" || yesorno == "Yes")
{
wasser = wasser + amounttobuy;
cout << "You bought " << amounttobuy << " of " << sales << endl;
checkout = 10;
}
}
}
}
}
else
{
cout << "You dont got enough money!";
}
}
if(GetKeyState('7') & 0x8000/*check if high-order bit is set (1 << 15)*/)
{
if (geld > 0)
{
SetMyCursor(1,12);
checkout = 2;
{
while (checkout == 2)
{
cout << "How much you wanna buy?" << endl;
cin >> amounttobuy;
if (amounttobuy > glassesinstock)
{
cout << "You cant buy more than " << glassesinstock << "!";
getch();
checkout = 10;
}
if (amounttobuy <= 0)
{
cout << "You cant buy less than one!";
getch();
checkout = 10;
}
else
{
if (sales == 3)
{
cout << "Are you sure you want to buy " << amounttobuy << " of glasses?" << endl;
}
cin >> yesorno;
if (yesorno == "Y" || yesorno == "y" || yesorno == "yes" || yesorno == "Yes")
{
glasses = glasses + amounttobuy;
cout << "You bought " << amounttobuy << " of " << sales << endl;
checkout = 10;
}
}
}
}
}
else
{
cout << "You dont got enough money!";
}
}
}
getch();
if(GetKeyState('0') & 0x8000/*check if high-order bit is set (1 << 15)*/)
{
shopping = 0;
gamerunning = 1;
system("cls");
spielfeld();
}
}
}
void hotkeys ()
{
if(GetKeyState('1') & 0x8000/*check if high-order bit is set (1 << 15)*/)
{
gamerunning = 0;
while (gamerunning == 0)
{
system("cls");
SetMyCursor(0,1);
{
cout << "Ants Info" << endl << endl << "Here you can see how your ants are feeling and what they need!" << endl << "Please check here regulary for happy ants." << endl;
cout << "Your colony have " << anz <<" ants." << endl << endl << "You got " << nahrung << " food." << endl << "You got " << wasser << " water." << endl;
if (happy == 3)
{
cout << "Your ants are very happy." << endl << "Good job!";
}
if (happy == 2)
{
cout << "Everything is okay." << endl << "No need to worry.";
}
if (happy == 1)
{
cout << "Your ants need some love." << endl << "Watch your food and water.";
}
if (happy == 0)
{
cout << "Your ants are in danger :(" << endl << "You need to do something now!";
}
}
SetMyCursor(1,20);
{
cout << "Press 0 to go back";
}
getch();
if(GetKeyState('0') & 0x8000/*check if high-order bit is set (1 << 15)*/)
{
gamerunning = 1;
system("cls");
spielfeld();
}
}
}
if(GetKeyState('2') & 0x8000/*check if high-order bit is set (1 << 15)*/)
{
gamerunning = 2;
while (gamerunning == 2)
{
shop();
}
}
}
/*
==============================================================================================================================
Ameisen bewegung und grundfunktionen
==============================================================================================================================
*/
void simulation()
{
int (start());
srand (time(NULL));
anz = rand()%50+3;
int x[anz];
int y[anz];
char ameisen[anz];
//const int anz = 5; //Anzahl der Ameisen
for (int i = 0; i < anz; i++) //Ameisen werden hinzugefügt
{
ameisen[i] = '*';
x[i] = rand()%77+2; //Ameisen Spawn
y[i] = rand()%21+2;
}
while (ende == 0) //Solange das Spiel nicht beendet ist, führe das aus.
{
for ( int zeit = 1; zeit++;)
{
hotkeys ();
Lebensmittel();
Nachrichten();
SetMyCursor(40,24);
{
cout << "Ameisen:" << anz;
cout << " ";
}
int zufallszahl;
SetMyCursor(29,24);
{
cout << "Tage:" << zeit;
_sleep(10);
cout << " ";
}
for (int i = 0; i < anz; i++)
{
zufallszahl = rand() %9 +1; //Hier wird die Ameise zufällig bewegt.
if (zufallszahl == 1 && x[i] != 78 && y[i] !=22)
BewegeAmeise(x[i], y[i], x[i]+1, y[i]+1);
if (zufallszahl == 2 && x[i] != 2 && y[i] != 2)
BewegeAmeise(x[i], y[i], x[i]-1, y[i]-1);
if (zufallszahl == 3 && x[i] != 2)
BewegeAmeise(x[i], y[i], x[i]-1, y[i]);
if (zufallszahl == 4 && y[i] != 2)
BewegeAmeise(x[i], y[i], x[i], y[i]-1);
if (zufallszahl == 4 && x[i] != 78)
BewegeAmeise(x[i], y[i], x[i]+1, y[i]);
if (zufallszahl == 5 && x[i] != 78 && y[i] != 2)
BewegeAmeise(x[i], y[i], x[i]+1, y[i]-1);
if (zufallszahl == 6 && x[i] != 2 && y[i] != 22)
BewegeAmeise(x[i], y[i], x[i]-1, y[i]+1);
if (zufallszahl == 7 && y[i] != 22)
BewegeAmeise(x[i], y[i], x[i], y[i]+1);
if (zufallszahl == 8) {};
}
/*
==============================================================================================================================
Spielende
==============================================================================================================================
*/
if (anz == 0)
{
SetMyCursor(0,5);
{
_sleep(2000);
system("cls");
cout << "GAME OVER" << endl << "You archived " << zeit << " days." << endl << "You got " << nahrung << " food and " << wasser << " water." << endl << "Your farm reached " << anz << " ants.";
_sleep(5000);
ofstream score;
score.open ("score.txt");
score << "You archived " << zeit << " days." << endl << "You got " << nahrung << " food and " << wasser << " water." << endl << "Your farm reached " << anz << " ants.";
score.close();
system("cls");
ende = 1;
}
}
if (ende == 1)
{
start();
}
}
}
}
/*
==============================================================================================================================
Startprogramm zum ausführen der Simulation.
==============================================================================================================================
*/
void start()
{
ofstream cfgconfig;
cfgconfig.open ("game.cfg");
cfgconfig << "test";
cfgconfig.close();
cout << " ____________________________________________________ " << endl;
cout << "|Willkommen zur Ameisen Simulation! |" << endl;
cout << "|Bitte waehle ein nummer. |" << endl;
cout << "|____________________________________________________|" << endl; //Start Menü
cout << "| |" << endl;
cout << "|1. Start |" << endl;
cout << "|2. Ende |" << endl;
cout << "|3. Highscore |" << endl;
cout << "|____________________________________________________|" << endl;
SetMyCursor(60,26); //Text für untere Leiste
{
cout << "Ant Sim. v. 1.0 Dev." ;
}
int zahl;
SetMyCursor(1,10);
cin >> zahl;
if (zahl == 1) //Bedingung für ausführung der Schleife 1, startet die Simulation
{
wasser = 50;
nahrung = 50;
glasses = 0;
anz = 0; //Anzahl der Ameisen Random
happy = 1;
tot = 0;
bornant = 0;
regen = 0;
sonne = 0;
sturm = 0;
blaetter = 0;
angreifer = 0;
ende = 0;
ameisenmax = 0;
gamerunning = 1;
geld = 50;
system("cls");
spielfeld();
simulation();
}
if (zahl == 2) //Bedingung für ausführung der Schleife 2, beendet das Programm
{
exit(0);
}
if (zahl == 3) //Highscore
{
system("cls");
string line;
ifstream score ("score.txt");
if (score.is_open())
{
while ( getline (score,line) )
{
cout << line << '\n';
}
score.close();
getch();
system("cls");
start();
}
else cout << "Unable to open file";
}
}
/*
==============================================================================================================================
Das Hauptprogramm wird inizialisiert und führt die unter Programme aus.
==============================================================================================================================
*/
int main()
{
HANDLE console; //Dient zur vergrößerung des Consolen Fensters
COORD screenBufferSize;
SMALL_RECT windowSize;
console = GetStdHandle(STD_OUTPUT_HANDLE);
screenBufferSize.X = 81;
screenBufferSize.Y = 29;
SetConsoleScreenBufferSize(console, screenBufferSize);
windowSize.Left = 0;
windowSize.Top = 0;
windowSize.Right = 80;
windowSize.Bottom = 30;
SetConsoleWindowInfo(console, true, &windowSize);
start(); //Führt das unterprogramm start aus
return 0;
}
| true |
dee32bc573fbe461e17e5c32d1edbf0b222f8dab | C++ | Hmilner1/MarioProject | /Mario/Mario/LevelMap.cpp | UTF-8 | 954 | 3.375 | 3 | [] | no_license | #include "LevelMap.h"
LevelMap::LevelMap(int map[MAP_HEIGHT][MAP_WIDTH])
{
//sets the map height and width
m_map = new int* [MAP_HEIGHT];
for (unsigned int i = 0; i < MAP_HEIGHT; i++)
{
m_map[i] = new int[MAP_WIDTH];
}
//populate the array
for (unsigned int i = 0; i < MAP_HEIGHT; i++)
{
for (unsigned int j = 0; j < MAP_WIDTH; j++)
{
m_map[i][j] = map[i][j];
}
}
}
LevelMap::~LevelMap()
{
for (unsigned int i = 0; i < MAP_HEIGHT; i++)
{
delete[] m_map[i];
}
delete[]m_map;
for (unsigned int i = 0; i < MAP_WIDTH; i++)
{
delete[] m_map[i];
}
}
int LevelMap::GetTileAt(unsigned int h, unsigned int w)
{
//checks what the tile is at a certian point and returns it
if (h < MAP_HEIGHT && w < MAP_WIDTH)
{
return m_map[h][w];
}
return 0;
}
void LevelMap::ChangeTileAt(unsigned int row, unsigned int column, unsigned int new_value)
{
//changes tile for new one at a certain point
m_map[row][column] = new_value;
} | true |
a7029a71f9115d854f09501c631c456c2c549e27 | C++ | qeedquan/challenges | /opengl4-mbsoftworks/common/static_meshes_3d/primitives/cone.h | UTF-8 | 832 | 2.78125 | 3 | [
"MIT"
] | permissive | #ifndef _CONE_H_
#define _CONE_H_
class Cone : public StaticMesh3D
{
public:
void init(Vec3f directix, Vec3f apex, float height, float radius, int num_slices,
bool has_positions, bool has_texcoords, bool has_normals);
void render();
void render_points();
Vec3f directix; // Axis defined as normalized vector from base to apex
Vec3f apex; // Point at the top of the cone
float radius; // Directix radius
int num_slices; // Number of slices
float height; // Height of the cone
int num_vertices_side; // How many vertices to render sides of the cone (represented by line connecting the apex point to the rotation of the directix vector)
int num_vertices_bottom; // How many vertices to render bottom circular portion of the cone
int num_vertices_total; // Number of vertices which is the sum of the above
};
#endif
| true |
1ec67eec8907fb21e6b69bda63d2472593ff229c | C++ | Carrazza/Tutoriais | /C++/7Classes_schenenigans.cpp | UTF-8 | 847 | 3.625 | 4 | [] | no_license | //o "a" colocado na função set_a não é o mesmo, por precaução, coloca o namespace
#include <iostream>
using namespace std;
class doubts
{
public:
int a;
int set_a(int a)
{
printf("'a' na função set= %d \n" , a);
a = a;
}
int set_a_com_namespace(int a)
{
doubts::a = a;
}
// int teste_namespace(int a)
// {
// printf("namespace stuffo mandado = %d" , a);
// }
};
int main()
{
doubts gon_try;
printf("'a' antes de tudo = %d\n", gon_try.a);
gon_try.set_a(3);
printf("'a' depois de set_a = %d\n", gon_try.a);
gon_try.set_a_com_namespace(10);
printf("'a' depois de set_a com namespace = %d \n", gon_try.a );
// no funfa ;-; doubts::teste_namespace(1000);
}
| true |
1a09c02e45ec9174483ad6ced9fc1d6a7dbc18d8 | C++ | fhartvigmark/BachelorProj | /Snap-4.1/snap-exp/test-dev/TableTest.cpp | UTF-8 | 2,168 | 2.546875 | 3 | [] | no_license | #include "Snap.h"
int main(){
TTableContext Context;
// create scheme
Schema AnimalS;
AnimalS.Add(TPair<TStr,TAttrType>("Animal", atStr));
AnimalS.Add(TPair<TStr,TAttrType>("Size", atStr));
AnimalS.Add(TPair<TStr,TAttrType>("Location", atStr));
AnimalS.Add(TPair<TStr,TAttrType>("Number", atInt));
TIntV RelevantCols;
RelevantCols.Add(0);
RelevantCols.Add(1);
RelevantCols.Add(2);
// create table
PTable T = TTable::LoadSS(AnimalS, "tests/animals.txt", Context, RelevantCols);
//PTable T = TTable::LoadSS("Animals", AnimalS, "animals.txt");
T->Unique("Animal");
TTable Ts = *T; // did we fix problem with copy-c'tor ?
//PTable Ts = TTable::LoadSS("Animals_s", AnimalS, "../../testfiles/animals.txt", RelevantCols);
//Ts->Unique(AnimalUnique);
// test Select
// create predicate tree: find all animals that are big and african or medium and Australian
TAtomicPredicate A1(atStr, true, EQ, "Location", "", 0, 0, "Africa");
TPredicateNode N1(A1); // Location == "Africa"
TAtomicPredicate A2(atStr, true, EQ, "Size", "", 0, 0, "big");
TPredicateNode N2(A2); // Size == "big"
TPredicateNode N3(AND);
N3.AddLeftChild(&N1);
N3.AddRightChild(&N2);
TAtomicPredicate A4(atStr, true, EQ, "Location", "", 0, 0, "Australia");
TPredicateNode N4(A4);
TAtomicPredicate A5(atStr, true, EQ, "Size", "", 0, 0, "medium");
TPredicateNode N5(A5);
TPredicateNode N6(AND);
N6.AddLeftChild(&N4);
N6.AddRightChild(&N5);
TPredicateNode N7(OR);
N7.AddLeftChild(&N3);
N7.AddRightChild(&N6);
TPredicate Pred(&N7);
TIntV SelectedRows;
Ts.Select(Pred, SelectedRows);
TStrV GroupBy;
GroupBy.Add("Location");
T->Group(GroupBy, "LocationGroup");
GroupBy.Add("Size");
T->Group(GroupBy, "LocationSizeGroup");
T->Count("LocationCount", "Location");
PTable Tj = T->Join("Location", Ts, "Location");
TStrV UniqueAnimals;
UniqueAnimals.Add("Animals_1.Animal");
UniqueAnimals.Add("Animals_2.Animal");
Tj->Unique(UniqueAnimals, false);
//print table
T->SaveSS("tests/animals_out_T.txt");
Ts.SaveSS("tests/animals_out_Ts.txt");
Tj->SaveSS("tests/animals_out_Tj.txt");
return 0;
}
| true |
1ccef3f6887e1aaca4c10d34e5df67ff4e64298a | C++ | tonychiu25/monopoly | /model/players/player.cpp | UTF-8 | 503 | 2.890625 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string.h>
using namespace std;
#include "player.h"
Player::Player(int i, std::string n) {
id = i;
name = n;
}
int Player::getId() {
return id;
}
int Player::getBoardPosition() {
return boardPosition;
}
int Player::getCashAmount() {
return cash;
}
std::string Player::getName() {
return name;
}
void Player::setBoardPosition(int pos) {
boardPosition = pos;
}
void Player::setCash(int amount) {
cash = amount;
}
| true |
81e956f793782ec9254b5e87b5556b722f056d1d | C++ | TheNitesWhoSay/EUD-Ops | /EUD-Ops/src/CommonFiles/Debug.cpp | UTF-8 | 3,426 | 2.859375 | 3 | [
"MIT"
] | permissive | #include "Debug.h"
#include "CommonFiles.h"
#include <cstdarg>
#include <cstdio>
#include <cstring>
#include <string>
#include <crtdbg.h>
bool debugging = false;
const u32 MAX_ERROR_LENGTH = 512;
char LastError[MAX_ERROR_LENGTH]; // Purposed for user-based errors
char LastErrorLoc[MAX_ERROR_LENGTH]; // Purposed for debugging internal errors
void PrintError(const char* file, unsigned int line, const char* msg, ...)
{
va_list args;
va_start(args, msg);
std::vsnprintf(LastError, MAX_ERROR_LENGTH, msg, args);
std::snprintf(LastErrorLoc, MAX_ERROR_LENGTH, "File: %s\nLine: %u", file, line);
//std::cout << LastErrorLoc << " | " << LastError << std::endl;
va_end(args);
}
void ShoutError(const char* file, unsigned int line, const char* msg, ...)
{
va_list args;
va_start(args, msg);
std::vsnprintf(LastError, MAX_ERROR_LENGTH, msg, args);
std::snprintf(LastErrorLoc, MAX_ERROR_LENGTH, "File: %s\nLine: %u", file, line);
//std::cout << LastErrorLoc << " | " << LastError << std::endl;
//MessageBox(NULL, LastError, LastErrorLoc, MB_OK | MB_ICONEXCLAMATION);
va_end(args);
}
#ifdef CHKD_DEBUG
void CheckInvariant(bool condition, const char* file, int line)
{
char invarError[MAX_ERROR_LENGTH];
std::snprintf(invarError, MAX_ERROR_LENGTH, "Invariant Check Failed!\n\nFile: %s\nLine: %i", file, line);
if ( condition == false )
MessageBox(NULL, invarError, "Error!", MB_OK|MB_ICONEXCLAMATION);
}
#endif
void Error(const char* ErrorMessage)
{
MessageBox(NULL, ErrorMessage, "Error!", MB_OK | MB_ICONEXCLAMATION);
}
void Coord(s32 x, s32 y, const char* title = "Coordinates")
{
char message[256];
std::snprintf(message, sizeof(message), "(x, y) --> (%d, %d)", x, y);
MessageBox(NULL, message, title, MB_OK);
}
void mb(const char* text)
{
MessageBox(NULL, text, "Message", MB_OK);
}
void mb(const char* text, const char* title)
{
MessageBox(NULL, text, title, MB_OK);
}
void mb(int i, const char* text)
{
MessageInt(i, text);
}
void mb(int i, const char character)
{
char msg[2] = { character, '\0' };
MessageBox(NULL, msg, std::to_string(i).c_str(), MB_OK);
}
void Debug()
{
debugging = true;
}
void DebugIf(bool condition)
{
debugging = condition;
}
void NoDebug()
{
debugging = false;
}
void db(const char* text)
{
if ( debugging )
MessageBox(NULL, text, "Message", MB_OK);
}
void db(int i, const char* text)
{
if ( debugging )
MessageInt(i, text);
}
void Message(std::string text)
{
MessageBox(NULL, text.c_str(), "Message", MB_OK);
}
void Message(std::string text, std::string caption)
{
MessageBox(NULL, text.c_str(), caption.c_str(), MB_OK);
}
void MessageInt(int integer, const char* caption)
{
MessageBox(NULL, std::to_string(integer).c_str(), caption, MB_OK);
}
void MessageChar(char character, int pos)
{
std::string posStr(std::to_string(pos));
std::string chrStr(std::to_string(character));
MessageBox(NULL, chrStr.c_str(), posStr.c_str(), MB_OK);
}
void FindLeaks()
{
#ifdef CHKD_DEBUG
if ( _CrtDumpMemoryLeaks() )
MessageBox(NULL, "CrtDumpMemoryLeaks Activated", "Message", MB_OK);
else
MessageBox(NULL, "No Leaks!", "Message", MB_OK);
#endif
}
bool RetryError(const char* text)
{
return MessageBox(NULL, text, "Error!", MB_YESNO|MB_ICONEXCLAMATION) == IDYES;
}
| true |
ae501ece74ce2d0ed5cd2cc4b9da86f5388c995f | C++ | Modesty-Li/leetcode | /leetcode/editor/cn/1518-water-bottles.cpp | UTF-8 | 1,272 | 2.984375 | 3 | [] | no_license | //小区便利店正在促销,用 numExchange 个空酒瓶可以兑换一瓶新酒。你购入了 numBottles 瓶酒。
//
// 如果喝掉了酒瓶中的酒,那么酒瓶就会变成空的。
//
// 请你计算 最多 能喝到多少瓶酒。
//
//
//
// 示例 1:
//
//
//
// 输入:numBottles = 9, numExchange = 3
//输出:13
//解释:你可以用 3 个空酒瓶兑换 1 瓶酒。
//所以最多能喝到 9 + 3 + 1 = 13 瓶酒。
//
//
// 示例 2:
//
//
//
// 输入:numBottles = 15, numExchange = 4
//输出:19
//解释:你可以用 4 个空酒瓶兑换 1 瓶酒。
//所以最多能喝到 15 + 3 + 1 = 19 瓶酒。
//
//
// 示例 3:
//
// 输入:numBottles = 5, numExchange = 5
//输出:6
//
//
// 示例 4:
//
// 输入:numBottles = 2, numExchange = 3
//输出:2
//
//
//
//
// 提示:
//
//
// 1 <= numBottles <= 100
// 2 <= numExchange <= 100
//
// Related Topics 贪心算法
// 👍 49 👎 0
#include "include/headers.h"
using namespace std;
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public:
int numWaterBottles(int numBottles, int numExchange) {
}
};
//leetcode submit region end(Prohibit modification and deletion)
int main()
{
Solution s;
} | true |
3273d0f18a6c98a67fc74e467f06afc3c460eaae | C++ | shams7734/ISSLab | /idea.cpp | UTF-8 | 6,548 | 2.78125 | 3 | [] | no_license | /* Implementation of IDEA
2015kucp1034
*/
#include<bits/stdc++.h>
using namespace std;
// Function to convert binary to integer
int convertBinaryToInt(int *a,int n)
{
int x=0,i;
for(i=0;i<n;i++){
x = x + a[i]*pow(2,(n-1)-i);
}
return x;
}
//Function to convert integer to binary
void convertIntToBinary(long int x,int *a,int n)
{
int i;
for(i = 0;i<n;i++){
a[n-1-i] = (x%2);
x = x/2;
}
}
int main()
{
int i,j,l;
int key[128]={1,0,0,0,1,0,1,0,0,1,1,1,
0,0,1,1,1,1,0,1,1,0,1,1,
1,1,1,0,1,1,0,1,0,1,1,1,
0,0,0,1,0,1,0,1,0,1,1,0,
1,0,1,0,1,1,1,0,1,0,0,0,
1,0,0,0,1,1,0,0,1,0,1,1,
1,0,1,1,1,0,1,0,0,0,1,0,
0,0,0,1,0,1,1,1,0,1,0,1,
1,1,1,0,1,1,1,0,1,1,0,1,
1,0,1,0,1,1,1,0,0,1,0,1,
0,1,0,1,0,1,1,1
};
int text[64]={1,1,0,1,1,1,0,1,
0,0,1,1,0,1,0,1,
0,1,0,1,1,1,0,1,
0,1,1,1,0,1,0,0,
1,0,1,1,1,0,1,0,
1,1,1,1,0,0,1,1,
0,1,1,0,1,1,1,0,
1,1,1,0,0,0,1,0
};
int key_mod[128];
int small_texts[4][16];
int small_keys[52][16];
l=0;
for(i=0;i<8;i++)
{
for(j=0;j<16;j++)
{
small_keys[i][j]=key[l];
l++;
}
}
// key rotation first
for(j=0;j<128;j++)
{
key_mod[j]=key[(j-25+128)%128];
}
for(i=0;i<128;i++)
key[i]=key_mod[i];
l=0;
for(i=8;i<16;i++)
{
for(j=0;j<16;j++)
{
small_keys[i][j]=key[l];
l++;
}
}
// key rotation second
for(j=0;j<128;j++)
{
key_mod[j]=key[(j-25+128)%128];
}
for(i=0;i<128;i++)
key[i]=key_mod[i];
l=0;
for(i=16;i<24;i++)
{
for(j=0;j<16;j++)
{
small_keys[i][j]=key[l];
l++;
}
}
// key rotation third
for(j=0;j<128;j++)
{
key_mod[j]=key[(j-25+128)%128];
}
for(i=0;i<128;i++)
key[i]=key_mod[i];
l=0;
for(i=24;i<32;i++)
{
for(j=0;j<16;j++)
{
small_keys[i][j]=key[l];
l++;
}
}
// key rotation four
for(j=0;j<128;j++)
{
key_mod[j]=key[(j-25+128)%128];
}
for(i=0;i<128;i++)
key[i]=key_mod[i];
l=0;
for(i=32;i<40;i++)
{
for(j=0;j<16;j++)
{
small_keys[i][j]=key[l];
l++;
}
}
// key rotation five
for(j=0;j<128;j++)
{
key_mod[j]=key[(j-25+128)%128];
}
for(i=0;i<128;i++)
key[i]=key_mod[i];
l=0;
for(i=40;i<48;i++)
{
for(j=0;j<16;j++)
{
small_keys[i][j]=key[l];
l++;
}
}
// key rotation six
for(j=0;j<128;j++)
{
key_mod[j]=key[(j-25+128)%128];
}
for(i=0;i<128;i++)
key[i]=key_mod[i];
l=0;
for(i=48;i<52;i++)
{
for(j=0;j<16;j++)
{
small_keys[i][j]=key[l];
l++;
}
}
// Texts in 16 bits
l=0;
for(i=0;i<4;i++)
{
for(j=0;j<16;j++)
{
small_texts[i][j]=text[l];
l++;
}
}
// The IDEA encryption process consist of the following 14 steps in each of the 8 rounds .
long int k[52]={0};
long int p[4]={0};
long int status=0;
long int step1=0,step2=0,step3=0,step4=0,step7=0,step8=0,step9=0,step10=0;
int temp[16]={0},temp1[16]={0};
int step5[16]={0},step6[16]={0},step11[16]={0},step12[16]={0},step13[16]={0},step14[16]={0};
for(j=0;j<52;j++)
{
k[j]=convertBinaryToInt(small_keys[j],16);
}
for(i=0;i<8;i++)
{
p[4]={0};
step1=0,step2=0,step3=0,step4=0,step7=0,step8=0,step9=0,step10=0;
step5[16]={0},step6[16]={0},step11[16]={0},step12[16]={0},step13[16]={0},step14[16]={0};
for(j=0;j<4;j++)
{
p[j]=convertBinaryToInt(small_texts[j],16);
}
// step 1
step1=(p[0]*k[0+(i*6)]) % 65537 ;
// step 2
step2=(p[1]+k[1+(i*6)]) % 65536 ;
// step 3
step3=(p[2]+k[2+(i*6)]) % 65536 ;
// step 4
step4=(p[3]*k[3+(i*6)]) % 65537 ;
// step 5
convertIntToBinary(step1,temp,16);
convertIntToBinary(step3,temp1,16);
for(j=0;j<16;j++)
step5[j]=temp[j]^temp1[j];
// step6
temp[16]={0};temp1[16]={0};
convertIntToBinary(step2,temp,16);
convertIntToBinary(step4,temp1,16);
for(j=0;j<16;j++)
step6[j]=temp[j]^temp1[j];
// step 7
status=convertBinaryToInt(step5,16);
step7=(status*k[4+(i*6)]) % 65537 ;
// step 8
status=0;
status=convertBinaryToInt(step6,16);
step8=(status+step7) % 65536 ;
// step 9
step9=(step8*k[5+(i*6)]) % 65537 ;
// step 10
step10=(step7+step9) % 65536 ;
// step 11
small_texts[0][16]={0};
temp[16]={0};temp1[16]={0};
convertIntToBinary(step1,temp,16);
convertIntToBinary(step9,temp1,16);
for(j=0;j<16;j++)
{
step11[j]=temp[j]^temp1[j];
small_texts[0][j]=step11[j];
}
// step 12
small_texts[1][16]={0};
temp[16]={0};temp1[16]={0};
convertIntToBinary(step3,temp,16);
convertIntToBinary(step9,temp1,16);
for(j=0;j<16;j++)
{
step12[j]=temp[j]^temp1[j];
small_texts[1][j]=step12[j];
}
// step 13
small_texts[2][16]={0};
temp[16]={0};temp1[16]={0};
convertIntToBinary(step2,temp,16);
convertIntToBinary(step10,temp1,16);
for(j=0;j<16;j++)
{
step13[j]=temp[j]^temp1[j];
small_texts[2][j]=step13[j];
}
// step 14
small_texts[3][16]={0};
temp[16]={0};temp1[16]={0};
convertIntToBinary(step4,temp,16);
convertIntToBinary(step10,temp1,16);
for(j=0;j<16;j++)
{
step14[j]=temp[j]^temp1[j];
small_texts[3][j]=step14[j];
}
}
// Output generation process
status=0;
// step 1
step1=0;
status=convertBinaryToInt(small_texts[0],16);
step1=(status*k[0+(i*6)]) % 65537 ;
status=0;
// step 2
step2=0;
status=convertBinaryToInt(small_texts[1],16);
step2=(status+k[1+(i*6)]) % 65536 ;
status=0;
// step 3
step3=0;
status=convertBinaryToInt(small_texts[2],16);
step3=(status+k[2+(i*6)]) % 65536 ;
status=0;
// step 4
step4=0;
status=convertBinaryToInt(small_texts[3],16);
step4=(status*k[3+(i*6)]) % 65537 ;
// Printing the cipher text
temp[16]={0};temp1[16]={0};
printf("The cipher text in binary is \n");
convertIntToBinary(step1,temp,16);
convertIntToBinary(step2,temp1,16);
for(j=0;j<16;j++)
printf("%d ",temp[j]);
printf("\n");
for(j=0;j<16;j++)
printf("%d ",temp1[j]);
printf("\n");
temp[16]={0};temp1[16]={0};
convertIntToBinary(step1,temp,16);
convertIntToBinary(step2,temp1,16);
for(j=0;j<16;j++)
printf("%d ",temp[j]);
printf("\n");
for(j=0;j<16;j++)
printf("%d ",temp1[j]);
printf("\n");
}
| true |
6660fc7663116f2775b3ffdd82d6c2ffe7732540 | C++ | mansisaksson/BachelorThesis | /Source/Exjobb/NetDataStructures.h | UTF-8 | 1,854 | 2.65625 | 3 | [] | no_license | #pragma once
#include "Runtime/Core/Public/Misc/NetworkGuid.h"
#include "NetDataStructures.generated.h"
namespace NetIDs
{
static const uint8 NetDataID = 0;
static const uint8 ChunkDataID = 1;
static const uint8 ChunkDataArrayID = 2;
};
USTRUCT()
struct FNetData
{
GENERATED_BODY()
uint32 packetID;
uint8 DataID;
FNetData(uint8 dataID = NetIDs::NetDataID)
: DataID(dataID)
{}
virtual FArchive& Serialize(FArchive &Ar)
{
Ar << packetID;
Ar << DataID;
return Ar;
}
};
FORCEINLINE FArchive& operator<<(FArchive &Ar, FNetData& netData)
{
return netData.Serialize(Ar);
}
USTRUCT()
struct FChunkData : public FNetData
{
GENERATED_BODY()
uint8 ChunkIndex;
FVector Location;
FRotator Rotation;
FChunkData()
: FNetData(NetIDs::ChunkDataID)
{}
FChunkData(const int32 &chunkIndex, const FVector &location, const FRotator &rotation)
: FNetData(NetIDs::ChunkDataID)
, ChunkIndex(chunkIndex)
, Location(location)
, Rotation(rotation)
{ }
virtual FArchive& Serialize(FArchive &Ar) override
{
Ar << packetID; // We need to know if the packet we received contains old information since UDP can arrive in the wrong order and we only care about the newest one
Ar << ChunkIndex;
Ar << Location;
Ar << Rotation;
//SerializePackedVector<1, 20>(Location, Ar);
//Rotation.SerializeCompressed(Ar); // Clamps every axis to one byte (360/255)
return Ar;
}
};
USTRUCT()
struct FChunkDataArray : public FNetData
{
GENERATED_BODY()
FNetworkGUID Recipient;
TArray<FChunkData> Chunks;
FChunkDataArray()
: FNetData(NetIDs::ChunkDataArrayID)
{}
FChunkDataArray(const FNetworkGUID &recipient)
: FNetData(NetIDs::ChunkDataArrayID)
, Recipient(recipient)
{}
virtual FArchive& Serialize(FArchive &Ar) override
{
Ar << packetID;
Ar << DataID;
Ar << Recipient;
Ar << Chunks;
return Ar;
}
}; | true |
8a701298d5c12160202800720e2e45220e43d85f | C++ | GodSang/BOJ | /실버/1463.cpp | UTF-8 | 429 | 2.828125 | 3 | [] | no_license | // 15:13 ~ 15:36
#include <iostream>
#include <algorithm>
using namespace std;
int arr[1000001];
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
for(int i=2;i<=n;i++) {
arr[i] = arr[i-1] + 1;
if(i%3 == 0) {
arr[i] = min(arr[i], arr[i/3] + 1);
}
if(i%2 == 0) {
arr[i] = min(arr[i], arr[i/2] + 1);
}
}
cout << arr[n];
} | true |
fe21b6de41e05f2beb97350198142c85337b3d02 | C++ | danielkummer/scenegraph | /OpenGL_SceneGraph_Stussman/Code/Aufgabe2/main.cpp | ISO-8859-3 | 7,351 | 2.84375 | 3 | [] | no_license | /**************************************************/
/* */
/* Main Sourcecode Aufgabe 2 */
/* */
/**************************************************/
/* Authors: Reto Bollinger */
/* bolliret@zhwin.ch */
/* */
/* Hanspeter Brhlmann */
/* bruehhan@zhwin.ch */
/* */
/**************************************************/
/* Date: 15. October 2004 */
/**************************************************/
#include "main.h"
#include "draw.h"
/**************************************************/
/* Variable definition */
/**************************************************/
KeyFlag keyFlag; // Placeholder for pressed keys
int width = 1024; // Dimensions of our window
int height = 768;
bool fullscreen = false; // Fullscreen or windowed mode
/**************************************************/
/* Exit */
/**************************************************/
void quit_program( int code )
{
SDL_Quit( ); // Quit SDL and restore previous video settings
exit( code ); // Exit program
}
/**************************************************/
/* Poll Keyevents */
/**************************************************/
void process_events( )
{
SDL_Event event; // SDL event placeholder
// Used for camera control
//////////////////////////
while( SDL_PollEvent( &event ) ) // Grab all the events off the queue
{
switch( event.type )
{
case SDL_QUIT: // Handle quit requests (like Ctrl-c)
quit_program( 0 );
break;
case SDL_MOUSEMOTION:
keyFlag.relMouseX = event.motion.xrel;
keyFlag.relMouseY = event.motion.yrel;
break;
case SDL_MOUSEBUTTONDOWN:
switch( event.button.button ){
case 4:
case 5:
keyFlag.rollButton = event.button.button;
break;
}
case SDL_MOUSEBUTTONUP:
switch( event.button.button ){
case 4:
case 5:
// keyFlag.rollButton = -1;
break;
}
case SDL_KEYDOWN: // Handle each keydown
switch( event.key.keysym.sym ) {
case SDLK_ESCAPE:
quit_program( 0 ); // Quit program
break;
case SDLK_RIGHT:
keyFlag.right = true; // Set keyflags
break;
case SDLK_LEFT:
keyFlag.left = true;
break;
case SDLK_UP:
keyFlag.up = true;
break;
case SDLK_DOWN:
keyFlag.down = true;
break;
case SDLK_PAGEUP:
keyFlag.pageUp = true;
break;
case SDLK_PAGEDOWN:
keyFlag.pageDown = true;
break;
default:
break;
}
break;
case SDL_KEYUP: // Handle each keyup
switch( event.key.keysym.sym )
{
case SDLK_RIGHT:
keyFlag.right = false; // Set keyflags
break;
case SDLK_LEFT:
keyFlag.left = false;
break;
case SDLK_UP:
keyFlag.up = false;
break;
case SDLK_DOWN:
keyFlag.down = false;
break;
case SDLK_PAGEUP:
keyFlag.pageUp = false;
break;
case SDLK_PAGEDOWN:
keyFlag.pageDown = false;
break;
case SDL_VIDEORESIZE: // Handle resize events
width = event.resize.w; // Set event width value
height = event.resize.h; // Set event height vlaue
SDL_Quit(); // Quit SDL
init_SDL(); // Restart SDL
init_OpenGL(); // Restart OpenGL
break;
default:
break;
}
break;
}
}
}
/**************************************************/
/* Init OpenGL */
/* Returnvalue: true if init was successful */
/**************************************************/
bool init_OpenGL( ) {
float ratio = (float) width / (float) height; // Calculate and store the aspect ratio of the display
glMatrixMode( GL_PROJECTION ); // Change to the projection matrix
gluPerspective( 60.0, ratio, 0.1, 1024.0 ); // Set view perspective
glMatrixMode( GL_MODELVIEW ); // Change to the modelview matrix
glEnable(GL_DEPTH_TEST); // Enable hidden surface removal
return true;
}
/**************************************************/
/* Init SDL */
/* Returnvalue: true if init was successful */
/**************************************************/
bool init_SDL()
{
const SDL_VideoInfo* info = NULL; // Information about the current video settings
int bpp = 0; // Color depth in bits of our window
int flags = 0; // Flags we will pass into SDL_SetVideoMode
if( SDL_Init( SDL_INIT_VIDEO ) < 0 ) // First, initialize SDL's video subsystem (video only)
{
fprintf( stderr, "Video initialization failed: %s\n", SDL_GetError( ) );
quit_program( 1 ); // Failed, exit
}
info = SDL_GetVideoInfo( ); // Get some video information
if( !info ) // This should probably never happen
{
fprintf( stderr, "Video query failed: %s\n", SDL_GetError( ) );
return false;
}
bpp = info->vfmt->BitsPerPixel; // Get color depth
SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 8 ); // Sets the color-depth of the red, green and blue color-part
SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 8 ); // to 8bit (standard today)
SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 8 );
SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 ); // Set depth buffer
SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); // Sets wether to enable or disable doublebuffering
flags = SDL_OPENGL; // Set flags for SDL OpenGL
flags = flags | SDL_RESIZABLE;
if (fullscreen) {
flags = flags | SDL_FULLSCREEN; // Set flag for fullscreen or windowed mode
}
if( SDL_SetVideoMode( width, height, bpp, flags ) == 0 ) // Set the video mode
{
fprintf( stderr, "Video mode set failed: %s\n", SDL_GetError( ) );
return false;
}
SDL_ShowCursor(false);
SDL_WM_GrabInput(SDL_GRAB_ON);
return true;
}
/**************************************************/
/* Main */
/* Returnvalue: 0 if main was successful */
/**************************************************/
int main( int argc, char* argv[] )
{
if(!init_SDL()) // If intialising of SDL fails -> quit the program with error code 1
{
quit_program( 1 );
}
if(!init_OpenGL()) // If intialising of OpenGL fails -> quit the program with error code 1
{
quit_program( 1 );
}
while(true) // Repeat forever
{
draw_screen(); // Draw your graphics
process_events( ); // Process any ocuring events
}
quit_program(0); // You shouldn't get here. Only if someone changes the while condition...
}
| true |
00ac95b591b832fa1b82bad812def9772645071b | C++ | bgki11er/StaticTaintAnalysis | /ASTReader/tmap.h | UTF-8 | 2,389 | 2.921875 | 3 | [] | no_license | #include <iostream>
#include <map>
#include "clang/Frontend/ASTUnit.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Basic/FileSystemOptions.h"
#include "clang/AST/RecursiveASTVisitor.h"
using namespace std;
using namespace clang;
using namespace llvm;
enum e_tattr{
TAINTED,
UNTAINTED,
RELATED
};
class Tainted_Attr
{
public:
friend class Tmap;
//构造函数
Tainted_Attr(){
attr = UNTAINTED;
relation = 0;
}
//拷贝构造函数
Tainted_Attr(const Tainted_Attr& b)
{
attr = b.attr;
relation = b.relation();
}
//信息输出函数 调试用
void output()
{
if (attr == TAINTED)
cout << "TAINTED ";
else if (attr == UNTAINTED)
cout << "UN ";
else
cout << "RE ";
cout << relation << endl;
}
//信息设置函数
void attr_set(e_tattr a, unsigned long long r)
{
attr = a;
relation |= r;
}
private:
e_tattr attr; //污染属性
unsigned long long relation; //污染与哪些变量相关
};
//封装了C++ map模板的污染表类
class Tmap
{
public:
//构造函数
Tmap(){}
//拷贝构造函数
Tmap(const Tmap& b)
{
Tainted_Attr *t = NULL, *newattr;
VarDecl *pdec = NULL;
map<VarDecl *, Tainted_Attr *>::iterator it = b.tmap.begin(), it_end = b.tmap.end();
while (it != it_end)
{
pdec = (*it).first;
t = (*it).second;
newattr = new Tainted_Attr;
newattr->attr = t->attr;
newattr->relation = t->relation;
tmap[pdec] = newattr;
}
}
//析构函数
~Tmap()
{
Tainted_Attr *t;
map<VarDecl *, Tainted_Attr *>::iterator iter = tmap.begin(), iter_end = tmap.end();
while (iter != iter_end)
{
t = (*iter).second;
delete t; //释放临时变量的空间
}
tmap.clear(); //清空所有元素
}
void output()
{
Tainted_Attr *t;
map<VarDecl *, Tainted_Attr *>::iterator iter = tmap.begin(), iter_end = tmap.end();
while (iter != iter_end)
{
t = (*iter).second;
t->output();
}
}
void insert(VarDecl *p)
{
Tainted_Attr *t = new Tainted_Attr();
int count;
count = tmap.count(p);
if (count == 0)
tmap[p] = t;
else
delete t;
}
void del(VarDecl *p)
{
Tainted_Attr *t = tmap[p];
delete t;
tmap.erase(p);
}
Tainted_Attr *getmap(VarDecl *p)
{
Tainted_Attr *t;
int count;
count = tmap.count(p);
if(count == 0)
return NULL;
else
return tmap[p];
}
private:
map<VarDecl *, Tainted_Attr *> tmap;
};
| true |
2c486e7dc4ab3ad20882764281cbfee4ce70a410 | C++ | daniel-riehm/burn-out | /library/utilities/rgb2yuv.h | UTF-8 | 1,387 | 2.65625 | 3 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | /*ckwg +5
* Copyright 2010-2015 by Kitware, Inc. All Rights Reserved. Please refer to
* KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
* Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
*/
#ifndef vidtk_rgb2yuv_h_
#define vidtk_rgb2yuv_h_
#include <limits>
namespace vidtk
{
template<class PIX_TYPE>
void rgb2yuv( PIX_TYPE R, PIX_TYPE G, PIX_TYPE B, PIX_TYPE * yuv )
{
// thanks to http://en.wikipedia.org/wiki/YUV
/*
// these integer approximations seem to give different results than
// the explicit double-valued equations...
int y = ( ( 66 * R + 129 * G + 25 * B + 128) >> 8) + 16;
int u = ( ( -38 * R - 74 * G + 112 * B + 128) >> 8) + 128;
int v = ( ( 112 * R - 94 * G - 18 * B + 128) >> 8) + 128;
*/
double min_v = std::numeric_limits<PIX_TYPE>::min();
double max_v = std::numeric_limits<PIX_TYPE>::max();
double rd = (R-min_v)/(max_v-min_v), gd=(G-min_v)/(max_v-min_v), bd=(B-min_v)/(max_v-min_v);
double yd = (0.299*rd) + (0.587*gd) + (0.114*bd);
double ud = 0.436*(bd - yd) / (1.0 - 0.114);
double vd = 0.615*(rd - yd) / (1.0 - 0.299);
yuv[0] = static_cast<PIX_TYPE>( yd * max_v + min_v );
yuv[1] = static_cast<PIX_TYPE>( (ud+0.436) * (max_v/(2*0.436))+min_v );
yuv[2] = static_cast<PIX_TYPE>( (vd+0.615) * (max_v/(2*0.615))+min_v );
}
} // end namespace vidtk
#endif // end vidtk_rgb2yuv_h_
| true |
7d6e637c2e0fd2c46432ff3ed1d272893962f4ad | C++ | Wen0313/Wen0313 | /Project13_KMatrix/main.cpp | GB18030 | 2,873 | 2.96875 | 3 | [] | no_license | //#include"KMatrix.h"
#include"KMatrix_less.h"
void test1(){
KMatrix<int> km;
km.init(5, 6);
KMatrix<int> km1 = km;
cout << "[km1 = km.init(5,6)]" << endl;
km1.print();
cout << "km1.v.size():" << km1.getV().size() << endl;
cout << "Rows:" << km.getRows() << endl;
cout << "Cols:" << km.getCols() << endl;
cout << endl;
km.setData(0, 1, 1);
km.setData(6, 6, 6);
km.setData(1, 10, 10);
km.setData(2, 3, 3);
cout << "[after km.setData()]" << endl;
km.print();
cout << "km.v.size():" << km.getV().size() << endl;
cout << "km.getData(0,1):" << km.getData(0, 1) << endl;
cout << "km.getData(2,2):" << km.getData(2, 2) << endl;
cout << endl;
km.erase_row(10);
km.erase_row(0);
cout << "[after km.erase_row(0)]" << endl;
km.print();
km.erase_col(10);
km.erase_col(3);
cout << "[after km.erase_col(3)]" << endl;
km.print();
cout << "km.v.size():" << km.getV().size() << endl << endl;
}
void test2() {
KMatrix<double> km;
km.init(5, 6);
KMatrix<double> km1 = km + 22.8;
cout << "[after km + 22.8]" << endl;
km1.print();
KMatrix<double> km2 = km - 2.8;
cout << "[after km - 2.8]" << endl;
km2.print();
km1.setData(0, 1, 10.1);
km1.setData(0, 2, 11.2);
km1.setData(1, 1, 30.3);
km1.setData(2, 5, 40.4);
km1.setData(3, 1, 50.5);
km1.setData(4, 3, 60.6);
cout << "[before km.transpose()]" << endl;
km1.print();
KMatrix<double> km3 = km1.transpose();
cout << "[after km.transpose()]" << endl;
km3.print();
}
void test3() {
KMatrix<int> km,km1;
km.init(2, 4);
km1.init(4, 3);
km.setData(0, 0, 1);
km.setData(0, 1, 2);
km.setData(0, 2, 3);
km.setData(0, 3, 4);
km.setData(1, 0, 5);
km.setData(1, 1, 6);
km.setData(1, 2, 7);
km.setData(1, 3, 8);
//km1.setData(0, 0, 1);
KMatrix<int>::Iterator it(&km1, 0, 0);
*it = 1; //IJ
km1.setData(0, 1, 5);
km1.setData(0, 2, 9);
km1.setData(1, 0, 2);
km1.setData(1, 1, 6);
km1.setData(1, 2, 1);
km1.setData(2, 0, 3);
km1.setData(2, 1, 7);
km1.setData(2, 2, 2);
km1.setData(3, 0, 4);
km1.setData(3, 1, 8);
km1.setData(3, 2, 3);
cout << "[km]" << endl;
km.print();
cout << "[km1] *it(0,0) = 1" << endl;
km1.print();
KMatrix<int> km2 = km * km1;
cout << "[km2 = km * km1]" << endl;
km2.print();
}
void test4() {
KMatrix<int> km;
km.init(2, 4);
km.setData(0, 0, 1);
km.setData(0, 1, 2);
km.setData(0, 2, 3);
km.setData(0, 3, 4);
km.setData(1, 0, 5);
km.setData(1, 1, 6);
km.setData(1, 2, 7);
km.setData(1, 3, 8);
KMatrix<int> km1(km);
//km1.erase_row(1);
cout << "[km]" << endl;
km.print();
cout << "[km1(km)]" << endl;
km1.print();
KMatrix<int> km2 = km.dotMul(km1);
cout << "[km2 = km km1]" << endl;
km2.print();
}
int main() {
cout << "[test1:]" << endl;
test1();
cout << "[test2:]" << endl;
test2();
cout << "[test3:]" << endl;
test3();
cout << "[test4:]" << endl;
test4();
return 0;
} | true |
7b68cac4211c2c83b8d782f5f621b42067bc75c1 | C++ | natrok/Nachos | /code/userprog/pageprovider.cc | UTF-8 | 598 | 2.703125 | 3 | [] | no_license | #ifdef CHANGED
#include "pageprovider.h"
//----------------------------------------------------------------------
// PageProvider
// Classe pour gérer les pages physiques depuis Init
//----------------------------------------------------------------------
PageProvider::PageProvider()
{
bitMap = new BitMap(NumPhysPages);
}
PageProvider::~PageProvider()
{
delete bitMap;
}
int PageProvider::getEmptyPage()
{
return bitMap->Find();
}
void PageProvider::releasePage(int page)
{
bitMap -> Clear(page);
}
int PageProvider::numAvailPage()
{
return bitMap->NumClear();
}
#endif // CHANGED
| true |
3c1b922830295bb1e27d645adf69941d0bfb63cd | C++ | czestmyr/Brewsic | /gui/background.h | UTF-8 | 599 | 2.625 | 3 | [] | no_license | #ifndef _BACKGROUND_H_
#define _BACKGROUND_H_
#include "Icontrol.h"
class Background: public IControl {
public:
Background(SafePtr<IControl> parent, int x, int y, int w, int h): IControl(parent) {
redim(x, y, w, h);
_rect.x = _x;
_rect.y = _y;
_rect.w = _w;
_rect.h = _h;
}
const char* controlClassName() { return "Background"; }
int getXMin() { return 10; }
int getYMin() { return 10; }
int getXMax() { return _w-10; }
int getYMax() { return _h-10; }
void draw(SDL_Surface* surf, int orig_x, int orig_y);
protected:
SDL_Rect _rect;
};
#endif
| true |
e334ff31992e50d19277cc9f684dc169789b7392 | C++ | NicoSchlager/AStarCalculation | /AStarCalculation/AStar.cpp | UTF-8 | 4,398 | 3.140625 | 3 | [] | no_license | #include "AStar.h"
AStar::AStar(const Grid _grid, const Pos _start, const Pos _goal) {
grid = _grid;
start = _start;
goal = _goal;
heuristic = manhattan;
counts = 0;
assert(grid.isValid(start) && grid.isValid(goal));
}
void AStar::setHeuristic(const function<double(Pos, Pos)> _H) {
heuristic = _H;
}
void AStar::solve() {
vector<vector<char>> curGrid(grid.getHeight(), vector<char>(grid.getWidth(), '.'));
frontier.push(Node{ start, heuristic(start, goal), counts });
parent[start] = start;
cost[start] = heuristic(start, goal);
while (!frontier.empty()) {
counts++;
Node cur = frontier.top();
frontier.pop();
updateGrid(curGrid, &cur.position, nullptr);
if (cur.position == goal) break;
for (Pos next : grid.neighbors(cur.position)) {
double new_cost = cost[cur.position] + grid.getCost(cur.position, next);
if (cost.find(next) == cost.end() || new_cost < cost[next]) {
cost[next] = new_cost;
frontier.push(Node{ next, new_cost + heuristic(next, goal), counts });
parent[next] = cur.position;
updateGrid(curGrid, nullptr, &next);
}
}
gridSeq.push_back(curGrid);
}
gridSeq.push_back(curGrid);
Pos cur(goal);
while (cur != start) {
path.push_back(cur);
cur = parent[cur];
}
path.push_back(cur);
reverse(path.begin(), path.end());
}
void AStar::drawSeq() const {
if (gridSeq.size() == 0) {
cout << "No solutions yet.\n";
return;
}
cout << "\n Here comes the solution sequence of A*.\n";
cout << "\'o\' stands for points marked as frontiers. \'+\' stands for points visited.\n";
vector<vector<char>> result = grid.getGrid();
Pos tStart{ result.size() - start.y, start.x - 1 };
Pos tGoal{ result.size() - goal.y, goal.x - 1 };
int count = 0;
for (auto i : gridSeq) {
count++;
cout << "The " << count << " step:" << endl;
for (size_t x = 0; x < i.size(); ++x) {
for (size_t y = 0; y < i[x].size(); ++y) {
if (i[x][y] != '.') {
if(i[x][y] == 'o' && result[x][y] == '.' || i[x][y] == '+' && result[x][y] == 'o')
result[x][y] = i[x][y];
}
if (x == tStart.x && y == tStart.y) {
result[x][y] = '+';
}
if (x == tGoal.x && y == tGoal.y) {
result[x][y] = '@';
}
}
}
Grid::draw(result);
}
}
void AStar::drawPath() const {
if (path.size() == 0) {
cout << "No solutions yet.\n";
return;
}
cout << "\n Here comes the final path.\n";
cout << "\'#\' stands for obstacles. \'*\' stands for rough terrain. "
<< "\'@\' stands for points on the path.\n";
vector<vector<char>> result = grid.getGrid();
for (Pos i : path) {
int row = result.size() - i.y;
int col = i.x - 1;
result[row][col] = '@';
}
Grid::draw(result);
}
vector<Pos> AStar::getPath() const {
return path;
}
int AStar::getCount() const {
return counts;
}
double AStar::manhattan(Pos _p, Pos _goal) {
return abs(_p.x - _goal.x) + abs(_p.y - _goal.y);
}
double AStar::euclidean(Pos _p, Pos _goal) {
return sqrt(pow(_p.x - _goal.x, 2) + pow(_p.y - _goal.y, 2));
}
void AStar::updateGrid(vector<vector<char>>& _grid, const Pos* _cur, const Pos* _neighbors) {
if (_cur != nullptr) {
int row = _grid.size() - _cur->y;
int col = _cur->x - 1;
_grid[row][col] = '+';
}
if (_neighbors != nullptr) {
int row = _grid.size() - _neighbors->y;
int col = _neighbors->x - 1;
_grid[row][col] = 'o';
}
}
/*
Please pay attention that indices of a point in a graph and indices of a vertex
in a grid are different. For a point, i.e., a variable of Pos, the indices of it
are x and y in a Cartesian coordinate system with the origin located at the bottom-left
corner of the graph.
A Grid is stored in a two-dimensional array of C++ and thus a vertex is accessed by
its row and column in the grid with the origin located at the top-left corner of the grid.
The ranges of x, y and row, column are also different. For a grid with m rows and n columns,
row is from 0 to m-1 and column is from 0 to n-1 whereas x is from 1 to n with y from 1 to m.
In a word, for a point in the grid with its coordinates x and y, the corresponding vertex
in the grid is accessed by x-1 and m-y. As a user, such transformations never bother you cause
the only type of data you can enter and read is Pos. It is defined in a cartesian coordinate system
and thus straightforward for you to understand. I wrote this down in case you would read this cpp
and want to find out what I have done in this program.
*/ | true |
4a9caa23e71d7360b93e70a281766ebebae58571 | C++ | santoshp1995/Game-Engine | /Models/Model.cpp | UTF-8 | 2,573 | 2.515625 | 3 | [] | no_license | #include "Model.h"
#include "File.h"
#include "PackageHeader.h"
#include "Texture.h"
namespace Azul
{
Model::Model()
: numVerts(0),
numTris(0),
vao(0),
vbo_verts(0),
vbo_trilist(0),
pRefSphere(new Sphere())
{
}
bool Model::eat(const char* const inFileName, ChunkType _type, const char* const chunkName,
unsigned char*& chunkBuff, unsigned int& chunkSize)
{
bool status = false;
bool isFound = false;
File::Handle fh;
File::Error ferror;
// unpack the package (Read Package HDR)
PackageHeader packageHDR;
ferror = File::Open(fh, inFileName, File::Mode::READ);
assert(ferror == File::Error::SUCCESS);
ferror = File::Read(fh, &packageHDR, sizeof(PackageHeader));
assert(ferror == File::Error::SUCCESS);
ferror = File::Seek(fh, File::Location::BEGIN, sizeof(PackageHeader));
assert(ferror == File::Error::SUCCESS);
ChunkHeader chunkHDR;
ferror = File::Read(fh, &chunkHDR, sizeof(ChunkHeader));
assert(ferror == File::Error::SUCCESS);
unsigned int index = 0;
if (chunkHDR.type == _type && strcmp(chunkHDR.chunkName, chunkName) == 0)
{
isFound = true;
status = true;
}
else
{
while (!isFound)
{
if (index >= packageHDR.numChunks) break;
int offset = (int)(chunkHDR.chunkSize);
ferror = File::Seek(fh, File::Location::CURRENT, offset);
assert(ferror == File::Error::SUCCESS);
File::Read(fh, &chunkHDR, sizeof(ChunkHeader));
assert(ferror == File::Error::SUCCESS);
index++;
if (chunkHDR.type == _type && strcmp(chunkHDR.chunkName, chunkName) == 0)
{
isFound = true;
status = true;
}
}
}
if (isFound)
{
chunkSize = chunkHDR.chunkSize;
chunkBuff = new unsigned char[chunkSize];
for (unsigned int i = 0; i < chunkSize; i++)
{
ferror = File::Read(fh, &chunkBuff[i], sizeof(char));
assert(ferror == File::Error::SUCCESS);
}
ferror = File::Close(fh);
}
return status;
}
// use for tga file reading.
bool Model::isFileInDirectory(const char* const pFileName)
{
bool status = false;
WIN32_FIND_DATAA data;
File::Handle fh;
fh = FindFirstFileA(pFileName, &data);
if (fh != INVALID_HANDLE_VALUE)
{
status = true;
}
return status;
}
void Model::SetModelType(Model::ModelType _type)
{
this->type = _type;
}
Model::ModelType Model::GetModelType() const
{
return this->type;
}
Model::~Model()
{
delete this->pRefSphere;
}
}
| true |
14982baaa82f20cd58064543cb606866863688f2 | C++ | fuglu/arduino-playground | /sketchbook/temp.ino | UTF-8 | 334 | 2.671875 | 3 | [] | no_license | #include <RGB.h>
#include <Temp.h>
RGB led = RGB(12, 11, 10);
Temp temp = Temp(1);
void setup()
{
led.initialize();
}
void loop()
{
double celsius = temp.celsius();
if (celsius > 30) {
led.red();
} else if (celsius > 20) {
led.green();
} else if (celsius > 10) {
led.blue();
} else {
led.off();
}
delay(1000);
}
| true |
f25b124d9db301be5ff43b997280f4b74e627ea0 | C++ | danielrayali/cryptopals | /set_1/aes.h | UTF-8 | 22,555 | 3.03125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | #pragma once
#include <cstdint>
#include <vector>
#include <cmath>
#include <utility>
#include "xor.h"
#include "util.h"
class Aes128EcbCms {
public:
Aes128EcbCms() = default;
~Aes128EcbCms() = default;
void SetKey(const std::vector<uint8_t>& key) {
this->GenerateRoundKeys(key);
}
std::vector<uint8_t> Encrypt(const std::vector<uint8_t>& plain_text) {
std::vector<uint8_t> cipher_text;
for (size_t i = 0; i < plain_text.size(); i += kKeySize) {
std::vector<uint8_t> block_cipher_text = this->EncryptRound(Slice(plain_text, i, kKeySize));
std::cout << "Block text: ";
for (auto datum : block_cipher_text) {
std::cout << std::setfill('0') << std::setw(2) << std::hex << (int)datum;
}
std::cout << std::endl;
cipher_text.insert(cipher_text.end(), block_cipher_text.begin(), block_cipher_text.end());
}
size_t remainder = (plain_text.size() % (kKeySize));
std::vector<uint8_t> last_block = Slice(plain_text, (plain_text.size() - remainder), remainder);
while (last_block.size() < kKeySize) {
last_block.emplace_back(kKeySize - remainder);
}
std::vector<uint8_t> last_block_cipher_text = this->EncryptRound(last_block);
cipher_text.insert(cipher_text.end(), last_block_cipher_text.begin(), last_block_cipher_text.end());
std::cout << "Cipher text: ";
for (auto datum : cipher_text) {
std::cout << std::setfill('0') << std::setw(2) << std::hex << (int)datum;
}
std::cout << std::endl;
return cipher_text;
}
std::vector<uint8_t> Decrypt(const std::vector<uint8_t>& cipher_text) {
if ((cipher_text.size() % kKeySize) != 0) {
throw std::runtime_error("Cannot decrypt a cipher text with byte size " + std::to_string(cipher_text.size()));
}
std::vector<uint8_t> plain_text;
for (size_t i = 0; i < cipher_text.size(); i += kKeySize) {
std::vector<uint8_t> cipher_text_block = Slice(cipher_text, i, kKeySize);
std::vector<uint8_t> plain_text_block = this->DecryptRound(cipher_text_block);
std::cout << "Block text: ";
PrintAscii(plain_text_block, 0);
std::cout << std::endl;
plain_text.insert(plain_text.end(), plain_text_block.begin(), plain_text_block.end());
}
while (plain_text.back() == 0) {
plain_text.pop_back();
}
return plain_text;
}
private:
const size_t kKeySize = (128/8);
std::vector<uint8_t> key_;
std::vector<std::vector<uint8_t>> round_keys_;
std::vector<std::vector<uint8_t>> round_constants_ = {
{ 0x01, 0x00, 0x00, 0x00 },
{ 0x02, 0x00, 0x00, 0x00 },
{ 0x04, 0x00, 0x00, 0x00 },
{ 0x08, 0x00, 0x00, 0x00 },
{ 0x10, 0x00, 0x00, 0x00 },
{ 0x20, 0x00, 0x00, 0x00 },
{ 0x40, 0x00, 0x00, 0x00 },
{ 0x80, 0x00, 0x00, 0x00 },
{ 0x1B, 0x00, 0x00, 0x00 },
{ 0x36, 0x00, 0x00, 0x00 }
};
const uint8_t s_box_[256] = {
0x63 ,0x7c ,0x77 ,0x7b ,0xf2 ,0x6b ,0x6f ,0xc5 ,0x30 ,0x01 ,0x67 ,0x2b ,0xfe ,0xd7 ,0xab ,0x76,
0xca ,0x82 ,0xc9 ,0x7d ,0xfa ,0x59 ,0x47 ,0xf0 ,0xad ,0xd4 ,0xa2 ,0xaf ,0x9c ,0xa4 ,0x72 ,0xc0,
0xb7 ,0xfd ,0x93 ,0x26 ,0x36 ,0x3f ,0xf7 ,0xcc ,0x34 ,0xa5 ,0xe5 ,0xf1 ,0x71 ,0xd8 ,0x31 ,0x15,
0x04 ,0xc7 ,0x23 ,0xc3 ,0x18 ,0x96 ,0x05 ,0x9a ,0x07 ,0x12 ,0x80 ,0xe2 ,0xeb ,0x27 ,0xb2 ,0x75,
0x09 ,0x83 ,0x2c ,0x1a ,0x1b ,0x6e ,0x5a ,0xa0 ,0x52 ,0x3b ,0xd6 ,0xb3 ,0x29 ,0xe3 ,0x2f ,0x84,
0x53 ,0xd1 ,0x00 ,0xed ,0x20 ,0xfc ,0xb1 ,0x5b ,0x6a ,0xcb ,0xbe ,0x39 ,0x4a ,0x4c ,0x58 ,0xcf,
0xd0 ,0xef ,0xaa ,0xfb ,0x43 ,0x4d ,0x33 ,0x85 ,0x45 ,0xf9 ,0x02 ,0x7f ,0x50 ,0x3c ,0x9f ,0xa8,
0x51 ,0xa3 ,0x40 ,0x8f ,0x92 ,0x9d ,0x38 ,0xf5 ,0xbc ,0xb6 ,0xda ,0x21 ,0x10 ,0xff ,0xf3 ,0xd2,
0xcd ,0x0c ,0x13 ,0xec ,0x5f ,0x97 ,0x44 ,0x17 ,0xc4 ,0xa7 ,0x7e ,0x3d ,0x64 ,0x5d ,0x19 ,0x73,
0x60 ,0x81 ,0x4f ,0xdc ,0x22 ,0x2a ,0x90 ,0x88 ,0x46 ,0xee ,0xb8 ,0x14 ,0xde ,0x5e ,0x0b ,0xdb,
0xe0 ,0x32 ,0x3a ,0x0a ,0x49 ,0x06 ,0x24 ,0x5c ,0xc2 ,0xd3 ,0xac ,0x62 ,0x91 ,0x95 ,0xe4 ,0x79,
0xe7 ,0xc8 ,0x37 ,0x6d ,0x8d ,0xd5 ,0x4e ,0xa9 ,0x6c ,0x56 ,0xf4 ,0xea ,0x65 ,0x7a ,0xae ,0x08,
0xba ,0x78 ,0x25 ,0x2e ,0x1c ,0xa6 ,0xb4 ,0xc6 ,0xe8 ,0xdd ,0x74 ,0x1f ,0x4b ,0xbd ,0x8b ,0x8a,
0x70 ,0x3e ,0xb5 ,0x66 ,0x48 ,0x03 ,0xf6 ,0x0e ,0x61 ,0x35 ,0x57 ,0xb9 ,0x86 ,0xc1 ,0x1d ,0x9e,
0xe1 ,0xf8 ,0x98 ,0x11 ,0x69 ,0xd9 ,0x8e ,0x94 ,0x9b ,0x1e ,0x87 ,0xe9 ,0xce ,0x55 ,0x28 ,0xdf,
0x8c ,0xa1 ,0x89 ,0x0d ,0xbf ,0xe6 ,0x42 ,0x68 ,0x41 ,0x99 ,0x2d ,0x0f ,0xb0 ,0x54 ,0xbb ,0x16
};
const uint8_t inverse_s_box_[256] = {
0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb,
0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb,
0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,
0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25,
0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92,
0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,
0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06,
0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b,
0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,
0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e,
0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b,
0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,
0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f,
0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef,
0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,
0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d
};
std::vector<uint8_t> DecryptRound(const std::vector<uint8_t>& cipher_text_block) {
if (cipher_text_block.size() != kKeySize) {
throw std::runtime_error("Cannot decyrpt a block that is not 128 bits wide");
}
std::vector<uint8_t> plain_text = XorEqual(cipher_text_block, round_keys_[10]);
std::cout << "After round 10 remove round key: ";
PrintHex(plain_text);
std::cout << std::endl;
this->InverseShiftRows(plain_text);
std::cout << "After round 10 inverse row shifts: ";
PrintHex(plain_text);
std::cout << std::endl;
for (size_t i = 0; i < plain_text.size(); ++i) {
plain_text[i] = this->InverseSBox(plain_text[i]);
}
std::cout << "After round 10 inverse substitutes: ";
PrintHex(plain_text);
std::cout << std::endl;
for (size_t i = 9; i >= 1; --i) {
plain_text = XorEqual(plain_text, round_keys_[i]);
std::cout << "After round " << i << " remove round key: ";
PrintHex(plain_text);
std::cout << std::endl;
this->InverseMixColumn(plain_text);
std::cout << "After round " << i << " inverse mix column: ";
PrintHex(plain_text);
std::cout << std::endl;
this->InverseShiftRows(plain_text);
std::cout << "After round " << i << " inverse shift rows: ";
PrintHex(plain_text);
std::cout << std::endl;
for (size_t j = 0; j < plain_text.size(); ++j) {
plain_text[j] = this->InverseSBox(plain_text[j]);
}
std::cout << "After round " << i << " inverse substitution: ";
PrintHex(plain_text);
std::cout << std::endl;
}
plain_text = XorEqual(plain_text, round_keys_[0]);
std::cout << "After round 0 remove round key: ";
PrintHex(plain_text);
std::cout << std::endl;
return plain_text;
}
std::vector<uint8_t> EncryptRound(const std::vector<uint8_t>& block) {
if (block.size() != kKeySize) {
throw std::runtime_error("Cannot encrypt block that is not 128 bits wide");
}
std::vector<uint8_t> cipher_text, round_text;
round_text = XorEqual(block, round_keys_[0]);
std::cout << "After round 0 add roundkey: ";
PrintHex(round_text);
std::cout << std::endl;
for (size_t i = 1; i < 10; ++i) {
for (size_t i = 0; i < round_text.size(); ++i) {
round_text[i] = this->SBox(round_text[i]);
}
std::cout << "After round " << i << " substitutes: ";
PrintHex(round_text);
std::cout << std::endl;
this->ShiftRows(round_text);
std::cout << "After round " << i << " row shifts: ";
PrintHex(round_text);
std::cout << std::endl;
this->MixColumn(round_text);
std::cout << "After round " << i << " mix column: ";
PrintHex(round_text);
std::cout << std::endl;
round_text = XorEqual(round_text, round_keys_[i]);
std::cout << "After round " << i << " add roundkey: ";
PrintHex(round_text);
std::cout << std::endl;
}
for (size_t i = 0; i < round_text.size(); ++i) {
round_text[i] = this->SBox(round_text[i]);
}
std::cout << "After round 10 substitutes: ";
PrintHex(round_text);
std::cout << std::endl;
this->ShiftRows(round_text);
std::cout << "After round 10 row shifts: ";
PrintHex(round_text);
std::cout << std::endl;
round_text = XorEqual(round_text, round_keys_[10]);
std::cout << "After round 10 add roundkey: ";
PrintHex(round_text);
std::cout << std::endl;
cipher_text = round_text;
return cipher_text;
}
inline uint8_t MixColumnMultiply(uint8_t times, uint8_t data) {
if (times == 3) {
return (((data * 2) ^ (data & 0x80 ? 0x1B : 0)) ^ data);
} else if (times == 2) {
return ((data * 2) ^ (data & 0x80 ? 0x1B : 0));
} else {
return data;
}
}
inline uint8_t InverseMixColumnMultiply(uint8_t constant, uint8_t data) {
static uint8_t by_nine[256] = {
0x00,0x09,0x12,0x1b,0x24,0x2d,0x36,0x3f,0x48,0x41,0x5a,0x53,0x6c,0x65,0x7e,0x77,
0x90,0x99,0x82,0x8b,0xb4,0xbd,0xa6,0xaf,0xd8,0xd1,0xca,0xc3,0xfc,0xf5,0xee,0xe7,
0x3b,0x32,0x29,0x20,0x1f,0x16,0x0d,0x04,0x73,0x7a,0x61,0x68,0x57,0x5e,0x45,0x4c,
0xab,0xa2,0xb9,0xb0,0x8f,0x86,0x9d,0x94,0xe3,0xea,0xf1,0xf8,0xc7,0xce,0xd5,0xdc,
0x76,0x7f,0x64,0x6d,0x52,0x5b,0x40,0x49,0x3e,0x37,0x2c,0x25,0x1a,0x13,0x08,0x01,
0xe6,0xef,0xf4,0xfd,0xc2,0xcb,0xd0,0xd9,0xae,0xa7,0xbc,0xb5,0x8a,0x83,0x98,0x91,
0x4d,0x44,0x5f,0x56,0x69,0x60,0x7b,0x72,0x05,0x0c,0x17,0x1e,0x21,0x28,0x33,0x3a,
0xdd,0xd4,0xcf,0xc6,0xf9,0xf0,0xeb,0xe2,0x95,0x9c,0x87,0x8e,0xb1,0xb8,0xa3,0xaa,
0xec,0xe5,0xfe,0xf7,0xc8,0xc1,0xda,0xd3,0xa4,0xad,0xb6,0xbf,0x80,0x89,0x92,0x9b,
0x7c,0x75,0x6e,0x67,0x58,0x51,0x4a,0x43,0x34,0x3d,0x26,0x2f,0x10,0x19,0x02,0x0b,
0xd7,0xde,0xc5,0xcc,0xf3,0xfa,0xe1,0xe8,0x9f,0x96,0x8d,0x84,0xbb,0xb2,0xa9,0xa0,
0x47,0x4e,0x55,0x5c,0x63,0x6a,0x71,0x78,0x0f,0x06,0x1d,0x14,0x2b,0x22,0x39,0x30,
0x9a,0x93,0x88,0x81,0xbe,0xb7,0xac,0xa5,0xd2,0xdb,0xc0,0xc9,0xf6,0xff,0xe4,0xed,
0x0a,0x03,0x18,0x11,0x2e,0x27,0x3c,0x35,0x42,0x4b,0x50,0x59,0x66,0x6f,0x74,0x7d,
0xa1,0xa8,0xb3,0xba,0x85,0x8c,0x97,0x9e,0xe9,0xe0,0xfb,0xf2,0xcd,0xc4,0xdf,0xd6,
0x31,0x38,0x23,0x2a,0x15,0x1c,0x07,0x0e,0x79,0x70,0x6b,0x62,0x5d,0x54,0x4f,0x46
};
static uint8_t by_eleven[256] = {
0x00,0x0b,0x16,0x1d,0x2c,0x27,0x3a,0x31,0x58,0x53,0x4e,0x45,0x74,0x7f,0x62,0x69,
0xb0,0xbb,0xa6,0xad,0x9c,0x97,0x8a,0x81,0xe8,0xe3,0xfe,0xf5,0xc4,0xcf,0xd2,0xd9,
0x7b,0x70,0x6d,0x66,0x57,0x5c,0x41,0x4a,0x23,0x28,0x35,0x3e,0x0f,0x04,0x19,0x12,
0xcb,0xc0,0xdd,0xd6,0xe7,0xec,0xf1,0xfa,0x93,0x98,0x85,0x8e,0xbf,0xb4,0xa9,0xa2,
0xf6,0xfd,0xe0,0xeb,0xda,0xd1,0xcc,0xc7,0xae,0xa5,0xb8,0xb3,0x82,0x89,0x94,0x9f,
0x46,0x4d,0x50,0x5b,0x6a,0x61,0x7c,0x77,0x1e,0x15,0x08,0x03,0x32,0x39,0x24,0x2f,
0x8d,0x86,0x9b,0x90,0xa1,0xaa,0xb7,0xbc,0xd5,0xde,0xc3,0xc8,0xf9,0xf2,0xef,0xe4,
0x3d,0x36,0x2b,0x20,0x11,0x1a,0x07,0x0c,0x65,0x6e,0x73,0x78,0x49,0x42,0x5f,0x54,
0xf7,0xfc,0xe1,0xea,0xdb,0xd0,0xcd,0xc6,0xaf,0xa4,0xb9,0xb2,0x83,0x88,0x95,0x9e,
0x47,0x4c,0x51,0x5a,0x6b,0x60,0x7d,0x76,0x1f,0x14,0x09,0x02,0x33,0x38,0x25,0x2e,
0x8c,0x87,0x9a,0x91,0xa0,0xab,0xb6,0xbd,0xd4,0xdf,0xc2,0xc9,0xf8,0xf3,0xee,0xe5,
0x3c,0x37,0x2a,0x21,0x10,0x1b,0x06,0x0d,0x64,0x6f,0x72,0x79,0x48,0x43,0x5e,0x55,
0x01,0x0a,0x17,0x1c,0x2d,0x26,0x3b,0x30,0x59,0x52,0x4f,0x44,0x75,0x7e,0x63,0x68,
0xb1,0xba,0xa7,0xac,0x9d,0x96,0x8b,0x80,0xe9,0xe2,0xff,0xf4,0xc5,0xce,0xd3,0xd8,
0x7a,0x71,0x6c,0x67,0x56,0x5d,0x40,0x4b,0x22,0x29,0x34,0x3f,0x0e,0x05,0x18,0x13,
0xca,0xc1,0xdc,0xd7,0xe6,0xed,0xf0,0xfb,0x92,0x99,0x84,0x8f,0xbe,0xb5,0xa8,0xa3
};
static uint8_t by_thirteen[256] = {
0x00,0x0d,0x1a,0x17,0x34,0x39,0x2e,0x23,0x68,0x65,0x72,0x7f,0x5c,0x51,0x46,0x4b,
0xd0,0xdd,0xca,0xc7,0xe4,0xe9,0xfe,0xf3,0xb8,0xb5,0xa2,0xaf,0x8c,0x81,0x96,0x9b,
0xbb,0xb6,0xa1,0xac,0x8f,0x82,0x95,0x98,0xd3,0xde,0xc9,0xc4,0xe7,0xea,0xfd,0xf0,
0x6b,0x66,0x71,0x7c,0x5f,0x52,0x45,0x48,0x03,0x0e,0x19,0x14,0x37,0x3a,0x2d,0x20,
0x6d,0x60,0x77,0x7a,0x59,0x54,0x43,0x4e,0x05,0x08,0x1f,0x12,0x31,0x3c,0x2b,0x26,
0xbd,0xb0,0xa7,0xaa,0x89,0x84,0x93,0x9e,0xd5,0xd8,0xcf,0xc2,0xe1,0xec,0xfb,0xf6,
0xd6,0xdb,0xcc,0xc1,0xe2,0xef,0xf8,0xf5,0xbe,0xb3,0xa4,0xa9,0x8a,0x87,0x90,0x9d,
0x06,0x0b,0x1c,0x11,0x32,0x3f,0x28,0x25,0x6e,0x63,0x74,0x79,0x5a,0x57,0x40,0x4d,
0xda,0xd7,0xc0,0xcd,0xee,0xe3,0xf4,0xf9,0xb2,0xbf,0xa8,0xa5,0x86,0x8b,0x9c,0x91,
0x0a,0x07,0x10,0x1d,0x3e,0x33,0x24,0x29,0x62,0x6f,0x78,0x75,0x56,0x5b,0x4c,0x41,
0x61,0x6c,0x7b,0x76,0x55,0x58,0x4f,0x42,0x09,0x04,0x13,0x1e,0x3d,0x30,0x27,0x2a,
0xb1,0xbc,0xab,0xa6,0x85,0x88,0x9f,0x92,0xd9,0xd4,0xc3,0xce,0xed,0xe0,0xf7,0xfa,
0xb7,0xba,0xad,0xa0,0x83,0x8e,0x99,0x94,0xdf,0xd2,0xc5,0xc8,0xeb,0xe6,0xf1,0xfc,
0x67,0x6a,0x7d,0x70,0x53,0x5e,0x49,0x44,0x0f,0x02,0x15,0x18,0x3b,0x36,0x21,0x2c,
0x0c,0x01,0x16,0x1b,0x38,0x35,0x22,0x2f,0x64,0x69,0x7e,0x73,0x50,0x5d,0x4a,0x47,
0xdc,0xd1,0xc6,0xcb,0xe8,0xe5,0xf2,0xff,0xb4,0xb9,0xae,0xa3,0x80,0x8d,0x9a,0x97
};
static uint8_t by_fourteen[256] = {
0x00,0x0e,0x1c,0x12,0x38,0x36,0x24,0x2a,0x70,0x7e,0x6c,0x62,0x48,0x46,0x54,0x5a,
0xe0,0xee,0xfc,0xf2,0xd8,0xd6,0xc4,0xca,0x90,0x9e,0x8c,0x82,0xa8,0xa6,0xb4,0xba,
0xdb,0xd5,0xc7,0xc9,0xe3,0xed,0xff,0xf1,0xab,0xa5,0xb7,0xb9,0x93,0x9d,0x8f,0x81,
0x3b,0x35,0x27,0x29,0x03,0x0d,0x1f,0x11,0x4b,0x45,0x57,0x59,0x73,0x7d,0x6f,0x61,
0xad,0xa3,0xb1,0xbf,0x95,0x9b,0x89,0x87,0xdd,0xd3,0xc1,0xcf,0xe5,0xeb,0xf9,0xf7,
0x4d,0x43,0x51,0x5f,0x75,0x7b,0x69,0x67,0x3d,0x33,0x21,0x2f,0x05,0x0b,0x19,0x17,
0x76,0x78,0x6a,0x64,0x4e,0x40,0x52,0x5c,0x06,0x08,0x1a,0x14,0x3e,0x30,0x22,0x2c,
0x96,0x98,0x8a,0x84,0xae,0xa0,0xb2,0xbc,0xe6,0xe8,0xfa,0xf4,0xde,0xd0,0xc2,0xcc,
0x41,0x4f,0x5d,0x53,0x79,0x77,0x65,0x6b,0x31,0x3f,0x2d,0x23,0x09,0x07,0x15,0x1b,
0xa1,0xaf,0xbd,0xb3,0x99,0x97,0x85,0x8b,0xd1,0xdf,0xcd,0xc3,0xe9,0xe7,0xf5,0xfb,
0x9a,0x94,0x86,0x88,0xa2,0xac,0xbe,0xb0,0xea,0xe4,0xf6,0xf8,0xd2,0xdc,0xce,0xc0,
0x7a,0x74,0x66,0x68,0x42,0x4c,0x5e,0x50,0x0a,0x04,0x16,0x18,0x32,0x3c,0x2e,0x20,
0xec,0xe2,0xf0,0xfe,0xd4,0xda,0xc8,0xc6,0x9c,0x92,0x80,0x8e,0xa4,0xaa,0xb8,0xb6,
0x0c,0x02,0x10,0x1e,0x34,0x3a,0x28,0x26,0x7c,0x72,0x60,0x6e,0x44,0x4a,0x58,0x56,
0x37,0x39,0x2b,0x25,0x0f,0x01,0x13,0x1d,0x47,0x49,0x5b,0x55,0x7f,0x71,0x63,0x6d,
0xd7,0xd9,0xcb,0xc5,0xef,0xe1,0xf3,0xfd,0xa7,0xa9,0xbb,0xb5,0x9f,0x91,0x83,0x8d
};
switch (constant) {
case 9: return by_nine[data]; break;
case 11: return by_eleven[data]; break;
case 13: return by_thirteen[data]; break;
case 14: return by_fourteen[data]; break;
}
throw std::runtime_error("Unknown Galios constant " + std::to_string(constant));
}
void InverseMixColumn(std::vector<uint8_t>& data) {
size_t size = sqrt(data.size());
std::vector<std::vector<uint8_t>> square = MakeSquareMatrix(data, size);
static std::vector<std::vector<uint8_t>> fixed = {
{ 0x0E, 0x09, 0x0D, 0x0B },
{ 0x0B, 0x0E, 0x09, 0x0D },
{ 0x0D, 0x0B, 0x0E, 0x09 },
{ 0x09, 0x0D, 0x0B, 0x0E }
};
// Destination loop
std::vector<std::vector<uint8_t>> output = Zeros(size);
for (size_t i = 0; i < size; ++i) {
for (size_t j = 0; j < size; ++j) {
output[i][j] = 0;
for (size_t k = 0; k < size; ++k) {
output[i][j] ^= InverseMixColumnMultiply(fixed[k][j], square[i][k]);
}
}
}
data = Concat(output);
}
void MixColumn(std::vector<uint8_t>& data) {
size_t size = sqrt(data.size());
std::vector<std::vector<uint8_t>> square = MakeSquareMatrix(data, size);
static std::vector<std::vector<uint8_t>> fixed = {
{ 0x02, 0x01, 0x01, 0x03 },
{ 0x03, 0x02, 0x01, 0x01 },
{ 0x01, 0x03, 0x02, 0x01 },
{ 0x01, 0x01, 0x03, 0x02 }
};
// Destination loop
std::vector<std::vector<uint8_t>> output = Zeros(size);
for (size_t i = 0; i < size; ++i) {
for (size_t j = 0; j < size; ++j) {
output[i][j] = 0;
for (size_t k = 0; k < size; ++k) {
output[i][j] ^= MixColumnMultiply(fixed[k][j], square[i][k]);
}
}
}
data = Concat(output);
}
void ShiftRows(std::vector<uint8_t>& data) {
std::vector<uint8_t> source(data);
size_t square_size = sqrt(data.size());
for (size_t i = 0; i < square_size; ++i) {
for (size_t j = 1; j < square_size; ++j) {
data[i * square_size + j] = source[(((i + j) % square_size) * square_size) + j];
}
}
}
void InverseShiftRows(std::vector<uint8_t>& data) {
std::vector<uint8_t> source(data);
size_t square_size = sqrt(data.size());
for (size_t i = 0; i < square_size; ++i) {
for (size_t j = 1; j < square_size; ++j) {
data[(((i + j) % square_size) * square_size) + j] = source[i * square_size + j];
}
}
}
void GenerateRoundKeys(const std::vector<uint8_t>& key) {
round_keys_ = std::vector<std::vector<uint8_t>>{ 1, key };
std::cout << "Round key[0]: ";
PrintHex(round_keys_[0]);
std::cout << std::endl;
for (size_t i = 0; i < 10; ++i) {
round_keys_.emplace_back(this->GetRoundKey(round_keys_[i], i));
std::cout << "Round key[" << i+1 << "]: ";
PrintHex(round_keys_.back());
std::cout << std::endl;
}
}
inline uint8_t SBox(const uint8_t value) {
return s_box_[value];
}
inline uint8_t InverseSBox(const uint8_t value) {
return inverse_s_box_[value];
}
std::vector<uint8_t> GetRoundKey(const std::vector<uint8_t>& prev_key, const int round) {
std::vector<std::vector<uint8_t>> w;
for (size_t i = 0 ; i < 4; ++i) {
w.push_back({});
std::cout << "w[" << i << "]: ";
for (size_t j = 0; j < 4; ++j) {
w.back().push_back(prev_key[(i * 4) + j]);
std::cout << std::hex << (int)w.back().back() << " ";
}
std::cout << std::endl;
}
w.emplace_back(XorEqual(w[0], g_func(w[3], round_constants_[round])));
std::cout << "w[" << 4 << "]: ";
PrintHex(w.back());
std::cout << std::endl;
for (size_t i = 1; i < 4; ++i) {
std::cout << "w[" << i+4 << "]: ";
w.emplace_back(XorEqual(w[i], w[i+3]));
PrintHex(w.back());
std::cout << std::endl;
}
return Concat( { w.begin() + 4, w.end() } );
}
std::vector<uint8_t> g_func(const std::vector<uint8_t>& input, const std::vector<uint8_t>& round_constant) {
if (input.size() != 4) {
throw std::runtime_error("Erroneous size passed to g()");
}
// Circular byte shift left
std::vector<uint8_t> output{input};
output.push_back(output[0]);
output.erase(output.begin());
std::cout << "Shifted: ";
PrintHex(output);
std::cout << std::endl;
// Byte substitution (S-Box)
for (size_t i = 0; i < output.size(); ++i) {
output[i] = this->SBox(output[i]);
}
std::cout << "S-Boxed: ";
PrintHex(output);
std::cout << std::endl;
std::cout << "Round constant: ";
PrintHex(round_constant);
std::cout << std::endl;
// Add round constant
output = XorEqual(output, round_constant);
std::cout << "After round constant: ";
PrintHex(output);
std::cout << std::endl;
return output;
}
};
| true |
4b67498fd759f3091fa0f3d4e059ba85929d1ff6 | C++ | celestialxevermore/Three_Kingoms | /기병전법사망확률.cpp | UHC | 1,161 | 3.15625 | 3 | [] | no_license | /**
, Ȯ մϴ.
@param leader δ
@param target δ 1( Ư )
@param critical ũƼ
@param tactics #Id
*/
int PK_⺴Ȯ(Person leader, Person target, bool critical, int tactics)
{
int result = 0;
// Ȯϴ κ ʽϴ.
switch (tactics)
{
case _: result += 1; break;
case _: result += 2; break;
}
if (Scenario(). == _)
result += 2;
if (critical)
result += 2;
switch (target.)
{
case _ҽ: result -= 1; break;
case _: result += 1; break;
}
int diff = std::max(leader., leader.) - std::max(target., target.);
// ǥ 庸 ɷġ
if (diff <= 0)
result -= 3;
// ǥ 庸 ɷġ
else if (diff <= 6)
result -= 1;
else if (diff <= 12)
result += 0;
else
result += 1;
return result;
} | true |
8cff8f9d32e6b79008469ed58cbb0768c4959918 | C++ | Nandhini1296/CS1035-Operating-Systems | /Least Recently Used.cpp | UTF-8 | 1,809 | 3.484375 | 3 | [] | no_license | #include <stdio.h>
struct cache {//lru
int first; // most recently used
int second; // second most recently used
int third; // least recently used
};
int main() {
struct cache c;
c.first = -1; // indicating that the pages are empty
c.second = -1;
c.third = -1;
int pages[100]; // array to hold all the individual pages
int count = 0, faults = 0; // count: total pages, faults: number of page faults
int i, j;
printf("Enter number of pages: ");
scanf("%d", &count);
for (i = 0; i < count; i++) {
printf("Page %d: ", i + 1);
scanf("%d", &pages[i]);//lru
}
for (i = 0; i < count; i++) {
int page = pages[i];
int isFault = 0;
if (c.first == page) {
c.first = page;
} else if (c.first == -1) {
c.first = page;
isFault = 1;
} else if (c.second == page) {
c.second = c.first;
c.first = page;
} else if (c.second == -1) {
c.second = c.first;
c.first = page;
isFault = 1;
} else if (c.third == page) {
c.third = c.second;
c.second = c.first;
c.first = page;
} else if (c.third == -1) {
c.third = c.second;
c.second = c.first;
c.first = page;
isFault = 1;
} else {
c.third = c.second;
c.second = c.first;
c.first = page;
isFault = 1;
}
if (isFault) {
printf("%d\t%d\t%d\t%s\n", c.first, c.second, c.third, "✗");
faults++;
} else {
printf("%d\t%d\t%d\t%s\n", c.first, c.second, c.third, "✓");
}
}
printf("Number of page faults: %d", faults);
return 0;
} | true |
6e9a68b65ee7b8a9861eb22c2231c3efa1f082f2 | C++ | Icelake15/pascal | /Programs/3rd/3.cpp | UTF-8 | 2,088 | 2.9375 | 3 | [] | no_license | #include<stdlib.h>
#include<GL/glut.h>
GLfloat vertices[][3] = {{-1, -1, -1},{1, -1, -1},{1, 1, -1},{-1, 1, -1},{-1, -1, 1},{1, -1, 1},{1, 1, 1},{-1, 1, 1}};
GLfloat colors[][3] = {{1, 0, 0},{1, 1, 0},{0, 1, 0},{0, 0, 1},{1, 0, 1},{1, 1, 1},{0, 1, 1},{0.5, 0.5, 0.5}};
void polygon (int a, int b, int c,int d)
{
glBegin(GL_POLYGON);
glColor3fv (colors[a]);
glVertex3fv (vertices[a]);
glColor3fv (colors[b]);
glVertex3fv (vertices[b]);
glColor3fv (colors[c]);
glVertex3fv(vertices[c]);
glColor3fv(colors[d]);
glVertex3fv(vertices[d]);
glEnd();
}
void colorcube(void)
{
polygon(0,4,2,1);
polygon(0,5,7,3);
polygon(5,2,0,1);
polygon(2,3,1,6);
polygon(1,2,3,5);
polygon(4,5,1,7);
}
GLfloat theta[]={0.0,0.0,0.0};
GLint axis=2;
void display (void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glRotatef(theta [0], 1.0, 0.0, 0.0);
glRotatef(theta [1], 0.0, 1.0, 0.0);
glRotatef(theta [2], 0.0, 0.0, 1.0);
colorcube();
glutSwapBuffers();
}
void spinCube()
{
theta [axis] += 1.0;
if(theta[axis] > 360.0)
theta [axis] -= 360.0;
glutPostRedisplay();
}
void mouse(int btn,int state,int x,int y)
{
if(btn==GLUT_LEFT_BUTTON && state == GLUT_DOWN) axis = 0;
if(btn==GLUT_MIDDLE_BUTTON && state == GLUT_DOWN)axis = 1;
if(btn==GLUT_RIGHT_BUTTON && state == GLUT_DOWN) axis = 2;
}
void myReshape(int w,int h)
{
glViewport(0,0,w,h);
glMatrixMode(GL_PROJECTION);
if(w<=h)
glOrtho(-2.0 ,2.0, -2.0 * (GLfloat) h / (GLfloat) w,
2.0 * (GLfloat)h /(GLfloat)w, -10.0, 10.0);
else
glOrtho(-2.0 * (GLfloat) w /(GLfloat) h,
2.0 * (GLfloat) w / (GLfloat) h, -2.0, 2.0, -10.0, 10.0);
glMatrixMode(GL_MODELVIEW);
}
void main(int argc, char *argv[])
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(500 , 500);
glutCreateWindow("Rotating a color Cube");
glutReshapeFunc(myReshape);
glutDisplayFunc(display);
glutIdleFunc(spinCube);
glutMouseFunc(mouse);
glEnable(GL_DEPTH_TEST);
glutMainLoop();
}
| true |
cd9d6732667651dfd7ac0801507cb5f865a16613 | C++ | rafaelhks/cc-unespar | /3º Ano/Computação Gráfica/Trabalho OpenGL 07/AbreOBJ/include/Face.h | UTF-8 | 396 | 2.625 | 3 | [] | no_license | #ifndef FACE_H
#define FACE_H
#include "Vertex3D.h"
#include<vector>
using namespace std;
class Face
{
public:
Face();
virtual ~Face();
void Add(Vertex3D* vertex);
void RemoveAt(int pos);
void clearAll();
Vertex3D* get(int pos);
int total();
private:
vector<Vertex3D*> vertices;
int nVertex;
};
#endif // FACE_H
| true |
e68996952b08c6aeb6381990f179dc3c42d6fdff | C++ | DevonMorris/l33tc0d3 | /cpp/0011.cpp | UTF-8 | 912 | 3.796875 | 4 | [
"Unlicense"
] | permissive | // Brute force O(n^2)
class Solution {
public:
int maxArea(vector<int>& height) {
int max_area = 0;
for (int i = 0; i < height.size(); ++i)
{
for (int j = 0; j < height.size(); ++j)
{
const int area = abs(i - j) * min(height[i], height[j]);
if (area > max_area)
{
max_area = area;
}
}
}
return max_area;
}
};
// Smarter solution O(n)
class Solution {
public:
int maxArea(vector<int>& height) {
int max_area = 0;
int i = 0;
int j = height.size() - 1;
while (j > i)
{
int area = abs(j - i) * min(height[i], height[j]);
if (area > max_area)
{
max_area = area;
}
if (height[i] > height[j])
{
--j;
}
else
{
++i;
}
}
return max_area;
}
};
| true |
09b912e476da6d843289e0565e912284162329b4 | C++ | and0rnot/luogu | /P1553/P1553.cpp | UTF-8 | 1,833 | 3.59375 | 4 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
void Revert(string& s) {
char c;
for (int i = 0; i < s.size()/2; i++) {
c = s[i];
s[i] = s[s.size()-i-1];
s[s.size()-i-1] = c;
}
}
// note: it can be many 0 like "000"
void RemoveHead0(string& s) {
int i = 0;
// overlook head 0
while (s[i] == '0' && i < s.size())
i++;
if (i == s.size())
s = "0";
else
s = s.substr(i);
}
void RemoveTail0(string& s) {
int i = s.size() - 1;
// overlook tail 0
while (s[i] == '0' && i >= 0)
i--;
if (i < 0)
s = "0";
else
s = s.substr(0, i+1);
}
void ProcessDecimal(string& s) {
string left, right;
int pos = s.find(".");
left = s.substr(0, pos);
right = s.substr(pos+1);
Revert(left);
Revert(right);
RemoveHead0(left);
RemoveTail0(right);
cout << left << "." << right << endl;
}
void ProcessFraction(string& s) {
string left, right;
int pos = s.find("/");
left = s.substr(0, pos);
right = s.substr(pos+1);
Revert(left);
Revert(right);
RemoveHead0(left);
RemoveHead0(right);
cout << left << "/" << right << endl;
}
void ProcessPercentage(string& s) {
string left;
int pos = s.find("%");
left = s.substr(0, pos);
Revert(left);
RemoveHead0(left);
cout << left << "%" << endl;
}
void ProcessInt(string& s) {
Revert(s);
RemoveHead0(s);
cout << s << endl;
}
int main() {
string all;
cin >> all;
if (all.find(".") != string::npos) {
ProcessDecimal(all);
} else if (all.find("/") != string::npos) {
ProcessFraction(all);
} else if (all.find("%") != string::npos) {
ProcessPercentage(all);
} else {
ProcessInt(all);
}
return 0;
} | true |
5c17c2b69565e1396e0a09f314422277cdf0e230 | C++ | Shatodor/Hex | /Hex v0.1/Leg.h | UTF-8 | 9,170 | 3.171875 | 3 | [] | no_license | #include <Servo.h>
#include <math.h>
#include "Arduino.h"
#define PI 3.141592653589793238
#define sqr(x) ((x)*(x)) //Square of number
#define rad2deg(x) ((180.0 / PI) * (x)) //Convert radians to degrees
#define deg2rad(x) ((PI / 180.0) * (x)) //Convert degrees to radians
const int FemurLenght = 70; //Lenght of first (from body) part of leg
const int TibaLenght = 102; //Lenght of second (from body) part of leg
const int FemurOffsetX = 12; //Offset from the origin by the coordinate x
const int FemurOffsetY = 10; //Offset from the origin by the coordinate y
const int FemurOffsetZ = 23; //Offset from the origin by the coordinate z
struct Point //Point in 3d space with x,y,z coordinates
{
float x, y, z;
Point()
{}
Point(float a, float b, float c)
{
x = a;
y = b;
z = c;
}
bool operator==(Point & that) //Operator == overloading
{
return ((x == that.x) && (y == that.y) && (y == that.y));
}
Point operator+(Point & that) //Operator + overloading
{
return Point(x + that.x, y + that.y, z + that.z);
}
Point operator-(Point & that) //Operator - overloading
{
return Point(x - that.x, y - that.y, z - that.z);
}
};
class Leg
{
private:
Servo CoxaServo; //Servo fastended to Hex body (leg turn)
Servo FemurServo; //Servo controling first(from body) part of leg
Servo TibaServo; //Servo controling first(from body) part of leg
int CoxaBaseAngleD; //CoxaServo base angle depends from servo and its mouinting (deg)
int FemurBaseAngleD; //FemurServo base angle depends from servo and its mouinting (deg)
int TibaBaseAngleD; //TibaServo base angle depends from servo and its mouinting (deg)
int Mirror; //-1 == left lengs, 1 -- right legs
Point CurrentPos; //Current leg position
float TurnOffsetX; //Offset between leg origin and Hex origin by local leg coordinate x
float TurnOffsetY; //Offset between leg origin and Hex origin by local leg coordinate y
int LegAngleD; //Angle bewteen leg axis x and Hex axis Y
int LegNumber; //0,1,2 - left legs; 3,4,5 - right legs
int CalcLegOffset; //Calculated leg offset from leg origin
void move(float CoxaAngle, float FemurAngle, float TibaAngle) //Move leg according to input angles (rad)
{
int CoxaAngleD = CoxaBaseAngleD - Mirror * rad2deg(CoxaAngle); //CoxaAngle correction for base angle and mirroring
int FemurAngleD = FemurBaseAngleD - Mirror * rad2deg(FemurAngle); //FemurAngle correction for base angle and mirroring
int TibaAngleD = TibaBaseAngleD + Mirror * rad2deg(TibaAngle); //TibaAngle correction for base angle and mirroring
CoxaServo.write(CoxaAngleD);
FemurServo.write(FemurAngleD);
TibaServo.write(TibaAngleD);
}
boolean checkServoAngles(float CoxaAngle, float FemurAngle, float TibaAngle) //Check if imput angles (rad) are within acceptable limits
{
boolean check = true; //Result flag
if (rad2deg(CoxaAngle) < -90 || rad2deg(CoxaAngle) > 65) //Check if CoxaAngle is within acceptable limits
{
Serial.print("Incorrect CoxaAngle: ");
Serial.println(rad2deg(CoxaAngle));
check = false;
}
if (rad2deg(FemurAngle) < -50 || rad2deg(FemurAngle) > 100) //Check if FemurAngle is within acceptable limits
{
Serial.print("Incorrect FemurAngle: ");
Serial.println(rad2deg(FemurAngle));
check = false;
}
if (rad2deg(TibaAngle) < 20 || rad2deg(FemurAngle) > 200) //Check if FemurAngle is within acceptable limits
{
Serial.print("Incorrect TibaAngle: ");
Serial.println(rad2deg(FemurAngle));
check = false;
}
if (check) return true;
else
{
Serial.print(" LegNumber: ");
Serial.println(LegNumber);
return false;
}
}
public:
Point getCurrentPos() {return CurrentPos;}
int getCalcLegOffset() {return CalcLegOffset;}
void moveTiba(int angle) {TibaServo.write(angle);} // Forced Tiba movement
void config(int legNumber, int coxaBaseAngleD, int femurBaseAngleD, int tibaBaseAngleD, int legAngleD) //Parameters configuration
{
LegNumber = legNumber;
CoxaBaseAngleD = coxaBaseAngleD;
FemurBaseAngleD = femurBaseAngleD;
TibaBaseAngleD = tibaBaseAngleD;
LegAngleD = legAngleD;
if (LegNumber < 3) Mirror = -1;
else Mirror = 1;
}
void configTurn(float turnOffsetX, float turnOffsetY) //Turn parameters configuration
{
TurnOffsetX = turnOffsetX;
TurnOffsetY = turnOffsetY;
}
void attach(int CoxaPin, int FemurPin, int TibaPin) //Attach servos to respective pins
{
CoxaServo.attach(CoxaPin);
FemurServo.attach(FemurPin);
TibaServo.attach(TibaPin);
}
void reach(Point dest) //Reach imput destination point
{
float CoxaAngle; //Coxa angle without correction
float FemurAngle; //Femur angle without correction
float TibaAngle; //Tiba angle without correciton
float xyDist = sqrt(sqr(dest.x) + sqr(dest.y)); //Distance between leg origin and destination point in XY plane
if (xyDist < 10) //Protection from incorrect reach point
{
Serial.print("Incorrect reach point (xyDist) ");
Serial.print("LegNumber: ");
Serial.println(LegNumber);
return;
}
float addCoxaAngle = asin(FemurOffsetY / xyDist); //Addition coxa angle is required because leg plane isn't pass through leg origin
float rawCoxaAngle = asin(dest.y / xyDist); //Coxa angle without correction
CoxaAngle = rawCoxaAngle - addCoxaAngle;
float x = xyDist * cos(addCoxaAngle); //xyDist projection on leg plane
//algolist.manual.ru/maths/geom/intersect/circlecircle2d.php aproach 2
float d = sqrt(sqr(x - FemurOffsetX) + sqr(dest.z - FemurOffsetZ)); //Distance between two circles centers (1- femur start; 2 - tiba end)
if ((d > FemurLenght + TibaLenght) || (d < TibaLenght - FemurLenght)) //Protection from incorrect reach point
{
Serial.print("Incorrect reach point d: ");
Serial.print(d);
Serial.print(" LegNumber: ");
Serial.print(LegNumber);
Serial.print(" x: ");
Serial.print(x);
Serial.print(" z: ");
Serial.println(dest.z);
return;
}
float a = (sqr(FemurLenght) - sqr(TibaLenght) + sqr(d)) / (2*d);
float h = sqrt(sqr(FemurLenght) - sqr(a));
float x2 = FemurOffsetX + (a/d) * (x - FemurOffsetX);
float z2 = FemurOffsetZ + (a/d) * (dest.z - FemurOffsetZ);
float KneeX = x2 - (h/d) * (dest.z - FemurOffsetZ); //x coordinate of femur end/tiba start (knee)
float KneeZ = z2 + (h/d) * (x - FemurOffsetX); //z coordinate of femur end/tiba start (knee)
CalcLegOffset = int(KneeX); //Writing knee x coordinate
if ((KneeX - FemurOffsetX) >= 0) FemurAngle = asin((KneeZ-FemurOffsetZ)/FemurLenght); //Calculation FemurAngle depending on knee location
else FemurAngle = PI - asin((KneeZ-FemurOffsetZ)/FemurLenght);
if (a >= 0) TibaAngle = acos(h/FemurLenght) + acos(h/TibaLenght); //Calculation TibaAngle depending on a location
else TibaAngle = - acos(h/FemurLenght) + acos(h/TibaLenght);
if (checkServoAngles(CoxaAngle, FemurAngle, TibaAngle)) //Checking angle correctness
{
move(CoxaAngle, FemurAngle, TibaAngle);
CurrentPos = dest;
}
}
//Transfer from XY to leg local cooridnates xy for move (Leg offset, step length, step direction angle form Y axis,
//x1,y1, x2,x2 - points coordinates of start and end point of step)
void transfer(int LegOffset, int StepLength, int DirectionAngle, float& x1, float& y1, float& x2, float& y2)
{
float x = 0.5 * StepLength * cos(deg2rad(LegAngleD - Mirror * DirectionAngle)); //Distance between leg base posinion and point 1/2 by x coordinate
x1 = LegOffset + x;
x2 = LegOffset - x;
y1 = 0.5 * StepLength * sin(deg2rad(LegAngleD - Mirror * DirectionAngle)); //Distance between leg base posinion and point 1 by y coordinate
y2 = -y1;
}
void turnPoint(int LegOffset, float TurnAngle, float& x, float& y) //Calculate turn point (Leg offset, angle from leg base position, x,y turn point coordinates)
{
int R; //Radius of circle on which turn point is lay
if (LegNumber == 1 || LegNumber == 4) R = 62 + LegOffset; // For middle legs; 62 - distance between Hex body origin and middle legs origins by X coordinate
else R = sqrt(sqr(40 + LegOffset * cos(deg2rad(45))) + sqr(62 + LegOffset * sin(deg2rad(45)))); // For front/rear legs;
//40 - distance between Hex body origin and front/rear legs origins by X coordinate; 62 - by coordinate; 45 - base angle on which front/rear legs are directed;
float BaseAngle = asin((-1) * TurnOffsetY/R); //Angle wich top is Hex body origin and it is between radius in leg base position and leg local x axis
x = TurnOffsetX + R * cos(TurnAngle + BaseAngle); //Calculation x turn point coordinate
y = TurnOffsetY + R * sin(TurnAngle + BaseAngle); //Calculation y turn point coordinate
}
};
| true |
367128dffc83300eb56e924e97a9df186e39eeaf | C++ | luas13/Leetcode_New | /src/Spiral Matrix 2/Spiral_Matrix2.cpp | UTF-8 | 910 | 3 | 3 | [] | no_license | class Solution {
public:
void helper(int sr, int sc, int er, int ec, vector<vector<int>> &result, int v)
{
while(sr<=er && sc<=ec)
{
for(int i=sc; i<=ec; i++)
result[sr][i] = v++;
sr++;
for(int i=sr; i<=er; i++)
result[i][ec] = v++;
ec--;
if (sr <= er)
{
for(int i=ec; i>=sc; i--)
result[er][i] = v++;
er--;
}
if (sc <= ec)
{
for(int i=er; i>=sr; i--)
result[i][sc] = v++;
sc++;
}
}
}
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> result(n, vector<int>(n));
if (!n)
return result;
helper(0, 0, n-1, n-1, result, 1);
return result;
}
}; | true |
0818693c4ca2ab4ab88ebd2ae91a08bbcdf1f813 | C++ | mlz000/Algorithms | /leetcode/435.cpp | UTF-8 | 549 | 2.78125 | 3 | [] | no_license | class Solution {
public:
int eraseOverlapIntervals(vector<Interval>& intervals) {
if (intervals.empty()) return 0;
sort(intervals.begin(), intervals.end(), [](Interval& a, Interval& b){return a.start < b.start;});
int res = 0, n = intervals.size(), endLast = intervals[0].end;
for (int i = 1; i < n; ++i) {
int t = endLast > intervals[i].start ? 1 : 0;
endLast = t == 1 ? min(endLast, intervals[i].end) : intervals[i].end;
res += t;
}
return res;
}
}; | true |
b4f37fa4cb67f9c1a18f40188e17aca5f739d934 | C++ | JackZhouSz/ebpd_vs2015 | /PCM/skinning.h | UTF-8 | 2,254 | 2.703125 | 3 | [] | no_license | #ifndef _SKINNING_H
#define _SKINNING_H
#include "QGLViewer/vec.h"
#include "QGLViewer/quaternion.h"
class Vertex;
namespace PCM
{
class RigidTransform;
class SkinWeight;
class Skining
{
public:
static void caculateOneSample( std::vector<qglviewer::Vec>& final_vertices , const std::vector<qglviewer::Vec>& ori_vertices ,const std::vector<RigidTransform>& rts ,const SkinWeight& sk)
{
int numVertices;
int numBones;
final_vertices.resize(ori_vertices.size());
for( int i = 0 ; i < numVertices; ++ i)
{
for( int j = 0 ; j < numBones ; j++)
{
final_vertices[i] += rts[j].rotation()*ori_vertices[i]* sk( i, j) + rts[j].translation();
}
}
}
};
class RigidTransform
{
public:
qglviewer::Quaternion rotation() const
{
return m_rotation;
}
qglviewer::Vec translation() const
{
return m_translation;
}
private:
qglviewer::Quaternion m_rotation;
qglviewer::Vec m_translation;
};
class Transforms
{
public:
Transforms( int _numExamp , int _numBone)
:numExample(_numExamp),numBones(_numBone)
{
if( _numExamp >0 && _numBone >0)
boneTrans.resize( numBones * numBones);
}
std::vector<RigidTransform> boneTrans;
RigidTransform operator()( int i ,int j) const
{
return boneTrans[ i*numBones+j];
}
private:
int numExample;
int numBones;
};
class SkinWeight
{
public:
SkinWeight( int _numVertices , int _numBoneIndix )
:numVertices(_numVertices),numIndices(_numBoneIndix)
{
if( numVertices >0 && numIndices >0)
{
weight.resize( numVertices*numIndices );
index.resize( numVertices*numIndices );
}
}
float operator()( int i_vertice ,int i_bone) const
{
return findIFboneInVertice( i_vertice, i_bone);
}
float findIFboneInVertice( int i_vertice ,int i_bone) const
{
for (int i = 0; i < numIndices; i++)
{
if( index[i_vertice * numIndices + i] == i_bone)
return weight[i_vertice * numIndices + i];
}
return 0.0f;
}
private:
int numVertices;
int numIndices;
//! Skinning weight (number of vertices x index number)
std::vector<float> weight;
//! Index (number of vertices x number of indexes)
std::vector<int> index;
int index; //number of indexes
};
}
#endif | true |
ddc508efe164456b0d3fa5f0b5940e89dd183c81 | C++ | rendoir/feup-cpar | /Eratosthenes Sieve/SequentialSieve.cpp | UTF-8 | 1,815 | 3.28125 | 3 | [] | no_license | #include "SequentialSieve.h"
#include "Utils.h"
#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
//Odd-only sequential sieve of Eratosthenes
void SequentialSieveOfEratosthenes::run(unsigned long long exponent)
{
unsigned long long n = pow(2, exponent);
bool *primes = new bool[n/2];
fill_n(primes, n/2, true);
unsigned long long k = 3;
clock_t begin = clock();
do {
for (unsigned long long j = k*k ; j<n ; j+=2*k)
primes[j>>1]=false;
do {
k+=2;
} while (k*k <= n && !primes[k>>1]);
} while (k*k <= n);
double run_time = (double)(clock() - begin) / CLOCKS_PER_SEC;
print(primes, n, run_time);
delete primes;
}
int SequentialSieveOfEratosthenes::test()
{
unsigned long long exponent = 0;
if(Parameters::automatic) {
exponent = Parameters::current_exponent;
} else {
while(exponent <= 1) {
cout << "Exponent: ";
cin >> exponent;
}
}
run(exponent);
return 0;
}
void SequentialSieveOfEratosthenes::print(bool *primes, unsigned long long n, double run_time) {
if(Parameters::automatic) {
ofstream ofs(Parameters::output_file, ofstream::app);
ofs << "sequencial" << ';' << Parameters::current_exponent << ';' << run_time << endl;
ofs.close();
} else {
unsigned long long n_primes = n >= 2 ? 1 : 0;
cout << (n >= 2 ? "2 " : "");
for (unsigned long long i=3; i<n; i+=2) {
if (primes[i>>1]) {
n_primes++;
cout << i << " ";
}
}
cout << endl << "Found " << n_primes << " prime numbers" << endl;
cout << "Run time: " << run_time << " seconds" << endl;
}
}
| true |
cd11489b520e17bea60e26eaca48a6dcad1376ef | C++ | gouchengqiu/2017_Campus_Recruitment | /InterviewQuestions_Offer/6001_赋值运算符函数/MyString.h | UTF-8 | 934 | 3.0625 | 3 | [] | no_license | #pragma once
#include <stdio.h>
#include <string>
class CMyString
{
public:
CMyString(char* vData = NULL);
CMyString(const CMyString& vStr);
~CMyString();
CMyString& operator= (const CMyString& vOther);
private:
char* m_pData;
};
CMyString::CMyString(char* vData)
{
//int StrLength = 0;
//if (vData == NULL)
//{
// StrLength = 1;
//}else
//{
// StrLength = strlen(vData) + 1;
//}
//m_pData = new char[StrLength];
//m_pData = vData; //NULL error
if (vData == NULL)
{
m_pData = new char[1];
m_pData[0] = '\0';
}else
{
m_pData = new char[strlen(vData) + 1];
strcpy(m_pData, vData);
//m_pData = vData;
}
}
CMyString::CMyString(const CMyString& vStr)
{
CMyString(vStr.m_pData);
}
CMyString::~CMyString()
{
}
CMyString& CMyString::operator=(const CMyString& vOther)
{
delete[] m_pData;
m_pData = NULL;
m_pData = new char[strlen(vOther.m_pData) + 1];
m_pData = vOther.m_pData;
return *this;
} | true |
8211874be176e22996f1525b4df1a8dfbab1f2f5 | C++ | MadinaZ/pro | /main.cpp | UTF-8 | 2,376 | 2.875 | 3 | [] | no_license | //
// main.cpp
// FINAL_PROJECT
//
// Created by Madina Sadirmekova on 11/8/19.
// Copyright © 2019 Madina Sadirmekova. All rights reserved.
//
#include<iostream>
#include<string>
using namespace std;
#include "Queue.h"
#include "DynamicArray.h"
#include<fstream>
#include<cstdlib>
#include<ctime>
#include<iomanip>
#include<cmath>
struct Customer
{
char id;
int ArrivalTime;
int stayLength;
};
int getRandomNumberOfArrivals(double averageArrivalRate)
{
int arrivals = 0;
double probOfnArrivals = exp(-averageArrivalRate);
for(double randomValue = (double)rand( ) / RAND_MAX; (randomValue -= probOfnArrivals) > 0.0; probOfnArrivals *= averageArrivalRate / static_cast<double>(++arrivals));
return arrivals;
}
char getLetter(char &letter)
{
letter++;
if(letter > 'Z')
letter = 'A';
return letter;
}
int main() {
srand(time(0));
rand();
Queue<Customer> waitLine;
DynamicArray<Customer> serving;
DynamicArray<bool> serverStatus;
Customer client;
fstream file;
string fname, fstar, flocation, fprice, frate;
int budget, cust_num, star, sstar, sprice;
char *location, *slocation, *sname;
double rate, srate;
char letter = 'Z';
cust_num = 5;
for(int i = 0; i < cust_num; i++)
{
client.id = getLetter(letter);
cout<<"Customer: "<<client.id<<endl;
cout<<"Enter the city: \n";
cin>>location;
cout<<"How many stars: \n";
cin>>star;
cout<<"Enter the budget: \n";
cin>>budget;
cout<<"The rate should be above: \n";
cin>>rate;
cout<<"How the arrival time: \n";
cin>>client.ArrivalTime;
cout<<"What is your stay length? \n";
cin>>client.stayLength;
}
file.open("simulation.txt");
if(!file.good())
cout<<"I/O error \n";
while(file.good())
{
getline(file,fname, '\n');
getline(file,fstar, '\n');
getline(file,flocation, '\n');
getline(file,fprice, '\n');
getline(file,frate, '\n');
sstar= stoi(fstar);
srate = stof(frate);
int n1 = (int)fname.length();
int n2 = (int)flocation.length();
char Name[n1 + 1];
strcpy(Name, fname.c_str());
char Location[n2 + 1];
strcpy(Location, flocation.c_str());
}
return 0;
}
| true |
0369bda6869e629876e52425aa200601680695da | C++ | JesseTime/AngryBirdsClone | /Gfx.cpp | UTF-8 | 1,873 | 2.71875 | 3 | [] | no_license | #include "Gfx.h"
using namespace std;
const int SCREEN_WIDTH = 1024;
const int SCREEN_HEIGHT = 640;
const int SCREEN_BPP = 32;
const char *TITLE = "SDL Game Engine Test";
Gfx::Gfx()
{
screen = NULL;
if (!init())
{
SDL_Quit();
exit(1);
}
}
Gfx::~Gfx()
{
// Destructor
SDL_FreeSurface(screen);
SDL_Quit();
printf("\nExited Cleanly.\n");
}
bool Gfx::init()
{
// Initialize SDL
if(SDL_Init(SDL_INIT_EVERYTHING) < 0)
{
printf( "Unable to init SDL Video: %s\n", SDL_GetError() );
return false;
}
// Create the screen surface
screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE);
if(screen == NULL)
{
printf("Unable to set %ix%ix%i video: %s\n", SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_GetError());
return false;
}
if(TTF_Init() < 0)
{
return false;
}
// Set the title of the window
SDL_WM_SetCaption(TITLE, 0);
SDL_initFramerate(&fpsman);
SDL_setFramerate(&fpsman, 50);
SDL_FillRect(screen, &screen->clip_rect, SDL_MapRGB(screen->format, 0x00, 0x00, 0x00));
return true;
}
void Gfx::update()
{
}
void Gfx::clear()
{
}
void Gfx::render()
{
SDL_Flip(screen);
}
void Gfx::delay()
{
SDL_framerateDelay(&fpsman);
}
SDL_Surface *loadImage(string file)
{
SDL_Surface *loadedImage = NULL;
SDL_Surface *optimizedImage = NULL;
loadedImage = IMG_Load(file.c_str());
if (loadedImage != NULL)
{
optimizedImage = SDL_DisplayFormat(loadedImage);
SDL_FreeSurface(loadedImage);
}
return optimizedImage;
}
void applySurface (int x, int y, SDL_Surface* source, SDL_Surface* destination, SDL_Rect* clip = NULL)
{
SDL_Rect offset;
offset.x = x;
offset.y = y;
SDL_BlitSurface(source, NULL, destination, &offset);
}
| true |
80c7080afcfabea95fe35a12a42c01043e1e796d | C++ | sakayaparp/CodeChef | /Easy/Array Rotation Returns/ArrayRotationReturns.cpp | UTF-8 | 1,821 | 2.53125 | 3 | [
"Apache-2.0"
] | permissive | #include <bits/stdc++.h>
using namespace std;
#define int long long
#define mod 1000000007
int* input(int n)
{
int *arr = new int[n];
for(int i=0;i<n;i++)
cin >> arr[i];
return arr;
}
int gcd(int a,int b){
if(b==0)
return a;
return gcd(b,a%b);
}
signed main()
{
int t;
cin >> t;
while(t--)
{
int n;
cin >> n;
int *arrA = input(n);
int *arrB = input(n);
int OutFirst[n], OutSecond[n];
int temp_a = -1, temp_b = -1;
int min_v = INT_MAX;
for(int i=0;i<n;i++){
int x = (arrA[0] + arrB[i])%n;
if(min_v>x){
temp_a = i;
min_v = x;
}
else{
if(min_v==x){
temp_b = i;
}
}
}
int y = n;
int i = 0;
for(int j=temp_a;y--;j++){
OutFirst[i] = (arrA[i] + arrB[j%n])%n;
i++;
}
if(temp_b!=-1){
int y = n;
int i = 0;
for(int j=temp_b;y--;j++){
OutSecond[i] = (arrA[i] + arrB[j%n])%n;
i++;
}
}
bool flag1 = true;
if(temp_b!=-1){
for(int i=0;i<n;i++){
if(OutSecond[i]>OutFirst[i]){
break;
}else{
if(OutSecond[i]<OutFirst[i]){
flag1 = false;
break;
}
}
}
}
if(flag1){
for(int i=0;i<n;i++){
cout << OutFirst[i] << " ";
}
}else{
for(int i=0;i<n;i++){
cout << OutSecond[i] << " ";
}
}
cout << endl;
}
}
| true |
7e5555ff8cbfb47e1afcc305f74f2d285d5e22f7 | C++ | AllanNozomu/CompetitiveProgramming | /Leetcode/res/Fizz Buzz/2.cpp | UTF-8 | 676 | 2.703125 | 3 | [
"MIT"
] | permissive | \*
Author: allannozomu
Runtime: 8 ms
Memory: 10.4 MB*\
class Solution {
public:
vector<string> fizzBuzz(int n) {
vector<string> res;
for (int i = 1 ; i <= n; ++i){
int res3 = i % 3 == 0;
int res5 = i % 5 == 0;
if (res3){
if (res5){
res.push_back("FizzBuzz");
} else {
res.push_back("Fizz");
}
} else {
if (res5){
res.push_back("Buzz");
} else {
res.push_back(to_string(i));
}
}
}
return res;
}
}; | true |
ce40b27d85841467623bccbfb9e07f93f86c02b5 | C++ | JPalka/xerxes | /misc/resources.cpp | UTF-8 | 1,980 | 3.296875 | 3 | [] | no_license | #include "resources.h"
#include <iostream> //TEMP
Resources &Resources::operator- ( const Resources &rhs ) {
this->wood -= rhs.wood;
this->stone -= rhs.stone;
this->iron -= rhs.iron;
return *this;
}
//TODO: change it to return new Resources object
Resources &Resources::operator+ ( const Resources &rhs ) {
this->wood += rhs.wood;
this->stone += rhs.stone;
this->iron += rhs.iron;
return *this;
}
Resources &Resources::operator+= ( const Resources &rhs ) {
this->wood += rhs.wood;
this->stone += rhs.stone;
this->iron += rhs.iron;
return *this;
}
bool Resources::operator== ( const Resources &rhs ) {
if ( this->wood != rhs.wood )
return false;
if ( this->stone != rhs.stone )
return false;
if ( this->iron != rhs.iron )
return false;
return true;
}
bool Resources::operator>= ( const Resources &rhs ) {
if ( this->wood < rhs.wood )
return false;
if ( this->stone < rhs.stone )
return false;
if ( this->iron < rhs.iron )
return false;
return true;
}
bool Resources::operator> ( const Resources &rhs ) {
if ( this->wood <= rhs.wood ) {
return false;
}
if ( this->stone <= rhs.stone ) {
return false;
}
if ( this->iron <= rhs.iron ) {
return false;
}
return true;
}
Resources Resources::operator* ( long rhs ) {
Resources result ( this->wood * rhs, this->stone * rhs, this->iron * rhs );
return result;
}
Resources::Resources () {
}
Resources::Resources ( double wood, double stone, double iron ): wood(wood), stone(stone), iron(iron) {
}
std::string Resources::toString () {
std::string result = "";
result += "Wood:" + std::to_string ((int)this->wood) + " Stone:" + std::to_string ((int)this->stone) + " Iron:" + std::to_string ((int)this->iron);
return result;
}
//TEMPORARY << OVERLOAD FOR DEBADGERING PURPOSES.
std::ostream &operator<< ( std::ostream &os, Resources &rhs ) {
os << "Wood: " << rhs.wood << std::endl;
os << "Stone: " << rhs.stone << std::endl;
os << "Iron: " << rhs.iron << std::endl;
return os;
}
| true |
ee2a693a39df69449e1bca8c84bc8d7836a2c99b | C++ | dalalsunil1986/OnlineJudge-Solution | /URI Online Judge/uri 1216.cpp | UTF-8 | 305 | 2.546875 | 3 | [] | no_license | #include<iostream>
#include<string>
#include<iomanip>
using namespace std;
int main()
{
double n,sum;
int c;
string str;
char ch;
while(getline(cin,str))
{
cin>>n;
ch = getchar();
sum+=n;
c++;
}
cout<<fixed<<setprecision(1)<<sum/c<<endl;
}
| true |
7a196a3b921f74bb567232739f9acd57ef901444 | C++ | profeIMA/PID-UdG | /installation/Windows/Window_Addon_Allegro/include/windowAddon/Figures.h | UTF-8 | 16,573 | 3.375 | 3 | [] | no_license | #ifndef FIGURES_H
#define FIGURES_H
#ifndef NULL
#define NULL 0
#endif
#include "Point2D.h"
#include "Angle.h"
#include "CommonUtils.h"
///@brief Contains some structs that can store information about some geometric figures.
/** This namespace contains a series of structs that store the information about some geometric figures usually used to draw objects on a Window. You can use them for any other purposes as well.*/
namespace figures {
struct Line {
Point2D p1, /**< An end point of the line. */
p2; /**< An end point of the line. */
/** Default constructor. */
Line() {}
/** Parametric constructor.
* @param p1 First end point of the line.
* @param p2 Last end point of the line.
*/
Line(Point2D p1, Point2D p2) { init(p1, p2); }
/** Parametric constructor.
* @param x1 X coordinate of the first end point of the line.
* @param y1 Y coordinate of the first end point of the line.
* @param x2 X coordinate of the other end point of the line.
* @param y2 Y coordinate of the other end point of the line.
*/
Line(float x1, float y1, float x2, float y2) { init(Point2D(x1, y1), Point2D(x2, y2)); }
/** Initializes the line.
* @param p1 First end point of the line.
* @param p2 Last end point of the line.
*/
void init(Point2D p1, Point2D p2) { this->p1 = p1; this->p2 = p2; }
};
struct Triangle {
Point2D p1, /**< A vertex of the triangle.*/
p2, /**< A vertex of the triangle.*/
p3; /**< A vertex of the triangle.*/
/** Default constructor. */
Triangle() {}
/** Parametric constructor.
* @param p1 First vertex of the triangle.
* @param p2 Second vertex of the triangle.
* @param p3 Third vertex of the triangle.
*/
Triangle(Point2D p1, Point2D p2, Point2D p3) { init(p1, p2, p3); }
/** Parametric constructor.
* @param x1 X coordinate of the first vertex of the triangle.
* @param y1 Y coordinate of the first vertex of the triangle.
* @param x2 X coordinate of the second vertex of the triangle.
* @param y2 Y coordinate of the second vertex of the triangle.
* @param x3 X coordinate of the third vertex of the triangle.
* @param y3 Y coordinate of the third vertex of the triangle.
*/
Triangle(float x1, float y1, float x2, float y2, float x3, float y3) { init(Point2D(x1, y1), Point2D(x2, y2), Point2D(x3, y3)); }
/** Initializes the triangle.
* @param p1 First vertex of the triangle.
* @param p2 Second vertex of the triangle.
* @param p3 Third vertex of the triangle.
*/
void init(Point2D p1, Point2D p2, Point2D p3) { this->p1 = p1; this->p2 = p2; this->p3 = p3; }
};
struct Rectangle {
Point2D p1, /**< Top left corner of the rectangle. */
p2; /**< Bottom right corner of the rectangle. */
/** Default constructor. */
Rectangle() {}
/** Parametric constructor.
* @param p1 Top left corner of the rectangle.
* @param p2 Bottom right corner of the rectangle.
*/
Rectangle(Point2D p1, Point2D p2) { init(p1, p2); }
/** Parametric constructor.
* @param x1 X coordinate of the top left corner of the rectangle.
* @param y1 Y coordinate of the top left corner of the rectangle.
* @param x2 X coordinate of the bottom right corner of the rectangle.
* @param y2 Y coordinate of the bottom right corner of the rectangle.
*/
Rectangle(float x1, float y1, float x2, float y2) { init(Point2D(x1, y1), Point2D(x2, y2)); }
/** Initializes the rectangle.
* @param p1 Top left corner of the rectangle.
* @param p2 Bottom right corner of the rectangle.
*/
void init(Point2D p1, Point2D p2) { this->p1 = p1; this->p2 = p2; }
};
struct RoundedRectangle {
Point2D p1, /**< Top left corner of the rectangle. */
p2; /**< Bottom right corner of the rectangle. */
float rx, /**< Horizontal radius of the rounding ellipse. */
ry; /**< Vertical radius of the rounding ellipse. */
/** Default constructor. */
RoundedRectangle() { rx = 0; ry = 0; }
/** Parametric constructor.
* @param p1 coordinates of the top left corner.
* @param p2 coordinates of the bottom right corner.
* @param rx Horizontal radius of the rounding ellipse.
* @param ry Vertical radius of the rounding ellipse.
*/
RoundedRectangle(Point2D p1, Point2D p2, float rx, float ry) { init(p1, p2, rx, ry); }
/** Parametric constructor.
* @param x1 X coordinate of the top left corner.
* @param y1 Y coordinate of the top left corner.
* @param x2 X coordinate of the bottom right corner.
* @param y2 Y coordinate of the bottom right corner.
* @param rx Horizontal radius of the rounding ellipse.
* @param ry Vertical radius of the rounding ellipse.
*/
RoundedRectangle(float x1, float y1, float x2, float y2, float rx, float ry) { init(Point2D(x1, y1), Point2D(x2, y2), rx, ry); }
/** Initializes the rectangle.
* @param p1 coordinates of the top left corner.
* @param p2 coordinates of the bottom right corner.
* @param rx Horizontal radius of the rounding ellipse.
* @param ry Vertical radius of the rounding ellipse.
*/
void init(Point2D p1, Point2D p2, float rx, float ry) { this->p1 = p1; this->p2 = p2; this->rx = rx; this->ry = ry; }
};
struct Circle {
Point2D center; /**< Center of the circle. */
float r; /**< Radius of the circle. */
/** Default constructor. */
Circle() { r = 0; }
/** Parametric constructor.
* @param c coordinates of the center of the circle.
* @param r Radius of the circle.
*/
Circle(Point2D center, float r) { init(center, r); }
/** Parametric constructor.
* @param cx X coordinate of the center of the circle.
* @param cy Y coordinate of the center of the circle.
* @param r Radius of the circle.
*/
Circle(float cx, float cy, float r) { init(Point2D(cx, cy), r); }
/** Initializes the circle.
* @param c coordinates of the center of the circle.
* @param r Radius of the circle.
*/
void init(Point2D center, float r) { this->center = center; this->r = r; }
};
struct Ellipse {
Point2D center; /**< Center of the ellipse. */
float rx, /**< Horizontal radius of the ellipse. */
ry; /**< Vertical radius of the ellipse. */
/** Default constructor. */
Ellipse() { rx = 0; ry = 0; }
/** Parametric constructor.
* @param c coordinates of the center of the ellipse.
* @param rx Horizontal radius of the ellipse.
* @param ry Vertical radius of the ellipse.
*/
Ellipse(Point2D center, float rx, float ry) { init(center, rx, ry); }
/** Parametric constructor.
* @param cx X coordinate of the center of the ellipse.
* @param cy Y coordinate of the center of the ellipse.
* @param rx Horizontal radius of the ellipse.
* @param ry Vertical radius of the ellipse.
*/
Ellipse(float cx, float cy, float rx, float ry) { init(Point2D(cx, cy), rx, ry); }
/** Initializes the ellipse.
* @param c coordinates of the center of the ellipse.
* @param rx Horizontal radius of the ellipse.
* @param ry Vertical radius of the ellipse.
*/
void init(Point2D center, float rx, float ry) { this->center = center; this->rx = rx; this->ry = ry; }
};
struct Arc {
Point2D center; /**< Center of the arc. */
float r; /**< Radius of the arc. */
Angle angle; /**< Angle of the arc. */
/** Default constructor. */
Arc() {}
/** Parametric constructor.
* @param c coordinates of the center of the arc.
* @param r Radius of the arc.
* @param angle Angle of the arc.
*/
Arc(Point2D center, float r, Angle angle) { init(center, r, angle); }
/** Parametric constructor.
* @param cx X coordinate of the center of the arc.
* @param cy Y coordinate of the center of the arc.
* @param r Radius of the arc.
* @param angle Angle of the arc.
*/
Arc(float cx, float cy, float r, Angle angle) { init(Point2D(cx, cy), r, angle); }
/** Parametric constructor.
* @param c coordinates of the center of the arc.
* @param r Radius of the arc.
* @param start Start point of the angle.
* @param delta Angle increase.
* @param angle_conversion_type If the angle has to be converted before creating the arc, a conversion type should be specified.
*/
Arc(Point2D center, float r, float start, float delta, int angle_conversion_type) { init(center, r, Angle(start, delta, angle_conversion_type)); }
/** Parametric constructor.
* @param cx X coordinate of the center of the arc.
* @param cy Y coordinate of the center of the arc.
* @param r Radius of the arc.
* @param start Start point of the angle.
* @param delta Angle increase.
* @param angle_conversion_type If the angle has to be converted before creating the arc, a conversion type should be specified.
*/
Arc(float cx, float cy, float r, float start, float delta, int angle_conversion_type) { init(Point2D(cx, cy), r, Angle(start, delta, angle_conversion_type)); }
/** Initializes the arc.
* @param c coordinates of the center of the arc.
* @param r Radius of the arc.
* @param angle Angle of the arc.
*/
void init(Point2D center, float r, Angle angle) { this->center = center; this->r = r; this->angle = angle; }
};
struct EllipticalArc {
Point2D center; /**< Center of the arc. */
float rx, /**< Horizontal radius of the arc.*/
ry; /**< Vertical radius of the arc. */
Angle angle; /**< Angle of the arc. */
/** Default constructor. */
EllipticalArc() {}
/** Parametric constructor.
* @param center coordinates of the center of the arc.
* @param rx Horizontal radius of the arc.
* @param ry Vertical radius of the arc.
* @param angle Angle of the arc.
*/
EllipticalArc(Point2D center, float rx, float ry, Angle angle) { init(center, rx, ry, angle); }
/** Parametric constructor.
* @param cx X coordinate of the center of the arc.
* @param cy Y coordinate of the center of the arc.
* @param rx Horizontal radius of the arc.
* @param ry Vertical radius of the arc.
* @param angle Angle of the arc.
*/
EllipticalArc(float cx, float cy, float rx, float ry, Angle angle) { init(Point2D(cx, cy), rx, ry, angle); }
/** Parametric constructor.
* @param center coordinates of the center of the arc.
* @param rx Horizontal radius of the arc.
* @param ry Vertical radius of the arc.
* @param start_theta Start point of the angle.
* @param delta_theta Angle increase.
* @param angle_conversion_type If the angle has to be converted before creating the arc, a conversion type should be specified.
*/
EllipticalArc(Point2D center, float rx, float ry, float start, float delta, int angle_conversion_type) { init(center, rx, ry, Angle(start, delta, angle_conversion_type)); }
/** Parametric constructor.
* @param cx X coordinate of the center of the arc.
* @param cy Y coordinate of the center of the arc.
* @param rx Horizontal radius of the arc.
* @param ry Vertical radius of the arc.
* @param start_theta Start point of the angle.
* @param delta_theta Angle increase.
* @param angle_conversion_type If the angle has to be converted before creating the arc, a conversion type should be specified.
*/
EllipticalArc(float cx, float cy, float rx, float ry, float start, float delta, int angle_conversion_type) { init(Point2D(cx, cy), rx, ry, Angle(start, delta, angle_conversion_type)); }
/** Initializes the arc.
* @param center coordinates of the center of the arc.
* @param rx Horizontal radius of the arc.
* @param ry Vertical radius of the arc.
* @param angle Angle of the arc.
*/
void init(Point2D center, float rx, float ry, Angle angle) { this->center = center; this->rx = rx; this->ry = ry; this->angle = angle; }
};
typedef Arc Pieslice; //A pie slice is basically an arc with two radii joining both ends with the center of that arc, the attributes are the same
//The following structs doesn't use Point2D for efficiency reasons.
struct Spline {
float* points; /**< Array of X and Y coordinates that defines the spline's control points.*/
/** Default constructor. */
Spline() { points = NULL; }
/** Parametric constructor.
* @param points Array of X and Y coordinates containing the spline's control points.
*/
Spline(const float points[8]) { init(points); }
/** Copy constructor.
* @param s The Spline to be copied.
*/
Spline(const Spline & s) { copy(s); }
/** Destructor. */
~Spline() { destroy(); }
/** Assignment operator.
* @param s The spline to be copied in the assignment.
*/
Spline& operator=(const Spline & s) {
if (this != &s) {
destroy();
copy(s);
}
return *this;
}
/** Initializes the spline.
* @param points Array of X and Y coordinates containing the spline's control points.
*/
void init(const float points[8]) { this->points = getCopyOfArray(points, 8); }
/** Copies the information of @p s into this Spline.
* @param s The spline to be copied.
*/
void copy(const Spline & s) { init(s.points); }
/** Frees all dynamic memory assigned to this struct. */
void destroy() { if (points) delete points; }
};
struct Polygon {
float* points; /**< Array of X and Y coordinates that defines the polygon's points.*/
int num_points; /**< Number of vertices the polygon has. */
/** Default constructor. */
Polygon() { points = NULL; num_points = 0; }
/** Parametric constructor.
* @param points Array of X and Y coordinates containing the polygon's points.
* @param num_points Number of pairs of coordinates @p points has.
*/
Polygon(const float* points, int num_points) { init(points, num_points); }
/** Copy constructor.
* @param p The Polygon to be copied.
*/
Polygon(const Polygon & p) { copy(p); }
/** Destructor. */
~Polygon() { destroy(); }
/** Assignment operator.
* @param p The polygon to be copied in the assignment.
*/
Polygon& operator=(const Polygon & p) {
if (this != &p) {
destroy();
copy(p);
}
return *this;
}
/** Initializes the polygon.
* @param points Array of X and Y coordinates containing the polygon's points.
* @param num_points Number of pairs of coordinates @p points has.
*/
void init(const float* points, int num_points) { this->points = getCopyOfArray(points, num_points * 2); this->num_points = num_points; }
/** Copies the information of @p p into this Polygon.
* @param p The polygon to be copied.
*/
void copy(const Polygon & p) { init(p.points, p.num_points); }
/** Frees all dynamic memory assigned to this struct. */
void destroy() { if (points) delete points; }
};
typedef Polygon Polyline; //The main difference is that a polygon joins the last point with the first, but the data stored is the same
typedef Polyline Ribbon; //basically the same thing
struct Multipolygon { //multiple polygons stored as one figure (its intended use is for polygonWithHoles() function)
float* vertices; /**< Array of X and Y coordinates that defines the polygons' vertices.*/
int* vertex_counts; /**< Number of vertices for each polygon */
/** Default constructor. */
Multipolygon() { vertices = NULL; vertex_counts = NULL; }
/** Parametric constructor.
* @param vertices Array of X and Y coordinates containing the polygons' vertices.
* @param vertex_counts Number of vertices of each polygon in @p vertices.
*/
Multipolygon(const float* vertices, const int* vertex_counts) { init(vertices, vertex_counts); }
/** Copy constructor.
* @param mp The Multipolygon to be copied.
*/
Multipolygon(const Multipolygon & mp) { copy(mp); }
/** Destructor. */
~Multipolygon() { destroy(); }
/** Assignment operator.
* @param mp The multipolygon to be copied in the assignment.
*/
Multipolygon& operator=(const Multipolygon & mp) {
if (this != &mp) {
destroy();
copy(mp);
}
return *this;
}
/** Initializes the polygon.
* @param vertices Array of X and Y coordinates containing the polygons' vertices.
* @param vertex_counts Number of vertices of each polygon in @p points.
*/
void init(const float* vertices, const int* vertex_counts) {
int total_vertices = 2 * intArraySum(vertex_counts);
this->vertices = getCopyOfArray(vertices, total_vertices);
this->vertex_counts = getCopyOfArray(vertex_counts, nElements(vertex_counts));
}
/** Copies the information of @p mp into this Polygon.
* @param mp The multipolygon to be copied.
*/
void copy(const Multipolygon & mp) { init(mp.vertices, mp.vertex_counts); }
/** Frees all dynamic memory assigned to this struct. */
void destroy() { if (vertices) delete vertices; if (vertex_counts) delete vertex_counts; }
};
}
#endif | true |
d64a4ca86f2c706f4357cb6af48c3b523e1eeee3 | C++ | gdehmlow/cs283-hw2 | /Screen.h | UTF-8 | 570 | 2.953125 | 3 | [] | no_license | /*
Screen.h
Responsible for holding pixel color data and displaying the image.
*/
#ifndef I_SCREEN
#define I_SCREEN
#include <glm/glm.hpp>
typedef unsigned char Byte;
class Screen {
public:
Screen();
~Screen();
void init(const int width, const int height);
void writePixel(const glm::dvec3& color, const int x, const int y);
void saveScreenshot(const char* outputFilename);
int getWidth();
int getHeight();
private:
int width;
int height;
Byte* pixelArray;
};
#endif
| true |
5a98713f210944c252972b03b56a902883c0cc38 | C++ | KakuyaShiraishi/MySocket | /proxy.cpp | UTF-8 | 1,214 | 2.734375 | 3 | [] | no_license | #include "Socket.h"
#include <iostream>
#include <process.h>
#include <sstream>
int portProxy;
std::string addrServer;
int portServer;
unsigned __stdcall RunProxyThread (void* a) {
Socket* s = (Socket*) a;
SocketClient c(addrServer, portServer);
while (1) {
SocketSelect sel(s, &c);
bool still_connected = true;
if (sel.Readable(s)) {
std::string bytes = s->ReceiveBytes();
c.SendBytes(bytes);
std::cout << "Server: " << bytes << std::endl;
if (bytes.empty()) still_connected=false;
}
if (sel.Readable(&c)) {
std::string bytes = c.ReceiveBytes();
s->SendBytes(bytes);
std::cout << "Client: " << bytes << std::endl;
if (bytes.empty()) still_connected=false;
}
if (! still_connected) {
break;
}
}
delete s;
return 0;
}
int main(int argc, char* argv[]) {
if (argc < 4) {
return -1;
}
std::stringstream s;
s<<argv[1]; s>>portProxy; s.clear();
addrServer=argv[2];
s<<argv[3]; s>>portServer;
SocketServer in(portProxy,5);
while (1) {
Socket* s=in.Accept();
unsigned ret;
_beginthreadex(0, 0, RunProxyThread,(void*) s,0,&ret);
}
return 0;
}
| true |
5cf9db8bb1f0c544634175779b60cdc0970f733d | C++ | freedomDR/coding | /codeforces/1189/D1/1189-D1.cpp | UTF-8 | 408 | 2.640625 | 3 | [
"MIT"
] | permissive | #include<bits/stdc++.h>
using namespace std;
int main()
{
int n; cin >> n;
vector<int> deg(n+1);
for(int i = 0; i < n-1; i++) {
int u, v; cin >> u >> v;
deg[u]++;
deg[v]++;
}
bool ok = true;
for(int i = 0; i < n+1; i++) {
if(deg[i] == 2) {
ok = false;
break;
}
}
cout << (ok?"YES":"NO") << endl;
return 0;
}
| true |
07aab92cfc4fc9c10e07f9c73b60d2743704c2c7 | C++ | anmeert/PhysiBoSSv2 | /sample_projects/template_BM/custom_modules/custom_main.cpp | UTF-8 | 1,066 | 2.6875 | 3 | [] | no_license | #include "./custom_main.h"
/**
* \main Template-BM custom main file
* \brief Custom module file for template-BM sample_project
*
* \details Modules needed for the template-BM sample_project. This custom module can be used as template to generate other PhysiBoSS examples.
*
* \date 19/10/2020
* \author Gerard Pradas and Miguel Ponce de Leon
*/
void inject_density_sphere(int density_index, double concentration, double membrane_lenght)
{
// Inject given concentration on the extremities only
#pragma omp parallel for
for( int n=0; n < microenvironment.number_of_voxels() ; n++ )
{
auto current_voxel = microenvironment.voxels(n);
std::vector<double> cent = {current_voxel.center[0], current_voxel.center[1], current_voxel.center[2]};
if ((membrane_lenght - norm(cent)) <= 0)
microenvironment.density_vector(n)[density_index] = concentration;
}
}
void remove_density( int density_index )
{
for( int n=0; n < microenvironment.number_of_voxels() ; n++ )
microenvironment.density_vector(n)[density_index] = 0;
std::cout << "Removal done" << std::endl;
} | true |
9f0af9b4536ef337b89ae9b323c53f983c6c33de | C++ | marco-c/gecko-dev-comments-removed | /third_party/libwebrtc/modules/congestion_controller/goog_cc/trendline_estimator_unittest.cc | UTF-8 | 4,782 | 2.5625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive |
#include "modules/congestion_controller/goog_cc/trendline_estimator.h"
#include <algorithm>
#include <numeric>
#include <vector>
#include "api/transport/field_trial_based_config.h"
#include "rtc_base/random.h"
#include "test/gtest.h"
namespace webrtc {
namespace {
class PacketTimeGenerator {
public:
PacketTimeGenerator(int64_t initial_clock, double time_between_packets)
: initial_clock_(initial_clock),
time_between_packets_(time_between_packets),
packets_(0) {}
int64_t operator()() {
return initial_clock_ + time_between_packets_ * packets_++;
}
private:
const int64_t initial_clock_;
const double time_between_packets_;
size_t packets_;
};
class TrendlineEstimatorTest : public testing::Test {
public:
TrendlineEstimatorTest()
: send_times(kPacketCount),
recv_times(kPacketCount),
packet_sizes(kPacketCount),
config(),
estimator(&config, nullptr),
count(1) {
std::fill(packet_sizes.begin(), packet_sizes.end(), kPacketSizeBytes);
}
void RunTestUntilStateChange() {
RTC_DCHECK_EQ(send_times.size(), kPacketCount);
RTC_DCHECK_EQ(recv_times.size(), kPacketCount);
RTC_DCHECK_EQ(packet_sizes.size(), kPacketCount);
RTC_DCHECK_GE(count, 1);
RTC_DCHECK_LT(count, kPacketCount);
auto initial_state = estimator.State();
for (; count < kPacketCount; count++) {
double recv_delta = recv_times[count] - recv_times[count - 1];
double send_delta = send_times[count] - send_times[count - 1];
estimator.Update(recv_delta, send_delta, send_times[count],
recv_times[count], packet_sizes[count], true);
if (estimator.State() != initial_state) {
return;
}
}
}
protected:
const size_t kPacketCount = 25;
const size_t kPacketSizeBytes = 1200;
std::vector<int64_t> send_times;
std::vector<int64_t> recv_times;
std::vector<size_t> packet_sizes;
const FieldTrialBasedConfig config;
TrendlineEstimator estimator;
size_t count;
};
}
TEST_F(TrendlineEstimatorTest, Normal) {
PacketTimeGenerator send_time_generator(123456789 ,
20 );
std::generate(send_times.begin(), send_times.end(), send_time_generator);
PacketTimeGenerator recv_time_generator(987654321 ,
20 );
std::generate(recv_times.begin(), recv_times.end(), recv_time_generator);
EXPECT_EQ(estimator.State(), BandwidthUsage::kBwNormal);
RunTestUntilStateChange();
EXPECT_EQ(estimator.State(), BandwidthUsage::kBwNormal);
EXPECT_EQ(count, kPacketCount);
}
TEST_F(TrendlineEstimatorTest, Overusing) {
PacketTimeGenerator send_time_generator(123456789 ,
20 );
std::generate(send_times.begin(), send_times.end(), send_time_generator);
PacketTimeGenerator recv_time_generator(987654321 ,
1.1 * 20 );
std::generate(recv_times.begin(), recv_times.end(), recv_time_generator);
EXPECT_EQ(estimator.State(), BandwidthUsage::kBwNormal);
RunTestUntilStateChange();
EXPECT_EQ(estimator.State(), BandwidthUsage::kBwOverusing);
RunTestUntilStateChange();
EXPECT_EQ(estimator.State(), BandwidthUsage::kBwOverusing);
EXPECT_EQ(count, kPacketCount);
}
TEST_F(TrendlineEstimatorTest, Underusing) {
PacketTimeGenerator send_time_generator(123456789 ,
20 );
std::generate(send_times.begin(), send_times.end(), send_time_generator);
PacketTimeGenerator recv_time_generator(987654321 ,
0.85 * 20 );
std::generate(recv_times.begin(), recv_times.end(), recv_time_generator);
EXPECT_EQ(estimator.State(), BandwidthUsage::kBwNormal);
RunTestUntilStateChange();
EXPECT_EQ(estimator.State(), BandwidthUsage::kBwUnderusing);
RunTestUntilStateChange();
EXPECT_EQ(estimator.State(), BandwidthUsage::kBwUnderusing);
EXPECT_EQ(count, kPacketCount);
}
TEST_F(TrendlineEstimatorTest, IncludesSmallPacketsByDefault) {
PacketTimeGenerator send_time_generator(123456789 ,
20 );
std::generate(send_times.begin(), send_times.end(), send_time_generator);
PacketTimeGenerator recv_time_generator(987654321 ,
1.1 * 20 );
std::generate(recv_times.begin(), recv_times.end(), recv_time_generator);
std::fill(packet_sizes.begin(), packet_sizes.end(), 100);
EXPECT_EQ(estimator.State(), BandwidthUsage::kBwNormal);
RunTestUntilStateChange();
EXPECT_EQ(estimator.State(), BandwidthUsage::kBwOverusing);
RunTestUntilStateChange();
EXPECT_EQ(estimator.State(), BandwidthUsage::kBwOverusing);
EXPECT_EQ(count, kPacketCount);
}
}
| true |
be6f3857d35e72ce6c6bcb499d18511bc1fe1fdd | C++ | PADrend/EScript | /EScript/Utils/Logger.h | UTF-8 | 3,087 | 2.609375 | 3 | [
"MIT"
] | permissive | // Logger.h
// This file is part of the EScript programming language (https://github.com/EScript)
//
// Copyright (C) 2012-2013 Claudius Jähn <ClaudiusJ@live.de>
// Copyright (C) 2012 Benjamin Eikel <benjamin@eikel.org>
//
// Licensed under the MIT License. See LICENSE file for details.
// ---------------------------------------------------------------------------------
#ifndef ES_Logger_H
#define ES_Logger_H
#include "EReferenceCounter.h"
#include "ObjRef.h"
#include <map>
#include <string>
#include <ostream>
namespace EScript {
//! [Logger]
class Logger : public EReferenceCounter<Logger> {
public:
enum level_t{
LOG_ALL = 0,
LOG_DEBUG = 1,
LOG_INFO = 2,
LOG_PEDANTIC_WARNING = 3,
LOG_WARNING = 4,
LOG_ERROR = 5,
LOG_FATAL = 6,
LOG_NONE = 10
};
Logger(level_t _minLevel = LOG_ALL,level_t _maxLevel = LOG_NONE) : minLevel(_minLevel),maxLevel(_maxLevel){}
virtual ~Logger(){}
void debug(const std::string & msg) { log(LOG_DEBUG,msg); }
void error(const std::string & msg) { log(LOG_ERROR,msg); }
void fatal(const std::string & msg) { log(LOG_FATAL,msg); }
level_t getMinLevel()const { return minLevel; }
level_t getMaxLevel()const { return maxLevel; }
void info(const std::string & msg) { log(LOG_INFO,msg); }
void log(level_t l,const std::string & msg) { if(testLevel(l)) doLog(l,msg); }
void pedantic(const std::string & msg) { log(LOG_PEDANTIC_WARNING,msg); }
void setMinLevel(level_t l) { minLevel = l; }
void setMaxLevel(level_t l) { maxLevel = l; }
void warn(const std::string & msg) { log(LOG_WARNING,msg); }
private:
bool testLevel(level_t t)const { return static_cast<int>(t)>=static_cast<int>(minLevel) &&
static_cast<int>(t)<=static_cast<int>(maxLevel); }
//! ---o
virtual void doLog(level_t l,const std::string & msg) = 0;
level_t minLevel;
level_t maxLevel;
};
// ------------------------------------------------------------------------------------------------
/*! [LoggerGroup] ---|>[Logger]
|
--------> [Logger*] */
class LoggerGroup : public Logger {
public:
LoggerGroup(level_t _minLevel = LOG_ALL,level_t _maxLevel = LOG_NONE) : Logger(_minLevel,_maxLevel){}
virtual ~LoggerGroup(){}
void addLogger(const std::string & name,Logger * logger);
bool removeLogger(const std::string & name);
void clearLoggers();
Logger * getLogger(const std::string & name);
private:
//! ---|> Logger
void doLog(level_t l,const std::string & msg) override;
typedef std::map<std::string, _CountedRef<Logger> > loggerRegistry_t;
loggerRegistry_t loggerRegistry;
};
// ------------------------------------------------------------------------------------------------
/*! [StdLogger] ---|>[Logger]
|
--------> std::ostream */
class StdLogger : public Logger {
public:
StdLogger(std::ostream & stream, level_t _minLevel = LOG_ALL,level_t _maxLevel = LOG_NONE) : Logger(_minLevel,_maxLevel),out(stream){}
virtual ~StdLogger(){}
private:
//! ---|> Logger
void doLog(level_t l,const std::string & msg) override;
std::ostream & out;
};
}
#endif // ES_Logger_H
| true |
1607ceb2a705ebf2adafeb5d8b66a8995b112913 | C++ | Cyanael/PatternMatching | /src/optimal_tradeoff_kmism/Propre/comparFiles.cpp | UTF-8 | 1,053 | 2.609375 | 3 | [] | no_license | /* Copyright : GNU GPL V3
Author : Tatiana Rocher, tatiana.rocher@gmail.com
*/
#include<iostream>
#include <fstream>
using namespace std;
int main(int argc, char* argv[]){
if (argc < 3) {
cout << "Usage: ./exec k_mism_res exact_res" << endl;
cout << "If no ouput file is mentionned, result is in verif.out." << endl;
cout << "/!\\ This algorithm is slow!" << endl;
}
int m, n;
string inText= argv[1];
ifstream fileText(inText.c_str(), ios::in);
if (!fileText){
cout << "Can't open first file." << endl;
return 0;
}
string inPat= argv[2];
ifstream filePattern(inPat.c_str(), ios::in);
if (!filePattern){
cout << "Can't open second file." << endl;
return 0;
}
int i=0;
int nb_errors = 0;
while(fileText >> n){
filePattern >> m;
if (m != n){
if (nb_errors == 0)
cout << "first error at position " << i << " " << n << " != " << m << endl;
nb_errors++;
}
i++;
}
if (nb_errors == 0)
cout << "Both files are identicals." << endl;
else
cout << "There are " << nb_errors << " errors between the files." << endl;
return 0;
}
| true |
b0effb913135470fdca68e1ded4681c089cb3358 | C++ | diegomazala/UE4_Studies | /Plugins/ImageLoaderPlugin/Source/ImageLoaderPlugin/Public/ImageLoader.h | UTF-8 | 3,450 | 2.578125 | 3 | [
"MIT"
] | permissive | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "UObject/NoExportTypes.h"
#include "PixelFormat.h"
#include "ImageLoader.generated.h"
class UTexture2D;
/**
Utility class for asynchronously loading an image into a texture.
Allows Blueprint scripts to request asynchronous loading of an image and be notified when loading is complete.
*/
UCLASS(BlueprintType)
class IMAGELOADERPLUGIN_API UImageLoader : public UObject
{
GENERATED_BODY()
public:
/**
Loads an image file from disk into a texture on a worker thread. This will not block the calling thread.
@return An image loader object with an OnLoadCompleted event that users can bind to, to get notified when loading is done.
*/
UFUNCTION(BlueprintCallable, Category = ImageLoader, meta = (HidePin = "Outer", DefaultToSelf = "Outer"))
static UImageLoader* LoadImageFromDiskAsync(UObject* Outer, const FString& ImagePath, int32 Id);
/**
Loads an image file from disk into a texture on a worker thread. This will not block the calling thread.
@return A future object which will hold the image texture once loading is done.
*/
static TFuture<UTexture2D*> LoadImageFromDiskAsync(UObject* Outer, const FString& ImagePath, TFunction<void()> CompletionCallback);
/**
Loads an image file from disk into a texture. This will block the calling thread until completed.
@return A texture created from the loaded image file.
*/
UFUNCTION(BlueprintCallable, Category = ImageLoader, meta = (HidePin = "Outer", DefaultToSelf = "Outer"))
static UTexture2D* LoadImageFromDisk(UObject* Outer, const FString& ImagePath);
UFUNCTION(BlueprintCallable, Category = ImageLoader, meta = (HidePin = "Outer", DefaultToSelf = "Outer"))
static UTexture2D* LoadDDSFromDisk(UObject* Outer, const FString& ImagePath);
/** Helper function to dynamically create a new texture from raw pixel data. */
UFUNCTION(BlueprintCallable, Category = ImageLoader, meta = (HidePin = "Outer", DefaultToSelf = "Outer"))
static UTexture2D* CreateTexture(UObject* Outer, const TArray<uint8>& PixelData, int32 InSizeX, int32 InSizeY,
EPixelFormat PixelFormat = EPixelFormat::PF_B8G8R8A8, FName BaseName = NAME_None);
/**
Declare a broadcast-style delegate type, which is used for the load completed event.
Dynamic multicast delegates are the only type of event delegates that Blueprint scripts can bind to.
*/
DECLARE_DYNAMIC_MULTICAST_DELEGATE_TwoParams(FOnImageLoadCompleted, UTexture2D*, Texture, int32, Id);
/** This accessor function allows C++ code to bind to the event. */
FOnImageLoadCompleted& OnLoadCompleted()
{
return LoadCompleted;
}
UFUNCTION(BlueprintCallable, Category = ImageLoader, meta = (HidePin = "Outer", DefaultToSelf = "Outer"))
static bool CopyTexture(UTexture2D* SourceTexture2D, UTexture2D* DestTexture2D);
private:
/** Helper function that initiates the loading operation and fires the event when loading is done. */
void LoadImageAsync(UObject* Outer, const FString& ImagePath, int32 Id);
/**
Holds the load completed event delegate.
Giving Blueprint access to this private variable allows Blueprint scripts to bind to the event.
*/
UPROPERTY(BlueprintAssignable, Category = ImageLoader, meta = (AllowPrivateAccess = true))
FOnImageLoadCompleted LoadCompleted;
/** Holds the future value which represents the asynchronous loading operation. */
TFuture<UTexture2D*> Future;
}; | true |
5f988e7846f4e189509a371984415658084772fc | C++ | Dishu5588/liverpool | /passing the structure as the argument of the function.cpp | UTF-8 | 349 | 3.328125 | 3 | [] | no_license | #include<stdio.h>
#include<string.h>
struct student
{
int rollno;
char name[50];
};
void display (student);
int main()
{
struct student s1;
s1.rollno=1;
strcpy(s1.name,"deshant kumar");
display(s1);
return 0;
}
void display (student s2)
{
printf("\n rollno=%d",s2.rollno);
printf("\n name=%s",s2.name);
}
| true |
8fa97fc47ce2cdbfab09470b56181d4cd6c91042 | C++ | Mueggrogondrolla/node.c | /simpleserver.cpp | UTF-8 | 3,847 | 2.890625 | 3 | [] | no_license | #include <iostream>
#include <dlfcn.h>
#ifndef DOXYGEN_SHOULD_SKIP_THIS
#include "./http/WebApp.h"
#include "./net/Importer.h"
#endif /* DOXYGEN_SHOULD_SKIP_THIS */
int simpleWebserver(int argc, char** argv) {
WebApp& app = WebApp::instance("/home/voc/projects/ServerVoc/build/html");
app.use("/",
[&] (const Request& req, const Response& res, const std::function<void (void)>& next) {
res.set("Connection", "Keep-Alive");
next();
});
app.get("/",
[&] (const Request& req, const Response& res) -> void {
std::string uri = req.originalUrl;
std::cout << "URL: " << uri << std::endl;
std::cout << "Cookie: " << req.cookie("rootcookie") << std::endl;
res.cookie("searchcookie", "cookievalue", {{"Max-Age", "3600"}, {"Path", "/search"}});
// res.clearCookie("rootcookie");
// res.clearCookie("rootcookie");
// res.clearCookie("searchcookie", {{"Path", "/search"}});
if (uri == "/") {
res.redirect("/index.html");
} else if (uri == "/end") {
app.stop();
} else {
res.sendFile(uri);
}
});
Router router;
router.get("/search",
[&] (const Request& req, const Response& res) -> void {
std::cout << "URL: " << req.originalUrl << std::endl;
std::cout << "Cookie: " << req.cookie("searchcookie") << std::endl;
res.sendFile(req.originalUrl);
});
app.get("/", router);
#define CERTF "/home/voc/projects/ServerVoc/certs/Volker_Christian_-_Web_-_snode.c.pem"
#define KEYF "/home/voc/projects/ServerVoc/certs/Volker_Christian_-_Web_-_snode.c.key.pem"
app.listen(8080,
[&] (int err) -> void {
if (err != 0) {
perror("Listen");
} else {
std::cout << "snode.c listening on port 8080" << std::endl;
app.sslListen(8088, CERTF, KEYF, "password",
[] (int err) -> void {
if (err != 0) {
perror("Listen");
} else {
std::cout << "snode.c listening on port 8088" << std::endl;
}
});
}
});
app.destroy();
return 0;
}
/**
* Tests the importer class
*/
void importerTests()
{
/*
* good cases
*/
// test for an existing library
std::cout << "Library 'libm.so' exists: " << Importer::LibraryExists("libm.so") << std::endl;
// get the importer
Importer importer = Importer("libm.so");
// declare the type of the function pointer for a wanted function
double (*cosine)(double);
// get the pointer to the function
*(void **) (&cosine) = importer.GetFunctionPointer("cos");
std::cout << (*cosine)(2.0) << std::endl; // execute the funtion pointer
// look, for if a function, we know exists, to exist
std::cout << "Function 'cos' exists: " << importer.FunctionExists("cos") << std::endl;
/*
* error cases
*/
// look, for if a function, we know does not exist, to exist
std::cout << "Function 'cors' exists: " << importer.FunctionExists("cors") << std::endl;
// try to execute a function with the wrong function pointer type
*(void **) (&cosine) = importer.GetFunctionPointer("cosf");
std::cout << (*cosine)(2.0) << std::endl; // execute the funtion pointer
// test for a non-existing library
std::cout << "Library 'Testlisb' exists: " << Importer::LibraryExists("Testlisb") << std::endl;
// Try to execute a non void function directly
importer.ExecuteFunction("cosf");
}
int main(int argc, char** argv) {
importerTests();
return simpleWebserver(argc, argv);
}
| true |
3e3e07d712f0e10894ad2dade637756c2b70bee8 | C++ | wyxmails/MyCode | /1_leetcode/longestPalSubs.cpp | UTF-8 | 2,190 | 3.546875 | 4 | [] | no_license | /*Longest Palindromic Substring
Given a string S, find the longest palindromic substring in S.
You may assume that the maximum length of S is 1000, i
and there exists one unique longest palindromic substring.*/
string longestPalindrome(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int b=0;
int e=s.size();
int i,j;
string res;
int MAX = 0;
for(int b=0;b<s.size();++b){
for(int e=s.size()-1;e>=b+MAX;--e){
i=b;
j=e;
while(i<j){
if(s[i]!=s[j])
break;
i++;
j--;
}
if(i>=j&&(e-b+1)>MAX){
res = s.substr(b,e-b+1);
MAX = res.size();
}
}
}
return res;
}
bool isP(const string&s,int l,int r){
while(r>l){
if(s[r]!=s[l]) return false;
r--; l++;
}
return true;
}
string longestPalindrome2(string s) {
int n = s.size();
if(n<=1) return s;
vector<int> len(n,1);
int end = n-2;
int Max = INT_MIN;
int begin;
while(end>=0){
if(end+len[end+1]+1<n&&s[end]==s[end+len[end+1]+1]){
len[end] = len[end+1]+2;
if(len[end]>Max){
Max = len[end];
begin = end;
}
}else{
for(int i=end+len[end+1];i>end;--i){
if(isP(s,end,i)){
len[end] = i-end+1;
if(len[end]>Max){
Max = len[end];
begin = end;
}
break;
}
}
}
end--;
}
return s.substr(begin,Max);
}
string longestPalindrome3(string s) {
int n = s.size();
if(n==0) return s;
int l,r;
l=r=0;
int j,k;
for(int i=0;i<n;++i){
j=k=i;
while(j>=0&&k<n&&s[j]==s[k]){j--;k++;}
j++;k--;
if(k-j>r-l){l = j;r=k;}
j=i;k=i+1;
while(j>=0&&k<n&&s[j]==s[k]){j--;k++;}
j++;k--;
if(k-j>r-l){l=j;r=k;}
}
return s.substr(l,r-l+1);
}
| true |
7e06de6b038d64c960e373bb9ee40c2485e18b09 | C++ | rkritika1508/ITM-Mentorship-Program | /Contest - 1 - October 18 2020/C++ Codes/CycleDetection.cpp | UTF-8 | 667 | 3.609375 | 4 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
struct SinglyLinkedListNode {
int data;
SinglyLinkedListNode* next;
};
bool has_cycle(SinglyLinkedListNode* head) {
SinglyLinkedListNode *t = head; // here t will point to head node
SinglyLinkedListNode *r = head;
if(head == NULL || head->next==NULL) // if linked list is empty or consits only of 1 node
return false;
while( r!=NULL&&r->next!=NULL) {
t = t->next; // Tortoise node i.e. node which will move one step at a time
r = r->next->next; // Hare node i.e. node which will move two steps at a time
if(t==r) return true;
}
return false;
}
| true |
be58f3491c64c933ae2113fa9e8170b2b42c342c | C++ | Nightwind0/stonering | /sr2/src/items/Omega.cpp | UTF-8 | 4,589 | 2.5625 | 3 | [] | no_license | /*
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) 2012 <copyright holder> <email>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Omega.h"
#include "AttributeModifier.h"
#include "StatusEffectModifier.h"
#include "Description.h"
namespace StoneRing {
Omega::Omega()
{
}
Omega::~Omega()
{
}
// TODO: Create a base class for equipment and omegas that shares this functionality
double Omega::GetAttributeMultiplier(uint attr) const
{
double multiplier = 1.0;
for(AttributeModifierSet::const_iterator iter = m_attr_mods.lower_bound(attr);
iter != m_attr_mods.upper_bound(attr);iter++)
{
if(iter->second->GetType() == AttributeModifier::EMULTIPLY)
multiplier *= iter->second->GetMultiplier();
}
return multiplier;
}
double Omega::GetAttributeAdd(uint attr)const
{
double add = 0.0;
for(AttributeModifierSet::const_iterator iter = m_attr_mods.lower_bound(attr);
iter != m_attr_mods.upper_bound(attr);iter++)
{
if(iter->second->GetType() == AttributeModifier::EADD)
add += iter->second->GetAdd();
}
return add;
}
bool Omega::GetAttributeToggle ( uint i_attr, bool current ) const
{
ICharacter::eCharacterAttribute attr = static_cast<ICharacter::eCharacterAttribute>(i_attr);
double base = current;
for(AttributeModifierSet::const_iterator iter = m_attr_mods.lower_bound(attr);
iter != m_attr_mods.upper_bound(attr); iter++)
{
if(iter->second->GetType() == AttributeModifier::ETOGGLE)
if(ICharacter::ToggleDefaultTrue(attr))
base = base && iter->second->GetToggle();
else
base = base || iter->second->GetToggle();
}
return base;
}
double Omega::GetStatusEffectModifier ( const std::string& statuseffect ) const
{
std::pair<StatusEffectModifierSet::const_iterator,
StatusEffectModifierSet::const_iterator> bounds = m_status_effect_mods.equal_range(statuseffect);
double modifier = 0.0;
for(StatusEffectModifierSet::const_iterator iter = bounds.first;
iter != bounds.second; iter++)
{
modifier += iter->second->GetModifier();
}
return modifier;
}
uint Omega::GetValue() const
{
return m_value;
}
bool Omega::handle_element ( Element::eElement element, Element* pElement )
{
if(NamedItemElement::handle_element ( element, pElement ))
return true;
switch(element){
case EDESCRIPTION:
m_desc = dynamic_cast<Description*>(pElement)->GetText();
delete pElement;
return true;
case EATTRIBUTEMODIFIER:{
AttributeModifier* am = dynamic_cast<AttributeModifier*>(pElement);
m_attr_mods.insert(std::pair<uint,AttributeModifier*>(am->GetAttribute(),am));
return true;
}
case ESTATUSEFFECTMODIFIER:{
StatusEffectModifier* em = dynamic_cast<StatusEffectModifier*>(pElement);
m_status_effect_mods.insert(std::pair<std::string,StatusEffectModifier*>(em->GetStatusEffect()->GetName(),em));
return true;
}
}
return false;
}
void Omega::load_attributes ( clan::DomNamedNodeMap attributes )
{
NamedItemElement::load_attributes ( attributes );
m_value = get_required_int("value",attributes);
}
void Omega::load_finished()
{
StoneRing::NamedItemElement::load_finished();
}
std::string Omega::GetName() const
{
return NamedItemElement::GetName();
}
uint Omega::GetMaxInventory() const
{
return NamedItemElement::GetMaxInventory();
}
clan::Image Omega::GetIcon() const
{
return NamedItemElement::GetIcon();
}
bool Omega::operator== ( const StoneRing::ItemRef& ref )
{
if(ref.GetType() == ItemRef::NAMED_ITEM) return false;
if(ref.GetItemName() != GetName()) return false;
return true;
}
} | true |
4d1397d1e1c676081ec50b59fcd5c7a30472bcd1 | C++ | Wizmann/ACM-ICPC | /POJ/2/2185.cc | UTF-8 | 1,027 | 2.609375 | 3 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | //Result:wizmann 2185 Accepted 2252K 1016MS G++ 1076B
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
#define print(x) cout<<x<<endl
#define input(x) cin>>x
#define X 80
#define Y 10010
char ga[Y][X];
char gb[X][Y];
int c,r;
int get_next(char *g)
{
int next[X];
next[0]=-1;
int i=0,j=-1;
int col=strlen(g);
while(i<col)
{
if(j==-1 || g[i]==g[j])
{
i++;j++;
next[i]=j;
}
else j=next[j];
}
return i-next[i];
}
int GCD(int a,int b)
{
if(a<b) return GCD(b,a);
else
{
if(a%b==0) return b;
else return GCD(b,b%a);
}
}
int LCM(int a,int b)
{
return a*b/GCD(a,b);
}
int main()
{
while(input(r>>c))
{
for(int i=0;i<r;i++)
{
input(ga[i]);
for(int j=0;ga[i][j];j++)
{
gb[j][i]=ga[i][j];
}
}
int ans_c,ans_r;
ans_c=ans_r=1;
for(int i=0;i<r;i++)
{
ans_c=LCM(ans_c,get_next(ga[i]));
}
for(int i=0;i<c;i++)
{
ans_r=LCM(ans_r,get_next(gb[i]));
}
print(ans_c*ans_r);
}
return 0;
}
| true |
314bdec83c46743ce6bb3ab03a45a03a4a0c09fc | C++ | ryanjw0903/CSCE-221 | /Ryan_Wenham/Stress_ball.h | UTF-8 | 630 | 2.71875 | 3 | [] | no_license | //
// Created by ryanj on 1/15/2020.
//
#ifndef PA1_STRESS_BALL_H
#define PA1_STRESS_BALL_H
#include <iostream>
using namespace std;
enum class Stress_ball_colors{red, blue, yellow, green};
enum class Stress_ball_sizes{small,medium,large};
class Stress_ball{
public:
Stress_ball();
Stress_ball(Stress_ball_colors c, Stress_ball_sizes s);
Stress_ball_colors get_color() const;
Stress_ball_sizes get_size() const;
bool operator==(const Stress_ball& sb);
private:
Stress_ball_colors color;
Stress_ball_sizes size;
};
ostream& operator<<(ostream& os, const Stress_ball& sb);
#endif //PA1_STRESS_BALL_H
| true |
6b5819023dddda848e8881094aa803e359dcf74c | C++ | VipulKhandelwal1999/Data-Structures-Algorithms | /Leetcode/Linked List/Insert into cyclic sorted Linked List.cpp | UTF-8 | 1,338 | 3.828125 | 4 | [] | no_license | /* The given head need not be the head node, it could be any possible node. So there are many cases
1. if head is null
create new node, and made it point to itself, make head point to newly created node and return the head node
2. Traverse till we find the maximum node, now if (curr-val >= max-val || curr-val <= min-val) then add new node b/w maximum & minimum node
3. Otherwise keep on traversing untill node->val < curr-val, and insert here
Ex: 3->5->1 and X = 4 (3->5->1 is same as 1->3->5 becz of circular nature)
O/P: 5->1->3->4 OR 1->3->4->5
TC: O(N)
*/
ListNode * insert(ListNode * head, int x)
{
if(head==nullptr)
{
ListNode* node = new ListNode(x);
node->next = node;
return node;
}
ListNode *max = head; // find the maximum node
while(max->next != head && max->val <= max->next->val)
max = max->next;
ListNode *min = max->next, *curr = min;
if(x >= max->val || x <= min->val)
{
ListNode *node = new ListNode(x);
max->next = node;
node->next = min;
}
else
{
while(curr->next->val < x)
curr = curr->next;
ListNode *node = new ListNode(x);
node->next = curr->next;
curr->next = node;
}
return head;
}
| true |
25735e977282af0492efa9dea2d017034e6bd62f | C++ | kennethhu418/LeetCode_Practice | /Search_for_a_Range/Search_for_a_Range.cpp | GB18030 | 1,292 | 3.125 | 3 | [] | no_license | // Search_for_a_Range.cpp : ̨Ӧóڵ㡣
//
#include "stdafx.h"
#include <vector>
using std::vector;
class Solution {
public:
vector<int> searchRange(int A[], int n, int target) {
vector<int> resultArr(2);
resultArr[0] = resultArr[1] = -1;
int startIndex = searchEdge(A, n, target);
if (startIndex == -1) return resultArr;
int endIndex = searchEdge(A, n, target, false);
resultArr[0] = startIndex; resultArr[1] = endIndex;
return resultArr;
}
private:
int searchEdge(int A[], int n, int target, bool searchLeftEdge = true){
int start = 0, end = n - 1, mid = 0;
while (start <= end){
mid = ((start + end) >> 1);
if (target == A[mid]){
if (searchLeftEdge){
if (mid - 1 < start || A[mid - 1] != target) return mid;
end = mid - 1;
}
else {
if (mid + 1 > end || A[mid + 1] != target) return mid;
start = mid + 1;
}
}
else if (target > A[mid]) start = mid + 1;
else end = mid - 1;
}
return -1;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}
| true |
3101ad1f6bf2b7189c17fa18905afe3312fc3419 | C++ | edwinandradeospino/CplusConsoleQt | /Testeur/PersonneTesteur.cpp | UTF-8 | 1,245 | 2.859375 | 3 | [] | no_license | /*
* PersonneTesteur.cpp
*
* Created on: 2017-11-26
* Author: etudiant
*/
#include<iostream>
#include<gtest/gtest.h>
#include"Personne.h"
#include"Electeur.h"
using namespace elections;
/**
* \class PersonneTest
* \brief Fixture Personne pour la création d'un objet testPersonne pour les tests
* \ des classes abstracts.
*/
class PersonneTest : public Personne {
public:
PersonneTest(const std::string& p_nas,
const std::string& p_prenom,
const std::string& p_nom,
const util::Date& p_dateNaissance,
const util::Adresse& p_adresse)
: Personne(p_nas, p_prenom, p_nom, p_dateNaissance,
p_adresse) {};
std::string reqPersonneFormate() const {
return " ";
}
PersonneTest* clone() const {
return new PersonneTest (*this);
}
};
/**
* \brief Test du constructeur Personne
* Cas Valides de tous les reqs
*/
TEST(personne, ConstructeurAvecParametresValides) {
PersonneTest UnePersonne("046 454 286", "Edwin", "Andrade",
util::Date(2,2,1980), util::Adresse(235,"Rue","Qc","g3g 3h3","Qc"));
ASSERT_EQ("046 454 286",UnePersonne.reqNas());
ASSERT_EQ("Andrade",UnePersonne.reqPrenom());
ASSERT_EQ("Edwin",UnePersonne.reqNom());
ASSERT_EQ(util::Date(2,2,1980),UnePersonne.reqDateNaissance());
}
| true |
15edfb04ac16a12fe904998967acc549a7219f49 | C++ | franciscoruivo/isec-material | /POO-2020/Exercicios/aula26nov/Agenda.cpp | UTF-8 | 1,734 | 3.25 | 3 | [] | no_license | #include "Agenda.h"
int Agenda::encontraContacto(string a) const {
for(int i = 0; i < v.size(); i++) {
if (v[i]->getNome() == a)
return i;
}
return -1;
}
int Agenda::encontraContacto(int n) const {
for(int i = 0; i < v.size(); i++) {
if (v[i]->getTel() == n)
return i;
}
return -1;
}
bool Agenda::addContacto(string nome, int tel) {
if (encontraContacto(nome) == -1) {
v.push_back(new Contacto(nome, tel));
return true;
} else return false;
}
int Agenda::getTel(string a) const {
int i = encontraContacto(a);
if (i != -1)
return v[i]->getTel();
else return -1;
}
bool Agenda::atualizaContacto(string a, int nt) {
int i = encontraContacto(a);
if (i != -1) {
v[i]->setTel(nt);
return true;
} else return false;
}
bool Agenda::eliminaContacto(int t) {
int i = encontraContacto(t);
if (i != -1) {
delete v[i];
v.erase(v.begin() + i);
return true;
} else return false;
}
Agenda& Agenda::operator=(const Agenda& dir) {
if (this == &dir) return *this; //Self assignment
for (int i = 0; i < v.size(); i++) {
delete v[i];
v.erase(v.begin() + i);
}
v.clear();
for (auto it = dir.v.begin(); it < dir.v.end(); it++) {
addContacto((*it)->getNome(), (*it)->getTel());
}
return *this;
}
string Agenda::getAsString() const {
ostringstream os;
os << "Numero de Contactos: " << v.size() << endl;
for (const Contacto *pc : v) {
os << *pc << endl;
}
return os.str();
}
ostream& operator<<(ostream& out, const Agenda& ref) {
out << ref.getAsString();
return out;
} | true |
5137982b28a393553197e08717654c44ed02626a | C++ | hohaidang/CPP_Basic2Advance | /Book_Source/Cpp-Primer-Plus-programming-exercises-master/Cpp-Primer-Plus-programming-exercises-master/code/Chapter11/11_5_stonevt.cpp | UTF-8 | 1,164 | 3.390625 | 3 | [] | no_license | // By luckycallor
// Welcome to my site: www.luckycallor.com
#include"11_5_stonewt.h"
Stonewt::Stonewt()
{
mode = PND;
stone = pounds = pds_left = 0;
}
Stonewt::Stonewt(int stn, double lbs,Mode form)
{
mode = form;
stone = stn;
pds_left = lbs;
pounds = lbs + Lbs_per_stn * stone;
}
Stonewt::Stonewt(double lbs,Mode form)
{
mode = form;
pounds = lbs;
stone = (int)pounds / Lbs_per_stn;
pds_left = pounds - stone * Lbs_per_stn;
}
Stonewt::~Stonewt(){}
Stonewt Stonewt::operator+(const Stonewt& w)const
{
return Stonewt(pounds+w.pounds);
}
Stonewt Stonewt::operator-(const Stonewt& w)const
{
return Stonewt(pounds-w.pounds);
}
Stonewt Stonewt::operator*(double n) const
{
return Stonewt(n*pounds);
}
Stonewt operator*(double n,const Stonewt& w)
{
return w*n;
}
std::ostream& operator<<(std::ostream& os,const Stonewt& w)
{
if(w.mode == Stonewt::STN) os << w.stone << " stones," << w.pds_left << " pounds";
else if(w.mode == Stonewt::PND) os << w.pounds << " pounds";
else if(w.mode == Stonewt::IPND) os << (int)(w.pounds+0.5) << " pounds";
else os << "Wrong Mode!\n";
return os;
}
| true |
0f2754a8194f0166e87e2c623be6d804b8fd8954 | C++ | abrulot1/CMD-fight-sim | /Inhabitant.h | UTF-8 | 1,018 | 2.90625 | 3 | [] | no_license | /******************************************************************
*Program Filename: Inhabitant.h
*Author: Adam Brulotte
*Date: 19 July 15
*Description: header file for an abtract base class inhabitant.
*Input: none
*Output: none
**********************************************************************/
#ifndef INHABITANT_H
#define INHABITANT_H
#include <string>
class Inhabitant
{
protected:
int strength;
int armor;
int faces;
std::string name;
bool achilles;
std::string alias;
public:
virtual void setAlias(std::string) = 0;
virtual std::string getAlias() = 0;
virtual void setName(std::string) = 0;
virtual std::string getName() = 0;
virtual void setHP(int) = 0;
virtual int getHP() = 0;
virtual void setArmor(int) = 0;
virtual int getArmor() = 0;
virtual void setFaces(int) = 0;
virtual int getFaces() = 0;
virtual int attRoll() = 0;
virtual int defRoll() = 0;
virtual void setAchilles(bool) = 0;
virtual bool getAchilles() = 0;
};
#endif | true |
ff96191f670a49260d6d538cad5f887b7304630e | C++ | Brook1711/-1-2 | /第二学期1、2/源.cpp | UTF-8 | 510 | 2.78125 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
bool T = true;
int s1 = 0;
int N = 0;
int s2 = 0;
int s = 0;
cin >> N;
//int * A = new int(N);
int A[100000];
for (int i = 0; i < N; i++)
{
cin >> A[i];
if (A[i] >= 0)
T = false;
}
for (int i = 0; i < N; i++)
{
for (int j = N - 1; j >= i; j--)
{
int temp = 0;
for (int k = 0; k <= j - i; k++)
temp += A[k + i];
if (temp > s)
s = temp;
}
}
if (T)
cout << 0;
else
cout << s;
//delete[] A;
return 0;
} | true |
33b87fa07e7b96c61320bd5eddbe62ef82731e3d | C++ | abhisheknaw/Data-Structures | /Linked list , Stack and Queue/inorder_successor.cpp | UTF-8 | 1,870 | 3.234375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
struct bstnode
{
int data;
struct bstnode *left;
struct bstnode *right;
};
bstnode *getnewnode(int data)
{
bstnode *newnode=new bstnode();
newnode->data=data;
newnode->left=NULL;
newnode->right=NULL;
return newnode;
}
bstnode *insert(bstnode *root,int data)
{
if(root==NULL)
{
root=getnewnode(data);
return root;
}
else if(root->data >= data)
{
root->left=insert(root->left,data);
return root;
}
else
{
root->right=insert(root->right,data);
return root;
}
}
struct bstnode* Find(bstnode*root, int data)
{
if(root == NULL) return NULL;
else if(root->data == data) return root;
else if(root->data < data) return Find(root->right,data);
else return Find(root->left,data);
}
struct bstnode* FindMIN(struct bstnode* root) {
if(root == NULL) return NULL;
while(root->left != NULL)
root = root->left;
return root;
}
struct bstnode *successor(struct bstnode *root,int data)
{
struct bstnode *current=Find(root,data);
if(current==NULL) return NULL;
if(current->right!=NULL)
return FindMIN(current->right);
else
{
struct bstnode *suc=NULL;
struct bstnode *anc=root;
while(anc!=current)
{
if(anc->data>current->data)
{
suc=anc;
anc=anc->left;
}
else
{
anc=anc->right;
}
}
return suc;
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
#ifndef ONLINE_JUDGE
// for getting input from input.txt
freopen("input.txt", "r", stdin);
// for writing output to output.txt
freopen("output.txt", "w", stdout);
#endif
bstnode *root=NULL;
root=insert(root,15);
root=insert(root,25);
root=insert(root,10);
root=insert(root,13);
root=insert(root,7);
root=insert(root,20);
root=insert(root,27);
struct bstnode *succ=successor(root,13);
if(succ==NULL)
{
cout<<"no successor:\n";
}
else
{
cout<<succ->data;
}
return 0;
} | true |
7ca289493a5531ce9ddf2e0f429448762f500216 | C++ | snizovtsev/cmc-ray | /xmlwriter.cpp | UTF-8 | 702 | 2.734375 | 3 | [] | no_license | #include "xmlwriter.h"
XMLWriter::XMLWriter(const QString &fileName)
: file(fileName)
{
if (!file.open(QFile::WriteOnly))
throw SerializeException("Can't write to file");
xml = new QXmlStreamWriter(&file);
xml->setAutoFormatting(true);
}
XMLWriter::~XMLWriter()
{
delete xml;
}
void XMLWriter::enterObject(const QString &name)
{
xml->writeStartElement(name);
xml->writeAttributes(attr);
attr.clear();
}
void XMLWriter::pushAttribute(const QString &name, const QString &value)
{
attr.append(name, value);
}
void XMLWriter::writeText(const QString &text)
{
xml->writeCharacters(text);
}
void XMLWriter::leaveObject()
{
xml->writeEndElement();
}
| true |
c294db241028a26fb9900bdaa3496e90202dac65 | C++ | ilovesoup/homework_template | /cpp/main.cpp | UTF-8 | 2,010 | 3.078125 | 3 | [] | no_license | #include <iostream>
#include "ASTNode.h"
#include "RowData.h"
#include "dummy/DummyEvaluator.h"
#include <iostream>
#include <chrono>
#include <cmath>
#include <exception>
#include <memory>
using std::cout;
using std::endl;
using std::chrono::high_resolution_clock;
using std::chrono::duration_cast;
using std::chrono::nanoseconds;
using std::unique_ptr;
const int NUM = 10000000;
void verify(RowDataPtr r, int num) {
for (int i = 0; i < num; i++) {
double e = (i - 99.88) + (i + 1 + i + 1.1);
double a = r->getDouble(i, 0);
if (abs(e - a) > 0.0001) {
throw new std::runtime_error("wrong answer");
}
}
}
RowDataPtr loadData(int num) {
DummyRowData * const pDummyRaw = new DummyRowData(NUM);
RowDataPtr pData(pDummyRaw);
for (int64_t i = 0; i < num; i++) {
Row row{Datum(i), Datum(i + 1), Datum(i + 1.1)};
pDummyRaw->addRow(row);
}
return pData;
}
void baseline(AstNodePtr root, RowDataPtr pData, int num) {
DummyEvaluatorBuilder builder;
unique_ptr<Evaluator<RowDataPtr>> evaluator(builder.build(root, NULL));
cout << "baseline started..." << endl;
auto start = high_resolution_clock::now();
RowDataPtr pRes = evaluator->evaluate(pData);
auto end = high_resolution_clock::now();
cout << duration_cast<nanoseconds>(end - start).count() / 1000000000.0 << "s" << endl;
verify(pRes, num);
}
void userCode(AstNodePtr root, RowDataPtr pData, int num) {}
int main() {
// col(0) = i; col(1) = i + 1; col(2) = i + 1.1
// lhs = col(0) - 99.98 = i - 99.98
// rhs = col(1) + col(2) = i + 1 + i + 1.1 = 2i + 2.1
// expr = 3i + 97.88
AstNodePtr lhs(new Minus(AstNodePtr(new ColumnRef(0)), AstNodePtr(new Constant(99.88))));
AstNodePtr rhs(new Plus(AstNodePtr(new ColumnRef(1)), AstNodePtr(new ColumnRef(2))));
AstNodePtr expr(new Plus(lhs, rhs));
RowDataPtr pData = loadData(NUM);
userCode(expr, pData, NUM);
baseline(expr, pData, NUM);
return 0;
} | true |
d34c2e207d60eadb598fbf7e3f794858b4b0b860 | C++ | superlb/My_ICPC_Code | /Lutece/2356.cpp | UTF-8 | 1,274 | 2.640625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
long m, n, m1;
bool isboss = true;
int a[100000];
int max = 0;
long themax;
bool skip = true;
cin >> m >> n;
m1 = m;
for (long i = 0; i < n - 1; ++i)
{
cin >> a[i];
if (m > a[i])
{
m -= a[i];
m += 6;
if (a[i] > max)
{
max = a[i];
themax = i;
}
}
else
{
if (skip)
{
m += 6;
skip = false;
continue;
}
else
{
isboss = false;
for (long i1 = i + 1; i1 < n; ++i1)
{
cin >> a[i1];
}
break;
}
}
}
if (isboss)
{
int boss;
cin >> boss;
if (m > boss)
{
cout << "YES";
}
else
{
if (m + max > boss && skip)
{
cout << "YES";
}
else
{
cout << "NO";
}
}
}
else
{
bool again = true;
skip = true;
for (long i = 0; i < n - 1; ++i)
{
if (i == themax && skip)
{
m1 += 6;
skip = false;
continue;
}
if (m1 > a[i])
{
m1 -= a[i];
m1 += 6;
}
else
{
if (skip)
{
m1 += 6;
skip = false;
continue;
}
else
{
again = false;
break;
}
}
}
if (again)
{
if (m1 > a[n - 1])
{
cout << "YES";
}
else
{
cout << "NO";
}
}
else
{
cout << "NO";
}
}
return 0;
}
| true |
ba12d9541f875101d52adc7008405884f846959c | C++ | Rupert-WLLP-Bai/data_structure_homework | /Q10-Linux-Repair/include/Sort.h | UTF-8 | 15,702 | 3.09375 | 3 | [
"MIT"
] | permissive | //Sort.h
#include <algorithm>
#include <cmath>
#include <ctime>
#include <iomanip>
#include <iostream>
#include <vector>
using namespace std;
//排序需要用到的函数
namespace SORT {
//交换
void swap(int& a, int& b);
//赋值
void assign(int* num, int* arr, int N);
} // namespace SORT
//排序类
class Sort {
private:
int* num;
int N;
int range;
//希尔排序的插入
int64_t Shell_insert(int* arr, int begin, int gap);
//快速排序递归函数
int64_t Q_Sort(int left, int right, int* arr);
//堆排序调整堆
int64_t adjustHeap(int* arr, int i, int n);
//归并排序
void MergeSort(int* A, int n, int64_t& count);
//归并
int64_t Merge(int* A, int* L, int leftCount, int* R, int rightCount);
//基数排序求最大位数
int max_bit(int* arr, int N);
//基数排序
void radixsort(int* data, int n);
public:
Sort(int N, int range);
~Sort();
void result();
void print_inital();
void Bubble_sort();
void Selection_sort();
void Insertion_sort();
void Shell_sort();
void Quick_sort();
void Heap_sort();
void Merge_sort();
void Radix_sort();
void print_arr(int* arr);
};
//构造函数
Sort::Sort(int N, int range) {
srand(time(NULL));
this->range = range;
this->N = N;
num = new int[N];
if (range == -1)
for (int i = 0; i < N; i++) {
num[i] = rand();
}
else
for (int i = 0; i < N; i++) {
num[i] = rand() % range;
}
}
//析构函数
Sort::~Sort() {
delete[] num;
}
//输出初始
void Sort::print_inital() {
cout << "--------------------排序前-------------------" << endl;
cout << "Before:";
//输出
// for (int i = 0; i < N; i++) {
// cout << setiosflags(ios::left) << setw(int(log10(range) + 1)) << num[i] << " ";
// if (i % 10 == 9)
// cout << endl
// << " ";
// }
//输出结束
cout << endl;
cout << "--------------------------------------------" << endl;
}
//输出结果
void Sort::print_arr(int* arr) {
cout << "Result:";
for (int i = 0; i < N; i++) {
cout << setiosflags(ios::left) << setw(int(log10(range) + 1)) << arr[i] << " ";
if (i % 10 == 9)
cout << endl
<< " ";
}
cout << endl;
}
//正确结果
void Sort::result() {
vector<int> L;
for (int i = 0; i < N; i++) {
L.push_back(num[i]);
}
//计时开始
timespec t1, t2;
clock_gettime(CLOCK_MONOTONIC, &t1);
//排序
sort(L.begin(), L.end());
clock_gettime(CLOCK_MONOTONIC, &t2);
int64_t deltaT = (t2.tv_sec - t1.tv_sec) * int64_t(pow(10, 9)) + t2.tv_nsec - t1.tv_nsec;
cout << "-------------------std::sort的结果-------------------" << endl;
cout << "Time :" << deltaT << " ns = " << double(deltaT / pow(10, 6)) << " ms" << endl;
cout << "Result:";
//输出
// for (int i = 0; i < N; i++) {
// cout << setiosflags(ios::left) << setw(int(log10(range) + 1)) << L[i] << " ";
// if (i % 10 == 9)
// cout << endl
// << " ";
// }
//输出结束
cout << endl;
cout << "---------------------------------------------------" << endl;
cout << endl;
}
//八种排序(10种)
//1.冒泡排序
void Sort::Bubble_sort() {
//计数
int64_t count = 0;
//申请
int* arr = new int[N];
//赋值
SORT::assign(num, arr, N);
//计时开始
timespec t1, t2;
clock_gettime(CLOCK_MONOTONIC, &t1);
//排序
for (int i = 0; i < N - 1; i++) {
for (int j = 0; j < N - 1; j++) {
if (arr[j] > arr[j + 1]) {
SORT::swap(arr[j], arr[j + 1]);
count++;
}
}
}
//计时结束
clock_gettime(CLOCK_MONOTONIC, &t2);
int64_t deltaT = (t2.tv_sec - t1.tv_sec) * int64_t(pow(10, 9)) + t2.tv_nsec - t1.tv_nsec;
cout << "--------------------冒泡排序的结果-------------------" << endl;
cout << "Time :" << deltaT << " ns = " << double(deltaT / pow(10, 6)) << " ms" << endl;
cout << "Count :" << count << endl;
//print_arr(arr);
cout << "--------------------------------------------------" << endl;
//释放
delete[] arr;
}
//2.选择排序
void Sort::Selection_sort() {
//计数
int64_t count = 0;
//申请
int* arr = new int[N];
//赋值
SORT::assign(num, arr, N);
//计时开始
timespec t1, t2;
clock_gettime(CLOCK_MONOTONIC, &t1);
//排序
for (int i = 0; i < N; i++) {
int m = arr[i];
int index = i;
for (int j = i + 1; j < N; j++) {
if (arr[j] < m) {
count++;
m = arr[j];
index = j;
}
}
if (i != index) {
swap(arr[i], arr[index]);
count++;
}
}
//计时结束
clock_gettime(CLOCK_MONOTONIC, &t2);
int64_t deltaT = (t2.tv_sec - t1.tv_sec) * int64_t(pow(10, 9)) + t2.tv_nsec - t1.tv_nsec;
cout << "--------------------选择排序的结果-------------------" << endl;
cout << "Time :" << deltaT << " ns = " << double(deltaT / pow(10, 6)) << " ms" << endl;
cout << "Count :" << count << endl;
//print_arr(arr);
cout << "--------------------------------------------------" << endl;
//释放
delete[] arr;
}
//3.直接插入排序
void Sort::Insertion_sort() {
//计数
int64_t count = 0;
//申请
int* arr = new int[N];
//赋值
SORT::assign(num, arr, N);
//计时开始
timespec t1, t2;
clock_gettime(CLOCK_MONOTONIC, &t1);
//排序
for (int i = 1; i < N; i++) {
int temp = i;
for (int j = i - 1; j >= 0; j--) {
if (arr[temp] < arr[j]) {
swap(arr[temp--], arr[j]);
count++;
}
}
}
//计时结束
clock_gettime(CLOCK_MONOTONIC, &t2);
int64_t deltaT = (t2.tv_sec - t1.tv_sec) * int64_t(pow(10, 9)) + t2.tv_nsec - t1.tv_nsec;
cout << "--------------------插入排序的结果-------------------" << endl;
cout << "Time :" << deltaT << " ns = " << double(deltaT / pow(10, 6)) << " ms" << endl;
cout << "Count :" << count << endl;
//print_arr(arr);
cout << "--------------------------------------------------" << endl;
//释放
delete[] arr;
}
//4.希尔排序
void Sort::Shell_sort() {
//计数
int64_t count = 0;
//申请
int* arr = new int[N];
//赋值
SORT::assign(num, arr, N);
//计时开始
timespec t1, t2;
clock_gettime(CLOCK_MONOTONIC, &t1);
//排序
int gap = N / 2;
while (gap > 0) {
int begin = gap - 1;
while (begin >= 0) {
count += Shell_insert(arr, begin, gap);
begin--;
}
gap = gap / 2;
}
//计时结束
clock_gettime(CLOCK_MONOTONIC, &t2);
int64_t deltaT = (t2.tv_sec - t1.tv_sec) * int64_t(pow(10, 9)) + t2.tv_nsec - t1.tv_nsec;
cout << "--------------------希尔排序的结果-------------------" << endl;
cout << "Time :" << deltaT << " ns = " << double(deltaT / pow(10, 6)) << " ms" << endl;
cout << "Count :" << count << endl;
//print_arr(arr);
cout << "--------------------------------------------------" << endl;
//释放
delete[] arr;
}
//4.希尔排序的插入(返回值为count的增量)
int64_t Sort::Shell_insert(int* arr, int begin, int gap) {
int64_t count = 0;
for (int i = begin + gap; i < N; i += gap) {
int temp = arr[i];
int j = i - gap;
for (; j >= 0 && temp < arr[j]; j -= gap) {
arr[j + gap] = arr[j];
count++;
}
arr[j + gap] = temp;
}
return count;
}
//5.快速排序
void Sort::Quick_sort() {
//计数
int64_t count = 0;
//申请
int* arr = new int[N];
//赋值
SORT::assign(num, arr, N);
//计时开始
timespec t1, t2;
clock_gettime(CLOCK_MONOTONIC, &t1);
//排序
count = Q_Sort(0, N - 1, arr);
//计时结束
clock_gettime(CLOCK_MONOTONIC, &t2);
int64_t deltaT = (t2.tv_sec - t1.tv_sec) * int64_t(pow(10, 9)) + t2.tv_nsec - t1.tv_nsec;
cout << "--------------------快速排序的结果-------------------" << endl;
cout << "Time :" << deltaT << " ns = " << double(deltaT / pow(10, 6)) << " ms" << endl;
cout << "Count :" << count << endl;
//print_arr(arr);
cout << "--------------------------------------------------" << endl;
//释放
delete[] arr;
}
//5.快速排序递归
int64_t Sort::Q_Sort(int left, int right, int* arr) {
static int64_t count = 0;
if (left >= right)
return 0;
int i, j, base;
i = left, j = right;
base = arr[left]; //取最左边的数为基准数
while (i < j) {
while (arr[j] >= base && i < j)
j--;
while (arr[i] <= base && i < j)
i++;
if (i < j) {
swap(arr[i], arr[j]);
count++;
}
}
//基准数归位
arr[left] = arr[i];
arr[i] = base;
Q_Sort(left, i - 1, arr); //递归左边
Q_Sort(i + 1, right, arr); //递归右边
return count;
}
//6.堆排序
void Sort::Heap_sort() {
//计数
int64_t count = 0;
//申请
int* arr = new int[N];
//赋值
SORT::assign(num, arr, N);
//计时开始
timespec t1, t2;
clock_gettime(CLOCK_MONOTONIC, &t1);
//排序
//1.构造大顶堆
count += adjustHeap(arr, 0, N);
//2.交换循环
for (int i = N - 1; i > 0; i--) {
SORT::swap(arr[0], arr[i]);
count++;
count += adjustHeap(arr, 0, i);
}
//计时结束
clock_gettime(CLOCK_MONOTONIC, &t2);
int64_t deltaT = (t2.tv_sec - t1.tv_sec) * int64_t(pow(10, 9)) + t2.tv_nsec - t1.tv_nsec;
cout << "----------------------堆排序的结果-------------------" << endl;
cout << "Time :" << deltaT << " ns = " << double(deltaT / pow(10, 6)) << " ms" << endl;
cout << "Count :" << count << endl;
//print_arr(arr);
cout << "--------------------------------------------------" << endl;
//释放
delete[] arr;
}
//6.调整堆
int64_t Sort::adjustHeap(int* arr, int i, int n) {
int64_t count = 0;
int parent = i; // 父节点下标
int child = 2 * i + 1; // 子节点下标
while (child < n) {
if (child + 1 < n && arr[child] < arr[child + 1]) { // 判断子节点那个大,大的与父节点比较
child++;
}
if (arr[parent] < arr[child]) { // 判断父节点是否小于子节点
SORT::swap(arr[parent], arr[child]); // 交换父节点和子节点
count++;
parent = child; // 子节点下标 赋给 父节点下标
}
child = child * 2 + 1; // 换行,比较下面的父节点和子节点
}
return count;
}
//7.归并排序
void Sort::Merge_sort() {
//计数
int64_t count = 0;
//申请
int* arr = new int[N];
//赋值
SORT::assign(num, arr, N);
//计时开始
timespec t1, t2;
clock_gettime(CLOCK_MONOTONIC, &t1);
//排序
MergeSort(arr, N, count);
//计时结束
clock_gettime(CLOCK_MONOTONIC, &t2);
int64_t deltaT = (t2.tv_sec - t1.tv_sec) * int64_t(pow(10, 9)) + t2.tv_nsec - t1.tv_nsec;
cout << "----------------------归并排序的结果-------------------" << endl;
cout << "Time :" << deltaT << " ns = " << double(deltaT / pow(10, 6)) << " ms" << endl;
cout << "Count :" << count << endl;
//print_arr(arr);
cout << "----------------------------------------------------" << endl;
//释放
delete[] arr;
}
//合并
int64_t Sort::Merge(int* A, int* L, int leftCount, int* R, int rightCount) {
int i, j, k;
int64_t count = 0;
// i - to mark the index of left aubarray (L)
// j - to mark the index of right sub-raay (R)
// k - to mark the index of merged subarray (A)
i = 0;
j = 0;
k = 0;
while (i < leftCount && j < rightCount) {
if (L[i] < R[j])
A[k++] = L[i++];
else {
A[k++] = R[j++];
count++;
}
while (i < leftCount)
A[k++] = L[i++];
while (j < rightCount)
A[k++] = R[j++];
}
return count;
}
// Recursive function to sort an array of integers.
void Sort::MergeSort(int* A, int n, int64_t& count) {
int mid, i, *L, *R;
if (n < 2)
return; // base condition. If the array has less than two element, do nothing.
mid = n / 2; // find the mid index.
// create left and right subarrays
// mid elements (from index 0 till mid-1) should be part of left sub-array
// and (n-mid) elements (from mid to n-1) will be part of right sub-array
L = new int[mid];
R = new int[n - mid];
for (i = 0; i < mid; i++)
L[i] = A[i]; // creating left subarray
for (i = mid; i < n; i++)
R[i - mid] = A[i]; // creating right subarray
MergeSort(L, mid, count); // sorting the left subarray
MergeSort(R, n - mid, count); // sorting the right subarray
count += Merge(A, L, mid, R, n - mid); // Merging L and R into A as sorted list.
// the delete operations is very important
delete[] R;
delete[] L;
}
//8.基数排序
void Sort::Radix_sort() {
//计数
int64_t count = 0;
//申请
int* arr = new int[N];
//赋值
SORT::assign(num, arr, N);
//计时开始
timespec t1, t2;
clock_gettime(CLOCK_MONOTONIC, &t1);
//排序
radixsort(arr, N);
//计时结束
clock_gettime(CLOCK_MONOTONIC, &t2);
int64_t deltaT = (t2.tv_sec - t1.tv_sec) * int64_t(pow(10, 9)) + t2.tv_nsec - t1.tv_nsec;
cout << "----------------------基数排序的结果-------------------" << endl;
cout << "Time :" << deltaT << " ns = " << double(deltaT / pow(10, 6)) << " ms" << endl;
cout << "Count :" << count << endl;
//print_arr(arr);
cout << "--------------------------------------------------" << endl;
//释放
delete[] arr;
}
//基数排序
void Sort::radixsort(int data[], int n) {
int d = max_bit(data, n);
int* tmp = new int[n];
int* count = new int[10]; //计数器
int i, j, k;
int radix = 1;
for (i = 1; i <= d; i++) //进行d次排序
{
for (j = 0; j < 10; j++)
count[j] = 0; //每次分配前清空计数器
for (j = 0; j < n; j++) {
k = (data[j] / radix) % 10; //统计每个桶中的记录数
count[k]++;
}
for (j = 1; j < 10; j++)
count[j] = count[j - 1] + count[j]; //将tmp中的位置依次分配给每个桶
for (j = n - 1; j >= 0; j--) //将所有桶中记录依次收集到tmp中
{
k = (data[j] / radix) % 10;
tmp[count[k] - 1] = data[j];
count[k]--;
}
for (j = 0; j < n; j++) //将临时数组的内容复制到data中
data[j] = tmp[j];
radix = radix * 10;
}
delete[] tmp;
delete[] count;
}
//8.基数排序求最大位数
int Sort::max_bit(int* arr, int N) {
int max = arr[0];
int bit = 0;
for (int i = 0; i < N; i++) {
if (arr[i] > max)
max = arr[i];
}
bit = int(log10(max)) + 1;
return bit;
}
//namespace sort
//交换
void SORT::swap(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
//赋值
void SORT::assign(int* num, int* arr, int N) {
for (int i = 0; i < N; i++) {
arr[i] = num[i];
}
}
//2021年10月19日17:42:02 | true |
f82b61c3ad07dab70ece9258162c4e6027771a99 | C++ | suganoo/algorithm_and_data_structure_for_procon | /abc147_c_2.cpp | UTF-8 | 710 | 2.703125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int N;
int shougen[size][size];
int shoujiki_cnt(int bit) {
bool pass = false;
for (int i = 0; i < N; i++){
if (bit & (1 << i)) {
if (shougen[i + 1][i + 1]){
}
}
}
}
int main(){
cin >> N;
int size = 20;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
shougen[i][j] = -1;
}
}
for (int i = 1; i <= N; i++) {
int A;
cin >> A;
for (int j = 1; j <= A; j++) {
int x = 0;
int y = 0;
cin >> x >> y;
shougen[A][x] = y;
}
}
int cnt = 0;
for (int bit = 0; bit < (1 << N); bit++) {
cnt = max(cnt, shoujiki_cnt(bit));
}
cout << cnt << endl;
}
| true |
09c1cbc1cffa88eb83c38aa9a5534520035c75ee | C++ | creekorful/majoris | /Source/Engine/Filesystem/Directory.cpp | UTF-8 | 1,032 | 3.234375 | 3 | [] | no_license | #include "Directory.h"
ma::Filesystem::Directory::Directory()
{
m_path = "";
m_pDirectory = nullptr;
}
ma::Filesystem::Directory::Directory(const std::string& path)
{
m_path = path;
m_pDirectory = opendir(m_path.c_str());
}
bool ma::Filesystem::Directory::isValid() const
{
return m_pDirectory != nullptr;
}
std::vector<ma::Filesystem::File> ma::Filesystem::Directory::fileEntries(const std::string& extension) const
{
std::vector<File> files;
struct dirent *dirent;
// while there is entry to process
while ((dirent = readdir(m_pDirectory)) != nullptr)
{
if (dirent->d_type == DT_REG)
{
std::string name = dirent->d_name;
// if need to search for specific extension
if (!extension.empty() && name.find(extension) != std::string::npos)
{
files.emplace_back(m_path + "/" + name);
}
}
}
return files;
}
std::string ma::Filesystem::Directory::path() const
{
return m_path;
}
| true |
aec3229f69c23cb4398d0d2a0da600aaf9e4fe96 | C++ | hyy199308/Leetcode | /p718_Maximum_Length_of_Repeated_Subarray/solution.cpp | UTF-8 | 1,338 | 3.09375 | 3 | [] | no_license | #include <string.h>
#include <stdio.h>
#include <vector>
#define MAXL 1000
using namespace std;
int dp[MAXL][MAXL]; // dp[i][j] is the longest common subarray/substring width ENDED EXACTLY at t1[i] & t2[j] respectively.
class Solution {
public:
int findLength(vector<int>& t1, vector<int>& t2) {
int l1 = t1.size(), l2 = t2.size();
if (l1 <= 0 || l2 <= 0) return 0;
// Init.
memset(dp, 0, sizeof(dp));
// Loop.
int maxDpVal = 0;
for (int i = 0; i < l1; ++i) {
for (int j = 0; j < l2; ++j) {
if (t1[i] != t2[j]) {
dp[i][j] = 0;
} else {
if (0 < i && 0 < j) {
dp[i][j] = dp[i-1][j-1] + 1;
} else {
dp[i][j] = 1;
}
}
if (dp[i][j] > maxDpVal) {
maxDpVal = dp[i][j];
}
}
}
return maxDpVal;
}
};
int main() {
int t1Arr[] = {1, 2, 3, 2, 1};
int t2Arr[] = {3, 2, 1, 4, 7};
vector<int> t1(t1Arr, t1Arr + sizeof(t1Arr)/sizeof(int));
vector<int> t2(t2Arr, t2Arr + sizeof(t2Arr)/sizeof(int));
Solution s;
int res = s.findLength(t1, t2);
printf("%d\n", res);
return 0;
}
| true |
77b1bffc6c7f91c6fd4273a534b35e0ba54eb13e | C++ | gwenbleyd/-library_information_system | /menu.cpp | UTF-8 | 15,352 | 2.53125 | 3 | [] | no_license | #include "menu.h"
menu::menu(){
mainWindow.size(nana::size{ 720, 900 });
mainWindow.caption("Library information system");
mainWindow.move(591, 60);
btn_add_book.create(mainWindow);
btn_add_reader.create(mainWindow);
btn_add_librarian.create(mainWindow);
btn_give.create(mainWindow);
btn_return.create(mainWindow);
btn_view.create(mainWindow);
btn_quit.create(mainWindow);
btn_author.create(mainWindow);
btn_version.create(mainWindow);
btn_add_book.caption("Add New Book");
btn_add_reader.caption("Add New Reader");
btn_add_librarian.caption("Add New Librarian");
btn_give.caption("Give out Book");
btn_return.caption("Returning Book");
btn_view.caption("View Books");
btn_quit.caption("Quit");
btn_author.caption("Author");
btn_version.caption("Version");
place.bind(mainWindow);
place.div("<><weight=90% vertical<><weight=85% vertical <vertical gap=5 menu> <weight=35 gap=25 buttons> ><>><>");
place.field("menu") << btn_add_book << btn_add_librarian << btn_add_reader << btn_give << btn_return << btn_view;
place.field("buttons") << btn_author << btn_version << btn_quit;
place.collocate();
}
void menu::print(Bookkeeping &db){
addBook(db);
addLibrarian(db);
addReader(db);
giveBook(db);
returnBook(db);
viewBook(db);
quit();
author();
version();
mainWindow.show();
nana::exec();
}
void menu::addBook(Bookkeeping& db){
btn_add_book.events().click([&db] {
nana::form addBookWindow;
addBookWindow.size(nana::size{ 360, 560 });
addBookWindow.caption("Add New Book");
addBookWindow.move(951 - 180, 540 - 300);
nana::textbox title{ addBookWindow },
ph{ addBookWindow },
quantity{ addBookWindow };
nana::date_chooser year_ph{ addBookWindow },
year_born{ addBookWindow };
nana::textbox name{ addBookWindow },
surname{ addBookWindow };
nana::combox box_country(addBookWindow);
std::vector<std::string> countries = { "Austria", "Belgium", "United Kingdom", "Hungary", "Germany", "Greece", "Denmark", "Spain", "Italy", "Netherlands", "Norway", "Poland", "Portugal", "Russia",
"Ukraine", "Finland", "France", "Croatia", "Czech Republic", "Switzerland", "Sweden", "USA", "Turkey", "China", "Japan", "Canada" };
for (auto x : countries) {
box_country.push_back(x);
}
box_country.option(0);
title.tip_string("Enter title of the book:").multi_lines(false);
ph.tip_string("Enter publishing house of the book:").multi_lines(false);
quantity.tip_string("Enter quantity of the book").multi_lines(false);
name.tip_string("Enter name of the author:").multi_lines(false);
surname.tip_string("Enter surname of the author:").multi_lines(false);
nana::button btn_quit(addBookWindow, "Quit");
nana::button btn_add(addBookWindow, "Add");
btn_quit.events().click([&addBookWindow] {
addBookWindow.close();
});
btn_add.events().click([&addBookWindow, &title, &ph, &quantity, &name, &surname, &box_country, &year_born, &year_ph, &db] {
int quantityBooks = quantity.to_int();
std::string titleBook, pH, nameAuthor, surnameAuthor, countryAuthor;
countryAuthor = box_country.text(box_country.option());
title.getline(0, titleBook);
ph.getline(0, pH);
name.getline(0, nameAuthor);
surname.getline(0, surnameAuthor);
nana::date::value yearAuthor = year_born.read().read();
nana::date::value yearBook = year_ph.read().read();
db.addBook(titleBook, pH, nameAuthor, surnameAuthor, countryAuthor, quantityBooks, yearBook, yearAuthor);
});
nana::place plc(addBookWindow);
plc.div("<><weight=90% vertical<><weight=85% vertical <vertical gap=10 book> <gap=10 date_book>"
"<vertical gap=10 author> <gap=10 date_author> <weight=25 gap=25 buttons> ><>><>");
plc.field("buttons") << btn_add << btn_quit;
plc.field("book") << title << ph << quantity;
plc.field("date_book") << year_ph;
plc.field("author") << name << surname << box_country;
plc.field("date_author") << year_born;
plc.collocate();
addBookWindow.show();
nana::exec();
});
}
void menu::addReader(Bookkeeping &db){
btn_add_reader.events().click([&db] {
nana::form addReaderWindow;
addReaderWindow.size(nana::size{ 360, 560 });
addReaderWindow.caption("Add New Reader");
addReaderWindow.move(951 - 180, 540 - 300);
nana::button btn_quit(addReaderWindow, "Quit");
nana::button btn_add(addReaderWindow, "Add");
nana::textbox city{ addReaderWindow },
street{ addReaderWindow },
house{ addReaderWindow },
apartment{ addReaderWindow };
nana::textbox name{ addReaderWindow },
surname{ addReaderWindow },
phone{ addReaderWindow };
nana::date_chooser year_born{ addReaderWindow };
nana::label date_lable{ addReaderWindow };
date_lable.format(true);
date_lable.caption("<color=0x808080>Enter the date of birth of the reader: </>");
name.tip_string("Enter name of the reader:").multi_lines(false);
surname.tip_string("Enter surname of the reader:").multi_lines(false);
phone.tip_string("Enter phone number of the reader:").multi_lines(false);
city.tip_string("Enter city of the reader").multi_lines(false);
street.tip_string("Enter street of the reader").multi_lines(false);
house.tip_string("Enter house number of the reader").multi_lines(false);
apartment.tip_string("Enter apartment number of the reader").multi_lines(false);
btn_add.events().click([&addReaderWindow, &city, &street, &house, &apartment, &name, &surname, &phone, &year_born, &db] {
unsigned int houseReader = house.to_int();
unsigned int apartmentReader = apartment.to_int();
std::string cityReader, streetReader, nameReader, surnameReader, phoneReader;
city.getline(0, cityReader);
street.getline(0, streetReader);
name.getline(0, nameReader);
surname.getline(0, surnameReader);
phone.getline(0, phoneReader);
nana::date::value yearReader = year_born.read().read();
db.addReader(nameReader, surnameReader, phoneReader, yearReader, cityReader, streetReader, houseReader, apartmentReader);
});
btn_quit.events().click([&addReaderWindow, &db] {
addReaderWindow.close();
});
nana::place plc(addReaderWindow);
plc.div("<><weight=90% vertical<><weight=85% vertical <vertical gap=10 reader> <vertical weight=20 gap=5 date_label> <vertical gap = 10 date_reader>"
"<vertical gap = 10 adress> <weight=25 gap=25 buttons> ><>><>");
plc.field("buttons") << btn_add << btn_quit;
plc.field("reader") << name << surname << phone;
plc.field("date_label") << date_lable;
plc.field("date_reader") << year_born;
plc.field("adress") << city << street << house << apartment;
plc.collocate();
addReaderWindow.show();
nana::exec();
});
}
void menu::addLibrarian(Bookkeeping &db){
btn_add_librarian.events().click([&db] {
nana::form addLibrarianWindow;
addLibrarianWindow.size(nana::size{ 240, 360 });
addLibrarianWindow.caption("Add New Librarian");
addLibrarianWindow.move(951 - 120, 540 - 200);
nana::button btn_quit(addLibrarianWindow, "Quit");
nana::button btn_add(addLibrarianWindow, "Add");
nana::label adress_label{ addLibrarianWindow };
nana::label librarian_label{ addLibrarianWindow };
adress_label.format(true);
librarian_label.format(true);
adress_label.caption("<color=0x808080>Enter librarian details: </>");
librarian_label.caption("<color=0x808080>Enter librarian address details : </>");
nana::textbox city{ addLibrarianWindow },
street{ addLibrarianWindow },
house{ addLibrarianWindow },
apartment{ addLibrarianWindow };
nana::textbox name{ addLibrarianWindow },
surname{ addLibrarianWindow },
phone{ addLibrarianWindow };
name.tip_string("Enter name of the librarian:").multi_lines(false);
surname.tip_string("Enter surname of the librarian:").multi_lines(false);
phone.tip_string("Enter phone number of the librarian:").multi_lines(false);
city.tip_string("Enter city of the librarian").multi_lines(false);
street.tip_string("Enter street of the librarian").multi_lines(false);
house.tip_string("Enter house number of the librarian").multi_lines(false);
apartment.tip_string("Enter apartment number of the librarian").multi_lines(false);
btn_add.events().click([&addLibrarianWindow, &name, &surname, &phone, &city, &street, &house, &apartment, &db] {
unsigned int houseLibrarian = house.to_int();
unsigned int apartmentLibrarian = apartment.to_int();
std::string cityLibrarian, streetLibrarian, nameLibrarian, surnameLibrarian, phoneLibrarian;
city.getline(0, cityLibrarian);
street.getline(0, streetLibrarian);
name.getline(0, nameLibrarian);
surname.getline(0, surnameLibrarian);
phone.getline(0, phoneLibrarian);
db.addLibrarian(nameLibrarian, surnameLibrarian, phoneLibrarian, cityLibrarian, streetLibrarian, houseLibrarian, apartmentLibrarian);
});
btn_quit.events().click([&addLibrarianWindow] {
addLibrarianWindow.close();
});
nana::place plc(addLibrarianWindow);
plc.div("<><weight=90% vertical<><weight=85% vertical <vertical weight=20 gap=5 label_librarian> <vertical gap=10 librarian>"
"<vertical weight=20 gap=5 label_adress> <vertical gap = 10 adress> <weight=25 gap=25 buttons> ><>><>");
plc.field("buttons") << btn_add << btn_quit;
plc.field("label_librarian") << librarian_label;
plc.field("librarian") << name << surname << phone;
plc.field("label_adress") << adress_label;
plc.field("adress") << city << street << house << apartment;
plc.collocate();
addLibrarianWindow.show();
nana::exec();
});
}
void menu::giveBook(Bookkeeping &db){
btn_give.events().click([&db] {
nana::form giveWindow;
giveWindow.size(nana::size{ 250, 180 });
giveWindow.caption("Give Book");
giveWindow.move(951 - 125, 540 - 100);
nana::button btn_quit(giveWindow, "Quit");
nana::button btn_add(giveWindow, "Add");
nana::textbox reader{ giveWindow },
librarian{ giveWindow },
label{ giveWindow };
reader.tip_string("Enter id of the reader:").multi_lines(false);
librarian.tip_string("Enter id of the librarian:").multi_lines(false);
label.tip_string("Enter label of the book:").multi_lines(false);
btn_add.events().click([&giveWindow, &reader, &librarian, &label, &db] {
unsigned int readerId = reader.to_int();
unsigned int librarianId = librarian.to_int();
std::string bookLabel;
label.getline(0, bookLabel);
db.actBook(readerId, librarianId, bookLabel, 0);
});
btn_quit.events().click([&giveWindow] {
giveWindow.close();
});
nana::place plc(giveWindow);
plc.div("<><weight=90% vertical<><weight=85% vertical <vertical gap=20 textbox> <weight=25 gap=25 buttons> ><>><>");
plc.field("buttons") << btn_add << btn_quit;
plc.field("textbox") << reader << librarian << label;
plc.collocate();
giveWindow.show();
nana::exec();
});
}
void menu::returnBook(Bookkeeping &db){
btn_return.events().click([&db] {
nana::form giveWindow;
giveWindow.size(nana::size{ 250, 180 });
giveWindow.caption("Return Book");
giveWindow.move(951 - 125, 540 - 100);
nana::button btn_quit(giveWindow, "Quit");
nana::button btn_add(giveWindow, "Add");
nana::textbox reader{ giveWindow },
librarian{ giveWindow },
label{ giveWindow };
reader.tip_string("Enter id of the reader:").multi_lines(false);
librarian.tip_string("Enter id of the librarian:").multi_lines(false);
label.tip_string("Enter label of the book:").multi_lines(false);
btn_add.events().click([&giveWindow, &reader, &librarian, &label, &db] {
unsigned int readerId = reader.to_int();
unsigned int librarianId = librarian.to_int();
std::string bookLabel;
label.getline(0, bookLabel);
db.actBook(readerId, librarianId, bookLabel, 1);
});
btn_quit.events().click([&giveWindow] {
giveWindow.close();
});
nana::place plc(giveWindow);
plc.div("<><weight=90% vertical<><weight=85% vertical <vertical gap=20 textbox> <weight=25 gap=25 buttons> ><>><>");
plc.field("buttons") << btn_add << btn_quit;
plc.field("textbox") << reader << librarian << label;
plc.collocate();
giveWindow.show();
nana::exec();
});
}
void menu::viewBook(Bookkeeping &db){
btn_view.events().click([&db] {
nana::form viewWindow;
viewWindow.size(nana::size{ 560, 360 });
viewWindow.caption("Return Book");
viewWindow.move(951 - 300, 540 - 180);
nana::listbox lb(viewWindow);
nana::button btn_quit(viewWindow, "Quit");
nana::button btn_act(viewWindow, "Execute");
nana::combox box_search(viewWindow);
box_search.push_back("Search books by author:");
box_search.push_back("Search for a book by title");
box_search.push_back("Show all books:");
box_search.push_back("Search books by country");
box_search.option(2);
nana::combox box_country(viewWindow);
std::vector<std::string> countries = { "Austria", "Belgium", "United Kingdom", "Hungary", "Germany", "Greece", "Denmark", "Spain", "Italy", "Netherlands", "Norway", "Poland", "Portugal", "Russia",
"Ukraine", "Finland", "France", "Croatia", "Czech Republic", "Switzerland", "Sweden", "USA", "Turkey", "China", "Japan", "Canada" };
for (auto x : countries) {
box_country.push_back(x);
}
box_country.option(0);
nana::textbox text_search(viewWindow);
nana::place plc(viewWindow);
plc.div("<><weight=90% vertical<><weight=90% vertical <vertical gap=20 listbox> <weight=25 gap=25 text> <weight=25 gap=25 buttons> ><>><>");
plc.field("listbox") << lb;
plc.field("buttons") << btn_act << btn_quit;
plc.field("text") << box_search << text_search;
plc.collocate();
box_country.move(nana::rectangle{ text_search.pos().x, text_search.pos().y, 241, 25 });
box_country.hide();
box_search.events().selected([&box_search, &box_country, &text_search] {
if (box_search.option() == 3) {
text_search.hide();
box_country.show();
}
else {
box_country.hide();
text_search.show();
}
});
text_search.tip_string("Enter what you are looking for: ").multi_lines(false);
lb.append_header("Title");
lb.append_header("Publication year");
lb.append_header("Publisher");
lb.append_header("Amount");
lb.append_header("Author");
nana::listbox::cat_proxy cat = lb.at(0);
lb.auto_draw(false);
cat = db.viewBooks(lb);
lb.auto_draw(true);
btn_act.events().click([&db, &lb, &cat, &text_search, &box_search, &box_country,&viewWindow] {
if (box_search.option() == 3) {
std::string country;
country = box_country.text(box_country.option());
cat = lb.at(0);
lb.auto_draw(false);
cat = db.search(lb, country, box_search.option());
lb.auto_draw(true);
}else {
std::string text;
text_search.getline(0, text);
cat = lb.at(0);
lb.auto_draw(false);
cat = db.search(lb, text, box_search.option());
lb.auto_draw(true);
}
});
btn_quit.events().click([&viewWindow] {
viewWindow.close();
});
viewWindow.show();
nana::exec();
});
}
void menu::quit(){
btn_quit.events().click([] {
nana::API::exit_all();
});
}
void menu::author(){
btn_author.events().click([] {
nana::msgbox msg_author("Author");
msg_author.icon(msg_author.icon_information);
msg_author << "My name is Andrey. I'm 20 years old. This my 3rd years course project.";
msg_author();
});
}
void menu::version(){
btn_version.events().click([] {
nana::msgbox msg_version("Version");
msg_version.icon(msg_version.icon_information);
msg_version << "Beta Version";
msg_version();
});
}
| true |
9feb542fcb649c9e8dcb2aef5167f9559f0006cd | C++ | l1007482035/vs2008PackPrj | /PdfTronHelper/Headers/Common/Matrix2D.h | UTF-8 | 10,312 | 3.140625 | 3 | [] | no_license | //---------------------------------------------------------------------------------------
// Copyright (c) 2001-2021 by PDFTron Systems Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------
#ifndef PDFTRON_H_CPPCommonMatrix2D
#define PDFTRON_H_CPPCommonMatrix2D
#include <Common/Common.h>
#include <C/Common/TRN_Types.h>
#include <C/Common/TRN_Matrix2D.h>
#include <PDF/Point.h>
#include <vector>
namespace pdftron {
namespace Common {
/**
* 2D Matrix
*
* A Matrix2D object represents a 3x3 matrix that, in turn, represents an affine transformation.
* A Matrix2D object stores only six of the nine numbers in a 3x3 matrix because all 3x3
* matrices that represent affine transformations have the same third column (0, 0, 1).
*
* Affine transformations include rotating, scaling, reflecting, shearing, and translating.
* In PDFNet, the Matrix2D class provides the foundation for performing affine transformations
* on vector drawings, images, and text.
*
* A transformation matrix specifies the relationship between two coordinate spaces.
* By modifying a transformation matrix, objects can be scaled, rotated, translated,
* or transformed in other ways.
*
* A transformation matrix in PDF is specified by six numbers, usually in the form
* of an array containing six elements. In its most general form, this array is denoted
* [a b c d h v]; The following table lists the arrays that specify the most common
* transformations:
*
* - Translations are specified as [1 0 0 1 tx ty], where tx and ty are the distances
* to translate the origin of the coordinate system in the horizontal and vertical
* dimensions, respectively.
*
* - Scaling is obtained by [sx 0 0 sy 0 0]. This scales the coordinates so that 1
* unit in the horizontal and vertical dimensions of the new coordinate system is
* the same size as sx and sy units, respectively, in the previous coordinate system.
*
* - Rotations are produced by [cos(A) sin(A) -sin(A) cos(A) 0 0], which has the effect
* of rotating the coordinate system axes by an angle 'A' counterclockwise.
*
* - Skew is specified by [1 tan(A) tan(B) 1 0 0], which skews the x axis by an angle
* A and the y axis by an angle B.
*
* Matrix2D elements are positioned as follows :
* | m_a m_b 0 |
* | m_c m_d 0 |
* | m_h m_v 1 |
*
* A single Matrix2D object can store a single transformation or a sequence of transformations.
* The latter is called a composite transformation. The matrix of a composite transformation is
* obtained by multiplying (concatenating) the matrices of the individual transformations.
* Because matrix multiplication is not commutative-the order in which matrices are multiplied
* is significant. For example, if you first rotate, then scale, then translate, you get a
* different result than if you first translate, then rotate, then scale.
*
* For more information on properties of PDF matrices please refer to PDF Reference Manual
* (Sections 4.2 'Coordinate Systems' and 4.2.3 'Transformation Matrices')
*
* @code
* The following sample illustrates how to use Matrix2D in order to position
* an image on the page. Note that PDFNet uses the same convention of matrix
* multiplication used in PostScript and OpenGL.
*
* Element element = eb.CreateImage(Image(...));
* double deg2rad = 3.1415926535 / 180.0;
*
* Matrix2D mtx = Matrix2D(1, 0, 0, 1, 0, 200); // Translate
* mtx *= Matrix2D(300, 0, 0, 200, 0, 0); // Scale
* mtx *= Matrix2D::RotationMatrix( 90 * deg2rad ); // Rotate
* element.GetGState().SetTransform(mtx);
* writer.WritePlacedElement(element);
* @endcode
*
* @code
* The following sample sample illustrates how to use Matrix2D in order to calculate
* absolute positioning for the text on the page.
* ...
* Matrix2D text_mtx = text_element.GetTextMatrix();
* double x, y;
* for (CharIterator itr = text_element.GetCharIterator(); itr.HasNext(); itr.Next()) {
* x = itr.Current().x; // character positioning information
* y = itr.Current().y;
* // Get current transformation matrix (CTM)
* Matrix2D ctm = text_element.GetCTM();
*
* // To get the absolute character positioning information concatenate current
* // text matrix with CTM and then multiply relative positioning coordinates with
* // the resulting matrix.
* Matrix2D mtx = ctm * text_mtx;
* mtx.Mult(x, y);
* }
* @endcode
*/
class Matrix2D : public TRN_Matrix2D
{
public:
/**
* Creates and initializes a Matrix object based on six numbers that define an
* affine transformation.
*
* @param a the matrix element in the first row, first column.
* @param b the matrix element in the first row, second column.
* @param c the matrix element in the second row, first column.
* @param d the matrix element in the second row, second column.
* @param h the matrix element in the third row, first column.
* @param v the matrix element in the third row, second column.
*
* @default when none the arguments are specified, an identity matrix is created.
*/
Matrix2D(double a = 1, double b = 0, double c = 0, double d = 1, double h = 0, double v = 0);
/**
* Copy constructor.
*/
Matrix2D(const Matrix2D& m);
/**
* Assignment operator.
*/
Matrix2D& operator= (const Matrix2D& m);
/**
* The Set method sets the elements of this matrix.
*
* @param a the matrix element in the first row, first column.
* @param b the matrix element in the first row, second column.
* @param c the matrix element in the second row, first column.
* @param d the matrix element in the second row, second column.
* @param h the matrix element in the third row, first column.
* @param v the matrix element in the third row, second column.
*/
void Set (double a, double b, double c, double d, double h, double v);
/**
* The Concat method updates this matrix with the product of itself and another matrix
* specified through an argument list.
*
* @param a the matrix element in the first row, first column.
* @param b the matrix element in the first row, second column.
* @param c the matrix element in the second row, first column.
* @param d the matrix element in the second row, second column.
* @param h the matrix element in the third row, first column.
* @param v the matrix element in the third row, second column.
*/
void Concat(double a, double b, double c, double d, double h, double v);
#if !defined(SWIG)
/**
* The multiply method updates this matrix with the product of itself and another matrix.
*
* @param m A matrix used to update this matrix
* @return updated this matrix representing the product of this matrix and given matrix 'm'.
*/
Matrix2D& operator*= (const Matrix2D& m);
/**
* Multiplies this matrix with another matrix and return the result in a new matrix.
*
* @return a matrix representing the product of this matrix and given matrix 'm'.
*/
Matrix2D operator* (const Matrix2D& m) const;
/**
* The equality operator determines whether the elements of this matrix are equal to
* the elements of another matrix.
*
* @param m A Matrix object that is compared with this Matrix object.
* @return A boolean regarding whether two matrices are the same.
*/
bool operator== (const Matrix2D& m) const;
/**
* The inequality operator determines whether the elements of this matrix are not equal to
* the elements of another matrix.
*
* @param A Matrix object that is compared with this Matrix object.
* @return A boolean regarding whether two matrices are different.
*/
bool operator!= (const Matrix2D& m) const {return !(this->operator ==(m));}
#else // !defined(SWIG)
Matrix2D Multiply(const Matrix2D& m);
bool IsEquals(const Matrix2D& m) const;
bool IsNotEquals(const Matrix2D& m) const
{
return (!this->IsEquals(m));
}
#endif // !defined(SWIG)
/**
* Transform/multiply the point (in_out_x, in_out_y) using this matrix
*/
PDF::Point Mult(const PDF::Point & pt) const;
#ifndef SWIG
void Mult(double& in_out_x, double& in_out_y) const;
#endif
/**
* @return If this matrix is invertible, the Inverse method returns its inverse matrix.
*/
Matrix2D Inverse () const;
/**
* Updates this matrix with the product of itself and a
* translation matrix (i.e. it is equivalent to this.m_h += h; this.m_v += v).
*
* @param h the horizontal component of the translation.
* @param v the vertical component of the translation.
* @note This method is deprecated. Please use PreTranslate or PostTranslate instead. The behavior of this method is identical to PreTranslate, but
* PostTranslate will be more suitable for some use cases.
*/
void Translate (double h, double v);
/**
* Updates this matrix to the concatenation of a translation matrix and the original matrix.
* M' = T(h, v) * M. It is equivalent to this.m_h += h; this.m_v += v.
*
* @param h the horizontal component of the translation.
* @param v the vertical component of the translation.
*/
void PreTranslate(double h, double v);
/**
* Updates this matrix by concatenating a translation matrix.
* M' = M * T(h, v). It is equivalent to this.Concat(1,0,0,1,h,v).
*
* @param h the horizontal component of the translation.
* @param v the vertical component of the translation.
*/
void PostTranslate(double h, double v);
/**
* The Scale method updates this matrix with the product of itself and a scaling matrix.
* @param h the horizontal scale factor.
* @param v the vertical scale factor
*/
void Scale (double h, double v);
/**
* Create zero matrix (0 0 0 0 0 0)
*/
static Matrix2D ZeroMatrix ();
/**
* Create identity matrix (1 0 0 1 0 0)
*/
static Matrix2D IdentityMatrix ();
/**
* @return A rotation matrix for a given angle.
* @param angle the angle of rotation in radians.
* Positive values specify clockwise rotation.
*/
static Matrix2D RotationMatrix (const double angle);
};
#include <Impl/Matrix2D.inl>
}; // namespace Common
}; // namespace pdftron
#endif // PDFTRON_H_CPPCommonMatrix2D
| true |
3a9df844f1e10f877cfdebe1609576d89cc31f8c | C++ | Nirach-N09/Arduino-CarSensorDashboard | /lib/VdoTemperatureSender/VdoTemperatureSender.h | UTF-8 | 404 | 2.609375 | 3 | [] | no_license | /**
* VDO Temperature Sender
*/
#ifndef VdoTemperatureSender_h
#define VdoTemperatureSender_h
#include <Arduino.h>
class VdoTemperatureSender
{
public:
VdoTemperatureSender(int analogPin, unsigned int dataTable[16]);
int getTemperature();
void debug(bool debug);
private:
int _analogPin;
bool _debug;
int _checkOrderTable;
unsigned int _dataTable[16];
int checkOrder();
};
#endif | true |
8627e8d75d157c093c48f6c63b360284982ea641 | C++ | abhilabh/DataStructure | /bfs using linklist.cpp | UTF-8 | 4,836 | 3.5 | 4 | [] | no_license | #include<iostream>
#include<cstring>
using namespace std;
class Queue
{
class node
{
public:
int info;
class node *next;
};
node *front,*rear;
public:
Queue()
{
front=NULL;
rear=NULL;
}
void enQueue(int n)
{
node *p=getnode(n);
if(isempty())
{
front=rear=p;
}
else
{
rear->next=p;
rear=p;
}
}
node* getnode(int k)
{
node* ptr=new node;
ptr->next=NULL;
ptr->info=k;
return ptr;
}
void display();
bool isempty();
int dequeue();
};
int Queue::dequeue()
{
int x;
node *p=front;
if(p==NULL)
{
cout<<"queue is empty";
}
else if(front->next==NULL)
front=rear=NULL;
else
front=front->next;
x=p->info;
delete p;
return x;
}
bool Queue::isempty()
{
if(front==NULL && rear==NULL)
return true;
else
return false;
}
void Queue::display()
{
node *p=front;
while(p!=NULL)
{
cout<<" "<<p->info;
p=p->next;
}
}
class bfs
{
class node
{
public:
int info;
node *next;
};
//node **headnode;
class hnode
{
public:
int info,dis;
char color[10];
node *next; //store the adress of class node not hnode
};
hnode **headnode;
public:
// char c[10];
node* getnode(int n) //for node
{
node *ptr;
if((ptr=new node)==NULL)
{
cout<<"node not created";
return NULL;
}
else
{
ptr->info=n;
ptr->next=NULL;
return ptr;
}
}
hnode* gethnode(int n) //for headnode
{
hnode *ptr;
if((ptr=new hnode)==NULL)
{
cout<<"head node not created";
return NULL;
}
else
{
char c[]={"white"};
ptr->info=n;
ptr->next=NULL;
strcpy(ptr->color,"white");
ptr->dis=-2222;
//cout<<ptr->color<<" ";
return ptr;
}
}
void create_graph(int);
bfs(int n);
void insert(int,node*);
void showlist(int);
void Bfs();
void vdisplay(int);
};
void bfs::create_graph(int n)
{
int no,x;
for(int i=0;i<n;i++)
{
cout<<"enter the no of adjecent vertex of "<<i<<" ";
cin>>no;
for(int j=0;j<no;j++)
{
cout<<"enter the adjecent of "<<i<<" ";
cin>>x;
insert(i,getnode(x));
}
}
}
bfs::bfs(int n) //constructor to initialize the value
{
headnode=new hnode*[n]; //initialize the array of pointer node
for(int i=0;i<n;i++)
{
headnode[i]=gethnode(i);
// hnode *ptr=headnode[i];
// cout<<headnode[i]->color<<" ";
}
}
void bfs::insert(int i,node *ptr)
{
node *p;
p=headnode[i]->next;
if(headnode[i]->next==NULL)
headnode[i]->next=ptr;
else
{
while(p->next!=NULL)
p=p->next;
p->next=ptr;
}
}
void bfs::showlist(int n)
{
node *ptr;
for(int i=0;i<n;i++)
{
ptr=headnode[i]->next;
cout<<"adjecent of vertex of "<<headnode[i]->info<<" is"<<endl;
// cout<<"adjecent vertex is ";
while(ptr!=NULL)
{
cout<<" "<<ptr->info;
ptr=ptr->next;
}
cout<<endl;
}
}
void bfs::Bfs() //bfs algo
{
int x,v;
char g[]={"grey"},b[]={"black"},w[]={"white"};
Queue q;
node *ptr;
cout<<"enter the vertex no from it started:";
cin>>x;
strcpy(headnode[x]->color,"grey");
headnode[x]->dis=0;
q.enQueue(x);
while(!(q.isempty()))
{
int u=q.dequeue();
ptr=headnode[u]->next;
while(ptr!=NULL)
{
v=ptr->info;
if(!strcmp(headnode[v]->color,w))
{
//cout<<"here";
strcpy(headnode[v]->color,"grey");
headnode[v]->dis=(headnode[u]->dis)+1;
q.enQueue(v);
}
ptr=ptr->next;
}
strcpy(headnode[u]->color,"black");
}
}
void bfs::vdisplay(int n)
{
for(int i=0;i<n;i++)
{
cout<<"vertex "<<i<<" ";
cout<<"distance= "<<headnode[i]->dis<<" ";
cout<<"color="<<headnode[i]->color<<" ";
cout<<endl;
}
}
int main()
{
int n;
cout<<"enter the no of vertices in the graph:";
cin>>n;
bfs b(n);
b.create_graph(n);
b.showlist(n);
cout<<"before apply bfs"<<endl;
b.vdisplay(n);
b.Bfs();
cout<<"after apply bfs"<<endl;
b.vdisplay(n);
}
| true |