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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
1eb154561234bb7f89d1f46d6614d8f151fba34b | C++ | KendalDroddy/CPP_EarlyObjects | /Chapter_6/6_6.cpp | UTF-8 | 1,804 | 3.90625 | 4 | [] | no_license | /*********************************************************************
** Author: Kendal Droddy
**
** Date: March 15, 2017
**
** Challenge: Write a program that asks for the weight of a package
** and the distance it is to be shipped. This information should be
** passed to a calculateCharge function that computes and returns the
** shipping charge to be displayed. The main function should loop to
** handle multiple packages until a weight of O is entered.
*********************************************************************/
#include <iostream>
#include <iomanip>
//Function prototype
double calculateCharge(int, int);
int main()
{
//Variables
int weight,
distance;
//Get user input
std::cout << "Calculate shipping charges for packages, or enter 0 to quit.\n";
do
{
std::cout << "\nEnter package weight (kg): ";
std::cin >> weight;
if (weight == 0)
{
return 0;
}
std::cout << "Enter distance package will be shipped (miles): ";
std::cin >> distance;
//Calculate and display results
double cost = calculateCharge(weight, distance);
std::cout << std::fixed << std::showpoint << std::setprecision(2);
std::cout << "Cost to ship package: $" << cost << "\n" << std::endl;
}while(weight != 0);
}
/*********************************************************************
** calculateCharge()
*********************************************************************/
double calculateCharge(int weight, int distance)
{
//Declare variable to hold shipping rate
double rate;
//Initialize rate depending on package weight
if (weight < 2)
rate = 3.1;
else if(weight > 2 && weight < 6)
rate = 4.20;
else if(weight > 6 && weight < 10)
rate = 5.30;
else
rate = 6.40;
//Calculate and return total charge
return (distance/500.0) * rate;
} | true |
dfab70954d430a9ab4105205541d92345db4286f | C++ | Jimut123/code-backup | /4rth_Sem_c++_backup/Amlyan/LCM.cpp | UTF-8 | 260 | 3.28125 | 3 | [
"MIT"
] | permissive | #include<iostream>
using namespace std;
// to return the LCM of a number
int main()
{
int a,b,i;
cout<<"\n Enter two numbers :\n"<<endl;
cin>>a;
cin>>b;
for(i=1;i<=b;i++)
{
if(a*i%b == 0)
{
cout<<"LCM = "<<a*i<<endl;
break;
}
}
return 0;
}
| true |
1bd578062a757d36f0a68347ce61e7f3ccc16280 | C++ | jwrzosek/PacMan | /Pill.cpp | UTF-8 | 751 | 3.046875 | 3 | [] | no_license | #include "Pill.h"
Pill::Pill()
{
this->initShape({ 0.f, 0.f });
}
Pill::Pill(sf::Vector2f shapePos)
{
this->initShape(shapePos);
}
Pill::~Pill()
{
}
void Pill::update()
{
}
void Pill::render(sf::RenderTarget& target)
{
if (!this->visited_) {
target.draw(this->shape_);
}
}
void Pill::setVisited()
{
this->shape_.setFillColor(sf::Color::Black);
this->visited_ = true;
}
bool Pill::getVisited()
{
return this->visited_;
}
void Pill::initShape(sf::Vector2f shapePos)
{
this->visited_ = false;
sf::Vector2f shifted_shape_pos = { (shapePos.x + this->shape_shift), (shapePos.y + this->shape_shift) };
this->shape_.setFillColor(sf::Color::Yellow);
this->shape_.setRadius(this->size_);
this->shape_.setPosition(shifted_shape_pos);
}
| true |
d1d6ac0dba0cd7b7c4f3488462174b13a6ebe2fb | C++ | AndriiD1/4.5 | /Project4.5/Square.cpp | UTF-8 | 720 | 3.3125 | 3 | [] | no_license | #include "Square.h"
Square::Square()
:a(0), b(0), c(0), x1(0), x2(0)
{}
Square::Square(int a, int b, int c, double x1, double x2)
: a(a), b(b), c(c), x1(x1), x2(x2)
{}
Square::Square(const Square& m)
: a(m.a), b(m.b), x1(m.x1), c(m.c), x2(m.x2)
{}
void Square::Result()
{
double D = GetB() * GetB() - 4 * GetA() * GetC();
if (D < 0)
SetX1(0);
else
{
SetX1((-1 * GetB() - sqrt(D)) / 2 * GetA());
SetX2((-1 * GetB() + sqrt(D)) / 2 * GetA());
}
}
void Square::Print()
{
cout << GetA() << "x^2" << " + " << GetB() << " x " << " + " << GetC() << " = 0 " << endl;
if (GetX1() != 0)
{
cout << "x1 = " << GetX1() << endl;
cout << "x2 = " << GetX2() << endl;
}
else
cout << "No Roots(D < 0)!" << endl;
} | true |
6fff1d09b5357e64be472e7b025e5b50e1fb1a39 | C++ | shamexln/nowcoder | /16-Merge.cpp | UTF-8 | 1,437 | 3.65625 | 4 | [] | no_license | /*合并两个有序链表*/
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
/*返回合并后的头结点,该问题可以化简为子问题,递归 */
/*
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
if (pHead1==nullptr) return pHead2;
if (pHead2==nullptr) return pHead1;
ListNode* head=nullptr;
if (pHead1->val<=pHead2->val){
head=pHead1;
head->next=Merge(pHead1->next,pHead2);
}else{
head=pHead2;
head->next=Merge(pHead1,pHead2->next);
}
return head;
}
*/
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
if (pHead1==nullptr) return pHead2;
if (pHead2==nullptr) return pHead1;
ListNode* pre1,*cur1,*pre2,*cur2;
pre1=cur1=pHead1;
pre2=cur2=pHead2;
while(cur1 && cur2){
if (cur1->val>cur2->val){
pre1->next=cur2;
while(cur2 && cur2->val<cur1->val){
pre2=cur2;
cur2=cur2->next;
}
pre2->next=cur1;
}else{
pre1=cur1;
cur1=cur1->next;
}
}
if (cur1==nullptr) pre1->next=cur2;
if (cur2==nullptr) pre2->next=cur1;
return pHead1;
}
};
| true |
37c4f81c10a5be69cc6cfe495e46ed42c9df7230 | C++ | briefgw/schunk_lwa4p_gazebo_simulation | /schunk_modular_robotics/schunk_powercube_chain/common/include/schunk_powercube_chain/Diagnostics.h | UTF-8 | 9,219 | 2.53125 | 3 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | permissive | /*!
*****************************************************************
* \file
*
* \note
* Copyright (c) 2012 \n
* Fraunhofer Institute for Manufacturing Engineering
* and Automation (IPA) \n\n
*
*****************************************************************
*
* \note
* Project name: schunk_modular_robotics
* \note
* ROS stack name: schunk_modular_robotics
* \note
* ROS package name: schunk_powercube_chain
*
* \author
* Author: Tim Fröhlich, email:tim.froehlich@ipa.fhg.de
* \author
* Supervised by: Tim Fröhlich, email:tim.froehlich@ipa.fhg.de
*
* \date Date of creation: Aug 2012
*
* \brief
* Implementation of a diagnostic class.
*
*****************************************************************
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. \n
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. \n
* - Neither the name of the Fraunhofer Institute for Manufacturing
* Engineering and Automation (IPA) nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission. \n
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License LGPL as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License LGPL for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License LGPL along with this program.
* If not, see <http://www.gnu.org/licenses/>.
*
****************************************************************/
#ifndef __DIAGNOSTICS_H_
#define __DIAGNOSTICS_H_
#include <chrono>
#include <deque>
/*!
* \brief ErrorcodeReport (helper-)class for status reporting of common libraries
*
* This class holds the error code and an error code namespace of a reported error.
* It is also a Code_Exists flag provided, which is default false and indicates that
* there is no error code for this message (e.g. if a hand written hind is reported)
* The error code namespace is used to lookup an error is there are multiple
* error code LUTs, as it is common in larger libraries.
*/
class ErrorcodeReport // Errorcode from library
{
public:
bool Code_Exists; // true when errorcode returned
int ErrorCode; // code number
std::string Errorcode_Namespace; // namespace of the code (for lookup)
/// Constructor
ErrorcodeReport() : Code_Exists(false), ErrorCode(0), Errorcode_Namespace(""){};
};
/*!
* \brief DiagnosticStatus (helper-)class for status reporting of common libraries
*
* This class holds a error level, an error message, a error recommendation, a time stamp
* and a ErrorcodeReport object. The level's default value is 0 (=OK), Message and
* Recommendation strings are empty. Time is set to now() during initializing.
*/
class DiagnosticStatus
{
public:
short Level; // 0 = OK, 1 = WARN, 2=ERROR
std::string Message; // Description of the error
std::string Recommendation; // Possible solutions for the user
ErrorcodeReport Errorcode_Report; // Errorcode that is returned from a function
std::chrono::time_point<std::chrono::system_clock> Time; // time when status is reported
/// Constructor
DiagnosticStatus() : Level(0), Message(""), Recommendation(""), Time(std::chrono::system_clock::now()){};
};
/*!
* \brief Diagnostics class for status reporting of common libraries
*
* This class is ment to provide a easy and short way to report the status
* (Errors and non-Errors) to the library itself and to ROS. It is designed close
* to the diagnostics msg topic to be easly wrapped.
*/
class Diagnosics
{
/*TODO: - select format for errorlookups (.h, .txt, yaml)
* - implement report status
* - implement read methodes
* - implement QueLength methodes
*/
public:
/// Constructor
Diagnosics()
{
m_StatusQueLength = 5; // 5 is default value
// initialize member variabeles
m_StatusList = new std::deque<DiagnosticStatus>[m_StatusQueLength];
// initialize default ok return value (default 0)
m_Default_Ok_Value = 0;
// TODO: read in errorcode lists
}
/// Destructor
~Diagnosics()
{
delete m_StatusList;
};
/*******************************************|
| Useage interface |
|*******************************************/
/// Report a Status
/*!
* \brief for simple status report by hand
*/
void ReportStatus(short Level, std::string Message)
{
DiagnosticStatus NewStatus;
NewStatus.Level = Level;
NewStatus.Time = std::chrono::system_clock::now();
NewStatus.Message = Message;
m_StatusList->push_front(NewStatus);
m_StatusList->pop_back();
}
/*!
* \brief for simple status report by hand with problem solution
*/
void ReportStatus(short Level, std::string Message, std::string Recommendation)
{
DiagnosticStatus NewStatus;
NewStatus.Level = Level;
NewStatus.Time = std::chrono::system_clock::now();
NewStatus.Message = Message;
NewStatus.Message = Recommendation;
m_StatusList->push_front(NewStatus);
m_StatusList->pop_back();
}
/*!
* \brief report with manually set level for a errorcode and additional comments
*/
void ReportStatus(short Level, int Errorcode, std::string Errorcode_Namespace, std::string Recommendation)
{
DiagnosticStatus NewStatus;
NewStatus.Level = Level;
NewStatus.Time = std::chrono::system_clock::now();
// TODO: generate message from errorcode
NewStatus.Message = Recommendation;
m_StatusList->push_front(NewStatus);
m_StatusList->pop_back();
}
/*!
* \brief automatic report of status by errorcode. Can be used for return values of library functions.
*/
void ReportStatus(int Errorcode, std::string Errorcode_Namespace)
{
DiagnosticStatus NewStatus;
// TODO: get message from errorcodelist
NewStatus.Time = std::chrono::system_clock::now();
m_StatusList->push_front(NewStatus);
m_StatusList->pop_back();
}
/// Read the status
/*!
* \brief Outputs the actual status to the passed pointers.
*
* string arguments are resized for the message
*/
void ReadActualStatus(short* Level, std::string* Message, std::string* Recommendation)
{
DiagnosticStatus ActualStatus = m_StatusList->at(0);
// resize strings for the size of the upcoming message
Message->clear();
Recommendation->clear();
// write output
Level = (short*)ActualStatus.Level;
Message->append(ActualStatus.Message);
Recommendation->append(ActualStatus.Recommendation);
}
/*!
* \brief Retuns the actual status level.
*/
int ReadActualStatusLevel()
{
DiagnosticStatus ActualStatus = m_StatusList->at(0);
return ActualStatus.Level;
}
/*!
* \brief Retuns the actual status message.
*/
std::string ReadActualStatusMessage()
{
DiagnosticStatus ActualStatus = m_StatusList->at(0);
return ActualStatus.Message;
}
/*!
* \brief Retuns the actual status recommendation.
*/
std::string ReadActualStatusRecommendation()
{
DiagnosticStatus ActualStatus = m_StatusList->at(0);
return ActualStatus.Recommendation;
}
/*******************************************|
| Configurations |
|*******************************************/
/// status que length
/*!
* \brief returns the Status que length right now
*/
int GetActualStatusQueLength()
{
return m_StatusQueLength;
}
/*!
* \brief Sets the maximal length of status history that can be read. Default is 5 elements.
*/
void SetMaxStatusQueLength(int StatusQueLength)
{
m_StatusQueLength = StatusQueLength;
}
/*!
* \brief Gets the maximal length of status history that can be read.
*/
int GetMaxStatusQueLength()
{
return m_StatusQueLength;
}
/// Default ok value read/write
/*!
* \brief returns the actual default ok value
*/
int GetDefaultOKValue()
{
return m_Default_Ok_Value = 0;
}
/*!
* \brief sets a new default ok value
*/
void SetDefaultOKValue(int Default_Ok_Value)
{
m_Default_Ok_Value = Default_Ok_Value;
}
private:
std::deque<DiagnosticStatus>* m_StatusList; // List that holds the last status messages in a deque
int m_StatusQueLength; // maximal length of status que
int m_Default_Ok_Value; // is used for check if return value needs to
// be reported
};
#endif
| true |
a78ffa9d7032800e5d4b1946f95f83a65d011951 | C++ | manthankhorwal/Competitive-programming | /GeeksForGeeks/Reverse a Linked List in groups of given size.cpp | UTF-8 | 1,508 | 3.296875 | 3 | [] | no_license | struct node *reverse (struct node *head, int k)
{
int Count=0;
stack<int> s; //this method is reverse by stack
node* temp=head;
while(temp!=NULL)
{Count++; //here we count number of nodes
temp=temp->next;
}
int num=Count/k; //divide with k to get a multiple of k
int remain=Count%k; //we will first reverse till multiple of k
//for ex. n=10 and k=4 then we first reverse 10/4=2
//means 2*k=8 nodes
//then remaining
int step;
step=0;
node* begineer=head;
node* ahead;
while(step!=num) //for every value of step we are reversing k no of nodes
{ Count=0;
node* ahead=begineer;
while(Count!=k)
{
s.push(ahead->data); //pushing k no of nodes in stack
ahead=ahead->next;
Count++;
}
while(begineer!=ahead)
{
begineer->data=s.top(); //assigning top of stack to first of node of window of k elements
s.pop();
begineer=begineer->next;
}
step++;
}
node* begineer1=begineer;
while(begineer!=NULL) //then for the remaining nodes
{
s.push(begineer->data);
begineer=begineer->next;
}
while(begineer1!=NULL)
{
begineer1->data=s.top();
s.pop();
begineer1=begineer1->next;
}return head;}
| true |
36d8a62203be68042f44e9396dcc6eb73396abfc | C++ | harukishima/BrickGame-SFML | /BrickGame/Brick.cpp | UTF-8 | 1,632 | 2.625 | 3 | [] | no_license | #include "Brick.h"
Brick::Brick()
{
setOutlineColor(sf::Color::Black);
setOutlineThickness(-2);
setFillColor(sf::Color::Transparent);
setSize(sf::Vector2f(mWidth * WinWidthRatio / wallWidth, mHeight * WinHeightRatio / wallHeight));
//50
//26.6
}
void Brick::checkCollision(Ball& ball)
{
if (HP == 0) return;
sf::Vector2f pos(ball.getPosition()), dir(ball.getDirection());
float radius = ball.getRadius();
sf::Vector2f brickPos(this->getPosition()), brickSize(this->getSize());
if (pos.x >= brickPos.x && pos.x <= brickPos.x + brickSize.x && pos.y + radius >= brickPos.y && pos.y - radius <= brickPos.y + brickSize.y)
{
if (pos.y + radius < brickPos.y + brickSize.y)
{
pos.y = brickPos.y - radius;
}
if (pos.y - radius > brickPos.y)
{
pos.y = brickPos.y + brickSize.y + radius;
}
dir.y = -dir.y;
damage();
ting.play();
}
if (pos.y >= brickPos.y && pos.y <= brickPos.y + brickSize.y && pos.x + radius >= brickPos.x && pos.x - radius <= brickPos.x + brickSize.x)
{
if (pos.x + radius < brickPos.x + brickSize.x)
{
pos.x = brickPos.x - radius;
}
if (pos.x - radius > brickPos.x)
{
pos.x = brickPos.x + brickSize.x + radius;
}
dir.x = -dir.x;
damage();
ting.play();
}
ball.setPosition(pos);
ball.setDirection(dir);
}
int Brick::getHP()
{
return HP;
}
int Brick::getScore()
{
return score;
}
void Brick::damage()
{
HP--;
if (HP <= hpBar / 2.f)
changeTexture();
}
void Brick::changeTexture()
{
if (HP != 0)
{
setTexture(&brickTex[1]);
}
}
void Brick::paddleAction(Paddle& player)
{
if (HP == 0)
{
player.setScore(player.getScore() + getScore());
}
}
| true |
d15b1b7314485d1f0e6fea706dd58a7b28a59ca3 | C++ | KushRohra/GFG_Codes | /Basic/Remove duplicate elements from sorted Array.cpp | UTF-8 | 166 | 2.65625 | 3 | [] | no_license | int remove_duplicate(int A[],int N)
{
int i=0,curr=0;
for(i=1;i<N;i++)
{
if(A[i]!=A[curr])
A[++curr]=A[i];
}
return curr+1;
}
| true |
dfe2ea5d0ff83a3adcdf95cc8f32ab6dca4f3c07 | C++ | MahaAmin/Algorithms | /Problem_Solving/Rosalind/INS.cpp | UTF-8 | 641 | 2.8125 | 3 | [] | no_license | #include <iostream>
#include <sstream>
#include <fstream>
using namespace std;
int INS(string fileName, int size)
{
int arr[size];
ifstream myfile(fileName);
string line;
int i = 0;
while(getline(myfile, line))
{
stringstream anyth(line);
while(anyth.good() && i<size)
{
anyth >> arr[i];
i++;
}
}
double key;
int counter = 0;
for(int i=1; i<size; i++)
{
key = arr[i];
int j = i-1;
while(j>=0 && arr[j] > key)
{
arr[j+1] = arr[j];
j--;
counter++;
}
arr[j+1] = key;
}
return counter;
}
int main()
{
cout<<INS("rosalind_ins.txt", 875)<<endl;
}
| true |
6b65b1c812650e43dea8fc72485bb1dca26c3380 | C++ | sequoian/dx-engine | /Source/Window.cpp | UTF-8 | 3,981 | 2.78125 | 3 | [] | no_license | #include "Window.h"
Window* g_pWindow;
Window window;
Window::Window()
{
g_pWindow = this;
m_isFullscreen = false;
}
Window::~Window()
{
}
bool Window::Initialize()
{
// Get the instance of this application.
m_hInstance = GetModuleHandle(NULL);
// Give the application a name.
m_appName = "Engine";
// Setup the windows class with default settings.
WNDCLASSEX wc;
ZeroMemory(&wc, sizeof(WNDCLASSEX));
wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
wc.lpfnWndProc = WndProc;
wc.hInstance = m_hInstance;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
wc.lpszClassName = m_appName;
wc.cbSize = sizeof(WNDCLASSEX);
// Register the window class.
RegisterClassEx(&wc);
// Determine the resolution of the clients desktop screen.
int screenWidth = GetSystemMetrics(SM_CXSCREEN);
int screenHeight = GetSystemMetrics(SM_CYSCREEN);
// Setup the screen settings depending on whether it is running in full screen or in windowed mode.
int posX, posY;
if (m_isFullscreen)
{
// If full screen set the screen to maximum size of the users desktop and 32bit.
DEVMODE dmScreenSettings;
memset(&dmScreenSettings, 0, sizeof(dmScreenSettings));
dmScreenSettings.dmSize = sizeof(dmScreenSettings);
dmScreenSettings.dmPelsWidth = (unsigned long)screenWidth;
dmScreenSettings.dmPelsHeight = (unsigned long)screenHeight;
dmScreenSettings.dmBitsPerPel = 32;
dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
// Change the display settings to full screen.
ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN);
// Set the position of the window to the top left corner.
posX = posY = 0;
}
else
{
// If windowed then set it to 800x600 resolution.
screenWidth = 800;
screenHeight = 600;
// Place the window in the middle of the screen.
posX = (GetSystemMetrics(SM_CXSCREEN) - screenWidth) / 2;
posY = (GetSystemMetrics(SM_CYSCREEN) - screenHeight) / 2;
}
// Create the window with the screen settings and get the handle to it.
m_hWnd = CreateWindowEx(
WS_EX_APPWINDOW, // extended window style
m_appName, // name of window class
m_appName, // title of window
WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_POPUP, // window style
posX, posY, // position of window
screenWidth, screenHeight, // dimensions of window
NULL, // parent window
NULL, // menus
m_hInstance, // application handle
NULL // for use with multiple windows
);
// Bring the window up on the screen and set it as main focus.
ShowWindow(m_hWnd, SW_SHOW);
SetForegroundWindow(m_hWnd);
SetFocus(m_hWnd);
return true;
}
void Window::Shutdown()
{
// Fix the display settings if leaving full screen mode.
if (m_isFullscreen)
{
ChangeDisplaySettings(NULL, 0);
}
// Remove the window.
DestroyWindow(m_hWnd);
m_hWnd = NULL;
// Remove the application instance.
UnregisterClass(m_appName, m_hInstance);
m_hInstance = NULL;
// Release the pointer to this class.
g_pWindow = NULL;
return;
}
void Window::Run()
{
// Initialize the message structure.
MSG msg;
ZeroMemory(&msg, sizeof(MSG));
// Loop until there is a quit message from the window or the user.
bool done = false;
while (!done)
{
// Handle the windows messages.
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
// If windows signals to end the application then exit out.
if (msg.message == WM_QUIT)
{
done = true;
}
}
return;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT uMessage, WPARAM wParam, LPARAM lParam)
{
switch (uMessage)
{
// Check if the window is being destroyed.
case WM_DESTROY:
{
PostQuitMessage(0);
return 0;
}
// Check if the window is being closed.
case WM_CLOSE:
{
PostQuitMessage(0);
return 0;
}
// All other messages pass to the message handler in the system class.
default:
{
return DefWindowProc(hWnd, uMessage, wParam, lParam);
}
}
} | true |
ed6cce7b40eab85867fc3163a5e31fb670a0f7ee | C++ | jmavis/CodingChallenges | /C++ and C/Hard/StringSeaching.cpp | UTF-8 | 1,776 | 3.5625 | 4 | [] | no_license | #include <stdio.h>
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
/*
void ParseLine(string line);
string ContainsSubstring(string base, unsigned int endOfBaseString);
/// Author Jared Mavis
/// Username jmavis
/// CodeEval String Searching
int main (int argc, char* argv[]){
ifstream file;
file.open(argv[1]);
string lineBuffer;
while (!file.eof()) {
getline(file, lineBuffer);
if (lineBuffer.length() == 0){
continue; //ignore all empty lines
} else {
ParseLine(lineBuffer);
}
}
}
/// Will call ContainsSubstring with the given line and print out the result
void ParseLine(string line){
int endOfBaseString = line.find(",");
cout << ContainsSubstring(line, endOfBaseString) << endl;
}
/// Will return true if the substrings occur inside of the given base string in order
string ContainsSubstring(string base, unsigned int endOfBaseString){
unsigned int sequenceIndex = 0;
unsigned int baseIndex = 0;
while (baseIndex < endOfBaseString && sequenceIndex+endOfBaseString+1 < base.length()){
char toFind = base[sequenceIndex+endOfBaseString+1];
if ((toFind == '/' && sequenceIndex+endOfBaseString+2 < base.length() && base[sequenceIndex+endOfBaseString+2] == '*') ||
(toFind == '*')) {
sequenceIndex++;
while (sequenceIndex < base.length() && base[sequenceIndex+endOfBaseString+1] == '*'){
sequenceIndex++;
}
}
if (base[baseIndex] == base[sequenceIndex+endOfBaseString+1]){
sequenceIndex++;
}
baseIndex++;
}
if (baseIndex == endOfBaseString && sequenceIndex+endOfBaseString+1 != base.length()){ // if we got through all the base string first then we didn't find the subsequence
return ("false");
} else {
return ("true");
}
}*/ | true |
583a3445490006e302b8765fc34b004e1fc8735e | C++ | DevinLeamy/Competitive-Programming | /Concepts/Dynammic_Programming/LCS.cpp | UTF-8 | 726 | 2.796875 | 3 | [] | no_license | #include <iostream>
using namespace std;
string dp[3001][3001];
int main() {
ios_base::sync_with_stdio(0);
string top, bottom;
cin >> top >> bottom;
for (int i = 1; i <= top.length(); i++) {
for (int j = 1; j <= bottom.length(); j++) {
if (top[i-1] == bottom[j-1]) {
dp[i][j] += top[i-1];
}
string newString;
newString = dp[i-1][j];
if (dp[i][j-1].length() > newString.length()) {newString = dp[i][j-1];}
if ((dp[i-1][j-1] + dp[i][j]).length() > newString.length()) {newString = dp[i-1][j-1] + dp[i][j];}
dp[i][j] = newString;
}
}
cout << dp[top.length()][bottom.length()] << endl;
}
| true |
278dccadc71318a69ee133b6a5f06b9f1044d78f | C++ | smsm8087/cabinet | /3d/랜더링파이프라인/Test.h | UTF-8 | 492 | 2.71875 | 3 | [] | no_license |
class Test
{
protected:
D3DXVECTOR2 worldPos;
float Angle;
bool isActive;
public:
virtual void Update() = 0;
virtual void Render() = 0;
virtual void SetAngle(float _Angle) { Angle = _Angle; }
virtual float GetAngle() { return Angle; }
virtual void SetActive(bool _isActive) { isActive = _isActive; }
virtual bool GetActive() { return isActive; }
virtual D3DXVECTOR2 GetWorldPos() { return worldPos; }
virtual void SetWorldPos(D3DXVECTOR2 _worldPos) { worldPos = _worldPos; }
}; | true |
d522a29279907e21adfa849609b7518e6064cd30 | C++ | hoge-fuga-piyo/bundlerWithModernLibraries | /src/core/hash_key.hpp | UTF-8 | 273 | 2.953125 | 3 | [] | no_license | #ifndef HASH_KEY_HPP
#define HASH_KEY_HPP
#include <tuple>
namespace std {
template<>
class hash<std::tuple<int, int>>{
public:
size_t operator () (const std::tuple<int, int> &map) const {
return std::get<0>(map)*std::get<1>(map);
}
};
}
#endif | true |
4e2726af11eaf86280d80c88508fc1591461a717 | C++ | kakaroto/e17 | /BINDINGS/cxx/edjexx/include/edjexx/StateEdit.h | UTF-8 | 24,442 | 2.65625 | 3 | [
"BSD-3-Clause"
] | permissive | #ifndef STATE_EDIT_H
#define STATE_EDIT_H
/* STD */
#include <string>
/* Project */
#include "Edit.h"
namespace Edjexx {
class StateEdit
{
public:
/*!
* Set a new name for the given state in the given part.
* Note that state and new_name must include the floating value inside the string (ex. "default 0.00")
*
* @param newName The new name to assign (including the value)
*
* @return true on success, false on failure
*/
bool setName (const std::string &newName, double newValue);
const std::string getName () const;
double getValue () const;
/*!
* Get the rel1 relative x value of state
*
* @return The 'rel1 relative X' value of the part state
*/
double getXRelativeRel1 () const;
/*!
* Get the rel1 relative y value of state
*
* @return The 'rel1 relative Y' value of the part state
*/
double getYRelativeRel1 () const;
/*!
* Get the rel2 relative x value of state
*
* @return The 'rel2 relative X' value of the part state
*/
double getXRelativeRel2 () const;
/*!
* Get the rel2 relative y value of state
*
* @return The 'rel2 relative Y' value of the part state
*/
double getYRelativeRel2 () const;
/*!
* Set the rel1 relative x value of state
*
* @param x The new 'rel1 relative X' value to set
*/
void setXRelativeRel1 (double x);
/*!
* Set the rel1 relative y value of state
*
* @param y The new 'rel1 relative Y' value to set
*/
void setYRelativeRel1 (double y);
/*!
* Set the rel2 relative x value of state
*
* @param x The new 'rel2 relative X' value to set
*/
void setXRelativeRel2 (double x);
/*!
* Set the rel2 relative y value of state
*
* @param y The new 'rel2 relative Y' value to set
*/
void setYRelativeRel2 (double y);
#if 0
/**Get the rel1 offset y value of state*/
EAPI int /// @return The 'rel1 offset Y' value of the part state
edje_edit_state_rel1_offset_y_get(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state ///< The name of the 'part state' (ex. "default 0.00")
);
/**Get the rel2 offset x value of state*/
EAPI int /// @return The 'rel2 offset X' value of the part state
edje_edit_state_rel2_offset_x_get(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state ///< The name of the 'part state' (ex. "default 0.00")
);
/**Get the rel2 offset y value of state*/
EAPI int /// @return The 'rel2 offset Y' value of the part state
edje_edit_state_rel2_offset_y_get(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state ///< The name of the 'part state' (ex. "default 0.00")
);
/**Set the rel1 offset x value of state*/
EAPI void
edje_edit_state_rel1_offset_x_set(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state, ///< The name of the 'part state' (ex. "default 0.00")
double x ///< The new 'rel1 offset X' value to set
);
/**Get the rel1 offset y value of state*/
EAPI void
edje_edit_state_rel1_offset_y_set(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state, ///< The name of the 'part state' (ex. "default 0.00")
double y ///< The new 'rel1 offset Y' value to set
);
/**Get the rel2 offset x value of state*/
EAPI void
edje_edit_state_rel2_offset_x_set(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state, ///< The name of the 'part state' (ex. "default 0.00")
double x ///< The new 'rel2 offset X' value to set
);
/**Get the rel2 offset y value of state*/
EAPI void
edje_edit_state_rel2_offset_y_set(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state, ///< The name of the 'part state' (ex. "default 0.00")
double y ///< The new 'rel2 offset Y' value to set
);
/**Get the part name rel1x is relative to. The function return NULL if the part is relative to the whole interface.*/
EAPI const char * ///@return The name of the part to apply the relativity
edje_edit_state_rel1_to_x_get(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state ///< The name of the 'part state' (ex. "default 0.00")
);
/**Get the part name rel1y is relative to. The function return NULL if the part is relative to the whole interface.*/
EAPI const char * ///@return The name of the part to apply the relativity
edje_edit_state_rel1_to_y_get(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state ///< The name of the 'part state' (ex. "default 0.00")
);
/**Get the part name rel2x is relative to. The function return NULL if the part is relative to the whole interface.*/
EAPI const char * ///@return The name of the part to apply the relativity
edje_edit_state_rel2_to_x_get(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state ///< The name of the 'part state' (ex. "default 0.00")
);
/**Get the part name rel2y is relative to. The function return NULL if the part is relative to the whole interface.*/
EAPI const char * ///@return The name of the part to apply the relativity
edje_edit_state_rel2_to_y_get(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state ///< The name of the 'part state' (ex. "default 0.00")
);
/**Set the part rel1x is relative to. Set rel_to to NULL make the part relative to the whole interface.*/
EAPI void
edje_edit_state_rel1_to_x_set(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state, ///< The name of the 'part state' (ex. "default 0.00")
const char *rel_to ///< The name of the part that is used as container/parent
);
/**Set the part rel1y is relative to. Set rel_to to NULL make the part relative to the whole interface.*/
EAPI void
edje_edit_state_rel1_to_y_set(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state, ///< The name of the 'part state' (ex. "default 0.00")
const char *rel_to ///< The name of the part that is used as container/parent
);
/**Set the part rel2x is relative to. Set rel_to to NULL make the part relative to the whole interface.*/
EAPI void
edje_edit_state_rel2_to_x_set(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state, ///< The name of the 'part state' (ex. "default 0.00")
const char *rel_to ///< The name of the part that is used as container/parent
);
/**Set the part rel2y is relative to. Set rel_to to NULL make the part relative to the whole interface.*/
EAPI void
edje_edit_state_rel2_to_y_set(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state, ///< The name of the 'part state' (ex. "default 0.00")
const char *rel_to ///< The name of the part that is used as container/parent
);
/**Get the color of a part state. Pass NULL to any of [r,g,b,a] to get only the others.*/
EAPI void
edje_edit_state_color_get(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state, ///< The name of the 'part state' (ex. "default 0.00")
int *r, ///< A pointer to store the red value
int *g, ///< A pointer to store the green value
int *b, ///< A pointer to store the blue value
int *a ///< A pointer to store the alpha value
);
/**Get the color2 of a part state. Pass NULL to any of [r,g,b,a] to get only the others.*/
EAPI void
edje_edit_state_color2_get(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state, ///< The name of the 'part state' (ex. "default 0.00")
int *r, ///< A pointer to store the red value
int *g, ///< A pointer to store the green value
int *b, ///< A pointer to store the blue value
int *a ///< A pointer to store the alpha value
);
/**Get the color3 of a part state. Pass NULL to any of [r,g,b,a] to get only the others.*/
EAPI void
edje_edit_state_color3_get(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state, ///< The name of the 'part state' (ex. "default 0.00")
int *r, ///< A pointer to store the red value
int *g, ///< A pointer to store the green value
int *b, ///< A pointer to store the blue value
int *a ///< A pointer to store the alpha value
);
/**Set the color of a part state. Pass -1 to any of [r,g,b,a] to leave the value untouched.*/
EAPI void
edje_edit_state_color_set(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state, ///< The name of the 'part state' (ex. "default 0.00")
int r, ///< The red value of the color
int g, ///< The green value of the color
int b, ///< The blue value of the color
int a ///< The alpha value of the color
);
/**Set the color2 of a part state. Pass -1 to any of [r,g,b,a] to leave the value untouched.*/
EAPI void
edje_edit_state_color2_set(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state, ///< The name of the 'part state' (ex. "default 0.00")
int r, ///< The red value of the color
int g, ///< The green value of the color
int b, ///< The blue value of the color
int a ///< The alpha value of the color
);
/**Set the color3 of a part state. Pass -1 to any of [r,g,b,a] to leave the value untouched.*/
EAPI void
edje_edit_state_color3_set(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state, ///< The name of the 'part state' (ex. "default 0.00")
int r, ///< The red value of the color
int g, ///< The green value of the color
int b, ///< The blue value of the color
int a ///< The alpha value of the color
);
/**Get the align_x value of a part state.*/
EAPI double ///@return The horizontal align value for the given state
edje_edit_state_align_x_get(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state ///< The name of the 'part state' (ex. "default 0.00")
);
/**Get the align_y value of a part state.*/
EAPI double ///@return The vertical align value for the given state
edje_edit_state_align_y_get(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state ///< The name of the 'part state' (ex. "default 0.00")
);
/**Set the align_x value of a part state.*/
EAPI void
edje_edit_state_align_x_set(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state, ///< The name of the 'part state' (ex. "default 0.00")
double align ///< The new horizontal align to set
);
/**Set the align_y value of a part state.*/
EAPI void
edje_edit_state_align_y_set(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state, ///< The name of the 'part state' (ex. "default 0.00")
double align ///< The new vertical align to set
);
/**Get the min_w value of a part state.*/
EAPI int ///@return The minimum width of a part state
edje_edit_state_min_w_get(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state ///< The name of the 'part state' (ex. "default 0.00")
);
/**Set the min_w value of a part state.*/
EAPI void
edje_edit_state_min_w_set(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state, ///< The name of the 'part state' (ex. "default 0.00")
int min_w ///< The new minimum width to set for the part state
);
/**Get the min_h value of a part state.*/
EAPI int ///@return The minimum height of a part state
edje_edit_state_min_h_get(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state ///< The name of the 'part state' (ex. "default 0.00")
);
/**Set the min_h value of a part state.*/
EAPI void
edje_edit_state_min_h_set(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state, ///< The name of the 'part state' (ex. "default 0.00")
int min_h ///< The new minimum height to set for the part state
);
/**Get the max_w value of a part state.*/
EAPI int ///@return The maximum width of a part state
edje_edit_state_max_w_get(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state ///< The name of the 'part state' (ex. "default 0.00")
);
/**Set the max_w value of a part state.*/
EAPI void
edje_edit_state_max_w_set(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state, ///< The name of the 'part state' (ex. "default 0.00")
int max_w ///< The new maximum width to set for the part state
);
/**Get the max_h value of a part state.*/
EAPI int ///@return The maximum height of a part state
edje_edit_state_max_h_get(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state ///< The name of the 'part state' (ex. "default 0.00")
);
/**Set the max_h value of a part state.*/
EAPI void
edje_edit_state_max_h_set(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state, ///< The name of the 'part state' (ex. "default 0.00")
int max_h ///< The new maximum height to set for the part state
);
/**Get the minimum aspect value of a part state.*/
EAPI double ///@return The aspect minimum value of a part state
edje_edit_state_aspect_min_get(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state ///< The name of the 'part state' (ex. "default 0.00")
);
/**Get the maximum aspect value of a part state.*/
EAPI double ///@return The aspect maximum value of a part state
edje_edit_state_aspect_max_get(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state ///< The name of the 'part state' (ex. "default 0.00")
);
/**Set the minimum aspect value of a part state.*/
EAPI void
edje_edit_state_aspect_min_set(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state, ///< The name of the 'part state' (ex. "default 0.00")
double aspect ///< The new minimum aspect value to set
);
/**Set the maximum aspect value of a part state.*/
EAPI void
edje_edit_state_aspect_max_set(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state, ///< The name of the 'part state' (ex. "default 0.00")
double aspect ///< The new maximum aspect value to set
);
/**Get the aspect preference value of a part state.*/
EAPI unsigned char ///@return The aspect preference (0=none, 1=vertical, 2=horizontal, 3=both)
edje_edit_state_aspect_pref_get(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state ///< The name of the 'part state' (ex. "default 0.00")
);
/**Set the aspect preference value of a part state.*/
EAPI void
edje_edit_state_aspect_pref_set(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state, ///< The name of the 'part state' (ex. "default 0.00")
unsigned char pref ///< The new aspect preference to set (0=none, 1=vertical, 2=horizontal, 3=both)
);
/**Get the fill origin relative x value of a part state.*/
EAPI double ///@return The fill offset x relative to area
edje_edit_state_fill_origin_relative_x_get(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state ///< The name of the 'part state' (ex. "default 0.00")
);
/**Get the fill origin relative y value of a part state.*/
EAPI double ///@return The fill origin y relative to area
edje_edit_state_fill_origin_relative_y_get(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state ///< The name of the 'part state' (ex. "default 0.00")
);
/**Get the fill origin offset x value of a part state.*/
EAPI int ///@return The fill origin offset x relative to area
edje_edit_state_fill_origin_offset_x_get(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state ///< The name of the 'part state' (ex. "default 0.00")
);
/**Get the fill origin offset y value of a part state.*/
EAPI int ///@return The fill origin offset y relative to area
edje_edit_state_fill_origin_offset_y_get(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state ///< The name of the 'part state' (ex. "default 0.00")
);
/**Set the fill origin relative x value of a part state.*/
EAPI void
edje_edit_state_fill_origin_relative_x_set(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state, ///< The name of the 'part state' (ex. "default 0.00")
double x ///< The new value to set
);
/**Set the fill origin relative y value of a part state.*/
EAPI void
edje_edit_state_fill_origin_relative_y_set(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state, ///< The name of the 'part state' (ex. "default 0.00")
double x ///< The new value to set
);
/**Set the fill origin offset x value of a part state.*/
EAPI void
edje_edit_state_fill_origin_offset_x_set(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state, ///< The name of the 'part state' (ex. "default 0.00")
double x ///< The new value to set
);
/**Set the fill origin offset x value of a part state.*/
EAPI void
edje_edit_state_fill_origin_offset_y_set(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state, ///< The name of the 'part state' (ex. "default 0.00")
double y ///< The new value to set
);
/**Get the fill size relative x value of a part state.*/
EAPI double ///@return The fill size offset x relative to area
edje_edit_state_fill_size_relative_x_get(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state ///< The name of the 'part state' (ex. "default 0.00")
);
/**Get the fill size relative y value of a part state.*/
EAPI double ///@return The fill size y relative to area
edje_edit_state_fill_size_relative_y_get(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state ///< The name of the 'part state' (ex. "default 0.00")
);
/**Get the fill size offset x value of a part state.*/
EAPI int ///@return The fill size offset x relative to area
edje_edit_state_fill_size_offset_x_get(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state ///< The name of the 'part state' (ex. "default 0.00")
);
/**Get the fill size offset y value of a part state.*/
EAPI int ///@return The fill size offset y relative to area
edje_edit_state_fill_size_offset_y_get(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state ///< The name of the 'part state' (ex. "default 0.00")
);
/**Set the fill size relative x value of a part state.*/
EAPI void
edje_edit_state_fill_size_relative_x_set(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state, ///< The name of the 'part state' (ex. "default 0.00")
double x ///< The new value to set
);
/**Set the fill size relative y value of a part state.*/
EAPI void
edje_edit_state_fill_size_relative_y_set(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state, ///< The name of the 'part state' (ex. "default 0.00")
double x ///< The new value to set
);
/**Set the fill size offset x value of a part state.*/
EAPI void
edje_edit_state_fill_size_offset_x_set(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state, ///< The name of the 'part state' (ex. "default 0.00")
double x ///< The new value to set
);
/**Set the fill size offset x value of a part state.*/
EAPI void
edje_edit_state_fill_size_offset_y_set(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state, ///< The name of the 'part state' (ex. "default 0.00")
double y ///< The new value to set
);
#endif
/*!
* Get the visibility of a part state.
*
* @return true if the state is visible
*/
bool getVisibility ();
/*!
* Set the visibility of a part state.
*
* @param visible true to set the state visible
*/
void setVisibility (bool visible);
#if 0
/**Get the color class of the given part state. Remember to free the string with edje_edit_string_free()*/
EAPI const char* ///@return The current color_class of the part state
edje_edit_state_color_class_get(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state ///< The name of the 'part state' (ex. "default 0.00")
);
/**Set the color class for the given part state.*/
EAPI void
edje_edit_state_color_class_set(
Evas_Object *obj, ///< The edje object
const char *part, ///< The name of the part
const char *state, ///< The name of the 'part state' (ex. "default 0.00")
const char *color_class ///< The new color_class to assign
);
#endif
void copyFrom (StateEdit &state);
protected:
StateEdit (Edit &edit, const std::string &part, const std::string &state, double value);
Edit *mEdit;
std::string mPart;
std::string mState;
double mValue;
private:
};
} // end namespace Edjexx
#endif // STATE_EDIT_H
| true |
f108fdc6cace47f9b178815d1a70b03d55f78472 | C++ | quickfix/quickfix | /src/C++/Dictionary.h | UTF-8 | 2,870 | 2.609375 | 3 | [
"BSD-2-Clause"
] | permissive | /* -*- C++ -*- */
/****************************************************************************
** Copyright (c) 2001-2014
**
** This file is part of the QuickFIX FIX Engine
**
** This file may be distributed under the terms of the quickfixengine.org
** license as defined by quickfixengine.org and appearing in the file
** LICENSE included in the packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.quickfixengine.org/LICENSE for licensing information.
**
** Contact ask@quickfixengine.org if any conditions of this licensing are
** not clear to you.
**
****************************************************************************/
#ifndef FIX_DICTIONARY_H
#define FIX_DICTIONARY_H
#ifdef _MSC_VER
#pragma warning( disable : 4503 4355 4786 4290 )
#endif
#include <map>
#include <string>
#include "Exceptions.h"
namespace FIX
{
/// For storage and retrieval of key/value pairs.
class Dictionary
{
public:
Dictionary( const std::string& name ) : m_name( name ) {}
Dictionary() {}
virtual ~Dictionary() {}
typedef std::map < std::string, std::string > Data;
typedef Data::const_iterator iterator;
typedef iterator const_iterator;
typedef Data::value_type value_type;
/// Get the name of the dictionary.
std::string getName() const { return m_name; }
/// Return the number of key/value pairs.
size_t size() const { return m_data.size(); }
/// Get a value as a string.
std::string getString( const std::string&, bool capitalize = false ) const
EXCEPT ( ConfigError, FieldConvertError );
/// Get a value as a int.
int getInt( const std::string& ) const
EXCEPT ( ConfigError, FieldConvertError );
/// Get a value as a double.
double getDouble( const std::string& ) const
EXCEPT ( ConfigError, FieldConvertError );
/// Get a value as a bool
bool getBool( const std::string& ) const
EXCEPT ( ConfigError, FieldConvertError );
/// Get a value as a day of week
int getDay( const std::string& ) const
EXCEPT ( ConfigError, FieldConvertError );
/// Set a value from a string.
void setString( const std::string&, const std::string& );
/// Set a value from a int.
void setInt( const std::string&, int );
/// Set a value from a double.
void setDouble( const std::string&, double );
/// Set a value from a bool
void setBool( const std::string&, bool );
/// Set a value from a day
void setDay( const std::string&, int );
/// Check if the dictionary contains a value for key.
bool has( const std::string& ) const;
/// Merge two dictionaries.
void merge( const Dictionary& );
iterator begin() const { return m_data.begin(); }
iterator end() const { return m_data.end(); }
private:
Data m_data;
std::string m_name;
};
/*! @} */
}
#endif //FIX_DICTIONARY_H
| true |
a1cf8fba72e672e1d2a4be147b9211ffed3cf94d | C++ | pedrovponte/AEDA | /aeda1920_fp07/Tests/dicionario.cpp | UTF-8 | 1,857 | 3.203125 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <fstream>
#include "dicionario.h"
#include "bst.h"
using namespace std;
BST<PalavraSignificado> Dicionario::getPalavras() const {
return palavras;
}
//a alterar
bool PalavraSignificado::operator < (const PalavraSignificado &ps1) const {
return palavra < ps1.palavra;
}
bool PalavraSignificado::operator == (const PalavraSignificado &ps1) const {
return palavra == ps1.palavra;
}
//a alterar
void Dicionario::lerDicionario(ifstream &fich)
{
string pal, sig;
while(!fich.eof()){
getline(fich, pal);
getline(fich, sig);
PalavraSignificado p1(pal, sig);
palavras.insert(p1);
}
}
//a alterar
string Dicionario::consulta(string palavra) const
{
PalavraSignificado p1(palavra,"");
PalavraSignificado px=palavras.find(p1);
PalavraSignificado pNotFound("","");
if (px==pNotFound)
{
BSTItrIn<PalavraSignificado> it(palavras);
string palAntes="",signifAntes="";
while (!it.isAtEnd() && it.retrieve()<p1)
{
palAntes=it.retrieve().getPalavra();
signifAntes=it.retrieve().getSignificado();
it.advance();
}
string palApos="",signifApos="";
if (!it.isAtEnd())
{
palApos=it.retrieve().getPalavra();
signifApos=it.retrieve().getSignificado();
}
throw PalavraNaoExiste(palAntes,signifAntes,palApos,signifApos);
}
else
return px.getSignificado();
}
//a alterar
bool Dicionario::corrige(string palavra, string significado)
{
return 0;
}
//a alterar
void Dicionario::imprime() const
{
BSTItrIn<PalavraSignificado> it(palavras);
while(!it.isAtEnd()){
cout << it.retrieve().getPalavra() << endl << it.retrieve().getSignificado() << endl;
it.advance();
}
}
| true |
929fdc9fd827f0f1581a107d4d8e121e3a6b4cd5 | C++ | iCoder0020/Competitive-Coding | /Codeforces/Codeforces Round #909/B. Segments.cpp | UTF-8 | 284 | 2.578125 | 3 | [] | no_license | /*
ID: iCoder0020
PROG: Segments
LANG: C++
*/
#include <iostream>
using namespace std;
int ans(int N)
{
if(N <= 2)
{
return N;
}
else
{
return ans(N-2) + N;
}
}
int main()
{
int N;
cin>>N;
cout<<ans(N)<<"\n";
return 0;
} | true |
84e8dc40c41b057e1c2a57513d09d185d1f1de87 | C++ | zijuan0810/calm3dx | /example/05/SimpleData.cpp | GB18030 | 5,905 | 2.9375 | 3 | [] | no_license | #include "SimpleData.h"
bool SimpleData::init()
{
if (!GLView::init()) {
return false;
}
_glProgram.setVertShader("shaders/05/vsh.glsl");
_glProgram.setFragShader("shaders/05/fsh.glsl");
// Generate a name for the buffer
glGenBuffers(MAX_BUFF_NUM, _buffers);
// Now bind it to the context using the GL_ARRAY_BUFFER binding point
//glBindBuffer(GL_ARRAY_BUFFER, _buffers[0]);
// Specify the amount of storage we want to use for the buffer
//glBufferData(GL_ARRAY_BUFFER, 1024 * 1024, nullptr, GL_STATIC_DRAW);
// Generate our attribute array
glGenVertexArrays(1, &_vao);
glBindVertexArray(_vao);
return true;
}
void SimpleData::render(double time)
{
const GLfloat black[] = { 0.0f, 0.0f, 0.0f, 1.0f };
glClearBufferfv(GL_COLOR, 0, black);
//render_updateBufferMethod1();
//render_updateBufferMethod2();
//render_arrayOfStructure();
render_structureOfArray();
}
void SimpleData::onEnter()
{
GLView::onEnter();
}
void SimpleData::onExit()
{
glDeleteVertexArrays(1, &_vao);
GLView::onExit();
}
void SimpleData::render_updateBufferMethod1()
{
// Դ
// This is the data that we will place into the buffer object
static float data_pos[] = {
0.25, -0.25, 0.0, 1.0,
-0.25, -0.25, 0.5, 1.0,
0.25, 0.25, 0.5, 1.0
};
// Now bind it to the context using the GL_ARRAY_BUFFER binding point
glBindBuffer(GL_ARRAY_BUFFER, _buffers[0]);
// Specify the amount of storage we want to use for the buffer
glBufferData(GL_ARRAY_BUFFER, sizeof(data_pos), nullptr, GL_STATIC_DRAW);
// buffer
// Put the data into the buffer at offset 0
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(data_pos), data_pos);
// First, bind our buffer object to the GL_ARRAY_BUFFER binding
// The subsequent call to glVertexAttributePointer will refrence this buffer
glBindBuffer(GL_ARRAY_BUFFER, _buffers[0]);
// vertex
// Now, describe the data to OpenGL, tell it where it is, and turn on
// automatic vertex fething for the specified attribute
glVertexAttribPointer(
0, // Attribute location 0
4, // Four components
GL_FLOAT, // Floating-point type data
GL_FALSE, // Not normalized (floating-point data never is)
0, // Stride, tightly packed
nullptr); // Offset zero (nullptr pointer)
glEnableVertexAttribArray(0);
glUseProgram(_glProgram.getProgram());
glDrawArrays(GL_TRIANGLES, 0, 3);
glDisableVertexAttribArray(0);
}
void SimpleData::render_updateBufferMethod2()
{
// Դ
// This is the data that we will place into the buffer object
static float data_pos[] = {
0.25, -0.25, 0.0, 1.0,
-0.25, -0.25, 0.5, 1.0,
0.25, 0.25, 0.5, 1.0
};
// Now bind it to the context using the GL_ARRAY_BUFFER binding point
glBindBuffer(GL_ARRAY_BUFFER, _buffers[0]);
// Specify the amount of storage we want to use for the buffer
glBufferData(GL_ARRAY_BUFFER, sizeof(data_pos), nullptr, GL_STATIC_DRAW);
// buffer - 2
// Get the pointer to the buffer's data store
void* ptr = glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY);
// Copy our data in it...
memcpy(ptr, data_pos, sizeof(data_pos));
// Tell OpenGL that we're done with the pointer
glUnmapBuffer(GL_ARRAY_BUFFER);
// First, bind our buffer object to the GL_ARRAY_BUFFER binding
// The subsequent call to glVertexAttributePointer will refrence this buffer
glBindBuffer(GL_ARRAY_BUFFER, _buffers[0]);
// vertex
// Now, describe the data to OpenGL, tell it where it is, and turn on
// automatic vertex fething for the specified attribute
glVertexAttribPointer(
0, // Attribute location 0
4, // Four components
GL_FLOAT, // Floating-point type data
GL_FALSE, // Not normalized (floating-point data never is)
0, // Stride, tightly packed
nullptr); // Offset zero (nullptr pointer)
glEnableVertexAttribArray(0);
glUseProgram(_glProgram.getProgram());
glDrawArrays(GL_TRIANGLES, 0, 3);
glDisableVertexAttribArray(0);
}
/*
* ṹ
*/
void SimpleData::render_arrayOfStructure()
{
// This is the data that we will place into the buffer object
static float data_pos[] = {
0.25, -0.25, 0.0, 1.0,
-0.25, -0.25, 0.5, 1.0,
0.25, 0.25, 0.5, 1.0
};
static float data_clr[] = {
1.0, 0.0, 0.0, 1.0f,
0.0, 1.0, 0.0, 1.0f,
0.0, 0.0, 1.0, 1.0f,
};
glBindBuffer(GL_ARRAY_BUFFER, _buffers[0]);
glBufferData(GL_ARRAY_BUFFER, sizeof(data_pos), data_pos, GL_STATIC_DRAW);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, nullptr);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, _buffers[1]);
glBufferData(GL_ARRAY_BUFFER, sizeof(data_clr), data_clr, GL_STATIC_DRAW);
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 0, nullptr);
glEnableVertexAttribArray(1);
glUseProgram(_glProgram.getProgram());
glDrawArrays(GL_TRIANGLES, 0, 3);
glDisableVertexAttribArray(0);
}
/*
* ṹ飬еֵһУͨglVertexAttribPointerstride
*
*/
void SimpleData::render_structureOfArray()
{
struct vertex {
// Position
float x;
float y;
float z;
float w;
// Color
float r;
float g;
float b;
float a;
};
static const vertex vertices[] = {
{ 0.25, -0.25, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0f },
{ -0.25, -0.25, 0.5, 1.0, 0.0, 1.0, 0.0, 1.0f },
{ 0.25, 0.25, 0.5, 1.0, 0.0, 0.0, 1.0, 1.0f },
};
glBindBuffer(GL_ARRAY_BUFFER, _buffers[0]);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
// Set up vertex position attribute
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(vertex), (void*)offsetof(vertex, x));
glEnableVertexAttribArray(0);
// Set up vertex color attribute
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(vertex), (void*)offsetof(vertex, r));
glEnableVertexAttribArray(1);
glUseProgram(_glProgram.getProgram());
glDrawArrays(GL_TRIANGLES, 0, 3);
glDisableVertexAttribArray(0);
}
//CREATE_MAIN(SimpleData); | true |
c691beafc4c7ec73e905c17670e4c532b7503fb1 | C++ | kahnon/Poisson2D-amg-lib | /src/amg_output.cpp | UTF-8 | 2,822 | 2.78125 | 3 | [] | no_license | #include <fstream>
#include <sstream>
#include <string>
#include <iomanip>
#include "matrix.h"
#include "amg_level.h"
#include "amg_tests.h"
void print_coarsening(const Matrix& matrix, int Nr, int Nz, std::string fn){
std::ofstream ofs(fn);
for(auto r=0;r<Nr;++r){
for(auto z=0;z<Nz;++z){
int i=r*Nz+z;
ofs<<std::setw(6)<<(int) matrix[i].status;
}
ofs<<std::endl;
}
}
void print_matrix(const Matrix& matrix, std::string fn){
std::ofstream ofs(fn);
for(auto i=0u;i<matrix.size();++i){
auto& ln = matrix[i];
ofs<< ln.ind<<" "<<std::setw(6)<< ln.val<<std::setw(6)<< (int) ln.status<<std::endl;
for(auto& cn : ln.conns){
ofs<<"-->"<<" "<<std::get<int>(cn)<<" "<<std::setw(6)<<std::get<double>(cn)<<std::setw(6)<<(int) std::get<ConnType>(cn)<<std::endl;
}
ofs<<std::endl;
}
}
void print_vector(const std::vector<double>& vec, int Nr, int Nz, std::string fn){
std::ofstream ofs(fn);
for(auto r=0;r<Nr;++r){
for(auto z=0;z<Nz;++z){
int i=r*Nz+z;
ofs<<std::setw(10)<<vec[i];
}
ofs<<std::endl;
}
}
void print_hierarchy(AMGhierarchy& hier, int Nr, int Nz, std::string fn){
size_t size = hier.front().size();
std::vector<int> hmap(size,0);
for(auto k=1u;k<hier.size();++k){
Matrix& intp=hier[k].interpolation;
size_t ctr=0;
for(auto i=0u;i<size && ctr<intp.size() ;++i){
if(hmap[i]==static_cast<int>(k)-1){
line& ln = intp[ctr++];
if((ln.conns.size() == 1) && std::get<double>(ln.conns.front())==1){
hmap[i]=k;
}
}
}
}
std::ofstream ofs(fn);
for(auto r=0;r<Nr;++r){
for(auto z=0;z<Nz;++z){
int i=r*Nz+z;
ofs<<hmap[i]<<" ";
}
ofs<<std::endl;
}
}
//to transfer matrix from PIC code to test
//assumes one line in file for each matrix line. diagonal entries come first
Matrix read_input_matrix(std::string fn){
Matrix inmatrix;
std::ifstream ifs(fn);
if(ifs.good()){
std::string line;
while(std::getline(ifs,line)){
double val;
int ind;
std::vector<std::tuple<int,double,ConnType>> conns;
std::istringstream iss(line);
//read first two values
iss >> ind;
iss >> val;
int conn_ind=-1;
while(iss >> conn_ind){
double conn_val=0;
iss >> conn_val;
conns.emplace_back(conn_ind,conn_val,WEAK);
}
inmatrix.emplace_back(ind,val,UNDECIDED,conns);
}
}
return inmatrix;
}
//to transfer rhs from PIC code to test
//assumes linear array (one line)
std::vector<double> read_input_vector(std::string fn){
std::vector<double> invec;
std::ifstream ifs(fn);
if(ifs.good()){
std::string line;
while(std::getline(ifs,line)){
std::istringstream iss(line);
double val=0;
while(iss >> val){
invec.push_back(val);
}
}
}
return invec;
}
| true |
e45ca7a1394bbb98ec425877d6a95fd2e443fdb2 | C++ | NeilBetham/rollkit | /components/rollkit/src/session.cpp | UTF-8 | 3,762 | 2.515625 | 3 | [
"MIT"
] | permissive | #include "rollkit/session.hpp"
#include <exception>
#include <esp_log.h>
#include "rollkit/request.hpp"
#include "rollkit/utils.hpp"
#include "rollkit/hkdf.hpp"
using namespace std;
namespace rollkit {
void Session::handle_request(string& data){
try {
if(_is_pair_verified == true){
ESP_LOGD("session", "Decrypting message");
ESP_LOGD("session", "Encrypted message length: %i", ((uint16_t)data[1] << 8 | (uint16_t)data[0]));
ESP_LOGD("session", "Total message length: %i", data.size());
auto plain_message = _session_sec.decrypt(data);
if(!plain_message) {
ESP_LOGE("session", "Decryption failed closing connection");
close();
return;
}
handle_message(*plain_message);
} else {
// Handle regular message
handle_message(data);
}
} catch(exception& e) {
ESP_LOGD("session", "Exception thrown while handling request: %s", e.what());
close();
}
}
void Session::handle_message(string& data){
ESP_LOGD("session", "Handling message of %u bytes...", data.size());
// Parse the http data
struct http_message message;
int result = mg_parse_http(data.c_str(), data.size(), &message, 1);
if(result < 1){
// There was an error parsing the message so return
// TODO: Add error handling
ESP_LOGD("session", "Error parsing http message: %i", result);
ESP_LOGD("session", "Errored Request: %u - `%s`", data.size(), to_hex(data).c_str());
return;
}
Request new_request(message, *this);
if(_delegate){
_delegate->request_recv(new_request);
}
}
void Session::close(){
_connection->flags |= MG_F_CLOSE_IMMEDIATELY;
for(auto& listener : _event_listeners) {
listener->session_closed(get_identifier());
}
}
bool Session::is_closed(){
return true;
}
void Session::head(int code){
string header_fmt = "HTTP/1.1 %d %s\r\n\r\n";
int buf_size = snprintf(NULL, 0, header_fmt.c_str(), code, mg_status_message(code));
string header(buf_size, 0);
(void)sprintf(&(header[0]), header_fmt.c_str(), code, mg_status_message(code));
send_data(header);
}
void Session::send(int code, const string& data, const string& content_type){
string header_fmt = "HTTP/1.1 %d %s\r\nContent-Length: %d\r\nContent-Type: %s\r\n\r\n";
int buf_size = snprintf(NULL, 0, header_fmt.c_str(), code, mg_status_message(code), data.size(), content_type.c_str());
string header(buf_size, 0);
(void)sprintf(&(header[0]), header_fmt.c_str(), code, mg_status_message(code), data.size(), content_type.c_str());
send_data(header + data);
}
void Session::event(const std::string& data) {
int code = 200;
string header_fmt = "EVENT/1.0 %d %s\r\nContent-Length: %d\r\nContent-Type: application/hap+json\r\n\r\n";
int buf_size = snprintf(NULL, 0, header_fmt.c_str(), code, mg_status_message(code), data.size());
string header(buf_size, 0);
(void)sprintf(&(header[0]), header_fmt.c_str(), code, mg_status_message(code), data.size());
send_data(header + data);
}
void Session::send_data(string to_send) {
string response;
if(_is_pair_verified) {
response = _session_sec.encrypt(to_send);
} else {
response = to_send;
}
mg_send(_connection, response.c_str(), response.size());
ESP_LOGD("session", "Sending %u bytes", response.size());
}
void Session::setup_security(const string& shared_secret, bool is_admin) {
_acc_to_cont_key = hkdf_sha512(
shared_secret,
"Control-Salt",
"Control-Read-Encryption-Key",
32
);
_cont_to_acc_key = hkdf_sha512(
shared_secret,
"Control-Salt",
"Control-Write-Encryption-Key",
32
);
_is_pair_verified = true;
_is_admin = is_admin;
_session_sec = SessionSecurity(_acc_to_cont_key, _cont_to_acc_key);
}
} // namespace rollkit
| true |
5f69030096f329b427ea4e4737bdc47b1ada1a05 | C++ | yunyu-Mr/myLeetcode | /cpp/one/a131.cpp | UTF-8 | 1,061 | 3.40625 | 3 | [] | no_license | class Solution {
public:
vector<vector<string>> partition(string s) {
vector<vector<string>> results;
vector<string> path;
partition(s, 0, path, results);
return results;
}
// Backtracking
void partition(const string& s, int i, vector<string> &path, vector<vector<string>> &results)
{
int N = s.length();
if (i == N) {
results.push_back(path);
return;
}
for (int j = i+1; j <= N; j++) // i: start point, j: partition point
{
const string& sub = s.substr(i, j-i);
if (isPalindrome(sub)) // constrain
{
path.push_back(sub);
partition(s, j, path, results);
path.pop_back();
}
}
}
// Constrain
bool isPalindrome(const string& s)
{
for (int i = 0, j = s.length() - 1; i < j; i++, j--)
if (s[i] != s[j])
return false;
return true;
}
}; | true |
25dc428a42bd48e8cd5631d3db7eed93728fd424 | C++ | Meaha7/DSA-Marathon | /Algorithms/Matrix_Exponentiation.cpp | UTF-8 | 1,450 | 3.546875 | 4 | [] | no_license | #include<iostream>
#include<vector>
using namespace std;
vector<vector<int>> Multiply(vector<vector<int>>&a, vector<vector<int>>&b)
{
int i,j,k,n;
n=a.size();
vector<vector<int>>ans(n,vector<int>(n,0));
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
for(k=0;k<n;k++)
{
ans[i][j]+=(a[i][k]*b[k][j]);
}
}
}
return ans;
}
vector<vector<int>> Matrix_Exponentiation(vector<vector<int>>&a, int n)
{
int sz,i,j;
sz=a.size();
if(n==0)
{
vector<vector<int>>identity(sz,vector<int>(sz,0));
for(i=0;i<sz;i++)
identity[i][i]=1;
return identity;
}
if(n==1)
{
return a;
}
vector<vector<int>>temp=Matrix_Exponentiation(a,n/2);
vector<vector<int>>ans=Multiply(temp,temp);
if(n&1)
{
ans=Multiply(ans,a);
}
return ans;
}
int main()
{
int n;
cin>>n;
vector<vector<int>>a(2,vector<int>(2,0));
a[0][0]=a[0][1]=a[1][0]=1;
a[1][1]=0;
/*
1 1
1 0
*/
vector<vector<int>>ans=Matrix_Exponentiation(a,n);
cout<<"\n\n";
int i,j;
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
cout<<ans[i][j]<<" ";
}
cout<<"\n";
}
cout<<"\nFib("<<n<<") = "<<ans[0][1];
}
//Fib in Log(N) time | true |
32c7cdcad1d485ad47a4098c96471477a9b4f7ed | C++ | HolyOlaf/LD39 | /Main.cpp | UTF-8 | 8,965 | 2.609375 | 3 | [] | no_license | #include <vector>
#include <iostream>
#include <ctime>
#include <random>
#include <Windows.h>
#include <SFML/Graphics.hpp>
#include "Player.h"
#include "Enemy.h"
#include "Tile.h"
#include "Bullet.h"
#include "Item.h"
#define PI 3.14159265359
void genTileTextures(std::string _sheetPath, int _tileSize)
{
sf::Texture* sheetTex = new sf::Texture();
sheetTex->loadFromFile(_sheetPath);
for (int y = 0; y < sheetTex->getSize().y; y += _tileSize)
{
for (int x = 0; x < sheetTex->getSize().x; x += _tileSize)
{
Tile::g_TileTextures.push_back(new sf::Sprite(*sheetTex, sf::IntRect(x, y, _tileSize, _tileSize)));
}
}
}
sf::Sprite* getSheet(std::string _sheetPath)
{
sf::Texture* sheetTex = new sf::Texture();
sheetTex->loadFromFile(_sheetPath);
return new sf::Sprite(*sheetTex);
}
int game(sf::RenderWindow* window)
{
genTileTextures("res/textures/tilesheet.png", 64);
Player player(64.f, 10.f, 64.f, 64.f, 350.f, 800.f, 150.f, "res/textures/charset.png");
std::vector<Tile*> ground;
std::vector<sf::RectangleShape*> colliders;
std::vector<Bullet*> bullets;
std::vector<Enemy*> enemies;
std::vector<Item*> items;
sf::Texture* itemTex = new sf::Texture();
itemTex->loadFromFile("res/textures/itemsheet.png");
sf::Sprite* batterySprite = new sf::Sprite(*itemTex, sf::IntRect(0, 0, 16, 16));
sf::Sprite* damageUpSprite = new sf::Sprite(*itemTex, sf::IntRect(16, 0, 16, 16));
sf::Sprite* maxEnergyUpSprite = new sf::Sprite(*itemTex, sf::IntRect(32, 0, 16, 16));
sf::Texture* bulletTex = new sf::Texture();
bulletTex->loadFromFile("res/textures/energybullet.png");
sf::Sprite* bulletSprite = new sf::Sprite(*bulletTex);
sf::Texture* gameoverTex = new sf::Texture;
gameoverTex->loadFromFile("res/textures/gameoverscreen.png");
sf::Sprite* gameOverScreen = new sf::Sprite(*gameoverTex);
gameOverScreen->scale(sf::Vector2f(0.5f, 0.5f));
for (int i = 0; i < window->getSize().x + 100; i += TILE_SIZE)
{
ground.push_back(new Tile(i, window->getSize().y - TILE_SIZE * 2, Tile::g_TileTextures[0]));
colliders.push_back(ground[i / TILE_SIZE]->getCollider());
}
for (int i = 0; i < window->getSize().x + 100; i += TILE_SIZE)
{
ground.push_back(new Tile(i, window->getSize().y - TILE_SIZE, Tile::g_TileTextures[1]));
}
sf::Sprite* lanternTop1 = new sf::Sprite(*Tile::g_TileTextures[2]);
sf::Sprite* lanternBottom1 = new sf::Sprite(*Tile::g_TileTextures[3]);
lanternBottom1->setPosition(TILE_SIZE, window->getSize().y - TILE_SIZE * 3);
lanternTop1->setPosition(TILE_SIZE, window->getSize().y - TILE_SIZE * 4);
sf::Sprite* lanternTop2 = new sf::Sprite(*Tile::g_TileTextures[2]);
sf::Sprite* lanternBottom2 = new sf::Sprite(*Tile::g_TileTextures[3]);
sf::Sprite* grass1 = new sf::Sprite(*Tile::g_TileTextures[4]);
grass1->setPosition(TILE_SIZE, window->getSize().y - TILE_SIZE * 3);
sf::Sprite* grass2 = new sf::Sprite(*Tile::g_TileTextures[4]);
grass2->setPosition(TILE_SIZE * 4, window->getSize().y - TILE_SIZE * 3);
sf::Sprite* wall1 = new sf::Sprite(*Tile::g_TileTextures[5]);
wall1->setPosition(0, window->getSize().y - TILE_SIZE * 3);
sf::Sprite* wall2 = new sf::Sprite(*Tile::g_TileTextures[6]);
wall2->setPosition(TILE_SIZE, window->getSize().y - TILE_SIZE * 3);
sf::Sprite* wall3 = new sf::Sprite(*Tile::g_TileTextures[7]);
wall3->setPosition(TILE_SIZE * 2, window->getSize().y - TILE_SIZE * 3);
lanternBottom2->setPosition(TILE_SIZE * 6, window->getSize().y - TILE_SIZE * 3);
lanternTop2->setPosition(TILE_SIZE * 6, window->getSize().y - TILE_SIZE * 4);
sf::Sprite* SpidersheetSprite = new sf::Sprite(*getSheet("res/textures/spidersheet.png"));
sf::Sprite* RobotsheetSprite = new sf::Sprite(*getSheet("res/textures/robotsheet.png"));
sf::Sprite* SkeletonsheetSprite = new sf::Sprite(*getSheet("res/textures/skeletonsheet.png"));
bool forceEnergyUpdate = false;
sf::Vector2i mousePos;
std::clock_t startTime;
startTime = std::clock();
std::mt19937 rng(time(NULL));
std::uniform_int_distribution<int> genEnemyPos(0, window->getSize().x);
std::uniform_int_distribution<int> genItemType(0, 1000);
std::uniform_int_distribution<int> genEnemyType(0, 1000);
std::uniform_int_distribution<int> genShouldDrop(0, 100);
float playerDamage = 8.0f;
int spawnCount = 0;
int spawnAmount = 1;
int spawnTime = 3000;
sf::Clock deltaClock;
while (window->isOpen())
{
sf::Time dt = deltaClock.restart();
mousePos = sf::Mouse::getPosition(*window);
forceEnergyUpdate = false;
sf::Event evnt;
while (window->pollEvent(evnt))
{
if (evnt.type == sf::Event::Closed)
{
window->close();
return 0;
}
if (evnt.type == sf::Event::KeyPressed)
{
if (evnt.key.code == sf::Keyboard::Space)
player.jump();
if (evnt.key.code == sf::Keyboard::R)
{
if (player.getEnergy() <= 0)
return 1;
}
}
if (evnt.type == sf::Event::MouseButtonPressed)
{
if (evnt.mouseButton.button == sf::Mouse::Button::Left)
{
float angle = atan2(mousePos.y - (player.getY() + player.getXSize() / 2), mousePos.x - (player.getX() + player.getYSize() / 2));
bullets.push_back(new Bullet(bulletSprite, sf::Vector2f(player.getX() + player.getXSize() / 2, player.getY() + player.getYSize() / 2), sf::Vector2f(cos(angle), sin(angle)), angle * (180 / PI), 900.f, playerDamage));
player.removeEnergy(3);
forceEnergyUpdate = true;
}
}
}
window->clear(sf::Color(96, 78, 66));
if (spawnCount > 5)
{
spawnCount = 0;
if (spawnTime > 500)
spawnTime -= 500;
else
{
spawnTime = 3000;
spawnAmount++;
}
}
window->draw(*wall1);
window->draw(*wall2);
window->draw(*wall3);
if (player.getEnergy() > 0)
{
if (std::clock() - startTime >= spawnTime)
{
spawnCount++;
startTime = std::clock();
for (int i = 0; i < spawnAmount; i++)
{
int xPos = genEnemyPos(rng);
while (!(xPos < player.getX() - 50) && !(xPos > player.getX() + player.getXSize() + 50))
{
xPos = genEnemyPos(rng);
}
int num = genItemType(rng);
if (num >= 0 && num <= 500)
{
enemies.push_back(new Enemy(xPos, window->getSize().y - TILE_SIZE * 2 - 1, 32.f, 32.f, 110.f, 100.f, 2.f, SpidersheetSprite));
}
else if (num >= 501 && num <= 900)
{
enemies.push_back(new Enemy(xPos, window->getSize().y - TILE_SIZE * 2 - 1, 32.f, 32.f, 80.f, 30.f, 5.f, RobotsheetSprite));
}
else if (num >= 901 && num <= 1000)
{
enemies.push_back(new Enemy(xPos, window->getSize().y - TILE_SIZE * 2 - 1, 32.f, 32.f, 200.f, 60.f, 10.f, SkeletonsheetSprite));
}
}
}
player.update(colliders, dt.asSeconds());
for (int i = 0; i < ground.size(); i++)
{
ground[i]->draw(*window);
}
for (int i = 0; i < bullets.size(); i++)
{
if (bullets[i]->getX() < 0 || bullets[i]->getY() < 0 || bullets[i]->getX() > 1000 || bullets[i]->getY() > 1000 || bullets[i]->shouldDestroy())
{
delete bullets[i];
bullets.erase(bullets.begin() + i);
}
else
{
bullets[i]->update(enemies, dt.asSeconds());
bullets[i]->draw(*window);
}
}
for (int i = 0; i < enemies.size(); i++)
{
if (enemies[i]->getHealth() <= 0)
{
if (genShouldDrop(rng) > 50 || enemies[i]->getDamage() >= 8.f)
{
int num = genItemType(rng);
if (num >= 0 && num <= 600)
{
items.push_back(new Item(enemies[i]->getX(), window->getSize().y - TILE_SIZE * 2 - 16, batterySprite, [&player] { player.addEnergy(player.getMaxEnergy() / 100 * 25); }));
}
else if (num >= 601 && num <= 950)
{
items.push_back(new Item(enemies[i]->getX(), window->getSize().y - TILE_SIZE * 2 - 16, damageUpSprite, [&playerDamage] { playerDamage += 5.f; }));
}
else if (num >= 951 && num <= 1000)
{
items.push_back(new Item(enemies[i]->getX(), window->getSize().y - TILE_SIZE * 2 - 16, maxEnergyUpSprite, [&player] { player.increaseMaxEnergy(40); }));
}
}
enemies[i]->die();
delete enemies[i];
enemies.erase(enemies.begin() + i);
}
else
{
enemies[i]->update(&player, dt.asSeconds());
enemies[i]->draw(*window);
}
}
for (int i = 0; i < items.size(); i++)
{
if (items[i]->isCollected())
{
delete items[i];
items.erase(items.begin() + i);
}
else
{
items[i]->update(&player);
items[i]->draw(*window);
}
}
player.draw(*window);
window->draw(*lanternBottom1);
window->draw(*lanternTop1);
window->draw(*lanternBottom2);
window->draw(*lanternTop2);
window->draw(*grass1);
window->draw(*grass2);
}
else
{
window->draw(*gameOverScreen);
}
window->display();
}
return 0;
}
int main()
{
FreeConsole();
sf::RenderWindow* window = new sf::RenderWindow(sf::VideoMode(500, 500), "Olafshot", sf::Style::Close);
window->setFramerateLimit(60);
while (game(window) == 1)
{
game(window);
}
return 0;
} | true |
02f09f3adce98abee976145ccb1067054cb811f9 | C++ | qyvlik/three.qml | /src/three/math/quaternion.cpp | UTF-8 | 4,656 | 2.953125 | 3 | [] | no_license | #include "quaternion.h"
#include "euler.h"
#include "vector3.h"
#include "matrix4.h"
namespace three {
Quaternion &Quaternion::setFromEuler(const Euler &euler, bool update)
{
// http://www.mathworks.com/matlabcentral/fileexchange/
// 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
// content/SpinCalc.m
Q_UNUSED(update);
double c1 = std::cos( euler.x / 2 );
double c2 = std::cos( euler.y / 2 );
double c3 = std::cos( euler.z / 2 );
double s1 = std::sin( euler.x / 2 );
double s2 = std::sin( euler.y / 2 );
double s3 = std::sin( euler.z / 2 );
Euler::RotationOrders order = euler.order;
if ( order == Euler::XYZ ) {
this->x = s1 * c2 * c3 + c1 * s2 * s3;
this->y = c1 * s2 * c3 - s1 * c2 * s3;
this->z = c1 * c2 * s3 + s1 * s2 * c3;
this->w = c1 * c2 * c3 - s1 * s2 * s3;
} else if ( order == Euler::YXZ ) {
this->x = s1 * c2 * c3 + c1 * s2 * s3;
this->y = c1 * s2 * c3 - s1 * c2 * s3;
this->z = c1 * c2 * s3 - s1 * s2 * c3;
this->w = c1 * c2 * c3 + s1 * s2 * s3;
} else if ( order == Euler::ZXY ) {
this->x = s1 * c2 * c3 - c1 * s2 * s3;
this->y = c1 * s2 * c3 + s1 * c2 * s3;
this->z = c1 * c2 * s3 + s1 * s2 * c3;
this->w = c1 * c2 * c3 - s1 * s2 * s3;
} else if ( order == Euler::ZYX ) {
this->x = s1 * c2 * c3 - c1 * s2 * s3;
this->y = c1 * s2 * c3 + s1 * c2 * s3;
this->z = c1 * c2 * s3 - s1 * s2 * c3;
this->w = c1 * c2 * c3 + s1 * s2 * s3;
} else if ( order == Euler::YZX ) {
this->x = s1 * c2 * c3 + c1 * s2 * s3;
this->y = c1 * s2 * c3 + s1 * c2 * s3;
this->z = c1 * c2 * s3 - s1 * s2 * c3;
this->w = c1 * c2 * c3 - s1 * s2 * s3;
} else if ( order == Euler::XZY ) {
this->x = s1 * c2 * c3 - c1 * s2 * s3;
this->y = c1 * s2 * c3 - s1 * c2 * s3;
this->z = c1 * c2 * s3 + s1 * s2 * c3;
this->w = c1 * c2 * c3 + s1 * s2 * s3;
}
// if ( update != false )
return *this;
}
Quaternion &Quaternion::setFromAxisAngle(const Vector3 &axis, const double &angle)
{
// http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
// assumes axis is normalized
double halfAngle = angle / 2
, s = std::sin( halfAngle );
this->x = axis.x * s;
this->y = axis.y * s;
this->z = axis.z * s;
this->w = std::cos( halfAngle );
return *this;
}
Quaternion &Quaternion::setFromRotationMatrix(const Matrix4 &m) {
// http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
// assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
const auto& te = m.elements;
double m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
trace = m11 + m22 + m33,
s;
if ( trace > 0 ) {
s = 0.5 / std::sqrt( trace + 1.0 );
this->w = 0.25 / s;
this->x = ( m32 - m23 ) * s;
this->y = ( m13 - m31 ) * s;
this->z = ( m21 - m12 ) * s;
} else if ( m11 > m22 && m11 > m33 ) {
s = 2.0 * std::sqrt( 1.0 + m11 - m22 - m33 );
this->w = ( m32 - m23 ) / s;
this->x = 0.25 * s;
this->y = ( m12 + m21 ) / s;
this->z = ( m13 + m31 ) / s;
} else if ( m22 > m33 ) {
s = 2.0 * std::sqrt( 1.0 + m22 - m11 - m33 );
this->w = ( m13 - m31 ) / s;
this->x = ( m12 + m21 ) / s;
this->y = 0.25 * s;
this->z = ( m23 + m32 ) / s;
} else {
s = 2.0 * std::sqrt( 1.0 + m33 - m11 - m22 );
this->w = ( m21 - m12 ) / s;
this->x = ( m13 + m31 ) / s;
this->y = ( m23 + m32 ) / s;
this->z = 0.25 * s;
}
return *this;
}
Quaternion &Quaternion::setFromUnitVectors(const Vector3 &vFrom, const Vector3 &vTo)
{
// http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final
// assumes direction vectors vFrom and vTo are normalized
Vector3 v1;
double r;
double EPS = 0.000001;
r = vFrom.dot( vTo ) + 1;
if ( r < EPS ) {
r = 0;
if ( std::abs( vFrom.x ) > std::abs( vFrom.z ) ) {
v1.set( - vFrom.y, vFrom.x, 0 );
} else {
v1.set( 0, - vFrom.z, vFrom.y );
}
} else {
v1.crossVectors( vFrom, vTo );
}
this->x = v1.x;
this->y = v1.y;
this->z = v1.z;
this->w = r;
this->normalize();
return *this;
}
} // namespace three
| true |
4251f616fe12e80ec0eb0fcc2680483bc4f109ef | C++ | s-valentin/Laboratoare-POO | /Exercitii R@f@/POO7_2/POO7_2/Vector_.h | UTF-8 | 2,504 | 3.59375 | 4 | [] | no_license | #pragma once
template<class T>
class MyVector
{
T* Array;
int Array_Size;
int Array_Count;
public:
MyVector();
~MyVector();
void Push(T);
T Pop();
void Delete(int);
void Insert(T, int);
void Sort(bool (*fun)(const T, const T) = nullptr);
const T& Get(int);
void Set(T, int);
int Count();
int FirstIndexOf(T, bool(*fun)(const T, const T) = nullptr);
};
//########################################################################
template<class T>
T* Realocate(T* arr, int& Count, int& Size)
{
Size = (Size << 1);
T* arrayAux = new T[Size];
//memcpy(arrayAux, arr, sizeof(T) * Count);
for (int i = 0; i < Count; i++)
arrayAux[i] = arr[i];
delete[] arr;
return arrayAux;
}
template<class T>
MyVector<T>::MyVector()
{
Array_Size = 4;
Array_Count = 0;
Array = new T[Array_Size];
}
template<class T>
MyVector<T>::~MyVector()
{
delete[] Array;
}
template<class T>
void MyVector<T>::Push(T x)
{
if (Array_Count == Array_Size)
Array=Realocate(Array, Array_Count, Array_Size);
Array[Array_Count++] = x;
}
template<class T>
T MyVector<T>::Pop()
{
return Array[Array_Count - 1];
}
template<class T>
void MyVector<T>::Delete(int index)
{
for (int i = index; i < Array_Count - 1; i++)
Array[i] = Array[i + 1];
delete Array[Array_Count - 1];
Array_Count--;
}
template<class T>
void MyVector<T>::Insert(T x, int index)
{
if (Array_Count == Array_Size)
Array=Realocate(Array, Array_Count, Array_Size);
for (int i = Array_Count; i >= index; i--)
{
Array[i] = Array[i - 1];
}
Array[index] = x;
Array_Count++;
}
template<class T>
bool isHigher(T a, T b)
{
return (a > b);
}
template<class T>
void MyVector<T>::Sort(bool (*fun)(const T, const T))
{
if (fun == nullptr) fun = isHigher;
T aux;
for (int i = 0; i < Array_Count - 1; i++)
for (int j = i + 1; j < Array_Count; j++)
if (fun(Array[i], Array[j]))
{
aux = Array[i];
Array[i] = Array[j];
Array[j] = aux;
}
}
template<class T>
const T& MyVector<T>::Get(int index)
{
return Array[index];
}
template<class T>
void MyVector<T>::Set(T x, int index)
{
if (index < Array_Count)
{
Array[index] = x;
}
}
template<class T>
int MyVector<T>::Count()
{
return Array_Count;
}
template<class T>
bool isEqual(const T a, const T b)
{
return (a == b);
}
template<class T>
int MyVector<T>::FirstIndexOf(T x, bool(*fun)(const T, const T))
{
if (fun == nullptr) fun = isEqual;
for (int index = 0; index < Array_Count; index++)
if (fun(x, Array[index]))
return index;
return -1;
} | true |
231c0c3cbfa693380abcad9f5ef1177a0406267f | C++ | TSAVideoGame/the-lady-and-the-trampoline | /src/ui/components/button/button.cpp | UTF-8 | 1,278 | 2.96875 | 3 | [] | no_license | #include "button.h"
#include <SDL2/SDL.h>
#include <cmath>
#include "game.h"
Button::Button(Renderer* renderer, SDL_Rect srcRect, SDL_Rect myPos, void (*clickHandler)(Button*)) : UIComponent(renderer)
{
this->srcRect = srcRect;
this->myPos = myPos;
destRect = myPos;
onClick = clickHandler;
state = ButtonState::NEUTRAL;
}
void Button::update()
{
switch (state)
{
case ButtonState::NEUTRAL:
{
ticks = 0;
if (focused())
{
state = ButtonState::HOVER;
}
break;
}
case ButtonState::HOVER:
{
ticks++;
int range = 4;
double compression = 0.25;
destRect.y = myPos.y + (std::sin(compression * ticks) * range);
if (Game::inputs.attack)
{
onClick(this);
}
if (!focused())
{
destRect = myPos;
state = ButtonState::NEUTRAL;
}
}
}
}
bool Button::focused()
{
return (Game::inputs.mouseX >= myPos.x &&
Game::inputs.mouseX <= myPos.x + destRect.w &&
Game::inputs.mouseY >= myPos.y &&
Game::inputs.mouseY <= myPos.y + destRect.h);
}
void Button::click()
{
onClick(this);
}
void Button::goTo(int x, int y)
{
myPos.x += (x - myPos.x) / 4;
myPos.y += (y - myPos.y) / 4;
destRect = myPos;
}
| true |
5592365dd1b6de50ffc102f29d56021c02da899a | C++ | BarsantiNicola/FourInARow-Cybersec- | /Application/src/utility/NetMessage.cpp | UTF-8 | 4,222 | 3.453125 | 3 | [] | no_license | #include "NetMessage.h"
namespace utility {
///////////////////////////////////////////////////////////////////////////////////////////////
// //
// COSTRUCTORS/DESTRUCTORS //
// //
///////////////////////////////////////////////////////////////////////////////////////////////
// costructor for the generation of a NetMessage starting from a byte array
NetMessage::NetMessage( unsigned char *mess, unsigned int length ) {
// verification of arguments validity
if( !mess || length<1 ){
verbose << "--> [NetMessage][Costructor] Error invalid arguments. Empty netmessage generated" << '\n';
this->message = nullptr;
this->len = 0;
return;
}
try {
this->message = new unsigned char[length];
myCopy( this->message, mess, length);
this->len = length;
vverbose << "--> [NetMessage][Costructor] Message correctly generated: [\t";
for( int a = 0; a<len; a++ )
vverbose<<(int)this->message[a];
vverbose<<"UINT32_MAX\t]\n";
}catch( bad_alloc e ){
this->message = nullptr;
this->len = 0;
verbose << "--> [NetMessage][Costructor] Error during the allocation of memory. Empty netmessage generated" << '\n';
}
}
// copy-constructor
NetMessage::NetMessage( NetMessage& value ){
// verification of arguments validity
if( !value.getMessage() ){
verbose << "--> [NetMessage][Costructor] Invalid arguments, empty netmessage generated" << '\n';
this->message = nullptr;
this->len = 0;
return;
}
try{
this->message = new unsigned char[value.length()];
myCopy(this->message, value.getMessage(), value.length());
this->len = value.length();
}catch( bad_alloc e ){
this->message = nullptr;
this->len = 0;
verbose << "--> [NetMessage][Costructor] Error during the allocation of memory. Empty netmessage generated" << '\n';
}
}
// utility function similar to std::memset
void NetMessage::myCopy( unsigned char* dest, unsigned char* source, int len ){
// verification of arguments validity. No control is needed on len(function resilient to len<=0)
if( !dest || !source ){
verbose << "--> [NetMessage][Costructor] Error invalid arguments. Operation Aborted" << '\n';
return;
}
for( int a = 0; a<len; a++ )
dest[a] = source[a];
}
NetMessage::~NetMessage(){
if( this->message )
delete[] this->message;
}
///////////////////////////////////////////////////////////////////////////////////////////////
// //
// GETTERS //
// //
///////////////////////////////////////////////////////////////////////////////////////////////
// return the content of the netmessage as an unsigned char* array
unsigned char* NetMessage::getMessage(){
// verification of used variables
if( !this->message || !this->len ) return nullptr;
try {
unsigned char *ret = new unsigned char[this->len];
myCopy( ret, this->message, this->len );
return ret;
}catch( bad_alloc e ){
verbose << "--> [NetMessage][getMessage] Error during the allocation of memory. Empty message given" << '\n';
return nullptr;
}
}
// return the length of the getMessage unsigned char* array
unsigned int NetMessage::length(){
return this->len;
}
} | true |
c1117d094c46c6a9b52518195c64877fdd58fef8 | C++ | shrushtijagtap/KMeans | /main.cpp | UTF-8 | 4,086 | 3.21875 | 3 | [] | no_license | #include <iostream>
using namespace std;
#include<vector>
#include<cmath>
int distance(int x1, int y1, int x2, int y2)
{
int dist = sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));
return dist;
}
int nearest_c(int cluster[][2],int k, int v1x, int v1y)
{
int minimum=9999, c_no=0, d;
for(int i=0; i<k; i++)
{
d=distance(cluster[i][0], cluster[i][1], v1x, v1y);
if(d<minimum)
{
minimum=d;
c_no=i;
}
}
return c_no;
}
int main()
{
vector <vector<int>> vertex;
int n,t,i,k,loop_no=0;
cout<<"enter no of clusters"<<endl;
cin>>k;
cout<<"enter points"<<endl;
cin>>n;
for(i=0; i<n; i++)
{
vector<int> temp;
for(int j=0; j<3; j++)
{
if(j==2)
{
temp.push_back(0);
}
else
{
cin>>t;
temp.push_back(t);
}
}
vertex.push_back(temp);
temp.clear();
}
cout<<"Input vertex"<<endl;
for(int i=0; i<n ;i ++)
{
for(int j=0; j<3;j++)
{
cout<<vertex[i][j]<<"\t";
}
cout<<endl;
}
int cluster[k][2], cluster_list[n], c1, flag;
for(i=0;i<k;i++)
{
c1=rand()%n;
cluster[i][0]=vertex[c1][0];
cluster[i][1]=vertex[c1][1];
}
cout<<" randomly selected clusters:"<<endl;
for(int i=0; i<k ;i ++)
{
for(int j=0; j<2;j++)
{
cout<<cluster[i][j]<<"\t";
}
cout<<endl;
}
while(1)
{
loop_no+=1;
cout<<"iter "<<loop_no<<endl;
flag=0;
for(i=0; i<n; i++)
{
int result = nearest_c(cluster ,k, vertex[i][0], vertex[i][1]);
vertex[i][2]=result;
cout<<"cluster "<<result<< " assigned to "<< i <<" "<<endl;
}
cout<<endl;
int new_cluster[k][2];
int c_count[k]={0};
int cluster_sum[k][2];
for(int j=0; j<k; j++)
{
for(int i=0; i<2; i++)
{
cluster_sum[j][i]=0;
}
}
for(int j=0; j<k; j++)
{
for(int i=0; i<n; i++)
{
if(vertex[i][2]==j)
{
c_count[j]+=1;
cluster_sum[j][0]+=vertex[i][0];
cluster_sum[j][1]+=vertex[i][1];
}
}
}
for(int j=0;j<k;j++)
{
if(c_count[j]!=0)
{
new_cluster[j][0]=cluster_sum[j][0]/c_count[j];
new_cluster[j][1]=cluster_sum[j][1]/c_count[j];
}
}
cout<<"new selected clusters:"<<endl;
for(int i=0; i<k ;i ++)
{
for(int j=0; j<2;j++)
{
cout<<new_cluster[i][j]<<"\t";
}
cout<<endl;
}
cout<<endl;
for(i=0; i<n; i++)
{
int result = nearest_c(new_cluster , k, vertex[i][0], vertex[i][1]);
cluster_list[i]=result;
}
for(int i=0; i<n;i++)
{
if(vertex[i][2]!=cluster_list[i])
{
flag=1;
break;
}
}
if(flag!=1)
{
cout<<"done"<<endl;
break;
}
if(loop_no>=10)
{
cout<<"loop end"<<endl;
break;
}
cout<<"centroid changed"<<endl;
for(int i=0;i<k;i++)
{
cluster[i][0]=new_cluster[i][0];
cluster[i][1]=new_cluster[i][1];
}
}
cout<<"final result"<<endl;
for(int i=0; i<n ;i ++)
{
for(int j=0; j<3;j++)
{
cout<<vertex[i][j]<<"\t";
}
cout<<endl;
}
return 0;
}
| true |
86b4869b465ef86797ed7c62e00a07a7b3507a3a | C++ | grh4542681/comm-libs | /libthread/thread_handler.h | UTF-8 | 1,123 | 2.59375 | 3 | [] | no_license | #ifndef _THREAD_INFO_H__
#define _THREAD_INFO_H__
#include <sys/types.h>
#include <string>
#include <thread>
#include <memory>
#include "thread_return.h"
#include "thread_id.h"
#include "thread_state.h"
#include "thread_role.h"
#include "thread_scopedlock.h"
namespace infra::thread {
template <typename H, typename F> class Template;
class Handler : virtual public ::infra::base::Object {
public:
template <typename H, typename F> friend class Template;
public:
Handler& SetThreadName(const char* name);
Handler& SetState(State&& state);
Handler& SetRole(Role&& role);
std::string GetThreadName();
ID GetTid();
State GetState();
Role GetRole();
Handler& AddRole(Role&& role);
Handler& DelRole(Role&& role);
Return Register();
Return Unregister();
Return Join();
Return Detach();
static Handler& Instance();
private:
Handler();
~Handler();
Handler& SetTid(ID&& tid);
std::string name_;
ID tid_;
Role role_;
State state_;
Mutex mutex_;
std::thread thread_;
thread_local static Handler* pInstance;
};
};
#endif
| true |
66fc68a72ab3550ef2dd29e9db237ec13d49d7b4 | C++ | vincentlai97/SP3-10 | /Base/Source/ReadFromText.cpp | UTF-8 | 3,897 | 2.6875 | 3 | [] | no_license | #include "ReadFromText.h"
ReadFromText::ReadFromText() :KeyPressed(false), talking(false)
{
LineParagraph = 0;
changetext = false;
speechspeed = 0;
letterofspeech = 0;
vectorspeech = 0;
copyspeech = "";
speedup = false;
}
ReadFromText::~ReadFromText()
{
}
void ReadFromText::Textfile(const char* filename, bool Character)
{
ifstream file;
string data;
file.open(filename);
if (file.is_open())
{
if (Character)
{
CharacterText.clear();
CharacterText.shrink_to_fit();
}
else
{
InstructionText.clear();
InstructionText.shrink_to_fit();
}
file.clear();
file.seekg(0, file.beg);
while (file.good()) {
getline(file, data, '\n');
if (Character)
CharacterText.push_back(data);
else
InstructionText.push_back(data);
}
}
file.close();
}
void ReadFromText::Dialogue(const char* filename)
{
ifstream file;
string data;
file.open(filename);
if (file.is_open())
{
line.clear();
line.shrink_to_fit();
file.clear();
file.seekg(0, file.beg);
while (file.good()) {
getline(file, data, '\n');
line.push_back(data);
}
}
file.close();
changetext = false;
speechspeed = 0;
letterofspeech = 0;
copyspeech = "";
speedup = false;
vectorspeech = 0;
filespeech = line[vectorspeech];
LineParagraph = 1;
}
void ReadFromText::Obtain(const char* filename, bool loot, string ItemName)
{
ifstream file;
string data;
file.open(filename);
if (file.is_open())
{
line.clear();
line.shrink_to_fit();
file.clear();
file.seekg(0, file.beg);
if (loot)
{
if (file.good())
{
getline(file, data, '\n');
line.push_back(data);
}
}
else
{
while (file.good()) {
getline(file, data, '\n');
}
line.push_back(data);
}
}
file.close();
changetext = false;
speechspeed = 0;
letterofspeech = 0;
copyspeech = "";
speedup = false;
vectorspeech = 0;
filespeech = line[vectorspeech] + ItemName + ".";
LineParagraph = 1;
}
void ReadFromText::Update(double dt)
{
if (speedup)
{
if (letterofspeech < filespeech.size())
{
while (letterofspeech < filespeech.size())
{
copyspeech += filespeech[letterofspeech];
letterofspeech += 1;
}
}
else if (vectorspeech < line.size() - 1)
{
if (line[vectorspeech + 1] != "")
{
if (vectorspeech < line.size() - 1)
{
letterofspeech = 0;
vectorspeech = vectorspeech + 1;
filespeech = line[vectorspeech];
copyspeech = "";
LineParagraph++;
}
}
else
{
changetext = true;
speedup = false;
}
}
}
speechspeed -= (float)dt;
if (speechspeed < 0 && vectorspeech < line.size() && !speedup)
{
if (letterofspeech < filespeech.size())
{
copyspeech += filespeech[letterofspeech];
letterofspeech += 1;
if (letterofspeech < filespeech.size())
{
if (filespeech[letterofspeech] == ' ')
{
copyspeech += filespeech[letterofspeech];
letterofspeech += 1;
}
}
speechspeed = 0.1;
}
else if (vectorspeech < line.size() - 1)
{
if (line[vectorspeech + 1] != "")
{
if (vectorspeech < line.size() - 1)
{
letterofspeech = 0;
vectorspeech = vectorspeech + 1;
filespeech = line[vectorspeech];
copyspeech = "";
LineParagraph++;
}
}
else
changetext = true;
}
}
if (KeyPressed && changetext && !speedup)
{
KeyPressed = false;
changetext = false;
letterofspeech = 0;
vectorspeech = vectorspeech + 2;
filespeech = line[vectorspeech];
copyspeech = "";
LineParagraph = 1;
}
else if (KeyPressed && !changetext && !speedup)
{
KeyPressed = false;
speedup = true;
}
if (KeyPressed && vectorspeech >= line.size() - 1)
{
KeyPressed = false;
talking = false;
filespeech = "";
copyspeech = "";
LineParagraph = 0;
}
}
string ReadFromText::GetText()
{
return copyspeech;
}
int ReadFromText::GetParagraphLine()
{
return LineParagraph;
} | true |
83678249522426d6c0a3c5543a570278d472ba90 | C++ | Kreyl/GardenOfShadows | /GSLeaf/GSLeaf_fw/wavreader.h | UTF-8 | 2,443 | 2.75 | 3 | [] | no_license | #pragma once
#include <cstddef>
#include <cstdint>
class WavReader
{
public:
typedef size_t (*TellCallback)(void *file_context);
typedef bool (*SeekCallback)(void *file_context, size_t offset);
typedef size_t (*ReadCallback)(void *file_context, uint8_t *buffer, size_t length);
enum class Mode
{
Single,
Continuous
};
enum class Format : unsigned int
{
Pcm = 1
};
static const unsigned int MAX_CHANNELS = 2;
static const unsigned int MAX_FRAME_SIZE = 16;
public:
WavReader(TellCallback tell_callback,
SeekCallback seek_callback,
ReadCallback read_callback);
bool open(void *file_context,
Mode mode = Mode::Single);
void close();
void rewind();
size_t decodeToI16(int16_t *buffer, size_t frames);
bool opened()
{
return opened_;
}
Format format()
{
return format_;
}
unsigned int channels()
{
return channels_;
}
unsigned long samplingRate()
{
return sampling_rate_;
}
unsigned long bytesPerSecond()
{
return bytes_per_second_;
}
size_t blockAlignment()
{
return block_alignment_;
}
unsigned int bitsPerSample()
{
return bits_per_sample_;
}
size_t frameSize()
{
return frame_size_;
}
private:
size_t tell();
bool seek(size_t offset);
size_t read(uint8_t *buffer, size_t length);
bool readU16(uint16_t *value);
bool readU32(uint32_t *value);
bool readCharBuffer(char *buffer, size_t length);
bool decodeNextFrame();
bool decodeNextPcmFrame();
size_t decodeUxToI16(int16_t *buffer, size_t frames);
size_t decodeIxToI16(int16_t *buffer, size_t frames);
private:
bool opened_;
Mode mode_;
void *file_context_;
TellCallback tell_callback_;
SeekCallback seek_callback_;
ReadCallback read_callback_;
size_t file_size_;
Format format_;
unsigned int channels_;
unsigned long sampling_rate_;
unsigned long bytes_per_second_;
size_t block_alignment_;
unsigned int bits_per_sample_;
size_t frame_size_;
size_t channel_size_;
size_t initial_data_chunk_offset_;
size_t final_data_chunk_offset_;
size_t next_data_chunk_offset_;
size_t current_data_chunk_frames_;
uint8_t frame_[MAX_FRAME_SIZE];
bool silence_;
};
| true |
d310de540cb2f1f82b0577c33f74dba78b03589f | C++ | QBseventy/ESP32-Special | /BME680/04 - ESP32-BLE/code/SerialBluetoothBidirectional/SerialBluetoothBidirectional.ino | UTF-8 | 395 | 2.78125 | 3 | [] | no_license | #include "BluetoothSerial.h"
BluetoothSerial bluetooth;
void setup() {
Serial.begin(115200);
if (!bluetooth.begin("ESP32")) {
Serial.println("Bluetooth konnte nicht aktiviert werden.");
} else {
Serial.println("Der ESP32 kann gekoppelt werden.");
}
}
void loop() {
while (bluetooth.available()) {
Serial.write(bluetooth.read());
}
delay(20);
}
| true |
dfbb6d59e35ad3c938c7a245b5582433787672cb | C++ | kyun2024/ProgramSolve | /17588.cpp | UTF-8 | 307 | 2.640625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(){
int n,a,c;
c = 1;
cin >> n;
for(int i=0;i<n;i++){
cin >> a;
while(c<a){
cout << c << endl;
c++;
}
c++;
}
if(a==n){
cout << "good job" << endl;
}
return 0;
} | true |
6dea22d55693f73a91270866d517fef9905a25eb | C++ | AguiarVicente/COTI | /LOGICA/Aula 05/prog2.cpp | ISO-8859-1 | 1,138 | 3.78125 | 4 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
/*
Criar um programa que leia dois
numeros.
A) O programa devera conter um menu com
as 4 operaes bsicas da matematica.
B) Imprimr o valor da operao selecionada.
*/
int a;
int b;
int opcao;
int main(){
int ope = 0;
printf("Digite um numero : ");
scanf("%d", &a);
printf("Digite um numero : ");
scanf("%d", &b);
printf("Menu : \n");
printf("1 - Adicao : \n");
printf("2 - Subtracao : \n");
printf("3 - Multiplicacao : \n");
printf("4 - Divisao : \n");
scanf("%d", &opcao);
switch(opcao){
case 1:
ope = a + b;
printf("Adicao : %d \n", ope);
break;
case 2:
ope = a - b;
printf("Subtracao : %d \n", ope);
break;
case 3:
ope = a * b;
printf("Multiplicacao : %d \n", ope);
break;
case 4:
if( b == 0){
printf("Nao ha divisao por zero! \n");
break;
}
ope = a / b;
printf("Divisao : %d \n", ope);
break;
default:
printf("Operacao Invalida! \n");
break;
}
system("pause");
return 0;
}
| true |
018a68e91dadd0c6a69e1ceb21e49f4a2cc1c5e8 | C++ | Igronemyk/OI | /CodeForces/862B.cpp | UTF-8 | 1,185 | 2.890625 | 3 | [] | no_license | #include <cstdio>
#include <vector>
#include <iostream>
using namespace std;
template<typename T>
T read(){
T result = 0;int f = 1;char c = getchar();
while(c >'9' || c < '0') {if(c == '-') f *= -1;c = getchar();}
while(c <= '9' && c >= '0') {result = result * 10 + c - '0';c = getchar();}
return result * f;
}
vector<int> graph[100000];
bool visit[100000],groups[100000];
int sizeA = 0,sizeB = 0;
void dfs(int now,int group){
visit[now] = true;
if(group){
sizeB++;
groups[now] = true;
}else{
sizeA++;
groups[now] = false;
}
for(vector<int>::iterator it = graph[now].begin();it != graph[now].end();it++){
if(visit[*it]) continue;
dfs(*it,!group);
}
}
int main(){
int n = read<int>();
for(int i = 0;i < n - 1;i++){
int nodeA = read<int>(),nodeB = read<int>();
nodeA--; nodeB--;
graph[nodeA].push_back(nodeB);
graph[nodeB].push_back(nodeA);
}
dfs(0,0);
long long result = 0;
for(int i = 0;i < n;i++){
result += (groups[i] ? sizeA : sizeB) - static_cast<int>(graph[i].size());
}
cout << result / 2 << endl;
return 0;
}
| true |
3c609ea732ffb519dc0bdad8cde2223272c42190 | C++ | kennyist/RushHourDX11 | /RushHour - Solution/Soft351SoundFile.cpp | UTF-8 | 3,120 | 2.765625 | 3 | [] | no_license | #include "Soft351SoundFile.h"
// Usefull links:
// Wave header:
// http://soundfile.sapp.org/doc/WaveFormat/
// WAVEFORMATEX:
// https://msdn.microsoft.com/en-us/library/windows/desktop/dd390970(v=vs.85).aspx
// Fopen:
// http://www.cplusplus.com/reference/cstdio/fopen/
// fRead:
// http://www.cplusplus.com/reference/cstdio/fread/
// fSeek:
// http://www.cplusplus.com/reference/cstdio/fseek/
// Constructor
Soft351SoundFile::Soft351SoundFile()
{
m_data = 0;
}
// Deconstructor
Soft351SoundFile::~Soft351SoundFile()
{
}
// Release objects before deletion
void Soft351SoundFile::Release() {
if (m_data)
delete m_data;
}
// Load a wave file into object
bool Soft351SoundFile::LoadFile(
char* fileLocation, // wave file location
long int volume // default game volume
) {
// Setup method variables
int error;
FILE* p_file;
unsigned int elements;
HRESULT result;
// set object volume
m_volume = volume;
// Open the wave file to FILE pointer
error = fopen_s(&p_file, fileLocation, "rb");
// if failed to open file, return false
if (error != 0)
{
return false;
}
// Read the wave file header data to m_header
elements = fread(&m_header, sizeof(m_header), 1, p_file);
// If failed return false, failed to read header
if (elements != 1)
{
return false;
}
// Check if file ID is RIFF
if (
(m_header.chunkId[0] != 'R') ||
(m_header.chunkId[1] != 'I') ||
(m_header.chunkId[2] != 'F') ||
(m_header.chunkId[3] != 'F')
)
{
// if failed return false, file ID is not RIFF
return false;
}
// Check if the file is in wave format
if (
(m_header.format[0] != 'W') ||
(m_header.format[1] != 'A') ||
(m_header.format[2] != 'V') ||
(m_header.format[3] != 'E')
)
{
// if failed return false, file format is not WAVE
return false;
}
// See if data chunk exists
if (
(m_header.dataChunk2Id[0] != 'd') ||
(m_header.dataChunk2Id[1] != 'a') ||
(m_header.dataChunk2Id[2] != 't') ||
(m_header.dataChunk2Id[3] != 'a')
)
{
// if failed return false, data chunk not found
return false;
}
// Set the wave format from header data
m_format.wFormatTag = m_header.audioFormat;
m_format.nSamplesPerSec = m_header.sampleRate;
m_format.wBitsPerSample = m_header.bitsPerSample;
m_format.nChannels = m_header.numChannels;
m_format.nBlockAlign = (m_format.wBitsPerSample / 8) * m_format.nChannels;
m_format.nAvgBytesPerSec = m_format.nSamplesPerSec * m_format.nBlockAlign;
m_format.cbSize = 0;
// Seek the beginning of data in data chunk
fseek(p_file, sizeof(WaveHeaderType), SEEK_SET);
// Initialize the data holder
m_data = new unsigned char[m_header.data];
// if failed return false, failed to create data holder
if (!m_data)
{
return false;
}
// Copy the file data to m_data holder
elements = fread(m_data, 1, m_header.data, p_file);
// if failed return false, failed to copy data
if (elements != m_header.data)
{
return false;
}
// Close the file
error = fclose(p_file);
// if failed return false, failed to close file
if (error != 0)
{
return false;
}
// Cleanup
p_file = NULL;
// Everything worked ok!
return true;
} | true |
9c51da20874c4660a938cf00028742b3c094aba6 | C++ | RadekVana/EmbeddedStateMechanic | /StateMechanic/State/State.cpp | UTF-8 | 3,207 | 2.859375 | 3 | [
"MIT"
] | permissive | #include "State.hpp"
/******************************************************************************/
//State
State::State(IStateMachineWithEventFireRequest& sm, auto_ptr<EvHandler> entry, auto_ptr<EvHandler> exit):
IStateWithMachineRef(sm),
entryHandler(entry),
exitHandler(exit){}
void State::SinkEntryHandler(auto_ptr<EvHandler> eh){
entryHandler = eh;
}
void State::SinkExitHandler(auto_ptr<EvHandler> eh){
exitHandler = eh;
}
void State::FireEntry(auto_ptr<Iinfo> info) const{
(*entryHandler)(info);
}
void State::FireExit(auto_ptr<Iinfo> info) const{
(*exitHandler)(info);
}
bool State::IsCurrent() const{
return (&(GetParentStateMachine().GetCurrentState())) == this;
}
/******************************************************************************/
//TransitionOn
bool State::TransitionOn(Event& ev)const{
return TransitionOnTo(ev, *this);
}
bool State::TransitionOnWith(Event& ev, auto_ptr<EvHandler> evh)const{
return TransitionOnToWith(ev, *this, evh);
}
bool State::TransitionOnWithGuard(Event& ev, auto_ptr<TransitionGuard> grd) const{
return TransitionOnToWithGuard(ev, *this, grd);
}
bool State::TransitionOnWithGuardAndHandler(Event& ev, auto_ptr<TransitionGuard> grd,
auto_ptr<EvHandler> evh) const{
return TransitionOnToWithGuardAndHandler(ev, *this, grd, evh);
}
/******************************************************************************/
//TransitionOnTo
bool State::TransitionOnTo(Event& ev, const State& to)const{
auto_ptr<EvHandler> evh(new DummyEvHandler());
return TransitionOnToWith(ev, to, evh);
}
bool State::TransitionOnToWith(Event& ev, const State& to, auto_ptr<EvHandler> evh)const{
auto_ptr<TransitionGuard> grd(new DummyTransitionGuard);
return TransitionOnToWithGuardAndHandler(ev, to, grd, evh);
}
bool State::TransitionOnToWithGuard(Event& ev, const State& to, auto_ptr<TransitionGuard> grd) const{
auto_ptr<EvHandler> evh(new DummyEvHandler());
return TransitionOnToWithGuardAndHandler(ev, to, grd, evh);
}
bool State::TransitionOnToWithGuardAndHandler(Event& ev, const State& to,
auto_ptr<TransitionGuard> grd, auto_ptr<EvHandler> evh) const{
return ev.AddTransition(*this, to, evh, grd);
}
/******************************************************************************/
//InnerSelfTransitionOn
bool State::InnerSelfTransitionOn(Event& ev) const{
auto_ptr<EvHandler> evh(new DummyEvHandler());
return InnerSelfTransitionOnWith(ev, evh);
}
bool State::InnerSelfTransitionOnWith(Event& ev, auto_ptr<EvHandler> evh) const{
auto_ptr<TransitionGuard> grd(new DummyTransitionGuard);
return InnerSelfTransitionOnWithGuardAndHandler(ev, grd, evh);
}
bool State::InnerSelfTransitionOnWithGuard(Event& ev, auto_ptr<TransitionGuard> grd) const{
auto_ptr<EvHandler> evh(new DummyEvHandler());
return InnerSelfTransitionOnWithGuardAndHandler(ev, grd, evh);
}
bool State::InnerSelfTransitionOnWithGuardAndHandler(Event& ev, auto_ptr<TransitionGuard> grd,
auto_ptr<EvHandler> evh) const{
return ev.AddInnerTransition(*this, evh, grd);
} | true |
e5e3cf4176d2fdc37e07b5a779735472e9187377 | C++ | JackDalton3110/Speed-Racing | /Upgrade.cpp | UTF-8 | 15,884 | 2.515625 | 3 | [] | no_license | #include "Upgrade.h"
Upgrade::Upgrade(Game &game, sf::Font font, sf::Font font1) :
m_game(&game),
m_HARLOW(font),
m_Motor(font1),
m_size(600, 200),
button_released(false),
m_status(false),
scrap_size(1,1),
scrap_dirction(0,0),
scrap_mover_positoin(0,0)
{
if (!m_texture[0].loadFromFile("images/whiteCarSprite.png"))
{
std::string s("error loading texture");
throw std::exception(s.c_str());
}
if (!m_texture[1].loadFromFile("images/redCarSprite.png"))
{
std::string s("error loading texture");
throw std::exception(s.c_str());
}
if (!m_texture[2].loadFromFile("images/yellowCarSprite.png"))
{
std::string s("error loading texture");
throw std::exception(s.c_str());
}
if (!m_texture[3].loadFromFile("images/greenCarSprite.png"))
{
std::string s("error loading texture");
throw std::exception(s.c_str());
}
m_Sprite[0].setTexture(m_texture[0]); // white car
m_Sprite[1].setTexture(m_texture[1]); // red car
m_Sprite[2].setTexture(m_texture[2]); // yellow car
m_Sprite[3].setTexture(m_texture[3]); // green car
m_Sprite[0].setPosition(325, 0);
m_Sprite[1].setPosition(325, 200);
m_Sprite[2].setPosition(325, 400);
m_Sprite[3].setPosition(325, 600);
m_Sprite[0].setRotation(90);
m_Sprite[1].setRotation(90);
m_Sprite[2].setRotation(90);
m_Sprite[3].setRotation(90);
//m_Sprite[3].setRotation(90);
m_textMessage[0].setPosition(700, 200);//set position
m_textMessage[0].setString("Max Speed");//set text
m_textMessage[0].setFont(m_HARLOW);//set font
m_textMessage[0].setColor(sf::Color::White);//set colour
m_textMessage[1].setPosition(700, 400);//set position
m_textMessage[1].setString("Aceleration");//set text
m_textMessage[1].setFont(m_HARLOW);//set font
m_textMessage[1].setColor(sf::Color::White);//set colour
m_textMessage[2].setPosition(700, 600);//set position
m_textMessage[2].setString("Handling");//set text
m_textMessage[2].setFont(m_HARLOW);//set font
m_textMessage[2].setColor(sf::Color::White);//set colour
m_textMessage[3].setPosition(450, 0);//set position
m_textMessage[3].setString("Upgrade");//set text
m_textMessage[3].setFont(m_Motor);//set font
m_textMessage[3].setColor(sf::Color::Red);//set colour
m_textMessage[3].setCharacterSize(110);
// car varibles
//Max Speed
m_textMessage[4].setPosition(700, 300);//set position
m_textMessage[4].setFont(m_Motor);//set font
m_textMessage[4].setColor(sf::Color::Red);//set colour
//Aceleration
m_textMessage[5].setPosition(700, 500);//set position
m_textMessage[5].setFont(m_Motor);//set font
m_textMessage[5].setColor(sf::Color::Red);//set colour
//Handling
m_textMessage[6].setPosition(700, 700);//set position
m_textMessage[6].setFont(m_Motor);//set font
m_textMessage[6].setColor(sf::Color::Red);//set colour
m_textMessage[7].setPosition(920, 340);//set position
m_textMessage[7].setFont(m_Motor);//set font
m_textMessage[7].setColor(sf::Color::Red);//set colour
m_textMessage[7].setString("MAX"); // set string
m_textMessage[8].setPosition(920, 540);//set position
m_textMessage[8].setFont(m_Motor);//set font
m_textMessage[8].setColor(sf::Color::Red);//set colour
m_textMessage[8].setString("MAX"); // set string
m_textMessage[9].setPosition(920, 740);//set position
m_textMessage[9].setFont(m_Motor);//set font
m_textMessage[9].setColor(sf::Color::Red);//set colour
m_textMessage[9].setString("MAX"); // set string
m_textMessage[10].setFont(m_Motor);
m_textMessage[10].setColor(sf::Color::Red);
m_textMessage[11].setFont(m_Motor);
m_textMessage[11].setColor(sf::Color::Red);
m_textMessage[11].setString("Need 1 Scrap");
for (int i = 0; i < 4; i++)
{
Max_speed_shape[i].setPosition(700 + i * 50, 340); // set positon
Max_speed_shape[i].setSize(sf::Vector2f(50, 40)); // set size
Max_speed_shape[i].setFillColor(sf::Color::Yellow); // set color
Max_speed_shape[i].setOutlineThickness(5);
Max_speed_shape[i].setOutlineColor(sf::Color::Blue);
Acceleration_shape[i].setPosition(700 + i * 50, 540); // set positon
Acceleration_shape[i].setSize(sf::Vector2f(50, 40)); // set size
Acceleration_shape[i].setFillColor(sf::Color::Yellow); // set color
Acceleration_shape[i].setOutlineThickness(5);
Acceleration_shape[i].setOutlineColor(sf::Color::Blue);
Handling_shape[i].setPosition(700 + i * 50, 740); // set positon
Handling_shape[i].setSize(sf::Vector2f(50, 40)); // set size
Handling_shape[i].setFillColor(sf::Color::Yellow); // set color
Handling_shape[i].setOutlineThickness(5);
Handling_shape[i].setOutlineColor(sf::Color::Blue);
}
m_selecter.setOutlineThickness(5);
m_selecter.setOutlineColor(sf::Color::Blue);
m_selecter.setFillColor(sf::Color::Black);
m_selecter.setSize(sf::Vector2f(300, 200));
warning_back.setOutlineThickness(5);
warning_back.setOutlineColor(sf::Color::Red);
warning_back.setFillColor(sf::Color::White);
warning_back.setSize(m_size);
warning_back.setOrigin(m_size.x / 2, m_size.y / 2);
warning_back.setPosition(500, 400);
m_textMessage[12].setFont(m_Motor);
m_textMessage[12].setColor(sf::Color::Red);
m_textMessage[12].setString("!! NOT ENOUGH SCRAP !! ");
sf::FloatRect textRect = m_textMessage[12].getLocalBounds();
m_textMessage[12].setOrigin(textRect.width / 2, textRect.height / 2);
m_textMessage[12].setPosition(500, 400);
if (!m_texture_scrap.loadFromFile("images/Scrap.png"))
{
std::string s("error loading texture");
throw std::exception(s.c_str());
}
m_sprite_scrap[0].setTexture(m_texture_scrap);
m_sprite_scrap[1].setTexture(m_texture_scrap);
m_sprite_scrap[1].setOrigin(50, 50.5);
m_sprite_scrap[1].setScale(0.5f, 0.5f);
m_sprite_scrap[2].setTexture(m_texture_scrap);
if (!shader.loadFromFile("upgrade.frag", sf::Shader::Fragment))
{
std::string s("error loading shader");
//throw std::exception(s.c_str);
}
shader.setParameter("time", 0);
shader.setParameter("resolution", 1000, 800);
shader.setParameter("mouse", 3, 3);
if (!shaderTxt.loadFromFile("images/shaderTxt.png"))
{
std::string s("error loading shader texture");
//throw std::exception(s.c_str);
}
shaderSprite.setTexture(shaderTxt);
shaderSprite.setPosition(0, 0);
}
Upgrade::~Upgrade()
{
std::cout << "destroying upgrade menu" << std::endl;
}
void Upgrade::update(double t, Xbox360Controller &controller, sf::Time dt)
{
m_cumulativeTime += dt;
updateShader = m_cumulativeTime.asSeconds();
shader.setParameter("time", updateShader);
if (!controller.Abutton() && !controller.Bbutton()) // button release check
{
button_released = true;
}
if (!m_status)
{
if (controller.Abutton() && button_released)// move to status select
{
m_status = true;
button_released = false; // when button pressed
}
if (controller.Bbutton() && button_released)// when player isn't in status back to mainmenu
{
backOut();
button_released = false;
}
}
else
{
if (controller.Abutton() && button_released && !warning && !move_scrap)
{
if (scrap > 0)
{
switch (button_ID)
{
case 0:
if (whiteCar_status[status_ID] < 3)
{
whiteCar_status[status_ID]++;
scrap--;
}
break;
case 1:
if (redCar_status[status_ID] < 3)
{
redCar_status[status_ID]++;
scrap--;
}
break;
case 2:
if (yellowCar_status[status_ID] < 3)
{
yellowCar_status[status_ID]++;
scrap--;
}
break;
case 3:
if (greenCar_status[status_ID] < 3)
{
greenCar_status[status_ID]++;
scrap--;
}
default:
break;
}
button_released = false;
move_scrap = true;
}
else
{
warning = true;
}
}
if (controller.Bbutton() && button_released) // when player isn in status back to car select
{
status_ID = 0;
m_status = false;
button_released = false;
}
m_selecter.setPosition(m_textMessage[status_ID].getPosition().x - 10, m_textMessage[status_ID].getPosition().y - 10); // set seleter's positoin
m_sprite_scrap[1].setPosition(m_textMessage[status_ID].getPosition().x + 25, m_textMessage[status_ID].getPosition().y + 75); // set seleter's positoin
m_sprite_scrap[1].rotate(3);
m_textMessage[11].setPosition(m_sprite_scrap[1].getPosition().x + 50, m_sprite_scrap[1].getPosition().y);
}
if (warning)
{
warning_time -= t;
m_size.y -= 2; // decrease the high of the warning background
m_size.x -= 2;
if (warning_time <= 0)
{
warning_time = 1.0f;
warning = false;
m_size.y = 200; // set the x and y back to start
m_size.x = 600;
}
warning_back.setSize(m_size);
warning_back.setOrigin(m_size.x / 2, m_size.y / 2);
}
if (controller.m_currentState.DPadDown && !controller.m_previousState.DPadDown)
{
if (!m_status)
{
if (button_ID < 3)
{
button_ID++;
}
else
{
button_ID = 0;
}
}
else
{
if (status_ID < 2)
{
status_ID++;
}
else
{
status_ID = 0;
}
}
}
if (controller.m_currentState.DPadUp && !controller.m_previousState.DPadUp)
{
if (!m_status)
{
if (button_ID > 0)
{
button_ID--;
}
else
{
button_ID = 3;
}
}
else
{
if (status_ID > 0)
{
status_ID--;
}
else
{
status_ID = 2;
}
}
}
// use up and down arrow to select car
if (button_ID == 0)
{
if (m_Sprite[0].getPosition().x < 450)//any key accepted to change screen to credits
{
m_Sprite[0].move(10, 0);
}
m_Sprite[1].setPosition(325, 200);
m_Sprite[2].setPosition(325, 400);
m_Sprite[3].setPosition(325, 600);
m_sprite_scrap[0].setPosition(0, 50);
m_textMessage[10].setPosition(100, 60);
m_textMessage[10].setString(m_game->floatToString(scrap));
whiteCar_values[0] = 118 + whiteCar_status[0] * 15;
whiteCar_values[1] = 4.2 - whiteCar_status[1] * 0.4;
whiteCar_values[2] = 50 + whiteCar_status[2] * 5;
m_textMessage[4].setString(m_game->floatToString(whiteCar_values[0]) + " kph");//set Max Speed
m_textMessage[5].setString(m_game->floatToString(whiteCar_values[1]) + " sec to Max Speed");//set Aceeleration
m_textMessage[6].setString(m_game->floatToString(whiteCar_values[2]) + "%");//set Handling
controller.m_previousState = controller.m_currentState;
}
else if (button_ID == 1)
{
if (m_Sprite[1].getPosition().x < 450)//any key accepted to change screen to credits
{
m_Sprite[1].move(10, 0);
}
m_Sprite[0].setPosition(325, 0);
m_Sprite[2].setPosition(325, 400);
m_Sprite[3].setPosition(325, 600);
m_sprite_scrap[0].setPosition(0, 250);
m_textMessage[10].setPosition(100, 260);
m_textMessage[10].setString(m_game->floatToString(scrap));
reaCar_values[0] = 115 + redCar_status[0] * 18;
reaCar_values[1] = 3.9 - redCar_status[1] * 0.35;
reaCar_values[2] = 55 + redCar_status[2] * 4;
m_textMessage[4].setString(m_game->floatToString(reaCar_values[0]) + " kph");//need to be changed to a player editable varible
m_textMessage[5].setString(m_game->floatToString(reaCar_values[1]) + " sec to Max Speed");//set Aceeleration
m_textMessage[6].setString(m_game->floatToString(reaCar_values[2]) + "%");//set Handling
controller.m_previousState = controller.m_currentState;
}
else if (button_ID == 2)
{
if (m_Sprite[2].getPosition().x < 450)//any key accepted to change screen to credits
{
m_Sprite[2].move(10, 0);
}
m_Sprite[0].setPosition(325, 0);
m_Sprite[1].setPosition(325, 200);
m_Sprite[3].setPosition(325, 600);
m_sprite_scrap[0].setPosition(0,450);
m_textMessage[10].setPosition(100, 460);
m_textMessage[10].setString(m_game->floatToString(scrap));
yellowCar_values[0] = 112 + yellowCar_status[0] * 12;
yellowCar_values[1] = 4.5 - yellowCar_status[1] * 0.5;
yellowCar_values[2] = 25 + yellowCar_status[2] * 10;
m_textMessage[4].setString(m_game->floatToString(yellowCar_values[0]) + " kph");
m_textMessage[5].setString(m_game->floatToString(yellowCar_values[1]) + " sec to Max Speed");//set Aceeleration
m_textMessage[6].setString(m_game->floatToString(yellowCar_values[2]) + "%");//set Handling
controller.m_previousState = controller.m_currentState;
}
else if (button_ID == 3)
{
if (m_Sprite[3].getPosition().x < 450)//any key accepted to change screen to credits
{
m_Sprite[3].move(10, 0);
}
m_Sprite[0].setPosition(325, 0);
m_Sprite[1].setPosition(325, 200);
m_Sprite[2].setPosition(325, 400);
m_sprite_scrap[0].setPosition(0, 650);
m_textMessage[10].setPosition(100, 660);
m_textMessage[10].setString(m_game->floatToString(scrap));
greenCar_values[0] = 118 + greenCar_status[0] * 15;
greenCar_values[1] = 4.0 - greenCar_status[1] * 0.4;
greenCar_values[2] = 30 + greenCar_status[2] * 8;
m_textMessage[4].setString(m_game->floatToString(greenCar_values[0]) + " kph");
m_textMessage[5].setString(m_game->floatToString(greenCar_values[1]) + " sec to Max Speed");//set Aceeleration
m_textMessage[6].setString(m_game->floatToString(greenCar_values[2]) + "%");//set Handling
controller.m_previousState = controller.m_currentState;
}
scrapAnimation(t);
}
/// <summary>
/// upgrade animation
/// </summary>
/// <param name="t"></param>
void Upgrade::scrapAnimation(double t)
{
if (!move_scrap)
{
m_sprite_scrap[2].setPosition(m_sprite_scrap[0].getPosition());
scrap_mover_positoin = m_sprite_scrap[0].getPosition();
scrap_dirction = m_sprite_scrap[1].getPosition() - scrap_mover_positoin;
scrap_size.x = 1;
scrap_size.y = 1;
}
else
{
scrap_time -= t;
scrap_mover_positoin.x += scrap_dirction.x * t;
scrap_mover_positoin.y += scrap_dirction.y * t;
scrap_size.x -= 1 * t;
scrap_size.y -= 1 * t;
m_sprite_scrap[2].setPosition(scrap_mover_positoin);
if (scrap_time <= 0)
{
scrap_time = 1.0f;
move_scrap = false;
}
}
m_sprite_scrap[2].setScale(scrap_size);
}
void Upgrade::changeScreen()
{
m_game->SetGameState(GameState::upgrade);
}
void Upgrade::backOut()
{
m_game->SetGameState(GameState::option);
}
void Upgrade::render(sf::RenderWindow &window)
{
window.clear(sf::Color(0, 0, 0, 255));
window.draw(shaderSprite, &shader);
window.draw(m_sprite_scrap[0]);
window.draw(m_textMessage[10]);
for (int i = 0; i < 4; i++)
{
window.draw(m_Sprite[i]);
}
if (m_status)
{
window.draw(m_selecter); // status seleter
window.draw(m_sprite_scrap[1]); // scrap image
window.draw(m_textMessage[11]); // scrap player needs
}
switch (button_ID)
{
case 0: // draw white car's status
drawStatusShape(window, whiteCar_status[0], whiteCar_status[1], whiteCar_status[2]);
break;
case 1: // draw red car's status
drawStatusShape(window, redCar_status[0], redCar_status[1], redCar_status[2]);
break;
case 2: // draw yellow car's status
drawStatusShape(window, yellowCar_status[0], yellowCar_status[1], yellowCar_status[2]);
break;
case 3: // draw green car's status
drawStatusShape(window, greenCar_status[0], greenCar_status[1], greenCar_status[2]);
break;
default:
break;
}
//Sound_Difficulty
window.draw(m_textMessage[0]);
window.draw(m_textMessage[1]);
window.draw(m_textMessage[2]);//main menu draw
window.draw(m_textMessage[3]);//setting draw
window.draw(m_textMessage[4]);
window.draw(m_textMessage[5]);
window.draw(m_textMessage[6]);
if (move_scrap)
{
window.draw(m_sprite_scrap[2]);
}
if (warning)
{
window.draw(warning_back);
window.draw(m_textMessage[12]);
}
//window.display();
}
void Upgrade::drawStatusShape(sf::RenderWindow &window, int maxSpeed, int acceleration, int handling)
{
for (int i = 0; i < maxSpeed + 1; i++)
{
window.draw(Max_speed_shape[i]);
}
for (int i = 0; i < acceleration + 1; i++)
{
window.draw(Acceleration_shape[i]);
}
for (int i = 0; i < handling + 1; i++)
{
window.draw(Handling_shape[i]);
}
if (maxSpeed == 3)
{
window.draw(m_textMessage[7]);
}
if (acceleration == 3)
{
window.draw(m_textMessage[8]);
}
if (handling == 3)
{
window.draw(m_textMessage[9]);
}
} | true |
c9d2d6cc2ed5c08e0e80c07eee7e899f492d1841 | C++ | yeargun/MovieLibrary | /LibrarySystem.cpp | UTF-8 | 4,405 | 3.359375 | 3 | [] | no_license | #include "LibrarySystem.h"
#include <fstream>
#include <iostream>
extern ofstream output;
LibrarySystem::LibrarySystem() {
this->movies->nextMovie = NULL;
this->user->nextUser = NULL;
this->user->previousUser = NULL;
output << "===Movie Library System===\n";
}
LibrarySystem::~LibrarySystem(){
}
bool LibrarySystem::differentThanLastCalledFunction(int functionNumber) {
//this function helps to print the ===method test()===
//Whenever you call a LibrarySystem which is different from the last called LibrarySystem function
//it returns true
if (lastCalledFunctionNumber != functionNumber)
return true;
else return false;
}
void LibrarySystem::updateUsersCheckedMovies(int movieId){
//when a movie gets deleted, this function deletes the movie from users' checkedOutMovies linked list
User* tempUser=this->user;
Movie* tempMovie;
do{
tempMovie=tempUser->checkedMovies->movieWithGivenId(movieId);
if(tempMovie!=NULL){
tempUser->checkedMovies->deleteMovie(movieId,true);
return;
}
tempUser=tempUser->nextUser;
}while (tempUser!=this->user && tempUser!=NULL);
}
void LibrarySystem::addMovie(const int movieId, const string movieTitle, const int year) {
if (differentThanLastCalledFunction(1)) {output << "\n===addMovie() method test===\n";}lastCalledFunctionNumber = 1;
this->movies->addMovie(movieId, movieTitle, year);
}
void LibrarySystem::deleteMovie(const int movieId) {
if (differentThanLastCalledFunction(2)) {output << "\n===deleteMovie() method test===\n";}lastCalledFunctionNumber = 2;
this->movies->deleteMovie(movieId);
updateUsersCheckedMovies(movieId);
updateNonCheckedMovies();
}
void LibrarySystem::addUser(const int userId, const string userName) {
if (differentThanLastCalledFunction(3)) {output << "\n===addUser() method test===\n";}lastCalledFunctionNumber = 3;
this->user->addUser(userId, userName);
}
void LibrarySystem::deleteUser(const int userId) {
if (differentThanLastCalledFunction(4)) {output << "\n===deleteUser() method test===\n";}lastCalledFunctionNumber = 4;
this->user->deleteUser(userId,this->movies);
//when a user gets deleted, the movies which her/his checkedOut gets deleted from library
}
void LibrarySystem::checkoutMovie(const int movieId, const int userId) {
if (differentThanLastCalledFunction(5)) {output << "\n===checkoutMovie() method test===\n";}lastCalledFunctionNumber = 5;
user->checkOutMovie(movies->movieWithGivenId(movieId), userId,movieId);
}
void LibrarySystem::updateNonCheckedMovies() {
//after the functions which can result changes on nonCheckedMovies linked list
//i call this function to update nonCheckedMovies linked list
nonCheckedMovies->nextMovie=NULL;
Movie* tempMovie=this->movies;
if(tempMovie->nextMovie==NULL)
return;
do{
if(!tempMovie->isChecked){
nonCheckedMovies->addMovie(tempMovie->id,tempMovie->name, tempMovie->year,true);
}
tempMovie=tempMovie->nextMovie;
}while(tempMovie!=this->movies && tempMovie!=NULL);
}
void LibrarySystem::returnMovie(const int movieId) {
if (differentThanLastCalledFunction(6)) {output << "\n===returnMovie() method test===\n";}lastCalledFunctionNumber = 6;
int userId = movies->returnMovie(movieId);
//if theres a "movie with given id" which can be returned, returnMovie function returns its userId.
// if it doesnt exists returns -1
//Also Return movie function turns that movies' attribute to "non checked movie"
if(userId!=-1){
(user->userWithGivenId(userId))->checkedMovies->deleteMovie(movieId,true);
}
}
void LibrarySystem::showAllMovies() {
if (differentThanLastCalledFunction(7)) {output << "\n===showAllMovie() method test===\n";}lastCalledFunctionNumber = 7;
this->movies->showAllMovies();
}
void LibrarySystem::showMovie(const int movieId) {
if (differentThanLastCalledFunction(8)) {output << "\n===showMovie() method test===\n";}lastCalledFunctionNumber = 8;
this->movies->showMovie(movieId);
}
void LibrarySystem::showUser(const int userId) {
if (differentThanLastCalledFunction(9)) {output << "\n===showUser() method test===\n";}lastCalledFunctionNumber = 9;
this->user->showUser(userId);
} | true |
c9ed39dd88c7df30fc7ca65d0b35a006536161f2 | C++ | frezo445/OpenMinecraft | /mclib/core/PlayerManager.h | UTF-8 | 3,394 | 2.734375 | 3 | [] | no_license | #ifndef MCLIB_CORE_PLAYER_MANAGER_H_
#define MCLIB_CORE_PLAYER_MANAGER_H_
#include <common/UUID.h>
#include <entity/EntityManager.h>
#include <entity/Player.h>
#include <util/ObserverSubject.h>
class PlayerManager;
class Player
{
friend class PlayerManager;
public:
Player(CUUID uuid, std::wstring name)
: m_UUID(uuid)
, m_Name(name)
{ }
std::shared_ptr<PlayerEntity> GetEntity() const { return m_Entity.lock(); }
void SetEntity(PlayerEntityPtr entity) { m_Entity = entity; }
const std::wstring& GetName() const { return m_Name; }
CUUID GetUUID() const { return m_UUID; }
private:
CUUID m_UUID;
std::wstring m_Name;
PlayerEntityPtr m_Entity;
};
typedef std::shared_ptr<Player> PlayerPtr;
class PlayerListener
{
public:
virtual ~PlayerListener() {}
// Called when a PlayerPositionAndLook packet is received (when client spawns or is teleported by server). The player's position is already updated in the entity.
virtual void OnClientSpawn(PlayerPtr player) {}
// Called when a player joins the server.
virtual void OnPlayerJoin(PlayerPtr player) {}
// Called when a player leaves the server
virtual void OnPlayerLeave(PlayerPtr player) {}
// Called when a player comes within visible range of the client
virtual void OnPlayerSpawn(PlayerPtr player) {}
// Called when a player leaves visible range of the client The PlayerPtr entity is already set to null at this point. The entity still exists in the entity manager, which can be grabbed by the entity id
virtual void OnPlayerDestroy(PlayerPtr player, EntityId eid) {}
// Called when a player changes position. Isn't called when player only rotates.
virtual void OnPlayerMove(PlayerPtr player, glm::dvec3 oldPos, glm::dvec3 newPos) {}
};
class PlayerManager
: public PacketHandler
, public EntityListener
, public ObserverSubject<PlayerListener>
{
public:
typedef std::map<CUUID, PlayerPtr> PlayerList;
typedef PlayerList::iterator iterator;
public:
MCLIB_API PlayerManager(PacketDispatcher* dispatcher, EntityManager* entityManager);
MCLIB_API ~PlayerManager();
PlayerManager(const PlayerManager& rhs) = delete;
PlayerManager& operator=(const PlayerManager& rhs) = delete;
PlayerManager(PlayerManager&& rhs) = delete;
PlayerManager& operator=(PlayerManager&& rhs) = delete;
iterator MCLIB_API begin();
iterator MCLIB_API end();
// Gets a player by their UUID. Fast method, just requires map lookup.
PlayerPtr MCLIB_API GetPlayerByUUID(CUUID uuid) const;
// Gets a player by their EntityId. Somewhat slow method, has to loop through player map to find the player with that eid. It should still be pretty fast though since there aren't many players on a server usually.
PlayerPtr MCLIB_API GetPlayerByEntityId(EntityId eid) const;
// Gets a player by their username.
PlayerPtr MCLIB_API GetPlayerByName(const std::wstring& name) const;
// EntityListener
void MCLIB_API OnPlayerSpawn(PlayerEntityPtr entity, CUUID uuid);
void MCLIB_API OnEntityDestroy(EntityPtr entity);
void MCLIB_API OnEntityMove(EntityPtr entity, glm::dvec3 oldPos, glm::dvec3 newPos);
// PacketHandler
void MCLIB_API HandlePacket(login::in::LoginSuccessPacket* packet);
void MCLIB_API HandlePacket(in::PlayerPositionAndLookPacket* packet);
void MCLIB_API HandlePacket(in::PlayerListItemPacket* packet);
private:
PlayerList m_Players;
EntityManager* m_EntityManager;
CUUID m_ClientUUID;
};
#endif
| true |
a4423f07827c2ad5046f4232094a5f22648409c3 | C++ | Wassasin/nebula | /src/gl/vbo.hpp | UTF-8 | 4,159 | 2.78125 | 3 | [] | no_license | // Copyright 2013 Maurice Bos
//
// This file is part of Moggle.
//
// Moggle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moggle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moggle. If not, see <http://www.gnu.org/licenses/>.
#pragma once
#include <utility>
#include <vector>
#include "gl.hpp"
template<typename> class vbo;
class generic_vbo {
private:
mutable GLuint id = 0;
public:
explicit generic_vbo(bool create_now = false) {
if (create_now) create();
}
~generic_vbo() { destroy(); }
generic_vbo(generic_vbo const &) = delete;
generic_vbo & operator = (generic_vbo const &) = delete;
generic_vbo(generic_vbo && v) : id(v.id) { v.id = 0; }
generic_vbo & operator = (generic_vbo && v) { std::swap(id, v.id); return *this; }
bool created() const { return id; }
explicit operator bool() const { return created(); }
void create() const { if (!id) gl::generate_buffers(1, &id); }
void destroy() { gl::delete_buffers(1, &id); id = 0; }
void bind(GLenum buffer) const {
create();
gl::bind_buffer(buffer, id);
}
};
template<typename T>
class vbo_mapping {
private:
T * const data_;
size_t size_;
template<typename> friend class vbo;
vbo_mapping(void * data, size_t size)
: data_(static_cast<T *>(data)), size_(size) {}
public:
T * data() const { return data_; }
size_t size() const { return size_; }
T * begin() const { return data_; }
T * end() const { return data_ + size_; }
~vbo_mapping() { gl::unmap_buffer(GL_ARRAY_BUFFER); }
};
template<typename T>
class vbo : public generic_vbo {
public:
explicit vbo(bool create_now = false) : generic_vbo(create_now) {}
vbo(T const * begin, T const * end, GLenum usage = GL_STATIC_DRAW) {
data(begin, end, usage);
}
vbo(T const * begin, size_t size, GLenum usage = GL_STATIC_DRAW) {
data(begin, size, usage);
}
vbo(std::vector<T> const & v, GLenum usage = GL_STATIC_DRAW) {
data(v, usage);
}
template<size_t N>
vbo(std::array<T, N> const & v, GLenum usage = GL_STATIC_DRAW) {
data(v, usage);
}
template<size_t N>
vbo(T const (&v)[N], GLenum usage = GL_STATIC_DRAW) {
data(v, usage);
}
vbo(std::initializer_list<T> list, GLenum usage = GL_STATIC_DRAW) {
data(list, usage);
}
size_t size() const {
GLint s;
bind(GL_ARRAY_BUFFER);
glGetBufferParameteriv(GL_ARRAY_BUFFER, GL_BUFFER_SIZE, &s);
return s / sizeof(T);
}
void data(T const * begin, size_t size, GLenum usage = GL_STATIC_DRAW) {
bind(GL_ARRAY_BUFFER);
gl::buffer_data(
GL_ARRAY_BUFFER,
size * sizeof(T),
begin,
usage
);
}
void resize(size_t size, GLenum usage = GL_STATIC_DRAW) {
bind(nullptr, size, usage);
}
void clear(GLenum usage = GL_STATIC_DRAW) {
resize(0, usage);
}
void data(T const * begin, T const * end, GLenum usage = GL_STATIC_DRAW) {
data(begin, end - begin, usage);
}
void data(std::vector<T> const & v, GLenum usage = GL_STATIC_DRAW) {
data(v.data(), v.size(), usage);
}
template<size_t N>
void data(std::array<T, N> const & v, GLenum usage = GL_STATIC_DRAW) {
data(v.data(), N, usage);
}
template<size_t N>
void data(T const (&v)[N], GLenum usage = GL_STATIC_DRAW) {
data(v, N, usage);
}
void data(std::initializer_list<T> list, GLenum usage = GL_STATIC_DRAW) {
data(list.begin(), list.size(), usage);
}
vbo_mapping<T const> map_read_only() const {
bind(GL_ARRAY_BUFFER);
return { gl::map_buffer(GL_ARRAY_BUFFER, GL_READ_ONLY), size() };
}
vbo_mapping<T> map_write_only() const {
bind(GL_ARRAY_BUFFER);
return { gl::map_buffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY), size() };
}
vbo_mapping<T> map_read_write() const {
bind(GL_ARRAY_BUFFER);
return { gl::map_buffer(GL_ARRAY_BUFFER, GL_READ_WRITE), size() };
}
};
| true |
4292b8e22a5c01143f8eb66581c97a59906b1871 | C++ | coderfamer/linuxstudy | /c++/c++primer_05/ch07/ex07_05_person.h | UTF-8 | 296 | 2.75 | 3 | [] | no_license | #ifndef _EX07_04_PERSON_H_
#define _EX07_04_PERSON_H_
#include <iostream>
#include <string>
struct Person
{
const std::string& get_name() const { return m_name; }
const std::string& get_address() const { return m_address; }
std::string m_name;
std::string m_address;
};
#endif | true |
026df62e83b9139207a4dd96aa11b36926abbcb5 | C++ | fatisar/cse532-lab2 | /src/player-main.cpp | UTF-8 | 3,139 | 2.59375 | 3 | [] | no_license | // CSE571 - player-main.cpp
// Authors: Jonathan Wald, Daniel Sarfati, Guangle Fan
// This file holds the main function that is run by the client program.
#include <iostream>
#include <ace/INET_Addr.h>
#include <ace/Connector.h>
#include <ace/SOCK_Connector.h>
#include "game-manager.h"
#include "player-game.h"
#include "signal-handler.h"
class PlayerSvcHandler;
typedef ACE_Connector<PlayerSvcHandler,ACE_SOCK_CONNECTOR>
PlayerConnector;
const int MTU = 1500;
extern char buffer[];
int parse_file(char* filename);
int main(int argc, char* argv[]) {
GameManager* manager = GameManager::instance();
// Process the command line switches. Look at every second arg for
// a recognizable flag.
const int NAME_FLAG = 0, FILE_FLAG = 1;
int flag;
bool parse_error = false;
string error_msg;
for (int i = 2; i < argc; i += 2) {
if (!strcmp("-n", argv[i-1])) flag = NAME_FLAG;
else if (!strcmp("-f", argv[i-1])) flag = FILE_FLAG;
else {
parse_error = true;
error_msg = "Unknown flag.";
break;
}
if ((argv[i][0] == '-') || (strlen(argv[i]) == 0)) {
parse_error = true;
error_msg = "Missing parameter for flag.";
break;
}
switch (flag) {
case NAME_FLAG:
manager->name = argv[i];
break;
case FILE_FLAG:
if (manager->parse_file(argv[i]) != 0) {
parse_error = true;
error_msg = "Could not parse defintion file.";
}
break;
}
}
if (parse_error) {
std::cout << "ERROR: " << error_msg << std::endl;
std::cout << "Usage: client -n <player name> -f <definition file> " << std::endl;
return -1;
}
PlayerConnector player_connector(ACE_Reactor::instance());
// keep track of the number of open connections so we can
// kill the client if no connections were able to be opened
int num_open_connections = manager->games.size();
for (unsigned int i = 0; i < manager->games.size(); ++i) {
PlayerGame* game = manager->games[i];
ACE_INET_Addr peer_addr;
if (peer_addr.set(game->port, game->host.c_str()) == -1) {
std::cout << "Unable to set server address for " << game->host << ":" << game->port << std::endl;
num_open_connections--;
continue;
}
peer_addr.addr_to_string (buffer, MTU);
std::cout << "Address and port: " << buffer << std::endl;
PlayerSvcHandler* connector_handler = &(game->handler);
if (player_connector.connect (connector_handler, peer_addr) == -1) {
std::cout << "Couldn't connect to server.\n" << std::endl;
num_open_connections--;
}
}
if (num_open_connections == 0) return -1; // kill the client if no connections were able to be opened
// Implement signal handler.
ACE_Sig_Action sa;
sa.register_action (SIGINT);
SigHandler sh (ACE_Reactor::instance());
while (!SigHandler::sigint_fired()) {
ACE_Reactor::instance()->handle_events();
}
if (GameManager::instance() != NULL) {
delete GameManager::instance();
}
return 0;
}
| true |
1c9e889523080e8c2a1f907fc660db8e45d2dae2 | C++ | AllenCompSci/FLOPPYGLORY | /ARMADA/ARMADA.CPP | UTF-8 | 53,881 | 2.703125 | 3 | [
"MIT"
] | permissive | //Rebecca Grigsby, Kathy Harrod, Rebecca Russell
//6th
//Mr. Baker
//Program:
#include<iostream.h>
#include<conio.h>
#include<apstring.h>
#include<iomanip.h>
#include<apvector.h>
#include<stdlib.h>
#include<stdio.h>
#include<fstream.h>
#include<graphics.h>
#include<ctype.h>
#include<dos.h>
//Constant
//Structures
struct track
{
int X; //Horizontal Screen coordinates for circle
int Y; //Vertical Screen coordinates for circle
bool Ships; //Flags location of ships
bool Fire; //Flags locations fired upon
};
//Variable
apvector <int> Compships (5); //Holds lengths of ships
apvector <track> Compships1 (2); //Holds X, Y, and hit or not status for computer's ship
apvector <track> Compships2 (3); //Holds X, Y, and hit or not status for computer's ship
apvector <track> Compships3 (3); //Holds X, Y, and hit or not status for computer's ship
apvector <track> Compships4 (4); //Holds X, Y, and hit or not status for computer's ship
apvector <track> Compships5 (5); //Holds X, Y, and hit or not status for computer's ship
apvector <track> Userships1 (2); //Holds X, Y, and hit or not status for user's ship
apvector <track> Userships2 (3); //Holds X, Y, and hit or not status for user's ship
apvector <track> Userships3 (3); //Holds X, Y, and hit or not status for user's ship
apvector <track> Userships4 (4); //Holds X, Y, and hit or not status for user's ship
apvector <track> Userships5 (5); //Holds X, Y, and hit or not status for user's ship
track User [10][10]; //Holds information regarding the user
track Computer [10][10]; //Holds information regarding the computer
int Choice; //Decides if game runs or not
int Xcoor; //0-9 coordinate for X portion of matrices and the values associated
int Ycoor; //0-9 coordinate for Y portion of matrices and the values associated
int Letnum; //0-9 coordinate for Y portion of matrices and the values associated
int Xcoor2; //Used to change values so they can be used in matrix
int D; //Direction
int AI; //Used to drive for loops
int AI2; //Used to drive for loops
int X2; //Second X coordinate
int Y2; //Second Y coordinate
int UI; //Used to drive for loops
int UI2; //Used to drive for loops
bool Continue1; //Holds user true/false value to decide if the game continues
bool Continue2; //Holds computer true/false value to decide if the game continues
bool Redo; //Used to determine if a ship is already in a location
int Grdriver, Grmode, Errorcode; //Given by Baker for graphics
ifstream In; //Used to take in coordinates from the disk
bool Usink1; //Used for determining if a ship is sunk already
bool Usink2; //Used for determining if a ship is sunk already
bool Usink3; //Used for determining if a ship is sunk already
bool Usink4; //Used for determining if a ship is sunk already
bool Usink5; //Used for determining if a ship is sunk already
bool Csink1; //Used for determining if a ship is sunk already
bool Csink2; //Used for determining if a ship is sunk already
bool Csink3; //Used for determining if a ship is sunk already
bool Csink4; //Used for determining if a ship is sunk already
int Count; //Used to keep track of ships hit by the computer
int Count2; //Used as a limit in do-while loops
int AIX; //Passed X coordinate value
int AIY; //Passed Y coordinate value
bool Csink5; //Used for determining if a ship is sunk already
bool Ugamego; //Returned value of user function to determine if the next turn goes or not
bool Cgamego; //Returned value of computer function to determine if the next turn goes or not
apstring Status; //Tells the computer where to look
int Endornot; //Ends the game or not
apvector <apstring> Nameships(5); //Holds the names of ships
int I; //Variable used in for loops
int Splash1; //randomly selected point for MISS line
int Splash2; //randomly selected point for MISS line
int Splash3; //randomly selected point for MISS line
int J; //Variable used in for loops
int Explod1; //randomly selected point for HIT line
int Explod2; //randomly selected point for HIT line
int Wave; //used in for loop to at title screen
int First1; //randomly selected point for ocean water lines
int First2; //randomly selected point for ocean water lines
int First3; //randomly selected point for ocean water lines
int Start1; //used in for loop at the title screen
int Var; //randomly selected color for WIN/LOSE screens
//Prototypes
void hit(); //Kathy
void miss(); //Kathy
void title_screen(); //Kathy
void sink(); //Kathy
int setup();
void grsetup (int&, int&, int&);
void intro(); //Me
void helpinstr(); // Someone needs to do
bool user(bool&, bool&, bool&, bool&, bool&); //Rebecca R
bool computer( int&, int&, bool&, bool&, bool&, bool&, bool&, apstring&); //Me
void credits(); //Kathy
void usersetup(); // Rebecca R working on this
void grid();
void compsetup();
void windowfill ();
void win ();
void lose ();
void main ()
{
/*I=430;
for (AI=0; AI<10; AI++)
{for (AI2=0; AI2<10; AI2++)
User[AI][AI2].X=I;
I=I+20;
}
I=190;
for (AI=0; AI<10; AI++)
{for (AI2=0; AI2<10; AI2++)
User[AI][AI2].Y=I;
I=I+20;
}
Out.open("a:\\Usergrid.dat");
for (AI=0; AI<10; AI++)
for (AI2=0; AI2<10; AI2++)
Out<<User[AI][AI2].X<<" ";
for (AI2=0; AI2<10; AI2++)
for (AI=0; AI<10; AI++)
Out<<User[AI][AI2].Y<<" ";
Out.close();
*/
randomize();
grsetup(Grdriver,Grmode,Errorcode);
cleardevice();
do
{
Ugamego=Cgamego=false;
Usink1=Usink2=Usink3=Usink4=Usink5=Csink1=Csink2=Csink3=Csink4=Csink5=false;
Status=" ";
do
{
Choice=setup();
if (Choice==1)
{
do
{
cleardevice();
grid();
setfillstyle(1,GREEN);
/*
for (AI=0; AI<10; AI++)
for (AI2=0; AI2<10; AI2++)
if (Computer[AI][AI2].Ships)
fillellipse(Computer[AI][AI2].X, Computer[AI][AI2].Y, 5, 5);
*/
for(UI=0; UI<10; UI++)
for(UI2=0; UI2<10; UI2++)
if(User[UI][UI2].Ships)
fillellipse(User[UI][UI2].X, User[UI][UI2].Y, 5,5);
setfillstyle(1,15);
for (AI=0; AI<10; AI++)
for (AI2=0; AI2<10; AI2++)
if (!Computer[AI][AI2].Ships && Computer[AI][AI2].Fire)
fillellipse(Computer[AI][AI2].X, Computer[AI][AI2].Y, 5, 5);
for (UI=0; UI<10; UI++)
for (UI2=0; UI2<10; UI2++)
if (!User[UI][UI2].Ships && User[UI][UI2].Fire)
fillellipse(User[UI][UI2].X, User[UI][UI2].Y, 5, 5);
setfillstyle(1,RED);
for (AI=0; AI<10; AI++)
for (AI2=0; AI2<10; AI2++)
if (Computer[AI][AI2].Ships && Computer[AI][AI2].Fire)
fillellipse(Computer[AI][AI2].X, Computer[AI][AI2].Y, 5, 5);
for (UI=0; UI<10; UI++)
for (UI2=0; UI2<10; UI2++)
if (User[UI][UI2].Ships && User[UI][UI2].Fire)
fillellipse(User[UI][UI2].X, User[UI][UI2].Y, 5, 5);
Continue1=user(Csink1, Csink2, Csink3, Csink4, Csink5);
if (!Continue1)
Continue2=computer(AIX, AIY, Usink1, Usink2, Usink3, Usink4, Usink5, Status);
}
while (!Continue1 && !Continue2);
//Congradulate winner
if(Continue1)
win();
else
lose();
Choice=2;
}
else
Choice=2;
}
while(Choice!=2);
cleardevice();
setcolor(15);
outtextxy(40,440,"Are you ready to leave? Press 1 for Yes or 2 for No.");
do
Endornot=getch();
while(Endornot<49 || Endornot>50);
}
while(Endornot==50);
};
void hit()
{//Displays a ship getting hit
//WORDS
setfillstyle(1,15);
bar (400,0,640,160);
bar (0,0,240,160);
setcolor(0);
line(10,20,10,150);
line(40,150,10,150);
line(40,150,40,100);
line(40,100,70,100);
line(70,100,70,150);
line(70,150,100,150);
line(100,150,100,20);
line(100,20,70,20);
line(70,20,70,80);
line(70,80,40,80);
line(40,80,40,20);
line(110,20,110,150);
line(110,150,140,150);
line(140,150,140,20);
line(140,20,110,20);
line(150,20,150,50);
line(150,50,180,50);
line(180,50,180,150);
line(180,150,210,150);
line(210,150,210,50);
line(210,50,230,50);
line(230,50,230,20);
line(230,20,150,20);
line(10,20,40,20);
setfillstyle(4,4);
delay(500);
floodfill(15,25,0);
delay(500);
floodfill(120,30,0);
delay(500);
floodfill(190,40,0);
delay(1000);
//Ship
setfillstyle(2,1);
setcolor(1);
rectangle(400,120,640,160);
floodfill(520,150,1);
setcolor(BLACK);
line(490,80,520,140);
line(520,140,640,140);
line(640,140,640,80);
line(640,80,490,80);
line(520,50,580,50);
line(580,50,580,60);
line(580,60,620,60);
line(620,60,620,80);
line(530,50,530,20);
line(530,20,540,20);
line(540,20,540,50);
line(520,50,520,80);
setfillstyle(1,8);
floodfill(540,100,0);
floodfill(540,60,0);
floodfill(535,30,0);
setfillstyle(1,2);
delay(500);
setcolor(3);
for(I=0;I<6;I++)
{
for(J=0;J<5;J++)
{setcolor(YELLOW);
delay(20);
Explod1=random(68)+516;
Explod2=random(68)+76;
line(550,110,Explod1,Explod2);
}
for(J=0;J<5;J++)
{setcolor(6);
delay(20);
Explod1=random(68)+516;
Explod2=random(68)+76;
line(550,110,Explod1,Explod2);
}
for(J=0;J<5;J++)
{setcolor(RED);
delay(20);
Explod1=random(68)+516;
Explod2=random(68)+76;
line(550,110,Explod1,Explod2);
}
}
}
void miss()
{//Show a ship not getting hit and the water exploding
setfillstyle(1,15);
bar (400,0,640,160);
bar (0,0,240,160);
//WORDS
delay(1550);
setcolor(0);
line(30,10,10,150);
line(10,150,30,150);
line(30,150,40,50);
line(40,50,50,70);
line(50,70,60,70);
line(60,70,70,50);
line(70,50,80,150);
line(80,150,100,150);
line(100,150,80,10);
line(80,10,70,10);
line(70,10,60,50);
line(60,50,50,50);
line(50,50,40,10);
line(40,10,30,10);
line(110,10,110,150);
line(110,150,120,150);
line(120,150,120,10);
line(120,10,110,10);
line(130,10,130,80);
line(130,80,160,80);
line(160,80,160,140);
line(160,140,130,140);
line(130,140,130,150);
line(130,150,170,150);
line(170,150,170,70);
line(170,70,140,70);
line(140,70,140,20);
line(140,20,170,20);
line(170,20,170,10);
line(170,10,130,10);
line(180,10,180,80);
line(180,80,210,80);
line(210,80,210,140);
line(210,140,180,140);
line(180,140,180,150);
line(180,150,220,150);
line(220,150,220,70);
line(220,70,190,70);
line(190,70,190,20);
line(190,20,220,20);
line(220,20,220,10);
line(220,10,180,10);
setfillstyle(5,2);
floodfill(35,40,0);
delay(500);
floodfill(115,40,0);
delay(500);
floodfill(135,40,0);
delay(500);
floodfill(185,40,0);
delay(500);
//Ship
setcolor(15);
bar(400,0,640,160);
setfillstyle(1,15);
rectangle(400,0,640,160);
floodfill(520,80,15);
setfillstyle(2,1);
setcolor(1);
rectangle(400,120,640,160);
floodfill(520,150,1);
setcolor(BLACK);
line(490,80,520,140);
line(520,140,640,140);
line(640,140,640,80);
line(640,80,490,80);
line(520,50,580,50);
line(580,50,580,60);
line(580,60,620,60);
line(620,60,620,80);
line(530,50,530,20);
line(530,20,540,20);
line(540,20,540,50);
line(520,50,520,80);
setfillstyle(1,8);
floodfill(540,100,0);
floodfill(540,60,0);
floodfill(535,30,0);
setfillstyle(1,2);
for(I=0;I<6;I++)
{
for(J=0;J<5;J++)
{setcolor(WHITE);
delay(20);
Splash1=random(68)+426;
Splash2=random(20)+90;
Splash3=random(5)+459;
line(Splash3,150,Splash1,Splash2);
}
for(J=0;J<5;J++)
{setcolor(1);
delay(20);
Splash1=random(68)+426;
Splash2=random(20)+90;
Splash3=random(5)+459;
line(Splash3,150,Splash1,Splash2);
}
for(J=0;J<5;J++)
{setcolor(3);
delay(20);
Splash1=random(68)+426;
Splash2=random(20)+90;
Splash3=random(5)+459;
line(Splash3,150,Splash1,Splash2);
}
}
}
void title_screen ()
{//Main screen that gives the user choices
setfillstyle (1,9);
floodfill(1,1,15);
setfillstyle (1,1);
bar (0,360,640,480);
for (Wave=1;Wave<5;Wave++)
{
for (Start1=1;Start1<300;Start1++)
{
setcolor(3);
First1=random(641)-1;
First2=random(641)-1;
First3=random(120)+360;
line(First1,First3,First2,First3);
}
for (Start1=1;Start1<200;Start1++)
{
setcolor(9);
First1=random(641)-1;
First2=random(641)-1;
First3=random(120)+360;
line(First1,First3,First2,First3);
}
for (Start1=1;Start1<200;Start1++)
{setcolor(1);
First1=random(641)-1;
First2=random(641)-1;
First3=random(120)+360;
line(First1,First3,First2,First3);
}
for (Start1=1;Start1<50;Start1++)
{setcolor(15);
First1=random(641)-1;
First2=random(641)-1;
First3=random(120)+360;
line(First1,First3,First2,First3);
}
}
setcolor(0);
arc(700,240,90,70,300);
setfillstyle(1,0);
floodfill(500,240,0);
setfillstyle(1,9);
bar(455,85,615,145);
bar(455,165,615,225);
bar(455,245,615,305);
bar(455,325,615,385);
setfillstyle(1,15);
bar(460,80,620,140);
bar(460,160,620,220);
bar(460,240,620,300);
bar(460,320,620,380);
setcolor(4);
//Menu
line(470,20,470,70);
line(470,70,480,70);
line(480,70,480,40);
line(480,40,485,50);
line(485,50,490,40);
line(490,40,490,70);
line(490,70,500,70);
line(500,70,500,20);
line(500,20,490,20);
line(490,20,485,30);
line(485,30,480,20);
line(480,20,470,20);
line(510,20,510,70);
line(510,70,540,70);
line(540,70,540,60);
line(540,60,520,60);
line(520,60,520,50);
line(520,50,530,50);
line(530,50,530,40);
line(530,40,520,40);
line(520,40,520,30);
line(520,30,540,30);
line(540,30,540,20);
line(540,20,510,20);
line(550,20,550,70);
line(550,70,560,70);
line(560,70,560,40);
line(560,40,570,70);
line(570,70,580,70);
line(580,70,580,20);
line(580,20,570,20);
line(570,20,570,54);
line(570,54,560,20);
line(560,20,550,20);
line(590,20,590,70);
line(590,70,620,70);
line(620,70,620,20);
line(620,20,610,20);
line(610,20,610,60);
line(610,60,600,60);
line(600,60,600,20);
line(600,20,590,20);
setfillstyle(9,4);
floodfill(480,30,4);
floodfill(515,30,4);
floodfill(555,30,4);
floodfill(595,30,4);
floodfill(575,30,4);
setcolor(0);
outtextxy(480,110," ntro");
outtextxy(480,190,"I structions");
outtextxy(480,270," lay");
outtextxy(480,350," uit");
setcolor(4);
outtextxy(480,110,"I");
outtextxy(486,190,"n");
outtextxy(480,270,"P");
outtextxy(480,350,"Q");
setcolor(0);
//Title Ship
line(20,260,380,260);
line(380,260,320,360);
line(320,360,80,360);
line(80,360,20,260);
line(80,260,80,200);
line(80,200,200,200);
line(200,200,200,260);
line(200,220,260,220);
line(260,220,260,260);
line(100,190,100,200);
line(100,190,160,190);
line(160,190,160,200);
setfillstyle(1,8);
floodfill(100,240,0);
floodfill(120,195,0);
floodfill(220,240,0);
floodfill(100,320,0);
circle(60,280,5);
circle(100,280,5);
circle(140,280,5);
circle(180,280,5);
circle(220,280,5);
circle(260,280,5);
circle(300,280,5);
circle(340,280,5);
setfillstyle(1,0);
floodfill(60,280,0);
floodfill(100,280,0);
floodfill(140,280,0);
floodfill(180,280,0);
floodfill(220,280,0);
floodfill(260,280,0);
floodfill(300,280,0);
floodfill(340,280,0);
line(300,285,300,310);
line(290,310,310,310);
circle(290,310,2);
circle(310,310,2);
circle(300,295,1);
outtextxy(245,265,"U.S.S. Lexington");
ellipse(40,260,0,180,15,18);
line(38,243,20,230);
line(34,244,18,237);
line(85,205,85,235);
line(85,235,120,235);
line(120,235,120,205);
line(120,205,85,205);
line(125,205,125,225);
line(125,225,160,225);
line(160,225,160,205);
line(160,205,125,205);
line(165,205,165,225);
line(165,225,195,225);
line(195,225,195,205);
line(195,205,165,205);
setfillstyle(1,9);
floodfill(100,220,0);
floodfill(140,220,0);
floodfill(180,220,0);
setfillstyle(1,8);
floodfill(30,250,0);
//WWII Words
//"W"
setcolor(15);
line(16,20,16,28);
line(16,28,20,28);
line(20,28,44,100);
line(44,100,64,100);
line(64,100,78,68);
line(78,68,92,100);
line(92,100,112,100);
line(112,100,136,28);
line(136,28,140,28);
line(140,28,140,20);
line(140,20,104,20);
line(104,20,104,28);
line(104,28,108,28);
line(108,28,100,76);
line(100,76,84,60);
line(84,60,86,60);
line(86,60,86,52);
line(86,52,70,52);
line(70,52,70,60);
line(70,60,72,60);
line(72,60,56,76);
line(56,76,48,28);
line(48,28,52,28);
line(52,28,52,20);
line(52,20,16,20);
line(148,20,148,28);
line(148,28,152,28);
line(152,28,176,100);
line(176,100,196,100);
line(196,100,210,68);
line(210,68,224,100);
line(224,100,244,100);
line(244,100,268,28);
line(268,28,272,28);
line(272,28,272,20);
line(272,20,236,20);
line(236,20,236,28);
line(236,28,240,28);
line(240,28,232,76);
line(232,76,216,60);
line(216,60,218,60);
line(218,60,218,52);
line(218,52,202,52);
line(202,52,202,60);
line(202,60,204,60);
line(204,60,188,76);
line(188,76,180,28);
line(180,28,184,28);
line(184,28,184,20);
line(184,20,148,20);
//"I"
line(280,20,280,28);
line(280,28,284,28);
line(284,28,284,92);
line(284,92,280,92);
line(280,92,280,100);
line(280,100,312,100);
line(312,100,312,92);
line(312,92,308,92);
line(308,92,308,28);
line(308,28,312,28);
line(312,28,312,20);
line(312,20,280,20);
line(320,20,320,28);
line(320,28,324,28);
line(324,28,324,92);
line(324,92,320,92);
line(320,92,320,100);
line(320,100,352,100);
line(352,100,352,92);
line(352,92,348,92);
line(348,92,348,28);
line(348,28,352,28);
line(352,28,352,20);
line(352,20,320,20);
setfillstyle(1,1);
delay(1000);
floodfill(40,40,15);
delay(1000);
floodfill(160,24,15);
delay(1000);
floodfill(300,28,15);
delay(1000);
floodfill(340,28,15);
delay(1500);
setcolor(0);
outtextxy(69,131,"A");
setcolor(15);
outtextxy(70,130,"A");
delay(500);
setcolor(0);
outtextxy(119,131,"R");
setcolor(15);
outtextxy(120,130,"R");
setcolor(0);
delay(500);
outtextxy(169,131,"M");
setcolor(15);
outtextxy(170,130,"M");
delay(500);
setcolor(0);
outtextxy(219,131,"A");
setcolor(15);
outtextxy(220,130,"A");
delay(500);
setcolor(0);
outtextxy(269,131,"D");
setcolor(15);
outtextxy(270,130,"D");
delay(500);
setcolor(0);
outtextxy(319,131,"A");
setcolor(15);
outtextxy(320,130,"A");
setcolor(15);
outtextxy(490,420,"Select the");
outtextxy(490,430,"letter to choose");
outtextxy(490,440,"an option");
setcolor(4);
outtextxy(580,420,"red");
}
void sink ()
{//Shows a ship sinking
setfillstyle(1,15);
bar (400,0,640,160);
bar (0,0,240,160);
//WORDS
setcolor (0);
line (10,10,10,80);
line (10,80,60,80);
line (60,80,60,140);
line (60,140,10,140);
line (10,140,10,150);
line (10,150,70,150);
line (70,150,70,70);
line (70,70,20,70);
line (20,70,20,20);
line (20,20,70,20);
line (70,20,70,10);
line (70,10,10,10);
line (80,10,80,150);
line (80,150,90,150);
line (90,150,90,10);
line (90,10,80,10);
line (100,10,100,150);
line (100,150,110,150);
line (110,150,110,60);
line (110,60,150,150);
line (150,150,160,150);
line (160,150,160,10);
line (160,10,150,10);
line (150,10,150,130);
line (150,130,110,10);
line (110,10,100,10);
line (170,10,170,150);
line (170,150,180,150);
line (180,150,180,80);
line (180,80,220,150);
line (220,150,230,150);
line (230,150,230,140);
line (230,140,190,70);
line (190,70,230,10);
line (230,10,220,10);
line (220,10,180,70);
line (180,70,180,10);
line (180,10,170,10);
setfillstyle (3,1);
delay(500);
floodfill(15,15,0);
delay(500);
floodfill(85,15,0);
delay(500);
floodfill(105,15,0);
delay(500);
floodfill(175,15,0);
delay(500);
//SHIP
setcolor(1);
setfillstyle (2,1);
rectangle (400,120,640,160);
floodfill (410,130,1);
setcolor (0);
line(540,10,454,60);
line(454,60,454,119);
line(454,119,540,119);
line(540,119,540,10);
line(540,40,570,40);
line(570,40,570,100);
line(570,100,560,100);
line(560,100,560,120);
line(560,120,540,120);
line(570,50,600,50);
line(600,50,600,60);
line(600,60,570,60);
setfillstyle(1,8);
floodfill(490,50,0);
floodfill(550,50,0);
floodfill(580,55,0);
delay(500);
setfillstyle(1,15);
bar(400,0,640,160);
setfillstyle(2,1);
bar (400,120,640,160);
setcolor(0);
line(454,120,454,90);
line(454,90,540,40);
line(540,40,540,120);
line(540,70,570,70);
line(570,70,570,120);
line(570,120,454,120);
line(570,80,600,80);
line(600,80,600,90);
line(600,90,570,90);
setfillstyle (1,8);
floodfill(490,90,0);
floodfill(550,90,0);
floodfill(580,85,0);
delay (500);
setfillstyle(1,15);
bar(400,0,640,160);
setfillstyle(2,1);
bar (400,120,640,160);
setcolor(0);
line(454,120,540,70);
line(540,70,540,100);
line(540,70,540,120);
line(540,100,570,100);
line(570,100,570,120);
line(578,120,454,120);
setfillstyle (1,8);
floodfill (510,100,0);
floodfill (550,110,0);
delay(500);
setfillstyle(1,15);
bar(400,0,640,160);
setfillstyle(2,1);
bar (400,120,640,160);
setcolor(0);
line(500,120,540,100);
line(540,100,540,120);
line(540,120,500,120);
setfillstyle(1,8);
floodfill(530,110,0);
delay (500);
setfillstyle(1,15);
bar(400,0,640,160);
setfillstyle(2,1);
bar (400,120,640,160);
}
int setup ()
{//Calls the title screen and takes in data as well as calls for the user and computer to setup
int Choice2;
do
{
title_screen();
switch(getch())
{
case 73 :
case 105 : intro();
break;
case 78 :
case 110 : helpinstr();
break;
case 80 : //Start
case 112 : Choice2=1;
break;
case 81 : //End
case 113 : Choice2=2;
break;
}
}
while(Choice2!=1 && Choice2!=2);
if (Choice2==1)
{
In.open("a:\\Compgri.dat");
for (AI=0; AI<10; AI++)
for (AI2=0; AI2<10; AI2++)
In>>Computer[AI][AI2].X;
for (AI2=0; AI2<10; AI2++)
for (AI=0; AI<10; AI++)
In>>Computer[AI2][AI].Y;
In.close();
In.open("a:\\Usergrid.dat");
for (AI=0; AI<10; AI++)
for (AI2=0; AI2<10; AI2++)
In>>User[AI][AI2].X;
for (AI2=0; AI2<10; AI2++)
for (AI=0; AI<10; AI++)
In>>User[AI2][AI].Y;
In.close();
Compships[0]=1;
Compships[1]=2;
Compships[2]=2;
Compships[3]=3;
Compships[4]=4;
// Set to false
for (AI=0; AI<10; AI++)
for (AI2=0; AI2<10; AI2++)
{Computer[AI2][AI].Ships=false;
User[AI2][AI].Ships=false;
Computer[AI2][AI].Fire=false;
User[AI2][AI].Fire=false;}
usersetup();
compsetup();
}
return Choice2;
}
void grsetup (int& Grdriver, int& Grmode, int& Errorcode)
{//Initializes graphics mode
Grdriver=VGA;
Grmode=VGAHI;
initgraph(&Grdriver, &Grmode, "C:\\TC\\BGI");
Errorcode=graphresult();
if (Errorcode!=grOk)
{clrscr();
cout<<"Error!";
getch();
exit(1);
}
}
void intro ()
{//Gives the background behind the game and the objectives of the game
cleardevice();
setcolor(15);
moveto(0,20);
outtext("In this classic naval game, set during World War II, you must sink the Japanese");
moveto(0,30);
outtext("before they sink you.");
delay(6000);
moveto(0,80);
outtext("Intelligence reports sightings of Japanese ships in nearby waters.");
delay(2000);
moveto(0,90);
outtext("The reports state sightings of the following.");
delay(2000);
moveto(0,110);
outtext("1 submarine, 1 frigate, 1 gunboat, 1 battleship, and 1 aircraft carrier.");
delay(2000);
moveto(0,150);
outtext("Unfortunately, the enemy has also detected you.");
delay(2000);
moveto(0,160);
outtext("You are now in a race against the clock to nail lurking Japanese navy vessels.");
delay(4000);
moveto(0,200);
outtext("Prepare for battle!!!");
delay(2000);
moveto(0,400);
outtext("Press any key to continue...");
getch();
cleardevice();
}
void helpinstr()
{//Gives instructions for playing the game
cleardevice();
setcolor(15);
outtextxy(0,20,"1. You will be asked to place your ships on your board.");
outtextxy(0,30,"2. Enter a CAPITAL letter for your Y coordinate of each ship.");
outtextxy(0,40,"3. Enter a number for your X coordinate of each ship.");
outtextxy(0,50,"4. The computer will then setup its ships.");
outtextxy(0,60,"5. Once the computer is done setting up, your board will displayed with your");
outtextxy(25,70,"ships in green.");
outtextxy(0,80,"6. You will then be asked to enter a CAPITAL letter and number to fire at");
outtextxy(25,90,"the enemy side.");
outtextxy(0,100,"7. A hit or miss animation will be displayed indicating the status of your");
outtextxy(25,110,"launch.");
outtextxy(0,120,"8. Should you sink a ship, you will see a ship sinking.");
outtextxy(0,130,"9. Then the computer will choose a location to fire upon you.");
outtextxy(0,140,"10. Should the shot hit one of your ships, the location will turn red.");
outtextxy(0,150,"11. You will continue to take turns until either you or the computer");
outtextxy(35,160,"sinks all the other's ships.");
outtextxy(0,200,"Press any key to continue...");
getch();
cleardevice();
}
bool user (bool& Csink1, bool& Csink2, bool& Csink3, bool& Csink4, bool& Csink5)
{//lets the user fire on the computer
windowfill();
do
{
do
{//moveto(0,400);
setcolor(15);
outtextxy(40,440,"Enter a CAPITAL letter coordinate to fire upon");
Letnum=getch()-65;
}while((Letnum<0) || (Letnum>9));
setcolor(0);
setfillstyle(1,0);
bar(40,420,620,460);
do
{setcolor(15);
outtextxy(40,440,"Enter the number coordinate to fire upon, use 0 for ten.");
Xcoor2=getch();
}while((Xcoor2<48)||(Xcoor2>57));
if (Xcoor2==48)
Xcoor=9;
else
Xcoor=Xcoor2-49;
setcolor(0);
setfillstyle(1,0);
bar(40,420,620,460);
}
while(Computer[Xcoor][Letnum].Fire);
setcolor(15);
if (!Computer[Xcoor][Letnum].Ships)
{
Computer[Xcoor][Letnum].Fire=true;
setfillstyle(1,15);
fillellipse(Computer[Xcoor][Letnum].X, Computer[Xcoor][Letnum].Y, 5,5);
miss();
Ugamego=false;
}
else
{
Computer[Xcoor][Letnum].Fire=true;
setfillstyle(1,RED);
fillellipse(Computer[Xcoor][Letnum].X, Computer[Xcoor][Letnum].Y, 5,5);
hit();
for(UI=0; UI<2; UI++)
if (Compships1[UI].X==Xcoor && Compships1[UI].Y==Letnum)
Compships1[UI].Ships=true;
for(UI=0; UI<3; UI++)
if (Compships2[UI].X==Xcoor && Compships2[UI].Y==Letnum)
Compships2[UI].Ships=true;
for(UI=0; UI<3; UI++)
if (Compships3[UI].X==Xcoor && Compships3[UI].Y==Letnum)
Compships3[UI].Ships=true;
for(UI=0; UI<4; UI++)
if (Compships4[UI].X==Xcoor && Compships4[UI].Y==Letnum)
Compships4[UI].Ships=true;
for(UI=0; UI<5; UI++)
if (Compships5[UI].X==Xcoor && Compships5[UI].Y==Letnum)
Compships5[UI].Ships=true;
if (Compships1[0].Ships && Compships1[1].Ships && !Csink1)
{
sink();
Csink1=true;
}
else if (Compships2[0].Ships && Compships2[1].Ships && Compships2[2].Ships && !Csink2)
{
sink();
Csink2=true;
}
else if (Compships3[0].Ships && Compships3[1].Ships && Compships3[2].Ships && !Csink3)
{
sink();
Csink3=true;
}
else if (Compships4[0].Ships && Compships4[1].Ships && Compships4[2].Ships && Compships4[3].Ships && !Csink4)
{
sink();
Csink4=true;
}
else if (Compships5[0].Ships && Compships5[1].Ships && Compships5[2].Ships && Compships5[3].Ships && Compships5[4].Ships && !Csink5)
{
sink();
Csink5=true;
}
else
{}
if (Csink1 && Csink2 && Csink3 && Csink4 && Csink5)
Ugamego=true;
else
Ugamego=false;
}
return Ugamego;
}
bool computer ( int& AIX, int& AIY, bool& Usink1, bool& Usink2, bool& Usink3, bool& Usink4, bool& Usink5, apstring& Status)
{//Lets the computer fire on the user
windowfill();
setcolor(15);
setfillstyle(1,0);
outtextxy(40,440,"The computer is now firing.");
delay(800);
bar(40,420,620,460);
if (Status==" ")
{
Xcoor=random(10);
Ycoor=random(10);
if (!User[Xcoor][Ycoor].Ships)
{
User[Xcoor][Ycoor].Fire=true;
setfillstyle(1,15);
fillellipse(User[Xcoor][Ycoor].X, User[Xcoor][Ycoor].Y, 5,5);
miss();
Status="M";
Cgamego=false;
}
else
{
User[Xcoor][Ycoor].Fire=true;
setfillstyle(1,RED);
fillellipse(User[Xcoor][Ycoor].X, User[Xcoor][Ycoor].Y, 5,5);
hit();
AIX=Xcoor;
AIY=Ycoor;
for(AI=0; AI<2; AI++)
if (Userships1[AI].X==Xcoor && Userships1[AI].Y==Ycoor)
Userships1[AI].Ships=true;
for(AI=0; AI<3; AI++)
if (Userships2[AI].X==Xcoor && Userships2[AI].Y==Ycoor)
Userships2[AI].Ships=true;
for(AI=0; AI<3; AI++)
if (Userships3[AI].X==Xcoor && Userships3[AI].Y==Ycoor)
Userships3[AI].Ships=true;
for(AI=0; AI<4; AI++)
if (Userships4[AI].X==Xcoor && Userships4[AI].Y==Ycoor)
Userships4[AI].Ships=true;
for(AI=0; AI<5; AI++)
if (Userships5[AI].X==Xcoor && Userships5[AI].Y==Ycoor)
Userships5[AI].Ships=true;
Status="H";
Cgamego=false;
}
}
//Miss
else if (Status=="M")
{
do
{
Xcoor=random(10);
Ycoor=random(10);
}
while(User[Xcoor][Ycoor].Fire==true);
if (!User[Xcoor][Ycoor].Ships)
{
User[Xcoor][Ycoor].Fire=true;
setfillstyle(1,16);
fillellipse(User[Xcoor][Ycoor].X, User[Xcoor][Ycoor].Y, 5,5);
miss();
Status="M";
Cgamego=false;
}
else
{
User[Xcoor][Ycoor].Fire=true;
setfillstyle(1,RED);
fillellipse(User[Xcoor][Ycoor].X, User[Xcoor][Ycoor].Y, 5,5);
hit();
AIX=Xcoor;
AIY=Ycoor;
for(AI=0; AI<2; AI++)
if (Userships1[AI].X==Xcoor && Userships1[AI].Y==Ycoor)
Userships1[AI].Ships=true;
for(AI=0; AI<3; AI++)
if (Userships2[AI].X==Xcoor && Userships2[AI].Y==Ycoor)
Userships2[AI].Ships=true;
for(AI=0; AI<3; AI++)
if (Userships3[AI].X==Xcoor && Userships3[AI].Y==Ycoor)
Userships3[AI].Ships=true;
for(AI=0; AI<4; AI++)
if (Userships4[AI].X==Xcoor && Userships4[AI].Y==Ycoor)
Userships4[AI].Ships=true;
for(AI=0; AI<5; AI++)
if (Userships5[AI].X==Xcoor && Userships5[AI].Y==Ycoor)
Userships5[AI].Ships=true;
if (Userships1[0].Ships && Userships1[1].Ships && !Usink1)
{
sink();
Usink1=true;
Status="M";
}
else if (Userships2[0].Ships && Userships2[1].Ships && Userships2[2].Ships && !Usink2)
{
sink();
Usink2=true;
Status="M";
}
else if (Userships3[0].Ships && Userships3[1].Ships && Userships3[2].Ships && !Usink3)
{
sink();
Usink3=true;
Status="M";
}
else if (Userships4[0].Ships && Userships4[1].Ships && Userships4[2].Ships && Userships4[3].Ships && !Usink4)
{
sink();
Usink4=true;
Status="M";
}
else if (Userships5[0].Ships && Userships5[1].Ships && Userships5[2].Ships && Userships5[3].Ships && Userships5[4].Ships && !Usink5)
{
sink();
Usink5=true;
Status="M";
}
else
{}
if (Usink1 && Usink2 && Usink3 && Usink4 && Usink5)
Cgamego=true;
else
Cgamego=false;
Status="H";
}
}
//Hit
else // (Status=="H")
{
Count2=1;
do
{
Ycoor=AIY;
Xcoor=AIX;
D=random(4);
switch(D)
{
case 0 : Xcoor=AIX+1;
break;
case 1 : Xcoor=AIX-1;
break;
case 2 : Ycoor=AIY+1;
break;
case 3 : Ycoor=AIY-1;
break;
}
Count2=Count2+1;
}
while(Xcoor>9 || Xcoor<0 || Ycoor>9 || Ycoor<0 || User[Xcoor][Ycoor].Fire==true || Count2<400);
if (Count2==400)
{
Status="M";
computer(AIX, AIY, Usink1, Usink2, Usink3, Usink4, Usink5, Status);
}
else
{
if (User[Xcoor][Ycoor].Ships)
{
User[Xcoor][Ycoor].Fire=true;
setfillstyle(1,RED);
fillellipse(User[Xcoor][Ycoor].X, User[Xcoor][Ycoor].Y, 5,5);
hit();
AIX=Xcoor;
AIY=Ycoor;
for(AI=0; AI<2; AI++)
if (Userships1[AI].X==Xcoor && Userships1[AI].Y==Ycoor)
Userships1[AI].Ships=true;
for(AI=0; AI<3; AI++)
if (Userships2[AI].X==Xcoor && Userships2[AI].Y==Ycoor)
Userships2[AI].Ships=true;
for(AI=0; AI<3; AI++)
if (Userships3[AI].X==Xcoor && Userships3[AI].Y==Ycoor)
Userships3[AI].Ships=true;
for(AI=0; AI<4; AI++)
if (Userships4[AI].X==Xcoor && Userships4[AI].Y==Ycoor)
Userships4[AI].Ships=true;
for(AI=0; AI<5; AI++)
if (Userships5[AI].X==Xcoor && Userships5[AI].Y==Ycoor)
Userships5[AI].Ships=true;
if (Userships1[0].Ships && Userships1[1].Ships && !Usink1)
{
sink();
Usink1=true;
Status="M";
}
else if (Userships2[0].Ships && Userships2[1].Ships && Userships2[2].Ships && !Usink2)
{
sink();
Usink2=true;
Status="M";
}
else if (Userships3[0].Ships && Userships3[1].Ships && Userships3[2].Ships && !Usink3)
{
sink();
Usink3=true;
Status="M";
}
else if (Userships4[0].Ships && Userships4[1].Ships && Userships4[2].Ships && Userships4[3].Ships && !Usink4)
{
sink();
Usink4=true;
Status="M";
}
else if (Userships5[0].Ships && Userships5[1].Ships && Userships5[2].Ships && Userships5[3].Ships && Userships5[4].Ships && !Usink5)
{
sink();
Usink5=true;
Status="M";
}
else
{}
if (Usink1 && Usink2 && Usink3 && Usink4 && Usink5)
Cgamego=true;
else
Cgamego=false;
Status="H";
}
else
{
User[Xcoor][Ycoor].Fire=true;
setfillstyle(1,16);
fillellipse(User[Xcoor][Ycoor].X, User[Xcoor][Ycoor].Y, 5,5);
miss();
Status="HM";
Cgamego=false;
}
}
}
return Cgamego;
}
void credits()
{//Indicates the the game is over
cleardevice();
outtextxy(320,240,"The game is over");
delay(2000);
}
void usersetup ()
{//Sets up the user's ships
cleardevice();
Nameships[0]=" Submarine";
Nameships[1]=" Frigate";
Nameships[2]=" Gun Boat";
Nameships[3]=" Battleship";
Nameships[4]=" Aircraft Carrier";
cout<<"You have 5 ships to place on the board."<<endl;
for(UI=0; UI<5; UI++)
{
cleardevice();
gotoxy(1,1);
do
{Redo=false;
do
{
do
{moveto(0,400);
cout<<"Enter a CAPITAL letter coordinate for the"<<Nameships[UI]<<": "<<endl;
Letnum=getch()-65;
}while((Letnum<0) || (Letnum>9));
do
{cout<<"Enter the number coordinate for the"<<Nameships[UI]<<", (use 0 for 10): "<<endl;
Xcoor2=getch();
}while((Xcoor2<48)||(Xcoor2>57));
if (Xcoor2==48)
Xcoor=9;
else
Xcoor=Xcoor2-49;
cout<<"Your 1st coordinates are("<<Xcoor+1<<", "<<char(Letnum+65)<<")"<<endl;
do
{cout<<"Would you like to move:"<<endl<<endl<<"1=Right"<<endl<<"2=Left"<<endl;
cout<<"3=Down"<<endl<<"4=Up"<<endl<<endl;
D=getch();
}while ((D<49)||(D>52));
D=D-48;
switch (D)
{case 1:X2=Xcoor+Compships[UI]; //right
break;
case 2:X2=Xcoor-Compships[UI]; //left
break;
case 3:Y2=Letnum+Compships[UI]; //down
break;
case 4:Y2=Letnum-Compships[UI]; //up
break;
}
}while(X2<0 || Y2<0 || X2>9 || Y2>9);
switch (D)
{case 1: for (UI2=0; UI2<=Compships[UI]; UI2++)
if(User[Xcoor+UI2][Letnum].Ships)
Redo=true;
break;
case 2: for(UI2=Xcoor; UI2>=X2; UI2--)
if(User[UI2][Letnum].Ships)
Redo=true;
break;
case 3: for(UI2=0; UI2<=Compships[UI]; UI2++)
if(User[Xcoor][Letnum + UI2].Ships)
Redo=true;
break;
case 4: for(UI2=Ycoor; UI2>=Y2; UI2--)
if(User[Xcoor][UI2].Ships)
Redo=true;
}
}while(Redo==true);
if ((D==1) || (D==2))
cout<<"Your ship ends at: ("<<X2+1<<", "<<char(Letnum+65)<<")"<<endl;
else
cout<<"Your ship ends at: ("<<Xcoor+1<<", "<<char(Y2+65)<<")"<<endl;
delay(1000);
switch(D)
{case 1: for(UI2=0; UI2<=Compships[UI]; UI2++)
{
User[Xcoor+UI2][Letnum].Ships=true;
switch (UI)
{
case 0 : Userships1[UI2].X=Xcoor+UI2;
Userships1[UI2].Y=Letnum;
Userships1[UI2].Ships=false;
break;
case 1 : Userships2[UI2].X=Xcoor+UI2;
Userships2[UI2].Y=Letnum;
Userships2[UI2].Ships=false;
break;
case 2 : Userships3[UI2].X=Xcoor+UI2;
Userships3[UI2].Y=Letnum;
Userships3[UI2].Ships=false;
break;
case 3 : Userships4[UI2].X=Xcoor+UI2;
Userships4[UI2].Y=Letnum;
Userships4[UI2].Ships=false;
break;
case 4 : Userships5[UI2].X=Xcoor+UI2;
Userships5[UI2].Y=Letnum;
Userships5[UI2].Ships=false;
break;
}
}
break;
case 2: for(UI2=Xcoor; UI2>=X2; UI2--)
{
User[UI2][Letnum].Ships=true;
switch (UI)
{
case 0 : Userships1[Xcoor-UI2].X=UI2;
Userships1[Xcoor-UI2].Y=Letnum;
Userships1[Xcoor-UI2].Ships=false;
break;
case 1 : Userships2[Xcoor-UI2].X=UI2;
Userships2[Xcoor-UI2].Y=Letnum;
Userships2[Xcoor-UI2].Ships=false;
break;
case 2 : Userships3[Xcoor-UI2].X=UI2;
Userships3[Xcoor-UI2].Y=Letnum;
Userships3[Xcoor-UI2].Ships=false;
break;
case 3 : Userships4[Xcoor-UI2].X=UI2;
Userships4[Xcoor-UI2].Y=Letnum;
Userships4[Xcoor-UI2].Ships=false;
break;
case 4 : Userships5[Xcoor-UI2].X=UI2;
Userships5[Xcoor-UI2].Y=Letnum;
Userships5[Xcoor-UI2].Ships=false;
break;
}
}
break;
case 3: for(UI2=0; UI2<=Compships[UI]; UI2++)
{
User[Xcoor][Letnum+UI2].Ships=true;
switch (UI)
{
case 0 : Userships1[UI2].X=Xcoor;
Userships1[UI2].Y=Letnum+UI2;
Userships1[UI2].Ships=false;
break;
case 1 : Userships2[UI2].X=Xcoor;
Userships2[UI2].Y=Letnum+UI2;
Userships2[UI2].Ships=false;
break;
case 2 : Userships3[UI2].X=Xcoor;
Userships3[UI2].Y=Letnum+UI2;
Userships3[UI2].Ships=false;
break;
case 3 : Userships4[UI2].X=Xcoor;
Userships4[UI2].Y=Letnum+UI2;
Userships4[UI2].Ships=false;
break;
case 4 : Userships5[UI2].X=Xcoor;
Userships5[UI2].Y=Letnum+UI2;
Userships5[UI2].Ships=false;
break;
}
}
break;
case 4: for(UI2=Letnum; UI2>=Y2; UI2--)
{
User[Xcoor][UI2].Ships=true;
switch (UI)
{
case 0 : Userships1[Letnum-UI2].X=Xcoor;
Userships1[Letnum-UI2].Y=UI2;
Userships1[Letnum-UI2].Ships=false;
break;
case 1 : Userships2[Letnum-UI2].X=Xcoor;
Userships2[Letnum-UI2].Y=UI2;
Userships2[Letnum-UI2].Ships=false;
break;
case 2 : Userships3[Letnum-UI2].X=Xcoor;
Userships3[Letnum-UI2].Y=UI2;
Userships3[Letnum-UI2].Ships=false;
break;
case 3 : Userships4[Letnum-UI2].X=Xcoor;
Userships4[Letnum-UI2].Y=UI2;
Userships4[Letnum-UI2].Ships=false;
break;
case 4 : Userships5[Letnum-UI2].X=Xcoor;
Userships5[Letnum-UI2].Y=UI2;
Userships5[Letnum-UI2].Ships=false;
break;
}
}
break;
}
}
cleardevice();
setfillstyle(1,4);
}
void grid ()
{//Sets up the grids for the user and computer
cleardevice();
setcolor(8);
setfillstyle(1,8);
//w
line(243,0,253,0);
line(253,0,263,50);
line(263,50,268,30);
line(268,30,278,30);
line(278,30,283,50);
line(283,50,293,0);
line(293,0,303,0);
line(303,0,293,70);
line(293,70,283,70);
line(283,70,273,45);
line(273,45,263,70);
line(263,70,253,70);
line(253,70,243,0);
//w
line(303,0,313,0);
line(313,0,323,50);
line(323,50,328,30);
line(328,30,338,30);
line(338,30,343,50);
line(343,50,353,0);
line(353,0,363,0);
line(363,0,353,70);
line(353,70,343,70);
line(343,70,333,45);
line(333,45,323,70);
line(323,70,313,70);
line(313,70,303,0);
//I
line(364,0,379,0);
line(379,0,379,70);
line(379,70,364,70);
line(364,70,364,0);
//I
line(381,0,396,0);
line(396,0,396,70);
line(396,70,381,70);
line(381,70,381,0);
floodfill(248,3,8);
floodfill(305,3,8);
floodfill(383,3,8);
floodfill(368,3,8);
setcolor(RED);
moveto(255,80);
outtext("A R M A D A");
//GRID
setcolor (9);
moveto(110,170);
outtext("Japan");
line (20,180,240,180);
line (20,200,240,200);
line (20,220,240,220);
line (20,240,240,240);
line (20,260,240,260);
line (20,280,240,280);
line (20,300,240,300);
line (20,320,240,320);
line (20,340,240,340);
line (20,360,240,360);
line (20,380,240,380);
line (20,400,240,400);
line (20,180,20,400);
line (40,180,40,400);
line (60,180,60,400);
line (80,180,80,400);
line (100,180,100,400);
line (120,180,120,400);
line (140,180,140,400);
line (160,180,160,400);
line (180,180,180,400);
line (200,180,200,400);
line (220,180,220,400);
line (240,180,240,400);
//GRID 2
moveto(500,170);
outtext("USA");
line (400,180,620,180);
line (400,200,620,200);
line (400,220,620,220);
line (400,240,620,240);
line (400,260,620,260);
line (400,280,620,280);
line (400,300,620,300);
line (400,320,620,320);
line (400,340,620,340);
line (400,360,620,360);
line (400,380,620,380);
line (400,400,620,400);
line (400,180,400,400);
line (420,180,420,400);
line (440,180,440,400);
line (460,180,460,400);
line (480,180,480,400);
line (500,180,500,400);
line (520,180,520,400);
line (540,180,540,400);
line (560,180,560,400);
line (580,180,580,400);
line (600,180,600,400);
line (620,180,620,400);
setcolor (14);
outtextxy (428,187,"1");
outtextxy (448,187,"2");
outtextxy (468,187,"3");
outtextxy (488,187,"4");
outtextxy (508,187,"5");
outtextxy (528,187,"6");
outtextxy (548,187,"7");
outtextxy (568,187,"8");
outtextxy (588,187,"9");
outtextxy (603,187,"10");
outtextxy (48,187,"1");
outtextxy (68,187,"2");
outtextxy (88,187,"3");
outtextxy (108,187,"4");
outtextxy (128,187,"5");
outtextxy (148,187,"6");
outtextxy (168,187,"7");
outtextxy (188,187,"8");
outtextxy (208,187,"9");
outtextxy (223,187,"10");
outtextxy (28,210,"A");
outtextxy (28,230,"B");
outtextxy (28,250,"C");
outtextxy (28,270,"D");
outtextxy (28,290,"E");
outtextxy (28,310,"F");
outtextxy (28,330,"G");
outtextxy (28,350,"H");
outtextxy (28,370,"I");
outtextxy (28,390,"J");
outtextxy (408,210,"A");
outtextxy (408,230,"B");
outtextxy (408,250,"C");
outtextxy (408,270,"D");
outtextxy (408,290,"E");
outtextxy (408,310,"F");
outtextxy (408,330,"G");
outtextxy (408,350,"H");
outtextxy (408,370,"I");
outtextxy (408,390,"J");
outtextxy (278,100,"Created by:");
outtextxy (273,110,"Kathy Harrod");
outtextxy (267,120,"Rebecca Grigsby");
outtextxy (257,130,"& Rebecca Russell");
setcolor(8);
}
void compsetup ()
{//sets up the computers ships
setfillstyle(0,0);
setcolor(15);
moveto(40,440);
outtext("The Computer is now setting up.");
for (AI=0; AI<5; AI++)
{do
{Redo=false;
do
{
do
{
Xcoor=random(10);
Ycoor=random(10);
}
while (Computer[Xcoor][Ycoor].Ships==true);
D=random(4);
switch(D)
{
case 0 : X2=Xcoor+Compships[AI];
break;
case 1 : X2=Xcoor-Compships[AI];
break;
case 2 : Y2=Ycoor+Compships[AI];
break;
case 3 : Y2=Ycoor-Compships[AI];
break;
};
}
while(X2<0 || Y2<0 || X2>9 || Y2>9);
switch (D)
{
case 0 : for (AI2=0; AI2<=Compships[AI]; AI2++)
if (Computer[Xcoor+AI2][Ycoor].Ships)
Redo=true;
break;
case 1 : for (AI2=X2; AI2<=Xcoor; AI2++)
if (Computer[AI2][Ycoor].Ships)
Redo=true;
break;
case 2 : for (AI2=0; AI2<=Compships[AI]; AI2++)
if (Computer[Xcoor][Ycoor+AI2].Ships)
Redo=true;
break;
case 3 : for (AI2=Y2; AI2<=Ycoor; AI2++)
if(Computer[Xcoor][AI2].Ships)
Redo=true;
break;
}
}
while(Redo==true);
switch(D)
{
case 0 : for (AI2=0; AI2<=Compships[AI]; AI2++)
{
Computer[Xcoor+AI2][Ycoor].Ships=true;
switch (AI)
{
case 0 : Compships1[AI2].X=Xcoor+AI2;
Compships1[AI2].Y=Ycoor;
Compships1[AI2].Ships=false;
break;
case 1 : Compships2[AI2].X=Xcoor+AI2;
Compships2[AI2].Y=Ycoor;
Compships2[AI2].Ships=false;
break;
case 2 : Compships3[AI2].X=Xcoor+AI2;
Compships3[AI2].Y=Ycoor;
Compships3[AI2].Ships=false;
break;
case 3 : Compships4[AI2].X=Xcoor+AI2;
Compships4[AI2].Y=Ycoor;
Compships4[AI2].Ships=false;
break;
case 4 : Compships5[AI2].X=Xcoor+AI2;
Compships5[AI2].Y=Ycoor;
Compships5[AI2].Ships=false;
break;
}
}
break;
case 1 : for (AI2=Xcoor; AI2>=X2; AI2--)
{
Computer[AI2][Ycoor].Ships=true;
switch (AI)
{
case 0 : Compships1[Xcoor-AI2].X=AI2;
Compships1[Xcoor-AI2].Y=Ycoor;
Compships1[Xcoor-AI2].Ships=false;
break;
case 1 : Compships2[Xcoor-AI2].X=AI2;
Compships2[Xcoor-AI2].Y=Ycoor;
Compships2[Xcoor-AI2].Ships=false;
break;
case 2 : Compships3[Xcoor-AI2].X=AI2;
Compships3[Xcoor-AI2].Y=Ycoor;
Compships3[Xcoor-AI2].Ships=false;
break;
case 3 : Compships4[Xcoor-AI2].X=AI2;
Compships4[Xcoor-AI2].Y=Ycoor;
Compships4[Xcoor-AI2].Ships=false;
break;
case 4 : Compships5[Xcoor-AI2].X=AI2;
Compships5[Xcoor-AI2].Y=Ycoor;
Compships5[Xcoor-AI2].Ships=false;
break;
}
}
break;
case 2 : for (AI2=0; AI2<=Compships[AI]; AI2++)
{
Computer[Xcoor][Ycoor+AI2].Ships=true;
switch (AI)
{
case 0 : Compships1[AI2].X=Xcoor;
Compships1[AI2].Y=Ycoor+AI2;
Compships1[AI2].Ships=false;
break;
case 1 : Compships2[AI2].X=Xcoor;
Compships2[AI2].Y=Ycoor+AI2;
Compships2[AI2].Ships=false;
break;
case 2 : Compships3[AI2].X=Xcoor;
Compships3[AI2].Y=Ycoor+AI2;
Compships3[AI2].Ships=false;
break;
case 3 : Compships4[AI2].X=Xcoor;
Compships4[AI2].Y=Ycoor+AI2;
Compships4[AI2].Ships=false;
break;
case 4 : Compships5[AI2].X=Xcoor;
Compships5[AI2].Y=Ycoor+AI2;
Compships5[AI2].Ships=false;
break;
}
}
break;
case 3 : for (AI2=Ycoor; AI2>=Y2; AI2--)
{
Computer[Xcoor][AI2].Ships=true;
switch (AI)
{
case 0 : Compships1[Ycoor-AI2].X=Xcoor;
Compships1[Ycoor-AI2].Y=AI2;
Compships1[Ycoor-AI2].Ships=false;
break;
case 1 : Compships2[Ycoor-AI2].X=Xcoor;
Compships2[Ycoor-AI2].Y=AI2;
Compships2[Ycoor-AI2].Ships=false;
break;
case 2 : Compships3[Ycoor-AI2].X=Xcoor;
Compships3[Ycoor-AI2].Y=AI2;
Compships3[Ycoor-AI2].Ships=false;
break;
case 3 : Compships4[Ycoor-AI2].X=Xcoor;
Compships4[Ycoor-AI2].Y=AI2;
Compships4[Ycoor-AI2].Ships=false;
break;
case 4 : Compships5[Ycoor-AI2].X=Xcoor;
Compships5[Ycoor-AI2].Y=AI2;
Compships5[Ycoor-AI2].Ships=false;
break;
}
}
break;
}
}
delay(10000);
bar(40,420,620,460);
moveto(40,440);
outtext("The Computer is now finished setting up.");
delay(1000);
}
void windowfill ()
{//Adds a screen for while waiting for firing
setfillstyle(1,0);
bar(400,0,640,160);
bar(0,0,240,160);
setfillstyle(7,2);
bar (400,0,636,160);
bar (0,0,240,160);
setcolor(15);
outtextxy(50,60,"Waiting for launch");
outtextxy(65,80,"confirmation.");
outtextxy(460,70,"Standing By....");
setcolor(YELLOW);
}
void win ()
{//informs the user they've won
setfillstyle(1,15);
bar(20,120,620,340);
setfillstyle(1,1);
bar(40,140,600,320);
setfillstyle(1,9);
bar(60,160,580,300);
setcolor(0);
//Y
line(80,180,100,240);
line(100,240,100,280);
line(100,280,120,280);
line(120,280,120,240);
line(120,240,140,180);
line(140,180,120,180);
line(120,180,110,220);
line(110,220,100,180);
line(100,180,80,180);
//0
line(148,200,148,260);
line(148,260,168,280);
line(168,280,188,280);
line(188,280,208,260);
line(208,260,208,200);
line(208,200,188,180);
line(188,180,168,180);
line(168,180,148,200);
line(172,200,168,204);
line(168,204,168,256);
line(168,256,172,260);
line(172,260,184,260);
line(184,260,188,256);
line(188,256,188,204);
line(188,204,184,200);
line(184,200,172,200);
//U
line(216,180,216,260);
line(216,260,236,280);
line(236,280,256,280);
line(256,280,276,260);
line(276,260,276,180);
line(276,180,256,180);
line(256,180,256,260);
line(256,260,236,260);
line(236,260,236,180);
line(236,180,216,180);
//W
line(336,180,360,280);
line(360,280,380,280);
line(380,280,400,240);
line(400,240,420,280);
line(420,280,440,280);
line(440,280,464,180);
line(464,180,444,180);
line(444,180,428,252);
line(428,252,408,220);
line(408,220,392,220);
line(392,220,372,252);
line(372,252,356,180);
line(356,180,336,180);
//I
line(472,180,472,280);
line(472,280,492,280);
line(492,280,492,180);
line(492,180,472,180);
//N
line(500,180,500,280);
line(500,280,520,280);
line(520,280,520,228);
line(520,228,540,280);
line(540,280,560,280);
line(560,280,560,180);
line(560,180,540,180);
line(540,180,540,232);
line(540,232,520,180);
line(520,180,500,180);
for(I=0;I<30;I++)
{Var=random(14)+1;
setfillstyle(1,Var);
floodfill(110,240,0);
floodfill(180,190,0);
floodfill(230,200,0);
floodfill(350,190,0);
floodfill(480,200,0);
floodfill(510,200,0);
delay(100);
}
setfillstyle(1,15);
floodfill(110,240,0);
floodfill(180,190,0);
floodfill(230,200,0);
floodfill(350,190,0);
floodfill(480,200,0);
floodfill(510,200,0);
setcolor(15);
outtextxy(170,440,"Press Any key to Exit the Program");
getch();
}
void lose ()
{//Tells the user they've lost
setfillstyle(1,15);
bar(20,120,620,340);
setfillstyle(1,1);
bar(40,140,600,320);
setfillstyle(1,9);
bar(60,160,580,300);
setcolor(0);
//Y
line(80,180,100,240);
line(100,240,100,280);
line(100,280,120,280);
line(120,280,120,240);
line(120,240,140,180);
line(140,180,120,180);
line(120,180,110,220);
line(110,220,100,180);
line(100,180,80,180);
//0
line(148,200,148,260);
line(148,260,168,280);
line(168,280,188,280);
line(188,280,208,260);
line(208,260,208,200);
line(208,200,188,180);
line(188,180,168,180);
line(168,180,148,200);
line(172,200,168,204);
line(168,204,168,256);
line(168,256,172,260);
line(172,260,184,260);
line(184,260,188,256);
line(188,256,188,204);
line(188,204,184,200);
line(184,200,172,200);
//U
line(216,180,216,260);
line(216,260,236,280);
line(236,280,256,280);
line(256,280,276,260);
line(276,260,276,180);
line(276,180,256,180);
line(256,180,256,260);
line(256,260,236,260);
line(236,260,236,180);
line(236,180,216,180);
//L
line(300,180,300,280);
line(300,280,360,280);
line(360,280,360,260);
line(360,260,320,260);
line(320,260,320,180);
line(320,180,300,180);
//O
line(368,200,368,260);
line(368,260,388,280);
line(388,280,408,280);
line(408,280,428,260);
line(428,260,428,200);
line(428,200,408,180);
line(408,180,388,180);
line(388,180,368,200);
line(388,204,388,256);
line(388,256,392,260);
line(392,260,404,260);
line(404,260,408,256);
line(408,256,408,204);
line(408,204,404,200);
line(404,200,392,200);
line(392,200,388,204);
//S
line(436,200,436,224);
line(436,224,444,232);
line(444,232,468,232);
line(468,232,476,240);
line(476,240,476,260);
line(476,260,456,260);
line(456,260,456,240);
line(456,240,436,240);
line(436,240,436,260);
line(436,260,456,280);
line(456,280,476,280);
line(476,280,496,260);
line(496,260,496,240);
line(496,240,488,228);
line(488,228,464,228);
line(464,228,456,220);
line(456,220,456,200);
line(456,200,476,200);
line(476,200,476,220);
line(476,220,496,220);
line(496,220,496,200);
line(496,200,476,180);
line(476,180,456,180);
line(456,180,436,200);
//E
line(504,180,504,280);
line(504,280,560,280);
line(560,280,560,260);
line(560,260,524,260);
line(524,260,524,240);
line(524,240,544,240);
line(544,240,544,220);
line(544,220,524,220);
line(524,220,524,200);
line(524,200,560,200);
line(560,200,560,180);
line(560,180,504,180);
for(I=0;I<30;I++)
{Var=random(14)+1;
setfillstyle(1,Var);
floodfill(110,240,0);
floodfill(180,190,0);
floodfill(230,200,0);
floodfill(310,190,0);
floodfill(370,200,0);
floodfill(460,190,0);
floodfill(510,200,0);
delay(100);
}
setfillstyle(1,15);
floodfill(110,240,0);
floodfill(180,190,0);
floodfill(230,200,0);
floodfill(310,190,0);
floodfill(370,200,0);
floodfill(460,190,0);
floodfill(510,200,0);
setcolor(15);
outtextxy(170,440,"Press Any key to Exit the Program");
getch();
}
| true |
958d0dd252ad30f65196608999adb764645c2ef4 | C++ | arijitroy003/An-Algorithm-A-Day | /Newton Raphson.cpp | UTF-8 | 458 | 2.953125 | 3 | [] | no_license | /*input
1.6 10
*/
/*~ @author = dwij28 (Abhinav Jha) ~*/
#include <bits/stdc++.h>
#define ll long long
#define pb push_back
#define mp make_pair
using namespace std;
float f (float x) { return 3*x - cos(x) - 1; }
float df(float x) { return 3 + sin(x); }
int main() {
int i, n;
float x;
scanf("%d%f", &n, &x); // number of iterations and initial value of root
for (i = 1; i <= n; i++) {
x = x - (f(x)/df(x));
}
printf("Value = %f\n", x);
return 0;
} | true |
3e4b06568c525a702a453fca62a5a7259d222698 | C++ | JeongYeonUk/Problem | /BOJ/15653.cpp | UTF-8 | 2,392 | 2.5625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
#include <queue>
#include <cmath>
using namespace std;
#define endl '\n'
typedef long long ll;
const int INF = 987654321;
const int MAX = 10 + 1;
const int dy[] = { 0,0,1,-1 };
const int dx[] = { 1,-1,0,0 };
struct INFO {
int ry, rx, by, bx, cnt;
};
int N, M;
int ry, rx, by, bx;
char board[MAX][MAX];
int visit[MAX][MAX][MAX][MAX];
int calDist(int ry, int rx, int by, int bx) {
return abs(ry - by) + abs(rx - bx);
}
int main()
{
ios_base::sync_with_stdio(false);
cout.tie(nullptr); cin.tie(nullptr);
queue<INFO> ball;
cin >> N >> M;
for (int y = 0; y < N; ++y) {
for (int x = 0; x < M; ++x) {
cin >> board[y][x];
if (board[y][x] == 'R') {
ry = y; rx = x;
board[y][x] = '.';
}
if (board[y][x] == 'B') {
by = y; bx = x;
board[y][x] = '.';
}
}
}
visit[ry][rx][by][bx] = true;
ball.push({ ry,rx,by,bx,0 });
while (!ball.empty()) {
int ry = ball.front().ry; int rx = ball.front().rx;
int by = ball.front().by; int bx = ball.front().bx;
int cnt = ball.front().cnt;
ball.pop();
for (int dir = 0; dir < 4; ++dir) {
bool redflag, blueflag;
redflag = blueflag = false;
int nry = ry + dy[dir];
int nrx = rx + dx[dir];
int nby = by + dy[dir];
int nbx = bx + dx[dir];
int nCnt = cnt + 1;
while (true) {
if (board[nry][nrx] == '#') {
nry -= dy[dir];
nrx -= dx[dir];
break;
}
if (board[nry][nrx] == 'O') {
redflag = true;
break;
}
nry += dy[dir]; nrx += dx[dir];
}
while (true) {
if (board[nby][nbx] == '#') {
nby -= dy[dir];
nbx -= dx[dir];
break;
}
if (board[nby][nbx] == 'O') {
blueflag = true;
break;
}
nby += dy[dir]; nbx += dx[dir];
}
if (blueflag)
continue;
if (redflag) {
cout << nCnt << endl;
return 0;
}
if (nry == nby && nrx == nbx) {
int redDist = calDist(ry, rx, nry, nrx);
int blueDist = calDist(by, bx, nby, nbx);
if (redDist > blueDist) {
nry -= dy[dir];
nrx -= dx[dir];
}
else {
nby -= dy[dir];
nbx -= dx[dir];
}
}
if (visit[nry][nrx][nby][nbx])
continue;
ball.push({ nry,nrx,nby,nbx, nCnt });
visit[nry][nrx][nby][nbx] = true;
}
}
cout << -1 << endl;
return 0;
}
| true |
55a943b7fb0864f8735f171da42334a29afd6224 | C++ | i-mozy/Automated-Tarot-Machine | /Automated_Tarot_Machine_v1.0/Automated_Tarot_Machine_v1.0.ino | UTF-8 | 98,862 | 2.6875 | 3 | [
"Apache-2.0"
] | permissive | #include "Adafruit_Thermal.h"
#include <SD.h>
#include <SPI.h>
#include "SoftwareSerial.h"
#include <Adafruit_NeoPixel.h>
#include <Entropy.h>
//Declare pin functions
#define stp 2
#define dir 3
#define MS1 4
#define MS2 5
#define EN 6 // stp, dir, MS1, MS2, EN are all for the Easy Driver
#define LED_PIN 7 // Optional, be sure to comment this outt if you aren't going to use LEDS
#define LED_COUNT 24
#define HOME_SENSOR 8 //This is the pin for the hall effect sensor
#define TX_PIN 9 // Arduino transmit YELLOW WIRE labeled RX on printer
#define RX_PIN 10 // Arduino receive GREEN WIRE labeled TX on printer
#define BUTTON_PIN 11 // Only relavent if you wish to operate the machine without the computer attached
#define SD_Pin 53 // Pin for the SD card module
Adafruit_NeoPixel strip(LED_COUNT, LED_PIN, NEO_GRBW + NEO_KHZ800); // declare LEDS
SoftwareSerial mySerial(RX_PIN, TX_PIN); // Declare SoftwareSerial obj first
Adafruit_Thermal printer(&mySerial, 48); // Pass addr to printer constructor
// Then see setup() function regarding serial & printer begin() calls.
//Declare variables for functions
char user_input;
int x;
inline void initSD() {
pinMode(SD_Pin, OUTPUT);
if (!SD.begin(SD_Pin)) {
Serial.println("SD Error");
} else {
Serial.println("SD Ok");
}
}
//****************************************************************************
//****************************************************************************
boolean lastButtonState = HIGH;
unsigned long currentButtonTime = 0, lastButtonTime = 0, ButtonCheckTime = 20;
//****************************************************************************
//****************************************************************************
void setup() {
initSD(); //Initialize the SD card
Entropy.initialize(); //Initialize the Entropy library
pinMode(stp, OUTPUT);
pinMode(dir, OUTPUT);
pinMode(MS1, OUTPUT);
pinMode(MS2, OUTPUT);
pinMode(EN, OUTPUT); //Set the pinmodes for the easydriver
pinMode(HOME_SENSOR, INPUT); // Set the pinmode for the hall effect sensor
pinMode(BUTTON_PIN, INPUT_PULLUP);
Serial.begin(9600); //Open Serial connection for debugging
Serial.println("Begin motor control");
strip.begin(); // INITIALIZE NeoPixel strip object (REQUIRED)
strip.show(); // Turn OFF all pixels ASAP
strip.setBrightness(50); // Set BRIGHTNESS to about 1/5 (max = 255)
mySerial.begin(19200); // Initialize SoftwareSerial
printer.begin(); // Init printer (same regardless of serial type)
FindHome(); // Go to the "Top of the deck" at startup
}
//****************************************************************************
//****************************************************************************
void loop(){
currentButtonTime = millis();
digitalWrite(EN, LOW); //Pull enable pin low to allow motor control
if ( currentButtonTime - lastButtonTime > ButtonCheckTime ) {
boolean buttonState = digitalRead(BUTTON_PIN);
if (buttonState == LOW && lastButtonState == HIGH) {
PickACard();
CardOfTheDay();
colorWipe(strip.Color(0, 0, 0, 0), 0); // OFF
FindHome();
}
lastButtonState = buttonState;
}
while(Serial.available()){
user_input = Serial.read(); //Read user input and trigger appropriate function
digitalWrite(EN, LOW); //Pull enable pin low to allow motor control
if (user_input == '1'){
Serial.println();
Serial.print("Your card of the day is... ");
PickACard();
CardOfTheDay();
colorWipe(strip.Color(0, 0, 0, 0), 0); // OFF
FindHome();
}
else if (user_input == '2'){
Serial.println();
Serial.print("Your past was... ");
PickACard();
Past();
colorWipe(strip.Color(0, 0, 0, 0), 0); // OFF
Reset();
Serial.print("Your present is... ");
PickACard();
Present();
colorWipe(strip.Color(0, 0, 0, 0), 0); // OFF
Reset();
Serial.print("Your future will be... ");
PickACard();
Future();
colorWipe(strip.Color(0, 0, 0, 0), 0); // OFF
FindHome();
}
else if (user_input == '3'){
Serial.println();
Serial.print("Your relationship card is... ");
PickACard();
Relationship();
colorWipe(strip.Color(0, 0, 0, 0), 0); // OFF
FindHome();
}
else if (user_input == '4'){
Serial.println();
Serial.print("Your vocational card is... ");
PickACard();
Vocation();
colorWipe(strip.Color(0, 0, 0, 0), 0); // OFF
FindHome();
}
}
}
//****************************************************************************
//****************************************************************************
void FindHome(){
digitalWrite(dir, LOW); //Pull direction pin low to move "forward"
digitalWrite(MS1, HIGH);
digitalWrite(MS2, HIGH); //Pull MS1, and MS2 high to set logic to 1/8th microstep resolution
Serial.println("Searching for home...");
for(x= 0; x< 500 ; x++) //Loop forward enough times to stop a false home
{
digitalWrite(stp,HIGH); //Trigger one step forward
delayMicroseconds(1275);
digitalWrite(stp,LOW); //Pull step pin low so it can be triggered again
delayMicroseconds(1275);
}
while(digitalRead(HOME_SENSOR)){
digitalWrite(stp,HIGH); //Trigger one step forward
delayMicroseconds(1275);
digitalWrite(stp,LOW); //Pull step pin low so it can be triggered again
delayMicroseconds(1275);
}
Serial.println("Home Found");
Serial.println();
Serial.println("What type of reading would you like?");
Serial.println();
Serial.println("1: Card of the day");
Serial.println("2: Past, Present, Future");
Serial.println("3: Love and relationships");
Serial.println("4: Career / Vocation");
}
//****************************************************************************
void Reset(){
digitalWrite(dir, LOW); //Pull direction pin low to move "forward"
digitalWrite(MS1, HIGH); //Pull MS1, and MS2 high to set logic to 1/8th microstep resolution
digitalWrite(MS2, HIGH);
for(x= 0; x< 500 ; x++) //Loop forward enough times to stop a false home
{
digitalWrite(stp,HIGH); //Trigger one step forward
delayMicroseconds(1275);
digitalWrite(stp,LOW); //Pull step pin low so it can be triggered again
delayMicroseconds(1275);
}
while(digitalRead(HOME_SENSOR)){
digitalWrite(stp,HIGH); //Trigger one step forward
delayMicroseconds(1275);
digitalWrite(stp,LOW); //Pull step pin low so it can be triggered again
delayMicroseconds(1275);
}
}
//****************************************************************************
void CardOfTheDay(){
printer.feed(1);
printer.boldOn();
printer.justify('C');
printer.setSize('L');
printer.upsideDownOn();
printer.println(F("CARD OF THE DAY"));
printer.feed(4);
printer.upsideDownOff();
printer.sleep(); // Tell printer to sleep
delay(3000L); // Sleep for 3 seconds
printer.wake(); // MUST wake() before printing again, even if reset
printer.setDefault(); // Restore printer to defaults
}
//****************************************************************************
void Past(){
printer.feed(1);
printer.boldOn();
printer.justify('C');
printer.setSize('L');
printer.upsideDownOn();
printer.println(F("PAST"));
printer.feed(4);
printer.upsideDownOff();
printer.sleep(); // Tell printer to sleep
delay(3000L); // Sleep for 3 seconds
printer.wake(); // MUST wake() before printing again, even if reset
printer.setDefault(); // Restore printer to defaults
}
//****************************************************************************
void Present(){
printer.feed(1);
printer.boldOn();
printer.justify('C');
printer.setSize('L');
printer.upsideDownOn();
printer.println(F("PRESENT"));
printer.feed(4);
printer.upsideDownOff();
printer.sleep(); // Tell printer to sleep
delay(3000L); // Sleep for 3 seconds
printer.wake(); // MUST wake() before printing again, even if reset
printer.setDefault(); // Restore printer to defaults
}
//****************************************************************************
void Future(){
printer.feed(1);
printer.boldOn();
printer.justify('C');
printer.setSize('L');
printer.upsideDownOn();
printer.println(F("FUTURE"));
printer.feed(4);
printer.upsideDownOff();
printer.sleep(); // Tell printer to sleep
delay(3000L); // Sleep for 3 seconds
printer.wake(); // MUST wake() before printing again, even if reset
printer.setDefault(); // Restore printer to defaults
}
//****************************************************************************
void Relationship(){
printer.feed(1);
printer.boldOn();
printer.justify('C');
printer.setSize('M');
printer.upsideDownOn();
printer.println(F("RELATIONSHIP CARD"));
printer.feed(4);
printer.upsideDownOff();
printer.sleep(); // Tell printer to sleep
delay(3000L); // Sleep for 3 seconds
printer.wake(); // MUST wake() before printing again, even if reset
printer.setDefault(); // Restore printer to defaults
}
//****************************************************************************
void Vocation(){
printer.feed(1);
printer.boldOn();
printer.justify('C');
printer.setSize('L');
printer.upsideDownOn();
printer.println(F("VOCATION CARD"));
printer.feed(4);
printer.upsideDownOff();
printer.sleep(); // Tell printer to sleep
delay(3000L); // Sleep for 3 seconds
printer.wake(); // MUST wake() before printing again, even if reset
printer.setDefault(); // Restore printer to defaults
}
//****************************************************************************
void PickACard()
{
int val =
Entropy.random(40, 1581); // Full range of cards excluding "blanks" #0 & #20
int rem;
rem = val % 20 ;
if (rem < 10)
val -= rem;
else
val += 20 - rem; //ensure value is a multiple of 20
digitalWrite(dir, LOW); //Pull direction pin low to move "forward"
digitalWrite(MS1, HIGH); //Pull MS1, and MS2 high to set logic to 1/8th microstep resolution
digitalWrite(MS2, HIGH);
for(x= 0; x< val + 1600 ; x++) // Move spindle one full rotation before going to the choosen card
{
digitalWrite(stp,HIGH);
delayMicroseconds(1275); // delay dictates how fast the spindle rotates.
digitalWrite(stp,LOW);
delayMicroseconds(1275);
}
//****************************************************************************
//****************************************************************************
// LED CODE
if (val > 20 && val < 470) { // Major Arcana
Yellow(1);
}
else if (val > 471 && val < 750) { // Wands element: Fire
Red(1);
}
else if (val > 751 && val < 1030) { // Cups element: Water
Blue(1);
}
else if (val > 1031 && val < 1310) { // Swords element: Air
White(1);
}
else if (val > 1311 && val < 1600) { // Pentacles element: Earth
Green(1);
}
//****************************************************************************
//****************************************************************************
// PRINTER CODE
if (val == 40) // The Fool
{
int readingType = Entropy.random(0, 31);
Serial.print("The Fool");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("0_p", FILE_READ);
printer.printBitmap(384, 660, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("0_o", FILE_READ);
printer.printBitmap(384, 660, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("0_n", FILE_READ);
printer.printBitmap(384, 660, dynamic_cast<Stream*>(&data));
data.close();
}
}
else if (val == 60) // The Magician
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("The Magician");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("1_p", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("1_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("1_n", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
}
else if (val == 80) // The High Priestess
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("The High Priestess");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("2_p", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("2_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("2_n", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
}
else if (val == 100) // The Empress
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("The Empress");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("3_p", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("3_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("3_n", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
}
else if (val == 120) // The Emperor
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("The Emperor");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("4_p", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("4_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("4_n", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
}
else if (val == 140) // The Hierophant
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("The Hierophant");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("5_p", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("5_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("5_n", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
}
else if (val == 160) // The Lovers
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("The Lovers");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("6_p", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("6_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("6_n", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
}
else if (val == 180) // The Chariot
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("The Chariot");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("7_p", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("7_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("7_n", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
}
else if (val == 200) // Strength
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.println("Strength");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("8_p", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("8_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("8_n", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
}
else if (val == 220) // The Hermit
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("The Hermit");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("9_p", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("9_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("9_n", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
}
else if (val == 240) // Wheel of Fortune
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Wheel of Fortune");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("10_p", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("10_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("10_n", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
}
else if (val == 260) // Justice
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Justice");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("11_p", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("11_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("11_n", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
}
else if (val == 280) // The Hanged Man
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("The Hanged Man");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("12_p", FILE_READ);
printer.printBitmap(384, 660, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("12_o", FILE_READ);
printer.printBitmap(384, 660, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("12_n", FILE_READ);
printer.printBitmap(384, 660, dynamic_cast<Stream*>(&data));
data.close();
}
}
else if (val == 300) // Death
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Death");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("13_p", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("13_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("13_n", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
}
else if (val == 320) // Temperance
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Temperance");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("14_p", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("14_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("14_n", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
}
else if (val == 340) // The Devil
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("The Devil");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("15_p", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("15_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("15_n", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
}
else if (val == 360) // The Tower
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("The Tower");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("16_p", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("16_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("16_n", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
}
else if (val == 380) //The Star
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("The Star");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("17_p", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("17_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("17_n", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
}
else if (val == 400) // The Moon
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("The Moon");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("18_p", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("18_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("18_n", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
}
else if (val == 420) // The Sun
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("The Sun");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("19_p", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("19_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("19_n", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
}
else if (val == 440) // Judgement
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Judgement");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("20_p", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("20_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("20_n", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
}
else if (val == 460) // The World
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("The World");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("21_p", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("21_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("21_n", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
}
else if (val == 480) // Ace of Wands
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Ace of Wands");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("a_w_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("a_w_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("a_w_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
}
else if (val == 500) // Two of Wands
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Two of Wands");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("2_w_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("2_w_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("2_w_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
printer.feed(1);
printer.justify('C');
printer.setSize('S');
printer.upsideDownOn();
printer.println(F("Two of Wands"));
}
else if (val == 520) // Three of Wands
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Three of Wands");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("3_w_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("3_w_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("3_w_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
printer.feed(1);
printer.justify('C');
printer.setSize('S');
printer.upsideDownOn();
printer.println(F("Three of Wands"));
}
else if (val == 540) // Four of Wands
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Four of Wands");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("4_w_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("4_w_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("4_w_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
printer.feed(1);
printer.justify('C');
printer.setSize('S');
printer.upsideDownOn();
printer.println(F("Four of Wands"));
}
else if (val == 560) // Five of Wands
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Five of Wands");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("5_w_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("5_w_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("5_w_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
printer.feed(1);
printer.justify('C');
printer.setSize('S');
printer.upsideDownOn();
printer.println(F("Five of Wands"));
}
else if (val == 580) // Six of Wands
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Six of Wands");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("6_w_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("6_w_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("6_w_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
printer.feed(1);
printer.justify('C');
printer.setSize('S');
printer.upsideDownOn();
printer.println(F("Six of Wands"));
}
else if (val == 600) // Seven of Wands
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Seven of Wands");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("7_w_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("7_w_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("7_w_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
printer.feed(1);
printer.justify('C');
printer.setSize('S');
printer.upsideDownOn();
printer.println(F("Seven of Wands"));
}
else if (val == 620) // Eight of Wands
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Eight of Wands");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("8_w_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("8_w_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("8_w_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
printer.feed(1);
printer.justify('C');
printer.setSize('S');
printer.upsideDownOn();
printer.println(F("Eight of Wands"));
}
else if (val == 640) // Nine of Wands
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Nine of Wands");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("9_w_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("9_w_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("9_w_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
printer.feed(1);
printer.justify('C');
printer.setSize('S');
printer.upsideDownOn();
printer.println(F("Nine of Wands"));
}
else if (val == 660) // Ten of Wands
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Ten of Wands");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("10_w_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("10_w_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("10_w_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
printer.feed(1);
printer.justify('C');
printer.setSize('S');
printer.upsideDownOn();
printer.println(F("Ten of Wands"));
}
else if (val == 680) // Page of Wands
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Page of Wands");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("p_w_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("p_w_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("p_w_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
}
else if (val == 700) // Knight of Wands
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Knight of Wands");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("kn_w_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("kn_w_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("kn_w_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
}
else if (val == 720) // Queen of Wands
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Queen of Wands");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("q_w_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("q_w_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("q_w_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
}
else if (val == 740) // King of Wands
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("King of Wands");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("k_w_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("k_w_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("k_w_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
}
else if (val == 760) // Ace of Cups
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Ace of Cups");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("a_c_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("a_c_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("a_c_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
}
else if (val == 780) // Two of Cups
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Two of Cups");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("2_c_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("2_c_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("2_c_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
printer.feed(1);
printer.justify('C');
printer.setSize('S');
printer.upsideDownOn();
printer.println(F("Two of Cups"));
}
else if (val == 800) // Three of Cups
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Three of Cups");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("3_c_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("3_c_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("3_c_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
printer.feed(1);
printer.justify('C');
printer.setSize('S');
printer.upsideDownOn();
printer.println(F("Three of Cups"));
}
else if (val == 820) // Four of Cups
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Four of Cups");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("4_c_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("4_c_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("4_c_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
printer.feed(1);
printer.justify('C');
printer.setSize('S');
printer.upsideDownOn();
printer.println(F("Four of Cups"));
}
else if (val == 840) // Five of Cups
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Five of Cups");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("5_c_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("5_c_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("5_c_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
printer.feed(1);
printer.justify('C');
printer.setSize('S');
printer.upsideDownOn();
printer.println(F("Five of Cups"));
}
else if (val == 860) // Six of Cups
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Six of Cups");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("6_c_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("6_c_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("6_c_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
printer.feed(1);
printer.justify('C');
printer.setSize('S');
printer.upsideDownOn();
printer.println(F("Six of Cups"));
}
else if (val == 880) // Seven of Cups
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Seven of Cups");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("7_c_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("7_c_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("7_c_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
printer.feed(1);
printer.justify('C');
printer.setSize('S');
printer.upsideDownOn();
printer.println(F("Seven of Cups"));
}
else if (val == 900) // Eight of Cups
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Eight of Cups");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("8_c_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("8_c_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("8_c_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
printer.feed(1);
printer.justify('C');
printer.setSize('S');
printer.upsideDownOn();
printer.println(F("Eight of Cups"));
}
else if (val == 920) // Nine of Cups
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Nine of Cups");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("9_c_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("9_c_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("9_c_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
printer.feed(1);
printer.justify('C');
printer.setSize('S');
printer.upsideDownOn();
printer.println(F("Nine of Cups"));
}
else if (val == 940) // Ten of Cups
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Ten of Cups");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("10_c_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("10_c_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("10_c_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
printer.feed(1);
printer.justify('C');
printer.setSize('S');
printer.upsideDownOn();
printer.println(F("Ten of Cups"));
}
else if (val == 960) // Page of Cups
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Page of Cups");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("p_c_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("p_c_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("p_c_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
}
else if (val == 980) // Knight of Cups
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Knight of Cups");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("kn_c_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("kn_c_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("kn_c_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
}
else if (val == 1000) // Queen of Cups
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Queen of Cups");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("q_c_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("q_c_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("q_c_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
}
else if (val == 1020) // King of Cups
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("King of Cups");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("k_c_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("k_c_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("k_c_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
}
else if (val == 1040) // Ace of Swords
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Ace of Swords");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("a_s_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("a_s_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("a_s_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
}
else if (val == 1060) // Two of Swords
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Two of Swords");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("2_s_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("2_s_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("2_s_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
printer.feed(1);
printer.justify('C');
printer.setSize('S');
printer.upsideDownOn();
printer.println(F("Two of Swords"));
}
else if (val == 1080) // Three of Swords
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Three of Swords");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("3_s_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("3_s_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("3_s_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
printer.feed(1);
printer.justify('C');
printer.setSize('S');
printer.upsideDownOn();
printer.println(F("Three of Swords"));
}
else if (val == 1100) // Four of Swords
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Four of Swords");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("4_s_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("4_s_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("4_s_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
printer.feed(1);
printer.justify('C');
printer.setSize('S');
printer.upsideDownOn();
printer.println(F("Four of Swords"));
}
else if (val == 1120) // Five of Swords
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Five of Swords");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("5_s_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("5_s_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("5_s_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
printer.feed(1);
printer.justify('C');
printer.setSize('S');
printer.upsideDownOn();
printer.println(F("Five of Swords"));
for(x= 0; x< 200 ; x++) //Loop forward enough times to stop a false home
{
digitalWrite(stp,HIGH); //Trigger one step forward
delayMicroseconds(1275);
digitalWrite(stp,LOW); //Pull step pin low so it can be triggered again
delayMicroseconds(1275);
}
}
else if (val == 1140) // Six of Swords
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Six of Swords");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("6_s_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("6_s_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("6_s_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
printer.feed(1);
printer.justify('C');
printer.setSize('S');
printer.upsideDownOn();
printer.println(F("Six of Swords"));
for(x= 0; x< 200 ; x++) //Loop forward enough times to stop a false home
{
digitalWrite(stp,HIGH); //Trigger one step forward
delayMicroseconds(1275);
digitalWrite(stp,LOW); //Pull step pin low so it can be triggered again
delayMicroseconds(1275);
}
}
else if (val == 1160) // Seven of Swords
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Seven of Swords");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("7_s_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("7_s_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("7_s_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
printer.feed(1);
printer.justify('C');
printer.setSize('S');
printer.upsideDownOn();
printer.println(F("Seven of Swords"));
for(x= 0; x< 200 ; x++) //Loop forward enough times to stop a false home
{
digitalWrite(stp,HIGH); //Trigger one step forward
delayMicroseconds(1275);
digitalWrite(stp,LOW); //Pull step pin low so it can be triggered again
delayMicroseconds(1275);
}
}
else if (val == 1180) // Eight of Swords
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Eight of Swords");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("8_s_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("8_s_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("8_s_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
printer.feed(1);
printer.justify('C');
printer.setSize('S');
printer.upsideDownOn();
printer.println(F("Eight of Swords"));
for(x= 0; x< 200 ; x++) //Loop forward enough times to stop a false home
{
digitalWrite(stp,HIGH); //Trigger one step forward
delayMicroseconds(1275);
digitalWrite(stp,LOW); //Pull step pin low so it can be triggered again
delayMicroseconds(1275);
}
}
else if (val == 1200) // Nine of Swords
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Nine of Swords");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("9_s_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("9_s_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("9_s_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
printer.feed(1);
printer.justify('C');
printer.setSize('S');
printer.upsideDownOn();
printer.println(F("Nine of Swords"));
}
else if (val == 1220) // Ten of Swords
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Ten of Swords");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("10_s_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("10_s_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("10_s_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
printer.feed(1);
printer.justify('C');
printer.setSize('S');
printer.upsideDownOn();
printer.println(F("Ten of Swords"));
}
else if (val == 1240) // Page of Swords
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Page of Swords");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("p_s_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("p_s_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("p_s_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
}
else if (val == 1260) // Knight of Swords
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Knight of Swords");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("kn_s_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("kn_s_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("kn_s_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
}
else if (val == 1280) // Queen of Swords
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Queen of Swords");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("q_s_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("q_s_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("q_s_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
}
else if (val == 1300) // King of Swords
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("King of Swords");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("k_s_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("k_s_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("k_s_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
}
else if (val == 1320) // Ace of Pentacles
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Ace of Pentacles");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("a_p_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("a_p_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("a_p_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
}
else if (val == 1340) // Two of Pentacles
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Two of Pentacles");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("2_p_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("2_p_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("2_p_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
printer.feed(1);
printer.justify('C');
printer.setSize('S');
printer.upsideDownOn();
printer.println(F("Two of Pentacles"));
}
else if (val == 1360) // Three of Pentacles
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Three of Pentacles");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("3_p_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("3_p_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("3_p_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
printer.feed(1);
printer.justify('C');
printer.setSize('S');
printer.upsideDownOn();
printer.println(F("Three of Pentacles"));
}
else if (val == 1380) // Four of Pentacles
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Four of Pentacles");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("4_p_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("4_p_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("4_p_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
printer.feed(1);
printer.justify('C');
printer.setSize('S');
printer.upsideDownOn();
printer.println(F("Four of Pentacles"));
}
else if (val == 1400) // Five of Pentacles
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Five of Pentacles");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("5_p_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("5_p_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("5_p_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
printer.feed(1);
printer.justify('C');
printer.setSize('S');
printer.upsideDownOn();
printer.println(F("Five of Pentacles"));
}
else if (val == 1420) // Six of Pentacles
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Six of Pentacles");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("6_p_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("6_p_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("6_p_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
printer.feed(1);
printer.justify('C');
printer.setSize('S');
printer.upsideDownOn();
printer.println(F("Six of Pentacles"));
}
else if (val == 1440) // Seven of Pentacles
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Seven of Pentacles");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("7_p_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("7_p_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("7_p_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
printer.feed(1);
printer.justify('C');
printer.setSize('S');
printer.upsideDownOn();
printer.println(F("Seven of Pentacles"));
}
else if (val == 1460) // Eight of Pentacles
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Eight of Pentacles");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("8_p_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("8_p_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("8_p_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
printer.feed(1);
printer.justify('C');
printer.setSize('S');
printer.upsideDownOn();
printer.println(F("Eight of Pentacles"));
}
else if (val == 1480) // Nine of Pentacles
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Nine of Pentacles");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("9_p_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("9_p_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("9_p_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
printer.feed(1);
printer.justify('C');
printer.setSize('S');
printer.upsideDownOn();
printer.println(F("Nine of Pentacles"));
}
else if (val == 1500) // Ten of Pentacles
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Ten of Pentacles");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("10_p_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("10_p_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("10_p_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
printer.feed(1);
printer.justify('C');
printer.setSize('S');
printer.upsideDownOn();
printer.println(F("Ten of Pentacles"));
}
else if (val == 1520) // Page of Pentacles
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Page of Pentacles");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("p_p_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("p_p_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("p_p_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
}
else if (val == 1540) // Knight of Pentacles
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Knight of Pentacles");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("kn_p_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("kn_p_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("kn_p_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
}
else if (val == 1560) // Queen of Pentacles
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("Queen of Pentacles");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("q_p_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("q_p_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("q_p_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
}
else if (val == 1580) // King of Pentacles
{
// int readingType = 5;
// int readingType = 15;
// int readingType = 25;
int readingType = Entropy.random(0, 31);
Serial.print("King of Pentacles");
Serial.println("");
Serial.println("");
if (readingType <= 9)
{
Serial.print("Reading type is: Upright");
Serial.println("");
File data = SD.open("k_p_u", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 10 && readingType <= 19)
{
Serial.print("Reading type is: Open");
Serial.println("");
File data = SD.open("k_p_o", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
else if (readingType >= 20)
{
Serial.print("Reading type is: Reversed");
Serial.println("");
File data = SD.open("k_p_r", FILE_READ);
printer.printBitmap(384, 661, dynamic_cast<Stream*>(&data));
data.close();
}
}
//****************************************************************************
//****************************************************************************
// delay(5000); // (For debugging only) Pause so I can see card
delay(5);
}
void Yellow(uint8_t wait) {
for(int i=0; i<150; i++) { // Ramp up from 0 to 255
// Fill entire strip with white at gamma-corrected brightness level 'j':
strip.fill(strip.Color(255, 205, 0));
strip.setBrightness(i);
strip.show();
delay(wait);
}
}
void Red(uint8_t wait) {
for(int i=0; i<150; i++) { // Ramp up from 0 to 255
// Fill entire strip with white at gamma-corrected brightness level 'j':
strip.fill(strip.Color(255, 0, 0));
strip.setBrightness(i);
strip.show();
delay(wait);
}
}
void Green(uint8_t wait) {
for(int i=0; i<150; i++) { // Ramp up from 0 to 255
// Fill entire strip with white at gamma-corrected brightness level 'j':
strip.fill(strip.Color(0, 245, 0));
strip.setBrightness(i);
strip.show();
delay(wait);
}
}
void Blue(uint8_t wait) {
for(int i=0; i<150; i++) { // Ramp up from 0 to 255
// Fill entire strip with white at gamma-corrected brightness level 'j':
strip.fill(strip.Color(0, 0, 255));
strip.setBrightness(i);
strip.show();
delay(wait);
}
}
void White(uint8_t wait) {
for(int i=0; i<150; i++) { // Ramp up from 0 to 255
// Fill entire strip with white at gamma-corrected brightness level 'j':
strip.fill(strip.Color(0, 0, 0, 255));
strip.setBrightness(i);
strip.show();
delay(wait);
}
}
void colorWipe(uint32_t color, int wait) {
for(int i=0; i<strip.numPixels(); i++) { // For each pixel in strip...
strip.setPixelColor(i, color); // Set pixel's color (in RAM)
strip.show(); // Update strip to match
delay(wait); // Pause for a moment
}
}
| true |
e159fb81f463d15d74ca9f83b76e797d77d70961 | C++ | laurencerwong/usc-cs-402 | /code/threads/synch.cc | UTF-8 | 19,622 | 2.953125 | 3 | [
"MIT-Modern-Variant"
] | permissive | // synch.cc
// Routines for synchronizing threads. Three kinds of
// synchronization routines are defined here: semaphores, locks
// and condition variables (the implementation of the last two
// are left to the reader).
//
// Any implementation of a synchronization routine needs some
// primitive atomic operation. We assume Nachos is running on
// a uniprocessor, and thus atomicity can be provided by
// turning off interrupts. While interrupts are disabled, no
// context switch can occur, and thus the current thread is guaranteed
// to hold the CPU throughout, until interrupts are reenabled.
//
// Because some of these routines might be called with interrupts
// already disabled (Semaphore::V for one), instead of turning
// on interrupts at the end of the atomic operation, we always simply
// re-set the interrupt state back to its original value (whether
// that be disabled or enabled).
//
// Copyright (c) 1992-1993 The Regents of the University of California.
// All rights reserved. See copyright.h for copyright notice and limitation
// of liability and disclaimer of warranty provisions.
#include "copyright.h"
#include "synch.h"
#include "system.h"
//----------------------------------------------------------------------
// Semaphore::Semaphore
// Initialize a semaphore, so that it can be used for synchronization.
//
// "debugName" is an arbitrary name, useful for debugging.
// "initialValue" is the initial value of the semaphore.
//----------------------------------------------------------------------
Semaphore::Semaphore(char* debugName, int initialValue)
{
name = debugName;
value = initialValue;
queue = new List;
}
//----------------------------------------------------------------------
// Semaphore::Semaphore
// De-allocate semaphore, when no longer needed. Assume no one
// is still waiting on the semaphore!
//----------------------------------------------------------------------
Semaphore::~Semaphore()
{
delete queue;
}
//----------------------------------------------------------------------
// Semaphore::P
// Wait until semaphore value > 0, then decrement. Checking the
// value and decrementing must be done atomically, so we
// need to disable interrupts before checking the value.
//
// Note that Thread::Sleep assumes that interrupts are disabled
// when it is called.
//----------------------------------------------------------------------
void
Semaphore::P()
{
IntStatus oldLevel = interrupt->SetLevel(IntOff); // disable interrupts
while (value == 0) { // semaphore not available
queue->Append((void *)currentThread); // so go to sleep
currentThread->Sleep();
}
value--; // semaphore available,
// consume its value
(void) interrupt->SetLevel(oldLevel); // re-enable interrupts
}
//----------------------------------------------------------------------
// Semaphore::V
// Increment semaphore value, waking up a waiter if necessary.
// As with P(), this operation must be atomic, so we need to disable
// interrupts. Scheduler::ReadyToRun() assumes that threads
// are disabled when it is called.
//----------------------------------------------------------------------
void
Semaphore::V()
{
Thread *thread;
IntStatus oldLevel = interrupt->SetLevel(IntOff);
thread = (Thread *)queue->Remove();
if (thread != NULL) // make thread ready, consuming the V immediately
scheduler->ReadyToRun(thread);
value++;
(void) interrupt->SetLevel(oldLevel);
}
// Dummy functions -- so we can compile our later assignments
// Note -- without a correct implementation of Condition::Wait(),
// the test case in the network assignment won't work!
Lock::Lock(char* debugName) {
name = debugName;
state = FREE; //not allowing more than one thread to acquire one Lock
//to conform to the monitor paradigm
queue = new List;
}
//---------------------------------------------------------------
//Deallocates Lock, assuming no thread is still trying to use lock
//--------------------------------------------------------------
Lock::~Lock() {
delete queue;
delete name;
}
//----------------------------------------------------------------
//--------------------------------------------------------------
//Lock::Acquire
//Allow thread to acquire the Lock, also allows us to remember which
//Thread called this function
//----------------------------------------------------------------
void Lock::Acquire() {
IntStatus oldLevel = interrupt->SetLevel(IntOff); // disable interrupts so the current thread
//cannot be switched out
if(isHeldByCurrentThread()){ //thread already has possession, if allowed to acquire again,
//thread would be blocked entire process indefinitely since interrupts are switched off
(void) interrupt->SetLevel(oldLevel); //so restore interrupts
return; //and do not wait
}
if(state == FREE){ //lock is free to be taken
state = BUSY;
threadWithPossession = currentThread; //make this thread the holder
}
else{
queue->Append( (void *) currentThread); //go into waiting queue
currentThread->Sleep(); //kick self out of processor to wait
}
(void) interrupt->SetLevel(oldLevel); // re-enable interrupts
}
void Lock::Release() {
Thread* thread;
IntStatus oldLevel = interrupt->SetLevel(IntOff);
if(!isHeldByCurrentThread()){ //shouldn't allow synchronization to be messed up if a thread calls release accidentally or maliciously
printf("Thread %s calling Release() on Lock %s does not have lock\n", currentThread->getName(), name);
(void) interrupt->SetLevel(oldLevel); // re-enable interrupts
return; //kicks out a thread that didn't acquire Lock
}
if(!queue->IsEmpty()){ //check this condition to avoid segmentation faults or bus errors
thread = (Thread *) queue->Remove();
threadWithPossession = thread; //give next thread immediate possession of the lock
scheduler->ReadyToRun(thread); //add to the system's ready queue
}
else{ //make sure lock can be grabbed by anyone if no one was waiting in te ready queue
state = FREE;
threadWithPossession = NULL;
}
(void) interrupt->SetLevel(oldLevel); //restore interrupts
}
//--------------------------------------------------------------
//Allows us to use the external system variable Thread* currentThread
//to check against the thread that last acquired the lock.
//---------------------------------------------------------
bool Lock::isHeldByCurrentThread(){
return currentThread == threadWithPossession;
}
#ifdef CHANGED
bool Lock::isBusy(){
if(state == BUSY){
return true;
}
else{
return false;
}
}
#endif
// Dummy functions -- so we can compile our later assignments
// Note -- without a correct implementation of Condition::Wait(),
// the test case in the network assignment won't work!
ServerLock::ServerLock(char* debugName) {
name = debugName;
state = FREE; //not allowing more than one thread to acquire one ServerLock
//to conform to the monitor paradigm
queue = new List;
currentClientRequest = NULL;
}
//---------------------------------------------------------------
//Deallocates ServerLock, assuming no thread is still trying to use ServerLock
//--------------------------------------------------------------
ServerLock::~ServerLock() {
delete queue;
delete name;
}
//----------------------------------------------------------------
//--------------------------------------------------------------
//ServerLock::Acquire
//Allow thread to acquire the ServerLock, also allows us to remember which
//Thread called this function
//----------------------------------------------------------------
ClientRequest* ServerLock::Acquire(ClientRequest* cr) {
IntStatus oldLevel = interrupt->SetLevel(IntOff); // disable interrupts so the current thread
//cannot be switched out
if(this->isHeldByRequester(cr)){ //thread already has possession, if allowed to acquire again,
//thread would be bServerLocked entire process indefinitely since interrupts are switched off
(void) interrupt->SetLevel(oldLevel); //so restore interrupts
cr->respond = true;
return cr; //and do not wait
}
if(state == FREE){ //ServerLock is free to be taken
state = BUSY;
//cout << "SL ACQUIRE: SETTING CURRENT CLIENT REQUEST TO " << cr << endl;
currentClientRequest = cr; //make this thread the holder
cr->respond = true;
}
else{
DEBUG('z', "Client with MachineID: %d, Mailbox: %d is waiting on lock\n", cr->machineID, cr->mailboxNumber);
queue->Append( (void *) cr); //go into waiting queue
cr->respond = false;
}
(void) interrupt->SetLevel(oldLevel); // re-enable interrupts
return cr;
}
ClientRequest* ServerLock::Release(ClientRequest* cr) {
IntStatus oldLevel = interrupt->SetLevel(IntOff);
if(!isHeldByRequester(cr)){ //shouldn't allow synchronization to be messed up if a thread calls release accidentally or maliciously
printf("Thread with machineID %d and mailboxNumber %d calling Release() on ServerLock %s does not have ServerLock\n", cr->machineID, cr->mailboxNumber, this->name);
(void) interrupt->SetLevel(oldLevel); // re-enable interrupts
cr->respond = false;
return cr; //kicks out a thread that didn't acquire ServerLock
}
if(!queue->IsEmpty()){ //check this condition to avoid segmentation faults or bus errors
delete cr;
cr = (ClientRequest *) queue->Remove();
//cout << "SL RELEASE: SETTING CURRENT CLIENT REQUEST TO " << cr << endl;
currentClientRequest = cr; //give next thread immediate possession of the ServerLoc
//cout << "In SERVERLOCK RELEASE, setting currentCR to " << cr << endl;
cr->respond = true;
}
else{ //make sure ServerLock can be grabbed by anyone if no one was waiting in te ready queue
state = FREE;
//cout << "SL RELEASE: SETTING CURRENT CLIENT REQUEST TO NULL" << endl;
currentClientRequest = NULL;
cr->respond = false;
}
(void) interrupt->SetLevel(oldLevel); //restore interrupts
return cr;
}
//--------------------------------------------------------------
//Allows us to use the external system variable Thread* currentThread
//to check against the thread that last acquired the ServerLock.
//---------------------------------------------------------
bool ServerLock::isHeldByRequester(ClientRequest* cr){
if(currentClientRequest == NULL) {
return false;
}
return cr->machineID == currentClientRequest->machineID && cr->mailboxNumber == currentClientRequest->mailboxNumber;
}
#ifdef CHANGED
bool ServerLock::isBusy(){
if(state == BUSY){
return true;
}
else{
return false;
}
}
#endif
Condition::Condition(char* debugName) {
name = debugName;
queue = new List;
}
Condition::~Condition() {
delete queue;
}
void Condition::Wait(Lock* conditionLock) {
IntStatus oldLevel = interrupt->SetLevel(IntOff); // disable interrupts so this operation is atomic
//(can't be switched out)
//a null argument would be improper, so don't allow current thread to execute rest of function
if(conditionLock == NULL){
printf("Argument passed to Condition::Wait() was null, returning without performing wait\n");
(void) interrupt->SetLevel(oldLevel);
return;
}
//set the current lock for the condition variable if we don't already remember it
if(waitingLock == NULL){
waitingLock = conditionLock;
}
//check that the lock passed in is the lock associated with this CV. Otherwise, it would be improper
//to allow the thread to release the lock, and would mess up the semantics of the CV
if(conditionLock != waitingLock){
printf("Argument passed to Condition::Wait() for Condition %s was the incorrect lock, returning without performing wait\n", name);
(void) interrupt->SetLevel(oldLevel);
return;
}
if(!waitingLock->isHeldByCurrentThread()){
printf("Thread %s calling Wait() on Condition %s does not have lock\n", currentThread->getName(), name);
(void) interrupt->SetLevel(oldLevel);
return;
}
//OK to wait
conditionLock->Release(); //release lock
queue->Append((void *) currentThread);
currentThread->Sleep(); //will sleep. current thread will be not regain processor until it is at the front of queue
//and Signal is called on this CV
conditionLock->Acquire(); //reacquire lock before returning ensures mutual exclusivity until current thread manually releases lock
(void) interrupt->SetLevel(oldLevel); // re-enable interrupts (atomic operation finished)
}
void Condition::Signal(Lock* conditionLock) {
Thread *thread;
IntStatus oldLevel = interrupt->SetLevel(IntOff); // disable interrupts so this opertion is atomic
if(conditionLock == NULL){
printf("Argument passed to Condition::Signal() was null, returning without performing wait\n");
(void) interrupt->SetLevel(oldLevel);
return;
} //(can't be switch out
if(queue->IsEmpty()){
(void) interrupt->SetLevel(oldLevel); //restore interrupts (atomic operation done)
return; //don't need to worry if an extraneous call to signal, just return
}
if(waitingLock != conditionLock){ //check that it is the proper lock, otherwise the thread woken up will try
//to acquire a lock that may not be free and be blocked as a result
printf("Argument passed to Condition::Signal() for Condition %s was the incorrect lock, returning without performing wait\n", name);
(void) interrupt->SetLevel(oldLevel); //restore interrupts (atomic operation done)
return;
}
if(!waitingLock->isHeldByCurrentThread()){
printf("Thread %s calling Signal() on Condition %s does not have lock\n", currentThread->getName(), name);
(void) interrupt->SetLevel(oldLevel);
return;
}
thread = (Thread *) queue->Remove(); //get the next thread waiting on CV
scheduler->ReadyToRun(thread); //add to system's ready queue
if(queue->IsEmpty()){
waitingLock = NULL; //if queue is empty, we no longer need to remember a lock
//and can allow a different lock to be passed in on the next Wait
}
(void) interrupt->SetLevel(oldLevel); // re-enable interrupts
}
void Condition::Broadcast(Lock* conditionLock) {
IntStatus oldLevel = interrupt->SetLevel(IntOff);
if(conditionLock == NULL){
printf("Argument passed to Condition::Broadcast() was null, returning without performing operation\n");
(void) interrupt->SetLevel(oldLevel);
return;
}
if(queue->IsEmpty()){
(void) interrupt->SetLevel(oldLevel); //restore interrupts (atomic operation done)
return; //don't need to worry if an extraneous call to signal, just return
}
if(waitingLock != conditionLock){ //check that it is the proper lock, otherwise the thread woken up will try
//to acquire a lock that may not be free and be blocked as a result
printf("Argument passed to Condition::Broadcast() for condition %s was the incorrect lock, returning without performing opeartion\n", name);
(void) interrupt->SetLevel(oldLevel); //restore interrupts (atomic operation done)
return;
}
if(!waitingLock->isHeldByCurrentThread()){
printf("Thread %s calling Signal() on Condition %s does not have lock\n", currentThread->getName(), name);
(void) interrupt->SetLevel(oldLevel);
return;
}
while(!queue->IsEmpty()) Signal(conditionLock); //all operations we need are in Signal, just need to call over and over
(void) interrupt->SetLevel(oldLevel);
}
//#ifdef CHANGED
bool Condition::hasWaiting(){
if(queue->IsEmpty()){
return false;
}
else{
return true;
}
}
//#endif
ServerCondition::ServerCondition(char* debugName) {
name = debugName;
queue = new List;
waitingLock = -1;
}
ServerCondition::~ServerCondition() {
delete queue;
}
ClientRequest* ServerCondition::Wait(int serverConditionLock, ClientRequest* cr) {
IntStatus oldLevel = interrupt->SetLevel(IntOff); // disable interrupts so this operation is atomic
//(can't be switched out)
//a null argument would be improper, so don't allow current thread to execute rest of function
//set the current lock for the ServerCondition variable if we don't already remember it
if(waitingLock == -1){
waitingLock = serverConditionLock;
}
//check that the lock passed in is the lock associated with this CV. Otherwise, it would be improper
//to allow the thread to release the lock, and would mess up the semantics of the CV
if(serverConditionLock != waitingLock){
printf("Argument passed to ServerCondition::Wait() for ServerCondition %s was the incorrect lock, returning without performing wait\n", name);
(void) interrupt->SetLevel(oldLevel);
cr->respond = true;
return cr;
}
//OK to wait
queue->Append((void *) cr);
//must find server equivalent of following line:
//ServerConditionLock->Acquire(); //reacquire lock before returning ensures mutual exclusivity until current thread manually releases lock
(void) interrupt->SetLevel(oldLevel); // re-enable interrupts (atomic operation finished)
return cr;
}
ClientRequest* ServerCondition::Signal(int ServerConditionLock, ClientRequest* cr) {
IntStatus oldLevel = interrupt->SetLevel(IntOff); // disable interrupts so this opertion is atomic //(can't be switch out
if(queue->IsEmpty()){
(void) interrupt->SetLevel(oldLevel); //restore interrupts (atomic operation done)
cr->respond = false;
return cr; //don't need to worry if an extraneous call to signal, just return
}
if(waitingLock != ServerConditionLock){ //check that it is the proper lock, otherwise the thread woken up will try
//to acquire a lock that may not be free and be blocked as a result
printf("Argument passed to ServerCondition::Signal() for ServerCondition %s was the incorrect lock, returning without performing wait\n", name);
(void) interrupt->SetLevel(oldLevel); //restore interrupts (atomic operation done)
cr->respond = false;
return cr;
}
delete cr;
cr = (ClientRequest *) queue->Remove(); //get the next thread waiting on CV
if(queue->IsEmpty()){
waitingLock = -1; //if queue is empty, we no longer need to remember a lock
//and can allow a different lock to be passed in on the next Wait
}
(void) interrupt->SetLevel(oldLevel); // re-enable interrupts
cr->respond = true;
return cr;
}
/**Dont' use
ClientRequest* ServerCondition::Broadcast(Lock* ServerConditionLock client) {
IntStatus oldLevel = interrupt->SetLevel(IntOff);
if(ServerConditionLock == NULL){
printf("Argument passed to ServerCondition::Broadcast() was null, returning without performing operation\n");
(void) interrupt->SetLevel(oldLevel);
return;
}
if(queue->IsEmpty()){
(void) interrupt->SetLevel(oldLevel); //restore interrupts (atomic operation done)
return; //don't need to worry if an extraneous call to signal, just return
}
if(waitingLock != conditionLock){ //check that it is the proper lock, otherwise the thread woken up will try
//to acquire a lock that may not be free and be blocked as a result
printf("Argument passed to Condition::Broadcast() for condition %s was the incorrect lock, returning without performing opeartion\n", name);
(void) interrupt->SetLevel(oldLevel); //restore interrupts (atomic operation done)
return;
}
if(!waitingLock->isHeldByCurrentThread()){
printf("Thread %s calling Signal() on Condition %s does not have lock\n", currentThread->getName(), name);
(void) interrupt->SetLevel(oldLevel);
return;
}
while(!queue->IsEmpty()) Signal(conditionLock); //all operations we need are in Signal, just need to call over and over
(void) interrupt->SetLevel(oldLevel);
}
*/
//#ifdef CHANGED
bool ServerCondition::hasWaiting(){
if(queue->IsEmpty()){
return false;
}
else{
return true;
}
}
//#endif
| true |
862761f48ea2334647af3e4c85c70b236f76ab0f | C++ | WZH-moyu/wuzhihu- | /10-19/test.cpp | UTF-8 | 337 | 3 | 3 | [] | no_license | #include<iostream>
#include<vector>
using namespace std;
void Func(int n,int m)
{
vector<int>v;
int num=n;
int ret=0;
while(num>0)
{
ret=num%m;
v.insert(v.begin(),ret);
num/=m;
}
for(int i=0;i<v.size();i++)
{
cout<<v[i];
}
cout<<endl;
}
int main()
{
int n,m;
cin>>n>>m;
Func(n,m);
return 0;
}
| true |
e120304ad51a83f5275e1217252af65fac4fca73 | C++ | celerity/celerity-runtime | /vendor/allscale/api/core/impl/reference/lock.h | UTF-8 | 5,978 | 2.953125 | 3 | [
"MIT"
] | permissive | #pragma once
#include <atomic>
#include <thread>
#if defined _MSC_VER
// required for YieldProcessor macro
#define NOMINMAX
#include "windows.h"
//#elif defined (__ppc64__) || defined (_ARCH_PPC64)
#endif
namespace allscale {
namespace api {
namespace core {
inline namespace simple {
/* Pause instruction to prevent excess processor bus usage */
#ifdef _MSC_VER
#define cpu_relax() YieldProcessor()
#elif defined (__ppc64__) || defined (_ARCH_PPC64)
#define __barrier() __asm__ volatile("": : :"memory")
#define __HMT_low() __asm__ volatile("or 1,1,1 # low priority")
#define __HMT_medium() __asm__ volatile("or 2,2,2 # medium priority")
#define cpu_relax() do { __HMT_low(); __HMT_medium(); __barrier(); } while (0)
#else
#define cpu_relax() __builtin_ia32_pause()
#endif
class Waiter {
int i;
public:
Waiter() : i(0) {}
void operator()() {
++i;
if ((i % 1000) == 0) {
// there was no progress => let others work
std::this_thread::yield();
} else {
// relax this CPU
cpu_relax();
}
}
};
class SpinLock {
std::atomic<int> lck;
public:
SpinLock() : lck(0) {
}
void lock() {
Waiter wait;
while(!try_lock()) wait();
}
bool try_lock() {
int should = 0;
return lck.compare_exchange_weak(should, 1, std::memory_order_acquire);
}
void unlock() {
lck.store(0, std::memory_order_release);
}
};
/**
* An optimistic read/write lock.
*/
class OptimisticReadWriteLock {
/**
* The type utilized for the version numbering.
*/
using version_t = std::size_t;
/**
* The version number.
* - even: there is no write in progress
* - odd: there is a write in progress, do not allow read operations
*/
std::atomic<version_t> version;
public:
/**
* The lease utilized to link start and end of read phases.
*/
class Lease {
friend class OptimisticReadWriteLock;
version_t version;
public:
Lease(version_t version = 0) : version(version) {}
Lease(const Lease& lease) = default;
Lease& operator=(const Lease& other) = default;
Lease& operator=(Lease&& other) = default;
};
OptimisticReadWriteLock() : version(0) {}
/**
* Starts a read phase, making sure that there is currently no
* active concurrent modification going on. The resulting lease
* enables the invoking process to later-on verify that no
* concurrent modifications took place.
*/
Lease start_read() {
Waiter wait;
// get a snapshot of the lease version
auto v = version.load(std::memory_order_acquire);
// spin while there is a write in progress
while((v & 0x1) == 1) {
// wait for a moment
wait();
// get an updated version
v = version.load(std::memory_order_acquire);
}
// done
return Lease(v);
}
/**
* Tests whether there have been concurrent modifications since
* the given lease has been issued.
*
* @return true if no updates have been conducted, false otherwise
*/
bool validate(const Lease& lease) {
// check whether version number has changed in the mean-while
return lease.version == version.load(std::memory_order_consume);
}
/**
* Ends a read phase by validating the given lease.
*
* @return true if no updates have been conducted since the
* issuing of the lease, false otherwise
*/
bool end_read(const Lease& lease) {
// check lease in the end
return validate(lease);
}
/**
* Starts a write phase on this lock be ensuring exclusive access
* and invalidating any existing read lease.
*/
void start_write() {
Waiter wait;
// set last bit => make it odd
auto v = version.fetch_or(0x1, std::memory_order_acquire);
// check for concurrent writes
while((v & 0x1) == 1) {
// wait for a moment
wait();
// get an updated version
v = version.fetch_or(0x1, std::memory_order_acquire);
}
// done
}
/**
* Tries to start a write phase unless there is a currently ongoing
* write operation. In this case no write permission will be obtained.
*
* @return true if write permission has been granted, false otherwise.
*/
bool try_start_write() {
auto v = version.fetch_or(0x1, std::memory_order_acquire);
return !(v & 0x1);
}
/**
* Updates a read-lease to a write permission by a) validating that the
* given lease is still valid and b) making sure that there is no currently
* ongoing write operation.
*
* @return true if the lease was still valid and write permissions could
* be granted, false otherwise.
*/
bool try_upgrade_to_write(const Lease& lease) {
auto v = version.fetch_or(0x1, std::memory_order_acquire);
// check whether write privileges have been gained
if (v & 0x1) return false;// there is another writer already
// check whether there was no write since the gain of the read lock
if (lease.version == v) return true;
// if there was, undo write update
abort_write();
// operation failed
return false;
}
/**
* Aborts a write operation by reverting to the version number before
* starting the ongoing write, thereby re-validating existing leases.
*/
void abort_write() {
// reset version number
version.fetch_sub(1,std::memory_order_release);
}
/**
* Ends a write operation by giving up the associated exclusive access
* to the protected data and abandoning the provided write permission.
*/
void end_write() {
// update version number another time
version.fetch_add(1,std::memory_order_release);
}
/**
* Tests whether currently write permissions have been granted to any
* client by this lock.
*
* @return true if so, false otherwise
*/
bool is_write_locked() const {
return version & 0x1;
}
};
} // end namespace simple
} // end namespace core
} // end namespace api
} // end namespace allscale
| true |
4191a666d20c04e0bfcb7f456823b35d1cebe9ca | C++ | XiangDeMei/Algorithm | /算法设计思想/Trie树变形hdu2846.cpp | WINDOWS-1252 | 1,639 | 3.0625 | 3 | [] | no_license | /*
Trie
http://acm.hdu.edu.cn/showproblem.php?pid=2846
*/
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <algorithm>
#include <vector>
#include <stack>
#include <queue>
#include <functional>
#include <iostream>
#include <string>
#include <map>
#include <set>
using namespace std;
#define MAX 26
#define MAXN 1000000
typedef struct TrieNode
{
int nCount;
int id;
struct TrieNode *next[MAX];
} TrieNode;
TrieNode Memory[MAXN];
int allocp = 0;
TrieNode * createTrieNode()
{
TrieNode * tmp = &Memory[allocp++];
tmp->nCount = 1;
tmp->id = -1;
for (int i = 0; i < MAX; i++)
tmp->next[i] = NULL;
return tmp;
}
void insertTrie(TrieNode ** pRoot, char * str, int num)
{
TrieNode * tmp = *pRoot;
int i = 0, k;
while (str[i])
{
k = str[i] - 'a';
if (tmp->next[k])
{
if(tmp->next[k]->id!=num){
tmp->next[k]->nCount++;
tmp->next[k]->id = num;
}
}
else
{
tmp->next[k] = createTrieNode();
tmp->next[k]->id = num;
}
tmp = tmp->next[k];
i++;
}
}
int searchTrie(TrieNode * root, char * str)
{
if (root == NULL)
return 0;
TrieNode * tmp = root;
int i = 0, k;
while (str[i])
{
k = str[i] - 'a';
if (tmp->next[k])
{
tmp = tmp->next[k];
}
else
return 0;
i++;
}
return tmp->nCount;
}
int main(void)
{
char s[21];
int i,n,m,l;
TrieNode *Root = createTrieNode();
scanf("%d",&n);
while (n--)
{
scanf("%s",s);
l=strlen(s);
for(i=0;i<l;i++)
{
insertTrie(&Root, s+i,n+1);
}
}
scanf("%d",&m);
while (m--)
{
scanf("%s",s);
printf("%d\n", searchTrie(Root, s));
}
return 0;
}
| true |
5961c81c225c6bdddb3943b42702896bffc9cde3 | C++ | DICL/VeloxMR | /src/blocknode/block_node.cc | UTF-8 | 2,726 | 2.796875 | 3 | [
"Apache-2.0"
] | permissive | // includes & usings {{{
#include "block_node.hh"
using namespace eclipse;
using namespace eclipse::messages;
using namespace eclipse::network;
using namespace std;
// }}}
namespace eclipse {
// Constructor & destructor {{{
BlockNode::BlockNode (ClientHandler* net) : Node () {
network = net;
network_size = context.settings.get<vec_str>("network.nodes").size();
}
BlockNode::~BlockNode() { }
// }}}
// replicate_message {{{
//! @brief Compute the right and left node of the current node
//! and send its replicas of the given block
void BlockNode::replicate_message(IOoperation* m) {
vector<int> nodes;
for (int i=1; i < 3; i++) {
if(i%2 == 1) {
nodes.push_back ((id + (i+1)/2 + network_size) % network_size);
} else {
nodes.push_back ((id - i/2 + network_size) % network_size);
}
}
network->send_and_replicate(nodes, m);
}
// }}}
// block_insert_local {{{
//! @brief This method insert the block locally and replicated it.
bool BlockNode::block_insert_local(Block& block, bool replicate) {
local_io.write(block.first, block.second);
if (replicate) {
INFO("[DFS] Saving locally BLOCK: %s", block.first.c_str());
IOoperation io;
io.operation = messages::IOoperation::OpType::BLOCK_INSERT_REPLICA;
io.block = move(block);
replicate_message(&io);
} else {
INFO("[DFS] Saving replica locally BLOCK: %s", block.first.c_str());
}
return true;
}
// }}}
// block_read_local {{{
//! @brief This method read the block locally.
bool BlockNode::block_read_local(Block& block, uint64_t off, uint64_t len, bool ignore_params) {
INFO("BLOCK REQUEST: %s", block.first.c_str());
block.second = local_io.read(block.first, off, len, ignore_params);
return true;
}
// }}}
// block_delete_local {{{
//! @brief This method read the block locally.
bool BlockNode::block_delete_local(Block& block, bool replicate) {
local_io.remove(block.first);
INFO("[DFS] Removed locally BLOCK: %s", block.first.c_str());
if (replicate) {
IOoperation io;
io.operation = messages::IOoperation::OpType::BLOCK_DELETE_REPLICA;
io.block = move(block);
replicate_message(&io);
}
return true;
}
// }}}
// block_update_local {{{
bool BlockNode::block_update_local(Block& block, uint32_t pos, uint32_t len, bool replicate) {
local_io.update(block.first, block.second, pos, len);
if (replicate) {
INFO("Block %s updated real host", block.first.c_str());
IOoperation io;
io.operation = messages::IOoperation::OpType::BLOCK_UPDATE_REPLICA;
io.pos = pos;
io.length = len;
io.block = move(block);
replicate_message(&io);
} else {
INFO("Block replica %s updated real host", block.first.c_str());
}
return true;
}
// }}}
}
| true |
26173075a08afa53bb68225eacbccbd09b5f7cde | C++ | lowsfish/OI | /wikioi/1039数的划分.cpp | UTF-8 | 736 | 2.53125 | 3 | [] | no_license | #include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int tot=0;
int n,k;
int dp[250][10];
/*void dfs(int sum,int last,int cur)
{
if(cur>k || sum>n) return;
if(cur==k)
{
if(sum==n)
{
++tot;
//for(int i=1;i<=k;++i) cout<<ans[i]<<' ';
//cout<<endl;
}
}
else
{
for(int i=last;i<=n;++i)
{
if(sum+i>n || (k-cur-1!=0 && (n-sum-i)/(k-cur-1)<1)) break;
dfs(sum+i,i,cur+1);
}
}
}
*/
int main()
{
//freopen("1.in","r",stdin);
cin>>n>>k;
dp[0][0]=1;
for(int i=1;i<=n;++i)
{
dp[i][1]=1;
}
for(int i=1;i<=n;++i)
for(int j=1;j<=i&&j<=k;++j)
{
dp[i][j]=dp[i-j][j]+dp[i-1][j-1];
}
/*for(int i=1;i<=n/k;++i)
{
dfs(i,i,1);
}
cout<<tot<<endl;*/
cout<<dp[n][k];
return 0;
}
| true |
1f50e939a376f0a4683f3585f05129a1296bc65c | C++ | easyproger/3dengine | /XMathBase.cpp | UTF-8 | 3,112 | 3 | 3 | [] | no_license | //
// XMathBase.cpp
//
//
// Created by easy proger on 02.09.14.
// Copyright (c) 2014 easy proger. All rights reserved.
//
#include "XMathBase.h"
using namespace std;
const char digit_pairs[201] = {
"00010203040506070809"
"10111213141516171819"
"20212223242526272829"
"30313233343536373839"
"40414243444546474849"
"50515253545556575859"
"60616263646566676869"
"70717273747576777879"
"80818283848586878889"
"90919293949596979899"
};
void itostr(int n, char* c) {
int sign = -(n<0);
unsigned int val = (n^sign)-sign;
int size;
if(val>=10000) {
if(val>=10000000) {
if(val>=1000000000) {
size=10;
}
else if(val>=100000000) {
size=9;
}
else size=8;
}
else {
if(val>=1000000) {
size=7;
}
else if(val>=100000) {
size=6;
}
else size=5;
}
}
else {
if(val>=100) {
if(val>=1000) {
size=4;
}
else size=3;
}
else {
if(val>=10) {
size=2;
}
else if(n==0) {
c[0]='0';
c[1] = '\0';
return;
}
else size=1;
}
}
size -= sign;
if(sign)
*c='-';
c += size-1;
while(val>=100) {
int pos = val % 100;
val /= 100;
*(short*)(c-1)=*(short*)(digit_pairs+2*pos);
c-=2;
}
while(val>0) {
*c--='0' + (val % 10);
val /= 10;
}
c[size+1] = '\0';
}
void itostr(unsigned val, char* c)
{
int size;
if(val>=10000)
{
if(val>=10000000)
{
if(val>=1000000000)
size=10;
else if(val>=100000000)
size=9;
else
size=8;
}
else
{
if(val>=1000000)
size=7;
else if(val>=100000)
size=6;
else
size=5;
}
}
else
{
if(val>=100)
{
if(val>=1000)
size=4;
else
size=3;
}
else
{
if(val>=10)
size=2;
else if (val==0) {
c[0]='0';
c[1] = '\0';
return;
}
else
size=1;
}
}
c += size-1;
while(val>=100)
{
int pos = val % 100;
val /= 100;
*(short*)(c-1)=*(short*)(digit_pairs+2*pos);
c-=2;
}
while(val>0)
{
*c--='0' + (val % 10);
val /= 10;
}
c[size+1] = '\0';
}
std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim)) {
elems.push_back(item);
}
return elems;
}
| true |
68b6d99644605b0f2e230765406f2ff118bd5d0b | C++ | Chris0016/School-Management-System | /School Sys/Managers/Club_Manager.h | UTF-8 | 558 | 2.875 | 3 | [] | no_license | //#include "../Ref.cpp"
using namespace std;
#ifndef __CLUB_MANAGER__
#define __CLUB_MANAGER__
class Club_Manager{
private:
static const int MAX_CLUB_AMOUNT = 10;
Club listOfClubs[MAX_CLUB_AMOUNT];
int numberOfClubs = 0;
public:
Club_Manager();
void removeFromList(int idx);
void printClubs();
int findClub(string clubName);
int addClub(Club clubIn);
int removeClub(string clubName);
Club getClub(string clubName);
int getNumberOfClubs();
bool clubExist(Club inputClub);
bool clubExist_byName(string clubName);
};
#endif | true |
cf7563d6eef7dec05bfdcaae82480fb4069503bb | C++ | arthurfeeney/nn | /include/Initializer/kaiming_uniform.hpp | UTF-8 | 626 | 2.53125 | 3 | [] | no_license |
#ifndef KAIMING_UNIFORM_HPP
#define KAIMING_UNIFORM_HPP
#include <cmath>
#include "init_aux.hpp"
namespace init {
template<typename Weights, typename Weight>
void kaiming_uniform(Weights& w, size_t fan_in, size_t fan_out,
double gain = 1, double a = 0)
{
double denom = (1.0 + a*a) * static_cast<double>(fan_in);
double inner = 6.0 / denom;
double bound = std::sqrt(inner);
rand::UniformRand<Weight> init(-bound, bound);
for(size_t i = 0; i < w.size(); ++i) {
for(size_t j = 0; j < w[i].size(); ++j) {
w[i][j] = init();
}
}
}
} // init
#endif
| true |
11bd74dce272b7b8fe9004ca0db9bed0e4887608 | C++ | rushioda/PIXELVALID_athena | /athena/Calorimeter/CaloEvent/test/CaloTowerSeg_test.cxx | UTF-8 | 6,673 | 2.625 | 3 | [] | no_license | /*
Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
*/
// $Id$
/**
* @file CaloTowerSeg_test.cxx
* @author scott snyder <snyder@bnl.gov>
* @date Jul, 2013
* @brief Component test for CaloTowerSeg.
*/
#undef NDEBUG
#include "CaloEvent/CaloTowerSeg.h"
#include <vector>
#include <cstdio>
#include <iostream>
#include <cmath>
#include <cassert>
using std::printf;
bool comp (double x1, double x2, double thresh = 1e-6)
{
double den = std::abs(x1) + std::abs(x2);
if (den == 0) return true;
double num = std::abs (x1 - x2);
return num / den < thresh;
}
// Null constructor
void test1()
{
std::cout << "test1\n";
CaloTowerSeg seg1;
assert (seg1.neta() == 0);
assert (seg1.nphi() == 0);
assert (seg1.deta() == 0);
assert (seg1.dphi() == 0);
assert (seg1.etamin() == 0);
assert (seg1.etamax() == 0);
assert (seg1.phimin() == 0);
assert (seg1.phimax() == 0);
}
// Window with no phi wrapping
void test2()
{
typedef CaloTowerSeg::index_t index_t;
index_t outOfRange = CaloTowerSeg::outOfRange;
std::cout << "test2\n";
CaloTowerSeg seg (10, 10, 0, 1, -1, 1);
assert (seg.neta() == 10);
assert (seg.nphi() == 10);
assert (seg.deta() == 0.1);
assert (seg.dphi() == 0.2);
assert (seg.etamin() == 0);
assert (seg.etamax() == 1);
assert (seg.phimin() == -1);
assert (seg.phimax() == 1);
assert ( seg.inbound ((index_t)1, (index_t)1));
assert ( seg.inbound ((index_t)10, (index_t)10));
assert ( seg.inbound ((index_t)6, (index_t)3));
assert (!seg.inbound ((index_t)6, (index_t)0));
assert (!seg.inbound ((index_t)6, (index_t)11));
assert (!seg.inbound ((index_t)0, (index_t)3));
assert (!seg.inbound ((index_t)11, (index_t)3));
assert ( seg.inbound ( 0.0, -1.0));
assert ( seg.inbound ( 1.0, 1.0));
assert ( seg.inbound ( 0.3, 0.2));
assert (!seg.inbound (-0.1, 0.2));
assert (!seg.inbound ( 0.3, -1.1));
assert (!seg.inbound ( 0.3, 1.1));
assert (seg.etaphi (1, 1) == 0);
assert (seg.etaphi (3, 4) == 23);
assert (seg.etaphi (3, 11) == outOfRange);
assert (seg.etaIndex ((index_t)23) == 3);
assert (seg.etaIndex ((index_t)0) == 1);
assert (seg.phiIndex ((index_t)23) == 4);
assert (seg.phiIndex ((index_t)0) == 1);
assert (seg.eta (3) == 0.25);
assert (seg.phi (3) == -0.5);
assert (std::abs (seg.phi (7) - 0.3) < 1e-12);
assert (seg.etaIndex (0.25) == 3);
assert (seg.etaIndex (-1.0) == outOfRange);
assert (seg.etaIndex (1.1) == outOfRange);
assert (seg.phiIndex (-0.5) == 3);
assert (seg.phiIndex (0.3) == 7);
assert (seg.phiIndex (-1.1) == outOfRange);
assert (seg.phiIndex (1.1) == outOfRange);
}
// Window with phi wrapping
void test3()
{
std::cout << "test3\n";
typedef CaloTowerSeg::index_t index_t;
index_t outOfRange = CaloTowerSeg::outOfRange;
double phimin = M_PI - 5*0.2;
double phimax = -M_PI + 5*0.2;
CaloTowerSeg seg (10, 10, 0, 1, phimin, phimax);
assert (seg.neta() == 10);
assert (seg.nphi() == 10);
assert (seg.deta() == 0.1);
assert (comp (seg.dphi(), 0.2));
assert (seg.etamin() == 0);
assert (seg.etamax() == 1);
assert (seg.phimin() == phimin);
assert (seg.phimax() == phimax);
assert ( seg.inbound ((index_t)1, (index_t)1));
assert ( seg.inbound ((index_t)10, (index_t)10));
assert ( seg.inbound ((index_t)6, (index_t)3));
assert (!seg.inbound ((index_t)6, (index_t)0));
assert (!seg.inbound ((index_t)6, (index_t)11));
assert (!seg.inbound ((index_t)0, (index_t)3));
assert (!seg.inbound ((index_t)11, (index_t)3));
assert ( seg.inbound ( 0.0, phimin));
assert ( seg.inbound ( 1.0, phimax));
assert ( seg.inbound ( 0.3, 3.1));
assert (!seg.inbound (-0.1, 3.1));
assert (!seg.inbound ( 0.3, 2.0));
assert (!seg.inbound ( 0.3, -2.0));
assert (seg.etaphi (1, 1) == 0);
assert (seg.etaphi (3, 4) == 23);
assert (seg.etaphi (3, 11) == outOfRange);
assert (seg.etaIndex ((index_t)23) == 3);
assert (seg.etaIndex ((index_t)0) == 1);
assert (seg.phiIndex ((index_t)23) == 4);
assert (seg.phiIndex ((index_t)0) == 1);
assert (seg.eta (3) == 0.25);
assert (std::abs (seg.phi (3) - M_PI + 0.5) < 1e-12);
assert (std::abs (seg.phi (7) + M_PI - 0.3) < 1e-12);
assert (seg.etaIndex (0.25) == 3);
assert (seg.etaIndex (-1.0) == outOfRange);
assert (seg.etaIndex (1.1) == outOfRange);
assert (seg.phiIndex (-0.5 + M_PI) == 3);
assert (seg.phiIndex ( 0.3 - M_PI) == 7);
assert (seg.phiIndex (-2.0) == outOfRange);
assert (seg.phiIndex (2.0) == outOfRange);
}
// Subseg tests
void test4()
{
std::cout << "test4\n";
CaloTowerSeg seg (50, 64, -2.5, 2.5);
CaloTowerSeg::SubSeg subseg1 = seg.subseg (0.7, 0.3, -0.2, 0.4);
assert (subseg1.etamin() == 30);
assert (subseg1.etamax() == 35);
assert (subseg1.phimin() == 26);
assert (subseg1.phimax() == 35);
assert (subseg1.neta() == 6);
assert (subseg1.nphi() == 10);
assert (subseg1.size() == 60);
CaloTowerSeg seg1 = subseg1.segmentation();
assert (comp (seg1.etamin(), 0.4));
assert (comp (seg1.etamax(), 1.0));
assert (comp (seg1.phimin(), 25*M_PI/32 - M_PI));
assert (comp (seg1.phimax(), 35*M_PI/32 - M_PI));
assert (seg1.neta() == 6);
assert (seg1.nphi() == 10);
CaloTowerSeg::SubSeg subseg2 = seg.subseg (0.7, 0.3, 3.1, 0.4);
assert (subseg2.etamin() == 30);
assert (subseg2.etamax() == 35);
assert (subseg2.phimin() == 60);
assert (subseg2.phimax() == 4);
assert (subseg2.neta() == 6);
assert (subseg2.nphi() == 9);
assert (subseg2.size() == 54);
CaloTowerSeg seg2 = subseg2.segmentation();
assert (comp (seg2.etamin(), 0.4));
assert (comp (seg2.etamax(), 1.0));
assert (comp (seg2.phimin(), 59*M_PI/32 - M_PI));
assert (comp (seg2.phimax(), 4*M_PI/32 - M_PI));
assert (seg2.neta() == 6);
assert (seg2.nphi() == 9);
}
void test5a (const std::vector<int>& tows,
const CaloTowerSeg::SubSeg& subseg)
{
typedef CaloTowerSeg::SubSegIterator<std::vector<int>::const_iterator>
tower_subseg_iterator;
tower_subseg_iterator it = tower_subseg_iterator::make (tows.begin(),
subseg);
size_t sz = subseg.size();
for (size_t i=0; i < sz; ++i, ++it) {
printf ("%2d %2d %d %d\n", *it, (int)it.itower(), *it/10, *it%10);
}
}
// SubSegIterator tests.
void test5()
{
std::cout << "test5\n";
std::vector<int> test_towers;
for (int i=0; i < 100; i++) test_towers.push_back(i);
CaloTowerSeg seg (10, 10, 0, 10);
test5a (test_towers, seg.subseg (5, 2, 0, 1));
printf ("\n");
test5a (test_towers, seg.subseg (5, 2, 3, 1));
}
int main()
{
test1();
test2();
test3();
test4();
test5();
return 0;
}
| true |
eadb9afcd4856ac23378201eaac7515b9885ad78 | C++ | stdstring/leetcode | /Algorithms/Tasks.0501.1000/0592.FractionAdditionSubtraction/solution.cpp | UTF-8 | 2,675 | 3.59375 | 4 | [
"MIT"
] | permissive | #include <string>
#include "gtest/gtest.h"
namespace
{
class Solution
{
public:
std::string fractionAddition(std::string const &expression) const
{
size_t index = 0;
int resultNumerator = 0;
int resultDenominator = 0;
readFraction(expression, index, resultNumerator, resultDenominator);
while (index < expression.size())
{
const char currentOp = expression[index++];
int numerator = 0;
int denominator = 0;
readFraction(expression, index, numerator, denominator);
resultNumerator = denominator * resultNumerator + (currentOp == '+' ? 1 : -1) * resultDenominator * numerator;
resultDenominator *= denominator;
if (resultNumerator == 0)
resultDenominator = 1;
else
{
const int gcd = calcGCD(resultNumerator, resultDenominator);
resultNumerator /= gcd;
resultDenominator /= gcd;
}
}
return std::to_string(resultNumerator) + "/" + std::to_string(resultDenominator);
}
private:
void readFraction(std::string const &expression, size_t &index, int &numerator, int &denominator) const
{
// read numerator
numerator = 0;
int numeratorSign = 1;
if (expression[index] == '-')
{
numeratorSign = -1;
++index;
}
while (expression[index] != '/')
numerator = 10 * numerator + (expression[index++] - '0');
numerator *= numeratorSign;
// read '/'
++index;
// read denominator
denominator = 0;
while (index < expression.size() && std::isdigit(expression[index]))
denominator = 10 * denominator + (expression[index++] - '0');
}
int calcGCD(int numerator, int denominator) const
{
int a = std::abs(numerator);
int b = std::abs(denominator);
if (a < b)
std::swap(a, b);
while (a % b != 0)
{
const int rest = a % b;
a = b;
b = rest;
}
return b;
}
};
}
namespace FractionAdditionSubtractionTask
{
TEST(TwoSumTaskTests, Examples)
{
const Solution solution;
ASSERT_EQ("0/1", solution.fractionAddition("-1/2+1/2"));
ASSERT_EQ("1/3", solution.fractionAddition("-1/2+1/2+1/3"));
ASSERT_EQ("-1/6", solution.fractionAddition("1/3-1/2"));
ASSERT_EQ("2/1", solution.fractionAddition("5/3+1/3"));
}
TEST(TwoSumTaskTests, FromWrongAnswers)
{
const Solution solution;
ASSERT_EQ("41/12", solution.fractionAddition("7/2+2/3-3/4"));
}
} | true |
a29e938fb68680b206f49b8243f21d108b3ff6a4 | C++ | GandT/learning | /C_C++/season4/p009-013/p010/p2.cpp | UTF-8 | 5,312 | 2.796875 | 3 | [] | no_license | /*
2016.10.25
OpenCV - マウス・コールバック処理演習
【参考文献】
福田 誠一郎, 勝元 甫(2016)「「OpenCV/OpenGLによる映像処理」 講義web 」,<http://www.nae-lab.org/b3exp/codes.html>
ロベール(2000)「第28章 静かなるメンバ」,<http://www7b.biglobe.ne.jp/~robe/cpphtml/html02/cpp02028.html>
OpenCV(発行年不明)「その他の画像変換」,<http://opencv.jp/opencv-2svn/cpp/miscellaneous_image_transformations.html>
OpenCV(発行年不明)「配列操作」,<http://opencv.jp/opencv-2.1/cpp/operations_on_arrays.html>
OpenCV(発行年不明)「基本構造体」,<http://opencv.jp/opencv-2.1/cpp/basic_structures.html>
OpenCV(発行年不明)「Operations on Arrays」,<http://docs.opencv.org/2.4.8/modules/core/doc/operations_on_arrays.html>
*/
#include <iostream>
#include <string>
#include <vector>
#include <cmath>
#include <opencv2/opencv.hpp>
//namespace宣言
using namespace std;
using namespace cv;
//各種define
#define IMG_WIN_NAME "image"
#define INPAINT_MODE 0
#define REVERSE_MODE 1
struct imgdata{
//画像変数
static Mat orig;
static Mat buff;
static Mat mask;
static Mat drawn;
//座標変数
static Point prevpt;
//フラグ変数
static int mode;
//画像作成
static bool init(string filename){
//画像読み込み
orig = imread(filename);
if(orig.empty()){
cerr << "エラー:" << filename << "が見つかりませんでした。";
return false;
}
//ほか実体作成
buff = orig.clone();
drawn = orig.clone();
mask.create(orig.size(), CV_8UC1);
//初期化
mask = Scalar(0);
drawn = Scalar(0);
mode = INPAINT_MODE;
return true;
}
//マウス入力処理
static void mouse(int event, int x, int y, int flags, void *){
//操作対象画像存在確認
if(buff.empty())return;
//ペイントモード
if(mode == INPAINT_MODE){
//右クリック開始時
if(event == CV_EVENT_LBUTTONDOWN){
//開始座標の設定
prevpt = Point(x,y);
}
//右クリック継続時
else if(flags & CV_EVENT_FLAG_LBUTTON){
//現在座標の取得
Point pt(x, y);
//開始点から現在点までマスクに直線を引く
line(mask, prevpt, pt, Scalar(255), 5, 8, 0);
line(buff, prevpt, pt, Scalar::all(255), 5, 8, 0);
//座標更新
prevpt = pt;
//描画
imshow(IMG_WIN_NAME, buff);
}
}
//反転モード
else if(mode == REVERSE_MODE){
//右クリック開始時
if(event == CV_EVENT_LBUTTONDOWN){
//開始座標の設定
prevpt = Point(x,y);
}
//右クリック終了時
else if(event == CV_EVENT_LBUTTONUP){
//終了座標の設定
Point pt(x,y);
//座標大小調整
int startx = pt.x<prevpt.x ? pt.x : prevpt.x;
int starty = pt.y<prevpt.y ? pt.y : prevpt.y;
int difx = abs(pt.x - prevpt.x);
int dify = abs(pt.y - prevpt.y);
//反転領域策定
Rect revrect(startx, starty, difx, dify);
mask = Scalar(0);
Mat rev = mask(revrect);
rev = Scalar(255);
//反転処理
buff.copyTo(drawn);
bitwise_not(buff, drawn, mask);
//描画
imshow("inpainted image", drawn);
//画像を保存
imwrite("output.jpg", drawn);
}
}
}
//画像リセット
static void reset()
{
//初期化
mask = Scalar(0);
orig.copyTo(buff);
//描画
imshow(IMG_WIN_NAME, buff);
}
//インペイント
static void inpainting()
{
//ウィンドウ用意
namedWindow("inpainted image", 1);
//インペイント処理
inpaint(buff, mask, drawn, 3.0, cv::INPAINT_TELEA);
//描画
imshow("inpainted image", drawn);
}
//反転処理
static void reversedraw()
{
}
};
Mat imgdata::orig;
Mat imgdata::buff;
Mat imgdata::mask;
Mat imgdata::drawn;
Point imgdata::prevpt;
int imgdata::mode;
int main(int argc, char *argv[])
{
//ファイルから画像を読み込む
string filename = (argc > 1) ? argv[1] : "fruits.jpg";
//画像実体の作成
if(!imgdata::init(filename))return 0;
//操作説明
cout << "【キー操作一覧(半角)】" << endl;
cout << "\t ESC/q - プログラムを終了" << endl;
cout << "\t i - インペイント(推測復元)処理" << endl;
cout << "\t r - 編集をリセット" << endl;
cout << "\t 0~1 - モード変更" << endl;
//ウィンドウ準備
namedWindow(IMG_WIN_NAME, 1);
//ウィンドウに画像表示
imshow(IMG_WIN_NAME, imgdata::buff);
//コールバック関数を登録(登録後は自動で呼び出される)
setMouseCallback(IMG_WIN_NAME, imgdata::mouse, 0);
//メインループ
bool loopfl = true;
while(loopfl){
//このあたりでコールバック関数が呼ばれた時は自動処理
//キーボード入力の受付
int keyinput = waitKey(0);
//キーボード入力で処理分岐
switch(keyinput){
//終了
case 27:
case 'q':
loopfl = false;
break;
//編集リセット
case 'r':
imgdata::reset();
break;
//インペイント処理
case 'i':
imgdata::inpainting();
break;
//モード変更
case '0': imgdata::mode = INPAINT_MODE; break;
case '1': imgdata::mode = REVERSE_MODE; break;
}
}
}
| true |
01e90ff12a8d9c73a17a92627e5b3ba7bc778699 | C++ | jamesptanner/arduino-arc-reactor | /decay.ino | UTF-8 | 3,848 | 2.828125 | 3 | [] | no_license | #include "decay.h"
#include "Arduino.h"
#include "MemoryFree.h"
void Decay::modeSetup()
{
setallPixels(0,0,0);
//init all animations so we dont have to deal with nulls in the first run.
for (int i = 0; i < PIXELCOUNT; i++)
{
pixelAnimation[i] = new Dead(m_pixel,i,true);
pixelAnimation[i]->animationSetup();
}
}
void Decay::run()
{
//step animations and then check for completed and replace.
for (int animationIndex = 0; animationIndex < PIXELCOUNT; animationIndex++)
{
pixelAnimation[animationIndex]->step();
if(pixelAnimation[animationIndex]==NULL ||!pixelAnimation[animationIndex]->isRunning())
{
// Serial.print("resetting animation ");
// Serial.println(animationIndex);
if(pixelAnimation[animationIndex]!=NULL)
{
delete pixelAnimation[animationIndex];
}
//time to replace. and setup.
m_pixel->setPixelColor(animationIndex,0,0,0);
int chance = random(0,chanceTotal-1);
for (int chanceIndex = 0; chanceIndex < chanceOptions; chanceIndex++)
{
// Serial.print("Using mode ");
// Serial.print("freeMemory()=");
// Serial.println(freeMemory());
if(chance < chances[chanceIndex]){
if(chanceIndex == 0){
//Serial.println("Dead");
pixelAnimation[animationIndex] = new Dead(m_pixel,animationIndex);
}
else if(chanceIndex == 1){
// Serial.println("Solid");
pixelAnimation[animationIndex] = new AnimSolid(m_pixel,animationIndex);
}
else if(chanceIndex == 2){
// Serial.println("pulse");
pixelAnimation[animationIndex] = new AnimPulse(m_pixel,animationIndex);
}
else if(chanceIndex == 3){
// Serial.println("pulse");
pixelAnimation[animationIndex] = new OnOff(m_pixel,animationIndex);
}
else {
//Serial.println("onoff")
pixelAnimation[animationIndex] = new Dead(m_pixel,animationIndex);
}
pixelAnimation[animationIndex]->animationSetup();
break;
}
else chance -= chances[chanceIndex];
}
}
}
m_pixel->show();
delay(1);
}
void Animation::step()
{
animationStep();
frame++;
if (frame >= duration)
{
running = false;
}
}
void Dead::animationSetup(){}
void Dead::animationStep(){m_pixel->setPixelColor(m_pixelId, 0,0,0);}
void AnimSolid::animationSetup(){}
void AnimSolid::animationStep(){
m_pixel->setPixelColor(m_pixelId, 30,0,0);
}
void OnOff::animationSetup(){}
void OnOff::animationStep(){
if(frame % random(0,23) == 0)
{
m_pixel->setPixelColor(m_pixelId,random()%2 ? 40:0,0,0);
}
}
void AnimPulse::animationSetup(){}
void AnimPulse::animationStep(){
uint8_t currentFrame = frame % pulseDuration;
Colour sendColour = {};
uint8_t effectiveFrame = forwards ? currentFrame : pulseDuration - currentFrame;
sendColour.r = (int)(((float) maxColour.r / (float) pulseDuration) * (float) effectiveFrame);
sendColour.g = (int)(((float) maxColour.g / (float) pulseDuration) * (float) effectiveFrame);
sendColour.b = (int)(((float) maxColour.b / (float) pulseDuration) * (float) effectiveFrame);
m_pixel->setPixelColor(m_pixelId,sendColour.r,sendColour.g,sendColour.b);
if( currentFrame == pulseDuration - 1)
{
forwards = !forwards;
}
}
| true |
29b13fa1702b60a10fce62719a63bd960ad12d0e | C++ | nerzhul250/Marathons | /cppMarProg/AlmostPrimeNumbers/main.cpp | UTF-8 | 1,958 | 3.15625 | 3 | [] | no_license | #include <iostream>
#include <math.h>
#include <bitset> // compact STL for Sieve, better than vector<bool>!
#include <vector>
#include <algorithm>
using namespace std;
typedef vector<int> vi;
typedef long long ll;
ll _sieve_size; // ll is defined as: typedef long long ll;
bitset<1000010> bs; // 10^7 should be enough for most cases
vi primes; // compact list of primes in form of vector<int>
void sieve(ll upperbound) { // create list of primes in [0..upperbound]
_sieve_size = upperbound + 1; // add 1 to include upperbound
bs.set(); // set all bits to 1
bs[0] = bs[1] = 0; // except index 0 and 1
for (ll i = 2; i <= _sieve_size; i++) if (bs[i]) {
// cross out multiples of i starting from i * i!
for (ll j = i * i; j <= _sieve_size; j += i) bs[j] = 0;
primes.push_back((int)i); // add this prime to the list of primes
} } // call this method in main method
bool isPrime(ll N) { // a good enough deterministic prime tester
if (N <= _sieve_size) return bs[N]; // O(1) for small primes
for (int i = 0; i < (int)primes.size(); i++)
if (N % primes[i] == 0) return false;
return true; // it takes longer time if N is a large prime!
} // note: only work for N <= (last prime in vi "primes")^2
ll countNonPrimes(ll low, ll high){
ll sum=0;
for(int i=0;i<primes.size() && primes[i]*primes[i]<=high;i++){
int l=ceil(log2(low)/log2(primes[i]));
int r=floor(log2(high)/log2(primes[i]));
if(l<=r){
if(l==0){
sum+=r-1;
}else if(l==1){
sum+=r-l;
}else{
sum+=r-l+1;
}
}
}
return sum;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
sieve(1000000); // can go up to 10^7 (need few seconds)
int N;
cin >> N;
while(N--){
ll low, high;
cin >> low >> high;
if(low > high) swap(low,high);
cout << countNonPrimes(low,high) << "\n";
}
return 0;
}
| true |
f4714e743ed0f5af62f008114e9b40957636d15b | C++ | tchen-tt/ExtractSequence | /googlemap.cpp | UTF-8 | 961 | 2.78125 | 3 | [] | no_license | #include <Rcpp.h>
#include <string>
using namespace std;
using namespace Rcpp;
const char baseMap[2][2] = {'0', '1', '2', '3'};
// [[Rcpp::export]]
CharacterVector getTitle(int x, int y, int level)
{
// check bundary
if (level < 1)
{
Rcerr << "level must be unsigend int" << endl;
return "error";
}
if (x < 1 || x > (1 << level))
{
Rcerr << "x and y must be in [1, 2^level]" << endl;
return "error";
}
if (y < 1 || y > (1 << level))
{
Rcerr << "x and y must be in [1, 2^level]" << endl;
return "error";
}
// make index start with 0
int _x = x - 1;
int _y = y - 1;
string title;
for (int i = level; i > 0; i--)
{
int temple = 1 << (i-1);
int _xRage = _x / temple;
int _yRange = _y / temple;
title.push_back(baseMap[_xRage][_yRange]);
_x %= temple;
_y %= temple;
}
return title;
}
| true |
3abf72f5fcff53fa4b5acc0eb9f83d4391f90a05 | C++ | tomas-pluskal/masspp | /src/common-plugin-view/MagnifyingViewPlugin/MagnifyingViewOperation.cpp | SHIFT_JIS | 7,078 | 2.515625 | 3 | [] | no_license | /**
* @file MagnifyingViewOperation.cpp
* @brief interfaces of MagnifyingViewOperation class
*
* @author S.Tanaka
* @date 2012.04.02
*
* Copyright (C) 2014 Shimadzu Corporation All rights reserved.
*/
#include "stdafx.h"
#include "MagnifyingViewOperation.h"
#include "MagnifyingViewManager.h"
using namespace kome::view;
#include <crtdbg.h>
#ifdef _DEBUG
#define new new( _NORMAL_BLOCK, __FILE__, __LINE__ )
#define malloc( s ) _malloc_dbg( s, _NORMAL_BLOCK, __FILE__, __LINE__ )
#endif // _DEBUG
// constructor
MagnifyingViewOperation::MagnifyingViewOperation() {
m_spec = NULL;
m_idx = -1;
m_start = -1.0;
m_end = -1.0;
m_scale = -1.0;
}
// destructor
MagnifyingViewOperation::~MagnifyingViewOperation() {
}
// set the spectrum
void MagnifyingViewOperation::setSpectrum( kome::objects::Spectrum* spec ) {
m_spec = spec;
}
// get the spectrum
kome::objects::Spectrum* MagnifyingViewOperation::getSpectrum() {
return m_spec;
}
// set the scale index
void MagnifyingViewOperation::setScaleIndex( const int idx ) {
m_idx = idx;
}
// get the scale index
int MagnifyingViewOperation::getScaleIndex() {
return m_idx;
}
// set the range
void MagnifyingViewOperation::setRange( const double start, const double end ) {
m_start = start;
m_end = end;
}
// get the range start
double MagnifyingViewOperation::getRangeStart(){
return m_start;
}
// get the range end
double MagnifyingViewOperation::getRangeEnd() {
return m_end;
}
// set the scale
void MagnifyingViewOperation::setScale( const double scale ) {
m_scale = scale;
}
// get the scale
double MagnifyingViewOperation::getScale() {
return m_scale;
}
// get the description
std::string MagnifyingViewOperation::onGetDescription() {
// [Operation Log]
// Operation Log ŕ\镶쐬܂B
std::string s = FMT( "Magnify" );
if( m_spec != NULL ) {
s.append( FMT( " %s", m_spec->getName() ) );
}
if( m_scale < 0.0 ) { // NA
s.append( " [Clear]");
}
else {
s.append( FMT( " [Range:%.2f-%.2f, Scale:%.2f]", std::max( 0.0, m_start ), std::max( 0.0, m_end ), m_scale ) );
}
// [Operation Log]
// ͕̕ύXKvƎv܂B
// ō string IuWFNg͂̃\bhƏĂ܂̂
// Operation NXɃoϐăZbg邩
// ߂l const char* ł͂Ȃ string ɂǂ܂B
return s;
}
// gets the parameter string
std::string MagnifyingViewOperation::onGetParametersString() {
// [Operation Log]
// onExecute sēłl string 쐬܂B
std::string s;
if( m_spec != NULL ) {
s = FMT( "%d,%d,%d,%f,%f,%f", m_spec->getSample()->getSampleId(), m_spec->getOrgSpectrum()->getId(), m_idx, m_start, m_end, m_scale );
}
// [Operation Log]
// string retrun ɂĂ onGetDescription Ɠl
// ō string IuWFNg͂̃\bhƏĂ܂̂
// Operation NXɃoϐăZbg邩
// ߂l const char* ł͂Ȃ string ɂǂ܂B
return s;
}
// sets the parameter string
void MagnifyingViewOperation::onSetParametersString( const char* strParam ) {
// [Operation Log]
// 胁oϐ܂B
std::vector< std::string > tokens;
stringtoken( strParam, ",", tokens );
if( tokens.size() < 5 ) {
return;
}
// sample
kome::objects::Sample* sample = kome::objects::Sample::getSampleById( toint( tokens[0].c_str(), 10, -1 ) );
if( sample == NULL ){
return;
}
setTargetSample( sample );
// spectrum
int specId = toint( tokens[ 1 ].c_str(), 10, -1 );
m_spec = m_targetSample->getSpectrumById( specId );
if( m_spec == NULL ){
return;
}
// index
m_idx = toint( tokens[ 2 ].c_str(), 10, -1 );
m_start = todouble( tokens[ 3 ].c_str(), -1.0 );
m_end = todouble( tokens[ 4 ].c_str(), -1.0 );
m_scale = todouble( tokens[ 5 ].c_str(), -1.0 );
}
// save the condition
void MagnifyingViewOperation::onSaveCondition( boost::function< int ( void*, int ) > writeFun ) {
// [Operation Log]
// Undo, Redo ׂ̈ɏԂۑ܂B
MagnifyingViewManager& mgr = MagnifyingViewManager::getInstance();
unsigned int num = mgr.getNumberOfScaleInfo( m_spec );
writeFun( &num, sizeof( num ) );
for( unsigned int i = 0; i < num; i++ ) {
MagnifyingViewManager::ScaleInfo* scaleInfo = mgr.getScaleInfo( m_spec, i );
int id = scaleInfo->spec->getId();
writeFun( &id, sizeof( id ) );
writeFun( &( scaleInfo->minX ), sizeof( scaleInfo->minX ) );
writeFun( &( scaleInfo->maxX ), sizeof( scaleInfo->maxX ) );
writeFun( &( scaleInfo->scale ), sizeof( scaleInfo->scale ) );
}
}
// load the condition
void MagnifyingViewOperation::onLoadCondition( boost::function< int ( void*, int ) > readFun ) {
// [Operation Log]
// Undo, Redo Ȃ save condition ŕۑe܂B
MagnifyingViewManager& mgr = MagnifyingViewManager::getInstance();
mgr.clearScaleInfo( m_spec );
unsigned int num = 0;
readFun( &num, sizeof( num ) );
for( unsigned int i = 0; i < num; i++ ) {
int specId = int();
double start = double();
double end = double();
int scale = int();
int idx = int();
readFun( &specId, sizeof( specId ) );
readFun( &start, sizeof( start ) );
readFun( &end, sizeof( end ) );
readFun( &scale, sizeof( scale ) );
// spectrum
kome::objects::Spectrum* spec = m_targetSample->getSpectrumById( specId );
// add
MagnifyingViewManager::ScaleInfo* scaleInfo = mgr.addScaleInfo( spec, start, end );
scaleInfo->scale = scale;
}
}
// execute
bool MagnifyingViewOperation::onExecute() {
// [Operation Log]
// ۂ̏sȂ܂B
// saveCondition ͂ł͂Ȃ Operation::execute \bh̒
// sȂĂ܂B
MagnifyingViewManager& mgr = MagnifyingViewManager::getInstance();
// check parameters
if( m_spec == NULL ) {
LOG_ERROR( FMT( "Failed to get the spectrum." ) );
return false;
}
if( m_idx < 0 ) { // add
MagnifyingViewManager::ScaleInfo* scaleInfo = mgr.addScaleInfo( m_spec, m_start, m_end );
scaleInfo->scale = m_scale;
}
else { // update
if( m_scale < 0 ) { // delete
mgr.removeScaleInfo( m_spec, m_idx );
}
else { // edit
MagnifyingViewManager::ScaleInfo* scaleInfo = mgr.getScaleInfo( m_spec, m_idx );
if( scaleInfo == NULL ) {
LOG_ERROR( FMT( "Failed to get the scale information." ) );
return false;
}
scaleInfo->minX = m_start;
scaleInfo->maxX = m_end;
scaleInfo->scale = m_scale;
}
}
return true;
}
| true |
2214543296394185e8feb513637272a1cd6f8b8c | C++ | Altanbagana2003/STACK-C- | /c++queue.cpp | UTF-8 | 1,109 | 3.90625 | 4 | [] | no_license | #include <iostream>
using namespace std;
template<class T>
struct queue {
struct node {
T data;
node *next;
};
node *head;
node *tail;
int len;
queue() {
head = NULL;
tail = NULL;
len = 0;
}
void push (T data) {
node *p = new node;
p -> data = data;
if (tail == NULL) {
tail = p;
head = p;
} else {
tail -> next = p;
tail = p;
}
len++;
}
void pop () {
node *p = head;
head = head -> next;
delete p;
len--;
}
int size () {
return len;
}
T top() {
return head -> data;
}
bool isEmpty () {
if (len == 0) {
return true;
} else {
return false;
}
}
};
int main () {
queue<int> s;
s.push(10);
s.push(20);
s.push(30);
s.pop();
s.pop();
s.pop();
s.push(10);
s.push(20);
s.push(30);
cout << s.top() << endl;
s.pop();
cout << s.top() << endl;
return 0;
} | true |
731934b63bbfe2d010894e1643d963b5077126f4 | C++ | frequem/sage | /include/sage/util/EventDispatcher.h | UTF-8 | 1,412 | 2.59375 | 3 | [] | no_license | #ifndef _SAGE_EVENTDISPATCHER_H
#define _SAGE_EVENTDISPATCHER_H
#include <SDL2/SDL.h>
#include <map>
#include <utility>
#include <functional>
#include <sage/util/Events.h>
namespace sage{
class Application;
class Scene;
class Node;
class EventDispatcher{
public:
EventDispatcher(Application&);
template<typename Function>
int addEventHandler(Event, Scene&, Function&&);
template<typename Function>
int addEventHandler(Event, Function&&);
template<typename Function>
int addEventHandler(NodeEvent, Node&, Function&&);
void removeEventHandler(int);
void handleEvents();
void dispatchEvent(Event, void* args);
template<typename CheckFunction>
void dispatchEvent(NodeEvent, CheckFunction&&, void* args);
~EventDispatcher();
private:
Application* application;
int nextHandlerId = 0;
std::map<Event, std::map<int, std::pair<Scene*, std::function<void(void*)>>>> handlers;
std::map<NodeEvent, std::map<int, std::pair<Node*, std::function<void(void*)>>>> node_handlers;
SDL_Event sdlEvent;
int mouse_click_x = 0, mouse_click_y = 0;
int mouse_click_count = 0;
uint32_t mouse_click_time = 0;
bool mouse_down = false;
int mouse_down_button;
bool isInsideClickRadius(int, int);
bool isSceneMember(Scene*, Node*);
Scene* getActiveScene();
};
}
#include <sage/util/EventDispatcher.tpp>
#endif //_SAGE_EVENTDISPATCHER_H
| true |
26d460890c0d665ab0ff1f3f7edb77c0aa707767 | C++ | dimi1441/GestionEtudiant | /TP2044/Matiere.h | UTF-8 | 882 | 3.140625 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
class Matiere{
private:
string code_Mat;
string nom_Mat;
string code_Cl;
int coef;
public:
void setCode_Mat(string);
string getCode_Mat();
void setCode_Cl(string);
string getCode_Cl();
void setNom_Mat(string);
string getNom_Mat();
void setCoef(int);
int getCoef();
};
void Matiere::setCode_Mat(string code_Mat){
this->code_Mat=code_Mat;
}
string Matiere::getCode_Mat(){
return this->code_Mat;
}
void Matiere::setNom_Mat(string nom_Mat){
this->nom_Mat=nom_Mat;
}
string Matiere::getNom_Mat(){
return this->nom_Mat;
}
void Matiere::setCoef(int coef){
this->coef=coef;
}
int Matiere::getCoef(){
return this->coef;
}
void Matiere::setCode_Cl(string code_Cl){
this->code_Cl=code_Cl;
}
string Matiere::getCode_Cl(){
return this->code_Cl;
}
| true |
947324be4460c542732d12c6ee0366bf7e2c4510 | C++ | sauravchaudharysc/Programming | /Novice/Algorithm/Backtracking/sudokuSolver.cpp | UTF-8 | 2,115 | 3.46875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
bool canPlace(int mat[][9],int row,int col,int n,int number)
{
//To Check The Cell Entire Row And Entire column
for(int x=0;x<n;x++)
{
if(mat[x][col]==number||mat[row][x]==number)
{
return false;
}
}
int rn=sqrt(n);
int sx=(row/rn)*rn;
int sy=(col/rn)*rn;
for(int x=sx;x<sx+rn;x++)
{
for(int y=sy;y<sy+rn;y++)
{
if(mat[x][y]==number){
return false;
}
}
}
return true;
}
bool sudokuSolver(int mat[9][9],int row,int col,int n)
{
//Base case
if(row==n) //Row traversal is equal to n
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cout<<mat[i][j]<<" ";
}
cout<<endl;
}
cout<<endl;
return true;
}
//Case for row-end i.e reach the end of row by traversal of columns
if(col==n)
{
return sudokuSolver(mat,row+1,0,n);
}
//Skip the pre-filled Cell
if(mat[row][col]!=0)
{
return sudokuSolver(mat,row,col+1,n); //Just change the column
}
//Recursive Case
//Fill the current cell with possible option
for(int number=1;number<=n;number++)
{
if(canPlace(mat,row,col,n,number))
{
mat[row][col]=number;
bool rest_of_the_sudoku=sudokuSolver(mat,row,col+1,n); //Rest of the sudoku is solved
if(rest_of_the_sudoku)
{
return true;
}
}
}
mat[row][col]=0; //If the entire number is traversed and it cant be filled in the current cell. So backtrack it.
return false;
}
int main()
{
int mat[9][9] = {
{5,3,0,0,7,0,0,0,0},
{6,0,0,1,9,5,0,0,0},
{0,9,8,0,0,0,0,6,0},
{8,0,0,0,6,0,0,0,3},
{4,0,0,8,0,3,0,0,1},
{7,0,0,0,2,0,0,0,6},
{0,6,0,0,0,0,2,8,0},
{0,0,0,4,1,9,0,0,5},
{0,0,0,0,8,0,0,7,9}
};
cout<<sudokuSolver(mat,0,0,9)<<endl;
} | true |
55ac9d57e29867e41180a5cea3d9e0706ba184ae | C++ | qiujun-shenzhen/SeetaFace6-Lib | /build/include/orz/utils/log.h | UTF-8 | 4,637 | 2.671875 | 3 | [] | no_license | //
// Created by Lby on 2017/6/6.
//
#ifndef ORZ_UTILS_LOG_H
#define ORZ_UTILS_LOG_H
#include <iostream>
#include <sstream>
#include "format.h"
#include "except.h"
#include <cstring>
#undef NONE
#undef DEBUG
#undef STATUS
#undef INFO
#undef ERROR
#undef FATAL
#if ORZ_PLATFORM_OS_ANDROID
#include "android/log.h"
#define ANDROID_LOG_TAG "TensorStack"
#define ANDROID_LOG(LEVEL, ...) __android_log_print(LEVEL, ANDROID_LOG_TAG, __VA_ARGS__)
#define ANDROID_LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, ANDROID_LOG_TAG, __VA_ARGS__)
#define ANDROID_LOGI(...) __android_log_print(ANDROID_LOG_INFO, ANDROID_LOG_TAG, __VA_ARGS__)
#define ANDROID_LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, ANDROID_LOG_TAG, __VA_ARGS__)
#define ANDROID_LOGE(...) __android_log_print(ANDROID_LOG_ERROR, ANDROID_LOG_TAG, __VA_ARGS__)
#endif
namespace orz {
enum LogLevel {
NONE = 0,
DEBUG = 1,
STATUS = 2,
INFO = 3,
ERROR = 4,
FATAL = 5,
};
#if ORZ_PLATFORM_OS_ANDROID
inline android_LogPriority __android_log_level(LogLevel level) {
switch (level) {
default: return ANDROID_LOG_UNKNOWN;
case NONE: return ANDROID_LOG_VERBOSE;
case DEBUG: return ANDROID_LOG_DEBUG;
case STATUS: return ANDROID_LOG_INFO;
case INFO: return ANDROID_LOG_INFO;
case ERROR: return ANDROID_LOG_ERROR;
case FATAL: return ANDROID_LOG_FATAL;
}
}
#endif
extern LogLevel InnerGlobalLogLevel;
inline LogLevel GlobalLogLevel(LogLevel level) {
LogLevel pre_level = InnerGlobalLogLevel;
InnerGlobalLogLevel = level;
return pre_level;
}
inline LogLevel GlobalLogLevel() {
return InnerGlobalLogLevel;
}
class Log {
public:
Log(LogLevel level, std::ostream &log = std::cout)
: m_level(level), m_log(log) {
}
~Log() {
flush();
}
const std::string message() const {
return m_buffer.str();
}
template<typename T>
Log &operator()(const T &message) {
if (m_level >= InnerGlobalLogLevel) {
m_buffer << message;
}
return *this;
}
template<typename T>
Log &operator<<(const T &message) {
return operator()(message);
}
using Method = Log &(Log &);
Log &operator<<(Method method) {
if (m_level >= InnerGlobalLogLevel) {
return method(*this);
}
return *this;
}
void flush()
{
std::string level_str = "Unkown";
switch (m_level) {
case NONE: return;
case DEBUG: level_str = "DEBUG"; break;
case STATUS: level_str = "STATUS"; break;
case INFO: level_str = "INFO"; break;
case ERROR: level_str = "ERROR"; break;
case FATAL: level_str = "FATAL"; break;
}
if (m_level >= InnerGlobalLogLevel) {
auto msg = m_buffer.str();
m_buffer.str("");
m_buffer << level_str << ": " << msg << std::endl;
m_log << m_buffer.str();
#if ORZ_PLATFORM_OS_ANDROID
ANDROID_LOG(__android_log_level(m_level), "%s", msg.c_str());
#endif
}
#if ORZ_PLATFORM_OS_ANDROID
else {
auto msg = m_buffer.str();
ANDROID_LOG(__android_log_level(m_level), "%s", msg.c_str());
}
#endif
m_level = NONE;
m_buffer.str("");
m_log.flush();
}
private:
LogLevel m_level;
std::ostringstream m_buffer;
std::ostream &m_log;
Log(const Log &other) = delete;
Log &operator=(const Log&other) = delete;
};
inline Log &crash(Log &log)
{
const auto msg = log.message();
log.flush();
throw Exception(msg);
}
}
#ifdef ORZ_SOLUTION_DIR
#define ORZ_LOCAL_FILE ( \
std::strlen(ORZ_SOLUTION_DIR) + 1 < std::strlen(__FILE__) \
? ((const char *)(__FILE__ + std::strlen(ORZ_SOLUTION_DIR) + 1)) \
: ((const char *)(__FILE__)) \
)
#else
#define ORZ_LOCAL_FILE (orz::Split(__FILE__, R"(/\)").back())
#endif
#define ORZ_LOG(level) (orz::Log(level))("[")(ORZ_LOCAL_FILE)(":")(__LINE__)("]: ")
#define ORZ_TIME(level) (orz::Log(level))("[")(orz::now_time())("]: ")
#define ORZ_TIME_LOG(level) (orz::Log(level))("[")(orz::now_time())("][")(ORZ_LOCAL_FILE)(":")(__LINE__)("]: ")
#endif //ORZ_UTILS_LOG_H
| true |
1300c802a8cb13fcc9c90a060798115505b992e1 | C++ | elias174/Paralelos-2017-2 | /OpenMP/Matrix-Vector/Matrix-Vector/main.cpp | UTF-8 | 1,420 | 3.09375 | 3 | [] | no_license | #include <iostream>
#include <omp.h>
#include <stdlib.h>
#include <stdio.h>
#include <ctime>
using namespace std;
void print_matrix(int **matrix, int m, int n){
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
cout << matrix[i][j] << "\t";
}
cout << endl;
}
}
void print_array(int *array, int n){
for(int i=0; i<n; i++){
cout << array[i] << '\t';
}
cout << endl;
}
void initialize_matrix(int **matrix, int m, int n){
for(int i=0; i<m; i++){
matrix[i] = new int[n];
for(int j=0; j<n; j++){
matrix[i][j] = rand() % 999;
}
}
}
void initialize_array(int *array, int n){
for(int i=0; i<n; i++){
array[i] = rand()%999;
}
}
int main(int argc, char** argv)
{
srand((int)time(0));
int thread_count = atoi(argv[3]);
int m=atoi(argv[1]);
int n=atoi(argv[2]);
int **matrix = new int*[m];
int *vector = new int[n];
int *result = new int[n];
initialize_matrix(matrix, m, n);
initialize_array(vector, n);
int i,j;
double start = omp_get_wtime();
#pragma omp parallel for num_threads(thread_count) default(none) private(i, j) shared(matrix, vector, result, m, n)
for(i=0; i<m; i++){
result[i] = 0;
for(j=0; j<n; j++)
result[i] += matrix[i][j]*vector[j];
}
printf("Time: \t %f \n", omp_get_wtime()-start);
return 0;
}
| true |
acfa7e3af641a48668bf7bb4cd5e7f32520a77d1 | C++ | pandaboy/StaticMemoryManager | /StaticMemoryManager/MemoryManager.cpp | UTF-8 | 8,717 | 3.59375 | 4 | [] | no_license | #include "MemoryManager.h"
namespace MemoryManager
{
// IMPORTANT IMPORTANT IMPORTANT IMPORTANT IMPORTANT IMPORTANT IMPORTANT IMPORTANT
//
// This is the only static memory that you may use, no other global variables may be
// created, if you need to save data make it fit in MM_pool
//
// IMPORTANT IMPORTANT IMPORTANT IMPORTANT IMPORTANT IMPORTANT IMPORTANT IMPORTANT
const int MM_POOL_SIZE = 65536;
char MM_pool[MM_POOL_SIZE];
// returns a generic pointer to the byte at buffer[i]
void* atIndex(unsigned int i = 0)
{
// if we try to access beyond the size of the array,
// return nullptr
if (i >= MM_POOL_SIZE)
{
return nullptr;
}
// return pointer using pointer arithmetic
return ((char *)MM_pool + i);
}
// Recursively searches for a free chunk, returns address of free chunk or nullptr
// size: size of chunk requested
// i: index of pool to look at
void* free(int size, unsigned short i = 0)
{
void* resource = nullptr;
// our helpfule struct definition
struct header
{
unsigned short size;
unsigned short free;
};
// get the header at index i
header* hp = (header *)atIndex(i);
if (hp != nullptr)
{
// if it's too small, or in use, check the next block
if (hp->size < size || hp->free != 0)
{
// calculate next block by available values:
// e.g. 0 + 4(long) + 4(header) -> index 8
resource = free(size, i + hp->size + sizeof(header));
}
else
{
// if the current block is adequate, point the resource to its address
// will move sizeof(header) bytes based on pointer arithmetic
resource = hp + 1;
}
}
return resource;
}
// recursively merges adjacent free blocks
void merge(unsigned short i = 0)
{
struct header
{
unsigned short size;
unsigned short free;
};
// left header/chunk
header* left = (header *)atIndex(i);
// calculate right header/chunk index position
// e.g. 0 + 4(long) + 4(header) = 8
unsigned int next = i + left->size + sizeof(header);
// right header/chunk
header* right = (header *)atIndex(next);
// if either headers are unavailable, nothing to test
if (left == nullptr || right == nullptr)
{
return;
}
// check if this chunk and the one next to it are
// both empty - if so merge them
if (left->free == 0 && right->free == 0)
{
// merging involves adding the right chunk size (header + data)
// to the current chunk
left->size += right->size + sizeof(header);
// call merge on this chunk again.
// - this is to cover situations where:
// [Free] -> [Free] -> [Free]
merge(i);
}
else
{
// otherwise carry on to the next header
merge(next);
}
}
// Initialize set up any data needed to manage the memory pool
void initializeMemoryManager(void)
{
// TODO : IMPLEMENT ME
// struct for tracking allocations:
// ++++++++++++++++++++++++++++++++++++++++++++++++++++
// + 65532 | 0 | +
// ++++++++++++++++++++++++++++++++++++++++++++++++++++
struct header {
unsigned short size; // Size of space AFTER header.
unsigned short free; // Indicates if the chunk is in use.
};
// Creates an initial chunk, by setting the size to (MM_POOL_SIZE - header size)
header* hp = (header *)MM_pool;
hp->size = MM_POOL_SIZE - sizeof(header);
hp->free = 0; // 0 indicates a free chunk of space
}
// return a pointer inside the memory pool
void* allocate(int aSize)
{
// TODO: IMPLEMENT ME
// are we trying to assign the impossible?
if (aSize < 1 || aSize > MM_POOL_SIZE) {
onIllegalOperation("Invalid size request: %d", 1);
}
// struct again!
struct header
{
unsigned short size;
unsigned short free;
};
// Recursive search for free block
void* resource = free(aSize);
// if we got a resource allocation:
// - update the header to mark it as in use
// - check if we can split the resource
if (resource != nullptr)
{
// the header is before the resource by sizeof(header) bytes
header* hp = (header *)resource - 1;
// mark the chunk as in use
hp->free = 1;
// Check if we can split this chunk into smaller chunks
// - calculate the minimum space we need for a split
unsigned short toAllocate = aSize + sizeof(header);
if (toAllocate < hp->size)
{
// Create a new header after the resource
// the index here will point to where the next header should be located at:
// - resource address + number of bytes to use in split
header* nhp = (header *)((char *)hp + toAllocate);
// next we set the information for the new header:
// size = original size - size_allocated
nhp->size = hp->size - toAllocate;
nhp->free = 0;
// update the original header information
// with the size allocated
hp->size = aSize;
}
}
else if(resource == nullptr)
{
// if we got a nullptr, there wasn't any space left
onOutOfMemory();
}
return resource;
}
// Free up a chunk previously allocated
void deallocate(void* aPointer)
{
// TODO: IMPLEMENT ME
struct header
{
unsigned short size;
unsigned short free;
};
// if aPointer is null, report error
if (aPointer == nullptr)
{
onIllegalOperation("Invalid reference provided: %d", 2);
}
// if aPointer is outside the bounds of MM_pool, report error
// our available space always starts sizeof(header) beyond the
// start i.e. at 4bytes or MM_Pool[4]
if (aPointer < atIndex(sizeof(header)) || aPointer > atIndex(MM_POOL_SIZE - 1))
{
onIllegalOperation("Invalid reference provided: %d", 2);
}
// get the header (always sizeof(header) before the resource)
header* hp = (header*)aPointer - 1;
// just mark it as free
hp->free = 0;
// next we call merge on the memory to merge any free areas
merge();
}
//---
//--- support routines
//---
// Will scan the memory pool and return the total free space remaining
int freeRemaining(void)
{
// TODO: IMPLEMENT ME
struct header
{
unsigned short size;
unsigned short free;
} *hp;
// loop through the buffer, incrementing based on header information
unsigned int i = 0;
unsigned int allocated = 0; // stores how much space we've taken up
while (i < MM_POOL_SIZE) {
hp = (header *)atIndex(i);
// add the size of the allocated header
allocated += sizeof(header);
// if it's in use, add the size as well
if (hp->free == 1)
{
allocated += hp->size;
}
// jump to next header
i += hp->size + sizeof(header);
}
// return how much space we've taken deducted from total size
return MM_POOL_SIZE - allocated;
}
// Will scan the memory pool and return the largest free space remaining
int largestFree(void)
{
// TODO: IMPLEMENT ME
struct header
{
unsigned short size;
unsigned short free;
} *hp;
// loop through the buffer, incrementing based on header information
unsigned int i = 0;
unsigned int largest = 0; // used to track the biggest allocation
while (i < MM_POOL_SIZE) {
hp = (header *)atIndex(i);
// if it's in use, and bigger than what we have, update our largest
if (hp->free == 0 && hp->size >= largest)
{
largest = hp->size;
}
// jump to next header
i += hp->size + sizeof(header);
}
return largest;
}
// will scan the memory pool and return the smallest free space remaining
int smallestFree(void)
{
// TODO: IMPLEMENT ME
struct header
{
unsigned short size;
unsigned short free;
} *hp;
// loop through the buffer, incrementing based on header information
unsigned int i = 0;
unsigned int smallest = MM_POOL_SIZE; // start at the maximum size
while (i < MM_POOL_SIZE) {
hp = (header *)atIndex(i);
// if the size is smaller (and in use) update our value
if (hp->free == 0 && hp->size < smallest)
{
smallest = hp->size;
}
// jump to next header
i += hp->size + sizeof(header);
}
// If we never updated the pool_size (and it's largest is always
// MM_POOL_SIZE - 4) then set smalles to 0
if (smallest == MM_POOL_SIZE)
{
smallest = 0;
}
return smallest;
}
} | true |
a08b0f5ba4dd56b7a66ec3bdc2adf4349f324ec0 | C++ | 314wind/CPOA | /profil.cpp | UTF-8 | 1,828 | 3.0625 | 3 | [] | no_license | #include <profil.h>
//#include <string>
Profil::Profil(): _nom(""), _moDePasse("") {} //constructeur vide
Profil::Profil(const string &nom, const string& mdp, gestionnairePaquets *gp): // Constructeur stand
_nom(nom), _moDePasse(mdp), gestionpak(gp)
{
}
Profil::Profil(const Profil & p) : //constructeur par recopie
_nom(p._nom), _moDePasse(p._moDePasse), gestionpak(p.gestionpak)
{
}
/* Destructeur */
Profil::~Profil()
{
delete [] gestionpak;
}
/*Getters et setters*/
const string& Profil::getNom() const
{
return _nom;
}
const string& Profil::getMdp() const
{
return _moDePasse;
}
void Profil::setNom(string& nom)
{
this->_nom = nom;
}
bool Profil::contientGestionPaquet() const
{
return gestionpak != NULL;
}
int Profil::getNbPaquet()const
{
return gestionpak->getNbPaquet();
}
gestionnairePaquets* Profil::getGestionPaquet() const
{
return gestionpak;
}
const Paquet *Profil::getPaquet() const
{
for(int i = 0; i < getNbPaquet(); i++)
gestionpak->getPaquet(i);
}
void Profil::supprimerPaquet()
{
if(contientGestionPaquet())
{
delete gestionpak;
gestionpak = NULL;
}
}
/*void Profil::ajoutPaquet(const Paquet &p)
{
supprimerPaquet();
this->gestionpak = new Paquet(p.getNom(), p.getDescription(), p.getGestionCarte());
}*/
const Profil & Profil::operator=(const Profil &p)
{
if(this != &p)
{
_nom = _nom;
_moDePasse = p._moDePasse;
gestionpak = p.gestionpak;
}
return *this;
}
bool Profil::operator==(const Profil &p) const
{
return (_nom == p._nom && _moDePasse == p._moDePasse);
}
void Profil::afficher(ostream & flux) const
{
flux << "Profil [ \n Nom:" << _nom << "\n Mot de passe :" << _moDePasse << (*gestionpak) << "\n ]" << endl;
}
| true |
2b3e741a0e61224b1bc723c5b8af9b6ecde896db | C++ | narongsakjob/adt-project | /webCaching.cpp | UTF-8 | 621 | 2.828125 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main(){
int n,m,x;
cin >> n;
cin >> m;
int a[n];
int count=0;
bool check=false;
for( int i = 0 ; i < m ; i++ ){
cin >> x;
if( i < n){
a[i] = x;
count++;
}else{
for( int j = 0 ; j < n ; j++ ){
if( x == a[j] ){
check = true;
break;
}else{
check = false;
}
}
if( check == false ){
for( int j = 0 ; j < n ; j++ ){
if( j < n-1) a[j] = a[j+1];
}
a[n-1] = x;
count++;
}
}
}
cout << count << endl;
}
| true |
f2a00895c94f3f79fd904924f3e46e5ba93b1cab | C++ | oliver-zeng/leetcode | /0341-Flatten_Nested_List_Iterator/main.cpp | UTF-8 | 2,074 | 3.875 | 4 | [] | no_license | /**
* // This is the interface that allows for creating nested lists.
* // You should not implement it, or speculate about its implementation
* class NestedInteger {
* public:
* // Return true if this NestedInteger holds a single integer, rather than a nested list.
* bool isInteger() const;
*
* // Return the single integer that this NestedInteger holds, if it holds a single integer
* // The result is undefined if this NestedInteger holds a nested list
* int getInteger() const;
*
* // Return the nested list that this NestedInteger holds, if it holds a nested list
* // The result is undefined if this NestedInteger holds a single integer
* const vector<NestedInteger> &getList() const;
* };
*/
class NestedIterator {
stack<NestedInteger> st;
public:
// 其实这题因为每个元素是,int还是新的vector都是不确定的
// vector层数不定,所以需要递归的处理问题
// 因此用dfs或栈实现,且最后的输出是顺序的,因此用栈的话要从后向前入栈
NestedIterator(vector<NestedInteger> &nestedList) {
for (int i = nestedList.size() - 1; i >= 0; i--)
st.push(nestedList[i]);
}
int next() {
NestedInteger tmp = st.top();
st.pop();
return tmp.getInteger();
}
// st.empty()不为空,不代表就真的不为空
// 比如 [[]] 虽然是空的,但st.empty()不为空
// 所以必须递归的判断是否为空,也就是用栈把真正的输出找到
bool hasNext() {
while (!st.empty()) {
NestedInteger tmp = st.top();
if (tmp.isInteger())
return true;
st.pop();
vector<NestedInteger> vec = tmp.getList();
for (auto iter = vec.rbegin(); iter != vec.rend(); iter++)
st.push(*iter);
}
return false;
}
};
/**
* Your NestedIterator object will be instantiated and called as such:
* NestedIterator i(nestedList);
* while (i.hasNext()) cout << i.next();
*/ | true |
e3c6128835ff56b0f51f810c5b20cb2da858231e | C++ | ExpertMicro/NumeroNatural | /Mainwindow.cpp | UTF-8 | 5,370 | 2.640625 | 3 | [] | no_license | #include "Mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButtonExecutar_clicked()
{
try {
int n1 = ui->lineEditPrimeiroNumero->text().toInt();
int n2 = ui->lineEditSegundoNumero->text().toInt();
NNatural numero1(n1);
NNatural numero2(n2);
QString n1Str = QString::number(n1);
QString n2Str = QString::number(n2);
//altera NÚMERO PERFEITO ==> linha
//ui->tableWidgetTabela->setVerticalHeaderItem(0,item);
//Altera colunas
QTableWidgetItem *itemN1 = new QTableWidgetItem("NÚMERO 1: "+n1Str);
QTableWidgetItem *itemN2 = new QTableWidgetItem("NÚMERO 2: "+n2Str);
ui->tableWidgetTabela->setHorizontalHeaderItem(0,itemN1);
ui->tableWidgetTabela->setHorizontalHeaderItem(1,itemN2);
QString str1 = "NAO";
QString str2 = "NAO";
if(numero1.eQuadradoPerfeito()) str1 = "SIM";
if(numero2.eQuadradoPerfeito()) str2 = "SIM";
QTableWidgetItem *item1 = new QTableWidgetItem(str1);
QTableWidgetItem *item2 = new QTableWidgetItem(str2);
ui->tableWidgetTabela->setItem(0,0,item1);
ui->tableWidgetTabela->setItem(0,1,item2);
long long int fat1 = numero1.fatorial();
long long int fat2 = numero2.fatorial();
QString strfat1 = QString::number(fat1);
QString strfat2 = QString::number(fat2);
QTableWidgetItem *itemf1 = new QTableWidgetItem(strfat1);
QTableWidgetItem *itemf2 = new QTableWidgetItem(strfat2);
ui->tableWidgetTabela->setItem(1,0,itemf1);
ui->tableWidgetTabela->setItem(1,1,itemf2);
QString strNumeroPerfeito1 = "NAO";
QString strNumeroPerfeito2 = "NAO";
if(numero1.perfeito()) strNumeroPerfeito1 = "SIM";
if(numero2.perfeito()) strNumeroPerfeito2 = "SIM";
QTableWidgetItem *nPerfeito1 = new QTableWidgetItem(strNumeroPerfeito1);
QTableWidgetItem *nPerfeito2 = new QTableWidgetItem(strNumeroPerfeito2);
ui->tableWidgetTabela->setItem(2,0,nPerfeito1);
ui->tableWidgetTabela->setItem(2,1,nPerfeito2);
QString strCapicua1 = "NAO";
QString strCapicua2 = "NAO";
if(numero1.capicua()) strCapicua1 = "SIM";
if(numero2.capicua()) strCapicua2 = "SIM";
QTableWidgetItem *nCapicua1 = new QTableWidgetItem(strCapicua1);
QTableWidgetItem *nCapicua2 = new QTableWidgetItem(strCapicua2);
ui->tableWidgetTabela->setItem(3,0,nCapicua1);
ui->tableWidgetTabela->setItem(3,1,nCapicua2);
QString strPrimo1 = "NAO";
QString strPrimo2 = "NAO";
if(numero1.primo()) strPrimo1 = "SIM";
if(numero2.primo()) strPrimo2 = "SIM";
QTableWidgetItem *nPrimo1 = new QTableWidgetItem(strPrimo1);
QTableWidgetItem *nPrimo2 = new QTableWidgetItem(strPrimo2);
ui->tableWidgetTabela->setItem(4,0,nPrimo1);
ui->tableWidgetTabela->setItem(4,1,nPrimo2);
QString bin1 = numero1.mudarBase(2);
QString bin2 = numero2.mudarBase(2);
QTableWidgetItem *nbin1 = new QTableWidgetItem(bin1);
QTableWidgetItem *nbin2 = new QTableWidgetItem(bin2);
ui->tableWidgetTabela->setItem(5,0,nbin1);
ui->tableWidgetTabela->setItem(5,1,nbin2);
QString bin3 = numero1.mudarBase(8);
QString bin4 = numero2.mudarBase(8);
QTableWidgetItem *nbin3 = new QTableWidgetItem(bin3);
QTableWidgetItem *nbin4 = new QTableWidgetItem(bin4);
ui->tableWidgetTabela->setItem(6,0,nbin3);
ui->tableWidgetTabela->setItem(6,1,nbin4);
QString bin5 = numero1.mudarBase(16);
QString bin6 = numero2.mudarBase(16);
QTableWidgetItem *nbin5 = new QTableWidgetItem(bin5);
QTableWidgetItem *nbin6 = new QTableWidgetItem(bin6);
ui->tableWidgetTabela->setItem(7,0,nbin5);
ui->tableWidgetTabela->setItem(7,1,nbin6);
NNatural mdc1 = numero1.mdc(numero2);
QString strmdc1 = QString::number(mdc1.getNumero());
QTableWidgetItem *xmdc1 = new QTableWidgetItem(strmdc1);
QTableWidgetItem *ymdc2 = new QTableWidgetItem(strmdc1);
ui->tableWidgetTabela->setItem(8,0,xmdc1);
ui->tableWidgetTabela->setItem(8,1,ymdc2);
NNatural mmc1 = numero1.mmc(numero2);
QString strmmc1 = QString::number(mmc1.getNumero());
QTableWidgetItem *xmmc1 = new QTableWidgetItem(strmmc1);
QTableWidgetItem *ymmc2 = new QTableWidgetItem(strmmc1);
ui->tableWidgetTabela->setItem(9,0,xmmc1);
ui->tableWidgetTabela->setItem(9,1,ymmc2);
QString strPrimosEntreSi1 = "NAO";
QString strPrimosEntreSi2 = "NAO";
if(numero1.primoEntreSi(n2)) strPrimosEntreSi1 = "SIM";
if(numero2.primoEntreSi(n1)) strPrimosEntreSi2 = "SIM";
QTableWidgetItem *nPrimosEntreSi1 = new QTableWidgetItem(strPrimosEntreSi1);
QTableWidgetItem *nPrimosEntreSi2 = new QTableWidgetItem(strPrimosEntreSi2);
ui->tableWidgetTabela->setItem(10,0,nPrimosEntreSi1);
ui->tableWidgetTabela->setItem(10,1,nPrimosEntreSi2);
} catch (QString erro) {
QMessageBox::information(this,"ERRO",erro);
}
}
| true |
c675f11ff177e3fbd458f693d18d2422827f99c4 | C++ | wkalb/2.009-Red-Team | /old/ai.ino | UTF-8 | 1,809 | 2.734375 | 3 | [] | no_license | ///////////////////////////////////////////////////
// PINS //
///////////////////////////////////////////////////
///////////////////////////////////////////////////
//// STRUCTS //
///////////////////////////////////////////////////
// expandable sensor structure
struct Sensors {
boolean left_arm;
boolean right_arm;
boolean belly;
// add integer, char, and other values
};
struct Action {
boolean (*listener)(void *self, Sensors *sensor);
void (*perform)(void);
};
///////////////////////////////////////////////////
// LISTENERS //
///////////////////////////////////////////////////
boolean belly_listener(void *self, Sensors *sensor)
{
return true;
}
boolean left_arm_listener(void *self, Sensors *sensor){
return true;
}
boolean right_arm_listener(void *self, Sensors *sensor){
return true;
}
///////////////////////////////////////////////////
// ACTIONS //
///////////////////////////////////////////////////
// open/close arms
void open_left_arm(void){
}
void close_left_arm(void){
}
void open_right_arm(void){
}
void close_right_arm(void){
}
void open_both_arms(void){
}
void close_both_arms(void){
}
void wave_left_arm(void){
}
void wave_right_arm(void){
}
void wave_both_arms(void){
}
// move body
void open_body(void){
}
void close_body(void){
}
///////////////////////////////////////////////////
// ARDUINO MAIN //
///////////////////////////////////////////////////
// Initialize body sensors
Sensors sensor;
void poll_sensors(Sensors *sensor)
{
sensor->left_arm = true;
sensor->right_arm = true;
sensor->belly = true;
}
void setup()
{
Serial.begin(9600);
}
void loop()
{
poll_sensors(&sensor);
}
| true |
5ab3801612529be7acbc200ce677f374b8f2e1fd | C++ | iCore-034/StroustrupBook | /Chapter 4/Exercise 5, chapter 4.cpp | UTF-8 | 898 | 3.765625 | 4 | [] | no_license | // Simple calculator
#include<iostream>
#include<vector>
using namespace std;
// I decided to write down the function to practice
void foo(char x, double y, double z) {
if (x == '+') {
cout << "The sum of " << y << " and " << z << " == " << y + z << endl;
}
else if (x == '-') {
cout << "The difference between " << y << " and " << z << " == " << y - z << endl;
}
else if (x == '*') {
cout << "The multiplication of " << y << " and " << z << " == " << y * z << endl;
}
else if (x == '/') {
cout << "The dividing " << y << " by " << z << " == " << y / z << endl;
}
else {
cout << "I don't understant.\n Try again.\n";
}
}
int main() {
cout << "Enter two number and symbol of operation (2.3 + 9.3): \n";
double first = 0;
double second = 0;
char symbol;
cin >> first >> symbol >> second;
foo(symbol, first, second);
getchar();
return 0;
} | true |
0de2246b4e4ac5726799ccf9bfd11ff7dd325c79 | C++ | mtreviso/university | /Problems & Contents/URI/4-DataStructures&Libraries/1439-BoraBora2.cpp | UTF-8 | 4,160 | 2.90625 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <stack>
#include <vector>
#include <deque>
#include <queue>
using namespace std;
typedef pair<int, int> ii;
typedef struct triple{
int first, second, third;
triple(){}
triple(int f, int s, int t){
first = f;
second = s;
third = t;
}
}triple;
const ii NONE = ii(-1,-1);
char toNaipe(int naipe){
if(naipe == 0)
return 'C';
if(naipe == 1)
return 'D';
if(naipe == 2)
return 'H';
return 'S';
}
int getNaipe(char naipe){
if(naipe == 'C')
return 0;
if(naipe == 'D')
return 1;
if(naipe == 'H')
return 2;
return 3;
}
int proxJogador(int i, int p, bool sentido){
if(sentido){
i++;
i = i % p;
}
else{
i--;
i = (i == -1) ? p-1 : i;
}
return i;
}
ii popSaque(queue<ii> &saque){
ii temp = saque.front();
saque.pop();
return temp;
}
bool ehMaior(ii i, ii j){
if(i.first != j.first)
return (i.first >= j.first);
return (i.second >= j.second);
}
int verQuemGanhou(vector<ii> *jogadores, queue<ii> &saque, ii descartada, int p){
bool sentido = true; //horario
int i = 0; // primeiro jogador
//triple ant = triple(descartada.first, descartada.second, 0);
if(descartada.first == 12){ // inverte sentido
sentido = !sentido;
}
else if(descartada.first == 7){ // saca 2 cartas e pula a vez
ii nova = popSaque(saque);
jogadores[i].push_back(nova);
nova = popSaque(saque);
jogadores[i].push_back(nova);
i = proxJogador(i, p, sentido);
}
else if(descartada.first == 1){ // saca 1 carta e pula a vez
ii nova = popSaque(saque);
jogadores[i].push_back(nova);
i = proxJogador(i, p, sentido);
}
else if(descartada.first == 11){ // so pula a vez
i = proxJogador(i, p, sentido);
}
//int x = 10;
bool debug = false;
if(debug)
printf("%d: %d %c\n", i, descartada.first, toNaipe(descartada.second));
while(true){
int old = i;
int maior = 0;
bool first = true;
bool ok = false;
for(int j=0; j<(int) jogadores[i].size(); j++){
if(jogadores[i][j].first == descartada.first or jogadores[i][j].second == descartada.second){
if(ehMaior(jogadores[i][j], jogadores[i][maior])){
maior = j;
}
if(first == true){
maior = j;
first = false;
}
ok = true;
}
}
ii proxCarta = NONE;
if(!ok){
if(!saque.empty()){
ii nova = popSaque(saque);
jogadores[i].push_back(nova);
int t = jogadores[i].size() - 1;
if(jogadores[i][t].first == descartada.first or jogadores[i][t].second == descartada.second){
ok = true;
maior = t;
}
}
}
if(ok){
proxCarta = jogadores[i][maior];
jogadores[i].erase(jogadores[i].begin()+maior);
int k = proxJogador(i, p, sentido);
if(proxCarta.first == 12){
sentido = !sentido;
//i = proxJogador(i, p, sentido);
}
else if(proxCarta.first == 7){
if(!saque.empty()){
ii nova = popSaque(saque);
jogadores[k].push_back(nova);
}
if(!saque.empty()){
ii nova = popSaque(saque);
jogadores[k].push_back(nova);
}
i = k;
}
else if(proxCarta.first == 1){
if(!saque.empty()){
ii nova = popSaque(saque);
jogadores[k].push_back(nova);
}
i = k;
}
else if(proxCarta.first == 11){
i = k;
}
}
if(proxCarta != NONE)
descartada = proxCarta;
if(debug)
printf("%d: %d %c\n", old, descartada.first, toNaipe(descartada.second));
if(jogadores[old].size() == 0)
return old;
i = proxJogador(i, p, sentido);
}
return 0;
}
int main(){
int p, m, n, valor;
char c;
while(scanf("%d %d %d", &p, &m, &n) and n > 0){
vector<ii> jogadores[12];
queue<ii> saque;
for(int i=0; i<p; i++){
for(int j=0; j<m; j++){
scanf("%d %c", &valor, &c);
jogadores[i].push_back(ii(valor, getNaipe(c)));
}
}
scanf("%d %c", &valor, &c);
ii descartada = ii(valor, getNaipe((int) c));
for(int i=p*m + 1; i<n; i++){
scanf("%d %c", &valor, &c);
saque.push(ii(valor, getNaipe((int) c)));
}
int ganhador = verQuemGanhou(jogadores, saque, descartada, p);
printf("%d\n", ganhador+1);
//w++;
//break;
}
return 0;
} | true |
9de76bf61c59acb676ff73d8bbbeb21b7509f9d8 | C++ | BradKing17/pong | /Source/Game.cpp | UTF-8 | 10,628 | 2.671875 | 3 | [] | no_license | #include <Engine/Keys.h>
#include <Engine/Input.h>
#include <Engine/InputEvents.h>
#include <Engine/Sprite.h>
#include "Constants.h"
#include "Game.h"
#include "GameFont.h"
#include <ctime>
/**
* @brief Default Constructor.
*/
Pong::Pong()
{
}
/**
* @brief Destructor.
* @details Remove any non-managed memory and callbacks.
*/
Pong::~Pong()
{
this->inputs->unregisterCallback(callback_id);
if (sprite)
{
delete sprite;
sprite = nullptr;
}
for (auto& font : GameFont::fonts)
{
delete font;
font = nullptr;
}
}
/**
* @brief Initialises the game.
* @details The game window is created and all assets required to
run the game are loaded. The keyHandler callback should also
be set in the initialise function.
* @return True if the game initialised correctly.
*/
bool Pong::init()
{
game_width = WINDOW_WIDTH;
game_height = WINDOW_HEIGHT;
if (!initAPI())
{
return false;
}
renderer->setWindowTitle("Pong");
renderer->setClearColour(ASGE::COLOURS::BLACK);
renderer->setSpriteMode(ASGE::SpriteSortMode::IMMEDIATE);
paddle_one = renderer->createRawSprite();
paddle_one->loadTexture(".\\Resources\\Textures\\Paddle.png");
paddle_one->width(15);
paddle_one->height(75);
paddle_one->xPos(10);
paddle_one->yPos((game_height / 2) - (paddle_one->height()/2));
paddle_two = renderer->createRawSprite();
paddle_two->loadTexture(".\\Resources\\Textures\\Paddle.png");
paddle_two->width(15);
paddle_two->height(75);
paddle_two->xPos(game_width - (paddle_two->width() + 10));
paddle_two->yPos((game_height / 2) - (paddle_one->height() / 2));
ball = renderer->createRawSprite();
ball->loadTexture(".\\Resources\\Textures\\Ball.png");
ball->width(30);
ball->height(30);
std::srand(time(NULL));
spawn();
toggleFPS();
callback_id = inputs->addCallbackFnc(
ASGE::E_KEY, &Pong::keyHandler, this);
// enable noob mode
inputs->use_threads = false;
return true;
}
/**
* @brief Processes any key inputs
* @details This function is added as a callback to handle the game's
keyboard input. For this assignment, calls to this function
are thread safe, so you may alter the game's state as you
see fit.
* @param data The event data relating to key input.
* @see KeyEvent
* @return void
*/
void Pong::keyHandler(ASGE::SharedEventData data)
{
auto key = static_cast<const ASGE::KeyEvent*>(data.get());
//Menu Functionality
if(in_menu)
{
if (key->key == ASGE::KEYS::KEY_ENTER &&
key->action == ASGE::KEYS::KEY_RELEASED &&
in_main_menu == true)
{
switch (menu_option)
{
case 0:
{
in_main_menu = false;
in_mode_select = true;
in_how_to_play = false;
menu_option = 0;
break;
}
case 1:
{
in_main_menu = false;
in_mode_select = false;
in_how_to_play = true;
menu_option = 0;
break;
}
case 2:
{
signalExit();
break;
}
}
}
//score menu navigation
else if ((key->key == ASGE::KEYS::KEY_ENTER &&
key->action == ASGE::KEYS::KEY_RELEASED &&
in_mode_select == true))
{
switch (menu_option)
{
case 0:
max_score = 5;
break;
case 1:
max_score = 10;
break;
case 2:
max_score = 20;
break;
}
in_mode_select = false;
in_menu = false;
}
if (key->key == ASGE::KEYS::KEY_W &&
key->action == ASGE::KEYS::KEY_RELEASED
&& menu_option != 0)
{
menu_option--;
}
if (key->key == ASGE::KEYS::KEY_S &&
key->action == ASGE::KEYS::KEY_RELEASED
&& menu_option != 2)
{
menu_option++;
}
if (key->key == ASGE::KEYS::KEY_UP &&
key->action == ASGE::KEYS::KEY_RELEASED
&& menu_option != 0)
{
menu_option--;
}
if (key->key == ASGE::KEYS::KEY_DOWN &&
key->action == ASGE::KEYS::KEY_RELEASED
&& menu_option != 2)
{
menu_option++;
}
if (key->key == ASGE::KEYS::KEY_ESCAPE &&
key->action == ASGE::KEYS::KEY_RELEASED &&
in_main_menu == false)
{
in_main_menu = true;
in_mode_select = false;
}
}
else
{
//paddle movement
if (key->key == ASGE::KEYS::KEY_ESCAPE)
{
signalExit();
}
if (key->action == ASGE::KEYS::KEY_PRESSED)
{
switch (key->key)
{
case ASGE::KEYS::KEY_W:
{
direction.set_dir_one(-1);
break;
}
case ASGE::KEYS::KEY_S:
{
direction.set_dir_one(1);
break;
}
case ASGE::KEYS::KEY_UP:
{
direction.set_dir_two(-1);
break;
}
case ASGE::KEYS::KEY_DOWN:
{
direction.set_dir_two(1);
break;
}
}
}
else if (key->action == ASGE::KEYS::KEY_RELEASED)
{
switch (key->key)
{
case ASGE::KEYS::KEY_W:
{
direction.set_dir_one(0);
break;
}
case ASGE::KEYS::KEY_S:
{
direction.set_dir_one(0);
break;
}
case ASGE::KEYS::KEY_UP:
{
direction.set_dir_two(0);
break;
}
case ASGE::KEYS::KEY_DOWN:
{
direction.set_dir_two(0);
break;
}
}
}
}
}
/**
* @brief Updates the scene
* @details Prepares the renderer subsystem before drawing the
current frame. Once the current frame is has finished
the buffers are swapped accordingly and the image shown.
* @return void
*/
void Pong::update(const ASGE::GameTime & us)
{
if (!in_menu)
{
//get current position of ball
auto x_pos = ball->xPos();
auto y_pos = ball->yPos();
//check if ball is hitting paddles
if (isInside(paddle_one, x_pos, y_pos))
{
ball_direction.set_x(ball_direction.get_x() * -1);
}
else if (isInside(paddle_two, x_pos, y_pos))
{
ball_direction.set_x(ball_direction.get_x() * -1);
}
//apply speed to ball
x_pos += ball_speed * ball_direction.get_x() * (us.delta_time.count() / 1000.f);
y_pos += ball_speed * ball_direction.get_y() * (us.delta_time.count() / 1000.f);
// update the position of the ball
ball->yPos(y_pos);
ball->xPos(x_pos);
//check for walls
if (y_pos >= game_height - ball->height() || y_pos <= 0)
{
ball_direction.set_y(ball_direction.get_y() * -1);
}
if ((paddle_one->yPos() <= 0) ||
(paddle_one->yPos() + paddle_one->height()) >= game_height)
{
direction.set_dir_one(direction.get_dir_one() * -1);
}
if ((paddle_two->yPos() <= 0) ||
(paddle_two->yPos() + paddle_two->height()) >= game_height)
{
direction.set_dir_two(direction.get_dir_two() * -1);
}
//check for point scoring
if (x_pos >= game_width - ball->width())
{
score_p_one++;
spawn();
}
if (x_pos <= 0)
{
score_p_two++;
spawn();
}
//paddle movement
auto y_pos_one = paddle_one->yPos();
auto y_pos_two = paddle_two->yPos();
y_pos_one += direction.get_dir_one() * move_speed * (us.delta_time.count() / 1000.f);
y_pos_two += direction.get_dir_two() * move_speed * (us.delta_time.count() / 1000.f);
paddle_one->yPos(y_pos_one);
paddle_two->yPos(y_pos_two);
}
}
/**
* @brief Renders the scene
* @details Renders all the game objects to the current frame.
Once the current frame is has finished the buffers are
swapped accordingly and the image shown.
* @return void
*/
void Pong::render(const ASGE::GameTime &)
{
if (in_main_menu)
{
renderer->renderText(menu_option == 0 ? ">PLAY" : "PLAY",
200, 200, 1.0, ASGE::COLOURS::AQUAMARINE);
renderer->renderText(menu_option == 1 ? ">HOW TO PLAY" : "HOW TO PLAY",
200, 250, 1.0, ASGE::COLOURS::AQUAMARINE);
renderer->renderText(menu_option == 2 ? ">OPTIONS" : "OPTIONS",
200, 300, 1.0, ASGE::COLOURS::AQUAMARINE);
renderer->renderText(menu_option == 3 ? ">QUIT" : "QUIT?",
200, 350, 1.0, ASGE::COLOURS::AQUAMARINE);
}
else if (in_how_to_play)
{
renderer->renderText("HOW TO PLAY",
200, 200, 1.0, ASGE::COLOURS::ORANGE);
renderer->renderText("PLAYER 1",
200, 250, 1.0, ASGE::COLOURS::AQUAMARINE);
renderer->renderText("W : MOVE YOUR PADDLE UP",
200, 300, 1.0, ASGE::COLOURS::AQUAMARINE);
renderer->renderText("S : MOVE YOUR PADDLE DOWN",
200, 325, 1.0, ASGE::COLOURS::AQUAMARINE);
renderer->renderText("PLAYER 2",
500, 250, 1.0, ASGE::COLOURS::AQUAMARINE);
renderer->renderText("UP ARROW : MOVE YOUR PADDLE UP",
500, 300, 1.0, ASGE::COLOURS::AQUAMARINE);
renderer->renderText("DOWN ARROW : MOVE YOUR PADDLE DOWN",
500, 325, 1.0, ASGE::COLOURS::AQUAMARINE);
renderer->renderText("SCORE POINTS BY HITTING THE BALL PAST THE\n"
"OTHER PLAYERS PADDLE INTO THEIR GOAL WHILE DEFENDING YOUR OWN GOAL.\n\n"
"PRESS ESCAPE WHEN IN GAME TO EXIT.",
200, 400, 1.0, ASGE::COLOURS::AQUAMARINE);
}
else if (in_mode_select)
{
renderer->renderText("FIRST TO: " ,
200, 200, 1.0, ASGE::COLOURS::AQUAMARINE);
renderer->renderText(menu_option == 0 ? ">5 POINTS" : "5 POINTS",
350, 200, 1.0, ASGE::COLOURS::AQUAMARINE);
renderer->renderText(menu_option == 1 ? ">10 POINTS" : "10 POINTS",
350, 300, 1.0, ASGE::COLOURS::AQUAMARINE);
renderer->renderText(menu_option == 2 ? ">20 POINTS" : "20 POINTS",
350, 400, 1.0, ASGE::COLOURS::AQUAMARINE);
}
else
{
// renderer->renderSprite(*background);
renderer->renderSprite(*paddle_one);
renderer->renderSprite(*paddle_two);
renderer->renderSprite(*ball);
std::string score_str_one = "SCORE: " + std::to_string(score_p_one);
renderer->renderText(score_str_one.c_str(), 150, 25, 1.0, ASGE::COLOURS::DARKORANGE);
std::string max_scr_str = "FIRST TO: " + std::to_string(max_score);
renderer->renderText(max_scr_str.c_str(), ((game_width / 2) - 50), 25, 1.0, ASGE::COLOURS::DARKORANGE);
std::string score_str_two = "SCORE: " + std::to_string(score_p_two);
renderer->renderText(score_str_two.c_str(), (game_width - 250), 25, 1.0, ASGE::COLOURS::DARKORANGE);
}
}
void Pong::spawn()
{
if (score_p_one == max_score)
{
in_menu = true;
in_main_menu = true;
}
else if (score_p_two == max_score)
{
in_menu = true;
in_main_menu = true;
}
else
{
auto x = (rand() % 10 + 1) - 5;
auto y = (rand() % 10 + 1) - 5;
if (x == 0)
{
x += 5;
}
if (y >= 7)
{
y -= 3;
}
ball_direction.set_x(x);
ball_direction.set_y(y);
ball_direction.normalise();
ball->xPos((game_width - ball->width()) / 2);
ball->yPos((game_height - ball->height()) / 2);
}
}
bool Pong::isInside(const ASGE::Sprite* paddle_sprite, float x, float y) const
{
float paddle_height = paddle_sprite->height();
float paddle_width = paddle_sprite->width();
float pos_x = paddle_sprite->xPos();
float pos_y = paddle_sprite->yPos();
if ((((x+ball->width()) >= pos_x) && (x <= pos_x + paddle_width)) &&
((y >= pos_y) && (y <= pos_y + paddle_height)))
{
return true;
}
else
{
return false;
}
}
| true |
dfca530fdded263466c6a17a0b8fbf913bfda7ba | C++ | chestnutme/pat-solution | /A1032.cpp | UTF-8 | 884 | 2.875 | 3 | [] | no_license | #include <cstdio>
#include <cstring>
const int maxn = 100007;
struct Node {
char data;
int next;
bool flag;
}List[maxn];
int main()
{
freopen("C:\\Users\\Alex\\Desktop\\showmethecode\\c\\pat\\data\\A1032.txt", "r", stdin);
for(int i = 0;i < maxn;i++)
{
List[i].flag = false;
}
int s1, s2, n;
scanf("%d%d%d", &s1, &s2, &n);
int add, next;
char data;
for(int i = 0;i < n;i++)
{
scanf("%d %c %d", &add, &data, &next);
List[add].data = data;
List[add].next = next;
}
for(add = s1;add != -1;add = List[add].next)
{
List[add].flag = true;
}
for(add = s2;add != -1;add = List[add].next)
{
if(List[add].flag == true)
break;
}
if(add == -1)
{
printf("-1\n");
}
else
{
printf("%05d\n", add);
}
return 0;
}
| true |
9e95dbeee6f6a78c233565eff1fc566774a9a47e | C++ | IakMastro/Snake-in-Cpp | /Food.cpp | UTF-8 | 426 | 2.75 | 3 | [] | no_license | #include "Food.h"
#include "Window.h"
Food::Food(int w, int h, int x, int y, int r, int g, int b, int a) :
w(w), h(h), x(x), y(y), r(r), g(g), b(b), a(a) {}
void Food::draw() const {
this->rect.w = w;
this->rect.h = h;
this->rect.x = x;
this->rect.y = y;
SDL_SetRenderDrawColor(Window::renderer, r, g, b, a);
SDL_RenderFillRect(Window::renderer, &rect);
SDL_RenderPresent(Window::renderer);
} | true |
4d8fdd8e84c38e1316ec4c214628fcf54508d072 | C++ | cliicy/autoupdate | /Central/Native/Setup/APMSetupUtility.exe/StatusObserver.h | UTF-8 | 565 | 2.53125 | 3 | [] | no_license | #include "ApmBackendStatus.h"
#include <string>
using namespace std;
class CStatusObserver
{
public:
CStatusObserver(const wstring &runningGuid, const wstring &busyGuid);
~CStatusObserver(void);
ApmBackendSatus GetStatus() const;
//************************************
// Parameter: int seconds must be > 0
//return 0: success; 2:Timeout
//************************************
DWORD WaitForOk(int seconds) const;
private:
BOOL IsPatchManagerRunning() const;
BOOL IsPatchManagerBusy() const;
private:
wstring m_runningGuid;
wstring m_busyGuid;
};
| true |
037c5ca071a4f5f3f29179f34fc82d71313a9b85 | C++ | dabercro/crombie2 | /include/crombie2/Hist.h | UTF-8 | 4,245 | 2.875 | 3 | [] | no_license | #ifndef CROMBIE2_HIST_H
#define CROMBIE2_HIST_H
// I really don't like ROOT's global hash tables and confusing lifetimes
// Here, I make a simple data structure that can make a histogram
// Try to use this and only get the TH1D object at the end
#include <list>
#include <string>
#include <vector>
#include <map>
#include <set>
#include "TH1D.h"
namespace crombie2 {
/**
@brief Implementation of histogram storage that doesn't do ROOT memory stuff
*/
class Hist {
public:
/**
@brief Constructor of custom Hist class
@param label Is the label to go on the x-axis
@param nbins The number of bins to show in the plot.
There is also one overflow and one underflow bin stored internally.
@param min The minimum value shown on the x-axis
@param max The maximum value on the x-axis
@param total_events Is the total weight of events in the file(s) filling this histogram
*/
Hist(const std::string& label = "",
unsigned nbins = 0, double min = 0, double max = 0,
double total_events = 0);
Hist(const std::string& title,
const std::string& label = "",
unsigned nbins = 0, double min = 0, double max = 0,
double total_events = 0);
/// Fills this histogram with some value and weight
void fill (double val, double weight = 1.0);
/// Adds another histogram's bin contents to this Hist
void add (const Hist& other, double factor = 1.0);
/// Scale this histogram by a direct scale factor
void scale (const double scale);
/**
@brief Scale this histogram to a luminosity and cross section.
This assumes no other absolute scaling has happened.
The result will be invalid if this scale function is called
after any other call to Hist::scale.
*/
void scale (const double lumi, const double xs);
/// Returns a Hist that is a ratio between this and another Hist
Hist ratio (const Hist& other) const;
/**
@brief Returns a pointer to a histogram that is owned by a list.
@param storeptr A pointer to a list to store the TH1D.
If null, use a member list that has same scope as this object
*/
TH1D* roothist (std::list<TH1D>* storeptr = nullptr);
std::pair<Hist, Hist> get_minmax_env (const std::string& key) const;
Hist& merge_envs (const std::string& key);
/// Sets the value of the total number of events, throws exception if total is already set
void set_total (double newtotal);
/// Get the maximum value including uncertainties (for plotting)
double max_w_unc () const;
/// Get the minimum value including uncertainties, but not less than 0.0 (for plotting)
double min_w_unc (const bool includezeros = true) const;
/**
@brief Get the maximum bin and the total number of bins.
Does not include overflow bins.
*/
std::pair<unsigned, unsigned> get_maxbin_outof () const;
void set_contents (const std::vector<double>& newcont,
const std::vector<double>& neww2);
double get_total () const;
const std::vector<double>& get_contents () const;
/// Actually returns the sum of squared weights
const std::vector<double>& get_errors () const;
/// Get the sum of the bin contents
double integral (bool overflow = false) const;
double get_bin (unsigned index) const;
void set_bin (unsigned index, double value);
void add_env (const std::string& key, const Hist& env);
const std::string& get_title () const;
private:
std::string hist_title {};
std::string label {};
unsigned nbins {};
double min {};
double max {};
std::vector<double> contents {};
std::vector<double> sumw2 {};
double total {}; ///< Stores the total weights of files filling this
std::list<TH1D> localstore; ///< Keep in mind, these TH1D have same scope as Hist
double get_unc (unsigned bin) const; ///< Find the full uncertainty from uncs hists and sumw2
/// Map envelopes to name
std::map<std::string, std::vector<Hist>> envs {};
std::set<std::string> merged {};
};
}
#endif
| true |
d9e05e2d2e9a615ad569d132170f115acc3de1ee | C++ | sorcerer0001/ConsoleApplication5 | /ConsoleApplication5/w2-6_1.cpp | UTF-8 | 1,223 | 2.5625 | 3 | [] | no_license | #include<stdio.h>
#include<string.h>
int ans,m,n,vis[1000000],step[10],now[10],num;
char s[10];
void dfs(int pos,int sum,int cnt)
{
int i,t;
if(pos>=m){
vis[sum]++;
if(sum>ans){
ans=sum; //记录最佳切割的和
num=cnt;
for(i=0;i<cnt;i++) //记录当前最佳方案
step[i]=now[i];
}
return ;
}
t=0;
for(i=pos;i<m;i++){
t=t*10+s[i]-'0';
if(sum+t>n)
return ;
now[cnt]=t;
dfs(i+1,sum+t,cnt+1);
}
}
int main()
{
int i,sum;
while(scanf("%d%s",&n,s)!=EOF){
m=strlen(s);
if(n==0&&s[0]=='0'&&m==1)
break;
sum=0;
for(i=0;i<m;i++)
sum+=s[i]-'0';
if(sum>n){ //若最小的和都大于targe,则肯定不可能切割出不超过targe的和
printf("error\n");
continue;
}
memset(vis,0,sizeof(vis));
num=ans=0;
dfs(0,0,0);
if(vis[ans]>1)
printf("rejected\n");
else{
printf("%d",ans);
for(i=0;i<num;i++)
printf(" %d",step[i]);
printf("\n");
}
}
return 0;
} | true |
d2abb9d5c16c48cfd95da13577da0485e223c0d5 | C++ | kvmn2000/COMP-345-Project | /MapLoader.cpp | UTF-8 | 5,771 | 3.265625 | 3 | [] | no_license | #include "MapLoader.h"
//default constructor
MapLoader::MapLoader()
{
}
//destructor
MapLoader::~MapLoader() {
}
//copy constructor
MapLoader::MapLoader(const MapLoader& copy) {
fileName = copy.fileName;
}
//assignment operator
MapLoader& MapLoader::operator=(const MapLoader& copy) {
this->fileName = copy.fileName;
return *this;
}
//stream insertion operator
ostream& operator<<(ostream& os, const MapLoader& copy) {
os << "path: " << copy.fileName << endl;
return os;
}
//stream extraction operator
istream& operator>>(istream& is, MapLoader& copy) {
cout << "Enter new file path: " << endl;
is >> copy.fileName;
return is;
}
string MapLoader::getFileName() {
return fileName;
}
Map* MapLoader::loadMap(string path) {
Map* map = new Map();
ifstream file_reader(path);
string current_continent = "";
string current_country = "";
bool readingContinent = false;
bool readingEdge = false;
for (string line; getline(file_reader, line);) {
if (line == "}" || line == "]") {
readingContinent = false;
readingEdge = false;
}
if (readingContinent) {
current_country = line;
Country* country = new Country(current_country, current_continent);
map->addCountry(country);
map->getContinent(current_continent)->addCountrytoContinent(country);
}
if (readingEdge) {
string neighbor = line;
map->getCountry(current_country)->addNeighbor(new Country(neighbor));
//cout << "Added " << neighbor << " to " << current_country << endl;
}
if (line.find('{') != string::npos) {
readingContinent = true;
current_continent = line.substr(0, line.find('{'));
Continent* continent = new Continent(current_continent);
map->addContinent(continent);
}
if (line.find('[') != string::npos) {
readingEdge = true;
current_country = line.substr(0, line.find('['));
}
}
return map;
}
// Displays all the available maps
vector<string> MapLoader::displayAllMaps(const string mapDirectory) {
vector<string> mapFiles;
DIR* directory;
struct dirent* file;
cout << endl << "---DISPLAYING ALL AVAILABLE MAPS---" << endl;
// Code for iterating through directories, works for Unix Operating Systems
if ((directory = opendir(mapDirectory.c_str())) == NULL) {
cout << "Could not open directory of maps, exiting." << endl << endl;
exit(1);
}
else {
int counter = 1;
cout << "Select a map: " << endl << endl;
while ((file = readdir(directory)) != NULL) {
struct stat pathStat;
stat((mapDirectory + file->d_name).c_str(), &pathStat);
int is_dir = S_ISDIR(pathStat.st_mode);
if (!is_dir) {
cout << counter++ << ": " << file->d_name << endl;
mapFiles.push_back(file->d_name);
}
}
}
closedir(directory);
return mapFiles;
}
Map* MapLoader::selectMap(const string mapDirectory) {
bool badMap = true;
Map* theMap;
do
{
theMap = new Map();
cout << endl << "---CHOOSING MAP---" << endl << endl;
vector<string> mapFiles = displayAllMaps(mapDirectory);
int mapNumber = getUserInputInteger("\nYour choice (-1 to quit): ", 1, mapFiles.size());
string fileSelected = mapDirectory + mapFiles[mapNumber - 1];
cout << "file name :" << fileSelected << endl;
fileName = fileSelected;
cout << endl << "The map you chose is: " << fileSelected << endl;
if (fileSelected.substr(fileSelected.length() - 4, fileSelected.length() - 1) != ".txt")
{
cout << endl << "File is not of type .txt" << endl;
fileSelected.clear();
}
else
{
theMap = loadMap(fileSelected);
if (theMap->validate()) {
cout << "New Game has been started! \n";
cout << "This gamemap is valid! \n";
badMap = false;
}
else
{
cout << "Game map is invalid. It has been deleted. Try again with a valid map file\n";
}
}
} while (badMap);
cout << "end of select map........." << endl;
return theMap;
}
// Helper function for getting user string input
string MapLoader::getUserInputString(string output, string choice1, string choice2) {
string input;
cout << output;
cin >> input;
// While the input is invalid
while ((input != choice1 && input != choice2) || cin.fail() || input == "q" || input == "Q") {
if (input == "q" || input == "Q") {
cout << "Quitting..." << endl;
exit(1);
}
// Clear the stream
cin.clear();
cout << "Invalid input" << endl;
cout << "Must be " << choice1 << " or " << choice2 << " and must be a string" << endl;
cout << "Try again ('q' to quit): ";
cin >> input;
}
return input;
}
// Helper function for getting user integer input
int MapLoader::getUserInputInteger(string output, int min, int max) {
string inputString;
int input;
bool failFlag;
cout << output;
cin >> inputString;
try {
input = stoi(inputString);
failFlag = false;
}
catch (invalid_argument e) {
failFlag = true;
}
// While the input is invalid
while (input < min || input > max || cin.fail() || failFlag || inputString.find(".") != string::npos) {
if (input == -1) {
cout << "Quitting..." << endl;
exit(1);
}
cin.clear();
//cin.ignore(numeric_limits<streamsize> std::max, '\n');
cout << "Invalid input" << endl;
if (inputString.find(".") == string::npos) {
cout << "Must be greater than " << min - 1 << " and less than " << max + 1 << " and must be an integer" << endl;
}
else {
cout << "Must be an integer" << endl;
}
cout << "Try again (-1 to quit): ";
cin >> inputString;
try {
input = stoi(inputString);
failFlag = false;
}
catch (invalid_argument e) {
failFlag = true;
}
}
return input;
} | true |
79cba9851d1deeecb31022da8ba44baf52fbc866 | C++ | katevi/Spbu-homeworks | /sem1/hw10/task1/Hw10t1.cpp | UTF-8 | 1,337 | 3 | 3 | [] | no_license | #include <stdio.h>
#include "graph.h"
#include "aStar.h"
#include <iostream>
#include <fstream>
int main()
{
Graph* graph = loadGraph("input.txt");
int xStart = 0;
int yStart = 0;
std::cout << "Enter a starting point. x (from 0 to " << graph->weight - 1 << "), y (from 0 to " << graph->height - 1 << ")\n";
std::cin >> xStart >> yStart;
std::cout << "Enter an endpoint. x (from 0 to " << graph->weight - 1 << "), y (from 0 to " << graph->height - 1 << ")\n";
int xFinish = 0;
int yFinish = 0;
std::cin >> xFinish >> yFinish;
int **used = createAuxiliaryMatrix(graph->height, graph->weight, 0);
int **distance = createAuxiliaryMatrix(graph->height, graph->weight, infinity);
int **previous = createAuxiliaryMatrix(graph->height, graph->weight, -1000);
int **heuristic = createAuxiliaryMatrix(graph->height, graph->weight, infinity);
int **currents = createAuxiliaryMatrix(graph->height, graph->weight, 0);
std::cout << "* - path algorithm founded:\n\n";
aStar(graph, used, distance, previous, heuristic, currents, xStart, yStart, xFinish, yFinish);
deleteAuxiliaryMatrix(used, graph->weight);
deleteAuxiliaryMatrix(distance, graph->weight);
deleteAuxiliaryMatrix(previous, graph->weight);
deleteAuxiliaryMatrix(currents, graph->weight);
deleteAuxiliaryMatrix(heuristic, graph->weight);
deleteGraph(graph);
}
| true |
ae3a1c31b910a141bdc5fffd883532a101612790 | C++ | dwelman/npuzzle | /src/readFile.cpp | UTF-8 | 495 | 2.9375 | 3 | [] | no_license | #include <npuzzle.h>
vector<string> readFile(string fileName)
{
ifstream file;
string line;
vector<string> fileData;
int i;
i = 0;
file.open(fileName);
if (!file)
{
cout << "ERROR: File could not be opened" << endl;
exit (-1);
}
while (!file.eof())
{
getline(file, line);
if (line.empty() && i == 0)
{
cout << "ERROR: File cannot be empty" << endl;
exit (-1);
}
if (!line.empty())
fileData.push_back(line);
i++;
}
file.close();
return (fileData);
} | true |
01b281b2fe7da33c10c078e8d05c67b90c2fc0bf | C++ | sergiyvan/robotic_vl | /src/tools/kalmanfilter/genericEKF_old.h | UTF-8 | 2,628 | 3.265625 | 3 | [] | no_license | #ifndef GENERICEKF_OLD_H
#define GENERICEKF_OLD_H
#include <armadillo>
/*------------------------------------------------------------------------------------------------*/
/**
* @brief Generic Extended Kalman Filter to implement your own KF.
*
* Implements the basic math of an EKF.
*
* See "Probabilistic Robotics" for more. The names of the variables
* are mostly consistent with the book, except where other names make
* more sense.
*
* There are no seperate varialbles for the predicted state and covariance,
* ie. state_t bel(state_t) etc.
* This makes the equations simpler and the implementation more efficient.
*
* Convention:
* - Matix --> CamelCase
* - Vector --> lower_case
*
* How to use it:
* - inherit from GenericEKF
* - make sure to initialize I, Sigma, state according to your problem
* - implement a function which
* - calls predictEKF with appropriate arguments: G, R, predictedState,
* (This means you have to implement the process model.)
* - calls correctEKF with appropriate arguments: H, Q, measurement_z,
* predicted_measurement
* (This means you have to implement the measurement model.)
*
* ======
* todo
* ======
* TODO add parameter for state dim and measurement dim in c'tor
* and initialize some vars
*
* TODO the functions don't really need the parameters. Q, R, H and G are
* member variables.
*
* TODO maybe add pure virtual functions to get Q, R, G, H etc.
*
*/
class GenericEKF_old
{
public:
GenericEKF_old() {};
GenericEKF_old(arma::colvec _state);
virtual ~GenericEKF_old() {};
virtual void predictEKF(const arma::mat& G,
const arma::mat& R,
const arma::colvec& predicted_state);
virtual void correctEKF(const arma::mat& H,
const arma::mat& Q,
const arma::colvec& measurement_z,
const arma::colvec& predicted_measurement);
virtual arma::mat calculateMeasurementCovS() const;
void setState(arma::colvec const& _state);
void setSigma(arma::mat const& _mat);
arma::mat const& getSigma() const;
arma::colvec const& getState() const;
protected:
/* data */
// state related
arma::colvec state; /// state (n): state of the KF
arma::mat Sigma; /// Sigma (n*n): covariance of the KF
// Jacobians
arma::mat G; /// Jacobian for prediction G (n*n): state = G * stateOld
arma::mat H; /// Jacobian for correction H (m*n): z = H * state
// noise
arma::mat R; /// process noise matrix in prediction step
arma::mat Q; /// measurement noise matrix in correction step
};
#endif
| true |
4748e2a76ca2330da2ca14a8d0308d23916d802b | C++ | redf0x/qtanks | /include/Entity.h | UTF-8 | 3,691 | 2.671875 | 3 | [] | no_license | #ifndef ENTITY_H
#define ENTITY_H
#include "common.h"
#define set_if_changed(variable) \
if (_ ## variable != variable) { _ ## variable = variable; emit variable ## Changed(_ ## variable); }
#define ATTRIBUTE_GENERIC "generic"
#define ATTRIBUTE_UNKNOWN "unknown"
#define EXPIRY_NEVER std::numeric_limits<long long>::max()
class Attribute {
public:
Attribute() : family(ATTRIBUTE_UNKNOWN), type(ATTRIBUTE_GENERIC), value(QVariant::fromValue(0)), expiry(0) { }
Attribute(QString f, QVariant v, long long exp = EXPIRY_NEVER, QString t = ATTRIBUTE_GENERIC) : family(f), type(t),
value(v), expiry(exp) { }
QVariant getValue () const { return value; }
void setValue (QVariant v) { value = v; }
void tickOff () { if (expiry - 1) expiry--; }
bool expired () { return !expiry; }
void extend (long long nexp) { expiry += nexp; }
QString getFamily () const { return family; }
QString getType () const { return type; }
protected:
QString family, type;
QVariant value;
long long expiry;
};
typedef QList<Attribute> AttrList;
class Entity : public QObject {
Q_OBJECT
public:
Q_PROPERTY(int x READ x WRITE setX NOTIFY xChanged)
Q_PROPERTY(int y READ y WRITE setY NOTIFY yChanged)
Q_PROPERTY(int width READ width WRITE setWidth NOTIFY widthChanged)
Q_PROPERTY(int height READ height WRITE setHeight NOTIFY heightChanged)
Q_PROPERTY(int rotation READ getRotation WRITE setRotation NOTIFY rotationChanged)
Q_PROPERTY(bool solid READ isSolid CONSTANT)
Q_PROPERTY(bool spawned READ isSpawned WRITE setSpawned NOTIFY spawnedChanged)
Q_PROPERTY(QString objectId READ getObjectId CONSTANT)
Q_PROPERTY(QString texture READ getTextureSource WRITE setTextureSource NOTIFY textureChanged)
Q_PROPERTY(int z READ z CONSTANT)
Q_PROPERTY(int armor READ getArmor WRITE setArmor NOTIFY armorChanged)
explicit Entity(QObject* parent = 0) : QObject(parent), _solid(true), _spawned(true),
_x(0), _y(0), _width(1), _height(1), _rotation(0), _z(1) { }
virtual ~Entity() { }
virtual QString getObjectId () const;
virtual int x () const;
virtual int y () const;
virtual int width () const;
virtual int height () const;
virtual QString getTextureSource () const;
virtual int getRotation () const;
virtual int z () const;
virtual bool isSolid () const;
virtual bool isSpawned () const;
virtual int getArmor () const;
virtual void setObjectId (QString id);
virtual void setX (int);
virtual void setY (int);
virtual void setWidth (int);
virtual void setHeight (int);
virtual void setTextureSource (const QString&);
virtual void setRotation (int);
virtual void setSolid (bool);
virtual void setSpawned (bool);
virtual void setArmor (int);
virtual Entity* create (QObject* parent, char sign, QPoint pos);
virtual void addAttribute (Attribute attr);
virtual Attribute& getAttribute (QString family, QString type = ATTRIBUTE_GENERIC);
virtual void removeAttribute (QString family, QString type = ATTRIBUTE_GENERIC);
protected:
virtual Entity* createObject (QObject* parent, char sign, QPoint pos);
signals:
void xChanged (int);
void yChanged (int);
void widthChanged (int);
void heightChanged (int);
void rotationChanged (int);
void textureChanged (QString);
void armorChanged (int);
void spawnedChanged (bool spawned);
private:
QString _id;
QString _texture;
bool _solid, _spawned;
int _x, _y, _width, _height;
int _rotation;
int _armor;
QMap<QString, Attribute> attributeSlots;
protected:
int _z;
};
#endif // ENTITY_H
| true |
e5bb95d5331c4bc9070f03dc06c04b892f431319 | C++ | omribenm/task-1 | /src/main.cpp | UTF-8 | 4,016 | 2.640625 | 3 | [] | no_license | #include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/foreach.hpp>
#include "../include/cyberpc.h"
#include "../include/cyberdns.h"
#include "../include/cyberworm.h"
#include "../include/cyberexpert.h"
#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
//Updating daily data
void DailyRun(CyberDNS *dns,vector<CyberExpert*> exp){
vector<string> list;
int length=exp.size();
int i=0;
int Last_checked=0;
//Update experts data
for( i=0;i<length;i++){
if (exp[i]->getWorkTime()>0){
Last_checked=(exp[i])->dailyCheck(*dns ,Last_checked);
exp[i]->setEfficiency();
exp[i]->setWorkTime();
if (Last_checked==-1)
Last_checked++;
}
else if(exp[i]->getResTime()>0)
exp[i]->setBrakeTime();
}
if(length>0){
if (exp[i-1]->efficiency!= exp[i-1]->getEfficiency())
exp[i-1]->setEfficiency();
}
list=dns->GetCyberPCList();
int size=list.size();
//Update all computers and their neighbors
for (int j=size-1 ;j>=0; j--)
dns->GetCyberPC(list[j]).Run(*dns);
Last_checked=0;
}
int main (){
CyberDNS *dns=new CyberDNS();
boost::property_tree::ptree tree;
int count_days=0;
int end_time;
vector<CyberExpert*> exp;
//Adding the computers to network
boost::property_tree::read_xml("./computers.xml",tree);
BOOST_FOREACH(boost::property_tree::ptree::value_type &v,tree.get_child("")){
CyberPC *pc=new CyberPC(v.second.get<std::string>("os"),v.second.get<std::string>("name"));
dns->AddPC(*pc);
cout<<"Adding to server: "<<pc->getName()<<" "<<std::endl;
cout<<pc->getName()<<" connected to server"<<" "<<std::endl;
};
//Build the network
boost::property_tree::read_xml("./network.xml",tree);
BOOST_FOREACH(boost::property_tree::ptree::value_type &v,tree.get_child("")){
cout<<"Connecting "<<v.second.get<std::string>("pointA")<<" to "<<v.second.get<std::string>("pointB")<<endl;
(dns->GetCyberPC(v.second.get<std::string>("pointA"))).AddConnection(v.second.get<std::string>("pointB"));
cout<<" "<<v.second.get<std::string>("pointA")<<" now connected to "<<v.second.get<std::string>("pointB")<<endl;
(dns->GetCyberPC(v.second.get<std::string>("pointB"))).AddConnection(v.second.get<std::string>("pointA"));
(cout<<" "<<v.second.get<std::string>("pointB"))<<" now connected to "<<v.second.get<std::string>("pointA")<<endl;
};
//Worms & experts are being created
boost::property_tree::read_xml("./events.xml",tree);
BOOST_FOREACH(boost::property_tree::ptree::value_type &v,tree.get_child("")){
if(v.first=="hack"){
//Update the date
cout<<"Day : "<<count_days<<endl;
count_days++;
//Get worm data & create it
string computer=v.second.get<string>("computer");
string worm_name=v.second.get<string>("wormName");
int worm_dormancy=v.second.get<int>("wormDormancy");
string worm_os=v.second.get<string>("wormOs");
CyberWorm *worm = new CyberWorm(worm_os, worm_name, worm_dormancy);
cout<<" "<<"Hack occurred on "<<computer<<endl;
dns->GetCyberPC(computer).Infect(*worm);
//Run the simulation of this day
DailyRun(dns,exp);
delete worm;
}else if(v.first=="clock-in"){
//Update the date
cout<<"Day : "<<count_days<<endl;
count_days++;
//Get expert data & create it
string name=v.second.get<string>("name");
int work_time=v.second.get<int>("workTime");
int rest_time=v.second.get<int>("restTime");
int efficiency=v.second.get<int>("efficiency");
CyberExpert *expert=new CyberExpert(name,work_time,rest_time,efficiency);
exp.push_back(expert);
//Print the result
cout<<" clocked in: "<<name<<" began working"<<endl;
DailyRun(dns,exp);
}else if(v.first=="termination")
end_time=v.second.get<int>("time");
};
//Keep working the days remaining
while(count_days<=end_time){
cout<<"Day : "<<count_days<<"\n";
DailyRun(dns,exp);
count_days++;
}
//Delete experts
for (int k=0;k<exp.size();k++)
delete exp[k];
delete dns;
}
| true |
78908520841862dcf3acebce5db543fb0aaae5eb | C++ | annequeentina/OpendTect | /include/Algo/changetracker.h | UTF-8 | 3,275 | 2.59375 | 3 | [] | no_license | #pragma once
/*+
________________________________________________________________________
(C) dGB Beheer B.V.; (LICENSE) http://opendtect.org/OpendTect_license.txt
Author: A.H. Bril
Date: 26/09/2000
________________________________________________________________________
-*/
#include "algomod.h"
#include "gendefs.h"
/*!
\brief Updates a variable when changes occur.
Use if you need to keep track of whether a variable changes when it is
assigned to another variable. Example: a 'not saved' flag in a UI. Also
facilitates giving unique change stamps.
*/
mClass(Algo) ChangeTracker
{
public:
ChangeTracker( bool* c=0 )
: chgd_(c), chgid_(0) {}
ChangeTracker( bool& c )
: chgd_(&c), chgid_(0) {}
ChangeTracker( unsigned int& c )
: chgid_(&c), chgd_(0) {}
ChangeTracker( unsigned int* c )
: chgid_(c), chgd_(0) {}
ChangeTracker( bool& c, unsigned int& ci )
: chgd_(&c), chgid_(&ci) {}
//! returns wether this value is changed
template <class T,class U>
inline bool set(const T& oldval,const U& newval);
//! Changes and returns wether this value is changed
template <class T,class U>
inline bool update(T& val,const U& newval);
//! specialisation for C-strings
inline bool set(const char*&,const char*&);
bool isChanged() const
{ return chgd_ ? *chgd_ : (bool)(chgid_ ? *chgid_ : 0);}
unsigned int changeId() const
{ return chgid_ ? *chgid_ : (chgd_ ? (*chgd_?1:0) : 0);}
inline void setChanged(bool yn=true);
void setChangeId( unsigned int c )
{ if ( chgid_ ) *chgid_ = c; }
bool hasBoolVar() const { return chgd_; }
bool hasIntVar() const { return chgid_; }
const bool& boolVar() const { return *chgd_; }
//!< Don't call if !hasBoolVar()
const unsigned int& intVar() const { return *chgid_; }
//!< Don't call if !hasIntVar()
void setVar( bool* m ) { chgd_ = m; }
void setVar( bool& m ) { chgd_ = &m; }
void setVar( unsigned int* m ) { chgid_ = m; }
void setVar( unsigned int& m ) { chgid_ = &m; }
protected:
bool* chgd_;
unsigned int* chgid_;
};
/*!
\ingroup Algo
\brief Macro to use when there is no direct access to data members.
chtr = the change tracker
obj = object instance
getfn = get function
setfn - set function
newval = new value
*/
#define mChgTrackGetSet(chtr,obj,getfn,setfn,newval) { \
if ( chtr.set( obj->getfn(), newval ) ) \
obj->setfn( newval ); }
inline void ChangeTracker::setChanged( bool ischgd )
{
if ( chgd_ )
{ if ( !*chgd_ ) *chgd_ = ischgd; }
else if ( chgid_ )
{ if ( ischgd ) (*chgid_)++; }
}
template <class T,class U>
inline bool ChangeTracker::set( const T& val, const U& newval )
{
bool ret = !(val == mCast(T,newval));
setChanged( ret );
return ret;
}
inline bool ChangeTracker::set( const char*& val, const char*& newval )
{
bool ret = (val && newval) || (!val && !newval);
if ( !ret ) { setChanged(true); return true; }
if ( !val ) return false;
ret = FixedString(val)!=newval;
setChanged( ret );
return ret;
}
template <class T,class U>
inline bool ChangeTracker::update( T& val, const U& newval )
{
bool ret = set( val, newval );
val = newval;
return ret;
}
| true |
877e8e07fd77f1e94baffdae2d8f948a13822b7d | C++ | David-Vice/Sea-Battle-Project | /ships.h | UTF-8 | 8,626 | 3.109375 | 3 | [] | no_license | /// ships.h
#pragma once
#include <iostream>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <Windows.h>
#include "showdesks.h"
using namespace std;
void PutShip(int** desk1, int** desk2, int shipsize);
void RandomPos(int** desk, int shipsize);
void GiveNewPosHor(int** desk, int& row, int& column, int shipsize);
void DelPrevPosHor(int** desk, int& row, int& column, int shipsize);
void GiveNewPosVer(int** desk, int& row, int& column, int shipsize);
void DelPrevPosVer(int** desk, int& row, int& column, int shipsize);
void Reverse(int** desk, int row, int column, int shipsize, int pos);
bool CheckPos(int** desk, int row, int column, int shipsize, int pos, bool manual);
void PutShip(int** desk1, int** desk2, int shipsize) {
int pos = 1;
int key = 0;
int row = 0;
int column = 0;
GiveNewPosHor(desk1, row, column, shipsize);
ShowDesks(desk1, desk2, false);
while (true)
{
key = _getch();
//cout << key;
if (key == 80 && row != 9)
{
//"Down"
if (pos == 1) {
DelPrevPosHor(desk1, row, column, shipsize);
row++;
GiveNewPosHor(desk1, row, column, shipsize);
}
else if (pos == 2 && row <= 9 - shipsize) {
DelPrevPosVer(desk1, row, column, shipsize);
row++;
GiveNewPosVer(desk1, row, column, shipsize);
}
system("cls");
ShowDesks(desk1, desk2, false);
}
else if (key == 72 && row != 0)
{
//"Up"
if (pos == 1) {
DelPrevPosHor(desk1, row, column, shipsize);
row--;
GiveNewPosHor(desk1, row, column, shipsize);
}
else if (pos == 2) {
DelPrevPosVer(desk1, row, column, shipsize);
row--;
GiveNewPosVer(desk1, row, column, shipsize);
}
system("cls");
ShowDesks(desk1, desk2, false);
}
else if (key == 75 && column != 0)
{
//"Left"
if (pos == 1) {
DelPrevPosHor(desk1, row, column, shipsize);
column--;
GiveNewPosHor(desk1, row, column, shipsize);
}
else if (pos == 2) {
DelPrevPosVer(desk1, row, column, shipsize);
column--;
GiveNewPosVer(desk1, row, column, shipsize);
}
system("cls");
ShowDesks(desk1, desk2, false);
}
else if (key == 77 && column != 9)
{
//"Right"
if (pos == 1 && column <= 9 - shipsize) {
DelPrevPosHor(desk1, row, column, shipsize);
column++;
GiveNewPosHor(desk1, row, column, shipsize);
}
else if (pos == 2) {
DelPrevPosVer(desk1, row, column, shipsize);
column++;
GiveNewPosVer(desk1, row, column, shipsize);
}
system("cls");
ShowDesks(desk1, desk2, false);
}
else if (key == 114) {
//"Reverse"
if (pos == 1 && row <= 10 - shipsize) {
Reverse(desk1, row, column, shipsize, pos);
pos = 2;
}
else if (pos == 2 && column <= 10 - shipsize) {
Reverse(desk1, row, column, shipsize, pos);
pos = 1;
}
system("cls");
ShowDesks(desk1, desk2, false);
}
else if (key == 113) {
system("cls");
cout << "Good bye!" << endl;
exit(EXIT_SUCCESS);
}
else if (key == 13) {
//"Save"
bool OK = CheckPos(desk1, row, column, shipsize, pos, true);
if (OK) {
system("cls");
break;
}
else {
cout << "Choose the correct position for your ship!" << endl;
system("pause");
system("cls");
ShowDesks(desk1, desk2, false);
}
}
}
}
void RandomPos(int** desk, int shipsize) {
srand(time(NULL));
for (int coord = 10; coord < 100; coord += 4) {
int row = coord / 10;
int column = coord % 10;
int pos = rand() % 2 + 1;
bool OK = CheckPos(desk, row, column, shipsize, pos, false);
if (OK) {
if (pos == 1 && column <= 10 - shipsize) { GiveNewPosHor(desk, row, column, shipsize); break; }
else if (pos == 2 && row <= 10 - shipsize) { GiveNewPosVer(desk, row, column, shipsize); break; }
}
}
}
void GiveNewPosHor(int** desk, int& row, int& column, int shipsize) {
for (int i = 0; i < shipsize; i++) {
desk[row][column + i]++;
}
}
void DelPrevPosHor(int** desk, int& row, int& column, int shipsize) {
for (int i = 0; i < shipsize; i++) {
desk[row][column + i]--;
}
}
void GiveNewPosVer(int** desk, int& row, int& column, int shipsize) {
for (int i = 0; i < shipsize; i++) {
desk[row + i][column]++;
}
}
void DelPrevPosVer(int** desk, int& row, int& column, int shipsize) {
for (int i = 0; i < shipsize; i++) {
desk[row + i][column]--;
}
}
void Reverse(int** desk, int row, int column, int shipsize, int pos) {
if (pos == 1) {
DelPrevPosHor(desk, row, column, shipsize);
GiveNewPosVer(desk, row, column, shipsize);
}
else if (pos == 2) {
DelPrevPosVer(desk, row, column, shipsize);
GiveNewPosHor(desk, row, column, shipsize);
}
}
bool CheckPos(int** desk, int row, int column, int shipsize, int pos, bool manual) {
bool OK = true;
for (int i = 0; i < shipsize; i++) {
if (pos == 1) {
if (i == 0) {
if (column != 0) {
if (desk[row][column - 1] == 1) { OK = false; break; }
if (row != 0) {
if (desk[row - 1][column - 1] == 1) { OK = false; break; }
}
if (row != 9) {
if (desk[row + 1][column - 1] == 1) { OK = false; break; }
}
}
}
if (desk[row][column + i] == 2 && manual) { OK = false; break; }
if (desk[row][column + i] == 1 && !manual) { OK = false; break; }
if (row != 0) {
if (desk[row - 1][column + i] == 1) { OK = false; break; }
}
if (row != 9) {
if (desk[row + 1][column + i] == 1) { OK = false; break; }
}
if (i == shipsize - 1) {
if (column + shipsize - 1 != 9) {
if (desk[row][column + i + 1] == 1) { OK = false; break; }
if (row != 0) {
if (desk[row - 1][column + i + 1] == 1) { OK = false; break; }
}
if (row != 9) {
if (desk[row + 1][column + i + 1] == 1) { OK = false; break; }
}
}
}
}
else if (pos == 2) {
if (i == 0) {
if (row != 0) {
if (desk[row - 1][column] == 1) { OK = false; break; }
if (column != 0) {
if (desk[row - 1][column - 1] == 1) { OK = false; break; }
}
if (column != 9) {
if (desk[row - 1][column + 1] == 1) { OK = false; break; }
}
}
}
if (desk[row + i][column] == 2 && manual) { OK = false; break; }
if (desk[row + i][column] == 1 && !manual) { OK = false; break; }
if (column != 0) {
if (desk[row + i][column - 1] == 1) { OK = false; break; }
}
if (column != 9) {
if (desk[row + i][column + 1] == 1) { OK = false; break; }
}
if (i == shipsize - 1) {
if (row + shipsize - 1 != 9) {
if (desk[row + i + 1][column] == 1) { OK = false; break; }
if (column != 0) {
if (desk[row + i + 1][column - 1] == 1) { OK = false; break; }
}
if (column != 9) {
if (desk[row + i + 1][column + 1] == 1) { OK = false; break; }
}
}
}
}
}
return OK;
}
| true |
84c653e97e07b786e5d9c28a23e279a18aa9062f | C++ | messlinger/mbug_devel | /c/include/mbug_2811.hpp | UTF-8 | 1,266 | 2.671875 | 3 | [] | no_license |
#ifndef MBUG_2811_HPP
#define MBUG_2811_HPP
//------------------------------------------------------------------------------
/** MBUG Library
Class wrapper for
2811 Thermometer device interface
*/
//------------------------------------------------------------------------------
#include "mbug.hpp"
#include "mbug_2811.h"
namespace mbug {
//------------------------------------------------------------------------------
class mbug_2811
{
public:
static device_list list( void )
{
return get_device_list(2811);
}
mbug_2811( int serial_num = 0 )
{
dev = mbug_2811_open(serial_num);
if (!dev) throw mbug::error("mbug_2811: Error opening device.");
}
mbug_2811( char* id )
{
dev = mbug_2811_open_str(id);
if (!dev) throw mbug::error("mbug_2811: Error opening device.");
}
~mbug_2811()
{
close();
}
void close( void )
{
mbug_2811_close(dev);
dev = 0;
}
double read( void )
{
return mbug_2811_read(dev);
}
int set_acq_mode(mbug_acq_mode mode)
{
return mbug_2811_set_acq_mode( dev, mode );
}
protected:
mbug_device dev;
};
//------------------------------------------------------------------------------
} // close namespace mbug
#endif // MBUG_2811_HPP
| true |
b65d669f69bf4ea7a243216c5a0c7af32611abc0 | C++ | jbrjnk/Robot2WD | /Firmware_Atmega/Robot2WDAtmega/Robot2WDAtmega/Timer1.cpp | UTF-8 | 1,438 | 2.734375 | 3 | [
"MIT"
] | permissive | #include "Timer1.h"
#include <avr/interrupt.h>
Timer1::Timer1()
{
TCCR1A = (1 << WGM11);
TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS10);
ICR1 = Timer1::C_CounterUpperBound;
TIMSK |= (1 << TOIE1);
ticksCount = 0;
}
uint32_t Timer1::GetTicksCount() const
{
cli();
uint32_t val = ticksCount;
sei();
return val;
}
void Timer1::SetChA(PwmChannelMode mode, uint16_t duty)
{
if(mode == PwmChannelMode::Disabled)
{
TCCR1A &= ~((1 << COM1A1) | (1 << COM1A0));
}
else if(mode == PwmChannelMode::Normal)
{
uint8_t v = TCCR1A;
v &= ~(1 << COM1A0);
v |= (1 << COM1A1);
TCCR1A = v;
}
else if(mode == PwmChannelMode::Inverted)
{
TCCR1A |= ((1 << COM1A1) | (1 << COM1A0));
}
OCR1A = duty;
}
void Timer1::SetChB(PwmChannelMode mode, uint16_t duty)
{
if(mode == PwmChannelMode::Disabled)
{
TCCR1A &= ~((1 << COM1B1) | (1 << COM1B0));
}
else if(mode == PwmChannelMode::Normal)
{
uint8_t v = TCCR1A;
v &= ~(1 << COM1B0);
v |= (1 << COM1B1);
TCCR1A = v;
}
else if(mode == PwmChannelMode::Inverted)
{
TCCR1A |= ((1 << COM1B1) | (1 << COM1B0));
}
OCR1B = duty;
}
uint32_t Timer1::GetIteration() const
{
return GetTicksCount() / C_TicksPerIteration;
}
Timer1::~Timer1()
{
}
Timer1 & Timer1::Instance()
{
static Timer1 instance;
return instance;
}
void timerInterrupt(void)
{
Timer1 & instance = Timer1::Instance();
instance.ticksCount++;
}
ISR(TIMER1_OVF_vect)
{
timerInterrupt();
}
| true |
575a717401c122c5dab790255d9731fe6b4e76da | C++ | HoOngEe/Study-algol | /Baekjoon/3059.cpp | UTF-8 | 444 | 2.65625 | 3 | [] | no_license | #include<cstdio>
#include<cstring>
using namespace std;
int main() {
int tc_count;
scanf("%d%*c", &tc_count);
for (int i = 0; i < tc_count; i++) {
char arr[26] = { 0 };
int total_sum = 0;
char c;
while (true) {
scanf("%c", &c);
if (c == '\n')
break;
else
arr[c - 'A'] = 1;
}
for (int j = 0; j < 26; j++) {
if (!arr[j])
total_sum += j + 'A';
}
printf("%d\n", total_sum);
}
} | true |
9807dfc13c1ccdf3d7bb38a36f4c65d24838c9f7 | C++ | HKCaesar/lucy-mpi | /MPI/mpi_main.cpp | UTF-8 | 1,374 | 2.953125 | 3 | [] | no_license | /**
* MPI implementation of the Richardson-Lucy Algorithem. The master loads in the
* images in ./images and passes them to the slaves for processsing. Upon being
* returned the images are saved to ./Output. The program accepts .bmp and .jpg
* images.
* The images rather then there location are passed so that the slaves do not
* require access to the location where the images are being read from and
* stored to*/
//required includes
#include "master_slave.h"
//the main program
int main(int argc, char *argv[]) {
int numprocs;
int myid;
MPI_Status stat;
MPI_Init(&argc, &argv); // all MPI programs start with MPI_Init; all 'N'
//processes exist thereafter
MPI_Comm_size(MPI_COMM_WORLD, &numprocs); // find out how big the SPMD
//world is
MPI_Comm_rank(MPI_COMM_WORLD, &myid); // and this processes' rank is
//if a master run this
if (myid == 0) {
//start the total time timer
double start = (clock() / (double) CLOCKS_PER_SEC);
master_program_main(stat, numprocs);
//stop the total time timer
double finish = (clock() / (double) CLOCKS_PER_SEC) - start;
printf("Job done in %g seconds\n", finish);
}
//else a slave so run this
else {
slave_program_main(stat);
}
printf("process %i finished\n", myid);
MPI_Finalize();
return 0;
} | true |
8f99ed2e2523caf87825cb48b5a3a6b0c4c689ab | C++ | thetedgt/SDP-PM-2019 | /Labs/Lab05 - Factory/main.cpp | UTF-8 | 618 | 2.75 | 3 | [] | no_license | #include "Factory.h"
void testFactory() {
Worker a("Ivan", "programmer", 100);
Worker b("Mitko", "programmer", 80);
Worker c("Kiro", "programmer", 70);
Worker d("Evstati", "programmer", 150);
b.setName("Go6o");
b.setSalary(120);
//a.print();
//b.print();
cout << endl;
Factory factory("FMI");
factory.print();
factory.addWorker(a);
factory.addWorker(b);
factory.addWorker(c);
factory.addWorker(d);
factory.addWorker(b);
factory.print();
cout << endl;
factory.sort();
factory.print();
}
int main() {
testFactory();
return 0;
}
| true |
8f93a99497711ceb57a3707ce4809ff66c1fc57f | C++ | surtweig/kpi-assignments | /parallel/matrix/main.cpp | UTF-8 | 3,140 | 2.96875 | 3 | [] | no_license | //#define FORCE_SINGLE_THREAD
#include <iostream>
#include <string>
#include <thread>
#include <mutex>
#include "matrix.h"
#include <cmath>
#include <chrono>
#define MSIZE 5
using namespace std;
mutex printlock;
void test()
{
matrix* m1 = matrix::random(3, 3, 0.0, 1.0);
matrix* m2 = matrix::fill(3, 3, 1.0);
m1->print(cout);
cout << "\n";
m2->print(cout);
matrix* m3 = matrix::multiply(*m1, *m2);
m3->print(cout);
delete m1;
delete m2;
delete m3;
}
void test2()
{
matrix* a = matrix::random(3, 7, 0.0, 1.0);
matrix* b = matrix::random(7, 6, 0.0, 1.0);
matrix* c = matrix::multiply(*a, *b);
matrix* v = matrix::random(10, 1, 0.0, 1.0);
c->print(cout);
v->print(cout);
v->sort();
v->print(cout);
delete a;
delete b;
delete c;
}
// 1.5 C = SORT(A) *(MA*ME) + SORT(B)
void F1()
{
matrix* MA = matrix::random(MSIZE, MSIZE, 0.0, 1.0);
matrix* ME = matrix::random(MSIZE, MSIZE, 0.0, 1.0);
matrix* A = matrix::random(MSIZE, 1, 0.0, 1.0);//matrix::getcolumn(*MA, 0);
matrix* B = matrix::random(MSIZE, 1, 0.0, 1.0);
matrix* ae = matrix::multiply(*MA, *ME);
A->sort();
B->sort();
matrix* aae = matrix::multiply(*ae, *A);
matrix* C = matrix::add(*aae, *B);
printlock.lock();
cout << "F1():\n";
C->print(cout);
printlock.unlock();
delete MA;
delete ME;
delete A;
delete B;
delete C;
delete ae;
delete aae;
}
// 2.5 MG = SORT(MF) * MK + ML
void F2()
{
matrix* MF = matrix::random(MSIZE, MSIZE, 0.0, 1.0);
matrix* MK = matrix::random(MSIZE, MSIZE, 0.0, 1.0);
matrix* ML = matrix::random(MSIZE, MSIZE, 0.0, 1.0);
MF->sort();
matrix* MFK = matrix::multiply(*MF, *MK);
matrix::addto(*MFK, *ML);
printlock.lock();
cout << "F2():\n";
MFK->print(cout);
printlock.unlock();
delete MF;
delete MK;
delete ML;
delete MFK;
}
// 3.5 O = (SORT(MP*MR)*S)
void F3()
{
matrix* MP = matrix::random(MSIZE, MSIZE, 0.0, 1.0);
matrix* MR = matrix::random(MSIZE, MSIZE, 0.0, 1.0);
matrix* S = matrix::random(MSIZE, 1, 0.0, 1.0);
matrix* MRP = matrix::multiply(*MP, *MR);
MRP->sort();
matrix* result = matrix::multiply(*MRP, *S);
printlock.lock();
cout << "F3():\n";
result->print(cout);
printlock.unlock();
delete MP;
delete MR;
delete S;
delete MRP;
delete result;
}
int main(int argc, char *argv[])
{
#ifdef FORCE_SINGLE_THREAD
auto begin = std::chrono::high_resolution_clock::now();
F1();
F2();
F3();
auto end = std::chrono::high_resolution_clock::now();
std::cout << std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() << " us" << std::endl;
#else
auto begin = std::chrono::high_resolution_clock::now();
thread tf1(F1);
thread tf2(F2);
thread tf3(F3);
tf1.join();
tf2.join();
tf3.join();
auto end = std::chrono::high_resolution_clock::now();
std::cout << std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() << " us" << std::endl;
#endif
cout << "\n";
return 0;
}
| true |
f23ab80b15703709520b183857817ab4c3202d72 | C++ | matthewfcarlson/arduino | /ESP32/Basics/Blink/Blink.ino | UTF-8 | 742 | 3.28125 | 3 | [
"MIT"
] | permissive | /*
* Simply turns on and off GPIO Pin 21 once a second.
*
* By Jon E. Froehlich
* @jonfroehlich
* http://makeabilitylab.io
*
* For a walkthrough and circuit diagram, see:
* https://makeabilitylab.github.io/physcomp/esp32/led-blink
*
*/
// The pin numbering on the Huzzah32 is a bit strange
// See pin diagram here: https://makeabilitylab.github.io/physcomp/esp32/
const int LED_OUTPUT_PIN = 21;
void setup() {
pinMode(LED_OUTPUT_PIN, OUTPUT);
}
void loop() {
digitalWrite(LED_OUTPUT_PIN, HIGH); // turn LED on (3.3V)
delay(1000); // delay is in milliseconds; so wait one second
digitalWrite(LED_OUTPUT_PIN, LOW); // turn LED off (0V)
delay(1000); // wait for a second
}
| true |