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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
c129eb610f173a272881d27d7ac42430dcfe5f7c | C++ | hnlylmlzh/cs | /EncapsulateInterfaceInherit/11_1/1.cpp | GB18030 | 553 | 2.921875 | 3 | [] | no_license | #include "A.h"
int main()
{
A* pa = new A();
pa->f();
B* pb = (B*)pa;
// е˼ģォpaתΪָB͵ָ벻٣ûиµֵ
// ָǿ飬new A()зصڴзA͵һĵַ@.@~.Ǻ½
// ָB͵ָpb,ΪpaһҲָnewǸġ
pb->f();
delete pa, pb;
pa = new B();
pa->f();
pb = (B*)pa;
pb->f();
return 0;
} | true |
95675b076478f24b5d2e9bfd1632da765471cec5 | C++ | Miao4382/Starting-Out-with-Cplusplus | /Chapter 5/Programming Exercise/5.cpp | UTF-8 | 584 | 3.171875 | 3 | [] | no_license | //5. Membership Fees Increase
#include<fstream>
#include<iostream>
#include<iomanip>
int main()
{
double charge=2500;
const double RATE = 1.04;
std::ofstream cout;
cout.open("D:\\5.txt");
cout << "Year" << std::setw(15) << "Charge" << std::endl;
cout << "--------------------\n";
cout << std::setw(2) << "0" << std::setw(15) << charge << std::endl;
for (int i = 1; i <= 6; i++)
{
charge *= RATE;
cout << std::setw(2) << i << std::setw(15) << charge << std::endl;
}
cout << "--------------------\n";
std::cout << "Writting complete.\n";
cout.close();
return 0;
} | true |
3f652bb9b7cbf7d125cdf95a8e98dab54627f2ca | C++ | jjchromik/hilti-104-total | /hilti/passes/id-resolver.h | UTF-8 | 1,144 | 2.953125 | 3 | [
"BSD-2-Clause"
] | permissive |
#ifndef HILTI_ID_RESOLVER_H
#define HILTI_ID_RESOLVER_H
#include "../pass.h"
namespace hilti {
namespace passes {
/// Resolves ID references. It replaces nodes of type ID with the node that
/// it's referencing.
class IdResolver : public Pass<> {
public:
IdResolver() : Pass<>("hilti::IdResolver", true)
{
}
virtual ~IdResolver();
/// Resolves ID references.
///
/// module: The AST to resolve.
///
/// report_unresolved: If true, IDs that we can't resolve are reported as
/// errorr; if false, they are simply left untouched.
///
/// Returns: True if no errors were encountered.
bool run(shared_ptr<Node> module, bool report_unresolved);
protected:
void visit(expression::ID* i) override;
void visit(Declaration* d) override;
void visit(Function* f) override;
void visit(type::Unknown* t) override;
void visit(declaration::Variable* d) override;
void visit(statement::ForEach* s) override;
private:
bool run(shared_ptr<Node> ast) override
{
return false;
};
std::set<string> _locals;
bool _report_unresolved = true;
};
}
}
#endif
| true |
fb0592ec7a4103094545842ab5793a96be3cd1e6 | C++ | CalebJohnstone/COS214-Software-Modelling | /1/Predator.h | UTF-8 | 1,300 | 2.984375 | 3 | [] | no_license | #ifndef Predator_H
#define Predator_H
#include <iostream>
#include <string>
#include "PredatorState.h"
#include "PredatorMemento.h"
#include "Prey.h"
using namespace std;
class Predator {
public:
//constructor and destructor
Predator(int healthPoints, string huntingMethod, int damage, string specialityAttack);
~Predator();
//methods
int getHP() const;
void setHP(int health);
string getHuntingMethod() const;
void setHuntingMethod(string method);
int getDamage() const;
void setDamage(int d);
string getSpeciality() const;
void setSpeciality(string s);
//template method
void hunt(Prey* p);
//primitive operations
virtual bool catchPrey(Prey* p) = 0;
virtual bool getAttacked(Prey* p) = 0;
virtual bool attack(Prey* p) = 0;
virtual void die() = 0;
virtual void speciality() = 0;
//used to get the type of predator when summarising the simulation results
virtual string getType() = 0;
//memento pattern
void setMemento(PredatorMemento* m);
PredatorMemento* createMemento();
protected:
int healthPoints;
string huntingMethod;
int damage;
string specialityAttack;
//memento pattern
PredatorState* state;
};
#endif | true |
66642a48333c37d4660a5ab53e39813731a7072d | C++ | prateek200/Data-Structures-and-Algorithm | /Linked List 2/Swap two Nodes of LL.cpp | UTF-8 | 742 | 3.53125 | 4 | [] | no_license | /****************************************************************
Following is the class structure of the Node class:
class Node
{
public:
int data;
Node *next;
Node(int data)
{
this->data = data;
this->next = NULL;
}
};
*****************************************************************/
Node * swapNodes(Node * head, int i, int j)
{
int k;
Node * temp = head;
for (k = 0; k < i; k++)
temp = temp -> next;
Node * temp1 = head;
for (k = 0; k < j; k++)
temp1 = temp1 -> next;
k = temp -> data;
temp -> data = temp1 -> data;
temp1 -> data = k;
return (head);
}
| true |
798e7e0ea44d202bf1bc638ca917dbbd22f74634 | C++ | Warzecha/Cpp-course | /lab5/textpool/TextPool.cpp | UTF-8 | 1,339 | 2.953125 | 3 | [] | no_license | //
// Created by torzmich on 27.03.18.
//
#include "TextPool.h"
namespace pool
{
TextPool::TextPool() {
}
size_t TextPool::StoredStringCount() const {
return set.size();
}
TextPool::~TextPool() {
set.clear();
}
std::experimental::string_view TextPool::Intern(const std::string &str) {
// set.emplace(std::experimental::string_view(str.c_str(),str.length()));
// return *set.find(str);
bool flag = true;
for (auto &n : this->set) {
if (n == str){
flag = false;
return n;
}
}
if (flag){
set.emplace(str);
return Intern(str);
}
}
TextPool::TextPool(const std::initializer_list<const std::string> &words) {
for (const auto &word : words) {
set.emplace(word);
}
}
TextPool::TextPool(TextPool &&other) : set(other.set) {
//std::swap(set, other.set);
//std::swap(set, other.set);
//other.set.clear();
other.set.clear();
}
TextPool & TextPool::operator=(TextPool && other) {
if(this!=&other) // prevent self-move
{
set.clear();
set = other.set;
other.set.clear();
}
return *this;
}
} | true |
2cf5522c214de01971792c17adf7c336c1cbf22c | C++ | ffeng271/recoded | /src/zzScenes/zzCloudyScene/emoji.cpp | UTF-8 | 950 | 2.53125 | 3 | [
"MIT"
] | permissive | //
// emoji.cpp
// cloudZZRecode1
//
// Created by Ann Kidder on 11/13/17.
//
//
#include "emoji.hpp"
Emoji::Emoji(){
}
void Emoji::setup(int x, int y, ofImage * icon){
x_start = x;
img = icon;
emojiSpeed = 1;
emojiSize = 1; //img->getWidth();
y_val = y;
creation_time = ofGetElapsedTimef();
randomOffset = ofRandom(0, TWO_PI);
randomSpeed = ofRandom(0.8, 1.2);
}
void Emoji::update(){
y_val += emojiSpeed*randomSpeed;
}
void Emoji::draw(){
//img.resize(emojiSize, emojiSize);
float time = ofGetElapsedTimef();
float time_diff = time - creation_time;
ofSetRectMode(OF_RECTMODE_CENTER);
float w = ofGetMouseX();
ofPushMatrix();
ofTranslate(x_start, y_val);
ofRotateZ(0 + sin(ofGetElapsedTimef() * randomSpeed + randomOffset) * 20);
img->draw(0,0, img->getWidth()*emojiSize, img->getHeight()*emojiSize);
ofPopMatrix();
ofSetRectMode(OF_RECTMODE_CORNER);
}
| true |
7d92e0704d2681fe1a93f5bf4ab06ce0424a7e1a | C++ | 1plus1equals2/practise | /src/accelerated_cpp/chapter03/output_format.cpp | GB18030 | 1,500 | 3.359375 | 3 | [
"Apache-2.0"
] | permissive | #include <iostream>
#include <ios>
#include <iomanip>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::setprecision;
using std::string;
using std::streamsize;
using std::setw;
/*
setfill(c) ַΪc
setprecision(n) ʾСΪnλ
setw(n) Ϊnַ
setioflags(ios::fixed) ̶ĸʾ
setioflags(ios::scientific) ָʾ
setiosflags(ios::left)
setiosflags(ios::right) Ҷ
setiosflags(ios::skipws ǰհ
setiosflags(ios::uppercase) 16д
setiosflags(ios::lowercase) 16Сд
setiosflags(ios::showpoint) ǿʾС
setiosflags(ios::showpos) ǿʾ
*/
int main(int argc, char** argv)
{
cout << string(80, '=') << endl;
streamsize prec = cout.precision();
cout << "default precision: " << prec << endl;
double pi = 3.1415926;
cout << "ouput pi:" << endl;
cout << setw(10) << setprecision(2) << pi << setprecision(prec) << endl;
cout << setw(10) << setiosflags(std::ios::fixed) << setiosflags(std::ios::right) << setprecision(2) << pi << setprecision(prec) << endl;
cout << string(80, '=') << endl;
cout << "output number: " << endl;
const int ival = 27;
cout << "oct: " << std::oct << ival << endl;
cout << "dec: " << std::dec << ival << endl;
cout << "hex: " << std::hex << ival << endl;
cout << "hex: " << std::uppercase << std::hex << ival << endl;
return 0;
}
| true |
f919440606f47a87dd5626879a86e6e9f208c52f | C++ | djeemie2000/MidiPlayground | /DueSerialReadTest/DueSerialReadTest.ino | UTF-8 | 621 | 2.734375 | 3 | [] | no_license | void setup() {
// put your setup code here, to run once:
const int OutBaudRate = 115200;
Serial.begin(115200);
Serial.println("Listening...");
const int InBaudRate = 31250;//19200;//9600;
Serial3.begin(InBaudRate);
}
void loop() {
// put your main code here, to run repeatedly:
int Cntr = 0;
while(true)
{
int Available = 0<Serial3.available();
if(0<Available)
{
int Value = Serial3.read();
Serial.print(Cntr++);
Serial.print(":");
Serial.print(Value, HEX);
Serial.print(" (");
Serial.print(Available, DEC);
Serial.println(")");
}
}
}
| true |
87a4e680849311c177dc6d64569ee6525de1c675 | C++ | itay-rafee/cpp_snowman_b | /MyMain.cpp | UTF-8 | 1,419 | 3.078125 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <stdexcept>
#include <math.h>
#include <thread>
#include <chrono>
#include "snowman.hpp"
using namespace std;
// using namespace ariel;
int build_snowman()
{
int ans = 0;
int len = 8;
for (size_t i = 0; i < len; i++)
{
ans = ans + pow(10, i) * (rand() % 4 + 1);
}
return ans;
}
int main()
{
int second = 1000;
int n = 11111111;
string s = ariel::snowman(n);
cout << "n = " + to_string(n) + ":" << endl;
cout << s << endl;
this_thread::sleep_for(chrono::milliseconds(second));
n = 22222222;
s = ariel::snowman(n);
cout << "\nn = " + to_string(n) + ":" << endl;
cout << s << endl;
this_thread::sleep_for(chrono::milliseconds(second));
n = 33333333;
s = ariel::snowman(n);
cout << "\nn = " + to_string(n) + ":" << endl;
cout << s << endl;
this_thread::sleep_for(chrono::milliseconds(second));
n = 44444444;
s = ariel::snowman(n);
cout << "\nn = " + to_string(n) + ":" << endl;
cout << s << endl;
this_thread::sleep_for(chrono::milliseconds(second));
int j = 50;
for (size_t i = 0; i < j; i++)
{
n = build_snowman();
s = ariel::snowman(n);
cout << "\nn = " + to_string(n) + ":" << endl;
cout << s << endl;
this_thread::sleep_for(chrono::milliseconds(second));
}
return 0;
}
// g++ -o m snowman.cpp MyMain.cpp | true |
8dbbbef42ae8d0c7995b27c6fa754ab879e0ffae | C++ | JasperStas/THO78-Roborescue | /Kjeld_Perquin/QT_Map_Test/map.cpp | UTF-8 | 1,253 | 3.40625 | 3 | [] | no_license | #include "map.h"
#include <iostream>
Map::Map():
nrOfRows(0),
nrOfColumns(0)
{
}
Map::Map(int rows, int columns):
nrOfRows(rows),
nrOfColumns(columns)
{
for(int i = 0; i < nrOfRows * nrOfColumns; i++)
{
tiles.push_back(new Tile);
}
}
Tile* Map::getTile(int row, int column)
{
return tiles[row * nrOfColumns + column];
}
int Map::getRows()
{
return nrOfRows;
}
int Map::getColumns()
{
return nrOfColumns;
}
std::ostream& operator<<(std::ostream& stream, Map& map)
{
stream << map.nrOfRows << ' ' << map.nrOfColumns << std::endl;
for(int columns = 0; columns < map.nrOfColumns; columns++)
{
for(int rows = 0; rows < map.nrOfRows; rows++)
{
stream << *map.tiles[columns*map.nrOfColumns + rows] << std::endl;
}
}
return stream;
}
std::istream& operator>>(std::istream& stream, Map& map)
{
for(int columns = 0; columns < map.nrOfColumns; columns++)
{
for(int rows = 0; rows < map.nrOfRows; rows++)
{
Tile *tile = new Tile;
stream >> *tile;
map.tiles[columns*map.nrOfColumns + rows] = tile;
}
}
return stream;
}
| true |
3ee01f7e2697f98837de5d2e05670b6bff3c72e3 | C++ | burybury/traffic_counter_old_vs | /Sunbeam Alpine/src/road/RoadDetector.cpp | UTF-8 | 4,737 | 2.515625 | 3 | [] | no_license | #include <road\RoadDetector.h>
#include <helper\Multiplex.h>
#include <iostream>
#include <opencv2\calib3d.hpp>
#include <opencv2\imgproc.hpp>
#include <opencv2\core.hpp>
#include <tuple>
using namespace cv;
using namespace std;
cv::Mat RoadDetector::largest_contour_mask(const cv::Mat& src)
{
double area{ 0 }, largest{ 0 };
double length{ 0 }, longest{ 0 };
int largestIndex{ 0 }, longestIndex{ 0 };
vector< vector< cv::Point> > contours;
findContours(src, contours, RETR_EXTERNAL, CHAIN_APPROX_NONE);
//Mat draw_contours = Mat::zeros(src.size(), CV_8UC3);
for (int i = 0; i < contours.size(); ++i)
{
area = contourArea(contours[i]);
if (area > largest) {
largest = area;
largestIndex = i;
}
length = arcLength(contours[i], true);
if (length > longest) {
longest = length;
longestIndex = i;
}
//// default all to grey
//drawContours(draw_contours, contours, i, Scalar(100, 100, 100), 2, 8);
}
//// largest area is blue
//drawContours(draw_contours, contours, largestIndex, Scalar(255, 0, 0), 2, 8);
//// longest area is red
//drawContours(draw_contours, contours, longestIndex, Scalar(0, 0, 255), 2, 8);
//// largest is bound with green rect
//Rect bounding_rect_largest = boundingRect(contours[largestIndex]);
//cv::rectangle(draw_contours, bounding_rect_largest, Scalar(0, 255, 0), 2);
Mat mask = Mat::zeros(src.size(), CV_8UC1);
cv::drawContours(mask, contours, largestIndex, Scalar(255, 255, 255), -1);
return mask;
}
cv::Mat RoadDetector::morph(const cv::Mat & src)
{
int morph_size = 1;
Mat morphed;
Mat element = getStructuringElement(MorphShapes::MORPH_RECT, Size(morph_size, morph_size));
// Apply the 'opening' morphology operation
morphologyEx(src, morphed, MORPH_OPEN, element, cv::Point(-1, -1), 2, BORDER_CONSTANT);
// 'close' artifacts on the road
morph_size = 3;
element = getStructuringElement(MorphShapes::MORPH_RECT, Size(morph_size, morph_size));
morphologyEx(morphed, morphed, MORPH_CLOSE, element, cv::Point(-1, -1), 2, BORDER_CONSTANT, Scalar(0, 0, 0));
return morphed;
}
cv::Mat RoadDetector::perform(const cv::Mat & src)
{
// resize for performance
Mat resized;
resize(src, resized, cv::Size(), resize_ratio, resize_ratio);
Multiplex mpx(4, 4, resized.size(), "Perform");
// Alternate 1-liner for whole code below, but it's slightly worse
//Mat in_range;
//inRange(resized_hsv, Scalar(_lowerb_h, _lowerb_s, _lowerb_v), Scalar(_upperb_h, _upperb_s, _upperb_v), in_range);
//mpx.Add(in_range, "in_range");
// convert to HSV
Mat resized_hsv;
cv::cvtColor(resized, resized_hsv, cv::COLOR_BGR2HSV);
mpx.Add(resized_hsv, "resized_hsv");
// color segmentation
Mat mean_shifted;
pyrMeanShiftFiltering(resized_hsv, mean_shifted, _sp, _sr, _maxLevel);
mpx.Add(mean_shifted, "mean_shifted");
// split into channels
vector<Mat> channels(3);
split(resized_hsv, channels);
const Mat ch1 = channels[0];
const Mat ch2 = channels[1];
const Mat ch3 = channels[2];
mpx.Add(ch1, "ch1");
mpx.Add(ch2, "ch2");
mpx.Add(ch3, "ch3");
// threshold 'not-road' as precise as possible
Mat ch1_thresholded;
Mat ch2_thresholded;
threshold(ch1, ch1_thresholded, _threshold1, 255, 0);
threshold(ch2, ch2_thresholded, _threshold2, 255, 1);
mpx.Add(ch1_thresholded, "ch1_thresholded");
mpx.Add(ch2_thresholded, "ch2_thresholded");
// 'ch1 & ch2' for filtering
Mat and_ch1_ch2;
bitwise_and(ch1_thresholded, ch2_thresholded, and_ch1_ch2);
mpx.Add(and_ch1_ch2, "and_ch1_ch2");
// remove bad pixels
Mat morph_opened = morph(and_ch1_ch2);
mpx.Add(morph_opened, "morph");
// mark largest contour as road
Mat road_mask = largest_contour_mask(morph_opened);
mpx.Add(road_mask, "road_mask");
//showMissionControl();
mpx.Show();
return road_mask;
}
void RoadDetector::showMissionControl()
{
AddSliders();
}
void RoadDetector::AddSliders()
{
//createTrackbar("sp", MISSION_CONTROL_W_NAME, &_sp, 255);
//createTrackbar("sr", MISSION_CONTROL_W_NAME, &_sr, 255);
//createTrackbar("maxLevel", MISSION_CONTROL_W_NAME, &_maxLevel, 8);
//createTrackbar("low", MISSION_CONTROL_W_NAME, &_low, 255);
//createTrackbar("high", MISSION_CONTROL_W_NAME, &_high, 255);
createTrackbar("lowerb_h", MISSION_CONTROL_W_NAME, &_lowerb_h, 255);
createTrackbar("lowerb_s", MISSION_CONTROL_W_NAME, &_lowerb_s, 255);
createTrackbar("lowerb_v", MISSION_CONTROL_W_NAME, &_lowerb_v, 255);
createTrackbar("upperb_h", MISSION_CONTROL_W_NAME, &_upperb_h, 255);
createTrackbar("upperb_s", MISSION_CONTROL_W_NAME, &_upperb_s, 255);
createTrackbar("upperb_v", MISSION_CONTROL_W_NAME, &_upperb_v, 255);
}
RoadDetector::RoadDetector()
{
namedWindow(MISSION_CONTROL_W_NAME);
}
RoadDetector::~RoadDetector()
{
destroyWindow(MISSION_CONTROL_W_NAME);
} | true |
2adb399b7645c8963f0c75565969ed891f928f9a | C++ | BlitzZart/CuteLilWebserver | /CuteLilWebserver/CuteLilWebserver/CLWS.h | UTF-8 | 3,867 | 2.59375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <atomic>
#include <map>
#include "ClientConnection.h"
#pragma comment(lib, "Ws2_32.lib")
#define DEFAULT_PORT "27015"
std::map<ClientConnection*, ClientConnection> connections;
int error = 0;
SOCKET initServer() {
WSADATA wsaData;
int iResult;
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed: %d\n", iResult);
error = 1;
return NULL;
}
struct addrinfo *result = NULL, *ptr = NULL, hints;
ZeroMemory(&hints, sizeof (hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;
// Resolve the local address and port to be used by the server
iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
if (iResult != 0) {
printf("getaddrinfo failed: %d\n", iResult);
WSACleanup();
error = 1;
return NULL;
}
SOCKET ListenSocket = INVALID_SOCKET;
// Create a SOCKET for the server to listen for client connections
ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
if (ListenSocket == INVALID_SOCKET) {
printf("Error at socket(): %ld\n", WSAGetLastError());
freeaddrinfo(result);
WSACleanup();
error = 1;
return NULL;
}
// Setup the TCP listening socket
iResult = bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen);
if (iResult == SOCKET_ERROR) {
printf("bind failed with error: %d\n", WSAGetLastError());
freeaddrinfo(result);
closesocket(ListenSocket);
WSACleanup();
error = 1;
return NULL;
}
freeaddrinfo(result);
if (listen(ListenSocket, SOMAXCONN) == SOCKET_ERROR) {
printf("Listen failed with error: %ld\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
error = 1;
return NULL;
}
error = 0;
return ListenSocket;
}
void removeConnection(ClientConnection cC) {
connections.erase(&cC);
}
void removeAllConnections() {
for (std::map<ClientConnection*, ClientConnection>::iterator iter = connections.begin(); iter != connections.end(); ++iter) {
iter->second.killMe();
}
connections.clear();
}
void userInOut() {
std::string s;
// wait for server initialisation
std::this_thread::sleep_for(std::chrono::milliseconds(250));
std::cout << "----------------------------" << std::endl;
if (error == 0) std::cout << "------Lil WS Started--------" << std::endl;
std::cout << "----Enter \"stop\" to quit----" << std::endl;
std::cout << "----------------------------\n" << std::endl;
for (;;) {
std::cin >> s;
if (s == "stop") {
break;
}
}
removeAllConnections();
WSACleanup();
exit(0);
}
int provideClientSockets(SOCKET &ListenSocket) {
for (;;) {
SOCKET ClientSocket = INVALID_SOCKET;
// accept a client socket
ClientSocket = accept(ListenSocket, NULL, NULL);
if (ClientSocket == INVALID_SOCKET) {
printf("accept failed: %d\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
error = 1;
return error;
}
// start new client socket object
ClientConnection cC = ClientConnection(ClientSocket);
// store connection
connections.insert(std::pair<ClientConnection*, ClientConnection>(&cC, cC));
}
error = 0;
return error;
}
void serverInitFailedMsg() {
printf("server initialization faild\n");
printf("restart program\n");
// wait for termiation - user input "stop"
for (;;) {}
}
void clientSocketFailedMsg() {
printf("client socket faild\n");
printf("restart program\n");
// wait for termiation (user input "stop" or closing window)
for (;;) {}
}
int main() {
std::thread inputThread(userInOut);
// init server and get ListenSocket
SOCKET ListenSocket = initServer();
if (error != 0) {
serverInitFailedMsg();
}
else {
// server initialized
if (provideClientSockets(ListenSocket) != 0) {
clientSocketFailedMsg();
}
}
return error;
} | true |
7b4274f0debc905d9f6768f067b1fd462ee573e7 | C++ | Shivamj075/CodeForBetter | /ArithmeticSlices.cpp | UTF-8 | 1,058 | 2.90625 | 3 | [] | no_license | //LeetCode
class Solution {
public:
int numberOfArithmeticSlices(vector<int>& A) {
if(A.size()<3)
return 0;
int i=0,j=1,k=2,len=2,ans=0;
while(k<A.size()){
if(A[k]-A[k-1]==A[j]-A[i]){
len++;
k++;
continue;
}
ans+=((len-1)*(len-2))/2;
i = k-1;
j=k;
len=2;
k++;
}
ans+=((len-1)*(len-2))/2;
return ans;
}
/*
int numberOfArithmeticSlices(vector<int>& A) {
if (A.size() < 3)
return 0;
int count = 0, contribution = 0, dist = A[1] - A[0];
for (int i = 2; i < A.size(); ++i)
{
if (A[i] - A[i - 1] == dist)
{
++contribution;
count += contribution;
continue;
}
contribution = 0;
dist = A[i] - A[i - 1];
}
return count;
}*/
};
| true |
7a339d803ff831e0dd42d3bfc962ef4cf2e3a3bc | C++ | PranavRayudu/Advent-of-Code-2020 | /day21_1.cpp | UTF-8 | 3,182 | 3.046875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
#include <set>
#include <sstream>
#include <algorithm>
// https://adventofcode.com/2020/day/21
using namespace std;
// trim from start (in place)
static inline void ltrim(string &s) {
s.erase(s.begin(), find_if(s.begin(), s.end(), [](unsigned char ch) {
return !isspace(ch);
}));
}
// trim from end (in place)
static inline void rtrim(string &s) {
s.erase(find_if(s.rbegin(), s.rend(), [](unsigned char ch) {
return !isspace(ch);
}).base(), s.end());
}
// trim from both ends (copying)
static inline string trim(string s) {
ltrim(s);
rtrim(s);
return s;
}
vector<string> tokenize(string l, char delim) {
stringstream ls(l);
vector<string> tokens;
string t;
while (getline(ls, t, delim))
if (!t.empty())
tokens.push_back(trim(t));
return tokens;
}
template <typename T>
set<T> vecToSet(vector<T> v) {
return {v.begin(), v.end()};
}
template <typename T>
set<T> diff(set<T> a, set<T> b) {
set<T> difference;
set_difference(
a.begin(), a.end(), b.begin(), b.end(),
inserter(difference, difference.begin()));
return difference;
}
// https://stackoverflow.com/questions/13448064/how-to-find-the-intersection-of-two-stdset-in-c
template <typename T>
set<T> intersection(set<T> a, set<T> b) {
set<T> intersect;
set_intersection(
a.begin(), a.end(), b.begin(), b.end(),
inserter(intersect, intersect.begin()));
return intersect;
}
void rm(pair<set<string>, set<string>> food,
vector<pair<set<string>, set<string>>> &foods) {
for (auto &f : foods) {
f.first = diff(f.first, food.first);
f.second = diff(f.second, food.second);
}
}
pair<set<string>, set<string>> common(
pair<set<string>, set<string>> a, pair<set<string>, set<string>> b) {
return {intersection(a.first, b.first), intersection(a.second, b.second)};
}
template <typename T>
bool in(T t, set<T> con) {
auto it = con.find(t);
return it != con.end();
}
int main() {
vector<pair<set<string>, set<string>>> foods;
set<string> allergens;
string line;
while(getline(cin, line)) {
int st = line.find("(contains ");
int end = line.find(")");
auto f = vecToSet(tokenize(line.substr(0, st), ' '));
auto a = vecToSet(tokenize(line.substr(st+10, end-st-10), ','));
foods.push_back({f, a});
allergens.insert(a.begin(), a.end());
}
// alt-intersection test
for (int i = 0; i < foods.size(); i++) {
auto allergens = foods[i].second;
for (auto allergen : allergens) {
auto food = foods[i].first;
for (int j = 0; j < foods.size(); j++) {
if (i != j && in(allergen, foods[j].second)) {
food = intersection(food, foods[j].first);
}
}
if (food.size() == 1)
rm({food, {allergen}}, foods);
}
}
int tot = 0;
for (int i = 0; i < foods.size(); i++) {
tot += foods[i].first.size();
}
cout << tot << endl;
return 0;
} | true |
b01d8dea01dce06abdc2decf64eb90b6f0c06e8b | C++ | hashinisenaratne/SIFEB | /Module Codes/Prototype - Techno/Sonar/Sonar.ino | UTF-8 | 1,880 | 3.140625 | 3 | [] | no_license | #include <Wire.h>
#include <NewPing.h>
#define TRIGGER_PIN 12 // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN 11 // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
int led = 13;
byte distance;
boolean ledshow=false;
void setup() {
pinMode(led, OUTPUT);
Wire.begin(11); // join i2c bus with address #11
Wire.onReceive(receiveEvent);
Wire.onRequest(requestEvent);
Serial.begin(9600);
}
void loop() {
delay(50); // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
unsigned int uS = sonar.ping(); // Send ping, get ping time in microseconds (uS).
distance = (byte)(uS / US_ROUNDTRIP_CM); // Convert ping time to distance in cm and print result (0 = outside set distance range)
if(ledshow == true){
digitalWrite(led, HIGH);
delay(5000); // wait for 5 seconds
digitalWrite(led, LOW);
ledshow = false;
}
}
void requestEvent()
{
if(distance == 0)
distance = 200;
Wire.write(distance);
Serial.println(distance);
}
void receiveEvent(int howMany)
{
//two types of messages - s and t1
char command;
int action;
//if got one byte
if (howMany == 1){
command = Wire.read ();
if(command == 's'){
show();
}
}
/*
//if got two bytes
if (howMany == 2){
command = Wire.read ();
if(command == 't' || command == 'a'){
action= Wire.read ();
play(action);
}
Serial.println("at 2");
}*/
}
// show device
void show(){
ledshow = true;
Serial.println("Shown");
}
| true |
7bd19c98884824758154fc9d44c9ae0722f76c6e | C++ | hiliuyin/LeetCodeOJ | /Algorithms/137.SingleNumberII.cpp | UTF-8 | 1,472 | 3.71875 | 4 | [] | no_license | /*
Given an array of integers, every element appears three times except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
*/
// Solution 1: O(N) solution
int singleNumber(std::vector<int>& nums)
{
std::map<int, int> m;
for (auto it = nums.cbegin(); it != nums.cend(); ++it)
{
if (m.find(*it) != m.end())
m[*it]++;
else
m[*it] = 1;
}
auto search = std::find_if(m.begin(), m.end(),
[&](const std::pair<int, int>& p)
{ return p.second != 3; });
return search->first;
}
// Solution 2: count the number of bits
int singleNumber(std::vector<int>& nums)
{
int count[32] = {0};
int result = 0;
for (int i = 0; i < 32; ++i)
{
for (auto&& num : nums)
{
if ((num>>i) & 1)
count[i]++;
}
result |= (count[i]%3) << i;
}
return result;
}
// Solution 3: use bit manip
int singleNumber(std::vector<int>& nums)
{
int ones = 0, twos = 0, threes = 0;
for (auto&& num : nums)
{
twos |= ones & num; // bit occurs twice
ones ^= num; // bit occurs once
threes = ones & twos; // bit occurs three times
// clear the bit which occurs three times
ones &= ~threes;
twos &= ~threes;
}
return ones;
}
| true |
c2ee1f0d832991225b38b0a0073c2aa14b832fd9 | C++ | HighPerMeshes/highpermeshes-dsl | /include/HighPerMeshes/dsl/loop_types/free_loops/ForEachEntity.hpp | UTF-8 | 1,203 | 2.75 | 3 | [
"MIT"
] | permissive | // Copyright (c) 2017-2020
//
// Distributed under the MIT Software License
// (See accompanying file LICENSE)
#ifndef DSL_LOOPTYPES_FREELOOPS_FOREACHENTITY_HPP
#define DSL_LOOPTYPES_FREELOOPS_FOREACHENTITY_HPP
#include <utility>
#include <HighPerMeshes/dsl/meshes/Range.hpp>
namespace HPM
{
//!
//! ForEachEntity iterates over all entities of a given dimension within a given mesh::Range
//! and calls the invocable `f` for each iteration.
//!
//! For example, given a range of entities `r`, `ForEachEntity(r, [](const auto& e) {})` iterates over all entities in `r`
//!
//! \tparam
//! EntityDimension The dimensionality of the entities within the mesh this function considers.
//!
//! \attention
//! `f` must be invocable with the requested entities
//!
//! \see
//! HPM::mesh::Range
//!
template <std::size_t EntityDimension, typename MeshT, typename LoopBody>
auto ForEachEntity(const ::HPM::mesh::Range<EntityDimension, MeshT>& range, LoopBody&& loop_body)
{
for (const auto& entity : range.GetEntities())
{
std::forward<LoopBody>(loop_body)(entity);
}
}
} // namespace HPM
#endif | true |
72237cf96c1310d85c7dc44886dd5c2043e4d6d8 | C++ | adrianrocamora/kng | /cpp/unordered_multimap/unordered_multimap_empty.cpp | UTF-8 | 357 | 3.3125 | 3 | [] | no_license | #include <iostream>
#include <unordered_map>
int main()
{
std::unordered_multimap<int,int> first;
std::unordered_multimap<int,int> second = {{1,10},{2,20},{1,15}};;
std::cout << "first " << (first.empty() ? "is empty" : "is not empty" ) << std::endl;
std::cout << "second " << (second.empty() ? "is empty" : "is not empty" ) << std::endl;
return 0;
}
| true |
6f084e88cfea68d4c7dc80bbfb5af5826b5ba6a5 | C++ | colehawkins3/Unit6_Hawkins_Task_4 | /main.cpp | UTF-8 | 538 | 3.109375 | 3 | [] | no_license | //Stephen Hawkins 2/20/19
//Unit 6 Assignment - Sorting
#include <iostream>
#include "accounts.h"
#include <algorithm>
using namespace std;
void printArray(int[], int);
int main()
{
cout << "\nStart: " << cpuTime() << endl;
sort(accountBalances, accountBalances+maxAccounts);
printArray(accountBalances, maxAccounts);
cout << "\nEnd: " <<cpuTime() << endl;
return 0;
}
void printArray(int arrayVals[], int size)
{
cout << "\nPrinted values in Array: " <<endl;
for(int i = 0; i < size; i++)
{
cout << arrayVals[i] << ",";
}
} | true |
51b8fb650e64591729aaa228fed44f90442db75a | C++ | Kochise/3dglrtvr | /Software rasterizer/Luke Thatcher/3DRasterizer/src/Intro3D/DepthBuffer.cpp | UTF-8 | 1,645 | 3.1875 | 3 | [] | no_license |
#include "stdafx.h"
#include "DepthBuffer.h"
#include <math.h>
DepthBuffer::DepthBuffer(UINT width, UINT height)
{
this->width = width;
this->height = height;
this->size = this->width * this->height;
this->data = new float[this->size];
this->dims = Vector2((float)(this->width - 1), (float)(this->height - 1));
}
DepthBuffer::DepthBuffer(const DepthBuffer& depthBuffer)
{
this->width = depthBuffer.width;
this->height = depthBuffer.height;
this->size = this->width * this->height;
this->data = new float[this->size];
this->dims = Vector2((float)(this->width - 1), (float)(this->height - 1));
// Copy the other buffer's data
memcpy(this->data, depthBuffer.data, this->size * sizeof(float));
}
DepthBuffer::~DepthBuffer(void)
{
if (this->data)
{
delete [] this->data;
this->data = NULL;
}
}
float DepthBuffer::GetValue(UINT pixelIndex) const
{
return this->data[pixelIndex];
}
void DepthBuffer::SetValue(UINT pixelIndex, float value)
{
this->data[pixelIndex] = value;
}
void DepthBuffer::Clear(float value)
{
for (UINT i = 0; i < size; i++)
{
this->data[i] = value;
}
}
UINT DepthBuffer::GetWidth(void) const
{
return this->width;
}
UINT DepthBuffer::GetHeight(void) const
{
return this->height;
}
float DepthBuffer::SamplePoint(const Vector2& texCoord) const
{
float x = fmod(texCoord.X, 1.0f);
float y = fmod(texCoord.Y, 1.0f);
Vector2 pixelPos = (dims * Vector2(x,y)) + Vector2(0.5f, 0.5f);
pixelPos = Vector2::Clamp(pixelPos, Vector2(0, 0), dims);
return this->data[(((int)floor(pixelPos.Y)) * this->width) + ((int)floor(pixelPos.X))];
} | true |
bcfb72242dc20c765a139e4d0ae27e720058b33d | C++ | AlanWills/Celeste | /Celeste/Source/Resources/3D/Model.cpp | UTF-8 | 6,240 | 2.6875 | 3 | [] | no_license | #include "Resources/3D/Model.h"
#include "SOIL2/SOIL2.h"
namespace Celeste::Resources
{
//------------------------------------------------------------------------------------------------
Model::Model() :
m_meshes()
{
}
//------------------------------------------------------------------------------------------------
bool Model::doLoadFromFile(const Path& path)
{
Assimp::Importer importer;
const aiScene* scene = importer.ReadFile(path.c_str(), aiProcess_Triangulate | aiProcess_FlipUVs);
if (scene == nullptr ||
scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE ||
scene->mRootNode == nullptr)
{
ASSERT_FAIL_MSG(importer.GetErrorString());
return false;
}
std::unordered_map<std::string, Texture> textureCache;
Directory directory(path.getParentDirectory());
processNode(scene->mRootNode, scene, directory, textureCache);
return true;
}
//------------------------------------------------------------------------------------------------
void Model::doUnload()
{
for (auto& mesh : m_meshes)
{
mesh.unload();
}
}
//------------------------------------------------------------------------------------------------
void Model::processNode(
aiNode* node,
const aiScene* scene,
const Directory& parentDirectory,
std::unordered_map<std::string, Texture>& textureCache)
{
// Process all the node's meshes
for (unsigned int i = 0; i < node->mNumMeshes; ++i)
{
aiMesh* mesh = scene->mMeshes[node->mMeshes[i]];
m_meshes.emplace_back(processMesh(mesh, scene, parentDirectory, textureCache));
}
// Then do the same for each child
for (unsigned int i = 0; i < node->mNumChildren; ++i)
{
processNode(node->mChildren[i], scene, parentDirectory, textureCache);
}
}
//------------------------------------------------------------------------------------------------
Mesh Model::processMesh(
aiMesh* mesh,
const aiScene* scene,
const Directory& parentDirectory,
std::unordered_map<std::string, Texture>& textureCache)
{
std::vector<Vertex> vertices;
std::vector<unsigned int> indices;
std::vector<Texture> textures;
for (unsigned int i = 0; i < mesh->mNumVertices; ++i)
{
Vertex vertex;
// Process vertex positions, normals and texture coordinates
vertex.m_position.x = mesh->mVertices[i].x;
vertex.m_position.y = mesh->mVertices[i].y;
vertex.m_position.z = mesh->mVertices[i].z;
if (mesh->mNormals != nullptr)
{
vertex.m_normal.x = mesh->mNormals[i].x;
vertex.m_normal.y = mesh->mNormals[i].y;
vertex.m_normal.z = mesh->mNormals[i].z;
}
if (mesh->mTextureCoords[0] != nullptr)
{
vertex.m_texCoords.x = mesh->mTextureCoords[0][i].x;
vertex.m_texCoords.y = mesh->mTextureCoords[0][i].y;
}
vertices.push_back(vertex);
}
// Process indices
for (unsigned int i = 0; i < mesh->mNumFaces; ++i)
{
const aiFace& face = mesh->mFaces[i];
for (unsigned int j = 0; j < face.mNumIndices; ++j)
{
indices.push_back(face.mIndices[j]);
}
}
// Process material
if (mesh->mMaterialIndex >= 0)
{
aiMaterial* material = scene->mMaterials[mesh->mMaterialIndex];
std::vector<Texture> diffuseMaps = loadMaterialTextures(
material,
aiTextureType_DIFFUSE,
"texture_diffuse",
parentDirectory,
textureCache);
textures.insert(textures.end(), diffuseMaps.begin(), diffuseMaps.end());
std::vector<Texture> specularMaps = loadMaterialTextures(
material,
aiTextureType_SPECULAR,
"texture_specular",
parentDirectory,
textureCache);
textures.insert(textures.end(), specularMaps.begin(), specularMaps.end());
}
Mesh createdMesh;
createdMesh.load(vertices, indices, textures);
return std::move(createdMesh);
}
//------------------------------------------------------------------------------------------------
std::vector<Texture> Model::loadMaterialTextures(
aiMaterial* mat,
aiTextureType type,
const std::string& typeName,
const Directory& parentDirectory,
std::unordered_map<std::string, Texture>& textureCache)
{
std::vector<Texture> textures;
for (unsigned int i = 0; i < mat->GetTextureCount(type); ++i)
{
aiString str;
mat->GetTexture(type, i, &str);
if (textureCache.find(str.C_Str()) != textureCache.end())
{
textures.push_back(textureCache[str.C_Str()]);
}
else
{
Texture texture;
texture.m_id = textureFromFile(Path(parentDirectory.getDirectoryPath(), str.C_Str()));
texture.m_type = typeName;
texture.m_path = str.C_Str();
textures.push_back(texture);
textureCache.emplace(str.C_Str(), texture);
}
}
return textures;
}
//------------------------------------------------------------------------------------------------
unsigned int Model::textureFromFile(const Path& path, bool /*gamma*/)
{
unsigned int textureID;
glGenTextures(1, &textureID);
int width, height, nrComponents;
unsigned char* data = SOIL_load_image(path.c_str(), &width, &height, &nrComponents, 0);
ASSERT_NOT_NULL(data);
if (data != nullptr)
{
// Use engine texture resource loading for this?
// RawImageLoader DEFINITELY
GLenum format = GL_RGBA;
if (nrComponents == 1)
format = GL_RED;
else if (nrComponents == 3)
format = GL_RGB;
else if (nrComponents == 4)
format = GL_RGBA;
glBindTexture(GL_TEXTURE_2D, textureID);
glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
SOIL_free_image_data(data);
}
return textureID;
}
} | true |
5f66fd480ff9c52307edecf720ce638982c8776f | C++ | RomanCrm/RPG | /ConsoleApplication84/ConsoleApplication84/MOBS.h | WINDOWS-1251 | 982 | 2.515625 | 3 | [] | no_license | #pragma once
#include "stdafx.h"
class MOBS
{
public:
std::string Name; //
int HealthPoint; //
int Damage; //
int Armor; //
int ExpFromMob; // ,
int NextLvlHp; // , .
int NextLvlArmor; // , .
int NextLvlExp; // , .
int NextLvlDamage; // , .
void RandNextLvl1MobsStats(); //
void RandNextLvl2MobsStats(); //
MOBS();
};
| true |
64a4252c603f6a079f2bb4a3b5989979a91b4219 | C++ | zhouzilong2020/Design_Pattern_Class_Design_2020 | /State_Factory_Template_Builder_Prototype/Component/IComponent.h | UTF-8 | 963 | 3.015625 | 3 | [] | no_license | #ifndef I_COMPONENT
#define I_COMPONENT
#include "config/ComponentType.h"
/**
* Interface
* 场馆内部件的接口,实现了prototype
*/
namespace facility {
class IComponent {
protected:
/// 部件的种类
ComponentType _componentType;
/// 部件的id
int _id;
/**
* 部件的构造函数
* @param componentType 传入一个枚举形变量
* @param 部件的id
*/
IComponent(ComponentType componentType, int id) : _componentType(componentType), _id(id) {};
public:
/// 虚函数,展示该部件的信息,需要concrete class实现
virtual void showInfo() = 0;
/// 虚函数,该部件的具体功能,需要concrete class实现
virtual void doSomething() = 0;
/// 虚函数,克隆该部件,为prototype必要接口,需要concrete class实现
virtual IComponent *clone() = 0;
};
}
#endif | true |
cf68dba3302e9a891bddf4286b981dcf94c4697f | C++ | zhiayang/mx | /source/Loader/Memory/PhysMM.cpp | UTF-8 | 5,042 | 2.5625 | 3 | [] | no_license | // PhysMM.c
// Copyright (c) 2011-2013, <zhiayang@gmail.com>
// Licensed under Creative Commons Attribution 3.0 Unported.
// Implements functions to allocate physical memory.
#include "../FxLoader.hpp"
namespace Memory
{
static FPL_t* CurrentFPL;
static uint32_t FPLBottomIndex;
static uint32_t NumberOfFPLPairs;
// Define a region of memory in which the VMM gets it's memory from, to create page strucures.
static uint64_t ReservedRegionForVMM;
static uint64_t LengthOfReservedRegion;
static uint64_t ReservedRegionIndex = (uint64_t) -0x1000;
uint64_t PageAlignDown(uint64_t x)
{
return x & ((uint64_t) ~0xFFF);
}
uint64_t PageAlignUp(uint64_t x)
{
return PageAlignDown(x + 0xFFF);
}
uint64_t AllocateFromReserved(uint64_t sz)
{
// we need this 'reserved' region especially to store page tables/directories etc.
// if not, we'll end up with a super-screwed mapping.
// possibly some overlap as well.
ReservedRegionIndex += (sz * 0x1000);
// memset((void*) (ReservedRegionForVMM + ReservedRegionIndex), 0x00, 0x1000);
return ReservedRegionForVMM + ReservedRegionIndex;
}
uint64_t AllocatePage_NoMap()
{
if(CurrentFPL->Pairs[FPLBottomIndex].LengthInPages > 1)
{
CurrentFPL->Pairs[FPLBottomIndex].LengthInPages--;
uint64_t raddr = CurrentFPL->Pairs[FPLBottomIndex].BaseAddr;
CurrentFPL->Pairs[FPLBottomIndex].BaseAddr += 0x1000;
// printk("[%x]\n", raddr);
return raddr;
}
else if(CurrentFPL->Pairs[FPLBottomIndex].LengthInPages == 1)
{
uint64_t raddr = CurrentFPL->Pairs[FPLBottomIndex].BaseAddr;
CurrentFPL->Pairs[FPLBottomIndex].BaseAddr = 0;
CurrentFPL->Pairs[FPLBottomIndex].LengthInPages = 0;
// Set the pointer to the next (B,L) pair.
FPLBottomIndex++;
return raddr;
}
else if(CurrentFPL->Pairs[FPLBottomIndex].BaseAddr == 0 && CurrentFPL->Pairs[FPLBottomIndex].LengthInPages == 0)
{
if(CurrentFPL->Pairs[FPLBottomIndex + 1].LengthInPages > 0)
FPLBottomIndex++;
else if(CurrentFPL->Pairs[FPLBottomIndex - 1].LengthInPages > 0)
FPLBottomIndex--;
return AllocatePage_NoMap();
}
return 0;
}
void FreePage_NoUnmap(uint64_t PageAddr)
{
for(uint32_t i = 0; i < NumberOfFPLPairs; i++)
{
if(PageAddr == CurrentFPL->Pairs[i].BaseAddr + (CurrentFPL->Pairs[i].LengthInPages * 0x1000))
{
CurrentFPL->Pairs[i].LengthInPages++;
return;
}
else if(PageAddr == CurrentFPL->Pairs[i].BaseAddr - 0x1000)
{
CurrentFPL->Pairs[i].BaseAddr -= 0x1000;
CurrentFPL->Pairs[i].LengthInPages++;
return;
}
else if(CurrentFPL->Pairs[i].BaseAddr == 0 && CurrentFPL->Pairs[i].LengthInPages == 0)
{
// Try not to create a new FPL
CurrentFPL->Pairs[i].BaseAddr = PageAddr;
CurrentFPL->Pairs[i].LengthInPages = 1;
NumberOfFPLPairs++;
return;
}
// Doesn't matter if it's not ordered, we'll get there sooner or later.
else
{
CurrentFPL->Pairs[NumberOfFPLPairs].BaseAddr = PageAddr;
CurrentFPL->Pairs[NumberOfFPLPairs].LengthInPages = 1;
NumberOfFPLPairs++;
return;
}
}
}
void InitialiseFPLs(MemoryMap_type* MemoryMap)
{
// First, allocate a single 4K page for our FPL.
CurrentFPL = (FPL_t*) AllocateFromReserved();
// Make sure they're 0, so we don't get any rubbish entries. Quite a problem.
// memset((void*) CurrentFPL, 0, 0x1000);
NumberOfFPLPairs = 0;
for(uint16_t i = 0; i < MemoryMap->NumberOfEntries; i++)
{
if(MemoryMap->Entries[i].MemoryType == G_MemoryTypeAvailable && MemoryMap->Entries[i].BaseAddress >= 0x00100000)
{
// It's available memory, add a (B,L) pair.
CurrentFPL->Pairs[NumberOfFPLPairs].BaseAddr = PageAlignUp(MemoryMap->Entries[i].BaseAddress);
CurrentFPL->Pairs[NumberOfFPLPairs].LengthInPages = (PageAlignDown(MemoryMap->Entries[i].Length) / 0x1000) - 1;
NumberOfFPLPairs++;
}
}
FPLBottomIndex = 0;
// The bottom-most FPL would usually be from 1MB up.
// However, we must set it to the top of our kernel.
// HACK: set it to 8 mb -- this sets a limit on our kernel being no bigger than about 6 mb.
uint64_t OldBaseAddr = CurrentFPL->Pairs[0].BaseAddr;
CurrentFPL->Pairs[0].BaseAddr = PageAlignUp((uint64_t) 0x00800000 + (uint64_t) CurrentFPL);
CurrentFPL->Pairs[0].LengthInPages = CurrentFPL->Pairs[0].LengthInPages - ((CurrentFPL->Pairs[0].BaseAddr - OldBaseAddr) / 0x1000);
}
uint64_t AllocatePage()
{
// This one allocates AND maps pages.
uint64_t p = AllocatePage_NoMap();
MapAddress(p, p, 0x03);
// Do us a favour and zero the memory first.
memset((void*) p, 0x00, 0x1000);
return p;
}
void FreePage(uint64_t PageAddr)
{
FreePage_NoUnmap(PageAddr);
// FIXME: This assumes that the memory to free is 1-1 mapped.
UnmapAddress(PageAddr);
}
void InitialisePhys(MemoryMap_type* map)
{
// See HAL_InitialiseFPLs() for an in-depth explanation on this
// FPL system.
ReservedRegionForVMM = PageAlignUp(KernelEnd);
LengthOfReservedRegion = 0x00300000;
InitialiseFPLs(map);
}
}
| true |
c5608a466bef0e1066697b57312de554942cb150 | C++ | flaming-snowman/pps | /2020-2021/summer-contest-2/Factor/factor.cpp | UTF-8 | 391 | 2.546875 | 3 | [] | no_license | // Submission by Alex Proshkin
#include <bits/stdc++.h>
using namespace std;
int main() {
long long n;
cin >> n;
double end = n;
while (n % 2 == 0) {
n /= 2;
cout << 2 << ' ';
}
for (int i = 3; i <= sqrt(n); i+=2) {
while (n % i == 0) {
n /= i;
cout << i << ' ';
}
}
if (n > 2) {
cout << n;
}
}
| true |
51294885739ad8970415017b2d340546e0a0d4a0 | C++ | chuzui/courses | /cs106x/assign-2-adts/maze-generator/src/maze-generator.cpp | UTF-8 | 3,028 | 3.3125 | 3 | [] | no_license | /**
* File: maze-generator.cpp
* ------------------------
* Presents an adaptation of Kruskal's algorithm to generate mazes.
*/
#include <iostream>
#include <algorithm>
#include <set>
#include <vector>
using namespace std;
#include "console.h"
#include "simpio.h"
#include "maze-graphics.h"
#include "maze-types.h"
static int getMazeDimension(string prompt,
int minDimension = 7, int maxDimension = 50) {
while (true) {
int response = getInteger(prompt);
if (response == 0) return response;
if (response >= minDimension && response <= maxDimension) return response;
cout << "Please enter a number between "
<< minDimension << " and "
<< maxDimension << ", inclusive." << endl;
}
}
static void genCellsAndWalls(vector<wall>& walls, vector<cell>& cells, int dimension)
{
for (int i = 0; i < dimension; ++i)
for (int j = 0; j < dimension; ++j)
{
cell c = {i, j};
cells.push_back(c);
}
for (int i = 0; i < dimension; ++i)
for (int j = 0; j < dimension - 1; ++j)
{
int index = i * dimension + j;
wall w = {cells[index], cells[index+1]};
walls.push_back(w);
}
for (int i = 0; i < dimension - 1; ++i)
for (int j = 0; j < dimension; ++j)
{
int index = i * dimension + j;
wall w = {cells[index], cells[index+dimension]};
walls.push_back(w);
}
}
static bool isSameChamber(const wall& w, vector<set<cell>>& chambers, int& wallOne, int& wallTwo)
{
for (int i = 0; i < chambers.size(); ++i)
{
if (chambers[i].find(w.one) != chambers[i].end())
wallOne = i;
if (chambers[i].find(w.two) != chambers[i].end())
wallTwo = i;
}
return wallOne == wallTwo;
}
int main() {
while (true) {
int dimension = getMazeDimension("What should the dimension of your maze be [0 to exit]? ");
if (dimension == 0) break;
vector<cell> cells;
vector<wall> walls;
genCellsAndWalls(walls, cells, dimension);
MazeGeneratorView mgv;
mgv.setDimension(dimension);
mgv.drawBorder();
for(auto& w: walls)
{
mgv.drawWall(w);
}
random_shuffle(walls.begin(), walls.end());
int removed_num = 0;
int removed_total = dimension * dimension - 1;
vector<set<cell>> chambers;
for (auto& c: cells)
{
set<cell> chamber;
chamber.insert(c);
chambers.push_back(chamber);
}
for (auto& w: walls)
{
int wallOne = 0;
int wallTwo = 0;
if (!isSameChamber(w, chambers, wallOne, wallTwo))
{
mgv.removeWall(w);
chambers[wallOne].insert(chambers[wallTwo].begin(), chambers[wallTwo].end());
chambers.erase(chambers.begin() + wallTwo);
++removed_num;
::pause(100);
if (removed_num == removed_total)
break;
}
}
// for(auto& w: walls)
// {
// mgv.re(w);
// }
int i;
cin >> i;
// cout << "This is where I'd animate the construction of a maze of dimension " << dimension << "." << endl;
}
return 0;
}
| true |
bc5c4111f6ba51b1b9f70d40be49cc9b23fbe5d3 | C++ | abdulkarim723/Hotel-Reservation-System | /include/Date.hpp | UTF-8 | 657 | 2.921875 | 3 | [
"MIT"
] | permissive | #ifndef Date_HPP
#define Date_HPP
#include "HotelException.hpp"
#include <iostream>
#include <regex>
const std::regex date_expr("^\\s*[0-9]{2}\\s*.\\s*[0-9]{2}\\s*.\\s*(19|20)[0-9]{2}\\s*$");
class Date {
private:
std::string day_;
std::string month_;
std::string year_;
static const int monthDays[];
public:
Date(std::string day = "09", std::string month = "01", std::string year = "2015");
friend std::istream& operator>>(std::istream& i, Date& d);
friend std::ostream& operator<<(std::ostream& o, const Date& d);
friend bool operator==(const Date& d1, const Date& d2);
~Date();
};
#endif
| true |
98aa012858d111b525184052ed2b46677291cf1b | C++ | Catanova/C-plus-plus | /C++/4_counter_and_whileLoop.cpp | UTF-8 | 430 | 3.25 | 3 | [] | no_license | # include <iostream>
using namespace std;
int main ()
{
float a, b;
cout << "enter a value: ";
cin >> a;
int count =0;
//while(a >0 && a < 10) // while accept only range number.
while(0<a<10 && a !=-9)
// while (a !=-9) -9 is our sentinel value
{
cout << "enter a value: ";
cin >> a;
count = count +1;
}
cout << "a is: "<< a<< endl;
cout << "Counter: "<< count << endl;
}
| true |
e4d19a8e43d554e93a190242f0e17f7368e29b0b | C++ | jacocal/software | /examen/primerParcial/Iterator.hpp | UTF-8 | 754 | 3.03125 | 3 | [] | no_license | #include "Aggregate.hpp"
#pragma once
template <class T>
class Iterator {
//friend class Aggregate;
protected:
int indx;
Iterator(){}
Aggregate<T>* lista;
public:
Iterator(const Aggregate<T>& lista) : indx(0)
{
this->lista = lista;
}
T first();
T next()
{
if(isNull()){
return lista->getElementAt(indx++);
//return lista->lista[indx++];
}else{
//return *(new T);
return NULL;
}
}
T last();
bool isNull()
{
return idx < lista->getMaxSize();
}
T* currentItem();
}; | true |
34e5ba474e66c662fc345fea643132390be7a89b | C++ | Tovermodus/monte_carlo_methods | /MikadoMonteCarlo/Medium.cpp | UTF-8 | 10,238 | 3 | 3 | [] | no_license | //
// Created by tovermodus on 12/2/20.
//
#include <sstream>
#include "Medium.h"
Medium::Medium(const MediumParameters ¶ms, std::mt19937 &rng) : parameters(params)
{
initialize_cells();
initialize_rods(rng);
if (cells[0]->get_height() < params.rod_length || cells[0]->get_height() < params.rod_length)
throw std::domain_error("rods are larger than cells");
}
void Medium::initialize_rods(std::mt19937 &rng)
{
int iterations = 0;
int total_number_of_rods = (int)(parameters.rods_per_volume * parameters.width * parameters.height);
int rod_number = 0;
while (rod_number < total_number_of_rods && iterations < parameters.rod_placing_max_iterations) {
std::shared_ptr<Rod> new_rod = create_random_rod(rng);
std::shared_ptr<Cell> cell = get_cell_of_rod(new_rod);
cell->add_rod(new_rod);
if (!rod_is_acceptable(new_rod)) {
cell->remove_rod(new_rod);
} else {
rods.push_back(new_rod);
rod_number++;
}
iterations++;
}
std::cout << rod_number << "rods placed\n";
}
double Medium::calculate_energy_for_rod(const std::shared_ptr<Rod> &rod) const
{
double ret = 0;
double rod_mass_difference = parameters.rod_length * parameters.rod_width * parameters.rod_width *
(parameters.rod_density - parameters.density);
ret += rod->get_y() * parameters.gravity * rod_mass_difference;
if (parameters.ellipsoidal_potential != 0)
ret += calculate_ellipsoidal_potential(rod);
if (!rod_is_acceptable(rod))
return 1e200;
return ret;
}
double Medium::calculate_energy() const
{
double ret = 0;
for (const std::shared_ptr<Cell> &cell : cells) {
for (int i = 0; i < cell->number_rods_in_cell(); ++i) {
std::shared_ptr<Rod> r = cell->get_rod_in_cell(i);
ret += calculate_energy_for_rod(r);
}
}
return ret;
}
bool Medium::rod_is_acceptable(const std::shared_ptr<Rod> &rod, bool log_reason) const
{
std::shared_ptr<Cell> cell_of_rod = rod->get_cell();
if (rod->get_y() - std::abs(std::sin(rod->get_angle()) * parameters.rod_length) < 0) {
if (log_reason)
std::cout << "y-overflow bottom ";
return false;
}
if (rod->get_y() + std::abs(std::sin(rod->get_angle()) * parameters.rod_length) > parameters.height) {
if (log_reason)
std::cout << "y-overflow top ";
return false;
}
if (!parameters.periodic_boundary_conditions) {
if (rod->get_x() - std::abs(std::cos(rod->get_angle()) * parameters.rod_length) < 0) {
if (log_reason)
std::cout << "x-overflow left ";
return false;
}
if (rod->get_x() + std::abs(std::cos(rod->get_angle()) * parameters.rod_length) > parameters.width) {
if (log_reason)
std::cout << "x-overflow right ";
return false;
}
}
for (int j = 0; j < cell_of_rod->number_rods_in_patch(); ++j) {
if (rod == cell_of_rod->get_rod_in_patch(j))
continue;
if (rod->check_collision(cell_of_rod->get_rod_in_patch(j))) {
if (log_reason)
std::cout << "collision ";
return false;
}
}
return true;
}
std::shared_ptr<Rod> Medium::create_random_rod(std::mt19937 &rng) const
{
std::uniform_real_distribution<> x_distrib(0, parameters.width);
std::uniform_real_distribution<> y_distrib(0, parameters.height);
std::uniform_real_distribution<> angle_distrib(0, M_PI);
double x = x_distrib(rng);
double y = y_distrib(rng);
std::shared_ptr<Cell> cell = get_cell_of_position(x, y);
return std::make_shared<Rod>(x, y, angle_distrib(rng), parameters.rod_width, parameters.rod_length, cell);
}
std::string Medium::to_string() const
{
std::ostringstream ret;
ret << std::scientific << parameters.width << " ";
ret << std::scientific << parameters.height << "\n";
ret << std::scientific << parameters.rod_width << " ";
ret << std::scientific << parameters.rod_length << "\n";
for (const std::shared_ptr<Rod> &r : rods) {
ret << std::scientific << r->get_x() << " ";
ret << std::scientific << r->get_y() << " ";
ret << std::scientific << r->get_angle() << "\n";
}
return ret.str();
}
std::shared_ptr<Cell> Medium::get_cell_of_rod(const std::shared_ptr<Rod> &rod) const
{
return get_cell_of_position(rod->get_x(), rod->get_y());
}
std::shared_ptr<Cell> Medium::get_cell_of_position(double x, double y) const
{
for (std::shared_ptr<Cell> c : cells)
if (c->check_if_position_in_cell(x, y))
return c;
return nullptr;
}
void Medium::initialize_cells()
{
int N = parameters.number_of_cells_per_direction;
double width = parameters.width / N;
double height = parameters.height / N;
if (parameters.periodic_boundary_conditions) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
cells.push_back(std::make_shared<Cell>(i * width + width / 2, j * height + height / 2,
width, height));
}
}
} else {
for (int i = 0; i <= N; i++) {
for (int j = 0; j <= N; j++) {
cells.push_back(std::make_shared<Cell>(i * width, j * height, width, height));
}
}
}
for (const std::shared_ptr<Cell> &c : cells) {
std::vector<std::shared_ptr<Cell>> neighbours = get_neighbours_of_cell(c);
c->add_neighbours(neighbours);
}
}
std::shared_ptr<Cell> Medium::get_cell_in_direction(const std::shared_ptr<Cell> &cell, int x_direction,
int y_direction) const
{
double cell_x_pos = cell->get_center_x();
double cell_y_pos = cell->get_center_y();
if (x_direction > 0)
cell_x_pos += cell->get_width();
if (x_direction < 0)
cell_x_pos -= cell->get_width();
if (y_direction > 0)
cell_y_pos += cell->get_height();
if (y_direction < 0)
cell_y_pos -= cell->get_height();
while (cell_x_pos < 0)
cell_x_pos += parameters.width;
while (cell_x_pos > parameters.width)
cell_x_pos -= parameters.width;
while (cell_y_pos < 0)
cell_y_pos += parameters.height;
while (cell_y_pos > parameters.height)
cell_y_pos -= parameters.height;
return get_cell_of_position(cell_x_pos, cell_y_pos);
}
std::vector<std::shared_ptr<Cell>> Medium::get_neighbours_of_cell(const std::shared_ptr<Cell> &cell) const
{
std::vector<std::shared_ptr<Cell>> ret;
ret.push_back(get_cell_in_direction(cell, 1, 0));
ret.push_back(get_cell_in_direction(cell, -1, 0));
ret.push_back(get_cell_in_direction(cell, 0, 1));
ret.push_back(get_cell_in_direction(cell, 0, -1));
ret.push_back(get_cell_in_direction(cell, 1, 1));
ret.push_back(get_cell_in_direction(cell, 1, -1));
ret.push_back(get_cell_in_direction(cell, -1, 1));
ret.push_back(get_cell_in_direction(cell, -1, -1));
for (const auto &c : ret)
if (c == nullptr || ret.size() != 8) {
std::cout << "this: " << cell->to_string() << "\n";
for (const auto &n : ret)
if (n != nullptr)
std::cout << "neighbours: " << n->to_string() << "\n";
else
std::cout << "neighbours: nullptr\n";
throw std::domain_error("something witht the domain went wrong");
}
return ret;
}
double Medium::calculate_ellipsoidal_potential(const std::shared_ptr<Rod> &rod) const
{
double ret = 0;
std::shared_ptr<Cell> cell_of_rod = rod->get_cell();
for (int j = 0; j < cell_of_rod->number_rods_in_patch(); ++j) {
std::shared_ptr<Rod> other = cell_of_rod->get_rod_in_patch(j);
if (other->get_x() - rod->get_x() > 2 * parameters.rod_length ||
other->get_y() - rod->get_y() > 2 * parameters.rod_length)
continue;
if (rod->ellipsoid_radius(other->get_x(), other->get_y()) == 0)
continue;
ret += parameters.ellipsoidal_potential /
std::pow(rod->ellipsoid_radius(other->get_x(), other->get_y()), 6);
ret += parameters.ellipsoidal_potential /
std::pow(other->ellipsoid_radius(rod->get_x(), rod->get_y()), 6);
}
return ret;
}
double Medium::Movement::calculate_energy_after_movement()
{
execute_movement();
double ret = m->calculate_energy();
reverse_movement();
return ret;
}
Medium::Movement::Movement(const std::shared_ptr<Medium> &m, const double time_step, std::mt19937 &rng) : m(m)
{
std::uniform_int_distribution<> cell_distrib(0, m->cells.size() - 1);
changed_cell_index = cell_distrib(rng);
if (m->cells[changed_cell_index]->number_rods_in_cell() == 0) {
nothing_to_move = true;
return;
}
std::uniform_int_distribution<> rod_distrib(0, m->cells[changed_cell_index]->number_rods_in_cell() - 1);
changed_rod_index_in_cell = rod_distrib(rng);
rod_changes_cell = false;
new_cell_index = changed_cell_index;
changed_cell = m->cells[changed_cell_index];
changed_rod = changed_cell->get_rod_in_cell(changed_rod_index_in_cell);
new_cell = changed_cell;
double amplitude_parallel = std::sqrt(2 * m->parameters.diffusion_coefficient_parallel * time_step);
double amplitude_perpendicular = std::sqrt(2 * m->parameters.diffusion_coefficient_perpendicular * time_step);
double amplitude_rotation = std::sqrt(2 * m->parameters.diffusion_coefficient_rotation * time_step);
std::uniform_real_distribution<> parallel_distrib(-amplitude_parallel, amplitude_parallel);
std::uniform_real_distribution<> perpendicular_distrib(-amplitude_perpendicular, amplitude_perpendicular);
std::uniform_real_distribution<> rotation_distrib(-amplitude_rotation, amplitude_rotation);
parallel_movement = parallel_distrib(rng);
perpendicular_movement = perpendicular_distrib(rng);
rotation_movement = rotation_distrib(rng);
}
void Medium::Movement::execute_movement()
{
if (nothing_to_move)
return;
if (!moved) {
rod_changes_cell = changed_rod->move_rod(parallel_movement, perpendicular_movement, rotation_movement);
boundary_movement =
changed_rod->apply_periodic_boundary_conditions(m->parameters.width, m->parameters.height);
if (rod_changes_cell)
new_cell = changed_cell->move_rod_to_neighbour(changed_rod);
}
moved = true;
}
void Medium::Movement::reverse_movement()
{
if (nothing_to_move)
return;
if (moved) {
changed_rod->reverse_move_rod(parallel_movement, perpendicular_movement, rotation_movement);
changed_rod->reverse_boundary_movement(boundary_movement);
changed_rod->move_to_cell(changed_cell);
}
moved = false;
}
double Medium::Movement::calculate_energy_after_movement_for_rod()
{
if (nothing_to_move)
return 0;
bool moved_before_manipulation = moved;
execute_movement();
double ret = m->calculate_energy_for_rod(changed_rod);
reverse_movement();
return ret;
}
double Medium::Movement::calculate_energy_before_movement_for_rod()
{
if (nothing_to_move)
return 0;
double ret = m->calculate_energy_for_rod(changed_rod);
return ret;
}
| true |
1f0312acf36f95c8628b52c909fd9dec46b899e4 | C++ | alexandraback/datacollection | /solutions_5709773144064000_1/C++/lunae/B.cpp | UTF-8 | 420 | 2.671875 | 3 | [] | no_license | #include <cstdio>
#include <vector>
using namespace std;
int main() {
int T;
scanf("%d",&T);
for (int tc=1; tc<=T; tc++) {
double C, F, X;
scanf("%lf%lf%lf", &C, &F, &X);
double answer = X / 2.0;
double speed = 2.0;
double t = 0;
while (t < answer) {
double t2 = t + C / speed;
answer = min(answer, t2 + X / (speed + F));
t = t2;
speed += F;
}
printf("Case #%d: %.10lf\n",tc,answer);
}
}
| true |
fbee95062c61a88e0a427e64cbf7d426241f6ffa | C++ | zizaimengzhongyue/cpp | /demo/interface.cpp | UTF-8 | 516 | 3.484375 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
class Car {
public:
virtual double getPrice() = 0;
};
class Benze : public Car {
public:
double getPrice() { return 300000; }
};
class Audi : public Car {
public:
double getPrice() { return 200000; }
};
int main()
{
vector<Car*> cs;
Benze* b = new Benze();
cs.push_back(b);
Audi* a = new Audi();
cs.push_back(a);
for (int i = 0; i < cs.size(); i++) {
cout << cs[i]->getPrice() << endl;
}
return 0;
}
| true |
e80516f2e3e7201b477e5ce60add279441dc48d3 | C++ | njoy/constants | /src/constants/map.hpp | UTF-8 | 796 | 2.984375 | 3 | [
"BSD-2-Clause"
] | permissive | template< typename Value, typename Uncertainty >
struct Map_t{
Value value;
Uncertainty uncertainty;
constexpr Map_t( Value v, Uncertainty u ):
value( v ),
uncertainty( u )
{ }
template <typename Key>
constexpr decltype(auto) operator[](Key&& key) & {
return static_cast<Value&>(value)[
std::forward<Key>(key)];
}
template <typename Key>
constexpr decltype(auto) operator[](Key&& key) && {
return static_cast<Value&&>(value)[
std::forward<Key>(key)];
}
template <typename Key>
constexpr decltype(auto) operator[](Key&& key) const& {
return static_cast<Value const&>(value)[
std::forward<Key>(key)];
}
};
// Deduction guide
template< typename Value, typename Keys >
Map_t( Value value, Keys keys ) -> Map_t< Value, Keys >;
| true |
2e6988b46bd9d1d688bd0662870dd1d02c342631 | C++ | lucabecci/cpp_programming | /basics/loops/do_while.cpp | UTF-8 | 242 | 3.296875 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
float pi = 3.14;
do
{
cout << "The short value of PI is: ";
cout << pi << endl;
}
while(pi == 3.14);
cout << "Closing the program..." << endl;
} | true |
3affa9900101bc575064aa5c59bc1a30952a20fa | C++ | alexandraback/datacollection | /solutions_5769900270288896_0/C++/slitvinov/B.cpp | UTF-8 | 1,526 | 2.578125 | 3 | [] | no_license | #include <algorithm>
#include <bitset>
#include <iostream>
#include <map>
#include <set>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <queue>
// q.push(el);
// q.front(); q.pop();
#include <sstream>
// ostringstream buf;
#include <cstdio>
// sscanf(time.c_str(), "%d:%d:%d", &H, &M, &S);
#include <limits>
// std::numeric_limits<long long>::max();
#include <cctype>
// std::toupper(c)
typedef long long ll;
int find_cn(const std::vector<std::vector<bool>>& M, int i, int j) {
int ans = 0;
if (M[i+1][j ]) ans++;
if (M[i ][j+1]) ans++;
if (M[i-1][j ]) ans++;
if (M[i ][j-1]) ans++;
return ans;
}
int main() {
int T;
std::cin >> T;
for (int icase = 1; icase<=T; icase++) {
int R, C, N;
std::cin >> R >> C >> N;
std::vector<std::vector<bool>> M(R + 2, std::vector<bool>(C + 2, false));
for (int i = 1; i<=R; i++)
for (int j = 1; j<=C; j++)
M[i][j] = true;
int nrem = R*C - N;
while (nrem--) {
int im = -1;
int jm = -1;
int nm = std::numeric_limits<int>::min();
for (int i = 1; i<=R; i++)
for (int j = 1; j<=C; j++) {
if (!M[i][j]) continue;
int const cn = find_cn(M, i, j);
if (cn>nm) {
im = i;
jm = j;
nm = cn;
}
}
M[im][jm] = false;
}
int ans = 0;
for (int i = 1; i<=R; i++)
for (int j = 1; j<=C; j++) {
if (!M[i][j]) continue;
ans += find_cn(M, i, j);
}
ans /= 2;
std::cout << "Case #" << icase << ": " << ans << '\n';
}
}
| true |
79899feb49b19b4e6fc5e3966b45958c519a312e | C++ | wcfulton2/Advanced-Cpp | /Seminar 1 Programming Exercise 2/Seminar 1 Programming Exercise 2/Programming Assignment 2.cpp | UTF-8 | 5,328 | 3.6875 | 4 | [] | no_license | //Program Name: Student Test Grader
//Description: Grade student tests from data in a file using dynamic arrays
//Developer: Bill Fulton of Baker College
//Date: 21 February 2017 - Winter
#include <string>
#include <iostream>
#include <fstream>
#include <regex>
using namespace std;
//function prototypes
void gradeTests();
int getNumber(string);
char getGrade(double, double);
void outputToScreen(string *IDs, string *answers, char *grades, int*);
string getData(string*, string*, int*);
void checkAnswers(string*, string*, char*, string, int*);
int main()
{
gradeTests(); //call the gradeTests function - line 30
system("PAUSE");
return 0;
} //end main
void gradeTests() //program entry function
{
string key;
int *numOfStudents = new int; //int pointer for the number of students in the file
*numOfStudents = getNumber("How many tests will be graded?"); //get valid user input for number of students - line 47
//create new dynaic arrays for ID, answers, and final grades
string *studentID = new string[*numOfStudents];
string *answers = new string[*numOfStudents];
char *grades = new char[*numOfStudents];
key = getData(studentID, answers, numOfStudents); //call the getData function and get the answer key - line 69
checkAnswers(studentID, answers, grades, key, numOfStudents); //check the student answers against the answer key - line 109
} //end gradeTests
int getNumber(string prompt) { //get a valid user input
string input;
bool valid = false;
regex numPattern("(-)?[0-9]+");
cout << prompt << endl; //prompt user for input
do {
cout << "Enter a positive whole number: "; //take in input
cin >> input;
cout << endl;
if (regex_match(input, numPattern) && stoi(input) >= 0) { //validate
valid = true;
}
else {
cout << "You may only enter numbers." << endl; //reject bad input
}
} while (!valid);
return atoi(input.c_str()); // return the valid input - line 35
} //end getNumber
string getData(string * studentID, string * answers, int *numOfStudents) //read from file and populate arrays
{
fstream iofile; //new filestream object
iofile.open("data.txt"); //define data.txt as the read file
string temp; //temporary storage for input
string key; //answer key
iofile >> key; //read answer key
int i = 0; //itterator for counting number of lines read and indexing arrays
iofile.ignore(numeric_limits<streamsize>::max(), '\n'); //clear input buffer
if (iofile.good()) //check for a good file
{
while (!iofile.eof() && i < *numOfStudents) //loop through file while there is still data to be read and up to the number of lines requested by the user - line 35
{
getline(iofile, temp);
studentID[i] = temp.substr(0, 8); //extract studentID
answers[i] = temp.substr(9); //extract answers
i++;
}
}
else //bad file error handling
{
cout << "File Error. Please Check the File and Try Again." << endl;
}
iofile.close(); //close file
if (i < *numOfStudents) //modify the numberOfStudents variable should the file contain data for fewer students than the user entered
{
cout << "Expected " << *numOfStudents << " entries but only found " << i << ". All available entries will be graded." << endl << endl;
*numOfStudents = i;
}
return key; //return the answer key - line 42
} //end getData
void checkAnswers(string * studentID, string * answers, char* grades, string key, int *numOfStudents) //check the student answers against the key
{
string temp; //temporary variable
int correct = 0;
int incorrect = 0;
for (int i = 0; i < *numOfStudents; i++) //iterate over each student
{
temp = answers[i]; //put each students answer in a temporary variable
for (int j = 0; j < 20; j++) //iterate over each char in temp to compare to key
{
if (temp.at(j) == key.at(j)) //if answer is correct, +2 points
correct += 2;
else if (temp.at(j) != key.at(j) && temp.at(j) != ' ') //if answer is wrong, but not blank, add 1 to the number of incorrect
incorrect++;
}
grades[i] = getGrade(correct, incorrect); //call to the getGrade function - gets letter grade and stores it in the grades array - function starts at line 136
correct = 0; //0 the correct and incorrect variables to prepare for the next student
incorrect = 0;
}
outputToScreen(studentID, answers, grades, numOfStudents); //output the studentID, answers, and grades to the screen after grading is complete - line 159
} //end checkAnswers
char getGrade(double correct, double incorrect) //get the student letter grades
{
int const MAX_SCORE = 40; //maximum possible points at 2 pointers per question
double score = 0;
char grade = ' ';
score = ((correct - incorrect) / MAX_SCORE) * 100; //get student precentage grade
//get student letter grade
if (score >= 90)
grade = 'A';
else if (score >= 80 && score <= 89.99)
grade = 'B';
else if (score >= 70 && score <= 79.99)
grade = 'C';
else if (score >= 60 && score <= 69.99)
grade = 'D';
else
grade = 'F';
return grade; //return letter grade - line 128
} //end getGrade
void outputToScreen(string *IDs, string *answers, char *grades, int *numOfStudents) //output the student id's, answers, and their letter grade to the screen
{
for (int i = 0; i < *numOfStudents; i++)
{
cout << IDs[i] << " " << answers[i] << " " << grades[i] << endl;
}
cout << endl;
} //end outputToScreen | true |
0d43862a629ae05609e6908a15c5af58cba25942 | C++ | nopesir/pds-project | /server/SymStyle.cpp | UTF-8 | 1,597 | 3.109375 | 3 | [] | no_license | //
// Created by gheb on 31/07/20.
//
#include "SymStyle.h"
SymStyle::SymStyle()
: is_bold(false), is_italic(false), is_underlined(false), font_family(DEFAULT_FONT_FAMILY), font_sz(DEFAULT_FONT_SIZE),
alignment(DEFAULT_ALIGNMENT), color(DEFAULT_COLOR) {}
SymStyle::SymStyle(bool isBold, bool isItalic, bool isUnderlined, std::string fontFamily, int fontSize, int alignment, std::string color)
: is_bold(isBold), is_italic(isItalic), is_underlined(isUnderlined), font_family(std::move(fontFamily)), font_sz(fontSize),
alignment(alignment), color(std::move(color)) {}
std::string SymStyle::get_font_family() const {
return font_family;
}
int SymStyle::get_font_sz() const {
return font_sz;
}
int SymStyle::get_alignment() const {
return alignment;
}
std::string SymStyle::getColor() const {
return color;
}
bool SymStyle::isBold() const {
return is_bold;
}
bool SymStyle::isItalic() const {
return is_italic;
}
bool SymStyle::isUnderlined() const {
return is_underlined;
}
void SymStyle::set_bold(bool bold) {
this->is_bold = bold;
}
void SymStyle::set_italic(bool italic) {
this->is_italic = italic;
}
void SymStyle::set_underlined(bool underlined) {
this->is_underlined = underlined;
}
void SymStyle::set_font_family(std::string family) {
this->font_family = std::move(family);
}
void SymStyle::set_font_sz(int size) {
this->font_sz = size;
}
void SymStyle::set_alignment(int value) {
this->alignment = value;
}
void SymStyle::set_color(std::string clr) {
this->color = std::move(clr);
} | true |
1b465a25f77017054ad2a86b50fa55040984a642 | C++ | siewkee/Data-Processing-Program | /src/Shared_Functions.cpp | UTF-8 | 13,595 | 3.328125 | 3 | [] | no_license | #include "A03_Header.h"
#include "MyTemplates.h"
vector<Point2D> Points_2D;
vector<Line2D> Lines_2D;
vector<Point3D> Points_3D;
vector<Line3D> Lines_3D;
void display_menu(string filtering_c, string sorting_c, string sorting_or)
{
cout << "\nStudent ID : 5986606" << endl;
cout << "Student Name : Hung Siew Kee" << endl;
cout << "-------------------------------" << endl;
cout << "\nWelcome to Assn3 program!" << endl;
cout << "\n1)\tRead in Data" << endl;
cout << "2)\tSpecify filtering criteria (Current: " << filtering_c << ")" << endl;
cout << "3)\tSpecify sorting criteria (Current: " << sorting_c << ")" << endl;
cout << "4)\tSpecify sorting criteria (Current: " << sorting_or << ")" << endl;
cout << "5)\tView data" << endl;
cout << "6)\tStore data" << endl;
cout << "7)\tExit program" << endl;
}
//read data
//check for duplicates before storing
void choice_1()
{
string fileName;
cout << "Please enter filename: ";
cin >> fileName;
fstream inputFile(fileName.c_str(), fstream::in);
if(!inputFile)
{
inputFile.close();
cout << "Fail to open file for reading!" << endl;
exit(-1);
}
string aLine;
int num_ofRecords = 0;
while(getline (inputFile, aLine))
{
num_ofRecords++;
vector<string> tokenStringVector = tokenizeString (aLine, ", ");
string obj_name = tokenStringVector[0];
if (obj_name == "Point2D")
{
string obj_point_x = tokenStringVector[1];
string obj_point_y = tokenStringVector[2];
tokenStringVector.clear();
tokenStringVector = tokenizeString (obj_point_x, "[");
obj_point_x = tokenStringVector[1];
int obj_point_x_int = stoi(obj_point_x);
tokenStringVector.clear();
tokenStringVector = tokenizeString (obj_point_y, "]");
obj_point_y = tokenStringVector[0];
int obj_point_y_int = stoi(obj_point_y);
Point2D point_2D(obj_point_x_int, obj_point_y_int);
bool duplicate = check_Duplicate(point_2D, Points_2D);
if (!duplicate)
Points_2D.push_back(point_2D);
}
else if (obj_name == "Point3D")
{
string obj_point_x = tokenStringVector[1];
string obj_point_y = tokenStringVector[2];
string obj_point_z = tokenStringVector[3];
int obj_point_y_int = stoi(obj_point_y);
tokenStringVector.clear();
tokenStringVector = tokenizeString (obj_point_x, "[");
obj_point_x = tokenStringVector[1];
int obj_point_x_int = stoi(obj_point_x);
tokenStringVector.clear();
tokenStringVector = tokenizeString (obj_point_z, "]");
obj_point_z = tokenStringVector[0];
int obj_point_z_int = stoi(obj_point_z);
Point3D point_3D = Point3D(obj_point_x_int, obj_point_y_int, obj_point_z_int);
bool duplicate = check_Duplicate(point_3D, Points_3D);
if (!duplicate)
Points_3D.push_back(point_3D);
}
else if (obj_name == "Line2D")
{
string obj_point_x = tokenStringVector[1];
string obj_point_y = tokenStringVector[2];
string obj_point_x2 = tokenStringVector[3];
string obj_point_y2 = tokenStringVector[4];
tokenStringVector.clear();
tokenStringVector = tokenizeString (obj_point_x, "[");
obj_point_x = tokenStringVector[1];
int obj_point_x_int = stoi(obj_point_x);
tokenStringVector.clear();
tokenStringVector = tokenizeString (obj_point_y, "]");
obj_point_y = tokenStringVector[0];
int obj_point_y_int = stoi(obj_point_y);
tokenStringVector.clear();
tokenStringVector = tokenizeString (obj_point_x2, "[");
obj_point_x2 = tokenStringVector[1];
int obj_point_x2_int = stoi(obj_point_x2);
tokenStringVector.clear();
tokenStringVector = tokenizeString (obj_point_y2, "]");
obj_point_y2 = tokenStringVector[0];
int obj_point_y2_int = stoi(obj_point_y2);
Point2D point_2D_pt1(obj_point_x_int, obj_point_y_int);
Point2D point_2D_pt2(obj_point_x2_int, obj_point_y2_int);
Line2D line_2D(point_2D_pt1, point_2D_pt2);
bool duplicate = check_Duplicate(line_2D, Lines_2D);
if (!duplicate)
Lines_2D.push_back(line_2D);
}
else if (obj_name == "Line3D")
{
string obj_point_x = tokenStringVector[1];
string obj_point_y = tokenStringVector[2];
string obj_point_z = tokenStringVector[3];
int obj_point_y_int = stoi(obj_point_y);
string obj_point_x2 = tokenStringVector[4];
string obj_point_y2 = tokenStringVector[5];
string obj_point_z2 = tokenStringVector[6];
int obj_point_y2_int = stoi(obj_point_y2);
tokenStringVector.clear();
tokenStringVector = tokenizeString (obj_point_x, "[");
obj_point_x = tokenStringVector[1];
int obj_point_x_int = stoi(obj_point_x);
tokenStringVector.clear();
tokenStringVector = tokenizeString (obj_point_z, "]");
obj_point_z = tokenStringVector[0];
int obj_point_z_int = stoi(obj_point_z);
tokenStringVector.clear();
tokenStringVector = tokenizeString (obj_point_x2, "[");
obj_point_x2 = tokenStringVector[1];
int obj_point_x2_int = stoi(obj_point_x2);
tokenStringVector.clear();
tokenStringVector = tokenizeString (obj_point_z2, "]");
obj_point_z2 = tokenStringVector[0];
int obj_point_z2_int = stoi(obj_point_z2);
Point3D point_3D_pt1(obj_point_x_int, obj_point_y_int, obj_point_z_int);
Point3D point_3D_pt2(obj_point_x2_int, obj_point_y2_int, obj_point_z2_int);
Line3D line_3D(point_3D_pt1, point_3D_pt2);
bool duplicate = check_Duplicate(line_3D, Lines_3D);
if (!duplicate)
Lines_3D.push_back(line_3D);
}
}
cout << "\n" << num_ofRecords << " records read in successfully!" << endl;
cout << "\nGoing back to main menu ..." << endl;
}
vector <string> tokenizeString(string input, string delimiter)
{
size_t pos = 0;
string token;
vector <string> result;
while ((pos = input.find(delimiter)) != string::npos)
{
token = input.substr(0, pos);
result.push_back (token);
input.erase(0, pos + delimiter.length());
}
result.push_back (input);
return (result);
}
void choice_5(string filtering_c, string sorting_c, string sorting_or)
{
print_filter_cond(filtering_c, sorting_c, sorting_or);
if (filtering_c == "Point2D")
cout << "\n" << point2D_table << endl;
else if (filtering_c == "Point3D")
cout << "\n" << point3D_table << endl;
else if (filtering_c == "Line2D")
cout << "\n" << line2D_table << endl;
else if(filtering_c == "Line3D")
cout << "\n" << line3D_table << endl;
}
string choice_2(string filtering_c)
{
cout << "\n[Specifying filtering criteria (current: " << filtering_c << ")]" << endl;
string a = "Point2D";
string b = "Point3D";
string c = "Line2D";
string d = "Line3D";
cout << "\n\ta)\t" << a << " records" << endl;
cout << "\tb)\t" << b << " records" << endl;
cout << "\tc)\t" << c << " records" << endl;
cout << "\td)\t" << d << " records" << endl;
cout << "\nPlease enter your criteria(a - d): ";
char criteria;
cin >> criteria;
if (criteria == 'a')
return a;
else if (criteria == 'b')
return b;
else if (criteria == 'c')
return c;
else
return d;
}
string choice_3(string filtering_c, string sorting_c)
{
string a_point = "x-ordinate ";
string b_point = "y-ordinate";
string c_point = "Dis. Fr Origin";
string d_point = "z-ordinate";
string a_line = "Pt. 1’s (x, y)";
string b_line = "Pt. 2’s (x, y)";
string c_line = "Length";
cout << "\n[Specifying sorting criteria (current: " << sorting_c << ")]" << endl;
if (filtering_c == "Point2D")
{
cout << "\n\ta)\t" << a_point << " value" << endl;
cout << "\tb)\t" << b_point << " value" << endl;
cout << "\tc)\t" << c_point << " value" << endl;
cout << "\nPlease enter your criteria(a - c): ";
char criteria;
cin >> criteria;
if (criteria == 'a')
{
cout << "\nStoring criteria successfully set to " << a_point << "!" << endl;
return a_point;
}
else if (criteria == 'b')
{
cout << "\nStoring criteria successfully set to " << b_point << "!" << endl;
return b_point;
}
else
{
cout << "\nStoring criteria successfully set to " << c_point << "!" << endl;
return c_point;
}
}
else if (filtering_c == "Point3D")
{
cout << "\n\ta)\t" << a_point << " value" << endl;
cout << "\tb)\t" << b_point << " value" << endl;
cout << "\tc)\t" << d_point << " value" << endl;
cout << "\td)\t" << c_point << " value" << endl;
cout << "\nPlease enter your criteria(a - d): ";
char criteria;
cin >> criteria;
if (criteria == 'a')
{
cout << "\nStoring criteria successfully set to " << a_point << "!" << endl;
return a_point;
}
else if (criteria == 'b')
{
cout << "\nStoring criteria successfully set to " << b_point << "!" << endl;
return b_point;
}
else if (criteria == 'c')
{
cout << "\nStoring criteria successfully set to " << c_point << "!" << endl;
return c_point;
}
else
{
cout << "\nStoring criteria successfully set to " << d_point << "!" << endl;
return d_point;
}
}
else
{
cout << "\n\ta)\t" << a_line << " value" << endl;
cout << "\tb)\t" << b_line << " value" << endl;
cout << "\tc)\t" << c_line << " value" << endl;
cout << "\nPlease enter your criteria(a - c): ";
char criteria;
cin >> criteria;
if (criteria == 'a')
{
cout << "\nStoring criteria successfully set to " << a_line << "!" << endl;
return a_line;
}
else if (criteria == 'b')
{
cout << "\nStoring criteria successfully set to " << b_line << "!" << endl;
return b_line;
}
else
{
cout << "\nStoring criteria successfully set to " << c_line << "!" << endl;
return c_line;
}
}
}
string choice_4(string sorting_or)
{
cout << "\n[Specifying sorting criteria (current: " << sorting_or << ")]" << endl;
string a = "ASC";
string b = "DSC";
cout << "\n\ta)\t" << a << " order" << endl;
cout << "\tb)\t" << b << " order" << endl;
cout << "\nPlease enter your criteria(a - b): ";
char criteria;
cin >> criteria;
if (criteria == 'a')
{
cout << "\nStoring criteria successfully set to " << a << "!" << endl;
return a;
}
else
{
cout << "\nStoring criteria successfully set to " << b << "!" << endl;
return b;
}
}
void print_filter_cond(string filtering_c, string sorting_c, string sorting_or)
{
cout << "\n[View data ...]"
<< "\nfiltering criteria: " << filtering_c
<< "\nsorting criteria: " << sorting_c
<< "\nsorting order: " << sorting_or << endl;
}
void choice_6(string filtering_c, string sorting_c, string sorting_or)
{
string fileName;
cout << "\nPlease enter filename: ";
cin >> fileName;
fstream outputFile(fileName.c_str(), fstream::out);
if (outputFile.is_open())
{
outputFile << "\n[View data ...]"
<< "\nfiltering criteria: " << filtering_c
<< "\nsorting criteria: " << sorting_c
<< "\nsorting order: " << sorting_or << endl;
if (filtering_c == "Point2D")
{
outputFile << "\n" << point2D_table << endl;
cout << Points_2D.size() << "records output successfully!" << endl;
}
else if (filtering_c == "Point3D")
{
outputFile << "\n" << point3D_table << endl;
cout << Points_3D.size() << "records output successfully!" << endl;
}
else if (filtering_c == "Line2D")
{
outputFile << "\n" << line2D_table << endl;
cout << Lines_2D.size() << "records output successfully!" << endl;
}
else if(filtering_c == "Line3D")
{
outputFile << "\n" << line3D_table << endl;
cout << "\n" << Lines_3D.size() << " records output successfully!" << endl;
}
outputFile.close();
}
else
{
outputFile.close();
cout << "Fail to open file for writing!" << endl;
exit(-1);
}
}
| true |
a4863d38dd1f05b61b11349c4fd1bc6d8e7b16ae | C++ | LorenzoLeonardini/competitive | /UVa/102 - Ecological Bin Packing/102.cpp | UTF-8 | 1,619 | 2.96875 | 3 | [] | no_license | /**
UVa 102 - Ecological Bin Packaging
by Lorenzo Leonardini
Submitted: 2018-08-19
Accepted 0.010 C++
*/
#include <stdio.h>
#include <algorithm>
// Yeah... I over-complicated everything...
int main(void)
{
int bottles[9];
while(scanf("%d %d %d %d %d %d %d %d %d", bottles, bottles + 1, bottles + 2, bottles + 3, bottles + 4, bottles + 5, bottles + 6, bottles + 7, bottles + 8) != EOF)
{
char better[4] = "BCG";
char def[4] = "asd";
int min = -1;
int moves;
int indexes[3];
do
{
if(better[0] == 'B') indexes[0] = 0;
else if(better[1] == 'B') indexes[0] = 1;
else if(better[2] == 'B') indexes[0] = 2;
if(better[0] == 'G') indexes[1] = 0;
else if(better[1] == 'G') indexes[1] = 1;
else if(better[2] == 'G') indexes[1] = 2;
if(better[0] == 'C') indexes[2] = 0;
else if(better[1] == 'C') indexes[2] = 1;
else if(better[2] == 'C') indexes[2] = 2;
moves = 0;
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
if(indexes[i] == j) continue;
moves += bottles[i + j * 3];
}
}
if(moves < min || min == -1)
{
min = moves;
def[0] = better[0];
def[1] = better[1];
def[2] = better[2];
}
}
while(std::next_permutation(better, better + 3));
printf("%s %d\n", def, min);
}
}
| true |
575677973e037f7f6691c62b31446a1c6a23080d | C++ | thaoc-demo/cpp_array | /scratch.cpp | UTF-8 | 336 | 3.46875 | 3 | [] | no_license | #include<iostream>
using namespace std;
void test(int* a, int size){
for(int i=0; i<size; i++){
cout << a[i] << endl;
}
}
int main(){
int a[] = {3,1,2,5,4};
int *b = a;
// test(b, 5);
int *c = new int[3] {1,2,3};
cout << sizeof(c)/sizeof(c[0]);
// test(c, 3);
return 0;
} | true |
0e2c507e3ea28e3ad5f6f697604dadcd88a50b2d | C++ | pv-912/Programming | /C++ Files/Previous/Finalised/rearangeArrayPositiveAndNegative.cpp | UTF-8 | 865 | 3.515625 | 4 | [] | no_license | //Given an array of positive and negative numbers, arrange them such that all negative integers appear before all the positive integers in the array without using any additional data structure like hash table, arrays, etc. The order of appearance should be maintained.
//Examples:
//Input: [12 11 -13 -5 6 -7 5 -3 -6]
//Output: [-13 -5 -7 -3 -6 12 11 6 5]
#include <iostream>
using namespace std;
void swap(int& a, int& b){
int temp = b;
b = a;
a = temp;
}
int main() {
int a[] = {1,-9,8,-6,87,5,1,-10};
int size =sizeof(a)/sizeof(a[0]);
// reverse(a, size);
int j=-1;
for(int i=0; i<size; i++){
if(a[i]<0){
j++;
swap(a[i],a[j]);
}else{
continue;
}
}
for(int i=0; i<size; i++){
cout<<a[i]<<" ";
}
return 0;
}
| true |
582429896d4657e82517caf6e9ec4f870547291b | C++ | ASGitH/aie-Code-Design-And-Data-Structures | /.vs/Implicit_Conversions_and_Casting/main.cpp | UTF-8 | 1,688 | 2.765625 | 3 | [] | no_license | #include <iostream>
#include "raylib/raylib.h"
//#include "originalClass.h"
//#include "newerClass.h"
//int main() {
// originalClass ma;
// newerClass mb = ma;
//
// // For the Closed Exercise (Newer2Original),...
// // ... <Step Four>: Now we create a new object for our...
// // ... Newer Class, as well as our Original Class...
// // ... than we make sure that whatever our Newer Class...
// // ... is, it will be the same for our Original Class.
// newerClass newerObject;
// originalClass originalObject = newerObject;
//
// return 0;
//}
// ---------------------- //
// This part on the bottom is seperate from the top, make sure if I...
// ... uncomment one then want to uncomment the other...
// ... make sure to comment the other one.
// ---------------------- //
//#include <iostream>
//
//#include "originalClass.h"
//#include "newerClass.h"
//int main() {
// newerClass ma;
// originalClass mb = ma;
// return 0;
//}
// ---------------------- //
// This part on the bottom is seperate from the top, make sure if I...
// ... uncomment one then want to uncomment the other...
// ... make sure to comment the other one.
// ---------------------- //
#include "wizard.h"
int screenWidth = 960;
int screenHeight = 540;
int main() {
InitWindow(screenWidth, screenHeight, "Implicit Conversions and Casting");
SetTargetFPS(60);
wizard wizardObject;
wizardObject.name = "Steve The Wizard";
wizardObject.health = 100;
wizardObject.position = { 100, 100 };
wizardObject.rotation = 0.0f;
wizardObject.speed = 50;
while (!WindowShouldClose()) {
wizardObject.update(GetFrameTime());
BeginDrawing();
ClearBackground(RAYWHITE);
wizardObject.draw();
EndDrawing();
}
} | true |
9ce40c2d742a7e5b7bc92bda3d0ab7a3e4f62720 | C++ | raokartikkumar24/CodingCompetition | /HackerEarth/March2018Circuit/missile_bombing.cpp | UTF-8 | 540 | 3.171875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int Matarray[1002][1002] = {{0}};
void solve(int P, int A, int B, int C , int D) {
for(int i = A; i <= C; i++) {
for(int j = B; j <= D; j++) {
Matarray[i][j] ^= P;
}
}
}
void printMatrix(int N) {
for(int i = 1; i <= N; i++) {
for(int j = 1; j <= N; j++) {
cout << Matarray[i][j] << " ";
}
cout << endl;
}
}
int main()
{
int N,M,P,A,B,C,D;
cin >> N;
cin >> M;
while(M--) {
cin >> P >> A >> B >> C >> D;
solve(P, A, B, C, D);
}
printMatrix(N);
return 0;
}
| true |
72fcb155670251393a953c49ed066f0f092f6012 | C++ | tinglai/Algorithm-Practice | /LeetCode/Search in Rotated Sorted Array II/main.cpp | UTF-8 | 1,593 | 3.46875 | 3 | [] | no_license | #include <iostream>
using namespace std;
class Solution{
public:
bool search(int A[], int n, int target){
if(n == 0) return false;
if(n == 1) return target == A[0];
if(A[0] < A[n - 1]) return binarySearch(A, 0, n - 1, target);
else if(A[0] > A[n - 1]) return help(A, 0, n - 1, target);
else{
int i = 1;
int last = A[0];
for(; i < n; i++){
if(A[i] != last) break;
}
if(i == n) return target == last;
else if(A[i] > last) return help(A, i, n - 1, target);
else return binarySearch(A, i, n - 1, target);
}
}
bool help(int A[], int a, int b, int target){
int mid = (a + b) / 2;
if(a > b) return false;
if(a == b) return target == A[mid];
if(target == A[mid]) return true;
if(A[mid] >= A[a]){
if(target < A[mid] && target >= A[a]) return binarySearch(A, a, mid - 1, target);
else return help(A, mid + 1, b, target);
}
else{
if(target > A[mid] && target <= A[b]) return binarySearch(A, mid + 1, b, target);
else return help(A, a, mid - 1, target);
}
}
bool binarySearch(int A[], int a, int b, int target){
int mid = (a + b) / 2;
if(a > b) return false;
if(a == b) return A[mid] == target;
else{
if(A[mid] == target) return true;
if(A[mid] > target) return binarySearch(A, a, mid - 1, target);
else return binarySearch(A, mid + 1, b, target);
}
}
};
int main(){
int A[] = {1, 3};
//int A[] = {5,5,5,6,7,1,2,2,3,3,4,5};
int n = 2;
int target = 0;
Solution soln;
bool result = soln.search(A, n, target);
if(result) cout << "found target" << endl;
else cout << "could not find target" << endl;
}
| true |
3aa1902145954b1bd016b07fdba23e33312d479d | C++ | EBPkobli/Cpp_ASCIIOyun | /OyunSistem.cpp | UTF-8 | 3,002 | 2.671875 | 3 | [] | no_license | #include "OyunSistem.h"
void OyunSistem::OyunYukle(const char * harita) const
{
int k = 0;
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 36;j++)
{
cout << harita[k];
k++;
}
cout << endl;
}
}
void OyunSistem::konsolTemizle(const HANDLE & KonsolHWND) const
{
COORD coordScreen = { 0, 0 }; /* here's where we'll home the
cursor */
BOOL bSuccess;
DWORD cCharsWritten;
CONSOLE_SCREEN_BUFFER_INFO csbi; /* to get buffer info */
DWORD dwConSize; /* number of character cells in
the current buffer */
/* get the number of character cells in the current buffer */
bSuccess = GetConsoleScreenBufferInfo(KonsolHWND, &csbi);
//PERR(bSuccess, "GetConsoleScreenBufferInfo");
dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
/* fill the entire screen with blanks */
bSuccess = FillConsoleOutputCharacter(KonsolHWND, (TCHAR) ' ',
dwConSize, coordScreen, &cCharsWritten);
//PERR(bSuccess, "FillConsoleOutputCharacter");
/* get the current text attribute */
bSuccess = GetConsoleScreenBufferInfo(KonsolHWND, &csbi);
//PERR(bSuccess, "ConsoleScreenBufferInfo");
/* now set the buffer's attributes accordingly */
bSuccess = FillConsoleOutputAttribute(KonsolHWND, csbi.wAttributes,
dwConSize, coordScreen, &cCharsWritten);
//PERR(bSuccess, "FillConsoleOutputAttribute");
/* put the cursor at (0, 0) */
bSuccess = SetConsoleCursorPosition(KonsolHWND, coordScreen);
//PERR(bSuccess, "SetConsoleCursorPosition");
return;
}
void OyunSistem::KonsoleHandleAl(const HANDLE & kHandle)
{
_KonsolHandle = kHandle;
}
void OyunSistem::OyunuYukle(const char * dosyaYeri, char *harita)const
{
ifstream dosyaOku;
dosyaOku.open(dosyaYeri);
unsigned char Okunan[360];
int j = 0;
if (dosyaOku.is_open())
{
while (!dosyaOku.eof())
{
dosyaOku >> Okunan;
for (int i = 0; i < 36; i++)
{
cout << Okunan[i];
harita[i+j] = Okunan[i];
}
cout << endl;
j += 36;
}
}
}
Koordinat OyunSistem::oyuncuBul(char *harita) const
{
int k = 0;
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 36; j++)
{
if (harita[k] == '@')
{
Koordinat KOR{ j,i };
return KOR;
}
k++;
}
}
return Koordinat();
}
void OyunSistem::Oyna(Koordinat& oyuncuKoor, const Koordinat& Hareket, char *harita) const
{
Koordinat yeniKoordinat = {oyuncuKoor.X + Hareket.X , oyuncuKoor.Y + Hareket.Y};
int diziYeri = (yeniKoordinat.X ) + (yeniKoordinat.Y * 36);
int oyuncuYeri = (oyuncuKoor.X )+ (oyuncuKoor.Y * 36);
char a = harita[diziYeri];
char b = harita[oyuncuYeri];
switch(harita[ diziYeri ])
{
case '.':
harita[diziYeri] = '@';
harita[oyuncuYeri] = '.';
konsolTemizle(_KonsolHandle);
OyunYukle(harita);
oyuncuKoor = yeniKoordinat;
break;
case '#':
cout << "Duvar var" << endl;
//MessageBoxA(NULL, "DUVAR VAR", "Dikkat!", MB_OK);
break;
}
}
| true |
5916929ec34d9e5e53b479d58700d03276dec2c3 | C++ | zhongfq/cocos-lua | /frameworks/cclua/src/cclua/Socket.h | UTF-8 | 1,938 | 2.6875 | 3 | [
"MIT"
] | permissive | #ifndef __CCLUA_SOCKET_H__
#define __CCLUA_SOCKET_H__
#include "cclua/runtime.h"
#include <string>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <stdint.h>
NS_CCLUA_BEGIN
#define BUF_SIZE 512
typedef struct buf_t {
struct buf_t *next;
int offset;
int size;
uint8_t data[BUF_SIZE];
} buf_t;
typedef struct {
int size;
buf_t *head;
buf_t *tail;
} buf_queue_t;
class Socket
{
public:
enum Status
{
INVALID = 0,
IO_ERROR,
CONNECTING,
CONNECTED,
DISCONNECTED,
};
public:
Socket();
virtual ~Socket();
bool init();
void connect(const std::string &host, uint16_t port);
void close();
void clear();
Status get_status() { return _status; };
int bytes_available();
void flush();
bool read_ubyte(uint8_t *value);
void write_ubyte(uint8_t value);
bool read_ushort(uint16_t *value);
void write_ushort(uint16_t value);
bool read_uint(uint32_t *value);
void write_uint(uint32_t value);
bool read_uint64(uint64_t *value);
void write_uint64(uint64_t value);
bool read_float(float *value);
void write_float(float value);
bool read_double(double *value);
void write_double(double value);
bool read_bytes(uint8_t *data, int len);
void write_bytes(const uint8_t *data, int len);
private:
bool pop_bytes(buf_queue_t *queue, uint8_t *data, int len);
buf_t *pop_buf(buf_queue_t *queue);
void push_buf(buf_queue_t *queue, const uint8_t *data, int len);
void start();
void start_conntect();
private:
bool _need_quit;
Status _status;
int _fd;
std::string _host;
uint16_t _port;
buf_queue_t _send_queue;
buf_queue_t _read_queue;
std::mutex _read_mutex;
std::mutex _send_mutex;
std::thread *_socket_thread;
};
NS_CCLUA_END
#endif
| true |
fabe1d9f188f00a886db6efb347b6ed96fb8649e | C++ | adamap/code-test2 | /217containdupI.cpp | UTF-8 | 646 | 3.609375 | 4 | [] | no_license |
//Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
class Solution {
public:
bool containsDuplicate(vector<int>& nums)
{
if ( nums.size() < 2 )
{
return 0;
}
unordered_map<int, int>hash_map;
for( int i = 0; i < nums.size(); i++)
{
hash_map[nums[i]]++;
if (hash_map[nums[i]] >= 2)
{
return 1;
}
}
return 0;
}
};
| true |
f3dec561b9e1d61f54d4d06cf8215c6aca184fb3 | C++ | RicardoTaverna/PUCPR_2019 | /ExperienciaCriativa/sketch_apr04a/sketch_apr04a.ino | UTF-8 | 3,924 | 2.53125 | 3 | [] | no_license | unsigned int potenciometro;
float pwm;
unsigned int tempoPadrao = 2000;
unsigned int tempoAgregado = 10000;
float tempoS;
float tempoP;
unsigned int tempoPedestre = 15000;
unsigned int chamaSemafP;
void semaforoPedestre(){
if(chamaSemafP == 1){
digitalWrite(10, HIGH);
digitalWrite(11, LOW);
//semaforo principal em vermelho
digitalWrite(4, HIGH);
digitalWrite(5, LOW);
digitalWrite(6, LOW);
//semaforo secundario em verde
digitalWrite(7, HIGH);
digitalWrite(8, LOW);
digitalWrite(9, LOW);
delay(tempoPedestre);
for(int i = 0; i < 5; i++){
digitalWrite(10, LOW);
digitalWrite(11, HIGH);
delay(tempoPadrao/2);
digitalWrite(10, LOW);
digitalWrite(11, LOW);
delay(tempoPadrao/2);
}
}
chamaSemafP = 0;
}
void setup(){
//pinMode(2, OUTPUT);//interrupção 0
attachInterrupt(0, chave, RISING);
//pinMode(3, OUTPUT);//interrupção 1
pinMode(4, OUTPUT);//semaforo primario vermelho
pinMode(5, OUTPUT);//semaforo primario amarelo
pinMode(6, OUTPUT);//semaforo primario verde
pinMode(7, OUTPUT);//semaforo secundario vermelho
pinMode(8, OUTPUT);//semaforo secundario amarelo
pinMode(9, OUTPUT);//semaforo secundario verde
pinMode(10, OUTPUT);//semaforo pedestre verde
pinMode(11, OUTPUT);//semaforo pedestre verde
pinMode(13, OUTPUT);//Regulador de fluxo
Serial.begin(9600);
}
void chave(){
chamaSemafP = 1;
}
void loop()
{
if(chamaSemafP == 0){
potenciometro = analogRead(A0);
if(potenciometro <= 341){
Serial.println(potenciometro);
pwm = (float)map(potenciometro, 0, 341, tempoAgregado/4 , tempoAgregado/2)/10000;//Controle de tempo com o regulador de fluxo
}else{
Serial.println(potenciometro);
pwm = (float)map(potenciometro, 342, 1023, tempoAgregado/2, (2*tempoAgregado)/3)/10000;
}
tempoP = tempoAgregado*pwm;
tempoS = tempoAgregado - tempoP;
Serial.println(pwm);
Serial.println(tempoP);
Serial.println(tempoS);
//semaforo principal em vermelho
digitalWrite(4, HIGH);
digitalWrite(5, LOW);
digitalWrite(6, LOW);
//semaforo secundario em verde
digitalWrite(7, LOW);
digitalWrite(8, LOW);
digitalWrite(9, HIGH);
digitalWrite(10, LOW);
digitalWrite(11, HIGH);
delay(tempoS);
//Amarelo ligado
digitalWrite(4, HIGH);
digitalWrite(5, LOW);
digitalWrite(6, LOW);
digitalWrite(7, LOW);
digitalWrite(8, HIGH);
digitalWrite(9, LOW);
digitalWrite(10, LOW);
digitalWrite(11, HIGH);
delay(tempoPadrao);
//Tempo de segurança em vermelho
digitalWrite(4, HIGH);
digitalWrite(5, LOW);
digitalWrite(6, LOW);
digitalWrite(7, HIGH);
digitalWrite(8, LOW);
digitalWrite(9, LOW);
digitalWrite(10, LOW);
digitalWrite(11, HIGH);
delay(tempoPadrao);
//semaforo Via Principal em verde usando o fluxo como delay
digitalWrite(4, LOW);
digitalWrite(5, LOW);
digitalWrite(6, HIGH);
//semaforo secundario em vermelho
digitalWrite(7, HIGH);
digitalWrite(8, LOW);
digitalWrite(9, LOW);
digitalWrite(10, LOW);
digitalWrite(11, HIGH);
delay(tempoP);
//Amarelo ligado
digitalWrite(4, LOW);
digitalWrite(5, HIGH);
digitalWrite(6, LOW);
digitalWrite(7, HIGH);
digitalWrite(8, LOW);
digitalWrite(9, LOW);
digitalWrite(10, LOW);
digitalWrite(11, HIGH);
delay(tempoPadrao);
//Tempo de segurança em vermelho
digitalWrite(4, HIGH);
digitalWrite(5, LOW);
digitalWrite(6, LOW);
digitalWrite(7, HIGH);
digitalWrite(8, LOW);
digitalWrite(9, LOW);
digitalWrite(10, LOW);
digitalWrite(11, HIGH);
delay(tempoPadrao);
semaforoPedestre();
}
}
| true |
d9b9d8b30226649e43b66aa85453ba2a75f66949 | C++ | AndreiHokage/Game_XO | /Game_XO/Game.cpp | UTF-8 | 518 | 3.0625 | 3 | [] | no_license | #include "Game.h"
bool Game::operator==(const Game& game) const noexcept {
return this->id == game.id;
}
/*Game& Game::operator=(const Game& game) { //It's doesn't want to change the id
this->dim = game.dim;
this->player = game.player;
this->table = game.table;
this->state = game.state;
return *this;
}*/
ostream& operator<<(ostream& os, const Game& game) {
os << "Id: " << game.id << " Dim: " << game.dim << " Table: " << game.table << " Player: " << game.player << " State: " << game.state;
return os;
} | true |
9616c32d47fdff93208a084af660deda6ed4ddcb | C++ | Pengsc0616/IAmAwesome | /655. Medium - Print Binary Tree.hpp | UTF-8 | 1,211 | 3.328125 | 3 | [] | no_license | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<string>> printTree(TreeNode* root) {
int height = getHeight(root);
int weight = (1<<height)-1;//2^height -1;
vector<vector<string>> ans(height, vector<string> (weight,""));
fillVector(ans, root, 0, 0, weight-1);
return ans;
}
private:
int getHeight(TreeNode* root){
if(!root) return 0;
return max(getHeight(root->left), getHeight(root->right))+1;
}
void fillVector(vector<vector<string>> &ans, TreeNode* root, int height, int left, int right) {
if(!root) return;
int mid = (left+right)/2;
ans[height][mid] = std::to_string(root->val);
fillVector(ans, root->left, height+1, left, mid-1);
fillVector(ans, root->right, height+1, mid+1, right);
}
};
| true |
bd09af965675d14f87df6779d272dbb26781f971 | C++ | KaranTalreja/LeetCode | /src/heaters/solution.cpp | UTF-8 | 946 | 3.234375 | 3 | [] | no_license | class Solution {
public:
int findHeater(int house, vector<int>& heaters) {
int start = 0;
int end = heaters.size();
while (end - start > 1) {
int mid = start + (end - start)/2;
if (heaters[mid] <= house) start = mid;
else end = mid;
}
int retval = abs(heaters[start] - house);
if (end < heaters.size()) {
if (retval > abs(heaters[end] - house)) retval = abs(heaters[end] - house);
}
return retval;
}
int findRadius(vector<int>& houses, vector<int>& heaters) {
int retval = 0;
if (!heaters.size()) return INT_MAX;
sort(houses.begin(), houses.end());
sort(heaters.begin(), heaters.end());
int numHouses = houses.size();
for (int h = 0; h < numHouses; h++) {
int closestHeater = findHeater(houses[h], heaters);
if (retval < closestHeater) retval = closestHeater;
}
return retval;
}
};
| true |
11f60d86805392aee05102134d52ab4aceef609f | C++ | vividos/MultiplayerOnlineGame | /src/Server/GameServer/ServiceControlManager.hpp | UTF-8 | 1,408 | 2.703125 | 3 | [] | no_license | //
// MultiplayerOnlineGame - multiplayer game project
// Copyright (C) 2008-2014 Michael Fink
//
/// \file ServiceControlManager.hpp Win32 Service Control Manager (SCM) access
//
#pragma once
/// \brief Win32 classes
namespace Win32
{
// forward references
class ServiceInfo;
/// service control handle type
typedef std::shared_ptr<SC_HANDLE__> ServiceControlHandle;
/// \brief service access
/// \details instances of this class are returned by ServiceControlManager.
class Service
{
public:
/// starts service
void Start();
/// stops service
void Stop();
/// pauses service
void Pause();
/// restarts service
void Restart();
private:
/// ctor
Service(ServiceControlHandle spService)
:m_spService(spService)
{
}
private:
friend class ServiceControlManager;
/// service handle
ServiceControlHandle m_spService;
};
/// \brief service control manager
/// \details administrator access may be needed to access SCM
class ServiceControlManager
{
public:
/// ctor
ServiceControlManager();
/// registers service
Service RegisterService(const ServiceInfo& service);
/// unregisters service by service name
void UnregisterService(LPCTSTR pszServiceName);
/// opens service object
Service OpenService(LPCTSTR pszServiceName);
private:
/// handle to service control manager
ServiceControlHandle m_spSCM;
};
} // namespace Win32
| true |
67ac2731a0c43521e3a739a6ce6d269fbdca2af1 | C++ | cnsuhao/galaxy3d | /engine/lib/src/Matrix4x4.h | UTF-8 | 2,160 | 2.96875 | 3 | [] | no_license | #ifndef __Matrix4x4_h__
#define __Matrix4x4_h__
#include "Vector3.h"
#include "Vector4.h"
#include "Quaternion.h"
namespace Galaxy3D
{
//column major
class Matrix4x4
{
public:
Matrix4x4(){}
Matrix4x4(float m00, float m01, float m02, float m03,
float m10, float m11, float m12, float m13,
float m20, float m21, float m22, float m23,
float m30, float m31, float m32, float m33):
m00(m00), m01(m01), m02(m02), m03(m03),
m10(m10), m11(m11), m12(m12), m13(m13),
m20(m20), m21(m21), m22(m22), m23(m23),
m30(m30), m31(m31), m32(m32), m33(m33){}
Matrix4x4 operator *(const Matrix4x4 &quat) const;
Vector4 operator *(const Vector4 &v) const;
Vector3 MultiplyPoint(const Vector3 &v) const;
Vector3 MultiplyPoint3x4(const Vector3 &v) const;
Vector3 MultiplyDirection(const Vector3 &v) const;
Matrix4x4 Inverse() const;
Matrix4x4 Transpose() const;
std::string ToString() const;
void SetRow(int row, const Vector4 &v);
Vector4 GetRow(int row);
void SetColumn(int row, const Vector4 &v);
Vector4 GetColumn(int row);
inline static Matrix4x4 Identity() {return m_identity;}
static Matrix4x4 Translation(const Vector3 &t);
static Matrix4x4 Rotation(const Quaternion &r);
static Matrix4x4 Scaling(const Vector3 &s);
static Matrix4x4 TRS(const Vector3 &t, const Quaternion &r, const Vector3 &s);
static Matrix4x4 Perspective(float fov, float aspect, float zNear, float zFar);
static Matrix4x4 LookTo(const Vector3 &eye_position, const Vector3 &to_direction, const Vector3 &up_direction);
static Matrix4x4 Ortho(float left, float right, float bottom, float top, float zNear, float zFar);
private:
Matrix4x4(const float *ms);
public:
float m00;
float m01;
float m02;
float m03;
float m10;
float m11;
float m12;
float m13;
float m20;
float m21;
float m22;
float m23;
float m30;
float m31;
float m32;
float m33;
private:
static float m_identity[];
};
}
#endif | true |
10f00b3c294ce27d6c1ed502ac94b07987165c09 | C++ | CodeeChallenge/GetIntoRocket | /sol47.cpp | UTF-8 | 542 | 2.875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
void func(int* Arr,int n);
int main(){
int a[]={2,1,3,4,1,2,5,7,1,2,5,4,3,7,2};
int n = sizeof(a)/sizeof(a[0]);
for(int i=0;i<n;i++)
printf("%d ",a[i]);
func(a,n);
printf("\n");
for(int i=0;i<n;i++)
printf("%d ",a[i]);
return 0;
}
int func(int* Arr,int n){
int min=
for(int i = n-2; i>=0; i--){
if(Arr[i] < replace){
replace = replace ^ Arr[i];
Arr[i] = replace ^ Arr[i];
replace = replace ^ Arr[i];
continue;
}
if(Arr[i] < Arr[i+1]){
Arr[i] = Arr[i+1];
}
}
} | true |
92c880fe511922100f0d2da9995134dd52f8e8e7 | C++ | PawelKapusta/ImplementationOfGrapghUsingAdjacentList | /Vertex.h | UTF-8 | 931 | 3.234375 | 3 | [] | no_license | //
// Created by sony on 23.04.2020.
//
#ifndef ZADANIE7A_VERTEX_H
#define ZADANIE7A_VERTEX_H
#include <iostream>
using namespace std;
#define MAX 1000
int size = 0;
class Vertex {
public:
int valueTab[MAX] = {};
int valueOfVertex = 0;
int id = 0 ;
public:
void setVertexValue(int value){
for (int i : valueTab) {
if (i == value) {
cout << "Vertex with this value is already exist in this graph " << endl;
return;
}
}
id = size;
valueOfVertex = value;
valueTab[size] = value;
size ++;
}
int getVertexValue(){
if (valueOfVertex == 0){
cout << "This vertex has no special value, only default equals: ";
}
return valueOfVertex;
}
int getId(){
return id;
}
void setId(int value){
id = value;
}
};
#endif //ZADANIE7A_VERTEX_H
| true |
e97dff51300496da1d9c336283ff2ee616bcfd55 | C++ | rodrigoms2004/ancientCStudies | /Agit/CPP/Projetos/ListaLigada/lista.h | UTF-8 | 1,408 | 3.53125 | 4 | [] | no_license | #ifndef LISTA_H
#define LISTA_H
#include <iostream>
using namespace std;
template <typename TIPO> //template <class TIPO> class Lista
class Lista
{
private:
struct Node
{
TIPO valor;
Node *next;
};
Node *root;
unsigned int numero_de_elementos;
unsigned int construidos;
unsigned int destruidos;
public:
Lista()
{
numero_de_elementos = 0;
construidos = 0;
destruidos = 0;
}
~Lista()
{
if(root != NULL)
delete root;
++destruidos;
}
void inserir(int valor)
{
if (root == NULL)
{
root = new Node;
root->valor = valor;
}
else
{
Node *temp = root;
while(temp != NULL)
{
if (temp->next == NULL)
{
temp->next = new Node;
temp->next->valor = valor;
break;
} // end if
temp = temp->next;
} // end while
} // end else
++numero_de_elementos;
}
void imprimir()
{
Node *temp = root;
while(temp != NULL)
{
cout << temp->valor << '\n';
temp = temp->next;
}
}
int getNumeroElementos()
{
return numero_de_elementos;
}
};
#endif // LISTA_H
| true |
7c61f131f25d85a7a3fbc1ca4e98e63fff676b2a | C++ | zraul/LeetCode | /Powxn/Powxn.cpp | UTF-8 | 274 | 2.859375 | 3 | [] | no_license | //
// Created by 郑巍 on 2020/1/9.
//
#include "Powxn.h"
double Powxn::myPow(double x, int n) {
if (n == 0) {
return 1;
}
if (n < 0) {
n = -n;
x = 1/x;
}
return (n % 2 == 0) ? myPow(x * x, n / 2) : x * myPow(x * x, n / 2);
} | true |
0b475fd69070b4a7d120c7e6b311627e0b527b83 | C++ | SashenGovender/BattleShip | /SashenGBattleBot/PlayGame.cpp | UTF-8 | 9,012 | 2.90625 | 3 | [] | no_license | #include "PlayGame.h"
#include "windows.h"
PlayGame::PlayGame(std::string playerKey, std::string workingDir)
{
_jsonGameState = nullptr;
_playerKey = playerKey;
_workingDir = workingDir;
_gameState = new GameState();
_previousJsonGameState = nullptr;
_shootingAI = nullptr;
}
PlayGame::~PlayGame()
{
if (_gameState != nullptr)
{
delete _gameState;
_gameState = nullptr;
}
if (_jsonGameState != nullptr)
{
_jsonGameState->Release();
}
if (_previousJsonGameState != nullptr)
{
_previousJsonGameState->Release();
}
if (_shootingAI != nullptr)
{
delete _shootingAI;
_shootingAI = nullptr;
}
}
void PlayGame::Play()
{
bool dataReadSuccess = ReadGameState();
if (dataReadSuccess)
{
SetInitialGameStateAttributes();
if (_gameState->GetPhase() == 1)
{
DeployShips();
//DeployShipsFromFile();
}
else
{
PopulateGameState();
FireShot();
SaveCurrentGameStateData();
SaveFinalGameState();
}
}
}
void PlayGame::SaveFinalGameState()
{
//Has the game ended?
if (_gameState->GetPlayerMap()->GetKilled() == true || _gameState->GetOpponentMap()->GetAlive() == false)
{
std::string filePathPreviousGameState = GetPreviousGameStatePath();
if (filePathPreviousGameState.length() > 0)
{
remove(filePathPreviousGameState.c_str());
SaveCurrentGameStateData(true);
}
}
}
bool PlayGame::ReadGameState()
{
std::string filepath = _workingDir + "\\" + stateFilename;
std::string stringCurrentGameStateRead = ReadFromFile(filepath);
if (stringCurrentGameStateRead == "" || stringCurrentGameStateRead.length() == 0)//Did we read any data
{
std::cout << "Error Reading GameState Data at:" << filepath << std::endl;
return false;
}
_jsonGameState = new JsonHelper();
const char* cstringCurrentGameStateRead = stringCurrentGameStateRead.c_str();
_jsonGameState->Deserialise(cstringCurrentGameStateRead);
std::string filePathPreviousGameState = GetPreviousGameStatePath();
if (filePathPreviousGameState.length() > 0)
{
std::string previousGameStateRead = ReadFromFile(filePathPreviousGameState);
if (previousGameStateRead != "" && previousGameStateRead.length() > 0)//Did we read any data
{
_previousJsonGameState = new JsonHelper();
const char* cstringPreviousGameStateRead = previousGameStateRead.c_str();
_previousJsonGameState->Deserialise(cstringPreviousGameStateRead);
}
}
return true;
}
void PlayGame::PopulateGameState()
{
if (_gameState != nullptr)//Retrieve Previous State Data starting from Phase 2 Round 2
{
JsonHelper* playerJsonMapData = _jsonGameState->GetJsonObject("PlayerMap");
_gameState->SetPlayerMapState(playerJsonMapData);
playerJsonMapData->Release();
JsonHelper* opponentJsonMapData = _jsonGameState->GetJsonObject("OpponentMap");
_gameState->SetOpponentMapState(opponentJsonMapData);
opponentJsonMapData->Release();
_gameState->SetGameVersion(_jsonGameState->GetString("GameVersion"));
_gameState->SetGameLevel(static_cast<unsigned __int16 >(_jsonGameState->GetInt("GameLevel")));
_gameState->SetRound(static_cast<unsigned __int16 >(_jsonGameState->GetInt("Round")));
//phase should have already been stored
//JsonHelper* player1Map =_jsonGameState->GetJsonObject("Player1Map");
//JsonHelper* player1Map=_jsonGameState->GetJsonObject("Player2Map");
}
//Previous Game State
if (_previousJsonGameState != nullptr)//Retrieve Previous State Data starting from Phase 2 Round 2
{
_gameState->RestorePreviousGameState(_previousJsonGameState);
}
_gameState->DetermineHitList();
_gameState->RefineHitList();//Remove destroyed ship cells
_shootingAI = new Shooting(_gameState);
}
void PlayGame::DeployShipsFromFile()
{
std::vector<std::string> shipLoctaion;
std::string deployShipPath = "";
char exepath[MAX_PATH + 1] = { 0 };
if (GetModuleFileName(0, exepath, MAX_PATH + 1))
{
std::string fullExePath = std::string(exepath);
std::string exePathWithoutExeFileName = fullExePath.substr(0, fullExePath.find_last_of("\\"));
deployShipPath = exePathWithoutExeFileName + "\\" + "deploy.txt";
}
std::string previousGameStateRead = ReadFromFile(deployShipPath);
std::string filepath = _workingDir + "\\" + placeFilename;
WriteToFile(filepath, previousGameStateRead);
}
void PlayGame::DeployShips()
{
std::vector<std::string> shipLoctaion;
shipLoctaion.reserve(5);//expect 5 ships
if (_gameState->GetMapDimensions() == 14)
{
shipLoctaion.push_back("Battleship 1 10 South\n");
shipLoctaion.push_back("Carrier 12 8 South\n");
shipLoctaion.push_back("Cruiser 5 12 East\n");
shipLoctaion.push_back("Submarine 2 6 South\n");
shipLoctaion.push_back("Destroyer 4 1 East\n");
}
else if (_gameState->GetMapDimensions() == 10)
{
shipLoctaion.push_back("Battleship 1 1 East\n");
shipLoctaion.push_back("Carrier 5 8 South\n");
shipLoctaion.push_back("Cruiser 6 1 East\n");
shipLoctaion.push_back("Submarine 4 7 West\n");
shipLoctaion.push_back("Destroyer 1 8 East\n");
}
else if (_gameState->GetMapDimensions() == 7)
{
shipLoctaion.push_back("Battleship 0 2 North\n");
shipLoctaion.push_back("Carrier 1 6 East\n");
shipLoctaion.push_back("Cruiser 5 3 North\n");
shipLoctaion.push_back("Submarine 4 1 East\n");
shipLoctaion.push_back("Destroyer 2 1 North\n");
}
std::string filepath = _workingDir + "\\" + placeFilename;
WriteToFile(filepath, shipLoctaion);
}
void PlayGame::FireShot()
{
_shootingAI->Fire();
Point fireShot = _shootingAI->GetFireLocation();
int command = _shootingAI->GetFireCommand();
std::string filePathCommand = _workingDir + "\\" + commandFilename;
std::string shot = std::to_string(command);
shot.append(",");
shot.append(std::to_string(fireShot._x));
shot.append(",");
shot.append(std::to_string(fireShot._y));
WriteToFile(filePathCommand, shot);//the command to carry out
}
void PlayGame::SetInitialGameStateAttributes()
{
unsigned __int8 phase = static_cast<unsigned __int8 >(_jsonGameState->GetInt("Phase"));
_gameState->SetPhase(phase);
unsigned __int8 mapDimension = static_cast<unsigned __int8 >(_jsonGameState->GetInt("MapDimension"));
_gameState->SetMapDimensions(mapDimension);
}
std::string PlayGame::GetPlayerKey()
{
return _playerKey;
}
std::string PlayGame::GetWorkingDirectory()
{
return _workingDir;
}
void PlayGame::SaveCurrentGameStateData(bool gameEnded)
{
Json::Value currentGameStateToSave;
_gameState->CreatePreviousGameStateToSave(_shootingAI->GetFireLocation(), currentGameStateToSave);
Json::FastWriter writer;
std::string previousGameState = writer.write(currentGameStateToSave);
//currentGameStateToSave.Serialise(previousGameState);
//store previous game state
std::string filePathPreviousGameState = GetPreviousGameStatePath();
if ((filePathPreviousGameState.length() > 0) && gameEnded==false)
{
WriteToFile(filePathPreviousGameState, previousGameState);
}
else if ((filePathPreviousGameState.length() > 0) && gameEnded == true)
{
//lets save the final game state for review :)
std::string finalGameStatePath = filePathPreviousGameState.substr(0, filePathPreviousGameState.find_last_of(".")) +"Final.txt";
WriteToFile(finalGameStatePath, previousGameState);
}
}
//Helper Read/Write from/to file Functions
#pragma region Helpers
std::string PlayGame::GetPreviousGameStatePath()
{
std::string filePathPreviousGameState = "";
char exepath[MAX_PATH + 1] = { 0 };
if (GetModuleFileName(0, exepath, MAX_PATH + 1))
{
std::string fullExePath = std::string(exepath);
std::string exePathWithoutExeFileName = fullExePath.substr(0, fullExePath.find_last_of("\\"));
filePathPreviousGameState = exePathWithoutExeFileName + "\\" + previousGameStateFilename;
}
return filePathPreviousGameState;
}
std::string PlayGame::ReadFromFile(std::string filepath)
{
std::ifstream ifs;
ifs.open(filepath);
std::stringstream bufferStream;
bufferStream << ifs.rdbuf();
std::string bufferFileData = bufferStream.str();
ifs.close();
return bufferFileData;
}
void PlayGame::WriteToFile(std::string filepath, std::vector<std::string>& data)
{
std::ofstream ofs;
ofs.open(filepath);
for (int index = 0; index < static_cast<int>(data.size()); index++)
{
ofs << data.at(index);
}
ofs.close();
}
void PlayGame::WriteToFile(std::string filepath, std::string data, bool append)
{
std::ofstream ofs;
if (append)
{
ofs.open(filepath, std::ios_base::app);
}
else
{
ofs.open(filepath);
}
ofs << data;
ofs.close();
}
#pragma endregion | true |
1a8afaf8d6e2de9ff30bb7c538231f5206ab4aa4 | C++ | hwinter/HyLoop | /c_codes/hdw_rk4.cc | UTF-8 | 1,448 | 3.140625 | 3 | [] | no_license |
//Include a i/o library
#include <iostream>
#include <math.h>
using namespace std;
//////////////////////////////////////////////////////////////////
/*
*/
//////////////////////////////////////////////////////////////////
double derivs(double x0, double y0){
double y;
y=2.0*x0;
return(y);
}
//////////////////////////////////////////////////////////////////
/*HDW_RK4
*/
//////////////////////////////////////////////////////////////////
double hdw_rk4(double x0, double y0, double h){
//Declare variables
double k1;
double k2;
double k3;
double k4;
double f;
double yn;
double x;
double y;
f=derivs(x0, y0);
k1=h*f;
x=x0+(h/2.0);
y=y0+(k1/2.0);
f=derivs(x, y);
k2=h*f;
x=x0+(h/2.0);
y=y0+(k2/2.0);
f=derivs(x, y);
k3=h*f;
x=x0+h;
y=y0+(k3);
f=derivs(x, y);
k4=h*f;
yn=y0+(k1/6.0)+(k2/3.0)+(k3/3.0)+(k4/6.0);
return(yn);
}
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
int main(){
//Declare variables
double x0;
double y0;
double h;
double yn;
double ans;
x0=1.0;
y0=0.0;
h=1.0;
yn=hdw_rk4(x0, y0, h);
cout << yn;
cout << " \n ";
ans=(4.0-1.0);
cout << (yn-ans)/ans;
cout << " \n ";
}
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
| true |
87d81c9f30ea3631161df98e8d11c7f882da3203 | C++ | malhayek2/cs4550-p01 | /scanner.cpp | UTF-8 | 1,827 | 3.046875 | 3 | [] | no_license | #include <string>
#include <cstdlib>
using namespace std;
#include "scanner.h"
#include "debug.h"
ScannerClass::ScannerClass(const char *file)
{
MSG("Initializing ScannerClass object");
/*mLineNumber set = 1 */
this->mLineNumber=1;
this->mFin.open(file,ios::binary);
if(!mFin)
{
MSG("failed to read input file");
}
this->mLocation=0;
}
/*Getter mLinerNumber*/
int ScannerClass::GetLineNumber(){
return mLineNumber;
}
ScannerClass::~ScannerClass(){this->mFin.close();}
TokenClass ScannerClass::GetNextToken()
{
StateMachineClass StateMachine;
TokenType tt;
string lexeme;
while(true)
{
//
/*read the next char*/
char c=mFin.get();
/*increment the lexeme char by char */
lexeme += c;
MachineState ms = StateMachine.UpdateState(c,tt);
/*carriage return incrment mLineNumber*/
if(lexeme=="\n") {mLineNumber++; }
/*Break when reaching a cantmove state*/
if(ms==CANTMOVE_STATE) { break; }
/*set start_state lexeme to nothing*/
if(ms==START_STATE) { lexeme = ""; }
}
if(tt==BAD_TOKEN)
{
cout<<"Bad State: " << tt << endl;
MSG("Bad Token Read : " + tt );
exit(1);
}
/* unget() decrease the current location in the stream by one character*/
mFin.unget();
/*decrment the mLineNumber */
//MSG("Current Line Number " << this->GetLineNumber());
if(lexeme=="\n"){mLineNumber--;}
lexeme.resize(lexeme.size()-1);
TokenClass newToken(tt, lexeme);
newToken.CheckReserved();
return newToken;
}
TokenClass ScannerClass::PeekNextToken()
{
//store current state
int linenum = mLineNumber;
streamoff offset = mFin.tellg();
//get info
TokenClass T=GetNextToken();
if(mFin.eof()) //should be this...
{
cout << "Clearing..." << endl;
mFin.clear();
}
mFin.clear();//...instead of this, but works for now
//restore
mFin.seekg(offset);
mLineNumber=linenum;
return T;
} | true |
6ffbee60c7ada116945e626341d72a5f9c871eb8 | C++ | krovyakovmikhail/repohomework | /DZ_lesson_2.cpp | UTF-8 | 3,672 | 3.171875 | 3 | [] | no_license | // DZ_lesson_2.cpp : Этот файл содержит функцию "main". Здесь начинается и заканчивается выполнение программы.
//
#include <iostream>
#include <vector>
#include <algorithm>
template <typename T> // шаблонная функция обмена значений в указателе.
void Swap(T* A, T* B)
{
T buf = *A;
*A = *B;
*B = buf;
};
template <typename T>
T SortPointers(T vec)
{
auto compair = [](const int* valA, const int* valB) { return *valA < *valB; }; // на выходе сравнениедвух эл., но в них указатели, а не значения.
std::sort(vec.begin(), vec.end(), compair);
return vec;
};
int main()
{
///////////////////////////////////////////////////////////////////////////////////////////
// Задание 1.
int a = 11;
int b = 22;
int* ptr_a = &a;
int* ptr_b = &b;
std::cout <<"--before--"<< std::endl;
std::cout << "ptr_a" << " "<< *ptr_a <<std:: endl;
std::cout << "ptr_a" << " " << ptr_a << std::endl;
std::cout << std::endl;
std::cout << "ptr_b" << " "<< *ptr_b << std::endl;
std::cout << "ptr_b" << " " << ptr_b << std::endl;
std::cout << std::endl;
Swap(ptr_a, ptr_b);
std::cout << "--after--" << std::endl;
std::cout << "ptr_a" << " " << *ptr_a << std::endl;
std::cout << "ptr_a" << " " << ptr_a << std::endl;
std::cout << std::endl;
std::cout << "ptr_b" << " " << *ptr_b << std::endl;
std::cout << "ptr_b" << " " << ptr_b << std::endl;
std::cout << std::endl;
///////////////////////////////////////////////////////////////////////////////////////////
// Задание 2.
int x = 25, y=13, z = 4, i=150;
int* ptr_x = &x, *prt_y= &y, *ptr_z = &z, *ptr_i = &i;
std::vector <int*> vector = {ptr_x, prt_y, ptr_z, ptr_i}; // вектор указателей
std::cout << "-- before sort --" << std::endl;
for (auto const& element : vector)
std::cout << *element << ' ';
vector = SortPointers(vector);
std::cout << std::endl;
std::cout << "-- After sort --" << std::endl;
for (auto const& element : vector)
std::cout << *element << ' ';
}
// Запуск программы: CTRL+F5 или меню "Отладка" > "Запуск без отладки"
// Отладка программы: F5 или меню "Отладка" > "Запустить отладку"
// Советы по началу работы
// 1. В окне обозревателя решений можно добавлять файлы и управлять ими.
// 2. В окне Team Explorer можно подключиться к системе управления версиями.
// 3. В окне "Выходные данные" можно просматривать выходные данные сборки и другие сообщения.
// 4. В окне "Список ошибок" можно просматривать ошибки.
// 5. Последовательно выберите пункты меню "Проект" > "Добавить новый элемент", чтобы создать файлы кода, или "Проект" > "Добавить существующий элемент", чтобы добавить в проект существующие файлы кода.
// 6. Чтобы снова открыть этот проект позже, выберите пункты меню "Файл" > "Открыть" > "Проект" и выберите SLN-файл.
| true |
b392f59e19e4bde684d58fe7549cfbcf443af3a6 | C++ | XiaotianJin/Templates | /被遗弃的角落/bitset.cpp | UTF-8 | 964 | 2.75 | 3 | [] | no_license | LL lowbit(LL x)
{
return x & (-x);
}
struct Bit
{
LL p[maxn/64+5];
int n;
int len;
Bit(int n = 0):n(n)
{
memset(p,0,sizeof(p));
len = n/64 + (n%64 != 0);
}
void setbit(int o)
{
int id = o/64;
int tid = o%64;
p[id] |= (1ULL << tid);
//printf("**** %d %d\n",id,tid);
}
void clearbit(int o)
{
int id = o/64;
int tid = o%64;
p[id] &= ~(1ULL << tid);
}
vector<int> getbit()
{
vector<int> V;
for(int i = 0;i < len;++i)
{
LL num = p[i];
while(num)
{
LL t = lowbit(num);
num -= t;
int x = (int)log2(t+0.5);
V.push_back(x + i*64);
}
}
return V;
}
};
Bit andbit(Bit A,Bit B)
{
Bit C(A.n);
for(int i = 0;i < C.len;++i)
C.p[i] = A.p[i] & B.p[i];
return C;
}
| true |
cf3cd94edb404ca03e8f1311ce67bf5d69d6932b | C++ | WhiZTiM/coliru | /Archive/da9cf86ee07cf209cda8cb24967a9ce6-f674c1a6d04c632b71a62362c0ccfc51/main.cpp | UTF-8 | 2,756 | 3.34375 | 3 | [] | no_license | #include <functional>
#include <type_traits>
#include <iostream>
/* The usual stuff */
template<typename T>
using EnableIf = typename std::enable_if<T::value, int>::type;
template<typename...>
struct void_ { using type = void; };
template<typename... T>
using Void = typename void_<T...>::type;
namespace detail {
template<typename Sfinae, typename F, typename R, typename... Args>
struct is_callable_impl: std::false_type {};
template<typename F, typename R, typename... Args>
struct is_callable_impl<Void<decltype( std::declval<F>()(std::declval<Args>()...) )>, F, R, Args...>
: std::integral_constant<
bool
, std::is_convertible<decltype( std::declval<F>()(std::declval<Args>()...) ), R>::value
|| std::is_void<decltype( std::declval<F>()(std::declval<Args>()...) )>::value
> {};
} // detail
template<typename F, typename R, typename... Args>
struct is_callable: detail::is_callable_impl<void, F, R, Args...> {};
/* Okay now done with the preparations */
namespace crummy {
void deleter_a(int)
{ std::cout << "crummy deleter_a\n"; }
void deleter_b(int, int*)
{ std::cout << "crummy deleter_b\n"; }
} // crummy
// This is just easier to work with:
struct deleter_a {
void operator()(int i) const
{ crummy::deleter_a(i); }
};
struct deleter_b {
void operator()(int i, int* p) const
{ crummy::deleter_b(i, p); }
};
namespace detail {
struct addressof {
template<typename T>
constexpr T* operator()(T& t)
{ return std::addressof(t); }
};
} // detail
template<typename Deleter>
struct holder_type {
holder_type(int id, Deleter deleter)
: id(id)
, deleter(std::forward<Deleter>(deleter))
{}
~holder_type() noexcept
{
try {
deleter(id);
} catch(...) {}
}
private:
int id;
Deleter deleter;
};
template<typename Deleter, EnableIf<is_callable<Deleter&, void, int&>>...>
holder_type<typename std::decay<Deleter>::type> holder(int id, Deleter&& deleter)
{
return { id, std::forward<Deleter>(deleter) };
}
template<typename Deleter, EnableIf<is_callable<Deleter&, void, int, int*>>...>
auto holder(int id, Deleter&& deleter)
-> decltype( holder(id, std::bind(std::forward<Deleter>(deleter), 1, std::bind(detail::addressof {}, std::placeholders::_1))) )
{ return holder(id, std::bind(std::forward<Deleter>(deleter), 1, std::bind(detail::addressof {}, std::placeholders::_1))); }
// How to make it convenient to embed a holder_type:
template<typename Deleter>
using Holder = decltype( holder(0, std::declval<Deleter>()) );
struct foo {
Holder<deleter_a> h;
};
struct bar {
Holder<deleter_b> h;
};
int main()
{
foo f { holder(42, deleter_a {}) };
bar b { holder(33, deleter_b {}) };
} | true |
9c323a305d1b6cf202e0f2ed6b46e847bb67c2f0 | C++ | Gavinysj/Answer-for-leetcode | /Climbing Stairs/Climbing Stairs/main.cpp | UTF-8 | 970 | 3.40625 | 3 | [] | no_license | //
// main.cpp
// Climbing Stairs
//
// Created by XTBlock on 14/12/30.
// Copyright (c) 2014年 XTBlock. All rights reserved.
//
/*
Question:
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
*/
#include <iostream>
class Solution {
public:
int climbStairs(int n) {
int n1=1, result=1;
int tmp;
for (int i=2; i<=n; i++) {
tmp = result;
result += n1;
n1 = tmp;
}
return result;
}
};
class Solution2 {
public:
int climbStairs(int n) {
if (n==1 || n==2)
return n;
int t = climbStairs(n-1) + climbStairs(n-2);
return t;
}
};
int main(int argc, const char * argv[]) {
// insert code here...
std::cout << "Hello, World!\n";
return 0;
}
| true |
e705b26fdc15d983c91717a1417aa83156897081 | C++ | BlitzModder/dava.engine | /Modules/TArc/Sources/TArc/Utils/Private/ReflectionHelpers.cpp | UTF-8 | 1,076 | 2.53125 | 3 | [] | permissive | #include "TArc/Utils/ReflectionHelpers.h"
#include <Reflection/Reflection.h>
#include <Reflection/ReflectedTypeDB.h>
namespace DAVA
{
void ForEachField(const Reflection& r, const Function<void(Reflection::Field&& field)>& fn)
{
Vector<Reflection::Field> fields = r.GetFields();
for (Reflection::Field& f : fields)
{
fn(std::move(f));
}
}
const ReflectedType* GetValueReflectedType(const Reflection& r)
{
const ReflectedType* type = GetValueReflectedType(r.GetValue());
if (type != nullptr)
{
return type;
}
return r.GetValueObject().GetReflectedType();
}
const ReflectedType* GetValueReflectedType(const Any& value)
{
if (value.IsEmpty() == true)
{
return nullptr;
}
const Type* type = value.GetType();
if (type->IsPointer())
{
void* pointerValue = value.Get<void*>();
if (pointerValue != nullptr)
{
return ReflectedTypeDB::GetByPointer(pointerValue, type->Deref());
}
}
return ReflectedTypeDB::GetByType(type);
}
} // namespace DAVA
| true |
5865f7cd10761726f4a231102a7ed74f018836ee | C++ | Woloda/Lab_9_2_A | /UnitTest(Lab_9.2(A))/UnitTest(Lab_9.2(A)).cpp | UTF-8 | 767 | 2.75 | 3 | [] | no_license | #include "pch.h"
#include "CppUnitTest.h"
#include "../Lab_9.2(A)/Lab_9.2(A).cpp"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace UnitTestLab92A
{
TEST_CLASS(UnitTestLab92A)
{
public:
TEST_METHOD(TestMethod1)
{
int kil_student = 2;
student* s = new student[kil_student];
s[0].prizv = "sdgsd"; s[1].prizv = "ssfsaf";
s[0].kurs = 4; s[1].kurs = 2;
s[0].specialization = (Special)2; s[1].specialization = (Special)0;
s[0].phisuka = 4; s[1].phisuka = 2;
s[0].matematic = 4; s[1].matematic = 3;
s[0].informatic = 5; s[1].informatic = 5;
Sort(s, kil_student);
Assert::AreEqual(s[0].kurs, 2);
}
};
}
| true |
0550fb7d12aea04b4cba7660f95de68603c7799a | C++ | Evil-crow/CPP | /Essential_CPP/Programming_with_Templete/handling_templete_type_parameters.cpp | UTF-8 | 1,550 | 3.453125 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
template <typename elemType>
class btNode {
public:
btNode();
btNode(elemType temp);
private:
elemType _val;
int _cnt;
btNode *_lchild;
btNode *_rchild;
};
template <typename valType>
class binaryTree {
public:
friend class btNode;
binaryTree();
binaryTree(const binaryTree &);
~binaryTree();
binaryTree& std::operator= (const binaryTree &);
friend std::ostream &operator<< (std::ostream &os = std::cout, btNode<valType> &bt);
bool empty() { return _root = 0; }
void clear();
private:
btNode<valType> *_root;
void copy(btNode<valType> *tar, btNode<valType> *src);
};
// 下面这种方法采用,参数初始化列表,对于复杂的类型很方便,减少一次拷贝,提高效率
btNode<std::string>::btNode(std::string str) : _val(str)
{
_cnt++;
_lchild = 0;
_rchild = 0;
}
// 此种方法就是正常的处理方法,其实使用参数初始化或者直接拷贝都是可以的,但是一般内置类型以外的都用参数初始化列表
btNode<std::string>::btNode(std::string str)
{
_val = str;
_cnt++;
_lchild = 0;
_rchild = 0;
}
// 所以,我们建议统一使用参数初始化列表的形式进行初始化.
// 对于operator运算符,我们一般会产生许多针对不同类型的运算符重载,所以就使用function template进行实现
template <typename T>
std::ostream &operator<< (std::ostream &os, btNode<T> &bt)
{
os << bt._cnt << " " << bt._val << " " << endl;
}
| true |
19770715122804b17d2812f7d6f6a7c869bce85a | C++ | RollerSimmer/Guildhall-Projects | /SD2/SimpleMiner/Code/Game/Entity.cpp | UTF-8 | 5,738 | 2.765625 | 3 | [] | no_license | #include "Game/Entity.hpp"
#include <cmath>
#include "Game/GameCommon.hpp"
#include "Engine/Math/MathUtil.hpp"
#include "Engine/Math/Disc2.hpp"
Entity::Entity(const Vector2& pos,float radius,float speed)
: m_pos(pos)
, m_vel(0.f, 0.f)
, m_orientationDegrees(0.f)
, m_graphicsRadius(radius)
, m_physicsRadius(radius*GRAPHICS_TO_PHYSICS_RADIUS_RATIO)
, m_angularVelocity(0.f)
, m_outOfBoundsCounterSeconds(0.f)
, m_drawScale(1.f)
{
m_angularVelocity = GetRandomFloatInRange(-135.f, 135.f);
m_vel.x = GetRandomFloatInRange(-1.f, 1.f);
m_vel.y = GetRandomFloatInRange(-1.f, 1.f);
this->setSpeed(speed);
}
float Entity::getMass()
{
return m_mass;
}
void Entity::setRadii(float radius)
{
m_graphicsRadius=radius;
m_physicsRadius=radius*GRAPHICS_TO_PHYSICS_RADIUS_RATIO;
}
float Entity::getGraphicsRadius()
{
return m_graphicsRadius;
}
Vector2 Entity::getVelocity()
{
return m_vel;
}
float Entity::getSpeed()
{
Vector2 vel=getVelocity();
return vel.calcLength();
}
float Entity::getOrientationDegrees()
{
return m_orientationDegrees;
}
void Entity::render() const
{
if (g_doShowDebugGraphics)
{
drawGraphicsShell();
drawPhysicsShell();
drawVelocityVector();
}
}
void Entity::drawGraphicsShell() const
{
const Rgba GRAPHICS_SHELL_COLOR = Rgba::BLUE;
g_theRenderer->drawCircle(m_pos.x, m_pos.y, m_graphicsRadius*m_drawScale, AMT_BOUNDS_CIRCLE_EDGES, GRAPHICS_SHELL_COLOR);
}
void Entity::drawPhysicsShell() const
{
const Rgba PHYSICS_SHELL_COLOR = Rgba::CYAN;
g_theRenderer->drawCircle(m_pos.x, m_pos.y, m_physicsRadius*m_drawScale, AMT_BOUNDS_CIRCLE_EDGES, PHYSICS_SHELL_COLOR);
}
void Entity::drawVelocityVector() const
{
const Rgba VELOCITY_VECTOR_COLOR = Rgba::PURPLE;
Vector2 endpoint=m_pos+m_vel*m_drawScale;
g_theRenderer->drawLine(m_pos.x,m_pos.y,endpoint.x,endpoint.y,VELOCITY_VECTOR_COLOR);
}
Vector2 Entity::calcMomentum()
{
return m_mass*m_vel;
}
void Entity::incOutOfBoundsCounter(float deltaSeconds)
{
m_outOfBoundsCounterSeconds+=deltaSeconds;
}
void Entity::resetOutOfBoundsCounter()
{
m_outOfBoundsCounterSeconds=0.f;
}
bool Entity::hasBeenOutOfBoundsTooLong()
{
return m_outOfBoundsCounterSeconds > MAX_ENTITY_OUT_OF_BOUNDS_TIME;
}
void Entity::adjustRotation(float degrees)
{
m_orientationDegrees+=degrees;
}
void Entity::adjustPosition(const Vector2& displacement)
{
m_pos+=displacement;
}
void Entity::setDrawScale(float scale)
{
m_drawScale=scale;
}
void separateEntities(Entity& a, Entity& b)
{
Disc2 adisc(a.m_pos,a.m_physicsRadius);
Disc2 bdisc(b.m_pos,b.m_physicsRadius);
if(!DoDiscsOverlap(adisc,bdisc))
return;
Vector2 displacement=b.m_pos-a.m_pos;
displacement.Normalize();
float radiusSum = a.m_physicsRadius + b.m_physicsRadius;
float dist = CalcDistance(adisc.m_center, bdisc.m_center);
float displacementLen = (radiusSum - dist) * 0.5f;
displacement *= displacementLen;
b.m_pos += displacement;
a.m_pos -= displacement;
}
void Entity::update(float deltaSeconds)
{
move(deltaSeconds);
rotate(deltaSeconds);
wrapAround();
}
bool Entity::isCompletelyOutOfBounds()
{
AABB2 expandedWorld = g_theWorldBounds->createdWorldExpandedBy(m_graphicsRadius);
if (m_pos.x < expandedWorld.m_mins.x)
return true;
if (m_pos.y < expandedWorld.m_mins.y)
return true;
if (m_pos.x > expandedWorld.m_maxs.x)
return true;
if (m_pos.y > expandedWorld.m_maxs.y)
return true;
if (isNan(m_pos.x))
return true;
if (isNan(m_pos.y))
return true;
return false;
}
bool Entity::isPartiallyOutOfBounds()
{
AABB2 contractedWorld = g_theWorldBounds->createdWorldExpandedBy(-m_graphicsRadius);
if (m_pos.x < contractedWorld.m_mins.x)
return true;
if (m_pos.y < contractedWorld.m_mins.y)
return true;
if (m_pos.x > contractedWorld.m_maxs.x)
return true;
if (m_pos.y > contractedWorld.m_maxs.y)
return true;
if (isNan(m_pos.x))
return true;
if (isNan(m_pos.y))
return true;
return false;
}
void Entity::teleportToOtherSide()
{
if (m_pos.x < g_theWorldBounds->m_mins.x - m_graphicsRadius)
m_pos.x = g_theWorldBounds->m_maxs.x + m_graphicsRadius;
else if (m_pos.x > g_theWorldBounds->m_maxs.x + m_graphicsRadius)
m_pos.x = g_theWorldBounds->m_mins.x - m_graphicsRadius;
if (m_pos.y < g_theWorldBounds->m_mins.y - m_graphicsRadius)
m_pos.y = g_theWorldBounds->m_maxs.y + m_graphicsRadius;
else if (m_pos.y > g_theWorldBounds->m_maxs.y + m_graphicsRadius)
m_pos.y = g_theWorldBounds->m_mins.y - m_graphicsRadius;
}
void Entity::setSpeedFromCurrentHeading(float speed)
{
m_vel=calcHeadingVector()*speed;
}
void Entity::setSpeed(float speed)
{
m_vel.setLength(speed);
}
Vector2& Entity::getpos()
{
return m_pos;
}
void Entity::setVelocity(const Vector2& newVelocity)
{
m_vel = newVelocity;
}
void Entity::move(float deltaSeconds)
{
m_pos += m_vel*deltaSeconds;
}
void Entity::rotate(float deltaSeconds)
{
m_orientationDegrees += m_angularVelocity*deltaSeconds;
m_orientationDegrees = (float)fmod(m_orientationDegrees, 360.0);
}
void Entity::wrapAround()
{
if (this->isCompletelyOutOfBounds())
this->teleportToOtherSide();
}
Vector2 Entity::calcHeadingVector()
{
float radians=ConvertDegreesToRadians(m_orientationDegrees);
Vector2 result(cos(radians),sin(radians));
result.Normalize();
return result;
}
bool Entity::doesCollideWith(const Entity& other)
{
Disc2 thisdisc(m_pos,m_physicsRadius);
Disc2 otherdisc(other.m_pos,other.m_physicsRadius);
return thisdisc.doesOverlapWith(otherdisc);
}
| true |
1485ff96ebb735601d84ad366f2eec6d7d318bd3 | C++ | Timoniche/ITMO | /ALGO_LABS/Algorithms1course/LCAIssues/E.cpp | UTF-8 | 2,021 | 2.796875 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
const int MAXN = 200010;
//9 3 2 4 2 1 2 5 1 1 6 7 6 6 8 8 9
//Possible answer: 0 1 2 2 1 1 6 6 8
//3 1 2 2 3
//Possible answer: 2 0 2
vector<bool> isVisited;
vector<int> adj[MAXN];
vector<int> subTreeSize;
vector<bool> isCut;
vector<int> ans;
unsigned int n;
void dfs(int v);
int centoidVertex(int v, int tmp) {
int maxSubTree = 0;
isVisited[v] = true;
for (int u : adj[v]) {
if (!isVisited[u]) {
if (!isCut[u] && subTreeSize[u] > tmp / 2 &&
subTreeSize[u] > subTreeSize[maxSubTree]) {
maxSubTree = u;
}
}
}
if (maxSubTree == 0) {
return v;
} else {
return centoidVertex(maxSubTree, tmp);
}
}
//возвращает новый корень
int decomposition(int v) {
int tmpSize;
isVisited = vector<bool>();
isVisited.resize(n + 1);
dfs(v);
tmpSize = subTreeSize[v];
if (tmpSize == 1) {
return v;
}
isVisited = vector<bool>();
isVisited.resize(n + 1);
int center = centoidVertex(v, tmpSize);
isCut[center] = true;
for (int u : adj[center]) {
if (!isCut[u]) {
ans[decomposition(u)] = center;
}
}
return center;
}
void dfs(int v) {
isVisited[v] = true;
subTreeSize[v] = 1;
for (int u : adj[v]) {
if (!isVisited[u] && !isCut[u]) {
dfs(u);
subTreeSize[v] += subTreeSize[u];
}
}
}
int main() {
ios_base::sync_with_stdio(false);
cin >> n;
isVisited.resize(n + 1);
subTreeSize.resize(n + 1);
isCut.resize(n + 1);
for (int i = 0; i < n + 1; i++) {
adj[i] = vector<int>();
}
for (int i = 0; i < n - 1; i++) {
int u, v;
cin >> u >> v;
adj[v].push_back(u);
adj[u].push_back(v);
}
ans.resize(n + 1);
decomposition(1);
for (int i = 1; i < n + 1; i++) {
cout << ans[i] << " ";
}
return 0;
}
| true |
0b321e5776f35ba011d73d33ff9bcb3466e726ed | C++ | AxlFullbuster/File-Rename | /test/catch2-tests.cpp | UTF-8 | 2,853 | 3.359375 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #include <catch.hpp>
#include <boost/filesystem.hpp>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using std::fstream;
using std::string;
using std::vector;
using std::cout;
using std::endl;
namespace fs = boost::filesystem;
/*
*methods and variables for testing
*/
string test_path = "/mnt/c/Users/Tdial/Desktop/coding-work/C++/Linux/File-Rename/test/build";
void createFiles(int n){
fs::create_directory(test_path + "/Files");
for(int i = 1; i <= n; i++){
string num = std::to_string(i);
string name = "Test " + num + ".txt";
fstream file ("./Files/" + name, fstream::out);
file.close();
}
}
/*
*Catch2 Test cases
*/
TEST_CASE( "Sanity Case", "[multi-file:1]" ){
SECTION( "Check that tests are possible"){
int example = 1;
int counter_example = 1;
REQUIRE(example == counter_example);
}
}
TEST_CASE("Base Case", "[base]"){
SECTION("1 singular file and a directory can be created."){
createFiles(1);
REQUIRE(fs::exists(test_path + "/Files/Test 1.txt") == true);
fs::remove_all(test_path + "/Files");
}
SECTION("Multiple files can be created and put into a directory."){
createFiles(10);
for(int i = 1; i <= 10; i++){
string num = std::to_string(i);
string name = "Test " + num + ".txt";
REQUIRE(fs::exists(test_path + "/Files/" + name) == true);
}
fs::remove_all(test_path + "/Files");
}
}
TEST_CASE("Renaming", "[rename]"){
SECTION("A single file can be renamed to a predetermined name"){
fs::create_directory(test_path + "/Files");
string new_name = "Hello.txt";
fstream test_file("Files/Test.txt", fstream::out);
test_file.close();
fs::rename(test_path + "/Files/Test.txt", test_path + "/Files/" + new_name);
REQUIRE(fs::exists(test_path + "/Files/" + new_name) == true);
fs::remove_all(test_path + "/Files");
}
}
TEST_CASE("Multiple Renaming", "[rename]"){
vector<string> new_names = {"Hi.txt", "Hello.txt", "Greetings.txt", "Salutations.txt"};
vector<string> old_names = {"Test 1.txt", "Test 2.txt", "Test 3.txt", "Test 4.txt"};
createFiles(4);
string path = test_path + "/Files/";
SECTION("Multiple files in a directory can be renamed"){
for(int i = 0; i < 4; i++){
fs::rename(path + old_names[i], path + new_names[i]);
}
for(int i = 0; i < 4; i++){
REQUIRE(fs::exists(path + new_names[i]) == true);
}
fs::remove_all(path);
}
}
| true |
fa3e8c14f3bc331f41ce4551fd6cd42aecd70070 | C++ | neilstc/TAKI | /Player.cpp | UTF-8 | 2,237 | 3.578125 | 4 | [] | no_license | /*Neil Michaeli 203536818*/
/*Yair Ivgi 308275601*/
#include "Player.h"
#include "Game.h"
Player::Player(){
this->name = "" ;
this->numOfCards = 0;
}
Player::Player(const string name,const int numOfCards){
this->name = name;
this->numOfCards = numOfCards;
fillCards();
}
Player::Player(const Player &player){
this->name = player.name ;
this->numOfCards = player.numOfCards;
this->cards = player.cards;// TODO make a deep copying
}
const bool Player:: play(Card ¤t){
bool isPlayed = false;
int cardIndex;
cin >> cardIndex;
cardIndex --;
if(-1 < cardIndex && cardIndex < this->numOfCards){ // checks if the player wants to choose an actual card and play or to take from the deck;
this->choosen = getCard(cardIndex);
}
// illegal move
while (!current.is_legal(choosen) && (-1 < cardIndex && cardIndex <numOfCards)){
this->choosen = getCard(cardIndex);
cout << "You can't put " << choosen << " on " << current << endl;
cin >> cardIndex;
cardIndex--;
}
if(-1 < cardIndex && cardIndex <numOfCards){
numOfCards-- ;// set the new value
deleteCard(cardIndex);//delete's the card
current = choosen; //replace current by this one ;
isPlayed = true;
} else {
Card newCard = newCard.generate_card(); // will generate a randon card
numOfCards++;
setCard(newCard); // new card added to the players cards.
}
return isPlayed;
}
void Player::fillCards(){
for (int i =0; i<numOfCards; i++) {
cards.push_back(Card::generate_card());
}
}
void Player:: deleteCard(const int cardIndex){
cards.erase(cards.begin()+cardIndex);
}
const Player& Player::operator=( Player const &player) {
this->name = player.name;
this->numOfCards = player.numOfCards;
this->cards = player.cards;
return *this;
}
//SETTERS & GETTERS
const string Player::getName()const{
return this->name;
}
const int Player::getNumOfCards()const{
return this->numOfCards;
}
const Card Player::getCard(const int index)const {
return cards[index];
}
void Player::setCard(const Card &card){
cards.push_back(card);
}
| true |
0d1ba012f1dde655bfcbd75caa81587388cdc116 | C++ | dimrirahul/programming | /codeforces/350/D/D.cc | UTF-8 | 1,413 | 2.8125 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
using VI = vector<int>;
const bool dbg = !true;
struct D {
int n, k, maxCookies;;
VI a, b;
bool canMake(int cks) {
int rem = k;
for (int i = 0; i < b.size(); i++) {
int diff = b[i] - a[i] * cks;
if (diff >= 0) continue;
rem -= abs(diff);
if (rem < 0) return false;
}
return true;
}
void start() {
cin >> n >> k;
maxCookies = 0;
for (int i = 0; i < n; i++) {
int t; cin >> t;
a.push_back(t);
}
for (int i = 0; i < n; i++) {
int t; cin >> t;
b.push_back(t);
maxCookies = max(maxCookies, (t + k) / a[i]);
}
if (dbg) cout << "maxCookies=" << maxCookies << "\n";
int start = 0, end = maxCookies + 1, res;
while (start < end) {
int mid = (start + end) / 2;
if (dbg) cout << "Start=" << start << " end=" << end << " res=" << res << " mid=" << mid << "\n";
if (canMake(mid)) {
if (dbg) cout << "can make = " << mid << " cookies\n";
start = mid + 1;
res = mid;
} else {
end = mid;
}
}
cout << res << "\n";
}
};
D d;
int main(int argc, char **argv) {
d.start();
return 0;
};
| true |
0698a34be8f06069b5f227b63c343696b8245135 | C++ | Joseph-Laithwaite/smart-greenhouse-university-fyp | /Arduino/SensorLibraries/StandardAnalogSensor.cpp | UTF-8 | 1,106 | 2.796875 | 3 | [] | no_license | /*
* StandardAnalogSensor.cpp
*
* Created on: 9 Mar 2018
* Author: josephlaithwaite
*/
#include "StandardAnalogSensor.h"
StandardAnalogSensor::StandardAnalogSensor(uint8_t sensorPinNumber, uint8_t powerPinNumber) {
// TODO Auto-generated constructor stub
this->sensorPinNumber = sensorPinNumber;
this->powerPinNumber = powerPinNumber;
pinMode(sensorPinNumber,INPUT);
}
StandardAnalogSensor::~StandardAnalogSensor() {
// TODO Auto-generated destructor stub
}
int StandardAnalogSensor::getSensorValue(){
int currentRawInput;
if (powerPinNumber==255){ //code for no power pin used
currentRawInput = analogRead(sensorPinNumber);
}else{
pinMode(powerPinNumber,OUTPUT);
digitalWrite(powerPinNumber, HIGH);
delay(500);
currentRawInput = analogRead(sensorPinNumber);
delay(300);
pinMode(powerPinNumber, OUTPUT);
pinMode(powerPinNumber, INPUT);
digitalWrite(powerPinNumber, LOW);
}
return currentRawInput;
}
uint8_t StandardAnalogSensor::getSensorPinNumber(){
return sensorPinNumber;
}
uint8_t StandardAnalogSensor::getPowerPinNumber(){
return powerPinNumber;
}
| true |
893d2d67abec7ce3ff3e51945a2b1b1b5c33a103 | C++ | GeekSprite/iOS-Algorithm | /linkedList/leetcode/easy/hasCycle.h | UTF-8 | 1,604 | 3.28125 | 3 | [] | no_license | //
// hasCycle.h
// linkedList
//
// Created by junl on 2019/7/17.
// Copyright © 2019 junl. All rights reserved.
//
#ifndef hasCycle_hpp
#define hasCycle_hpp
#include <stdio.h>
#include "singlyLinkedList.h"
namespace leetcode {
/*
141.给定一个链表,判断链表中是否有环。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
示例 1:
输入:head = [3,2,0,-4], pos = 1
输出:true
解释:链表中有一个环,其尾部连接到第二个节点。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/linked-list-cycle
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
bool hasCycle(ListNode *head) {
ListNode *fast,*slow;
fast = slow = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) {
return true;
}
}
return false;
}
void test_hasCycle(){
singlyLinkedList ll;
ll.insertTail(3);
ll.insertTail(2);
ll.insertTail(0);
ll.insertTail(-4);
ListNode *l2 = ll.findByValue(2);
ListNode *l4 = ll.findByValue(-4);
l4->next = l2;
std::cout << "test_hasCycle: " << hasCycle(ll.start()) << std::endl;
}
}
#endif /* hasCycle_hpp */
| true |
fcc047d469a5399a9cdf34c3406ed3895b76dee9 | C++ | prw/montecarloraytracer | /vector.cpp | UTF-8 | 669 | 3.28125 | 3 | [] | no_license | #include <cmath>
#include "vector.h"
Vector::Vector():Point(){}
Vector::Vector(double xx, double yy, double zz):Point(xx, yy, zz){}
Vector::Vector(double vals[]):Point(vals){}
void Vector::cross(Vector &a, Vector &b){
x=a.y*b.z - a.z*b.y;
y=a.z*b.x - a.x*b.z;
z=a.x*b.y - a.y*b.x;
}
double Vector::dot(Vector &b){
return x*b.x+y*b.y+z*b.z;
}
double Vector::lengthSquared(){
return x*x+y*y+z*z;
}
double Vector::length(){
return sqrt(lengthSquared());
}
void Vector::normalize(){
double norm = length();
x/=norm; y/=norm; z/=norm;
}
Vector &Vector::operator=(const Vector &rhs){
x=rhs.x; y=rhs.y; z=rhs.z;
return *this;
}
| true |
c01383415dda51886647d213d406ab0b3601dfd0 | C++ | arnavkundalia/Algorithms-and-Data-Structres_Extra | /Dynamic Programming/Subset-Sum-Problem.cpp | UTF-8 | 954 | 3.140625 | 3 | [] | no_license | /*
Problem URL :- https://practice.geeksforgeeks.org/problems/subset-sum-problem/0
*/
#include<bits/stdc++.h>
using namespace std;
bool subsum(int arr[], int n, int sum) { // recursive solution
// base case
bool dp[n+1][sum+1];
for(int i=0; i<=n; i++) {
for(int j=0; j<=sum; j++) {
if(j==0) dp[i][j]=true;
else dp[i][j]=false;
}
}
for(int i=1; i<=n; i++) {
for(int j=1; j<=sum; j++) {
dp[i][j] = dp[i-1][j];
if(j-arr[i-1]>=0) dp[i][j] = dp[i][j] || dp[i-1][j-arr[i-1]];
}
}
return dp[n][sum];
}
// {
int main() {
//code
int t;
cin>>t;
for(int cs=0; cs<t; cs++) {
int n;
cin>>n;
int arr[n];
for(int i=0; i<n; i++) cin>>arr[i];
int sum=0;
for(int i=0; i<n; i++) sum+=arr[i];
if(sum%2==0 && subsum(arr,n,sum/2)==true) cout<<"YES";
else cout<<"NO";
cout<<endl;
}
return 0;
}
// }
| true |
631c80315a9464208796298952f318d1a6978420 | C++ | WhiZTiM/coliru | /Archive2/6d/a776855a686ce5/main.cpp | UTF-8 | 1,624 | 3.84375 | 4 | [] | no_license | #include <iostream>
#include <type_traits>
#include <cstddef>
template <typename... Types>
struct Foo;
template <typename T, typename... Types>
struct Foo<T, Types...> : Foo<Types...>
{
// bring get() member functions from parent class into current scope
using Foo<Types...>::get;
Foo(T member, Types... others) : Foo<Types...>{others...}, m_member{member} {}
template <typename U>
auto get(T* = nullptr) -> typename std::enable_if<std::is_same<U, T>::value, T>::type
{
return m_member;
}
template <std::size_t N>
auto get(T* = nullptr) -> typename std::enable_if<N == sizeof...(Types), T>::type
{
return m_member;
}
private:
T m_member;
};
template <typename T>
struct Foo<T>
{
Foo(T member) : m_member{member} {}
template <typename U>
auto get(T* = nullptr) -> typename std::enable_if<std::is_same<U, T>::value, T>::type
{
return m_member;
}
template <std::size_t N>
auto get(T* = nullptr) -> typename std::enable_if<N == 0, T>::type
{
return m_member;
}
private:
T m_member;
};
int main()
{
Foo<char, int, bool, double> a{ 'a', 42, true, 1.234 };
std::cout << a.get<char>() << std::endl;
std::cout << a.get<int>() << std::endl;
std::cout << a.get<bool>() << std::endl;
std::cout << a.get<double>() << std::endl;
std::cout << a.get<3>() << std::endl;
std::cout << a.get<2>() << std::endl;
std::cout << a.get<1>() << std::endl;
std::cout << a.get<0>() << std::endl;
}
| true |
0068f2ef1185c56dc08f9107a6a4a82f5946723e | C++ | xUhEngwAng/oj-problems | /thuoj/等差数列.cpp | UTF-8 | 2,293 | 2.890625 | 3 | [] | no_license | #include <cstdio>
#include <vector>
#include <cstring>
#include <algorithm>
using namespace std;
struct entry{
int row, col, value;
entry() = default;
entry(int r, int c, int v): row(r), col(c), value(v){}
};
bool cmp(const entry &one, const entry &two){
if(one.row == two.row)
return one.col < two.col;
return one.row < two.row;
}
int arr[1000][1000];
int row_cnt[1000], col_cnt[1000];
vector<entry> ans;
int main(){
int n, m;
scanf("%d %d", &n, &m);
memset(row_cnt, 0, sizeof(row_cnt));
memset(col_cnt, 0, sizeof(col_cnt));
for(int ix = 0; ix != n; ++ix)
for(int jx = 0; jx != m; ++jx){
scanf("%d", &arr[ix][jx]);
if(arr[ix][jx]){
row_cnt[ix]++;
col_cnt[jx]++;
}
}
/*for(int ix = 0; ix != n; ++ix)
printf("%d ", row_cnt[ix]);
printf("\n");
for(int ix = 0; ix != m; ++ix)
printf("%d ", col_cnt[ix]);
printf("tag\n");*/
bool flag = true;
int d, cnt, v[2], p[2], curr, first;
while(flag){
flag = false;
for(int ix = 0; ix != n; ++ix){
if(row_cnt[ix] < 2 || row_cnt[ix] == m) continue;
flag = true;
cnt = 0;
for(int jx = 0; jx != m; ++jx){
if(arr[ix][jx]){
v[cnt] = arr[ix][jx];
p[cnt++] = jx;
if(cnt == 2) break;
}
}
d = (v[1] - v[0]) / (p[1] - p[0]);
first = v[0] - p[0] * d;
for(int jx = 0, curr = first; jx != m; ++jx){
if(!arr[ix][jx]){
arr[ix][jx] = curr;
col_cnt[jx]++;
ans.emplace_back(ix, jx, curr);
}
curr += d;
}
row_cnt[ix] = m;
}
for(int ix = 0; ix != m; ++ix){
if(col_cnt[ix] < 2 || col_cnt[ix] == n) continue;
flag = true;
cnt = 0;
for(int jx = 0; jx != n; ++jx){
if(arr[jx][ix]){
v[cnt] = arr[jx][ix];
p[cnt++] = jx;
if(cnt == 2) break;
}
}
d = (v[1] - v[0]) / (p[1] - p[0]);
first = v[0] - p[0] * d;
for(int jx = 0, curr = first; jx != n; ++jx){
if(!arr[jx][ix]){
arr[jx][ix] = curr;
row_cnt[ix]++;
ans.emplace_back(jx, ix, curr);
}
curr += d;
}
col_cnt[ix] = n;
}
/*for(int ix = 0; ix != n; ++ix)
printf("%d ", row_cnt[ix]);
printf("\n");
for(int ix = 0; ix != m; ++ix)
printf("%d ", col_cnt[ix]);
printf("tag\n");*/
}
sort(ans.begin(), ans.end(), cmp);
for(auto e : ans){
printf("%d %d %d\n", e.row + 1, e.col + 1, e.value);
}
return 0;
}
| true |
c675fa162e943817510d51ace7c49fec324f3289 | C++ | acrowise/kaacore | /src/log.cpp | UTF-8 | 1,973 | 2.8125 | 3 | [
"MIT"
] | permissive | #include <cstring>
#include <SDL.h>
#include "kaacore/exceptions.h"
#include "kaacore/log.h"
namespace kaacore {
bool logging_initialized = false;
LogLevel
get_logging_level(const LogCategory category)
{
return static_cast<LogLevel>(
SDL_LogGetPriority(static_cast<int>(category)));
}
void
set_logging_level(const LogCategory category, const LogLevel level)
{
SDL_LogSetPriority(
static_cast<int>(category), static_cast<SDL_LogPriority>(level));
}
void
set_logging_level(const LogCategory category, const char* level_name)
{
LogLevel level;
if (strcmp(level_name, "VERBOSE") == 0) {
level = LogLevel::verbose;
} else if (strcmp(level_name, "DEBUG") == 0) {
level = LogLevel::debug;
} else if (strcmp(level_name, "INFO") == 0) {
level = LogLevel::info;
} else if (strcmp(level_name, "WARN") == 0) {
level = LogLevel::warn;
} else if (strcmp(level_name, "ERROR") == 0) {
level = LogLevel::error;
} else if (strcmp(level_name, "CRITICAL") == 0) {
level = LogLevel::critical;
} else {
log<LogLevel::critical, LogCategory::misc>(
"Unsupported logging level_name provided: %s", level_name);
throw exception("Unsupported logging level_name provided");
}
set_logging_level(category, level);
}
void
initialize_logging()
{
if (not logging_initialized) {
set_logging_level(LogCategory::engine, KAACORE_LOGLEVEL_ENGINE);
set_logging_level(LogCategory::renderer, KAACORE_LOGLEVEL_RENDERER);
set_logging_level(LogCategory::input, KAACORE_LOGLEVEL_INPUT);
set_logging_level(LogCategory::audio, KAACORE_LOGLEVEL_AUDIO);
set_logging_level(LogCategory::nodes, KAACORE_LOGLEVEL_NODES);
set_logging_level(LogCategory::physics, KAACORE_LOGLEVEL_PHYSICS);
set_logging_level(LogCategory::misc, KAACORE_LOGLEVEL_MISC);
logging_initialized = true;
}
}
} // namespace kaacore
| true |
1c6f1198a7eea44a4ff5ebcc461ab09c63b4e810 | C++ | GT-IEEE-Robotics/2018 | /Distance Sensing/beaglebone_i2c_distance/app_note.cpp | UTF-8 | 3,703 | 2.90625 | 3 | [] | no_license | /**
* Quickstart to get distance measurements from VL6180 infrared laser time-of-flight based distance sensor
* adapted from Hamblen's mbed example code in the Application Note
*/
// new headers for beaglebone linux to use to comm to i2c bus 0, pins 19,20 for scl,sda (serial clock, serial data)
#include <linux/i2c.h>
#include <linux/i2c-dev.h>
#include <sys/ioctl.h>
#include <unistd.h> // for sleeping/time delays on unix systems. call with usleep(unsigned int microseconds);
I2C i2c(I2C_SDA, I2C_SCL); //@TODO: need to update this i2c class to be for beaglebone
#define addr (0x52) // I2C address of VL6180X shifted by 1 bit
//(0x29 << 1) so the R/W command can be added
// NOTE: we'll be wanting to using doxygen for documentation (javadocs style documentation for C++)
// to describe our functions/classes/member variables
// haven't decided which our preferred commenting style is yet, but we'll fix this
// -Philip
/**
* Writes data in byte form to an i2c register's address:
* Split 16-bit register address into two bytes and write
* the address + data via I2C
*/
void WriteByte(wchar_t reg,char data) {
char data_write[3];
data_write[0] = (reg >> 8) & 0xFF; // MSB of register address
data_write[1] = reg & 0xFF; // LSB of register address
data_write[2] = data & 0xFF;
i2c.write(addr, data_write, 3); // make sure this function call is compatible with our
}
/**
* Reads data using bytes for i2c:
* Split 16-bit register address into two bytes and write
* required register address to VL6180X and read the data back
*/
char ReadByte(wchar_t reg) {
char data_write[2]; char data_read[1];
data_write[0] = (reg >> 8) & 0xFF; // MSB of register address
data_write[1] = reg & 0xFF; // LSB of register address
i2c.write(addr, data_write, 2);
i2c.read(addr, data_read, 1);
return data_read[0];
}
/**
* Loads Settings
*/
int VL6180X_Init() {
char reset;
reset = ReadByte(0x016);
if (reset==1){ // check to see has it be Initialised already
// Added latest settings here - see Section 8
WriteByte(0x016, 0x00); //change fresh out of set status to 0
}
return 0;
}
/**
* Start a range measurement in single shot mode
*/
int VL6180X_Start_Range() {
WriteByte(0x018,0x01);
return 0;
}
/**
* Check for new dstance reading:
* Polls the distance sensor to see if a new sample has arrived
*/
int VL6180X_Poll_Range() {
char status;
char range_status;
// check the status
status = ReadByte(0x04f);
range_status = status & 0x07;
// wait for new measurement ready status
while (range_status != 0x04) {
status = ReadByte(0x04f);
range_status = status & 0x07;
wait_ms(1); // (can be removed)
}
return 0;
}
/**
* Reads distance in mm:
* reads the register storing last distance value measured (in milimeters)
*/
int VL6180X_Read_Range() {
return ReadByte(0x62);
}
/**
* Clear interrupts
*/
int VL6180X_Clear_Interrupts() {
WriteByte(0x015,0x07);
return 0;
}
/**
* Main
*/
int main() {
int range;
// load settings onto VL6180X
VL6180X_Init();
while (1) {
// start single range measurement
VL6180X_Start_Range();
}
// poll the VL6180X till new sample ready
VL6180X_Poll_Range();
// read range result
range = VL6180X_Read_Range();
// clear the interrupt on VL6180X
VL6180X_Clear_Interrupts();
// send range to pc by serial
printf("%d\r\n", range);
usleep(100000); //waits 0.1s
}
| true |
e2bd184e977ce367a6baa01710c294487b646fa9 | C++ | caurdy/Secret-Messages | /self_destructing.h | UTF-8 | 1,154 | 2.796875 | 3 | [] | no_license | #ifndef SELF_DESTRUCTING_H
#define SELF_DESTRUCTING_H
#include <string>
using std::string;
#include <vector>
using std::vector;
#include <ios>
using std::ostream; using std::istream;
class SelfDestructingMessage {
private:
vector<string> messages_;
long remaining_views_=0;
vector<long> views_vec_;
public:
SelfDestructingMessage()=default;
SelfDestructingMessage(vector<string>, long);
SelfDestructingMessage(SelfDestructingMessage&);
long remaining_views() const {return remaining_views_;};
vector<string> messages() const {return messages_;};
vector<long> views_vec() const {return views_vec_;};
int size();
vector<string> get_redacted();
long number_of_views_remaining(int index);
void add_array_of_lines(string [], long);
friend ostream& operator<<(ostream&, const SelfDestructingMessage &);
friend istream& operator>>(istream&, SelfDestructingMessage &);
const string& operator[](size_t);
SelfDestructingMessage& operator=(SelfDestructingMessage);
};
//ostream& operator<<(ostream&, const SelfDestructingMessage &);
#endif | true |
f1fbbf5d62351551099de5f5f1acffaa76010b70 | C++ | DonaldWhyte/parcel-game-engine | /include/Exceptions.h | UTF-8 | 1,962 | 3.390625 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /*
* File: Exceptions.h
* Author: Donald
*
* Created on December 18, 2008, 7:40 PM
*/
#ifndef EXCEPTIONS_H
#define EXCEPTIONS_H
#include <string>
#include <iostream>
namespace parcel
{
namespace debug
{
/* Generic exception class. All other exceptions derive from this. */
class Exception
{
protected:
std::string message; // Message displayed/logged when exception is caught
public:
//Exception() {} // Default constructor for inheritence
Exception(const std::string& errorMessage) : message(errorMessage) {} // Constructor
/* Gets the message the exception holds. */
const std::string& Message() const { return message; }
/* Prints the message the exception holds. */
void PrintMessage() const { std::cout << message << std::endl; }
};
/* Exception thrown when null pointer is given instead of object. */
class NullPointerException : public Exception
{
public:
NullPointerException(const std::string& errorMessage) : Exception(errorMessage) {}
};
/* Exception thrown when a memory allocation failed due to lack of memory space. */
class OutOfMemoryException : public Exception
{
public:
OutOfMemoryException(const std::string& errorMessage) : Exception(errorMessage) {}
};
/* Exception thrown when an invalid argument was given for a function. */
class InvalidArgumentException : public Exception
{
public:
InvalidArgumentException(const std::string& errorMessage) : Exception(errorMessage) {}
};
/* Exception thrown when an operation for a class is not supported. */
class UnsupportedOperationException : public Exception
{
public:
UnsupportedOperationException(const std::string& errorMessage) : Exception(errorMessage) {}
};
}
}
#endif
| true |
504dd9f6d118bc13ef1842f69a1a89ebef9f48c1 | C++ | Norseman055/immaterial-engine | /libs/dev/Math/MathEngine/QuatApp.cpp | UTF-8 | 2,353 | 2.921875 | 3 | [
"MIT"
] | permissive | /*****************************************************************************/
/* */
/* File: QuatApp.cpp */
/* */
/* Quaternioin Application Class */
/* */
/*****************************************************************************/
#include "MathEngine.h"
#include "MathApp.h"
#include <math.h>
// ************************ ERROR HERE ********************************
void QuatApp::Slerp( Quat &result, const Quat &source, const Quat &tar, const float slerpFactor )
{
Quat target;
// Constants.
const float QUAT_EPSILON = 0.001f;
float cosom = source.dot(tar);
// adjust signs if necessary
if ( cosom < 0.0f )
{
cosom = -cosom;
target = -tar;
}
else
{
target = tar;
}
// If the the source and target are close, we can do a lerp.
float tarFactor = slerpFactor;
float srcFactor = 1.0f - slerpFactor;
// calculate coefficients
if ( cosom < (1.0f - QUAT_EPSILON) )
{
// Quats are not close enough for a lerp.
// Calculating coefficients for a slerp.
const float omega = acosf( cosom );
const float sinom = 1.0f / sinf( omega );
srcFactor = sinf( srcFactor * omega ) * sinom;
tarFactor = sinf( tarFactor * omega ) * sinom;
}
// MY mistake: I had tar instead of target in the lines below
result.set(source[x] * srcFactor + target[x] * tarFactor,
source[y] * srcFactor + target[y] * tarFactor,
source[z] * srcFactor + target[z] * tarFactor,
source[w] * srcFactor + target[w] * tarFactor);
};
// ************************ ERROR HERE ********************************
void QuatApp::SlerpArray( Quat *result, const Quat *source, const Quat *target, const float slerpFactor, const int numQuats )
{
for (int i = 0; i < numQuats; i++)
{
QuatApp::Slerp(result[i], source[i], target[i], slerpFactor);
}
};
/***** END of File QuatApp.cpp ***********************************************/
| true |
ccdfbf67540a0d1d18d32c2a4c33ccbbd0140629 | C++ | mdcurtis/micromanager-upstream | /DeviceAdapters/PICAM/PICAMParam.h | UTF-8 | 15,388 | 2.765625 | 3 | [
"BSD-3-Clause"
] | permissive | #ifndef _PICAM_PARAM_H_
#define _PICAM_PARAM_H_
#include "DeviceBase.h"
#include "PICAMAdapter.h"
#include <algorithm>
#include <iterator>
#ifndef WIN32
typedef long long long64;
#endif
/***
* A base class for PICAM parameters. This is used for easy access to specific camera parameters.
*/
class PvParamBase
{
public:
PvParamBase( std::string aName, PicamParameter aParamId, Universal* aCamera ) :
mId( aParamId ), mCamera( aCamera ), mName( aName),
mAvail( FALSE ), mAccess( PicamValueAccess_ReadOnly ), mType(PicamValueType_Integer)
{
initialize();
}
bool IsAvailable() { return (mAvail == TRUE); }
bool IsReadOnly() { return (mAccess == PicamValueAccess_ReadOnly); }
bool IsEnum() { return (mType == PicamValueType_Enumeration); }
protected:
PicamParameter mId;
Universal* mCamera;
std::string mName;
pibln mAvail;
pibln mReadable;
PicamConstraintType mConstraint_type;
PicamValueAccess mAccess;
PicamValueType mType;
private:
int initialize()
{
mAvail=TRUE;
Picam_CanReadParameter(mCamera->Handle(), mId, &mReadable );
//Picam_IsParameterRelevant(mCamera->Handle(), mId, &mAvail );
Picam_DoesParameterExist(mCamera->Handle(), mId, &mAvail );
Picam_GetParameterConstraintType(mCamera->Handle(), mId, &mConstraint_type);
if ( mAvail )
{
Picam_GetParameterValueAccess(mCamera->Handle(), mId, &mAccess );
Picam_GetParameterValueType(mCamera->Handle(), mId, &mType);
if (mType>=PicamValueType_Rois)
{
// We can ignore this, the mType is not used anyway
mCamera->LogCamError(__LINE__, "IsParameterRelevant false");
return DEVICE_ERR;
}
}
return DEVICE_OK;
}
};
/***
* Template class for PICAM parameters. This class makes the access to PICAM parameters easier.
* The user must use the correct parameter type as defined in PICAM manual.
* Usage: PvParam<int16> prmTemperature = new PvParam<int16>( "Temperature", PARAM_TEMP, this );
*/
template<class T>
class PvParam : public PvParamBase
{
public:
PvParam( std::string aName, PicamParameter aParamId, Universal* aCamera ) :
PvParamBase( aName, aParamId, aCamera ),
mCurrent(0), mMax(0), mMin(0), mCount(0), mIncrement(0)
{
if (IsAvailable())
{
Update();
}
}
// Getters
T Current() { return mCurrent; }
T Max() { return mMax; }
T Min() { return mMin; }
T Increment() { return mIncrement; }
piint Count() { return mCount; }
/***
* Returns the current parameter value as string (useful for settings MM property)
*/
virtual std::string ToString()
{
std::ostringstream os;
os << mCurrent;
return os.str();
}
/***
* Sets the parameter value but does not apply the settings. Use Write() to
* send the parameter to the camera.
* TODO: Revisit the method name (might be confusing to have Set/Apply/Update methods)
*/
int Set(T aValue)
{
mCurrent = aValue;
return DEVICE_OK;
}
/***
* Reads the current parameter value and range from the camera
*/
int Update()
{
switch(mType){
case PicamValueType_Integer:
case PicamValueType_Boolean:
case PicamValueType_Enumeration:
if (PicamError_None!=Picam_GetParameterIntegerValue(
mCamera->Handle(), mId,
(piint *)&mCurrent))
return DEVICE_ERR;
break;
case PicamValueType_FloatingPoint:
if (PicamError_None!=Picam_GetParameterFloatingPointValue(
mCamera->Handle(), mId,
(piflt *)&mCurrent ))
{
return DEVICE_ERR;
}
break;
case PicamValueType_LargeInteger:
if (PicamError_None!=Picam_GetParameterLargeIntegerValue(
mCamera->Handle(), mId,
(pi64s *)&mCurrent))
return DEVICE_ERR;
break;
default:
return DEVICE_ERR;
}
switch( mConstraint_type )
{
case PicamConstraintType_None:
return DEVICE_ERR;
case PicamConstraintType_Range:
const PicamRangeConstraint* capable;
Picam_GetParameterRangeConstraint(
mCamera->Handle(), mId,
PicamConstraintCategory_Capable,
&capable);
mMin=static_cast<T>(capable->minimum);
mMax=static_cast<T>(capable->maximum);
mCount= capable->excluded_values_count;
mIncrement=capable->increment;
Picam_DestroyRangeConstraints(capable);
break;
case PicamConstraintType_Collection:
const PicamCollectionConstraint* collection;
Picam_GetParameterCollectionConstraint(
mCamera->Handle(), mId,
PicamConstraintCategory_Capable,
&collection);
mMin=static_cast<T>(collection->values_array[0]);
mMax=static_cast<T>(collection->values_array[collection->values_count-1]);
mCount = collection->values_count;
mIncrement = 1.0;
Picam_DestroyCollectionConstraints(collection);
break;
default:
return DEVICE_ERR;
}
return DEVICE_OK;
}
/***
* Sends the parameter value to the camera
*/
int Apply()
{
PicamError err=PicamError_InvalidOperation;
// Write the current value to camera
switch(mType){
case PicamValueType_Integer:
case PicamValueType_Boolean:
case PicamValueType_Enumeration:
case PicamValueType_LargeInteger:
err=Picam_SetParameterIntegerValue(
mCamera->Handle(), mId,
(piint )mCurrent);
break;
case PicamValueType_FloatingPoint:
err=Picam_SetParameterFloatingPointValue(
mCamera->Handle(), mId,
(piflt )mCurrent );
break;
}
//if (plSetParam(mCamera->Handle(), mId, mCurrent) != PV_OK)
if (err!=PicamError_None)
{
Update(); // On failure we need to update the cache with actual camera value
mCamera->LogCamError(__LINE__, "Picam_SetParameter");
return DEVICE_CAN_NOT_SET_PROPERTY;
}
return DEVICE_OK;
}
/***
* Sends the parameter value to the camera
*/
int OnLineApply()
{
pibln onlineable;
PicamError err=PicamError_InvalidOperation;
Picam_CanSetParameterOnline(mCamera->Handle(), mId, &onlineable );
// Write the current value to camera
if (onlineable){
switch(mType){
case PicamValueType_Integer:
case PicamValueType_Boolean:
case PicamValueType_Enumeration:
case PicamValueType_LargeInteger:
err=Picam_SetParameterIntegerValueOnline(
mCamera->Handle(), mId,
(piint )mCurrent);
break;
case PicamValueType_FloatingPoint:
err=Picam_SetParameterFloatingPointValueOnline(
mCamera->Handle(), mId,
(piflt )mCurrent );
break;
}
}
//if (plSetParam(mCamera->Handle(), mId, mCurrent) != PV_OK)
if (err!=PicamError_None)
{
Update(); // On failure we need to update the cache with actual camera value
mCamera->LogCamError(__LINE__, "Picam_SetParameter");
return DEVICE_CAN_NOT_SET_PROPERTY;
}
return DEVICE_OK;
}
protected:
T mCurrent;
T mMax;
T mMin;
piint mCount; // ATTR_COUNT is always TYPE_UNS32
T mIncrement;
private:
};
/***
* A special case of PvParam that contains supporting functions for reading the enumerable parameter
* types.
*/
class PvEnumParam : public PvParam<piint>
{
public:
/***
* Initializes the enumerable PICAM parameter type
*/
PvEnumParam( std::string aName, PicamParameter aParamId, Universal* aCamera )
: PvParam<piint>( aName, aParamId, aCamera )
{
if ( IsAvailable() )
{
enumerate();
}
}
/***
* Overrided function. Return the enum string instead of the value only.
*/
std::string ToString()
{
if ( IsAvailable() )
{
int index = std::distance(mEnumValues.begin(),
std::find(mEnumValues.begin(), mEnumValues.end(), mCurrent));
if (index < mEnumValues.size())
return mEnumStrings[index];
}
return "Invalid";
}
/***
* Returns all available enum values for this parameter
*/
std::vector<std::string>& GetEnumStrings()
{
return mEnumStrings;
}
std::vector<piint>& GetEnumValues()
{
return mEnumValues;
}
/***
* Sets the enumerable PICAM parameter from string. The string agrument must be exactly the
* same as obtained from ToString() or GetEnumStrings().
*/
int Set(const std::string& aValue)
{
if ( IsAvailable() ){
for ( unsigned i = 0; i < mEnumStrings.size(); ++i )
{
if ( mEnumStrings[i].compare( aValue ) == 0 )
{
mCurrent = mEnumValues[i];
return DEVICE_OK;
}
}
}
mCamera->LogCamError(__LINE__, "Picam_EnumParam::Set() invalid argument");
return DEVICE_CAN_NOT_SET_PROPERTY;
}
/***
* Sets the enumerable PICAM parameter from value. The value agrument must be exactly the
* same as obtained from GetEnumValues().
*/
int Set(const piint aValue)
{
if ( IsAvailable() ){
mCurrent = aValue;
return DEVICE_OK;
}
mCamera->LogCamError(__LINE__, "PvEnumParam::Set() invalid argument");
return DEVICE_CAN_NOT_SET_PROPERTY;
}
/**
* Overrided function. If we want to re-read the parameter, we also need to re-enumerate the values.
*/
int Update()
{
PvParam<piint>::Update();
enumerate();
return 0;
}
private:
/**
* Read all the enum values and correspondig string descriptions
*/
void enumerate()
{
mEnumStrings.clear();
mEnumValues.clear();
if ( IsAvailable() ){
piint enumVal;
// Enumerate the parameter with the index and find actual values and descriptions
if (mConstraint_type ==PicamConstraintType_Collection){
const PicamCollectionConstraint* capable;
Picam_GetParameterCollectionConstraint(
mCamera->Handle(), mId,
PicamConstraintCategory_Capable,
&capable );
const pichar* string;
PicamEnumeratedType type;
Picam_GetParameterEnumeratedType(mCamera->Handle(), mId, &type );
for ( piint i = 0; i < capable->values_count; i++ )
{
piint enumStrLen = 0;
enumVal=(piint)capable->values_array[i];
//if (enumVal==mCurrent) mCurrentIndex=i;
Picam_GetEnumerationString( type, enumVal, &string );
enumStrLen=(piint)strlen(string);
char* enumStrBuf = new char[enumStrLen+1];
strcpy(enumStrBuf, string);
enumStrBuf[enumStrLen] = '\0';
mEnumStrings.push_back( std::string( enumStrBuf ) );
mEnumValues.push_back( enumVal );
Picam_DestroyString( string );
delete[] enumStrBuf;
}
}
}
}
// Enum values and their corresponding names
std::vector<std::string> mEnumStrings;
std::vector<piint> mEnumValues;
protected:
piint mCurrentIndex;
};
//*****************************************************************************
//********************************************* PvParamUniversal implementation
/***
* Union used to store universal PICAM parameter value
*/
typedef union
{
pibln rs_bool_val;
//int8 int8_val;
//uns8 uns8_val;
//int16 int16_val;
//uns16 uns16_val;
piint int32_val;
piint enum_val;
//uns32 uns32_val;
piflt flt64_val;
pi64s long64_val;
//ulong64 ulong64_val; // Not supported since this exceeds the double type range
} PvUniversalParamValue;
/***
* Class for 'Universal' parameters.
* The initial idea probably was to have all the PICAM parameters as universal so we'd not
* have to implement separate handlers (On**Property()) for every parameter. However due to
* PICAM nature it's impossible to create such universal class. The MM supports Long, String,
* and Double parameter values, but PICAM supports much more types, there are many parameters
* that requires special handling (e.g. value conversion) and a change in some parameter
* requires update of other parameter.
*
* This class is not perfect. It can handle only some types of PICAM parameters and it's kept here
* only for compatibility. See PICAMUniversal::g_UniversalParams.
*/
class PvUniversalParam : public PvParamBase
{
public:
PvUniversalParam( std::string aName, PicamParameter aParamId, Universal* aCamera );
std::vector<std::string>& GetEnumStrings();
// Getters: MM property can be either string, double or long
std::string ToString();
double ToDouble();
long ToLong();
// Setters
int Set(std::string aValue);
int Set(double aValue);
int Set(long aValue);
int Read();
int Write();
double GetMax();
double GetMin();
protected:
int initialize();
protected:
PvUniversalParamValue mValue;
PvUniversalParamValue mValueMax;
PvUniversalParamValue mValueMin;
// Enum values and their corresponding names obtained by pl_get_enum_param
std::vector<std::string> mEnumStrings;
std::vector<int> mEnumValues;
private:
int plGetParam( PvUniversalParamValue& aValueOut );
int plSetParam( PvUniversalParamValue& aValueOut );
};
#endif // _PICAM_PARAM_H_
| true |
a34629aa5c26aa358555e50b4a44a0b6e235f79a | C++ | saisrivatsan/Codeforces | /109/B.cpp | UTF-8 | 711 | 2.78125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
#define LL long long int
bool cmp(pair<LL,LL> l, pair<LL,LL> r)
{
if(l.second == r.second)
return l.first > r.first;
else
return l.second > r.second;
}
int main()
{
LL n,i,j,k,a,b;
cin>>n;
vector <pair<LL,LL> > A;
for(i=0;i<n;i++)
{
cin>>a>>b;
A.push_back(make_pair(a,b));
}
sort(A.begin(),A.end(),cmp);
//for(i=0;i<n;i++)
// cout<<A[i].first<<" "<<A[i].second<<"\n";
LL rem = 1,currIdx = 0,pt = 0;
while(rem && currIdx <n)
{
rem = rem - 1 + A[currIdx].second;
pt = pt + A[currIdx++].first;
}
cout<<pt<<"\n";
return 0;
}
| true |
52b4ceb5dd20f70aed35c76aecdcbc18c4c78a92 | C++ | wangjiangxing/GitDS | /BiTree/BiTree/BiTree.cpp | UTF-8 | 2,596 | 2.984375 | 3 | [] | no_license | // BiTree.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include "pch.h"
#include "LiQueue.h"
ElemType dat = 1;
LinkQueue Q=(LinkQueue)malloc(sizeof(LiQueue));
int sumNoLeafNum = 0;
int main()
{
BiTree T;
createTree(T, 3);
preOrder(T);
printf("*****************************\n");
inOrder(T);
printf("*****************************\n");
postOrder(T);
printf("****************************\n");
LevelOrder(T);
sumNoLeaf(T);
printf("该树的非叶子结点有%d个\n", sumNoLeafNum);
printf("该树的高度为%d", sumHeight(T));
return 0;
}
void initTree(BiTree & T)
{
T = (BiTNode *)malloc(sizeof(BiTNode));
T->data = 0;
T->Lchild = NULL;
T->Rchild = NULL;
}
void makeTree(BiTree & T,int i)
{
if (i >1)
{
T->Lchild = (BiTree)malloc(sizeof(BiTNode)); initTree(T->Lchild);
dat++;
T->Lchild->data = dat;
T->Rchild = (BiTree)malloc(sizeof(BiTNode)); initTree(T->Rchild);
dat++;
T->Rchild->data = dat;
makeTree(T->Lchild, i - 1);
makeTree(T->Rchild, i - 1);
}
}
void createTree(BiTree & T,int i)
{
T = (BiTree)malloc(sizeof(BiTNode));
T->data = 1;
makeTree(T, i);
}
void visitNode(BiTree & T)
{
printf("访问结点的值为%d\n", T->data);
}
void preOrder(BiTree T)
{
if (T != NULL) {
visitNode(T);
preOrder(T->Lchild);
preOrder(T->Rchild);
}
}
void inOrder(BiTree T)
{
if (T != NULL) {
inOrder(T->Lchild);
visitNode(T);
inOrder(T->Rchild);
}
}
void postOrder(BiTree T)
{
if (T != NULL) {
postOrder(T->Lchild);
postOrder(T->Rchild);
visitNode(T);
}
}
void LevelOrder(BiTree T)
{
initQueue(Q);
BiTree p;
enQueue(Q, T);
while (!isEmpty(Q))
{
deQueue(Q, p);
visitNode(p);
if (p->Lchild != NULL)
enQueue(Q,p->Lchild);
if (p->Rchild != NULL)
enQueue(Q, p->Rchild);
}
}
void sumNoLeaf(BiTree T)//使用先序遍历的思想
{
if (T != NULL)
{
if (T->Lchild != NULL || T->Rchild != NULL)//统计非叶子结点个数
sumNoLeafNum++;
//if ((T->Lchild == NULL && T->Rchild != NULL) || (T->Lchild != NULL && T->Rchild == NULL))//统计度为1的结点
// sumNoLeafNum++;
//if (T->Lchild != NULL && T->Rchild != NULL)//统计度数为2的结点
// sumNoLeafNum++;
//if (T->Lchild == NULL && T->Rchild == NULL)//统计叶子结点个数
// sumNoLeafNum++;
sumNoLeaf(T->Lchild);
sumNoLeaf(T->Rchild);
}
//printf("该树的非叶子结点有%d个", sumNoLeafNum);
}
int sumHeight(BiTree T)
{
if (T == NULL)
return 0;
int LeftNum = sumHeight(T->Lchild);
int RightNum = sumHeight(T->Rchild);
return LeftNum >RightNum ? LeftNum + 1:RightNum + 1;
}
| true |
6e1748fca85f9ab6a409171073f4997be1477ec2 | C++ | zbierak/bento | /src/gather/gather-registry.h | UTF-8 | 2,501 | 2.6875 | 3 | [] | no_license | /*
* gather-registry.h
*
* Created on: Nov 13, 2013
* Author: zbierak
*/
#ifndef GATHER_REGISTRY_H_
#define GATHER_REGISTRY_H_
#include <boost/shared_ptr.hpp>
#include <boost/unordered_set.hpp>
#include <boost/unordered_map.hpp>
#include "gather-message-info.h"
namespace bento {
/*
* GatherRegistry accumulates messages (for registered message types only) until
* it obtains at least minMessages messages of a given type from different nodes,
* each containing exactly the same contents.
*
* Note that when exactly the minMessages messages arrive, GatherRegistry notifies
* of that fact, but when more identical messages arrive, it does not. Oh well,
* this doesn't make it easier now, does it? Suppose message of type X has set
* minMessages to 3. Then, when onMessage for message type X with exactly the same
* contents from different nodes is called, then it will return true only for the
* third call, and for the fourth it will return false. This is made in order to prevent
* multiple notifications on the same message.
*/
class GatherRegistry
{
public:
GatherRegistry();
virtual ~GatherRegistry();
/*
* Register new message type in the GatherRegistry
*/
void registerMessageType(int32_t type, unsigned minMessages);
/*
* Deregister a message type from the registry. Do not use (unless 100% sure)
* when some messages have already been received, as it will remove them
* permanently.
*/
void deregisterMessageType(int32_t type);
/*
* Called when a new message has arrived. Returns true if exactly required number
* of messages (including this message) has been obtained and it hasn't returned
* true yet for such message earlier on.
*/
bool onMessage(const std::string& from, int32_t type, const std::string& msg);
/*
* Cleanup the contents of message registry to save memory. This entirely erases
* the log of delivered messages, which might lead to delivering an already delivered
* message once again. Only use when you understand this and all possible implications.
*/
void cleanup();
private:
typedef boost::unordered_map<int32_t, unsigned> AmountMap;
AmountMap m_requiredMinimum;
typedef boost::unordered_map<std::string, boost::shared_ptr<GatherMessageInfo> > MessageMap;
typedef boost::unordered_map<int32_t, MessageMap> TypesMap;
TypesMap m_awaitingMessages;
typedef boost::unordered_set<std::string> MessageSet;
MessageSet m_processedMessages;
};
} /* namespace bento */
#endif /* GATHER_REGISTRY_H_ */
| true |
21bacb2bec51937738c8b17ff3a8662b97239ac8 | C++ | scheuchi/MadMummies | /code/MadMummies/MadMummies/src/Engine/Core/Mesh.h | UTF-8 | 1,017 | 2.625 | 3 | [] | no_license | #pragma once
#include "Transformable.h"
#include "Shader.h"
#include "Texture.h"
#include "VertexBufferObject.h"
#include <vector>
class Mesh : public Transformable
{
typedef Transformable Base;
public:
Mesh(void);
virtual ~Mesh(void);
virtual void Update(double deltaT);
virtual void Render();
virtual void UploadToVram();
virtual void UnloadFromVram();
void SetShader(Shader* shader) { m_shader = shader; }
Shader* GetShader() { return m_shader; }
void AddTexture(Texture* texture) { if (texture != 0) { m_vecTextures.push_back(texture); } }
std::vector<Texture*> GetTextures() { return m_vecTextures; }
void SetVertexBufferObject(VertexBufferObject* vbo) { m_vertexBufferObject = vbo; }
VertexBufferObject* GetVertexBufferObject() { return m_vertexBufferObject; }
private:
Shader* m_shader;
std::vector<Texture*> m_vecTextures;
GLuint m_vaoHandle;
VertexBufferObject* m_vertexBufferObject;
glm::mat4 m_mvpMatrix;
glm::mat3 m_normalMatrix;
}; | true |
f3b582c586af53a7d1fdaa87be31f10b106d264d | C++ | Ishank-Gupta/CPP_code | /HybridInheritance.cpp | UTF-8 | 370 | 2.78125 | 3 | [] | no_license | #include <iostream>
#pragma pack(4)
using namespace std;
class CA {
public:
int a;
};
class CB :virtual public CA {
public:
int b;
};
class CC :virtual public CA {
public:
int c;
};
class CD : public CB, public CC {
public:
int d;
};
int main()
{
cout << "Size of the CA object : " << sizeof(CD) << endl;
CD obj1;
obj1.a = 100;
} | true |
223db8f5e65971115a734b6bf9d1910abea9c3ee | C++ | devoidofreason/ChessGame | /include/Bishop.cpp | UTF-8 | 1,178 | 2.734375 | 3 | [
"BSD-3-Clause"
] | permissive | #include "Bishop.h"
std::vector<Square*> Bishop::possibleSquares(Board* board, Square* square){
std::vector<Square*> ret;
int x = square->getX(), y = square->getY();
int i, j;
i = x - 1;
j = y - 1;
while(board->onBoard(i,j)){
if(!board->board[i][j]->getPiece())
ret.push_back(board->board[i][j]);
else{
if(canCapture(board->board[i][j]))
ret.push_back(board->board[i][j]);
break;
}
i--;
j--;
}
i = x + 1;
j = y - 1;
while(board->onBoard(i,j)){
if(!board->board[i][j]->getPiece())
ret.push_back(board->board[i][j]);
else{
if(canCapture(board->board[i][j]))
ret.push_back(board->board[i][j]);
break;
}
i++;
j--;
}
i = x - 1;
j = y + 1;
while(board->onBoard(i,j)){
if(!board->board[i][j]->getPiece())
ret.push_back(board->board[i][j]);
else{
if(canCapture(board->board[i][j]))
ret.push_back(board->board[i][j]);
break;
}
i--;
j++;
}
i = x + 1;
j = y + 1;
while(board->onBoard(i,j)){
if(!board->board[i][j]->getPiece())
ret.push_back(board->board[i][j]);
else{
if(canCapture(board->board[i][j]))
ret.push_back(board->board[i][j]);
break;
}
i++;
j++;
}
return ret;
} | true |
0c588f5f3d7847fbdf428affc8e6c27321afc61b | C++ | bengross234/CSE332S-FL2020 | /oop_work-evinlanedavidstudio16-21/SharedCode/SimpleFileSystem.cpp | UTF-8 | 1,863 | 3 | 3 | [] | no_license | // define methods of SimpleFileSystem class here
#include "SimpleFileSystem.h"
#include "TextFile.h"
#include "ImageFile.h"
#include <iostream>
using namespace std;
set<string> SimpleFileSystem::getFileNames() {
set<string> fileNames;
//iterate over allFiles, adding names to set
map<std::string, AbstractFile*>::iterator it;
for (it = allFiles.begin(); it != allFiles.end(); ++it) {
fileNames.insert(it->first);
}
return fileNames;
}
int SimpleFileSystem::addFile(std::string name, AbstractFile* file){
//check null ptr
if (file == nullptr){
return returns::null_Pointer;
}
//check already included
if (allFiles.find(name) != allFiles.end()){
return returns::already_Exists;
}
//otherwise insert
allFiles.insert(std::pair<std::string, AbstractFile*>(name,file));
return returns::successlocal;
}
int SimpleFileSystem::deleteFile(std::string name) {
//check if exists
if (allFiles.find(name) == allFiles.end()){
return returns::doesNotExist;
}
//check if open
auto it = allFiles.find(name);
AbstractFile* file = it->second;
if (openFiles.find(file) != openFiles.end()){
return returns::cantDeleteOpenFile;
}
//else remove file from map, delete pointer
allFiles.erase(name);
delete file;
return successlocal;
}
AbstractFile* SimpleFileSystem::openFile(string name) {
//if file exists
if (allFiles.find(name) != allFiles.end()){
auto it = allFiles.find(name);
AbstractFile* file = it->second;
//if file is not already open
if (openFiles.find(file) == openFiles.end()){
openFiles.insert(file);
return file;
}
}
//if failed to open, return nullptr
return nullptr;
}
int SimpleFileSystem::closeFile(AbstractFile* file) {
//if file is currently open
if (openFiles.find(file) != openFiles.end()) {
openFiles.erase(file);
return successlocal;
}
else {
return cantCloseUnopenedFile;
}
}
| true |
dc4f5f6a0661fd7cacb8536a49448d3fa5b4e25d | C++ | hyemmie/algorithm_study | /Backjoon/Tree/13016.cpp | UTF-8 | 1,723 | 3.390625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
using namespace std;
int diameterStart, diameterEnd, maxLength = 0;
int distanceFromStart[50001], distanceFromEnd[50001], visited[50001];
vector<pair<int,int>> roads[50001];
void dfs(int pos, int length) {
// 이미 방문했으면 통과
if(visited[pos]) return;
// 방문하고 현재까지의 거리를 갱신
visited[pos] = 1;
distanceFromEnd[pos] = length;
// 최장 거리 갱신하며 현재 노드 저장
if(maxLength < length) {
diameterEnd = pos;
maxLength = length;
}
// 현재 노드와 연결된 모든 노드 방문
for(int i = 0; i < roads[pos].size(); i++)
dfs(roads[pos][i].first, length + roads[pos][i].second);
// 다음 순회를 위해 초기화
visited[pos] = 0;
}
int main() {
int n, from, to, length;
cin >> n;
for(int i = 0; i < n-1; i++) {
cin >> from >> to >> length;
roads[from].push_back(make_pair(to, length));
roads[to].push_back(make_pair(from, length));
}
// 첫 순회 : 1번 노드부터 최장길이 0인채로 시작하여 maxLength, 지름의 시작점 구함
dfs(1,0);
diameterStart = diameterEnd;
maxLength = 0;
// 두 번째 순회 : 지름 시작 노드부터 각 노드까지의 거리 저장하고 가장 먼 노드(지름의 끝점) 구함
dfs(diameterStart,0);
for(int i = 1; i <= n; i++) {
distanceFromStart[i] = distanceFromEnd[i];
distanceFromEnd[i] = 0;
}
// 마지막 순회 : 지름 끝점부터 각 노드까지의 거리 저장
dfs(diameterEnd,0);
// 각 노드에서 가장 먼 노드(시작점 or 끝점)까지의 거리 출력
for(int i = 1; i <= n; i++)
cout << max(distanceFromStart[i], distanceFromEnd[i]) << "\n";
} | true |
b43947362b77206084b370c9b8645283eb6170b9 | C++ | V2beach/Algorithm-exercise | /浙大PAT/A1071.cpp | UTF-8 | 1,319 | 3.09375 | 3 | [] | no_license | #pragma warning(disable: 4996)
#include <map>
#include <string>
#include <iostream>
using namespace std;
bool isAlphanumeric(char &character) {
if (character >= '0' && character <= '9')
return true;
else if (character >= 'a' && character <= 'z')
return true;
else if (character >= 'A' && character <= 'Z') {
character = character - 'A' + 'a';
return true;
}
return false;
}
int main(int argc, char* argv[]) {
ios::sync_with_stdio(false);
string testcase;
getline(cin, testcase);//注意读一行要用getline,老是忘记
map<string, long> words;
map<string, long>::iterator it;
string substring;
long index = 0, prev = 0;
for (; index < testcase.size(); index++) {
if (isAlphanumeric(testcase[index])) {
prev = index;
while (isAlphanumeric(testcase[++index]));//找到之后的第一个non-alphanumeric
substring = testcase.substr(prev, index - prev);
it = words.find(substring);
if (it == words.end())
words.insert(pair<string, long>(substring, 1));
else
it->second++;
}
}
long sax = 0;
for (it = words.begin(); it != words.end(); it++) {
//cout << it->first << " " << it->second << endl;
if (it->second > sax) {
sax = it->second;
substring = it->first;
}
}
cout << substring << " " << sax << endl;
system("pause");
return 0;
}
//光速完成 | true |
9694566beda7717fbffc8cebdd5339a60743686f | C++ | starptr/Simple-Statistics | /Simple Statistics/main.cpp | UTF-8 | 5,326 | 3.078125 | 3 | [] | no_license | #include <iostream>
#include <vector>
//for testing constructor feeder
#include <array>
#include <stack>
#include <queue>
#include <deque>
#include <forward_list>
#include <list>
#include "llist.h"
#include "simple_stats.h"
#include "randomdata.h"
#include "pair.h"
int main(int argc, char* argv[]) {
Random_data<int> test;
std::vector<int> v1 = test.get_random_vector(10, 1, 5);
std::set<int> v2;
for (int v : v1)
std::cout << v << ' ';
std::cout << std::endl;
for (int v : v1)
v2.insert(v);
for (int v : v2)
std::cout << v << ' ';
std::cout << std::endl;
LList<int> i_linked_list;
for (int v : v1)
i_linked_list.append(v);
std::cout << "Mode is ";
for (int m : i_linked_list.get_mode())
std::cout << m << " ";
std::cout << std::endl;
std::cout << "Median is " << i_linked_list.get_median() << std::endl;
std::cout << "Mean is " << i_linked_list.get_mean() << std::endl;
std::cout << "SD is " << i_linked_list.get_SD() << std::endl;
std::cout << "Min is " << i_linked_list.get_min() << std::endl;
std::cout << "Max is " << i_linked_list.get_max() << std::endl;
Random_data<int> randgen;
std::vector<int> randomvector = randgen.get_random_vector(100, 0, 25);
std::cout << "Randomvector: ";
for (int i : randomvector) {
std::cout << i << ", ";
}
simple_stats<int> test0;
//Empty constructor:
std::cout << "\nPrinting all elements in EMPTIED class:";
test0.printallelements();
std::cout << "printing finished" << std::endl;
//1. Append():
test0.append(4);
test0.append(2);
for (int i : randomvector) {
test0.append(i);
}
test0.printallelements();
//2. removen();
for (int i = 0; i < 3; i++) {
test0.append(4);
test0.append(8);
}
std::cout << "Printing simple_stats before removing elements:" << std::endl;
test0.printallelements();
test0.removen(4, 2); //Removing some but not all 4s
test0.removen(8, 10000); //Removing 10000 of 8s, demonstrating removal of unique value and program having safety limits that prevent decrementing a value's repetitions into the negatives
test0.removen(100000, 20); //Recognizing when a value does not exist
test0.printallelements();
std::cout << "Removen finished" << std::endl;
//3. empty();
std::cout << "Emptying simple_stats \n";
test0.empty();
std::cout << "Printing simple_stats after emptying: \n";
test0.printallelements();
//4. feed from any standard C++ container
simple_stats<int> test1(randomvector);
std::cout << "Printing test 1: \n";
test1.printallelements();
//initializing an std::array
std::array<int, 100> stlarray1;
for (int i = 0; i < randomvector.size(); i++) {
stlarray1[i] = randomvector[i];
}
simple_stats<int> test2(stlarray1);
std::cout << "Printing test 2: \n";
test2.printallelements();
//initializing double std array
std::array<double, 100> stlarray2;
for (int i = 0; i < randomvector.size(); i++) {
stlarray2[i] = randomvector[i];
}
simple_stats<double> test3(stlarray2);
std::cout << "Printing test 3: \n";
test3.printallelements();
//initializing long std array
std::array<long, 100> stlarray3;
for (int i = 0; i < randomvector.size(); i++) {
stlarray3[i] = randomvector[i];
}
simple_stats<double> test4(stlarray3);
std::cout << "Printing test 4: \n";
test4.printallelements();
//initializing stack
/*std::stack<int> stack;
for (int i = 0; i < randomvector.size(); i++) {
stack.push(randomvector[i]);
}
simple_stats<int> test5(stack);
std::cout << "Printing test 5: \n";
test5.printallelements();
//insert more tests here if time
*/
//5. search
std::cout << "Now searching for value 5 in test2" << std::endl;
std::cout << "Found it at position " << test2.search(5).value << " where there are " << test2.search(5).freq << " of them" << std::endl;
//6. array index []
std::cout << "The 7th unique element in test2 is \n";
std::cout << test2[7] << std::endl;
std::cout << "(due to high duplication and even spread of randomdata.h, the value at an index number is likely the index number \n\n";
//7. length_unique: number of unique elements in your data object
std::cout << "There are " << test2.length_unique() << " unique elements in test2 \n";
//8. length_total : total number of elements in your data object
std::cout << "and " << test2.length_total() << " total elements. \n";
// 9. unique_set : return all the unique elements as an std::set
std::cout << "All the unique numbers in test2 are: \n";
// test2.unique_set
std::set<int> unique_set = test2.unique_set();
std::set<int>::const_iterator setIter = unique_set.begin();
for (int i = 0; i < test2.length_unique(); i++) {
std::cout << *(setIter)+i << " ";
}
std::cout << "\n";
//10.1 get_mode
std::cout << "\n The mode(s) of test2, if there is any, are \n";
for(int i: test2.get_mode())
std::cout << i << " ";
std::cout << std::endl;
//10.2 get_median
std::cout << "\nThe median of test2 is: \n";
std::cout << test2.get_median() << std::endl;
//10.3 get_mean
std::cout << "\nThe mean of test2 is: \n";
std::cout << test2.get_mean() << std::endl;
//10.4 get_SD
std::cout << "\n The standard deviation of set {\n";
for (int i : randomvector) {//copy and paste this guy into a standard deviations calculator to check
std::cout << i << ", ";
}
std::cout << "} \n is: \n";
std::cout << test2.get_SD() << std::endl;
return 0;
}
| true |
5eba5fd258cb7bd546f969ee8dc6a19f047b35da | C++ | Sankalpbp/KarumanchiProblems | /searching/closestToZero.cpp | UTF-8 | 734 | 3.296875 | 3 | [] | no_license | #include <iostream>
#include <cmath>
#include <climits>
#include <algorithm>
using namespace std;
int pairSum(int * arr, int n) {
int closestSum = arr[0] + arr[1];
int sum = 0;
for(int i = 0; i < n - 1; ++i) {
sum = 0;
for(int j = i + 1; j < n; ++j) {
sum = arr[i] + arr[j];
if(abs(sum) < abs(closestSum)) {
closestSum = sum;
}
}
}
return closestSum;
}
int main() {
//code
int t;
cin >> t;
while(t--) {
int n;
cin >> n;
int * arr = new int[n];
for(int i = 0; i < n; ++i) {
cin >> arr[i];
}
cout << pairSum(arr, n) << endl;
delete[] arr;
}
return 0;
}
| true |
4d867b614539bf086908fa493b5c1f18773cb491 | C++ | kohyatoh/contests | /pku/2410/2410.cpp | UTF-8 | 1,070 | 2.75 | 3 | [] | no_license | #include <stdio.h>
#include <iostream>
#include <string>
#include <algorithm>
#define rep(i, n) for(int i=0; i<(int)(n); i++)
using namespace std;
string enc(int n) {
string s;
rep(i, 8) { s += n%2+'0'; n/=2; }
reverse(s.begin(), s.end());
return s;
}
int dec(const string& s) {
int n=0;
rep(i, s.size()) { n*=2; n+=s[i]-'0'; }
return n;
}
int accu, pc;
int mem[256];
int main() {
for(;;) {
string s;
if(!(cin>>s)) return 0;
mem[0] = dec(s);
rep(i, 31) { cin>>s; mem[i+1]=dec(s); }
accu = 0; pc = 0;
for(;;) {
int op=mem[pc]/32, x=mem[pc]%32;
pc = (pc+1)%32;
if(op==0) { mem[x] = accu; }
else if(op==1) { accu = mem[x]; }
else if(op==2) { if(accu==0) pc = x; }
else if(op==3) {}
else if(op==4) { accu--; if(accu<0) accu=255; }
else if(op==5) { accu = (accu+1) % 256; }
else if(op==6) { pc = x; }
else { break; }
}
cout << enc(accu) << endl;
}
}
| true |
f4f4173166faa66c332580a390891bbfe8ee7169 | C++ | nabond251/gardener | /main.cpp | UTF-8 | 1,359 | 2.828125 | 3 | [] | no_license | /**
* @brief Gardener main application.
*/
#include "main.h"
#include <iostream>
#include <wiringPi.h>
#include "config.h"
#include "gardener.h"
#include "pump.h"
#include "timer.h"
#include <ctime>
using namespace gardener;
using namespace std;
const int PWM0_pin = 1; /* GPIO 1 as per WiringPi, GPIO18 as per BCM */
const int PWM1_pin = 24;
/**
* @brief Gardener execution entry point.
*
* @param [in] argc CLI argument count.
* @param [in] argv CLI argument vector.
*
* @returns 0 if executed successfully, else error code.
*/
int main(int argc, char *argv[])
{
cout << argv[0]
<< " Version "
<< Gardener_VERSION_MAJOR
<< "."
<< Gardener_VERSION_MINOR
<< endl;
if (wiringPiSetup() == -1)
{
exit(1);
}
const int msPerDay = 24 * 60 * 60 * 1000;
const int waterTimeMs = 50 * 1000;
const int waitTimeMs = msPerDay - waterTimeMs;
IConfig *cfg = new Config(waitTimeMs, waterTimeMs);
ITimer *gardenerTmr = new Timer();
ITimer *dwellTmr = new Timer();
IPump *pump = new Pump(PWM0_pin, PWM1_pin, *dwellTmr);
IGardener *gardener = new Gardener(*cfg, *pump, *gardenerTmr);
while (1)
{
pump->transition();
gardener->transition();
pump->execute();
gardener->execute();
delay(10);
}
}
| true |
b2e1205c8dadac11f3da056305514f5ada53f46d | C++ | umamibeef/SpeedRoute | /SpeedRoute/FileParser.cpp | UTF-8 | 4,172 | 2.96875 | 3 | [] | no_license | //
// FileParser.cpp
// SpeedRoute
//
// Created by Michel Kakulphimp on 2018-03-24.
// Copyright © 2018 Michel Kakulphimp. All rights reserved.
//
#include "FileParser.hpp"
#include "Types.h"
int g_enlargementFactor = SPACE_ENLARGEMENT_FACTOR;
FileParser::FileParser(std::string netFilename, std::string placementFilename)
{
mNetFilename = netFilename;
mPlacementFilename = placementFilename;
if(g_enlargementFactor > 1)
{
std::cout << "Warning, space enlargement factor is greater than 1! (" << g_enlargementFactor << ")" << std::endl << std::endl;
}
}
FileParser::~FileParser(void)
{
}
void FileParser::setFilenames(std::string netFilename, std::string placementFilename)
{
mNetFilename = netFilename;
mPlacementFilename = placementFilename;
}
bool FileParser::parseInput(void)
{
bool rv = true;
// Try parsing the net file
if(!parseNetFile())
{
rv = false;
}
// Now try parsing the placement file
if(!parsePlacementFile())
{
rv = false;
}
return rv;
}
parsedInputStruct_t FileParser::getParsedInput(void)
{
return mParsedInput;
}
bool FileParser::parseNetFile(void)
{
unsigned int i, j, numNodes;
std::string line;
std::vector<std::string> stringVec;
std::ifstream inputFile(mNetFilename, std::ios::in);
// Check if file was opened properly
std::cout << "Parsing net file..." << std::endl;
if (inputFile.is_open())
{
std::cout << "File " << mNetFilename << " opened! Here's what's in it:" << std::endl;
}
else
{
std::cout << "FATAL ERROR! File " << mNetFilename << " could not be opened!" << std::endl;
return false;
}
// Get number of cells, number of nets, and grid size
std::getline(inputFile, line);
stringVec = Util_SplitString(line, ' ');
mParsedInput.numNodes = stoi(stringVec[0]);
mParsedInput.numConnections = stoi(stringVec[1]);
mParsedInput.numRows = stoi(stringVec[2]) * g_enlargementFactor;
mParsedInput.numCols = stoi(stringVec[3]) * g_enlargementFactor;
std::cout << "Grid size is: " << mParsedInput.numRows << " rows x " << mParsedInput.numCols << " cols" << std::endl;
std::cout << "Number of nodes is: " << mParsedInput.numNodes << std::endl;
std::cout << "Number of connections is: " << mParsedInput.numConnections << std::endl << std::endl;
// Get all connections
for (i = 0; i < mParsedInput.numConnections; i++)
{
std::getline(inputFile, line);
stringVec = Util_SplitString(line, ' ');
// Get number of nodes for this net
numNodes = stoi(stringVec[0]);
// Now get all nodes for this net
// Push back a new vector for this
mParsedInput.nets.push_back(std::vector<int>());
for (j = 0; j < numNodes; j++)
{
mParsedInput.nets[i].push_back(stoi(stringVec[j + 1]));
}
}
inputFile.close();
return true;
}
bool FileParser::parsePlacementFile(void)
{
unsigned int i;
std::string line;
std::vector<std::string> stringVec;
posStruct_t tempPos;
std::ifstream inputFile(mPlacementFilename, std::ios::in);
// Check if file was opened properly
std::cout << "Parsing placement file..." << std::endl;
if (inputFile.is_open())
{
std::cout << "File " << mPlacementFilename << " opened!" << std::endl;
}
else
{
std::cout << "FATAL ERROR! File " << mPlacementFilename << " could not be opened!" << std::endl;
return false;
}
// There will be exactly enough placements, so iterate through the expected amount
for(i = 0; i < mParsedInput.numNodes; i++)
{
std::getline(inputFile, line);
stringVec = Util_SplitString(line, ' ');
// Row comes first followed by column
tempPos.row = stoi(stringVec[1]) * g_enlargementFactor;
tempPos.col = stoi(stringVec[2]) * g_enlargementFactor;
// Push back a placement
mParsedInput.placement.push_back(tempPos);
}
std::cout << std::endl;
inputFile.close();
return true;
}
| true |
0d86037c7718f15341e533b5bba5c1e60ea68d9d | C++ | amirharati/hunter_trainer | /spectrogram/spectrogram_test.cc | UTF-8 | 3,215 | 2.84375 | 3 | [] | no_license | // file: spectrogram_test.cc
//
// isip include files
//
#include "spectrogram.h"
// spectrogram: automated sound comparison utility
//
// This is a driver program that demonstrates the functionality
// of the sound comparison module.
//
long readfile(double **sig,char *filename);
int savefile(double *sig,long num_samples, char *filename);
int main(int argc, const char** argv) {
// create a sound comparison object
//
Spectrogram spg;
double *sig;
long num_samples;
long error_code;
// declare local variables
//
//---------------------------------------------------------------------------
// configure and parse the command line:
// nothing fancy here, a fixed argument structure is assumed
//---------------------------------------------------------------------------
// check the arguments
//
if (argc < 1) {
system("cat help_message.text");
exit(-1);
}
// grab the arguments
//
char* input_file = (char*)argv[1];
//char* input_type = (char*)argv[3]; //short , int, double
// echo the command line
//
fprintf(stdout, "This program is to test the spectrogram.\n");
fprintf(stdout, "The input signal should be saved in \"double\" format.\n");
fprintf(stdout, "input file: %s\n", input_file);
//--------------------------------------------------------------------------
//
// main processing loop
//
//---------------------------------------------------------------------------
num_samples=readfile(&sig,input_file);
if (spg.set_signal(sig,num_samples) !=0)
{
fprintf(stdout," Error in set_signal.\n");
exit(-1);
}
if ((error_code=spg.set_params(64,4,1,HAMMING,NORMAL)) !=0)
{
fprintf(stdout," Error in set_params %ld \n",error_code);
exit(-1);
}
spg.spectrogram();
for (int i=0;i<spg.nFreq_bins;i++)
{
for (int j=0;j<spg.nTime_bins;j++)
{
fprintf(stdout, "(%f,%f)\t",spg.spectrogram1[i][j],spg.spectrogram2[i][j]);
}
fprintf(stdout,"\n");
}
//savefile(spg.sigpow,num_samples,output_file);
// exit gracefully
//
free(sig);
exit(0);
}
long readfile(double **sig,char *filename)
{
// open the file read only
//
long num_samples;
FILE* fp = fopen(filename, "r");
if (fp == NULL) {
fprintf(stdout, "*> Spectrogram_test:: readfile: error opening file (%s)\n",
filename);
return 0;
}
// grab the file size
//
fseek (fp, 0, SEEK_END);
long num_samples_in_file = ftell(fp) / sizeof(double);
rewind (fp);
// load the file into memory
//
*sig = (double*)malloc(num_samples_in_file*sizeof(double));
num_samples = fread(*sig, sizeof(double), num_samples_in_file, fp);
if (num_samples != num_samples_in_file) {
fprintf(stdout, "*> Spectrogram_test:: readfile: Number of samples is not the same as expected.");
return 0;
}
// close the file
//
fclose(fp);
return num_samples;
}
int savefile(double *sig,long num_samples, char *filename)
{
FILE *fo=fopen(filename,"w");
for(int i=0;i<num_samples;i++)
{
fprintf(fo,"%f ",sig[i]);
}
fclose(fo);
return 0;
}
| true |