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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
1a654b3c425a26aac300dacd17884740256b5777 | C++ | vrosnet/arduino-1 | /gameduino_test/gameduino_test.ino | UTF-8 | 4,425 | 2.65625 | 3 | [] | no_license | #include <EEPROM.h>
#include <SPI.h>
#include <GD2.h>
#include <stdlib.h> // for malloc and free
//#include <new.h>
#include <Ethernet.h>
#include <MsTimer2.h>
//void* operator new(size_t size) { return malloc(size); }
//void operator delete(void* ptr) { free(ptr); }
byte mac[] = {
0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0xfe };
char server[] = "google.com"; // name address for Google (using DNS)
EthernetClient client;
static void blocktext(int x, int y, byte font, const char *s)
{
GD.SaveContext();
GD.ColorRGB(0x000000);
GD.cmd_text(x -1, y-1, 31, 0, s);
GD.cmd_text(x +1, y-1, 31, 0, s);
GD.cmd_text(x -1, y+1, 31, 0, s);
GD.cmd_text(x +1, y+1, 31, 0, s);
GD.RestoreContext();
GD.cmd_text(x, y, 31, 0, "Clock");
}
class Clock
{
private:
int counter;
int x_pos;
public:
Clock(){
counter = 0;
x_pos = 0;
}
void render(){
GD.ColorA(160);
GD.ColorRGB(0x222288);
GD.ColorA(255);
blocktext(190+x_pos/10 -1, 80-1, 31, "Clock");
GD.cmd_number(240, 60, 31, OPT_CENTER, counter);
x_pos ++;
if (x_pos>1000) x_pos = 0;
}
void inc(){
counter ++;
}
};
class Weather
{
public:
void render(){
GD.ColorA(128);
GD.ColorRGB(0xffffff);
GD.cmd_text(240, 120, 31, OPT_CENTER, "Weather");
}
};
class Network
{
public:
int a0,a1,a2,a3;
bool hasAddress, hasConnection;
Network(){
hasAddress = false;
hasConnection = false;
}
void getIpAddress(){
if (Ethernet.begin(mac)==0){
hasAddress=false;
} else {
a0 = Ethernet.localIP()[0];
a1 = Ethernet.localIP()[1];
a2 = Ethernet.localIP()[2];
a3 = Ethernet.localIP()[3];
hasAddress=true;
}
}
char *getStatus(){
if (hasConnection == true){
return "Connection successfull !";
}
if (hasAddress == true){
return "Got IP address, but connection failed !";
}
return "No network !";
}
void initNetwork(){
Serial.begin(9600);
Serial.println("Obtaining IP address...");
getIpAddress();
if (hasAddress){
Serial.println("Got IP address");
}
delay(1000);
Serial.println("connecting...");
if (isConnected()){
hasConnection = true;
Serial.println("connected");
} else {
hasConnection = false;
Serial.println("NOT connected");
}
}
bool isConnected(){
if (hasAddress && client.connect(server, 80)) {
client.stop();
Serial.println("Connecting ok");
return true;
} else {
return false;
}
}
void render(){
if (hasAddress){
GD.ColorA(170);
GD.cmd_text(200, 200, 30, OPT_CENTER, "Ip address:");
GD.cmd_number(200, 226, 29, OPT_CENTER, a0);
GD.cmd_number(250, 226, 29, OPT_CENTER, a1);
GD.cmd_number(300, 226, 29, OPT_CENTER, a2);
GD.cmd_number(350, 226, 29, OPT_CENTER, a3);
}
GD.ColorA(255);
GD.cmd_text(200, 250, 29, OPT_CENTER, getStatus());
}
};
Clock *clock;
Weather *weather;
Network *network;
void setup()
{
clock = new Clock();
weather = new Weather();
network = new Network();
GD.begin();
GD.ClearColorRGB(0x104000);
GD.Clear();
GD.cmd_text(200, 100, 30, OPT_CENTER, "Searching for network...");
GD.swap();
// set up ISR for timer2.
pinMode(13,OUTPUT);
MsTimer2::set(1000,flash);
MsTimer2::start();
network->initNetwork();
//MsTimer2::stop();
GD.ClearColorRGB(0x104000);
GD.Clear();
GD.cmd_text(200, 100, 30, OPT_CENTER, "Done searching...");
GD.swap();
GD.cmd_loadimage(0, 0);
GD.load("back_50.jpg");
//GD.load("healsky3.jpg");
}
void flash(){
clock->inc();
}
void renderWeather(){
GD.cmd_text(240, 80, 31, OPT_CENTER, "Weather");
}
void loop(){
GD.ClearColorRGB(0x104000);
GD.Clear();
GD.Begin(BITMAPS);
GD.Vertex2ii(0, 0);
//GD.cmd_gradient(0,0,0x0060c0, 0,271,0xc06000);
GD.PointSize(16*100);
GD.Begin(POINTS);
GD.ColorA(255);
GD.ColorRGB(0xff8000);
GD.Vertex2ii(160,110);
clock->render();
weather->render();
network->render();
GD.swap();
}
| true |
38b9369d1650f9748837022f6583db0650d656fc | C++ | ratopythonista/programacao-competitiva | /solutions/URI/DataStructure/1110.cpp | UTF-8 | 514 | 2.6875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main(){
int n;
while(scanf("%d", &n) && n!=0){
queue<int> fila, remain;
for(int i=1; i<=n; i++) fila.push(i);
while(fila.size()>1){
remain.push(fila.front());
fila.pop();
fila.push(fila.front());
fila.pop();
}
printf("Discarded cards:");
while(!remain.empty()){
printf(" %d", remain.front());
remain.pop();
if(remain.size()!=0) printf(",");
}printf("\n");
printf("Remaining card: %d\n", fila.front());
}
return 0;
}
| true |
e432907d350a03f1562463bcca30f8ff2e7ccfe7 | C++ | tenaiti/DALT | /FINAL/DALT.cpp | UTF-8 | 2,442 | 2.71875 | 3 | [] | no_license | #include <iostream>
#include <stdlib.h>
using namespace std;
#include "movie.h"
#include "room.h"
#include "shift.h"
#include "revenue.h"
#include "ticket.h"
#include "times.h"
#include "detailTimes.h"
#include "models.h"
MovieController movies;
RoomController rooms;
TicketController tickets;
ShiftController shifts;
TimesController times;
RevenueController revenues;
class {
public:
class {
public:
int menu() {
system("cls");
cout<< "+-------------------------------------------------+" <<endl
<< "| NHOM DALT_02 - 18TCLDT3-18N15 |" << endl
<< "| THANH VIEN NHOM: NGUYEN KIM HUY |" << endl
<< "| VO VAN MUOI |" << endl
<< "| VAN NGOC DAT |" << endl
<< "| NGUYEN NGOC KHOI |" << endl
<< "+-------------------------------------------------+" << endl
<< "| |" << endl
<< "| CNIEMA Management System |" << endl
<< "| |" << endl
<< "+-------------------------------------------------+" << endl
<< "|1. MOVIE |" << endl
<< "|2. ROOM |" << endl
<< "|3. TICKET |" << endl
<< "|4. SHIFT |" << endl
<< "|5. SHOWTIMES |" << endl
<< "|6. REVENUE |" << endl
<< "|7. EXIT |" << endl
<< "+-------------------------------------------------+" << endl
<< "Your option: ";
int n;
cin >> n;
return n;
}
} views;
void render() {
switch (views.menu())
{
case 1:
movies.menuMovie();
this->render();
break;
case 2:
rooms.menuRoom();
this->render();
break;
case 3:
tickets.menuTicket();
this->render();
break;
case 4:
shifts.menuShift();
this->render();
break;
case 5:
times.menuTimes();
this->render();
break;
case 6:
revenues.menuRevenue();
this->render();
break;
case 7:
break;
default:
this->render();
}
}
} home;
int main()
{
system("cls");
home.render();
return 0;
} | true |
0d424d1d868492b56de58b5dd47f0532442a88df | C++ | Danielhp95/tennis-model | /tennis_model/sim/tennis-simulations/match.hpp | UTF-8 | 1,819 | 2.546875 | 3 | [] | no_license | //#define NOISE
class Player;
class Set;
class Match {
private:
//Player *_player[2];
double _spw[2];
bool _player1_serving;
int _sets_to_win, sets_played, _sets_won[2];
double _noise[2];
Set *set[5];
bool _tiebreaker;
bool _tiebreaker_final_set;
int _total_games;
int _serves_played[2];
int _serves_won[2];
void reset_match() {
sets_played = 0;
_total_games = 0;
_sets_won[0] = 0;
_sets_won[1] = 0;
_serves_played[0] = 0;
_serves_played[1] = 0;
_serves_won[0] = 0;
_serves_won[1] = 0;
_player1_serving = (drand48() > 0.5);
_tiebreaker = false;
}
public:
Match(double spw1, double stddev1, double spw2, double stddev2, bool five_sets, bool tiebreaker_final_set);
bool match_over() {
return player_won(0) || player_won(1);
}
bool player_won(int __player) { return _sets_won[__player] >= _sets_to_win; }
void print_score() {
}
void increase_games() {
_total_games++;
}
bool play_match();
bool player1_serving() {
return _player1_serving;
}
bool switch_server() {
_player1_serving = !_player1_serving;
return _player1_serving;
}
/* Player *player(int __player) {
return _player[__player];
}
double noise(int __player) {
return _noise[__player];
}*/
int sets_to_win() const { return _sets_to_win; }
int sets_won(int player) { return _sets_won[player]; }
void increase_serves_played(int player) { _serves_played[player]++; }
int serves_played(int player) { return _serves_played[player]; }
void increase_serves_won(int player) { _serves_won[player]++; }
int serves_won(int player) { return _serves_won[player]; }
bool tiebreaker() const { return _tiebreaker; }
void set_tiebreaker() { _tiebreaker = true; }
int total_games() { return _total_games; }
};
| true |
984f43250ff3c8729271e7570838801f0e571df4 | C++ | GuanyiLi-Craig/interview | /Array/q46.cpp | UTF-8 | 2,989 | 3.328125 | 3 | [] | no_license | /****************************************************************************************************
46. Permutations
-----------------------------------------------------------------------------------------------------
Given a collection of distinct numbers, return all possible permutations.
For example,
[1,2,3] have the following permutations:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
****************************************************************************************************/
#include "problems\problems\Header.h"
namespace std
{
class Solution {
public:
vector<vector<int>> permute(vector<int>& nums) {
// dp. f(n) = g(f(n-1)): g: insert the nth element to n possible position from f(n-1) results.
vector<vector<int> > rst;
int len=nums.size();
if (len<1) return rst;
if (len==1) {rst.push_back(nums); return rst;}
vector<int> csol; csol.push_back(nums[0]);
rst.push_back(csol);
for(int i=1;i<len;i++)
{
vector<vector<int> > temp;
int ilen=rst.size();
for(int j=0;j<ilen;j++)
{
csol=rst[j];
for(int k=0;k<=csol.size();k++)
{
vector<int> icsol=csol;
vector<int>::iterator it=icsol.begin();
icsol.insert(it+k,1,nums[i]);
temp.push_back(icsol);
}
}
rst=temp;
}
return rst;
}
};
class Solution2 {
public:
vector<vector<int>> permute(vector<int>& nums) {
int len=nums.size();
vector<vector<int> > rst;
if (len<=1)
{
rst.push_back(nums);
return rst;
}
vector<int> current;
helper(nums,current,rst);
return rst;
}
void helper(vector<int> nums, vector<int> current, vector<vector<int> >& rst)
{
int len=nums.size();
if (len==1)
{
current.push_back(nums[0]);
rst.push_back(current);
return;
}
for(int i=0;i<len;i++)
{
current.push_back(nums[i]);
nums.erase(nums.begin()+i);
helper(nums,current,rst);
nums.insert(nums.begin()+i,current.back());
current.pop_back();
}
}
};
}
/****************************************************************************************************
Note
remember it is a dp problem.
****************************************************************************************************/ | true |
416cdd9f07530059382e9c6183f6688d3b43fb35 | C++ | marcinklimek/cpp_rt_2 | /day2/ex_pi/boost/pi.cpp | UTF-8 | 2,212 | 3.28125 | 3 | [] | no_license | #include <iostream>
#include <cstdlib>
#include <ctime>
#include <iomanip>
#include "boost/thread.hpp"
#include <omp.h>
using namespace std;
double darts(int num_darts)
{
int i, p=0;
for (i = 1; i <= num_darts; i++)
{
double x, y;
x = static_cast< double >( rand() )/RAND_MAX;
y = static_cast< double >( rand() )/RAND_MAX;
if ( (x*x + y*y) <= 1.0)
p++;
}
return 4.0*static_cast< double >( p )/num_darts;
}
void darts_threaded(int num_darts, int& result)
{
int i, p=0;
for (i = 1; i <= num_darts; i++)
{
double x, y;
x = static_cast< double >( rand() )/RAND_MAX;
y = static_cast< double >( rand() )/RAND_MAX;
if ( (x*x + y*y) <= 1.0)
p++;
}
result = p;
}
void calculate_serial(int num_darts, int seed)
{
srand(seed);
boost::posix_time::ptime start = boost::posix_time::microsec_clock::local_time();
double PI = darts(num_darts);
boost::posix_time::ptime stop = boost::posix_time::microsec_clock::local_time();
cout << "For " << num_darts << " darts thrown the value of PI is " << PI << " time " << (stop - start).total_milliseconds() << endl;
}
void calculate_threaded(int num_darts, int seed)
{
int num_threads = boost::thread::hardware_concurrency();
srand(seed);
std::vector<int> results( num_threads );
boost::posix_time::ptime start = boost::posix_time::microsec_clock::local_time();
boost::thread_group grp;
for(int i=0; i<num_threads; i++)
grp.create_thread(boost::bind(darts_threaded, num_darts/num_threads, boost::ref(results[i])));
grp.join_all();
int result = std::accumulate(results.begin(), results.end(), 0);
double PI = 4.0*static_cast< double >( result )/num_darts;
//stop = omp_get_wtime();
boost::posix_time::ptime stop = boost::posix_time::microsec_clock::local_time();
cout << "For " << num_darts << " darts thrown the value of PI is " << PI << " time " << (stop - start).total_milliseconds() << endl;
}
int main()
{
int num_darts = 10000000;
int seed = time(NULL);
calculate_serial(num_darts, seed);
calculate_threaded(num_darts, seed);
}
| true |
2b94f9e23786aaf7c2ad3707bdbfc4a056cdc1d2 | C++ | gagan86nagpal/Interview-prep | /Coin Change/main.cpp | UTF-8 | 775 | 2.78125 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
#include <sstream>
namespace patch
{
template < typename T > std::string to_string( const T& n )
{
std::ostringstream stm ;
stm << n ;
return stm.str() ;
}
}
using namespace std;
vector <int> v;
int dp[1000];
int coinChange(int n,int m,string result)
{
if(n<0)
return 0;
if(n==0)
{
cout<<result.substr(1)<<"\n";
return 1;
}
if(m==-1)
return 0;
return coinChange(n-v[m],m,result+" "+patch::to_string(v[m]) )+coinChange(n,m-1,result);
}
int main()
{
int n,m,x;
cin>>m>>n;
for(int i=0;i<m;i++)
{
cin>>x;
v.push_back(x);
}
int ans=coinChange(n,m-1,"");
cout<<ans<<"\n";
return 0;
}
| true |
5d2959bf9f18fab399c24572104d41f7ba863b20 | C++ | tobin/hilfingr-ctest | /2009/7.cc | UTF-8 | 4,078 | 2.875 | 3 | [] | no_license | #include "contest.h"
#include <assert.h>
int N;
int grid[12][12];
int crossed[12][12]; // 0 = not crossed out, 1 = crossed out, -1 = undecided
#define D if (0)
int one_piece() {
int reachable[12][12];
for (int i=0; i<N+2; i++)
for (int j=0; j<N+2; j++)
reachable[i][j] = 0;
// find an uncrossed square to set
int uncrossed_found = 0;
for (int r=1; r<N+1; r++)
for (int c=1; c<N+1; c++) {
if (crossed[r][c]==0) {
uncrossed_found = 1;
reachable[r][c] = 1;
break;
}
}
if (!uncrossed_found)
return 1;
// floodfill
for (int iteration=0; iteration<100; iteration++) {
for (int r=1; r<N+1; r++)
for (int c=1; c<N+1; c++) {
if (crossed[r][c]==1)
continue;
// if this square is uncrossed, it can reach any of its (uncrossed) neighbors
reachable[r][c] |= (crossed[r][c+1]!=1 && reachable[r][c+1]);
reachable[r][c] |= (crossed[r][c-1]!=1 && reachable[r][c-1]);
reachable[r][c] |= (crossed[r+1][c]!=1 && reachable[r+1][c]);
reachable[r][c] |= (crossed[r-1][c]!=1 && reachable[r-1][c]);
}
}
int any_unreachable = 0;
for (int r=1; r<N+1; r++)
for (int c=1; c<N+1; c++)
if (crossed[r][c]!=1 && !reachable[r][c])
any_unreachable = 1;
return !any_unreachable;
}
int error_found() {
int occurs_row[102];
int occurs_col[102];
// check for adjacent crossings
for (int r=1; r<N+1; r++)
for (int c=1; c<N+1; c++)
if (crossed[r][c]==1) {
if (crossed[r][c+1]==1 || crossed[r][c-1]==1 || crossed[r+1][c]==1 || crossed[r-1][c]==1)
return 1;
}
// search row and column j
for (int j=1; j<N+1; j++) {
// initialize
for (int i=0; i<100; i++) {
occurs_row[i] = 0;
occurs_col[i] = 0;
}
for (int i=1; i<N+1; i++) {
if (crossed[i][j]==0) {
if (occurs_row[grid[i][j]])
return 1;
occurs_row[grid[i][j]] = 1;
}
if (crossed[j][i]==0) {
if (occurs_col[grid[j][i]])
return 1;
occurs_col[grid[j][i]] = 1;
}
}
}
if (!one_piece())
return 1;
return 0; // no errors found
}
int solve(int x, int N, int depth) {
int row = (x / N) + 1;
int col = x - (row - 1)*N + 1;
D printf("solve(%d = (%d, %d))\n", x, row, col);
assert(row>0);
assert(col>0);
// if there's an error -- backtrack
if (error_found()) {
D printf("Error found - backtracking\n");
return 0;
}
// if we've set all the puzzle elements with no errors, we're done
if (x > N*N) {
D printf("Solution found!");
return 1;
}
// if there are still errors but we've used up all our crosses, there's no solution
if (depth==0)
return 0;
// no errors, not done
for (int choice=0; choice<2; choice ++) {
D printf("choosing crossed[%d][%d]==%d\n", row, col, choice);
crossed[row][col] = choice;
if (solve(x+1, N, choice ? (depth-1) : (depth)))
return 1;
}
D printf("unsetting crossed[%d][%d]\n", row, col);
crossed[row][col] = -1;
return 0;
}
void print_board() {
for (int i=0; i<N; i++) {
for (int j=0; j<N; j++) {
printf(" %c%d%c",
crossed[i+1][j+1]==1 ? '(' : ' ', grid[i+1][j+1],
crossed[i+1][j+1]==1 ? ')' : ' ' );
}
printf("\n");
}
}
void initialize() {
for (int i=0; i<=N+1; i++) {
crossed[0][i] = 0;
crossed[N+1][i] = 0;
crossed[i][0] = 0;
crossed[i][N+1] = 0;
}
for (int i=0; i<N; i++)
for (int j=0; j<N; j++)
crossed[i+1][j+1] = -1; // undecided
}
int do_solve() {
int solved = 0;
for (int depth=0; depth<(N*N); depth++) {
D printf("Initiating search at depth %d\n", depth);
initialize();
if (solve(0, N, depth)) {
solved = 1;
break;
}
}
return solved;
}
int main(int argc, char **argv) {
int G = 0;
while (1 == scanf("%d", &N) && N>0) {
G ++;
printf("Grid %d:\n", G);
for (int i=0; i<N; i++)
for (int j=0; j<N; j++)
scanf("%d", &(grid[i+1][j+1]));
if (do_solve()) {
D printf("Solved!\n");
} else
printf("NOT SOLVED\n");
print_board();
}
return 0;
}
| true |
6b86db4f80726dc1b6c0f6c248845e0c10d621aa | C++ | chromex/gamejaming | /ld25/project/Session.cpp | UTF-8 | 25,519 | 2.8125 | 3 | [] | no_license | #include "Session.h"
#include "Log.h"
#include "Settings.h"
#include "Colors.h"
#include "World.h"
#include "Contracts.h"
#include <boost/bind.hpp>
#include <istream>
#define SendStream(S) {std::stringstream ss; ss << S; Send(ss.str());}
Session::Session( boost::asio::io_service& service )
: _socket(service)
, _loginStage(0)
, _user(0)
, _authUser(0)
, _closing(false)
, _sending(false)
, _recving(false)
, _shouldQuit(false)
{}
Session::~Session()
{
Log("Session destroyed");
World::Instance()->RemoveSession(this);
}
tcp::socket& Session::Socket()
{
return _socket;
}
User* Session::GetUser()
{
return _user;
}
void Session::Start()
{
Log("Starting session");
SendWelcome();
ChainRecv();
}
void Session::Stop()
{
_socket.close();
_closing = true;
if(!_sending && !_recving)
{
delete this;
}
}
void Session::SendWelcome()
{
Send("\r\n\
::: ::::::::: :::::::: :::::::::: \r\n\
:+: :+: :+: :+: :+: :+: :+: \r\n\
+:+ +:+ +:+ +:+ +:+ \r\n\
+#+ +#+ +:+ +#+ +#++:++#+ \r\n\
+#+ +#+ +#+ +#+ +#+ \r\n\
#+# #+# #+# #+# #+# #+# \r\n\
########## ######### ########## ######## \r\n\
\r\n");
SendStream(REDCOLOR << "Connected to EndNet, a LD25 entry\r\n" << CLEARCOLOR);
Send("What is the username you have or would like to have?\r\n");
SendPrompt();
_loginStage = 1;
}
void Session::SendPrompt()
{
if(!_closing)
{
if(0 != _user && _user->Started && !_user->Done)
{
int minutes = 60 - _user->StartTime->MinutesFromLocal();
SendStream(REDCOLOR << minutes << "m remaining" << GREENCOLOR << "> " << CLEARCOLOR);
}
else if(0 != _user && _user->Done)
{
SendStream(REDCOLOR << "Time's up" << GREENCOLOR << "> " << CLEARCOLOR)
}
else
{
SendStream(GREENCOLOR << "> " << CLEARCOLOR);
}
}
}
bool IsAlnum(const std::string& message)
{
for(size_t idx = 0; idx < message.length(); ++idx)
{
if(!isalnum(message[idx]))
return false;
}
return true;
}
void Session::LoginMessage( const std::string& message )
{
switch(_loginStage)
{
case 0:
LogWarning("Received message before auth began, ignoring");
return;
case 1:
{
_authUser = Users::Instance()->GetUserByUsername(message);
if(0 == _authUser)
{
if(!IsAlnum(message))
{
Send("Username can only contain letters and numbers. Try again!\r\n");
}
else if(message.length() < 33)
{
SendStream("Creating new user '" << message << "'\r\n");
Send("What would you like for your password?\r\nKnow that telnet is not secure so don't use your normal password!\r\n");
++_loginStage;
_authUsername = message;
}
else
{
Send("Username is too long, 32 character max. Try again!\r\n");
}
}
else
{
Send("And your password?\r\n");
_loginStage = 10;
_authUsername = message;
}
}
break;
case 2:
{
if(message.length() < 129)
{
Send("Again!\r\n");
++_loginStage;
_authPassword = message;
}
else
{
Send("Password was too long, try again!\r\n");
}
}
break;
case 3:
{
if(_authPassword == message)
{
_user = Users::Instance()->CreateUser(_authUsername, _authPassword);
if(0 != _user)
{
SendStream("Created user '" << _authUsername << "' with password '" << _authPassword << "'\r\n");
_loginStage = -1;
World::Instance()->AddSession(this);
DoHelp("story");
SendStream(REDCOLOR << "\r\nNew to the game? Try 'help game', 'help contracts', and 'help commands'\r\n" << CLEARCOLOR);
}
else
{
Send("It looks like your username was taken while you were signing up.\r\nWhat username would you like?\r\n");
_loginStage = 1;
}
}
else
{
Send("Passwords don't match.\r\nWhat would you like for your password?\r\n");
--_loginStage;
}
}
break;
case 10:
{
if(_authUser->Password == message)
{
_user = _authUser;
SendStream(GREENCOLOR << "Authentication successful\r\n" << CLEARCOLOR);
if(_user->Admin)
{
SendStream("Welcome back, administrator.\r\n");
}
_loginStage = -1;
Log("User '" << _user->Username << "' returns");
World::Instance()->AddSession(this);
}
else
{
SendStream("Failed authentication!\r\nWhat is the username you have or would like to have?\r\n");
_authUser = 0;
_loginStage = 1;
}
}
break;
}
}
std::string ExtractCommand(const std::string& message, std::string& remainder)
{
size_t idx = message.find(' ');
std::string command;
if(std::string::npos == idx)
{
command = message;
remainder = "";
}
else
{
command = message.substr(0, idx);
idx = message.find_first_not_of(' ', idx);
if(std::string::npos == idx)
remainder = "";
else
remainder = message.substr(idx);
}
for(idx = 0; idx < command.length(); ++idx)
{
if(isupper(command[idx]))
command[idx] = tolower(command[idx]);
}
return command;
}
void Session::DoWho()
{
std::vector<User*> users;
World::Instance()->GetUsers(users);
std::stringstream ss;
ss << "--[" << GREENCOLOR << "Users Online" << CLEARCOLOR << "]------\r\n";
for(std::vector<User*>::const_iterator user = users.begin(); user != users.end(); ++user)
{
User* up = *user;
if(up->Admin)
ss << "[Admin] ";
else if(up->Done)
ss << "[Dead] ";
ss << up->Username << " - $" << up->Money << " R" << up->Respect << " - " << up->About.substr(0,30) << "\r\n";
}
Send(ss.str());
}
void Session::DoHelp(const std::string& message)
{
std::string remainder;
std::string topic = ExtractCommand(message, remainder);
if("commands" == topic)
{
std::stringstream ss;
ss << "--[" << GREENCOLOR << "Help - Commands" << CLEARCOLOR << "]------\r\n";
ss << "[" << REDCOLOR << "Social Commands" << CLEARCOLOR << "]\r\n";
ss << GREENCOLOR << "about" << CLEARCOLOR << " <player> - Get information about the player\r\n";
ss << GREENCOLOR << "setabout" << CLEARCOLOR << " <message> - Set the message for your 'about' page\r\n";
ss << GREENCOLOR << "say" << CLEARCOLOR << " <message> - Send a message on global chat\r\n";
ss << GREENCOLOR << "tell" << CLEARCOLOR << " <player> <message> - Send the online player a message\r\n";
ss << GREENCOLOR << "leaders" << CLEARCOLOR << " - Show the richest players ever\r\n";
ss << GREENCOLOR << "who" << CLEARCOLOR << " - Show online players\r\n\r\n";
ss << "[" << REDCOLOR << "Contract List Commands" << CLEARCOLOR << "]\r\n";
ss << GREENCOLOR << "offers" << CLEARCOLOR << " - Show pending offers that involve you\r\n";
ss << GREENCOLOR << "contracts" << CLEARCOLOR << " - Show currently running contracts that involve you\r\n";
ss << GREENCOLOR << "results" << CLEARCOLOR << " - Show contracts that have completed that involve you\r\n\r\n";
ss << "[" << REDCOLOR << "Contract Commands" << CLEARCOLOR << "]\r\n";
ss << GREENCOLOR << "accept" << CLEARCOLOR << " <player> - Accept the offer from the player\r\n";
ss << GREENCOLOR << "evilaccept" << CLEARCOLOR << " <player> - Backstab on the offer from the player\r\n";
ss << GREENCOLOR << "offer" << CLEARCOLOR << " <investment1> <player> <investment2> <duration>\r\n";
ss << " - Offer a contract, you invest investment1, they invest investment2\r\n";
ss << GREENCOLOR << "eviloffer" << CLEARCOLOR << " <investment1> <player> <investment2> <duration>\r\n";
ss << " - Offer a backstab contract with the player\r\n";
ss << GREENCOLOR << "reject" << CLEARCOLOR << " <player> - Reject the offer from the player\r\n";
ss << GREENCOLOR << "rate" << CLEARCOLOR << " <id> <player> <rating> - Rate the player on the finished contract\r\n";
Send(ss.str());
}
else if("game" == topic)
{
std::stringstream ss;
ss << "--[" << GREENCOLOR << "Help - Game" << CLEARCOLOR << "]------\r\n";
ss << "The point of the game is to make money on contracts with a prisoner's dilemma\r\n";
ss << "twist. Either or both of the players involved in a contract can choose to\r\n";
ss << "backstab the other with the \"evil\" versions of the offer and accept commands.\r\n";
ss << "If neither uses the evil version, both players profit. If both are evil, both\r\n";
ss << "loose everything invested as well as the contract slot for its duration. And\r\n";
ss << "if only one is evil, then they take all of the money for themselves. Whether\r\n";
ss << "or not you got screwed is not known until the contract is complete.\r\n\r\n";
ss << "Since you only have one hour to make as much money as you can, picking who you\r\n";
ss << "make deals with and if you screw them over is paramount. To facilitate this\r\n";
ss << "players can chat globally (say) and privately (tell) and can see info about\r\n";
ss << "players (about). \r\n\r\n";
ss << "To aid in this, a reputation system is in place. Each player starts with 10\r\n";
ss << "reputation. When a contract completes, both players involved can rate the\r\n";
ss << "contract interaction in the range of -3 to +3. This is applied to the other\r\n";
ss << "player and is reflected on their public reputation where higher is better.\r\n";
Send(ss.str());
}
else if("story" == topic)
{
std::stringstream ss;
ss << "--[" << GREENCOLOR << "Help - Story" << CLEARCOLOR << "]------\r\n";
ss << "Money. Its all about the damn money. To make everything \"fair\" it was decided\r\n";
ss << "in the year 2025 to make it so everyone had access to the trade markets. The\r\n";
ss << "problem? You only get one shot. For one hour.\r\n\r\n";
ss << "Everyone is given a preset amount of cash and once you start trading, you have\r\n";
ss << "one hour to make as much money as you can. Whats going on behind the trades?\r\n";
ss << "It doesn't matter any more. Its just a system.\r\n\r\n";
ss << "Once the hour is up, you'll still be able to connect to the system but you can\r\n";
ss << "no longer trade. No longer make more money. You failed? Whelp, your boned. \r\n\r\n";
ss << "Don't fail.\r\n";
Send(ss.str());
}
else if("contracts" == topic)
{
std::stringstream ss;
ss << "--[" << GREENCOLOR << "Help - Contracts" << CLEARCOLOR << "]------\r\n";
ss << "Contracts are how you make money. To create a contract, one player makes an\r\n";
ss << "offer to another with the contract details. The other player can choose to\r\n";
ss << "accept or reject the contract. Once accepted the contract lasts the specified\r\n";
ss << "duration. Any one player can only have a maximum of 5 open contracts at a \r\n";
ss << "time. The \"offer\" and \"accept\" have evil versions called \"eviloffer\" and \r\n";
ss << "\"evilaccept\", the effects of which are described in \"help game\".\r\n\r\n";
ss << "The parameters of the offer commands are:\r\n";
ss << " - offer <investment1> <player> <investment2> <duration>\r\n\r\n";
ss << "investment1 - The investment of the offering player\r\n";
ss << "player - The player you are making the offer to\r\n";
ss << "investment2 - How much the other player is supposed to invest\r\n";
ss << "duration - How long the contract lasts in minutes if accepted, max of 5\r\n\r\n";
ss << "Profit multipliers increase with duration. At 1 minute, each player makes\r\n";
ss << "back their investment plus the average of both investments and at 5 minutes\r\n";
ss << "each makes back their investment plus 16x the average of their investments!\r\n";
Send(ss.str());
}
else
{
SendStream("--[" << GREENCOLOR << "Help Topics" << CLEARCOLOR << "]------\r\n");
SendStream("Syntax: help <topic>\r\n\r\n[" << GREENCOLOR << "Topics" << CLEARCOLOR << "]\r\n");
Send("commands\r\ngame\r\nstory\r\ncontracts\r\n");
}
}
void Session::DoLeaders()
{
const std::vector<User*>& users = Users::Instance()->GetLeaders();
int pos = 1;
std::stringstream ss;
ss << "--[" << GREENCOLOR << "Leaders" << CLEARCOLOR << "]------\r\n";
for(std::vector<User*>::const_iterator up = users.begin(); up != users.end(); ++up)
{
if((*up)->Done)
ss << "[Dead] ";
ss << pos << " - " << (*up)->Username << " $" << (*up)->Money << "\r\n";
++pos;
}
Send(ss.str());
}
void Session::DoAbout( const std::string& message )
{
std::string remainder;
std::string username = ExtractCommand(message, remainder);
if(0 == username.length())
{
Send("Syntax: about <user>\r\n");
return;
}
User* user = Users::Instance()->GetUserByUsername(username);
if(0 == user)
{
SendStream("No such user '" << username << "'\r\n");
return;
}
SendStream("--[" << GREENCOLOR << "About " << username << CLEARCOLOR << "]------\r\n");
SendStream(user->About << "\r\n");
SendStream("Money: $" << user->Money << "\r\n");
SendStream("Respect: R" << user->Respect << "\r\n");
if(user->Done)
Send("The user is out of time\r\n");
}
void Session::DoTell( const std::string& message )
{
std::string remainder;
std::string username = ExtractCommand(message, remainder);
if(0 == username.length() || 0 == remainder.length())
{
Send("Syntax: tell <user> <message>\r\n");
return;
}
Session* session = World::Instance()->GetSession(username);
if(0 == session)
{
SendStream("No user named '" << username << "' is online\r\n");
return;
}
std::stringstream ss;
ss << _user->Username << " whispers: " << remainder.substr(0,256) << "\r\n";
session->Send(ss.str());
Log(_user->Username << " whispers to " << session->GetUser()->Username << ": " << remainder.substr(0,256));
}
void Session::DoSay( const std::string& message )
{
if(message.length() > 0)
{
std::stringstream ss;
ss << "<" << _user->Username << "> " << message.substr(0,256) << "\r\n";
World::Instance()->Broadcast(ss.str());
Log(_user->Username << " says: " << message.substr(0,256));
}
else
{
Send("Syntax: say <message>\r\n");
}
}
void Session::DoSetAbout( const std::string& message )
{
_user->About = message.substr(0,80);
SendStream("About set to:\r\n" << _user->About << "\r\n");
}
void Session::DoQuit()
{
SendImmediate("Bye\r\n");
_shouldQuit = true;
}
void Session::DoSave()
{
Users::Instance()->Save();
Contracts::Instance()->Save();
SendStream(REDCOLOR << "Saved\r\n" << CLEARCOLOR);
}
void Session::DoOffer( const std::string& message )
{
if(_user->Done)
{
Send("Sorry, your done and can no longer do that.\r\n");
return;
}
std::string remainder;
std::string myAmountStr = ExtractCommand(message, remainder);
std::string target = ExtractCommand(remainder, remainder);
std::string theirAmountStr = ExtractCommand(remainder, remainder);
std::string timeStr = ExtractCommand(remainder, remainder);
if(0 == myAmountStr.length() || 0 == target.length() || 0 == theirAmountStr.length() || 0 == timeStr.length())
{
Send("Syntax: offer <my amount> <target user> <their amount> <minutes>\r\n");
return;
}
int myAmount = atoi(myAmountStr.c_str());
int theirAmount = atoi(theirAmountStr.c_str());
int time = atoi(timeStr.c_str());
if(0 >= myAmount || 0 >= theirAmount || 0 >= time)
{
Send("Syntax: offer <my amount> <target user> <their amount> <minutes>\r\n");
return;
}
time = std::min(Settings::maxDuration, time);
Contracts::Instance()->CreateContract(this, myAmount, target, theirAmount, time, false);
}
void Session::DoEvilOffer( const std::string& message )
{
if(_user->Done)
{
Send("Sorry, your done and can no longer do that.\r\n");
return;
}
std::string remainder;
std::string myAmountStr = ExtractCommand(message, remainder);
std::string target = ExtractCommand(remainder, remainder);
std::string theirAmountStr = ExtractCommand(remainder, remainder);
std::string timeStr = ExtractCommand(remainder, remainder);
if(0 == myAmountStr.length() || 0 == target.length() || 0 == theirAmountStr.length() || 0 == timeStr.length())
{
Send("Syntax: eviloffer <my amount> <target user> <their amount> <minutes>\r\n");
return;
}
int myAmount = atoi(myAmountStr.c_str());
int theirAmount = atoi(theirAmountStr.c_str());
int time = atoi(timeStr.c_str());
if(0 >= myAmount || 0 >= theirAmount || 0 >= time)
{
Send("Syntax: eviloffer <my amount> <target user> <their amount> <minutes>\r\n");
return;
}
time = std::min(Settings::maxDuration, time);
Contracts::Instance()->CreateContract(this, myAmount, target, theirAmount, time, true);
}
void Session::DoOffers()
{
std::vector<Contract*> offers;
Contracts::Instance()->GetOffers(_user, offers);
std::stringstream ss;
ss << "--[" << GREENCOLOR << "Offers" << CLEARCOLOR << "]------\r\n";
if(0 == offers.size())
{
ss << "No pending offers.\r\n";
}
for(std::vector<Contract*>::iterator offer = offers.begin(); offer != offers.end(); ++offer)
{
Contract* ptr = *offer;
ss << ptr->User1 << " (" << ptr->User1Contribution << ") <-> (" << ptr->User2Contribution << ") " << ptr->User2 << " -- " << ptr->Duration << " minute(s)\r\n";
}
Send(ss.str());
}
void Session::DoContracts()
{
std::vector<Contract*> contracts;
Contracts::Instance()->GetContracts(_user, contracts);
std::stringstream ss;
ss << "--[" << GREENCOLOR << "Contracts " << contracts.size() << "/" << Settings::maxContracts << CLEARCOLOR << "]------\r\n";
if(0 == contracts.size())
{
ss << "No existing contracts.\r\n";
}
for(std::vector<Contract*>::iterator contract = contracts.begin(); contract != contracts.end(); ++contract)
{
Contract* ptr = *contract;
ss << ptr->User1 << " (" << ptr->User1Contribution << ") <-> (" << ptr->User2Contribution << ") " << ptr->User2 << " -- " << ptr->Duration << " minute(s)\r\n";
}
Send(ss.str());
}
void Session::DoResults()
{
std::vector<Contract*> contracts;
Contracts::Instance()->GetFinished(_user, contracts);
std::stringstream ss;
ss << "--[" << GREENCOLOR << "Completed " << contracts.size() << CLEARCOLOR << "]------\r\n";
if(0 == contracts.size())
{
ss << "No completed contracts.\r\n";
}
int index = 1;
for(std::vector<Contract*>::iterator contract = contracts.begin(); contract != contracts.end(); ++contract)
{
Contract* ptr = *contract;
ss << "id " << index << " ] " << ptr->User1 << " (" << ptr->User1Profit << " - " << ptr->User1Contribution << ") <-> (" << ptr->User2Profit << " - " << ptr->User2Contribution << ") " << ptr->User2 << "\r\n";
++index;
}
Send(ss.str());
}
void Session::DoRate(const std::string& message)
{
if(_user->Done)
{
Send("Sorry, your done and can no longer do that.\r\n");
return;
}
std::string remainder;
std::string idStr = ExtractCommand(message, remainder);
std::string user = ExtractCommand(remainder, remainder);
std::string ratingStr = ExtractCommand(remainder, remainder);
if(0 == idStr.length() || 0 == user.length() || 0 == ratingStr.length())
{
Send("Syntax: rate <id> <user> <rating>\r\n");
return;
}
User* otherUser = Users::Instance()->GetUserByUsername(user);
if(0 == otherUser)
{
SendStream("No such user '" << user << "' to rate.\r\n");
return;
}
if(otherUser == _user)
{
Send("Can't rate yourself, jackass.\r\n");
return;
}
int id = atoi(idStr.c_str()) - 1;
int rating = atoi(ratingStr.c_str());
if(rating < -3 || rating > 3)
{
Send("Ratings must fall in the range of -3 to 3, inclusive.\r\n");
return;
}
std::vector<Contract*> contracts;
Contracts::Instance()->GetFinished(_user, contracts);
if(id < 0 || id >= (int)contracts.size())
{
Send("Bad contract ID. Grab the ID from the 'results' command.\r\n");
return;
}
Contract* c = contracts[id];
if(otherUser->Username != c->User1 && otherUser->Username != c->User2)
{
Send("Specified username is not on the contract, try again?\r\n");
return;
}
if(((_user->Username == c->User1) && c->Rated1) || ((_user->Username == c->User2) && c->Rated2))
{
Send("I can't let you do that, you have already rated that contract interaction.\r\n");
return;
}
otherUser->Respect += rating;
if(_user->Username == c->User1)
c->Rated1 = true;
else if(_user->Username == c->User2)
c->Rated2 = true;
Log(_user->Username << " rated " << otherUser->Username << " with a " << rating << " rating");
SendStream("You rated '" << otherUser->Username << "' with a " << rating << " rating on contract id " << id+1 << ".\r\n");
}
void Session::DoAccept(const std::string& message)
{
if(_user->Done)
{
Send("Sorry, your done and can no longer do that.\r\n");
return;
}
std::string remainder;
std::string target = ExtractCommand(message, remainder);
if(0 == target.length())
{
Send("Syntax: accept <user>\r\n");
return;
}
Contracts::Instance()->AcceptOffer(this, target, false);
}
void Session::DoEvilAccept(const std::string& message)
{
if(_user->Done)
{
Send("Sorry, your done and can no longer do that.\r\n");
return;
}
std::string remainder;
std::string target = ExtractCommand(message, remainder);
if(0 == target.length())
{
Send("Syntax: evilaccept <user>\r\n");
return;
}
Contracts::Instance()->AcceptOffer(this, target, true);
}
void Session::DoReject(const std::string& message)
{
if(_user->Done)
{
Send("Sorry, your done and can no longer do that.\r\n");
return;
}
std::string remainder;
std::string target = ExtractCommand(message, remainder);
if(0 == target.length())
{
Send("Syntax: reject <user>\r\n");
return;
}
Contracts::Instance()->RejectOffer(this, target);
}
void Session::CommandMessage( const std::string& message )
{
std::string remainder;
std::string command = ExtractCommand(message, remainder);
if(command.length() == 0)
{
Send("Empty command received\r\n");
return;
}
switch(command[0])
{
case 'a':
if("about" == command)
{
DoAbout(remainder);
return;
}
else if("accept" == command)
{
DoAccept(remainder);
return;
}
break;
case 'b':
break;
case 'c':
if("contracts" == command)
{
DoContracts();
return;
}
break;
case 'd':
break;
case 'e':
if("evilaccept" == command)
{
DoEvilAccept(remainder);
return;
}
else if("eviloffer" == command)
{
DoEvilOffer(remainder);
return;
}
break;
case 'f':
break;
case 'g':
break;
case 'h':
if("help" == command)
{
DoHelp(remainder);
return;
}
break;
case 'i':
// Ignore?
break;
case 'j':
break;
case 'k':
break;
case 'l':
if("leaders" == command)
{
DoLeaders();
return;
}
break;
case 'm':
break;
case 'n':
break;
case 'o':
if("offer" == command)
{
DoOffer(remainder);
return;
}
else if("offers" == command)
{
DoOffers();
return;
}
break;
case 'p':
break;
case 'q':
if("quit" == command)
{
DoQuit();
return;
}
break;
case 'r':
if("reject" == command)
{
DoReject(remainder);
return;
}
else if("results" == command)
{
DoResults();
return;
}
else if("rate" == command)
{
DoRate(remainder);
return;
}
break;
case 's':
if("say" == command)
{
DoSay(remainder);
return;
}
else if("save" == command && _user->Admin)
{
DoSave();
return;
}
else if("setabout" == command)
{
DoSetAbout(remainder);
return;
}
// Stats
break;
case 't':
if("tell" == command)
{
DoTell(remainder);
return;
}
break;
case 'u':
break;
case 'v':
break;
case 'w':
if("who" == command)
{
DoWho();
return;
}
break;
case 'x':
break;
case 'y':
break;
case 'z':
break;
}
SendStream("Unknown command '" << command << "'\r\n");
}
// NETWORK
//
void Session::Send( const std::string& message )
{
_sendQueue.push(message);
if(1 == _sendQueue.size())
{
ChainSend();
}
}
void Session::SendImmediate(const std::string& message)
{
boost::asio::write(_socket, boost::asio::buffer(message.data(), message.length()));
}
void Session::HandleSend( const boost::system::error_code& error )
{
_sending = false;
if(!error)
{
_sendQueue.pop();
if(!_sendQueue.empty())
{
ChainSend();
}
}
else
{
_closing = true;
if(!_sending && !_recving)
{
delete this;
}
}
}
std::string StripInput(const char* input)
{
std::stringstream ss;
bool leading = true;
while(0 != *input)
{
if(*input & (0x1 << 7))
{
++input;
if(0 == *input)
break;
++input;
if(0 == *input)
break;
++input;
continue;
}
if(!(leading && ' ' == *input) && isprint(*input))
{
leading = false;
ss << *input;
}
++input;
}
return ss.str();
}
void Session::HandleRecv( const boost::system::error_code& error, size_t nRecvd )
{
_recving = false;
if(!error)
{
std::string line;
std::istream is(&_buffer);
getline(is, line);
line = StripInput(line.c_str());
if(line.length() > 1024)
{
LogWarning("Over long message received, killing session");
Stop();
return;
}
else if(line.length() > 0)
{
if(_loginStage > 0)
{
LoginMessage(line);
}
else
{
CommandMessage(line);
}
SendPrompt();
}
ChainRecv();
if(_shouldQuit)
Stop();
}
else
{
_closing = true;
if(!_sending && !_recving)
{
delete this;
}
}
}
void Session::ChainSend()
{
if(!_closing)
{
_sending = true;
boost::asio::async_write(_socket,
boost::asio::buffer(_sendQueue.front().data(), _sendQueue.front().length()),
boost::bind(&Session::HandleSend, this, boost::asio::placeholders::error));
}
}
void Session::ChainRecv()
{
if(!_closing)
{
_recving = true;
boost::asio::async_read_until(_socket,
_buffer,
"\r\n",
boost::bind(&Session::HandleRecv, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
}
}
| true |
ec7d98805e7ea360b9ba9535b7a6be3b99c7326f | C++ | aliefhooghe/View | /src/helpers/layout_builder.cpp | UTF-8 | 2,011 | 2.890625 | 3 | [
"BSD-3-Clause"
] | permissive |
#include "layout_builder.h"
namespace View
{
layout_builder::layout_builder(
float horizontal_step,
float vertical_step) noexcept
: _horizontal_step{horizontal_step},
_vertical_step{vertical_step}
{
}
std::unique_ptr<View::header> layout_builder::header(std::unique_ptr<widget>&& child, color_theme::color background, float internal_border_size, float header_size, float border_size) const
{
return std::make_unique<View::header>(std::move(child), background, header_size, border_size, internal_border_size);
}
std::shared_ptr<View::header> layout_builder::shared_header(std::unique_ptr<widget>&& child, color_theme::color background, float internal_border_size, float header_size, float border_size) const
{
return std::make_shared<View::header>(std::move(child), background, header_size, border_size, internal_border_size);
}
std::unique_ptr<map_wrapper> layout_builder::map(std::unique_ptr<widget>&& child, float width, float height) const
{
return std::make_unique<map_wrapper>(std::move(child), width, height);
}
std::shared_ptr<map_wrapper> layout_builder::shared_map(std::unique_ptr<widget>&& child, float width, float height) const
{
return std::make_shared<map_wrapper>(std::move(child), width, height);
}
std::unique_ptr<background> layout_builder::windows(std::unique_ptr<widget>&& child, float border_width, float border_heith) const
{
return std::make_unique<View::background>(
std::make_unique<border_wrapper>(
std::move(child),
border_heith, border_heith,
border_width, border_width));
}
std::unique_ptr<widget> layout_builder::empty_space(float width, float height, size_constraint width_constraint, size_constraint height_constraint) const
{
return std::make_unique<widget>(width, height, width_constraint, height_constraint);
}
} | true |
bb30bd42760fdf01d308463ee4e6b5293096777b | C++ | cristianmusic7/CPP-Piscine | /day05/ex05/CentralBureaucracy.cpp | UTF-8 | 2,956 | 2.59375 | 3 | [] | no_license | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* CentralBureaucracy.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cfranco <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/07/03 20:30:49 by cfranco #+# #+# */
/* Updated: 2018/07/03 20:30:51 by cfranco ### ########.fr */
/* */
/* ************************************************************************** */
#include "CentralBureaucracy.hpp"
CentralBureaucracy::CentralBureaucracy(void)
{
this->_office_blocks = new OfficeBlock[20];
return;
}
CentralBureaucracy::CentralBureaucracy(CentralBureaucracy const & src)
{
*this = src;
return;
}
CentralBureaucracy::~CentralBureaucracy(void)
{
delete [] this->_office_blocks;
}
CentralBureaucracy &CentralBureaucracy::operator=(CentralBureaucracy const & rhs)
{
(void)rhs;
return (*this);
}
void CentralBureaucracy::doBureaucracy(void)
{
int i = 0;
int x = 0;
Intern intern;
std::string input[] = {"Shrubbery Creation","Presidential Pardon","Robotomy Request"};
while (i < 20)
{
this->_office_blocks[i].setIntern(intern);
i++;
}
i = 0;
if (this->_targets[0] == "")
{
std::cout << "No targets on the queue" << std::endl;
return;
}
while (this->_targets[i] != "")
{
x = rand() % 20;
if (this->_office_blocks[x].getIntern() != NULL && this->_office_blocks[x].getSigner() != NULL
&& this->_office_blocks[x].getExecutor() != NULL)
{
this->_office_blocks[x].doBureaucracy(input[x % 3], this->_targets[i++]);
std::cout << std::endl;
}
}
std::cout << std::endl << "doBureaucracy completed" << std::endl;
}
void CentralBureaucracy::feedSigner(Bureaucrat &obj)
{
int i = 0;
while (i < 20)
{
if (this->_office_blocks[i].getSigner() == NULL)
{
this->_office_blocks[i].setSigner(obj);
return;
}
i++;
}
std::cout << "queue full, no more signers allowed" << std::endl;
return;
}
void CentralBureaucracy::feedExecuter(Bureaucrat &obj)
{
int i = 0;
while (i < 20)
{
if (this->_office_blocks[i].getExecutor() == NULL)
{
this->_office_blocks[i].setExecutor(obj);
return;
}
i++;
}
std::cout << "queue full, no more executers allowed" << std::endl;
return;
}
void CentralBureaucracy::queueUp(std::string target)
{
int i = 0;
while (i < 100)
{
if (this->_targets[i] == "")
{
this->_targets[i] = target;
return;
}
i++;
}
std::cout << "queue full" << std::endl;
return;
}
int CentralBureaucracy::_srand = std::time(NULL); | true |
6d71f9127f0c2f51175c2543992ea6dfebaa0b96 | C++ | jlopez2022/cpp_utils | /Switch_case.cpp | UTF-8 | 523 | 2.890625 | 3 | [] | no_license | #include <stdio.h>
//Do not pass through all cases!!: run in debug mode
//Not needed braquets {}
#pragma warning(disable:4996) //o cualquier otro
int main()
{
printf("Seguir en modo debug\n");
long i,j=0;
for (i=0;i<5;i++)
{
switch (i)
{
case 0:
printf("i==0\n");
j+=i;
break;
case 1:
printf("i==1\n");
j+=i;
break;
case 2:
printf("i==2\n");
j+=i;
break;
default:
printf("i>3\n");
j++;
break;
}
}
printf("j=%li\n FIN \n",j);
getchar();getchar();
return 1;
}
| true |
b561c4bee5d529c5a89927ffe1a7c3704b1d947b | C++ | Azanul/LeetCode-Solutions | /C++/1172. DinnerPlateStacks.cpp | UTF-8 | 2,731 | 4.09375 | 4 | [
"MIT"
] | permissive | /**
You have an infinite number of stacks arranged in a row and numbered (left to right) from 0, each of the stacks has the same maximum capacity.
Implement the DinnerPlates class:
- DinnerPlates(int capacity) Initializes the object with the maximum capacity of the stacks.
- void push(int val) Pushes the given positive integer val into the leftmost stack with size less than capacity.
- int pop() Returns the value at the top of the rightmost non-empty stack and removes it from that stack, and returns -1 if all stacks are empty.
- int popAtStack(int index) Returns the value at the top of the stack with the given index and removes it from that stack, and returns -1 if the stack with that given index is empty.
Constraints:
- 1 <= capacity <= 20000
- 1 <= val <= 20000
- 0 <= index <= 100000
- At most 200000 calls will be made to push, pop, and popAtStack
* ref: https://leetcode.com/problems/dinner-plate-stacks/
*/
/**
* Your DinnerPlates object will be instantiated and called as such:
* DinnerPlates* obj = new DinnerPlates(capacity);
* obj->push(val);
* int param_2 = obj->pop();
* int param_3 = obj->popAtStack(index);
*/
class DinnerPlates {
private:
int capacity;
vector<vector<int>> plates;
int i;
public:
DinnerPlates(int capacity):capacity{capacity} {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
i = 0;
}
void push(int val) {
if (plates.empty()){
vector<int> temp;
temp.push_back(val);
plates.push_back(temp);
}else{
//int i = 0;
while (i < plates.size() && plates[i].size() == capacity){
i++;
}
// create new item
vector<int> temp;
temp.push_back(val);
//all stacks full, create new stack
if (i == plates.size()){
plates.push_back(temp);
}else{
//use stack i
plates[i].push_back(val); //add to stack i
}
}
}
int pop() {
i = 0;
if (plates.empty() || plates.back().empty()){
return -1;
}else{
int ret = plates.back().back();
plates.back().pop_back();
if(!plates.empty() && plates.back().empty()){
plates.pop_back();
}
return ret;
}
}
int popAtStack(int index) {
i = 0;
if (plates.empty() || index >= plates.size() || plates[index].empty()){
return -1;
}else{
int ret = plates[index].back();
plates[index].pop_back();
return ret;
}
}
};
| true |
799122e66f5c0fa333372183239af1227b3be895 | C++ | kaustavsaha018/OOPS-Lab-6-KIIT- | /2.cpp | UTF-8 | 1,072 | 3.421875 | 3 | [] | no_license | #include<iostream>
using namespace std;
class Account{
static int interest_rate;
char name[30];
int account_no;
float balance;
public:
void getdata(char s[], int ac, float b){
int i;
for(i=0;i<30;i++){
name[i] = s[i];
}
account_no=ac;
balance=b;
}
float find_balance(int years){
float Amt=balance+(balance*interest_rate*years)/100;
return Amt;
}
void show(){
int i;
cout<<"Name: "<<name<<endl;
cout<<"Account Number: "<<account_no<<endl;
cout<<"Balance: "<<balance<<endl;
}
static void change_rate(int rate){
interest_rate=rate;
}
};
int Account::interest_rate=0;
int main(){
Account a1;
a1.getdata((char *)"Kaustav Saha", 1929018, 1000);
a1.show();
a1.change_rate(10);
cout<<"\nWhen interest rate is 10%"<<endl;
int curr_bal=a1.find_balance(2);
cout<<"The current balance is: "<<curr_bal<<endl;
a1.change_rate(15);
cout<<"\nWhen interest rate is 15%"<<endl;
curr_bal=a1.find_balance(2);
cout<<"The current balance is: "<<curr_bal<<endl;
return 0;
}
| true |
8f30c59592596cc102edb48053d1c0e4d526ec6e | C++ | stratigoster/UW | /cs240/a4/HEncode.cc | UTF-8 | 2,942 | 2.90625 | 3 | [] | no_license | #include <vector>
#include <map>
#include <list>
#include <string>
#include <queue>
#include <iostream>
#include <fstream>
#include <math.h>
using namespace std;
map<int,int> freq;
list<int> buffer;
struct node {
node* left;
node* right;
node* parent;
int c;
int freq;
};
int bin2dec(string binstr) {
int result = 0;
char c;
for(unsigned int i=0; i<binstr.length(); ++i) {
c = binstr.at(i);
if (c=='1') {
result += (int)pow(2,i);
}
}
return result;
}
struct nodeCmp {
bool operator() (const node* na, const node* nb) {
return (na->freq > nb->freq);
}
};
node* root;
void buildTree() {
priority_queue<node*,vector<node*>,nodeCmp> PQ;
for (int i=0; i<128; ++i) {
node* curr = new node;
curr->left = curr->right = curr->parent = NULL;
curr->c = i;
curr->freq = freq[i];
PQ.push(curr);
}
node* left;
node* right;
node* newroot;
while (PQ.size() > 1) {
left = PQ.top(); PQ.pop();
right = PQ.top(); PQ.pop();
newroot = new node;
newroot->left = left;
newroot->right = right;
newroot->parent = NULL;
newroot->c = EOF;
newroot->freq = left->freq + right->freq;
left->parent = right->parent = newroot;
PQ.push(newroot);
}
root = PQ.top();
}
node* findNode(int c) {
node* temp = root;
list<node*> Q;
Q.push_back(temp);
while (!Q.empty()) {
temp = Q.front(); Q.pop_front();
if (temp->c == c) {
return temp;
}
if (temp->right) {
Q.push_back(temp->right);
}
if (temp->left) {
Q.push_back(temp->left);
}
}
return NULL;
}
string encode(int c) {
node* curr = findNode(c);
string path = "";
while (curr != root) {
if (curr == curr->parent->left) {
path = "0" + path;
}
else {
path = "1" + path;
}
curr = curr->parent;
}
return path;
}
int charCount = 0;
int blockCount = 3;
int main() {
for (int i=0; i<128; ++i) {
// initialize frequences of all chars to 1
freq[i]=1;
}
buildTree();
int c;
string s;
while ((c=getchar()) != EOF) {
s = encode(c);
for (unsigned int i=0; i<s.length(); ++i) {
buffer.push_back(s.at(i));
}
if (buffer.size() > 7) {
string temp = "";
for (int i=0; i<8; ++i) {
temp += buffer.front();
buffer.pop_front();
}
cout << (char)bin2dec(temp);
}
freq[c]++;
charCount++;
if (charCount == pow(10,blockCount)) {
blockCount++;
buildTree();
charCount = 0;
}
}
if (!buffer.empty()) {
string temp = "";
while (!buffer.empty()) {
temp += buffer.front();
buffer.pop_front();
}
cout << (char)bin2dec(temp);
}
ofstream huff_freq("huff.freq");
for (int i=0; i<128; ++i) {
huff_freq << freq[i] << endl;
}
huff_freq.close();
ofstream huff_code("huff.code");
for (int i=0; i<128; ++i) {
huff_code << encode(i) << endl;
}
huff_code.close();
}
| true |
c263f661aafe4202a4ed81b8113f1a42d8d1a130 | C++ | kshiraki3/SHIRAKI-Project | /src/Record/Member.cpp | UTF-8 | 2,344 | 3.234375 | 3 | [] | no_license | //
// Record/Member.cpp
// SHIRAKI Project
//
// Created by 白木滉平 on 2016/10/20.
// Copyright (c) 2016 SHIRAKI System. All rights reserved.
//
#include "Record/Member.hpp"
Member::Member() {
}
Member::Member(const std::string& id) : mID(id) {
}
Member::Member(FileReader* fr) {
// 会員ID
mID.resize(mIDLength);
fr->Read(&mID[0], 1, mIDLength);
// 氏名
unsigned char nameSize;
fr->Read(&nameSize, 1, 1);
mName.resize(nameSize);
fr->Read(&mName[0], 1, nameSize);
// フリガナ
unsigned char rubySize;
fr->Read(&rubySize, 1, 1);
mRuby.resize(rubySize);
fr->Read(&mRuby[0], 1, rubySize);
// 住所
unsigned char addressSize;
fr->Read(&addressSize, 1, 1);
mAddress.resize(addressSize);
fr->Read(&mAddress[0], 1, addressSize);
// 電話番号
mPhoneNumber.resize(mPhoneNumberLength);
fr->Read(&mPhoneNumber[0], 1, mPhoneNumberLength);
// 生年月日
mBirthday = Date(fr);
}
void Member::WriteToFile(FileWriter* fw) const {
// 会員ID
fw->Write(&mID[0], 1, 12);
// 氏名
auto nameSize = static_cast<unsigned char>(mName.size());
fw->Write(&nameSize, 1, 1);
fw->Write(&mName[0], 1, nameSize);
// フリガナ
auto rubySize = static_cast<unsigned char>(mRuby.size());
fw->Write(&rubySize, 1, 1);
fw->Write(&mRuby[0], 1, rubySize);
// 住所
auto addressSize = static_cast<unsigned char>(mAddress.size());
fw->Write(&addressSize, 1, 1);
fw->Write(&mAddress[0], 1, addressSize);
// 電話番号
fw->Write(&mPhoneNumber[0], 1, mPhoneNumberLength);
// 生年月日
mBirthday.WriteToFile(fw);
}
bool Member::operator <(const Member& rhs) const {
return mID < rhs.mID;
}
bool Member::operator ==(const Member& rhs) const {
return mID == rhs.mID;
}
// チェック
bool Member::CheckIDSyntax(const std::string& id, std::string* msg) {
if(id.size() != mIDLength) {
if(msg != nullptr) { *msg = "会員IDは12桁で入力してください"; }
return false;
}
for(char c : id) {
if(c < '0' || '9' < c) {
if(msg != nullptr) { *msg = "会員IDは数字のみで入力してください"; }
return false;
}
}
return true;
}
bool Member::CheckPhoneNumber(const std::string& num) {
if(num.size() != mPhoneNumberLength) {
return false;
}
for(char c : num) {
if((c < '0' || '9' < c) && c != '-') {
return false;
}
}
return true;
}
| true |
e0b09ef4c07d307ab60b950e86e5c151467e709d | C++ | JonathanAlderson/Rubiks-Cube | /confetti.cpp | UTF-8 | 3,008 | 3.078125 | 3 | [] | no_license | #include "confetti.h"
#include <iostream>
#include <GL/glu.h>
#include <GL/glut.h>
Confetti::Confetti(int xMin, int xMax,
int yMin, int yMaxIn,
int zMin, int zMax,
float speedIn)
{
// On initiailse, give random variables between input parameters
yMax = yMaxIn;
x = randFloat(xMin, xMax);
y = randFloat(yMin, yMax);
z = randFloat(zMin, zMax);
size = randFloat(0.2, 0.9);
speed = speedIn;
chaos = speed;
xRot = rand() % 360;
zRot = rand() % 360;
// Money paraters
moneySize = 0.5;
rainingMoney = 0;
frame = rand() % 360; // Stars the sin functions in different places
// Random Colours
r = randFloat(0.0, 1.0);
g = randFloat(0.0, 1.0);
b = randFloat(0.0, 1.0);
}
void Confetti::update()
{
// Update the colours and clamp them
r += randFloat(-0.1, 0.1);
g += randFloat(-0.1, 0.1);
b += randFloat(-0.1, 0.1);
if(r < 0.0){ r = 0.0; }
if(r > 1.0){ r = 1.0; }
if(g < 0.0){ g = 0.0; }
if(g > 1.0){ g = 1.0; }
if(b < 0.0){ b = 0.0; }
if(b > 1.0){ b = 1.0; }
frame += 1; // Frame controls the position in the sin function
chaos = chaos + randFloat(0.0, speed / 5.0); // Makes the speed vary as it's going down
y = y - chaos;
zRot = 8 * frame; // Have a constant spin
xRot = (sin((float)frame / (speed*1000.0)) * 90) + 90; // makes the nice flopping back and forth
draw();
// Check if went too far down, then reset the position
if(y < -30)
{
y = 15;
chaos = speed;
}
}
float Confetti::randFloat(float a, float b)
{
// just a simple random float function.
// because I kept on having to make random
// numbers so I thought I'd make one
float c = a + (float) (rand()) /( (float) (RAND_MAX/(b-a)));
return c;
}
void Confetti::draw()
{
glPushMatrix();
glTranslatef(x, y ,z); // Move to position
glRotatef(xRot, 1.0, 0.0, 0.0); // do the x and z rotation
glRotatef(zRot, 0.0, 0.0, 1.0);
glDisable(GL_LIGHTING); // disable lighting for the textures part
glBegin(GL_POLYGON);
// Either the earth texture or the marc texture
if(rainingMoney == 0)
{
glColor3f(r, g, b);
glTexCoord2f(0.0, 1.0); // Plot out the texture and draw a simple square
glVertex3f(-size, -size, size);
glTexCoord2f(0.0, 0.0);
glVertex3f( size, -size, size);
glTexCoord2f(1.0, 0.0);
glVertex3f( size, size, size);
glTexCoord2f(1.0, 1.0);
glVertex3f(-size, size, size);
}
// Draw with money parameters
else
{
glColor3f(1.0, 1.0, 1.0);
glTexCoord2f(0.0, 1.0); // Plot out the texture and draw a simple square
glVertex3f(-moneySize, -moneySize * 2, moneySize);
glTexCoord2f(0.0, 0.0);
glVertex3f( moneySize, -moneySize * 2, moneySize);
glTexCoord2f(1.0, 0.0);
glVertex3f( moneySize, moneySize * 2, moneySize);
glTexCoord2f(1.0, 1.0);
glVertex3f(-moneySize, moneySize * 2, moneySize);
}
glEnd();
glEnable(GL_LIGHTING);
glPopMatrix();
}
| true |
23ef57f5e4d444bc696afd11016a31ed805d584d | C++ | conan-io/conan-center-index | /recipes/magnum-integration/all/test_package/test_package.cpp | UTF-8 | 1,672 | 2.765625 | 3 | [
"MIT"
] | permissive |
#include <iostream>
#include <assert.h>
#ifdef WITH_BULLET
#include "Magnum/BulletIntegration/Integration.h"
void with_bullet() {
std::cout << "With Bullet\n";
Magnum::Math::Vector3<btScalar> a{btScalar(1.0), btScalar(2.0), btScalar(3.0)};
btVector3 b{btScalar(1.0), btScalar(2.0), btScalar(3.0)};
assert(Magnum::Math::Vector3<btScalar>{b} == a);
}
#endif
#ifdef WITH_EIGEN
#include <Eigen/Geometry>
#include "Magnum/EigenIntegration/Integration.h"
void with_eigen() {
std::cout << "With Eigen\n";
Magnum::Math::Quaternion<float> q{};
Eigen::Quaternion<float> eq{q.scalar(), q.vector().x(), q.vector().y(), q.vector().z()};
}
#endif
#ifdef WITH_GLM
#include "Magnum/Magnum.h"
#include "Magnum/Math/Matrix3.h"
#include "Magnum/Math/Matrix4.h"
#include "Magnum/GlmIntegration/Integration.h"
void with_glm() {
std::cout << "With GLM\n";
Magnum::Math::BoolVector<2> a{0x6};
glm::bvec2 b{false, true};
assert(glm::bvec2(a) == b);
}
#endif
#ifdef WITH_IMGUI
#include <Magnum/Magnum.h>
#include <Magnum/Math/Color.h>
#include "Magnum/ImGuiIntegration/Integration.h"
void with_imgui() {
std::cout << "With ImGui\n";
ImVec2 imVec2{1.1f, 1.2f};
Magnum::Vector2 vec2(1.1f, 1.2f);
assert(Magnum::Vector2{imVec2} == vec2);
}
#endif
int main() {
#ifdef WITH_BULLET
with_bullet();
#endif
#ifdef WITH_EIGEN
with_eigen();
#endif
#ifdef WITH_GLM
with_glm();
#endif
#ifdef WITH_IMGUI
with_imgui();
#endif
return 0;
}
| true |
edf753d8fe69f0860d56de21295fb2c078cb1079 | C++ | Shukina/Trees | /Trees/Trees/Record.h | WINDOWS-1251 | 1,247 | 3.53125 | 4 | [] | no_license |
#ifndef _RECORD_H
#define _RECORD_H
#include <iostream>
using namespace std;
typedef double Key;
class Record
{
public:
Key key;
int value;
public:
Record()
{
key = NULL;
value = NULL;//0
}
Record(Record& m)
{
key = m.GetKey();
value = m.GetValue();
}
Record( Key _key ,int _val)
{
key = _key;
value = _val;
}
Key GetKey() const
{
return key;
}
int GetValue(void) const
{
return value;
}
void SetKey(Key _key)
{
key = _key;
}
void SetValue(int _value)
{
value = _value;
}
//string Refresh(string s)//
//{
// char c = s[0];
// char* word = new char[30];
// int i = 0, j = 0;
// while (s[i] != '\0'&& isalpha(s[i]))
// {
// word[i] = tolower(s[i]);
// i++;
// }
// word[i] = '\0';
// return word;
//}
Record operator++(int)
{
value++;
return *this;
}
Record& operator=(const Record& m)
{
if (this == &m) {
return *this;
}
key = m.GetKey();
value = m.GetValue();
return *this;
}
bool operator==(const Record &rec)
{
return key == rec.key;
}
friend ostream& operator << (ostream &os,Record &w)
{
os << w.key;
cout << " : " << w.value;
return os;
}
};
#endif | true |
f1fe763808f9487bdb279c73aa6be12f17dd7150 | C++ | radsn/cplusplus | /stlcontainers/vector/Vector.h | UTF-8 | 8,880 | 3.65625 | 4 | [] | no_license | /**
@file Vector.h
*/
#ifndef Vector_H
#define Vector_H
#include <memory>
#include<string>
namespace STLContainer{
template<typename T>
class Vector{
constexpr static size_t INITIAL_CAPACITY = 1;
constexpr static size_t GROWTH_FACTOR = 2;
public:
// Type Definitions:
using size_type = size_t; // alias
using value_type = T;
using pointer = value_type*;
using const_pointer = const value_type*;
using iterator = pointer;
using const_iterator = const_pointer;
using reference = value_type&;
using const_reference = const value_type&;
// Constructors:
// Default constructor:
Vector(): size_(0), capacity_(0){
reserve(INITIAL_CAPACITY);
}
Vector(size_type count, const T& value): size_(0), capacity_(0){
reserve(GROWTH_FACTOR * count); // sets capacity_ to twice of count
for(size_type index = 0; index < count; ++index){
data_[index] = value;
}
size_ = count; // sets vector size to count
}
explicit Vector(size_type count) : Vector(count, "") {}
Vector(std::initializer_list<T> init): size_(0), capacity_(0){
size_type count = init.size();
reserve(count);
for(auto &element: init){
push_back(element);
}
size_ = count;
}
// Copy constructor:
Vector(const Vector& other): size_(0), capacity_(0){
reserve(other.capacity()); // sets capacity_ to other.capacity
copy_elements(other.data_.get(), data_.get(), other.size());
size_ = other.size(); // copies vector size to other's size
}
// Move constructor:
Vector( Vector&& other): Vector(){ // invoke the default constructor
std::swap(data_, other.data_); // then swap their pointers
std::swap(size_, other.size_); // then swap their sizes
std::swap(capacity_, other.capacity_); // then swap their capacities
}
// Operator=:
// Copy assignment:
Vector& operator=(const Vector& other){
Vector output(other);
std::swap(data_, output.data_); // self-assignment
size_ = other.size();
capacity_ = other.capacity();
return *this;
}
// Move assignment:
Vector& operator=(Vector&& other){
std::swap(data_, other.data_); // then swap their pointers
std::swap(size_, other.size_); // then swap their sizes
std::swap(capacity_, other.capacity_); // then swap their capacities
return *this;
}
// Iterators:
// Returns an iterator to the first element of the container. If the container is empty, the returned iterator will be equal to end().
iterator begin() noexcept{
if(!empty()){
return data_.get();}
else{
return end();
}
}
const_iterator begin() const noexcept{
if(!empty()){
return data_.get();}
else{
return end();
}
}
// Returns an iterator to the element following the last element of the container.
// This element acts as a placeholder; attempting to access it results in undefined behavior.
iterator end() noexcept{
return (data_.get() + size());
}
const_iterator end() const noexcept{
return (data_.get() + size());
}
// Capacity:
// Empty:
bool empty() const noexcept { return (size()==0); }
// Size:
size_type size() const { return size_; }
// Capacity:
size_type capacity() const { return capacity_; }
//Reserve member function:
void reserve(size_type new_cap){
if(new_cap <= capacity_){ // does not proceed further if new capacity is less than vector capcity
return;
}
auto new_data = std::make_unique<value_type[]>(new_cap); // new pointer new_data
copy_elements(data_.get(), new_data.get(), size_);
data_.reset(new_data.release()); // delete previous memory
capacity_ = new_cap - 1; // capacity_ is the new capacity
}
// Modifiers:
// Clear: Erases all elements from the container. After this call, size() returns zero.
void clear() noexcept{
size_=0;
}
// InsertAt member function:
void insertAt(size_type pos, T value){
if(pos<0 && pos>size()){
return;
}
if(size_ == capacity_){
reserve(GROWTH_FACTOR * capacity_);
}
for(size_type index = size(); index > pos; --index){ // moves all element one ahead
data_[index] = data_[index-1];
}
data_[pos]= value; // sets value to pos index
}
// DeleteAt member function: accepts an index value that removes the element at the given index and shifts all elements backwards.
void deleteAt(size_type pos){
if(pos>=0 && pos<size()){
for(size_type index = pos; index< size()-1; ++index){ // copies one element ahead to element behind
data_[index] = data_[index+1];
}
size_--;
}
}
// Push back member function: Adds an element to the end of the vector if the capacity allows.
void push_back(const T& value){
if(size_ == capacity_){
reserve(GROWTH_FACTOR * capacity_); // sets to twice capacity
}
data_[size_] = value; // sets last element plus one to value
size_++;
}
void push_back(T&& value){
if(size_ == capacity_){
reserve(GROWTH_FACTOR * capacity_); // sets to twice capacity
}
data_[size_] = value; // sets last element plus one to value
size_++;
}
// Pop Back member function: removes the last element of the vector by updating the size of the vector.
void pop_back(){
if(size()!=0){
size_--; // deletes one element as long as size is not zero
}
}
// Element access:
// At member function: Returns a reference to the element at specified location pos, with bounds checking.
// If pos is not within the range of the container, an exception of type std::out_of_range is thrown.
reference at( size_type pos ) {
if(pos>=0 && pos<size()){
return data_[pos];
}
else{
throw std::out_of_range {"Vector::operator[]"};
}
}
const_reference at( size_type pos ) const{
if(pos>=0 && pos<size()){
return data_[pos];
}
else{
throw std::out_of_range {"Vector::operator[]"};
}
}
// Returns a reference to the element at specified location pos. No bounds checking is performed.
reference operator[] (size_type pos){
return data_[pos];
}
const_reference operator[] (size_type pos) const{
return data_[pos];
}
// Returns a reference to the first element in the container. Calling front on an empty container is undefined.
reference front(){
if(!empty()){
return *data_;
}
}
const_reference front() const{
if(!empty()){
return *data_;
}
}
// Returns reference to the last element in the container. Calling back on an empty container is undefined.
reference back(){
if(!empty()){
return *(data_ + size() - 1);
}
}
const_reference back() const{
if(!empty()){
return *(data_ + size() - 1);
}
}
private:
size_type size_; // size of the vector
size_type capacity_; // capacity of the vector
std::unique_ptr<value_type[]> data_;
void copy_elements(value_type* from, value_type* to, size_type count){
for(size_type index = 0; index < count; ++index){
to[index] = from[index];
}
}
};
}
#endif /* Vector_H */
| true |
eac61550499214eee227c8a46f26955f36f91fc1 | C++ | NickGeorgiev/sdp-kn-20-21-playground | /group1/Monika_Lambeva_82017/PolishNotation/main.cpp | UTF-8 | 705 | 2.59375 | 3 | [] | no_license | #include"shared/specs/specHelper.h"
#include "postFix.h"
TEST_CASE("Correction test")
{
PostFix p("{x+(y+[1+2])}");
PostFix s("{(x+y)*3]+(x+(1+2}");
PostFix p1("(x+(y+(1+2)))");
PostFix s1("((x+y)*3+(x+(1+2)");
PostFix p2("(6*(8/(1-2)))");
CHECK(p.advancedCorrect() == 1);
CHECK(s.advancedCorrect() == 0);
CHECK(p1.correctBracket() == 1);
CHECK(s1.correctBracket() == 0);
CHECK(p.correct() == 0);
CHECK(p2.correct() == 1);
}
TEST_CASE("Calculating test")
{
PostFix p("(5+(7+(1+2)))");
PostFix s("((1+2)*3/(1+2))");
PostFix f("1^2-1*4");
CHECK(p.calculating() == 15);
CHECK(s.calculating() == 3);
CHECK(f.calculating() == -3);
}
| true |
5189eaeb964dd2a802094ac3bce3c8a804bc4774 | C++ | Anubhav12345678/competitive-programming | /PLAYWITHWORDSTWOLPSWITHMAXPRODVVVVVVVVVVVVVVVVVIMPHACKERRANK.cpp | UTF-8 | 2,063 | 3.3125 | 3 | [] | no_license | int playWithWords(string s) {
/*
* Write your code here.
Shaka and his brother have created a boring game which is played like this:
They take a word composed of lowercase English letters and try to get the maximum possible score by building exactly
2 palindromic subsequences. The score obtained is the product of the length of these 2 subsequences.
Let's say and are two subsequences from the initial string. If & are the smallest and the largest positions
(from the initial word) respectively in ; and & are the smallest and the largest positions (from the initial word)
respectively in , then the following statements hold true:
,
, &
.
i.e., the positions of the subsequences should not cross over each other.
Hence the score obtained is the product of lengths of subsequences & . Such subsequences can be numerous for a larger
initial word, and hence it becomes harder to find out the maximum possible score. Can you help Shaka and his brother find this out?
Input Format
Input contains a word composed of lowercase English letters in a single line.
Constraints
each character will be a lower case english alphabet.
Output Format
Output the maximum score the boys can get from .
*/
ll i,j,k,l,n=s.size();
vector<vector<ll>> dp(n+1,vector<ll>(n+1,0));
// memset(dp,0,sizeof(dp));
for(i=0;i<n;i++)
dp[i][i]=1;
for(i=0;i<n-1;i++)
{
if(s[i]==s[i+1]) dp[i][i+1]=2;
else
dp[i][i+1]=1;
}
for(l=3;l<=n;l++){
for(i=0;i<n-l+1;i++){
j=i+l-1;
if(s[i]==s[j]) dp[i][j] = 2+dp[i+1][j-1];
else
dp[i][j] = max(dp[i+1][j],dp[i][j-1]);
}
}
ll left[n];
ll right[n];
right[n-1] = 1;
left[0]=1;
for(i=n-2;i>=0;i--)
right[i] = max(right[i+1],dp[i][n-1]);
for(i=1;i<n;i++)
left[i] = max(left[i-1],dp[0][i]);
long long int ans=0;
for(i=0;i<n-1;i++)
{
long long int x = (long long int)left[i]*(long long int)right[i+1];
ans = max(ans,x);
}
return ans;
} | true |
8c0ddcb43a2e02eaf4918c9a90c602c2ed40de5a | C++ | agenciapsd/bebe | /main.cpp | UTF-8 | 305 | 2.75 | 3 | [
"Unlicense"
] | permissive | #include <stdio.h>
int main()
{
int idade;
printf("Informe sua idade");
scanf("%d" ,&idade);
if (idade<0)
{
printf("Sua idade inesistente!");
}
else
if (idade<=3)
{
printf("Voce e um Bebe!");
}
else
{
printf("Voce nao e um Bebe!");
}
}
| true |
66b17fa6d2e470cc6fedb8f8c0b95b91e5026bce | C++ | siconos/siconos | /externals/numeric_bindings/libs/numeric/bindings/lapack/test/ublas_potrf_potrs.cc | UTF-8 | 3,756 | 2.828125 | 3 | [
"BSL-1.0",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive |
// solving A * X = B
// A symmetric/hermitian positive definite
// factor (potrf()) and solve (potrs())
#include <cstddef>
#include <iostream>
#include <complex>
#include <boost/numeric/bindings/lapack/computational/potrf.hpp>
#include <boost/numeric/bindings/lapack/computational/potrs.hpp>
#include <boost/numeric/bindings/ublas/matrix.hpp>
#include <boost/numeric/bindings/ublas/symmetric.hpp>
#include <boost/numeric/bindings/ublas/hermitian.hpp>
#include "utils.h"
namespace ublas = boost::numeric::ublas;
namespace lapack = boost::numeric::bindings::lapack;
using std::size_t;
using std::cout;
using std::endl;
typedef float real_t;
typedef std::complex<real_t> cmplx_t;
typedef ublas::matrix<real_t, ublas::column_major> m_t;
typedef ublas::matrix<cmplx_t, ublas::column_major> cm_t;
typedef ublas::symmetric_adaptor<m_t, ublas::lower> symml_t;
typedef ublas::hermitian_adaptor<cm_t, ublas::lower> herml_t;
typedef ublas::symmetric_adaptor<m_t, ublas::upper> symmu_t;
typedef ublas::hermitian_adaptor<cm_t, ublas::upper> hermu_t;
int main() {
// for more descriptive comments see ublas_posv.cc
cout << endl;
// symmetric
cout << "real symmetric\n" << endl;
size_t n = 5;
size_t nrhs = 2;
m_t al (n, n), au (n, n); // matrices (storage)
symml_t sal (al); // symmetric adaptor
symmu_t sau (au); // symmetric adaptor
m_t x (n, nrhs);
m_t bl (n, nrhs), bu (n, nrhs); // RHS matrices
init_symm (sal, 'l');
init_symm (sau, 'u');
print_m (sal, "sal");
cout << endl;
print_m (al, "al");
cout << endl;
print_m (sau, "sau");
cout << endl;
print_m (au, "au");
cout << endl;
for (int i = 0; i < x.size1(); ++i) {
x (i, 0) = 1.;
x (i, 1) = 2.;
}
bl = prod (sal, x);
bu = prod (sau, x);
print_m (bl, "bl");
cout << endl;
print_m (bu, "bu");
cout << endl;
int ierr = lapack::potrf (sal);
if (!ierr) {
lapack::potrs (sal, bl);
print_m (bl, "xl");
}
cout << endl;
ierr = lapack::potrf (sau);
if (!ierr) {
lapack::potrs (sau, bu);
print_m (bu, "xu");
}
cout << endl;
//////////////////////////////////////////////////////////
// hermitian
cout << "\n==========================================\n" << endl;
cout << "complex hermitian\n" << endl;
cm_t cal (3, 3), cau (3, 3); // matrices (storage)
herml_t hal (cal); // hermitian adaptor
hermu_t hau (cau); // hermitian adaptor
cm_t cx (3, 1);
cm_t cbl (3, 1), cbu (3, 1); // RHS
hal (0, 0) = cmplx_t (25, 0);
hal (1, 0) = cmplx_t (-5, 5);
hal (1, 1) = cmplx_t (51, 0);
hal (2, 0) = cmplx_t (10, -5);
hal (2, 1) = cmplx_t (4, 6);
hal (2, 2) = cmplx_t (71, 0);
hau (0, 0) = cmplx_t (25, 0);
hau (0, 1) = cmplx_t (-5, -5);
hau (0, 2) = cmplx_t (10, 5);
hau (1, 1) = cmplx_t (51, 0);
hau (1, 2) = cmplx_t (4, -6);
hau (2, 2) = cmplx_t (71, 0);
print_m (cal, "cal");
cout << endl;
print_m (cau, "cau");
cout << endl;
cm_t cbl2 (3, 2);
cbl2 (0, 0) = cmplx_t (60, -55);
cbl2 (1, 0) = cmplx_t (34, 58);
cbl2 (2, 0) = cmplx_t (13, -152);
cbl2 (0, 1) = cmplx_t (70, 10);
cbl2 (1, 1) = cmplx_t (-51, 110);
cbl2 (2, 1) = cmplx_t (75, 63);
cm_t cbu2 (cbl2);
print_m (cbl2, "cbl");
cout << endl;
ierr = lapack::potrf (hal);
if (ierr == 0) {
lapack::potrs (hal, cbl2);
print_m (cbl2, "cxl");
}
else
cout << "matrix is not positive definite: ierr = "
<< ierr << endl << endl;
cout << endl;
ierr = lapack::potrf (hau);
if (ierr == 0) {
ierr = lapack::potrs (hau, cbu2);
print_m (cbu2, "cxu");
}
else
cout << "matrix is not positive definite: ierr = "
<< ierr << endl << endl;
cout << endl;
}
| true |
0c4c543d6e6d2884b6e4a58ba8f53f4ccb92fc97 | C++ | oborges/CPP | /divingdeeper/dynallocarray.cpp | UTF-8 | 552 | 3.453125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int arraySize = 10;
int *myDynamicArray = new int[arraySize]; // here, the pointer lives in the stack, the array in the heap
for (int i = 0; i < arraySize; i++) {
myDynamicArray[i] = i;
cout << myDynamicArray[i] << endl;
}
delete[] myDynamicArray; //delete[] since it is an array
myDynamicArray = nullptr; //best practice
//note - avoid to use malloc and free from C. Instead, use new and delete, or new[] and delete[]
return 0;
} | true |
7640d1d9196fd689ca3ac6a5baadb710ae130036 | C++ | Roboy/bldc_testbed | /src/motor_control_encoder/encoder.cpp | UTF-8 | 959 | 2.71875 | 3 | [
"BSD-3-Clause"
] | permissive | #include "encoder.h"
#include "Arduino.h"
// countiner
long counter[2]={0};
/**
Encoder methods
*/
int A1_=0;
int B1_=0;
int A2_=0;
int B2_=0;
/*
A channel
*/
void doEncoder1A(){
int A = digitalRead(A0);
if( A!= A1_ ){
if(A1_ == B1_){
counter[ENCODER_1] += 1;
}else{
counter[ENCODER_1] -= 1;
}
A1_ = A;
}
}
/*
B channel
*/
void doEncoder1B(){
int B = digitalRead(A1);
if( B!= B1_ ){
if( A1_ != B1_ ){
counter[ENCODER_1] += 1;
}else{
counter[ENCODER_1] -= 1;
}
B1_ = B;
}
}
/*
A channel
*/
void doEncoder2A(){
int A = digitalRead(A2);
if( A!= A2_ ){
if(A2_ == B2_){
counter[ENCODER_2] += 1;
}else{
counter[ENCODER_2] -= 1;
}
A2_ = A;
}
}
/*
B channel
*/
void doEncoder2B(){
int B = digitalRead(A3);
if( B!= B2_ ){
if( A2_ != B2_ ){
counter[ENCODER_2] += 1;
}else{
counter[ENCODER_2] -= 1;
}
B2_ = B;
}
}
| true |
b9b8c39ae7f2575c7cfad75f4a1f0b2d58043da4 | C++ | rpakdel/arduino | /halleffect/halleffect.ino | UTF-8 | 335 | 2.828125 | 3 | [] | no_license | int inputPin = 12;
void setup()
{
Serial.begin(9600);
pinMode(inputPin, INPUT_PULLUP);
pinMode(13, OUTPUT);
digitalWrite(inputPin, HIGH); // pull resistor
}
int pinState = LOW;
void loop()
{
int v = digitalRead(inputPin);
if (pinState != v)
{
Serial.println(v);
pinState = v;
digitalWrite(13, !v);
}
}
| true |
14a7f5a5259e5cafa5b59f0d2813738a176e662b | C++ | Alsu-SM/CFile | /CFile/main.cpp | WINDOWS-1251 | 4,980 | 3.03125 | 3 | [] | no_license | #include <iostream>
#include<locale.h>
#include <stdlib.h>
#include <time.h>
#include <fstream>
#include<Windows.h>
#include "CFile.h"
using namespace std;
CFile* file;
CMyDataFile* myfile;
fstream f;
string fileName, header, Name;
bool isOpen;
string studentName;
string studentSurname;
string birthYear;
string status;
int seek = 0;
int main()
{
setlocale(LC_ALL, "Russian");
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
for (;;)
{
int v;
v = menu();
switch (v) {
case 1: //
cout << " , dat\n - txt\n" << endl;
cout << "\n : ";
cin >> fileName;
cout << "\n : ";
cin >> header;
Name = fileName + '.' + header;
file->Create(Name);
cout << "\n\n " << endl;
if (header == "txt")
file = new CFile(fileName, header);
if (header == "dat")
myfile = new CMyDataFile(fileName, header);
break;
case 2: //
cout << " , dat.\n - txt\n" << endl;
cout << "\n : ";
cin >> fileName;
cout << "\n : ";
cin >> header;
Name = fileName + '.' + header;
isOpen = file->Open(Name);
if (isOpen)
{
cout << "\n\n " << endl;
if (header == "txt")
file = new CFile(fileName, header);
if (header == "dat")
myfile = new CMyDataFile(fileName, header);
}
else {
cout << "\n\n , " << endl;
}
break;
case 3: //
if (header == "txt")
file->Close();
if (header == "dat")
myfile->Close();
cout <<"\n \n\n"<< endl;
break;
case 4: //
cout << " \n\n: \n1) \n2) 0 \n3) -1 \n\n : ";
cin >> seek;
if (header == "txt")
file->Seek(seek);
if (header == "dat")
myfile->Seek(seek);
cout << "\n \n" << endl;
break;
case 5: //
cout << " :\n1 - \n2 - " << endl;
int ans;
cout << "\n : ";
cin >> ans;
cout << "\n :\n" << endl;
if (header == "txt")
file->Read(ans);
if (header == "dat")
myfile->Read(ans);;
break;
case 6: //
if (header == "txt")
{
string s;
cout << "\n . - Ctrl-Z\n" << endl;
char c;
while ((c = getchar()) != EOF)
s += c;
file->Write(s);
}
if (header == "dat")
{
cout << "\n \n" << endl;
cout << " : "; cin >> studentName;
cout << " : "; cin >> studentSurname;
cout << " : "; cin >> birthYear;
cout << " : "; cin >> status;
string s = studentName + " " + studentSurname + " " + birthYear + " " + status + "\n";
myfile->Write(s);
}
break;
case 7: //
if (header == "txt")
cout << "\n : " << file->GetPosition() << endl;
if (header == "dat")
cout << "\n : " << myfile->GetPosition() << endl;
break;
case 8: //
if (header == "txt")
cout << " : " << file->GetLength() << " ." << endl;
if (header == "dat")
{
cout << " : " << myfile->GetLength() << " ." << endl;
cout << " : " <<myfile->HowManyEntries() <<" "<< endl;
}
break;
case 9:
exit(0);
break;
}
}
return 0;
} | true |
aadb176d99595064a5cc3405a02e5332a3b857f9 | C++ | ttyang/sandbox | /sandbox/rpc/boost/rpc/simple_connector.hpp | UTF-8 | 497 | 2.609375 | 3 | [] | no_license | #ifndef BOOST_RPC_SIMPLE_CONNECTOR
#define BOOST_RPC_SIMPLE_CONNECTOR
#include <boost/asio.hpp>
namespace boost {
namespace rpc {
class simple_connector
{
public:
simple_connector(const asio::ip::tcp::endpoint &endpoint_) : endpoint_recv(endpoint_) {}
void connect(boost::asio::ip::tcp::socket &socket)
{
socket.connect(endpoint_recv);
}
private:
boost::asio::ip::tcp::endpoint endpoint_recv;
};
} // namespace rpc
} // namespace boost
#endif // BOOST_RPC_SIMPLE_CONNECTOR
| true |
443bfb1c0633566772455ffb5a620716a0ea12f0 | C++ | LuYanFCP/Leetcode | /cpp/11.cpp | UTF-8 | 2,504 | 3.28125 | 3 | [] | no_license | #include <iostream>
#include <cassert>
#include <vector>
#include <algorithm>
#include <climits>
using std::cout;
using std::vector;
using std::endl;
using std::min;
using std::max;
// #define min(a, b) (a) > (b) ? (b) : (a)
// #define max(a, b) (a) > (b) ? (a) : (b)
class Solution {
private:
// int **ptr;
// int len;
int *ptr;
public:
void Clear() {
// for (int i = 0; i < len; i++) {
// delete[] ptr[i];
// }
// delete[] ptr;
if (!ptr) {
delete[] ptr;
}
}
~Solution() {
Clear();
}
int maxArea(vector<int>& height) {
/*
* 从i-j之间最大的矩形为 m(i, j)
* 它可以变成
* m(i, j) = max(m(i-1, j), m(i-1, j), min(h[i], h[j]) * (j - i))
*/
int n = height.size();
int rs = 0;
// 初始化二维数组
// len = n;
// ptr = new int*[n];
// for (int i = 0; i < n; i++) {
// ptr[i] = new int[n];
// }
ptr = new int[n]();
// // 遍历数组进行计算
// for (int i = 1; i < n; i++) {
// for (int j = n - 1; j >=0; j--) {
// // if (j != 0) {
// // ptr[i][j] = max( max(ptr[i - 1][j], ptr[i][j - 1]), min(height[i], height[j]) * (i - j));
// // } else {
// // ptr[i][j] = max(ptr[i - 1][j], (min(height[i], height[j]) * (i - j)));
// // }
// // cout << "{i: " << i << ", j:" << j << "}" << endl;
// cout << ptr[j] << endl;
// if (j != 0)
// ptr[j] = max(max (ptr[j], ptr[j - 1]), min(height[i], height[j]) * (i - j));
// else
// ptr[j] = max(ptr[j], min(height[i], height[j]) * (i - j));
// if (ptr[j] > rs)
// rs = ptr[j];
// // if (ptr[i][j] > rs) {
// // rs = ptr[i][j];
// // }
// }
// }
int p = 0,q = height.size() - 1;
int ans=INT_MIN;
while(p < q) {
ans=max(ans, min(height[p],height[q]) * (q - p));
if(height[p]<height[q]) p++;
else q--;
}
return rs;
}
};
int main() {
Solution s;
vector<int> heights{1, 8, 6, 2, 5, 4, 8, 3, 7};
cout << s.maxArea(heights) << endl;
} | true |
9bf5bddc47f9a229442af30edab88be3a8ebad01 | C++ | aman1228/LeetCode | /Algorithms/remove-9.cpp | UTF-8 | 592 | 3.90625 | 4 | [] | no_license | // 660. Remove 9
// https://leetcode.com/problems/remove-9/
/*
Start from integer 1, remove any integer that contains 9 such as 9, 19, 29...
So now, you will have a new integer sequence: 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, ...
Given a positive integer n, you need to return the n-th integer after removing. Note that 1 will be the first integer.
Example 1:
Input: 9
Output: 10
Hint: n will not exceed 9 x 10^8.
*/
class Solution {
public:
int newInteger(int n) {
int result = 0, base = 1;
while (n > 0) {
result += (n % 9) * base;
n /= 9;
base *= 10;
}
return result;
}
}; | true |
5bc9814d58dbb33319ba4bfd527343c07d182c1b | C++ | tbcmangos/ZenonEngine | /znCore/Log/Log.h | UTF-8 | 1,075 | 2.671875 | 3 | [] | no_license | #pragma once
#include <mutex>
class ZN_API CLog : public ILog
{
friend class Log;
public:
CLog();
virtual ~CLog();
// ILog
bool AddDebugOutput(std::shared_ptr<IDebugOutput> _debugOutput) override;
bool DeleteDebugOutput(std::shared_ptr<IDebugOutput> _debugOutput) override;
private:
void PushMessageToAllDebugOutputs(IDebugOutput::DebugMessageType Type, const char* Message, va_list& _vaList);
void PushMessageToDebugOutput(const std::shared_ptr<IDebugOutput>& DebugOutput, IDebugOutput::DebugMessageType Type, const std::string& Message);
private:
std::vector<std::pair<IDebugOutput::DebugMessageType, std::string>> m_Messages;
std::vector<std::shared_ptr<IDebugOutput>> m_DebugOutputs;
std::mutex m_Mutex;
};
// Helper class to fast access
class ZN_API Log
{
public:
static void Info(const char* _message, ...);
static void Print(const char* _message, ...);
static void Green(const char* _message, ...);
static void Warn(const char* _message, ...);
static void Error(const char* _message, ...);
static void Fatal(const char* _message, ...);
}; | true |
548149c38a737a1b2fc85496d78ed407c6ab936e | C++ | fedcba499/Arduino | /HC12_RECEIVER_PASS/HC12_RECEIVER_PASS.ino | UTF-8 | 3,067 | 2.84375 | 3 | [] | no_license | #include <SoftwareSerial.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <Servo.h>
SoftwareSerial mySerial(2, 3); // RX, TX
Servo myServo;
#define ONE_WIRE_BUS 4
int vibPin = 5;
int servoPosn = 0;
#define glowPlug 8
#define engHeat 9
int ledPin = 13;
unsigned long last = millis();//set timer
float temp;
float temp_1;
int tempPin = 0;
// Setup a OneWire instance to communicate with any OneWire Devices
//(not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);
//Pass our oneWire reference to Dallas Temperature
DallasTemperature sensors(&oneWire);
void setup() {
Serial.begin(9600);
mySerial.begin(9600);
pinMode(ledPin, OUTPUT);
pinMode(vibPin, INPUT);
sensors.begin();
Serial.println("Temperature Sensor");
myServo.attach(6);
pinMode(glowPlug, OUTPUT);
pinMode(engHeat, OUTPUT);
digitalWrite(glowPlug, HIGH);
digitalWrite(engHeat, HIGH);
}
void loop() {
boolean ledState = digitalRead(ledPin);//check if the LED is turned on or off. Returns 1 or 0
int val;
// call sensors.requestTemperatures() to issue a global temperature
// request to all devices on the bus
Serial.print("Requesting temperatures...");
sensors.requestTemperatures();
// Send the command to get temperature readings
Serial.println("DONE");
// read analog volt from sensor and save to variable temp
temp = sensors.getTempCByIndex(0);
temp_1 = 1000.00 + temp;
Serial.println(val);
mySerial.println(int(temp_1));
delay(20);
//send unique code to the receiver in this case 1000 + temp
if (val == 1)
{
temp_1 = temp_1 + 100;
delay(20);
Serial.println("vib = ON");
}
Serial.print("Temperature = ");
Serial.print(temp); // display temperature value
Serial.print("*C");
Serial.println();
if(mySerial.available() > 1){
int input = mySerial.parseInt();//read serial input and convert to integer (-32,768 to 32,767)
Serial.print("1234");
if(millis() - last > 250)
{
//if time now is 250 milliseconds greater than last time
if(ledState == 0 && input == 1111)
{
//if LED is off and button code is ok
digitalWrite(ledPin, HIGH);
for (servoPosn = 0; servoPosn <=180; servoPosn +=1)
{
myServo.write(servoPosn);
delay(10);
}
}
else if(ledState == 1 && input == 2222)
{
//if LED is on and button code is ok
digitalWrite(ledPin, LOW);
for (servoPosn=180; servoPosn >= 0; servoPosn -=1)
{
myServo.write(servoPosn);
delay(10);
}
}
}
mySerial.flush();//clear the serial buffer for unwanted inputs
last = millis();//reset timer
}
delay(20);//delay little for better serial communication
delay(1000); //update sensor reading after every second
val = digitalRead(vibPin);
}
| true |
cc1fe54883db98ed35d74c7b26b393a5fc3d7609 | C++ | achint740/Data-Structures | /Trees/BST-Insertion.cpp | UTF-8 | 519 | 3.84375 | 4 | [] | no_license |
/*
Node is defined as
class Node {
public:
int data;
Node *left;
Node *right;
Node(int d) {
data = d;
left = NULL;
right = NULL;
}
};
*/
Node* insert(Node* root,int data)
{
if(root==NULL)
{
root = new Node(data);
return root;
}
if((data)<=(root->data))
root->left =insert(root->left,data);
if((data)>(root->data))
root->right = insert(root->right,data);
return root;
}
| true |
900fbaebe0eecaa47434e404d52a5f32409a825e | C++ | skotti/islutils | /islutils/matchers.cc | UTF-8 | 12,983 | 2.53125 | 3 | [
"MIT"
] | permissive | #include "islutils/matchers.h"
namespace matchers {
/*
void RelationMatcher::printMatcher(raw_ostream &OS,
int indent) const {
switch (current_) {
case RelationKind::read:
OS.indent(indent) << "Read access\n";
break;
case RelationKind::write:
OS.indent(indent) << "Write access\n";
break;
case RelationKind::readOrWrite:
OS.indent(indent) << "ReadOrWrite\n";
break;
default:
OS.indent(indent) << "ND\n";
}
int n_children_ = Indexes_.size();
for(int i=0; i < n_children_; ++i) {
OS.indent(indent) << Indexes_[i] << "\n";
}
int n_dims_ = SetDim_.size();
OS.indent(indent) << "Number of dims: =" << n_dims_ << "\n";
for(size_t i=0; i<n_dims_; ++i) {
auto payload = SetDim_[i];
for(size_t j=0; j<payload.size(); ++j) {
OS.indent(indent +2) << payload[j] << "\n";
}
}
}
// returns the number of literals assigned to the matcher.
int RelationMatcher::getIndexesSize() const {
return indexes_.size();
}
// returns literal at position i
char RelationMatcher::getIndex(unsigned i) const {
return indexes_[i];
}
// is a write matcher?
bool RelationMatcher::isWrite() const {
if((type_ == RelationKind::write) ||
(type_ == RelationKind::readOrWrite))
return true;
else return false;
}
// is a read matcher?
bool RelationMatcher::isRead() const {
if((type_ == RelationKind::read) ||
(type_ == RelationKind::readOrWrite))
return true;
else return false;
}
// print the structure of the tree matcher.
void ScheduleNodeMatcher::printMatcher(raw_ostream &OS,
const ScheduleNodeMatcher &matcher,
int indent) const {
switch (matcher.current_) {
case ScheduleNodeKind::sequence:
OS.indent(indent) << "Sequence Node\n";
break;
case ScheduleNodeKind::set:
OS.indent(indent) << "Set Node\n";
break;
case ScheduleNodeKind::band:
OS.indent(indent) << "Band Node\n";
break;
case ScheduleNodeKind::context:
OS.indent(indent) << "Context Node\n";
break;
case ScheduleNodeKind::domain:
OS.indent(indent) << "Domain Node\n";
break;
case ScheduleNodeKind::extension:
OS.indent(indent) << "Extension Node\n";
break;
case ScheduleNodeKind::filter:
OS.indent(indent) << "Filter Node\n";
break;
case ScheduleNodeKind::guard:
OS.indent(indent) << "Guard Node\n";
break;
case ScheduleNodeKind::mark:
OS.indent(indent) << "Mark Node\n";
break;
case ScheduleNodeKind::leaf:
OS.indent(indent) << "Leaf Node\n";
break;
default:
OS.indent(indent) << "ND\n";
}
if (matcher.children_.empty()) {
return;
}
int n_children_ = matcher.children_.size();
for (int i = 0; i < n_children_; ++i) {
printMatcher(OS, matcher.children_[i], indent + 2);
}
OS << "\n";
}
*/
bool ScheduleNodeMatcher::isMatching(const ScheduleNodeMatcher &matcher,
isl::schedule_node node) {
if (!node.get()) {
return false;
}
if (matcher.current_ == ScheduleNodeType::Any) {
matcher.capture_ = node;
return true;
}
if (toIslType(matcher.current_) != isl_schedule_node_get_type(node.get())) {
return false;
}
if (matcher.nodeCallback_ && !matcher.nodeCallback_(node)) {
return false;
}
size_t nChildren =
static_cast<size_t>(isl_schedule_node_n_children(node.get()));
if (matcher.children_.size() != nChildren) {
return false;
}
for (size_t i = 0; i < nChildren; ++i) {
if (!isMatching(matcher.children_.at(i), node.child(i))) {
return false;
}
}
matcher.capture_ = node;
return true;
}
static bool hasPreviousSiblingImpl(isl::schedule_node node,
const ScheduleNodeMatcher &siblingMatcher) {
while (isl_schedule_node_has_previous_sibling(node.get()) == isl_bool_true) {
node = isl::manage(isl_schedule_node_previous_sibling(node.release()));
if (ScheduleNodeMatcher::isMatching(siblingMatcher, node)) {
return true;
}
}
return false;
}
static bool hasNextSiblingImpl(isl::schedule_node node,
const ScheduleNodeMatcher &siblingMatcher) {
while (isl_schedule_node_has_next_sibling(node.get()) == isl_bool_true) {
node = isl::manage(isl_schedule_node_next_sibling(node.release()));
if (ScheduleNodeMatcher::isMatching(siblingMatcher, node)) {
return true;
}
}
return false;
}
std::function<bool(isl::schedule_node)>
hasPreviousSibling(const ScheduleNodeMatcher &siblingMatcher) {
return std::bind(hasPreviousSiblingImpl, std::placeholders::_1,
siblingMatcher);
}
std::function<bool(isl::schedule_node)>
hasNextSibling(const ScheduleNodeMatcher &siblingMatcher) {
return std::bind(hasNextSiblingImpl, std::placeholders::_1, siblingMatcher);
}
std::function<bool(isl::schedule_node)>
hasSibling(const ScheduleNodeMatcher &siblingMatcher) {
return [siblingMatcher](isl::schedule_node node) {
return hasPreviousSiblingImpl(node, siblingMatcher) ||
hasNextSiblingImpl(node, siblingMatcher);
};
}
std::function<bool(isl::schedule_node)>
hasDescendant(const ScheduleNodeMatcher &descendantMatcher) {
isl::schedule_node n;
return [descendantMatcher](isl::schedule_node node) {
// Cannot use capturing lambdas as C function pointers.
struct Data {
bool found;
const ScheduleNodeMatcher &descendantMatcher;
};
Data data{false, descendantMatcher};
auto r = isl_schedule_node_foreach_descendant_top_down(
node.get(),
[](__isl_keep isl_schedule_node *cn, void *user) -> isl_bool {
auto data = static_cast<Data *>(user);
if (data->found) {
return isl_bool_false;
}
auto n = isl::manage_copy(cn);
data->found =
ScheduleNodeMatcher::isMatching(data->descendantMatcher, n);
return data->found ? isl_bool_false : isl_bool_true;
},
&data);
return r == isl_stat_ok && data.found;
};
}
} // namespace matchers
/*
namespace constraint {
struct MatcherConstraints;
// build a set of constraints for a given matcher and the given
// memory accesses. It returns a struct containing the dimensions involved
// (size of Indexes_ in the matcher) and the list of constraints introduced
// by the matcher.
MatcherConstraints buildMatcherConstraints(const matchers::RelationMatcher &m,
llvm::SmallVector<polly::MemoryAccess*, 32> &a) {
MatcherConstraints matcherConstraints;
for(auto *MemA = a.begin(); MemA != a.end(); MemA++) {
polly::MemoryAccess *MemAccessPtr = *MemA;
if(m.isMatching(*MemAccessPtr)) {
auto AccMap = MemAccessPtr->getLatestAccessRelation();
isl::pw_multi_aff MultiAff = isl::pw_multi_aff::from_map(AccMap);
for(unsigned u = 0; u < AccMap.dim(isl::dim::out); ++u) {
isl::pw_aff PwAff = MultiAff.get_pw_aff(u);
auto a = std::make_tuple(m.getIndex(u), PwAff);
matcherConstraints.constraints.push_back(a);
}
}
}
matcherConstraints.dimsInvolved = m.getIndexesSize();
return matcherConstraints;
}
// check if two singleConstraint are equal.
bool isEqual(singleConstraint &a, singleConstraint &b) {
if((std::get<0>(a) == std::get<0>(b)) &&
(std::get<1>(a).to_str().compare(std::get<1>(b).to_str()) == 0))
return true;
else return false;
}
// remove duplicate singleConstraint
// from a list of singleConstraints
void removeDuplicate(MultipleConstraints &c) {
for(int i=0; i<c.size(); ++i) {
for(int j=i+1; j<c.size(); ++j) {
if(isEqual(c[i],c[j])) {
//LLVM_DEBUG(dbgs() << "removing\n");
//LLVM_DEBUG(dbgs() << c[j] << "\n");
//LLVM_DEBUG(dbgs() << c[i] << "\n");
//LLVM_DEBUG(dbgs() << "j=" << j << "\n");
//LLVM_DEBUG(dbgs() << "i=" << i << "\n");
c.erase(c.begin()+j);
}
}
}
}
// new constrain list generated by comparing two
// different matchers. We combine the constraints of
// two matchers and we output a new list of constraints.
// i starting index for valid constraint matcher one
// j starting index for valid constraint matcher two
// TODO: notice that for now we are assuming a single
// matching.
MatcherConstraints createNewConstrainList(int i, int j,
MatcherConstraints &mOne, MatcherConstraints &mTwo) {
MatcherConstraints result;
int dimsInvolvedOne = mOne.dimsInvolved;
int dimsInvolvedTwo = mTwo.dimsInvolved;
MultipleConstraints newConstraints;
for(int ii=i; ii<dimsInvolvedOne+i; ++ii) {
auto a = std::make_tuple(std::get<0>(mOne.constraints[ii]),
std::get<1>(mOne.constraints[ii]));
//LLVM_DEBUG(dbgs() << a << "\n");
newConstraints.push_back(a);
}
//LLVM_DEBUG(dbgs() << "#####\n");
for(int jj=j; jj<dimsInvolvedTwo+j; ++jj) {
auto a = std::make_tuple(std::get<0>(mTwo.constraints[jj]),
std::get<1>(mTwo.constraints[jj]));
//LLVM_DEBUG(dbgs() << a << "\n");
newConstraints.push_back(a);
}
//LLVM_DEBUG(dbgs() << newConstraints.size() << "\n");
removeDuplicate(newConstraints);
result.constraints = newConstraints;
result.dimsInvolved = newConstraints.size();
//LLVM_DEBUG(dbgs() << newConstraints.size() << "\n");
//LLVM_DEBUG(dbgs() << "result : =" << result << "\n");
return result;
}
// TODO: for now we assume a single match.
// brute force: we compare all the possibilities and we try
// to find out one that satisfies the constraints for the two input lists.
// the if checks the following conditions:
// 1. (B, i1) and (c, i1) [this should be rejected since i1 is assigned both to B and C]
// 2. (A, i0) and (A, i2) [this should be rejected since A is assigned both to i0 and i2]
MatcherConstraints compareLists(MatcherConstraints &mOne, MatcherConstraints &mTwo) {
//int dummyDebug = 0;
//LLVM_DEBUG(dbgs() << mOne.constraints << "\n");
//LLVM_DEBUG(dbgs() << mTwo.constraints << "\n");
MatcherConstraints result;
int sizeListOne = mOne.constraints.size();
int sizeListTwo = mTwo.constraints.size();
int dimsInvolvedOne = mOne.dimsInvolved;
int dimsInvolvedTwo = mTwo.dimsInvolved;
for(int i=0; i<sizeListOne; i+=dimsInvolvedOne) {
for(int j=0; j<sizeListTwo; j+=dimsInvolvedTwo) {
bool isPossible = true;
for(int ii=i; ii<i+dimsInvolvedOne; ++ii) {
for(int jj=j; jj<j+dimsInvolvedTwo; ++jj) {
//LLVM_DEBUG(dbgs() << "mOne label : " << std::get<0>(mOne.constraints[ii]) << "\n");
//LLVM_DEBUG(dbgs() << "mTwo label : " << std::get<0>(mTwo.constraints[jj]) << "\n");
//LLVM_DEBUG(dbgs() << "mOne PW : " << std::get<1>(mOne.constraints[ii]).to_str() << "\n");
//LLVM_DEBUG(dbgs() << "mTwo PW : " << std::get<1>(mTwo.constraints[jj]).to_str() << "\n");
//LLVM_DEBUG(dbgs() << "ii" << ii << "\n");
//LLVM_DEBUG(dbgs() << "*********** " << "\n");
if((std::get<0>(mOne.constraints[ii]) != std::get<0>(mTwo.constraints[jj]) &&
(std::get<1>(mOne.constraints[ii]).to_str().compare(std::get<1>(mTwo.constraints[jj]).to_str()) == 0)) ||
(std::get<0>(mOne.constraints[ii]) == std::get<0>(mTwo.constraints[jj]) &&
(std::get<1>(mOne.constraints[ii]).to_str().compare(std::get<1>(mTwo.constraints[jj]).to_str()) != 0))) {
isPossible = false;
//LLVM_DEBUG(dbgs() << "not pass\n");
}
else {
//bool cond = std::get<0>(mOne.constraints[ii]) == std::get<0>(mTwo.constraints[jj]);
//bool cond1 = (std::get<1>(mOne.constraints[ii]).to_str().compare(std::get<1>(mTwo.constraints[jj]).to_str()) == 0);
//LLVM_DEBUG(dbgs() << "cond 1 " << cond << "\n");
//LLVM_DEBUG(dbgs() << "cond 2 " << cond1 << "\n");
//LLVM_DEBUG(dbgs() << "pass" << "\n");
}
}
}
//LLVM_DEBUG(dbgs() << "TUPLE =" << isPossible << "\n");
//LLVM_DEBUG(dbgs() << "DummyDebug =" << ++dummyDebug << "\n");
if(isPossible) {
//TODO: for now we assume a single match.
result = createNewConstrainList(i, j, mOne, mTwo);
//LLVM_DEBUG(dbgs() << "index i = " << i << "\n");
//LLVM_DEBUG(dbgs() << "index j = " << j << "\n");
//LLVM_DEBUG(dbgs() << "possible comb " << "\n");
//for(int ii=i; ii<dimsInvolvedOne+i; ++ii) {
// LLVM_DEBUG(dbgs() << std::get<0>(mOne.constraints[ii]) << "\n");
// LLVM_DEBUG(dbgs() << std::get<1>(mOne.constraints[ii]).to_str() << "\n");
//}
//for(int jj=j; jj<dimsInvolvedTwo+j; ++jj) {
// LLVM_DEBUG(dbgs() << std::get<0>(mTwo.constraints[jj]) << "\n");
// LLVM_DEBUG(dbgs() << std::get<1>(mTwo.constraints[jj]).to_str() << "\n");
//}
}
}
}
return result;
}
} // namespace constraint
*/
| true |
734b4ddb92faf29ce39741e0d248cb632775366c | C++ | mvelazco231201/ejercios-con-c- | /p5.6ElevarNum.cpp | ISO-8859-1 | 708 | 3.859375 | 4 | [] | no_license | //Hacer una funcin que calcule x^[n] sin la librera math.h
#include<iostream>
using namespace std;
float elevarNum(float entero, short pow);
main()
{
float num;
short elevar;
cout<<"Introduzca un numero: ";cin>>num;
cout<<"\nIntroduzca la potencia a la que desea elevar: ";cin>>elevar;
cout<<"\nEl resultado es ";
cout<<elevarNum(num,elevar);
}
float elevarNum(float entero, short pow)
{
short i;
float result=1;
if(entero==0)
result=1;
if(entero>0 && pow%2==0)
entero=entero*-1;
if(pow>0)
for(i=1;i<=pow;i++)
result=result*entero;
if(pow<0)
{
pow=pow*-1;
for(i=1;i<=pow;i++)
result=result/entero;
}
return result;
}
| true |
0db91afcdb1a69d164f4ecd363472c51df903909 | C++ | Goose4me/sfml_arcanoid | /Arcanoid/Platform.cpp | UTF-8 | 1,176 | 2.75 | 3 | [
"Apache-2.0"
] | permissive | #include "Platform.h"
void Platform::initializeSprite()
{
this->sprite.setOrigin(sf::Vector2f(this->width / 2, this->height / 2));
this->sprite.setPosition(this->position);
this->sprite.setSize(sf::Vector2f(this->width, this->height));
this->sprite.setFillColor(sf::Color::White);
this->sprite.setOutlineColor(sf::Color::Color(200, 200, 200));
this->sprite.setOutlineThickness(1.f);
}
void Platform::initializeVariables()
{
this->velocity = sf::Vector2f(0,0);
}
Platform::Platform(sf::Vector2f position)
{
this->position = position;
this->initializeVariables();
this->initializeSprite();
}
Platform::~Platform()
{
}
sf::RectangleShape Platform::getSprite()
{
return this->sprite;
}
void Platform::move(sf::VideoMode* vm)
{
this->sprite.move(this->velocity);
if (this->sprite.getPosition().x + this->width / 2 >= (*vm).width) {
this->sprite.setPosition(sf::Vector2f((*vm).width - this->width / 2, this->sprite.getPosition().y));
}
else if (this->sprite.getPosition().x - this->width / 2 <= 0)
{
this->sprite.setPosition(sf::Vector2f(this->width / 2, this->sprite.getPosition().y));
}
}
float Platform::getHeight()
{
return this->height;
}
| true |
658b9db7e83f263bb455a2130a83a526c6e57ab8 | C++ | zyr17/AKR | /AKR/data.cpp | GB18030 | 1,725 | 2.546875 | 3 | [] | no_license | #include "data.h"
namespace data {
void query::write(std::string filename){
FILE *f = fopen(filename.c_str(), "w");
fprintf(f, writestr().c_str());
fclose(f);
}
std::string query::writestr(){
std::string res;
auto &q = *this;
char buffer[1000] = { 0 };
sprintf(buffer, "%d\n", q.start.size());
res += buffer;
for (auto i : q.start){
sprintf(buffer, "%f %f\n", i.x, i.y);
res += buffer;
}
sprintf(buffer, "%d\n", q.endcategory.size());
res += buffer;
for (auto i : q.endcategory){
res += i == -1 ? "Unknown Keyword" : init::num2words[i];
res += "\n";
}
sprintf(buffer, "%d\n", q.needcategory.size());
res += buffer;
for (auto i : q.needcategory){
res += i == -1 ? "Unknown Keyword" : init::num2words[i];
res += "\n";
}
return res;
}
void result::write(std::string filename, query *q){
FILE *f = fopen(filename.c_str(), "w");
if (q != nullptr){
fprintf(f, "query data\n----------------\n");
fprintf(f, q->writestr().c_str());
fprintf(f, "----------------\n");
}
fprintf(f, writestr().c_str());
fclose(f);
}
//endpoint resΪintӦmappointsеĵ㡣
std::string result::writestr(){
//TODO mappointsԼݽ֤
std::string resstr;
char buffer[1000] = { 0 };
sprintf(buffer, "reslength: %.6f\n", reslength);
resstr += buffer;
sprintf(buffer, "endpoint: %d\n", endpoint);
resstr += buffer;
for (int i = 0; i < lines.size(); i++){
sprintf(buffer, "route ID %d, length: %.6f\nroute:", i, lines[i].length);
resstr += buffer;
for (auto j : lines[i].res){
sprintf(buffer, " %d", j);
resstr += buffer;
}
resstr += "\n";
}
return resstr;
}
} | true |
d43dca69ec5716db0f16c9564c45110d356c1b2d | C++ | GuangYueCHEN/3ds_intern | /projet/mesh_generator/Interfaces/Mesh.h | ISO-8859-1 | 1,920 | 3.09375 | 3 | [] | no_license | #pragma once
#include "Triangle.h"
#include <vector>
#include <array>
class Point3D;
class Mesh {
public:
/*Constructors*/
Mesh(const std::vector<Triangle> & iTriangles);
Mesh(const Mesh & mesh) = default;
Mesh() = default;
/*get values*/
Triangle get_triangle(const size_t & index) const;
size_t nb_triangles() const;
Point3D near_with(const Point3D & pt) const; //get the nearest point
/*methods*/
bool is_closed() const;
bool is_closed_2() const;
double volume() const;
int point_position(const Point3D & pt) const; //0: on mesh; 1 : in mesh; -1 : out of mesh
Mesh remeshing(const Point3D & near, const Point3D & pt) const; //remeshing mesh with replaced Point3
void augmentation(const size_t & n_triangle);
size_t add_point(const Point3D & p, bool SearchForPoint = false);
size_t add_triangle(const std::array<size_t,3> & indices, bool SearchForTriangle = false);
void remove_triangle(size_t iNumTriangle);
void remove_vertex(size_t iNumVertex);
std::vector<size_t> GetVerticesAroundVertex(size_t iNumVertex) const;
std::vector<size_t> GetTrianglesAroundVertex(size_t iNumVertex) const; //renvoie la liste des triangles qui contiennent un vertex
std::vector<size_t> GetTrianglesAroundTriangles(size_t itr) const;
std::vector<size_t> GetTrianglesAroundEdge(size_t iNumVertex1, size_t iNumVertex2) const; //renvoie la liste des triangles qui partagent une edge donne (sans ordre) par 2 vertices
void flip_edge(size_t Vertex1, size_t Vertex2);
void SplitEdge(size_t Vertex1, size_t Vertex2, const Point3D & p); //coupe une edge en insrant un point
void CollapseEdge(size_t Vertex1, size_t Vertex2);
void LaplacianSmoothing(size_t itr, double alpha);
private:
static size_t point_reduce(const std::vector <Point3D> & pts);
static double SignedVolumeOfTriangle(const Triangle & tri);
std::vector<Point3D> m_points;
std::vector<std::array<size_t,3>> m_triangles;
};
| true |
b8f78fb8c1dbd7a8c90ee4dfa47920ac8ae4dc51 | C++ | koganlee/code | /20180228/Point3.cc | UTF-8 | 1,073 | 3.296875 | 3 | [] | no_license | ///
/// @file Point3.cc
/// @author kogan(koganlee@163.com)
/// @date 2018-03-03 09:28:45
///
#include <iostream>
#include <cmath>
using std::cout;
using std::endl;
class Point;
class Line
{
public:
Line(int z = 0) : _z(z)
{
cout << "Line(int) .\n";
}
float distance(const Point & lhs, const Point &rhs);
void setPoint( Point & rhs, int x, int y);
private:
int _z;
};
class Point
{
friend class Line;
public:
Point(int x = 0, int y = 0) : _x(x), _y(y)
{
cout << "Point:" << endl;
}
void print() const
{
cout << "(" << _x << "," << _y << ")" << endl;
}
private:
int _x;
int _y;
};
float Line::distance(const Point & lhs, const Point &rhs)
{
return sqrt((lhs._x - rhs._x)*(lhs._x - rhs._x) + (lhs._y - rhs._y)* (lhs._y - rhs._y));
}
void Line::setPoint( Point & rhs, int x, int y)
{
rhs._x = x;
rhs._y = y;
}
int main()
{
Point point1(3,4);
Point point2(0,0);
Line line(3);
point1.print();
point2.print();
line.setPoint(point2, 4, 4);
point2.print();
return 0;
}
| true |
1b6817d2ae2d8f2061823e5a056b1b62e6517449 | C++ | lcy5201314/Computer-Algorithms | /P71_MNS.cpp | UTF-8 | 2,153 | 2.828125 | 3 | [] | no_license | #include <cstdio>
#include <algorithm>
using namespace std;
void MNS(int pi[],int n,int **size){
// 初始化第一行
for(int j=0;j<pi[1];j++)
size[1][j]=0;
for(int j=pi[1];j<=n;j++)
size[1][j]=1;
// 2->n-1行按状态转移方程计算
for(int i=2;i<n;i++){
for(int j=0;j<pi[i];j++)
size[i][j]=size[i-1][j];
for(int j=pi[i];j<=n;j++)
size[i][j]=max(size[i-1][j],size[i-1][pi[i]-1]+1);
}
// 最后一行只算最后一列,单拎出来
size[n][n]=max(size[n-1][n],size[n-1][pi[n]-1]+1);
}
void Traceback(int pi[],int **size,int n,int Net[],int &m){
int j=n;// 列坐标(下端接线柱)
m=0;
for(int i=n;i>1;i--){// 行坐标(上端接线柱)
if(size[i][j]!=size[i-1][j]){
Net[m++]=i;
j=pi[i]-1;
}
}
// 这里要改,这两句明显只针对第一行,应和前面的n->2行分开
// 第一行的上方格子不能用,只能特判
if(j>=pi[1])
// 如果下段接线柱pi[2]在pi[1]后面,那么上端接线柱1一定可以加入集合
Net[m++]=1;
}
bool PrintMatrix(int **m,int r,int c,int pi[]){
printf(" ");
for (int i=1;i<=c;i++)
printf("%4d",i);
printf("\n");
printf(" ");
for (int i=1;i<=c;i++)
printf("____");
printf("\n");
for (int i=1;i<=r;i++){
printf("(%2d,%2d) %2d|",i,pi[i],i);
for (int j=1;j<=c;j++)
printf("%4d",m[i][j]);
printf("\n");
}
printf("\n");
return true;
}
int main(){
const int n=10;
int pi[n+1]={0,2,4,7,8,5,6,9,3,10,1};
// int pi[n+1]={0,8,7,4,2,5,1,9,3,10,6};
int Net[n]={0};
int m=0;
int size[n+1][n+1]={0};
int* psize[n+1];
for(int i=0;i<(n+1);i++)
psize[i]=size[i];
MNS(pi,n,psize);
PrintMatrix(psize,n,n,pi);
Traceback(pi,psize,n,Net,m);
printf("{(%d,%d)",Net[m-1],pi[Net[m-1]]);
for(int i=m-2;i>=0;i--)
printf(",(%d,%d)",Net[i],pi[Net[i]]);
printf("}");
return 0;
} | true |
4a1976fb583e2b82b43b16a2ddfff47ba3a40702 | C++ | LijunChang/Near-Maximum-Independent-Set | /Graph.h | UTF-8 | 2,695 | 2.578125 | 3 | [] | no_license | #ifndef _GRAPH_H_
#define _GRAPH_H_
#include "Utility.h"
using namespace std;
struct Edge {
int id, duplicate;
int next;
};
class Graph {
private:
string dir; //input graph directory
ui n, m; //number of nodes and edges of the graph
ui *pstart; //offset of neighbors of nodes
ui *edges; //adjacent ids of edges
public:
Graph(const char *_dir) ;
~Graph() ;
void read_graph() ;
void degree_one_kernal_and_remove_max_degree() ;
void degree_two_kernal_and_remove_max_degree_with_contraction() ;
void degree_two_kernal_and_remove_max_degree_without_contraction() ;
void degree_two_kernal_dominate_lp_and_remove_max_degree_without_contraction() ;
void greedy() ;
void greedy_dynamic() ;
private:
int general_swap(char *is, char *fixed = NULL) ;
void check_is(const char *is, int count) ;
void compute_upperbound(const char *is, char *fixed = NULL) ;
void get_two_neighbors(ui u, char *is, ui &u1, ui &u2) ;
ui get_other_neighbor(ui u, char *is, ui u1) ;
int exist_edge(ui u1, ui u2) ;
void edge_rewire(ui u, ui u1, ui u2) ;
int exist_edge(ui u, ui v, const ui *pend) ;
int find_other_endpoint(ui u, ui v, char *is) ;
ui edge_rewire(ui u, const ui *pend, ui v, ui w) ;
int remove_degree_one_two(vector<ui> °ree_ones, vector<ui> °ree_twos, char *is, int *degree, vector<pair<ui,ui> > &S) ;
int initial_dominance_and_degree_two_remove(vector<ui> °ree_ones, vector<ui> °ree_twos, char *is, int *degree, char *adj, vector<pair<ui,ui> > &S) ;
int lp_reduction(ui *ids, ui ids_n, char *is, int *degree) ;
void shrink(ui u, ui &end, const char *is) ;
void shrink(ui u, ui &end, const char *is, ui *tri) ;
void update_triangle(ui u1, ui u2, ui *pend, char *is, char *adj, ui *tri, int *degree, char *dominate, vector<ui> &dominated) ;
int dominated_check(ui u, ui *pend, char *is, ui *tri, int *degree) ;
int compute_triangle_counts(ui *tri, ui *pend, char *adj, char *is, int *degree, char *dominate, vector<ui> &dominated) ;
void construct_degree_increase(ui *ids) ;
int delete_vertex(ui v, char *is, int *degree, vector<ui> °ree_ones) ;
int delete_vertex(ui v, char *is, int *degree, vector<ui> °ree_ones, vector<ui> °ree_twos) ;
int delete_vertex(ui v, const ui *pend, char *is, int *degree, vector<ui> °ree_ones, vector<ui> °ree_twos) ;
int delete_vertex(ui u, ui *pend, char *is, vector<ui> °ree_twos, ui *tri, char *adj, int *degree, char *dominate, vector<ui> &dominated) ;
int delete_vertex(ui v, char *is, int *degree, int *head, Edge *es, int *bin_head, int *bin_next, int *bin_pre, vector<ui> °ree_ones, vector<ui> °ree_twos) ;
};
#endif
| true |
e868a3959c54ac0bc0e3496039a2c50f88525b28 | C++ | 4SpecID/4SpecID | /src/4SpecIDApp/gradingoptionsdialog.cpp | UTF-8 | 2,409 | 2.546875 | 3 | [] | no_license | #include "gradingoptionsdialog.h"
#include "ui_gradingoptionsdialog.h"
#include <QMessageBox>
#include <qdebug.h>
GradingOptionsDialog::GradingOptionsDialog(ispecid::datatypes::grading_parameters params , QWidget *parent) :
QDialog(parent),
ui(new Ui::GradingOptionsDialog)
{
ui->setupUi(this);
connect(ui->save_options_button, SIGNAL(clicked()),
this, SLOT(onSaveOptionsButtonClicked()));
connect(ui->ok_button, SIGNAL(clicked()),
this, SLOT(onOkButtonClicked()));
ui->min_lab_text->setText(QString::number(params.min_sources));
ui->min_sequences_text->setText(QString::number(params.min_size));
ui->max_dist_text->setText(QString::number(params.max_distance));
}
void showErrorMessage(QString error_name, QString error){
QMessageBox::critical(nullptr, error_name, error, QMessageBox::Cancel);
}
bool GradingOptionsDialog::handleClick(){
double dist = 2;
int labs = 2;
int seqs = 3;
bool ok;
if(!ui->max_dist_text->text().isEmpty())
{
dist = ui->max_dist_text->text().toDouble(&ok);
if(!ok ||(dist > 100 || dist < 0) ){
showErrorMessage("Maximun distance error","Value should be between 0 and 100");
dist = 2;
}
}
if(!ui->min_lab_text->text().isEmpty())
{
labs= ui->min_lab_text->text().toInt(&ok);
if(!ok || labs < 1){
showErrorMessage("Minimum of laboratories deposited sequences error","Value should be a positive integer value");
labs = 2;
}if(ok && labs == 1){
QMessageBox::warning(nullptr,"Minimum of laboratories deposited sequences error","Warning: not advisable except to validate local repositories.",QMessageBox::Ok,QMessageBox::Ok);
}
}
if(!ui->min_sequences_text->text().isEmpty())
{
seqs= ui->min_sequences_text->text().toInt(&ok);
if(!ok || seqs < 3){
showErrorMessage("Sequences deposited or published independently error", "Value should be an integer value greater or equal 3");
seqs = 3;
}
}
emit saveConfig(dist,labs,seqs);
return true;
}
GradingOptionsDialog::~GradingOptionsDialog()
{
delete ui;
}
void GradingOptionsDialog::onSaveOptionsButtonClicked()
{
handleClick();
}
void GradingOptionsDialog::onOkButtonClicked()
{
auto ok = handleClick();
if(ok)
this->close();
}
| true |
9f31114e5ce50a8e66ec796e2da1e09dc18f50c6 | C++ | jtsagata/graph-algo | /code/main.cpp | UTF-8 | 396 | 2.578125 | 3 | [] | no_license | #include "DGraph.h"
#include <fstream>
#include <iostream>
int main() {
DGraph g(4);
g.nameNode(0, std::string("Start"));
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
std::ofstream os("graph1.dot");
os << g.toGraphViz();
os.close();
std::system("dot -Tpng graph1.dot -o ../grpah1.png");
g.DFS();
return 0;
} | true |
bef3039a0f014faaf66ca0a870f7724f85874fb9 | C++ | adubredu/rascapp_robot | /arduino_codes/rascapp_joy_char/rascapp_joy_char.ino | UTF-8 | 810 | 2.921875 | 3 | [] | no_license | #define UP 6
#define DOWN 7
#define LEFT 8
#define RIGHT 9
void setup()
{
setupPins();
Serial.begin(38400);
}
void loop()
{
char inst = getInst();
Serial.print(inst);
init_pins();
}
char getInst(void)
{
char inst = 'c';
if (!digitalRead(UP)) inst = 'u';
else if (!digitalRead(DOWN)) inst = 'd';
else if (!digitalRead(LEFT)) inst = 'l';
else if (!digitalRead(RIGHT)) inst = 'r';
else if (digitalRead(UP) and digitalRead(DOWN) and digitalRead(LEFT) and digitalRead(RIGHT))
inst = 'c';
return inst;
}
void setupPins(void)
{
for (int i=6; i<10; i++)
{
pinMode(i, INPUT);
digitalWrite(i, HIGH);
}
}
void init_pins(void)
{
for (int i=6; i<10; i++)
digitalWrite(i, HIGH);
}
| true |
dbfd0a57d5d851006c17c8a64d3523d65f4602d3 | C++ | aliyildirimm/Data-Structures | /Word Cursor with Stack/stack.h | UTF-8 | 1,855 | 3.703125 | 4 | [] | no_license | #ifndef STACK
#define STACK
using namespace std;
template <class T>
class Stack
{
public:
Stack( );
Stack( const Stack & rhs );
~Stack( );
void makeEmpty( );
bool isEmpty( ) const;
void pop( );
void push( const T & x );
T topAndPop( );
const T & top( ) const;
const Stack & operator=( const Stack & rhs );
private:
struct Node
{
T element;
Node *next;
Node( const T & theElement, Node * n = NULL )
: element( theElement ), next( n ) { }
};
Node *topOfStack; // list itself is the stack
};
template <class T>
Stack<T>::Stack( )
{
topOfStack = NULL;
}
template <class T>
bool Stack<T>::isEmpty( ) const
{
return topOfStack == NULL;
}
template <class T>
const T & Stack<T>::top( ) const
{
return topOfStack->element;
}
template <class T>
void Stack<T>::pop( )
{
Node *oldTop = topOfStack;
topOfStack = topOfStack->next;
delete oldTop;
}
template <class T>
void Stack<T>::push( const T & x )
{
topOfStack = new Node( x, topOfStack );
}
template <class T>
T Stack<T>::topAndPop( )
{
T topItem = top( );
pop( );
return topItem;
}
template <class T>
void Stack<T>::makeEmpty( )
{
while ( topOfStack != nullptr )
pop( );
}
template <class T>
const Stack<T> & Stack<T>::
operator=( const Stack<T> & rhs )
{
if ( this != &rhs )
{
makeEmpty( );
if ( rhs.isEmpty( ) )
return *this;
Node *rptr = rhs.topOfStack;
Node *ptr = new Node( rptr->element );
topOfStack = ptr;
for ( rptr = rptr->next; rptr != NULL; rptr = rptr->next )
ptr = ptr->next = new Node( rptr->element );
}
return *this;
}
template <class T>
Stack<T>::Stack( const Stack<T> & rhs )
{
topOfStack = NULL;
*this = rhs; // deep copy
}
template <class T>
Stack<T>::~Stack( )
{
makeEmpty( );
}
#endif
| true |
078fd3d23480ece54123dc39f53514293e9ce667 | C++ | Yuhan-Lu/OpenFlight | /pagerank.h | UTF-8 | 2,318 | 2.90625 | 3 | [] | no_license | #pragma once
#include "airlines.h"
#include "airports.h"
#include "planes.h"
#include "routes.h"
#include "cs225/graph.h"
#include "utils.h"
#include "airlineFlow.h"
#include <unordered_map>
using utils::Matrix;
/**
* Pagerank class, use the method of Markov Chain
*/
class Pagerank {
public:
/**
* Constructs pageRank
* @param g the pointer to graph
* @param loadType load label with 0, load weight with 1
*/
Pagerank(AirlineFlow& _airlineFlow, bool loadType);
/**
* Return the matrix used for PageRank
* @returns matrix used for PageRank
*/
Matrix* returnMatrix() {
return _graphMat;
}
/**
* Do pagerank and return a ranked list, ordered in decreasing popular order, the return
* vector contains pairs which first entry is the airportID, and second entry the airport
* name
* @param _airlineFlow airlineflow pointer to get airport
* @param alpha used in inital transition matrix generation
* @returns vector specified above
*/
vector<pair<int, string>> pageRank(double alpha);
/**
* Generate a report about PageRank, outputing the most populat airports in the given airlineFlow
* @param top the number of most popular airports included in the report
*/
string getPageRankReport(int top = 10);
private:
/**
* Load the matrix with edge label (number of airlines that fly in this route) as the weight
*/
void _loadLabelRank();
/**
* Load the matrix with edge weight (distance between two airports) as the weight
*/
void _loadWeightRank();
/** Graph used when generating matrix */
const Graph* _graph;
/** Graph used when generating matrix */
Airports* _airportsData;
//AirlineFlow _airlineFlow;
/** Generated matrix */
Matrix* _graphMat;
/** Mapping from vertex to its associated index in the matrix */
unordered_map<Vertex, int> _vertexToIdx;
/** PageRank result */
vector<pair<int, string>> _rankingResult;
/** Alpha used in last PageRank operation */
double _lastAlpha;
}; | true |
4e03417319706af2c6ac09ce87a1cc15c79213c9 | C++ | Mukit09/Some-Basic-Algorithm | /checkingBipartite.cpp | UTF-8 | 1,162 | 2.890625 | 3 | [] | no_license | #include<stdio.h>
#include<vector>
using namespace std;
#define SIZE 30
int vis[SIZE];
int color[SIZE];
vector<int>ve[SIZE];
int dfs(int node, int currentNodeColor) {
int i, l, u, ret;
l=ve[node].size();
color[node]=currentNodeColor;
for(i=0;i<l;i++) {
u=ve[node][i];
if(vis[u]==0) {
vis[u]=1;
ret=dfs(u, 1-currentNodeColor);
if(!ret)
return ret;
}
else if(color[u] == currentNodeColor)
return 0;
}
return 1;
}
int main() {
int testCase, node, edge, i, u, v;
scanf("%d", &testCase);
while(testCase--) {
scanf("%d%d", &node, &edge);
for(i = 1;i <=node;i++) {
vis[i]=0;
color[i]=-1;
ve[i].clear();
}
for(i = 0; i < edge; i++) {
scanf("%d%d", &u, &v);
ve[u].push_back(v);
ve[v].push_back(u);
}
int check=dfs(1, 0);
if(check) {
printf("Bipartite\n");
}
else {
printf("Not Bipartite\n");
}
}
}
/*
7 9
1 2
1 4
1 6
2 3
3 4
2 7
4 5
6 7
5 6
*/
| true |
4acbf7536b05094082fd0d50db2459ffd3522a41 | C++ | CaptainTPS/LeetCodeRep | /LeetCode/lc222.cpp | UTF-8 | 1,070 | 3.484375 | 3 | [] | no_license | #include <cstdlib>
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution222 {
public:
typedef TreeNode* ptr;
typedef long long ll;
int countNodes(TreeNode* root) {
if (root == NULL)
return 0;
ll levels = 0;
ptr curr = root;
while (curr){
curr = curr->left;
levels++;
}
if (levels == 1)
return 1;
ll result = (1 << (levels - 1)) - 1;
ll last = biSearchNull(root, levels);
return result + last;
}
private:
bool lastlevel(TreeNode* root, ll order, ll levels){
ptr curr = root;
levels -= 2;
while (levels >= 0){
if (order & (1<< levels))
curr = curr->right;
else
curr = curr->left;
levels--;
}
if (curr)
return true;
else
return false;
}
ll biSearchNull(ptr root, ll levels){
ll left = 0, right = (1 << (levels - 1)) - 1;
while (left <= right){
ll mid = (left + right) / 2;
if (lastlevel(root, mid, levels)){
left = mid + 1;
}
else
right = mid - 1;
}
return left;
}
}; | true |
50d8c404bfd623b32d52216bd774d26431dd7f17 | C++ | achillez16/CS_22A | /Assignments/PrintShape.cpp | UTF-8 | 1,077 | 4 | 4 | [] | no_license | //Write a C++ program named "PrintShape" that will read in from the user the shape integer number
// (1 for triangle and 2 for square) and the character used in the printed shape. It then prints out the given shape
// using the given character. If the user did not enter 1 or 2 for the shape number, it will print out an error message.
//For now, the shape can be a simple 3 lines.
// Created by Preetesh Barretto on 4/25/20.
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
char C;
int input;
cout << " Which shape do you want to display (1 for triangle, 2 for square) ? ";
cin >> input;
cout << "Which character do you want to be used in the shape ? ";
cin >> C;
if (input == 1) {
printf("%*c\n", 3, C);
printf("%*c%c%c\n", 2, C , C, C);
printf("%*c%c%c%c%c\n", 1, C , C, C, C, C);
}
else if (input == 2) {
printf("%*c%c%c\n",1,C,C,C);
printf("%c%*c\n",C,2,C);
printf("%*c%c%c\n",1,C,C,C);
}
else {
cout << "Unsupported shape number.";
}
return 0;
}
| true |
7b0c417a8738dd62c1948a854705fc5faa417e46 | C++ | warmsuns/c_examples | /bar.h | UTF-8 | 409 | 2.90625 | 3 | [] | no_license | #ifndef BAR_H
#define BAR_H
#include <istream>
namespace yao{
class Bar
{
public:
Bar() : Bar(0){}
Bar(const int &v) : v(v) {}
Bar(const Bar& other);
Bar& operator = (const Bar& other);
private:
int v;
friend inline std::ostream& operator<<(std::ostream& os, const Bar& obj){
return os << obj.v;
}
};
}
#endif // BAR_H
| true |
f1d60af7fdaf5be990825521efc1016846c16f8d | C++ | Robert-MacWha/Personal-Projects | /C_C++/C++/Airline Database/Person.cpp | UTF-8 | 384 | 3.078125 | 3 | [] | no_license | #include "Person.h"
Person::Person() {
fName = "__UNDEFINED__";
lName = "__UNDEFINED__";
address = "__UNDEFINED__";
phoneNum = "__UNDEFINED__";
}
Person::Person(string fN, string lN, string add, string num) {
fName = fN;
lName = lN;
address = add;
phoneNum = num;
}
void Person::printInfo() {
cout << fName << ", " << lName<< " : " << address << " : " << phoneNum;
} | true |
45ad6b929495c154176ee2ae747bad19c938480e | C++ | LArSoft/lardata | /lardata/Utilities/PxHitConverter.h | UTF-8 | 2,926 | 2.796875 | 3 | [] | no_license | ////////////////////////////////////////////////////////////////////////
// \file PxHitConverter.h
//
// \brief conversion utulities from recob::Hit to PxHit
//
// \author andrzej.szelc@yale.edu, based on LarLite code by Kazu
//
////////////////////////////////////////////////////////////////////////
#ifndef UTIL_PXHITCONVERTER_H
#define UTIL_PXHITCONVERTER_H
#include "PxUtils.h"
#include "lardata/Utilities/Dereference.h"
#include "lardataobj/RecoBase/Hit.h"
#include "canvas/Persistency/Common/Ptr.h"
#include <algorithm>
#include <type_traits>
#include <vector>
///General LArSoft Utilities
namespace util {
class GeometryUtilities;
class PxHitConverter {
public:
explicit PxHitConverter(GeometryUtilities const& geomUtils);
/// Generate: from 1 set of hits => 1 set of PxHits using indexes (association)
void GeneratePxHit(const std::vector<unsigned int>& hit_index,
const std::vector<art::Ptr<recob::Hit>> hits,
std::vector<PxHit>& pxhits) const;
/// Generate: from 1 set of hits => 1 set of PxHits using using all hits
void GeneratePxHit(std::vector<art::Ptr<recob::Hit>> const& hits,
std::vector<PxHit>& pxhits) const;
void GenerateSinglePxHit(art::Ptr<recob::Hit> const& hit, PxHit& pxhits) const;
/// Generates and returns a PxHit out of a recob::Hit
PxHit HitToPxHit(recob::Hit const& hit) const;
/// Generates and returns a PxHit out of a pointer to recob::Hit
/// or a hit itself
template <typename HitObj>
PxHit ToPxHit(HitObj const& hit) const;
/// Returns a vector of PxHit out of a vector of hits
template <typename Cont, typename Hit = typename Cont::value_type>
std::vector<PxHit> ToPxHitVector(Cont const& hits) const;
private:
GeometryUtilities const& fGeomUtils;
}; // class PxHitConverter
} //namespace util
//******************************************************************************
//*** Template implementation
//***
template <typename HitObj>
util::PxHit util::PxHitConverter::ToPxHit(HitObj const& hit) const
{
// check that the argument is an object convertible to a recob::Hit,
// or it is a pointer to such an object
static_assert(
std::is_convertible<typename lar::util::dereferenced_type<HitObj>::type, recob::Hit>::value,
"The argument to PxHitConverter::ToPxHit() does not point to a recob::Hit");
return HitToPxHit(lar::util::dereference(hit));
} // PxHitConverter::ToPxHit()
template <typename Cont, typename Hit /* = typename Cont::value_type */>
std::vector<util::PxHit> util::PxHitConverter::ToPxHitVector(Cont const& hits) const
{
std::vector<PxHit> pxhits;
pxhits.reserve(hits.size());
std::transform(hits.begin(), hits.end(), std::back_inserter(pxhits), [this](Hit const& hit) {
return this->ToPxHit(hit);
});
return pxhits;
} // util::PxHitConverter::ToPxHitVector()
#endif // UTIL_PXHITCONVERTER_H
| true |
1b0bfd265a3e229d4808c727f49b2ab6efbc5ee1 | C++ | sarimabbas/moxel | /arduino-sketch/arduino-sketch.ino | UTF-8 | 4,926 | 2.671875 | 3 | [] | no_license |
// Neopixel imports
#include <Adafruit_NeoPixel.h>
// WiFi imports
#include <SPI.h>
#include <WiFi101.h>
// MQTT imports
#include <ArduinoMqttClient.h>
// JSON parser
#include <ArduinoJson.h>
// Neopixel setup
// Which pin on the Arduino is connected to the NeoPixels?
#define PIN 10 // On Trinket or Gemma, suggest changing this to 1
// How many NeoPixels are attached to the Arduino?
#define NUMPIXELS 24 // Popular NeoPixel ring size
// When setting up the NeoPixel library, we tell it how many pixels,
// and which pin to use to send signals. Note that for older NeoPixel
// strips you might need to change the third parameter -- see the
// strandtest example for more information on possible values.
Adafruit_NeoPixel pixels(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);
// WiFi setup
int status = WL_IDLE_STATUS; // the WiFi radio's status
WiFiClient wifiClient;
//String ssid[] = { "yale wireless", "vagrantwifi", "FJORD" };
//String password[] = {"", "whatthefooklydook", "WTJ7EZ00" };
// MQTT setup
const char broker[] = "test.mosquitto.org";
int port = 1883;
const char topic[] = "ceid-workshop";
MqttClient mqttClient(wifiClient);
void setup() {
// serial port
Serial.begin(9600);
// Neopixels
Serial.println("Starting Neopixels...");
pixels.begin();
resetNeopixels();
// connect to wifi
WiFi.setPins(8,7,4,2);
while (WiFi.begin("yale wireless") != WL_CONNECTED) {
// failed, retry
Serial.print(".");
delay(5000);
}
Serial.println("You're connected to the network");
printWiFiData();
printCurrentNet();
Serial.println();
// connect to mqtt
Serial.print("Attempting to connect to the MQTT broker: ");
Serial.println(broker);
if (!mqttClient.connect(broker, port)) {
Serial.print("MQTT connection failed! Error code = ");
Serial.println(mqttClient.connectError());
while (1);
}
Serial.println("You're connected to the MQTT broker!");
Serial.println();
// connect to mqtt topic
Serial.print("Subscribing to topic: ");
Serial.println(topic);
Serial.println();
mqttClient.subscribe(topic);
// topics can be unsubscribed using:
// mqttClient.unsubscribe(topic);
Serial.print("Waiting for messages on topic: ");
Serial.println(topic);
Serial.println();
}
void loop() {
// mqtt
int messageSize = mqttClient.parseMessage();
// if message received
if (messageSize) {
StaticJsonDocument<2048> doc;
DeserializationError err = deserializeJson(doc, mqttClient);
if (err) { defaultNeopixels(); resetNeopixels(); return; }
// find RGB
JsonArray red = doc["red"];
JsonArray green = doc["green"];
JsonArray blue = doc["blue"];
lightNeopixels(red, green, blue);
for(int i = 0; i < red.size(); i++) {
Serial.print(red[i].as<int>());
}
// light neo
delay(200);
resetNeopixels();
}
delay(500);
}
void resetNeopixels() {
pixels.clear();
for (int i = 0; i < NUMPIXELS; i++) {
pixels.setPixelColor(i, pixels.Color(0, 0, 0));
pixels.show();
}
}
void defaultNeopixels() {
// turn on the pixels
for (int i = 0; i < NUMPIXELS; i++) {
pixels.setPixelColor(i, pixels.Color(150, 0, 150));
pixels.show();
delay(50); // Pause before next pass through loop
}
}
void lightNeopixels(JsonArray red, JsonArray green, JsonArray blue) {
for (int i = 0; i < red.size(); i++) {
pixels.setPixelColor(i, pixels.Color(red[i].as<int>(), green[i].as<int>(), blue[i].as<int>()));
pixels.show();
delay(50); // Pause before next pass through loop
}
}
void printWiFiData() {
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
Serial.println(ip);
// print your MAC address:
byte mac[6];
WiFi.macAddress(mac);
Serial.print("MAC address: ");
printMacAddress(mac);
// print your subnet mask:
IPAddress subnet = WiFi.subnetMask();
Serial.print("NetMask: ");
Serial.println(subnet);
// print your gateway address:
IPAddress gateway = WiFi.gatewayIP();
Serial.print("Gateway: ");
Serial.println(gateway);
}
void printCurrentNet() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print the MAC address of the router you're attached to:
byte bssid[6];
WiFi.BSSID(bssid);
Serial.print("BSSID: ");
printMacAddress(bssid);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.println(rssi);
// print the encryption type:
byte encryption = WiFi.encryptionType();
Serial.print("Encryption Type:");
Serial.println(encryption, HEX);
}
void printMacAddress(byte mac[]) {
for (int i = 5; i >= 0; i--) {
if (mac[i] < 16) {
Serial.print("0");
}
Serial.print(mac[i], HEX);
if (i > 0) {
Serial.print(":");
}
}
Serial.println();
}
| true |
b69c18372c54b68d0c3390e4bf3d902d7280d42b | C++ | jdlugosz/repertoire | /classics/pointers=const_baro.h | UTF-8 | 2,383 | 2.734375 | 3 | [] | no_license | // The Repertoire Project copyright 2006 by John M. Dlugosz : see <http://www.dlugosz.com/Repertoire/>
// File: classics\pointers=const_baro.h
// Revision: post-public build 9
STARTWRAP
namespace classics {
template <typename T> class handle; //forward declaration
template <typename T>
class const_baro : public handle_structure<T> {
typedef handle_structure<T> Base;
unsigned flags;
void release() const;
void claim (unsigned flags) const;
public:
explicit const_baro (T* p=0)
: Base(p), flags(0) { inc_unowned_reference(); }
const_baro (const Base& other)
: Base(other), flags(0) { inc_unowned_reference(); }
const_baro (const const_baro& other)
: Base(other), flags(other.flags) { claim(flags); }
~const_baro()
{ release(); }
const_baro& operator= (const const_baro<T>& other)
{ other.claim(other.flags); release(); flags=other.flags; Base::operator=(other); return *this; }
const_baro& operator= (const const_handle<T>& other)
{ other.inc_unowned_reference(); release(); flags=0; Base::operator=(other); return *this; }
const_baro& operator= (T* p);
void own (bool); //turn ownership on or off.
};
template <typename T>
void const_baro<T>::release() const
{
if (flags & 1) dec_owned_reference();
dec_unowned_reference();
}
template <typename T>
void const_baro<T>::claim (unsigned flags_) const
{
inc_unowned_reference();
if (flags_ & 1) claim_owned_reference();
}
template <typename T>
void const_baro<T>::own (bool state)
{
if (flags & 1) { //already on
if (!state) {
dec_owned_reference(); //release ownership
flags &= ~1;
}
}
else { //currently off
if (state) {
claim_owned_reference(); //claim ownership
flags |= 1;
}
}
}
template <typename T>
const_baro<T>& const_baro<T>::operator= (T* other)
{
// make a spare copy of my existing data before I overwrite it
Base old (*this);
// grab "other"
Base::operator= (other);
inc_unowned_reference();
// now get rid of the old. I have to grab first then delete the old, in
// case both old and other refer to the same complete object and
// the reference count was 1.
if (flags & 1) dec_owned_reference(old);
dec_unowned_reference(old);
flags= 0;
return *this;
}
/* /\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ */
} // end of classics
ENDWRAP
| true |
c0b233d84c48a13351cc611562fd34bf52b25c9a | C++ | bahlo-practices/bs | /semester4/practice2/main.cpp | UTF-8 | 3,392 | 3.171875 | 3 | [
"WTFPL",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #include <iostream>
#include <unistd.h>
#include <vector>
#include <sstream>
#include <iterator>
#include <algorithm>
#include <exception>
#include "colors.h"
using namespace std;
vector<string> split_str(string input, char delimiter) {
vector<string> splitted;
size_t pos = input.find(delimiter);
// Check if we have only one parameter, if yes, return it
if (pos == input.npos) {
splitted.push_back(input);
return splitted;
} else {
splitted.push_back(input.substr(0, pos));
}
// Get all other parameters
size_t start = 0;
string arg = "";
while (pos < input.size()) {
start = pos + 1;
pos = input.find(delimiter, start);
if (pos == input.npos) {
// We're at the end
pos = input.size();
}
arg = input.substr(start, pos - start);
if (arg.size() > 0) {
splitted.push_back(arg);
}
}
return splitted;
}
int main(int argc, char* argv[]) {
try {
// Print emblem and welcome message
cout << BLUE << " _______ _" << endl;
cout << "|__ __| | |" << endl;
cout << " | |_ __ __ _ ___| |__" << endl;
cout << " | | '__/ _` / __| '_ \\" << endl;
cout << " | | | | (_| \\__ \\ | | |" << endl;
cout << " |_|_| \\__,_|___/_| |_|" << RESET << endl << endl;
cout << BLUE << "Welcome to Trash! Exit with <logout>" << RESET << endl;
while (true) {
string input = "";
cout << "$ ";
// Get command
// cin >> input would stop reading at spaces
getline(cin, input);
if (input == "logout") {
break; // free
} else if (input != "") {
int status;
bool forkIt = false;
// Split string by space
vector<string> arguments = split_str(input, ' ');
// Check if the last argument is '&'
if (arguments.size() > 0 && arguments.at(arguments.size() -1) == "&") {
forkIt = true;
// Remove '&'
arguments.pop_back();
}
// Transform arguments vector<string> to char *const *
char ** crguments = new char*[arguments.size() + 1];
for(size_t i = 0; i < arguments.size(); ++i){
crguments[i] = new char[arguments[i].size() + 1];
strcpy(crguments[i], arguments[i].c_str());
}
crguments[arguments.size() + 1] = NULL; // Null-terminate array
// Fork it, make it, do it, makes us
// harder, better, faster, stronger
pid_t childPID = fork();
switch (childPID) {
case -1:
cerr << "[" << childPID << "]" << " Error creating child process" << endl;
case 0:
// We're at the child process
// Execute
// v: char pointer array as arguments
// p: also search in $PATH
execvp(crguments[0], crguments);
// Exit child pid
exit(childPID);
break;
default:
if (!forkIt) {
waitpid(childPID, &status, 0);
}
break;
}
}
}
} catch(const string &e) {
cerr << RED << e << RESET << endl;
return 1;
} catch(const std::exception &e) {
cerr << RED << e.what() << RESET << endl;
return 2;
} catch(...) {
cerr << RED << "An unknown error occured" << RESET << endl;
return 3;
}
return 0;
}
| true |
1496285ad02b379b037a7b43cb407930d99cd0e8 | C++ | octolith/grafika_hazi_2018_2019_1 | /Julia/Julia/Julia.cpp | UTF-8 | 14,822 | 2.5625 | 3 | [] | no_license | //=============================================================================================
// Julia fractals on the GPU
//=============================================================================================
#define _USE_MATH_DEFINES
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <vector>
#if defined(__APPLE__)
#include <GLUT/GLUT.h>
#include <OpenGL/gl3.h>
#include <OpenGL/glu.h>
#else
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__)
#include <windows.h>
#endif
#include <GL/glew.h> // must be downloaded
#include <GL/freeglut.h> // must be downloaded unless you have an Apple
#endif
const unsigned int windowWidth = 600, windowHeight = 600;
// OpenGL major and minor versions
int majorVersion = 3, minorVersion = 3;
//---------------------------
class Shader {
//--------------------------
void getErrorInfo(unsigned int handle) {
int logLen, written;
glGetShaderiv(handle, GL_INFO_LOG_LENGTH, &logLen);
if (logLen > 0) {
char * log = new char[logLen];
glGetShaderInfoLog(handle, logLen, &written, log);
printf("Shader log:\n%s", log);
delete log;
}
}
void checkShader(unsigned int shader, char * message) { // check if shader could be compiled
int OK;
glGetShaderiv(shader, GL_COMPILE_STATUS, &OK);
if (!OK) { printf("%s!\n", message); getErrorInfo(shader); getchar(); }
}
void checkLinking(unsigned int program) { // check if shader could be linked
int OK;
glGetProgramiv(program, GL_LINK_STATUS, &OK);
if (!OK) { printf("Failed to link shader program!\n"); getErrorInfo(program); getchar(); }
}
public:
unsigned int shaderProgram, vertexShader, geometryShader, fragmentShader;
Shader() {
// Create vertex shader from string
vertexShader = glCreateShader(GL_VERTEX_SHADER);
if (!vertexShader) {
printf("Error in vertex shader creation\n");
exit(1);
}
// Create fragment shader from string
fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
if (!fragmentShader) {
printf("Error in fragment shader creation\n");
exit(1);
}
geometryShader = glCreateShader(GL_GEOMETRY_SHADER);
if (!geometryShader) {
printf("Error in geometry shader creation\n");
exit(1);
}
shaderProgram = glCreateProgram();
if (!shaderProgram) {
printf("Error in shader program creation\n");
exit(1);
}
}
void Attach(const char * vertexSource, const char * geometrySource, const char * fragmentSource) {
if (vertexSource) {
glShaderSource(vertexShader, 1, &vertexSource, NULL);
glCompileShader(vertexShader);
checkShader(vertexShader, "Vertex shader error");
glAttachShader(shaderProgram, vertexShader);
}
// Create geometry shader from string
if (geometrySource) {
glShaderSource(geometryShader, 1, &geometrySource, NULL);
glCompileShader(geometryShader);
checkShader(geometryShader, "Geometry shader error");
glAttachShader(shaderProgram, geometryShader);
}
if (fragmentSource) {
glShaderSource(fragmentShader, 1, &fragmentSource, NULL);
glCompileShader(fragmentShader);
checkShader(fragmentShader, "Fragment shader error");
glAttachShader(shaderProgram, fragmentShader);
// Connect the fragmentColor to the frame buffer memory
glBindFragDataLocation(shaderProgram, 0, "fragmentColor"); // fragmentColor goes to the frame buffer memory
// program packaging
glLinkProgram(shaderProgram);
checkLinking(shaderProgram);
}
}
~Shader() { glDeleteProgram(shaderProgram); }
};
//---------------------------
class IterationShader : public Shader {
//---------------------------
// vertex shader in GLSL
const char * vertexSource = R"(
#version 330
precision highp float;
uniform vec2 cameraCenter;
uniform vec2 cameraSize;
layout(location = 0) in vec2 cVertex; // Attrib Array 0
out vec2 z0; // output attribute
void main() {
gl_Position = vec4(cVertex, 0, 1);
z0 = cVertex * cameraSize/2 + cameraCenter;
}
)";
// fragment shader in GLSL
const char * fragmentSource = R"(
#version 330
precision highp float;
uniform vec2 c;
uniform int function;
in vec2 z0; // variable input
out vec4 fragmentColor; // output that goes to the raster memory as told by glBindFragDataLocation
vec2 expComplex(vec2 z) {
return vec2(cos(z.y), sin(z.y)) * exp(z.x);
}
vec2 cosComplex(vec2 z) {
vec2 zi = vec2(-z.y, z.x);
return (expComplex(zi) + expComplex(-zi))/2;
}
void main() {
vec2 z = z0;
for(int i = 0; i < 1000; i++) z = $;
fragmentColor = (dot(z, z) < 100) ? vec4(0, 0, 0, 1) : vec4(1, 1, 1, 1);
}
)";
public:
IterationShader() { Attach(vertexSource, NULL, NULL); }
void EditFragment(char * instruction) {
char newFragmentSource[8000];
char *sw = &newFragmentSource[0];
const char *sr = fragmentSource;
while (*sr != '\0') {
if (*sr == '$')
while (*instruction) *sw++ = *instruction++;
else *sw++ = *sr;
sr++;
}
*sw = '\0';
Attach(NULL, NULL, newFragmentSource);
}
};
//---------------------------
class InverseIterationShader : public Shader {
//---------------------------
// vertex shader in GLSL
const char * vertexSource = R"(
#version 330
precision highp float;
layout(location = 0) in vec2 zRoot; // Attrib Array 0
void main() { gl_Position = vec4(zRoot, 0, 1); }
)";
// geometry shader in GLSL
const char * geometrySource = R"(
#version 330
precision highp float;
uniform vec2 cameraCenter;
uniform vec2 cameraSize;
uniform vec2 c;
#define nPoints 63
layout(points) in;
layout(points, max_vertices = nPoints) out;
vec2 sqrtComplex(vec2 z) {
float r = length(z);
float phi = atan(z.y, z.x);
return vec2(cos(phi / 2), sin(phi / 2)) * sqrt(r);
}
void main() {
vec2 zs[nPoints];
zs[0] = gl_in[0].gl_Position.xy;
gl_Position = vec4((zs[0] - cameraCenter) / (cameraSize/2), 0, 1);
EmitVertex();
for(int i = 0; i < nPoints/2; i++) {
vec2 z = sqrtComplex(zs[i] - c);
for(int j = 1; j <= 2; j++) {
zs[2 * i + j] = z;
gl_Position = vec4((z - cameraCenter) / (cameraSize/2), 0, 1);
EmitVertex();
z = -z;
}
}
EndPrimitive();
}
)";
// fragment shader in GLSL
const char * fragmentSource = R"(
#version 330
precision highp float;
out vec4 fragmentColor; // output that goes to the raster memory as told by glBindFragDataLocation
void main() { fragmentColor = vec4(0, 0, 0, 0); }
)";
public:
InverseIterationShader() {
Attach(vertexSource, geometrySource, fragmentSource);
}
};
// 2D point in Cartesian coordinates
struct vec2 {
float x, y;
vec2(float _x = 0, float _y = 0) { x = _x; y = _y; }
vec2 operator-(vec2& right) {
vec2 res(x - right.x, y - right.y);
return res;
}
vec2 operator+(vec2& right) {
vec2 res(x + right.x, y + right.y);
return res;
}
vec2 operator*(float s) {
vec2 res(x * s, y * s);
return res;
}
vec2 operator/(float s) {
vec2 res(x / s, y / s);
return res;
}
vec2 operator-() {
return vec2(-x, -y);
}
float Length() { return sqrtf(x * x + y * y); }
void SetUniform(unsigned shaderProg, char * name) {
int location = glGetUniformLocation(shaderProg, name);
if (location >= 0) glUniform2fv(location, 1, &x);
else printf("uniform %s cannot be set\n", name);
}
};
vec2 sqrt(vec2 z) {
float r = z.Length();
float phi = atan2(z.y, z.x);
return vec2(cosf(phi / 2), sinf(phi / 2)) * sqrtf(r);
}
// 2D camera
struct Camera {
vec2 wCenter; // center in world coordinates
vec2 wSize; // width and height in world coordinates
Camera() {
wSize = vec2(4, 4);
wCenter = vec2(0, 0);
}
void SetUniform(unsigned int shaderProg) {
wSize.SetUniform(shaderProg, "cameraSize");
wCenter.SetUniform(shaderProg, "cameraCenter");
}
};
// 2D camera
Camera camera;
// handle of the shader program
InverseIterationShader * inverseIterationShader;
IterationShader * iterationShader;
vec2 c(0, 0);
class Seed {
unsigned int vao, vbo; // vertex array object id and texture id
public:
void Create() {
glGenVertexArrays(1, &vao); // create 1 vertex array object
glBindVertexArray(vao); // make it active
glGenBuffers(1, &vbo); // Generate 1 vertex buffer objects
// vertex coordinates: vbo[0] -> Attrib Array 0 -> vertexPosition of the vertex shader
glBindBuffer(GL_ARRAY_BUFFER, vbo); // make it active, it is an array
// Map Attribute Array 0 to the current bound vertex buffer (vbo[0])
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, NULL); // stride and offset: it is tightly packed
}
void Draw() {
glUseProgram(inverseIterationShader->shaderProgram);
c.SetUniform(inverseIterationShader->shaderProgram, "c");
camera.SetUniform(inverseIterationShader->shaderProgram);
glBindVertexArray(vao); // make the vao and its vbos active playing the role of the data source
glBindBuffer(GL_ARRAY_BUFFER, vbo); // make it active, it is an array
vec2 z = vec2(0.5, 0) + sqrt(vec2(0.25 - c.x, -c.y));
z = -sqrt(z - c);
const int nSeedsPerPacket = 10000;
const int nPackets = 100;
for (int p = 0; p < nPackets; p++) {
vec2 vertices[nSeedsPerPacket];
for (int i = 0; i < nSeedsPerPacket; i++) {
z = sqrt(z - c) * (rand() & 1 ? 1 : -1);
vertices[i] = -z;
}
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_DYNAMIC_DRAW);
glDrawArrays(GL_POINTS, 0, nSeedsPerPacket);
}
}
};
class FullScreenQuad {
unsigned int vao, vbo; // vertex array object id and texture id
public:
void Create() {
glGenVertexArrays(1, &vao); // create 1 vertex array object
glBindVertexArray(vao); // make it active
glGenBuffers(1, &vbo); // Generate 1 vertex buffer objects
// vertex coordinates: vbo[0] -> Attrib Array 0 -> vertexPosition of the vertex shader
glBindBuffer(GL_ARRAY_BUFFER, vbo); // make it active, it is an array
float vertices[] = { -1, -1, 1, -1, 1, 1, -1, 1 };
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // copy to that part of the memory which will be modified
// Map Attribute Array 0 to the current bound vertex buffer (vbo[0])
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, NULL); // stride and offset: it is tightly packed
}
void Draw() {
glUseProgram(iterationShader->shaderProgram);
c.SetUniform(iterationShader->shaderProgram, "c");
camera.SetUniform(iterationShader->shaderProgram);
glBindVertexArray(vao); // make the vao and its vbos active playing the role of the data source
glDrawArrays(GL_TRIANGLE_FAN, 0, 4); // draw two triangles forming a quad
}
};
// The virtual world: collection of objects
Seed seeds;
FullScreenQuad quad;
bool inverseIteration = false;
// popup menu event handler
void processMenuEvents(int option) {
char buffer[256], *instruction;
inverseIteration = false;
switch (option) {
case 0: instruction = "vec2(z.x * z.x - z.y * z.y, 2 * z.x * z.y) + c";
iterationShader->EditFragment(instruction);
break;
case 1: instruction = "expComplex(z) + c";
iterationShader->EditFragment(instruction);
break;
case 2: instruction = "cosComplex(z + c)";
iterationShader->EditFragment(instruction);
break;
case 3: printf("\nz = ");
instruction = &buffer[0];
while ((*instruction++ = getchar()) != '\n');
*(instruction - 1) = '\0';
iterationShader->EditFragment(&buffer[0]);
break;
case 4: inverseIteration = true;
}
glutPostRedisplay();
}
// Initialization, create an OpenGL context
void onInitialization() {
// create the menu and tell glut that "processMenuEvents" will handle the events: Do not use it in your homework, because it is prohitibed by the portal
int menu = glutCreateMenu(processMenuEvents);
//add entries to our menu
glutAddMenuEntry("Filled: z^2 + c", 0);
glutAddMenuEntry("Filled: exp(z) + c", 1);
glutAddMenuEntry("Filled: cos(z + c)", 2);
glutAddMenuEntry("Filled: user defined", 3);
glutAddMenuEntry("Inverse Iteration: z^2 + c", 4);
// attach the menu to the right button
glutAttachMenu(GLUT_RIGHT_BUTTON);
glViewport(0, 0, windowWidth, windowHeight);
quad.Create();
iterationShader = new IterationShader();
processMenuEvents(0);
seeds.Create();
inverseIterationShader = new InverseIterationShader();
}
// Window has become invalid: Redraw
void onDisplay() {
glClearColor(1, 1, 1, 0); // background color
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // clear the screen
if (inverseIteration) seeds.Draw();
else quad.Draw();
glutSwapBuffers(); // exchange the two buffers
}
// Key of ASCII code pressed
void onKeyboard(unsigned char key, int pX, int pY) {
if (key == ' ') {
glutPostRedisplay();
}
}
// Key of ASCII code released
void onKeyboardUp(unsigned char key, int pX, int pY) {
}
// Move mouse with key pressed
void onMouseMotion(int pX, int pY) {
float cX = 2.0f * pX / windowWidth - 1; // flip y axis
float cY = 1.0f - 2.0f * pY / windowHeight;
c = vec2(cX, cY);
glutPostRedisplay();
}
// Mouse click event
void onMouse(int button, int state, int pX, int pY) {
if (button == GLUT_LEFT_BUTTON) {
if (state == GLUT_DOWN) {
float cX = 2.0f * pX / windowWidth - 1; // flip y axis
float cY = 1.0f - 2.0f * pY / windowHeight;
c = vec2(cX, cY);
}
}
glutPostRedisplay();
}
// Idle event indicating that some time elapsed: do animation here
void onIdle() {
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Do not touch the code below this line
int main(int argc, char * argv[]) {
glutInit(&argc, argv);
#if !defined(__APPLE__)
glutInitContextVersion(majorVersion, minorVersion);
#endif
glutInitWindowSize(windowWidth, windowHeight); // Application window is initially of resolution 600x600
glutInitWindowPosition(100, 100); // Relative location of the application window
#if defined(__APPLE__)
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH | GLUT_3_3_CORE_PROFILE); // 8 bit R,G,B,A + double buffer + depth buffer
#else
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
#endif
glutCreateWindow(argv[0]);
#if !defined(__APPLE__)
glewExperimental = true; // magic
glewInit();
#endif
printf("GL Vendor : %s\n", glGetString(GL_VENDOR));
printf("GL Renderer : %s\n", glGetString(GL_RENDERER));
printf("GL Version (string) : %s\n", glGetString(GL_VERSION));
glGetIntegerv(GL_MAJOR_VERSION, &majorVersion);
glGetIntegerv(GL_MINOR_VERSION, &minorVersion);
printf("GL Version (integer) : %d.%d\n", majorVersion, minorVersion);
printf("GLSL Version : %s\n", glGetString(GL_SHADING_LANGUAGE_VERSION));
onInitialization();
glutDisplayFunc(onDisplay); // Register event handlers
glutMouseFunc(onMouse);
glutIdleFunc(onIdle);
glutKeyboardFunc(onKeyboard);
glutKeyboardUpFunc(onKeyboardUp);
glutMotionFunc(onMouseMotion);
glutMainLoop();
return 1;
} | true |
f598699432c6c3cb4989850b0e0f0806120f0726 | C++ | wkmkymt/AOJ | /100/33.cpp | UTF-8 | 810 | 3.546875 | 4 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
using namespace std;
void push(int, char);
char pop(int);
void move(int, int);
vector< vector<char> > stacks(0, vector<char> (1000));
int main()
{
int n;
cin >> n;
stacks.resize(n);
for(string ins; cin >> ins && ins != "quit";) {
int p;
cin >> p;
if(ins == "push") {
char c;
cin >> c;
push(p - 1, c);
}
else if(ins == "pop")
cout << pop(p - 1) << endl;
else if(ins == "move") {
int q;
cin >> q;
move(p - 1, q - 1);
}
}
return 0;
}
void push(int p, char c)
{
stacks[p].push_back(c);
}
char pop(int p)
{
char lastc = stacks[p][stacks[p].size() - 1];
stacks[p].pop_back();
return lastc;
}
void move(int p, int q)
{
char lastc = pop(p);
push(q, lastc);
}
| true |
3cf7f3432f8299e708e4e942deb7216b2a61b2df | C++ | zw896/Simple-File-Archiver | /VersionRec.cpp | UTF-8 | 3,957 | 2.625 | 3 | [] | no_license | /*
* File: VersionRec.cpp
* Author: duo
*
* Created on August 26, 2015, 9:38 PM
*/
#include "VersionRec.h"
VersionRec::VersionRec() {
}
VersionRec::VersionRec(const VersionRec& orig) {
}
VersionRec::~VersionRec() {
}
void VersionRec::setModifyTime() {
time_t now = time(0);
struct tm tstruct;
char buf[80];
tstruct = *localtime(&now);
// Visit http://en.cppreference.com/w/cpp/chrono/c/strftime
// for more information about date/time format
strftime(buf, sizeof(buf), "%Y-%m-%d.%X", &tstruct);
this->modifyTime=buf;
}
void VersionRec::addBlockIds(std::string blockids) {
// Should it be an error to specify the same role more than once? No, it
// will not really matter - so don't throw exception, just don't duplicate.
std::vector<string>::iterator it;
it = find(this->blockIds.begin(), this->blockIds.end(), blockids);
if (it != this->blockIds.end()) return; // Found it, so don't duplicate
blockIds.push_back(blockids);
}
void VersionRec::addBlockHashes(string& filename) {
int temp;
int count = this->getLength()/4096;
ifstream ins(filename.c_str(), ios::binary);
for(int i =0;i<count;i++)
{ char data[4096] = {0};
ins.read(data,4096);
temp = MurmurHashNeutral2(data, 4096,1);
cout<<data<<endl;
this->blockHashes.push_back(temp);
}
count = this->getLength()%4096;
if(count!=0){
char* data = new char[count];
ins.read(data,count);
cout<<data<<endl;
cout<<"The Last one"<<endl;
temp = MurmurHashNeutral2(data, count,1);
this->blockHashes.push_back(temp);
}
ins.close();
// Should it be an error to specify the same role more than once? No, it
// will not really matter - so don't throw exception, just don't duplicate.
vector<int>::iterator it;
cout<<"Printing VersionRec hash number start!"<<endl;
for(it=blockHashes.begin();it!=blockHashes.end();it++)
cout<<*it<<endl;
cout<<"-------------------------------------------"<<endl;
}
mongo::BSONObj VersionRec::toBSON() {
mongo::BSONObjBuilder b;
if (this->_oid.empty()) {
b.genOID();
} else {
mongo::OID theoid(this->_oid);
b.append("_id", theoid);
}
b.append("versionnumber", this->versionnumber);
b.append("length", this->length);
b.append("modifytime", this->modifyTime);
b.append("ovhash", this->ovhash);
b.append("blockids", this->blockIds);
mongo::BSONObj result = b.obj();
if (this->_oid.empty()) {
mongo::BSONElement thing;
result.getObjectID(thing);
mongo::OID anoid = thing.OID();
this->_oid = anoid.toString();
}
return result;
}
void VersionRec::fromBSON(const mongo::BSONObj &data) {
mongo::BSONElement thing;
data.getObjectID(thing);
mongo::OID anoid = thing.OID();
this->_oid = anoid.toString();
int versionnumber = data.getIntField("versionnumber");
this->setVersionNumber(versionnumber);
unsigned int length = data.getIntField("length");
this->setLength(length);
std::string modifyTime(data.getStringField("modifytime"));
this->setModifyTime(modifyTime);
int ovhash = data.getIntField("ovhash");
this->setOvhash(ovhash);
mongo::BSONObjIterator blockit(data.getObjectField("blockids"));
while (blockit.more()) {
this->blockIds.push_back(blockit.next().String());
}
}
void VersionRec::createData(std::string& filename,int version) {
//Read file size.
FILE *p_file = NULL;
p_file = fopen(filename.c_str(),"rb");
fseek(p_file,0,SEEK_END);
this->length = ftell(p_file);
fclose(p_file);
//Read file size.
//Calculate the all hash
std::cout<<"*****************************************"<<endl;
// this->set_oid(filename);
this->setVersionNumber(version);
this->setModifyTime();
this->setOvhash(AllHash(filename));
this->addBlockHashes(filename);
} | true |
b29cc33599dd6a290d1e56824cd02c80925622d7 | C++ | admantium-sg/learning-cpp | /ccc/17_tracer.cpp | UTF-8 | 575 | 2.890625 | 3 | [
"BSD-3-Clause"
] | permissive | /*
* ---------------------------------------
* Copyright (c) Sebastian Günther 2021 |
* |
* devcon@admantium.com |
* |
* SPDX-License-Identifier: BSD-3-Clause |
* ---------------------------------------
*/
#include <stdio.h>
#include <iostream>
struct Tracer {
Tracer(const char* name):name{name}{
std::cout << "Hello " << name << "\n";
}
~Tracer() {
std::cout << "Goodbye " << name << "\n";
}
const char* const name;
};
int main() {
Tracer t1{"T!"};
Tracer t2{"T33"};
} | true |
a9f0b39858757968374653c8432309a15d70a28b | C++ | yy727-phd/Advanced-Programming-Techniques | /hw7/inc/matrix.h | UTF-8 | 1,657 | 3.171875 | 3 | [] | no_license | /* Copyright 2019 Jeremy S Lewis CSCE240 Templated Dynamic Array */
#ifndef _MATRIX_H_ // NOLINT
#define _MATRIX_H_ // NOLINT
#include <cassert>
// using assert
#include <ostream>
class MatrixTester;
template <class T>
class Matrix {
public:
friend class MatrixTester;
Matrix(); // for testing, useless in practice
Matrix(unsigned int rows, unsigned int cols);
/* Copy Constructor: 2 Points
* Performs deep copy.
*/
Matrix(const Matrix& that);
/* Destructor: Required For Any Points
* Cleans up memory to avoid leaks
*/
~Matrix();
/* Accessor: 1 Point
* Precondition(s):
* - Parameter row is less than rows in matrix
* - Parameter col is less than cols in matrix
* Returns matrix element from row and col. Type is same as matrix type.
*/
T Get(unsigned int row, unsigned int col) const;
/* Assignment Op: 2 Points
* Precondition(s):
* - lhs rows must equal rhs rows
* - lhs cols must equal rhs cols
* Performs deep copy.
*/
const Matrix& operator=(const Matrix& rhs);
/* Times Equals Op: 1 Point
* Returns calling object with matrix scaled by rhs.
* Parameter:
* - rhs will be the same type as the matrix
*/
const Matrix& operator*=(T rhs);
/* Add Op: 1 Point
* Returns the sum of calling object's matrix and rhs's matrix as a new
* object.
* Precondition(s):
* - lhs rows must equal rhs rows
* - lhs cols must equal rhs cols
*/
const Matrix operator+(const Matrix& rhs) const;
private:
T **m_;
unsigned int rows_;
unsigned int cols_;
};
#include "../src/matrix.cc" // NOLINT
#endif // NOLINT
| true |
d023ae4dd28fc1f986689f8f8fc727c20132a72f | C++ | huahuati/jichu-c- | /对象模型探索/6-8内存池概念_代码实现和详细分析.cpp | GB18030 | 3,277 | 3.1875 | 3 | [] | no_license | #include<iostream>
#include<ctime>
using namespace std;
namespace _nmsp1
{
//һڴصĸʵԭ
//malloc:ڴ˷ѣƵСڴ棬˷Ѹ
// "ڴ",Ҫʲô?
//(1)mallocĵômalloc()ôζżٶڴ˷
//(2)mallocĵôǷܹ߳Ч? һЩٶȺЧϵԣ
//"ڴصʵԭ":
//(1)malloc һڴ棬Ҫʱڴһһķ㣬һڴIJʱ
//mallocһڴ棬Ȼһһķ㡣
//ڴã
//(1)ڴ˷
//(2)Ч
void func()
{
}
}
namespace _nmsp2
{
//#define MYMEMPOOL
//:һڴʵʾ
//һڴ A
//A *pa = new A(); delete pa; ڴصֶʵnewdeleteһ
//:ڴش˵
class A
{
public:
static void* operator new(size_t size);
static void operator delete(void* phead);
static int m_iCout;//ͳƣÿnewһΣͳһ
static int m_iMallocCout; //ûmallocһΣͳһ
private:
A* next;
static A* m_FreePosi; //ָһԷȥڴַ
static int m_sTrunkCout; //һηٱĸڴ
};
int A::m_iCout = 0;
int A::m_iMallocCout = 0;
A* A::m_FreePosi = nullptr;
int A::m_sTrunkCout = 5; //һη5ĸڴΪڴӵĴС
void* A::operator new(size_t size)
{
#ifdef MYMEMPOOL
A *ppoint = (A*)malloc(size);
return ppoint;
#endif
//ڴصĺʵִ
A* tmplink;
if (m_FreePosi == nullptr)
{
//ΪգҪڴ棬Ҫһڴ
size_t realsize = m_sTrunkCout * size; //m_sTrunkCoutôڴ
m_FreePosi = reinterpret_cast<A*>(new char[realsize]); //ͳnewõǵײmalloc
tmplink = m_FreePosi;
//ѷһڴ(5С)˴Ҫʹ
for (; tmplink != &m_FreePosi[m_sTrunkCout - 1]; ++tmplink)
{
tmplink->next = tmplink + 1;
}
tmplink->next = nullptr;
++m_iMallocCout;
}
tmplink = m_FreePosi;
m_FreePosi = m_FreePosi->next;
++m_iCout;
return tmplink;
}
void A::operator delete(void* phead) //ûͷڴ棬Ƿʹڴ
{
#ifdef MYMEMPOOL
free (phead);
return ;
#endif
(static_cast<A*>(phead))->next = m_FreePosi;
m_FreePosi = static_cast<A*>(phead);
}
void func()
{
clock_t start, end;// ͷļ #include<ctime>
start = clock();
for (int i = 0; i < 15; i++)
{
A* pa = new A();
//printf("%p\n", pa);
}
end = clock();
cout << "ڴĴΪ:" << A::m_iCout << " ʵmallocĴΪ: " << A::m_iMallocCout
<< " ʱ():" << end - start << endl;
}
}
int main() {
_nmsp2::func();
return 0;
} | true |
edbba447ac245850c2b4c22543f6d0a1ea929e20 | C++ | SoftwareEngineeringToolDemos/FSE-2014-Aalta | /buchi/buchi_automata.cpp | UTF-8 | 4,300 | 2.5625 | 3 | [] | no_license | /*
* File: buchi_automata.cpp
* Author: yaoyinbo
*
* Created on October 30, 2013, 4:58 PM
*/
#include "buchi_automata.h"
#include "../util/utility.h"
#include "../sat_solver.h"
buchi_automata::buchi_automata (const char* input)
{
buchi_node node (aalta_formula (input).unique ());
explore (node);
_initial = _nodes[node];
}
buchi_automata::buchi_automata (aalta_formula* formula)
{
buchi_node node (formula->unique ());
explore (node);
_initial = _nodes[node];
}
buchi_automata::~buchi_automata ()
{
for (node_map::const_iterator it = _nodes.begin (); it != _nodes.end (); it++)
delete it->second;
}
/**
* 构造Buchi Automata
* @param v
*/
void
buchi_automata::explore (buchi_node& node)
{
//print_msg(("node: " + node.to_string ()).c_str());
if (_nodes.find (node) != _nodes.end ()) return;
buchi_node *v = node.clone ();
_nodes[node] = v;
dnf_formula::dnf_clause_set* dc_set = dnf_formula (node.get_state ()).get_next ();
sat_solver::edge_set set;
for (dnf_formula::dnf_clause_set::iterator it = dc_set->begin (); it != dc_set->end (); it++)
{
aalta_formula *tmp = aalta_formula::merge_and (node.get_p (), (*it).current);
set.clear ();
sat_solver::split2set (aalta_formula::And, tmp, &set);
if (sat_solver::scc_sat ((*it).next, &set))
tmp = NULL;
buchi_node next ((*it).next, tmp);
//buchi_node next ((*it).next, aalta_formula::merge_and (node.get_p (), (*it).current));
explore (next);
v->add_edge ((*it).current, _nodes[next]);
}
}
std::string
buchi_automata::to_neverclaim () const
{
std::string ret = "never { /* ";
ret += _initial->get_state ()->to_string ();
ret += " */\n";
hash_map<buchi_node *, int> ids;
int id;
for (node_map::const_iterator it = _nodes.begin (); it != _nodes.end (); it++)
{
if (ids.find (it->second) == ids.end ())
{
id = ids.size ();
ids[it->second] = id;
}
}
for (node_map::const_iterator it = _nodes.begin (); it != _nodes.end (); it++)
{
if (_initial == it->second) ret += "accept_init";
else
{
ret += "T" + convert_to_string (ids[it->second]);
if (it->second->get_p () == NULL)
ret += "_accept";
}
ret += ":\n if\n";
const std::list<buchi_node::edge_t> *edges = it->second->get_edges ();
for (std::list<buchi_node::edge_t>::const_iterator lit = edges->begin (); lit != edges->end (); lit++)
{
ret += " :: (";
ret += (*lit).first->to_string ();
ret += ") -> goto ";
if (_initial == (*lit).second) ret += "accept_init";
else
{
ret += "T" + convert_to_string (ids[(*lit).second]);
if ((*lit).second->get_p () == NULL)
ret += "_accept";
}
ret += "\n";
}
ret += " fi;\n";
}
ret += "}";
return ret;
}
std::string
buchi_automata::to_lbtt () const
{
std::string ret = convert_to_string (_nodes.size ());
ret += " 1s\n";
hash_map<buchi_node *, int> ids;
ids[_initial] = 0;
int id;
for (node_map::const_iterator it = _nodes.begin (); it != _nodes.end (); it++)
{
if (ids.find (it->second) == ids.end ())
{
id = ids.size ();
ids[it->second] = id;
}
}
for (node_map::const_iterator it = _nodes.begin (); it != _nodes.end (); it++)
{
ret += convert_to_string (ids[it->second]);
if (_initial == it->second) ret += " 1 0 -1\n";
else
{
ret += " 0 ";
if (it->second->get_p () == NULL)
ret += "0 ";
ret += "-1\n";
}
const std::list<buchi_node::edge_t> *edges = it->second->get_edges ();
for (std::list<buchi_node::edge_t>::const_iterator lit = edges->begin (); lit != edges->end (); lit++)
{
ret += convert_to_string (ids[(*lit).second]);
ret += " ";
ret += (*lit).first->to_RPN ();
ret += "\n";
}
ret += "-1\n";
}
return ret;
}
std::string
buchi_automata::to_string () const
{
std::string ret;
for (node_map::const_iterator it = _nodes.begin (); it != _nodes.end (); it++)
ret += it->second->to_string ();
return ret;
}
| true |
5447887e9b35818d5a56b8cca68ec83b36f9fa4c | C++ | scintil89/Next_HCI | /0726/src/PenRectangle.cpp | UTF-8 | 651 | 3.046875 | 3 | [] | no_license | #include "PenRectangle.h"
PenRectangle::PenRectangle()
{
}
PenRectangle::~PenRectangle()
{
}
void PenRectangle::setup()
{
position.clear();
color.clear();
}
void PenRectangle::add(ofRectangle rect, ofColor c)
{
position.push_back(rect);
color.push_back(c);
}
void PenRectangle::draw()
{
for (int i = 0; i < position.size(); i++)
{
ofSetColor(color[i]);
ofSetRectMode(OF_RECTMODE_CORNER);
ofDrawRectangle(position[i]);
}
}
void PenRectangle::clear()
{
position.clear();
color.clear();
}
void PenRectangle::pop_back()
{
if (position.empty() == false && color.empty() == false)
{
position.pop_back();
color.pop_back();
}
}
| true |
8f5a0d0ee3fe38bdc5c7eabce9a6b34eeb4fc420 | C++ | piotrek24061988/AutomaticTesting | /module1/module1_tests/source/smsSender_test1.cpp | UTF-8 | 2,697 | 2.53125 | 3 | [] | no_license | #include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "smsSender.hpp"
#include "smsDevice.hpp"
#include "smsDevice_mock.hpp"
#include <memory>
using ::testing::Ge;
using ::testing::NotNull;
using ::testing::Return;
using ::testing::_;
class smsSender_test1 : public testing::Test
{
protected:
virtual void SetUp()
{
if(!device)
{
device = std::make_shared<smsDevice>();
}
if(!sender)
{
sender = std::make_unique<smsSender>(device);
}
if(!device_mock)
{
device_mock = std::make_shared<smsDevice_mock>();
}
if(!sender_mock)
{
sender_mock = std::make_unique<smsSender>(device_mock);
}
}
virtual void TearDown()
{
//smart_ptr used so no need to clean anything
}
std::unique_ptr<smsSender> sender;
std::unique_ptr<smsSender> sender_mock;
std::shared_ptr<smsDevice> device;
std::shared_ptr<smsDevice_mock> device_mock;
};
TEST_F(smsSender_test1, sendValidatedSms)
{
#ifdef IntegrationTests
EXPECT_CALL(*device_mock, init()).Times(1);
EXPECT_CALL(*device_mock, send(std::string("537240688"), std::string("Hello"))).Times(1);
EXPECT_CALL(*device_mock, deInit()).Times(1);
#else
EXPECT_CALL(*device_mock, init()).Times(1).WillOnce(Return(true));
EXPECT_CALL(*device_mock, send(std::string("537240688"), std::string("Hello"))).Times(1).WillOnce(Return(true));
EXPECT_CALL(*device_mock, deInit()).Times(1).WillOnce(Return(true));
#endif
EXPECT_TRUE(sender_mock->send(std::string("537240688"), std::string("Hello")));
}
//smsDevice initialization error simulation by mock. Only unit test.
#ifndef IntegrationTests
TEST_F(smsSender_test1, sendValidatedSmsInitError)
{
EXPECT_CALL(*device_mock, init()).Times(1).WillOnce(Return(false));
EXPECT_FALSE(sender_mock->send(std::string("537240688"), std::string("Hello")));
}
#endif
//smsDevice send error simulation by mock. Only unit test.
#ifndef IntegrationTests
TEST_F(smsSender_test1, sendValidatedSmsSendError)
{
EXPECT_CALL(*device_mock, init()).Times(1).WillOnce(Return(true));
EXPECT_CALL(*device_mock, send(std::string("537240688"), std::string("Hello"))).Times(1).WillOnce(Return(false));
EXPECT_FALSE(sender_mock->send(std::string("537240688"), std::string("Hello")));
}
#endif
//smsDevice deinitialization error simulation by mock. Only unit test.
#ifndef IntegrationTests
TEST_F(smsSender_test1, sendValidatedSmsDeinitError)
{
EXPECT_CALL(*device_mock, init()).Times(1).WillOnce(Return(true));
EXPECT_CALL(*device_mock, send(std::string("537240688"), std::string("Hello"))).Times(1).WillOnce(Return(true));
EXPECT_CALL(*device_mock, deInit()).Times(1).WillOnce(Return(false));
EXPECT_FALSE(sender_mock->send(std::string("537240688"), std::string("Hello")));
}
#endif
| true |
47152f3e0fa01dfd4f8b062e17fc600d61f8f1ee | C++ | matiashf/blockbuster | /src/Destructible.hpp | UTF-8 | 626 | 3.484375 | 3 | [] | no_license | #ifndef DESTRUCTIBLE_HPP
#define DESTRUCTIBLE_HPP
/** A virtual class with a health counter, that can be damaged and destroyed. */
class Destructible {
public:
/// We use a type to improve code readability
typedef float Health;
/// Sets the health counter to the given value
Destructible(Health);
/// Reduces the health counter by the given value
virtual void damage(Health);
/// Returns the health counter
inline Health health() { return health_; }
private:
Health health_;
protected:
/// Called when the health counter goes to or below zero. Only called once.
virtual void destroy() = 0;
};
#endif
| true |
0f353cb90634f1965a149654df87440181688f7c | C++ | Luke-Newman/DSA | /mini_SHRDLU_v2/Cell.h | UTF-8 | 828 | 2.765625 | 3 | [] | no_license | //
// Created by Luke on 28/03/2017.
//
#ifndef MINI_SHRDLU_V1_CELL_H
#define MINI_SHRDLU_V1_CELL_H
#include "AtomGoal.h"
class Cell { // This was implemented for flexibility, also comes from one of the only limitations of using a vector
// for this assignment; I need a row and column for only a few functions
private:
int row, col, label;
public:
Cell(int label, int row, int col) {
this->label = label;
this->row = row;
this->col = col;
}
void getLabel(int label) {
this->label = label;
}
void setLabel(int value) {
this-> label = value;
}
int getLabel() const{
return label;
}
int getRow() {
return this->row;
}
int getCol() {
return this->col;
}
};
#endif //MINI_SHRDLU_V1_CELL_H
| true |
78e2ed6a452504364122be2ab74860b429445465 | C++ | huddy987/Arduino-Battleship | /draw_handler.cpp | UTF-8 | 10,443 | 3.015625 | 3 | [] | no_license | #include <Adafruit_GFX.h> // Core graphics library
#include <SPI.h> // Library for SPI mode
#include <Adafruit_ILI9341.h> // Controller chip library
#include "TouchScreen.h" // Library for TouchScreen
#include "./block.h"
#include "./game.h"
#include "./data_handler.h" // Contains determine_block() function
#include "./draw_handler.h"
// Draws outcome (0 is lose, 1 is win, 2 is tie)
void draw_outcome(Adafruit_ILI9341 display, int win_status) {
// Need to do this to rotate text
display.setRotation(1);
// Set text size and color
display.setTextColor(ILI9341_WHITE);
display.setTextSize(10);
// Have to make cursor x different for each case of character sizes
if (win_status == 0) {
display.setCursor(45, 85);
display.fillScreen(ILI9341_RED);
display.print("Lose");
} else if (win_status == 1) {
display.setCursor(50, 85);
display.fillScreen(ILI9341_GREEN);
display.print("Win!");
} else if (win_status == 2) {
// Use black text because white is hard to see on yellow background
display.setTextColor(ILI9341_BLACK);
display.setCursor(50, 85);
display.fillScreen(ILI9341_YELLOW);
display.print("Tie!");
}
}
// Draws a main menu
void draw_menu(Adafruit_ILI9341 display) {
// Need to do this to rotate text
display.setRotation(1);
// Fill screen with blue
display.fillScreen(ILI9341_BLUE);
// Set text size and color
display.setTextColor(ILI9341_WHITE);
display.setTextSize(10);
display.setCursor(20, 85);
display.print("PLAY!");
}
// Draw menu for # of players selection
void draw_menu_mode(Adafruit_ILI9341 display) {
int char_size = 10;
// Need to do this to rotate text
display.setRotation(1);
display.fillRect((display.width() / 2), 0, (display.width() / 2),
display.height(), ILI9341_BLUE);
display.fillRect(0, 0, (display.width() / 2), display.height(), ILI9341_PINK);
// Characters are (5,7) * char_size
// Using this expression, we can center characters
display.drawChar(((display.width() / 4) - (char_size * (5 / 2))),
((display.height() / 2) - (char_size * (7 / 2))),
'1', ILI9341_WHITE, ILI9341_PINK, char_size);
display.drawChar((((3 * display.width()) / 4) - (char_size * (5 / 2))),
((display.height() / 2)- (char_size * (7 / 2))),
'2', ILI9341_WHITE, ILI9341_BLUE, char_size);
}
// Draws a waiting screen when waiting for a response from the other arduino
void draw_waiting(Adafruit_ILI9341 display) {
// Need to do this to rotate text
display.setRotation(1);
// Fill screen with black
display.fillScreen(ILI9341_BLACK);
// Set text size and color
display.setTextColor(ILI9341_WHITE);
display.setTextSize(5);
display.setCursor(40, 103);
display.print("Waiting.");
}
// Draws an empty grid
void draw_empty_grid(Adafruit_ILI9341 display, int BOXSIZE) {
// Need to do this to rotate to proper game orientation
display.setRotation(0);
display.fillScreen(ILI9341_BLACK);
// Draws a 6 x 7 grid of 40x40 pixel boxes
// Starts at index 0 because 40*0=0
for (int i = 1; i < 8; i++) {
for (int j = 1; j < 7; j++) {
display.drawRect((display.width() - BOXSIZE * j),
(display.height() - BOXSIZE * i), BOXSIZE, BOXSIZE, ILI9341_WHITE);
}
}
}
// Draws a grey confirm button
void draw_grey_confirm(Adafruit_ILI9341 display, int BOXSIZE) {
display.fillRect(120, 0, 120, BOXSIZE, 0x8410);
}
// Draws a green confirm button
void draw_green_confirm(Adafruit_ILI9341 display, int BOXSIZE) {
display.fillRect(120, 0, 120, BOXSIZE, ILI9341_GREEN);
}
// Draws a red cancel button
void draw_cancel(Adafruit_ILI9341 display, int BOXSIZE) {
display.fillRect(0, 0, 120, BOXSIZE, ILI9341_RED);
/* // displays "RESET" on the red block. Un-comment if you want
display.setTextColor(ILI9341_WHITE);
display.setTextSize(2);
display.setCursor(30, 13);
display.print("RESET");
*/
}
// Draws an empty battleship map
void draw_empty_map(Adafruit_ILI9341 display, int BOXSIZE) {
draw_empty_grid(display, BOXSIZE);
draw_grey_confirm(display, BOXSIZE);
draw_cancel(display, BOXSIZE);
}
// Fill in grid box at a given location
void draw_at_grid_pos(Adafruit_ILI9341 display, int BOXSIZE,
String grid_pos, int color) {
char let[7] = {'A', 'B', 'C', 'D', 'E', 'F', 'G'};
char num[6] = {'0', '1', '2', '3', '4', '5'};
// Indice shifted because of the menu on the left side of the screen.
for (int i = 7; i > 0; i--) {
for (int j = 5; j > -1; j--) {
if (let[i - 1] == grid_pos[0] && num[j] == grid_pos[1]) {
// Fill the rectangle
display.fillRect((BOXSIZE * j), (BOXSIZE * i), BOXSIZE,
BOXSIZE, color);
// Redraw the white border
display.drawRect((BOXSIZE * j), (BOXSIZE * i), BOXSIZE,
BOXSIZE, ILI9341_WHITE);
}
}
}
}
// Clears selected tile(s)
void clear_all_selections(Adafruit_ILI9341 display, int BOXSIZE,
String block_array[], int length) {
for (int i = 0; i < length; i++) {
// Draw black at every previously selected square
draw_at_grid_pos(display, BOXSIZE, block_array[i], ILI9341_BLACK);
}
draw_grey_confirm(display, BOXSIZE); // Draws a grey confirm button
}
/*
0 = undisturbed
1 = has been shot but no boat
2 = has a boat hidden; not shot
3 = has a boat that's been shot
4 = has a full boat sunk
5 = enemy's: shot but no boat
6 = enemy's: shot and there is a boat
7 = enemy's: full boat sunk
8 = enemy's: has boat but not shot
*/
// Draws state-relevent color at given grid position
void draw_state(Adafruit_ILI9341 display, int BOXSIZE,
String grid_pos, int state) {
switch (state) {
case 0:
case 8:
// Case 0 is the same as case 8 for the purpose of drawing
// Draws black tile if nothing has happened
draw_at_grid_pos(display, BOXSIZE, grid_pos, ILI9341_BLACK);
break;
case 1:
case 5:
// Shot but no boat: BLUE
draw_at_grid_pos(display, BOXSIZE, grid_pos, ILI9341_BLUE);
break;
case 2:
// Your own boat hidden: GREY
draw_at_grid_pos(display, BOXSIZE, grid_pos, 0x8410);
break;
case 3:
case 6:
// Boat hit but not sunk: ORANGE
draw_at_grid_pos(display, BOXSIZE, grid_pos, 0xFD20);
break;
case 4:
case 7:
// All parts of the boat dead: RED
draw_at_grid_pos(display, BOXSIZE, grid_pos, ILI9341_RED);
break;
}
}
// Blinks a selected grid position a given amount of times
// mode 0: show my enemy's shot on my board
// mode 1: show my shot on my enemy's board
void blink_block(Adafruit_ILI9341 display, int BOXSIZE,
Block play_arr[], String *grid_pos, int blink_times, int mode) {
// Converts grid position to grid number
int block_number = determine_array_element(*grid_pos);
// Determine the state before it was shot
int previous_state = determine_previous_state(play_arr, block_number);
for (int i = 0; i < blink_times; i++) {
if (mode == 0) {
delay(250); // Half second delay between transitions
draw_state(display, BOXSIZE, *grid_pos, previous_state);
delay(250);
draw_state(display, BOXSIZE, *grid_pos,
play_arr[block_number].getBlock());
} else if (mode == 1) {
delay(250); // Half second delay between transitions
draw_at_grid_pos(display, BOXSIZE, *grid_pos, ILI9341_BLACK);
delay(250);
draw_state(display, BOXSIZE, *grid_pos,
play_arr[block_number].getEnemy());
}
}
}
// Draws the message "opponent" vertically on the left side of the screen
void draw_opponent_message(Adafruit_ILI9341 display) {
// Set text size and color
display.setTextColor(ILI9341_WHITE);
display.setTextSize(2);
display.setCursor(60, 13);
display.print("YOUR BOATS");
}
// Draws appropriate color at every grid position on our own board
void draw_board_self(Adafruit_ILI9341 display,
int BOXSIZE, Block play_arr[], String *opponent_selection, bool animations) {
// Need to do this to rotate to standard game rotations as
// specified in readme (after main menu).
display.setRotation(0);
draw_empty_grid(display, BOXSIZE);
for (int i = 0; i < 42; i++) {
// Draw the state for each self block
draw_state(display, BOXSIZE, determine_block(i), play_arr[i].getBlock());
}
// Draw the word "opponent" to know that it's our opponent's shot
draw_opponent_message(display);
// Blink the last the opponent shot block 2 times if animations are turned on
if (animations == true){
blink_block(display, BOXSIZE, play_arr, opponent_selection, 2, 0);
}
}
// Draws appropriate color at every grid position on the enemy's board
void draw_board_enemy(Adafruit_ILI9341 display, int BOXSIZE,
Block play_arr[], String *my_selection, bool animations) {
draw_empty_map(display, BOXSIZE);
for (int i = 0; i < 42; i++) {
// Draw the state for each self block
draw_state(display, BOXSIZE, determine_block(i), play_arr[i].getEnemy());
}
// Blink the last block I shot 1 time if animations are turned on
if (animations == true){
blink_block(display, BOXSIZE, play_arr, my_selection, 1, 1);
}
}
/*
* This function draws the grey block that
* tells the user how many blocks to press
* SELECT + <a number>
*/
void draw_select(Adafruit_ILI9341 display, int BOXSIZE, String message) {
display.fillRect(120, 0, 120, BOXSIZE, 0x8410);
display.setTextColor(ILI9341_WHITE);
display.setTextSize(2);
display.setCursor(132, 13);
display.print("SELECT " + message);
}
/*
* This function determines how many blocks the user should enter
* and calls a function to let prompt the user for the boat
*/
void draw_grey_setup(Adafruit_ILI9341 display, int BOXSIZE, int block_number) {
String message = "";
// if the first boat has not been entered fully
if ((0 <= block_number) && (block_number <= 4)) {
message = "5";
} else if ((5 <= block_number) && (block_number <= 8)) {
// if the second boat has not been entered fully
message = "4";
} else if ((9 <= block_number) && (block_number <= 13)) {
// if the thrid boat has not been entered fully
message = "3";
} else {
// This should never execute
Serial.println("Error in draw_grey_setup.");
}
// Calls the function that actually does the drawing
draw_select(display, BOXSIZE, message);
}
| true |
d97161cca7ecb65cf44497ad250bb399714c9477 | C++ | Fluci/GooBalls | /src/lib/physics/2d/kernel_test.cc | UTF-8 | 11,639 | 2.78125 | 3 | [
"BSD-3-Clause"
] | permissive | #include "kernel_test.hpp"
#include <boost/test/unit_test.hpp>
#include <random>
#include <iostream>
namespace GooBalls {
namespace d2 {
namespace Physics {
/**
* Properties a kernel should have:
* C^0, C^1 continuous
* evaluated at r = h, the value should be zero
* Kernel must be normalized: int_X W(|x - x_i|) dx = 1
*/
/// Create `samples` 2d points on unit disk
Coordinates2d randomUnitDisk(int samples){
std::mt19937 rnd;
rnd.seed(23);
std::uniform_real_distribution<> dist(0.0, 1.0);
Coordinates2d Xs(samples, 2);
for(int i = 0; i < samples; ++i){
do {
Xs(i, 0) = dist(rnd);
Xs(i, 1) = dist(rnd);
// rejection sampling
} while (Xs.row(i).norm() > 1.0);
}
return Xs;
}
Coordinates1d increasingToOne(int n){
Coordinates1d Xorig(n);
for(int i = 0; i < n; ++i){
Xorig[i] = double(i)/n;
}
assert(Xorig.maxCoeff() < 1.0);
return Xorig;
}
std::vector<Float> getHs(){
std::vector<Float> hs;
hs.push_back(0.1);
hs.push_back(0.5);
hs.push_back(1.0);
hs.push_back(5.0);
hs.push_back(10.0);
hs.push_back(50.0);
hs.push_back(100.0);
return hs;
}
void testRadialSymmetry(Kernel& k, int experiments){
int radiusSamples = std::sqrt(experiments);
int angleSamples = radiusSamples;
auto hs = getHs();
for(auto h : hs){
k.setH(h);
Coordinates2d Xs(angleSamples, 2);
Coordinates1d w, wgradN, wlap;
Coordinates2d wgrad;
Coordinates2d dirs(angleSamples, 2);
for(int i = 1; i < radiusSamples; ++i){
Float radius = i/double(radiusSamples) * h;
for(int j = 0; j < angleSamples; ++j){
Float angle = i/double(angleSamples) * 2*M_PI;
dirs(j, 0) = std::sin(angle);
dirs(j, 1) = std::cos(angle);
}
Xs = dirs * radius;
k.compute(Xs, &w, &wgrad, &wlap);
wgradN = wgrad.rowwise().norm();
BOOST_TEST(w.maxCoeff() - w.minCoeff() < 0.0001);
BOOST_TEST(wlap.maxCoeff() - wlap.minCoeff() < 0.0001);
BOOST_TEST(wgradN.maxCoeff() - wgradN.minCoeff() < 0.0001);
// TODO: check gradient direction
}
}
}
void testZeroBorder1d(Kernel& k){
auto hs = getHs();
Coordinates1d ws(hs.size());
for(size_t i = 0; i < hs.size(); ++i){
Float h = hs[i];
k.setH(h);
Coordinates1d Xs(1);
Xs[0] = h;
Coordinates1d w;
k.compute1d(Xs.array()*Xs.array(), &w, nullptr, nullptr);
ws[i] = w[0];
// BOOST_TEST(w[0] == 0.0);
}
ws = ws.array().abs();
BOOST_TEST(ws.maxCoeff() == 0.0);
}
void testZeroBorder(Kernel& k, int experiments){
std::mt19937 rnd;
rnd.seed(17); // we use a fixed seed for repeatability
std::uniform_real_distribution<> dist(-10.0, 10.0);
Coordinates1d ws(experiments);
for(int i = 0; i < experiments; ++i){
Coordinates2d x(1,2);
x(0,0) = dist(rnd);
x(0,1) = dist(rnd);
auto h = x.norm();
k.setH(h);
Coordinates1d w;
k.compute(x, &w, nullptr, nullptr);
ws[i] = w[0];
//BOOST_TEST(w[0] == 0.0);
}
ws = ws.array().abs();
BOOST_TEST(ws.maxCoeff() == 0.0);
}
void testZeroBorderGradient1d(Kernel& k){
auto hs = getHs();
for(auto h : hs){
k.setH(h);
Coordinates1d Xs(1);
Xs[0] = h;
Coordinates1d w;
k.compute1d(Xs.array()*Xs.array(), nullptr, &w, nullptr);
BOOST_TEST(w[0] == 0.0);
}
}
void testZeroBorderGradient(Kernel& k, int experiments){
Coordinates2d Xorig = randomUnitDisk(experiments).rowwise().normalized();
auto hs = getHs();
for(auto h : hs){
Coordinates2d Xs = h*Xorig;
Coordinates2d Wgrad;
k.setH(h);
k.compute(Xs, nullptr, &Wgrad, nullptr);
int i;
auto extrema = Wgrad.rowwise().norm();
extrema.maxCoeff(&i);
BOOST_TEST(Wgrad.row(i).norm() == 0.0);
BOOST_TEST(Wgrad(i, 0) == 0.0);
BOOST_TEST(Wgrad(i, 1) == 0.0);
}
}
void testNonNegativity(Kernel& k, int experiments){
Coordinates2d Xs = randomUnitDisk(experiments);
Coordinates1d W;
k.setH(1.0);
k.compute(Xs, &W, nullptr, nullptr);
for(int i = 0; i < experiments; ++i){
BOOST_TEST(0 <= W[i]);
}
}
void testMonotonicity(Kernel& k, int experiments){
Coordinates2d Xs(experiments, 2);
Xs.setZero();
Float h = 1.0;
for(int i = 0; i < experiments; ++i){
Xs(i, 0) = i/double(experiments-1)*h;
}
k.setH(h);
Coordinates1d w;
k.compute(Xs, &w, nullptr, nullptr);
for(int i = 1; i < experiments; ++i){
BOOST_TEST(w[i-1] >= w[i], std::to_string(i) + ": " + std::to_string(w[i-1]) + " >=! " + std::to_string(w[i]));
}
}
void testGradientFiniteDifference(Kernel& k, int experiments){
const Coordinates2d Xorig = randomUnitDisk(experiments);
auto hs = getHs();
for(auto h : hs){
Float dx = h * 0.00000001;
k.setH(h);
Coordinates2d Xs = 0.99 * h * Xorig.array();
Coordinates2d Xsx = Xs;
Xsx.col(0).array() += dx;
Coordinates2d Xsy = Xs;
Xsy.col(1).array() += dx;
Coordinates1d W0, Wx, Wy;
Coordinates2d WgradReceived;
k.compute(Xs, &W0, &WgradReceived, nullptr);
k.compute(Xsx, &Wx, nullptr, nullptr);
k.compute(Xsy, &Wy, nullptr, nullptr);
Coordinates2d gradExpected(Xs.rows(), 2);
gradExpected.col(0) = (Wx - W0)/dx;
gradExpected.col(1) = (Wy - W0)/dx;
auto diff = (gradExpected - WgradReceived).array().abs();
int i, j;
diff.maxCoeff(&i,&j);
BOOST_TEST(gradExpected(i, j) == WgradReceived(i, j));
}
}
void testGradientFiniteDifference1d(Kernel& k, int experiments){
auto hs = getHs();
Coordinates1d Xorig = increasingToOne(experiments);
for(auto h : hs){
Float dx = h * 0.000001;
k.setH(h);
Coordinates1d Xs = 0.99 * h * Xorig;
Coordinates1d Xsx = Xs.array() + dx;
Coordinates1d W0, Wx;
Coordinates1d WgradReceived;
k.compute1d(Xs.array()*Xs.array(), &W0, &WgradReceived, nullptr);
k.compute1d(Xsx.array()*Xsx.array(), &Wx, nullptr, nullptr);
Coordinates1d gradExpected = (Wx - W0)/dx;
auto diff = (gradExpected - WgradReceived).array().abs();
int i;
diff.maxCoeff(&i);
BOOST_TEST(gradExpected[i] == WgradReceived[i]);
}
}
void testLaplacianFromGradientFiniteDifferences1d(Kernel& k, int experiments){
const Coordinates1d Xorig = increasingToOne(experiments);
auto hs = getHs();
for(auto h : hs){
Float dx = h * 0.000001;
k.setH(h);
Coordinates1d Xs = 0.99*h*Xorig.array();
Coordinates1d Xsx = Xs.array() + dx;
Coordinates1d G0, Gx;
Coordinates1d Wlap;
k.compute1d(Xs.array()*Xs.array(), nullptr, &G0, &Wlap);
k.compute1d(Xsx.array()*Xsx.array(), nullptr, &Gx, nullptr);
Coordinates1d expectedLaplacian = (Gx - G0)/dx;
auto diff = (expectedLaplacian - Wlap).array().abs();
int i;
diff.maxCoeff(&i);
BOOST_TEST(expectedLaplacian[i] == Wlap[i]);
}
}
void testLaplacianFromGradientFiniteDifferences(Kernel& k, int experiments){
const Coordinates2d Xorig = randomUnitDisk(experiments);
auto hs = getHs();
for(auto h : hs){
Float dx = h * 0.000001;
k.setH(h);
Coordinates2d Xs = 0.99*h*Xorig;
Coordinates2d Xsx, Xsy;
Xsx = Xs; Xsx.col(0).array() += dx;
Xsy = Xs; Xsy.col(1).array() += dx;
Coordinates2d G0, Gx, Gy;
Coordinates1d Wlap;
k.compute(Xs, nullptr, &G0, &Wlap);
k.compute(Xsx, nullptr, &Gx, nullptr);
k.compute(Xsy, nullptr, &Gy, nullptr);
Coordinates1d expectedLaplacian = (Gx - G0).col(0)/dx + (Gy - G0).col(1)/dx;
auto diff = (expectedLaplacian - Wlap).array().abs();
int i;
diff.maxCoeff(&i);
BOOST_TEST(expectedLaplacian[i] == Wlap[i]);
}
}
void testLaplacianFiniteDifference1d(Kernel& k, int experiments){
const Coordinates1d Xorig = increasingToOne(experiments);
auto hs = getHs();
for(auto h : hs){
Float dx = h * 0.0001;
k.setH(h);
Coordinates1d Xs = 0.99 * h * Xorig.array() + dx;
Coordinates1d Xsx1 = Xs.array() - dx;
Coordinates1d Xsx2 = Xs.array() + dx;
Coordinates1d W0, Wx1, Wx2;
Coordinates1d Wlap;
k.compute1d(Xs.array()*Xs.array(), &W0, nullptr, &Wlap);
k.compute1d(Xsx1.array()*Xsx1.array(), &Wx1, nullptr, nullptr);
k.compute1d(Xsx2.array()*Xsx2.array(), &Wx2, nullptr, nullptr);
Coordinates1d expectedLaplacian = (Wx1 + Wx2 - 2*W0) / (dx*dx);
auto diff = (expectedLaplacian - Wlap).array().abs();
int i;
diff.maxCoeff(&i);
BOOST_TEST(expectedLaplacian[i] == Wlap[i]);
}
}
void testLaplacianFiniteDifference(Kernel& k, int experiments){
const Coordinates2d Xorig = randomUnitDisk(experiments);
auto hs = getHs();
for(auto h : hs){
Float dx = h * 0.00001;
k.setH(h);
Coordinates2d Xs = 0.99 * h * Xorig.array() + dx;
Coordinates2d Xsx1, Xsx2, Xsy1, Xsy2;
Xsx1 = Xs; Xsx1.col(0).array() -= dx;
Xsx2 = Xs; Xsx2.col(0).array() += dx;
Xsy1 = Xs; Xsy1.col(1).array() -= dx;
Xsy2 = Xs; Xsy2.col(1).array() += dx;
Coordinates1d W0, Wx1, Wx2, Wy1, Wy2;
Coordinates1d Wlap;
k.compute(Xs, &W0, nullptr, &Wlap);
k.compute(Xsx1, &Wx1, nullptr, nullptr);
k.compute(Xsx2, &Wx2, nullptr, nullptr);
k.compute(Xsy1, &Wy1, nullptr, nullptr);
k.compute(Xsy2, &Wy2, nullptr, nullptr);
Coordinates1d expectedLaplacian = (Wx1 + Wx2 + Wy1 + Wy2 - 4*W0) / (dx*dx);
auto diff = (expectedLaplacian - Wlap).array().abs();
int i;
diff.maxCoeff(&i);
BOOST_TEST(expectedLaplacian[i] == Wlap[i]);
}
}
void testNormalization1d(Kernel& k, int experiments){
auto hs = getHs();
Coordinates1d Xorig = increasingToOne(experiments);
// we integrate over [-h, h] with `experiments` steps of size (2*h/experiments)
for(auto h : hs){
Coordinates1d Xs = h*(Xorig.array()*2 - 1);
Float dA = h*2/experiments; // area of one test segment
Coordinates1d W;
k.setH(h);
k.compute1d(Xs.array()*Xs.array(), &W, nullptr, nullptr);
Float totalWeight = W.sum()*dA;
BOOST_TEST(totalWeight == 1.0);
}
}
void testNormalization(Kernel& k, int experiments){
auto hs = getHs();
int n = std::max(100.0, std::sqrt(experiments));
for(auto h : hs){
Coordinates2d Xs(n*n, 2);
int inserted = 0;
for(int i = 0; i < n; ++i){
for(int j = 0; j < n; ++j){
TranslationVector pos;
pos[0] = h*(2*i/double(n)-1);
pos[1] = h*(2*j/double(n)-1);
if(pos.norm() > h){
continue;
}
Xs.row(inserted++) = pos;
}
}
Xs.conservativeResize(inserted, Eigen::NoChange);
Float dA;
dA = 2*h/n; // area of one test square
dA = dA*dA;
Coordinates1d W;
k.setH(h);
k.compute(Xs, &W, nullptr, nullptr);
Float totalWeight = W.sum()*dA;
BOOST_TEST(totalWeight == 1.0);
}
}
} // Physics
} // d2
} // GooBalls
| true |
ff27777497565f73ebb95e8b996462f7e8597159 | C++ | ahfakt/Math | /include/Math/mat4.h | UTF-8 | 960 | 2.546875 | 3 | [
"MIT"
] | permissive | #ifndef MATH_MAT4_H
#define MATH_MAT4_H
#include "vec4.h"
namespace Math {
struct mat4 {
vec4 X, Y, Z, W;
mat4(float Ax = 1, float Ay = 0, float Az = 0, float Aw = 0, float Bx = 0, float By = 1, float Bz = 0, float Bw = 0, float Cx = 0, float Cy = 0, float Cz = 1, float Cw = 0, float Dx = 0, float Dy = 0, float Dz = 0, float Dw = 1);
mat4(vec4 const& X, vec4 const& Y, vec4 const& Z, vec4 const& W);
mat4(mat3 const& M, vec3 const& W);
mat4(mat3 const& M);
mat4& operator*=(mat4 const&);
mat4& operator/=(mat4 const&);
mat4& operator*=(float);
mat4& operator*=(double);
mat4& operator*=(vec4 const&);
};//struct mat4
mat4 operator!(mat4 const&);
mat4 operator~(mat4 const&);
mat4 operator*(mat4 const&, mat4 const&);
mat4 operator/(mat4 const&, mat4 const&);
mat4 operator*(mat4 const&, float);
mat4 operator*(mat4 const&, double);
mat4 operator*(mat4 const&, vec4 const&);
float Det(mat4 const&);
}//namespace Math
#endif //MATH_MAT4_H
| true |
ed7d3f851bf87843c35f6118eb32551d9b47f5d5 | C++ | nyanpasu/nettest | /SDL2/Client/game.hpp | UTF-8 | 4,890 | 2.921875 | 3 | [] | no_license | #ifndef GAME_H_
#define GAME_H_
const uint kGridSize = 9;
const int kMaxX = 80;
const int kMaxY = 60;
const uint kWindowWidth = 800;
const uint kWindowHeight = 600;
const uint kTimeOut = 100;
const std::string kWindowTitle = "Just liek maek gaem";
class Game
{
public:
Game();
public:
void game_loop();
void get_input(Player&);
void drawRedGrid();
void drawGreenSquare(int, int);
void drawBlueSquare(int, int);
void draw_square(int, int, SDL_Color);
void resetGrid();
void draw_grid(Player, std::vector <Player>);
public:
SDL_Window* window;
SDL_Renderer* renderer;
SDL_Event event;
bool loop;
bool timeout;
Client client;
Player me;
Uint32 lastTick;
Uint32 currentTick;
};
Game::Game()
{
if ( SDL_Init( SDL_INIT_VIDEO ) < 0 )
{
std::cout << "Couldn't start SDL: " << SDL_GetError() << std::endl;
}
window = SDL_CreateWindow(
kWindowTitle.c_str(),
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
kWindowWidth, kWindowHeight,
0
);
renderer = SDL_CreateRenderer( window, -1, 0 );
loop = true;
timeout = false;
lastTick = 0;
currentTick = SDL_GetTicks();
}
void Game::game_loop()
{
while (loop)
{
while (SDL_PollEvent(&event)){
if (event.type == SDL_QUIT){
loop = false;
}
}
// Handle the server... see what it's trying to tell the local client.
if (client.server)
{
// Only bother trying if the server actually sent something.
if (SDLNet_CheckSockets(client.server_monitor, 0))
{
client.handle_server(client.server);
}
}
draw_grid(me, client.players);
// Render everything that's been drawn.
SDL_RenderPresent(renderer);
// Timeout handler.
if (timeout == true)
{
currentTick = SDL_GetTicks();
if (currentTick > lastTick + kTimeOut){
timeout = false;
}
}
// Rest of the loop that's executed once every 300 milliseconds.
if (timeout == false)
{
timeout = true;
lastTick = SDL_GetTicks();
// Handle keyboard and movement of self.
SDL_PumpEvents();
get_input(me);
// Update server.
if (client.server){
client.update_server(client.server, me);
}
}
}
}
void Game::get_input(Player& me)
{
const Uint8 *keyboard_state = SDL_GetKeyboardState(NULL);
if (keyboard_state[SDLK_ESCAPE])
{
loop = false;
}
if (keyboard_state[SDLK_RIGHT])
{
if (me.x + 1< kMaxX )
{
me.x++;
}
}
if (keyboard_state[SDLK_LEFT])
{
if (me.x > 0)
{
me.x--;
}
}
if (keyboard_state[SDLK_UP])
{
if (me.y > 0)
{
me.y--;
}
}
if (keyboard_state[SDLK_DOWN])
{
if (me.y + 1 < kMaxY)
{
me.y++;
}
}
}
void Game::drawRedGrid()
{
// Set up rect that will be drawn repeatedly.
SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255);
SDL_Rect rect;
rect.w = kGridSize;
rect.h = kGridSize;
// Draw a grid.
for ( uint x = 0; x < kMaxX; x++ )
{
for ( uint y = 0; y < kMaxY; y++ )
{
rect.x = x * 10;
rect.y = y * 10;
SDL_RenderFillRect( renderer, &rect );
}
}
}
void Game::drawGreenSquare(int x, int y)
{
SDL_SetRenderDrawColor( renderer, 0, 255, 0, 255 );
SDL_Rect rect;
rect.w = kGridSize;
rect.h = kGridSize;
rect.x = x * 10;
rect.y = y * 10;
SDL_RenderFillRect(renderer, &rect);
}
void Game::drawBlueSquare(int x, int y)
{
SDL_SetRenderDrawColor(renderer, 0, 0, 255, 255);
SDL_Rect rect;
rect.w = kGridSize;
rect.h = kGridSize;
rect.x = x * 10;
rect.y = y * 10;
SDL_RenderFillRect(renderer, &rect);
}
void Game::draw_square(int x, int y, SDL_Color color)
{
SDL_Rect rect;
rect.w = kGridSize;
rect.h = kGridSize;
rect.x = x * 10;
rect.y = y * 10;
SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, 255 );
SDL_RenderFillRect(renderer, &rect);
}
void Game::resetGrid()
{
// Clear screen first.
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
SDL_RenderClear(renderer);
drawRedGrid();
}
void Game::draw_grid(Player me, std::vector <Player> players)
{
resetGrid();
// Draw me
drawGreenSquare(me.x, me.y);
// Draw other clients.
for (uint i = 0; i < players.size(); i++ )
{
Player remote_player = players[i];
draw_square(remote_player.x, remote_player.y, remote_player.color);
}
}
#endif | true |
4af35e61d64dcaf90c527bd14566637413057176 | C++ | lieuwex/isa | /compiler/imp/optimiser.cpp | UTF-8 | 2,601 | 2.828125 | 3 | [] | no_license | #include <queue>
#include <unordered_set>
#include <unordered_map>
#include <cassert>
#include "optimiser.h"
using namespace std;
// All blocks in 'chain', except possibly the last, should have a JMP terminator
static void mergeChain(IFunc &ifunc, const vector<Id> &chain) {
if (chain.size() <= 1) return;
BB &bb0 = ifunc.BBs[chain[0]];
assert(bb0.term.tag == IRTerm::JMP);
for (size_t i = 1; i < chain.size(); i++) {
const BB &bb1 = ifunc.BBs.find(chain[i])->second;
if (i < chain.size() - 1) assert(bb1.term.tag == IRTerm::JMP);
bb0.inss.insert(bb0.inss.end(), bb1.inss.begin(), bb1.inss.end());
}
bb0.term = ifunc.BBs.find(chain.back())->second.term;
for (size_t i = 1; i < chain.size(); i++) {
ifunc.BBs.erase(ifunc.BBs.find(chain[i]));
}
}
static void mergeBlocks(IFunc &ifunc) {
unordered_map<Id, Id> singleNexts, singlePrevs;
unordered_map<Id, vector<Id>> allPrevs;
for (const auto &p : ifunc.BBs) {
if (p.second.term.tag == IRTerm::JMP) {
singleNexts.emplace(p.first, p.second.term.id);
}
for (Id n : p.second.term.nexts()) {
allPrevs[n].push_back(p.first);
}
}
for (const auto &p : allPrevs) {
if (p.second.size() == 1) {
singlePrevs.emplace(p.first, p.second[0]);
}
}
vector<Id> sources;
for (const auto &p : singleNexts) sources.push_back(p.first);
unordered_set<Id> seen;
for (Id bid : sources) {
if (seen.count(bid) != 0) continue;
cerr << "source: " << bid << endl;
while (true) {
auto it = singlePrevs.find(bid);
if (it == singlePrevs.end()) break;
if (singleNexts.find(it->second) == singleNexts.end()) break;
bid = it->second;
}
vector<Id> chain;
while (true) {
chain.push_back(bid);
seen.insert(bid);
auto it = singleNexts.find(bid);
if (it == singleNexts.end()) break;
if (singlePrevs.find(it->second) == singlePrevs.end()) break;
bid = it->second;
}
if (chain.size() == 1) continue;
mergeChain(ifunc, chain);
}
}
static void deadCode(IFunc &ifunc) {
unordered_set<Id> reachable;
queue<Id> q;
q.push(0);
while (q.size() > 0) {
Id id = q.front(); q.pop();
reachable.insert(id);
for (Id n : ifunc.BBs[id].term.nexts()) {
if (reachable.count(n) == 0) {
q.push(n);
}
}
}
vector<Id> unreachable;
for (const auto &p : ifunc.BBs) {
if (reachable.count(p.first) == 0) {
unreachable.push_back(p.first);
}
}
for (Id id : unreachable) {
ifunc.BBs.erase(ifunc.BBs.find(id));
}
}
static void optimise(IFunc &ifunc) {
mergeBlocks(ifunc);
deadCode(ifunc);
}
void optimise(IR &ir) {
for (auto &p : ir.funcs) {
optimise(p.second);
}
}
| true |
9caae389daaa6bf38e57ca1b99173491d3c8eeb5 | C++ | liufei-go/training | /python/datetime.cpp | UTF-8 | 6,730 | 3.453125 | 3 | [] | no_license | #include "datetime.h"
#include <iostream>
namespace {
enum {
JAN = 1,
FEB = 2,
MAR = 3,
APR = 4,
MAY = 5,
JUN = 6,
JUL = 7,
AUG = 8,
SEP = 9,
OCT = 10,
NOV = 11,
DEC = 12,
DAYS_NOT_IN_LEAP_YEAR = 365,
DAYS_IN_LEAP_YEAR = 366
};
const int DAYS_IN_EACH_MONTH[] =
{
31,
28,
31,
30,
31,
30,
31,
31,
30,
31,
30,
31
};
bool is_leap_year(const int year)
{
if (year % 4 == 0)
{
if (year % 100 == 0)
{
if (year % 400 == 0)
{
return true;
}
else
{
return false;
}
}
else
{
return true;
}
}
else
{
return false;
}
}
bool is_month_30(const int month)
{
if (month == APR ||
month == JUN ||
month == SEP ||
month == NOV)
{
return true;
}
else
{
return false;
}
}
bool is_valid_date(const int month, const int day, const int year)
{
if (month < JAN || month > DEC)
{
return false;
}
if (day < 1 || day > 31)
{
return false;
}
if (year < 0)
{
return false;
}
if (is_month_30(month))
{
if (day > 30)
{
return false;
}
}
if (month == FEB)
{
if (is_leap_year(year))
{
if (day > 29)
{
return false;
}
}
else
{
if (day > 28)
{
return false;
}
}
}
return true;
}
void invalid_date_log_error(const int month, const int day, const int year)
{
std::cerr << "Invalid date: month " << month
<< " day " << day
<< " year " << year << std::endl;
}
}
// End of anonymous namespace
Date::Date(const int month, const int day, const int year)
{
if (is_valid_date(month, day, year))
{
m_month = month;
m_day = day;
m_year = year;
m_serialDate = date_to_number(*this);
}
else
{
invalid_date_log_error(month, day, year);
reset();
}
}
Date::Date(const int date_yyyymmdd)
{
if (date_yyyymmdd <= 10000000)
{
reset();
return;
}
int year = date_yyyymmdd % 10000;
int month = (date_yyyymmdd - year * 10000) % 100;
int day = date_yyyymmdd - year * 10000 - month * 100;
set_date(month, day, year);
}
Date::Date(const Date& date)
{
m_month = date.month();
m_day = date.day();
m_year = date.year();
m_serialDate = date_to_number(*this);
}
Date Date::operator=(const Date& date)
{
m_month = date.month();
m_day = date.day();
m_year = date.year();
m_serialDate = date_to_number(*this);
return *this;
}
Date Date::operator+(const int n)
{
Date date;
if (!this->is_valid())
{
std::cerr << "Input date is invalid" << std::endl;
return date;
}
int& num = this->m_serialDate;
num += n;
return number_to_date(num);
}
Date Date::operator-(const int n)
{
Date date;
if (!this->is_valid())
{
std::cerr << "Input date is invalid" << std::endl;
return date;
}
int& num = this->m_serialDate;
num -= n;
return number_to_date(num);
}
Date& Date::operator++()
{
*this = number_to_date(this->m_serialDate + 1);
return *this;
}
Date Date::operator++(int)
{
Date temp(*this);
operator++();
return temp;
}
Date& Date::operator--()
{
*this = number_to_date(this->m_serialDate - 1);
return *this;
}
Date Date::operator--(int)
{
Date temp(*this);
operator--();
return temp;
}
std::ostream& operator<< (std::ostream& os, const Date& date)
{
os << date.month() << "/" << date.day() << "/" << date.year();
return os;
}
bool operator<(const Date& date1, const Date& date2)
{
return (date1.date_to_yyyymmdd() < date2.date_to_yyyymmdd());
}
bool operator>(const Date& date1, const Date& date2)
{
return (date1.date_to_yyyymmdd() > date2.date_to_yyyymmdd());
}
bool operator==(const Date& date1, const Date& date2)
{
return (date1.date_to_yyyymmdd() == date2.date_to_yyyymmdd());
}
void Date::set_date(const int month, const int day, const int year)
{
if (is_valid_date(month, day, year))
{
m_month = month;
m_day = day;
m_year = year;
m_serialDate = date_to_number(*this);
}
else
{
invalid_date_log_error(month, day, year);
reset();
}
}
bool Date::is_valid() const
{
return is_valid_date(m_month, m_day, m_year);
}
int Date::date_to_yyyymmdd() const
{
int date_yyyymmdd = 0;
if (!is_valid())
{
return 0;
}
date_yyyymmdd += m_year * 10000;
date_yyyymmdd += m_month * 100;
date_yyyymmdd += m_day;
return date_yyyymmdd;
}
void Date::reset()
{
m_month = 0;
m_day = 0;
m_year = 0;
m_serialDate = 0;
}
int Date::date_to_number(const Date& date)
{
int m = date.month();
int d = date.day();
int y = date.year() - 1;
int num = 0;
num += DAYS_NOT_IN_LEAP_YEAR * y + y /4 - y / 100 + y / 400;
for (size_t i = 0; i < m - 1; ++i)
{
num += DAYS_IN_EACH_MONTH[i];
}
num += d;
if (is_leap_year(y + 1) && m > FEB)
{
++num;
}
return num;
}
Date Date::number_to_date(const int number)
{
Date date;
int year = number / DAYS_NOT_IN_LEAP_YEAR - 1;
int remainder = number - (365 * year + year / 4 - year / 100 + year / 400);
if (remainder < 0)
{
--year;
remainder = number - (365 * year + year / 4 - year / 100 + year / 400);
}
++year;
int month = 0;
int day = 0;
int num = 0;
for (size_t i = 0; i < DEC; ++i)
{
int increment = DAYS_IN_EACH_MONTH[i];
if (is_leap_year(year))
{
if (i == FEB - 1)
{
++increment;
}
}
num += increment;
if (num > remainder)
{
month = i + 1;
day = remainder - (num - increment);
break;
}
}
date.set_date(month, day, year);
return date;
}
| true |
cf9cab4633a6e85452a300c5ad290af303c468f9 | C++ | shahril96/snippets | /algorithm-related/articulation_point.cpp | UTF-8 | 2,479 | 2.65625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
/**
Input :
7 8
0 1 1
1 2 1
2 0 1
1 3 1
1 4 1
1 6 1
3 5 1
4 5 1
Output :
List of all articulation points :
1
Input :
4 4
1 2 1
2 3 1
4 3 1
4 2 1
Output :
List of all articulation points :
2
**/
typedef vector<int> vi;
typedef pair<int, int> ii;
typedef map<int, multiset<ii> > adj_list;
typedef vector<ii> vii;
typedef map<int, int> mii;
map<int, set<ii > > graph;
mii dfs_low, dfs_num, parent;
map<int, bool> ap;
set<int> vertices, visited;
void articulation_p(int u) {
static int time = 0;
int child = 0; // count number of childs in DFS tree (not normal tree)
visited.insert(u);
dfs_low[u] = dfs_num[u] = ++time;
for(ii vp : graph[u]) {
int v = vp.first;
// if forward-edge
if(visited.find(v) == visited.end()) {
child++; // count number of unvisited child with parent of `u`
parent[v] = u;
articulation_p(v);
// check if subtree rooted with `v` (child of `u`)
// have dfs_low lower than dfs_low of `u`
dfs_low[u] = min(dfs_low[u], dfs_low[v]);
// find articulation for below 2 cases
// 1) if `u` is root and has more than one childs in DFS tree
if(parent[u] == -1 && child > 1)
ap[u] = true;
// 2) if `u` is not root, and dfs_low time of its child
// is more than or eq to the discovery time of itself
if(parent[u] != -1 && dfs_low[v] >= dfs_num[u])
ap[u] = true;
// if back-edge
// v != parent[u] is to ignore back-edge to the parent node (undirected node)
} else if (v != parent[u])
dfs_low[u] = min(dfs_low[u], dfs_num[v]);
}
}
int main() {
int v, e;
cin >> v >> e;
while(e --> 0) {
int u, v, w;
cin >> u >> v >> w;
vertices.insert(u); vertices.insert(v);
graph[u].insert(make_pair(v, w));
graph[v].insert(make_pair(u, w));
}
// find all articulation point on all connected components
for(int i = 0; i < vertices.size(); i++) {
if(visited.find(i) == visited.end()) {
parent[i] = -1;
articulation_p(i);
}
}
cout << "List of all articulation points : \n";
for(int i = 0; i < vertices.size(); i++) {
if(ap[i] == true) {
cout << i << endl;
}
}
}
| true |
f560ef13f1d45e5a297890473c092264af370c74 | C++ | wu-zero/MyWebServer | /tests/TestTcpServer.cpp | UTF-8 | 671 | 2.578125 | 3 | [] | no_license | /// \file TestTcpServer.cpp
///
/// Tcp服务端测试
///
/// \author wyw
/// \version 1.0
/// \date 2020/4/15.
#include <iostream>
#include "EventLoop.h"
#include "TcpServer.h"
#include "ConnectionManager.h"
using SPtrTcpConnection = std::shared_ptr<TcpConnection>;
// 接收socket后的回调
static void onMessage(const SPtrTcpConnection &sPtrTcpConnection, Buffer *pBuf){
std::string message = pBuf->retrieveAllAsString();
std::cout << "onMessage: " << message << std::endl;
}
int main()
{
EventLoop loop;
TcpServer<> myTcpServer(&loop);
myTcpServer.start();
myTcpServer.setMessageCallback(onMessage);
loop.loop();
return 0;
}
| true |
1536854f302084372ac0ca458e8079d9d064ec6c | C++ | sanjnair/projects | /university/usc_csci_565_compiler_design/Project4/adjlist.h | UTF-8 | 1,605 | 2.625 | 3 | [
"MIT"
] | permissive | #if !defined __adjlist_H__
#define __adjlist_H__
#include "adjmatrix.h"
//forward declare the class
class AdjList;
typedef std::vector<AdjList> AdjListVector;
typedef std::list<my_simple_reg> MyRegList;
/**
* Encapsulates the adjlist of the node
*/
class AdjList {
public:
/**
* Constructs a AdjList
*/
AdjList();
/**
* Destroys the adjlist
*/
~AdjList ();
/**
* Builds the adjacency list,
*/
static void build( const AdjMatrix &adjMatrix,
IntMap ®Map,
AdjListVector &adjVector );
/**
* returns true, if the item is in the reglist
*/
static bool isItemInRegList( const MyRegList &list,
const my_simple_reg ® );
/**
* Returns the position of the item in the adjvector
*/
static int getPos( const AdjListVector &adjVector,
const my_simple_reg ® );
/**
* removes the item form the list
*/
static void removeItemFromList( MyRegList &list,
const my_simple_reg ® );
/**
* returns true, if the regs are equal
*/
static bool isRegEqual( const my_simple_reg ®1,
const my_simple_reg ®2 );
/**
* prints the lower triangular matrix
*/
static void print( const AdjListVector &adjVector,
FILE *fd );
//----------------------------------------------------
my_simple_reg _reg;
int _nints;
int _color;
int _disp;
float _spcost;
bool _spill;
MyRegList _adjnds;
MyRegList _rmvadj;
};
#endif //__adjlist_H__
| true |
9f8d59f108ca63a5cf1ee8cf370485a3b6684d6a | C++ | CNU-ANT/1st-Thinking-PC | /B/sub/datagen.cpp | UTF-8 | 1,087 | 2.90625 | 3 | [] | no_license | #include <cassert>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int score(int a, int b) {
return a==b ? 100 + a : (a + b) % 10;
}
void createData(int a, int b, string filename) {
assert(1 <= a && a <= 10);
assert(1 <= b && b <= 10);
int cnt[11];
for (int x=1; x<=10; x++) cnt[x] = 2;
cnt[a]--;
cnt[b]--;
vector<int> cards;
for (int x=1; x<=10; x++)
while (cnt[x]--)
cards.push_back(x);
assert(cards.size() == 18);
int winCount = 0;
for (int i=0; i<cards.size(); i++) for (int j=i+1; j<cards.size(); j++) {
int aa = cards[i];
int bb = cards[j];
if (score(a, b) > score(aa, bb))
winCount++;
}
double ans = (double)winCount / 153;
FILE *in = fopen((filename + ".in").data(), "w");
fprintf(in, "%d %d\n", a, b);
FILE *out = fopen((filename + ".out").data(), "w");
fprintf(out, "%.3f\n", ans);
}
int main() {
int i = 1;
for (int a=1; a<=10; a++) for (int b=a; b<=10; b++) {
char tmp[123];
itoa(i++, tmp, 10);
createData(a, b, tmp);
}
return 0;
} | true |
99fe0c12b0d37c833cb834bc40eff5854d756a03 | C++ | vvim/pdfcutter | /pagerangelistwidgetitem.cpp | UTF-8 | 2,232 | 2.71875 | 3 | [] | no_license | #include "pagerangelistwidgetitem.h"
PageRangeListWidgetItem::PageRangeListWidgetItem() : QListWidgetItem()
{
start=0;
end=0;
}
int PageRangeListWidgetItem::getPageRangeStart_int()
{
return start;
}
QString PageRangeListWidgetItem::getPageRangeStart_qstring()
{
QString ret;
return ret.setNum(start);
}
int PageRangeListWidgetItem::getPageRangeEnd_int()
{
return end;
}
QString PageRangeListWidgetItem::getPageRangeEnd_qstring()
{
QString ret;
return ret.setNum(end);
}
void PageRangeListWidgetItem::setPageRangeStart(int pagerangestart)
{
start = pagerangestart;
setData( LIST_ITEM_DATA_START ,pagerangestart);
}
void PageRangeListWidgetItem::setPageRangeEnd(int pagerangeend)
{
end = pagerangeend;
setData( LIST_ITEM_DATA_END ,pagerangeend);
}
QString PageRangeListWidgetItem::getPDFtkPageRange(QString param)
{
return QString(param + getPageRangeStart_qstring() + "-" + getPageRangeEnd_qstring());
}
void PageRangeListWidgetItem::setChapterNaming(chapternaming cn)
{
chaptername = cn;
}
QString PageRangeListWidgetItem::getNameBookTitle()
{
return chaptername.booktitle;
}
QString PageRangeListWidgetItem::getNameStudentLevel()
{
return chaptername.studentlevel;
}
QString PageRangeListWidgetItem::getNameChapter()
{
return chaptername.chapter;
}
QString PageRangeListWidgetItem::getNameManualType()
{
return chaptername.manualtype;
}
QString PageRangeListWidgetItem::getNamePagerange()
{
return chaptername.pagerange;
}
int PageRangeListWidgetItem::getPagerangeStart()
{
/*
if ui->NamePageRange->text() is of the type p<int>-<int>
return <int>
else
*/
return chaptername.pagerange_start;
}
int PageRangeListWidgetItem::getPagerangeEnd()
{
/*
if ui->NamePageRange->text() is of the type p<int>-<int>
return <int>
else
*/
return chaptername.pagerange_end;
}
QString PageRangeListWidgetItem::getChaptertoString()
{
return chaptername.booktitle + " " + chaptername.studentlevel + " " + chaptername.manualtype + " " + chaptername.chapter + " " + chaptername.pagerange;
}
| true |
9de6fc6b94915a9e24aea8422f13a02cda01db40 | C++ | Buwaka/PNG-Encoder-and-Decoder | /PNG Encoder and Decoder/Source.cpp | UTF-8 | 954 | 2.875 | 3 | [] | no_license | #include "pch.h"
#include <iostream>
#include <string>
#include <fstream>
#include "PNG.h"
#include "PPM.h"
int main()
{
std::wstring input;
std::cout << "PNG file to read (with extension, type 'END' to terminate program): ";
std::getline(std::wcin, input);
while (input != L"END")
{
PNG copy(input);
std::vector<pixel8> temp = copy.GetPixels();
//ppm test
PPM ppm(input + L".ppm", temp, copy.GetWidth(), copy.GetHeight());
std::cout << "\nWrote ppm file.";
copy.Write(input + L"_copy.png");
std::wcout << L"\nWrote png straight from copied in data stream. " + input + L"_copy.png";
PNG newpng;
newpng.ReadPixels(temp, copy.GetWidth(), copy.GetHeight());
newpng.Write(input + L"_scratch.png");
std::wcout << L"\nWrote png from raw rgb values. " + input + L"_scratch.png";
std::cout << "\nPNG file to read (with extension, type 'END' to terminate program): ";
std::getline(std::wcin, input);
}
} | true |
7d093b79559d830577eebe33e2c40d62a1ff9349 | C++ | berherremans/pannenkoeken | /Body.h | UTF-8 | 9,154 | 3.6875 | 4 | [] | no_license | #ifndef BODY_H
#define BODY_H
#include <cmath>
#include <vector>
double G = 1.;
// klasse die vectoren in 3D voorstelt
class Vec {
private:
double x;
double y;
double z;
public:
Vec() { x = 0; y = 0; z = 0; }
Vec(double x, double y, double z) { this->x = x; this->y = y; this->z = z; }
void setx(double x) { this->x = x; }
void sety(double y) { this->y = y; }
void setz(double z) { this->z = z; }
double getx() { return x; }
double gety() { return y; }
double getz() { return z; }
double norm() const { return sqrt(x*x + y*y + z*z); }
double norm2() const { return x*x + y*y + z*z; }
double norm3() const { double r = sqrt(x*x + y*y + z*z); return r*r*r; }
Vec& operator+=(Vec v) {
x += v.x;
y += v.y;
z += v.z;
return *this;
}
Vec& operator-=(Vec v) {
x -= v.x;
y -= v.y;
z -= v.z;
return *this;
}
Vec& operator*=(double s) {
x *= s;
y *= s;
z *= s;
return *this;
}
Vec& operator/=(double s) {
x /= s;
y /= s;
z /= s;
return *this;
}
};
// operations between two vectors
Vec operator+(Vec a, Vec b) { return a += b; }
Vec operator-(Vec a, Vec b) { return a -= b; }
// operations between a vector and a scalar
Vec operator*(Vec a, double s) { return a *= s; }
Vec operator*(double s, Vec b) { return b *= s; }
Vec operator/(Vec a, double s) { return a /= s; }
// klasse die de gradiënt van een body in de faseruimte voorstelt
// (basicly gewoon een vector met 6 componenten)
class Grad {
private:
Vec position_grad;
Vec velocity_grad;
public:
// basisconstructor: nulgradiënt
Grad() { position_grad = Vec(); velocity_grad = Vec(); }
// constructor waarin positie- en snelheidsgradiënt worden meegegeven
Grad(Vec pos_grad, Vec vel_grad) {
position_grad = pos_grad;
velocity_grad = vel_grad;
}
void setpos_grad(Vec pos_grad) { position_grad = pos_grad; }
void setvel_grad(Vec vel_grad) { velocity_grad = vel_grad; }
Vec getpos_grad() { return position_grad; }
Vec getvel_grad() { return velocity_grad; }
Grad& operator+=(Grad g) {
position_grad += g.position_grad;
velocity_grad += g.velocity_grad;
return *this;
}
Grad& operator-=(Grad g) {
position_grad -= g.position_grad;
velocity_grad -= g.velocity_grad;
return *this;
}
Grad& operator*=(double s) {
position_grad *= s;
velocity_grad *= s;
return *this;
}
Grad& operator/=(double s) {
position_grad /= s;
velocity_grad /= s;
return *this;
}
};
// operations between two gradients
Grad operator+(Grad a, Grad b) { return a += b; }
Grad operator-(Grad a, Grad b) { return a -= b; }
// operations between a gradient and a scalar
Grad operator*(Grad a, double s) { return a *= s; }
Grad operator*(double s, Grad b) { return b *= s; }
Grad operator/(Grad a, double s) { return a /= s; }
// klasse die de ogenblikkelijke toestand van een lichaam voorselt
class Body {
private:
Vec position;
Vec velocity;
double mass;
public:
// basisconstructor: stilstaand deeltje in de oorsprong met massa = 1
Body() { position = Vec(); velocity = Vec(); mass = 1; }
// constructor waarin alle componenten van de positie en de snelheid, en de massa worden meegegeven
Body(double rx, double ry, double rz, double vx, double vy, double vz, double m) {
position = Vec(rx, ry, rz);
velocity = Vec(vx, vy, vz);
mass = m;
}
void setpos(Vec pos) { position = pos; }
void setvel(Vec vel) { velocity = vel; }
void setmass(double M) { mass = M; }
Vec getpos() { return position; }
Vec getvel() { return velocity; }
double getmass() { return mass; }
// bewerkingen om een gradiënt bij een body op te tellen: evolutie in de faseruimte
Body& operator+=(Grad g) {
position += g.getpos_grad();
velocity += g.getvel_grad();
return *this;
}
Body& operator-=(Grad g) {
position -= g.getpos_grad();
velocity -= g.getvel_grad();
return *this;
}
};
// bewerkingen om een gradiënt bij een body op te tellen: evolutie in de faaseruimte
Body operator+(Body b, Grad g) { return b += g; }
Body operator+(Grad g, Body b) { return b += g; }
Body operator-(Body b, Grad g) { return b -= g; }
// nu een heleboel operatoren om bewerkingen op vectoren van de klassen hierboven uit te voeren
// operatoren om 2 vectoren met als elementen Vec op te tellen en af te trekken
std::vector<Vec> operator+(std::vector<Vec> a, std::vector<Vec> b) {
std::vector<Vec> c;
for (unsigned int i = 0; i < a.size(); i++) {
c.push_back(a[i] + b[i]);
}
return c;
}
std::vector<Vec> operator-(std::vector<Vec> a, std::vector<Vec> b) {
std::vector<Vec> c;
for (unsigned int i = 0; i < a.size(); i++) {
c.push_back(a[i] - b[i]);
}
return c;
}
// operator om een vector met als elementen Vec te vermenigvuldigen met een getal
std::vector<Vec> operator*(double a, std::vector<Vec> b) {
std::vector<Vec> c;
for (unsigned int i = 0; i < b.size(); i++) {
c.push_back(a*b[i]);
}
return c;
}
std::vector<Vec> operator*(std::vector<Vec> b, double a) {
std::vector<Vec> c;
for (unsigned int i = 0; i < b.size(); i++) {
c.push_back(a*b[i]);
}
return c;
}
// operatoren om 2 vectoren met als elementen Grad op te tellen en af te trekken
std::vector<Grad> operator+(std::vector<Grad> a, std::vector<Grad> b) {
std::vector<Grad> c;
for (unsigned int i = 0; i < a.size(); i++) {
c.push_back(a[i] + b[i]);
}
return c;
}
std::vector<Grad> operator-(std::vector<Grad> a, std::vector<Grad> b) {
std::vector<Grad> c;
for (unsigned int i = 0; i < a.size(); i++) {
c.push_back(a[i] - b[i]);
}
return c;
}
// operatoren om een vector met als elementen Grad te vermenigvuldigen met een getal
std::vector<Grad> operator*(double a, std::vector<Grad> b) {
std::vector<Grad> c;
for (unsigned int i = 0; i < b.size(); i++) {
c.push_back(a*b[i]);
}
return c;
}
std::vector<Grad> operator*(std::vector<Grad> b, double a) {
std::vector<Grad> c;
for (unsigned int i = 0; i < b.size(); i++) {
c.push_back(a*b[i]);
}
return c;
}
// operatoren om 2 vectoren met als elementen Body en Grad op te tellen en af te trekken
std::vector<Body> operator+(std::vector<Body> a, std::vector<Grad> b) {
std::vector<Body> c;
for (unsigned int i = 0; i < a.size(); i++) {
c.push_back(a[i] + b[i]);
}
return c;
}
std::vector<Body> operator-(std::vector<Body> a, std::vector<Grad> b) {
std::vector<Body> c;
for (unsigned int i = 0; i < a.size(); i++) {
c.push_back(a[i] - b[i]);
}
return c;
}
std::vector<Body> operator+(std::vector<Grad> b, std::vector<Body> a) {
std::vector<Body> c;
for (unsigned int i = 0; i < a.size(); i++) {
c.push_back(a[i] + b[i]);
}
return c;
}
// en nu de fysica
// gegeven een lijst (vector) van body's, geeft de versnelling terug die elke body ondervindt
std::vector<Vec> calc_accel(std::vector<Body> points) {
// initialiseren van een lijst met N lege versnellingsvectoren
std::vector<Vec> accel;
// alle body's overlopen en de versnelling berekenen door te itereren over de andere body's
for (unsigned int i = 0; i < points.size(); i++) {
Vec a = Vec();
for (unsigned int j = 0; j < points.size(); j++) {
if (i != j) {
a -= points[j].getmass() * (points[i].getpos() - points[j].getpos()) / (points[i].getpos() - points[j].getpos()).norm3();
}
}
a *= G;
accel.push_back(a);
}
return accel;
}
// berekenen van de totale energie gegeven een lijst van alle body's
double calc_ener(std::vector<Body> points) {
double ener_kin = 0;
double ener_pot = 0;
for (unsigned int i = 0; i < points.size(); i++) {
ener_kin += points[i].getmass() * points[i].getvel().norm2();
for (unsigned int j = 0; j < points.size(); j++) {
if (i != j) {
ener_pot -= points[i].getmass() * points[j].getmass() / (points[i].getpos() - points[j].getpos()).norm();
}
}
}
ener_kin *= 0.5;
ener_pot *= 0.5 * G;
return ener_kin + ener_pot;
}
// berekenen van de totale gradiënt (vector met als elementen de gradiënt van elk deeltje)
// van het systeem gegeven de configuratie van het systeem (vector met als elementen de lichamen)
std::vector<Grad> calc_grad(std::vector<Body> bodies) {
std::vector<Grad> g;
std::vector<Vec> accelerations = calc_accel(bodies);
for (unsigned int i = 0; i < bodies.size(); i++) {
// voor de posities is g gewoon de snelheid
g.push_back(Grad(bodies[i].getvel(), accelerations[i]));
}
return g;
}
// berekenen van de verschillende k's voor de Runge-Kutta methoden
std::vector<Vec> calc_k(std::vector<Vec> y, std::vector<double> mass, double h) {
std::vector<Vec> g;
for (unsigned int i = 0; i < mass.size(); i++) {
// voor de posities is g gewoon de snelheid
g.push_back(y[2 * i + 1]);
// voor de snelheden wordt dit de versnelling
Vec a = Vec();
for (unsigned int j = 0; j < mass.size(); j++) {
if (i != j) {
a -= mass[j] * (y[2*i] - y[2*j]) / (y[2*i] - y[2*j]).norm3();
}
}
a *= G;
g.push_back(a);
}
return h*g;
}
#endif BODY_H
| true |
a41538cb0f2132f6243fb46cb8e285092ccd36ad | C++ | LiHai1997/418a4 | /src/insert_triangle_into_box.cpp | UTF-8 | 1,664 | 3.015625 | 3 | [] | no_license | #include "insert_triangle_into_box.h"
#include <iostream>
void insert_triangle_into_box(
const Eigen::RowVector3d & a,
const Eigen::RowVector3d & b,
const Eigen::RowVector3d & c,
BoundingBox & B)
{
////////////////////////////////////////////////////////////////////////////
// Add your code here
float min_x,min_y,min_z,max_x,max_y,max_z;
if (a(0) < b(0) && a(0) < c(0))
{
min_x = a(0);
}else if (b(0) < c(0))
{
min_x = b(0);
}else
{
min_x = c(0);
}
if (a(1) < b(1) && a(1) < c(1))
{
min_y = a(1);
}else if (b(1) < c(1))
{
min_y = b(1);
}else
{
min_y = c(1);
}
if (a(2) < b(2) && a(2) < c(2))
{
min_z = a(2);
}else if (b(2) < c(2))
{
min_z = b(2);
}else
{
min_z = c(2);
}
if (a(0) > b(0) && a(0) > c(0))
{
max_x = a(0);
}else if (b(0) > c(0))
{
max_x = b(0);
}else
{
max_x = c(0);
}
if (a(1) > b(1) && a(1) > c(1))
{
max_y = a(1);
}else if (b(1) > c(1))
{
max_y = b(1);
}else
{
max_y = c(1);
}
if (a(2) > b(2) && a(2) > c(2))
{
max_z = a(2);
}else if (b(2) > c(2))
{
max_z = b(2);
}else
{
max_z = c(2);
}
if (B.min_corner(0) >= min_x)
{
B.min_corner(0) = min_x;
}
if (B.min_corner(1) >= min_y)
{
B.min_corner(1) = min_y;
}
if (B.min_corner(2) >= min_z)
{
B.min_corner(2) = min_z;
}
if (B.max_corner(0) <= max_x)
{
B.max_corner(0) = max_x;
}
if (B.max_corner(1) <= max_y)
{
B.max_corner(1) = max_y;
}
if (B.max_corner(2) <= max_z)
{
B.max_corner(2) = max_z;
}
////////////////////////////////////////////////////////////////////////////
}
| true |
6404c57f7f2c546de3b89845c6a6f3923cd97d9d | C++ | mazen930/Paint-for-kids | /Figures/CRectangle.cpp | UTF-8 | 3,244 | 3.15625 | 3 | [] | no_license | #include "CRectangle.h"
CRectangle::CRectangle(Point P1, Point P2, GfxInfo FigureGfxInfo):CFigure(FigureGfxInfo)
{
Corner1 = P1;
Corner2 = P2;
length=Corner2.y-Corner1.y;
width=Corner2.x-Corner1.x;
centre.x=(Corner1.x+Corner2.x)/2;
centre.y=(Corner1.y+Corner2.y)/2;
}
void CRectangle::Rotates()
{
double center_x = (double)(Corner1.x + Corner2.x) / 2.00000;
double center_y = (double)(Corner1.y + Corner2.y) / 2.00000;
Corner1.x = (double)Corner1.x- center_x;
Corner1.y = (double)Corner1.y- center_y;
Corner2.x = (double)Corner2.x- center_x;
Corner2.y = (double)Corner2.y- center_y;
int x_temp = Corner1.x;
int y_temp = Corner1.y;
Corner1.x = -y_temp;
Corner1.y = x_temp;
x_temp = Corner2.x;
y_temp = Corner2.y;
Corner2.x = -y_temp;
Corner2.y = x_temp;
Corner1.x = (double)Corner1.x+ center_x;
Corner1.y = (double)Corner1.y+ center_y;
Corner2.x = (double)Corner2.x+ center_x;
Corner2.y = (double)Corner2.y+ center_y;
}
CRectangle::CRectangle(GfxInfo FigureGfxInfo ):CFigure(FigureGfxInfo)
{
}
bool CRectangle::InsideMe(int a,int b)const
{
if(Corner1.x>Corner2.x&&Corner1.y>Corner2.y)
{
if(a>=Corner2.x&&a<=Corner1.x&&b>=Corner2.y&&b<=Corner1.y)
{
return true;
}
}
else if(Corner1.x>Corner2.x&&Corner1.y<=Corner2.y)
{
if(a>=Corner2.x&&a<=Corner1.x&&b<=Corner2.y&&b>=Corner1.y)
{
return true;
}
}
else if(Corner1.x<=Corner2.x&&Corner1.y>Corner2.y)
{
if(a<=Corner2.x&&a>=Corner1.x&&b>=Corner2.y&&b<=Corner1.y)
{
return true;
}
}
else if(Corner1.x<=Corner2.x&&Corner1.y<=Corner2.y)
{
if(a<=Corner2.x&&a>=Corner1.x&&b<=Corner2.y&&b>=Corner1.y)
{
return true;
}
}
return false;
}
void CRectangle::Draw(Output* pOut) const
{
//Call Output::DrawRect to draw a rectangle on the screen
pOut->DrawRect(Corner1, Corner2, FigGfxInfo, Selected);
}
CFigure*CRectangle::copy()
{
CFigure*c=new CRectangle(Corner1,Corner2,FigGfxInfo);
return c;
}
void CRectangle::Transfer(Point To,Point Major)
{
//getting coordinates diffrences
int X_diff=Major.x-centre.x;
int Y_diff=Major.y-centre.y;
centre.x=To.x-X_diff; centre.y=To.y-Y_diff;
//allocating the position of the 2 corners to each other
if((Corner1.x>Corner2.x)&&(Corner1.y>Corner2.y))
{
Corner1.x=centre.x-width/2;
Corner1.y=centre.y-length/2;
Corner2.x=centre.x+width/2;
Corner2.y=centre.y+length/2;
}
else
{
Corner1.x=centre.x+width/2;
Corner1.y=centre.y-length/2;
Corner2.x=centre.x-width/2;
Corner2.y=centre.y+length/2;
}
}
void CRectangle::PrintInfo(Output*pOut)
{
int height=abs(Corner1.y-Corner2.y);
int width=abs(Corner1.x-Corner2.x);
pOut->PrintMessage("Rectangle->ID="+to_string(ID)+",Height="+to_string(height)+",Width="+to_string(width));
}
void CRectangle::Save(ofstream &OutFile)
{
OutFile<<RECTANGLE<<'\t'<<ID<<'\t'<<Corner1.x<<'\t'<<Corner1.y<<'\t'<<Corner2.x<<'\t'<<Corner2.y<<'\t'
<<to_number(FigGfxInfo.DrawClr)<<'\t';
if( FigGfxInfo.isFilled == false )
OutFile<<-1;
else
OutFile<<to_number(FigGfxInfo.FillClr);
OutFile<<'\n';
}
bool CRectangle::Load(ifstream &Infile)
{
Infile>>ID>>Corner1.x>>Corner1.y>>Corner2.x>>Corner2.y;
if( CFigure::Load(Infile) ) //to load draw & fill color
return true;
else
return false;
}
| true |
edbcec439b7dfc7834dccd1b8bf8817426701d08 | C++ | guilhermess/algorithms | /list/list.ipp | UTF-8 | 8,539 | 2.734375 | 3 | [] | no_license | /*
MIT License
Copyright (c) 2021 Guilherme Simoes Schlinker
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <list/list.h>
namespace list {
namespace detail {
template<typename T>
struct ListNode<T, ListLinkType::Single> {
template <typename U>
ListNode(U &&d, ListNode<T, ListLinkType::Single> *n) : data{std::forward<U>(d)}, next{n}
{}
T data;
ListNode<T, ListLinkType::Single> *next;
};
template<typename T>
struct ListNode<T, ListLinkType::Double> {
template <typename U>
ListNode(U &&d,
ListNode<T, ListLinkType::Double> *n,
ListNode<T, ListLinkType::Double> *p) : data{std::forward<U>(d)}, next{n}, prev{p}
{}
T data;
ListNode<T, ListLinkType::Double> *next;
ListNode<T, ListLinkType::Double> *prev;
};
}
template<typename T, detail::ListLinkType type, typename NodeType>
List<T, type, NodeType>::List() : head_{nullptr}, size_{0} {
}
//TODO implement copy constructor: deep copy nodes
template<typename T, detail::ListLinkType type, typename NodeType>
List<T, type, NodeType>::List(List const &other) {
}
template<typename T, detail::ListLinkType type, typename NodeType>
List<T, type, NodeType>::List(List &&other) : head_{std::move(other.head_)}, size_{std::move(other.size_)} {
}
template<typename T, detail::ListLinkType type, typename NodeType>
template<typename U>
void List<T, type, NodeType>::emplace_front(U &&value) {
if constexpr (type == detail::ListLinkType::Single) {
NodeType *node{new NodeType(std::forward<T>(value), head_)};
head_ = node;
} else {
NodeType *node{new NodeType(std::forward<T>(value), head_, nullptr)};
if (head_) head_->prev = node;
head_ = node;
}
++size_;
}
template<typename T, detail::ListLinkType type, typename NodeType>
template<typename U>
void List<T, type, NodeType>::emplace_back(U &&value) {
NodeType **noderef = &head_;
NodeType *nodeprev = nullptr;
while (*noderef) {
nodeprev = *noderef;
noderef = &(*noderef)->next;
}
if constexpr (type == detail::ListLinkType::Single) {
NodeType *newnode{new NodeType(std::forward<T>(value), nullptr)};
*noderef = newnode;
} else {
NodeType *newnode{new NodeType(std::forward<T>(value), nullptr, nodeprev)};
*noderef = newnode;
if (nodeprev)
nodeprev->next = newnode;
}
++size_;
}
template<typename T, detail::ListLinkType type, typename NodeType>
T &List<T, type, NodeType>::front() {
return head_->data;
}
template<typename T, detail::ListLinkType type, typename NodeType>
T &List<T, type, NodeType>::back() {
NodeType *node = head_;
while(node && node->next)
node = node->next;
return node->data;
}
template<typename T, detail::ListLinkType type, typename NodeType>
const T &List<T, type, NodeType>::front() const {
return head_->data;
}
template<typename T, detail::ListLinkType type, typename NodeType>
const T &List<T, type, NodeType>::back() const {
NodeType *node = head_;
while(node && node->next)
node = node->next;
return node->data;
}
template<typename T, detail::ListLinkType type, typename NodeType>
void List<T, type, NodeType>::pop_front() {
auto node = head_;
head_ = node->next;
if constexpr (type == detail::ListLinkType::Double) {
if (head_) head_->prev = nullptr;
}
--size_;
delete node;
}
template<typename T, detail::ListLinkType type, typename NodeType>
void List<T, type, NodeType>::pop_back() {
NodeType **noderef = &head_;
while (*noderef && (*noderef)->next) {
noderef = &(*noderef)->next;
}
delete *noderef;
*noderef = nullptr;
--size_;
}
template<typename T, detail::ListLinkType type, typename NodeType>
NodeType *List<T, type, NodeType>::tail() const {
NodeType *node = head_;
while (node->next)
node = node->next;
return node;
}
template<typename T, detail::ListLinkType type, typename NodeType>
size_t List<T, type, NodeType>::size() const {
return size_;
}
template<typename T, detail::ListLinkType type, typename NodeType>
bool List<T, type, NodeType>::empty() const {
return size() == 0;
}
template<typename T, detail::ListLinkType type, typename NodeType>
void List<T, type, NodeType>::reverse() {
if constexpr (type == detail::ListLinkType::Single) {
NodeType *p = nullptr;
auto node = head_;
while (node) {
auto n = node->next;
node->next = p;
p = node;
node = n;
}
head_ = p;
} else {
auto node = head_;
NodeType *prev = nullptr;
while (node) {
prev = node;
std::swap(node->prev, node->next);
node = node->prev;
}
head_ = prev;
}
}
template<typename T, detail::ListLinkType type, typename NodeType>
template<bool is_const>
List<T, type, NodeType>::base_iterator<is_const>::base_iterator(list_type *list) : current_(list->head_) {
}
template<typename T, detail::ListLinkType type, typename NodeType>
template<bool is_const>
List<T, type, NodeType>::base_iterator<is_const>::base_iterator(NodeType *node) : current_{node} {}
template<typename T, detail::ListLinkType type, typename NodeType>
template<bool is_const>
List<T, type, NodeType>::base_iterator<is_const>::base_iterator() : current_{nullptr} {}
template<typename T, detail::ListLinkType type, typename NodeType>
template<bool is_const>
typename List<T, type, NodeType>::template base_iterator<is_const> &
List<T, type, NodeType>::base_iterator<is_const>::operator++() {
current_ = current_->next;
return *this;
}
template<typename T, detail::ListLinkType type, typename NodeType>
template<bool is_const>
typename List<T, type, NodeType>::template base_iterator<is_const>
List<T, type, NodeType>::base_iterator<is_const>::operator++(int) {
base_iterator <is_const> retval = *this;
++(*this);
return retval;
}
template<typename T, detail::ListLinkType type, typename NodeType>
template<bool is_const>
typename List<T, type, NodeType>::template base_iterator<is_const> &
List<T, type, NodeType>::base_iterator<is_const>::operator--() requires (type == detail::ListLinkType::Double) {
current_ = current_->prev;
return *this;
}
template<typename T, detail::ListLinkType type, typename NodeType>
template<bool is_const>
typename List<T, type, NodeType>::template base_iterator<is_const>
List<T, type, NodeType>::base_iterator<is_const>::operator--(int) requires (type == detail::ListLinkType::Double) {
base_iterator <is_const> retval = *this;
--(*this);
return retval;
}
template<typename T, detail::ListLinkType type, typename NodeType>
template<bool is_const>
bool
List<T, type, NodeType>::base_iterator<is_const>::operator==(const base_iterator &other) const {
return this->current_ == other.current_;
}
template<typename T, detail::ListLinkType type, typename NodeType>
template<bool is_const>
bool
List<T, type, NodeType>::base_iterator<is_const>::operator!=(const base_iterator &other) const {
return this->current_ != other.current_;
}
template<typename T, detail::ListLinkType type, typename NodeType>
template<bool is_const>
typename List<T, type, NodeType>::template base_iterator<is_const>::reference
List<T, type, NodeType>::base_iterator<is_const>::operator*() {
return current_->data;
}
} | true |
857a87b10921212fc445c29d6001f23ee0d6bdb6 | C++ | andrewminai24/EGR-030 | /Lab3/part4.cpp | UTF-8 | 485 | 3.03125 | 3 | [] | no_license | #include <iostream>
#include <iomanip>
using namespace std;
int main()
{
float num1, num2, num3, num4, num5, num6;
num1 = 12.42325;
num2 = 11.0;
num3 = 1252.2131;
num4 = 652.3;
num5 = 1.1;
num6 = 1.3;
cout << setprecision(2) << fixed;
cout << setw(9) << "List 1" << setw(9) << "list2" << endl;
cout << setw(9) << num1 << setw(9)<< num2 << endl;
cout << setw(9) << num3 << setw(9)<< num4 << endl;
cout << setw(9) << num5 << setw(9)<< num6 << endl;
}
| true |
b7286eefaef2270be471b84bb41a7553d090ba3f | C++ | bigfootone/GPCoursework | /GPCoursework/cSoundMgr.cpp | UTF-8 | 1,846 | 2.75 | 3 | [] | no_license | /*
==================================================================================
cSoundMgr.cpp
==================================================================================
*/
#include "cSoundMgr.h"
cSoundMgr* cSoundMgr::pInstance = NULL;
/*
=================================================================================
Constructor
=================================================================================
*/
cSoundMgr::cSoundMgr()
{
createContext();
}
/*
=================================================================================
Singleton Design Pattern
=================================================================================
*/
cSoundMgr* cSoundMgr::getInstance()
{
if (pInstance == NULL)
{
pInstance = new cSoundMgr();
}
return cSoundMgr::pInstance;
}
void cSoundMgr::createContext()
{
m_OALDevice = alcOpenDevice(NULL);
if (m_OALDevice)
{
//Create a context
m_OALContext = alcCreateContext(m_OALDevice, NULL);
//Set active context
alcMakeContextCurrent(m_OALContext);
}
}
void cSoundMgr::add(LPCSTR sndName, LPCSTR fileName)
{
if (!getSnd(sndName))
{
cSound * newSnd = new cSound();
newSnd->loadWAVFile(fileName);
gameSnds.insert(make_pair(sndName, newSnd));
}
}
cSound* cSoundMgr::getSnd(LPCSTR sndName)
{
map<LPCSTR, cSound*>::iterator snd = gameSnds.find(sndName);
if (snd != gameSnds.end())
{
return snd->second;
}
else
{
return NULL;
}
}
void cSoundMgr::deleteSnd()
{
for (map<LPCSTR, cSound*>::iterator snd = gameSnds.begin(); snd != gameSnds.end(); ++snd)
{
delete snd->second;
}
}
cSoundMgr::~cSoundMgr()
{
m_OALContext = alcGetCurrentContext();
//Get device for active context
m_OALDevice = alcGetContextsDevice(m_OALContext);
//Release context(s)
alcDestroyContext(m_OALContext);
//Close device
alcCloseDevice(m_OALDevice);
}
| true |
11da126c8a9c71f8ae691365ec0bd2ec923b4fab | C++ | opendarkeden/server | /src/Core/CGMoveHandler.cpp | UHC | 2,132 | 2.546875 | 3 | [] | no_license | //////////////////////////////////////////////////////////////////////////////
// Filename : CGMoveHandler.cpp
// Written By : reiot@ewestsoft.com , elca@ewestsoft.com
// Description :
//////////////////////////////////////////////////////////////////////////////
#include "CGMove.h"
#ifdef __GAME_SERVER__
#include "GamePlayer.h"
#include "Zone.h"
#include "ZoneUtil.h"
#include "Slayer.h"
#include "Effect.h"
#include "Timeval.h"
#include "skill/Sniping.h"
#endif
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
void CGMoveHandler::execute (CGMove* pPacket , Player* pPlayer)
{
__BEGIN_TRY __BEGIN_DEBUG_EX
#ifdef __GAME_SERVER__
Assert(pPacket != NULL);
Assert(pPlayer != NULL);
GamePlayer* pGamePlayer = dynamic_cast<GamePlayer*>(pPlayer);
if (pGamePlayer->getPlayerStatus() == GPS_NORMAL)
{
// ¿ ũó ǰ εǾ ϹǷ, NULL ƴϾ Ѵ.
// PLAYER_INGAME ü ũó ε Ǿ ǹѴ.
Creature* pCreature = pGamePlayer->getCreature();
Assert(pCreature != NULL);
if (pCreature->isDead()) return;
// Ż ̵ ұϰ, Ŭ̾Ʈ ã ؼ
// ũó IPM Ű ¿ CGMove ƿ
// ɼ ִ. ..
if (pCreature->getZone() == NULL) return;
Zone* pZone = pCreature->getZone();
Assert(pZone != NULL);
if (pCreature->isSlayer() && pCreature->isFlag(Effect::EFFECT_CLASS_SNIPING_MODE))
{
g_Sniping.checkRevealRatio(pCreature, 10, 20);
}
// Ư PC ̵ óǴ , PC ̵ ִ ٸ PC鿡
// εijƮؾ ϱ ̴. ̶, CGMove Ŷ Ӹ ƴ϶ ǥ
// Ե , üũ ϱ ؼ̴.
pZone->movePC(pCreature , pPacket->getX() , pPacket->getY() , pPacket->getDir());
}
#endif
__END_DEBUG_EX __END_CATCH
}
| true |
9faf93e99cb192a275bd00e8728646f1042a2224 | C++ | charlottetan/Algos | /Stanford/linked_list_stanford.cpp | WINDOWS-1252 | 29,743 | 3.953125 | 4 | [] | no_license | /*
* PROBLEM 1. Finding length of the linked list.
* unsigned int getLength(node* head)
*
* PROBLEM 2. Get Nth node
* int getNth(node* head, int index)
*
* PROBLEM 3. Delete the complete list
* void deleteList(node*& headRef)
*
* PROBLEM 4. Pop function
* int pop(node*& head)
*
* PROBLEM 5. InsertNth to insert at any place
* InsertNth to insert at any place using Push
* void insertNth(struct node*& head, unsigned int index, int value)
*
* PROBLEM 6. Sorted Insert
* void sortedInsert(node*& headRef, node* node)
*
* PROBLEM 7. Insertion Sort
* void insertionSort(node*& headRef)
*
* PROBLEM 8. Append two lists
* void appendLists(node*& list1, node*& list2)
*
* PROBLEM 9. Front Back Split
* void frontBackSplit(node* original, node*& frontList, node*& backList)
* void frontBackSplitWithoutLength(node* original, node*& frontList, node*& backList)
*
* PROBLEM 10. Remove Duplicates
* void removeDuplicates(node* head)
*
* PROBLEM 11. Move Node
* void moveNode(node*& dstList, node*&srcList)
*
* PROBLEM 12. Alternating Split
* void alternatingSplit(node* src, node*& aRef, node*& bRef)
*
* PROBLEM 13. ShuffleMerge
* node* shuffleMerge(node* a, node* b)
*
* PROBLEM 14. Bloomber Problem Reverse Last 5 nodes
* void reverseLast5Node(struct node*& head)
*
* PROBLEM 15. Minimum node in a linked list
* void minimumNode(node* head)
*
* PROBLEM 16. Delete Nodes that have a certain value
* void removeNode(node*& head, int val)
*
* PROBLEM 17. Reverse a list Recursive and Iterative way
* void reverseList(node*& head)
* void reverseListRecursive(node*& head)
* void reverseUtil(node *curr, node *prev, node*& head)
*
* PROBLEM 18. Check if a linked list is a palindrome without using extra space.
* bool isListPalindrome(node*& head)
*
* PROBLEM 19. Add two numbers represented as LinkedList
*
*/
#include <iostream>
#include <climits> // INT_MAX, INT_MIN, numeric_limits
#include <cmath> // ciel
using namespace std;
struct node
{
int data;
struct node* next;
node () : data (0), next (NULL) { }
node (int x) : data (x), next (NULL) { }
};
// A simple push function that inserts the new value at the beginning of the list.
void Push(node*& head, int value)
{
struct node* temp = new node();
temp->data = value;
temp->next = head;
head = temp;
}
// Utility function to print all values of the list.
void printList(node* head)
{
while (head != NULL)
{
cout << head->data << " " ;
head = head->next;
}
cout << endl;
}
// A utility function to create a linked list with 3 nodes.
void build123()
{
struct node* head = new node();
// Crate an empty list to start with
head = NULL;
Push(head, 1);
Push(head, 2);
Push(head, 3);
}
// -----------------------------------------------------------------------------------------
// Q1: Finding length of the linked list.
// P1. Don't use head pointer to traverse the list as head should always point to the First Entry
// P2: Function argument can just be "node* head" instead of "struct node* head"
// http://stackoverflow.com/questions/6526225/struct-keyword-in-function-parameter-and-const-correctness
// http://stackoverflow.com/questions/1675351/typedef-struct-vs-struct-definitions
// -----------------------------------------------------------------------------------------
unsigned int getLength(node* head)
{
unsigned int length = 0;
while (head != NULL)
{
length++;
head = head->next;
}
return length;
}
// -----------------------------------------------------------------------------------------
// Q2: Get Nth node
// -----------------------------------------------------------------------------------------
int getNth(node* head, int index)
{
int temp = 0;
struct node* tmpHead = head;
// the given index is not valid
if (index < 0)
{
return -1;
}
while (tmpHead != NULL)
{
if (temp == index)
{
return tmpHead->data;
}
tmpHead = tmpHead->next;
temp++;
}
return -1;
}
// -----------------------------------------------------------------------------------------
// Q3: Delete the complete list
// -----------------------------------------------------------------------------------------
void deleteList(node*& headRef)
{
struct node* temp;
while (headRef != NULL)
{
temp = headRef->next;
delete headRef;
headRef = temp;
}
// Safety check to make sure headRef is NULL
headRef = NULL;
}
// -----------------------------------------------------------------------------------------
// Q4. Pop function
// -----------------------------------------------------------------------------------------
int pop(node*& head)
{
struct node* temp;
int data;
// Fail if the passed in head is not valid
if (head == NULL)
{
return -1;
}
data = head->data;
temp = head->next;
delete head;
head = temp;
return data;
}
// -----------------------------------------------------------------------------------------
// Q5. InsertNth to insert at any place
// -----------------------------------------------------------------------------------------
void insertNth(struct node*& head, unsigned int index, int value)
{
unsigned int tmpCount = 0;
struct node* tmpNewNode = new node();
struct node* tmpHead = head;
// Proceed only if the index is valid
if (index <= getLength(head))
{
tmpNewNode->data = value;
tmpNewNode->next = NULL;
//if (head == NULL)
if (index == 0)
{
tmpNewNode->next = head;
head = tmpNewNode;
return;
}
while (tmpCount < index-1)
{
tmpHead = tmpHead->next;
tmpCount++;
}
tmpNewNode->next = tmpHead->next;
tmpHead->next = tmpNewNode;
}
}
// Q5b. InsertNth to insert at any place using Push
/*
void insertNth(struct node*& head, unsigned int index, int value)
{
unsigned int tmpCount = 0;
struct node* tmpNewNode = new node();
struct node* tmpHead = head;
// Proceed only if the index is valid
if (index <= getLength(head))
{
tmpNewNode->data = value;
tmpNewNode->next = NULL;
//if (head == NULL)
if (index == 0)
{
Push(head, value);
return;
}
while (tmpCount < index-1)
{
tmpHead = tmpHead->next;
tmpCount++;
}
tmpNewNode->next = tmpHead->next;
tmpHead->next = tmpNewNode;
}
}
*/
// -----------------------------------------------------------------------------------------
// Q6: Sorted Insert
// -----------------------------------------------------------------------------------------
void sortedInsert(node*& headRef, node* node)
{
struct node* tmpHead = headRef;
// This can be combined with the next IF block
/*
if (tmpHead == NULL)
{
// Node should be inserted at Head.
node->next = tmpHead;
tmpHead = node;
return;
}
// Insert node at the front of the list
// IMP: This is WRONG. We should instead use the HeadRef itself
if (tmpHead == NULL || tmpHead->data > node->data)
{
node->next = tmpHead;
tmpHead = node;
return;
}
*/
if (headRef == NULL || headRef->data > node->data)
{
node->next = headRef;
headRef = node;
return;
}
while (tmpHead->next != NULL)
{
if (tmpHead->next->data < node->data)
{
tmpHead = tmpHead->next;
}
else
{
break;
}
}
node->next = tmpHead->next;
tmpHead->next = node;
}
// -----------------------------------------------------------------------------------------
// Q7: Insertion Sort
// -----------------------------------------------------------------------------------------
void insertionSort(node*& headRef)
{
node* tmpHead = headRef;
//node* result = new node();
//result = NULL;
struct node* result = NULL;
struct node* next;
while (tmpHead != NULL)
{
next = tmpHead->next;
sortedInsert(result, tmpHead);
tmpHead = next;
}
headRef = result;
}
// -----------------------------------------------------------------------------------------
// Q8: Append two lists
// -----------------------------------------------------------------------------------------
void appendLists(node*& list1, node*& list2)
{
if (list1 == NULL)
{
list1 = list2;
list2 = NULL;
}
else
{
struct node* tmpList1 = list1;
while (tmpList1 -> next != NULL)
{
tmpList1 = tmpList1->next;
}
tmpList1->next = list2;
list2 = NULL;
}
}
// -----------------------------------------------------------------------------------------
// Q9: Front Back Split
// Given a list, split it into two sublists one for the front half, and one for the back half.
// If the number of elements is odd, the extra element should go in the front list.
// -----------------------------------------------------------------------------------------
void frontBackSplit(node* original, node*& frontList, node*& backList)
{
// VERY IMP: Should start from 1
// Consider Length = 2.
// Half Length = 1. If we start from 0, then we can't split it.
unsigned int count = 1;
// VERY IMP. Make it a double
unsigned int half = ceil(getLength(original) / 2.0);
if (original == NULL || original->next == NULL)
{
frontList = original;
return;
}
frontList = original;
while (count < half)
{
frontList = frontList->next;
count++;
}
backList = frontList->next ;
frontList->next = NULL;
// Finally make front list point to original list
frontList = original;
}
void frontBackSplitWithoutLength(node* original, node*& frontList, node*& backList)
{
frontList = original;
backList = original;
node* slowHead = original;
node* fastHead = original;
if (fastHead == NULL || fastHead->next == NULL)
{
backList = NULL;
return;
}
while (fastHead != NULL)
{
if (fastHead->next != NULL)
{
fastHead = fastHead->next->next;
if (fastHead != NULL)
{
slowHead = slowHead->next;
}
else
{
break;
}
}
else
{
break;
}
}
backList = slowHead->next;
slowHead->next = NULL;
}
//From MS Stanford material
void FrontBackSplitStanford(struct node* source, struct node** frontRef, struct node** backRef)
{
int len = getLength(source);
int i;
struct node* current = source;
if (len < 2)
{
*frontRef = source;
*backRef = NULL;
}
else
{
int hopCount = (len-1)/2; //(figured these with a few drawings)
for (i = 0; i<hopCount; i++) {
current = current->next;
}
// Now cut at current
*frontRef = source;
*backRef = current->next;
current->next = NULL;
}
}
// -----------------------------------------------------------------------------------------
// Q10: Remove Duplicated nodes
// Take a list sorted in increasing order and delete any duplicate nodes from the list
// -----------------------------------------------------------------------------------------
void removeDuplicates(node* head)
{
node* tmpHead = head;
node* tmpHold;
int tempVal;
bool deleteHappened = false;
while (tmpHead != NULL)
{
deleteHappened = false;
if (tmpHead->next != NULL)
{
if (tmpHead->data == tmpHead->next->data)
{
deleteHappened = true;
tmpHold = tmpHead->next->next;
delete tmpHead->next;
tmpHead->next = tmpHold;
}
// IMP: only advance if no deletion. Else we cannot delete more than
// TWO duplicates
}
if (!deleteHappened)
{
tmpHead = tmpHead->next;
}
}
}
// -----------------------------------------------------------------------------------------
// Q11: Move Node
// Instead of creating a new node and pushing it onto the given list,
// MoveNode() takes two lists, removes the front node from the second list and
// pushes it onto the front of the first
// -----------------------------------------------------------------------------------------
void moveNode(node*& dstList, node*&srcList)
{
if (srcList == NULL)
{
return ;
}
node* tmpDst = srcList->next;
srcList->next = dstList;
dstList = srcList;
srcList = tmpDst;
}
// -----------------------------------------------------------------------------------------
// Q12 Alternating Split
// AlternatingSplit() that takes one list and divides up its nodes to make two smaller lists.
// The sublists should be made from alternating elements in the original list.
// So if the original list is {a, b, a, b, a}, then one sublist should be {a, a, a} and the
// other should be {b, b}. You may want to use MoveNode() as a helper.
// -----------------------------------------------------------------------------------------
void alternatingSplit(node* src, node*& aRef, node*& bRef)
{
node* tmpSrc = src;
while (tmpSrc != NULL)
{
moveNode(aRef, tmpSrc);
if (tmpSrc != NULL)
{
moveNode(bRef, tmpSrc);
}
}
}
// -----------------------------------------------------------------------------------------
// Q13: ShuffleMerge
// Given two lists, merge their nodes together to make one list, taking nodes alternately
// between the two lists.
// So ShuffleMerge() with {1, 2, 3} and {7, 13, 1} should yield {1, 7,
// 2, 13, 3, 1}. If either list runs out, all the nodes should be taken from the other list.
// -----------------------------------------------------------------------------------------
node* shuffleMerge(node* a, node* b)
{
node* srcMerged = NULL;
node** merged = &srcMerged;
while (a != NULL && b != NULL)
{
moveNode(*merged, a);
merged=&((*merged)->next);
moveNode(*merged, b);
merged=&((*merged)->next);
}
while (a != NULL)
{
moveNode(*merged, a);
merged=&((*merged)->next);
}
while (b != NULL)
{
moveNode(*merged, b);
merged=&((*merged)->next);
}
return srcMerged;
}
// -----------------------------------------------------------------------------------------
// Helper routine to move first node from node b to node a
// This rountine when called on a linked list will reverse the complete list.
// -----------------------------------------------------------------------------------------
void moveNode2(struct node*& a, struct node*& b)
{
if (b != NULL)
{
struct node* temp = a;
a = b;
b = b->next;
a->next = temp;
}
}
// -----------------------------------------------------------------------------------------
// Bloomberg Coding Prep 2.
// Problem 1:
// Given the root node to a singly linked list, reverse the last 5
// nodes in the list. For a list with 5 or less nodes, reverse the whole list.
// Algorithm:
// Have first node pointing to head and second node pointing to the node 5 steps
// ahead.
//
// Then traverse both head and the other node till the other node reaches NULL.
// Now we will have head pointing to last but 5 nodes.
//
// Complexity: O(N)
// -----------------------------------------------------------------------------------------
void reverseLast5Node(struct node*& head)
{
// We will never move the position of head.
struct node* tmpHead = head; // A temporary node storing head's position. We will never mo
struct node* headFive = head; // A temp node that points five nodes ahead.
struct node* result = NULL; // A temporary node to store the reversed list.
unsigned int count = 0;
while (headFive != NULL &&
count < 5)
{
headFive = headFive->next;
count++;
}
// If count is five and tmpHead is not null, then we have more atleast five nodes
if (count == 5 && headFive != NULL)
{
// Now "tmpHead" is 5 steps behind. So move both tmpHead and headFive till headFive
// reaches NULL. Then tmpHead will be pointing to the last five nodes.
while(headFive->next != NULL)
{
tmpHead = tmpHead->next;
headFive = headFive->next;
}
// Reverse the last five nodes of the linked list.
while(tmpHead->next != NULL)
{
moveNode2(result, tmpHead->next);
}
// Set the next pointer to point to the reversed list.
tmpHead->next = result;
}
else
{
// This takes care of reversing the linked list if it has 5 or lesser nodes.
while(head != NULL)
{
moveNode2(result, head);
}
head = result;
}
}
// -----------------------------------------------------------------------------------------
// PROBLEM 15. Minimum node in a linked list
// -----------------------------------------------------------------------------------------
void minimumNode(node* head)
{
struct node* minNode = new node();
minNode->data = INT_MAX;
minNode->next = NULL;
while (head != NULL)
{
// If the minimum element is M and we have N elements greater than M which are
// ahead of M, then the if block will be executed N times.
if (minNode->data > head->data)
{
minNode->data = head->data;
}
head = head->next;
}
cout << minNode->data << endl;
}
// -----------------------------------------------------------------------------------------
// PROBLEM 16. Delete Nodes that have a certain value
// -----------------------------------------------------------------------------------------
void removeNode(node*& head, int val)
{
if (head == NULL)
{
return;
}
node* cur = head;
while (cur != NULL && cur->data == val)
{
node* tmp = cur->next;
delete cur;
head = tmp;
cur = tmp;
}
struct node* curNext = cur->next;
while(curNext != NULL)
{
if(curNext->data == val)
{
cur->next = curNext->next;
delete curNext;
curNext = cur->next;
}
else
{
cur = cur->next;
curNext = cur->next;
}
}
}
// -----------------------------------------------------------------------------------------
// PROBLEM 17. Reverse a list Recursive and Iterative way
// -----------------------------------------------------------------------------------------
void reverseList(node*& head)
{
node* prev = NULL;
node* current = head;
node* curNext = NULL;
while (current != NULL)
{
curNext = current->next;
current->next = prev;
prev = current;
current = curNext;
}
head = prev;
}
// A simple and tail recursive function to reverse
// a linked list. prev is passed as NULL initially.
// Tail Recursive Approach from GeeksForGeeks
void reverseUtil(node *curr, node *prev, node*& head)
{
/* If last node mark it head*/
if (!curr->next)
{
head = curr;
/* Update next to prev node */
curr->next = prev;
return;
}
/* Save curr->next node for recursive call */
node *next = curr->next;
/* and update next ..*/
curr->next = prev;
reverseUtil(next, curr, head);
}
void reverseNeat(node*& head)
{
if (!head)
{
return;
}
reverseUtil(head, NULL, head);
}
// From MS Stanford
void reverseListRecursive(node*& head)
{
if (NULL == head)
{
return;
}
node* first = head;
node* rest = head->next;
if (NULL == rest)
{
return;
}
reverseListRecursive(rest);
first->next->next = first;
first->next = NULL;
head = rest;
}
// -----------------------------------------------------------------------------------------
// PROBLEM 18. Check if a linked list is a palindrome without using extra space.
// Original list can be modified
// -----------------------------------------------------------------------------------------
bool compareLists(node* list1, node* list2)
{
while (list1 != NULL && list2 != NULL)
{
if (list1->data != list2->data)
{
return false;
}
list1 = list1->next;
list2 = list2->next;
}
return true;
}
bool isListPalindrome(node* head)
{
node* list1 = NULL;
node* list2 = NULL;
//printList(head);
frontBackSplitWithoutLength(head, list1, list2);
reverseList(list2);
//printList(list1);
//printList(list2);
return compareLists(list1, list2);
}
// When passed by pointer
// - ONLY the object that the pointer points gets modified. Not the pointer itself
// When pointer is passed by reference then,
// - The pointer itself gets modified
//
// Head 1: 0xfc1008
// Addr 1: 0x61fef0
// Head 2: 0xfc1008
// Addr 2: 0x61fed0
void samp(node* head)
{
cout << "Head 2: " << head << endl;
cout << "Addr 2: " << &head << endl;
/*
node* b = head;
b->next = NULL;
*/
head = head->next;
head = NULL;
// head->next = NULL;
}
// -----------------------------------------------------------------------------
// PROBLEM 19. Add two numbers represented as LinkedList
// -----------------------------------------------------------------------------
node* addTwoNumbers(node* l1, node* l2) {
int carry = 0;
node* result = NULL;
node* resultHead = result;
while (l1 != NULL && l2 != NULL) {
int sum = carry + l1->data + l2->data;
carry = sum / 10;
node* temp = new node(sum % 10);
if (result == NULL) {
result = temp;
resultHead = temp;
} else if (result->next == NULL) {
result->next = temp;
result = result->next;
}
l1 = l1->next;
l2 = l2->next;
}
while (l1 != NULL) {
int sum = carry + l1->data;
carry = sum / 10;
node* temp = new node(sum % 10);
if (result == NULL) {
result = temp;
resultHead = temp;
} else if (result->next == NULL) {
result->next = temp;
result = result->next;
}
l1 = l1->next;
}
while (l2 != NULL) {
int sum = carry + l2->data;
carry = sum / 10;
node* temp = new node(sum % 10);
if (result == NULL) {
result = temp;
resultHead = temp;
} else if (result->next == NULL) {
result->next = temp;
result = result->next;
}
l2 = l2->next;
}
if (carry != 0) {
node* temp = new node(carry);
result->next = temp;
}
return resultHead;
}
// -----------------------------------------------------------------------------------------
// Main Function
// -----------------------------------------------------------------------------------------
int main()
{
cout << "Stanford Linked List Problems" << endl;
// Create an empty list to start with
node* head = new node();
head = NULL;
// node* head2 = new node();
node* head2 = NULL;
// Fill in values
{
/*
Push(head2, 1);
Push(head2, 2);
Push(head2, 3);
*/
Push(head, 1);
Push(head, 2);
Push(head, 3);
Push(head, 4);
Push(head, 5);
Push(head, 6);
Push(head, 7);
Push(head, 8);
}
// Reversing the List
{
//moveNode2(head2, head);
printList(head);
reverseLast5Node(head);
printList(head);
//reverseLast5Node(head2);
//printList(head2);
}
// PROBLEM 2. Get Nth Element
{
cout << "PROBLEM 2. Get Nth Element: " << endl;
cout << getNth(head, 0) << endl;
cout << getNth(head, 1) << endl;
cout << getNth(head, 2) << endl;
}
// PROBLEM 3. Delete the complete list
//deleteList(head);
printList(head);
// PROBLEM 4. Pop
{
cout << "PROBLEM 4. Pop: " << endl;
cout << pop(head) << endl;
cout << pop(head) << endl;
cout << pop(head) << endl;
cout << pop(head) << endl;
}
// PROBLEM 5. InsertNth
{
cout << endl << "PROBLEM 5. Insert Nth" << endl;
head = NULL;
insertNth(head, 0, 5);
insertNth(head, 0, 10);
insertNth(head, 0, 10);
insertNth(head, 0, 10);
insertNth(head, 0, 10);
insertNth(head, 3, 16);
insertNth(head, 2, 3);
insertNth(head, 0, 5);
insertNth(head, 0, 2);
insertNth(head, 0, 1);
insertNth(head, 3, 6);
insertNth(head, 2, 3);
printList(head);
}
// PROBLEM 6. Sorted Insert
{
node* temp2 = new node();
temp2->next = NULL;
temp2->data = 0;
node* temp3 = new node();
temp3->next = NULL;
temp3->data = 0;
node* temp4 = new node();
temp4->next = NULL;
//temp4->data = 17;
temp4->data = 5;
sortedInsert(head, temp2);
sortedInsert(head, temp3);
sortedInsert(head, temp4);
//printList(head);
}
// PROBLEM 7. Insertion Sort
{
cout << endl << "PROBLEM 7. Insertion Sort" << endl;
insertionSort(head);
printList(head);
}
// PROBLEM 9. Front Back Split
{
cout << endl << "PROBLEM 9. Front Back Split" << endl;
node* list1 = NULL;
node* list2 = NULL;
printList(head);
// frontBackSplit(head, list1, list2);
//frontBackSplitWithoutLength(head, list1, list2);
FrontBackSplitStanford(head, &list1, &list2);
printList(head);
//printList(list1);
//printList(list2);
// PROBLEM 8. Append two lists
cout << endl << "PROBLEM 8. Append two lists" << endl;
appendLists(list1, list2);
printList(list1);
}
// PROBLEM 10. Remove Duplicates
{
cout << endl << "PROBLEM 10. Remove Duplicates" << endl;
removeDuplicates(head);
printList(head);
}
cout << "Another List" << endl;
printList(head2);
/*
// PROBLEM 11. Move Node
{
cout << endl << "PROBLEM 11. Move Node" << endl;
moveNode(head, head2);
printList(head);
printList(head2);
cout << "Move Node again" << endl;
moveNode(head, head2);
moveNode(head, head2);
printList(head);
printList(head2);
}
// PROBLEM 12. Alternating Split
node* aRef = NULL;
node* bRef = NULL;
{
cout << endl << "PROBLEM 12. Alternating Split" << endl;
alternatingSplit(head, aRef, bRef);
printList(aRef);
printList(bRef);
}
// PROBLEM 13. Shuffle Merge
node* merged = NULL;
{
cout << endl << "PROBLEM 13. Shuffle Merge" << endl;
merged = shuffleMerge(aRef, bRef);
printList(merged);
}
// PROBLEM 15. Minimum Node in the list
{
cout << endl << "PROBLEM 15. Minimum Node" << endl;
printList(merged);
minimumNode(merged);
}
// PROBLEM 16. Delete nodes containing a Value
{
cout << endl << "PROBLEM 16. Delete Nodes Having a Value" << endl;
node* head = NULL;
insertNth(head, 0, 5);
insertNth(head, 0, 5);
insertNth(head, 0, 5);
insertNth(head, 0, 3);
insertNth(head, 0, 5);
insertNth(head, 0, 5);
insertNth(head, 0, 5);
int val = 5;
removeNode(head, val);
printList(head);
}
node* head1 = NULL;
insertNth(head1, 0, 5);
insertNth(head1, 1, 3);
insertNth(head1, 2, 7);
insertNth(head1, 3, 1);
insertNth(head1, 4, 7);
insertNth(head1, 5, 3);
insertNth(head1, 6, 5);
// PROBLEM 17. Reverse a list Recursive and Iterative way
{
cout << endl << "PROBLEM 17. Reverse List" << endl;
reverseList(head1);
printList(head1);
reverseListRecursive(head1);
printList(head1);
reverseNeat(head1);
printList(head1);
}
// Passing by Pointer and Passing Pointer by Reference
{
node* list1 = NULL;
node* list2 = NULL;
//printList(head1);
//samp(head1);
//printList(head1);
}
// PROBLEM 18. Check if a linked list is a palindrome without using extra space.
// Original list can be modified
{
cout << endl << "PROBLEM 18. Is list Palindrome" << endl;
cout << isListPalindrome(head1) << endl;
}
*/
// PROBLEM 19. Add two numbers represented as LinkedList
{
cout << endl << "PROBLEM 19. Add two numbers represented as LinkedList" << endl;
}
cout << endl;
return 0;
}
| true |
4f742c79aefc1b670c3436a6cdf018a3849d1744 | C++ | mihirm05/cpp | /operatoroverloading/mainFile.cpp | UTF-8 | 449 | 3.390625 | 3 | [] | no_license | #include<iostream>
#include<string>
#include "overload.h"
using namespace std;
int main(){
// creating one object with 50
Overload o1(70);
// creating another object with 30
Overload o2(30);
// creating one more empty object
Overload o3;
// + has been overloaded to add objects now
o3 = o1 + o2;
// alternate method to write the previous line
// o3 = o1.operator+(o2);
cout<<o3.num<<endl;
} | true |
cc551182e9d3fc74d58247932d44f5f1a8a19cde | C++ | aibees/algorithm | /baekjoon/baekjoon_3015.cpp | UTF-8 | 675 | 2.796875 | 3 | [] | no_license | #include <iostream>
#include <stack>
#include <utility>
using namespace std;
stack<pair<int, int> > s;
long long answer = 0;
int main(void) {
int n = 0; cin >> n;
for(int i = 0; i < n; i++) {
int h = 0; cin >> h;
while(!s.empty() && s.top().first < h) {
answer += s.top().second;
s.pop();
}
if(s.empty()) {
s.push(make_pair(h, 1));
}
else {
if(s.top().first == h) {
pair<int, int> current = s.top();
s.pop();
answer += current.second;
if(!s.empty())
answer++;
current.second++;
s.push(current);
}
else {
s.push(make_pair(h, 1));
answer++;
}
}
}
cout << answer << '\n';
return 0;
} | true |
03890b75ae3d650031b169dca03c9750458f3ced | C++ | sonbhuynh/Comp_Sci_III-IV | /A5.CPP | UTF-8 | 4,098 | 3.734375 | 4 | [] | no_license | // Program name: A5
// Date: Feb 1, 2012
//
// Programmer: Son Huynh
// Course: CS III
// Mrs. Roszko Period: 1
//
// Description: This program will input an employee's gross wages.
// Then calculate the taxes (25%), union dues (5%) and net pay.
// Then write all this information to a Data file
//
// Input: Users will input Employee's number and Gross Pay
//
// Output: Program will output Taxes, Union dues, and Net pay to the screen and data file
//
// Assumptions/Limitations: None
//--------------------------------------------------------------------------
//////////////////////LIBRARIES
#include <iostream.h>
#include <iomanip.h>
#include <fstream.h>
#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
void input(int& employee, double& grosspay); //Prototype for inputting data function
void calculation(double& grosspay, double& taxes, double& dues, double& netpay); //Prototype for Calculating function
void outputdata(ofstream& output1, int employee, double grosspay, double taxes, double dues, double netpay); //Prototype for Outputting data
void magic(ofstream& output1); //Prototype for magic formula
void purpose(); //Prototype for purpose
int main()
{
ofstream output1; //Declaration
int employee;
double grosspay, taxes, dues, netpay;
char choice;
output1.open("F:/Aprogs/A5.dat");
purpose(); //Function call for outputting purpose
magic(output1); //Function call for magic formula
if(output1.fail())
{
cout<<"Outputting to A5.dat failed. \n"; //Outputs error message
getch();
exit(1);
}
output1<<setw(8)<<"Employee"<<setw(14)<<"Gross Pay"<<setw(10)<<"Taxes"
<<setw(9)<<"Dues"<<setw(12)<<"Net Pay"; //Outputs Titles to data file
do
{
input(employee, grosspay); //Function call for Inputting data
calculation(grosspay, taxes, dues, netpay); //Function call for Calculation
outputdata(output1, employee, grosspay, taxes, dues, netpay); //Function call for Outputting data
cout<<"\n\nEnter another record? (Y/N): "; //Inputs Y or N
cin>>choice;
choice = toupper(choice);
clrscr();
}
while(choice != 'N');
output1.close();
return 0;
}
//This function will allow the user to input the employee's number and gross pay
void input(int& employee, double& grosspay)
{
cout<<"\nEnter Employee's number: "; //Input employee's number
cin>>employee;
cout<<"\nEnter Gross Pay: $"; //Input gross pay
cin>>grosspay;
}
//This function will calculate the Taxes, Union dues and Net Pay
void calculation(double& grosspay, double& taxes, double& dues, double& netpay)
{
taxes = grosspay * .25; //Calculating Taxes
dues = grosspay * .05; //Calculating Union dues
netpay = grosspay - taxes - dues; //Calculating Net Pay
}
//This function will output the data to the screen and data file
void outputdata(ofstream& output1, int employee, double grosspay, double taxes, double dues, double netpay)
{
cout<<"\n"<<setw(8)<<"Employee"<<setw(14)<<"Gross Pay"<<setw(10)<<"Taxes"
<<setw(9)<<"Dues"<<setw(12)<<"Net Pay"; //Outputs Titles to screen
cout<<"\n"<<setw(8)<<employee<<setw(14)<<grosspay<<setw(10)<<taxes<<setw(9)<<dues<<setw(12)<<netpay; //Outputs data on screen
output1<<"\n"<<setw(8)<<employee<<setw(14)<<grosspay<<setw(10)<<taxes<<setw(9)<<dues<<setw(12)<<netpay; //Outputs data to data file
}
//This function contains the magic formula
void magic(ofstream& output1)
{
cout.setf(ios::fixed); //Magic formula
cout.setf(ios::showpoint);
cout.precision(2);
output1.setf(ios::fixed); //Magic formula
output1.setf(ios::showpoint);
output1.precision(2);
}
void purpose()
{
cout<<"\nThis program will input an employee's gross wages. " //Outputs purpose
<<"\nThen calculate the taxes (25%), union dues (5%) and net pay. "
<<"\nThen write all this information to a Data file. ";
cout<<"\n\nPress enter to continue ";
getchar();
clrscr();
} | true |
1ccb81fe82c1b8d083664f9268d992149191eab8 | C++ | sakshamchecker/DSA | /rev.cpp | UTF-8 | 242 | 3.09375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int rev(int a[],int size){
for(int i=0,j=size-1;i<size/2;i++,j--){
swap(a[i],a[j]);
}
for(int i=0;i<size;i++)
cout<<a[i];
return 0;
}
int main(){
int a[]={1,2,3,4,5,6};
rev(a,6);
return 0;
} | true |
d5d4e99339e282994af88115409ecf8399ae869b | C++ | JJProgram/CodesPrograII | /ClasesACompletar/ClaseRacional/Racional.cpp | UTF-8 | 1,178 | 3.265625 | 3 | [] | no_license | #include <iostream>
#include "Racional.h"
#define modulo(X)((X)<0?-(X):(X))
void Racional::normalizarRacional(int& n,int& d)
{
int divisor=2;
if(d==0)
{
d=1;
cout << "No esta permitido un denominador = 0, cambiado a 1" << endl;
}
else
{
//AGREGAR CORRECCION NEGATIVOS!!!
if(n==d)
{
n/=n;
d/=d;
return;
}
else
while(divisor<=(n/2)||divisor<=(d/2))
{
if(n%divisor==0&&d%divisor==0)
{
n/=divisor;
d/=divisor;
}
divisor++;
}
}
}
void Racional::mostrarRacional(void)
{
cout << numerador << "/" << denominador << endl;
}
Racional::Racional(int numerador,int denominador)
{
normalizarRacional(numerador,denominador);
this->numerador=numerador;
this->denominador=denominador;
}
Racional::~Racional()
{
}
Racional& Racional::operator=(const Racional& obj)
{
numerador=obj.numerador;
denominador=obj.denominador;
return (*this);
}
/*
Racional Racional::operator+(const Racional& obj)const
{
}
*/
| true |
b3423beee33f8b409955772ffbdf6321a5cbde31 | C++ | sainisajal147/Problem_solving | /division_by_2.cpp | UTF-8 | 1,240 | 2.921875 | 3 | [] | no_license | /*
AUTHOR : SAJAL SAINI
*/
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
template <class t>
void disp(vector<vector<t>> v)
{
for(int i=0;i<v.size();i++)
{
for(int j=0;j<v[i].size();j++)
{
cout<<v[i][j]<<" ";
}
cout<<endl;
}
}
template <class t>
void disp(vector<t> v)
{
for(int i=0;i<v.size();i++)
{
cout<<v[i]<<" ";
}
cout<<endl;
}
string division_by_2(string dividend)
{
if(dividend=="0")
return "0";
if(dividend=="1")
return "1";
if(!(dividend.back()=='0' or dividend.back()=='2' or dividend.back()=='4' or dividend.back()=='6' or dividend.back()=='8'))
return "-1";
string quotient="",rem="";
for(int i=0;i<dividend.size();i++)
{
rem+=dividend[i];
if(stoi(rem)>=2)
{
if(stoi(rem)%2==0)
{
quotient+=to_string(stoi(rem)/2);
rem.clear();
}
else
{
quotient+=to_string(stoi(rem)/2);
rem="1";
}
}
else
{
quotient+="0";
}
}
while(quotient[0]=='0')
quotient.erase(quotient.begin());
return quotient;
}
int main(void) {
cout<<division_by_2("4");
return 0;
} | true |
c296626e56a6a16ef993885bec5376ea80f7f44a | C++ | prashooshukla/codechef | /july-long-challenge-2020/CHFNSWPS.cpp | UTF-8 | 3,018 | 2.53125 | 3 | [] | no_license | // https://www.codechef.com/JULY20B/problems/CHFNSWPS
#include <bits/stdc++.h>
#define MOD 1000000007
#define endl '\n'
using namespace std;
typedef long long ll;
typedef unsigned long long int ullu;
void print(map<long long, long long> mp) {
for (auto m: mp) {
cout << "m " << m.first << " " << m.second << endl;
}
}
void printu(vector<long long> V) {
for (auto v: V) {
cout << v << " ";
} cout << '\n';
}
int main() {
// your code goes here
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int tt;
cin >> tt;
while (tt--) {
int N;
cin >> N;
std::vector<long long> A(N);
std::vector<long long> B(N);
unordered_map<long long, long long> frequency;
map<long long, long long> A_1;
map<long long, long long> B_1;
long long smallest = INT_MAX;
for (int i = 0; i < N; i++) {
cin >> A[i];
frequency[A[i]]++;
A_1[A[i]]++;
smallest = min(smallest, A[i]);
}
for (int i = 0; i < N; i++) {
cin >> B[i];
frequency[B[i]]++;
B_1[B[i]]++;
smallest = min(smallest, B[i]);
}
long long ans = 0;
bool flag = true;
for (auto m: frequency) {
if (m.second % 2 != 0) {
flag = false;
ans = -1;
break;
}
}
if (flag) {
map<long long, long long> extra_A;
map<long long, long long> extra_B;
long long A_unbalanced = 0;
long long B_unbalanced = 0;
for (auto a: A_1) {
if (a.second > B_1[a.first]) {
extra_A[a.first] = (a.second - B_1[a.first]) / 2;
A_unbalanced += extra_A[a.first];
}
}
for (auto b: B_1) {
if (b.second > A_1[b.first]) {
extra_B[b.first] = (b.second - A_1[b.first]) / 2;
B_unbalanced += extra_B[b.first];
}
}
vector<long long> alpha;
vector<long long> beta;
for (auto a: extra_A) {
for (int i = 0; i < a.second; i++) {
alpha.push_back(a.first);
}
}
for (auto a: extra_B) {
for (int i = 0; i < a.second; i++) {
beta.push_back(a.first);
}
}
// cout << "a: "; printu(alpha); cout << "b: "; printu(beta);
reverse(beta.begin(), beta.end());
int len = (int) alpha.size();
for (int i = 0; i < len; i++) {
// cout << "s: " << (2 * smallest) << " a: " << alpha[i] << " b: " << beta[i] << " r: " << min(2 * smallest, min(alpha[i], beta[i])) << endl;
ans += min(2 * smallest, min(alpha[i], beta[i]));
}
}
cout << ans << endl;
}
return 0;
} | true |
d1f37c7f5b131ca5ee3bd920db0334f1f76a7f66 | C++ | tanvirtareq/programming | /vjudge/CSE 150 ( 2017 batch) Marathon Contest 1 (STL)/andy's 2nd dictionary.cpp | UTF-8 | 1,849 | 2.75 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
map<string, int>s;
map<string, int>::iterator it;
vector<string> v;
string stte;
int x;
string inp(char ar[])
{
string st;
int l=strlen(ar);
for(int i=0;i<l;i++)
{
if(isalpha(ar[i])||ar[i]=='-')
{
ar[i]=tolower(ar[i]);
st.push_back(ar[i]);
}
else
{
if(x==1)
{
stte+=st;
if(s[stte]!=1&&stte!="-"&&stte.size()!=0) v.push_back(stte);
// if(s[stte]!=1) cout<<"("<<stte<<")"<<endl;
s[stte]=1;
stte.clear();
x=0;
st.clear();
}
else
{
if(s[st]!=1&&st!="-"&&st.size()!=0) v.push_back(st);
// if(s[st]!=1) cout<<"("<<st<<")"<<endl;
s[st]=1;
st.clear();
}
}
}
return st;
}
int main()
{
string st;
char ar[1000];
while(scanf("%s", ar)!=EOF)
{
st=inp(ar);
if(st[st.size()-1]=='-')
{
st.erase(st.end()-1);
stte+=st;
st.clear();
x=1;
}
else if(x==1)
{
stte+=st;
if(s[stte]!=1&&stte!="-"&&stte.size()!=0) v.push_back(stte);
// if(s[stte]!=1) cout<<"("<<stte<<")"<<endl;
s[stte]=1;
stte.clear();
x=0;
}
else
{
if(s[st]!=1&&st!="-"&&st.size()!=0) v.push_back(st);
// if(s[st]!=1) cout<<"("<<st<<")"<<endl;
s[st]=1;
}
}
sort(v.begin(), v.end());
for(int i=0;i<v.size();i++)
cout<<v[i]<<endl;
return 0;
}
| true |
41a72e3630255c998903d0663f5e631ffe7cc9e5 | C++ | roli666/KompGraf | /HF1/BSpline.h | UTF-8 | 976 | 2.671875 | 3 | [] | no_license | #pragma once
#pragma warning( disable : 4244 )
#include "bevgrafmath2017.h"
#include <deque>
class BSpline {
public:
void AddPoint(float x, float y);
void RemovePoint(float x, float y);
void MovePoint(float x, float y);
void MoveGrabbedPoint(float x, float y);
void SetGrabbedPoint(float x, float y);
void DrawPoints();
void DrawSpline(float lineThickness);
bool MouseOverPoint(float x, float y);
vec2 * grabbedPoint = nullptr;
BSpline(int pointSize)
{
points = std::deque<vec2>();
this->pointSize = pointSize;
}
private:
void DrawCircle(float x, float y);
int pointSize;
mat24 G;
std::deque<vec2> points;
vec2 ghostStart;
vec2 ghostEnd;
float t1 = -1;
float t2 = 0;
float t3 = 1;
mat4 T = mat4
(
vec4(pow(t1, 3), pow(t1, 2), t1, 1),
vec4(pow(t2, 3), pow(t2, 2), t2, 1),
vec4(pow(t3, 3), pow(t3, 2), t3, 1),
vec4(3 * pow(t3, 2), 2 * t3, 1, 0),
true
);
mat4 M = inverse(T) / 6;
//vec4 tder = { 3.0f * pow(t1, 2), 2.0f * t1, 1, 0 };
}; | true |
5cdb1d2083236e3187433ad8775a523dd909c766 | C++ | anmolduainter/cLionProjects | /SudokuSolver/main.cpp | UTF-8 | 2,909 | 2.890625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
bool isSafe(int a[][9],int row,int col,int n,int k){
for (int i = 0; i < n ; ++i) {
if (a[i][col]==k || a[row][i]==k){
return false;
}
}
int subn=sqrt(n);
int subx=(row/subn)*subn;
int suby=(col/subn)*subn;
for (int i = subx; i < subx+subn ; ++i) {
for (int j = suby; j < suby+subn ; ++j) {
if (a[i][j]==k){
return false;
}
}
}
return true;
}
bool isSafe1(int a[][6],int row,int col,int n,int k){
for (int i = 0; i < n ; ++i) {
if (a[i][col]==k || a[row][i]==k){
return false;
}
}
int subn=sqrt(n);
int subx=(row/subn)*subn;
int suby=(col/subn)*subn;
for (int i = subx; i < subx+subn ; ++i) {
for (int j = suby; j < suby+subn ; ++j) {
if (a[i][j]==k){
return false;
}
}
}
return true;
}
bool SolveSudoku(int a[][9],int row,int col,int n){
if(row==n){
for (int i = 0; i < n ; ++i) {
for (int j = 0; j < n ; ++j) {
cout<<a[i][j]<<" ";
}
cout<<endl;
}
return true;
}
if (col==n){
return SolveSudoku(a,row+1,0,n);
// return;
}
if(a[row][col]!=0){
return SolveSudoku(a,row,col+1,n);
}
for (int i = 1; i <= n ; ++i) {
if (isSafe(a,row,col,n,i)){
a[row][col]=i;
bool sovehui=SolveSudoku(a,row,col+1,n);
if(sovehui){
return true;
}
}
}
a[row][col]=0;
return false;
}
bool SolveSudoku1(int a[][6],int row,int col,int n){
if(row==n){
for (int i = 0; i < n ; ++i) {
for (int j = 0; j < n ; ++j) {
cout<<a[i][j]<<" ";
}
cout<<endl;
}
return true;
}
if (col==n){
return SolveSudoku1(a,row+1,0,n);
// return;
}
if(a[row][col]!=0){
return SolveSudoku1(a,row,col+1,n);
}
for (int i = 1; i <= n ; ++i) {
if (isSafe1(a,row,col,n,i)){
a[row][col]=i;
bool sovehui=SolveSudoku1(a,row,col+1,n);
if(sovehui){
return true;
}
}
}
a[row][col]=0;
return false;
}
// Main
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;
cin>>n;
if (n==9){
int mat[n][9];
for (int i = 0; i < n ; ++i) {
for (int j = 0; j < n; ++j) {
cin >> mat[i][j];
}
}
SolveSudoku(mat,0,0,9);
}
else if (n==6){
int mat[n][6];
for (int i = 0; i < n ; ++i) {
for (int j = 0; j < n ; ++j) {
cin>>mat[i][j];
}
SolveSudoku1(mat,0,0,6);
}
}
} | true |
161e2311da42b5ddbbff5806c27f95177b780d0d | C++ | WhiteRabbitIndustries/ResDev | /PlayLight/examples/CityLightsMini/lightSpot.cpp | UTF-8 | 1,763 | 3.078125 | 3 | [
"CC-BY-4.0"
] | permissive | #include "lightSpot.h" //include the declaration for this class
void lightSpot::lightSpotInitiate(int _id){
id = _id;
//gPal = HeatColors_p;
gPal = CRGBPalette16( CRGB::Black, CRGB::Red, 0xFF0088);
//pinMode(LED_PIN, OUTPUT); //make that pin an OUTPUT
ledNumber = random(6,20);
brightness = random (127,255);
// if(DEBUG) Serial.print(id);
// if(DEBUG) Serial.print(": ledNumber: ");
// if(DEBUG) Serial.print(ledNumber);
// if(DEBUG) Serial.print(" brightness: ");
// if(DEBUG) Serial.print(brightness);
// if(DEBUG) Serial.println();
//
}
//<<const>>
lightSpot::lightSpot(){/*nothing to const*/}
//<<destructor>>
lightSpot::~lightSpot(){/*nothing to destruct*/}
//set color
void lightSpot::setColor(){
//digitalWrite(LED_PIN,HIGH); //set the pin HIGH and thus turn LED on
}
//update values
void lightSpot::update(){
brightness = brightness + fadeAmount;
// reverse the direction of the fading at the ends of the fade:
if (brightness < 30)
{
//brightness = 0;
fadeAmount = -fadeAmount ;
}
else if (brightness > 255)
{
brightness = 255;
fadeAmount = -fadeAmount ;
}
}
//
//
////turn the LED on
//void lightSpot::on(){
// digitalWrite(LED_PIN,HIGH); //set the pin HIGH and thus turn LED on
//}
//
////turn the LED off
//void lightSpot::off(){
// digitalWrite(LED_PIN,LOW); //set the pin LOW and thus turn LED off
//}
//
////blink the LED in a period equal to paramterer -time.
//void lightSpot::blink(int time){
// on(); //turn LED on
// delay(time/2); //wait half of the wanted period
// off(); //turn LED off
// delay(time/2); //wait the last half of the wanted period
//}
| true |
2a51014346c81c0eba2827e867b27280c922ef14 | C++ | abzaremba/nauka_cpp | /text_care.cpp | UTF-8 | 3,422 | 3.453125 | 3 | [] | no_license | #include "text_care.h"
#include <algorithm>
//#include <map>
#include <iostream>
using std::vector;
using std::string;
using std::max;
using std::map;
using std::istream;
vector<string> split(const string& s)
{
vector<string> ret;
typedef string::size_type string_size;
string_size i=0;
// invariant: we have processed characters [original value of i, i)
while (i != s.size()) {
// ignore leading blanks
//invariant: characters in range [original i, current i) are all spaces
while (i != s.size() && isspace(s[i]))
++i;
// find end of next word
string_size j = i;
// invariant: none of the character isn range [original j, current j) is a space
while (j != s.size() && !isspace(s[j]))
++j;
//if we found some nonwhitespace characters
if (i != j) {
//copy from s starting at i and taking j-i chars
ret.push_back(s.substr(i, j-i));
i=j;
}
}
return ret;
}
string::size_type width(const vector<string>& v)
{
string::size_type maxlen = 0;
for(vector<string>::size_type i = 0; i != v.size(); ++i)
maxlen = max(maxlen, v[i].size());
return maxlen;
}
vector<string> frame(const vector<string>& v)
{
vector<string> ret;
string::size_type maxlen = width(v);
string border(maxlen + 4, '*');
// write the top border
ret.push_back(border);
// write each interior row, bordered by an asterisk and a space
for (vector<string>::size_type i = 0; i != v.size(); ++i) {
ret.push_back("* " + v[i] + string(maxlen - v[i].size(), ' ') + " *");
}
// write the bottom border
ret.push_back(border);
return ret;
}
vector<string> vcat (const vector<string>& top, const vector<string>& bottom)
{
// copy the top picture
vector<string> ret = top;
// copy entire bottom picture
/*for (vector<string>::const_iterator it = bottom.begin(); it != bottom.end(); ++it)
ret.push_back(*it);*/
ret.insert(ret.end(), bottom.begin(), bottom.end());
return ret;
}
vector<string> hcat(const vector<string>& left, const vector<string>& right)
{
vector<string> ret;
// add 1 to leave a space between pictures
string::size_type width1= width(left) + 1;
// indices to look at elements from left and right respectively
vector<string>::size_type i=0, j=0;
// continue until we've seen all rows from both pictures
while (i != left.size() || j != right.size()) {
// construct new string to hold characters from both pictures
string s;
// copy a row from the left-hand side, if there is one
if (i != left.size())
s = left[i++];
// pad to full witdth
s += string(width1 - s.size(), ' ');
// copy a row from the right-hand side, if there is one
if (j != right.size())
s += right[j++];
// add s to the picture we're ctrreating
ret.push_back(s);
}
return ret;
}
// find all the lines that refer to each word in the input
map<string, vector<int> > xref(istream& in, vector<string> find_words(const string&))
{
string line;
int line_number = 0;
map<string, vector<int> > ret;
//read the next line
while (getline(in, line)) {
++line_number;
//break the input into words
vector<string> words = find_words(line);
// remember that each word occurs on the current line
for (vector<string>::const_iterator it= words.begin(); it != words.end(); ++it)
ret[*it].push_back(line_number);
}
return ret;
} | true |
694deb2b75f905ec0c19a1a905ac490984ef5ad2 | C++ | JakobVokac/BezierSurfaceDistance | /optimizer/preprocessor/quadraticInterpolation.h | UTF-8 | 1,100 | 2.84375 | 3 | [] | no_license | //
// Created by s3179222 on 12/10/19.
//
/*
* This is the implementation of the quadratic interpolation method.
*
* The 1D version simply interpolates from three starting locations (t = 0,0.5,1) on the edge and replaces the worst
* point by the minimum of the quadratic approximation of the curve. It continues this for a specified number of iterations.
*
* The 2D method alternates between parameters u and v and makes an interpolation along one, while using the current best
* solution for the other parameter as a constant. It continues this for the specified number of iterations for each parameter.
*/
#ifndef HEARTVALVEMODEL_QUADRATICINTERPOLATION_H
#define HEARTVALVEMODEL_QUADRATICINTERPOLATION_H
#include "preprocessor.h"
class quadraticInterpolation : public preprocessor{
public:
explicit quadraticInterpolation(int iter) : preprocessor(iter){};
~quadraticInterpolation() = default;
OptState2D preprocess(surface &sur, const vec3d &P) override;
OptState1D preprocess(curve &crv, const vec3d &P) override;
};
#endif //HEARTVALVEMODEL_QUADRATICINTERPOLATION_H
| true |