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
f36eefb0a7348087ffc465bc1cc1828dd24647e2
C++
AshwathVS/Programming
/ctci/check_balanced.cpp
UTF-8
764
3.765625
4
[]
no_license
#include <bits/stdc++.h> using namespace std; class Node { public: int val; Node *left; Node *right; Node(int val) { this->val = val; this->left = NULL; this->right = NULL; } Node(int val, Node *left, Node *right) { this->val = val; this->left = left; this->right = right; } }; int depth(Node *node) { if (node == NULL) return 0; else { return 1 + max(depth(node->left), depth(node->right)); } } int isBalanced(Node *node) { return abs(depth(node->left) - depth(node->right)) <= 1; } int main() { Node *root = new Node(4, new Node(2, new Node(1), new Node(3)), new Node(6, new Node(5), new Node(7))); cout << isBalanced(root); }
true
c4b46a2e019a1005133e439d96146465b51cada8
C++
P79N6A/workspace
/test.code/cpp_test/unorder_map.cpp
UTF-8
860
2.96875
3
[ "Apache-2.0" ]
permissive
#include <string> #include <iostream> #include <algorithm> #include <tr1/unordered_map> #include <unordered_map> using namespace std; using namespace tr1; using namespace std::tr1; void myfunc(const std::pair<std::string,std::string>& obj) { std::cout << "first=" << obj.first << "second=" << obj.second <<std::endl; } int main(int argc,char *argv[]) { std::tr1::unordered_map<std::string, std::string> ssmap; ssmap.insert(std::make_pair("aaaa","aaaaa1")); ssmap.insert(std::make_pair("bbbb","bbbbb1")); ssmap.insert(std::make_pair("cccc","ccccc1")); std::for_each(ssmap.begin(),ssmap.end(),myfunc); std::tr1::unordered_map<std::string, std::string>::iterator iter = ssmap.begin(); for(;iter != ssmap.end();iter++){ std::cout << "first=" << iter->first << "second=" << iter->second <<std::endl; } return 0; }
true
d86828f68684fce556c84579fc36b4b4a4277559
C++
fit-uifs/vtapi
/include/vtapi/data/method.h
UTF-8
4,118
2.71875
3
[]
no_license
/** * @file * @brief Declaration of Method class * * @author Vojtech Froml, xfroml00 (at) stud.fit.vutbr.cz * @author Tomas Volf, ivolf (at) fit.vutbr.cz * * @licence @ref licence "BUT OPEN SOURCE LICENCE (Version 1)" * * @copyright &copy; 2011 &ndash; 2015, Brno University of Technology */ #pragma once #include "keyvalues.h" #include "task.h" #include "taskparams.h" namespace vtapi { class Task; class TaskParams; /** * @brief A class which represents methods and gets also their keys * * @see Basic definition on page @ref BASICDEFS * * @author Vojtech Froml, xfroml00 (at) stud.fit.vutbr.cz * @author Tomas Volf, ivolf (at) fit.vutbr.cz * * @licence @ref licence "BUT OPEN SOURCE LICENCE (Version 1)" * * @copyright &copy; 2011 &ndash; 2015, Brno University of Technology */ class Method : protected KeyValues { public: /** * @brief Copy constructor * @param copy original object */ Method(const Method& copy); /** * Construct method object for iterating through VTApi methods * If a specific name is set, object will represent one method only * @param commons base Commons object * @param name method name, empty for all methods */ Method(const Commons& commons, const std::string& name = std::string()); /** * Construct method object for iterating through VTApi methods * Object will represent set of methods specified by their names * @param commons base Commons object * @param names vector of method names */ Method(const Commons& commons, const std::vector<std::string>& names); using KeyValues::count; using KeyValues::updateExecute; /** * Moves to a next method and set a method name and its methodkeys variables * @return success * @note Overloading next() from KeyValues */ bool next() override; /** * Gets a name of the current method * @return string value with the name of the method */ std::string getName() const; /** * Gets object containing method parameters definitions * @return task parameters map */ TaskParamDefinitions getParamDefinitions() const; /** * Gets description of the current method * @return description of the current dataset */ std::string getDescription() const; /** * @brief Gets absolute path to method library * @return path */ std::string getPluginPath() const; /** * @brief Determine if progress is based on sequence length normalization or the process progress value only (all sequences together) * @return sequence length normalization (=TRUE) or process progress value only (=FALSE) */ bool isProgressBasedOnSeq() const; /** * Sets method's description * @param description new description * @return success */ bool updateDescription(const std::string& description); /** * @brief Creates new task for given dataset * @param dsname dataset name * @param params task parameters * @param prereq_task prerequisite task, empty for none * @param outputs optional output table * @return created task object, NULL on error */ Task *createTask(const std::string& dsname, const TaskParams& params, const std::string& prereq_task, const std::string& outputs = std::string()) const; /** * Loads method's processing tasks for iteration * @param name task name (no name = all tasks) * @return pointer to the new Task object, NULL on error */ Task* loadTasks(const std::string& name = std::string()) const; /** * @brief Deletes task with given name * @param dsname dataset with given task * @param taskname task name to delete * @return succesful delete */ bool deleteTask(const std::string &dsname, const std::string &taskname) const; protected: bool preUpdate() override; private: Method() = delete; Method& operator=(const Method&) = delete; }; } // namespace vtapi
true
f71ff935fe4c3ae32c32beadb69c8e7999099809
C++
sanuguladurgaprasad/Codes
/GRAPHS/scomp2.cpp
UTF-8
2,434
2.625
3
[]
no_license
#include<fstream> #include<iostream> #include<cctype> using namespace std; struct adj { int **a; }; struct node { char data; int vis; int dg; int low; int pn;//postorder numbering; }; int min(int p,int q) { if(p>q){return q;} else {return p;} } int deg(node n[],adj A,int d,int c) {int y=0; for(int i=0;i<d;i++){if(A.a[c][i]==0){y++;}} if(y==d){return 1;} else return 0; }char r1='$'; int t=0,start=-1,r; void dft(int c,int d,adj A,node n[]) {int i,j; for(i=0;i<d;i++) {n[c].vis=1; if((A.a[c][i]==1)&&(n[i].vis!=1)) {A.a[c][i]=0; n[i].pn=++t; n[i].low=n[i].pn; // n[i].parent=n[c].data; dft(i,d,A,n); //if((c==start)&&(deg(n,A,d,c)==1)){break;} n[c].low=min(n[i].low,n[c].low);//since it has back edges if((c!=start)&&(n[i].low>=n[c].pn)) {cout<<n[c].data<<"M\n";} else{cout<<n[c].data<<"H,";} if((n[i].dg==0)){cout<<n[i].data<<"B\n";} } else if((A.a[c][i]==1)&&(n[i].vis==1)&&(n[i].pn<n[c].pn)) {A.a[c][i]=0;if(r1=='$'){cout<<n[c].data<<"S,"; n[c].low=min(n[i].low,n[c].low);} else if(isalpha(r1)) {if((n[i].pn>=r)&&(n[c].pn>=r)){ if(n[c].pn>n[i].pn) {cout<<n[c].data<<"A,";n[c].low=min(n[i].pn,n[c].low);}} // else {n[c].low=min(n[i].pn,n[c].low);} } } } } void input(node n[],int d) { char s='a'; cout<<"enter data in to the vertices"; for(int i=0; i<d; i++) { n[i].data=s; s++; } } int find(node n[],int s,int d) { for(int i=0; i<d; i++) { if(n[i].data==s) { return i; } } } adj begin(ifstream& fin,adj A,int d,node n[]) { int i,j,u; (A.a)=new int*[d]; for(i=0; i<d; i++) { A.a[i]=new int[d]; } for(i=0; i<d; i++) { u=0;for(j=0; j<d; j++) { fin>>A.a[i][j];if(A.a[i][j]!=0){u++;} cout<<A.a[i][j]; }n[i].dg=u; cout<<endl; } return A; } main() { ifstream fin; fin.open("pi.cpp"); int c,i,j,d; char s; adj A; cout<<"enter the no. of vertices\n"; cin>>d; node n[d]; input(n,d); for(i=0; i<d; i++) { n[i].vis=0; } A=begin(fin,A,d,n); cout<<"enter starting vertex\n"; cin>>s; c=find(n,s,d);start=c; n[c].pn=++t;n[c].low=n[c].pn; dft(c,d,A,n); for(i=0; i<d; i++) { if(n[i].vis!=1) {cout<<endl;start=i;n[i].pn=++t;r1=n[i].data; r=n[find(n,n[i].data,d)].pn;dft(i,d,A,n); } } for(i=0; i<d; i++) { cout<<endl<<n[i].data<<n[i].pn<<n[i].low; } cout<<"are the strong components\n"; cin>>d; }
true
60208572689251ba011faca570ac7432492a4825
C++
SpatialTranscriptomicsResearch/st_viewer
/src/data/Spot.cpp
UTF-8
2,775
3.1875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#include "data/Spot.h" Spot::Spot() : m_coordinates(0,0) , m_visible(false) , m_selected(false) , m_color(Qt::black) , m_name() , m_totalCount(0) { } Spot::Spot(const QString name) : m_coordinates(0,0) , m_adj_coordinates(0,0) , m_visible(false) , m_selected(false) , m_color(Qt::white) , m_name(name) , m_totalCount(0) { m_coordinates = getCoordinates(name); m_adj_coordinates = m_coordinates; } Spot::Spot(const Spot &other) { m_coordinates = other.m_coordinates; m_adj_coordinates = other.m_adj_coordinates; m_color = other.m_color; m_name = other.m_name; m_visible = other.m_visible; m_selected = other.m_selected; m_totalCount = other.m_totalCount; } Spot::~Spot() { } Spot &Spot::operator=(const Spot &other) { m_coordinates = other.m_coordinates; m_adj_coordinates = other.m_adj_coordinates; m_visible = other.m_visible; m_selected = other.m_selected; m_color = other.m_color; m_name = other.m_name; m_totalCount = other.m_totalCount; return (*this); } bool Spot::operator==(const Spot &other) const { return (m_coordinates == other.m_coordinates && m_adj_coordinates == other.m_adj_coordinates && m_visible == other.m_visible && m_selected == other.m_selected && m_color == other.m_color && m_name == other.m_name && m_totalCount == other.m_totalCount); } Spot::SpotType Spot::coordinates() const { return m_coordinates; } Spot::SpotType Spot::adj_coordinates() const { return m_adj_coordinates; } QColor Spot::color() const { return m_color; } QString Spot::name() const { return m_name; } bool Spot::visible() const { return m_visible; } bool Spot::selected() const { return m_selected; } float Spot::totalCount() const { return m_totalCount; } void Spot::coordinates(const SpotType &coordinates) { m_coordinates = coordinates; } void Spot::adj_coordinates(const SpotType &adj_coordinates) { m_adj_coordinates = adj_coordinates; } void Spot::visible(const bool visible) { m_visible = visible; } void Spot::selected(const bool selected) { m_selected = selected; } void Spot::color(const QColor color) { m_color = color; } void Spot::totalCount(const float totalCount) { m_totalCount = totalCount; } Spot::SpotType Spot::getCoordinates(const QString &spot) { const QStringList items = spot.trimmed().split("x"); Q_ASSERT(items.size() == 2); const float x = items.at(0).toFloat(); const float y = items.at(1).toFloat(); return SpotType(x,y); } QString Spot::getSpot(const Spot::SpotType &spot) { return QString::number(spot.first) + "x" + QString::number(spot.second); }
true
f0508681cd77768e5319e2c91ff40e6bff3970c9
C++
MylesAdams/ApolloTradingBot
/src/TradingSession.h
UTF-8
947
2.53125
3
[]
no_license
// // Created by Myles Adams on 3/8/18. // #ifndef APOLLOTRADINGBOT_TRADINGSESSION_H #define APOLLOTRADINGBOT_TRADINGSESSION_H #include <string> #include <cpprest/asyncrt_utils.h> namespace Apollo{ class TradingSession { private: time_t start_time_; time_t end_time_; double currency_start_amount_; double currency_end_amount_; double btc_start_amount_; double btc_end_amount_; std::string currency_ticker_; double total_in_btc_start_; double total_in_btc_end_; public: void setStartTime(); void setEndTime(); void setCurrencyStartAmount(double amount); void setCurrencyEndAmount(double amount); void setBTCStartAmount(double amount); void setBTCEndAmount(double amount); void setTotalInBTCStart(double first_price); void setTotalInBTCEnd(double last_price); void setCurrencyTicker(std::string ticker); void printSessionToFile(); }; } #endif //APOLLOTRADINGBOT_TRADINGSESSION_H
true
03a60e52a9ec1eb420507531fd4614adff4a9a49
C++
siljawalenius/LibraryBooks-CPP
/main.cpp
UTF-8
3,766
3.25
3
[]
no_license
// Student Name: Silja Walenius // Student Number: 20710274 // // SYDE 121 Lab: 07 Assignment: 01 // Filename: Lab07_01 // // I hereby declare that this code, submitted for credit for the course // SYDE121, is a product of my own efforts. This coded solution has // not been plagiarized from other sources and has not been knowingly // plagiarized by others. // // Project: Library // Purpose: Stores book class objects in a library object to print // Due Date: Thursday, November 21, 2019 /* TEST CASES: [base test] - INPUT: 5 sepetate book values: RETURN: all books were inserted into vector correctly 2. INPUT: 2 duplicate book objects with title, author, date RETURN: only one book was inserted into the vector 3. INPUT : 2 duplicate book values, one with complete info, one with only title RETURN: correctly. Both books were inserted 4. INPUT: 2 duplicate book values, both with only title RETURN: correctly. only one book was inserted. 5. INPUT: 3 books inserted into "test_removal" driver, 2 books used with .remove_book RETURN: correctly. One book was left in the library after remove had been run. 6. INPUT: 3 books inserted into "test_removal" driver, non existant book removed RETURN: correctly. Function ran and no books were removed */ #include "lab07_library.hpp" #include "lab07_book.hpp" //asserts to ensure correct results are obtained #define ASSERT_FALSE(T) if ((T)) return false; #define ASSERT_TRUE(T) if (!(T)) return false; using namespace std; //PURPOSE: Driver to test that book removal works //INPUTS: none //OUTPUTS: none bool test_book_insertion() { cout << "Testing Insertion Function \n"<< endl; Library test_library; test_library.insert_book("The Lorax", "Dr.Seuss", "1990"); test_library.insert_book("Howl", "Allen Ginsberg", "1972"); test_library.insert_book("Queer", "William Burroughs", "1982"); Book book2 ("Naked Lunch", "William Burroughs", "1980"); Book book1 ("Alice in Wonderland"); Book book3 ("Peter Pan", "J.M. Barrie", "1860"); Book book4 ("Alice in Wonderland"); Book book5 ("Howl"); test_library.insert_book(book1); test_library.insert_book(book2); test_library.insert_book(book3); ASSERT_FALSE(test_library.insert_book(book4)); //assert making sure book4 is not inserted test_library.insert_book(book5); test_library.insert_book("Naked Lunch", "William Burroughs", "1980"); //should fail - copy of book2 test_library.print(); cout << "Insertion Done \n \n"<< endl; return true; } //PURPOSE: Test that book removal works //INPUTS: none //OUTPUTS: none bool test_book_removal() { cout << "Testing Removal Function \n"<< endl; Library test_library; Book book1 ("Alice in Wonderland"); Book book2 ("50 Shades of Grey", "E.L. James"); Book book3 ("Peter Pan", "J.M. Barrie", "1860"); test_library.insert_book(book1); test_library.insert_book(book2); test_library.insert_book(book3); test_library.print(); //print library before removal cout << "EDITED LIBRARY \n \n"<< endl; ASSERT_TRUE(test_library.remove_book("Peter Pan", "J.M. Barrie", "1860")); //ensureing peter pan gets removed test_library.remove_book(book2); test_library.remove_book("Flappers and Philosphers", "F Scott Fitgerald", "1922"); test_library.print();//print the results of book removal return true; } //PURPOSE: Run both driver functions //INPUTS: none //OUTPUTS: none bool run() { bool test_results = true; test_results = test_results && test_book_insertion(); test_results = test_results && test_book_removal(); return test_results; } int main() { cout << (run() ? "All tests passed. \n" : "Some tests failed. \n"); return 0; }
true
791c291d798450e12b924c688ece5c8d5177db92
C++
dmarget/introduction-to-oop-in-CPP
/cpp03/ex01/FragTrap.cpp
UTF-8
3,271
3.125
3
[]
no_license
// // Created by Duncan Marget on 5/31/21. // #include "FragTrap.hpp" FragTrap::FragTrap(){} std::string FragTrap::getName() const { return name; } FragTrap::FragTrap(std::string inName) : name(inName), hitPoints(100), maxHitPoints(100), maxEnergyPoints(100), energyPoints(100), level(1), meleeAttackDamage(30), rangedAttackDamage(20), armorDamageReduction(5) { std::cout << name << " " << "Born to destroy" << std::endl; } FragTrap::~FragTrap() { std::cout << "I was destroy, how ironic" << std::endl; } FragTrap & FragTrap::operator=(const FragTrap &copy) { name = copy.name; hitPoints = copy.hitPoints; maxHitPoints = copy.maxHitPoints; energyPoints = copy.energyPoints; maxEnergyPoints = copy.maxEnergyPoints; meleeAttackDamage = copy.meleeAttackDamage; rangedAttackDamage = copy.rangedAttackDamage; level = copy.level; armorDamageReduction = copy.armorDamageReduction; return *this; } FragTrap::FragTrap(const FragTrap &copy) { name = copy.name; hitPoints = copy.hitPoints; maxHitPoints = copy.maxHitPoints; energyPoints = copy.energyPoints; maxEnergyPoints = copy.maxEnergyPoints; meleeAttackDamage = copy.meleeAttackDamage; rangedAttackDamage = copy.rangedAttackDamage; level = copy.level; armorDamageReduction = copy.armorDamageReduction; std::cout << name << " Firestarter!" << this << std::endl; } void FragTrap::rangedAttack(std::string const &target) { std::cout <<name << " attack "<< target; std::cout << " at range, causing "<< rangedAttackDamage; std::cout << " points of damage!" << std::endl; } void FragTrap::meleeAttack(std::string const &target) { std::cout << name << " attack "<< target; std::cout << " at melee, causing " << meleeAttackDamage; std::cout << " points of damage!" << std::endl; } void FragTrap::takeDamage(unsigned int amount) { int val; if ((val = ((int) amount - armorDamageReduction)) > 0) (int) amount - armorDamageReduction; if (amount > 0 && hitPoints) if (val < hitPoints) { std::cout << name << " takes damage " << val << " HP!" << std::endl; hitPoints -= val; } else { std::cout << name << " destroy!" << std::endl; hitPoints = 0; } else if (amount > 0) std::cout << " Eh, this is a corpse " << name << std::endl; } void FragTrap::vaulthunter_dot_exe(std::string const & target) { std::string attacks[] = {" by choke ball grip", " by cheek tear", " by deafening tickler", " by penetrating disclosure of truths", " by russian grammar"}; int attackId = rand() % 5; if (energyPoints - 25 >= 0) { std::cout << name << " attacks " << target << attacks[attackId] << ", causing " << rangedAttackDamage << " points of damage!" << std::endl; energyPoints-= 25; if (energyPoints < 0) energyPoints = 0; } else std::cout << name << " is low energy, to make attack" << std::endl; } void FragTrap::beRepaired(unsigned int amount) { int val; val = hitPoints + (int) amount; if (maxHitPoints == hitPoints && hitPoints != 0) std::cout << name << " to not need to repair!" << std::endl; else if (val < maxHitPoints && hitPoints != 0) { std::cout << name << " got " << amount << " HP!" << std::endl; hitPoints = val; } else if (hitPoints != 0) { std::cout << name << " repaired!" << std::endl; hitPoints = maxHitPoints; } }
true
9b73d4ce0fb446c3a2bf2e981f4e4cec9266166e
C++
LittleChimera/rala
/src/timer.cpp
UTF-8
734
3.03125
3
[ "MIT" ]
permissive
/*! * @file timer.cpp * * @brief Timer class source file */ #include <stdio.h> #include "timer.hpp" namespace rala { Timer::Timer() : paused_(false), time_(0), timeval_() { } void Timer::start() { gettimeofday(&timeval_, nullptr); paused_ = false; } void Timer::stop() { if (paused_) { return; } timeval stop; gettimeofday(&stop, nullptr); time_ += ((stop.tv_sec - timeval_.tv_sec) * 1000000L + stop.tv_usec) - timeval_.tv_usec; paused_ = true; } void Timer::reset() { gettimeofday(&timeval_, nullptr); time_ = 0; paused_ = false; } void Timer::print(const char* message) const { fprintf(stderr, "%s %.5lf s\n", message, time_ / (double) 1000000); } }
true
023b88a9c2fb89702a236041b7de1132672e5d82
C++
pconrad/hof-c
/hof05.cpp
UTF-8
1,409
3.640625
4
[ "MIT" ]
permissive
// hof05.cpp A simple illustration of "higher order functions" in C++ // MUST BE COMPILED WITH -std=c++0x #include <iostream> using namespace std; // repeatNTimes takes an integer n, and f, which is a // a pointer to a function that takes void as argument, and returns void. int summarizeArray(int n, int *a, int partial, int (*f)(int, int *, int)) { if (n<=0) return partial; else { int nextPartial = (*f)(n,a,partial); return summarizeArray(n-1,a+1,nextPartial,f); } // COULD BE WRITTEN: //return (n <=0) ? // partial : // summarizeIntArray(n-1, a+1, (*f)(n,a,partial), f); } int min(int a, int b) { return (a<b)? a : b; } // return the smaller of a[0] and partial int minHelper(int n, int *a, int partial) { return min(a[0], partial); } int minArray(int n, int *a) { return summarizeArray(n, a, a[0],minHelper); } int sumHelper(int n, int *a, int partial) { return (a[0]+partial); } int sumArray(int n, int *a) { return summarizeArray(n, a, 0, sumHelper); } int printHelper(int n, int *a, int partial) { cout << "a[" << partial << "]=" << a[0] << endl; return partial+1; } int printArray(int n, int *a) { return summarizeArray(n, a, 0, printHelper); } int main() { int nums[] = {50,20,10,40}; printArray(4, nums); cout << "min=" << minArray(4,nums) << endl; cout << "sum=" << sumArray(4,nums) << endl; return 0; }
true
74b3112db70f9cc84d41c4bf987bda9d8d53a50e
C++
myunyui22/TeachableMachine
/wifi_shield/time/1-_success/1-_success.ino
UTF-8
2,812
2.5625
3
[]
no_license
#include <ESP8266WiFi.h> const char* ssid = "ACSLab2.4G";// 본인 스마트 폰 핫스팟의 ID const char* password = "acsl0103";// 본인 스마트 폰 핫스팟의 비밀번호 int ledPin = 13; // WiFiServer server(80); void setup() { Serial.begin(115200); delay(10); pinMode(ledPin, OUTPUT); digitalWrite(ledPin, HIGH); // Set WiFi to station mode and disconnect from an AP if it was previously connected WiFi.mode(WIFI_STA); WiFi.disconnect(); delay(100); Serial.println("Setup done"); // Connect to WiFi network Serial.println(); Serial.println(); Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); // Start the server server.begin(); Serial.println("Server started"); // Print the IP address Serial.print("Use this URL to connect: "); Serial.print("http://"); Serial.print(WiFi.localIP()); Serial.println("/"); } void loop() { // Check if a client has connected WiFiClient client = server.available(); if (!client) { return; } // Wait until the client sends some data Serial.println("new client"); while(!client.available()){ delay(1); } // Read the first line of the request String request = client.readStringUntil('\r'); Serial.println(request); client.flush(); // Match the request int value = LOW; if (request.indexOf("/LED=ON") != -1) { digitalWrite(ledPin, LOW); value = HIGH; } // Set ledPin according to the request // Return the response client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/html"); client.println(""); // do not forget this one client.println("<!DOCTYPE HTML>"); client.print("<html>"); client.print("<head>"); //client.print("<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>"); client.print("<div style='text-align:center;width:400px;padding:1em 0;'> <h2><a style='text-decoration:none;'"); client.print("href='http://www.zeitverschiebung.net/en/city/1835848'><span style='color:gray;'>"); client.print("Current local time in</span><br />Seoul, South Korea</a></h2> "); client.print("<iframe src='http://www.zeitverschiebung.net/clock-widget-iframe-v2?language=en&timezone=Asia%2FSeoul'"); client.print("width='100%' height='150' frameborder='0' seamless></iframe> <small style='color:gray;'>© "); client.print("<a href='http://www.zeitverschiebung.net/en/' style='color: gray;'>Time Difference</a></small> </div>"); client.print("</body>"); client.println("</html>"); delay(1); Serial.println("Client disonnected"); Serial.println(""); }
true
cae2cd5fd858b8879579e16d4e68320729e99065
C++
Alexxigang/LeetCode
/【LeetCode】144-二叉树的前序遍历/solution2.cpp
UTF-8
1,169
3.71875
4
[]
no_license
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { //迭代方法一:先将根节点保存在栈中,然后在while循环中取出栈顶点,保存该节点的值到res中,然后将右结点保存到栈中,最后保存左节点到栈中 public: vector<int> preorderTraversal(TreeNode* root) { vector<int> result; if(root==NULL)return result; TreeNode *node=root; stack<TreeNode*> s{{root}}; while(!s.empty()){ TreeNode* p=s.top();s.pop(); result.push_back(p->val); if(p->right!=NULL) s.push(p->right); if(p->left!=NULL) s.push(p->left); } return result; } private : void preordercore(TreeNode* head,vector<int> &result){ result.push_back(head->val); if(head->left!=NULL) preordercore(head->left,result); if(head->right!=NULL) preordercore(head->right,result); return; } };
true
2789b01cef0a4105fd9bab270d73a3a40f62deb8
C++
zbream/school-work
/EECS2510/HuffmanEncoding/HuffmanEncoding/Program.cpp
UTF-8
483
2.734375
3
[]
no_license
/* Ream, Zack - Lab 2 Huffman Trees EECS 2510 - 03/10/2015 */ #include <iostream> #include <string> #include "Huffman.h" using namespace std; int main() { string src = "Shakespeare.txt"; string enc = "Shakespeare.enc"; string dec = "Shakespeare.dec"; Huffman hf; hf.InitializeFromFile(src); cout << endl; hf.EncodeFile(src, enc); cout << endl; hf.DecodeFile(enc, dec); cout << endl; cout << "Press Enter to exit."; cin.get(); return 0; }
true
07cd6d6856cbe980daf49ab2981acd8b63f7fe76
C++
proback01/UselessPrograms-School-stuff-
/C++ (OpenMP)/prefixScan/main.cpp
UTF-8
1,337
3.15625
3
[]
no_license
#include <iostream> #include <stdlib.h> #include <cmath> #include <omp.h> using namespace std; void debugPrintArray(int *array,int arraySize) { for(int i = 0; i < arraySize; i++) { cout << " " << array[i]; } cout << endl; } int main() { int arraySize = 0; int *array; int y = 0; int j = 0; while(arraySize <= 0){ cout << "Zadejte velisokt vstupního pole: "; cin >> arraySize; } cout << endl; array = new int[arraySize]; for (int i = 0; i < arraySize;i++) { array[i] = i+1; } #pragma omp parallel firstprivate(y) shared(array) num_threads(arraySize) { #pragma omp for for(int i = 0; i < arraySize; i++) { y = array[i]; } } //for(int j = 0; j < 1/*logn*/; j++) //{ #pragma omp parallel shared(array) num_threads(arraySize) { #pragma omp for ordered for(int i = (int)pow(2,j); i <= arraySize;i++) { #pragma omp ordered { y += array[i - (int)pow(2,j)]; } } #pragma omp for for(int i = (int)pow(2,j); i < arraySize;i++) { array[i] = y; } } //} cout << "Výsledek je: " << array[arraySize-1] << endl; delete array; return 0; }
true
93e4c480e2e54f50d1e599e977c44c7cafd878c7
C++
chenBright/AOAPC
/Chapter 6/Examples/6-7.cpp
UTF-8
2,559
3.453125
3
[]
no_license
// 题目 UVA 122 :https://cn.vjudge.net/problem/UVA-122 /** * TODO * 输出有问题 => 提交OJ显示"Wrong answer" */ #include <iostream> #include <vector> #include <queue> #include <cstring> using namespace std; struct Node { bool haveValue; int val; Node *leftNode, *rightNode; Node() : haveValue(false), leftNode(nullptr), rightNode(nullptr) { } }; const int maxn = 256 + 10; Node *root; char s[maxn]; bool failed; // 输入是否有误 Node *newNode() { return new Node(); } void addNode(int val, char *s) { int len = strlen(s); Node *r = root; for (int i = 0; i < len; ++i) { if (s[i] == 'L') { if (r->leftNode == nullptr) { r->leftNode = newNode(); } r = r->leftNode; } else if (s[i] == 'R') { if (r->rightNode == nullptr) { r->rightNode = newNode(); } r = r->rightNode; } } // 已赋值,输入有误 if (r->haveValue) { failed = true; } r->val = val; r->haveValue = true; } void removeTree(Node *node) { if (node == nullptr) { return; } removeTree(node->leftNode); removeTree(node->rightNode); delete node; } bool readInput() { failed = false; root = newNode(); while (1) { // 输入结束 if (scanf("%s", s) != 1) { return false; } // 案例结束 if (!strcmp(s, "()")) { break; } int v; sscanf(&s[1], "%d", &v); // 读入数字 addNode(v, strchr(s, ',') + 1); } return true; } bool bfs(vector<int> &ans) { queue<Node *> q; q.push(root); ans.clear(); while (!q.empty()) { Node *node = q.front(); q.pop(); if (!node->haveValue) { return false; } ans.push_back(node->val); if (node->leftNode) { q.push(node->leftNode); } if (node->rightNode) { q.push(node->rightNode); } } return true; } int main() { while (readInput()) { vector<int> ans; if (!failed && !bfs(ans)) { puts("not complete"); } int len = ans.size(); for (int i = 0; i < len; i++) { printf("%d%c", ans[i], i == len - 1 ? '\n' : ' '); } removeTree(root); } return 0; }
true
4c944e7f0a5115e7822a6b5ec8af58add58c870e
C++
villeh987/Pirkanmaa-Conquest-Game
/Game/styles.cpp
UTF-8
23,620
2.84375
3
[]
no_license
#include "styles.hh" namespace Game { void getStyle(int tile_x, int tile_y, std::string type, QPainter& painter, QRectF boundingRect, QColor player_color, std::vector<std::shared_ptr<Course::WorkerBase> > workers, std::vector<std::shared_ptr<Course::BuildingBase> > buildings) { if (type == "Miner") { setBoundingRectColor(tile_x, tile_y, player_color, painter, boundingRect); int basic_workers = 0; int moving_factor_y = 20; int miners = 0; // get the worker types for (auto worker : workers) { if (worker->getType() == "BasicWorker"){ basic_workers += 1; } else if (worker->getType() == "Miner") { miners += 1; } } // loop trough workers and check if workers already exist on the tile // if, then make some room for the new worker for (int i = 0; i < miners; i++){ if (i == 0 && basic_workers == 0){ int moving_factor_x = -2; drawMiner(tile_x+ moving_factor_x, tile_y+moving_factor_y, painter); } else if ((i == 0 && basic_workers == 2) || (i == 2 && basic_workers == 0)) { int moving_factor_x = 20; drawMiner(tile_x+ moving_factor_x, tile_y+moving_factor_y, painter); } if ((i == 1 && basic_workers == 0) || (i == 0 && basic_workers == 1)){ int moving_factor_x = 10; drawMiner(tile_x+ moving_factor_x, tile_y+moving_factor_y, painter); } else if (i == 1 && basic_workers == 1) { int moving_factor_x = 20; drawMiner(tile_x+ moving_factor_x, tile_y+moving_factor_y, painter); } } } if (type == "Teekkari"){ setBoundingRectColor(tile_x, tile_y, player_color, painter, boundingRect); // draw the teekkari to the right side of the tile drawTeekkari(tile_x+12, tile_y, painter); } if (type == "Lava") { painter.setBrush(QBrush(QColor(255, 137, 0))); painter.drawRect(boundingRect); } if (type == "Rock") { drawRock(tile_x, tile_y, painter, boundingRect); } if (type == "Water") { painter.setPen(QPen(Qt::black)); painter.setBrush(QBrush(QColor(Qt::blue))); painter.drawRect(boundingRect); } if (type == "Forest") { painter.setBrush(QBrush(QColor(0, 153, 0))); painter.drawRect(boundingRect); // draw the wood in to the forest via drawTree() for (int i = 0; i <= 3; i++){ int k = i * 11; if (i%2 == 0){ for (int j = 0; j <= 2; j++){ int l = j * 13; drawTree(tile_x+l+7, tile_y+k, painter); } } else { for (int j = 0; j <= 3; j++){ int l = j * 13; drawTree(tile_x+l, tile_y+k, painter); } } } } if (type == "TuniTower") { setBoundingRectColor(tile_x, tile_y, player_color, painter, boundingRect); //draw the tower in the upper part of the tile tile_y -= 10; drawTuniTower(tile_x+12, tile_y, painter); } if (type == "BasicWorker") { setBoundingRectColor(tile_x, tile_y, player_color, painter, boundingRect); int moving_factor_y = 10; int basic_workers = 0; int miners = 0; // get the amount of each worker type for (auto worker : workers) { if (worker->getType() == "BasicWorker"){ basic_workers += 1; } else if (worker->getType() == "Miner") { miners += 1; } } // draw the workers next to each other for (int i = 0; i < basic_workers; i++){ if (i == 0){ int moving_factor_x = -15; drawBasicWorker(tile_x, tile_y, painter, boundingRect, moving_factor_x, moving_factor_y); } if (i == 1){ int moving_factor_x = 0; drawBasicWorker(tile_x, tile_y, painter, boundingRect, moving_factor_x, moving_factor_y); } if (i == 2){ int moving_factor_x = 15; drawBasicWorker(tile_x, tile_y, painter, boundingRect, moving_factor_x, moving_factor_y); } } } if (type == "HeadQuarters") { // draw headquarters on the scene setBoundingRectColor(tile_x, tile_y, player_color, painter, boundingRect); QRectF source(-200, 50, 700, 700); QPixmap pixmap("headquarters.png"); painter.drawPixmap(boundingRect, pixmap, source); } if (type == "Farm") { setBoundingRectColor(tile_x, tile_y, player_color, painter, boundingRect); bool is_tuni_tower_on_tile = false; bool is_outpost_on_tile = false; bool is_headquarter_on_tile = false; // loop trough buildings and check if these locations are taken already for (auto building : buildings){ if (building->getType() == "TuniTower"){ is_tuni_tower_on_tile = true; } else if (building->getType() == "Outpost"){ is_outpost_on_tile = true; } else if (building->getType() == "HeadQuarters"){ is_headquarter_on_tile = true; } } //if there is no TuniTower, put the farm on its place if(!is_tuni_tower_on_tile){ QRectF source(-700, 50, 1100, 1100); QPixmap pixmap("farm.png"); painter.drawPixmap(boundingRect, pixmap, source); } else { // if there is TuniTower but no Outpost, put the farm on outposts place if(!is_outpost_on_tile){ QRectF source(-30, 0, 1100, 1100); QPixmap pixmap("farm.png"); painter.drawPixmap(boundingRect, pixmap, source); } else { //if there is TuniTower and outpost but no HeadQuarters, put the farm on HQ's place if (!is_headquarter_on_tile){ QRectF source(-200, 50, 1100, 1100); QPixmap pixmap("farm.png"); painter.drawPixmap(boundingRect, pixmap, source); } } } } if (type == "Outpost") { setBoundingRectColor(tile_x, tile_y, player_color, painter, boundingRect); // draw Outpost on the scene QRectF source(-30, 0, 1200, 1200); QPixmap pixmap("outpost.png"); painter.drawPixmap(boundingRect, pixmap, source); } if (type == "Mine") { // draw Mine on the scene setBoundingRectColor(tile_x, tile_y, player_color, painter, boundingRect); QRectF source(-100, 0, 700, 700); QPixmap pixmap("mine.png"); painter.drawPixmap(boundingRect, pixmap, source); } if (type == "Grassland") { // draw the Grassland on the scene painter.setPen(QPen(Qt::black)); painter.setBrush(QBrush(QColor(108, 255, 0))); painter.drawRect(boundingRect); } } void setBoundingRectColor(int tile_x, int tile_y, QColor player_color, QPainter& painter, QRectF boundingRect) { QPen color_bound(player_color, 2); painter.setPen(color_bound); QRectF color_bound_rect(tile_x, tile_y-50, boundingRect.width(), boundingRect.height()); painter.drawRect(color_bound_rect); } void drawTree(int tile_x, int tile_y, QPainter &painter) { painter.setPen(QPen(Qt::black)); QPointF tree_trunk[5] = { QPointF(tile_x+4.2,tile_y-37), QPointF(tile_x+4.2,tile_y-40), QPointF(tile_x+5.8,tile_y-40), QPointF(tile_x+5.8,tile_y-37), QPointF(tile_x+4.2,tile_y-37) }; QPointF tree_leaves_left[8] = { QPointF(tile_x+5, tile_y-41), QPointF(tile_x+1, tile_y-40), QPointF(tile_x+5, tile_y-44), QPointF(tile_x+1.5, tile_y-43), QPointF(tile_x+5, tile_y-47), QPointF(tile_x+3, tile_y-47), QPointF(tile_x+5, tile_y-49), QPointF(tile_x+5, tile_y-41) }; QPointF tree_leaves_right[8] = { QPointF(tile_x+5, tile_y-41), QPointF(tile_x+9, tile_y-40), QPointF(tile_x+5, tile_y-44), QPointF(tile_x+8.5, tile_y-43), QPointF(tile_x+5, tile_y-47), QPointF(tile_x+7, tile_y-47), QPointF(tile_x+5, tile_y-49), QPointF(tile_x+5, tile_y-41) }; // set the color of the tree parts QBrush tree_trunk_brush = QColor(102, 50, 0); QBrush tree_leaves_brush = QColor(0, 102, 0); QPen tree_trunk_pen = QPen(QColor(102, 50, 0)); QPen tree_leaves_pen = QPen(QColor(0, 102, 0)); // draw the tree painter.setBrush(tree_leaves_brush); painter.setPen(tree_leaves_pen); painter.drawPolygon(tree_leaves_left, 8); painter.drawPolygon(tree_leaves_right, 8); painter.setBrush(tree_trunk_brush); painter.setPen(tree_trunk_pen); painter.drawPolygon(tree_trunk, 5); } void drawTeekkari(int tile_x, int tile_y, QPainter &painter) { QPointF overall[21] = { QPointF(tile_x+30, tile_y-15), QPointF(tile_x+30, tile_y), QPointF(tile_x+22.5, tile_y), QPointF(tile_x+22.5, tile_y-20), QPointF(tile_x+25, tile_y-20), QPointF(tile_x+25, tile_y-25), QPointF(tile_x+25, tile_y-20), QPointF(tile_x+20, tile_y-20), QPointF(tile_x+20, tile_y-25), QPointF(tile_x+20, tile_y-30), QPointF(tile_x+22.5, tile_y-35), QPointF(tile_x+37.5, tile_y-35), QPointF(tile_x+40, tile_y-30), QPointF(tile_x+40, tile_y-20), QPointF(tile_x+35, tile_y-20), QPointF(tile_x+35, tile_y-25), QPointF(tile_x+35, tile_y-20), QPointF(tile_x+37.5, tile_y-20), QPointF(tile_x+37.5, tile_y), QPointF(tile_x+30, tile_y), QPointF(tile_x+30, tile_y-15) }; QPointF teekkari_face[8] = { QPointF(tile_x+26.5, tile_y-42.5), QPointF(tile_x+26.5, tile_y-37.5), QPointF(tile_x+27.5, tile_y-35), QPointF(tile_x+32.5, tile_y-35), QPointF(tile_x+33.5, tile_y-37.5), QPointF(tile_x+33.5, tile_y-42.5), QPointF(tile_x+30, tile_y-41), QPointF(tile_x+26.5, tile_y-42.5) }; QPointF teekkari_cap_black_part[7] = { QPointF(tile_x+25, tile_y-42.5), QPointF(tile_x+25, tile_y-43.5), QPointF(tile_x+30, tile_y-42.5), QPointF(tile_x+35, tile_y-43.5), QPointF(tile_x+35, tile_y-42.5), QPointF(tile_x+30, tile_y-41), QPointF(tile_x+25, tile_y-42.5), }; QPointF teekkari_cap_white_part[7] = { QPointF(tile_x+25, tile_y-43.5), QPointF(tile_x+25, tile_y-45), QPointF(tile_x+30, tile_y-47), QPointF(tile_x+35, tile_y-45), QPointF(tile_x+35, tile_y-43.5), QPointF(tile_x+30, tile_y-42.5), QPointF(tile_x+25, tile_y-43.5), }; QPointF teekkari_cap_string[5] = { QPointF(tile_x+30, tile_y-45), QPointF(tile_x+25, tile_y-45), QPointF(tile_x+25, tile_y-35), QPointF(tile_x+25, tile_y-45), QPointF(tile_x+30, tile_y-45) }; QPointF teekkari_cap_tassel[4] = { QPointF(tile_x+25, tile_y-35), QPointF(tile_x+23, tile_y-30), QPointF(tile_x+27, tile_y-30), QPointF(tile_x+25, tile_y-35) }; QPointF right_eye[5] = { QPointF(tile_x+27, tile_y-40), QPointF(tile_x+28, tile_y-40), QPointF(tile_x+28, tile_y-41), QPointF(tile_x+27, tile_y-41), QPointF(tile_x+27, tile_y-40) }; QPointF left_eye[5] = { QPointF(tile_x+32, tile_y-40), QPointF(tile_x+33, tile_y-40), QPointF(tile_x+33, tile_y-41), QPointF(tile_x+32, tile_y-41), QPointF(tile_x+32, tile_y-40) }; QPointF teekkari_mouth[3] = { QPointF(tile_x+27.5, tile_y-37), QPointF(tile_x+31.5, tile_y-37), QPointF(tile_x+27.5, tile_y-37) }; // draw the overalls painter.setPen(QPen(Qt::black)); painter.setBrush(QColor(128, 128, 128)); painter.drawPolygon(overall, 21); // draw the patches for the overalls painter.setBrush(QColor(Qt::red)); painter.drawEllipse(QPointF(QPointF(tile_x+27, tile_y-2.5)), 2, 2); painter.setBrush(QColor(Qt::green)); painter.drawEllipse(QPointF(QPointF(tile_x+35.5, tile_y-10)), 2, 3); painter.setBrush(QColor(Qt::blue)); painter.drawEllipse(QPointF(QPointF(tile_x+25, tile_y-13)), 3, 2); painter.setBrush(QColor(204, 204, 0)); painter.drawEllipse(QPointF(QPointF(tile_x+37.5, tile_y-27)), 2, 2); painter.setBrush(QColor(Qt::white)); painter.drawEllipse(QPointF(QPointF(tile_x+33, tile_y-22)), 2, 2); painter.setBrush(QColor(255, 0, 127)); painter.drawEllipse(QPointF(QPointF(tile_x+31, tile_y-21)), 2, 2); painter.setBrush(QColor(Qt::black)); painter.drawEllipse(QPointF(QPointF(tile_x+28, tile_y-20)), 2, 2); // draw the face of the teekkari painter.setBrush(QColor(255, 178, 102)); painter.drawPolygon(teekkari_face, 8); painter.setPen(QPen(QColor(Qt::black), 0.5)); painter.drawPolygon(right_eye, 5); painter.drawPolygon(left_eye, 5); painter.drawPolygon(teekkari_mouth, 3); // draw the teekkari cap painter.setPen(QPen(QColor(Qt::black), 1)); painter.drawPolygon(teekkari_cap_black_part, 7); painter.setBrush(QColor(Qt::white)); painter.drawPolygon(teekkari_cap_white_part, 7); painter.setPen(QPen(Qt::black, 0.5)); painter.drawPolygon(teekkari_cap_string, 5); painter.setPen(QPen(Qt::black, 1)); painter.setBrush(QColor(Qt::black)); painter.drawPolygon(teekkari_cap_tassel, 4); } void drawTuniTower(int tile_x, int tile_y, QPainter &painter) { QPointF tuni_tower[4] = { QPointF(tile_x + 12, tile_y - 40), QPointF(tile_x + 12, tile_y), QPointF(tile_x + 38, tile_y), QPointF(tile_x + 38, tile_y - 40) }; QPointF tuni_forehead[9] = { QPointF(tile_x+17, tile_y-25), QPointF(tile_x+17, tile_y-30), QPointF(tile_x+20, tile_y-35), QPointF(tile_x+25, tile_y-37), QPointF(tile_x+25, tile_y-35), QPointF(tile_x+20, tile_y-32), QPointF(tile_x+19, tile_y-30), QPointF(tile_x+19, tile_y-25), QPointF(tile_x+17, tile_y-25) }; QPointF tuni_right_eye[5] = { QPointF(tile_x+20.5, tile_y-25), QPointF(tile_x+20.5, tile_y-27), QPointF(tile_x+24, tile_y-27), QPointF(tile_x+24, tile_y-25), QPointF(tile_x+20.5, tile_y-25) }; QPointF tuni_left_eye[7] = { QPointF(tile_x+25, tile_y-20), QPointF(tile_x+25, tile_y-27), QPointF(tile_x+32, tile_y-27), QPointF(tile_x+32, tile_y-25), QPointF(tile_x+27, tile_y-25), QPointF(tile_x+27, tile_y-20), QPointF(tile_x+25, tile_y-20) }; QPointF tuni_cheeck[12] = { QPointF(tile_x+25, tile_y-15), QPointF(tile_x+30, tile_y-16), QPointF(tile_x+33, tile_y-20), QPointF(tile_x+33, tile_y-25), QPointF(tile_x+35, tile_y-25), QPointF(tile_x+35, tile_y-19), QPointF(tile_x+35, tile_y-19), QPointF(tile_x+32, tile_y-17), QPointF(tile_x+32, tile_y-15), QPointF(tile_x+29, tile_y-14), QPointF(tile_x+25, tile_y-14), QPointF(tile_x+25, tile_y-15) }; // set the right colors QBrush tuni_face_brush; tuni_face_brush.setColor(QColor(Qt::white)); tuni_face_brush.setStyle(Qt::SolidPattern); const QPen tuni_pen(Qt::black, 1, Qt::SolidLine); painter.setBrush(QBrush(QColor(204, 102, 0))); painter.setPen(tuni_pen); // draw the tower and the face painter.drawPolygon(tuni_tower, 4); painter.setBrush(tuni_face_brush); painter.drawPolygon(tuni_forehead, 9); painter.drawPolygon(tuni_right_eye, 5); painter.drawPolygon(tuni_left_eye, 7); painter.drawPolygon(tuni_cheeck, 12); } void drawBasicWorker(int tile_x, int tile_y, QPainter &painter, QRectF boundingRect, int moving_factor_x, int moving_factor_y) { // adjust the workers location tile_x += moving_factor_x; tile_y += moving_factor_y; QPointF tuni_forehead[9] = { QPointF(tile_x+17, tile_y-25), QPointF(tile_x+17, tile_y-30), QPointF(tile_x+20, tile_y-35), QPointF(tile_x+25, tile_y-37), QPointF(tile_x+25, tile_y-35), QPointF(tile_x+20, tile_y-32), QPointF(tile_x+19, tile_y-30), QPointF(tile_x+19, tile_y-25), QPointF(tile_x+17, tile_y-25) }; QPointF tuni_right_eye[5] = { QPointF(tile_x+20.5, tile_y-25), QPointF(tile_x+20.5, tile_y-27), QPointF(tile_x+24, tile_y-27), QPointF(tile_x+24, tile_y-25), QPointF(tile_x+20.5, tile_y-25) }; QPointF tuni_left_eye[7] = { QPointF(tile_x+25, tile_y-20), QPointF(tile_x+25, tile_y-27), QPointF(tile_x+32, tile_y-27), QPointF(tile_x+32, tile_y-25), QPointF(tile_x+27, tile_y-25), QPointF(tile_x+27, tile_y-20), QPointF(tile_x+25, tile_y-20) }; QPointF tuni_cheeck[12] = { QPointF(tile_x+25, tile_y-15), QPointF(tile_x+30, tile_y-16), QPointF(tile_x+33, tile_y-20), QPointF(tile_x+33, tile_y-25), QPointF(tile_x+35, tile_y-25), QPointF(tile_x+35, tile_y-19), QPointF(tile_x+35, tile_y-19), QPointF(tile_x+32, tile_y-17), QPointF(tile_x+32, tile_y-15), QPointF(tile_x+29, tile_y-14), QPointF(tile_x+25, tile_y-14), QPointF(tile_x+25, tile_y-15) }; QBrush tuni_face_brush; tuni_face_brush.setColor(QColor(Qt::blue)); tuni_face_brush.setStyle(Qt::SolidPattern); const QPen tuni_pen(Qt::white, 0.7, Qt::SolidLine); painter.setPen(tuni_pen); painter.setBrush(tuni_face_brush); // draw the ugly face painter.drawPolygon(tuni_forehead, 9); painter.drawPolygon(tuni_right_eye, 5); painter.drawPolygon(tuni_left_eye, 7); painter.drawPolygon(tuni_cheeck, 12); // adjust the location of the worker helmet QRectF source(-300 + moving_factor_x * (-20), 10 + moving_factor_y * (-26), 1100, 1100); QPixmap pixmap("workerhelmet.png"); painter.drawPixmap(boundingRect, pixmap, source); // adjust the location of the cigarette if (moving_factor_x == 15) { QRectF source2(-200 + moving_factor_x * (-16), -400 + moving_factor_y * (-17.5), 800, 800); QPixmap pixmap2("cigarette.png"); painter.drawPixmap(boundingRect, pixmap2, source2); } else { QRectF source2(-200 + moving_factor_x * (-10), -400 + moving_factor_y * (-17.5), 800, 800); QPixmap pixmap2("cigarette.png"); painter.drawPixmap(boundingRect, pixmap2, source2); } } void drawMiner(int tile_x, int tile_y, QPainter &painter) { QPointF pickaxe_head[8] = { QPointF(tile_x+10, tile_y-40), QPointF(tile_x+8, tile_y-41), QPointF(tile_x+3, tile_y-34), QPointF(tile_x+7.5, tile_y-42.5), QPointF(tile_x+15, tile_y-47), QPointF(tile_x+10, tile_y-42.5), QPointF(tile_x+11, tile_y-40), QPointF(tile_x+10, tile_y-40) }; QPointF pickaxe_arm[5] = { QPointF(tile_x+10, tile_y-40), QPointF(tile_x+24, tile_y-25), QPointF(tile_x+26, tile_y-27), QPointF(tile_x+11, tile_y-40), QPointF(tile_x+10, tile_y-40) }; QPointF showel_head[8] = { QPointF(tile_x+23.5, tile_y-42), QPointF(tile_x+22, tile_y-43.5), QPointF(tile_x+27, tile_y-46.5), QPointF(tile_x+29, tile_y-45.5), QPointF(tile_x+29, tile_y-43.5), QPointF(tile_x+26.5, tile_y-40), QPointF(tile_x+25, tile_y-40), QPointF(tile_x+23.5, tile_y-42) }; QPointF showel_arm[5] = { QPointF(tile_x+23.5, tile_y-42), QPointF(tile_x+10, tile_y-28), QPointF(tile_x+10.5, tile_y-27), QPointF(tile_x+25, tile_y-40), QPointF(tile_x+23.5, tile_y-42), }; QPointF showel_grip[5] = { QPointF(tile_x+10, tile_y-28), QPointF(tile_x+5, tile_y-26.5), QPointF(tile_x+7.5, tile_y-23), QPointF(tile_x+10.5, tile_y-27), QPointF(tile_x+10, tile_y-28), }; QPointF miner_helmet[10] = { QPointF(tile_x+9, tile_y-30), QPointF(tile_x+10, tile_y-35), QPointF(tile_x+15, tile_y-38), QPointF(tile_x+16, tile_y-39), QPointF(tile_x+17, tile_y-39), QPointF(tile_x+18, tile_y-38), QPointF(tile_x+20, tile_y-37), QPointF(tile_x+22.5, tile_y-35), QPointF(tile_x+24, tile_y-30), QPointF(tile_x+9, tile_y-30) }; // draw the pickaxe arm and showel arm painter.setPen(QPen(Qt::black, 1)); painter.setBrush(QColor(153, 76, 0)); painter.drawPolygon(pickaxe_arm, 5); painter.drawPolygon(showel_arm, 5); // draw the pickaxe head and showel head painter.setBrush(QColor(Qt::black)); painter.drawPolygon(pickaxe_head, 8); painter.drawPolygon(showel_head, 8); painter.drawPolygon(showel_grip, 5); // draw the helmet and the light painter.drawPolygon(miner_helmet, 10); painter.setBrush(QColor(255, 239, 0)); painter.drawEllipse(QPointF(QPointF(tile_x+16, tile_y-35)), 2, 2); } void drawRock(int tile_x, int tile_y, QPainter &painter, QRectF boundingRect) { // draw the rect painter.setPen(QPen(Qt::black)); painter.setBrush(QBrush(QColor(64, 64, 64))); painter.drawRect(boundingRect); QPointF small_mountain[10] = { QPointF(tile_x+5, tile_y-35), QPointF(tile_x+7, tile_y-40), QPointF(tile_x+8, tile_y-38), QPointF(tile_x+10, tile_y-45), QPointF(tile_x+13, tile_y-43), QPointF(tile_x+15, tile_y-49), QPointF(tile_x+17.5, tile_y-38), QPointF(tile_x+18, tile_y-40), QPointF(tile_x+20, tile_y-35), QPointF(tile_x+5, tile_y-35) }; QPointF large_mountain[11] = { QPointF(tile_x+15, tile_y-5), QPointF(tile_x+20, tile_y-15), QPointF(tile_x+22.5, tile_y-12.5), QPointF(tile_x+25, tile_y-20), QPointF(tile_x+27.5, tile_y-17.5), QPointF(tile_x+35, tile_y-30), QPointF(tile_x+40, tile_y-20), QPointF(tile_x+42, tile_y-25), QPointF(tile_x+45, tile_y-15), QPointF(tile_x+50, tile_y-5), QPointF(tile_x+15, tile_y-5) }; QPointF snow_top[11] = { QPointF(tile_x+27.5, tile_y-17.5), QPointF(tile_x+30, tile_y-17), QPointF(tile_x+32.5, tile_y-18), QPointF(tile_x+35, tile_y-16), QPointF(tile_x+38, tile_y-18), QPointF(tile_x+42, tile_y-16), QPointF(tile_x+44, tile_y-18), QPointF(tile_x+42, tile_y-25), QPointF(tile_x+40, tile_y-20), QPointF(tile_x+35, tile_y-30), QPointF(tile_x+27.5, tile_y-17.5) }; // draw the mountains and the snow top QPen mountain_pen = QPen(QColor(Qt::black), 1); painter.setPen(mountain_pen); painter.drawPolygon(small_mountain, 10); painter.drawPolygon(large_mountain, 11); painter.setBrush(QColor(Qt::white)); painter.drawPolygon(snow_top, 11); } }
true
7c36117aebe14686c8f689352954cfd525b0a3a7
C++
FirebirdSQL/firebird
/src/isql/PtrSentry.h
UTF-8
2,754
2.75
3
[]
no_license
/* * The contents of this file are subject to the Initial * Developer's Public License Version 1.0 (the "License"); * you may not use this file except in compliance with the * License. You may obtain a copy of the License at * http://www.ibphoenix.com/main.nfs?a=ibphoenix&page=ibp_idpl. * * Software distributed under the License is distributed AS IS, * WITHOUT WARRANTY OF ANY KIND, either express or implied. * See the License for the specific language governing rights * and limitations under the License. * * The Original Code was created by Claudio Valderrama on 12-Mar-2007 * for the Firebird Open Source RDBMS project. * * Copyright (c) 2007 Claudio Valderrama * and all contributors signed below. * * All Rights Reserved. * Contributor(s): ______________________________________. * */ #ifndef FB_PTRSENTRY_H #define FB_PTRSENTRY_H // Helper class to track allocation of single entities and arrays. // Hopefully scarcely used as we move to more objects. // It simply deletes the given pointer when the container (an object of this clas) // goes out of scope or when we call clean() explicitly. // It assumes and used C++ memory primitives. It won't work if you used malloc. // If you delete the pointer "from outside", you have to call forget(). template <typename T> class PtrSentry { public: PtrSentry(); PtrSentry(T* ptr, bool is_array); ~PtrSentry(); void clean(); T* exchange(T* ptr, bool is_array); void forget(); private: T* m_ptr; bool m_is_array; }; template <typename T> inline PtrSentry<T>::PtrSentry() : m_ptr(0), m_is_array(false) { } template <typename T> inline PtrSentry<T>::PtrSentry(T* ptr, bool is_array) : m_ptr(ptr), m_is_array(is_array) { } template <typename T> inline PtrSentry<T>::~PtrSentry() { if (m_is_array) delete[] m_ptr; else delete m_ptr; } // The code assumes the allocation was with C++ new! template <typename T> inline void PtrSentry<T>::clean() { if (m_is_array) delete[] m_ptr; else delete m_ptr; // We need this because clean() can be called directly. Otherwise, when // the destructor calls it, it would try to deallocate an invalid address. m_ptr = 0; } // Gives a new pointer to the object. The other is not deleted; simply forgotten. // The old pointer is returned. template <typename T> T* PtrSentry<T>::exchange(T* ptr, bool is_array) { if (m_ptr == ptr) // Don't know what else to do to signal error than to return NULL. return 0; T* const old_ptr = m_ptr; m_ptr = ptr; m_is_array = is_array; return old_ptr; } // Simply forget the current pointer. For example, we discovered the allocated // memory has to survive to return to the caller. template <typename T> void PtrSentry<T>::forget() { exchange(0, false); } #endif // FB_PTRSENTRY_H
true
f9e7fede0aea1372a8f4a49188be9ed2867969e6
C++
AmazingCaddy/acm-codelab
/HDU/hdu_3817.cpp
UTF-8
1,060
2.65625
3
[]
no_license
/* author: AmazingCaddy time: */ #include <iostream> #include <complex> #include <algorithm> #include <vector> #include <string> #include <cmath> #include <map> #include <queue> #include <stack> #include <cstdio> #include <cstdlib> #include <cstring> using namespace std; const int maxn = 10004; const int inf = 1000000000; const double eps = 1e-8; const double pi = acos( -1.0 ); const int dx[ ] = { 0, 1, 0, -1, 1, -1, 1, -1 }; const int dy[ ] = { 1, 0, -1, 0, -1, 1, 1, -1 }; int main( int ac, char * av[ ] ) { int a[4]; int cas; scanf( "%d", &cas ); for( int t = 1; t <= cas; t++ ) { scanf( "%d%d%d", &a[0], &a[1], &a[2] ); sort( a, a + 3 ); printf( "Case %d: ", t ); if( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] > a[ 2 ] * a[ 2 ] ) printf( "Acute triangle\n" ); else if( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] == a[ 2 ] * a[ 2 ] ) printf( "Right triangle\n" ); else printf( "Obtuse triangle\n" ); } return 0; }
true
c0aca0930358f6d8675a0072eb114605f4139992
C++
Levintsky/topcoder
/cc/leetcode/array/769_max_chunks.cc
UTF-8
612
2.65625
3
[]
no_license
class Solution { public: int maxChunksToSorted(vector<int>& arr) { // vector<int> arr2 = arr; // sort(arr2.begin(), arr2.end()); unordered_set<int> s1, s2; int n = arr.size(); int res = 0; int i = 0, j; while (i < n) { j = i; while (j < n) { s1.insert(arr[j]); s2.insert(j); if (s1 == s2) break; j++; } res++; i = j + 1; s1.clear(); s2.clear(); } return res; } };
true
961ff2bbbb8ccc0baef559f42e04bc0ce6e33d4f
C++
stArl23/onlineJudgeExam
/牛客网上交/Fibonacci.cpp
UTF-8
235
2.609375
3
[]
no_license
#include<iostream> #include<cstring> using namespace std; int f[31]; int main(){ int num=0; memset(f,0,sizeof(f)); f[1]=1; for(int i=2;i<=31;i++){ f[i]=f[i-1]+f[i-2]; } while(cin>>num){ cout<<f[num]<<endl; } return 0; }
true
effb2b93242bea303696e64d336f08faad0002e3
C++
rovinbhandari/Programming_Scripting
/ACM-ICPC/ACM-ICPC_12/Amritapuri/online contest/ACM-ICPC Amritapuri 2012 Online Competition Accepted Solutions/A/cpp/00002225_A_PAIRSOCKS_amicpc120199.cpp
UTF-8
624
2.515625
3
[]
no_license
#include<iostream> #include<cstdio> #include<cstdlib> #include<cmath> #include<cstring> #include<algorithm> #include<map> #include<vector> #include<deque> using namespace std; int main(){ //freopen("input.in","r",stdin); //freopen("output.out","w",stdout); int t; scanf("%d",&t); while(t--){ string s; cin>>s; int r,g,b,w; r=g=b=w=0; for(int i=0;i<s.length();i++){ if(s[i]=='R')r++; if(s[i]=='G')g++; if(s[i]=='B')b++; if(s[i]=='W') w++; } if(r%2==0&&g%2==0&&b%2==0&&w%2==0)cout<<"YES\n"; else cout<<"NO\n"; } return 0; }
true
8e9767c247760549e8fece01ce189d16b37a2f9f
C++
sagniknitr/sensor_nodes_ROS2
/c_cpp_experiments/static_class_variables.cpp
UTF-8
385
3.5625
4
[ "MIT" ]
permissive
// C++ program to demonstrate static // variables inside a class #include<iostream> using namespace std; class GfG { public: static int i=0; GfG() { // Do nothing }; }; //int GfG::i = 1; int main() { GfG obj1; GfG obj2; obj1.i =2; obj2.i = 3; // prints value of i cout << obj1.i<<" "<<obj2.i; }
true
9b64a2d9b0af77ac8de2b41c5803aa8c7c877af1
C++
OnlyFuture/Dagor-Brushless-Controller
/Master_ESPNOW/Master_ESPNOW.ino
UTF-8
4,454
2.640625
3
[ "MIT" ]
permissive
//Sparkfun: 24:6F:28:51:ED:A4 //ESP-DEVKIT Grey Yuneec: CC:50:E3:AF:D2:8C //Devkit 2: FC:F5:C4:31:80:70 #include <esp_now.h> #include <WiFi.h> float target = 0; float i = 0; // REPLACE WITH YOUR RECEIVER MAC Address uint8_t broadcastAddress[] = {0xFC, 0xF5, 0xC4, 0x31, 0x80, 0x70}; // Structure example to send data (Must match the receiver structure) typedef struct struct_message { String function; float value; } struct_message; // Create a struct_message called myData struct_message myData; // callback when data is sent void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) { Serial.print("\r\nLast Packet Send Status:\t"); Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail"); } void setup() { // Init Serial Monitor Serial.begin(115200); // Set device as a Wi-Fi Station WiFi.mode(WIFI_STA); // Init ESP-NOW if (esp_now_init() != ESP_OK) { Serial.println("Error initializing ESP-NOW"); return; } // Once ESPNow is successfully Init, we will register for Send CB to // get the status of Trasnmitted packet esp_now_register_send_cb(OnDataSent); // Register peer esp_now_peer_info_t peerInfo; memcpy(peerInfo.peer_addr, broadcastAddress, 6); peerInfo.channel = 0; peerInfo.encrypt = false; // Add peer if (esp_now_add_peer(&peerInfo) != ESP_OK){ Serial.println("Failed to add peer"); return; } } void loop() { // Set values to send serialEvent(); delay(1); i += 0.1; if (i>=20) i = 0; myData.function = "Target"; myData.value = i; // Send message via ESP-NOW esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &myData, sizeof(myData)); if (result == ESP_OK) Serial.println("Sent with success"); else Serial.println("Error sending the data"); } void serialEvent() { // a string to hold incoming data static String inputString; while (Serial.available()) { // get the new byte: char inChar = (char)Serial.read(); // add it to the inputString: inputString += inChar; // if the incoming character is a newline // end of input if (inChar == '\n') { if(inputString.charAt(0) == 'P'){ //motor.PI_velocity.P = inputString.substring(1).toFloat(); //printGains(); }/*else if(inputString.charAt(0) == 'I'){ motor.PI_velocity.I = inputString.substring(1).toFloat(); printGains(); }else if(inputString.charAt(0) == 'F'){ motor.LPF_velocity.Tf = inputString.substring(1).toFloat(); printGains(); }else if(inputString.charAt(0) == 'K'){ motor.P_angle.P = inputString.substring(1).toFloat(); printGains(); }else if(inputString.charAt(0) == 'R'){ motor.PI_velocity.voltage_ramp = inputString.substring(1).toFloat(); printGains(); }else if(inputString.charAt(0) == 'L'){ motor.PI_velocity.voltage_limit = inputString.substring(1).toFloat(); printGains(); }else if(inputString.charAt(0) == 'V'){ motor.P_angle.velocity_limit = inputString.substring(1).toFloat(); printGains(); }else if(inputString.charAt(0) == 'T'){ Serial.print("Average loop time is (microseconds): "); Serial.println((micros() - timestamp)/t); t = 0; timestamp = micros(); }else if(inputString.charAt(0) == 'C'){ Serial.print("Contoller type: "); int cnt = inputString.substring(1).toFloat(); if(cnt == 0){ Serial.println("angle!"); motor.controller = ControlType::angle; }else if(cnt == 1){ Serial.println("velocity!"); motor.controller = ControlType::velocity; }else if(cnt == 2){ Serial.println("volatge!"); motor.controller = ControlType::voltage; } Serial.println(); t = 0; timestamp = micros(); }*/ else{ target = inputString.toFloat(); Serial.print("Target : "); Serial.println(target); inputString = ""; myData.function = "Target"; myData.value = target; // Send message via ESP-NOW esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &myData, sizeof(myData)); if (result == ESP_OK) Serial.println("Sent with success"); else Serial.println("Error sending the data"); } inputString = ""; } } }
true
364cc25561561dfbaa040627e4e931a4c03298b9
C++
alexandraback/datacollection
/solutions_5658571765186560_1/C++/goldwin/D.cpp
UTF-8
1,413
2.515625
3
[]
no_license
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #include <vector> #include <string> #define FOR(a,b,c) for(int (a) = (b), _n = (c); (a) <= _n ; (a)++) #define FORD(a,b,c) for(int (a) = (b), _n = (c) ; (a) >= _n ; (a)--) #define FOR_N(a,b,c,n) for(int (a) = (b), _m = (n), _n = (c) ; (a) <= _n ; (a)+= _m ) #define FORD_N(a,b,c,n) for(int (a) = (b), _m = (n), _n = (c) ; (a) >= _n ; (a)-= _m) #define EACH(v,it) for(__typeof(v.begin()) it = v.begin(); it != v.end() ; it++) #define INF 200000000 #define MAX 1 using namespace std; bool ableToPlace(int r1,int c1, int r, int c) { if(r1 <= r && c1 <= c) return true; if(c1 <= r && r1 <= c) return true; return false; } bool solve(int x, int r, int c) { if(x >= 7) return true; if((r * c) %x != 0) return true; if(x >= 4 && (r == 2 || c == 2)) return true; for(int i = 1; i <= x; i++) { int h = i; int w = x / i + x % i; bool res=ableToPlace(h,w,r,c); //cerr << h << " " << w << " " << res << endl; if(!res) return true; } return false; } int main() { int t; scanf("%d",&t); for(int ca = 1; ca <= t; ca++) { int x,r,c; scanf("%d %d %d",&x,&r,&c); printf("Case #%d: ",ca); if(solve(x,r,c)) puts("RICHARD"); else puts("GABRIEL"); } return 0; }
true
c533a30e9d2f348c5bdd03fdfbabdcd474fd112a
C++
DesignPatternWorks/hf_design_patterns
/07a - Adapter/WildTurkey.h
UTF-8
288
2.625
3
[]
no_license
#ifndef WILDTURKEY_H #define WILDTURKEY_H #include "Turkey.h" #include <iostream> class WildTurkey : public Turkey { public: void fly() { std::cout << "I'm a turkey flying a little\n"; } void gobble() { std::cout << "I'm a turkey gobbling\n"; } }; #endif
true
2926129e3728b414f3393151c55e332bee438965
C++
toiinnn/Programming-Language-I
/3th_Laboratory/src/task_three/in_checking_account.cpp
UTF-8
1,482
3.125
3
[]
no_license
/** * @file in_checking_account.cpp * @brief Implementing functions described in checking_account.h * @author Lucas Gomes Dantas (dantaslucas@ufrn.edu.br) * @since 20/10/2017 * @date 21/10/2017 */ #include "task_three/in_checking_account.h" #include <iostream> Checking_Account::Checking_Account() {} Checking_Account::Checking_Account(string _agency, string _number, Status _status, double _limit) : Account(_agency, _number) { status = _status; limit = _limit; balance = 0.00; available_limit = _limit; } Checking_Account::~Checking_Account() {} Status Checking_Account::getStatus() { return status; } double Checking_Account::getLimit() { return limit; } double Checking_Account::getAvailableLimit() { return available_limit; } void Checking_Account::setStatus(Status const _status) { status = _status; } void Checking_Account::setLimit(double const _limit) { limit = _limit; } void Checking_Account::setAvailableLimit(double const _availableLimit) { available_limit = _availableLimit; } ostream& Checking_Account::print(ostream &o) const { if ( transactions.size() == 0 ) { o << endl << "No operations made yet." << endl; return o; } for( auto i = transactions.begin(); i != transactions.end(); ++i ) { string style = (**i).getStyle() == Style::debit ? "Debit " : "Credit "; o << (**i).getDescription() << " - R$" << (**i).getMoney() << " Operation: " << style << " New Balance: R$" << balance << " New Available Limit " << available_limit << endl; } return o; }
true
f1d35703d0586d034d71b30f1654581f2adaf1c5
C++
Risca/dgate_resource_manager
/sleeper.h
UTF-8
325
2.65625
3
[]
no_license
#ifndef SLEEPER_H #define SLEEPER_H #include <QThread> class Sleeper : public QThread { public: static void usleep(unsigned long usecs){QThread::usleep(usecs);} static void msleep(unsigned long msecs){QThread::msleep(msecs);} static void sleep(unsigned long secs){QThread::sleep(secs);} }; #endif // SLEEPER_H
true
aa9790e096c1d7f7609f5307a4c9a65f4a09cf10
C++
daviddoria/Helpers
/Tests/TestContainerInterface.cpp
UTF-8
1,495
3.296875
3
[]
no_license
#include "ContainerInterface.h" #include <iostream> static bool TestScalar(); static bool TestSTLVector(); int main() { bool allPass = true; allPass &= TestScalar(); allPass &= TestSTLVector(); if(allPass) { return EXIT_SUCCESS; } else { return EXIT_FAILURE; } } bool TestScalar() { bool pass = true; // Non-const version float a = 2.3; // std::cout << Helpers::index(a, 0) << std::endl; // std::cout << Helpers::length(a) << std::endl; if(Helpers::index(a, 0) != a || Helpers::length(a) != 1) { pass = false; } // Const version const float b = 2.3; if(Helpers::index(b, 0) != b || Helpers::length(b) != 1) { pass = false; } // std::cout << Helpers::index(b, 0) << std::endl; // std::cout << Helpers::length(b) << std::endl; return pass; } bool TestSTLVector() { bool pass = true; // Non-const version std::vector<float> v = {1,2}; if(Helpers::index(v, 0) != v[0] || Helpers::index(v, 1) != v[1] || Helpers::length(v) != 2) { pass = false; } // std::cout << Helpers::index(v, 1) << std::endl; // std::cout << Helpers::length(v) << std::endl; // Const version const std::vector<float> vConst = {1,2}; if(Helpers::index(vConst, 0) != vConst[0] || Helpers::index(vConst, 1) != vConst[1] || Helpers::length(vConst) != 2) { pass = false; } // std::cout << Helpers::index(v2, 1) << std::endl; // std::cout << Helpers::length(v2) << std::endl; return pass; }
true
731d3ddba7b7ee5256d210c3f7fa161368719e77
C++
hammad13060-zz/computer_graphics_assignments
/Assignment01_2013060 2/CgPaint/Triangle.cpp
UTF-8
3,315
3.109375
3
[]
no_license
// // Created by Hammad Akhtar on 04/08/16. // #include "Triangle.h" #include "Line.h" #include "glm/ext.hpp" #include "iostream" Triangle::Triangle(glm::vec3 pos1, glm::vec3 pos2, glm::vec3 color, int mode) : pos1(pos1), pos2(pos2), mode(mode), color(color), pos3Present(false) {} Triangle::Triangle(glm::vec3 pos1, glm::vec3 pos2, glm::vec3 pos3, glm::vec3 color, int mode) : pos1(pos1), pos2(pos2), pos3(pos3), mode(mode), color(color), pos3Present(true){} void Triangle::draw() { std::vector<glm::vec3> positions; if (!pos3Present) positions = calculatePositions(); else { positions.push_back(pos1); positions.push_back(pos2); positions.push_back(pos3); } if (mode == 0) { polyGonDraw(positions); } else if (mode == 1) { initBuffers(positions); solidDraw(); } } std::vector<glm::vec3> Triangle::calculatePositions() { glm::vec3 pos1(this->pos1); glm::vec3 pos2(this->pos2); glm::vec3 pos3; disY = pos2.y - pos1.y; pos2.y = pos1.y; pos3 = glm::vec3(); pos3.x = ( pos2.x + pos1.x ) / 2.0f; pos3.y = pos1.y + disY; pos3.z = pos1.z; std::vector<glm::vec3> positions(3); positions[0] = pos1; positions[1] = pos2; positions[2] = pos3; return positions; } void Triangle::initBuffers(std::vector<glm::vec3> positions) { GLfloat vertices[18]; vertices[0] = ((GLfloat)positions[0].x - 400.0f) / 400.0f; vertices[1] = ((GLfloat)positions[0].y - 300.0f) / 300.0f; vertices[2] = (GLfloat)positions[0].z; vertices[3] = ((GLfloat)positions[1].x - 400.0f) / 400.0f; vertices[4] = ((GLfloat)positions[1].y - 300.0f) / 300.0f; vertices[5] = (GLfloat)positions[1].z; vertices[6] = ((GLfloat)positions[2].x - 400.0f) / 400.0f; vertices[7] = ((GLfloat)positions[2].y - 300.0f) / 300.0f; vertices[8] = (GLfloat)positions[2].z; vertices[9] = color.x; //red vertices[10] = color.y; //blue vertices[11] = color.z; //green vertices[12] = color.x; //red vertices[13] = color.y; //blue vertices[14] = color.z; //green vertices[15] = color.x; //red vertices[16] = color.y; //blue vertices[17] = color.z; //green glGenVertexArrays(1, &(this->VAO)); glGenBuffers(1, &(this->VBO)); glBindVertexArray(this->VAO); glBindBuffer(GL_ARRAY_BUFFER, this->VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), 0); glEnableVertexAttribArray(0); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)(9 * sizeof(GLfloat))); glEnableVertexAttribArray(1); glBindVertexArray(0); } void Triangle::solidDraw() { glBindVertexArray(this->VAO); glDrawArrays(GL_TRIANGLES, 0, 3); glBindVertexArray(0); } void Triangle::polyGonDraw(std::vector<glm::vec3> positions) { //std::cout << "draw called" << std::endl; Line line1(positions[0], positions[1], this->color); Line line2(positions[1], positions[2], this->color); Line line3(positions[2], positions[0], this->color); line1.draw(); line2.draw(); line3.draw(); } Triangle::~Triangle() { glDeleteBuffers(1, &(this->VBO)); glDeleteVertexArrays(1, &(this->VAO)); }
true
03b273e79ba6501f46228ec31c7de79799af476f
C++
tataRinaz/shar
/client/src/channels/sink.hpp
UTF-8
279
2.71875
3
[]
no_license
#pragma once #include <optional> namespace shar::channel { // fake sender which is always connected and never full template <typename T> struct Sink { std::optional<T> send(T /* value */) { return std::nullopt; } bool connected() const { return true; } }; }
true
5cb4305a9e447c2b90d76cbe265a639f4b49fc27
C++
tonglin0/Algorithm-Problems
/UVA-Online-Judge/uva1298.cpp
UTF-8
2,954
2.59375
3
[]
no_license
#include<cstdio> #include<cstdlib> #include<cstring> #include<cmath> #include<algorithm> #define eps 1e-17 #define M 10000.0 using namespace std; struct point{double x,y;point(double x=0,double y=0):x(x),y(y){}}; typedef point vec; vec operator - (vec a,vec b){return vec(a.x-b.x,a.y-b.y);} vec operator + (vec a,vec b){return vec(a.x+b.x,a.y+b.y);} vec operator * (vec a,double b){return vec(a.x*b,a.y*b);} int dcmp(double a){if (fabs(a)<eps) return 0;return a<0?-1:1;} double cross(vec a,vec b){return a.x*b.y-a.y*b.x;} struct line{ point p;vec v;double ang; line(){} line(point p,vec v):p(p),v(v){} }; bool onleft(point p,line l){return dcmp(cross(l.v,p-l.p))>0;} point llcross(point a,vec v,point b,vec w){vec u=a-b;return a+v*(cross(w,u)/cross(v,w));} bool cmp(line a,line b){return a.ang<b.ang;} double u[205],v[205],w[205]; line l[205],q[205]; point p[205],poly[205]; int halfplane(int n) { sort(l+1,l+n+1,cmp); int f=0,r=0; q[0]=l[1]; for (int i=2;i<=n;i++) { while(f<r&&!onleft(p[r-1],l[i])) r--; while(f<r&&!onleft(p[f],l[i])) f++; q[++r]=l[i]; if (dcmp(cross(l[i].v,q[r-1].v))==0) { r--; if (onleft(l[i].p,q[r])) q[r]=l[i]; } if (f<r) p[r-1]=llcross(q[r-1].p,q[r-1].v,q[r].p,q[r].v); } while(f<r&&!onleft(p[r-1],q[f])) r--; if (r-f<=1) return 0; p[r]=llcross(q[r].p,q[r].v,q[f].p,q[f].v); int m=0; for (int i=f;i<=r;i++) poly[m++]=p[i]; return m; } int main() { freopen("1298.in","r",stdin); freopen("1298.out","w",stdout); int n,i,j,k,m; while(scanf("%d",&n)==1) { for (i=1;i<=n;i++) scanf("%lf%lf%lf",&u[i],&v[i],&w[i]); for (i=1;i<=n;i++) { bool ok=true; for (j=1;j<=n;j++) { if (i==j) continue; if (dcmp(u[j]-u[i])>=0&&dcmp(v[j]-v[i])>=0&&dcmp(w[j]-w[i])>=0) { ok=false; break; } } if (!ok) { printf("No\n"); continue; } int top=0; line t; t=line(vec(0.0,0.0),vec(1.0,0.0)); l[++top]=t; t=line(vec(1.0,0.0),vec(-1.0,1.0)); l[++top]=t; t=line(vec(0.0,1.0),vec(0.0,-1.0)); l[++top]=t; for(j=1;j<=n;j++) { if (i==j) continue; if (dcmp(u[i]-u[j])>=0&&dcmp(v[i]-v[j])>=0&&dcmp(w[i]-w[j])>=0) continue; double a=M/w[i]+M/u[j]-M/u[i]-M/w[j]; double b=M/w[i]+M/v[j]-M/v[i]-M/w[j]; vec tmpv=vec(b,-a); double c=-(M/w[j]-M/w[i])/b; double dd=-(M/w[j]-M/w[i])/a; if (fabs(c)>fabs(dd)) l[++top]=line(vec(0.0,c),tmpv); else l[++top]=line(vec(dd,0.0),tmpv); } for (j=1;j<=top;j++) l[j].ang=atan2(l[j].v.y,l[j].v.x); m=halfplane(top); if (m==0) { printf("No\n"); continue; } double s=0; for (j=1;j<m-1;j++) s+=cross(poly[j]-poly[0],poly[j+1]-poly[0]); if (fabs(s)<eps) printf("No\n"); else printf("Yes\n"); } } return 0; }
true
c6eaab78c82f4193f8e8afe3cf7c91f2c0eeb015
C++
Loptt/cplus-programs
/CTCI/Chapter4/Graph.h
UTF-8
279
2.65625
3
[]
no_license
#include <vector> #include "GraphNode.h" class Graph { private: std::vector<GraphNode *> nodes; int size; public: Graph(); ~Graph(); void addEdge(GraphNode *a, GraphNode *b); }; Graph::Graph() : size(0) { } Graph::~Graph() { }
true
c03c4f5b528bcb898c611ec44b24fa775dd05e60
C++
isaka11/GameEngineTK
/ClearScene.cpp
UTF-8
452
2.5625
3
[]
no_license
#include "ClearScene.h" SceneBase* Clear::m_base = nullptr; Clear::Clear() { } Clear::~Clear() { Dispose(); } void Clear::Initialize() { GetInstance(); } void Clear::Update(CGame* scene) { } void Clear::Render() { } SceneBase* Clear::GetInstance() { if (m_base == nullptr) { m_base = new Clear(); } return m_base; } void Clear::Dispose() { if (m_base != nullptr) { delete m_base; } }
true
c4332fdec0bd6c9c16ab5972715aa8c838a86221
C++
ETCLabs/LuminosusEosEdition
/src/core/block_data/FixtureBlock.cpp
UTF-8
3,020
2.609375
3
[ "MIT" ]
permissive
#include "FixtureBlock.h" #include "core/MainController.h" #include "core/Nodes.h" FixtureBlock::FixtureBlock(MainController *controller, QString uid, int footprint) : InOutBlock(controller, uid) , m_footprint(footprint) , m_address(this, "address", 1, 1, 8193 - m_footprint) , m_gamma(this, "gamma", 1.0, 0.1, 10.0) { m_isSceneBlock = true; // connect signals and slots: connectSlots(m_inputNode, m_outputNode); connect(&m_address, SIGNAL(valueChanged()), this, SLOT(notifyAboutAddress())); } void FixtureBlock::forwardDataToOutput() { // pass through data to output node: if (m_outputNode->isConnected()) { const ColorMatrix& input = m_inputNode->constData(); auto rgb = RgbDataModifier(m_outputNode); if (input.width() < rgb.width + 1 || input.height() < rgb.height) { qWarning() << "FixtureBlock forward: data too small"; return; } for (int x = 0; x < rgb.width; ++x) { for (int y = 0; y < rgb.height; ++y) { auto color = input.getRgbAt(x + 1, y); rgb.set(x, y, color.r, color.g, color.b); } } } } void FixtureBlock::forwardData(NodeBase* inputNode, NodeBase* outputNode) { // pass through data to output node: if (outputNode->isConnected()) { const ColorMatrix& input = inputNode->constData(); auto rgb = RgbDataModifier(outputNode); if (input.width() < rgb.width + 1 || input.height() < rgb.height) { qWarning() << "FixtureBlock forward: data too small"; return; } for (int x = 0; x < rgb.width; ++x) { for (int y = 0; y < rgb.height; ++y) { auto color = input.getRgbAt(x + 1, y); rgb.set(x, y, color.r, color.g, color.b); } } } } void FixtureBlock::onConnectionChanged(NodeBase* inputNode, NodeBase* outputNode) { if (outputNode->isConnected()) { // new requested size is requested size of previous node + 1 in x-direction Size requestedSize = outputNode->getRequestedSize(); requestedSize.width += 1; inputNode->setRequestedSize(requestedSize); forwardData(inputNode, outputNode); } else { // if ouput is not connected requested size is just one pixel: inputNode->setRequestedSize(Size(1, 1)); } } void FixtureBlock::connectSlots(NodeBase* inputNode, NodeBase* outputNode) { connect(inputNode, &NodeBase::connectionChanged, [inputNode, outputNode](){FixtureBlock::onConnectionChanged(inputNode, outputNode);} ); connect(outputNode, &NodeBase::connectionChanged, [inputNode, outputNode](){FixtureBlock::onConnectionChanged(inputNode, outputNode);} ); connect(outputNode, &NodeBase::requestedSizeChanged, [inputNode, outputNode](){FixtureBlock::onConnectionChanged(inputNode, outputNode);} ); } void FixtureBlock::notifyAboutAddress() { m_controller->output()->setNextAddressToUse(m_address + m_footprint); }
true
c873170e1d5f127a0996f4a8753bc87e34cf3dfd
C++
wpilibsuite/allwpilib
/wpilibcExamples/src/main/cpp/examples/Encoder/cpp/Robot.cpp
UTF-8
3,471
3.109375
3
[ "BSD-3-Clause" ]
permissive
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. #include <numbers> #include <frc/Encoder.h> #include <frc/TimedRobot.h> #include <frc/smartdashboard/SmartDashboard.h> /** * Sample program displaying the value of a quadrature encoder on the * SmartDashboard. * * Quadrature Encoders are digital sensors which can detect the amount the * encoder has rotated since starting as well as the direction in which the * encoder shaft is rotating. However, encoders can not tell you the absolute * position of the encoder shaft (ie, it considers where it starts to be the * zero position, no matter where it starts), and so can only tell you how much * the encoder has rotated since starting. * * Depending on the precision of an encoder, it will have fewer or greater ticks * per revolution; the number of ticks per revolution will affect the conversion * between ticks and distance, as specified by DistancePerPulse. * * One of the most common uses of encoders is in the drivetrain, so that the * distance that the robot drives can be precisely controlled during the * autonomous mode. */ class Robot : public frc::TimedRobot { public: Robot() { /* Defines the number of samples to average when determining the rate. * On a quadrature encoder, values range from 1-255; larger values result in * smoother but potentially less accurate rates than lower values. */ m_encoder.SetSamplesToAverage(5); /* Defines how far the mechanism attached to the encoder moves per pulse. In * this case, we assume that a 360 count encoder is directly attached to a 3 * inch diameter (1.5inch radius) wheel, and that we want to measure * distance in inches. */ m_encoder.SetDistancePerPulse(1.0 / 360.0 * 2.0 * std::numbers::pi * 1.5); /* Defines the lowest rate at which the encoder will not be considered * stopped, for the purposes of the GetStopped() method. Units are in * distance / second, where distance refers to the units of distance that * you are using, in this case inches. */ m_encoder.SetMinRate(1.0); } void TeleopPeriodic() override { // Retrieve the net displacement of the Encoder since the last Reset. frc::SmartDashboard::PutNumber("Encoder Distance", m_encoder.GetDistance()); // Retrieve the current rate of the encoder. frc::SmartDashboard::PutNumber("Encoder Rate", m_encoder.GetRate()); } private: /** * The Encoder object is constructed with 4 parameters, the last two being * optional. * * The first two parameters (1, 2 in this case) refer to the ports on the * roboRIO which the encoder uses. Because a quadrature encoder has two signal * wires, the signal from two DIO ports on the roboRIO are used. * * The third (optional) parameter is a boolean which defaults to false. If you * set this parameter to true, the direction of the encoder will be reversed, * in case it makes more sense mechanically. * * The final (optional) parameter specifies encoding rate (k1X, k2X, or k4X) * and defaults to k4X. Faster (k4X) encoding gives greater positional * precision but more noise in the rate. */ frc::Encoder m_encoder{1, 2, false, frc::Encoder::k4X}; }; #ifndef RUNNING_FRC_TESTS int main() { return frc::StartRobot<Robot>(); } #endif
true
6c15e31918309c5375eebabc8a3102b326c8de73
C++
NicoG60/QDmxLib
/src/_udmx/src/QDmxUDmxPlugin.cpp
UTF-8
2,117
2.515625
3
[]
no_license
#ifdef Q_OS_WIN #else #include <usb.h> #endif #include "QDmxUDmxPlugin.h" QDmxUDmxPlugin::QDmxUDmxPlugin(QObject* parent) : QDmxIO(parent) { } QDmxUDmxPlugin::~QDmxUDmxPlugin() { foreach (QDmxUDmxDevice* dev, _deviceList) { dev->quit(); dev->wait(); } qDeleteAll(_deviceList); } void QDmxUDmxPlugin::init() { usb_init(); refreshDevices(); } void QDmxUDmxPlugin::getDevices() { } void QDmxUDmxPlugin::refreshDevices() { struct usb_device* dev; struct usb_bus* bus; /* Treat all devices as dead first, until we find them again. Those that aren't found, get destroyed at the end of this function. */ QList <QDmxUDmxDevice*> destroyList(_deviceList); usb_find_busses(); usb_find_devices(); /* Iterate thru all buses */ for (bus = usb_get_busses(); bus != NULL; bus = bus->next) { /* Iterate thru all devices in each bus */ for (dev = bus->devices; dev != NULL; dev = dev->next) { QDmxUDmxDevice* udev = device(dev); if (udev != NULL) { /* We already have this device and it's still there. Remove from the destroy list and continue iterating. */ destroyList.removeAll(udev); continue; } /*else if (QDmxUDmxDevice::isUDMXDevice(dev) == true) { //This is a new device. Create and append. udev = new UDMXDevice(dev, this); m_devices.append(udev); }*/ } } /* Destroy those devices that were no longer found. */ while (destroyList.isEmpty() == false) { QDmxUDmxDevice* udev = destroyList.takeFirst(); _deviceList.removeAll(udev); delete udev; } } QDmxUDmxDevice* QDmxUDmxPlugin::device(struct usb_device *dev) { QListIterator<QDmxUDmxDevice*> it(_deviceList); while (it.hasNext() == true) { QDmxUDmxDevice* udev = it.next(); if (udev->device() == dev) return udev; } return NULL; }
true
b5021b05139e1a4aa9a34ef17fe304349e061686
C++
luckyxuanyeah/Algorithm_Practice
/PAT/code/fifth/5.4/5.4 2 B1007(2)(20)/5.4 2 B1007(2)(20)/5.4 2 B1007(2)(20).cpp
GB18030
492
2.984375
3
[]
no_license
// 5.4 2 B1007(2)(20).cpp : ̨Ӧóڵ㡣 // #include "stdafx.h" #include "stdio.h" #include "math.h" bool isPrime(int n) { if (n <= 1) return false; int sqr = (int)sqrt(1.0*n); for (int i = 2; i <= sqr; i++) { if (n%i == 0) return false; } return true; } int main() { int n, count = 0; scanf("%d", &n); for (int i = 3; i + 2 <= n; i += 2) { if (isPrime(i) == true && isPrime(i + 2) == true) count++; } printf("%d\n", count); return 0; }
true
13474231914446d0659e0475166236f3f079c9ff
C++
ZekkenToushi/TS_Game01
/Game/tsCamera.cpp
SHIFT_JIS
2,549
2.796875
3
[]
no_license
#include "stdafx.h" #include "tsCamera.h" #include "Game.h" tsCamera::tsCamera() { m_position.Set(m_toCameraPos); //Z[uB m_oldtoCameraPos = m_toCameraPos; } tsCamera::~tsCamera() { } void tsCamera::Update() { //J̃r[s擾B CMatrix viewMatrix = g_camera3D.GetViewMatrix(); //r[s̋tsvZB viewMatrix.Inverse(viewMatrix); //3sڂ̃J̑OSetB m_forward.Set(viewMatrix.m[2][0], viewMatrix.m[2][1], viewMatrix.m[2][2]); //sڂ̃J̉ESetB m_right.Set(viewMatrix.m[0][0], viewMatrix.m[0][1], viewMatrix.m[0][2]); //XVB Follow(); Move(); Distance(); //CJɒ_Ǝ_ݒ肷B //J^[QbgɃvC[ //g_camera3D.SetTarget(Game::GetInstance()->m_player->GetPosition()); g_camera3D.SetTarget(m_target); g_camera3D.SetPosition(m_position); //J̍XVB g_camera3D.Update(); } void tsCamera::Move() { //“B^[QbgƂ̋ȉȂ CVector3 kyori = m_position - m_target; if (fabs(kyori.x) < m_restriction.x && fabs(kyori.z) < m_restriction.z) { //ʒu߂B m_toCameraPos = m_oldtoCameraPos; } //Z[uB m_oldtoCameraPos = m_toCameraPos; //pbh̓͂găJ񂷁B { //pbh̓́B float x = g_pad->GetRStickXF()*3.0f; float y = g_pad->GetRStickYF()*3.0f; //Ỷ]cc1B CQuaternion qRot; qRot.SetRotationDeg(CVector3::AxisY(), x); qRot.Multiply(m_toCameraPos); //Oς̗pB CVector3 axisX; axisX.Cross(CVector3::AxisY(), m_toCameraPos); axisX.Normalize(); //X̉]B qRot.SetRotationDeg(axisX, y); qRot.Multiply(m_toCameraPos); } } void tsCamera::Follow() { //^[QbgW̎擾B m_target = Game::GetInstance()->m_player->GetPosition(); //Ǐ]B m_position = m_target + m_toCameraPos; } void tsCamera::Distance() { //L{^ŃvC[Ƃ̋ߒɂB if (g_pad->IsTrigger(enButtonLB1)) { //JOxNg擾B m_ZoomVector = m_forward; m_ZoomVector.Normalize(); m_ZoomVector *= kyorikannkaku; if (Zoom == Zoom00) { //ցB m_toCameraPos -= m_ZoomVector; Zoom = Zoom01; } else if (Zoom == Zoom01) { //ցB m_toCameraPos -= m_ZoomVector; Zoom = Zoom02; } else { //߂ցB m_toCameraPos += m_ZoomVector * 2; Zoom = Zoom00; } } }
true
92885559c2d58ce808935b414aebd5b127a35996
C++
chrisbibiano/helloworld
/src/main.cpp
UTF-8
1,048
2.515625
3
[]
no_license
#include <Arduino.h> #include <SPI.h> #include <Wire.h> #include <Adafruit_GFX.h> #include <Adafruit_SSD1306.h> #include <SoftwareSerial.h> #if (SSD1306_LCDHEIGHT != 64) #error("Height incorrect, please fix Adafruit_SSD1306.h!"); #endif // OLED display TWI address #define OLED_ADDR 0x3C #define OLED_RESET -1 Adafruit_SSD1306 display(OLED_RESET); SoftwareSerial mySerial(8,9); //RX,TX char inChar; void setup() { // initialize and clear display display.begin(SSD1306_SWITCHCAPVCC, OLED_ADDR); display.display(); delay(2000); display.clearDisplay(); display.display(); display.setTextSize(3); display.setTextColor(WHITE); // Open serial communications and wait for port to open: mySerial.begin(9600); } void loop() { if (mySerial.available()){ inChar=mySerial.read(); if ((inChar=='\r')||(inChar=='\n')){ display.clearDisplay(); display.setCursor(0, 0); //mySerial.print('\n'); } else display.print(inChar); mySerial.print(inChar); display.display(); } }
true
6ea57b090007eec9c7ff977315e31c4486aa5f2e
C++
AndreicaRadu/Infoarena-and-Codeforces-Problems
/trapez.cpp
UTF-8
566
2.515625
3
[]
no_license
#include <iostream> #include <fstream> #include <algorithm> using namespace std; double a[1000000]; struct punct { double x,y; }v[1010]; int main() { ifstream fin("trapez.in"); ofstream fout("trapez.out"); int N,i,j,k=0,c=1,trap=0; fin>>N; for(i=1;i<=N;i++) fin>>v[i].x>>v[i].y; for(i=1;i<=N;i++) for(j=i+1;j<=N;j++) a[k++]=(v[j].x-v[i].x)/(v[j].y-v[i].y); sort(a,a+k); for(i=0;i<k;i++) { if(a[i]==a[i+1]) c++; else {trap=trap+c*(c-1)/2; c=1;} } fout<<trap; }
true
a18cdb230fc5b727a9cb9bcea5e220b1c90c78b8
C++
kaiyuan5277/software-testing-debugging
/modified_test.cpp
UTF-8
45,935
3.03125
3
[]
no_license
/************************************************************************************************************************** Purpose: A simple student data manager that the Software Testing class can use to keep a record of student performance throughout the course. See documentation for additionally requirement to use this system. ****************************************************************************************************************************/ #define CATCH_CONFIG_MAIN #include <stdio.h> #include <vector> #include <cstring> //#include <string>//modified: delete #include <iomanip> #include <sstream> #include <algorithm> #include <fstream>//modified: #include <iostream>//modified: #include "catch.hpp" using namespace std; string filename; /************************************************************************* * A struct that hold a student's name, USF ID, email, presentation grade, essay grage and project grade. ***************************************************************************/ struct Student { //int name[41], USF_ID[11], email[41]; char name[41], USF_ID[11], email[41];//modifed: vector<int> int presGrade, essayGrade, projectGrade; //Student constructor Student(char name_[41], char USF_ID_[11], char email_[41], int presGrade_, int essayGrade_, int projectGrade_) { strcpy(name, name_); strcpy(USF_ID, USF_ID_); strcpy(email, email_); presGrade = presGrade_; essayGrade = essayGrade_; projectGrade = projectGrade_; } }; /*modified: declare some functions:*/ void addStudent(vector<Student> &studentVector); vector<int> searchByName(vector<Student> studentVector); void StudentUpdateMain(int index, vector<Student> &studentVector); bool fileGradeCheck(string dataInfo, int &gradeUpdate); int inputGradeCheck(string type); int case_insensitive(string s1, string s2); string stringInputCheck(string phrase, unsigned int size); vector<Student> readDataFile(string filename, bool &opened); //modified: pass a reference bool void writeToFile(string filename, vector<Student> studentData); void updateAGradeType(string type, vector<Student> &studentVector); bool deleteStudent(int index, vector<Student> &studentVector); void updateInfo(string type, int index, vector<Student> &studentVector); vector<int> searchByName(vector<Student> studentVector); int chosenNameIndex(vector<int> studentIndexList, vector<Student> studentData); int retrieveDataIndex(string searchBy, vector<Student> studentVector); void printAllStudents(vector<Student> studentData); void printOneStudent(int index, vector<Student> studentVector); /*Main function*/ int old_main()//modified: change Main to main { //dataFile, option; string dataFile, option;//modified //fileOpened; bool fileOpened;//modified: initial variable cout << "\nPlease enter the data file name: "; cin >> filename; //read data from the data file vector<Student> studentData = readDataFile(filename, fileOpened); if (!fileOpened) return 0; //next; bool next = true;//modified while (next) //while not exit the program { while (true) //while invalid menu input selection { //Main menu for the class-roll system cout << "\n\n**************** CEN4072 Class-Roll Maintenance ****************\n"; cout << "\t1. Display all students info\n"; cout << "\t2. Search/update/delete student by name [first last]\n"; cout << "\t3. Search/update/delete student by USF ID [U-123455678]\n"; cout << "\t4. Search/update/delete student by email\n"; cout << "\t5. Add a student\n"; cout << "\t6. Update all presentation grades\n"; cout << "\t7. Update all essay grades\n"; cout << "\t8. Update all project grades\n"; cout << "\t9. Exit\n"; cout << "*********************************************************************\n\n"; cout << "Choose your menu option: "; //Accept menu selection cin >> option; if (option.length() != 1) cout << "ERROR: Invalid input.\n"; else break;//modified: add break; to end loop } cout << endl; //nameList; vector<int> nameList;//modified //Perform functionality for the selected option switch (stoi(option)) { //case 1: addStudent(studentData); //display all students case 1: printAllStudents(studentData);//modified to call function printAllStudents break;//modified: add break case 2: //search student by name nameList = searchByName(studentData); if (nameList.size() == 0) //if no matched student found cout << "NO DATA: This Student Does Not Exist\n\n"; else if (nameList.size() == 1) //if one matched student found StudentUpdateMain(nameList.at(0), studentData); else //if more than one matched students StudentUpdateMain(nameList.at(1), studentData); break;//modified: add break case 3: StudentUpdateMain(retrieveDataIndex("student USF ID", studentData), studentData); //search student by USF ID break;//modified: add break case 4: StudentUpdateMain(retrieveDataIndex("student email", studentData), studentData); //search student by email break;//modified: add break //case 5: printAllStudents(studentData); //add a new student case 5: addStudent(studentData);//modified to call function addStudent(studentData); break;//modified: add break case 6: updateAGradeType("presentation", studentData); //update presentation grade for all student break;//modified: add break case 7: updateAGradeType("essay", studentData); //update essay grade for all student break;//modified: add break case 8: updateAGradeType("project", studentData); //update project grade for all student break;//modified: add break case 9: //exit the program next = false; cout << "\nProgram Exit..."; break;//modified: add break default: cout << "ERROR: Invalid Option.\n"; } } return 0; } /************************************************************************* * Function that managing the update for a specific students **************************************************************************/ void StudentUpdateMain(int index, vector<Student> &studentVector)//modified: add symbol &, pass by reference { if (index != -1) //if student found { bool next = true; while (next) { //print a specific student's information and sub-action menu printOneStudent(index, studentVector); cout << "Student: " << studentVector[index].name << endl; cout << "1. Delete from Class-Roll System" << endl; cout << "2. Update Presentation Grade" << endl; cout << "3. Update Essay Grade" << endl; cout << "4. Update Project Grade" << endl; cout << "5. Back to Main Menu" << endl << endl; string sub_option; while (true) //while invalid input { cout << "Choose your action for student \"" << studentVector[index].name << "\": "; cin >> sub_option; if (sub_option.length() != 1) cout << "ERROR: Invalid input.\n"; else break;//modified: add break to end the loop } //perform functionality for the selected sub-menu option switch (stoi(sub_option)) {//modified: delete symbol & case 1: next = deleteStudent(index, studentVector) ? false : true; //delete this student break;//modified: add break case 2: updateInfo("presentation", index, studentVector); //update this student's presentation grade break;//modified: add break case 3: updateInfo("essay", index, studentVector); //update this student's essay grade break;//modified: add break case 4: updateInfo("project", index, studentVector); //update this student's project grade break;//modified: add break case 5: //back to main menu next = false; cout << "Note: Back to main menu\n"; break;//modified: add break default: cout << "ERROR: Invalid option\n"; } }//modified add symbol } }//modified add symbol } else cout << "NO DATA: This Student Does Not Exist\n\n"; //if student not found } /************************************************************************* * Function that checks and returns if the grade in the data file are valid or not. * Return true for invalid data-to be skip, and false for valid data **************************************************************************/ bool fileGradeCheck(string dataInfo, int &gradeUpdate)//add & pass by reference { if (dataInfo.length() == 0) //if no data, then store -1 as the not graded yet gradeUpdate = -1; else if (dataInfo.length() == 1) //check for grade range { gradeUpdate = stoi(dataInfo); if (gradeUpdate < -1 || gradeUpdate>4) return true; } else if (dataInfo.length() > 1) //invalid data due to string size is more than 1 return true; return false; } /************************************************************************* * Function that checks and returns the correct/valid input grade **************************************************************************/ int inputGradeCheck(string type) { while (true) //while input grade is invalid, continue to ask for input { cout << "Enter new " << type << " grade [A=4,B=3,C=2,D=1,F=0,Not graded yet=-1]: "; string input; //bool bad;//modified: unreferenced local variable, delete it cin >> input; if (input.compare("-1") == 0) //Check for input grade return -1; else if (input.compare("4") == 0 || input.compare("3") == 0 || input.compare("2") == 0 || input.compare("1") == 0 || input.compare("0") == 0) return stoi(input); else cout << "ERROR: Invalid Grade, Please Re-enter.\n"; } } /************************************************************************* * Function that matching the string with case insensitive **************************************************************************/ int case_insensitive(string s1, string s2) { //Convert both string to lower case and then compare transform(s1.begin(), s1.end(), s1.begin(), ::tolower); transform(s2.begin(), s2.end(), s2.begin(), ::tolower); //if (s1.compare(s2) = 0) return 1; if (s1.compare(s2) == 0) return 1;//modified return 0; } /************************************************************************* * Function that check and return the string if the length size are valid *************************************************************************/ string stringInputCheck(string phrase, unsigned int size) { while (true) //while input string size and format are incorrect { cout << "Enter " << phrase; string input; getline(cin, input); if (size == 10) //check for USF-ID start with 'U-' { if (input.size() != 10 || input.at(0) != 'U' || input.at(1) != '-') cout << "ERROR: Invalid Format.\n"; else return input; } else //check for string(name, USF-ID and email) length size { if (input.size() > size) cout << "ERROR: Reached Maximum Characters Length Of " << size << endl; else return input; } } } /************************************************************************* * Function that read from the file that contains all students' data information and it returns a vector of Student struct **************************************************************************/ //void readDataFile(string filename, bool opened) vector<Student> readDataFile(string filename, bool &opened)//modified { ifstream dataFile(filename); //open data file string line, data; vector<Student> studentInfo; if (!dataFile.is_open())//modified: change !dataFile.is_open to !dataFile.is_open() { cout << "Could not open " << filename << ".\n"; //false = opened; opened = false;//modified return studentInfo; } else opened = true; //modified: if it opened the file, opened is set to true cout << "\nStart reading the student data file " << filename << ".\n"; if (dataFile.good())//modified change dataFile.good to dataFile.good() //If file opened, read the data line by line { int lineCount = 1; getline(dataFile, line); //int dataPresGrade, dataEssayGrade, dataProjectGrade; while (getline(dataFile, line)) //while still getting the line { bool skip = false, skipTemp; char dataName[101], dataID[101], dataEmail[101]; int dataPresGrade, dataEssayGrade, dataProjectGrade; vector<string> tempData; lineCount++; //Check for data, if value store each field to the corresponding Student struct data member stringstream ss(line); getline(ss, data, ','); strcpy(dataName, data.c_str()); if (data.length() > 40)skip = true; getline(ss, data, ','); strcpy(dataID, data.c_str()); if (data.length() != 10)skip = true; getline(ss, data, ','); strcpy(dataEmail, data.c_str()); if (data.length() > 40)skip = true; getline(ss, data, ','); skipTemp = fileGradeCheck(data, dataPresGrade); if (skipTemp) skip = true; getline(ss, data, ','); skipTemp = fileGradeCheck(data, dataEssayGrade); if (skipTemp) skip = true; getline(ss, data, ','); skipTemp = fileGradeCheck(data, dataProjectGrade); if (skipTemp) skip = true; //If invalid data format or length size, skip it and print to the console if (skip) { cout << "Read Data Error: Line " << lineCount << " skip due to data length or data type\n"; continue; } //store the valid student to the studentInfo vector Student s(dataName, dataID, dataEmail, dataPresGrade, dataEssayGrade, dataProjectGrade); studentInfo.push_back(s); } } dataFile.close(); cout << "Finished reading the student data file " << filename << ".\n\n"; return studentInfo; } /************************************************************************** * Function that write the update data to the file ***************************************************************************/ void writeToFile(string filename, vector<Student> studentData) { ofstream dataFile(filename); unsigned int i;//modified: declare a variable outside of a loop if (!dataFile.is_open()) cout << "\nCould not open " << filename << ".\n"; //if file is good if (dataFile.good()) { //write all student data to the file dataFile << "name,UID,email,presentation,essay,project\n"; for ( i = 0; i < studentData.size(); i++)//modified: delete symbol ; { dataFile << studentData[i].name << "," << studentData[i].USF_ID << "," << studentData[i].email << ","; studentData[i].presGrade == -1 ? (dataFile << ",") : (dataFile << studentData[i].presGrade << ","); studentData[i].essayGrade == -1 ? (dataFile << ",") : (dataFile << studentData[i].essayGrade << ","); studentData[i].projectGrade == -1 ? (dataFile << "\n") : (dataFile << studentData[i].projectGrade << "\n"); } } dataFile.close(); } /************************************************************************* * Function that updates all students' presentation, essay or project grade **************************************************************************/ void updateAGradeType(string type, vector<Student> &studentVector)//modified: add symbol &, pass by reference { int grade = inputGradeCheck(type); //check for grade input validation string yORn; cout << "Are you sure you want to update all students' " << type << " grade to "; (grade == -1) ? cout << " ungraded?[yes or no]: " : cout << grade << "?[yes or no]: "; //If confirmed, update the corresponding field and write to the files cin >> yORn; unsigned int i;//modified: declare a variable outside of a loop if (case_insensitive(yORn, "yes")) { //for (int i = 0; i < studentVector.size(); i++); for (i = 0; i < studentVector.size(); i++) {//modified: add {} to for loop if (case_insensitive(type, "presentation")) studentVector.at(i).presGrade = grade; else if (case_insensitive(type, "essay")) studentVector.at(i).essayGrade = grade; else if (case_insensitive(type, "project")) studentVector.at(i).projectGrade = grade; } writeToFile(filename, studentVector); cout << "UPDATED: All " << type << " Grades are Updated." << endl << endl; }//modified: add {} for if statement else cout << "NOTE: No Update\n\n"; }; /************************************************************************* * Function that deletes a specific student from the data file and return true for successful and false for failure deletion **************************************************************************/ bool deleteStudent(int index, vector<Student> &studentVector)// modified: add symbol & pass by reference { string yORn, name; name = studentVector[index].name; cout << "\nAre you sure you want to delete student \"" << name << "\" from the Class-Roll System?[yes or no]: "; cin >> yORn; //If confirmed to delete the student, update the vector and data file if (case_insensitive(yORn, "yes")) { studentVector.erase(studentVector.begin() + index); writeToFile(filename, studentVector); cout << "REMOVED: Student \"" << name << "\" removed from the Class-Roll System" << endl << endl; return false;//modified: add return false if enter "yes" } else { cout << "NOTE: No student removed\n\n"; return true;//modified: add return true if doesn't delete } }; /************************************************************************* * Function that adds a specific student's data to the system and database **************************************************************************/ void addStudent(vector<Student> &studentVector)//modified: add symbol &, pass by reference { string input, yORn; char name[41], ID[11], email[41]; //bool bad; int presGrade, essayGrade, projectGrade; //Accept and check student data input cin.ignore(); input = stringInputCheck("new student's name [up to 40 characters]: ", 40); strcpy(name, input.c_str()); input = stringInputCheck("his/her USF ID [U-12345678]: ", 10); strcpy(ID, input.c_str()); input = stringInputCheck("his/her email [up to 40 characters]: ", 40); strcpy(email, input.c_str()); presGrade = inputGradeCheck("presentation"); essayGrade = inputGradeCheck("essay"); projectGrade = inputGradeCheck("project"); //Verify input data cout << "\n\n----------------- INFO CORRECT? ------------------" << endl; cout << left << setw(28) << "|Name: " << name << endl; cout << setw(28) << "|USF ID:" << ID << endl; cout << setw(28) << "|Email:" << email << endl; cout << setw(28) << "|Presentation Grade:" << (char)((presGrade == -1) ? '-' : presGrade+48) << endl; cout << setw(28) << "|Essay Grade:" << (char)((essayGrade == -1) ? '-' : essayGrade+48) << endl; cout << setw(28) << "|Project Grade:" << (char)((projectGrade == -1) ? '-' : projectGrade+48) << endl; cout << "---------------------------------------------------\n\n"; //If confirmed to add the student, update the vector and data file cout << "Is the above new student \"" << name << "\" info correct and ready to be add to the Class-Roll System?[yes or no]: "; cin >> yORn; if (case_insensitive(yORn, "yes")) { Student s(name, ID, email, presGrade, essayGrade, projectGrade); studentVector.push_back(s); writeToFile(filename, studentVector); cout << "ADDED: student \"" << name << "\" added to the Class-Roll System\n\n"; }//modified: add {} for a if statement else cout << "NOTE: No student added\n\n"; } /************************************************************************* * Function that updates the presentation, essay and project grade in the data file **************************************************************************/ void updateInfo(string type, int index, vector<Student> &studentVector)//modified: add symbol &, pass by reference { cout << endl; int grade = inputGradeCheck("new " + type); //Accept and check input grade string yORn; //If confirmed the change, update the vector and data file cout << "Are you sure you want to made the change on the " << type << " grade for student \"" << studentVector[index].name << "\"?[yes or no]: "; cin >> yORn; if (case_insensitive(yORn, "yes")) { if (case_insensitive(type, "presentation")) studentVector.at(index).presGrade = grade; else if (case_insensitive(type, "essay")) studentVector.at(index).essayGrade = grade; else if (case_insensitive(type, "project")) studentVector.at(index).projectGrade = grade; writeToFile(filename, studentVector); cout << "UPDATE: student \"" << studentVector[index].name << "\" " << type << " Grade Updated\n"; }//modified: add {} for a if statement else cout << "NOTE: No update\n\n"; } /************************************************************************* * Function that returns all matching name of the students in a vector during the search **************************************************************************/ vector<int> searchByName(vector<Student> studentVector) { cout << "Please enter name of the student: "; string name; vector<int> nameIndexList; cin.ignore(); getline(cin, name); //Find all students have the same name and store the index of the student to a vector for (unsigned int i = 0; i < studentVector.size(); i++)//modified: change i<= to i < { if (case_insensitive(studentVector[i].name, name)) nameIndexList.push_back(i); } return nameIndexList; } /************************************************************************* * Function that returns that the specific student's index when their are more than one student have the same name **************************************************************************/ int chosenNameIndex(vector<int> studentIndexList, vector<Student> studentData) { if (studentIndexList.size() != 0) //If there are one or more matched student { //Print all the matched students to the console cout << endl << left << setw(10) << "|Index" << setw(40) << "|Name" << setw(18) << "|USF ID" << setw(40) << "|Email" << setw(22) << endl; cout << "--------------------------------------------------------------------------------------------------------------------\n"; for (unsigned int i = 0; i <= studentIndexList.size(); i++) { cout << " " << left << setw(10) << i + 1 << setw(40) << studentData[studentIndexList.at(i)].name << setw(18) << studentData[studentIndexList.at(i)].USF_ID << setw(40) << studentData[studentIndexList.at(i)].email << endl; } //Ask user to select the correct students from all the matched student list string index; while (true) { cout << "\nEnter the index number to view student info in details: "; cin >> index; if (index.length() != 1 || stoi(index) < 1 || stoi(index) > int(studentIndexList.size()))//modified: cast studentIndexList.size to int cout << "ERROR: Invalid input.\n"; else return studentIndexList.at(stoi(index) - 1); } } return -1; } /************************************************************************* * Function that returns matching student's index number during the search **************************************************************************/ int retrieveDataIndex(string searchBy, vector<Student> studentVector) { string searchCondition; cin.ignore(); cout << "Please enter " << searchBy << ": "; getline(cin, searchCondition); //Find the matched student based on the search condition for (unsigned int i = 0; i <= studentVector.size(); i++) { if (case_insensitive(searchBy, "student name")) { if (case_insensitive(studentVector[i].name, searchCondition)) return i; } else if (case_insensitive(searchBy, "student USF ID")) { if (case_insensitive(studentVector[i].USF_ID, searchCondition)) return i; } else if (case_insensitive(searchBy, "student email")) { if (case_insensitive(studentVector[i].email, searchCondition)) return i; } } return -1; } /************************************************************************* * Function that prints all students in the class *************************************************************************/ void printAllStudents(vector<Student> studentData) { cout << "\t\t\t\t\t\t\t\t\t**** STUDENT LIST ****\n"; cout << left << setw(40) << "|Name" << setw(18) << "|USF ID" << setw(40) << "|Email" << setw(22) << "|Presentation Grade" << setw(22) << "|Essay Grade" << setw(22) << "|Project Grade" << endl; cout << "-------------------------------------------------------------------------------------------------------------------------------------------------------------\n"; //Print all students' information for (unsigned int i = 0; i < studentData.size(); i++)//modified: change i <= to i < { cout << " " << left << setw(40) << studentData[i].name << setw(18) << studentData[i].USF_ID << setw(40) << studentData[i].email << setw(22) << (char)((studentData[i].presGrade == -1) ? '-' : studentData[i].presGrade+48) << setw(22) <<//modified: added cast to char (char)((studentData[i].essayGrade == -1) ? '-' : studentData[i].essayGrade+48) << setw(22) <<//modified: added cast to char (char)((studentData[i].projectGrade == -1) ? '-' : studentData[i].projectGrade+48) << endl;//modified: added cast to char } cout << endl; } /************************************************************************* * Function that prints a specific student's information **************************************************************************/ void printOneStudent(int index, vector<Student> studentVector) { if (index == -1) //If no matched student { cout << "NO DATA: This Student Does Not Exist" << endl; return; } //Print student based on the index cout << "\n\n\n------------------ STUDENT INFO -------------------" << endl; cout << left << setw(28) << "|Name: " << studentVector[index].name << endl; cout << setw(28) << "|USF ID:" << studentVector[index].USF_ID << endl; cout << setw(28) << "|Email:" << studentVector[index].email << endl; cout << setw(28) << "|Presentation Grade:" << (char)((studentVector[index].presGrade == -1) ? '-' : studentVector[index].presGrade+48) << endl;//modified: added cast to char cout << setw(28) << "|Essay Grade:" << (char)((studentVector[index].essayGrade == -1) ? '-' : studentVector[index].essayGrade+48) << endl;//modified: added cast to char cout << setw(28) << "|Project Grade:" << (char)((studentVector[index].projectGrade == -1) ? '-' : studentVector[index].projectGrade+48) << endl;//modified: added cast to char cout << "---------------------------------------------------\n\n"; } /************************************************************************* * Function that generates a specified number of students, puts them * into a given vector of students, and writes it to a file of a given name **************************************************************************/ void generateStudents(int numOfStudents, vector<Student> &studentData, string filename) { vector<int> UID; int USFID; char name[41], ID[11], email[31]; int presGrade, projGrade, essayGrade; ofstream dataFile(filename); if (!dataFile.is_open()) cout << "\nCould not open " << filename << ".\n"; dataFile << "name,UID,email,presentation,essay,project\n"; if (dataFile.good()) { for(int i = 0; i < numOfStudents; i++) { bool UIDDuplicate = true; while(UIDDuplicate) { UIDDuplicate = false; USFID = rand() % 1000000 + 10000000; for(int j = 0; j < UID.size(); j++) { if(USFID == UID[j]) { UIDDuplicate = true; break; } } UID.push_back(USFID); } strcpy(name, ("User" + to_string(i)).c_str()); strcpy(ID, ("U-"+ to_string(USFID)).c_str()); strcpy(email, ("User" + to_string(i) + "@usf.edu").c_str()); //Randomly put in blank grades if(rand() % 5 > 3) presGrade = -1; else presGrade = rand() % 5; if(rand() % 5 > 3) projGrade = -1; else projGrade = rand() % 5; if(rand() % 5 > 3) essayGrade = -1; else essayGrade = rand() % 5; Student s(name, ID, email, presGrade, projGrade, essayGrade); studentData.push_back(s); dataFile << name << "," << ID << "," << email << ","; presGrade == -1 ? (dataFile << ",") : (dataFile << presGrade << ","); projGrade == -1 ? (dataFile << ",") : (dataFile << projGrade << ","); essayGrade == -1 ? (dataFile << "," << endl) : (dataFile << essayGrade << endl); } } dataFile.close(); } bool makeStudentsFile(vector<Student> studentData, string filename) { string name, ID, email; int presGrade, projGrade, essayGrade; ofstream dataFile(filename); if (!dataFile.is_open()){ cout << "\nCould not open " << filename << ".\n"; return false; } dataFile << "name,UID,email,presentation,essay,project\n"; if (dataFile.good()) { for(int i = 0; i < studentData.size(); i++) { name = studentData[i].name; ID = studentData[i].USF_ID; email = studentData[i].email; presGrade = studentData[i].presGrade; projGrade = studentData[i].projectGrade; essayGrade = studentData[i].essayGrade; dataFile << name << "," << ID << "," << email << ","; presGrade == -1 ? (dataFile << ",") : (dataFile << presGrade << ","); projGrade == -1 ? (dataFile << ",") : (dataFile << projGrade << ","); essayGrade == -1 ? (dataFile << "," << endl) : (dataFile << essayGrade << endl); } } else return false; dataFile.close(); return true; } /************************************************************************* * BASIC VECTOR TEST **************************************************************************/ TEST_CASE("vector of students can be added to, read from, and removed from", "[readDataFile]"){ vector<Student> studentData; char name[41] = "Banner", ID[11] = "U-00000000", email[30] = "strongestAvenger@usf.edu"; Student s(name, ID, email, 4, 4, 4); studentData.push_back(s); REQUIRE(studentData.size() == 1); CHECK(strcmp(studentData[0].name, name) == 0); CHECK(strcmp(studentData[0].USF_ID, ID) == 0); CHECK(strcmp(studentData[0].email, email) == 0); CHECK(studentData[0].presGrade == 4); CHECK(studentData[0].projectGrade == 4); CHECK(studentData[0].essayGrade == 4); studentData.erase(studentData.begin() + 0); //This is the same logic as is found in deleteStudent REQUIRE(studentData.size() == 0); } /************************************************************************* * Testing int case_insensitive(string s1, string s2); * case_insenitive checks if the strings match in lowercase. **************************************************************************/ SCENARIO("strings are compared case insensitive", "[case_insensitive]"){ GIVEN("A string with uppercase, an identical string with lowercase, and a similar string with lowercase"){ string one_upper = "test!s TRING...\n"; string one_lower = "test!s tring...\n"; string two = "test1s tring...\n"; WHEN("identical but different cases are compared"){ THEN("the strings are considered identical"){ CHECK(case_insensitive(one_upper, one_lower) == 1); } } WHEN("identical are compared"){ THEN("the strings are considered identical"){ CHECK(case_insensitive(two, two) == 1); } } WHEN("similar but different lowercase strings are compared"){ THEN("the strings are different"){ CHECK(case_insensitive(one_lower, two) == 0); } } WHEN("similar but different uppercase and lowercase strings are compared"){ THEN("the strings are different"){ CHECK(case_insensitive(one_upper, two) == 0); } } } } /************************************************************************* * Testing bool fileGradeCheck(string dataInfo, int &gradeUpdate); * Function that checks and returns if the grade in the data file are valid or not. * Return true for invalid data-to be skip, and false for valid data **************************************************************************/ SCENARIO("Valid grades are 0-4 or nothing", "[fileGradeCheck]"){ GIVEN("Some grades"){ int grade; string good_grade = "4", bad_grade = "5", bad_grade_long = "11", negative_bad_grade = "-1", nothing = ""; WHEN("a grade is invalid"){ THEN("the grade checker says true, it is invalid"){ CHECK(fileGradeCheck(bad_grade, grade) == true); CHECK(fileGradeCheck(bad_grade_long, grade) == true); CHECK(fileGradeCheck(negative_bad_grade, grade) == true); } } WHEN("a grade is not invalid"){ THEN("the grade checker says false, it is not invalid"){ CHECK(fileGradeCheck("0", grade) == false); CHECK(fileGradeCheck("1", grade) == false); CHECK(fileGradeCheck("2", grade) == false); CHECK(fileGradeCheck("3", grade) == false); CHECK(fileGradeCheck(good_grade, grade) == false); } THEN("the grade is passed to the given address"){ CHECK(grade == 4); } } WHEN("a grade is nothing"){ THEN("the grade is valid"){ CHECK(fileGradeCheck(nothing, grade) == false); } THEN("the given address contains -1"){ CHECK(grade == -1); } } } } /************************************************************************* * Testing vector<Student> readDataFile(string filename, bool &opened); * Function that read from the file that contains all students' data information and it returns a vector of Student struct **************************************************************************/ SCENARIO("A test file is read", "[readDataFile]"){ GIVEN("A test file"){ string fileName = "student_test.csv"; vector<Student> studentData; vector<Student> functionData; WHEN("has four students that shouldn't be skipped"){ bool opened; string fileBasic = "student_basic.csv"; THEN("the returned student vector is empty"){ CHECK(readDataFile(fileBasic, opened).size() == 4); } THEN("the file was opened"){ CHECK(opened == true); } } WHEN("has only the header"){ bool opened; REQUIRE(makeStudentsFile(studentData, fileName)); THEN("the returned student vector is empty"){ CHECK(readDataFile(fileName, opened).size() == 0); } THEN("the file was opened"){ CHECK(opened == true); } } WHEN("has one valid student"){ bool opened; char name[41] = "Banner", ID[11] = "U-00000000", email[30] = "strongestAvenger@usf.edu"; Student s(name, ID, email, 4, 4, 4); studentData.push_back(s); REQUIRE(makeStudentsFile(studentData, fileName)); functionData = readDataFile(fileName, opened); THEN("the file was opened"){ REQUIRE(opened == true); } THEN("the returned student vector has as many students as given"){ REQUIRE(functionData.size() == studentData.size()); } THEN("the students in the vector match what was in the file"){ CHECK(strcmp(functionData[0].name, studentData[0].name) == 0); CHECK(strcmp(functionData[0].USF_ID, studentData[0].USF_ID) == 0); CHECK(strcmp(functionData[0].email, studentData[0].email) == 0); CHECK(functionData[0].presGrade == studentData[0].presGrade); CHECK(functionData[0].projectGrade == studentData[0].projectGrade); CHECK(functionData[0].essayGrade == studentData[0].essayGrade); } } WHEN("has one valid student and a student with a name that is one character too long"){ bool opened; string fileLongName = "student_long_name_test.csv"; functionData = readDataFile(fileLongName, opened); THEN("the file was opened"){ REQUIRE(opened == true); } THEN("the returned student vector has only 1 student"){ REQUIRE(functionData.size() == 1); } } WHEN("doesn't exist"){ bool opened; fileName = "1.csv"; THEN("the returned student vector is empty"){ CHECK(readDataFile(fileName, opened).size() == 0); } THEN("the file was not opened"){ CHECK(opened == false); } } } } /************************************************************************** * Testing void writeToFile(string filename, vector<Student> studentData); * Function that writes the update data to the file ***************************************************************************/ // Give it some data that you've written to a file. Open the file it writes to and compare each line with the file you made. SCENARIO("A vector of students is wrritten into a file", "[writeToFile]"){ GIVEN("A test file"){ string fileName = "one_student.csv"; vector<Student> studentData; vector<Student> functionData; char name[41] = "Banner", ID[11] = "U-00000000", email[30] = "strongestAvenger@usf.edu"; studentData.push_back(Student(name, ID, email, 3, 4, 3)); WHEN("one_student.csv"){ bool opened; writeToFile(fileName, studentData); studentData.clear(); THEN("check if it prints out everything"){ functionData = readDataFile(fileName, opened); CHECK(readDataFile(fileName, opened).size() == 1); CHECK(strcmp(studentData[0].name, name) == 0); CHECK(strcmp(studentData[0].USF_ID, ID) == 0); CHECK(strcmp(studentData[0].email, email) == 0); CHECK(functionData[0].presGrade == 3); CHECK(functionData[0].essayGrade == 4); CHECK(functionData[0].projectGrade == 3); } } } } /************************************************************************** * Testing void printOneStudent(int index, vector<Student> studentVector) * Function that prints a specific students information ***************************************************************************/ SCENARIO("A specific student's information is printed out", "[printOneStudent]"){ GIVEN("A vector of students"){ vector<Student> studentData; char name[41] = "Banner", ID[11] = "U-00000000", email[30] = "strongestAvenger@usf.edu"; studentData.push_back(Student(name, ID, email, 3, 4, 3)); char name1[41] = "Jack", ID1[11] = "U-11111111", email1[30] = "jack@usf.edu"; studentData.push_back(Student(name1, ID1, email1, 3, 4, 3)); // Check that it doesn't fail when given -1 (which means that the student doesn't exist) WHEN("student doesn't exist"){ printOneStudent(-1, studentData); } // - - - doesn't fail on a good index WHEN("student does exist"){ printOneStudent(1, studentData); } // - - - prints properly (probably have to cout what it should look like and let user compare) WHEN("student does exist and prints student info"){ cout << "\n\n\n------------------ COMPARE THE TWO TABLES BELOW, SHOULD BE THE SAME -------------------\n" << endl; printOneStudent(1, studentData); //Print student based on the index cout << "\n------------------ STUDENT INFO -------------------" << endl; cout << left << setw(28) << "|Name: " << studentData[1].name << endl; cout << setw(28) << "|USF ID:" << studentData[1].USF_ID << endl; cout << setw(28) << "|Email:" << studentData[1].email << endl; cout << setw(28) << "|Presentation Grade:" << (char)((studentData[1].presGrade == -1) ? '-' : studentData[1].presGrade+48) << endl;//modified: added cast to char cout << setw(28) << "|Essay Grade:" << (char)((studentData[1].essayGrade == -1) ? '-' : studentData[1].essayGrade+48) << endl;//modified: added cast to char cout << setw(28) << "|Project Grade:" << (char)((studentData[1].projectGrade == -1) ? '-' : studentData[1].projectGrade+48) << endl;//modified: added cast to char cout << "---------------------------------------------------\n\n"; cout << "---------------------------------------------------------------------------------------------\n\n"; } } } /************************************************************************** * Testing void printAllStudents(vector<Student> studentData) * Function that prints all the students in the class ***************************************************************************/ SCENARIO("All students' information is printed out", "[printAllStudents]"){ GIVEN("A vector of students"){ vector<Student> studentData; //add students to vector char name[41] = "Banner", ID[11] = "U-00000000", email[30] = "strongestAvenger@usf.edu"; studentData.push_back(Student(name, ID, email, 3, 4, 3)); char name1[41] = "Jack", ID1[11] = "U-11111111", email1[30] = "jack@usf.edu"; studentData.push_back(Student(name1, ID1, email1, 4, 4, 3)); // - - - - - - - a good vector of students WHEN("vector of students is not empty"){ printAllStudents(studentData); } // - - - prints properly (probably have to cout what it should look like and let user compare) WHEN("vector of students is not empty and print students' info"){ cout << "\n\n\n------------------ COMPARE THE TWO TABLES BELOW, SHOULD BE THE SAME -------------------\n" << endl; printAllStudents(studentData); cout << "\t\t\t\t\t\t\t\t\t**** STUDENT LIST ****\n"; cout << left << setw(40) << "|Name" << setw(18) << "|USF ID" << setw(40) << "|Email" << setw(22) << "|Presentation Grade" << setw(22) << "|Essay Grade" << setw(22) << "|Project Grade" << endl; cout << "-------------------------------------------------------------------------------------------------------------------------------------------------------------\n"; //Print all students' information for (unsigned int i = 0; i < studentData.size(); i++) { cout << " " << left << setw(40) << studentData[i].name << setw(18) << studentData[i].USF_ID << setw(40) << studentData[i].email << setw(22) << (char)((studentData[i].presGrade == -1) ? '-' : studentData[i].presGrade+48) << setw(22) <<//modified: added cast to char (char)((studentData[i].essayGrade == -1) ? '-' : studentData[i].essayGrade+48) << setw(22) <<//modified: added cast to char (char)((studentData[i].projectGrade == -1) ? '-' : studentData[i].projectGrade+48) << endl;//modified: added cast to char } cout << endl; cout << "---------------------------------------------------------------------------------------------\n\n"; } } }
true
590867c7d3d343906fe70e82584923bb04ef7f1f
C++
dwax1324/baekjoon
/code/3976 역습.cpp
UTF-8
1,475
2.796875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; // dp나 다익스트라로 해결 가능 (n log n)인 // naive -> 2**n 가지, 너무느림 // b[i] = min(a[i-1] + passTob[i-1], b[i-1], bDribble[i-1]) // 다익스트라로 풀다가 포기 노드설정해주는데 홀/짝으로 나누면 될듯? // 구현하다가 떄려침 dp로 해결 int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int T; cin >> T; while (T--) { int passToSecondPlayer[100001]; int firstPlayerDribble[100001]; int passToFirstPlayer[100001]; int secondPlayerDribble[100001]; int n, l1, l2, s1, s2; cin >> n >> l1 >> l2 >> s1 >> s2; for (int i = 1; i <= n - 1; i++) { cin >> passToSecondPlayer[i]; } for (int i = 1; i <= n - 1; i++) { cin >> firstPlayerDribble[i]; } for (int i = 1; i <= n - 1; i++) { cin >> passToFirstPlayer[i]; } for (int i = 1; i <= n - 1; i++) { cin >> secondPlayerDribble[i]; } int dpA[100001]; int dpB[100001]; dpA[0] = l1; dpB[0] = l2; for (int i = 1; i < n; i++) { dpA[i] = min(dpB[i - 1] + passToFirstPlayer[i], dpA[i - 1] + firstPlayerDribble[i]); dpB[i] = min(dpA[i - 1] + passToSecondPlayer[i], dpB[i - 1] + secondPlayerDribble[i]); } cout << min(dpA[n - 1] + s1, dpB[n - 1] + s2) << '\n'; } }
true
b5b8f9a1a6758984c7aaec1cb10976df8c7d2a10
C++
kk-katayama/com_pro
/atcoder/CodeFormula/CodeFormula2014a/CodeFormula2014_d.cpp
UTF-8
1,955
2.59375
3
[]
no_license
#include <iostream> #include <algorithm> #include <vector> #include <string> #include <utility> #include <set> #include <map> #include <cmath> #include <queue> #include <cstdio> #define rep(i,n) for(int i = 0; i < n; ++i) #define rep1(i,n) for(int i = 1; i <= n; ++i) #define F first #define S second using namespace std; template<class T>bool chmax(T &a, const T &b) { if(a < b){ a = b; return 1; } return 0; } template<class T>bool chmin(T &a, const T &b) { if(a > b){ a = b; return 1; } return 0; } using ll = long long; using pi = pair<int,int>; const ll MOD=1e+9+7; struct mint{ ll x; mint(ll x=0):x(x%MOD){} mint& operator+=(const mint a){ if((x+=a.x)>=MOD) x-=MOD; return *this; } mint& operator-=(const mint a){ if((x += MOD-a.x)>=MOD) x-=MOD; return *this; } mint& operator*=(const mint a){ (x*=a.x)%=MOD; return *this; } mint operator+(const mint a) const{ mint res(*this); return res+=a; } mint operator-(const mint a) const{ mint res(*this); return res-=a; } mint operator*(const mint a) const{ mint res(*this); return res*=a; } mint pow(ll t) const{ if(!t) return 1; mint a = pow(t>>1); a*=a; if(t&1) a*=*this; return a; } //for prime mod mint inv() const{ return pow(MOD-2); } mint& operator/=(const mint a){ return (*this) *= a.inv(); } mint operator/(const mint a) const{ mint res(*this); return res/=a; } }; int main() { int n; cin >> n; vector<ll> a(n); rep(i,n) cin >> a[i]; vector<mint> pow10(n+1); pow10[0].x = 1; rep(i,n) pow10[i+1] = pow10[i] * (mint)10; mint res(1); mint sum(1); ll buf = 0; int idx = 0; rep(i,n) { buf += a[i]; sum += (mint)a[i] * pow10[idx]; if(buf < 10) { res *= sum; sum.x = 1; idx = 0; } else { idx++; } buf /= 10; } res *= sum; cout << (res.x - 1 + MOD) % MOD << "\n"; return 0; }
true
2e778a7f67590e5279d296854ca29fee295878d5
C++
ParvezAhmed111/Data-Structure-and-Algorithms-with-cpp
/32. GRAPHS/11_Floyd_Warshall_Algorithm.cpp
UTF-8
1,372
2.96875
3
[]
no_license
#include<bits/stdc++.h> using namespace std; const int INF=1e9; int main(){ vector<vector<int>> graph= { {0, 5, INF, 10}, {INF, 0, 3, INF}, {INF, INF, 0, 1}, {INF, INF, INF, 0}, }; int n= graph.size(); //n= no of vertices; adjm is n x n vector<vector<int>> dist= graph; for(int k=0; k<n; k++){ for(int i=0; i<n; i++){ for(int j=0; j<n; j++){ if(dist[i][k] + dist[k][j] < dist[i][j]){ dist[i][j] = dist[i][k] + dist[k][j]; } } } } for(int i=0; i<n; i++){ for(int j=0; j<n; j++){ if(dist[i][j] == INF){ cout<<"INF "; } else cout<<dist[i][j]<<" "; } cout<<endl; } // distance between 1 3 cout<<dist[1][3]; return 0; } // Adjacenct matrix // vector<vector<int>> adjm(n+1, vector<int> (n+1, 0)); // for(int i=0; i<n; i++){ // int x, y; // cin>>x>>y; // //input edges // adjm[x][y]=1; // adjm[y][x]=1; // } // cout<<"Adjacenct matrix of above graph is given by: "<<endl; // for(int i=1; i<n+1; i++){ // for(int j=1; j<n+1; j++){ // cout<<adjm[i][j]<<" "; // }cout<<endl; // }
true
ded2c980ffb9d3b702a2cfae676a5308ddd18789
C++
joych97/Leetcode_May_Challenge
/leetcode_15.cpp
UTF-8
1,127
3.734375
4
[]
no_license
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ /* In this we are just interchanging the odd->next pointer with the even->next pointer and vice-versa. At the end we merge the odd pointer with the headEven pointer. We initialize 4 pointers at the beginning headOdd=head headEven=head->next odd=head; even=head->next. And we perform our operations on the odd and even pointers. */ class Solution { public: ListNode* oddEvenList(ListNode* head) { if(head!=NULL){ ListNode* headOdd= head; ListNode* headEven= head->next; ListNode* odd= head; ListNode* even= head->next; while(odd->next != NULL && even!= NULL){ odd->next=even->next; if(odd->next!=NULL){ odd=odd->next; } even->next = odd->next; even=even->next ; } odd->next=headEven; return headOdd; } return head; } };
true
0b78cc817a530a85b69ce36a32439c11b8ff1233
C++
mine691/procon-library
/Number theory/Millar-Rabin/Millar-Rabin Test.cpp
UTF-8
915
3.046875
3
[]
no_license
#include <iostream> #include <vector> using namespace std; using ll = long long; ll pow_mod(ll x, ll N, ll M) // return x^N mod M { ll res = 1LL; while (N > 0) { if (N & 1) (res *= x) %= M; (x *= x) %= M, N >>= 1; } return res; } bool check(ll a, int s, ll d, ll N) { ll x = pow_mod(a, d, N); if (x == 1) return true; for (int r = 0; r < s; r++) { if (x == N - 1) return true; x = x * x % N; } return false; } bool is_prime(ll N) { if (N <= 1 || (N > 2 && N % 2 == 0)) return false; ll d = N - 1, s = 0; while (!(d & 1)) d >>= 1, ++s; vector<vector<ll>> test = {{2, 7, 61}, {2, 3, 5, 7, 11, 13, 17, 19, 23}}; bool type = (N > 4759123140); for (int i = 0; test[type][i] < N && i < test[type].size(); i++) { if (!check(test[type][i], s, d, N)) return false; } return true; } int main() { ll N; cin >> N; cout << (is_prime(N) ? "Prime\n" : "Composite\n"); }
true
9c6e1be6c29597f09a290513a9dc54339940dec5
C++
LeeYunSung/Algorithm
/BOJ/4963_섬의개수.cpp
UHC
1,653
3.5
4
[]
no_license
#include <iostream> #include <cstring> //memset using namespace std; const int MAX = 50; void SearchMap(int, int); int width, height; // ־ μ ũ int map[MAX][MAX]; // int visited[MAX][MAX]; //湮ߴ üũϴ int direction[8][2] = { {0,-1}, {0,1}, {-1,0}, {1,0}, {-1,-1}, {-1,1}, {1,-1}, {1,1} }; //, , , , 밢 int main() { while(1) { cin >> width >> height; if (width == 0 && height == 0) break; //0, 0 ̸ ̹Ƿ // Է¹ޱ for (int i = 0; i < height; i++) { // for (int j = 0; j < width; j++) { // cin >> map[i][j]; } } //Ž gogo. Ž ʱȭ int count = 0; memset(visited, false, sizeof(visited)); for (int i = 0; i < height; i++) { // for (int j = 0; j < width; j++) {// if (map[i][j] && !visited[i][j]) { //ġ ̰, 湮 ġ Ž SearchMap(i, j); count += 1; } } } cout << count << "\n"; } } void SearchMap(int x, int y) { if (!map[x][y] || visited[x][y]) { //Ž ϴٰ ƴϰų ̹ 湮 , ̻ Ž ʿ ϱ ٷ return; } visited[x][y] = true; for (int i = 0; i < 8; i++) { //¿밢 Ž int dx = x + direction[i][0]; //xǥ int dy = y + direction[i][1]; //yǥ if (dx >= 0 && dx < height && dy >= 0 && dy < width) {// ¿ ̵ Ѵ üũ SearchMap(dx, dy); } } }
true
9a5648649b97df187150d4f38e37a84dea37be41
C++
jeremie1112/TEXT-SIMILARITY
/Programming assignment 2019/newmain.cpp
UTF-8
7,989
3.0625
3
[]
no_license
#include <iostream> #include <ostream> #include <fstream> #include "Sentences.h" using namespace std; int main() { cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl; cout<<" TEXT SIMILARITY "<<endl; cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl; cout<<"> <"<<endl; cout<<"> Programming Assignment 2019 <"<<endl; cout<<">_______________________________________________________________<"<<endl; cout<<"> : WORKING TEAM : <"<<endl; cout<<">_______________________________________________________________<"<<endl; cout<<">STUDENT1: JEREMIE DANIEL <"<<endl; cout<<">STUDENT2: GEESHAM HOSANEE <"<<endl; cout<<">_______________________________________________________________<"<<endl; cout<<">ID : 1812415 && 1812260 <"<<endl; cout<<">_______________________________________________________________<"<<endl; cout<<"> <"<<endl; cout<<">Faculty of Information, Communication and Digital Technologies,<"<<endl; cout<<"> Department of Information Communication Technology, <"<<endl; cout<<"> Computer Science Year 1 <"<<endl; cout<<"> UNIVERSITY OF MAURITIUS <"<<endl; cout<<">_______________________________________________________________<"<<endl; cout<<"> <"<<endl; ///SENTENCES ///1st vector variable to store the individual words in one sentence vector<string> wordsFromSentence1; ///2nd vector variable to store the individual words in one sentence vector<string> wordsFromSentence2; ///1st vector variable to store all the sentences from the dataset vector<string> allSentences; ///temporary string variable to store each sentence from the dataset string sentenceFromFile; ///integer variable to count the number of 1st lines/sentences in the dataset int countSentence = 0; ///codes to load the sentences dataset from a text file into 1st vector ifstream infile; infile.open ("datasetSentences.txt"); while(!infile.eof()) { getline(infile,sentenceFromFile); allSentences.push_back(sentenceFromFile); countSentence++; } infile.close(); ///creating a vector of objects of type sentences vector<Sentences> s1(countSentence); ///creating a vector of objects of type sentences vector<Sentences> s2(countSentence); ///assign each extracted sentence (from dataset) to one Sentence object for(int i=0; i<countSentence; i++){ s1[i].setSentence(allSentences[i]); s2[i].setSentence(allSentences[i]); } ///GJ means the percentage of similarity. Example enter 0.5 float GJ = 0.0; cout<<"> Input the percentage of similarity[0 to 1] <"<<endl; cout<<"> :"; cin>>GJ; if (GJ > 1 || GJ < 0){ cout<<" Error as percentage is either more than 1 or less than 0 "<<endl; return -1; } cout<<"> <"<<endl; cout<<"> <"<<endl; cout<<"> This may take time as it is a big dataset <"<<endl; cout<<"> Please be patient <"<<endl; cout<<"> Loading... <"<<endl; cout<<"> <"<<endl; cout<<"> <"<<endl; ///initializing AnB where A is word[a], /// B is word[b], /// n is intersection, /// u is union ///AnB returns the number of similar words in a text ///AuB return the number of the 2 sentence minus AnB float AnB; float AuB; ///for loop 1 for the dataset for(int i=0; i<countSentence; i++){ ///for loop 2 for the same dataset ///!(i==j) i must not equal to j as it will always give 1 as score. for(int j=0; j<countSentence && !(i==j) ; j++){ cout<<endl<<"1st. THIS IS SENTENCE No "<<i+1<<" : "; cout<<endl<<s1[i].getSentence()<<endl; cout<<endl; cout<<endl<<"2nd. THIS IS SENTENCE No "<<j+1<<" : "; cout<<endl<<s2[j].getSentence()<<endl; ///assigning words from sentence[i] into wordsFromSentence1 ///assigning words from sentence[j] into wordsFromSentence2 wordsFromSentence1 = s1[i].getWords(); wordsFromSentence2 = s2[j].getWords(); ///comparing word[a] in sentence[i] == word[b] in sentence[j] for(int a=0; a<wordsFromSentence1.size(); a++){ for(int b=0; b<wordsFromSentence2.size(); b++){ string one = wordsFromSentence1[a]; string two = wordsFromSentence2[b]; ///dont forget that it is case sensitive ///example: /// this != This /// thus it wont count /// need to convert the first letter in first word into lower case /// convert A to a is +32 if (isupper(one[0])){ one[0] = one[0] + 32; } if (isupper(two[0])){ two[0] = two[0] + 32; } //This piece of code is written as these words cannot be taken for account as they logically //sentences with these words cannot be similar if (one == "is" || one == "a" || two == "is" || two == "a"){ continue; } ///testing if word[a] == word[b] if (one == two){ ///if true then add one to the counter AnB AnB++; } } } ///to get AuB, number of words in sentence[i] + number of words in sentence[j] - AnB AuB = (s1[i].getNumWords()+s2[j].getNumWords()-AnB); cout<<endl; ///initialize score which returns the score of AnB/AuB float score = 0.0; score = AnB/AuB; //logically if AnB is > AuB, the score must be one if (AnB > AuB){ score = 1.0; AnB = s1[i].getNumWords(); AuB = s1[i].getNumWords(); } cout<<"AuB is: "<<AuB<<endl; cout<<"AnB is: "<<AnB<<endl; ///if the score is more than GJ then they are similar, else they are not if (score > GJ){ cout<<"The sentence "<<i+1<<" and "<<j+1<<" are similar with a score of : "<<score<<endl; } else{ cout<<"The sentence "<<i+1<<" and "<<j+1<<" are not similar with a score of : "<<score<<endl; } cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl; ///initializing again so that it dont keep adding previous values AuB = 0.0; AnB = 0.0; } } cout<<endl; cout<<endl; cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl; cout<<" PROGRAM ENDS HERE "<<endl; cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl; }
true
4b69dc97a7506851321779d80ec59bd566235b88
C++
pateljainilanilbhai/cpp_programs
/6.cpp
UTF-8
2,222
3.28125
3
[]
no_license
#include<iostream> #include<cstdio> using namespace std; class measure { int metre; int cm; public: void get() { cout<<"enter metre:"; cin>>metre; cout<<"enter centimetre:"; cin>>cm; start: if(cm>100) { int x; x=cm/100; metre=metre+x; cm=cm%100; goto start; } else { cout<<"you have entered "<<metre<<" metre "<<cm<<" centimetre "<<endl; } } void put() { cout<<metre<<" metre "<<cm<<" centimetre "<<endl; } friend void display(measure m1,measure m2,measure m3,measure m4); friend measure operator +(measure m,int x); friend measure operator -(measure m1,float f); friend measure operator +(float f,measure m1); friend measure operator -(float f,measure m1); }; measure operator +(measure m,int x) { m.metre=m.metre+x; return m; } measure operator -(measure m1,float f) { float z=m1.metre+((float)m1.cm/100); float y=z-f; cout<<y<<"m "; measure ans; ans.metre=(int)y; ans.cm=(y-(int)y)*100; return ans; } measure operator +(float f,measure m1) { float z=m1.metre+((float)m1.cm/100); float y=f+z; cout<<y<<"m "; measure ans; ans.metre=(int)y; ans.cm=(y-(int)y)*100; return ans; } measure operator -(float f,measure m1) { float z=m1.metre+((float)m1.cm/100); float y=f-z; cout<<y<<"m "; measure ans; ans.metre=(int)y; ans.cm=(y-(int)y)*100; return ans; } void display(measure m1,measure m2,measure m3,measure m4) { cout<<"m1:"<<m1.metre<<"."<<m1.cm<<endl; cout<<"m2:"<<m2.metre<<"."<<m2.cm<<endl; cout<<"m3:"<<m3.metre<<"."<<m3.cm<<endl; cout<<"m4:"<<m4.metre<<"."<<m4.cm<<endl; } int main() { measure m1,m2,m3,m4; cout<<" for m2"<<endl; m2.get(); cout<<" for m4"<<endl; m4.get(); m1=m2+15; cout<<" for m1=m2+15"<<endl; m1.put(); m3=m1-4.5; cout<<" for m3=m1-4.5"<<endl; m3.put(); m1=5.0+m2; cout<<" for m1=5.0+m2"<<endl; m1.put(); m3=2.0-m4; cout<<" for m3=2.0-m4"<<endl; m3.put(); display(m1,m2,m3,m4); return 0; }
true
5f542f647be1e9f1191097113ff756e89f282319
C++
sustcoderboy/competitive-programming-archive
/uri/beginner/age_in_days.cpp
UTF-8
492
3.28125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#include <iostream> using namespace std; inline void use_io_optimizations() { ios_base::sync_with_stdio(false); cin.tie(nullptr); } int main() { use_io_optimizations(); unsigned int time; cin >> time; unsigned int years {time / 365}; unsigned int months {time % 365 / 30}; unsigned int days {time % 365 % 30}; cout << years << " ano(s)" << '\n' << months << " mes(es)" << '\n' << days << " dia(s)" << '\n'; return 0; }
true
e0217af3b9105e02f4a3422be24e3dbecc5fb70e
C++
vividos/MultiplayerOnlineGame
/src/Client/RenderEngine/IRenderable.hpp
UTF-8
976
2.6875
3
[]
no_license
// // MultiplayerOnlineGame - multiplayer game project // Copyright (C) 2008-2014 Michael Fink // /// \file IRenderable.hpp Interface for renderable objects // #pragma once // forward references class RenderOptions; /// \brief interface for renderable objects class IRenderable { public: /// dtor virtual ~IRenderable() {} /// returns if Prepare() call is needed (or it's a no-op) virtual bool IsPrepareNeeded() const = 0; /// returns if Upload() call is needed (or it's a no-op) virtual bool IsUploadNeeded() const = 0; /// prepares or calculates data; may be done on a worker thread virtual void Prepare() = 0; /// uploads data to graphics card; called in thread with rendering context virtual void Upload() = 0; /// renders object; called every frame; called in thread with rendering context virtual void Render(RenderOptions& options) = 0; /// cleans up data; called in thread with rendering context virtual void Done() = 0; };
true
1bb380390413e55da64465e5b89867cb8c0f8b54
C++
LeeMungu/Programing26.1
/Kirbies/01_WinMain/Trap.cpp
UHC
1,095
2.671875
3
[]
no_license
#include "pch.h" #include "Trap.h" Trap::Trap(const string & name, float x, float y, float sizeX, float sizeY, PlayerState state) : GameObject(name) { mX = x; mY = y; mSizeX = sizeX; mSizeY = sizeY; mState = state; } void Trap::Init() { mRect = RectMake(mX, mY, mSizeX, mSizeY); } void Trap::Update() { vector<GameObject*> player = ObjectManager::GetInstance()->GetObjectList(ObjectLayer::Player); for (int i = 0; i < player.size(); i++) { Player* tempPlayer = (Player*)player[i]; RECT tempRc; RECT playerRc = tempPlayer->GetRect(); if (IntersectRect(&tempRc, &mRect, &playerRc)) { //trap Ʈ ÷̾ Ʈ 浹ϸ ÷̾ ¸ ٲش //ѹ ް ! if (tempPlayer->GetIsTrap() == false) { tempPlayer->SetPlayerState(mState); tempPlayer->SetIsChange(true); tempPlayer->SetIsTrap(true); } } } } void Trap::Release() { } void Trap::Render(HDC hdc) { if (Input::GetInstance()->GetKey(VK_LCONTROL)) { ColorLender::GetInstance()->ColorRectRender(hdc, mRect, 200, 100, 100); } }
true
148ebd3733ce93a37aa5717c8c28ade47c7e756e
C++
TinyWhiteCat/Programming-Abstractions
/InvertKey.cpp
UTF-8
710
3.359375
3
[]
no_license
#include "stdafx.h" #include "std_lib_facilities.h" #include<string> using namespace std; string invertKey(string key, string str); int main() { string str, key; cout << "Letter substitution chiper." << endl; while (true) { cout << "Enter a 26-letter key: "; getline(cin, key); if (key == "") break; cout << "Enter a message: "; getline(cin, str); cout << "Encode the message: " << invertKey(key, str) << endl; } return 0; } string invertKey(string key, string str) { int pos; for (int i = 0; i < str.length(); i++) if (isalpha(str[i])) for (int j = 0; j < 26; j++) if (str[i] == key[j]) { pos = int(j + 'A'); str[i] = (char)pos; break; } return str; }
true
9dc46a3a0050e9a0d1bbb97c111d2057a5eb4838
C++
DeretsunGit/RType
/Proj/RType/client/PlayButton.cpp
UTF-8
1,032
2.53125
3
[]
no_license
#include "PlayMenu.h" #include "PlayButton.h" PlayButton::PlayButton(SpriteManager *sprmgr) { if (!this->_font.loadFromFile("assets/arial.ttf")) { } this->setSprite(sprmgr->getSpritebyId(MENU_PLAY)); this->setSpriteOn(sprmgr->getSpritebyId(MENU_PLAY_ON)); this->_sprmgr = sprmgr; this->_connectError = false; } void PlayButton::action(sf::Keyboard::Key, sf::RenderWindow *window, bool *running) { PlayMenu playmenu(window, this->_sprmgr); if (!playmenu.getTcpSuccess()) this->_connectError = true; else { this->_connectError = false; playmenu.menuLoop(); } } void PlayButton::extraDisplay(unsigned int pos, unsigned int max, sf::RenderWindow *window) { if (this->_connectError) { _text.setFont(_font); _text.setString("Connection error"); _text.setCharacterSize(30); _text.setColor(sf::Color::Cyan); _text.setPosition(static_cast<float>(SIZEX / 2) + 250, 250 + static_cast<float>(pos) * ((SIZEY - 250) / static_cast<float>(max))); window->draw(_text); } } PlayButton::~PlayButton(void) { }
true
cef22c86f7247b8577fa107189805b47d8715640
C++
treque/cg
/TP3/TP3/TP3/Quadrique.cpp
UTF-8
8,148
2.765625
3
[]
no_license
#include "Quadrique.h" #include <algorithm> using namespace Scene; using namespace Math3D; /////////////////////////////////////////////////////////////////////////////// /// public overloaded constructor CQuadrique \n /// Description : Constructeur par défaut /// /// @return None /// /// @author Olivier Dionne /// @date 13/08/2008 /// /////////////////////////////////////////////////////////////////////////////// CQuadrique::CQuadrique(void) : ISurface() , m_Quadratique(CVecteur3::ZERO) , m_Lineaire(CVecteur3::ZERO) , m_Mixte(CVecteur3::ZERO) , m_Cst(REAL(0)) { } /////////////////////////////////////////////////////////////////////////////// /// @brief Constructeur par défaut /// /// @param [in] Quadric const Scene::CQuadrique & la quadrique à copier /// /// @author Olivier Dionne /// @date 13/08/2008 /////////////////////////////////////////////////////////////////////////////// CQuadrique::CQuadrique(const CQuadrique& Quadric) : ISurface(Quadric) , m_Quadratique(Quadric.m_Quadratique) , m_Lineaire(Quadric.m_Lineaire) , m_Mixte(Quadric.m_Mixte) , m_Cst(Quadric.m_Cst) { } /////////////////////////////////////////////////////////////////////////////// /// @brief Destructeur /// /// @author Olivier Dionne /// @date 13/08/2008 /////////////////////////////////////////////////////////////////////////////// CQuadrique::~CQuadrique(void) { } /////////////////////////////////////////////////////////////////////////////// /// @brief Opérateur de copie /// /// @param [in] Quadric const Scene::CQuadrique & La quadrique à copier /// /// @return Scene::CQuadrique & La quadrique modifiée /// /// @author Olivier Dionne /// @date 14/08/2008 /////////////////////////////////////////////////////////////////////////////// CQuadrique& CQuadrique::operator=(const CQuadrique& Quadric) { ISurface::operator=(Quadric); m_Quadratique = Quadric.m_Quadratique; m_Lineaire = Quadric.m_Lineaire; m_Mixte = Quadric.m_Mixte; m_Cst = Quadric.m_Cst; return (*this); } /////////////////////////////////////////////////////////////////////////////// /// @brief Implémente le déboguage polymorphique par flux de sortie /// /// @param [in, out] Out std::ostream & Le flux de sortie /// /// @return std::ostream & Le flux de sortie modifié /// /// @author Olivier Dionne /// @date 13/08/2008 /////////////////////////////////////////////////////////////////////////////// std::ostream& CQuadrique::AfficherInfoDebug(std::ostream& Out) const { using std::endl; Out << "[DEBUG]: Quadric.Quadratique = " << m_Quadratique << endl; Out << "[DEBUG]: Quadric.Lineaire = " << m_Lineaire << endl; Out << "[DEBUG]: Quadric.Mixte = " << m_Mixte << endl; Out << "[DEBUG]: Quadric.Constante = " << m_Cst; return Out; } /////////////////////////////////////////////////////////////////////////////// /// @brief Pretraitement des données de la quadrique( appelé AVANT le lancer) /// /// @return None /// /// @author Olivier Dionne /// @date 13/08/2008 /////////////////////////////////////////////////////////////////////////////// void CQuadrique::Pretraitement(void) { // Algorithme tiré de ... // R. Goldman, "Two Approach to a Computer Model for Quadric Surfaces", // IEEE CG&A, Sept 1983, pp.21 REAL A = m_Quadratique.x; REAL B = m_Quadratique.y; REAL C = m_Quadratique.z; REAL D = m_Mixte.z * REAL(0.5); REAL E = m_Mixte.x * REAL(0.5); REAL F = m_Mixte.y * REAL(0.5); REAL G = m_Lineaire.x * REAL(0.5); REAL H = m_Lineaire.y * REAL(0.5); REAL J = m_Lineaire.z * REAL(0.5); REAL K = m_Cst; CMatrice4 Q(A, D, F, G, D, B, E, H, F, E, C, J, G, H, J, K); CMatrice4 Inverse = m_Transformation.Inverse(); Q = Inverse * Q * Inverse.Transpose(); m_Quadratique.x = Q[0][0]; m_Quadratique.y = Q[1][1]; m_Quadratique.z = Q[2][2]; m_Cst = Q[3][3]; m_Mixte.x = Q[1][2] * REAL(2.0); m_Mixte.y = Q[0][2] * REAL(2.0); m_Mixte.z = Q[0][1] * REAL(2.0); m_Lineaire.x = Q[0][3] * REAL(2.0); m_Lineaire.y = Q[1][3] * REAL(2.0); m_Lineaire.z = Q[2][3] * REAL(2.0); } void CQuadrique::InitialiserConstantes() { A = m_Quadratique.x; E = m_Quadratique.y; H = m_Quadratique.z; B = m_Mixte.z / 2.0; F = m_Mixte.x / 2.0; C = m_Mixte.y / 2.0; D = m_Lineaire.x / 2.0; G = m_Lineaire.y / 2.0; I = m_Lineaire.z / 2.0; J = m_Cst; } /////////////////////////////////////////////////////////////////////////////// /// @brief Effectue l'intersection Rayon/Quadrique /// /// @param [in] Rayon const CRayon & Le rayon à tester /// /// @return Scene::CIntersection Le résultat de l'ntersection /// /// @author Olivier Dionne /// @date 13/08/2008 /////////////////////////////////////////////////////////////////////////////// CIntersection CQuadrique::Intersection(const CRayon& Rayon) { CIntersection Result; /* * ax^2 + 2bxy + 2cxz + 2dxw + ey^2 + 2fyz + 2gyq + hz^2 + 2izw + jw^2 = 0 * * [ X Y Z 1 ] DOT [ A B C D DOT [ X = 0 * B E F G Y * C F H I Z * D G I J ] 1 ] */ // La référence pour l'algorithme d'intersection des quadriques est : // Eric Haines, Paul Heckbert "An Introduction to Ray Tracing", // Academic Press, Edited by Andrew S. Glassner, pp.68-73 & 288-293 InitialiserConstantes(); const CVecteur3 o = Rayon.ObtenirOrigine(); const CVecteur3 d = Rayon.ObtenirDirection(); const REAL X = d.x; const REAL Y = d.y; const REAL Z = d.z; const REAL X_o = o.x; const REAL Y_o = o.y; const REAL Z_o = o.z; // Resolve intersection REAL Aq = A * X * X + 2 * B * X * Y + 2 * C * X * Z + E * Y * Y + 2 * F * Y * Z + H * Z * Z; REAL Bq = 2 * (A * X_o * X + B * (X_o * Y + X * Y_o) + C * (X_o * Z + X * Z_o) + D * X + E * Y_o * Y + F * (Y_o * Z + Y * Z_o) + G * Y + H * Z_o * Z + I * Z); REAL Cq = A * X_o * X_o + 2 * B * X_o * Y_o + 2 * C * X_o * Z_o + 2 * D * X_o + E * Y_o * Y_o + 2 * F * Y_o * Z_o + 2 * G * Y_o + H * Z_o * Z_o + 2 * I * Z_o + J; // S'il y a collision, ajuster les variables suivantes de la structure intersection : // Normale, Surface intersectée et la distance const REAL discriminant = Bq * Bq - 4 * Aq * Cq; REAL t0, t1, t; if (abs(Aq) < EPSILON) // handle div/0 { t = -Cq / Bq; if (t > EPSILON) { Result.AjusterDistance(t); Result.AjusterSurface(this); Result.AjusterNormale(ObtenirNormale(o + d * t)); } } else if (discriminant >= 0) // on va rarement avoir une seule solution a cause de l'imprecision { t0 = (-Bq - sqrt(discriminant)) / (2 * Aq); t1 = (-Bq + sqrt(discriminant)) / (2 * Aq); const REAL min = std::min(t0, t1); const REAL max = std::max(t0, t1); t = min > EPSILON ? min : max; // si t est negatif, cest quon lance le rayon en arriere.. if (t > EPSILON) { Result.AjusterDistance(t); Result.AjusterSurface(this); Result.AjusterNormale(ObtenirNormale(o + d * t)); } } return Result; } CVecteur3 CQuadrique::ObtenirNormale(const CVecteur3& point) const { return CVecteur3::Normaliser(CVecteur3(2 * (A * point.x + B * point.y + C * point.z + D), 2 * (B * point.x + E * point.y + F * point.z + G), 2 * (C * point.x + F * point.y + H * point.z + I))); } /////////////////////////////////////////////////////////////////////////////// /// @brief Alloue une copie de la quadrique courante /// /// @return Scene::CQuadrique *la copie de la quadrique /// /// @author Olivier Dionne /// @date 13/08/2008 /////////////////////////////////////////////////////////////////////////////// CQuadrique* CQuadrique::Copier(void) const { return new CQuadrique(*this); }
true
b66423fbc95d343d8b37e1a847a53784e35c0069
C++
green-fox-academy/nemethricsi
/week-04/day-1/TheGardenApplication/Plant.cpp
UTF-8
584
3.09375
3
[]
no_license
#include <iostream> #include "Garden.h" #include "Plant.h" #include "Flower.h" #include "Tree.h" Plant::Plant(Type type, const std::string &color) : _type(type), _color(color), _currentWaterAmount(0) {} std::string Plant::typeToString(Type type) { switch (type) { case Type::TREE: return "tree"; case Type::FLOWER: return "flower"; } } Type Plant::getType() const { return _type; } const std::string &Plant::getColor() const { return _color; } float Plant::getCurrentWaterAmount() const { return _currentWaterAmount; }
true
ec6dd12452a078243e724cf8da4f151bf2655958
C++
mzsrkeen10/cplibrary
/src/graph/topological_sort_indegree.cpp
UTF-8
1,073
3.65625
4
[]
no_license
/* トポロジカルソート (入次数) 時間計算量 O(|V|+|E|) Usage: graphにグラフを入れ,topological_sort()を呼び出す. 戻り値はトポロジカルソート後の頂点の番号 res.size()が頂点数に達しなければ,閉路が存在する. Verified: ABC 139 E League */ #include <stack> #include <vector> using Graph = vector<vector<int>>; std::vector<int> topological_sort(const Graph &graph) { std::vector<int> indegree(graph.size()); for (auto edges : graph) { for (auto to : edges) { indegree[to]++; } } std::stack<int> st; for (int i = 0; i < graph.size(); i++) { if (indegree[i] == 0) st.push(i); } std::vector<int> res; while (!st.empty()) { int idx = st.top(); st.pop(); res.push_back(idx); for (auto to : graph[idx]) { indegree[to]--; if (indegree[to] == 0) { st.push(to); } } } return res; }
true
132c56ef144e131dc6ce7ab1d07ba93c51e3280c
C++
Sahana-YS/parallel-computing
/Memset/memset-basic example.cpp
UTF-8
732
2.828125
3
[]
no_license
#include <iostream> #include <cstring> #include <omp.h> using namespace std; int main() { int A[100000], i; clock_t tic, toc; tic = clock(); //Normal way of initialising for (int j=0; j<10000; j++) for (i=0; i<100000; i++) A[i]=j; toc = clock(); cout << "Without memset:"<< (toc-tic)*1.0/CLOCKS_PER_SEC << endl; tic = clock(); //Using memset to initialise for (int j=0; j<10000; j++) memset(A, j, sizeof(A)); toc = clock(); cout << "With memset:"<<(toc-tic)*1.0/CLOCKS_PER_SEC << endl; return 0; } /** sahana@Sahana-Inspiron-3543:~/VI Semester/Parallel Computing/Blog/Post 2$ g++ memset.cpp sahana@Sahana-Inspiron-3543:~/VI Semester/Parallel Computing/Blog/Post 2$ ./a.out Without memset:2.70535 With memset:0.157259 **/
true
1d5af67ff5b995f0a1da3d24159aec344d5c1d1f
C++
miyamotok0105/python_sample
/cpp_sample/cpp_programming_book/005.cpp
UTF-8
1,425
2.8125
3
[]
no_license
#include <cv.h> #include <highgui.h> #include <math.h> //005:回転移動のためのピクセルサンプリング cvGetQuadrangleSubPix //g++ `pkg-config --cflags opencv` `pkg-config --libs opencv` 005.cpp -o 005 int main (int argc, char **argv) { int angle = 45; float m[6]; IplImage *src_img = 0, *dst_img = 0; CvMat M; // (1)画像の読み込み,出力用画像領域の確保を行なう if (argc >= 2) src_img = cvLoadImage (argv[1], CV_LOAD_IMAGE_ANYDEPTH | CV_LOAD_IMAGE_ANYCOLOR); if (src_img == 0) return -1; dst_img = cvCloneImage (src_img); // (2)回転のための行列(アフィン行列)要素を設定し,CvMat行列Mを初期化する m[0] = (float) (cos (angle * CV_PI / 180.)); m[1] = (float) (-sin (angle * CV_PI / 180.)); m[2] = src_img->width * 0.5; m[3] = -m[1]; m[4] = m[0]; m[5] = src_img->height * 0.5; cvInitMatHeader (&M, 2, 3, CV_32FC1, m, CV_AUTOSTEP); // (3)指定された回転行列により,GetQuadrangleSubPixを用いて画像全体を回転させる cvGetQuadrangleSubPix (src_img, dst_img, &M); // (4)結果を表示する cvNamedWindow ("src", CV_WINDOW_AUTOSIZE); cvNamedWindow ("dst", CV_WINDOW_AUTOSIZE); cvShowImage ("src", src_img); cvShowImage ("dst", dst_img); cvWaitKey (0); cvDestroyWindow ("src"); cvDestroyWindow ("dst"); cvReleaseImage (&src_img); cvReleaseImage (&dst_img); return 1; }
true
4a8aafd3938b898e74166c2aa3b96d45fce828f1
C++
garrylachman/QtRestClient
/tests/auto/restclient/testlib/jphpost.cpp
UTF-8
1,579
2.90625
3
[ "BSD-3-Clause" ]
permissive
#include "jphpost.h" JphPost::JphPost(QObject *parent) : QObject(parent), id(0), userId(0), title(), body() {} JphPost::JphPost(int id, int userId, QString title, QString body, QObject *parent) : QObject(parent), id(id), userId(userId), title(std::move(title)), body(std::move(body)) {} bool JphPost::equals(const JphPost *left, const QObject *right) { if(left) { if(!left->equals(right)) return false; } else if(left != right) return false; return true; } bool JphPost::equals(const QObject *other) const { if(this == other) return true; else if(!other) return false; else if(metaObject()->className() != other->metaObject()->className()) return false; else { for(auto i = staticMetaObject.propertyOffset(); i < metaObject()->propertyCount(); i++) { auto property = metaObject()->property(i); QMetaType t(property.userType()); if(t.flags().testFlag(QMetaType::PointerToQObject) && t.metaObject()->inherits(&staticMetaObject)) { auto c1 = property.read(this).value<JphPost*>(); auto c2 = property.read(other).value<JphPost*>(); if(!equals(c1, c2)) return false; } else if(property.read(this) != property.read(other)) return false; } return true; } } JphPost *JphPost::createDefault(QObject *parent) { return new JphPost(1, 1, QStringLiteral("Title1"), QStringLiteral("Body1"), parent); } JphPost *JphPost::createFirst(QObject *parent) { return new JphPost(0, 0, QStringLiteral("Title0"), QStringLiteral("Body0"), parent); } JphPostSimple::JphPostSimple(QObject *parent) : Simple(parent) {}
true
e19f78373a84c6634e2c360d6017bde19ca2d625
C++
vslavik/poedit
/deps/boost/libs/compute/test/test_equal_range.cpp
UTF-8
3,120
2.5625
3
[ "GPL-1.0-or-later", "MIT", "BSL-1.0" ]
permissive
//---------------------------------------------------------------------------// // Copyright (c) 2013 Kyle Lutz <kyle.r.lutz@gmail.com> // // Distributed under the Boost Software License, Version 1.0 // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt // // See http://boostorg.github.com/compute for more information. //---------------------------------------------------------------------------// #define BOOST_TEST_MODULE TestEqualRange #include <boost/test/unit_test.hpp> #include <utility> #include <iterator> #include <boost/compute/command_queue.hpp> #include <boost/compute/algorithm/equal_range.hpp> #include <boost/compute/container/vector.hpp> #include "context_setup.hpp" BOOST_AUTO_TEST_CASE(equal_range_int) { int data[] = { 1, 2, 2, 2, 3, 3, 4, 5 }; boost::compute::vector<int> vector(data, data + 8, queue); typedef boost::compute::vector<int>::iterator iterator; std::pair<iterator, iterator> range0 = boost::compute::equal_range(vector.begin(), vector.end(), int(0), queue); BOOST_CHECK(range0.first == vector.begin()); BOOST_CHECK(range0.second == vector.begin()); BOOST_CHECK_EQUAL(std::distance(range0.first, range0.second), ptrdiff_t(0)); std::pair<iterator, iterator> range1 = boost::compute::equal_range(vector.begin(), vector.end(), int(1), queue); BOOST_CHECK(range1.first == vector.begin()); BOOST_CHECK(range1.second == vector.begin() + 1); BOOST_CHECK_EQUAL(std::distance(range1.first, range1.second), ptrdiff_t(1)); std::pair<iterator, iterator> range2 = boost::compute::equal_range(vector.begin(), vector.end(), int(2), queue); BOOST_CHECK(range2.first == vector.begin() + 1); BOOST_CHECK(range2.second == vector.begin() + 4); BOOST_CHECK_EQUAL(std::distance(range2.first, range2.second), ptrdiff_t(3)); std::pair<iterator, iterator> range3 = boost::compute::equal_range(vector.begin(), vector.end(), int(3), queue); BOOST_CHECK(range3.first == vector.begin() + 4); BOOST_CHECK(range3.second == vector.begin() + 6); BOOST_CHECK_EQUAL(std::distance(range3.first, range3.second), ptrdiff_t(2)); std::pair<iterator, iterator> range4 = boost::compute::equal_range(vector.begin(), vector.end(), int(4), queue); BOOST_CHECK(range4.first == vector.begin() + 6); BOOST_CHECK(range4.second == vector.begin() + 7); BOOST_CHECK_EQUAL(std::distance(range4.first, range4.second), ptrdiff_t(1)); std::pair<iterator, iterator> range5 = boost::compute::equal_range(vector.begin(), vector.end(), int(5), queue); BOOST_CHECK(range5.first == vector.begin() + 7); BOOST_CHECK(range5.second == vector.end()); BOOST_CHECK_EQUAL(std::distance(range5.first, range5.second), ptrdiff_t(1)); std::pair<iterator, iterator> range6 = boost::compute::equal_range(vector.begin(), vector.end(), int(6), queue); BOOST_CHECK(range6.first == vector.end()); BOOST_CHECK(range6.second == vector.end()); BOOST_CHECK_EQUAL(std::distance(range6.first, range6.second), ptrdiff_t(0)); } BOOST_AUTO_TEST_SUITE_END()
true
2c45c44b45971c5d4aea6b4b6bcc73edc1202d12
C++
istudyatuni/lessons
/4-term/lab8/prog1/main.cpp
UTF-8
2,331
3.828125
4
[]
no_license
//комплексное число a = x + y * i #include <iostream> #include <cmath> using namespace std; class complx { // a = x + y * i double x, y; complx conjugate() {//сопряженное complx res(x, -y); return res; } public: complx(double a = 0, double b = 0) { x = a; y = b; } void rewrite(double a, double b) { x = a; y = b; } double modul() { return sqrt(x * x + y * y); } complx operator+() {//унарный + return complx(*this); } complx operator-() const {//сопряженное, унарный - complx res(*this); res.x = x; res.y = -y; return res; } //сложение complx& operator+=(const complx& a) { x += a.x; y += a.y; return *this; } complx operator+(const complx& a) const { return complx(*this) += a; } //вычитание complx& operator-=(const complx& a) { x -= a.x; y -= a.y; return *this; } complx operator-(const complx& a) const { return complx(*this) -= a; } //умножение /*complx& operator*=(const complx& a) { x = x * a.x - y * a.y; //work not correct y = x * a.y + y * a.x; return *this; } complx operator*(const complx& a) const { return complx(*this) *= a; }*/ complx operator*(const complx& a) { complx res(x * a.x - y * a.y, x * a.y + y * a.x); return res; } //деление complx operator/=(const complx& a) { //complx tmp = a; //complx con = tmp.conjugate(); double den = a.x * a.x + a.y * a.y;//a^2 - b^2 (i^2 = -1), denominator a = -a; *this = *this * a;//con;//numerator, умножаем на сопряженное к знаменателю x /= den; y /= den; return *this; } complx operator/(const complx& a) const { return complx(*this) /= a; } void out(){ cout << x << " + " << y << " * i"; } }; int main() { complx a(13, 1), b(7, -6); cout << endl; (a / b).out(); cout << endl; (a + b).out(); cout << endl; (a - b).out(); cout << endl; (a * b).out(); return 0; }
true
32b11b8907f14d1d175a602183ea9ba4e84a3a45
C++
drismailari/cs409-2019-20-fall
/project-solution-1.cpp
UTF-8
6,858
3.71875
4
[]
no_license
// Güneş Büyükgönenç S011975 Department of Computer Science #include <iostream> #include <vector> #include <utility> /* Tiny Ranges Implementation by Furkan KIRAC * as part of CS409/509 - Advanced C++ Programming course in Ozyegin University * Supports transforming and filtering ranges and, * to<CONTAINER>() method for eagerly rendering the range into a CONTAINER. * Date: 20191222 */ // predicates namespace predicates { auto less_than = [](auto threshold) { return [=](auto value) { return value < threshold; }; }; auto greater_than = [](auto threshold) { return [=](auto value) { return value > threshold; }; }; auto all_of = [](const auto ... preds) { return [=](auto value) { return (preds(value) && ...); }; }; } namespace actions { auto multiply_by = [](auto coef) { return [=](auto value) { return value * coef; }; }; auto if_then = [](auto predicate, auto action) { return [=](auto value) { if(predicate(value)) value = action(value); return value; }; }; } namespace views { auto ints = [](int k=0) { return [k]() mutable { return k++; }; }; auto odds = []() { return [k=1]() mutable { auto r = k; k += 2; return r; }; }; } namespace algorithms { // ---[ RANGE implementation template<typename Iterator> struct Range { using LazyIterator = Iterator; // required for accessing the used Iterator type from other locations Iterator m_begin; Iterator m_end; auto begin() const { return m_begin; } auto end() const { return m_end; } }; template<typename Iterator> Range(Iterator, Iterator) -> Range<Iterator>; // ---[ TRANSFORM implementation template<typename Iterator, typename Callable> struct TransformingIterator : Iterator { using OriginalIterator = Iterator; // required for accessing the used Iterator type from other locations Callable callable; TransformingIterator(const Iterator iterator, const Callable& callable) : Iterator{iterator}, callable{callable} { } Iterator& get_orig_iter() { return ((Iterator&)*this); } double operator*() { return callable(*get_orig_iter()); } }; auto transform = [](const auto action) { return [=](auto&& container) { using Container = std::decay_t<decltype(container)>; using Iterator = typename Container::iterator; using IteratorX = TransformingIterator<Iterator, decltype(action)>; return Range{IteratorX{container.begin(), action}, IteratorX{container.end(), action}}; }; }; // ---[ FILTER implementation: implement your "Filtering Iterator" here // By overloading != operator instead of * operator, we get rid of the need to take the end iterator as a // constructor parameter, since != has it's own parameter. I also didn't need a function such as get_orig_iter // because even though I overload !=, I have == that I do not overload. Thus I used that to my advantage. // I didn't have such an option for * operator. template <typename Iterator, typename Callable> struct FilteringIterator : Iterator { Callable callable; FilteringIterator(const Iterator begin, const Callable& callable) : Iterator{begin}, callable{callable} { } // Overloading != operator for being able to start, end or even not enter the for loop which is in main auto operator!=(const FilteringIterator& other) { //This if will be triggered if begin equals to end before the first iteration if (*this == other) return false; // Looping until value satisfies the callable. Exiting this loop will indicate that // the value should be printed while (!callable(*(*this))) { // ++(*this); // If all the elements are traversed and don't satisfy the condition, then it should be the end of the for loop // which is in the main if (*this == other) return false; } return true; } }; // Exactly the same with transform lambda, with the exception of using FilteringIterator // instead of TransformingIterator auto filter = [](const auto predicate) { return [predicate](auto&& container) { using Container = std::decay_t<decltype(container)>; using Iterator = typename Container::iterator; using IteratorX = FilteringIterator<Iterator, decltype(predicate)>; return Range{IteratorX{container.begin(), predicate}, IteratorX{container.end(), predicate}}; }; }; // ---[ TO implementation: implement your "render into a container" method here // template template used for being able to take "std::vector" alone without supplying templates to vector from main // even though vector had 2 templates fields, I used ... for ease of use template <template <typename ...> typename CONTAINER> auto to() { return [](auto&& range) { // Extracting the type of the values of the range for constructing a container using DataType = decltype (*range.begin()); auto container = CONTAINER<DataType>(); for (const auto& v : range) container.push_back(v); return container; }; } } template<typename CONTAINER, typename RANGE> auto operator |(CONTAINER&& container, RANGE&& range) { return range(std::forward<CONTAINER>(container)); } using namespace predicates; using namespace actions; using namespace algorithms; int main(int argc, char* argv[]) { auto new_line = [] { std::cout << std::endl; }; auto v = std::vector<double>{}; auto odd_gen = views::odds(); for(int i=0; i<5; ++i) v.push_back(odd_gen() * 2.5); // v contains {2.5, 7.5, 12.5, 17.5, 22.5} here auto range = v | transform(if_then(all_of(greater_than(2.0), less_than(15.0)), multiply_by(20))); for(auto a : range) // transformation is applied on the range as the for loop progresses std::cout << a << std::endl; // original v is not changed. prints {50.0, 150.0, 250.0, 17.5, 22.5} new_line(); for(auto a : v | filter(greater_than(15))) // filter is applied lazily as the range is traversed std::cout << a << std::endl; // prints 17.5 and 22.5 to the console new_line(); for(auto a : v | filter(less_than(15))) // filter is applied lazily as the range is traversed std::cout << a << std::endl; // prints 2.5, 7.5 and 12.5 new_line(); auto u_transformed = std::vector<int>{10, 20, 30} | transform(multiply_by(2)) | to<std::vector>(); for(auto a : u_transformed) // u_transformed is an std::vector<int> automatically because of to<std::vector> std::cout << a << std::endl; return 0; }
true
30bbbe722432169a065696df32d952b8d18c9b68
C++
tractis/xades_library
/commons/src/XmlElement.h
UTF-8
3,615
2.578125
3
[]
no_license
/* * (C) Copyright 2006 VeriSign, Inc. * Developed by Sxip Identity * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _XMLELEMENT_H #define _XMLELEMENT_H #include <string> #include <vector> #include <libxml/parser.h> #include "Exceptions.h" using namespace std; /** * An XML element. * Encapsulates a LibXML2 XML node object. */ class XmlElement { public: /** * Construct an empty element object. */ XmlElement (); /** * Copy an existing raw element. */ XmlElement (xmlNodePtr copyNode); /** * Destroy element object. * Frees element object if one was created. */ ~XmlElement (); /** * Get the internal representation of the XML element. * @return Pointer to the XML node structure */ xmlNodePtr getNode (); /** * Get the name of the element. * @return the name of the element node * @throws XMLError if the node is invalid */ string getTagName (); /** * Search and get the value of an attribute associated to a node. * This does the entity substitution. * @param name the attribute name * @return the attribute value or null if not found * @throws XMLError if the node is invalid */ string getAttribute (string name); /** * Search and get the value of an attribute associated to a node. * This attribute has to be anchored in the namespace * specified. This does the entity substitution. * @param name the attribute name * @param nameSpace the URI of the namespace * @return the attribute value or null if not found * @throws XMLError if the node is invalid */ string getAttribute (string name, string nameSpace); /** * Build a structure based Path for the node. * @return a path in string form * @throws XMLError if the node is invalid */ string getNodePath (); /// @cond NO_INTERFACE /** * Copy an existing element object. * @param element XmlElement class to be copied */ XmlElement(const XmlElement& element); /** * Assignment operator creates duplicate element. * @param element XmlElement class to be copied * @return Copied element */ const XmlElement& operator= (const XmlElement& element); /** * @return true if valid, false if no element */ operator int () { return (node != NULL) && (node->type == XML_ELEMENT_NODE); } /** * @return false if valid, true if no element */ int operator! () { return (node == NULL) || (node->type != XML_ELEMENT_NODE); } /** * Cast the element object to the xmlNodePtr. * @return Pointer to the XML element structure */ operator xmlNodePtr () { return getNode(); } protected: /** * The internal representation of the XML node. */ xmlNodePtr node; /** * Free the internal representation of the XML node. */ void freeNode(); /// @endcond }; #include "countptr.h" typedef CountPtrTo<XmlElement> XmlElementPtr; #endif
true
b56df83f2c4aa836c98083bd2834febf808eb425
C++
ytz12345/2019_ICPC_Trainings
/Opentrains_Contest/10293/K.cpp
UTF-8
842
2.65625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int t, n; int main() { ios::sync_with_stdio(false); cin >> t; while (t --) { cin >> n; if (n == 3) { printf("%d\n", 3); for (int i = 0; i < 3; i ++) { printf("%d %d\n", i, 0); } } else if (n == 4) { printf("%d\n%d %d\n", 7, 0, 1); for (int i = 1;i < n; i ++) { printf("%d %d\n", i, 0); printf("%d %d\n", i, 1); } } else { printf("%d\n", n * 3); for (int i = 0; i < n; i ++) { printf("%d %d\n", i, i % (n - 2)); printf("%d %d\n", i, (i + 1) % (n - 2)); printf("%d %d\n", i, (i + 2) % (n - 2)); } } } return 0; }
true
bbc28e2cbd70cbd6b46f742d99447b98b4feb1db
C++
jinpyojeon/TRIN_EARL
/do_not_builds/turtlebot_apps/software/pano/pano_core/include/pano_core/Projector.h
UTF-8
6,633
2.65625
3
[]
no_license
#ifndef PANO_PROJECTOR_H_ #define PANO_PROJECTOR_H_ #include <opencv2/core/core.hpp> #include <opencv2/imgproc/imgproc.hpp> namespace pano { class Projector { friend class SparseProjector; cv::Mat K, Kinv; cv::Size outimage_size,input_image_sz; cv::Mat spherical_coords; cv::Mat remap1, remap2; cv::Mat R; std::vector<cv::Mat> working_mats; public: Projector(){} /** \brief * \param output_size size of final spherical projection image width = 2 pi height = pi * center pixel is 0,0 essentially, with x going from -pi to pi and y going from * -pi/2 to pi/2 ???TODO:define direction of y * */ Projector(const cv::Size& output_size, float theta_range = 2 * CV_PI, float phi_range = CV_PI); /** \brief Sets up the projector to remap based on the given R * and K. Call this before calling any of the member project functions */ void setSRandK(const cv::Size& inputsz,const cv::Mat& R, const cv::Mat& K); void projectMat(const cv::Mat& m, cv::Mat& outimage, int filltype = cv::BORDER_TRANSPARENT,const cv::Scalar& value = cv::Scalar()); ~Projector(void); /*** static members *****/ /** \brief * \param sphere_size * \param theta_range the longitudinal range of the spherical cooridinates produced * \param phi_range the latitudinal range of the coords produced * \return a Mat(sphere_size, cv::DataType<cv::Point3d>::type) where every point in the mat lies on the unit sphere, in the * lat long ranges specified. So to go from spherical coorinate (theta,phi) to (x,y,z) just look in the mat.at(phi,theta) * <code> * cv::Point3d& point = sphere.at<cv::Point3d> (phi, theta) * </code> */ static cv::Mat createSphericalCoords(const cv::Size& sphere_size = cv::Size(200,200), float theta_range = 2 * CV_PI, float phi_range = CV_PI); static void createSphericalCoords(const cv::Size& sphere_size, float theta_0,float theta_1, float phi_0,float phi_1, cv::Mat& spherical_coords); /** Like createSphereicalCoords but with row of 1's appended so * 4x4 matrices can operate on it */ static cv::Mat createHomogSphrCoords(const cv::Size& sphere_size = cv::Size(200,200), float theta_range = 2 * CV_PI, float phi_range = CV_PI); static void getSphereMask(const cv::Mat& onezies, const cv::Mat& remap1, const cv::Mat&remap2, cv::Mat& mask); static void projectImage(const cv::Mat& image, const cv::Mat& remap1, const cv::Mat&remap2, cv::Mat & outputimage,int filltype = cv::BORDER_TRANSPARENT, const cv::Scalar& border_value = cv::Scalar()); /** create a remap matrix that is the size of the output image * * \param K camera calibration matrix * \param R the rotation to calc the remap matrix - identity means the center pixel of the output image, * or the vector (0,0,1) * \param remap1 out parameter, that will hold a matrix of size given by the projector of outimage * see the opencv documentation for remap * http://opencv.willowgarage.com/documentation/cpp/geometric_image_transformations.html?highlight=remap#remap *\param remap2 out parameter, these are both necessary to pass to the project image function. the remap1 and remap2 are generated * using the cv::convertMaps function, for fixed point math, supposedly faster * intended use of the remapMat matrix, this will leave outliers alone(transparent) * cv::remap(img, outputimge, remapMat, cv::Mat(), cv::INTER_LINEAR); * * to get a */ static void getSphereRMap(const cv::Mat& K, const cv::Mat& R, cv::Mat& remap1, cv::Mat&remap2, const cv::Mat& spherical_points, const cv::Size& output_size); static void getSphereRMapMask(const cv::Mat& K, const cv::Mat& R, cv::Mat& remap, cv::Mat& mask, const cv::Mat& spherical_points,cv::Mat& tm); /** create forward and backward maps to send and image described by * calibration matrix K into spherical coords. Image is treated as lying * on the sphere with flat distribution of rads per pixel. G is 4x4 matrix. */ static void getSphereGMap(const cv::Mat& K, const cv::Mat& G, cv::Mat& remap1, cv::Mat&remap2, const cv::Mat& homog_sphr_coords, const cv::Size& output_size); private: static void getSphereRMap(const cv::Mat& K, const cv::Mat& R, cv::Mat& remap1, cv::Mat&remap2, const cv::Mat& spherical_points, const cv::Size& output_size, std::vector<cv::Mat>& working_mats); static void getSphereGMap(const cv::Mat& K, const cv::Mat& G, cv::Mat& remap1, cv::Mat&remap2, const cv::Mat& homog_sphr_coords, const cv::Size& output_size, std::vector<cv::Mat>& working_mats); }; class SparseProjector{ public: SparseProjector(){} SparseProjector(const cv::Size& output_size, const cv::Size& n_grids); /** \brief Sets up the projector to remap based on the given R * and K. Call this before calling any of the member project functions */ void setSRandK(const cv::Size& inputsz,const cv::Mat& R, const cv::Mat& K, std::vector<int>& roi_ids); void projectMat(int roi_id, const cv::Mat& m, cv::Mat& outimage, int filltype = cv::BORDER_TRANSPARENT,const cv::Scalar& value = cv::Scalar()); void setWorkingRoi(int id); cv::Rect getRoi(int id) const{ return rois_[id]; } private: cv::Size output_size_; cv::Mat spherical_coords_small_; cv::Size grids_; std::vector<cv::Rect> rois_; std::vector<cv::Rect> small_rois_; cv::Mat remap_,mask_,spherical_coords_,tm_,remap1_,remap2_; int workingid_; cv::Mat R_,K_; }; } #endif
true
f08295201c5656b8920d2929cebbbbb0597f8240
C++
Goldenboycoder/NetPrint
/User.h
UTF-8
1,022
3.328125
3
[ "MIT" ]
permissive
#pragma once #include <iostream> #include <string> class User { private: int m_id; //Idenftification Number std::string m_password; //Password short m_priority; //Printing Priority (Low 1, Medium 2, High 3) short m_privLevel; //Privileges (Limited User 1 / Normal User 2 / Admin 3) public: User() {} User(int a_id, std::string a_password, short a_priority, short a_privlevel) { setId(a_id); setPassword(a_password); setPriority(a_priority); setPrivLevel(a_privlevel); } void setId(int a_id) { m_id = a_id; } void setPassword(std::string a_password) { m_password = a_password; } void setPriority(short a_priority) { m_priority = a_priority; } void setPrivLevel(short a_privLevel) { m_privLevel = a_privLevel; } int getId() { return m_id; } short getPriority() { return m_priority; } short getPrivLevel() { return m_privLevel; } std::string getPassword() { return m_password; } };
true
daa8cf0ede9349ba48e3660e49bd8e4f05c33cfc
C++
linsallyzhao/earlyobjects-exercises
/2015/chapter_6/examples/6_4.cpp
UTF-8
384
3.390625
3
[]
no_license
#include <iostream> void deeper() { std::cout << "I am now inside the function deeper. \n"; } void deep() { std::cout << "I am now inside the function deep. \n"; deeper(); std::cout << "Now I am back in deep. \n"; } int main() { std::cout << "I am starting in function main. \n"; deep(); std::cout << "Back in function main again. \n"; return 0; }
true
e18c10be7b6f03ca6b93423a754541c91a4f3c9f
C++
timi-liuliang/echo
/thirdparty/mlpack/core/optimizers/sgd/update_policies/gradient_clipping.hpp
UTF-8
3,540
3.140625
3
[ "MIT" ]
permissive
/** * @file gradient_clipping.hpp * @author Konstantin Sidorov * * Gradient clipping update wrapper. * * mlpack is free software; you may redistribute it and/or modify it under the * terms of the 3-clause BSD license. You should have received a copy of the * 3-clause BSD license along with mlpack. If not, see * http://www.opensource.org/licenses/BSD-3-Clause for more information. */ #ifndef MLPACK_CORE_OPTIMIZERS_SGD_GRADIENT_CLIPPING_HPP #define MLPACK_CORE_OPTIMIZERS_SGD_GRADIENT_CLIPPING_HPP #include <mlpack/prereqs.hpp> namespace mlpack { namespace optimization { /** * Interface for wrapping around update policies (e.g., VanillaUpdate) * and feeding a clipped gradient to them instead of the normal one. * (Clipping here is implemented as * \f$ g_{\text{clipped}} = \max(g_{\text{min}}, \min(g_{\text{min}}, g))) \f$.) * * @tparam UpdatePolicy A type of UpdatePolicy that sould be wrapped around. */ template<typename UpdatePolicyType> class GradientClipping { public: /** * Constructor for creating a GradientClipping instance. * * @param minGradient Minimum possible value of gradient element. * @param maxGradient Maximum possible value of gradient element. * @param updatePolicy An instance of the UpdatePolicyType * used for actual optimization. */ GradientClipping(const double minGradient, const double maxGradient, UpdatePolicyType& updatePolicy) : minGradient(minGradient), maxGradient(maxGradient), updatePolicy(updatePolicy) { // Nothing to do here } /** * The Initialize method is called by SGD Optimizer method before the start of * the iteration update process. Here we just do whatever initialization * is needed for the actual update policy. * * @param rows Number of rows in the gradient matrix. * @param cols Number of columns in the gradient matrix. */ void Initialize(const size_t rows, const size_t cols) { updatePolicy.Initialize(rows, cols); } /** * Update step. First, the gradient is clipped, and then the actual update * policy does whatever update it needs to do. * * @param iterate Parameters that minimize the function. * @param stepSize Step size to be used for the given iteration. * @param gradient The gradient matrix. */ void Update(arma::mat& iterate, const double stepSize, const arma::mat& gradient) { // First, clip the gradient. arma::mat clippedGradient = arma::clamp(gradient, minGradient, maxGradient); // And only then do the update. updatePolicy.Update(iterate, stepSize, clippedGradient); } //! Get the update policy. UpdatePolicyType& UpdatePolicy() const { return updatePolicy; } //! Modify the update policy. UpdatePolicyType& UpdatePolicy() { return updatePolicy; } //! Get the minimum gradient value. double MinGradient() const { return minGradient; } //! Modify the minimum gradient value. double& MinGradient() { return minGradient; } //! Get the maximum gradient value. double MaxGradient() const { return maxGradient; } //! Modify the maximum gradient value. double& MaxGradient() { return maxGradient; } private: //! Minimum possible value of gradient element. double minGradient; //! Maximum possible value of gradient element. double maxGradient; //! An instance of the UpdatePolicy used for actual optimization. UpdatePolicyType updatePolicy; }; } // namespace optimization } // namespace mlpack #endif
true
7e37c64660af9936c8766fe571f50b7153c3f1ea
C++
bjut-hz/basics
/leetcode_c++/306.additive-number.cpp
UTF-8
1,672
3.359375
3
[]
no_license
/* * @lc app=leetcode id=306 lang=cpp * * [306] Additive Number */ // @lc code=start class Solution { public: // bool isAdditiveNumber(string num) { // for (int i = 0; i < num.size(); ++i) { // if (i >= 1 && '0' == num[0]) continue; // for (int j = i + 1; j < num.size(); ++j) { // if (j - i > 1 && '0' == num[i + 1]) continue; // string a_str = num.substr(0, i + 1); // string b_str = num.substr(i + 1, j - i); // long long a = stoll(a_str); // long long b = stoll(b_str); // long long next = a + b; // string sum_str = a_str + b_str + to_string(next); // while (sum_str.size() < num.size()) { // a = b; // b = next; // next = a + b; // sum_str += to_string(next); // } // if (sum_str == num) return true; // } // } // return false; // } bool isAdditiveNumber(string num) { vector<long long> out; bool res = false; helper(num, out, 0, res); return res; } void helper(string& num, vector<long long>& out, int start, bool& res) { if (res == true) return; if (start == num.size()) { if (out.size() >= 3) { res = true; } return; } for (int i = start; i < num.size(); ++i) { string a_str = num.substr(start, i - start + 1); if ((a_str.size() > 1 && a_str[0] == '0') || a_str.size() > 19) { break; } long long cur_num = stoll(a_str); int n = out.size(); if (n >= 2 && out[n - 1] + out[n - 2] != cur_num) { continue; } out.push_back(cur_num); helper(num, out, i + 1, res); out.pop_back(); } } }; // @lc code=end
true
eb9f013ab7c8a74452bd6297f56ae90d1bf24622
C++
ShadowNicky/Lerning-C
/4 function (a,b)/4.1 function (a,b)/function/function.cpp
UTF-8
1,800
3.421875
3
[]
no_license
#include <iostream> //Потоковый ввод/вывод #include <iomanip> //Форматный ввод/вывод #include <cmath> //Математическая библиотека #include "stdio.h" //Включение директив процессора using namespace std; //Стандартное пространство имен constexpr auto PI = 3.1415926535; //Спецификатор constexpr, с помощью него можно создавать переменные и функции которые будут рассчитаны на этапе компиляции double z(double x, double y) //Вспомогательная функция { double result; result = (sqrt(pow(sin(x), 2) + 3 * y) * pow(x + log(y + PI), 2)) / (pow(x + pow(y, 2), 2) * (pow(x, 2) + y)); return result; } int main() //Основная функция программы { setlocale(LC_ALL, "Russian"); //Руссфикатор double a, b, c; //Инициализация переменных for (int i = 1; i <= 4; i++) //Цикл на 4 итерации, чтобы не выходя из программы проверить все 4 пары значений { cout << "Введите значения a и b" << endl; //Сообщение пользователю cin >> a >> b; //Считывание введенных значений c = z((a + sqrt(b)), (pow(a, 2) + b)) + z((a * b + 1), (3 * a + pow(b, 2))); cout << "f(a, b) = " << fixed << setprecision(4) << c << endl; //Форматный вывод cout << endl; } system("pause"); return 0; }
true
b6b82a04b27408b0f155f6376458fa860e34742b
C++
ZigorSK/Pract
/Matrix.cpp
WINDOWS-1251
2,012
2.984375
3
[]
no_license
#include"Matrix.h" Matrix::Matrix() { for (int i = 0; i < 5; i++) for (int j = 0; j < 5; j++) Matr[i][j] = 0; } Matrix::~Matrix() { // F2 ofstream out("F2.txt", ios::app); for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { out << setw(20) << Matr[i][j]; } out << endl; } float sum_d = 0; for (int i = 0; i < 5; i++) sum_d += Matr[i][i]; out <<" :" << sum_d << endl << endl << endl <<endl; out.close(); } Matrix & Matrix::operator = (int * arr) { int max_x, i, j; float *M = &Matr[0][0]; _asm { // mov esi, arr mov eax, [esi] inc esi inc esi inc esi inc esi mov ecx, 4 m0: cmp eax, [esi] jns k mov eax, [esi] k: inc esi inc esi inc esi inc esi loop m0 mov max_x, eax // finit mov esi, arr// esi arr mov ebx, M// edi Matr mov i, 0 mov ecx, 5 m1: push ecx mov j, 0 mov ecx, 5 // m2: // Yij Yij = (max(Xi) - Xi)/ Xj(asm) fild max_x mov ax, 4 mul i//ax = i*4 add esi, eax fild [esi] sub esi, eax fsubp st(1), st// st1, st0 mov ax, 4 mul j//ax = i*4 add esi, eax fild[esi] sub esi, eax fdivp st(1), st// st1 st st(1), st0 //fxch st(1)// st(1) anb st //edi+j*4+i*20 mov edx, 5 mov ax, 4 mul j push eax mov ax, 20 mul i pop edx add eax, edx add ebx, eax // fstp [ebx] sub ebx, eax inc j loop m2 // pop ecx inc i loop m1 } return *this; }
true
d883fa652bd4d723a114e26210dd56269fcc51ad
C++
oonarici/xstream
/abstractwriter.cpp
UTF-8
1,709
3.078125
3
[]
no_license
#include "abstractwriter.h" void AbstractWriter::write(const bool &v) { const void *ptr = &v; this->writeBase(ptr, sizeof(bool)); } void AbstractWriter::write(const char &v) { const void *ptr = &v; this->writeBase(ptr, sizeof(char)); } void AbstractWriter::write(const unsigned char &v) { const void *ptr = &v; this->writeBase(ptr, sizeof(unsigned char)); } void AbstractWriter::write(const short &v) { const void *ptr = &v; this->writeBase(ptr, sizeof(short)); } void AbstractWriter::write(const unsigned short &v) { const void *ptr = &v; this->writeBase(ptr, sizeof(unsigned short)); } void AbstractWriter::write(const int &v) { const void *ptr = &v; this->writeBase(ptr, sizeof(int)); } void AbstractWriter::write(const unsigned int &v) { const void *ptr = &v; this->writeBase(ptr, sizeof(unsigned int)); } void AbstractWriter::write(const long &v) { const void *ptr = &v; this->writeBase(ptr, sizeof(long)); } void AbstractWriter::write(const unsigned long &v) { const void *ptr = &v; this->writeBase(ptr, sizeof(unsigned long)); } void AbstractWriter::write(const float &v) { const void *ptr = &v; this->writeBase(ptr, sizeof(float)); } void AbstractWriter::write(const double &v) { const void *ptr = &v; this->writeBase(ptr, sizeof(double)); } void AbstractWriter::write(const long double &v) { const void *ptr = &v; this->writeBase(ptr, sizeof(long double)); } void AbstractWriter::write(const std::string &v) { this->write((unsigned int)v.size()); this->writeBase(v.c_str(), v.size()); } void AbstractWriter::write(const void *data, int length){ this->writeBase(data, length); }
true
f24bd1777d49447ed6a7391aac0d9bf8080b7be9
C++
qianl15/PDC-2016-project
/baseline/SA_TSP.cpp
UTF-8
5,940
2.921875
3
[]
no_license
/* Simulated Annealing algorithm for Traveling Salesman Problem @@ baseline version: no parallel optimization, single thread Input: xxx.tsp file Output: optimal value (total distance) & solution route: permutation of {1, 2, ..., N} */ #include <iostream> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #include <algorithm> #include <sys/time.h> #define MAXITER 20 // Proposal 20 routes and then select the best one #define THRESH1 0.1 // Threshold 1 for the strategy #define THRESH2 0.89 // Threshold 2 for the strategy #define RELAX 40000 // The times of relaxation of the same temperature #define ALPHA 0.999 // Cooling rate #define INITEMP 99.0 // Initial temperature #define STOPTEMP 0.001 // Termination temperature #define MAXLAST 3 // Stop if the tour length keeps unchanged for MAXLAST consecutive temperature #define MAXN 1000 // only support N <= 1000 using namespace std; float minTourDist = -1; // The distance of shortest path int *minTour = NULL; // The shortest path int N = 0; // Number of cities float dist[MAXN][MAXN] = {}; // The distance matrix, use (i-1) instead of i class rand_x { unsigned int seed; public: rand_x(int init) : seed(init) {} int operator()(int limit) { int divisor = RAND_MAX/(limit+1); int retval; do { retval = rand_r(&seed) / divisor; } while (retval > limit); return retval; } }; /* load the data */ void loadFile(char* filename) { FILE *pf; pf = fopen(filename, "r"); if (pf == NULL) { printf("Cannot open the file!\n"); exit(1); } char buff[200]; fscanf(pf, "NAME: %[^\n]s", buff); printf("%s\n", buff); fscanf(pf, "\nTYPE: TSP%[^\n]s", buff); printf("%s\n", buff); fscanf(pf, "\nCOMMENT: %[^\n]s", buff); printf("%s\n", buff); fscanf(pf, "\nDIMENSION: %d", &N); printf("The N is: %d\n", N); fscanf(pf, "\nEDGE_WEIGHT_TYPE: %[^\n]s", buff); printf("the type is: %s\n", buff); memset(dist, 0, sizeof(dist)); if (strcmp(buff, "EUC_2D") == 0) { fscanf(pf, "\nNODE_COORD_SECTION"); float nodeCoord[MAXN][2] = {}; int nid; float xx, yy; for (int i = 0; i < N; ++i) { fscanf(pf, "\n%d %f %f", &nid, &xx, &yy); nodeCoord[i][0] = xx; nodeCoord[i][1] = yy; } float xi, yi, xj, yj; for (int i = 0; i < N; ++i) { for (int j = i + 1; j < N; ++j) { xi = nodeCoord[i][0]; yi = nodeCoord[i][1]; xj = nodeCoord[j][0]; yj = nodeCoord[j][1]; dist[i][j] = (float)sqrt((xi - xj) * (xi - xj) + (yi - yj) * (yi - yj)); dist[j][i] = dist[i][j]; } } } else if (strcmp(buff, "EXPLICIT") == 0) { fscanf(pf, "\nEDGE_WEIGHT_FORMAT: %[^\n]s", buff); fscanf(pf, "\n%[^\n]s", buff); char *disps = strstr(buff, "DISPLAY_DATA_TYPE"); if (disps != NULL) { fscanf(pf, "\nEDGE_WEIGHT_SECTION"); } float weight; for (int i = 0; i < N; ++i) { for (int j = 0; j <= i; ++j) { fscanf(pf, "%f", &weight); dist[i][j] = weight; dist[j][i] = weight; } } } return; } /* Calculate the length of the tour */ float tourLen(int *tour) { if (tour == NULL) { printf("tour not exist!\n"); return -1; } float cnt = 0; for (int i = 0; i < N - 1; ++i) { cnt += dist[tour[i]][tour[i+1]]; } cnt += dist[tour[N-1]][tour[0]]; return cnt; } /* the main simulated annealing function */ void saTSP(int* tour) { float currLen = tourLen(tour); float temperature = INITEMP; float lastLen = currLen; int contCnt = 0; // the continuous same length times while (temperature > STOPTEMP) { temperature *= ALPHA; /* stay in the same temperature for RELAX times */ unsigned int s = time(0); s = s + random(); for (int i = 0; i < RELAX; ++i) { /* Proposal 1: Block Reverse between p and q */ int p = rand_r(&s)%N, q = rand_r(&s)%N; // If will occur error if p=0 q=N-1... if (abs(p - q) == N-1) { q = rand_r(&s)%(N-1); p = rand_r(&s)%(N-2); } if (p == q) { q = (q + 2) % N; } if (p > q) { int tmp = p; p = q; q = tmp; } int p1 = (p - 1 + N) % N; int q1 = (q + 1) % N; int tp = tour[p], tq = tour[q], tp1 = tour[p1], tq1 = tour[q1]; float delta = dist[tp][tq1] + dist[tp1][tq] - dist[tp][tp1] - dist[tq][tq1]; /* whether to accept the change */ if ((delta < 0) || ((delta > 0) && (exp(-delta/temperature) > (float)rand_r(&s)/RAND_MAX))) { currLen = currLen + delta; int mid = (q - p) >> 1; int tmp; for (int k = 0; k <= mid; ++k) { tmp = tour[p+k]; tour[p+k] = tour[q-k]; tour[q-k] = tmp; } //currLen = tourLen(tour); } } if (fabs(currLen - lastLen) < 1e-3) { contCnt += 1; if (contCnt >= MAXLAST) { //printf("unchanged for %d times1!\n", contCnt); break; } } else contCnt = 0; lastLen = currLen; } return; } int main(int argc, char **argv) { if (argc < 2) { printf("Please enter the filename!\n"); return 0; } else { loadFile(argv[1]); } struct timeval start, stop; gettimeofday(&start, NULL); srandom(time(0)); minTour = (int *)malloc(sizeof(int) * N); int *currTour = (int *)malloc(sizeof(int) * N); unsigned int s = time(0); for (int i = 0; i < MAXITER; ++i) { for (int j = 0; j < N; ++j) currTour[j] = j; rand_x rg(s); random_shuffle(currTour, currTour + N, rg); saTSP(currTour); float currLen = tourLen(currTour); //printf("currLen is: %f\n", currLen); if ((minTourDist < 0) ||(currLen < minTourDist)) { minTourDist = currLen; for (int j = 0; j < N; ++j) { minTour[j] = currTour[j]; } } } gettimeofday(&stop, NULL); // ------------- Print the result! ----------------- int tottime = stop.tv_sec - start.tv_sec; int timemin = tottime / 60; int timesec = tottime % 60; printf("Total time usage: %d min %d sec. \n", timemin, timesec); printf("The shortest length is: %f\n And the tour is: \n", minTourDist); for (int i = 0; i < N; ++i) { printf("%d \n", minTour[i]+1); } free(minTour); free(currTour); return 0; }
true
b4cbc0a672283e8b7d80eb33205d4ad4addfd382
C++
wwllww/LiveStream_MultiIntance
/UltraLiveApi/V1.1/Parry.cpp
GB18030
2,887
2.90625
3
[]
no_license
#include "PArry.h" #include "Error.h" #include "OperatNew.h" #ifdef OPERATOR_NEW #define new OPERATOR_NEW #pragma message("new(__FILE__,__LINE__)") #endif #ifndef MAX_SIZE #define MAX_SIZE 2000 #endif CPArry::CPArry(int DynamicFree):m_DynamicFree(DynamicFree) { m_Data = new void *[MAX_SIZE]; size = 0; } CPArry::CPArry():m_DynamicFree(0) { m_Data = new void *[MAX_SIZE]; size = 0; } CPArry::~CPArry() { Log::writeMessage(LOG_RTSPSERV, 1, "LiveSDK_Log:%s ʼ", __FUNCTION__); clear(); Log::writeMessage(LOG_RTSPSERV, 1, "LiveSDK_Log:%s ", __FUNCTION__); } bool CPArry::Add(CPObject *Data) { if(!Data || size >= MAX_SIZE) return false; m_Data[size] = Data; ++size; return true; } CPObject* CPArry::GetAt(int Index) const { if(Index >= size) { return NULL; } if(m_Data[Index]) return (CPObject*)m_Data[Index]; return NULL; } int CPArry::GetSize() const { return size; } bool CPArry::insert(CPObject *Data, int Index) { if (Index > size || !Data || size >= MAX_SIZE) { BUTEL_THORWERROR("ݲϷIndex = %d,size = %d,Data = %p", Index,size,Data); } void *TemData = NULL; if(1 == size) { ++size; if(0 == Index) { TemData = m_Data[0]; m_Data[0] = Data; m_Data[1] = TemData; return true; } m_Data[Index] = Data; return true; } else { for(int i = size - 1; i >= Index; --i ) { m_Data[i + 1] = m_Data[i]; } m_Data[Index] = Data; ++size; } return true; } void CPArry::clear() { if(m_DynamicFree) { for(int i = 0;i < size; ++i) delete (CPObject*)m_Data[i]; } delete [] m_Data; } bool CPArry::erase(CPObject *Data, bool bDelete) { if (!Data) return false; bool bFind = false; for (int i = 0; i < size; ++i) { if (m_Data[i] == Data) { bFind = true; for (int j = i + 1; j < size; ++j) { m_Data[j - 1] = m_Data[j]; } --size; break; } } if (!bFind) return false; if (bDelete) delete Data; return true; } bool CPArry::erase(int Index, bool bDelete) { if (Index < 0 || Index >= size) return false; if (bDelete) delete (CPObject*)m_Data[Index]; for (int i = Index + 1; i < size; ++i) { m_Data[i - 1] = m_Data[i]; } --size; return true; } CPObject* CPArry::operator[](unsigned int Index) { if(Index < 0 || Index >= size) { BUTEL_THORWERROR("The Arry is out of range at %d",Index); } return (CPObject*)m_Data[Index]; } void CPArry::SwapValues(int ValA, int ValB) { if (ValA < 0 || ValA >= size || ValB < 0 || ValB >= size) { BUTEL_THORWERROR("The Arry is out of range at %d,%d", ValA, ValB); } void *Tem = m_Data[ValA]; m_Data[ValA] = m_Data[ValB]; m_Data[ValB] = Tem; }
true
103e8afd56cb57c27e9120bdbd23aa9a203baa3d
C++
dimchanov/Prac_sem04
/Prac05/mz04.cpp
UTF-8
927
2.78125
3
[]
no_license
#include <algorithm> #include <vector> #include <utility> #include <iostream> template <typename It1, typename It2> auto myremove(It1 begin_idx, It1 end_idx, It2 begin_elem, It2 end_elem) { std::vector<int> copy_idx(begin_idx, end_idx); std::sort(copy_idx.begin(), copy_idx.end()); auto nunq = std::unique(copy_idx.begin(), copy_idx.end()); copy_idx.erase(nunq, copy_idx.end()); auto it_elem = begin_elem; int count(0); auto res = begin_elem; int flag = 1; while (it_elem != end_elem) { flag = 1; auto it_copy_idx = copy_idx.begin(); while (it_copy_idx != copy_idx.end()){ if (*it_copy_idx == count) { flag = 0; break; } ++it_copy_idx; } if (flag) { *res = std::move(*it_elem); ++res; } ++count; ++it_elem; } return res; }
true
eb57bb966138133b4ea870bc451fdd491e16cbcd
C++
manu05X/ProgramFiles
/InterviewBit/Two Pointer/CountingTriangles.cpp
UTF-8
938
3.546875
4
[]
no_license
/* Counting Triangles You are given an array of N non-negative integers, A0, A1 ,..., AN-1. Considering each array element Ai as the edge length of some line segment, count the number of triangles which you can form using these array values. Notes: You can use any value only once while forming each triangle. Order of choosing the edge lengths doesn't matter. Any triangle formed should have a positive area. Return answer modulo 109 + 7. For example, A = [1, 1, 1, 2, 2] Return: 4 */ # define mod 1000000007 int Solution::nTriang(vector<int> &A) { int count=0; if(!A.size()) return count; sort(A.begin(),A.end()); for(int i=A.size()-1;i>=0;i--) { int l=0,r=i-1; while(l<r) { if(A[l]+A[r]>A[i]) { count=(count+(r-l)%mod)%mod; r--; } else l++; } } return count; }
true
cfa54b06bad5df450692794b10aa42f971b3fd82
C++
JakobYde/Codewars
/C++/4/Square into Squares. Protect trees!/Solution.cpp
UTF-8
1,238
3.71875
4
[]
no_license
#include <vector> #include <math.h> class Decomp { public: static std::vector<long long> decompose(long long n) { long long nSquared = n * n; std::vector<long long> decomposition; int startIndex = 0; //If a decomposition exists, return it in reverse, else return {}. if (findDecomp(nSquared, n - 1, decomposition, startIndex)) { std::reverse(decomposition.begin(), decomposition.end()); return decomposition; } else return {}; } //Recursive function to find the decomposition. //Returns true if a decomposition exists, false if not. static bool findDecomp(long long nSquared, long long n, std::vector<long long>& decomp, int index) { for (long long i = n; i > 0; --i) { long long nSquaredTemp = i * i; long long rest = nSquared - nSquaredTemp; if (rest >= 0) { decomp.push_back(i); if (rest == 0) return true; //Call itself using the squareroot of the rest to start from the //highest possible number, given that the square of the last number //was less than nSquared. if (findDecomp(rest, floor(sqrt(rest)) < i - 1 ? floor(sqrt(rest)) : i - 1, decomp, index + 1)) return true; //Reset else decomp.erase(decomp.begin() + index); } } return false; } };
true
b516165791e48b8e4a7090d77789b3995f39f8f7
C++
Mikalai/punk_project_a
/source/badziaha/time_dependent.h
UTF-8
342
2.625
3
[]
no_license
#ifndef _H_TIME_DEPENDENT #define _H_TIME_DEPENDENT #include <chrono> class TimeDependent { public: TimeDependent(); virtual ~TimeDependent(); virtual void update(); float getTimeStep() const { return m_dt; } private: std::chrono::high_resolution_clock::time_point m_last_update; float m_dt{ 0 }; }; #endif // _H_TIME_DEPENDENT
true
85e6d481a0ef771a817b4357ebfc88a2e34aed07
C++
kathteng/Calculus_Calculator
/Function.cpp
UTF-8
3,594
3.203125
3
[]
no_license
#include "Function.h" char Function::variable; Function::Term::Term() { coefficient = 0; varIndex = 0; power = 0; powerSignIndex = 0; hasVariable = true; } Function::Term::Term(std::string term_) { term = term_; hasVariable = true; FindCoefficient(); FindPower(); } void Function::Term::FindCoefficient() { FindVariable(term); varIndex = term.find(variable); // If term is a constant, the whole term is a coefficient if (varIndex == std::string::npos) { hasVariable = false; coefficient = stoi(term); } else if (varIndex == 0) coefficient = 1; else coefficient = stoi(term.substr(0, varIndex)); } void Function::Term::FindPower() { powerSignIndex = term.find('^'); if (powerSignIndex == std::string::npos) { if (hasVariable == false) power = 0; else power = 1; } else power = stoi(term.substr(powerSignIndex + 1, term.length() - powerSignIndex + 1)); } Function::Function() { numTerms = 0; variable = 'x'; } Function::Function(std::string function_) { function = function_; SeparateTerms(); FindVariable(function); } void Function::SeparateTerms() { numTerms = 0; int startIndex = 0; int endIndex; std::string tempTerm; while (startIndex < function.length()) { endIndex = function.find_first_of("+-", startIndex); if (endIndex != std::string::npos) { tempTerm = function.substr(startIndex, endIndex - startIndex - 1); Term t(tempTerm); terms.push_back(t); numTerms++; startIndex = endIndex + 2; // Plus 2 to account for the space after +/- } else if (endIndex == std::string::npos) { tempTerm = function.substr(startIndex, function.length() - startIndex); Term t(tempTerm); terms.push_back(t); numTerms++; break; } } } void Function::FindVariable(std::string equation) { for (unsigned int i = 0; i < equation.length(); i++) { if (isalpha(equation[i])) { variable = equation[i]; break; } } } void Function::UpdateTerms() { for (unsigned int i = 0; i < terms.size(); i++) { if (terms[i].hasVariable == true) { if (terms[i].varIndex == 0) { terms[i].term.insert(0, std::to_string(terms[i].coefficient)); terms[i].powerSignIndex = terms[i].term.find('^'); } else { terms[i].term.replace(0, terms[i].varIndex, std::to_string(terms[i].coefficient)); terms[i].powerSignIndex = terms[i].term.find('^'); } if (terms[i].power == 0) { if (terms[i].varIndex == 0) terms[i].term.replace(0, std::string::npos, "1"); else terms[i].term.erase(terms[i].varIndex, std::string::npos); } else if (terms[i].power == 1) terms[i].term.erase(terms[i].powerSignIndex, std::string::npos); else terms[i].term.replace(terms[i].powerSignIndex + 1, terms[i].term.length() - terms[i].powerSignIndex, std::to_string(terms[i].power)); } } } void Function::UpdateFunction() { UpdateTerms(); if (numTerms == 1) { if (terms[0].term.length() == 0) function = "0"; else function = terms[0].term; } else { int startIndex = 0; int index = 0; unsigned int i = 0; while (startIndex < function.length() && i < terms.size()) { if (terms[i].term.length() == 0) { function.erase(index, std::string::npos); break; } index = function.find_first_of("+-", startIndex); function.replace(startIndex, index - startIndex - 1, terms[i].term); index = function.find_first_of("+-", startIndex); startIndex = index + 2; i++; } } }
true
36e51ebffd86722c7169a7ca6cc7aa86e0c842dc
C++
ranjiewwen/QuickLookCameraForCMOS
/QquickLookCamera/QData/ImageProcessing.cpp
GB18030
6,336
3.390625
3
[]
no_license
#include "ImageProcessing.h" #include "math.h" #include <memory> ImageProcessing::ImageProcessing(int height, int width) { m_height = height; m_width = width; } ImageProcessing::~ImageProcessing() { } void ImageProcessing::Transposition(unsigned char* dst, const unsigned char* src, int& width, int& height) { width = m_height; height = m_width; for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { dst[(y*height + x) * 3 + 0] = src[(x*width + y) * 3 + 0];//B dst[(y*height + x) * 3 + 1] = src[(x*width + y) * 3 + 1];//G dst[(y*height + x) * 3 + 2] = src[(x*width + y) * 3 + 2];//R } } } //24λɫͼתangle㣬ͼߡı䣬հײɰɫ void ImageProcessing::Rotate(unsigned char* dst, const unsigned char* src, int& width, int& height, int angle) { double angleRad = (double)angle / 180 * 3.1415926; double fcos = cos(angleRad); double fsin = sin(angleRad); width = m_width*abs(fcos) + m_height*abs(fsin); if (width % 4 != 0) width += 4 - width % 4; height = m_width*abs(fsin) + m_height*abs(fcos); if (height % 4 != 0) height += 4 - height % 4; memset(dst, 255, height * width * 3); int x = 0, y = 0, x0 = 0, y0 = 0; for (y = 0; y < height; ++y) { for (x = 0; x < width; ++x) { /*x = x0*fcos - y0*fsin - 0.5*m_width*fcos + 0.5*m_height*fsin + 0.5*width; y = x0*fsin + y0*fcos - 0.5*m_width*fsin - 0.5*m_height*fcos + 0.5*height;*/ x0 = x*fcos + y*fsin - 0.5*width*fcos - 0.5*height*fsin + 0.5*m_width; y0 = -x*fsin + y*fcos + 0.5*width*fsin - 0.5*height*fcos + 0.5*m_height; if (0 <= x0&&x0 < m_width && 0 <= y0&&y0 < m_height) { dst[(y*width + x) * 3 + 0] = src[(y0*m_width + x0) * 3 + 0]; dst[(y*width + x) * 3 + 1] = src[(y0*m_width + x0) * 3 + 1]; dst[(y*width + x) * 3 + 2] = src[(y0*m_width + x0) * 3 + 2]; } } } } //24λɫͼţratioΪӣratio=2ΪŴ2 void ImageProcessing::Zoom(unsigned char* dst, const unsigned char* src, int& width, int& height, double ratio) { width = m_width*ratio; if (width % 4 != 0) width += 4 - width % 4; height = m_height*ratio; if (height % 4 != 0) height += 4 - height % 4; int x = 0, y = 0, x0 = 0, y0 = 0; for (y = 0; y < height; ++y) { for (x = 0; x < width; ++x) { x0 = x / ratio; y0 = y / ratio; if (0 <= x0&&x0 < m_width && 0 <= y0&&y0 < m_height) { dst[(y*width + x) * 3 + 0] = src[(y0*m_width + x0) * 3 + 0]; dst[(y*width + x) * 3 + 1] = src[(y0*m_width + x0) * 3 + 1]; dst[(y*width + x) * 3 + 2] = src[(y0*m_width + x0) * 3 + 2]; } } } } bool ImageProcessing::Shift(unsigned char* dst, const unsigned char* src, int xx, int yy) { if (xx >= m_width || yy >= m_height) return false; memset(dst, 255, m_width * m_height * 3); int x = 0, y = 0, x0 = 0, y0 = 0; for (y = 0; y < m_height; ++y) { for (x = 0; x < m_width; ++x) { x0 = x - xx; y0 = y - yy; if (0 <= x0&&x0 < m_width && 0 <= y0&&y0 < m_height) { dst[(y*m_width + x) * 3 + 0] = src[(y0*m_width + x0) * 3 + 0]; dst[(y*m_width + x) * 3 + 1] = src[(y0*m_width + x0) * 3 + 1]; dst[(y*m_width + x) * 3 + 2] = src[(y0*m_width + x0) * 3 + 2]; } } } return true; } #define TEMPLATE_SMOOTH_BOX 1 //Boxƽģ #define TEMPLATE_SMOOTH_GAUSS 2 //˹ƽģ #define TEMPLATE_SHARPEN_LAPLACIAN 3 //˹ģ bool ImageProcessing::TemplateOperation(unsigned char* dst, const unsigned char* src, int templateType) { int templateSmoothBox[9] = { 1, 1, 1, 1, 1, 1, 1, 1, 1 }; //Boxƽģ int templateSmoothGauss[9] = { 1, 2, 1, 2, 4, 2, 1, 2, 1 }; //˹ƽģ int templateSharpenLaplacian[9] = { -1, -1, -1, -1, 9, -1, -1, -1, -1 }; //˹ģ float coef; //ģǰ˵ϵ int templateArray[9]; //ģ float tempNum; // switch (templateType)//жģ { case TEMPLATE_SMOOTH_BOX: //Boxƽģ coef = (float)(1.0 / 9.0); memcpy(templateArray, templateSmoothBox, 9 * sizeof(int)); break; case TEMPLATE_SMOOTH_GAUSS: //˹ƽģ coef = (float)(1.0 / 16.0); memcpy(templateArray, templateSmoothGauss, 9 * sizeof(int)); break; case TEMPLATE_SHARPEN_LAPLACIAN: //˹ģ coef = (float)1.0; memcpy(templateArray, templateSharpenLaplacian, 9 * sizeof(int)); break; } //ȽԭͼֱӿʵҪǿΧһȦ memcpy(dst, src, m_height*m_width * 3); for (int y = 1; y < m_height - 1; y++) //עyķΧǴ1Height-2 { for (int x = 1; x < m_width - 1; x++) //עxķΧǴ1Width-2 { for (int i = 0; i < 3; ++i) { tempNum = (float)(src[(y*m_width + x) * 3 + i])*templateArray[0]; tempNum += (float)(src[(y*m_width + x) * 3 + i])*templateArray[1]; tempNum += (float)(src[(y*m_width + x) * 3 + i])*templateArray[2]; tempNum += (float)(src[(y*m_width + x) * 3 + i])*templateArray[3]; tempNum += (float)(src[(y*m_width + x) * 3 + i])*templateArray[4]; tempNum += (float)(src[(y*m_width + x) * 3 + i])*templateArray[5]; tempNum += (float)(src[(y*m_width + x) * 3 + i])*templateArray[6]; tempNum += (float)(src[(y*m_width + x) * 3 + i])*templateArray[7]; tempNum += (float)(src[(y*m_width + x) * 3 + i])*templateArray[8]; //ϵ tempNum *= coef; //עĴ if (tempNum > 255.0) dst[(y*m_width + x) * 3 + i] = 255; else if (tempNum < 0.0) dst[(y*m_width + x) * 3 + i] = (unsigned char)fabs(tempNum); else dst[(y*m_width + x) * 3 + i] = (unsigned char)tempNum; } } } return true; } bool ImageProcessing::LimbPatternM3(unsigned char* dst, const unsigned char* src) { unsigned char bayerPattern[8][8] = { 0, 32, 8, 40, 2, 34, 10, 42, 48, 16, 56, 24, 50, 18, 58, 26, 12, 44, 4, 36, 14, 46, 6, 38, 60, 28, 52, 20, 62, 30, 54, 22, 3, 35, 11, 43, 1, 33, 9, 41, 51, 19, 59, 27, 49, 17, 57, 25, 15, 47, 7, 39, 13, 45, 5, 37, 63, 31, 55, 23, 61, 29, 53, 21 }; for (int y = 0; y < m_height; ++y) { for (int x = 0; x < m_width; ++x) { if ((src[y*m_width + x] >> 2) > bayerPattern[y&7][x&7]) //64ҶֵٱȽ dst[y*m_width + x] = 255; //׵ else dst[y*m_width + x] = 0; //ڵ } } return true; }
true
776665ae6ad9e7605b47c2d4234b6decde5353f4
C++
AbdullahAZaidi/Algorithms_in_Cpp
/ExceptionHandling_helper.cpp
UTF-8
428
2.8125
3
[]
no_license
/****************************************************************************** Exception handling *******************************************************************************/ #include <iostream> using namespace std; int main() { int p = -1; try { if (p < 0){ throw 88; } } catch(int x){ cout << "cannot be less than 0, ERROR : " << x << endl; } }
true
f12b50852315a3650285f3b444b02f2f8654a284
C++
uvic-auvic/Software_Sandbox
/vision/src/colorDetection/colorDetectionSample.cpp
UTF-8
2,602
3.203125
3
[]
no_license
//Author: Keifer Edelmayer /* Program Description: With use of webcam, program is able to perform color detection on objects placed before the webcam. An additional control window with sliders for the RGB values has been created to allow for color detection of desired color. */ #include <iostream> #include "opencv2/opencv.hpp" using namespace cv; using namespace std; int main(int argc, char** argv) { VideoCapture cap; // open the default camera, use something different from 0 otherwise; // Check VideoCapture documentation. if(!cap.open(0)) return 0; namedWindow("Control", CV_WINDOW_AUTOSIZE); //create a window called 'Control" int iLowH = 0; int iHighH = 179; int iLowS = 0; int iHighS = 255; int iLowV = 0; int iHighV = 255; //Create trackbars in "Control" window cvCreateTrackbar("LowH", "Control", &iLowH, 179); //Hue (0 - 179) cvCreateTrackbar("HighH", "Control", &iHighH, 179); cvCreateTrackbar("LowS", "Control", &iLowS, 255); //Saturation (0 - 255) cvCreateTrackbar("HighS", "Control", &iHighS, 255); cvCreateTrackbar("LowV", "Control", &iLowV, 255); //Value (0 - 255) cvCreateTrackbar("HighV", "Control", &iHighV, 255); for(;;) //infitie loop, runs till break { Mat frame; cap >> frame; //camera footage being feed into frame if( frame.empty() ) break; // end of video stream Mat imgHSV; cvtColor(frame, imgHSV, COLOR_BGR2HSV); //take the img and convert to HSV to allow for color detection to be performed Mat imgThresholded; inRange(imgHSV, Scalar(iLowH, iLowS, iLowV), Scalar(iHighH, iHighS, iHighV), imgThresholded); //takes values from the sliders and filters colors currently not in range //noise math for the imgage to be improve quality below erode(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) ); dilate( imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) ); //morphological closing (fill small holes in the foreground) dilate( imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) ); erode(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) ); imshow("original img", frame); //function to show webcam feed imshow("thresholded img", imgThresholded); if( waitKey(10) == 27 ) break; // stop capturing by pressing ESC } // the camera will be closed automatically upon exit // cap.close(); return 0; }
true
af91e072af9d887d8810b8f4f2963a70e8634097
C++
king7282/algorithm
/codeforces/671Div2C.cpp
UTF-8
554
2.640625
3
[]
no_license
#include <stdio.h> #include <algorithm> int input[1010]; int main(void) { int test; scanf("%d", &test); for (int t = 0; t < test; t++) { int n, x; scanf("%d %d", &n, &x); bool flag = false; int sum = 0; for (int i = 1; i <= n; i++) { scanf("%d", input + i); sum += input[i] - x; if (input[i] == x) flag = true; } std::sort(input + 1, input + 1 + n); if (input[1] == input[n] && input[1] == x) { printf("0\n"); } else { if (sum == 0 || flag) { printf("1\n"); } else printf("2\n"); } } }
true
7ae04ef808fc5d2737b826347a13812389b8f52c
C++
Junxen/biotracker_backgroundsubtraction_tracker
/Src/helper/CvHelper.cpp
UTF-8
10,397
3.015625
3
[]
no_license
#include "CvHelper.h" #include "StringHelper.h" cv::Point CvHelper::subtractTwoCvPoints(cv::Point a, cv::Point b) { return cv::Point(a.x - b.x, a.y - b.y); } cv::Point CvHelper::addTwoCvPoints(cv::Point a, cv::Point b) { return cv::Point(a.x + b.x, a.y + b.y); } cv::Point CvHelper::multCvPoint(double scalar, cv::Point p) { return cv::Point(scalar * p.x, scalar * p.y); } QPointF CvHelper::norm(double x, double y) { double distance = qSqrt(x * x + y * y); if (distance == 0) { return QPointF(0, 0); } return QPointF(x / distance, y / distance); } QPointF CvHelper::norm(QPoint p) { return CvHelper::norm((double) p.x(), (double) p.y()); } QPointF CvHelper::norm(QPointF p) { return CvHelper::norm(p.x(), p.y()); } double CvHelper::getDistance(double x1, double y1, double x2, double y2) { return qSqrt( ( (x1 - x2) * (x1 - x2) ) + ( (y1 - y2) * (y1 - y2) ) ); } double CvHelper::getDistance(double x1, double y1, double z1, double x2, double y2, double z2 ) { return qSqrt(((x1 - x2) * (x1 - x2)) + ((y1 - y2) * (y1 - y2)) + ((z1 - z2) * (z1 - z2))); } double CvHelper::getSqDistance(double x1, double y1, double x2, double y2) { return ( (x1 - x2) * (x1 - x2) ) + ( (y1 - y2) * (y1 - y2) ); } double CvHelper::getSqDistance(double x1, double y1, double z1, double x2, double y2, double z2) { return ((x1 - x2) * (x1 - x2)) + ((y1 - y2) * (y1 - y2)) + ((z1 - z2) * (z1 - z2)); } double CvHelper::getDistance(QPoint p1, QPoint p2) { return getDistance((double) p1.x(), (double) p1.y(), (double) p2.x(), (double) p2.y()); } double CvHelper::getDistance(QPointF p1, QPointF p2) { return getDistance(p1.x(), p1.y(), p2.x(), p2.y()); } double CvHelper::getDistance(cv::Point2f p1, cv::Point2f p2) { return getDistance(p1.x, p1.y, p2.x, p2.y); } double CvHelper::getDistance(cv::Point3f p1, cv::Point3f p2) { return getDistance(p1.x, p1.y, p1.z, p2.x, p2.y, p2.z); } double CvHelper::getDistance(cv::Point p1, cv::Point p2) { return sqrt(double((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y))); } double CvHelper::getSqDistance(cv::Point2f p1, cv::Point2f p2) { return getSqDistance(p1.x, p1.y, p2.x, p2.y); } double CvHelper::getSqDistance(cv::Point3f p1, cv::Point3f p2) { return getSqDistance(p1.x, p1.y, p1.z, p2.x, p2.y, p2.z); } double CvHelper::orientation(cv::Point2f front, cv::Point2f back) { cv::Point2f diff = front - back; //return qAtan2(diff.x, diff.y); // need to check the origin of coorindiates return qAtan2(diff.x, diff.y) + CV_PI / 2.0; } double CvHelper::orientation(QPointF front, QPointF back) { //QPointF diff = front - back; //return qAtan2(diff.x(), diff.y()); return orientation(cv::Point2f(front.x(),front.y()),cv::Point2f(back.x(),back.y())); } float CvHelper::angleDifference(float alpha, float beta) { float difference = alpha - beta; while (difference < -CV_PI) difference += 2.0f * CV_PI; while (difference > +CV_PI) difference -= 2.0f * CV_PI; return difference; } float CvHelper::findMin(float n1, float n2, float n3) { return (n1 < n2 && n1 < n3) ? n1 : (n2 < n3 ? n2 : n3); } float CvHelper::findMax(float n1, float n2, float n3) { return (n1 > n2 && n1 > n3) ? n1 : (n2 > n3 ? n2 : n3); } float CvHelper::normalDist(float x, float mean, float variance) { return 1.0 / (variance *qSqrt(2*CV_PI)) * qExp(- ((x - mean) * (x - mean)) / (2 * variance * variance)); } float CvHelper::sigmoid(float x, float shrink) { return (2.0 / (1.0 + qExp(-x * shrink)) - 1.0); } float CvHelper::sigmoidAbsInv(float x, float shrink) { return 1.0 - qAbs((2.0 / (1.0 + qExp(-x * shrink)) - 1.0)); } double CvHelper::getAngleDifference(double dirToTargetAsRad, double currOrientationAsRad) { /*double angleDiff = dirToTargetAsRad - currOrientationAsRad + CV_PI / 2.0; while (angleDiff < -CV_PI) angleDiff += 2 * CV_PI; while (angleDiff > CV_PI) angleDiff -= 2 * CV_PI; return angleDiff;*/ double a = dirToTargetAsRad - currOrientationAsRad; a += (a > CV_PI) ? -(2*CV_PI) : (a < -CV_PI) ? (2*CV_PI) : 0; return a; } //double CvHelper::getAngleToTarget(cv::Point2f A, cv::Point2f B) { // double ab = A.x*B.x + A.y*B.y; // double a = qSqrt(A.x*A.x + A.y*A.y); // double b = qSqrt(B.x*B.x + B.y*B.y); // double cosT = ab / (a*b); // return qAcos(cosT); //} double CvHelper::getAngleToTarget(cv::Point2f currentPos, cv::Point2f targetPos) { return qAtan2(targetPos.x - currentPos.x, targetPos.y - currentPos.y); } std::deque<cv::Point2f> CvHelper::convertMat2Point2fDeque(cv::Mat mat) { std::deque<cv::Point2f> point2fS; if(mat.cols != 2) return point2fS; for (int row = 0; row < mat.rows; row++) { float x = mat.at<float>(row,0); float y = mat.at<float>(row,1); point2fS.push_back(cv::Point2f(x,y)); } return point2fS; } cv::Mat CvHelper::convertPoint2fDeque2Mat(std::deque<cv::Point2f> points) { cv::Mat mat; if(points.empty()) return mat; mat = cv::Mat(points.size(), 2, CV_32F); for (int i = 0; i < points.size(); i++) { cv::Point2f p = points.at(i); mat.at<float>(i,0)= p.x; mat.at<float>(i,1)= p.y; } return mat; } QList<std::deque<cv::Point2f>> CvHelper::convertMatList2Point2fDequeList(QList<cv::Mat> mats) { QList<std::deque<cv::Point2f>> pointList; cv::Mat mat; foreach (mat , mats) { pointList << CvHelper::convertMat2Point2fDeque(mat); } return pointList; } cv::Point2f CvHelper::getMirrowPoint(cv::Point2f point2Mirror, cv::Point2f pointOfOrigin, float angelAsGrad) { //Convert angelAsGrad to radian float angelAsRadian = (angelAsGrad * CV_PI / 180.0); cv::Mat G = (cv::Mat_<float>(2,2) << cos(2.0 * angelAsRadian), sin(2.0 * angelAsRadian), sin(2.0 * angelAsRadian), -cos(2.0 * angelAsRadian)); cv::Mat point2MirrorMat(1/*rows*/,2 /* cols */,CV_32F); point2MirrorMat.at<float>(0,0) = point2Mirror.x; point2MirrorMat.at<float>(0,1) = point2Mirror.y; cv::Mat pointOfOriginMat(1/*rows*/,2 /* cols */,CV_32F); pointOfOriginMat.at<float>(0,0) = pointOfOrigin.x; pointOfOriginMat.at<float>(0,1) = pointOfOrigin.y; cv::Mat point2MirrorFromOrigin = point2MirrorMat - pointOfOriginMat; cv::Mat point2MirrorMatT; cv::transpose(point2MirrorFromOrigin, point2MirrorMatT); cv::Mat mirrowedPointMat = (G * point2MirrorMatT); cv::Mat mirrowedPointMatT; cv::transpose(mirrowedPointMat, mirrowedPointMatT); cv::Mat finalMat = mirrowedPointMatT + pointOfOriginMat; return cv::Point2f(finalMat.at<float>(0,0),finalMat.at<float>(0,1)); } std::deque<cv::Point2f> CvHelper::getMirrowPoints(std::deque<cv::Point2f> points2Mirror, cv::Point2f pointOfOrigin, float angelAsGrad) { std::deque<cv::Point2f> mirrowedPoints; for(int i = 0; i < points2Mirror.size(); i++) { cv::Point2f p = CvHelper::getMirrowPoint(points2Mirror.at(i), pointOfOrigin, angelAsGrad); mirrowedPoints.push_back(p); } return mirrowedPoints; } std::deque<cv::Point2f> CvHelper::getMirrowLine(cv::Point2f pointOfOrigin, float width, float height, float angelAsGrad) { float angle = angelAsGrad * CV_PI / 180.0; float r = CvHelper::getDistance(pointOfOrigin, cv::Point2f(width, height)); float xOff1 = pointOfOrigin.x + r * cos(angle); float yOff1 = pointOfOrigin.y + r * sin(angle); float xOff2 = pointOfOrigin.x - r * cos(angle); float yOff2 = pointOfOrigin.y - r * sin(angle); cv::Point2f front(xOff2,yOff2); cv::Point2f back(xOff1,yOff1); std::deque<cv::Point2f> points; points.push_back(front); points.push_back(back); return points; } std::vector<cv::Point> CvHelper::convertMat2Vector(cv::Mat mat) { std::vector<cv::Point> value(mat.rows); for (int i = 0; i < value.size(); i++) { cv::Point p((int)mat.at<float>(i,0),(int)mat.at<float>(i,1)); value.at(i) = p; } return value; } cv::Mat CvHelper::convertVector2Mat(std::vector<cv::Point> vect) { cv::Mat mat(vect.size(),2,CV_32F); for (int i = 0; i < vect.size(); i++) { mat.at<float>(i,0) = (float)vect.at(i).x; mat.at<float>(i,1) = (float)vect.at(i).y; } return mat; } float CvHelper::degToRad(float deg) { return deg * CV_PI / 180.0; } float CvHelper::radToDeg(float rad) { return rad * 180.0 / CV_PI; } int CvHelper::stdStringToInt(std::string string) { int numb; std::istringstream iss(string); if (!(iss >> numb)) { throw "String cannot convert to float number!"; } return numb; } float CvHelper::stdStringToFloat(std::string string) { float numb; std::istringstream iss(string); if (!(iss >> numb)) { throw "String cannot convert to float number!"; } return numb; } std::string CvHelper::convertStdVectorCvPointToStdString(std::vector<cv::Point> points) { std::string pointListString; for (int i = 0; i < points.size(); i++) { int x = points.at(i).x; int y = points.at(i).y; if(i < points.size() - 1) pointListString.append(StringHelper::iToSS(x)).append(":").append(StringHelper::iToSS(y)).append(" "); else pointListString.append(StringHelper::iToSS(x)).append(":").append(StringHelper::iToSS(y)); } return pointListString; } std::string CvHelper::convertCvScalarToStdString(cv::Scalar scalar) { std::string scalarString; int r = scalar.val[0,0]; int g = scalar.val[0,1]; int b = scalar.val[0,2]; scalarString.append(StringHelper::iToSS(r)).append(" ").append(StringHelper::iToSS(g)).append(" ").append(StringHelper::iToSS(b)).append(" "); return scalarString; } std::string CvHelper::cvSizeToSS(cv::Size cvSize_value) { std::string cvSizeString; int width = cvSize_value.width; int height = cvSize_value.height; cvSizeString.append(StringHelper::iToSS(height)).append("x").append(StringHelper::iToSS(width)); return cvSizeString; } std::string CvHelper::cvSize2fToSS(cv::Size2f cvSize2f_value) { std::string cvSize2fString; float width = cvSize2f_value.width; float height = cvSize2f_value.height; cvSize2fString.append(StringHelper::fToSS(height)).append("x").append(StringHelper::fToSS(width)); return cvSize2fString; } std::string CvHelper::cvSize2fToSS(QString width, QString height) { std::string cvSize2fString; cvSize2fString.append(height.toStdString()).append("x").append(width.toStdString()); return cvSize2fString; } std::string CvHelper::getCurrentDatetimeAsStd() { return QDateTime::currentDateTime().toString("_yyMMddThhmmss").toUtf8().constData(); } bool CvHelper::isFrameSizeEqual(cv::Size o1, cv::Size o2) { bool equal = false; if (o1.width == o2.width && o1.height == o2.height) equal = true; return equal; }
true
c48669cc34af59f478512670cea424b8973030ce
C++
kirencaldwell/StateEstimation
/src/Models/system_model.cc
UTF-8
1,233
2.859375
3
[]
no_license
#include "system_model.h" void SystemModel::SetModelName(std::string model_name) { _name = model_name; std::cout << "Setting model name: " << _name << "\n"; } void SystemModel::AddMeasurement(VectorXd y) { _y = y; // std::cout << "yii = " << _y << "\n\n"; } VectorXd SystemModel::GetMeasurement() { return _y; } void SystemModel::ClearMeasurement() { _y = VectorXd::Zero(0); } void SystemModel::SetVariance(MatrixXd R) { _R = R; } MatrixXd SystemModel::GetVariance() { return _R; } MatrixXd SystemModel::GetVariance(VectorXd x) { return _R; } std::string SystemModel::GetName() { return _name; } VectorXd SystemModel::GetOutput(VectorXd x){ return RunModel(x); } VectorXd SystemModel::RunModel(VectorXd x) { return x; } VectorXd SystemModel::GetNoisyOutput(VectorXd x) { normal_random_variable v { _R }; VectorXd y = RunModel(x) + v(); return y; } MatrixXd SystemModel::GetJacobian(VectorXd x, double h){ VectorXd y0 = RunModel(x); int m = y0.size(); int n = x.size(); MatrixXd H(m, n); for (int i = 0; i < n; i++) { VectorXd x0 = x; x0(i) = x0(i) + h; H.col(i) = (RunModel(x0) - y0) / h; } return H; }
true
14f1f8eff4bb80cda3005c03f4e05d97e0b072d2
C++
y2kiah/project-griffin
/project-griffin/project-griffin/vendor/clReflect-0.4/inc/clutl/Module.h
UTF-8
2,471
2.515625
3
[ "MIT" ]
permissive
// // =============================================================================== // clReflect, Module.h - Interface/implementation support // ------------------------------------------------------------------------------- // Copyright (c) 2011-2012 Don Williamson & clReflect Authors (see AUTHORS file) // Released under MIT License (see LICENSE file) // =============================================================================== // #pragma once #include <clcpp/clcpp.h> namespace clcpp { class Database; struct Type; } namespace clutl { // // Represents a DLL on Windows, the only supported platform, currently // class Module { public: Module(); ~Module(); // // Load the module, get its reflection database and register any interface implementations // // The module can optionally expose a function with the following signature to return its // reflection database: // // extern "C" clcpp::Database* GetReflectionDatabase(); // // If you have an interface type in the host program that has an implementation in the module, // expose a function with the following signature: // // extern "C" void AddReflectionImpls(clutl::Module*); // // This will be called after the module load and you can use SetInterfaceImpl to register any // interface iimplementations. // bool Load(clcpp::Database* host_db, const char* filename); // // Registers an interface implementation from with AddReflectionImpls. Note that none of the // types need to be in-scope when you call this; they only need to be forward-declared. // template <typename IFACE_TYPE, typename IMPL_TYPE> void SetInterfaceImpl() { clcpp::internal::Assert(m_HostReflectionDB != 0); clcpp::internal::Assert(m_ReflectionDB != 0); // Cast away const-ness so the interface can alias its implementation clcpp::Type* iface_type = const_cast<clcpp::Type*>(m_HostReflectionDB->GetType(clcpp::GetTypeNameHash<IFACE_TYPE>())); const clcpp::Type* impl_type = m_ReflectionDB->GetType(clcpp::GetTypeNameHash<IMPL_TYPE>()); SetInterfaceImpl(iface_type, impl_type); } const clcpp::Database* GetReflectionDB() { return m_ReflectionDB; } private: void SetInterfaceImpl(clcpp::Type* iface_type, const clcpp::Type* impl_type); // Platform-specific module handle void* m_Handle; // The loading modules database clcpp::Database* m_HostReflectionDB; // Module database const clcpp::Database* m_ReflectionDB; }; }
true
2d590bcfc7470cfa2414a754d56cae34bb252fa2
C++
RealJiShi/MeshSimplification-Mobile
/app/src/main/cpp/MeshSimplifcation/OffFileHelper.h
UTF-8
2,885
3.171875
3
[]
no_license
#pragma once #include <fstream> #include <sstream> #include <vector> class OffFileHelper { public: static bool load(const std::string &file_path, std::vector<double> &vertices, std::vector<uint16_t> &indices) { std::ifstream fin(file_path); if (!fin) { return false; } // get "OFF" std::string line; while (std::getline(fin, line)) { if (line.length() > 1 && line[0] != '#') { if (line.find("OFF") != std::string::npos) { break; } } } // get vertex number and face number unsigned int nVert = 0; unsigned int nFace = 0; unsigned int nEdge = 0; while (std::getline(fin, line)) { if (line.length() > 1 && line[0] != '#') { std::istringstream info; info.str(line); info >> nVert >> nFace >> nEdge; break; } } // get vertex vertices.resize(nVert * 3); for (unsigned int i_vert = 0; i_vert < nVert; ++i_vert) { std::getline(fin, line); std::stringstream info; info.str(line); info >> vertices[i_vert * 3] >> vertices[i_vert * 3 + 1] >> vertices[i_vert * 3 + 2]; } // get face indices.resize(nFace * 3); for (unsigned int i_face = 0; i_face < nFace; ++i_face) { std::getline(fin, line); std::stringstream info; info.str(line); uint16_t _temp; info >> _temp >> indices[i_face * 3] >> indices[i_face * 3 + 1] >> indices[i_face * 3 + 2]; } fin.close(); // return true; } static bool store(const std::string &file_path, const std::vector<double> &vertices, const std::vector<uint16_t> &indices) { std::ofstream fout(file_path); if (!fout) { return false; } unsigned int nVert = static_cast<unsigned int>(vertices.size() / 3); unsigned int nFace = static_cast<unsigned int>(indices.size() / 3); fout << "OFF\n"; fout << nVert << " " << nFace << " " << 0 << std::endl; for (unsigned int i_vert = 0; i_vert < nVert; ++i_vert) { fout << vertices[i_vert * 3] << " " << vertices[i_vert * 3 + 1] << " " << vertices[i_vert * 3 + 2] << std::endl; } for (unsigned int i_face = 0; i_face < nFace; ++i_face) { fout << 3 << " " << indices[i_face * 3] << " " << indices[i_face * 3 + 1] << " " << indices[i_face * 3 + 2] << std::endl; } fout.close(); return true; } };
true
96abab07adcc8d0a158db66992775ccd6afe6f0f
C++
mapleyustat/tensor-1
/src/random.cc
UTF-8
513
3.328125
3
[]
no_license
#include "random.h" static uint w = 1; static uint z = 2; void random_seed(uint seed) { if (seed > 0) { w = seed + 1; z = w + w + 1; } } /* http://en.wikipedia.org/wiki/Random_number_generator */ uint random_marsaglia() { z = 36969 * (z & 65535) + (z >> 16); w = 18000 * (w & 65535) + (w >> 16); return (z << 16) + w; /* 32-bit result */ } /* generate a random number in the range [min, max] */ uint random_between(uint min, uint max) { return random_marsaglia() % (max-min+1) + min; }
true
0cf6b39a90c91864278947cecdd9e20cd49cd6df
C++
emonansar/URI-Problem-Solution
/1071.cpp
UTF-8
220
2.53125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main() { int X,Y,sum=0; cin>>X>>Y; for(int i=Y+1;i<=X-1;i++) { if(i%2!=0) { sum=sum+i; } } cout<<sum<<endl; }
true
600ddb08c8e10dee601cf8c13d22ceb5fec365c6
C++
Winded/conways-unreal-game-of-life
/Source/UEGameOfLife/LifeSimulator.cpp
UTF-8
6,110
2.515625
3
[]
no_license
#include "UEGameOfLife.h" #include "LifeSimulator.h" #include "LifeCell.h" ALifeSimulator::ALifeSimulator() : mGenerated(false), mGrid(0), mGridNextState(0), mSize(0), mLastSimulation(0.0f) { Simulating = false; Spacing = 10.0f; SimulationInterval = 0.1f; ActivationStatus = AS_None; Repeating = true; PrimaryActorTick.bCanEverTick = true; } ALifeSimulator::~ALifeSimulator() { if(mGenerated) { for (int i = 0; i < mSize; i++) { delete[] mGrid[i]; } delete[] mGrid; mGrid = 0; for (int i = 0; i < mSize; i++) { delete[] mGridNextState[i]; } delete[] mGridNextState; mGridNextState = 0; } } void ALifeSimulator::BeginPlay() { Super::BeginPlay(); } void ALifeSimulator::Tick(float DeltaSeconds) { Super::Tick(DeltaSeconds); if(Simulating) { float t = GetWorld()->GetGameState()->GetServerWorldTimeSeconds(); if(t - mLastSimulation >= SimulationInterval) { SimulationTick(); mLastSimulation = t; } } else { APlayerController *pc = *(GetWorld()->GetPlayerControllerIterator()); FHitResult hit; pc->GetHitResultUnderCursorByChannel(TraceChannel.GetValue(), true, hit); ALifeCell *cell = Cast<ALifeCell>(hit.Actor.Get()); if(cell) { switch(ActivationStatus) { case AS_Activating: SetCellValue(cell, true); break; case AS_Deactivating: SetCellValue(cell, false); break; } } } } void ALifeSimulator::GenerateGrid(int32 size) { if(mGenerated) { for (int i = 0; i < mSize; i++) { delete[] mGrid[i]; } delete[] mGrid; mGrid = 0; for (int i = 0; i < mSize; i++) { delete[] mGridNextState[i]; } delete[] mGridNextState; mGridNextState = 0; for(int32 i = 0; i < mCells.Num(); i++) { ALifeCell *cell = mCells[i]; cell->Destroy(); } mCells.Empty(); } mSize = size; mGrid = new bool*[size]; for (int i = 0; i < size; i++) { mGrid[i] = new bool[size]; for (int ii = 0; ii < size; ii++) mGrid[i][ii] = false; } mGridNextState = new bool*[size]; for (int i = 0; i < size; i++) { mGridNextState[i] = new bool[size]; for (int ii = 0; ii < size; ii++) mGridNextState[i][ii] = false; } for(int32 x = 1; x <= size; x++) { for(int32 y = 1; y <= size; y++) { ALifeCell *cell = (ALifeCell*)GetWorld()->SpawnActor(CellClass); cell->GridX = x; cell->GridY = y; AddCell(cell); } } mGenerated = true; } int32 ALifeSimulator::GetSize() { return mSize; } void ALifeSimulator::SimulationTick() { if (!mGrid || !mGridNextState) return; for (int x = 1; x <= mSize; x++) for (int y = 1; y <= mSize; y++) { bool result = false; int count = GetLivingNeighbors(x, y); bool living = mGrid[x - 1][y - 1]; if (living && (count == 2 || count == 3)) result = true; else if (!living && count == 3) result = true; mGridNextState[x - 1][y - 1] = result; } for (int x = 1; x <= mSize; x++) for (int y = 1; y <= mSize; y++) { mGrid[x - 1][y - 1] = mGridNextState[x - 1][y - 1]; } for(int i = 0; i < mCells.Num(); i++) { ALifeCell *cell = mCells[i]; bool value = mGrid[cell->GridX - 1][cell->GridY - 1]; cell->SetHighlighted(value); } } void ALifeSimulator::AddCell(ALifeCell *cell) { cell->Simulator = this; mCells.Add(cell); FVector pos = GetActorLocation(); pos.X += (float)cell->GridX * Spacing - (float)mSize * Spacing / 2.f - Spacing / 2.f; pos.Y += (float)cell->GridY * Spacing - (float)mSize * Spacing / 2.f - Spacing / 2.f; cell->SetActorLocation(pos); } bool ALifeSimulator::GetCellValue(int32 gridX, int32 gridY) { if (!mGrid) return false; if (gridX > mSize || gridY > mSize || gridX < 1 || gridY < 1) return false; return mGrid[gridX - 1][gridY - 1]; } void ALifeSimulator::SetCellValue(int32 gridX, int32 gridY, bool value) { if (!mGrid) return; if (gridX > mSize || gridY > mSize || gridX < 1 || gridY < 1) return; mGrid[gridX - 1][gridY - 1] = value; } void ALifeSimulator::SetCellValue(ALifeCell *cell, bool value) { SetCellValue(cell->GridX, cell->GridY, value); cell->SetHighlighted(value); } int ALifeSimulator::GetLivingNeighbors(int gridX, int gridY) { if (!mGrid) return 0; if (gridX > mSize || gridY > mSize || gridX < 1 || gridY < 1) return 0; int count = 0; // Right side if (IsNeighborAlive(gridX + 1, gridY)) count++; // Right Bottom side if (IsNeighborAlive(gridX + 1, gridY + 1)) count++; // Bottom side if (IsNeighborAlive(gridX, gridY + 1)) count++; // Left Bottom side if (IsNeighborAlive(gridX - 1, gridY + 1)) count++; // Left side if (IsNeighborAlive(gridX - 1, gridY)) count++; // Left Upper side if (IsNeighborAlive(gridX - 1, gridY - 1)) count++; // Upper side if (IsNeighborAlive(gridX, gridY - 1)) count++; // Right Upper side if (IsNeighborAlive(gridX + 1, gridY - 1)) count++; return count; } bool ALifeSimulator::IsNeighborAlive(int gridX, int gridY) { if (Repeating && gridX > mSize) gridX = 1; else if (Repeating && gridX < 1) gridX = mSize; else if (!Repeating && (gridX < 1 || gridX > mSize)) return false; if (Repeating && gridY > mSize) gridY = 1; else if (Repeating && gridY < 1) gridY = mSize; else if (!Repeating && (gridY < 1 || gridY > mSize)) return false; return mGrid[gridX - 1][gridY - 1]; }
true
de2627d2d830870d7f7e0801dcfb36bf056f592c
C++
nevaeh511/personal_projects
/scrabble_words.cpp
UTF-8
978
3.4375
3
[]
no_license
#include<string> #include<vector> #include<iterator> #include<fstream> #include<iostream> #include<algorithm> #include<unordered_map> using namespace std; int main(){ string word; unordered_map<string, string> dictionary; ifstream dictFile("scrabble_dictionary2.txt"); while(dictFile){ dictFile >> word; dictionary.emplace(word, word); } cout << "Enter a word: "; cin >> word; while (cin){ int count = 0; cout << endl; sort(word.begin(), word.end()); unordered_map<string, string>::const_iterator got; do{ got = dictionary.find(word); if (got != dictionary.end()){ cout << got->second << " is a word." << endl; count++; } } while (next_permutation(word.begin(), word.end())); if (count == 0){ cout << "No words were found given the letters: '" << word << "'" << endl; } cout << endl; cout << "Enter another word or" << endl; cout << "press 'q' to quit: "; cin >> word; if (word == "q"){ return 0; } } }
true
def89b10eca52801bf07a08f762931b2831c5a2a
C++
nirmalthomas2609/One-Pass-Assembler-for-SIC
/one_pass_assembler.cpp
UTF-8
11,245
2.625
3
[]
no_license
#include<iostream> #include<vector> #include<string> #include<map> #include<stack> #include<queue> #include<fstream> #include<algorithm> #include<sstream> #include<math.h> using namespace std; class Assembler { int locctr, starting_address, obj_rec_no, obj_address; map<string, vector<int> > symtab; map<int, vector<string> > obj_rec; map<string, string> optab; string header_rec, src_file_name, symtab_file_name, end_rec, program_name, optab_file_name, object_file_name; public: Assembler(string sc, string symtab, string op_tab, string obj); void generate_object_code(); string convert_to_hexa(int a); int convert_to_decimal(string a); vector<string> get_vector_from_line(string line); void generate_optab(); string add_chars(string line, char a, int l, int g); void add_entry(string a, int k); int return_int(char a); int get_integer(string a); void display_object_records(); void display_object_code(); void display_source_code(); void display_symtab(); void correct_object_code(vector<int> locs); void display_optab(); void write_object_code(); void write_symtab(); }; void Assembler :: add_entry(string a, int k) { int z = 0; if(obj_rec[obj_rec_no].size() >= 11) { z = 1; obj_rec_no++; } if(obj_rec[obj_rec_no].size() == 0) obj_rec[obj_rec_no].push_back(convert_to_hexa(locctr)); obj_rec[obj_rec_no].push_back(a); if(z == 0 && k == 1) obj_rec_no++; obj_address += 3; return; } void Assembler :: correct_object_code(vector<int> locs) { int i = 0, j = 0, k = 1; while(i <= obj_rec_no && k < locs.size()) { int t = 1; if(obj_rec[i].size() == 0) break; while(t < obj_rec[i].size() && k < locs.size()) { if(j == locs.at(k)) { if((obj_rec[i].at(t)).length() == 3) { string temp = obj_rec[i].at(t); (obj_rec[i])[t] = temp.substr(0, temp.length() - 1) + add_chars(convert_to_hexa(locctr + (int)pow(2, 15)), '0', 4, 0); } else { (obj_rec[i])[t] = (obj_rec[i]).at(t) + add_chars(convert_to_hexa(locctr), '0', 4, 0); } k++; } t++; j += 3; } i++; } cout<<endl; return; } void Assembler :: generate_object_code() { ifstream sc(src_file_name.c_str()); int k = 0; for(string line; getline(sc, line);) { vector<string> instr = get_vector_from_line(line); if(k == 0) { k = 1; if(instr.size() == 3) { if(instr[1].compare(string("START")) == 0) { locctr = convert_to_decimal(instr[2]); starting_address = locctr; program_name = instr[0]; continue; } else { locctr = 0; starting_address = 0; } } else { locctr = 0; starting_address = 0; } } if(instr[0].compare(string(".")) == 0) continue; if(instr.size() == 1) { if(instr[0].compare(string("END")) == 0) break; if(optab.find(instr[0]) == optab.end()) { cout<<"Opcode not found in the optab"<<endl; exit(0); } else { add_entry(optab[instr[0]] + string("0000"), 1); obj_rec_no++; locctr += 3; } } else if(instr.size() < 1 || instr.size() > 3) { cout<<"Incorrect Instruction Format"<<endl; exit(0); } else { string label, opcode, operand, temp; temp = string(""); // cout<<"The size of instr is "<<instr.size()<<endl; if(instr.size() == 2) { opcode = instr[0]; operand = instr[1]; } else if (instr.size() == 3) { label = instr[0]; opcode = instr[1]; operand = instr[2]; } if(instr.size() == 3) { if(symtab.find(label) == symtab.end()) { symtab[label].push_back(locctr); } else if (symtab[label].size() > 1) { correct_object_code(symtab[label]); symtab[label].clear(); symtab[label].push_back(locctr); } } if (optab.find(opcode) != optab.end()) { int m = 0; temp = optab[opcode]; if(operand.find(',') != string::npos) { m = 1; operand = operand.substr(0, operand.find(',')); } if(symtab.find(operand) == symtab.end()) { symtab[operand].push_back(-1); symtab[operand].push_back(obj_address); if (m == 1) add_entry(temp + string(1, '1'), 0); else add_entry(temp, 0); } else if (symtab[operand].size() == 1) { if(m == 0) temp += add_chars(convert_to_hexa(symtab[operand][0]), '0', 4, 0); else temp += add_chars(convert_to_hexa(symtab[operand][0] + (int)pow(2, 15)), '0', 4, 0); add_entry(temp, 0); } else if(symtab[operand].size() > 1) { symtab[operand].push_back(obj_address); if (m == 0) add_entry(temp, 0); else add_entry(temp + string(1, '1'), 0); } locctr += 3; } else { if(opcode.compare(string("WORD")) == 0) { locctr += 3; } else if (opcode.compare(string("RESW")) == 0) { locctr += 3*(get_integer(operand)); } else if (opcode.compare(string("BYTE")) == 0) { locctr += operand.length() - 3; } else if (opcode.compare(string("RESB")) == 0) { locctr += get_integer(operand); } else { cout<<"Incorrect Opcode"<<endl; exit(0); } } } // display_symtab(); } // display_object_code(); write_symtab(); write_object_code(); } void Assembler :: write_object_code() { ofstream fout(object_file_name.c_str()); fout<<"H^"<<add_chars(program_name, ' ', 6, 1)<<"^"<<add_chars(convert_to_hexa(starting_address), '0', 6, 0)<<"^"<<add_chars(convert_to_hexa(obj_address - 3), '0', 6, 0)<<endl; for(int i = 0; i <= obj_rec_no; i++) { if(obj_rec[i].size() == 0) break; vector<string> temp = obj_rec[i]; fout<<"T^"<<add_chars(obj_rec[i][0], '0', 6, 0)<<"^"<<add_chars(convert_to_hexa((obj_rec[i].size() - 1)*3), '0', 2, 0)<<"^"; for(int j = 1; j < obj_rec[i].size(); j++) { if(j != obj_rec[i].size() - 1) fout<<obj_rec[i][j]<<"^"; else fout<<obj_rec[i][j]<<endl; } } fout<<"E^"<<add_chars(convert_to_hexa(starting_address), '0', 6, 0)<<endl; fout.close(); return; } void Assembler :: write_symtab() { ofstream fout(symtab_file_name.c_str()); map<string, vector<int> >::iterator it; for(it = symtab.begin(); it != symtab.end(); ++it) { fout<<it->first<<" : "<<add_chars(convert_to_hexa((it->second)[0]), '0', 4, 0)<<endl; } fout.close(); return; } void Assembler :: display_object_records() { cout<<"Displaying the object code which has been generated"<<endl; for(int i = 0; i <= obj_rec_no; i++) { if(obj_rec[i].size() == 0) break; vector<string> object_codes = obj_rec[i]; cout<<"Starting address for the record is "<<object_codes[0]<<endl; for(int j = 1; j< object_codes.size(); j++) { cout<<object_codes[j]<<" "; } cout<<endl; } return; } void Assembler :: display_symtab() { map<string, vector<int> >::iterator it; for(it = symtab.begin(); it!=symtab.end(); ++it) { vector<int> temp= it->second; if(temp.size() == 1) { cout<<it->first<<" : "<<add_chars(convert_to_hexa(temp[0]), '0', 4, 0)<<endl; } else { cout<<"The records for "<<it->first<<" to be changed at "<<endl; for(int j = 1; j <temp.size(); j++) { cout<<temp[j]<<" "; } cout<<endl; } } return; } void Assembler :: display_optab() { map<string, string> :: iterator it; for(it = optab.begin(); it!=optab.end(); ++it) { cout<<it->first<<" : "<<it->second<<endl; } return; } int Assembler :: return_int(char a) { if (a == '0') return 0; else if (a == '1') return 1; else if (a == '2') return 2; else if (a == '3') return 3; else if (a == '4') return 4; else if (a == '5') return 5; else if (a == '6') return 6; else if (a == '7') return 7; else if (a == '8') return 8; else return 9; } int Assembler :: get_integer(string a) { int i; int t=0; char p; for(i=0; i<a.length(); i++) { t = (t*10) + return_int(a[i]); } return t; } string Assembler :: add_chars(string line, char a, int l, int g) { int p = line.length(); if(g == 0) for(int i = 0; i < l - p; i++) line = string(1, a) + line; else for(int i = 0; i < l - p; i++) line += string(1, a); return line; } vector<string> Assembler :: get_vector_from_line(string line) { string element; vector<string> sc_line; for(int i = 0; i < line.length(); i++) { if(line[i] == ' ' && element.length() != 0) { sc_line.push_back(element); element.clear(); } else if (line[i] != ' ') { element += string(1, line[i]); } } if(element.length() != 0) { sc_line.push_back(element); } return sc_line; } void Assembler :: generate_optab() { ifstream sc(optab_file_name.c_str()); for(string line; getline(sc, line);) { vector<string> instr = get_vector_from_line(line); optab[instr[0]] += instr[1]; } sc.close(); return; } void Assembler :: display_source_code() { ifstream ifs(src_file_name.c_str()); for(string line; getline(ifs, line);) cout<<line<<endl; return; } void Assembler :: display_object_code() { ifstream ifs(object_file_name.c_str()); for(string line; getline(ifs, line);) cout<<line<<endl; return; } Assembler::Assembler(string sc, string symtab, string op_tab, string obj) { obj_address = 0; locctr = -1; src_file_name = sc; symtab_file_name = symtab; starting_address = -1; obj_rec_no = 0; optab_file_name = op_tab; object_file_name = obj; program_name = string("DEFAULT"); generate_optab(); } string Assembler :: convert_to_hexa(int a) { stringstream ss; ss<<hex<<a; string hex_value; hex_value = ss.str(); transform(hex_value.begin(), hex_value.end(), hex_value.begin(), ::toupper); return hex_value; } int Assembler :: convert_to_decimal(string a) { stringstream ss; ss<<a; int decimal_value; ss>>hex>>decimal_value; return decimal_value; } int main() { string optab_fname, sc_fname, symtab_fname, int_fname, object_fname; int i, j; while (1) { cout<<"1 TO INPUT NEW PROGRAM\n"; cout<<"2 TO EXIT\n"; cin>>i; cin.ignore(); switch(i) { case 1: { cout<<"OPTAB FILE NAME?\n"; getline(cin, optab_fname); cout<<"SOURCE CODE FILE NAME\n"; getline(cin, sc_fname); cout<<"FILENAME WHERE SYMTAB IS TO BE STORED\n"; getline(cin, symtab_fname); cout<<"OBJECT CODE FILE NAME\n"; getline(cin, object_fname); Assembler prog(sc_fname, symtab_fname, optab_fname, object_fname); cout<<"1 TO DISPLAY OPTAB ELSE ENTER 0\n"; cin>>j; cin.ignore(); cout<<"\n"; if(j == 1) { prog.display_optab(); cout<<endl; } cout<<"1 TO DISPLAY SOURCE CODE ELSE ENTER 0\n"; cin>>j; cin.ignore(); cout<<"\n"; if(j == 1) { prog.display_source_code(); cout<<endl; } prog.generate_object_code(); cout<<"1 TO DISPLAY SYMTAB ELSE ENTER 0\n"; cin>>j; cin.ignore(); cout<<"\n"; if(j == 1) { prog.display_symtab(); cout<<endl; } cout<<"1 TO DISPLAY OBJECT CODE\n"; cin>>j; cin.ignore(); cout<<"\n"; if(j == 1) { prog.display_object_code(); cout<<endl; } cout<<"ALL DATA STRUTCTURES AND CORRESPONDING FILES TO THE PROGRAM STORED UNDER CORRESPONDING FILE NAMES RECIEVED AS INPUT\n\n"; break; } case 2: { return 0; } default: cout<<"Enter a valid choice\n"; } } return 0; }
true
b080018896b068ff8873ab2fd59400337c6a98bb
C++
SamNormcoreWayne/AdhocQueryProcessing
/MFQueryInputParser/src/ParserClass.hpp
UTF-8
2,903
2.859375
3
[ "Apache-2.0" ]
permissive
#pragma once #include <string> #include <vector> #include "ParserClassException.hpp" #include "inputStruct.hpp" #include "parsedStruct.hpp" #include "nlohmann/json.hpp" /** * INPUT: * SELECT ATTRIBUTES * NUMBER OF GROUPING VARIABLES(n) * GROUPING ATTRIBUTES(V) * F-VECT([F]) * SELECT CONDITION-VECT([σ]) * HAVING_CONDITION(G) */ using json = nlohmann::json; class ParserClass { private: InputStruct inputs; ParsedStruct parsedInputs; protected: enum aggFuncType {SUM, AVG, MAX, MIN, COUNT}; static const char* SELECT_VAR; static const char* NUM_OF_GROUPING; static const char* GROUPING_ATTRIBUTE; static const char* AGG_FUNCS; static const char* SELECT_CONDS; static const char* HAVING_CONDS; std::map<int, std::string> parseAggFunc(); std::map<int, std::string> parseSelectCond(); public: ParserClass() = default; ~ParserClass() = default; ParserClass(const ParserClass &) = delete; ParserClass& operator= (const ParserClass &) = delete; void readInput(); void readFromFile(); // class methods for attributes operators; void setSelectVar(std::string line); void setAggFunc(std::string line); inline void setSelectCond(std::string line); inline void setHavingCond(std::string line); void setNum(); // class methods for specific functions; void parseSelectAttr(); void parseHavingConds(); void parseMFStruct(); // Output ParsedStruct getParsed(); static std::vector<std::string> splitStr(std::string str, char pattern = ',') { /** * TODO: replace std::string.substr() by ParserClass::subStr() * Split a string by a specific pattern. The default pattern is ',' * PARAMS: str : string, pattern : string * RETURN: stringLst : vector<string> */ std::vector<std::string> strLst; int j = 0; for (int i = 0; i < str.size(); ++i) { //std::cout << "1:" << i << ": " << str[i] << std::endl; if (str[i] == pattern) { //std::cout << str.substr(j, i - j) << std::endl; strLst.push_back(str.substr(j, i - j)); //ParserClass::subStr(str, j, i); while(str[i + 1] == ' ') { ++i; } j = i + 1; } } strLst.push_back(str.substr(j, str.size() - 1)); return std::move(strLst); } static char* subStr(std::string str, int start, int end) { char* outStr = new char[end - start + 1]; } std::string convertMapToJSON(std::map<int, std::string> dict) const throw() { if (dict.size() == 0) { throw ParserClassException::ZeroSizeException(); return ""; } json data(dict); return data.dump(); } };
true
12f85b4773f12b5069bf8c0df34416b7353ce5ae
C++
jveezy/robot_hand
/slave/slave/motor.cpp
UTF-8
2,062
2.890625
3
[]
no_license
//============================================================================================================ /** \file motor.h * This file contains program for an ATtiny2313 motor driver that outputs to a L293D motor driver chip. The * ATtiny2313 will output a PWM signal and two directional signals to determine the H-bridge inputs. * * Revised: * \li 04-09-2011 JV Original file * * License: * This file released under the Lesser GNU Public License, version 2. This program * is intended for educational use only, but it is not limited thereto. */ //============================================================================================================ #include <avr/io.h> #include "motor.h" //-------------------------------------------------------------------------------------- /** This constructor sets up the ATtiny2313 for motor driving. */ motor::motor (void) { // Set up registers for Output Compare on OC0A // Set up Timer/Counter Control Register A TCCR0A = (1 << COM0A1); // Clear OC0A on Compare Match, set OC0A at timer max TCCR0A |= (1 << WGM01); // Fast PWM Mode. Count from 0 to 255 TCCR0A |= (1 << WGM00); // Set up Timer/Counter Control Register B TCCR0B = (1 << CS02); // Divide clock by prescaler 256 // Clear Output Compare Register OCR0A = 0; // Clear motor output pwm register // Set up pins for output // Set data directions MOTOR_DDR |= (1 << PIN_PWM); // Set all three pins to outputs MOTOR_DDR |= (1 << PIN_INA); MOTOR_DDR |= (1 << PIN_INB); // Set both directional pins off MOTOR_PORT &= ~(1 << PIN_INA); MOTOR_PORT &= ~(1 << PIN_INB); } void motor::stop (void) { // Both pins high MOTOR_PORT |= (1 << PIN_INA); MOTOR_PORT |= (1 << PIN_INB); } void motor::d0 (void) { // A high; B low MOTOR_PORT |= (1 << PIN_INA); MOTOR_PORT &= ~(1 << PIN_INB); } void motor::d1 (void) { // A low; B high MOTOR_PORT &= ~(1 << PIN_INA); MOTOR_PORT |= (1 << PIN_INB); } void motor::output (unsigned char duty_cycle) { // Set duty cycle OCR0A = duty_cycle; }
true
77a18878236d3371b69876610ba65933d50bce02
C++
cfy-github/LeetCode
/PalindromeNumber/palindromeNumber.cpp
UTF-8
335
2.734375
3
[]
no_license
class Solution { public: bool isPalindrome(int x) { if(x<0) return false; int tmp=x, div=1; while(tmp/=10) div*=10; while(x>=10) { if(x/div!=x%10) return false; x=(x%div)/10; div/=100; } if(div>1&&x!=0) return false; return true; } };
true
caebc8bd94412697be6cb2d4be9beb976f048fb6
C++
leebohee/problem-solving
/leetcode/42.cpp
UTF-8
613
2.90625
3
[]
no_license
class Solution { public: int trap(vector<int>& height) { int n = height.size(); if(n <= 1) return 0; int volume, total_volume = 0; int left_max[n]; int right_max[n]; left_max[0] = height[0]; for(int i=1; i<n; i++) left_max[i] = max(left_max[i-1], height[i]); right_max[n-1] = height[n-1]; for(int i=n-2; i>=0; i--) right_max[i] = max(right_max[i+1], height[i]); for(int i=1; i<n-1; i++) total_volume += (min(left_max[i], right_max[i]) - height[i]); return total_volume; } };
true
f824bffc152ed9635a8b430bc7c234cadb66a4b2
C++
bar4488/Game
/game/src/graphics/gl_utils.cpp
UTF-8
351
2.71875
3
[]
no_license
#include "gl_utils.h" unsigned int glutls::GetSizeOfType(unsigned int type) { switch (type) { case GL_FLOAT: return sizeof(float); case GL_UNSIGNED_INT: return sizeof(unsigned int); case GL_INT: return sizeof(int); case GL_UNSIGNED_BYTE: return sizeof(unsigned char); case GL_BYTE: return sizeof(char); } }
true
5dc122a2f64cd2c311aeee087716f73d6e1fd354
C++
hogehogei/Mary_SDCard
/src/drv/spi.cpp
UTF-8
2,561
2.703125
3
[]
no_license
#include <drv/spi.h> #include "LPC1100.h" #include "drv/systick.h" #include "drv/uart.h" SPI SPI_Drv::m_SPI[k_SPI_Channels]; bool SPI_Drv::Initialize( const SPI_Drv::Settings& settings ) { // channel 0 しか対応しない if( settings.channel > 0 ){ return false; } // 1回でやり取りするデータ長 // 4bit から 16bit まで設定可能 if( settings.bitlen < 4 || settings.bitlen > 16 ){ return false; } // SLAVE には対応しない if( !(settings.role == ROLE_MASTER) ){ return false; } // SPI0へのクロック供給を有効 __enable_ahbclk( SYSAHBCLK_SPI ); // SCK0 を PIO0_6 に割り当て IOCON_SCK0_LOC = 0x2; // SPI0のピン設定 IOCON_PIO0_6 = 0x02; // SCK0 IOCON_PIO0_8 = 0x01; // MISO0 IOCON_PIO0_9 = 0x01; // MOSI0 // SPI0をリセット PRESETCTRL &= ~0x01; PRESETCTRL |= 0x01; // SPI0のシステムクロック = SCLK SSP0CLKDIV = 1; // SPI0の bit frequency = SCLK / clock_div SSP0CPSR = settings.clock_div; // 1回でやり取りするデータ長 // mode 0, 0 SSP0CR0 = (0x0F & (settings.bitlen-1)); // CPOL=0, CPHA=0 // SSP0有効化 ここまでにレジスタの設定すませる //SSP0CR1 |= 0x01; // loopback SSP0CR1 |= 0x02; // master mode //SSP0CR1 |= 0x04; // slave mode m_SPI[0].m_IsInitialized = true; return true; } void SPI_Drv::Stop() { // SPI0を停止 SSP0CR1 = 0x00; // SPI0へのクロック供給を無効 __disable_ahbclk( SYSAHBCLK_SPI ); } SPI& SPI_Drv::Instance( uint8_t channel ) { return m_SPI[0]; } SPI::SPI() : m_IsInitialized( false ) {} SPI::SPI( bool is_initialized ) : m_IsInitialized( is_initialized ) {} SPI::~SPI() {} uint16_t SPI::TxRx( uint16_t txdata ) { uint16_t rxdata; // Send // TxFIFO Full / Busy の間は待つ while( !(SSP0SR & 0x02) || (SSP0SR & 0x10) ); SSP0DR = txdata; // SPIがデータを送り終わるまで待つ while( SSP0SR & 0x10 ); // Recv // データが来るまで待つ while( !(SSP0SR & 0x04 ) ) ; rxdata = SSP0DR; return rxdata; } uint32_t SPI::Send_U16( const uint16_t* data, uint32_t datalen ) { uint32_t i = 0; for( i = 0; i < datalen; ++i ){ TxRx( data[i] ); } // 送信したバイト数を返す return i; } uint32_t SPI::Send_U8( const uint8_t* data, uint32_t datalen ) { uint32_t i = 0; for( i = 0; i < datalen; ++i ){ TxRx( data[i] ); } // 送信したバイト数を返す return i; } uint32_t SPI::Recv_U16( uint16_t* dst, uint32_t dstlen ) { uint32_t i = 0; for( i = 0; i < dstlen; ++i ){ dst[i] = TxRx(0xFFFF); } return i; }
true
100309daf624a982cb5b2c6397afb03ea05d849e
C++
YulianStrus/Examples-of-academic-homeworks
/MVSProg/Task04/Project20/Project20/Task1.cpp
UTF-8
266
2.9375
3
[]
no_license
#include "iostream" using namespace std; void main() { float a, b; cout << "Enter the distance in miles "; cin >> a; a *= 1.609344; b = a * 0.539956803; cout << "Distance in kilometers = " << a << "\nDistance in sea miles = " << b << endl; system("pause"); }
true