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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
6019714c9372febf53a744db3298e4a47718aee5 | C++ | amarzial/project-euler-Cpp | /prob/prob41.cpp | UTF-8 | 256 | 2.6875 | 3 | [] | no_license | #include "utils.hpp"
#include <iostream>
namespace prob41 {
int Start() {
for (auto i = 7654321; i > 1235; i -= 2) {
if (utils::is_pandigital(i) and utils::is_prime(i)) {
std::cout << i << std::endl;
return 0;
}
}
return 0;
}
}
| true |
3c7d66ee65cfbf7e12f6f0cb4cd251ff3a6a33d1 | C++ | Stef997/3060_phase_2 | /deposit/deposit.cpp | UTF-8 | 5,494 | 4.0625 | 4 | [] | no_license | /*
* Deposit transaction class. Takes the address of a user
* and adds a value to the account class associated with
* the user using the named 'deposit' class with
* supplementary functions intended to check for correct
* inputs.
*
*/
#include "deposit.h"
/*
* This method takes an admin user object. It then prompts the
* user for input, tests the input, and deposits the money into
* the bank account if all inputs are valid.
*/
bool Deposit::startTransaction(AdminUser& user) {
string name;
string nameString;
string bankAccountID;
string bankAccountIDString;
string amount;
string amountString;
if (user.isAdmin()){
cout << "Enter Account Holder’s Name:";
cin >> name;
}
else{
name = user.getName();
}
// User Input
cout << "Enter account number to deposit to:";
cin >> bankAccountID;
cout << "Enter amount to deposit:";
cin >> amount;
// Validate User Input For Account
if (!isValidAccountNumber(bankAccountID)){
//Output error message indicating the lack of privileges
cout << "Error: Account number is invalid!" << endl;
return false;
} else if(!isValidName(name)){
//Output error message indicating invalid info
cout << "Error: Account holders name is invalid!" << endl;
return false;
} else{
// Convert transaction info to transaction string format
bankAccountIDString = bankAccountID;
amountString = amount;
nameString = name;
convertNameStringFormat(nameString);
convertAccountIDStringFormat(bankAccountIDString);
convertCurrencyStringFormat(amountString);
// Find User
if (!user.findAccount(name, bankAccountID)){
return false;
}
// Get user account
Account& account = user.getAccount(name, bankAccountID);
// Validate User Input For Deposit
if(!isValidAmount(amount, account)){
cout << "Error: invalid value amount!" << endl;
return false;
} else{
// Deposit into user account
deposit(stof(amountString), account);
return true;
}
}
return false;
}
/*
* This method takes a standard user object. It then prints an error
* message for invalid privilege and returns false.
*/
bool Deposit::startTransaction(StandardUser& user) {
string name;
string nameString;
string bankAccountID;
string bankAccountIDString;
string amount;
string amountString;
if (user.isAdmin()){
cout << "Enter Account Holder’s Name:";
cin >> name;
}
else{
name = user.getName();
}
// User Input
cout << "Enter account number to pay bill from:";
cin >> bankAccountID;
cout << "Enter amount to deposit:";
cin >> amount;
// Validate User Input For Account
if (!isValidAccountNumber(bankAccountID)){
//Output error message indicating the lack of privileges
cout << "Error: Account number is invalid!" << endl;
return false;
} else if(!isValidName(name)){
//Output error message indicating invalid info
cout << "Error: Account holders name is invalid!" << endl;
return false;
} else{
// Convert transaction info to transaction string format
bankAccountIDString = bankAccountID;
amountString = amount;
nameString = name;
convertNameStringFormat(nameString);
convertAccountIDStringFormat(bankAccountIDString);
convertCurrencyStringFormat(amountString);
// Find User
if (!user.findAccount(name, bankAccountID)){
return false;
}
// Get user account
Account& account = user.getAccount(name, bankAccountID);
// Validate User Input For Deposit
if(!isValidAmount(amount, account)){
cout << "Error: invalid value amount!" << endl;
return false;
} else{
// Deposit into user account
deposit(stof(amountString), account);
return true;
}
}
return false;
}
/*
* This method takes in a float values and Account object.
* It then adds the float value to the balance of the account.
*/
//Apply changes to the account associated with the user
void Deposit::deposit(float amount, Account& account){
account.addBalance(amount);
// TODO: back end stuff
}
/*
* This method takes in a string and account and checks if the string
* follows the requirements of deposit and does not go under or over
* the boundaries of the account balance.
*/
// TODO: add user parameter and current balance parameter
bool Deposit::isValidAmount(string amount, Account account){
if (!Transaction::isValidAmount(amount)){
return false;
}
// Convert inputted amount to a float value
float value;
string amountWithNoDollarSign;
//Check for dollar sign within amount string
if (amount.substr(0,1).compare("$") == 0){
amountWithNoDollarSign = amount.substr(1);
}
else{
amountWithNoDollarSign = amount;
}
// convert to float value
value = stof(amountWithNoDollarSign);
//Check for negative values
if (value < 0){
return false;
}
//Check for the value amount on deposits
if (value + account.getBalance() >= 10000){
return false;
}
return true;
}
| true |
2e4ca3b73d06e3ad699ac43d2b67d722d29c0c70 | C++ | tuogy/usaco-solutions | /milk3.cc | UTF-8 | 1,106 | 2.6875 | 3 | [] | no_license | /*
USER: guobich1
TASK: milk3
LANG: C++
*/
#ifndef __clang__
#include <bits/stdc++.h>
#endif
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
bool vis[21*21*21];
bool visC[21];
int A, B, C;
int hash3(int a, int b, int c) {
return a * 21 * 21 + b * 21 + c;
}
void dfs(int a, int b, int c) {
if (vis[hash3(a, b, c)]) return;
vis[hash3(a, b, c)] = true;
if (a == 0) visC[c] = true;
int a2b = min(a, B - b), a2c = min(a, C - c);
int b2a = min(b, A - a), b2c = min(b, C - c);
int c2a = min(c, A - a), c2b = min(c, B - b);
dfs(a - a2b, b + a2b, c);
dfs(a - a2c, b, c + a2c);
dfs(a + b2a, b - b2a, c);
dfs(a, b - b2c, c + b2c);
dfs(a + c2a, b, c - c2a);
dfs(a, b + c2b, c - c2b);
}
int main() {
ifstream fin("milk3.in");
ofstream fout("milk3.out");
fin >> A >> B >> C;
memset(vis, 0, 21*21*21*sizeof(bool));
memset(visC, 0, 21*sizeof(bool));
dfs(0, 0, C);
for (int i = 0; i < C; i++) {
if (visC[i]) fout << i << " ";
}
fout << C << endl;
return 0;
} | true |
b9390db4dedd4a4c87504ed1c68996bedac8bdd3 | C++ | sureshmangs/Code | /competitive programming/leetcode/1365. How Many Numbers Are Smaller Than the Current Number.cpp | UTF-8 | 1,793 | 3.484375 | 3 | [
"MIT"
] | permissive | Given the array nums, for each nums[i] find out how many numbers in the array are smaller than it. That is, for each nums[i] you have to count the number of valid j's such that j != i and nums[j] < nums[i].
Return the answer in an array.
Example 1:
Input: nums = [8,1,2,2,3]
Output: [4,0,1,1,3]
Explanation:
For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3).
For nums[1]=1 does not exist any smaller number than it.
For nums[2]=2 there exist one smaller number than it (1).
For nums[3]=2 there exist one smaller number than it (1).
For nums[4]=3 there exist three smaller numbers than it (1, 2 and 2).
Example 2:
Input: nums = [6,5,4,8]
Output: [2,1,0,3]
Example 3:
Input: nums = [7,7,7,7]
Output: [0,0,0,0]
Constraints:
2 <= nums.length <= 500
0 <= nums[i] <= 100
// Brute Force
class Solution {
public:
vector<int> smallerNumbersThanCurrent(vector<int>& nums) {
vector<int> res;
int n=nums.size();
for(int i=0;i<n;i++){
int cnt=0;
for(int j=0;j<n;j++){
if(i!=j && nums[j]<nums[i])
cnt++;
}
res.push_back(cnt);
}
return res;
}
};
// Optimized
// Store the count in a bucket and take the running sum.
class Solution {
public:
vector<int> smallerNumbersThanCurrent(vector<int>& nums) {
vector<int> res;
vector<int> freq(101, 0);
int n=nums.size();
for(auto &x :nums)
freq[x]++;
for(int i=1;i<101;i++){
freq[i]+=freq[i-1];
}
for(int i=0;i<n;i++){
if(nums[i]==0){
res.push_back(0);
} else {
res.push_back(freq[nums[i]-1]);
}
}
return res;
}
};
| true |
e483e1288274fd430e4ab9cb2a4fefe9284eaad7 | C++ | rosen90/GitHub | /Projects/Kostadin/21. Class String and String Stream Processing/1/Rot13.cpp | UTF-8 | 725 | 3.28125 | 3 | [] | no_license | //============================================================================
// Name : Rot13.cpp
// Author :
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <string>
using namespace std;
int main() {
string a;
cout << "Enter string: ";
getline(cin, a);
char tmp;
string res = "";
for(int i = 0; i < a.length(); i++)
{
tmp = a.at(i);
tmp = tmp + 13;
res += tmp;
}
cout<< res<< endl;
string decRes = "";
for(int i = 0; i < res.length(); i++)
{
tmp = res.at(i);
tmp -= 13;
decRes += tmp;
}
cout << decRes;
return 0;
}
| true |
cc3640b695317861d2f8cd1d1dc2346db90004d4 | C++ | vprover/vampire | /Lib/FreshnessGuard.hpp | UTF-8 | 1,073 | 2.5625 | 3 | [
"BSD-2-Clause",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /*
* This file is part of the source code of the software program
* Vampire. It is protected by applicable
* copyright laws.
*
* This source code is distributed under the licence found here
* https://vprover.github.io/license.html
* and in the source directory
*/
/**
* @file FreshnessGuard.hpp
* Defines class FreshnessGuard.
*/
#ifndef __FreshnessGuard__
#define __FreshnessGuard__
#include "Forwards.hpp"
#include "Debug/Assertion.hpp"
#include "Exception.hpp"
namespace Lib {
/**
* Some objects can be used only once. This auxiliary object
* can be used to enforce this constraint.
*/
class FreshnessGuard {
public:
FreshnessGuard() : _fresh(true) {}
bool isFresh() const { return _fresh; }
/**
* This function can be called only when the object is fresh.
* It makes the object non-fresh.
*/
void use() {
ASS(isFresh());
if(!isFresh()) {
INVALID_OPERATION("using non-fresh object");
}
_fresh = false;
}
void refresh() {
_fresh = true;
}
private:
bool _fresh;
};
}
#endif // __FreshnessGuard__
| true |
d98fe6f2d0116f64f075a59c8a3ecfd2aa7b314f | C++ | Adjuvo/SenseGlove-API | /Core/SGCoreCpp/incl/ThumperCmd.h | UTF-8 | 1,224 | 2.65625 | 3 | [
"MIT"
] | permissive | // ----------------------------------------------------------------------------------
// Thumper command
// @author: Max Lammers
// ----------------------------------------------------------------------------------
#pragma once
#include "SGCore.h"
namespace SGCore
{
namespace Haptics
{
class SGCORE_API ThumperCmd
{
protected:
int Validate(int value);
/// <summary> Minimum Force-Feedback Level </summary>
static int thmpMin;
/// <summary> Maximum Force-Feedback Level </summary>
static int thmpMax;
public:
/// <summary> Thumper intensity, a level between 0 and 100. </summary>
int magnitude;
/// <summary> Create a new Thumper Command </summary>
/// <param name="magn"></param>
/// <returns></returns>
ThumperCmd(int magn);
/// <summary> Duplicate Thumper command </summary>
/// <returns></returns>
ThumperCmd Copy();
/// <summary> Merge two ThumperCommands into one. </summary>
/// <param name="other"></param>
/// <returns></returns>
ThumperCmd Merge(ThumperCmd other);
virtual bool Equals(ThumperCmd other);
/// <summary> A command that turns off all force feedback on the Sense Glove. </summary>
static const ThumperCmd off;
};
}
} | true |
4e2c3a5f751fb22953e70a3a14abbecd865c54c9 | C++ | Murphster4DK/CSC120WEEK4 | /while/main.cpp | UTF-8 | 836 | 3.03125 | 3 | [] | no_license | #include <iostream>
using namespace std ;
int main() {
int account, balance, totalCharge, totalCredit, creditLimit;
char cont = 'h';
while (cont != '1') {
cout << "Account number: ";
cin >> account;
cout << "Balance: ";
cin >> balance;
cout << "Total Charges: ";
cin >> totalCharge;
cout << "Total Credit: ";
cin >> totalCredit;
cout << "Credit Limit: ";
cin >> creditLimit;
int endBalance = balance + totalCharge - totalCredit;
if (endBalance > creditLimit) {
cout << "Credit limit exceded";
cout << "\naccount number: " << account << "\nBalance; " << endBalance << "\nCredit Limite: "
<< creditLimit;
};
cout << "\nenter 1 to quit";
cin >> cont;
} } | true |
442e4adbdf47c0e576b8ad5e65b5ea240934d0bd | C++ | lleaff/Cpptests | /acccpp/stdstringTests.cpp | UTF-8 | 174 | 2.828125 | 3 | [] | no_license | #include <iostream>
#include <string>
int main()
{
std::string yolo = "Yolo";
std::string banga = yolo + ", banga" + '!';
std::cout << banga << std::endl;
return 0;
}
| true |
8681c8cf93adfb7e21d929c323df1e71f668e63f | C++ | hashr25/DataStructures | /Assignments/BinaryTreeSearch/src/TreeNode.cpp | UTF-8 | 137 | 2.609375 | 3 | [] | no_license | #include "TreeNode.h"
TreeNode::TreeNode(int value)
{
this -> value = value;
leftChild = NULL;
rightChild = NULL;
}
| true |
c3ff1df2ee0f754b13147ff0fb57cfb9daf55bd7 | C++ | nopanderer/ps | /bf/1963.cc | UTF-8 | 1,071 | 2.953125 | 3 | [] | no_license | /**
* 소수 경로
* 1963
*/
#include <iostream>
#include <queue>
#include <algorithm>
#include <string>
using namespace std;
int T,A,B;
int c[10000];
bool prime[10000];
int change(int num,int i,int j){
if(i==0 && j==0) return -1;
string s = to_string(num);
s[i] = j+'0';
return stoi(s);
}
int main(){
for(int i=2;i<=10000;i++){
if(prime[i] == false){
for(int j=i*i;j<=10000;j+=i){
prime[j] = true;
}
}
}
for(int i=0;i<=10000;i++){
prime[i] = !prime[i];
}
cin>>T;
while(T--){
fill(c,c+10000,0);
cin>>A>>B;
c[A] = 1;
queue<int> q;
q.push(A);
while(!q.empty()){
int cur = q.front();
q.pop();
for(int i=0;i<4;i++){
for(int j=0;j<10;j++){
int next = change(cur,i,j);
if(next != -1){
if(prime[next] && c[next]==0){
c[next] = c[cur] + 1;
q.push(next);
}
}
}
}
}
if(c[B]){
cout<<c[B]-1<<'\n';
}
else{
cout<<"Impossible\n";
}
}
return 0;
}
| true |
a1b1452f8f26ff332376394d95c1223e32b75aae | C++ | Gfast2/ABArbeit | /_2014_5_29_Final_01/processCommand.ino | UTF-8 | 9,673 | 2.765625 | 3 | [] | no_license |
//------------------------------------------------------------------------------
void releaseMotor(int num){
switch(num){
case 0: digitalWrite(ORIG_X_ENABLE_PIN,HIGH); break;//TODO: try out if this pin get low will disable the motors
case 1: digitalWrite(ORIG_Y_ENABLE_PIN,HIGH); break;
case 2: digitalWrite(ORIG_Z_ENABLE_PIN,HIGH); break;
}
}
//------------------------------------------------------------------------------
void activeMotor(int num){
switch(num){
case 0: digitalWrite(ORIG_X_ENABLE_PIN,LOW); break;//TODO: try out if this pin get low will disable the motors
case 1: digitalWrite(ORIG_Y_ENABLE_PIN,LOW); break;
case 2: digitalWrite(ORIG_Z_ENABLE_PIN,LOW); break;
}
}
//------------------------------------------------------------------------------
static void where() {
Serial.print("X:"); Serial.print(posx);
Serial.print("mm Y:"); Serial.print(posy);
Serial.print("mm Z:"); Serial.print(posz);
Serial.print("mm F"); Serial.print(123);//printFeedRate();
Serial.print("\n");
}
void fanOn(){
digitalWrite(HEATER_0_PIN,HIGH);
Serial.println(F("Mainboard Fan On"));
}
void fanOff(){
digitalWrite(HEATER_0_PIN,LOW);
Serial.println(F("Mainboard Fan Off"));
}
void motorDisable(){
digitalWrite(ORIG_X_ENABLE_PIN, HIGH); //disable all motor.
digitalWrite(ORIG_Y_ENABLE_PIN, HIGH);
digitalWrite(ORIG_Z_ENABLE_PIN, HIGH);
Serial.println(F("motors disabled."));
}
void motorEnable(){
digitalWrite(ORIG_X_ENABLE_PIN, LOW); //disable all motor.
digitalWrite(ORIG_Y_ENABLE_PIN, LOW);
digitalWrite(ORIG_Z_ENABLE_PIN, LOW);
Serial.println(F("motors enabled."));
}
void ledCOn (){ //cold led control
}
void ledCOff (){
}
void ledWOn (){
}
void ledWOff (){
}
//Input coordinate y, get x on this line
float ac(float y){
float x;
//y=k·x+(COORDMOTORC[Y])
//k = (Ya-Yc) / (Xa-Xc)
float k = ((float)COORDMOTORA[Y]-(float)COORDMOTORC[Y]) / ((float)COORDMOTORA[X] - (float)COORDMOTORC[X]);// huge fund! if wanna get float value from integer value based
/*
Serial.print("COORDMOTORA[Y]");
Serial.println(COORDMOTORA[Y]);
Serial.print("COORDMOTORC[Y]");
Serial.println(COORDMOTORC[Y]);
Serial.print("COORDMOTORA[X]");
Serial.println(COORDMOTORA[X]);
Serial.print("COORDMOTORC[X]");
Serial.println(COORDMOTORC[X]);
Serial.print("k: ");
Serial.println(k);
*/
x = (DELTA_RADIUS + y) / k;
return x;
}
//this return the value x is minus the same value from ac()
float bc(){
float x;
return x;
}
// Check if possible get target coordinate.
int coordcheck(float x, float y, float z){
// check y value legel.
/*
Serial.println(F("X,Y,Z in coordcheck function: "));
Serial.println(x); Serial.println(y); Serial.println(z);
*/
if(y <= COORDMOTORC[Y] || y >= COORDMOTORA[Y]){
Serial.println(F("y coord inpossible."));
return 0;
}
/* //Deactive this z check for original Test.
// check z value legel
if(z < 0 || z > 2000){
Serial.println(F("z coord inpossible."));
return 0;
}
*/
//Through y get x value on both line BC and AC.
float tempX = ac(y); //tempX should always positive. and -tempX should always on line BC
Serial.println(tempX);
if(x >= tempX || x <= -tempX){
Serial.println(F("line coord inpossible."));
return 0;
}
return 1; //legal
}
/*
//------------------------------------------------------------------------------
static void printConfig() {
Serial.print(m1d); Serial.print("="); Serial.print(limit_top); Serial.print(",");
Serial.print(limit_left); Serial.print("\n");
Serial.print(m2d); Serial.print("="); Serial.print(limit_top); Serial.print(",");
Serial.print(limit_right);Serial.print("\n");
Serial.print("Bottom="); Serial.println(limit_bottom);
Serial.print("Feed rate="); printFeedRate();
}
*/
//------------------------------------------------------------------------------
static void help() {
Serial.println();
Serial.println(F("== DRAWBOT - http://github.com/i-make-robots/Drawbot/ =="));
Serial.println(F("All commands end with a semi-colon."));
Serial.println(F("Input M100 to show up this help."));
Serial.println(F("CONFIG [Tx.xx] [Bx.xx] [Rx.xx] [Lx.xx];"));
Serial.println(F(" - display/update this robot's configuration."));
Serial.println(F("TELEPORT [Xx.xx] [Yx.xx]; - move the virtual plotter."));
Serial.println(F("support the following G-codes (http://en.wikipedia.org/wiki/G-code):"));
Serial.println(F("G00,G01,G02,G03,G04,G20,G21,G28,G90,G91,M18,M114"));
}
/*
//------------------------------------------------------------------------------
static void printFeedRate() {
//Serial.print("f1= ");
Serial.print(feed_rate * 60.0 / mode_scale);
Serial.print(mode_name);
Serial.println("/min");
}
*/
//------------------------------------------------------------------------------
// feed rate is given in units/min and converted to cm/s ************************
// the units/min, units can be in "mm" or in "in"
static void setFeedRate(float v) {
/*
float v1 = v * mode_scale / 60.0;
if( feed_rate != v1 ) {
feed_rate = v1; //feed rate is now in unit: cm/s
if(feed_rate > MAX_VEL) feed_rate=MAX_VEL;
if(feed_rate < MIN_VEL) feed_rate=MIN_VEL;
}
long step_delay1 = 1000000.0 / (feed_rate/THREADPERSTEP1); //where comes the 1000000
long step_delay2 = 1000000.0 / (feed_rate/THREADPERSTEP2); //in () unit: steps/s
step_delay = step_delay1 > step_delay2 ? step_delay1 : step_delay2;
Serial.print("step_delay=");
Serial.println(step_delay);
//printFeedRate();
*/
}
/*
//------------------------------------------------------------------------------
// instantly move the virtual plotter position
// does not validate if the move is valid
static void teleport(float x,float y) {
posx=x;
posy=y;
// @TODO: posz?
long L1,L2; //teleport the new set point
IK(posx,posy,L1,L2);
laststep1=L1;
laststep2=L2;
}
//------------------------------------------------------------------------------
static int processSubcommand() {
int found=0;
char *ptr=buffer;
while(ptr && ptr<buffer+sofar && strlen(ptr)) {
if(!strncmp(ptr,"G20",3)) {
Serial.println("input Unite: inches");
mode_scale=25.4f; // inches -> mm, 1 inche == 25.4 mm
strcpy(mode_name,"in");
//printFeedRate();
found=1;
}
else if(!strncmp(ptr,"G21",3)) { //say the imput parameter is always set to "mm" and be here convertered.
Serial.println("input Unite: mm");
mode_scale=1; // mm -> mm, 1 mm = 1 mm
strcpy(mode_name,"mm");
//printFeedRate();
found=1;
}
else if(!strncmp(ptr,"G90",3)) {
// absolute mode
absolute_mode=1;
found=1;
Serial.println("in absolute mode");
}
else if(!strncmp(ptr,"G91",3)) {
// relative mode
absolute_mode=0;
found=1;
Serial.println("in relative mode");
}
//ptr=strchr(ptr,' ')+1; //here is the deal!!
//when strchr() return NULL, this ChipKIT IDE can not handle
ptr=strchr(ptr,' ');
if(ptr != NULL){
ptr += 1;
}
}
return found;
}
*/
/**
* Set the logical position
* @input npx new position x
* @input npy new position y
*/
void position(float npx,float npy,float npz) {
// here is a good place to add sanity tests
posx=npx;
posy=npy;
posz=npz;
}
/**
* Look for character /code/ in the buffer and read the float that immediately follows it.
* @input code the character to look for.
* @input val the return value if /code/ is not found.
**/
float parsenumber(char code, float val){
char *ptr=buffer;
while(ptr && *ptr && ptr<buffer+sofar){
if(*ptr==code) {
return atof(ptr+1);
}
ptr=strchr(ptr,' ') + 1;
}
return val;
}
/**
* The Serial command parser
*/
void processCommand(){
int cmd = parsenumber('G', -1);
switch(cmd){
case 0:
case 1: //move as line
//motorEnable();
/* //original code:
line( parsenumber('X',(mode_abs?posx:0)) + (mode_abs?0:posx),
parsenumber('Y',(mode_abs?posy:0)) + (mode_abs?0:posy),
parsenumber('Z',(mode_abs?posz:0)) + (mode_abs?0:posz) );
*/
/*
float X = parsenumber('X',(mode_abs?posx:0));
float Y = parsenumber('Y',(mode_abs?posy:0));
float Z = parsenumber('Z',(mode_abs?posz:0));
*/
float X,Y,Z;
X = parsenumber('X',(mode_abs?posx:0));
Y = parsenumber('Y',(mode_abs?posy:0));
Z = parsenumber('Z',(mode_abs?posz:0));
if(coordcheck(X,Y,Z)){
line(X,Y,Z);
} else {
Serial.println(F("coordinate beyond the possible area"));
}
/*
line( parsenumber('X',(mode_abs?posx:0)) ,
parsenumber('Y',(mode_abs?posy:0)) ,
parsenumber('Z',(mode_abs?posz:0)) );
*/
//motorDisable();
break;
case 90: mode_abs=1; break; //absolute mode
case 91: mode_abs=0; break; //relative mode
case 92: //set logical position (Teleport)
position( parsenumber('X',0),
parsenumber('Y',0),
parsenumber('Z',0) );
break;
}
cmd = parsenumber('M', -1);
switch(cmd){
case 84: motorDisable(); break;
case 85: motorEnable(); break;
case 100: help(); break;
case 114: where(); break;
case 106: fanOn(); break;
case 107: fanOff();break;
case 200: ledCOn();break;
case 201: ledCOff(); break;
case 202: ledWOn(); break;
case 203: ledWOff(); break;
case 204: parsenumber('c',-1);
case 205: parsenumber('w',-1);
case 251: calibration();
}
}
| true |
93e2dceba300fac7412e38270ab31cc73dbaa374 | C++ | GohEK/Assignment-CGP- | /GameAssignment/Player.cpp | UTF-8 | 2,602 | 2.6875 | 3 | [] | no_license | #include "Player.h"
#include "GGraphic.h"
#include "GInput.h"
Player::Player()
{
sprite = NULL;
texture = NULL;
}
Player::~Player()
{
sprite->Release();
sprite = NULL;
texture->Release();
texture = NULL;
}
void Player::init()
{
D3DXCreateSprite(GGraphic::getInstance()->d3dDevice, &sprite);
D3DXCreateTextureFromFileEx(GGraphic::getInstance()->d3dDevice, "image/character.png", D3DX_DEFAULT, D3DX_DEFAULT,
D3DX_DEFAULT, NULL, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED,
D3DX_DEFAULT, D3DX_DEFAULT,
D3DCOLOR_XRGB(255, 255, 255),
NULL,
NULL,
&texture);
characterSize.x = 32;
characterSize.y = 48;
characterCurrentFrame = 0;
characterSpriteRect.left = 0;
characterSpriteRect.top = 0;
characterSpriteRect.right = characterSpriteRect.left + characterSize.x;
characterSpriteRect.bottom = characterSpriteRect.top + characterSize.y;
scaling.x = 1.5f;
scaling.y = 1.5f;
animationTimer = 0;
animationRate = 1.0f / 4;
speed = 100.0f;
animationRow = 0;
isCharacterMoving = false;
direction.x = 0;
direction.y = 1;
position.x = 50;
position.y = 200;
}
void Player::update()
{
if (GInput::getInstance()->isKeyDown(DIK_A))
{
animationRow = 1;
isCharacterMoving = true;
direction.x = -1;
direction.y = 0;
}
else if (GInput::getInstance()->isKeyDown(DIK_W))
{
animationRow = 3;
isCharacterMoving = true;
direction.x = 0;
direction.y = -1;
}
else if (GInput::getInstance()->isKeyDown(DIK_S))
{
animationRow = 0;
isCharacterMoving = true;
direction.x = 0;
direction.y = 1;
}
else if (GInput::getInstance()->isKeyDown(DIK_D))
{
animationRow = 2;
isCharacterMoving = true;
direction.x = 1;
direction.y = 0;
}
else
{
characterCurrentFrame = 0;
isCharacterMoving = false;
}
}
void Player::fixedUpdate()
{
if (isCharacterMoving)
{
animationTimer += 1 / 60.0f;
D3DXVECTOR2 velocity = direction * (speed / 60.0f);
position += velocity;
}
if (animationTimer >= animationRate)
{
animationTimer -= animationRate;
characterCurrentFrame++;
characterCurrentFrame %= 3;
}
characterSpriteRect.left = characterSize.x * characterCurrentFrame;
characterSpriteRect.top = animationRow * characterSize.y;
characterSpriteRect.right = characterSpriteRect.left + characterSize.x;
characterSpriteRect.bottom = characterSpriteRect.top + characterSize.y;
D3DXMatrixTransformation2D(&mat, NULL, 0.0, &scaling, NULL, NULL, &position);
}
void Player::draw()
{
sprite->Begin(D3DXSPRITE_ALPHABLEND);
sprite->SetTransform(&mat);
sprite->Draw(texture, &characterSpriteRect, NULL, NULL, D3DCOLOR_XRGB(255, 255, 255));
sprite->End();
} | true |
e0440bc2ef475e241e8d230bdf57c148abc8f245 | C++ | kitschpatrol/Cinder-Zmq | /samples/ImagePublisher/src/ImagePublisherApp.cpp | UTF-8 | 2,118 | 2.609375 | 3 | [] | no_license | #include "cinder/Log.h"
#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"
#include "cinder/ip/Resize.h"
#include "ofxZmq.h"
using namespace ci;
using namespace ci::app;
using namespace std;
class ImagePublisherApp : public App {
public:
void setup() override;
void mouseDown(MouseEvent event) override;
void update() override;
void draw() override;
private:
ofxZmqPublisher publisher;
SurfaceRef mTestImage;
gl::TextureRef mTestTexture;
};
void ImagePublisherApp::setup() {
// start server
// If we want to send from one publisher to multiple subscribers, we bind the publisher and connect the subscriber
// publisher.bind("tcp://*:9999");
// If we want to send from mulitple publishers to one subscriber, we connect the publisher and bind the subscriber
publisher.connect("tcp://localhost:9999");
}
void ImagePublisherApp::mouseDown(MouseEvent event) {
CI_LOG_V("Sending...");
mTestImage = Surface::create(loadImage(loadUrl("http://thecatapi.com/api/images/get")));
mTestTexture = gl::Texture::create(*mTestImage);
// Resize Image
// SurfaceRef testImageResized = Surface::create(500, 500, false);
// ip::resize(*mTestImage, testImageResized.get());
// ImageSourceRef testImageSource = (ImageSourceRef)*testImageResized;
// Compress to jpeg
OStreamMemRef os = OStreamMem::create();
DataTargetRef target = DataTargetStream::createRef(os);
writeImage(target, (ImageSourceRef)*mTestImage, ImageTarget::Options().quality(0.5), "jpg");
// Write to ZeroMQ
const void *data = os->getBuffer();
size_t size = os->tell();
if (publisher.send(data, size)) {
CI_LOG_V("Sent " << size / 1000 << "kB");
} else {
CI_LOG_E("Send failed.");
}
}
void ImagePublisherApp::update() {
}
void ImagePublisherApp::draw() {
gl::clear(Color(0, 0, 0));
gl::draw(mTestTexture);
gl::drawString("Click anywhere to send a cat to subscribers over ZeroMQ.", vec2(10, 10));
}
CINDER_APP(ImagePublisherApp, RendererGl, [](App::Settings *settings) { //
settings->setTitle("Cinder-Zmq Image Publisher Sample"); //
}) //
| true |
fe50977347b79177599b15ca1dd61f6136ed5914 | C++ | GJP1106/C-_Study | /C++笔记/第四章/4-4/4-4/ca.h | GB18030 | 633 | 3.09375 | 3 | [] | no_license | #ifndef _CA_H__
#define __CA_H__
template <typename C>
class A { //ͨ
public:
template <typename T2>
A(T2 v1, T2 v2);
//A(T2 v1, T2 v2) { //캯ҲԼģ壬ģCûйϵ
//}
template <typename T>
void myft(T tmpt) { //Աģ
cout << tmpt << endl;
}
void myftpt() {}
C m_ic;
};
template <typename C> //ȸģб
template <typename T2> //ٸ캯Լģб
A<C>::A(T2 v1, T2 v2) {
cout << v1 << v2 << endl;
}
template <typename T>
void myfunc123(T v1, T v2) {
cout << v1 + v2 << endl;
}
#endif | true |
61be197448d45e19936b18325c2285f1bf322902 | C++ | SlaveWilson/leetcode | /solved/easy/1450. Number of Students Doing Homework at a Given Time/main.cpp | UTF-8 | 570 | 3.4375 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <vector>
using namespace std;
class Solution
{
public:
int busyStudent(vector<int> &startTime, vector<int> &endTime, int queryTime)
{
int count = 0;
for (int i = 0; i < startTime.size(); i++)
{
if (queryTime >= startTime[i] && queryTime <= endTime[i])
count++;
}
return count;
}
};
int main()
{
vector<int> startTime{1, 2, 3};
vector<int> endTime{3, 2, 7};
int queryTime = 4;
Solution solution;
int output = solution.busyStudent(startTime, endTime, queryTime);
cout << output << endl;
} | true |
133054f13aa39a3eb216411a356a7ec4e3c64b7a | C++ | mehrta/monotone-polygon-decomposition | /source code/PolygonDecomposition/trapezoidal_decomposition.h | UTF-8 | 5,473 | 2.96875 | 3 | [] | no_license | #pragma once
#include "simple_polygon.h"
namespace pd
{
enum QueryStructureNodeType { QSNT_X, QSNT_Y, QSNT_TRAPEZOID };
struct Trapezoid
{
int id;
pd::Point top_left, top_right, bottom_left, bottom_right; // vertices of the trapezoid
int top_left_trap, top_right_trap, bottom_left_trap, bottom_right_trap; // ID of adjecent trapezoids
int left, right;
};
struct XNode
{
int id;
int left;
int right;
};
struct YNode
{
int id;
int top;
int bottom;
};
// forward declartion
struct QsnTag;
//
// Query Structure Node (QSN)
struct Qsn
{
QueryStructureNodeType type; // Type of this node
QsnTag *tag; // A tag that discribes this node
int id; // ID of this node (not used by algorithm)
int visit_count; // how many times this node visited
Qsn()
{
id = (++id_counter_);
visit_count = 0;
}
static void ResetIdCounter()
{
id_counter_ = 0;
}
private:
static int id_counter_;
};
struct QsnTag // Query Structure Node Tag
{ };
struct QsnTag_X : QsnTag
{
int value; // Index of line segment associated to this node
Qsn *left_child; // Query point is located in the left of the line segment
Qsn *right_child; // Query point is located in the right of the line segment
};
struct QsnTag_Y : QsnTag
{
float value; // Y-coordinate of a point that is associated to this node
Qsn *left_child; // Y-Cordinate of the Query point is smaller than this->value
Qsn *right_child; // Y-Cordinate of the Query point is greater than this->value
};
struct QsnTag_Trapezoid : QsnTag
{
float y1; // Y-Cordinate of the higher horizontal edge of the trapezoid
float y2; // Y-Cordinate of the lower horizontal edge of the trapezoid
int left_edge; // Index of left line segment of the trapezoid
int right_edge; // Index of right line segment of the trapezoid
Qsn *bottom_left_trapezoid; // Bottom-Left adjacent trapezoid
Qsn *bottom_right_trapezoid; // Bottom-Right adjacent trapezoid
Qsn *top_left_trapezoid; // Top-Left adjacent trapezoid
Qsn *top_right_trapezoid; // Top-Right adjacent trapezoid
QsnTag_Trapezoid()
{
bottom_left_trapezoid =
bottom_right_trapezoid =
top_left_trapezoid =
top_right_trapezoid = nullptr;
}
};
class TrapezoidalDecomposition
{
public:
TrapezoidalDecomposition(void);
~TrapezoidalDecomposition(void);
// Decompose simple polygon to trapezoidal components (using Seidel's algorithm)
// and returns the root of the query structure
Qsn* Decompose();
// Sets polygon that should be decompose
void set_polygon(SimplePolygon *sp);
//
void set_bounding_box(Rectangle *bounding_box);
//
void TraverseQueryStructureTree();
void AddDiagonal(int v1, int v2);
// Release all allocated memory
void FreeMemory();
// Locates a split or merge vertex
Qsn* LocateVertex(int vertex, VERTEX_TYPE vertex_type);
Point GetTrapezoidTopLeft(QsnTag_Trapezoid* tag);
Point GetTrapezoidTopRight(QsnTag_Trapezoid* tag);
Point GetTrapezoidBottomLeft(QsnTag_Trapezoid* tag);
Point GetTrapezoidBottomRight(QsnTag_Trapezoid* tag);
bool IsInternalTrapezoid(QsnTag_Trapezoid* tag);
std::list<Qsn*> *get_trapezoids();
std::list<Qsn*> *get_x_nodes();
std::list<Qsn*> *get_y_nodes();
LineSegment* get_line_segments();
SimplePolygon* get_polygon();
int get_num_x_nodes();
int get_num_y_nodes();
int get_num_trapezoids();
int get_num_line_segments();
void print(Qsn *node);
void print();
private:
SimplePolygon *sp_;
Rectangle* bounding_box_;
LineSegment *line_segments_; // Line segments (edges of polygon + diagonals)
int num_line_segments_; // Number of line segments
Qsn *root_; // Root of the query structure (produced by Seidel's algorithm)
std::list<Qsn*> trapezoids_;
std::list<Qsn*> x_nodes_;
std::list<Qsn*> y_nodes_;
int num_x_nodes_;
int num_y_nodes_;
int num_trapezoids_;
int traverse_counter_; // how many times Query Structure Nodes is traversed
// Should be called before decomposition
void Initialize();
// Generates a random permutation
static void GenerateRandomPermutation (int size, int *buffer);
// Locates trapezoid that contains upper point of line_segment
Qsn* LocateUpperVertex(int line_segment);
// Adds a line segment to the query structure
void AddLineSegment(int line_segment);
// Get next bottom (adjecent) trapezoid that should be divided verticaly
Qsn* GetNextTrapezoid(Qsn *current_trapezoid, int line_segment);
// Divides a trapezoid horizontally and returns upper trapezoid
Qsn* DivideTrapezoidHorizontally(Qsn *trapezoid, float y_value);
// Divides a trapezoid vertically
void DivideTrapezoidVertically(Qsn *trap, int line_segment, Qsn **left_trap, Qsn **right_trap);
//
void UpdateAdjacentVertexTag (Qsn* trap);
void TraverseQueryStructureTree(Qsn *node);
};
inline QsnTag_Trapezoid* GetTag_T(Qsn *trapezoid)
{
return static_cast<QsnTag_Trapezoid*>(trapezoid->tag);
}
inline QsnTag_X* GetTag_X(Qsn *x_node)
{
return static_cast<QsnTag_X*>(x_node->tag);
}
inline QsnTag_Y* GetTag_Y(Qsn *y_node)
{
return static_cast<QsnTag_Y*>(y_node->tag);
}
inline void CreateTrapezoid(float y1, float y2, Qsn **new_trap, QsnTag_Trapezoid **tag_new_trap)
{
Qsn *trap = new Qsn();
QsnTag_Trapezoid *tag = new QsnTag_Trapezoid();
tag->y1 = y1;
tag->y2 = y2;
trap->type = QSNT_TRAPEZOID;
trap->tag = tag;
(*new_trap) = trap;
(*tag_new_trap) = tag;
}
} | true |
09321707ef3ca543d21af236223e02df8419517d | C++ | Paynekk/Learning_c_plus_plus | /fundamentos/15_tipos_estructurados/4_ como_se_copian_tablas_y_tuplas.cpp/0_copia_de_tablas_y_tuplas.cpp | UTF-8 | 349 | 3.125 | 3 | [] | no_license | #include <iostream>
using namespace std;
typedef double TresReales[3];
struct Grupito{
int a;
bool b;
char c;
};
int main(){
TresReales R = {0.5, 1.0, 2.0};
TresReales S;
Grupito G = {1, false, 'S'};
Grupito H;
H = G;// struct si que se puede hacer
// S = R en array no se puede hacer
for(int i = 0;i < 3; i++) S[i] = R[i];
} | true |
56e5776a2293602295687f4bce90cdbe5aac9142 | C++ | LoA-Xyh/TSinghua_C-Basic | /C2语言基础/C2-3实心菱形/2-3实心菱形/源.cpp | WINDOWS-1252 | 722 | 3.140625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
int floor = 0;
cin >> floor;
for (int sFloor = floor-1; sFloor >= 0; sFloor--) {
for (int fSpace = 1; fSpace <= sFloor; fSpace++) {
cout << " ";
}
for (int sign = 2 * (floor - sFloor) -1; sign > 0;sign--) {
cout << "*";
}
for (int bSpace = 1; bSpace <= floor; bSpace++) {
cout << " ";
}
cout << endl;
}
//ӡN
for (int sFloor = floor - 1; sFloor > 0; sFloor--) {
for (int fSpace = floor; fSpace > sFloor; fSpace--) {
cout << " ";
}
for (int sign = 2 * (sFloor)-1; sign > 0; sign--) {
cout << "*";
}
for (int bSpace = floor; bSpace > sFloor; bSpace--) {
cout << " ";
}
cout << endl;
}
return 0;
} | true |
ff65a6ae4b44181ac6c3a1e6a300fbcfdfb1641c | C++ | Hansimov/cs-notes | /leetcode/0300_v2.cpp | UTF-8 | 2,212 | 3.21875 | 3 | [] | no_license | /*
- [LeetCode] Longest Increasing Subsequence 最长递增子序列 - Grandyang - 博客园
https://www.cnblogs.com/grandyang/p/4938187.html
- algorithm - How to determine the longest increasing subsequence using dynamic programming? - Stack Overflow
https://stackoverflow.com/questions/2631726/how-to-determine-the-longest-increasing-subsequence-using-dynamic-programming
- Longest Increasing Subsequence Size (N log N) - GeeksforGeeks
https://www.geeksforgeeks.org/longest-monotonically-increasing-subsequence-size-n-log-n/
- Longest increasing subsequence - Wikipedia
https://en.wikipedia.org/wiki/Longest_increasing_subsequence
*/
#include <iostream>
#include <fstream>
#include <sstream>
#include <stdio.h>
#include <string>
#include <cstring>
#include <stack>
#include <vector>
#include <algorithm>
#include <math.h>
using namespace std;
int lengthOfLIS(vector<int>& nums) {
if (nums.size()==0) return 0;
int n = nums.size();
vector <int> v;
for (auto num : nums) {
auto idx = lower_bound(v.begin(), v.end(), num);
if (idx == v.end()) {
v.push_back(num);
} else {
*idx = num;
}
}
return v.size();
}
int main() {
string sin, rin;
vector<string> vs;
vector<vector<int>> vn;
vector<int> vr;
ifstream fp;
fp.open("0300.txt");
int d;
int c=0;
while (getline(fp, sin, '\n')) {
vs.push_back(sin);
stringstream ss(sin);
vector<int> vni = {};
while (ss >> d) {
vni.push_back(d);
// printf("%d ", d);
}
vn.push_back(vni);
getline(fp, rin, '\n');
vr.push_back(stoi(rin.c_str(),NULL,10));
// ++c;printf("==%d==\n", c);
}
fp.close();
printf("%s\t%s\t%s\t%s\n", "T","L", "√", "?");
printf("--- --- --- --- \n");
int correct_cnt=0;
for (int i=0; i<vs.size(); ++i) {
int res = lengthOfLIS(vn[i]);
bool is_correct = res==vr[i];
printf("%d\t%d\t%d\t%d\n", is_correct, 2*i+1, vr[i], res);
if (is_correct) ++correct_cnt;
}
printf("--- --- --- --- \n");
printf("%d/%d\n", correct_cnt, vr.size());
return 0;
} | true |
446a1824ae78e0f40ae8633ee50cc3ca97c28dc8 | C++ | mickey9910326/Homework | /DataStructure/HW5/Queue.cpp | UTF-8 | 915 | 3.453125 | 3 | [] | no_license | #include "Queue.h"
template<typename ItemType>
Queue<ItemType>::Queue(int max){
maxQueue = max;
top = -1;
item = new ItemType[maxQueue];
}
template<typename ItemType>
bool Queue<ItemType>::IsEmpty() const{
return (top == -1);
}
template<typename ItemType>
bool Queue<ItemType>::IsFull() const{
return (top == maxQueue - 1);
}
template<typename ItemType>
void Queue<ItemType>::Push(ItemType newItem){
if(IsFull())
throw FullQueue();
top++;
item[top] = newItem;
}
template<typename ItemType>
PopItem Queue<ItemType>::Pop(){
if(IsEmpty())
throw EmptyQueue();
top--;
ItemType PopItem = item[0];
for (int i = 0; i < top; i++) {
item[i] = item[i+1];
}
return PopItem;
}
template<typename ItemType>
ItemType Queue<ItemType>::Size() const{
return top+1;
}
template<typename ItemType>
Queue<ItemType>::~Queue(){
delete []item;
}
| true |
3b2e0d17d8f556ce3d59e89cb53c473aa6de8c1e | C++ | ChesssFish/DS | /AVL/AVL/AVL.h | GB18030 | 1,320 | 3.28125 | 3 | [] | no_license | /*-----------------------------------------------
ļAVL.h
AVLĽڵ㡣
˰汾ʵBSTĹ
ҪkeyTypeʵֱȽ븳ֵ
-----------------------------------------------*/
#pragma once
template<typename keyType = int>class AVL;
template<typename keyType = int>
class AVLnode
{
public:
AVLnode();
AVLnode(const keyType& key);
~AVLnode();
AVLnode& operator=(AVLnode& node);
bool operator==(AVLnode& node);
bool operator<(AVLnode& node);
bool operator>(AVLnode& node);
bool operator<=(AVLnode& node);
private:
int mHeight;
keyType mKey;
AVLnode* pParent;
AVLnode* pLchild;
AVLnode* pRchild;
void _calcHeight();
friend class AVL<keyType>;
};
template<typename keyType>
class AVL
{
public:
AVL();
~AVL();
void clear(void);
void ins(keyType rec);
void del(const keyType& del);
bool find(const keyType& key);
void getInOrder();
keyType* mInOrder;
int mlen;
private:
AVLnode<keyType>* root;
int mCount;
//curΪ
void _r(AVLnode<keyType>* cur);
//curΪ
void _l(AVLnode<keyType>* cur);
//ɾcurڵ
void _del(AVLnode<keyType>* &cur);
//AVLnode*͵Ľڵ
AVLnode<keyType>*& _find(const keyType& key);
void _visit(AVLnode<keyType>* cur);
void _print(AVLnode<keyType>* cur);
}; | true |
0dbba4a3b2efd8bf6765f83b89bf0a6d4fc2631f | C++ | FefuIR/Tasks | /hash/hash.h | UTF-8 | 509 | 2.671875 | 3 | [] | no_license | #ifndef HASH_HASH_H
#define HASH_HASH_H
#include <string>
using namespace std;
struct Rec {
string fio;
unsigned int number = 0;
unsigned short int status = 0;
};
class HashEntry {
private:
unsigned int size;
Rec *table;
int HashFunction1(int number);
bool Review(Rec R);
int HashFunction2(int number);
public:
HashEntry(int n);
~HashEntry();
void Add (Rec R);
int Search(Rec R);
void Delete(Rec R);
void PrintTheTable ();
};
#endif //HASH_HASH_H
| true |
baeba65510587e50b7c4558c4404075ba5eac3e8 | C++ | SebastianDang/OpenGL | /Extra/MatrixTransform.h | UTF-8 | 507 | 2.84375 | 3 | [] | no_license | #pragma once
#ifndef MATRIX_TRANSFORM_H
#define MATRIX_TRANSFORM_H
#include "Window.h"
#include "Group.h"
/* MatrixTransform should store a 4x4 transformation matrix M which is multiplied with matrix C, which is passed to the draw method. */
class MatrixTransform : public Group
{
private:
public:
//Constructor methods.
MatrixTransform();
~MatrixTransform();
//Stores a 4x4 transformation matrix in M.
glm::mat4 M;
//Upate methods.
virtual void update(glm::mat4 C);
};
#endif
| true |
fcddedb527b09ca6ef7b683ad75a48a799a68a3b | C++ | rishabhkukreja30/DSA-questions | /Greedy Algorithms/Load_Balancing .cpp | UTF-8 | 851 | 2.703125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main() {
#ifndef ONLINE_JUDGEs
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int arr[9000];
int n, i, t, diff;
cin>>t;
while(t--) {
//take input current test case
int max_load = 0, load = 0;
cin>>n;
//stop taking input if n= -1
if(n == -1) {
break;
}
for(int i=0;i<n;i++) {
cin>>arr[i];
load += arr[i];
}
// check if load is an integer or not
if(load % n != 0) {
cout<<"-1"<<endl;
continue;
}
//find the load that is to be divided equally
load = load /n;
//greedy step
for(int i=0;i<n;i++) {
//find the difference between final load to be assigned and current load
diff += (arr[i] - load);
int ans = max(diff , -diff);
max_load = max(max_load, ans);
}
cout<<max_load<<endl;
}
return 0;
} | true |
8e83a70852cefede68e6e198126adbac08506d48 | C++ | nheyr08/OOP-Lab6-Linked-list | /LinkedList.cpp | WINDOWS-1250 | 2,913 | 4.0625 | 4 | [] | no_license | #include"LinkedList.h"
LinkedList::LinkedList()
{
//Constructor
Head = NULL;
}
void LinkedList::Push_back(int x)
{
//TODO : Insert a node to the end of the linked list, the nodes value is x.
ListNode*temp = new ListNode;
temp->data = x;
temp->next = NULL;
ListNode *ptr = Head;
if (Head == NULL)
{
Head = temp;
}//check if list is empty
else
{
while (ptr->next != NULL)
{
ptr = ptr->next;
}//find the last element of the linked list
ptr->next = temp;
}
}
void LinkedList::Push_front(int x)
{
//TODO : Insert a node to the front of the linked list, the nodes value is x.
ListNode*temp1 = new ListNode();
temp1->data = x;
temp1->next = NULL;
temp1->next = Head;
Head = temp1;
//for(int i; i<)
}
void LinkedList::Insert(int n, int data )
{
//n = n + 1;?
//TODO : Insert a node to the linked list at position index, the node's value is x.
//The index of the first node in the linked list is 0.
//create a node call to malloc
ListNode*temp1 = new ListNode();
temp1->data = data;
temp1->next = NULL;
if (n == 0)
{
Push_front(data);
}
/* if (n == 1)
{
// ListNode* Head;
temp1->next = Head;
Head = temp1;
//return;
//temp1->next = LinkedList->Head;
//LinkedList->Head = temp1;
}
*/
else {
ListNode*temp2 = Head;
for (int i = 1; i < n ; i++)
{
//if (temp2 == NULL)
temp2 = temp2->next;
}
temp1->next = temp2->next;
temp2->next = temp1;
}
}
void LinkedList::Delete(int index)
{
int n = index;
//TODO : Remove the node with index index in the linked list.
//fix the links! just ignore theone in between
//when we do that it detached but still in the memory in the heap section//for that we need to free the space taken and finally the mfcker is gone
ListNode* temp1 = Head;
if (n == 0)
{
Head = temp1->next;//head now points to second Node
free(temp1);
}
else
{
int i;
for (i = 0; i < n -2; i++)
temp1 = temp1->next;
//temp1 points to (n-1)th node
ListNode*temp2 = temp1->next;//represents the nth node
temp1->next = temp2->next; //reference (n+1)th node
free(temp2); //delete temp2
}
}
void LinkedList::Reverse()
{
//TODO : Reverse the linked list.
//this uses the iterative method
ListNode *temp,*prev,*next;
temp = Head;
prev = NULL;
while (temp != NULL)
{
next = temp->next;
temp->next=prev;
prev = temp;
temp = next; //to adjust the variable head
}
Head = prev;
//return Head;
}
void LinkedList::Print()
{
cout << "List: ";
//TODO : Print all the elements in the linked list in order.
ListNode*temp = Head;
while (temp != NULL) {
cout << temp->data<<" ";
temp = temp->next;
}
cout << endl;
}
LinkedList::~LinkedList()
{
//Destructor
//cout << "everything is destroyed" << endl;
}
| true |
07cda2deed625432ea78277f9a365a33b64e65fc | C++ | fanxinglanyu/AcceleratedC | /Unit3/3.cpp | UTF-8 | 733 | 3.484375 | 3 | [] | no_license | //3
#include<iostream>
#include<string>
#include<vector>
using std::string; using std::endl;
using std::cout; using std::cin;
using std::vector;
int main(int argc, char const *argv[])
{
cout << "Please enter word:";
vector<string> word;
vector<int> count;
typedef vector<string>::size_type vec_sz;
string s;
while(cin >> s){
bool found = false;
for (int i = 0; i != word.size(); ++i)
{
if(s == word[i]){
++count[i];
found = true;
}
}
if(found == false){
word.push_back(s);
count.push_back(1);
}
}
cout << endl;
for (int i = 0; i != word.size(); ++i)
{
cout << word[i] << " appear " << count[i] << " times!"<< endl;
}
return 0;
}
| true |
fc0e711504b26895eddbd937ce96ce6df0811f3d | C++ | veteran12/leetcode_veteran | /PlusOne.cpp | UTF-8 | 481 | 3 | 3 | [] | no_license | class Solution {
public:
vector<int> plusOne(vector<int> &digits) {
int len = digits.size();
int carry = 0;
vector<int> res;
digits[len-1] += 1;
for(int i=len-1; i>=0; i--) {
res.push_back((carry + digits[i]) % 10);
carry = (carry + digits[i]) / 10;
}
if(carry != 0)
res.push_back(carry);
reverse(res.begin(), res.end());
return res;
}
}; | true |
0d7f26177241748eb1aaa3cd7fbb081afea71682 | C++ | codingFreak-Adisin/Av-Automation-V1 | /RFID_Sensor_Powered_by_Arduino_Uno.ino | UTF-8 | 3,562 | 3.015625 | 3 | [] | no_license | #include <SPI.h>
#include <RFID.h>
#include <Servo.h>
RFID rfid(10, 9); //D10:pin of tag reader SDA. D9:pin of tag reader RST
unsigned char status;
unsigned char str[MAX_LEN]; //MAX_LEN is 16: size of the array
String accessGranted [2] = {"29010156614"}; //RFID serial numbers to grant access to
int accessGrantedSize = 2; //The number of serial numbers
Servo lockServo; //Servo for locking mechanism
int lockPos = 15; //Locked position limit
int unlockPos = 75; //Unlocked position limit
boolean locked = true;
int redLEDPin = 5;
int greenLEDPin = 6;
void setup()
{
Serial.begin(9600); //Serial monitor is only required to get tag ID numbers and for troubleshooting
SPI.begin(); //Start SPI communication with reader
rfid.init(); //initialization
pinMode(redLEDPin, OUTPUT); //LED startup sequence
pinMode(greenLEDPin, OUTPUT);
digitalWrite(redLEDPin, HIGH);
delay(200);
digitalWrite(greenLEDPin, HIGH);
delay(200);
digitalWrite(redLEDPin, LOW);
delay(200);
digitalWrite(greenLEDPin, LOW);
lockServo.attach(3);
lockServo.write(lockPos); //Move servo into locked position
Serial.println("Place card/tag near reader...");
}
void loop()
{
if (rfid.findCard(PICC_REQIDL, str) == MI_OK) //Wait for a tag to be placed near the reader
{
Serial.println("Card found");
String temp = ""; //Temporary variable to store the read RFID number
if (rfid.anticoll(str) == MI_OK) //Anti-collision detection, read tag serial number
{
Serial.print("The card's ID number is : ");
for (int i = 0; i < 4; i++) //Record and display the tag serial number
{
temp = temp + (0x0F & (str[i] >> 4));
temp = temp + (0x0F & str[i]);
}
Serial.println (temp);
checkAccess (temp); //Check if the identified tag is an allowed to open tag
}
rfid.selectTag(str); //Lock card to prevent a redundant read, removing the line will make the sketch read cards continually
}
rfid.halt();
}
void checkAccess (String temp) //Function to check if an identified tag is registered to allow access
{
boolean granted = false;
for (int i=0; i <= (accessGrantedSize-1); i++) //Runs through all tag ID numbers registered in the array
{
if(accessGranted[i] == temp) //If a tag is found then open/close the lock
{
Serial.println ("Access Granted");
granted = true;
if (locked == true) //If the lock is closed then open it
{
lockServo.write(unlockPos);
locked = false;
}
else if (locked == false) //If the lock is open then close it
{
lockServo.write(lockPos);
locked = true;
}
digitalWrite(greenLEDPin, HIGH); //Blue LED sequence
delay(200);
digitalWrite(greenLEDPin, LOW);
delay(200);
digitalWrite(greenLEDPin, HIGH);
delay(200);
digitalWrite(greenLEDPin, LOW);
delay(200);
}
}
if (granted == false) //If the tag is not found
{
Serial.println ("Access Denied");
digitalWrite(redLEDPin, HIGH); //Red LED sequence
delay(200);
digitalWrite(redLEDPin, LOW);
delay(200);
digitalWrite(redLEDPin, HIGH);
delay(200);
digitalWrite(redLEDPin, LOW);
delay(200);
}
}
| true |
5b8290b6c6c638df23b41a15f83eaaa21e2e7c77 | C++ | redrumrobot/unvanquished-engine | /src/Core/Terminal.cpp | UTF-8 | 11,451 | 2.5625 | 3 | [] | no_license | //@@COPYRIGHT@@
// NCurses/PDCurses-based terminal
static bool cursesOn = false;
// Basic print function for when not using curses
static void BasicPrint(printLevel_t level, const char *msg)
{
char buffer[MAX_PRINTMSG];
// Appropriate prefix for the error level
switch (level) {
case PRINT_ERROR:
strcpy(buffer, "ERROR: ");
break;
case PRINT_WARNING:
strcpy(buffer, "WARNING: ");
break;
case PRINT_MESSAGE:
case PRINT_DEBUG:
buffer[0] = '\0';
break;
NO_DEFAULT
}
strlcat(buffer, msg, sizeof(buffer));
// Add a newline at the end
unsigned int len = strlen(buffer);
if (len >= sizeof(buffer) - 1)
len = sizeof(buffer) - 2;
buffer[len++] = '\n';
buffer[len] = '\0';
// Strip color codes from the message
StripColor(buffer);
fputs(buffer, stdout);
}
#ifdef USE_CURSES
#include <curses.h>
#define TITLE "^2[ ^3Unvanquished Console ^2]"
#define INPUT_SCROLL 15
#define LOG_SCROLL 5
#define MAX_LOG_LINES 1024
#define CURSES_REFRESH_RATE 100
static ConsoleField inputField;
static WINDOW *logWin = NULL;
static WINDOW *inputWin = NULL;
static WINDOW *clockWin = NULL;
static Mutex cursesLock;
static int scrollLine = 0;
static int lastLine = 1;
static bool forceRedraw = false;
static short savedColor[3];
#define LOG_LINES (LINES - 3)
static inline void SetColor(WINDOW *win, int color)
{
// We don't want pure black, use grey instead.
// Using (void) to shut up warnings about unused return values.
if (color == 0 && has_colors() && !can_change_color())
(void)wattrset(win, COLOR_PAIR(color + 1) | A_BOLD);
else
(void)wattrset(win, COLOR_PAIR(color + 1) | A_NORMAL);
}
static inline void UpdateCursor()
{
// pdcurses uses a different mechanism to move the cursor than ncurses
#ifdef _WIN32
move(LINES - 1, ColorStrlen(CONSOLE_PROMPT) + 8 + inputField.GetCursor());
wnoutrefresh(stdscr);
#else
wmove(inputWin, 0, inputField.GetCursor());
wnoutrefresh(inputWin);
#endif
}
static void ColorPrint(WINDOW *win, const char *msg, bool stripcodes)
{
char buffer[MAX_PRINTMSG];
int length = 0;
SetColor(win, 7);
while (*msg) {
if (IsColorString(msg) || *msg == '\n') {
// First empty the buffer
if (length > 0) {
buffer[length] = '\0';
waddstr(win, buffer);
length = 0;
}
if (*msg == '\n') {
// Reset the color and then print a newline
SetColor(win, 7);
waddch(win, '\n');
msg++;
} else {
// Set the color
SetColor(win, msg[1] - '0');
if (stripcodes)
msg += 2;
else {
if (length >= MAX_PRINTMSG - 3)
break;
buffer[length++] = *msg++;
buffer[length++] = *msg++;
}
}
} else {
if (length >= MAX_PRINTMSG - 1)
break;
buffer[length++] = *msg++;
}
}
// Empty anything still left in the buffer
if (length > 0) {
buffer[length] = '\0';
waddstr(win, buffer);
}
}
static void UpdateClock()
{
char buffer[17];
time_t t = time(NULL);
struct tm *realtime = localtime(&t);
werase(clockWin);
snprintf(buffer, sizeof(buffer) / sizeof(*buffer), "^0[^3%02d%c%02d^0]^7 ", realtime->tm_hour, (realtime->tm_sec & 1) ? ':' : ' ', realtime->tm_min);
ColorPrint(clockWin, buffer, true);
wnoutrefresh(clockWin);
}
static void Redraw()
{
int col;
// This function is called both for resizes and initialization
if (logWin) {
// Update the window size
#ifndef _WIN32
struct winsize winsz = {0, 0, 0, 0};
ioctl(fileno(stdout), TIOCGWINSZ, &winsz);
if (winsz.ws_col < 12 || winsz.ws_row < 5)
return;
resizeterm(winsz.ws_row, winsz.ws_col);
#endif
// Delete all windows
delwin(logWin);
delwin(inputWin);
delwin(clockWin);
erase();
wnoutrefresh(stdscr);
}
// Create the log window
logWin = newpad(MAX_LOG_LINES, COLS);
scrollok(logWin, TRUE);
idlok(logWin, TRUE);
ColorPrint(logWin, Log::GetBuffer(), true);
Log::ReleaseBuffer();
getyx(logWin, lastLine, col);
if (col)
lastLine++;
scrollLine = lastLine - LOG_LINES;
if (scrollLine < 0)
scrollLine = 0;
pnoutrefresh(logWin, scrollLine, 0, 1, 0, LOG_LINES, COLS);
// Create the input field
inputWin = newwin(1, COLS - ColorStrlen(CONSOLE_PROMPT) - 8, LINES - 1, ColorStrlen(CONSOLE_PROMPT) + 8);
inputField.SetWidth(COLS - ColorStrlen(CONSOLE_PROMPT) - 9);
UpdateCursor();
wnoutrefresh(inputWin);
// Create the clock
clockWin = newwin(1, 8, LINES - 1, 0);
UpdateClock();
// Create the border
SetColor(stdscr, 2);
for (int i = 0; i < COLS; i++) {
mvaddch(0, i, ACS_HLINE);
mvaddch(LINES - 2, i, ACS_HLINE);
}
// Display the title bar
move(0, (COLS - ColorStrlen(TITLE)) / 2);
ColorPrint(stdscr, TITLE, true);
// Display the input prompt
move(LINES - 1, 8);
ColorPrint(stdscr, CONSOLE_PROMPT, true);
wnoutrefresh(stdscr);
doupdate();
}
static void TTY_Clear_f(CmdArgs *)
{
// Clear the window
werase(logWin);
pnoutrefresh(logWin, scrollLine, 0, 1, 0, LOG_LINES, COLS);
// Move the cursor back to the input field
UpdateCursor();
doupdate();
}
static void Print(printLevel_t level, const char *msg)
{
int col;
char buffer[MAX_PRINTMSG];
if (!cursesOn)
return;
if (level == PRINT_ERROR) {
// Shutdown curses now because the screen is cleared on shutdown, and
// we don't want the error message to get cleared.
Terminal::Shutdown();
BasicPrint(level, msg);
return;
}
// Appropriate prefix for the error level
switch (level) {
case PRINT_WARNING:
strcpy(buffer, "^3WARNING: ");
break;
case PRINT_MESSAGE:
buffer[0] = '\0';
break;
case PRINT_DEBUG:
strcpy(buffer, "^5");
break;
NO_DEFAULT
}
strlcat(buffer, msg, sizeof(buffer));
// Add a newline at the end if there isn't one.
unsigned int len = strlen(buffer);
if (len == sizeof(buffer) - 1)
len = sizeof(buffer) - 2;
buffer[len++] = '\n';
buffer[len] = '\0';
AutoLock lock(cursesLock);
// Print the message in the log window
ColorPrint(logWin, buffer, true);
getyx(logWin, lastLine, col);
if (col)
lastLine++;
scrollLine = lastLine - LOG_LINES;
if (scrollLine < 0)
scrollLine = 0;
pnoutrefresh(logWin, scrollLine, 0, 1, 0, LOG_LINES, COLS);
// Move the cursor back to the input field
UpdateCursor();
doupdate();
}
static inline void Update()
{
int numChars = 0;
static int lastTime = -1;
AutoLock lock(cursesLock);
if (time(NULL) != lastTime) {
lastTime = time(NULL);
UpdateClock();
numChars++;
}
while (true) {
int chr = getch();
numChars++;
switch (chr) {
case ERR:
if (forceRedraw) {
forceRedraw = false;
Redraw();
} else if (numChars > 1) {
werase(inputWin);
ColorPrint(inputWin, inputField.GetText(), false);
#ifdef _WIN32
// Need this for pdcurses to display the cursor properly
wrefresh(inputWin);
#else
wnoutrefresh(inputWin);
#endif
UpdateCursor();
doupdate();
}
return;
case KEY_ENTER:
case '\n':
case '\r':
lock.Unlock();
inputField.RunCommand();
lock.Lock();
continue;
case KEY_STAB:
case '\t':
lock.Unlock();
inputField.Autocomplete();
lock.Lock();
continue;
case KEY_LEFT:
inputField.CursorLeft();
continue;
case KEY_RIGHT:
inputField.CursorRight();
continue;
case KEY_UP:
inputField.HistoryUp();
continue;
case KEY_DOWN:
inputField.HistoryDown();
continue;
case KEY_HOME:
inputField.CursorHome();
continue;
case KEY_END:
inputField.CursorEnd();
continue;
case KEY_NPAGE:
if (scrollLine < lastLine - LOG_LINES) {
scrollLine = std::min(scrollLine + LOG_SCROLL, lastLine - LOG_LINES);
pnoutrefresh(logWin, scrollLine, 0, 1, 0, LOG_LINES, COLS);
}
if (scrollLine >= lastLine - LOG_LINES) {
SetColor(stdscr, 2);
for (int i = COLS - 7; i < COLS - 1; i++)
mvaddch(LINES - 2, i, ACS_HLINE);
}
continue;
case KEY_PPAGE:
if (scrollLine > 0) {
scrollLine = std::max(scrollLine - LOG_SCROLL, 0);
pnoutrefresh(logWin, scrollLine, 0, 1, 0, LOG_LINES, COLS);
}
if (scrollLine < lastLine - LOG_LINES) {
SetColor(stdscr, 1);
mvaddstr(LINES - 2, COLS - 7, "(more)");
}
continue;
case KEY_BACKSPACE:
case '\b':
case 127:
inputField.Backspace();
continue;
case KEY_DC:
inputField.Delete();
continue;
case 'w' - 'a' + 1:
inputField.WordDelete();
continue;
default:
if (isprint(chr))
inputField.AddChar(chr);
continue;
}
}
}
static void UpdateThread()
{
while (true) {
// Sleep until we get input from stdin, or 100ms have passed
#ifdef _WIN32
WaitForSingleObject(GetStdHandle(STD_INPUT_HANDLE), CURSES_REFRESH_RATE);
#else
struct timeval timeout;
fd_set fdset;
FD_ZERO(&fdset);
FD_SET(STDIN_FILENO, &fdset);
timeout.tv_sec = CURSES_REFRESH_RATE / 1000;
timeout.tv_usec = CURSES_REFRESH_RATE * 1000;
select(STDIN_FILENO + 1, &fdset, NULL, NULL, &timeout);
#endif
Update();
}
}
#ifndef _WIN32
static void Resize(int)
{
// Don't call Redraw() directly, because it is slow, and we might miss more
// resize signals while redrawing.
forceRedraw = true;
}
#endif
static inline bool CursesInit()
{
// Make sure we're on a real terminal
if (!isatty(STDIN_FILENO) || !isatty(STDOUT_FILENO))
return false;
#ifndef _WIN32
const char* term = getenv("TERM");
if (term && (!strcmp(term, "raw") || !strcmp(term, "dumb")))
return false;
// Enable more colors
if (!strncmp(term, "xterm", 5) || !strncmp(term, "screen", 6))
setenv("TERM", "xterm-256color", 1);
#endif
// Initialize curses and set up the root window
initscr();
cbreak();
noecho();
nonl();
intrflush(stdscr, FALSE);
nodelay(stdscr, TRUE);
keypad(stdscr, TRUE);
meta(stdscr, TRUE);
wnoutrefresh(stdscr);
// Set up colors
if (has_colors()) {
use_default_colors();
start_color();
init_pair(1, COLOR_BLACK, -1);
init_pair(2, COLOR_RED, -1);
init_pair(3, COLOR_GREEN, -1);
init_pair(4, COLOR_YELLOW, -1);
init_pair(5, COLOR_BLUE, -1);
init_pair(6, COLOR_CYAN, -1);
init_pair(7, COLOR_MAGENTA, -1);
init_pair(8, -1, -1);
init_pair(9, -1, -1);
init_pair(10, -1, -1);
// Use dark grey instead of black
if (can_change_color()) {
color_content(COLOR_BLACK, &savedColor[0], &savedColor[1], &savedColor[2]);
init_color(COLOR_BLACK, 250, 250, 250);
}
}
#ifndef _WIN32
// Catch window resizes
System::AttachSignalHandler(SIGWINCH, Resize);
#endif
// Some libraries (such as OpenAL) insist on printing to stderr, which
// messes up ncurses. So we just shut them up.
fclose(stderr);
// Create everything
Redraw();
RegisterPrintHandler(Print);
Cmd::Register("tty_clear", TTY_Clear_f);
// Set up a thread to handle input and redrawing
Thread::SpawnThread(UpdateThread);
return true;
}
static inline void CursesShutdown()
{
RemovePrintHandler(Print);
// Restore colors
if (can_change_color())
init_color(COLOR_BLACK, savedColor[0], savedColor[1], savedColor[2]);
erase();
refresh();
endwin();
RegisterPrintHandler(BasicPrint);
Cmd::UnRegister("tty_clear");
}
#else
static inline bool CursesInit()
{
return false;
}
static inline void CursesShutdown()
{
}
#endif
void Terminal::Init()
{
#ifdef BUILD_SERVER
bool useCurses = true;
#else
bool useCurses = false;
#endif
if (Engine::GetArg("-curses", 0, NULL))
useCurses = true;
else if (Engine::GetArg("-nocurses", 0, NULL))
useCurses = false;
if (useCurses)
cursesOn = CursesInit();
// Fall back to a basic print handler
if (!cursesOn)
RegisterPrintHandler(BasicPrint);
}
void Terminal::Shutdown()
{
if (cursesOn) {
cursesOn = false;
CursesShutdown();
}
}
| true |
dfea35364fa2f58db13d7792b4795f0a3b93654f | C++ | Danicast-c/Cache_Coherence | /delay_control.cpp | UTF-8 | 983 | 3.140625 | 3 | [] | no_license | //
// Created by Daniel Castro on 9/14/19.
//
#include <iostream>
#include "delay_control.h"
delay_control::delay_control(core *c1, core *c2, core *c3, core *c4, queue_control *my_queue) {
core_1 = c1;
core_2 = c2;
core_3 = c3;
core_4 = c4;
queues = my_queue;
}
void delay_control::read_delay_queue() {
while (!queues->core_delay_is_empty()) { //Cambiar por if si se ocupa solo un step
core_delay coreDelay = queues->core_delay_read();
if (coreDelay.core_to_delay == 1) {
core_1->update_delay(coreDelay.delay);
} else if (coreDelay.core_to_delay == 2) {
core_2->update_delay(coreDelay.delay);
} else if (coreDelay.core_to_delay == 3) {
core_3->update_delay(coreDelay.delay);
} else if (coreDelay.core_to_delay == 4) {
core_4->update_delay(coreDelay.delay);
} else {
std::cout << "ERROR en delay_control::read_delay_queue" << std::endl;
}
}
}
| true |
a9e1fbc41d42e99b2415430668a74962045bae4e | C++ | Lexkane/Cpp | /Shops/ShopApp.cpp | UTF-8 | 4,197 | 3.125 | 3 | [] | no_license | // ShopApp.cpp : main project file.
#pragma once
//include "stdafx.h"
#include"Product.h"
#include"Shop.h"
#include <vector>
#include <string>
using namespace std;
void shop_input()
{
int check = 1;
Shop shop;
vector <Shop> shoplist;
cout <<" Please Input Name ShopNumber" << endl;
do
{
cin>>(shop);
shoplist.push_back(shop);
cout << "Continue input?\n1 - yes\t0 - no\n" << endl;
cin >> check;
} while (check != 0);
ofstream outputFile("Data/shoplist.txt");
//outputFile << "This is ShopList"<<endl;
for (auto f : shoplist)
{ outputFile << f; }
}
void product_input()
{
int check = 1;
vector <Product> productlist;
cout << "Please Input Name Date Measurement TypeCode CheckNumber Price Quantity TotalPrice" << endl;
do
{
Product product;
cin >> product;
productlist.push_back(product);
cout << "Continue input?\n1 - yes\t0 - no\n" << endl;
cin >> check;
} while (check != 0);
ofstream outputFile("Data/productlist.txt");
//outputFile << "productlist";
for (auto f : productlist)
{ outputFile << f << endl; }
}
void shop_display()
{
string line;
int checker;
while (checker != 0)
{
std::ifstream inFile("Data/shoplist.txt");
if (!inFile.is_open()) {
std::cout << "Can't open file";
exit(1);
}
cout << "\nShop data: ";
cout << "\n________________________";
cout << "\n|Name | Number |";
cout << "\n|__________|____________|" << endl;
while (getline(inFile, line))
{
cout << line << endl;
}
cout << "\n\nContinue output?\n1 - yes\t0 - no\n";
cin >> checker;
inFile.close();
}
}
void product_display()
{
string line;
int checker;
while (checker != 0)
{
std::ifstream inFile("Data/productlist.txt");
if (!inFile.is_open())
{
std::cout << "Can't open file";
exit(1);
}
cout << "\nProduct data: ";
cout << "\n________________________________________________________________________________________________________________";
cout << "\n|Name | Type | Date | Measurement | CheckNumber | Price | Quantity |TotalPrice |";
cout << "\n|__________|____________|____________|______________|______________|__________________|___________|_____________|"<<endl;
while (getline(inFile, line))
{
cout << line << endl;
}
cout << "\n\nContinue output?\n1 - yes\t0 - no\n";
cin >> checker;
inFile.close();
}
}
int main() {
int choice;
menu:
do
{
system("cls");
cout << "Menu:";
cout << "\n0 - Exit";
cout << "\n1 - Shop info";
cout << "\n2 - Product info\n";
cin >> choice;
while (choice != 0){
if (choice == 0)
{
exit(1);
}
if (choice == 1)
{
goto shop_info;
}
if (choice == 2)
{
goto product_info;
}
else {
break;
}
}
shop_info:
while (choice != 0)
{
//system("cls");
cout << "Shop info:";
cout << "\n0 - Back to menu";
cout << "\n1 - Add shop";
cout << "\n2 - Edit shop";
cout << "\n3 - Delete shop";
cout << "\n4 - Display shops\n";
cin >> choice;
if (choice == 0)
{
goto menu;
}
if (choice == 1)
{
shop_input(); break;
}
if (choice == 2)
{
continue;
}
if (choice == 4)
{
shop_display(); break;
}
else {
break;
}
}
product_info:
while (choice != 0)
{
//system("cls");
cout << " Input Product info:";
cout << "\n0 - Back to menu";
cout << "\n1 - Add product";
cout << "\n2 - Edit product";
cout << "\n3 - Delete product";
cout << "\n4 - Display products \n";
cin >> choice;
if (choice == 0)
{
goto menu;
}
if (choice == 1)
{
product_input(); break;
}
if (choice == 2)
{
continue;
}
if (choice == 4)
{
product_display(); break;
}
else {
break;
}
}
} while (choice != 0);
return 0;
}
| true |
71b369a953c3b773c4a62b88467b20c263afb04e | C++ | wyxmails/MyCode | /1_leetcode/linkListCycle.cpp | UTF-8 | 610 | 3.734375 | 4 | [] | no_license | /*
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode *s1,*s2;
s1=s2=head;
while(s1!=NULL&&s2!=NULL){
s1 = s1->next;
s2 = s2->next;
if(s2==NULL) break;
s2 = s2->next;
if(s1==s2) return true;
}
return false;
}
};
| true |
d5c0b0f4c628e445ca1f1cfaa632c96e9a9f4937 | C++ | ajithcnambiar/cpp-condition-variable | /zeroevenodd.h | UTF-8 | 1,490 | 3.53125 | 4 | [] | no_license | #ifndef _ZERO_EVEN_ODD_H_
#define _ZERO_EVEN_ODD_H_
#include <functional>
#include <condition_variable>
#include <mutex>
#include <iostream>
class ZeroOddEven{
// input integer, generates until n
int n;
// counter counts upto n
int counter;
// condition variable, helps to realize unblock a thread until a condition is met.
std::condition_variable cv;
// used part of condition to generate "0"
bool generate0;
// used part of condition to signal to end worker thread
bool done;
// mutex used to synchronize changes on shared variables n, counter, generate0 and done
// used side by side with condition variable
std::mutex m;
// stores result
std::string result;
void togglegenerate0(){
generate0 = !generate0;
}
void incCounter(){
counter++;
}
public:
ZeroOddEven(int n): n(n), counter(1), generate0(true),done(false),result(""){}
// Generating methods wait on condition variable until lambda returns true.
// lambda is different for each method to generate intended number
// Condition variable uses mutex to synchronize changes on shared variables
// notify_all is used instead of notify_one b/c multiple threads will be waiting on condition at same time.
void zero(std::function<void(std::string&, int)>);
void odd(std::function<void(std::string&, int)>);
void even(std::function<void(std::string&, int)>);
std::string get_result(){return result;}
};
#endif
| true |
0a648ea6cee8cb0f5eec3c1f222e11e608d45f45 | C++ | Jrende/Hondo | /src/gfx/Octree.hpp | UTF-8 | 1,592 | 2.9375 | 3 | [
"MIT"
] | permissive | #pragma once
#include <array>
#include <memory>
#define GLM_FORCE_RADIANS
#include <glm/glm.hpp>
#include <unordered_set>
#include <vector>
#include "AABB.hpp"
#include "Entity.hpp"
#include "Frustum.hpp"
class Octree {
friend class DebugRenderer;
friend class Test;
private:
void add_point(int entity_id, const glm::vec3& point);
public:
Octree(): root(Node(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(1024.0f, 1024.0f, 1024.0f)))
{
root.tree = this;
}
bool contains_point(const glm::vec3& point);
void add_aabb(Entity entity, const AABB& r_obj);
std::vector<int> get_items_in_frustum(const Frustum& frustum);
struct Node {
Octree* tree;
std::unique_ptr<std::array<Node, 8>> children = nullptr;
std::unique_ptr<glm::vec3> point = nullptr;
int entity_id = -1;
glm::vec3 pos, half_size;
Node():
pos(0, 0, 0), half_size(1, 1, 1)
{}
Node(glm::vec3 pos, glm::vec3 half_size):
pos(pos), half_size(half_size)
{}
bool contains_point(const glm::vec3& p);
int get_octant(const glm::vec3& point) const;
void convert_to_interior();
bool is_contained_by_frustum(const Frustum& frustum);
void get_points_in_frustum(const Frustum& frustum, std::vector<int>& result);
/*
* Three cases:
* Node is interior
* Insert to appropriate node
* Node is leaf with no data
* Found correct node!
* Node is leaf with data
* Convert leaf to interior, add points to correct leafs
*/
void add_point(int entity_id, const glm::vec3& point);
};
Node root;
};
| true |
75ad9a23cb7d57b6e0d56f0a4690c3606a6d6221 | C++ | IohannRabeson/lexy | /include/lexy/dsl/production.hpp | UTF-8 | 4,894 | 2.578125 | 3 | [
"BSL-1.0"
] | permissive | // Copyright (C) 2020-2021 Jonathan Müller <jonathanmueller.dev@gmail.com>
// This file is subject to the license terms in the LICENSE file
// found in the top-level directory of this distribution.
#ifndef LEXY_DSL_PRODUCTION_HPP_INCLUDED
#define LEXY_DSL_PRODUCTION_HPP_INCLUDED
#include <lexy/dsl/base.hpp>
#include <lexy/dsl/branch.hpp>
namespace lexyd
{
/// Parses the rule of the production as if it were part of the current production.
template <typename Production>
constexpr auto inline_ = lexy::production_rule<Production>{};
} // namespace lexyd
namespace lexyd
{
// Not inline: one function per production.
template <typename Rule, typename Context, typename Reader>
constexpr bool _parse(Context& context, Reader& reader)
{
return lexy::rule_parser<Rule, lexy::context_value_parser>::parse(context, reader);
}
template <typename Rule, typename Context, typename Reader>
constexpr auto _try_parse(Context& context, Reader& reader)
{
return lexy::rule_parser<Rule, lexy::context_value_parser>::try_parse(context, reader);
}
template <typename Production, typename Rule, typename NextParser>
struct _prd_parser
{
struct _continuation
{
template <typename Context, typename Reader, typename ProdContext, typename... Args>
LEXY_DSL_FUNC bool parse(Context& context, Reader& reader, ProdContext& prod_context,
Args&&... args)
{
// If we're about to parse a token production, we need to continue with the parent's
// (i.e. our current context) whitespace.
using ws_next
= std::conditional_t<lexy::is_token_production<Production>,
lexy::whitespace_parser<Context, NextParser>, NextParser>;
if constexpr (std::is_void_v<typename ProdContext::return_type>)
{
LEXY_MOV(prod_context).finish();
return ws_next::parse(context, reader, LEXY_FWD(args)...);
}
else
{
return ws_next::parse(context, reader, LEXY_FWD(args)...,
LEXY_MOV(prod_context).finish());
}
}
};
template <typename Context, typename Reader, typename... Args>
LEXY_DSL_FUNC auto try_parse(Context& context, Reader& reader, Args&&... args)
-> lexy::rule_try_parse_result
{
auto prod_context = context.production_context(Production{}, reader.cur());
if (auto result = _try_parse<Rule>(prod_context, reader);
result == lexy::rule_try_parse_result::ok)
{
// We succesfully parsed the production.
// The continuation will call `.finish()` for us.
return static_cast<lexy::rule_try_parse_result>(
_continuation::parse(context, reader, prod_context, LEXY_FWD(args)...));
}
else // backtracked or canceled
{
// Need to backtrack the partial production in either case.
LEXY_MOV(prod_context).backtrack();
return result;
}
}
template <typename Context, typename Reader, typename... Args>
LEXY_DSL_FUNC bool parse(Context& context, Reader& reader, Args&&... args)
{
auto prod_context = context.production_context(Production{}, reader.cur());
if (!_parse<Rule>(prod_context, reader))
{
// We failed to parse, need to backtrack.
LEXY_MOV(prod_context).backtrack();
return false;
}
// The continuation will call `.finish()` for us.
return _continuation::parse(context, reader, prod_context, LEXY_FWD(args)...);
}
};
template <typename Production>
struct _prd : rule_base
{
using _rule = lexy::production_rule<Production>;
static constexpr auto is_branch = _rule::is_branch;
static constexpr auto is_unconditional_branch = _rule::is_unconditional_branch;
template <typename NextParser>
using parser = _prd_parser<Production, _rule, NextParser>;
template <typename Whitespace>
constexpr auto operator[](Whitespace ws) const
{
return whitespaced(*this, ws);
}
};
/// Parses the production.
template <typename Production>
constexpr auto p = _prd<Production>{};
template <typename Production>
struct _rec : rule_base
{
template <typename NextParser>
struct parser : _prd_parser<Production, lexy::production_rule<Production>, NextParser>
{};
template <typename Whitespace>
constexpr auto operator[](Whitespace ws) const
{
return whitespaced(*this, ws);
}
};
/// Parses the production, recursively.
/// `dsl::p` requires that the production is already defined in order to propagate a branch
/// condition outwards.
template <typename Production>
constexpr auto recurse = _rec<Production>{};
} // namespace lexyd
#endif // LEXY_DSL_PRODUCTION_HPP_INCLUDED
| true |
fbc05f41f02980b7c152bbf068d19ff8ddd832fd | C++ | betinag/Matrix | /matrix.h | UTF-8 | 1,800 | 3.40625 | 3 | [] | no_license | #include <cstddef>
#include <vector>
const double MATRIX_DEFAULT_VALUE = 0.0;
class Matrix
{
public:
typedef std::vector<double>::size_type size_type;
Matrix();
Matrix(size_type, size_type, double = MATRIX_DEFAULT_VALUE);
Matrix(const std::vector<double>&);
Matrix(const std::vector<std::vector<double> >&);
Matrix(const Matrix&);
Matrix(Matrix&&);
Matrix& operator=(const Matrix&);
Matrix& operator=(Matrix&&);
size_type rows() const { return m_rows; }
size_type cols() const { return m_cols; }
double& operator()(size_type, size_type);
double operator()(size_type, size_type) const;
bool isEmpty() const { return (m_rows == 0 || m_cols == 0); }
bool isSquare() const { return m_rows == m_cols; }
bool isFinite() const;
Matrix operator+(double) const;
Matrix operator-(double) const;
Matrix operator*(double) const;
Matrix operator/(double) const;
Matrix& operator+=(double);
Matrix& operator-=(double);
Matrix& operator*=(double);
Matrix& operator/=(double);
Matrix operator-() const;
friend Matrix operator+(const Matrix&, const Matrix&);
friend Matrix operator-(const Matrix&, const Matrix&);
friend Matrix operator*(const Matrix&, const Matrix&);
Matrix& operator+=(const Matrix&);
Matrix& operator-=(const Matrix&);
Matrix transpose() const;
private:
size_type m_rows;
size_type m_cols;
std::vector<double> m_data;
int maxRowSize(const std::vector<std::vector<double> >&);
};
inline Matrix operator+(double scalar, const Matrix& rhs)
{
return rhs + scalar;
}
inline Matrix operator-(double scalar, const Matrix& rhs)
{
return -rhs + scalar;
}
inline Matrix operator*(double scalar, const Matrix& rhs)
{
return rhs * scalar;
}
| true |
fa6152dd052933f0f443fee8fff28c923ff19d95 | C++ | seub/Harmony | /h2triangle.cpp | UTF-8 | 4,030 | 2.875 | 3 | [] | no_license | #include "h2triangle.h"
#include "h2polygon.h"
#include "h2isometry.h"
H2Triangle::H2Triangle()
{
}
H2Triangle::H2Triangle(const H2Point &a, const H2Point &b, const H2Point &c): a(a), b(b), c(c)
{
}
void H2Triangle::getPoints(H2Point &a, H2Point &b, H2Point &c) const
{
a = this->a;
b = this->b;
c = this->c;
}
std::vector<H2Point> H2Triangle::getPoints() const
{
return {a, b, c};
}
std::vector<H2GeodesicArc> H2Triangle::getSides() const
{
return {H2GeodesicArc(a, b), H2GeodesicArc(b, c), H2GeodesicArc(c, a)};
}
double H2Triangle::area() const
{
Complex zA = a.getDiskCoordinate(), zB = b.getDiskCoordinate(), zC = c.getDiskCoordinate();
Complex ZA, ZB, ZC;
ZB = (zB - zA)/(1.0 - conj(zA)*zB);
ZC = (zC - zA)/(1.0 - conj(zA)*zC);
double angleA = std::abs(std::arg(ZC*conj(ZB)));
ZC = (zC - zB)/(1.0 - conj(zB)*zC);
ZA = (zA - zB)/(1.0 - conj(zB)*zA);
double angleB = std::abs(std::arg(ZA*conj(ZC)));
ZA = (zA - zC)/(1.0 - conj(zC)*zA);
ZB = (zB - zC)/(1.0 - conj(zC)*zB);
double angleC = std::abs(std::arg(ZB*conj(ZA)));
return M_PI - (angleA + angleB + angleC);
}
void H2Triangle::getSideLengths(double &A, double &B, double &C) const
{
A = H2Point::distance(b,c);
B = H2Point::distance(a,c);
C = H2Point::distance(a,b);
}
bool H2Triangle::contains(const H2Point &point) const
{
H2Polygon P;
getAsPolygon(P);
return P.contains(point);
}
void H2Triangle::getAsPolygon(H2Polygon & outputPolygon) const
{
outputPolygon.setVertices({a, b, c});
}
void H2Triangle::getAngles(double &angleA, double &angleB, double &angleC) const
{
Complex z1 = a.getDiskCoordinate();
Complex z2 = b.getDiskCoordinate();
Complex z3 = c.getDiskCoordinate();
Complex u,v;
u = (z3 - z1) / (1.0 - conj(z1)*z3);
v = (z2 - z1) / (1.0 - conj(z1)*z2);
angleA = Tools::mod2Pi(arg(v*conj(u)));
u = (z1 - z2) / (1.0 - conj(z2)*z1);
v = (z3 - z2) / (1.0 - conj(z2)*z3);
angleB = Tools::mod2Pi(arg(v*conj(u)));
u = (z2 - z3) / (1.0 - conj(z3)*z2);
v = (z1 - z3) / (1.0 - conj(z3)*z1);
angleC = Tools::mod2Pi(arg(v*conj(u)));
}
bool H2Triangle::isVertexCloseInDiskModel(const H2Point &point, double detectionRadiusSquared, uint &vertexIndex) const
{
bool res = false;
Complex z = point.getDiskCoordinate();
double min = 0;
double A = norm(z - a.getDiskCoordinate());
double B = norm(z - b.getDiskCoordinate());
double C = norm(z - c.getDiskCoordinate());
if (A < detectionRadiusSquared)
{
min = A;
vertexIndex = 0;
res = true;
}
if (B < detectionRadiusSquared)
{
if (res)
{
if (B<min)
{
min = B;
vertexIndex = 1;
}
}
else
{
min = B;
vertexIndex = 1;
res = true;
}
}
if (C < detectionRadiusSquared)
{
if (res)
{
if (C<min)
{
min = C;
vertexIndex = 2;
}
}
else
{
min = C;
vertexIndex = 2;
res = true;
}
}
return res;
}
H2Point H2Triangle::getVertex(uint index) const
{
switch (index)
{
case 0:
return a;
break;
case 1:
return b;
break;
case 2:
return c;
break;
default:
std::cerr << "ERROR in H2Triangle::getVertex: wrong index" << std::endl;
return a;
break;
}
}
void H2Triangle::getVertices(H2Point &Aout, H2Point &Bout, H2Point &Cout) const
{
Aout = a;
Bout = b;
Cout = c;
}
std::ostream & operator<<(std::ostream &out, const H2Triangle &T)
{
out << "Triangle with vertices a = " << T.a << ", b = " << T.b << ", c = " << T.c << std::endl;
return out;
}
H2Triangle operator*(const H2Isometry &f, const H2Triangle &T)
{
return H2Triangle(f*(T.a), f*(T.b), f*(T.c));
}
| true |
ed0d2642ca5f254f08b3bf4e0141f0abd87a27cb | C++ | DELFIN-GO/plot | /plot_test/main.cpp | UTF-8 | 1,089 | 2.625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
//const double M_PI=3.14159265358979323846;
double f(double x){
return x*x/100;
}
double g(double x){
return x*x*4*3.14*3.14*(375.1+376.1);
}
double h(double x){
return x*10.2*9.82*pow(pow(0.003/x,2)+pow(0.1/10.2,2),0.5);
}
int main()
{
freopen("input.txt","r",stdin);
freopen("../datafile.dat","w",stdout);
int n=13;
double x,y;
for (int j=0;j<1;j++){
double a[n],b[n],m[n];
for (int i=0;i<n;i++){
cin >> x >> y;
b[i]=x;
m[i]=y;
a[i]=49-b[i];
double d=pow(pow(0.5/(x/10),2)+pow((0.1+0.1)/(375.7+376.1),2)+4*pow(0.1/y,2),0.5);
cout << fixed << setprecision(6) << f(x) << " " << g(y) << " " << d << " " << d << "\n";
}
cout << "\n\n";
double f[n];
for (int i=0;i<n;i++){
f[i]=2*9.82*10.2*148.3*m[i]/a[i];
}
double f_s=0;
for (int i=0;i<n;i++){
f_s+=f[i];
}
f_s/=9;
// cout << f_s << "\n\n";
}
return 0;
}
| true |
39ffdb8ca26f38b5cab79265ed3d1f1f612a6ef6 | C++ | Anshika-Srivastava/Important-ques-by-seniors | /Binary Tree Zigzag Level Order Traversal.cpp | UTF-8 | 1,274 | 3.5625 | 4 | [] | no_license | //Using BFS
//Data Structure used: Queue
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> ans;
//corner case
if(root==NULL)
return ans;
queue<TreeNode*> q;
bool dir=1;//1-left to right, 0-right to left
q.push(root);//push the first element to the queue
while(!q.empty()){//check if queue is not empty
int size=q.size();
vector<int> res(size);//a vector to store the elements present at that time
for(int i=0;i<size;i++){
TreeNode* curr=q.front();//extract the front element of the root
q.pop();//pop it from queue
if(dir==1)//see the direction to travel
res[i]=curr->val;
else
res[size-i-1]=curr->val;
if(curr->left!=NULL)//if left sub tree exists
q.push(curr->left);//push it to queue
if(curr->right!=NULL)//if right sub tree exists
q.push(curr->right);//push it to queue
}
dir=!dir;//change the direction
ans.push_back(res);//push the vector to our final answer
}
return ans;
}
};
| true |
3c3a4ac81910280571108ba034095879a2e939ea | C++ | frandibar/pacman3d | /client/Player.cpp | UTF-8 | 3,876 | 2.59375 | 3 | [] | no_license | #include "Player.h"
#include "SDLHelpers.h"
#include "lib/debug.h"
#include <iostream>
#include <string>
const double Player::RADIUS = 0.5;
// constructor
Player::Player(unsigned int playerId, tRole role) : _id(playerId), _role(role), _score(0), _name(""),
_glTextureNormal(-1), _glTexturePowerUp(-1),
_glTextureEaten(-1), _glIcon(-1),
_isAlive(true), _powerupEnabled(false), _orientation(WEST)
{
}
void Player::setOrientation(tOrientation newOrientation)
{
if (newOrientation == _orientation)
return;
// rotate player
switch (_orientation) {
case NORTH:
switch (newOrientation) {
case EAST: turnRight(90.0); break;
case SOUTH: turnLeft(180.0); break;
case WEST: turnLeft(90.0); break;
default: break;
}
break;
case EAST:
switch (newOrientation) {
case SOUTH: turnRight(90.0); break;
case WEST: turnLeft(180.0); break;
case NORTH: turnLeft(90.0); break;
default: break;
}
break;
case SOUTH:
switch (newOrientation) {
case WEST: turnRight(90.0); break;
case NORTH: turnLeft(180.0); break;
case EAST: turnLeft(90.0); break;
default: break;
}
break;
case WEST:
switch (newOrientation) {
case NORTH: turnRight(90.0); break;
case EAST: turnLeft(180.0); break;
case SOUTH: turnLeft(90.0); break;
default: break;
}
break;
default: break;
}
_orientation = newOrientation;
}
void Player::init()
{
// load player's textures
std::string colors = "ygcmr678";
std::string filename = "/etc/Pacman3D/data/";
filename += colors[_id];
filename += "_player.bmp";
loadTexture(&_glTextureNormal, filename.c_str(), false);
if (_role == GHOST) {
loadTexture(&_glTexturePowerUp, "/etc/Pacman3D/data/b_player.bmp", false);
loadTexture(&_glTextureEaten, "/etc/Pacman3D/data/x_player.bmp", false);
}
// load player's icon texture
filename = "/etc/Pacman3D/data/";
filename += colors[_id];
filename += "_icon.bmp";
loadTexture(&_glIcon, filename.c_str(), MASK_COLOR);
setPos(0.5, 0.5); // put in arbitrary position
}
void Player::draw(bool asDot)
{
glPushMatrix();
GLUquadricObj* quad = gluNewQuadric();
gluQuadricNormals(quad, GL_SMOOTH); // generate smooth normals for the quad
gluQuadricTexture(quad, GL_TRUE); // enable texture coords for the quad
glTranslatef(pos[OB_X], pos[OB_Y], pos[OB_Z]);
glDisable(GL_BLEND);
glEnable(GL_TEXTURE_2D);
// bind corresponding texture and draw
if (_role == PACMAN) {
// set up sphere mapping
glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
glBindTexture(GL_TEXTURE_2D, _glTextureNormal);
gluSphere(quad, RADIUS, 32, 16);
}
else {
if (!_isAlive)
glBindTexture(GL_TEXTURE_2D, _glTextureEaten);
else if (_powerupEnabled)
glBindTexture(GL_TEXTURE_2D, _glTexturePowerUp);
else
glBindTexture(GL_TEXTURE_2D, _glTextureNormal);
if (asDot)
gluSphere(quad, RADIUS, 32, 16);
else {
glTranslatef(0.0f, 0.0f, -RADIUS/2);
gluCylinder(quad, RADIUS, 2*RADIUS/3, 0.5f, 32, 32); // base radius, upper radius, height
}
}
glPopMatrix();
}
| true |
22770a6059ffa59d897417a1883efac734c03069 | C++ | weirenw/Database-System-Implementation | /project 4-1/a3/SortedFile.h | UTF-8 | 2,048 | 2.65625 | 3 | [] | no_license | #ifndef SORTED_FILE_H_
#define SORTED_FILE_H_
#include <string>
#include "GenericDBFile.h"
#include "Pipe.h"
#include "BigQ.h"
class SortedFile: public GenericDBFile{
static const size_t PIPE_BUFFER_SIZE = PIPE_SIZE;
public:
enum Mode{READ, WRITE, UNKNOWN} mode;
SortedFile(): sortOrder(NULL), runLength(0), inPipe(NULL), outPipe(NULL), biq(NULL), useMem(false), mode(UNKNOWN) {}
~SortedFile() {}
int Create (char* fpath, void* startup);
int Open (char* fpath);
int Close ();
void Add (Record& addme);
void Load (Schema& myschema, char* loadpath);
void MoveFirst();
int GetNext (Record& fetchme);
int GetNext (Record& fetchme, CNF& cnf, Record& literal);
protected:
void startWrite();
void startRead();
private:
OrderMaker* sortOrder; // may come from startup or meta file; need to differentiate
int runLength;
std::string tpath;
std::string table;
Pipe *inPipe, *outPipe;
BigQ *biq;
int curPageIdx;
const char* metafName() const; // meta file name
// temp file name used in the merge phase
inline const char* tmpfName() const;
void merge(); // merge BigQ and File
int binarySearch(Record& fetchme, OrderMaker& queryorder, Record& literal, OrderMaker& cnforder, ComparisonEngine& cmp);
bool useMem; // this is used to indicate whether SortInfo is passed or created
// it is default to false, and set in allocMem()
void allocMem();
void freeMem();
void createQ()
{
inPipe = new Pipe(PIPE_BUFFER_SIZE);
outPipe = new Pipe(PIPE_BUFFER_SIZE);
biq = new BigQ(*inPipe, *outPipe, *sortOrder, runLength);
}
void deleteQ()
{
delete biq; delete inPipe; delete outPipe;
biq = NULL; inPipe = outPipe = NULL;
}
};
const char* SortedFile::tmpfName() const
{
return (tpath+".tmp").c_str();
}
inline void SortedFile::startRead()
{
if(mode == WRITE)
{
merge();
mode = READ;
return;
}
else if(mode == READ)
return;
else
mode = READ;
return;
}
inline void SortedFile::startWrite()
{
if (mode==WRITE) return;
mode = WRITE;
createQ();
}
#endif
| true |
f2f5d6da9cf511a91dd119ade9ec610ae6ab9bc5 | C++ | mikevo/uibk-acc | /mcc/tac/src/float_literal.cpp | UTF-8 | 313 | 2.546875 | 3 | [
"MIT"
] | permissive | #include "mcc/tac/float_literal.h"
namespace mcc {
namespace tac {
FloatLiteral::FloatLiteral(float value, Scope::ptr_t scope)
: Operand(Type::FLOAT, scope), value(value) {}
bool FloatLiteral::isLeaf() const { return true; }
std::string FloatLiteral::getValue() const { return std::to_string(value); }
}
} | true |
5c623b4779db5505376bbf4a03a997b4dd486f04 | C++ | xuau34/competitive-programming | /PCCA2017s/Day4/J.cpp | UTF-8 | 909 | 2.53125 | 3 | [] | no_license | #include <iostream>
#include <utility>
#include <algorithm>
using namespace std;
int T, N, M, Q;
pair<long long, pair<long long, long long> > arr[40005];
void ini(void){
scanf("%d", &N);
for(int i = 0; i < N; ++i){
scanf("%lld %lld %lld", &arr[i].first, &arr[i].second.first, &arr[i].second.second);
}
sort(arr, arr + N);
}
void sol(void){
long long ans = 0;
for(int i = 0; i < N; ++i){
int j = 1;
while( arr[i + j].first < arr[i].second.first ){
if( arr[i + j].second.second > arr[i].second.second ){
arr[i].second.first = arr[i + j].first;
}else{
arr[i + j].first = arr[i].second.first;
}
++j;
}
//printf("(%d, %d)%d ", arr[i].first, arr[i].second.first, arr[i].second.second);
ans += ( arr[i].second.first - arr[i].first) * arr[i].second.second;
}
printf("%lld\n", ans);
}
int main(void){
int i, j;
ini();
sol();
}
| true |
e929d947412056f6880773216487221a2ac4ce82 | C++ | lvcargnini/zircon | /system/core/devmgr/bootfs.h | UTF-8 | 2,065 | 2.53125 | 3 | [
"BSD-3-Clause",
"MIT"
] | permissive | // Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#pragma once
#include <zircon/boot/bootdata.h>
#include <zircon/types.h>
#include <zircon/compiler.h>
#include <stdint.h>
#include <fbl/algorithm.h>
#include <lib/zx/vmo.h>
namespace devmgr {
class Bootfs {
public:
// Create an empty Bootfs with no backing |vmo_|.
Bootfs() : Bootfs(zx::vmo(), 0, nullptr) {}
// Destroys the underlying |vmo_|, but does not unmap the memory
// backing the filesystem.
~Bootfs();
// Destroys the given bootfs file system.
//
// Closes the underlying |vmo_| and unmaps the memory backing the file system.
void Destroy();
// Create a bootfs file system from |vmo|.
//
// Takes ownership of |vmo|.
static zx_status_t Create(zx::vmo vmo, Bootfs* bfs_out);
// Opens the file with the given |name| in the bootfs file system.
//
// The contents of the file are returned as a copy-on-write VMO clone. Upon
// success, the caller owns the returned |vmo_out|.
zx_status_t Open(const char* name, zx::vmo* vmo_out, uint32_t* size_out);
// Parses the bootfs file system and calls |callback| for each |bootfs_entry_t|.
using Callback = zx_status_t (void* cookie, const bootfs_entry_t* entry);
zx_status_t Parse(Callback callback, void* cookie);
// Attempts to duplicate the underling |vmo_| with the same
// rights, and returns it. Returns ZX_HANDLE_INVALID on any
// failure to do so.
zx::vmo DuplicateVmo();
private:
Bootfs(zx::vmo vmo, uint32_t dirsize, void* dir) :
vmo_(fbl::move(vmo)), dirsize_(dirsize), dir_(dir) {}
Bootfs(const Bootfs&) = delete;
Bootfs& operator=(const Bootfs&) = delete;
Bootfs(Bootfs&&) = default;
Bootfs& operator=(Bootfs&&) = default;
size_t MappingSize() const {
return dirsize_ + sizeof(bootfs_header_t);
}
zx::vmo vmo_;
uint32_t dirsize_;
void* dir_;
};
} // namespace devmgr
| true |
45fb05ea27cbe947e5b5e72bc4b7c57a54f5000e | C++ | zonasse/Algorithm | /normal problems/tree/distance_of_two.cpp | GB18030 | 1,871 | 3.625 | 4 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
struct tNode{
int data;
tNode *left;
tNode *right;
tNode(int x):data(x),left(NULL),right(NULL){}
};
class Solution{
public:
/*
* ˼·t1t2Ϊancestor,dis(t1,t2) = dis(root,t1)+dis(root,t2)-2*dis(root,ancestor)
*/
int distance_of_two(tNode *root,tNode *t1,tNode *t2){
if(!root || !t1 || !t2){
return -1;
}
vector<tNode *> node_vec1;
vector<tNode *> node_vec2;
bool find1 = get_node_path(root,t1,node_vec1);
bool find2 = get_node_path(root,t2,node_vec2);
if(!find1 || !find2){
return -1;
}
int ancestorIndex=0;
while(ancestorIndex < node_vec1.size() && ancestorIndex < node_vec2.size()){
if(node_vec1[ancestorIndex] != node_vec2[ancestorIndex]){
break;
}
ancestorIndex++;
}
return node_vec1.size() + node_vec2.size() - 2*ancestorIndex;
}
bool get_node_path(tNode *root,tNode *target,vector<tNode*> &path){
if(!root){
return false;
}
path.push_back(root);
if(root == target){
return true;
}
bool find = get_node_path(root->left,target,path);
if(!find){
find = get_node_path(root->right,target,path);
}
if(!find){
path.pop_back();
}
return find;
}
};
int main(){
tNode *n1 = new tNode(1);
tNode *n2 = new tNode(2);
tNode *n3 = new tNode(3);
tNode *n4 = new tNode(4);
tNode *n5 = new tNode(5);
tNode *n6 = new tNode(6);
n1->left = n2;
n1->right = n3;
n2->left = n4;
n2->right = n5;
n5->right = n6;
Solution handle;
printf("dis = %d\n",handle.distance_of_two(n1,n3,n6));
return 0;
}
| true |
179808ebfa6b0ea557d643d0bea894060a296167 | C++ | shivarao96/MineCraft-Clone | /src/mesh/mesh.h | UTF-8 | 450 | 2.875 | 3 | [] | no_license | #pragma once
/*
* Mesh class representing the DS with following data:
* 1. vertexPositions: position in 3D world
* 2. textureCoordinates: texture for the vertex side.
* 3. indices: to represents the correct index without having duplicate vertices
*/
#include <vector>
class Mesh {
public:
std::vector<float> vertexPositions;
std::vector<float> textureCoordinates;
std::vector<unsigned int> indices;
// clearing the data
void clearData();
}; | true |
dfbafc8d4d1ef3301a8b72bbed57b028ff3e7037 | C++ | DEGoodmanWilson/statlerbot | /beep_boop_persist.h | UTF-8 | 2,688 | 3.03125 | 3 | [] | no_license | //
// Created by D.E. Goodman-Wilson on 8/9/16.
//
#pragma once
// There are far more clever ways to do this. I'd like to use the subscript operator with a custom member class
// so you could use this just like a hash map. But, hey, that can come later.
#include <string>
#include <map>
#include <cpr/cpr.h>
#include "logging.h"
class beep_boop_persist
{
public:
beep_boop_persist(const std::string &url, const std::string &token) :
url_{url}, header_{{"Authorization", "Bearer " + token}}
{
if (url.empty())
{
in_memory_ = true;
LOG(DEBUG) << "beep_boop_persist: Using in-memory store";
}
}
~beep_boop_persist()
{}
template<class K>
bool get(K &&key, std::string &value) const
{
if (in_memory_)
{
if (mem_store_.count(key))
{
value = mem_store_.at(key);
return true;
}
else
{
return false;
}
}
auto resp = cpr::Get(url_ + "/persist/kv" + key, header_);
if (resp.status_code != 200)
{
LOG(WARNING) << "KV GET failure " << resp.status_code << " " << resp.text;
return false;
}
value = resp.text;
return true;
}
// template<class Ks>
// std::string mget(Ks &&keys...) const
// {
// auto resp = cpr::get(url_+"/persist/kv"+key, header_);
// return resp.text;
// }
template<class K, class V>
bool set(K &&key, V &&value)
{
if (key.empty()) return false;
if (in_memory_)
{
mem_store_[key] = value;
return true;
}
auto my_headers = header_;
my_headers["Content-Type"] = "application/json";
auto resp = cpr::Put(url_ + "/persist/kv" + key, my_headers, cpr::Body{value});
if (resp.status_code != 200)
{
LOG(WARNING) << "KV PUT failure " << resp.status_code << " " << resp.text;
return false;
}
return true;
};
template<class K>
bool erase(K &&key)
{
if (key.empty()) return "";
if (in_memory_)
{
mem_store_.erase(key);
return true;
}
auto resp = cpr::Delete(url_ + "/persist/kv" + key, header_);
if (resp.status_code != 200)
{
LOG(WARNING) << "KV DELETE failure " << resp.status_code << " " << resp.text;
return false;
}
return true;
}
private:
cpr::Url url_;
cpr::Header header_;
bool in_memory_;
std::map<std::string, std::string> mem_store_;
};
| true |
f27e4ffb2573904f14ec855cc4627f9fcb4eb1ac | C++ | Shimmen/Prospect | /src/UniformValue.h | UTF-8 | 1,863 | 2.96875 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #pragma once
#include <glad/glad.h>
#include <glm/glm.hpp>
namespace prospect
{
namespace internal
{
template<typename T>
void PerformUniformUpdate(GLuint program, GLint location, T value)
{
assert(false);
}
template <>
inline void PerformUniformUpdate(GLuint program, GLint location, int value)
{
glProgramUniform1i(program, location, value);
}
template <>
inline void PerformUniformUpdate(GLuint program, GLint location, float value)
{
glProgramUniform1f(program, location, value);
}
template <>
inline void PerformUniformUpdate(GLuint program, GLint location, glm::vec2 value)
{
glProgramUniform2fv(program, location, 1, &value.x);
}
template <>
inline void PerformUniformUpdate(GLuint program, GLint location, glm::vec3 value)
{
glProgramUniform3fv(program, location, 1, &value.x);
}
template <>
inline void PerformUniformUpdate(GLuint program, GLint location, glm::vec4 value)
{
glProgramUniform4fv(program, location, 1, &value.x);
}
}
}
template<typename T>
struct Uniform
{
Uniform(const char *name, T initialValue)
{
this->name = name;
assert(value != initialValue);
this->value = initialValue;
}
Uniform(Uniform& other) = delete;
Uniform(Uniform&& other) = delete;
Uniform& operator=(Uniform& other) = delete;
Uniform& operator=(Uniform&& other) = delete;
~Uniform() = default;
void UpdateUniformIfNeeded(GLuint program)
{
if (location == 0 || program != lastProgram)
{
location = glGetUniformLocation(program, name);
}
if (value != lastValue || program != lastProgram)
{
prospect::internal::PerformUniformUpdate(program, location, value);
lastValue = value;
}
lastProgram = program;
}
GLint location = 0;
T value = std::numeric_limits<T>::max();
private:
const char *name;
GLuint lastProgram = 0;
T lastValue = T{};
};
| true |
26af4cf853b1bd83eea7ae39b287d3baaab01853 | C++ | Pentagon03/competitive-programming | /codeforces/Codeforces Round #432/2B.cc | UTF-8 | 553 | 2.84375 | 3 | [] | no_license | #include <cstdio>
using int64 = long long;
int64 dis(int64 x1, int64 y1, int64 x2, int64 y2) {
return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
}
bool coline(int64 x1, int64 y1, int64 x2, int64 y2, int64 x3, int64 y3) {
return (x2 - x1) * (y3 - y1) - (y2 - y1) * (x3 - x1) == 0;
}
int main() {
int64 x1, y1, x2, y2, x3, y3;
scanf("%lld%lld%lld%lld%lld%lld", &x1, &y1, &x2, &y2, &x3, &y3);
if (coline(x1, y1, x2, y2, x3, y3) || dis(x1, y1, x2, y2) != dis(x2, y2, x3, y3)) {
puts("No");
} else {
puts("Yes");
}
return 0;
} | true |
a594d874f94b45889c05f991674fa9b03669ee75 | C++ | unball/ieee-very-small-2012 | /software/vision/output_data.h | UTF-8 | 805 | 2.6875 | 3 | [] | no_license | #ifndef OUTPUT_DATA_H
#define OUTPUT_DATA_H
#include "opencv2/opencv.hpp"
using namespace cv;
#include "tracker.h"
class OutputData
{
public:
OutputData();
~OutputData();
bool Update(Tracker& tracker, float scale = 4.0);
Point2f team_pos[3];
double team_orientation[3];
Point2f opponent_pos[3];
double opponent_orientation[3];
Point2f ball_pos;
protected:
private:
};
/*
O campo possui 170 cm de gol a gol por 130 cm de largura. A imagem tem 640x480.
Para fazer a devida conversao de valores o campo deve cobrir toda a altura da
imagem 480 pixels. Os valores devem ser normalizados sabendo-se que sob as condicoes
acima 480 pixels equivalem a 130 cm. Logo o campo tera 554 pixels de comprimento.
*/
#endif // OUTPUT_DATA_H
| true |
bcf757cb5165c7bbe886e82dab5a7195fa8dd8dd | C++ | von6yka/Arcanoid-3D | /Engine/Render/GLShadowMapGenerator.cpp | UTF-8 | 6,514 | 2.53125 | 3 | [] | no_license | #include "Engine/pch.h"
#include <sstream>
#include "Engine/Render/GLShadowMapGenerator.h"
#include "Engine/Render/GLShaderProperties.h"
#include "Engine/Render/GLMesh.h"
#include "Engine/Scene/Scene.h"
#include "Engine/Scene/SceneObject.h"
#include "Engine/Resource/Mesh.h"
#include "Engine/Resource/ResourceStorage.h"
namespace engine
{
static const int size = 1024; //FIXME:
GLShadowMapGenerator::GLShadowMapGenerator(ResourceStorage& resourceStorage) :
_textureCube(GL_TEXTURE_CUBE_MAP),
_texture2d(GL_TEXTURE_2D)
{
std::stringstream ss;
ss << "#define VERTEX_POSITION " << GLShaderProperties::VERTEX_POSITION << std::endl;
_shader.addDefine(GL_VERTEX_SHADER, "VERTEX");
_shader.addShaderSrc(GL_VERTEX_SHADER, ss.str());
_shader.addShaderFile(GL_VERTEX_SHADER, resourceStorage.basePath() + L"/shaders/Shadow.glsl");
_shader.addDefine(GL_FRAGMENT_SHADER, "FRAGMENT");
_shader.addShaderFile(GL_FRAGMENT_SHADER, resourceStorage.basePath() + L"/shaders/Shadow.glsl");
_shader.build();
initializeShadowMapCube();
initializeShadowMap2d();
}
GLShadowMapGenerator::~GLShadowMapGenerator()
{
}
GLTexture& GLShadowMapGenerator::generate(const Scene& scene, const SceneObject& lightedSceneObject)
{
glDisable(GL_BLEND);
if (lightedSceneObject.light()->type() == Light::Type_Point) {
return generatePoint(scene, lightedSceneObject);
}
else if (lightedSceneObject.light()->type() == Light::Type_Spot) {
return generateSpot(scene, lightedSceneObject);
}
else if (lightedSceneObject.light()->type() == Light::Type_Directional) {
return generateDirection(scene, lightedSceneObject);
}
throw std::runtime_error("Unknown light type");
}
void GLShadowMapGenerator::initializeShadowMapCube()
{
_textureCube.bind(0);
_textureCube.setParameter(GL_TEXTURE_MIN_FILTER, GL_LINEAR);
_textureCube.setParameter(GL_TEXTURE_MAG_FILTER, GL_LINEAR);
_textureCube.setParameter(GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
_textureCube.setParameter(GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
_textureCube.setParameter(GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
_textureCube.setParameter(GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
_textureCube.setParameter(GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);
for (int i = 0; i < 6; ++i) {
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_DEPTH_COMPONENT24, size, size, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);
}
_textureCube.unbind();
}
void GLShadowMapGenerator::initializeShadowMap2d()
{
_texture2d.bind(0);
_texture2d.setParameter(GL_TEXTURE_MIN_FILTER, GL_LINEAR);
_texture2d.setParameter(GL_TEXTURE_MAG_FILTER, GL_LINEAR);
_texture2d.setParameter(GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
_texture2d.setParameter(GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
_texture2d.setParameter(GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
_texture2d.setParameter(GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, size, size, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);
_texture2d.unbind();
_frameBuffer2d.bind();
_frameBuffer2d.attach(GL_DEPTH_ATTACHMENT, _texture2d);
_frameBuffer2d.unbind();
}
GLTexture& GLShadowMapGenerator::generatePoint(const Scene& scene, const SceneObject& lightedSceneObject)
{
const Mat4 projection = Mat4::perspective(90.0f, 1.0, 1.0f, 2048.0f); //FIXME: range
const Mat4 lightTranslation = Mat4::translation(-lightedSceneObject.position());
std::vector<Mat4> viewProjectionVector;
viewProjectionVector.reserve(6);
viewProjectionVector.push_back(projection * Mat4::rotationY(90.0f) * Mat4::rotationX(180.0f) * lightTranslation);
viewProjectionVector.push_back(projection * Mat4::rotationY(-90.0f) * Mat4::rotationX(180.0f) * lightTranslation);
viewProjectionVector.push_back(projection * Mat4::rotationX(-90.0f) * lightTranslation);
viewProjectionVector.push_back(projection * Mat4::rotationX(90.0f) * lightTranslation);
viewProjectionVector.push_back(projection * Mat4::rotationY(180.0f) * Mat4::rotationZ(180.0f) * lightTranslation);
viewProjectionVector.push_back(projection * Mat4::rotationZ(180.0f) * lightTranslation);
_frameBufferCube.bind();
for (std::vector<Mat4>::size_type i = 0; i < viewProjectionVector.size(); ++i) {
_frameBufferCube.attach(GL_DEPTH_ATTACHMENT, GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, _textureCube);
Mat4& viewProjection = viewProjectionVector[i];
renderScene(scene, viewProjection);
}
_frameBufferCube.unbind();
return _textureCube;
}
GLTexture& GLShadowMapGenerator::generateSpot(const Scene& scene, const SceneObject& lightedSceneObject)
{
SpotLight* spotLight = static_cast<SpotLight*>(lightedSceneObject.light());
Mat4 view = lightedSceneObject.orientation().inversed().toMat4() * Mat4::translation(-lightedSceneObject.position());
Mat4 projection = Mat4::perspective(spotLight->angle(), 1.0f, 1.0f, spotLight->range());
Mat4 viewProjection = projection * view;
_frameBuffer2d.bind();
renderScene(scene, viewProjection);
_frameBuffer2d.unbind();
return _texture2d;
}
GLTexture& GLShadowMapGenerator::generateDirection(const Scene& scene, const SceneObject& lightedSceneObject)
{
Mat4 view = lightedSceneObject.orientation().inversed().toMat4() * Mat4::translation(-lightedSceneObject.position());
Mat4 projection = Mat4::ortho(-1000.0f, 1000.0f, -1000.0f, 1000.0f, 1.0f, 2000.0f);
Mat4 viewProjection = projection * view;
_frameBuffer2d.bind();
renderScene(scene, viewProjection);
_frameBuffer2d.unbind();
return _texture2d;
}
void GLShadowMapGenerator::renderScene(const Scene& scene, const Mat4& viewProjection)
{
glViewport(0, 0, size, size);
glClear(GL_DEPTH_BUFFER_BIT);
_shader.use();
std::set<SceneObject*>::const_iterator i = scene.objectSet().begin();
for (i; i != scene.objectSet().end(); ++i) {
SceneObject* sceneObject = *i;
if (sceneObject->isVisible() && !sceneObject->mesh().isNull()) {
Mat4 modelMatrix = Mat4::translation(sceneObject->position()) * sceneObject->orientation().toMat4();
Mat4 modelViewProjection = viewProjection * modelMatrix;
_shader.setUniform("modelViewProjection", modelViewProjection);
static_cast<GLMesh*>(sceneObject->mesh()->renderSystemData)->render();
}
}
}
}//namespace engine
| true |
2e59af6e73b1b8aa2a8ce10f82f1e8965cddded0 | C++ | milczarekIT/agila | /app/Document/SaleDocument/DocumentFK.cpp | UTF-8 | 2,055 | 2.71875 | 3 | [] | no_license | #include "DocumentFK.h"
DocumentFK::DocumentFK()
{
this->documentDate = QDate::currentDate();
this->documentType = "FK";
}
DocumentFK::DocumentFK(Invoice fv)
{
this->fv = fv;
this->copyInvoiceData();
}
void DocumentFK::setInvoice(Invoice fv)
{
this->fv = fv;
}
Invoice DocumentFK::getInvoice()
{
return fv;
}
void DocumentFK::copyInvoiceData()
{
this->contractor = fv.getContractor();
this->discount = fv.getDiscount();
this->saleDate = fv.getSaleDate();
this->paymentDate = fv.getPaymentDate();
this->documentPlace = fv.getDocumentPlace();
this->documentPositions = fv.getDocumentPositions();
this->methodOfPayment = fv.getMethodOfPayment();
this->total = fv.getTotal();
this->issueName = fv.getIssueName();
this->receiveName = fv.getReceiveName();
this->paid = fv.isPaid();
}
int DocumentFK::operator==(DocumentFK doc)
{
if(!(this->fv == doc.getInvoice()))
return 0;
else if(this->methodOfPayment.getId() != doc.getMethodOfPayment().getId())
return 0;
else if(!(this->contractor == doc.getContractor()))
return 0;
else if(this->saleDate != doc.getSaleDate())
return 0;
else if(this->paymentDate != doc.getPaymentDate())
return 0;
else if(this->paid!= doc.isPaid())
return 0;
else if(this->discount != doc.getDiscount())
return 0;
else if (this->documentSymbol !=doc.getSymbol())
return 0;
else if(this->documentPositions != doc.getDocumentPositions())
return 0;
else if(this->documentPlace != doc.getDocumentPlace())
return 0;
else if(this->documentDate != doc.getDocumentDate())
return 0;
else if(this->issueName != doc.getIssueName())
return 0;
else if(this->receiveName != doc.getReceiveName())
return 0;
else if(this->storeResult != doc.getStoreResult())
return 0;
else if(!(this->total-doc.getTotal()<=0.0001 && this->total - doc.getTotal() >= -0.0001))
return 0;
else
return 1;
}
| true |
b7ce53df80ea68db17e7ca8e178f8907de34d680 | C++ | beejeke/cya-ull | /p1-cya/clase_protagonista.cpp | WINDOWS-1250 | 2,143 | 2.75 | 3 | [] | no_license | #include <iostream>
#include "clase_protagonista.hpp"
using namespace std;
Hero::Hero(unsigned x, unsigned y,int vida): //Pasa los parmetros del personaje
x_(x),y_(y),vida_(vida) //Parmetros de coordenadas y vida
{
amuleto_=false;
}
void Hero::move_character(char** mapa){ //Movimiento del personaje
char a='@';
if (kbhit()){// kbhit funcion de conio.h para detectar si se presiona una tecla
char tecla =getch(); //damos el valor de la tecla a una variable
if ((tecla==ARRIBA )&&( mapa[x_-1][y_]!='*') && (mapa[x_-1][y_]!='-')) {
mapa[x_][y_]='.';
x_--;
mapa[x_][y_]=a;
} // si presiinamos j se mueve hacia la izquierda
if ((tecla==ABAJO )&& (mapa[x_+1][y_]!='*') && (mapa[x_+1][y_]!='-')){
mapa[x_][y_]='.';
x_++;
mapa[x_][y_]=a;
} // si presionamos l se mueve hacia la derecha
if ((tecla==IZQUIERDA) && (mapa[x_][y_-1]!='*') && (mapa[x_][y_-1]!='-')){
mapa[x_][y_]='.';
y_--;
mapa[x_][y_]=a;
}// si presionamos i se mueve hacia arriba
if ((tecla==DERECHA) && (mapa[x_][y_+1]!='*') && (mapa[x_][y_+1]!='-')){
mapa[x_][y_]='.';
y_++;
mapa[x_][y_]=a;
}//si presionamos k se mueve hacia abajo
if (mapa[x_][y_]!='&'){
mapa[x_][y_]=a;
amuleto_=true;
}//si presionamos k se mueve hacia abajo
}
}
void Hero::salud(){
vida_--; //Al chocar, te resta una vida
}
unsigned Hero::get_vida(){
return vida_;
}
bool Hero::amuleto(){
amuleto_=true; //Al conseguirlo, te devuelve el amuleto
return amuleto_;
}
| true |
3c60af2e130c14d55d1bb5db10747723de62e2ba | C++ | cpillion/AdvancedComputerGraphics | /hw08/hw08viewer.cpp | UTF-8 | 2,062 | 2.515625 | 3 | [] | no_license | //
// Hw08viewer Widget
//
#include <QComboBox>
#include <QLabel>
#include <QGridLayout>
#include "hw08viewer.h"
//
// Constructor
//
Hw08viewer::Hw08viewer()
{
// Set window title
setWindowTitle(tr("Hw08: Textures for Data Storage (by Chris Pillion)"));
// Create new OpenGL widget
ogl = new Hw08opengl;
// Select shader
QComboBox* shader = new QComboBox();
shader->addItem("Shader Off");
shader->addItem("Shader On");
// View angle and zoom
QLabel* angles = new QLabel();
// Slider
QSlider* slider = new QSlider(Qt::Horizontal);
slider->setRange(1,50);
// Slider
QSlider* slider2 = new QSlider(Qt::Horizontal);
slider2->setRange(0,20);
// Reset
QPushButton* rst = new QPushButton("Reset");
// Quit
QPushButton* quit = new QPushButton("Quit");
// Set layout of child widgets
QGridLayout* layout = new QGridLayout;
layout->addWidget(ogl,0,0,6,1);
layout->addWidget(new QLabel("Shader"),0,1);
layout->addWidget(shader,0,2);
layout->addWidget(new QLabel("Angles"),1,1);
layout->addWidget(angles,1,2);
layout->addWidget(new QLabel("Map Size"),2,1);
layout->addWidget(slider,2,2);
layout->addWidget(new QLabel("Peak Size"),3,1);
layout->addWidget(slider2,3,2);
layout->addWidget(rst,5,1);
layout->addWidget(quit,5,2);
// Manage resizing
layout->setColumnStretch(0,100);
layout->setColumnMinimumWidth(0,100);
layout->setRowStretch(4,100);
setLayout(layout);
// Connect valueChanged() signals to ogl
connect(shader,SIGNAL(currentIndexChanged(int)), ogl,SLOT(setMode(int)));
// Connect angles() and zoom() signal to labels
connect(ogl,SIGNAL(angles(QString)) , angles,SLOT(setText(QString)));
// Connect reset() signal
connect(slider,SIGNAL(valueChanged(int)) , ogl,SLOT(setMsize(int)));
connect(slider2,SIGNAL(valueChanged(int)) , ogl,SLOT(setHsize(int)));
connect(rst ,SIGNAL(pressed()),ogl,SLOT(reset()));
// Connect quit() signal to qApp::quit()
connect(quit,SIGNAL(pressed()) , qApp,SLOT(quit()));
}
| true |
eb98e74e203b46882ca827259f8b30c94d901669 | C++ | linxinwNeo/CS162 | /labs/lab4/Player.cpp | UTF-8 | 5,545 | 3.65625 | 4 | [] | no_license | #include "Player.h"
using namespace std;
//constructors
Player::Player() {
this->hand = Hand();
this->books = NULL;
this->n_books = 0;
}
Player::Player(Hand hand, int* books, int n_books) {
this->books = books;
this->n_books = n_books;
this->hand = hand;
}
//copy constructor
Player::Player(const Player& old_player){
this->hand = old_player.hand;
this->n_books = old_player.n_books;
if(old_player.books!=NULL){
this->books = new int [this->n_books];
for(int i=0;i<this->n_books;i++){
this->books[i] = old_player.books[i];
}
}else
this->books = NULL;
}
//operator overload
Player& Player::operator=(const Player& old_player){
if (this != &old_player){
if(this->books!=NULL){
delete [] this->books;
this->books = NULL;
this->n_books = 0;
}
this->hand = old_player.hand;
this->n_books = old_player.n_books;
if(old_player.books!=NULL){
this->books = new int [this->n_books];
for(int i=0;i<this->n_books;i++){
this->books[i] = old_player.books[i];
}
}else
this->books = NULL;
}
return *this;
}
//destructor
Player::~Player(){
if(this->books!=NULL && this->n_books!=0){
delete [] this->books;
}
this->books = NULL;
this->n_books = 0;
}
//mutators and accessors
void Player::set_hand(Hand hand) {
this->hand = hand;
}
void Player::set_books(int* books) {
this->books = books;
}
void Player::set_n_books(int n_books) {
this->n_books = n_books;
}
Hand Player::get_hand()const {
return this->hand;
}
int* Player::get_books()const {
return this->books;
}
int Player::get_n_books()const {
return this->n_books;
}
//other member functions
void Player::display_unique_ranks() {
Card* cards = this->hand.get_cards();
int unique_card[13];
int count = 0;
for (int i = 0; i < this->hand.get_n_cards(); i++) {
bool condition = true;
for (int j = 0; j < count; j++) {
if (cards[i].get_rank() == unique_card[j]) {
condition = false;
break;
}
}
if (condition == true) {
unique_card[count] = cards[i].get_rank();
count++;
}
}
//sort array
for (int i = 0; i < count; i++) {
for (int j = i + 1; j < count; j++){
if (unique_card[j] < unique_card[i]) {
int temp = unique_card[i];
unique_card[i] = unique_card[j];
unique_card[j] = temp;
}
}
}
cout << "You can ask Carlos one of the following rank: \n";
for (int i = 0; i < count; i++) {
cout << "\t" <<cards[0].map_rank(unique_card[i]) << " ";
}
cout << endl << endl;;
}
void Player::add_book(int rank) {
Card c;
cout << "You got a new book from your cards, it is: " << c.map_rank(rank) << endl;
if (this->books == NULL) {
this->books = new int[1];
this->books[0] = rank;
}
else {
//books array exists, make a bigger one and copy
int* new_arr = new int[this->n_books + 1];
for (int i = 0; i < this->n_books; i++) {
new_arr[i] = this->books[i];
}
new_arr[this->n_books] = rank;
delete[] this->books;
this->books = new_arr;
}
this->n_books++;
this->hand.remove_this_rank(rank);
return;
}
void Player::add_book_computer(int rank) {
Card c;
cout << "Carlos got a new book from his cards, it is: " << c.map_rank(rank) << endl;
if (this->books == NULL) {
this->books = new int[1];
this->books[0] = rank;
}
else {
//books array exists, make a bigger one and copy
int* new_arr = new int[this->n_books + 1];
for (int i = 0; i < this->n_books; i++) {
new_arr[i] = this->books[i];
}
new_arr[this->n_books] = rank;
delete[] this->books;
this->books = new_arr;
}
this->n_books++;
this->hand.remove_this_rank(rank);
return;
}
void Player::display_books()const {
Card c;
if (this->n_books != 0) {
cout << "You now have " << this->n_books << " book(s): " << endl;
for (int i = 0; i < this->n_books; i++) {
cout << "\t" << c.map_rank(this->books[i]) << endl;
}
cout << endl;
}
return;
}
void Player::display_books_computer()const {
Card c;
if (this->n_books != 0) {
cout << "Carlos now has " << this->n_books << " book(s): " << endl;
for (int i = 0; i < this->n_books; i++) {
cout << "\t" << c.map_rank(this->books[i]) << endl;
}
cout << endl;
}
return;
}
void Player::make_book() {
int rank = this->hand.which_book();
switch (rank) {
case -1: break;//there is no book can be made, do nothing
case 0: add_book(0); break;
case 1: add_book(1); break;
case 2: add_book(2); break;
case 3: add_book(3); break;
case 4: add_book(4); break;
case 5: add_book(5); break;
case 6: add_book(6); break;
case 7: add_book(7); break;
case 8: add_book(8); break;
case 9: add_book(9); break;
case 10: add_book(10); break;
case 11: add_book(11); break;
case 12: add_book(12); break;
}
}
void Player::make_book_computer() {
int rank = this->hand.which_book();
switch (rank) {
case -1: break;//there is no book can be made, do nothing
case 0: add_book_computer(0); break;
case 1: add_book_computer(1); break;
case 2: add_book_computer(2); break;
case 3: add_book_computer(3); break;
case 4: add_book_computer(4); break;
case 5: add_book_computer(5); break;
case 6: add_book_computer(6); break;
case 7: add_book_computer(7); break;
case 8: add_book_computer(8); break;
case 9: add_book_computer(9); break;
case 10: add_book_computer(10); break;
case 11: add_book_computer(11); break;
case 12: add_book_computer(12); break;
}
} | true |
dc67f412c8898c8e4e9afa555b7b7aa3ff360973 | C++ | alexandraback/datacollection | /solutions_5690574640250880_1/C++/Jubanka/mine.cpp | UTF-8 | 3,348 | 2.875 | 3 | [] | no_license | #include <iostream>
using namespace std;
#define MIN(x, y) ( ((x) < (y)) ? (x) : (y))
#define MAX(x, y) ( ((x) > (y)) ? (x) : (y))
char board[50][50], tmpb[50][50];
int R, C, M;
inline bool blocked(int x, int y)
{
if (x >= C || y >= R || x < 0 || y < 0) return true;
return (board[y][x] == '*');
}
void print(ostream &s = cout)
{
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
s << board[i][j];
}
s << endl;
}
}
void printb(void)
{
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
cerr << tmpb[i][j];
}
cerr << endl;
}
}
bool floodRow(int r, int c, int res)
{
//cerr << "floodRow" << endl;
int cnt = 0;
int xs;
for (xs = 0; ! blocked(xs, r); xs++, cnt++);
int put;
if (cnt <= M)
put = cnt;
else if (M + res < cnt)
put = M;
else
put = cnt - res;
//cerr << M << " " << put << " " << cnt << " " << r << " " << c << endl;
if (put <= 0) return false;
for (int x = 0; x < put; board[r][xs - 1 - x] = '*', x++);
//print(cerr);
M -= put;
return (put == cnt);
}
bool floodCol(int r, int c, int res)
{
//cerr << "floodCol" << endl;
int cnt = 0;
int ys;
for (ys = R - 1; ! blocked(C - 1 - c, ys); ys--, cnt++);
int put;
if (cnt <= M)
put = cnt;
else if (M + res < cnt)
put = M;
else
put = cnt - res;
//cerr << M << " " << put << " " << cnt << " " << r << " " << c << endl;
if (put <= 0) return false;
for (int y = 0; y < put; board[ys + 1 + y][C - 1 - c] = '*', y++);
//print(cerr);
M -= put;
return (put == cnt);
}
bool solve(void)
{
int i, j, m;
m = MIN(R, C);
if (R * C - M == 0) return false;
for (i = 0; i < R; i++)
for (j = 0; j < C; j++)
board[i][j] = '.';
int rtg = 0, ctg = 0;
while (true) {
if (M == 0) return true;
bool row = (R - rtg >= C - ctg);
if (row) {
if (! floodRow(rtg, ctg, 2)) {
rtg++;
if (! floodCol(rtg, ctg, 2))
return false;
else
ctg++;
} else
rtg++;
} else {
if (! floodCol(rtg, ctg, 2)) {
ctg++;
if (! floodRow(rtg, ctg, 2))
return false;
else
rtg++;
} else
ctg++;
}
}
}
bool hasstar(int r, int c)
{
for (int i = MAX(0, r - 1); i <= MIN(r + 1, R - 1); i++)
for (int j = MAX(0, c - 1); j <= MIN(c + 1, C - 1); j++)
if (tmpb[i][j] == '*')
return true;
return false;
}
void vr(int r, int c)
{
//cerr << r << c << hasstar(r,c) << endl;
if (tmpb[r][c] == 'X') return;
tmpb[r][c] = 'X';
if (hasstar(r, c)) return;
for (int i = MAX(0, r - 1); i <= MIN(r + 1, R - 1); i++)
for (int j = MAX(0, c - 1); j <= MIN(c + 1, C - 1); j++) {
//cerr << "Rec" << i << j << "-" << MAX(0, c-1) << MIN (c+1, C -1) << endl;
vr(i, j);
//cerr << "Recout" << i << j << endl;
}
}
bool verify(void)
{
for (int i = 0; i < R; i++)
for (int j = 0; j < C; j++)
tmpb[i][j] = board[i][j];
vr(R - 1, 0);
//printb();
for (int i = 0; i < R; i++)
for (int j = 0; j < C; j++)
if (tmpb[i][j] == '.')
return false;
return true;
}
int main(void)
{
int T, Mo;
cin >> T;
for (int t = 1; t <= T; t++) {
cin >> R >> C >> M;
Mo = M;
cout << "Case #" << t << ":" << endl;
cerr << "Case #" << t << ":" << endl;
solve();
if (M == 0 && verify()) {
board[R - 1][0] = 'c';
print();
} else {
cout << "Impossible" << endl;
//cerr << M << " " << Mo << endl;
//print(cerr);
//printb();
}
}
return 0;
}
| true |
73484bef06a281bab63c434dec1dd3bf517a4705 | C++ | Sophistt/Draftcode | /C++/C-plus-learn/practice/作业5/Screen.cpp | UTF-8 | 587 | 3.28125 | 3 | [
"MIT"
] | permissive | #include "Screen.h"
#include <cstdlib>
Screen* Screen::instance = 0;
void Screen::exitWhenInvalidScreen(int width, int height){
if( width <= 0 || width > 1000 || height <=0 || height > 1000 ){
std::cout << "invalid screen size";
exit(0);
}
}
Screen* Screen::getInstance(int width, int height){
if (Screen::instance == 0){
Screen* p = new Screen(width, height);
Screen::instance = p;
return Screen::instance;
}
else{
return Screen::instance;
}
}
void Screen::deleteInstance() {
if (Screen::instance != 0) {
delete Screen::instance;
Screen::instance = 0;
}
} | true |
33cfea0a12434b49ac69ad17b6c75238c78861db | C++ | sharmaashish/emory-cci-fast-ia-gsoc | /fastIA-master/src/segment/opencl/utils/ocl_utils.cpp | UTF-8 | 3,115 | 2.59375 | 3 | [
"Apache-2.0"
] | permissive | #include "ocl_utils.h"
#include <iostream>
void oclSimpleInit(cl_device_type type,
cl::Context& context, std::vector<cl::Device>& devices)
{
try{
std::vector<cl::Platform> platforms;
cl_int err = CL_SUCCESS;
cl::Platform::get(&platforms);
if (!platforms.size())
{
std::cout << "Platform size 0" << std::endl;
}
else
{
std::cout << "Platforms size: " << platforms.size() << std::endl;
std::string platform_name = platforms[0].getInfo<CL_PLATFORM_NAME>();
std::cout << "Platform name: " << platform_name << std::endl;
std::cout << "Platform name: "
<< platforms[0].getInfo<CL_PLATFORM_NAME>() << std::endl;
}
cl_context_properties properties[] =
{CL_CONTEXT_PLATFORM, (cl_context_properties)(platforms[0])(), 0};
context = cl::Context(type, properties, NULL, NULL, &err);
//std::cout << (err == CL_SUCCESS ? "true" : "false") << std::endl;
int num_devices = context.getInfo<CL_CONTEXT_NUM_DEVICES>();
std::cout << "num devices: " << num_devices << std::endl;
devices = context.getInfo<CL_CONTEXT_DEVICES>();
for(int i = 0; i < devices.size(); ++i){
cl::Device& device = devices[i];
std::cout << device.getInfo<CL_DEVICE_NAME>() << std::endl;
}
}
catch (cl::Error err)
{
oclPrintError(err);
}
}
void oclPrintError(cl::Error &error)
{
std::cerr << "ERROR: " << error.what()
<< "(" << error.err() << ")" << std::endl;
}
cl::Buffer ocvMatToOclBuffer(cv::Mat& mat, cl::CommandQueue& queue)
{
cl::Context context = queue.getInfo<CL_QUEUE_CONTEXT>();
int size_in_bytes = mat.rows * mat.step;
cl::Buffer buffer(context, CL_TRUE, size_in_bytes);
queue.enqueueWriteBuffer(buffer, CL_TRUE, 0, size_in_bytes, mat.data);
return buffer;
}
void ocvMatToOclBuffer(cv::Mat& mat, cl::Buffer& buffer,
cl::Context& context, cl::CommandQueue& queue)
{
size_t data_size = mat.step * mat.size().height;
buffer = cl::Buffer(context, CL_TRUE, data_size);
queue.enqueueWriteBuffer(buffer, CL_TRUE, 0, data_size, mat.data);
}
void oclBufferToOcvMat(cv::Mat& mat, cl::Buffer& buffer,
int size, cl::CommandQueue& queue)
{
queue.enqueueReadBuffer(buffer, CL_TRUE, 0, size, mat.data);
}
void oclBuferToOcvMat(cv::Mat& mat, cl::Buffer buffer,
cl::CommandQueue queue)
{
queue.enqueueReadBuffer(buffer, CL_TRUE,
0, mat.step * mat.size().height, mat.data);
}
#ifdef OPENCL_PROFILE
static float executionTime;
float getLastExecutionTime()
{
return executionTime;
}
void setLastExecutionTime(float time)
{
executionTime = time;
}
bool checkProfilingSupport(cl::CommandQueue& queue)
{
cl_command_queue_properties queue_properties
= queue.getInfo<CL_QUEUE_PROPERTIES>();
return (queue_properties & CL_QUEUE_PROFILING_ENABLE) != 0;
}
#endif
| true |
2a7b698b66f85d1f8bf04b0e5f25a16cc4fa06ba | C++ | Farrius/cp | /codeforces/educational_91/as.cpp | UTF-8 | 466 | 2.59375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main(){
int t;
cin >> t;
while(t--){
int n;
cin >> n;
int a[n];
for(int i = 0; i < n; i++){
cin >> a[i];
}
bool ok = false;
for(int i = 2; i < n; i++){
if(ok) break;
if(a[i] < a[i - 1] && a[i - 1] > a[i - 2]){
cout << "YES" << '\n';
cout << i - 2 + 1 << ' ' << i - 1 + 1 << ' ' << i + 1 << '\n';
ok = true;
}
}
if(!ok) cout << "NO" << '\n';
}
}
| true |
074ba1cc8d7e5584de26e97c24fd2a60611715db | C++ | prakharss/Mind-Blowing-Approaches-and-Code | /BST/Distance between Nodes of BST.cpp | UTF-8 | 1,734 | 3.734375 | 4 | [] | no_license | /**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
/*
O(H) S(1)
It is assumed that both keys exists in the tree (that's why not checking if(root!=NULL))
*/
//Iterative solution
int distanceBetweenRootAndNode(TreeNode* A, int key) {
int res=0;
while(1) {
if(key<A->val) {
res++;
A=A->left;
}
else if(A->val<key) {
res++;
A=A->right;
}
else
break;
}
return res;
}
int distanceBetweenTwoNodes(TreeNode* A,int B,int C) {
while(1) {
if(B<A->val && C<A->val)
A=A->left;
else if(A->val<B && A->val<C)
A=A->right;
else
break;
}
return distanceBetweenRootAndNode(A,B)+distanceBetweenRootAndNode(A,C);
}
int Solution::solve(TreeNode* A, int B, int C) {
return distanceBetweenTwoNodes(A,B,C);
}
//Recursive solution O(H) S(H)
/*
int distanceBetweenRootAndNode(TreeNode* A, int key) {
if(key<A->val) {
return 1+distanceBetweenRootAndNode(A->left,key);
}
else if(A->val<key) {
return 1+distanceBetweenRootAndNode(A->right,key);
}
return 0;
}
int distanceBetweenTwoNodes(TreeNode* A,int B,int C) {
if(B<A->val && C<A->val) {
return distanceBetweenTwoNodes(A->left,B,C);
}
else if(A->val<B && A->val<C) {
return distanceBetweenTwoNodes(A->right,B,C);
}
return distanceBetweenRootAndNode(A,B)+distanceBetweenRootAndNode(A,C);
}
int Solution::solve(TreeNode* A, int B, int C) {
return distanceBetweenTwoNodes(A,B,C);
}
*/
| true |
14fe8d2ff2b0a5d2d6b22c10c443fc3f5fb90bca | C++ | ravi-kr-singh/CSES_Competitive_Programming | /Dynamic Programming/14_increasing_subsequence.cpp | UTF-8 | 1,132 | 3.53125 | 4 | [] | no_license | /*
Time limit: 1.00 s Memory limit: 512 MB
You are given an array containing n integers. Your task is to determine the longest increasing subsequence in the array, i.e., the longest subsequence where every element is larger than the previous one.
A subsequence is a sequence that can be derived from the array by deleting some elements without changing the order of the remaining elements.
Input
The first line contains an integer n: the size of the array.
After this there are n integers x1,x2,…,xn: the contents of the array.
Output
Print the length of the longest increasing subsequence.
Constraints
1≤n≤2⋅105
1≤xi≤10^9
Example
Input:
8
7 3 5 3 6 2 9 8
Output:
4
*/
#include<iostream>
using namespace std;
int main(){
int n;
cin>>n;
int* arr = new int[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
int dp[n];
dp[0] = 1;
int ans = 1;
for(int i=1;i<n;i++){
dp[i] = 1;
for(int j=0;j<i;j++){
if(arr[i]>arr[j] && dp[j]>=dp[i])
dp[i] = dp[j] + 1;
}
ans = max(ans,dp[i]);
}
cout<<ans<<" ";
return 0;
} | true |
4045b3316497a5ad421575e36461e03300629000 | C++ | jcao02/Problems | /done/MAXWOODS.cpp | UTF-8 | 1,355 | 2.5625 | 3 | [] | no_license | #include <iostream>
#include <cstring>
#define MAX 200
int rows, cols;
char map[MAX+1][MAX+1];
int dp[MAX + 2];
int solve() {
if (map[0][0] == '#') {
return 0;
}
dp[1] = 0;
int maxWoods = 0;
for (int r = 0; r < rows; ++r) {
if (r % 2 == 0) {
for (int c = 0; c < cols; ++c) {
if (map[r][c] == '#' || (dp[c] == -1 && dp[c + 1] == -1)) {
dp[c + 1] = -1;
} else {
dp[c + 1] = (map[r][c] == 'T' ? 1 : 0) + std::max(dp[c + 1], dp[c]);
}
maxWoods = std::max(dp[c + 1], maxWoods);
}
} else {
for (int c = cols - 1; c >= 0; --c) {
if (map[r][c] == '#' || (dp[c + 2] == -1 && dp[c + 1] == -1)) {
dp[c + 1] = -1;
} else {
dp[c + 1] = (map[r][c] == 'T' ? 1 : 0) + std::max(dp[c + 2], dp[c + 1]);
}
maxWoods = std::max(dp[c + 1], maxWoods);
}
}
}
return maxWoods;
}
int main() {
int t;
std::cin >> t;
while (t--) {
std::cin >> rows >> cols;
for (int i = 0; i < rows; ++i) {
std::cin >> map[i];
}
memset(dp, -1, sizeof(dp));
std::cout << solve() << std::endl;
}
}
| true |
2b98bc1202bc95951c06ae4d58a59fde3e2ceb6b | C++ | edison-caldwell/SchoolWork | /2017SPRING/CSCI313/project/checkOut.cpp | UTF-8 | 4,896 | 2.84375 | 3 | [] | no_license | /*
* This application ends a reservation and creates a bill for the guest.
* Compile Line: c++ -o checkOut checkOut.cpp $(mysql_config --libs)
*/
#include "/usr/include/mysql/mysql.h"
#include <iostream>
#include <string>
#include <sstream>
#include <cstdlib>
using namespace std;
const string DB = "teamF";
const string PASSWORD = "070396";
const string LOGIN_TABLE = "Guest";
const string RES_TABLE = "Reservation";
const string RES_ROOM_TABLE = "ResRooms";
const string ROOM_TABLE = "Room";
const string BILL_TABLE = "Bill";
const float ROOM_COST = 49.99;
int main()
{
MYSQL * conn;
MYSQL_RES * queryResult;
MYSQL_ROW aRow;
string command,
memberID,
resID,
password,
hotelID,
cost_str;
bool logged_in = false;
int fieldCnt;
//Get user ID.
cout << "Enter memberID=>";
cin >> memberID;
//Get user password.
cout << "Enter password=>";
cin >> password;
cout << endl;
//Connect to database.
conn = mysql_init(NULL);
if (mysql_real_connect(conn, "", "", PASSWORD.c_str(), DB.c_str(), 0, NULL, 0)
== NULL)
{
cout << "Connection Failed: " << endl;
cout << mysql_error(conn) << endl;
return -1;
}
//Validate password.
command = "SELECT password FROM " + LOGIN_TABLE + " WHERE memberID = " + memberID;
if (mysql_query(conn, command.c_str()) != 0)
{
cout << "Query failed: " << endl;
cout << mysql_error(conn) << endl;
return -1;
}
queryResult = mysql_store_result(conn);
if ((aRow = mysql_fetch_row(queryResult)) != NULL)
{
if(aRow[0] == password)
{
logged_in = true;
cout << "Login successful!" << endl;
}else{
cout << "MemberID or Password is incorrect. Login failed." << endl;
return -1;
}
}
mysql_free_result(queryResult);
//Get reservation ID.
cout << "Enter reservation ID=>";
cin >> resID;
cout << endl;
//Free rooms.
//Get hotel ID.
command = "SELECT hotelID FROM " + RES_TABLE + " WHERE reservationID = " + resID;
if (mysql_query(conn, command.c_str()) != 0)
{
cout << "Query failed: " << endl;
cout << mysql_error(conn) << endl;
return -1;
}
queryResult = mysql_store_result(conn);
if ((aRow = mysql_fetch_row(queryResult)) != NULL)
{
hotelID = aRow[0];
}else{
cout << "Something is incorrect. Request denied." << endl;
return -1;
}
mysql_free_result(queryResult);
//Get room nums.
command = "SELECT roomNum FROM " + RES_ROOM_TABLE + " WHERE reservationID = " + resID;
if (mysql_query(conn, command.c_str()) != 0)
{
cout << "Query failed: " << endl;
cout << mysql_error(conn) << endl;
return -1;
}
queryResult = mysql_store_result(conn);
//Free one room at a time.
fieldCnt = mysql_num_fields(queryResult);
while ((aRow = mysql_fetch_row(queryResult)) != NULL)
{
for(int i = 0; i < fieldCnt; i++){
if (aRow[i] != NULL){
command = "UPDATE " + ROOM_TABLE + " SET open = 1 where roomNum = " + aRow[i] + " and hotelID = " + hotelID;
if (mysql_query(conn, command.c_str()) != 0)
{
cout << "Query failed: " << endl;
cout << mysql_error(conn) << endl;
return -1;
}
}
}
}
mysql_free_result(queryResult);
//Delete room reservation.
command = "DELETE FROM " + RES_ROOM_TABLE + " WHERE reservationID = " + resID;
if (mysql_query(conn, command.c_str()) != 0)
{
cout << "Query failed: " << endl;
cout << mysql_error(conn) << endl;
return -1;
}
//Create guest bill.
//Get cost.
command = "SELECT cost FROM " + RES_TABLE + " WHERE reservationID = " + resID;
if (mysql_query(conn, command.c_str()) != 0)
{
cout << "An error has occured." << endl;
cout << mysql_error(conn) << endl;
return -1;
}
queryResult = mysql_store_result(conn);
if ((aRow = mysql_fetch_row(queryResult)) != NULL)
{
cost_str = aRow[0];
}
mysql_free_result(queryResult);
//Create bill.
command = "INSERT INTO " + BILL_TABLE + " VALUES(NULL," + resID + "," + memberID + "," + cost_str + ");";
if (mysql_query(conn, command.c_str()) != 0)
{
cout << "Query failed: " << endl;
cout << mysql_error(conn) << endl;
return -1;
}
//Delete reservation
command = "DELETE FROM " + RES_TABLE + " WHERE reservationID = " + resID + " and memberID = " + memberID;
if (mysql_query(conn, command.c_str()) != 0)
{
cout << "Query failed: " << endl;
cout << mysql_error(conn) << endl;
return -1;
}else{
cout << "Check out complete." << endl;
cout << "Amount due: " << cost_str << "." << endl;
}
mysql_close(conn);
return 0;
}
| true |
bd181e862876e0e359fb70984bcce0d7f8cfb873 | C++ | zossem/D001_Ulamek_Zwykly | /D001_ulamek_zwykly/ulamek_zwykly.cpp | UTF-8 | 11,470 | 2.625 | 3 | [] | no_license | #include <iostream>
#include <cmath>
#include "ulamek_zwykly.h"
using namespace std;
cUlamekZwykly::cUlamekZwykly(long long int Calosci, long long int Licznik, long long int Mianownik)
{
m_Calosci=Calosci;
m_Licznik=Licznik;
while(Mianownik==0)
{
cout<<"Nie dziel przez zero i podaj inny mianownik"<<endl;
cin>>Mianownik;
}
m_Mianownik=Mianownik;
}
void cUlamekZwykly::Skracanie()
{
long long int NWD=NajwiekszyWspolnyDzielnik(m_Licznik, m_Mianownik);
m_Licznik=m_Licznik/NWD;
m_Mianownik=m_Mianownik/NWD;
if(m_Mianownik<0)
{
m_Mianownik=m_Mianownik*(-1);
m_Licznik=m_Licznik*(-1);
}
}
void cUlamekZwykly::WyciaganieCalosciPrzed()
{
m_Calosci=(m_Licznik/m_Mianownik)+m_Calosci;
m_Licznik=m_Licznik%m_Mianownik;
if(m_Calosci<0)
{
if(m_Licznik<0)
m_Licznik=m_Licznik*(-1);
}
}
void cUlamekZwykly::CalosciDoLicznika()
{
m_Licznik=m_Licznik+m_Mianownik*m_Calosci;
m_Calosci=0;
}
long long int cUlamekZwykly::Licznik(){return m_Licznik;}
long long int cUlamekZwykly::Mianownik(){return m_Mianownik;}
long long int cUlamekZwykly::Calosci(){return m_Calosci;}
void cUlamekZwykly::Wypisz()
{
cout<<"To ulamek zwykly:"<<endl;
int ile_cyfr_calosci=0, ile_cyfr_licznik=0, ile_cyfr_mianownik=0;
long long int calosci=m_Calosci, licznik=m_Licznik, mianownik=m_Mianownik;
while(calosci!=0)
{
calosci=calosci/10;
ile_cyfr_calosci++;
}
while(licznik!=0)
{
licznik=licznik/10;
ile_cyfr_licznik++;
}
while(mianownik!=0)
{
mianownik=mianownik/10;
ile_cyfr_mianownik++;
}
if(m_Calosci<0)
ile_cyfr_calosci++;
if(m_Licznik<0)
ile_cyfr_licznik++;
if(m_Mianownik<0)
ile_cyfr_mianownik++;
if(ile_cyfr_mianownik>ile_cyfr_licznik)
{
if(m_Calosci!=0)
{
if(m_Licznik!=0)
{
for(int i=0; i<ile_cyfr_calosci+ile_cyfr_mianownik-ile_cyfr_licznik; i++)
{
cout<<" ";
}
cout<<m_Licznik<<endl<<m_Calosci;
for(int i=0; i< ile_cyfr_mianownik; i++)
{
cout<<"-";
}
cout<<endl;
for(int i=0; i<ile_cyfr_calosci; i++)
{
cout<<" ";
}
cout<<m_Mianownik<<endl<<endl;
}
else
{
cout<<m_Calosci<<endl<<endl;
}
}
else
{
if(m_Licznik!=0)
{
for(int i=0; i<ile_cyfr_mianownik-ile_cyfr_licznik; i++)
{
cout<<" ";
}
cout<<m_Licznik<<endl;
for(int i=0; i< ile_cyfr_mianownik; i++)
{
cout<<"-";
}
cout<<endl;
cout<<m_Mianownik<<endl<<endl;
}
else
{
cout<<m_Calosci<<endl<<endl;
}
}
}
else
{
if(m_Calosci!=0)
{
if(m_Licznik!=0)
{
for(int i=0; i<ile_cyfr_calosci; i++)
{
cout<<" ";
}
cout<<m_Licznik<<endl<<m_Calosci;
for(int i=0; i< ile_cyfr_licznik; i++)
{
cout<<"-";
}
cout<<endl;
for(int i=0; i<ile_cyfr_calosci-ile_cyfr_mianownik+ile_cyfr_licznik; i++)
{
cout<<" ";
}
cout<<m_Mianownik<<endl<<endl;
}
else
{
cout<<m_Calosci<<endl<<endl;
}
}
else
{
if(m_Licznik!=0)
{
cout<<m_Licznik<<endl;
for(int i=0; i< ile_cyfr_licznik; i++)
{
cout<<"-";
}
cout<<endl;
for(int i=0; i<ile_cyfr_licznik-ile_cyfr_mianownik; i++)
{
cout<<" ";
}
cout<<m_Mianownik<<endl<<endl;
}
else
{
cout<<m_Calosci<<endl<<endl;
}
}
}
}
long long int cUlamekZwykly::NajwiekszyWspolnyDzielnik(long long int LiczbaA, long long int LiczbaB)
{
long long int reszta;
while(LiczbaB!=0)
{
reszta=LiczbaA%LiczbaB;
LiczbaA=LiczbaB;
LiczbaB=reszta;
}
if(LiczbaA>0)
return LiczbaA;
else
return (LiczbaA*(-1));
}
long long int cUlamekZwykly::NajmniejszaWspolnaWielokrotnosc(long long int LiczbaA, long long int LiczbaB)
{
long long int NWD=NajwiekszyWspolnyDzielnik(LiczbaA, LiczbaB);
if (((LiczbaA/NWD)*LiczbaB)>0)
return ((LiczbaA/NWD)*LiczbaB);
else
return ((LiczbaA/NWD)*LiczbaB* (-1));
}
cUlamekZwykly cUlamekZwykly::operator*(cUlamekZwykly UlamekP)
{
cUlamekZwykly UlamekLewy(m_Calosci, m_Licznik, m_Mianownik);
cUlamekZwykly UlamekPrawy(UlamekP.Calosci(), UlamekP.Licznik(), UlamekP.Mianownik());
UlamekLewy.CalosciDoLicznika();
UlamekPrawy.CalosciDoLicznika();
long long int Licznik=UlamekLewy.Licznik()*UlamekPrawy.Licznik();
long long int Mianownik=UlamekLewy.Mianownik()*UlamekPrawy.Mianownik();
cUlamekZwykly rezultat(0, Licznik, Mianownik);
rezultat.Skracanie();
rezultat.WyciaganieCalosciPrzed();
return rezultat;
}
cUlamekZwykly cUlamekZwykly::operator/(cUlamekZwykly UlamekP)
{
cUlamekZwykly UlamekLewy(m_Calosci, m_Licznik, m_Mianownik);
cUlamekZwykly UlamekPrawy(UlamekP.Calosci(), UlamekP.Licznik(), UlamekP.Mianownik());
UlamekLewy.CalosciDoLicznika();
UlamekPrawy.CalosciDoLicznika();
cUlamekZwykly Odwrotnosc(0, UlamekPrawy.Mianownik(), UlamekPrawy.Licznik());
cUlamekZwykly rezultat=UlamekLewy*Odwrotnosc;
return rezultat;
}
cUlamekZwykly cUlamekZwykly::operator+(cUlamekZwykly UlamekP)
{
cUlamekZwykly UlamekLewy(m_Calosci, m_Licznik, m_Mianownik);
cUlamekZwykly UlamekPrawy(UlamekP.Calosci(), UlamekP.Licznik(), UlamekP.Mianownik());
UlamekLewy.CalosciDoLicznika();
UlamekPrawy.CalosciDoLicznika();
long long int NWW=NajmniejszaWspolnaWielokrotnosc(UlamekLewy.Mianownik(), UlamekPrawy.Mianownik());
long long int Licznik=(NWW/UlamekLewy.Mianownik())*UlamekLewy.Licznik() + (NWW/UlamekPrawy.Mianownik())*UlamekPrawy.Licznik();
long long int Mianownik=NWW;
cUlamekZwykly rezultat(0, Licznik, Mianownik);
rezultat.Skracanie();
rezultat.WyciaganieCalosciPrzed();
return rezultat;
}
cUlamekZwykly cUlamekZwykly::operator-(cUlamekZwykly UlamekP)
{
cUlamekZwykly UlamekLewy(m_Calosci, m_Licznik, m_Mianownik);
cUlamekZwykly UlamekPrawy(UlamekP.Calosci(), UlamekP.Licznik(), UlamekP.Mianownik());
UlamekLewy.CalosciDoLicznika();
UlamekPrawy.CalosciDoLicznika();
long long int NWW=NajmniejszaWspolnaWielokrotnosc(UlamekLewy.Mianownik(), UlamekPrawy.Mianownik());
long long int Licznik=(NWW/UlamekLewy.Mianownik())*UlamekLewy.Licznik() - (NWW/UlamekPrawy.Mianownik())*UlamekPrawy.Licznik();
long long int Mianownik=NWW;
cUlamekZwykly rezultat(0, Licznik, Mianownik);
rezultat.Skracanie();
rezultat.WyciaganieCalosciPrzed();
return rezultat;
}
bool cUlamekZwykly::operator==(cUlamekZwykly UlamekP)
{
cUlamekZwykly UlamekLewy(m_Calosci, m_Licznik, m_Mianownik);
cUlamekZwykly UlamekPrawy(UlamekP.Calosci(), UlamekP.Licznik(), UlamekP.Mianownik());
UlamekLewy.CalosciDoLicznika();
UlamekPrawy.CalosciDoLicznika();
long long int NWW=NajmniejszaWspolnaWielokrotnosc(UlamekLewy.Mianownik(), UlamekPrawy.Mianownik());
long long int LicznikLewy=(NWW/UlamekLewy.Mianownik())*UlamekLewy.Licznik();
long long int LicznikPrawy=(NWW/UlamekPrawy.Mianownik())*UlamekPrawy.Licznik();
bool rezultat=(LicznikLewy==LicznikPrawy);
return rezultat;
}
bool cUlamekZwykly::operator!=(cUlamekZwykly UlamekP)
{
cUlamekZwykly UlamekLewy(m_Calosci, m_Licznik, m_Mianownik);
cUlamekZwykly UlamekPrawy(UlamekP.Calosci(), UlamekP.Licznik(), UlamekP.Mianownik());
UlamekLewy.CalosciDoLicznika();
UlamekPrawy.CalosciDoLicznika();
long long int NWW=NajmniejszaWspolnaWielokrotnosc(UlamekLewy.Mianownik(), UlamekPrawy.Mianownik());
long long int LicznikLewy=(NWW/UlamekLewy.Mianownik())*UlamekLewy.Licznik();
long long int LicznikPrawy=(NWW/UlamekPrawy.Mianownik())*UlamekPrawy.Licznik();
bool rezultat=(LicznikLewy!=LicznikPrawy);
return rezultat;
}
bool cUlamekZwykly::operator>(cUlamekZwykly UlamekP)
{
cUlamekZwykly UlamekLewy(m_Calosci, m_Licznik, m_Mianownik);
cUlamekZwykly UlamekPrawy(UlamekP.Calosci(), UlamekP.Licznik(), UlamekP.Mianownik());
UlamekLewy.CalosciDoLicznika();
UlamekPrawy.CalosciDoLicznika();
long long int NWW=NajmniejszaWspolnaWielokrotnosc(UlamekLewy.Mianownik(), UlamekPrawy.Mianownik());
long long int LicznikLewy=(NWW/UlamekLewy.Mianownik())*UlamekLewy.Licznik();
long long int LicznikPrawy=(NWW/UlamekPrawy.Mianownik())*UlamekPrawy.Licznik();
bool rezultat=(LicznikLewy>LicznikPrawy);
return rezultat;
}
bool cUlamekZwykly::operator<(cUlamekZwykly UlamekP)
{
cUlamekZwykly UlamekLewy(m_Calosci, m_Licznik, m_Mianownik);
cUlamekZwykly UlamekPrawy(UlamekP.Calosci(), UlamekP.Licznik(), UlamekP.Mianownik());
UlamekLewy.CalosciDoLicznika();
UlamekPrawy.CalosciDoLicznika();
long long int NWW=NajmniejszaWspolnaWielokrotnosc(UlamekLewy.Mianownik(), UlamekPrawy.Mianownik());
long long int LicznikLewy=(NWW/UlamekLewy.Mianownik())*UlamekLewy.Licznik();
long long int LicznikPrawy=(NWW/UlamekPrawy.Mianownik())*UlamekPrawy.Licznik();
bool rezultat=(LicznikLewy<LicznikPrawy);
return rezultat;
}
bool cUlamekZwykly::operator>=(cUlamekZwykly UlamekP)
{
cUlamekZwykly UlamekLewy(m_Calosci, m_Licznik, m_Mianownik);
cUlamekZwykly UlamekPrawy(UlamekP.Calosci(), UlamekP.Licznik(), UlamekP.Mianownik());
UlamekLewy.CalosciDoLicznika();
UlamekPrawy.CalosciDoLicznika();
long long int NWW=NajmniejszaWspolnaWielokrotnosc(UlamekLewy.Mianownik(), UlamekPrawy.Mianownik());
long long int LicznikLewy=(NWW/UlamekLewy.Mianownik())*UlamekLewy.Licznik();
long long int LicznikPrawy=(NWW/UlamekPrawy.Mianownik())*UlamekPrawy.Licznik();
bool rezultat=(LicznikLewy>=LicznikPrawy);
return rezultat;
}
bool cUlamekZwykly::operator<=(cUlamekZwykly UlamekP)
{
cUlamekZwykly UlamekLewy(m_Calosci, m_Licznik, m_Mianownik);
cUlamekZwykly UlamekPrawy(UlamekP.Calosci(), UlamekP.Licznik(), UlamekP.Mianownik());
UlamekLewy.CalosciDoLicznika();
UlamekPrawy.CalosciDoLicznika();
long long int NWW=NajmniejszaWspolnaWielokrotnosc(UlamekLewy.Mianownik(), UlamekPrawy.Mianownik());
long long int LicznikLewy=(NWW/UlamekLewy.Mianownik())*UlamekLewy.Licznik();
long long int LicznikPrawy=(NWW/UlamekPrawy.Mianownik())*UlamekPrawy.Licznik();
bool rezultat=(LicznikLewy<=LicznikPrawy);
return rezultat;
}
ostream& operator<<(ostream& tekst, const cUlamekZwykly Ulamek)
{
tekst<<Ulamek.m_Calosci<<" "<<Ulamek.m_Licznik<<"/"<<Ulamek.m_Mianownik;
return tekst;
}
| true |
91585a3904e935b320de4d57f8e7726b706b1617 | C++ | eXceediDeaL/OI | /Problems/POJ/模拟/1002.cpp | UTF-8 | 900 | 3 | 3 | [] | no_license | /*
487-3279
题意:给你一些由大写字母、数字、和'-'组成的字符串,并给出大写字母各自对应的数字。求出转换为数字后重复的次数。
分析:模拟,注意转数字
*/
#include<iostream>
#include<cstdio>
#include<cstring>
#include<set>
#include<map>
#include<cctype>
using namespace std;
int num[]={2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,0,7,7,8,8,8,9,9,9};
map<int, int> s;
char buf[128];
int main(){
int t;
scanf("%d", &t);
bool flag=false;
for(int i=0;i<t;i++){
scanf("%s",buf);
int c=0;
for(int j=0;buf[j];j++){
if(isdigit(buf[j]))c=c*10+buf[j]-'0';
else if(isalpha(buf[j]))c=c*10+num[buf[j]-'A'];
}
s[c]++;
}
for(map<int,int>::iterator it=s.begin();it!=s.end();it++)
if(it->second>1){
flag=true;
printf("%03d-%04d %d\n", it->first/10000, it->first%10000,it->second);
}
if(!flag)puts("No duplicates.");
return 0;
}
| true |
8782eebdd8b8a8389746a611da4db991294c77f9 | C++ | 3ICE/Programming-2017 | /weekly-assignment-02/main.cpp | UTF-8 | 1,424 | 3.609375 | 4 | [] | no_license | #include <iostream>
#include <iomanip>
using namespace std;
class Clock {
public:
Clock(int hour, int minute);
void print() const;
int difference(Clock o);
private:
int hours_;
int minutes_;
};
int main() {
int min, hour;
cout<<"Please type in an hour: ";
cin>>hour;
cout<<"Please type in a minute: ";
cin>>min;
Clock one(hour, min);
cout<<"You entered: "; one.print();
cout<<endl<<"Please type in another hour: ";
cin>>hour;
cout<<"Please type in another minute: ";
cin>>min;
Clock two(hour, min);
cout<<"You entered: "; two.print();
cout<<endl<<"Difference will be calculated between: "<<endl;
one.print(); cout<<" and "; two.print();
cout<<endl<<"Calculating..."<<endl;
cout<<endl<<"And the results are in:"<<endl<<endl;
cout << one.difference(two) << endl<< endl;
//Clock.difference(one,two);
}
Clock::Clock(int hour, int minute):
hours_(hour), minutes_(minute) {
}
int Clock::difference(Clock o) {
//3ICE: 23.55 - 00.05 -> 10 makes no sense :(
//3ICE: I'd much rather take the absolute value
//3ICE: of their difference! Oh well...
int x=hours_*60+minutes_ - o.hours_*60-o.minutes_;
if(x<0){return -x;}else{return 1440-x;}
}
void Clock::print() const {
cout << setw(2) << setfill('0') << hours_<< ":"<< setw(2) << minutes_;
}
| true |
80dfb4688a9811899b8f70aa16c443a94e2ddc68 | C++ | ccdxc/logSurvey | /data/crawl/git/new_hunk_2025.cpp | UTF-8 | 157 | 2.6875 | 3 | [] | no_license | static int write_buffer(int fd, const void *buf, size_t len)
{
if (write_in_full(fd, buf, len) < 0)
return error_errno("file write error");
return 0;
}
| true |
d1e12acf7288b4b9161d780db4e152a4cc01f25c | C++ | nikitablack/animation | /Headers/MeshAsciiParser.h | UTF-8 | 13,735 | 2.734375 | 3 | [] | no_license | #pragma once
#include <string>
#include <regex>
#include <fstream>
#include <DirectXMath.h>
#include <vector>
#include <cassert>
using namespace std;
using namespace DirectX;
namespace detail
{
char* memblock{ new char[4] };
}
using namespace detail;
struct Bone
{
int32_t parent;
string name;
XMFLOAT3 pos;
};
struct Vertex
{
XMFLOAT3 pos;
XMFLOAT3 normal;
XMINT4 color;
XMFLOAT2 uv;
XMINT3 bones;
XMFLOAT3 bonesWeights;
};
ostream& operator<<(ostream& os, Bone& bone)
{
os.write(reinterpret_cast<char*>(&bone.parent), sizeof(int32_t));
uint32_t numChars{ static_cast<uint32_t>(bone.name.size()) };
os.write(reinterpret_cast<char*>(&numChars), sizeof(uint32_t));
os.write(bone.name.data(), sizeof(char) * numChars);
os.write(reinterpret_cast<char*>(&bone.pos.x), sizeof(float));
os.write(reinterpret_cast<char*>(&bone.pos.y), sizeof(float));
os.write(reinterpret_cast<char*>(&bone.pos.z), sizeof(float));
return os;
}
ostream& operator<<(ostream& os, Vertex& vertex)
{
os.write(reinterpret_cast<char*>(&vertex.pos.x), sizeof(float));
os.write(reinterpret_cast<char*>(&vertex.pos.y), sizeof(float));
os.write(reinterpret_cast<char*>(&vertex.pos.z), sizeof(float));
os.write(reinterpret_cast<char*>(&vertex.normal.x), sizeof(float));
os.write(reinterpret_cast<char*>(&vertex.normal.y), sizeof(float));
os.write(reinterpret_cast<char*>(&vertex.normal.z), sizeof(float));
os.write(reinterpret_cast<char*>(&vertex.color.x), sizeof(int32_t));
os.write(reinterpret_cast<char*>(&vertex.color.y), sizeof(int32_t));
os.write(reinterpret_cast<char*>(&vertex.color.z), sizeof(int32_t));
os.write(reinterpret_cast<char*>(&vertex.color.w), sizeof(int32_t));
os.write(reinterpret_cast<char*>(&vertex.uv.x), sizeof(float));
os.write(reinterpret_cast<char*>(&vertex.uv.y), sizeof(float));
os.write(reinterpret_cast<char*>(&vertex.bones.x), sizeof(int32_t));
os.write(reinterpret_cast<char*>(&vertex.bones.y), sizeof(int32_t));
os.write(reinterpret_cast<char*>(&vertex.bones.z), sizeof(int32_t));
os.write(reinterpret_cast<char*>(&vertex.bonesWeights.x), sizeof(float));
os.write(reinterpret_cast<char*>(&vertex.bonesWeights.y), sizeof(float));
os.write(reinterpret_cast<char*>(&vertex.bonesWeights.z), sizeof(float));
return os;
}
istream& operator >> (istream& is, Bone& bone)
{
is.read(memblock, sizeof(int32_t));
bone.parent = *(reinterpret_cast<int32_t*>(memblock));
is.read(memblock, sizeof(uint32_t));
uint32_t numChars{ *(reinterpret_cast<uint32_t*>(memblock)) };
char* strBlock{ new char[numChars] };
is.read(strBlock, sizeof(char) * numChars);
bone.name = string{ strBlock, numChars };
delete[] strBlock;
is.read(memblock, sizeof(float));
bone.pos.x = *(reinterpret_cast<float*>(memblock));
is.read(memblock, sizeof(float));
bone.pos.y = *(reinterpret_cast<float*>(memblock));
is.read(memblock, sizeof(float));
bone.pos.z = *(reinterpret_cast<float*>(memblock));
return is;
}
istream& operator>>(istream& is, Vertex& vertex)
{
// pos
is.read(memblock, sizeof(float));
vertex.pos.x = *(reinterpret_cast<float*>(memblock));
is.read(memblock, sizeof(float));
vertex.pos.y = *(reinterpret_cast<float*>(memblock));
is.read(memblock, sizeof(float));
vertex.pos.z = *(reinterpret_cast<float*>(memblock));
// normal
is.read(memblock, sizeof(float));
vertex.normal.x = *(reinterpret_cast<float*>(memblock));
is.read(memblock, sizeof(float));
vertex.normal.y = *(reinterpret_cast<float*>(memblock));
is.read(memblock, sizeof(float));
vertex.normal.z = *(reinterpret_cast<float*>(memblock));
// color
is.read(memblock, sizeof(int32_t));
vertex.color.x = *(reinterpret_cast<int32_t*>(memblock));
is.read(memblock, sizeof(int32_t));
vertex.color.y = *(reinterpret_cast<int32_t*>(memblock));
is.read(memblock, sizeof(int32_t));
vertex.color.z = *(reinterpret_cast<int32_t*>(memblock));
is.read(memblock, sizeof(int32_t));
vertex.color.w = *(reinterpret_cast<int32_t*>(memblock));
// uv
is.read(memblock, sizeof(float));
vertex.uv.x = *(reinterpret_cast<float*>(memblock));
is.read(memblock, sizeof(float));
vertex.uv.y = *(reinterpret_cast<float*>(memblock));
// bones
is.read(memblock, sizeof(int32_t));
vertex.bones.x = *(reinterpret_cast<int32_t*>(memblock));
is.read(memblock, sizeof(int32_t));
vertex.bones.y = *(reinterpret_cast<int32_t*>(memblock));
is.read(memblock, sizeof(int32_t));
vertex.bones.z = *(reinterpret_cast<int32_t*>(memblock));
// bones weights
is.read(memblock, sizeof(float));
vertex.bonesWeights.x = *(reinterpret_cast<float*>(memblock));
is.read(memblock, sizeof(float));
vertex.bonesWeights.y = *(reinterpret_cast<float*>(memblock));
is.read(memblock, sizeof(float));
vertex.bonesWeights.z = *(reinterpret_cast<float*>(memblock));
return is;
}
class MeshAsciiParser
{
private:
enum class ParseState
{
NONE,
BONES,
MESHES,
UV_LAYERS,
TEXTURES,
VERTICES
};
enum class BoneState
{
NAME,
PARENT,
POSITION
};
enum class VertexState
{
POSITION,
NORMAL,
COLOR,
UV,
BONES,
BONES_WEIGHTS
};
public:
static void parse(string filePath)
{
vector<Bone> bones;
vector<vector<Vertex>> meshes;
vector<vector<uint32_t>> faces;
ParseState currState{ ParseState::NONE };
VertexState currVertexState;
regex bonesStartPattern("(\\d+) *# *bones");
smatch bonesStartMatch;
regex meshesStartPattern("(\\d+) *# *meshes");
smatch meshesStartMatch;
regex uvLayersStartPattern("(\\d+) *# *uv *layers");
smatch uvLayersStartMatch;
regex texturesStartPattern("(\\d+) *# *textures");
smatch texturesStartMatch;
regex verticesStartPattern("(\\d+) *# *vertices");
smatch verticesStartMatch;
regex facesStartPattern("(\\d+) *# *faces");
smatch facesStartMatch;
ifstream infile(filePath);
string line;
while (getline(infile, line))
{
if (regex_search(line, bonesStartMatch, bonesStartPattern))
{
int numBones{ stoi(bonesStartMatch.str(1)) };
bones = parseBones(numBones, infile);
continue;
}
else if (regex_search(line, meshesStartMatch, meshesStartPattern))
{
int numMeshes{ stoi(meshesStartMatch.str(1)) };
currState = ParseState::MESHES;
currVertexState = VertexState::POSITION;
continue;
}
else if (regex_search(line, uvLayersStartMatch, uvLayersStartPattern))
{
int numUvLayers{ stoi(uvLayersStartMatch.str(1)) };
currState = ParseState::UV_LAYERS;
continue;
}
else if (regex_search(line, texturesStartMatch, texturesStartPattern))
{
int numTextures{ stoi(texturesStartMatch.str(1)) };
currState = ParseState::TEXTURES;
continue;
}
else if (regex_search(line, verticesStartMatch, verticesStartPattern))
{
int numVertices{ stoi(verticesStartMatch.str(1)) };
meshes.push_back(parseVertices(numVertices, infile));
continue;
}
else if (regex_search(line, facesStartMatch, facesStartPattern))
{
int numFaces{ stoi(facesStartMatch.str(1)) };
faces.push_back(parseFaces(numFaces, infile));
continue;
}
}
ofstream outfile("kitana", ios::binary | ios::out | ios::trunc);
uint32_t numBones{ static_cast<uint32_t>(bones.size()) };
outfile.write(reinterpret_cast<char*>(&numBones), sizeof(uint32_t));
for (Bone& bone : bones)
{
outfile << bone;
}
uint32_t numMeshes{ static_cast<uint32_t>(meshes.size()) };
outfile.write(reinterpret_cast<char*>(&numMeshes), sizeof(uint32_t));
for (int i{ 0 }; i < meshes.size(); ++i)
{
// write vertices
vector<Vertex> vertices{ meshes[i] };
uint32_t numVertices{ static_cast<uint32_t>(vertices.size()) };
outfile.write(reinterpret_cast<char*>(&numVertices), sizeof(uint32_t));
for (Vertex& vertex : vertices)
{
outfile << vertex;
}
// write indices
vector<uint32_t> indices{ faces[i] };
uint32_t numIndices{ static_cast<uint32_t>(indices.size()) };
outfile.write(reinterpret_cast<char*>(&numIndices), sizeof(uint32_t));
for (uint32_t ind : indices)
{
outfile.write(reinterpret_cast<char*>(&ind), sizeof(uint32_t));
}
}
}
static void read(const string& filePath, vector<Bone>& bones, vector<vector<Vertex>>& meshes, vector<vector<uint32_t>>& faces)
{
ifstream infile(filePath, ios::binary | ios::in);
infile.read(memblock, sizeof(uint32_t));
uint32_t numBones{ *(reinterpret_cast<uint32_t*>(memblock)) };
for (uint32_t i{ 0 }; i < numBones; ++i)
{
Bone bone;
infile >> bone;
bones.push_back(bone);
}
infile.read(memblock, sizeof(uint32_t));
uint32_t numMeshes{ *(reinterpret_cast<uint32_t*>(memblock)) };
for (uint32_t i{ 0 }; i < numMeshes; ++i)
{
// meshes
vector<Vertex> vertices;
infile.read(memblock, sizeof(uint32_t));
uint32_t numVertices{ *(reinterpret_cast<uint32_t*>(memblock)) };
for (uint32_t j{ 0 }; j < numVertices; ++j)
{
Vertex vertex;
infile >> vertex;
vertices.push_back(vertex);
}
meshes.push_back(vertices);
// faces
vector<uint32_t> indicies;
infile.read(memblock, sizeof(uint32_t));
uint32_t numIndices{ *(reinterpret_cast<uint32_t*>(memblock)) };
for (uint32_t j{ 0 }; j < numIndices; ++j)
{
infile.read(memblock, sizeof(uint32_t));
uint32_t ind{ *(reinterpret_cast<uint32_t*>(memblock)) };
indicies.push_back(ind);
}
faces.push_back(indicies);
}
}
private:
static vector<uint32_t> parseFaces(int num, ifstream& infile)
{
num *= 3;
vector<uint32_t> data;
regex threeIntsPattern("(\\d+) +(\\d+) +(\\d+)");
smatch threeIntsMatch;
string line;
while (getline(infile, line))
{
regex_search(line, threeIntsMatch, threeIntsPattern);
assert(threeIntsMatch.size() == 4);
data.push_back(static_cast<uint32_t>(stoi(threeIntsMatch.str(1))));
data.push_back(static_cast<uint32_t>(stoi(threeIntsMatch.str(2))));
data.push_back(static_cast<uint32_t>(stoi(threeIntsMatch.str(3))));
if (data.size() == num)
{
break;
}
}
assert(num == data.size());
return data;
}
static vector<Vertex> parseVertices(int num, ifstream& infile)
{
vector<Vertex> data;
regex threeFloatsPattern("(.*) +(.*) +(.*)");
smatch threeFloatsMatch;
regex fourIntsPattern("(\\d+) +(\\d+) +(\\d+) +(\\d+)");
smatch fourIntsMatch;
regex twoFloatsPattern("(.*) +(.*)");
smatch twoFloatsMatch;
regex threeIntsPattern("(\\d+) +(\\d+) +(\\d+)");
smatch threeIntsMatch;
VertexState currState{ VertexState::POSITION };
string line;
while (getline(infile, line))
{
if (currState == VertexState::POSITION)
{
regex_search(line, threeFloatsMatch, threeFloatsPattern);
assert(threeFloatsMatch.size() == 4);
Vertex vertex;
vertex.pos = { stof(threeFloatsMatch.str(1)), stof(threeFloatsMatch.str(2)), stof(threeFloatsMatch.str(3)) };
data.push_back(vertex);
currState = VertexState::NORMAL;
}
else if (currState == VertexState::NORMAL)
{
regex_search(line, threeFloatsMatch, threeFloatsPattern);
assert(threeFloatsMatch.size() == 4);
Vertex& vertex{ data[data.size() - 1] };
vertex.normal = { stof(threeFloatsMatch.str(1)), stof(threeFloatsMatch.str(2)), stof(threeFloatsMatch.str(3)) };
currState = VertexState::COLOR;
}
else if (currState == VertexState::COLOR)
{
regex_search(line, fourIntsMatch, fourIntsPattern);
assert(fourIntsMatch.size() == 5);
Vertex& vertex{ data[data.size() - 1] };
vertex.color = { stoi(fourIntsMatch.str(1)), stoi(fourIntsMatch.str(2)), stoi(fourIntsMatch.str(3)), stoi(fourIntsMatch.str(4)) };
currState = VertexState::UV;
}
else if (currState == VertexState::UV)
{
regex_search(line, twoFloatsMatch, twoFloatsPattern);
assert(twoFloatsMatch.size() == 3);
Vertex& vertex{ data[data.size() - 1] };
vertex.uv = { stof(twoFloatsMatch.str(1)), stof(twoFloatsMatch.str(2)) };
currState = VertexState::BONES;
}
else if (currState == VertexState::BONES)
{
regex_search(line, threeIntsMatch, threeIntsPattern);
assert(threeIntsMatch.size() == 4);
Vertex& vertex{ data[data.size() - 1] };
vertex.bones = { stoi(threeIntsMatch.str(1)), stoi(threeIntsMatch.str(2)), stoi(threeIntsMatch.str(3)) };
currState = VertexState::BONES_WEIGHTS;
}
else if (currState == VertexState::BONES_WEIGHTS)
{
regex_search(line, threeFloatsMatch, threeFloatsPattern);
assert(threeFloatsMatch.size() == 4);
Vertex& vertex{ data[data.size() - 1] };
vertex.bonesWeights = { stof(threeFloatsMatch.str(1)), stof(threeFloatsMatch.str(2)), stof(threeFloatsMatch.str(3)) };
currState = VertexState::POSITION;
if (data.size() == num)
{
break;
}
}
}
assert(num == data.size());
return data;
}
static vector<Bone> parseBones(int num, ifstream& infile)
{
vector<Bone> data;
regex threeFloatsPattern("(.*) +(.*) +(.*)");
smatch threeFloatsMatch;
BoneState currState{ BoneState::NAME };
string line;
while (getline(infile, line))
{
if (currState == BoneState::NAME)
{
Bone bone;
bone.name = line;
data.push_back(bone);
currState = BoneState::PARENT;
}
else if (currState == BoneState::PARENT)
{
Bone& bone{ data[data.size() - 1] };
bone.parent = stoi(line);
currState = BoneState::POSITION;
}
else if (currState == BoneState::POSITION)
{
regex_search(line, threeFloatsMatch, threeFloatsPattern);
assert(threeFloatsMatch.size() == 4);
Bone& bone{ data[data.size() - 1] };
bone.pos = { stof(threeFloatsMatch.str(1)), stof(threeFloatsMatch.str(2)), stof(threeFloatsMatch.str(3)) };
currState = BoneState::NAME;
if (data.size() == num)
{
break;
}
}
}
assert(num == data.size());
return data;
}
}; | true |
76582b164425b9476dc64d58db0cb17d2b5fa5ed | C++ | thar/Klondike | /models/Game.cpp | UTF-8 | 607 | 2.546875 | 3 | [] | no_license | #include "Game.h"
#include "KlondikeCommandShopBuilder.h"
Game::Game(GameDeck gameDeck)
: gameBoard_(gameDeck.getSuitsNames(), gameDeck.getPile()), score_(0),
gameCommandShop_(KlondikeCommandShopBuilder::createCommandShop(gameBoard_, score_))
{
}
std::shared_ptr<KlondikeCommand> Game::getCommand(unsigned int index)
{
assert(index < gameCommandShop_.size());
return gameCommandShop_.getCommand(index);
}
bool Game::isFinished()
{
return gameBoard_.isGameFinished();
}
std::ostream& operator<<(std::ostream& os, const Game& obj)
{
os << obj.gameBoard_;
return os;
} | true |
d2e2c594b6ec78dde39809012f2de1d5d1483010 | C++ | amoghkashyap/STL_cplusplus | /STLMay/algorithms/algorithm_8.cpp | UTF-8 | 1,763 | 3.046875 | 3 | [] | no_license | //============================================================================
// Name : STLMay.cpp
// Author :
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include<vector>
#include<iostream>
#include<fstream>
#include<algorithm>
#include<iterator>
#include<set>
#include<sstream>
using namespace std;
//#define MYMAIN
#ifdef MYMAIN
class Resource {
public:
string m_resourceName;
set<string> m_permissionRequired;
Resource(const string& resrId, const string& resourcePermissions) {
m_resourceName = resrId;
istringstream iss(resourcePermissions);
copy(istream_iterator<string>(iss), istream_iterator<string>(),
inserter(m_permissionRequired, m_permissionRequired.begin()));
}
};
class User {
public:
string m_userName;
set<string> m_hasPermissions;
User(const string& user, const string& userPermissions) {
m_userName = user;
istringstream iss(userPermissions);
copy(istream_iterator<string>(iss), istream_iterator<string>(),
inserter(m_hasPermissions, m_hasPermissions.begin()));
}
bool hasPermissionOn(const Resource& resrc) {
vector<string> inters;
set_intersection(m_hasPermissions.begin(), m_hasPermissions.end(),
resrc.m_permissionRequired.begin(),
resrc.m_permissionRequired.end(), back_inserter(inters));
return !(inters.empty());
}
};
int main() {
Resource mgwResource("MGW-1", "permMGWUser permFaultMgmt permSuperUser");
Resource imsResource("IMS-1", "permMGWUser permFaultMgmt permSuperUser");
User loggedUser("mgw-user", "permMGWUser permFaultMgmt permSecurityMgmt");
cout << loggedUser.hasPermissionOn(mgwResource);
return 0;
}
#endif
| true |
90852c54745825598fd1d5ad5a68a6cbf06eeb7c | C++ | SimoV8/Jobs-Scheduler | /src/Resource.h | UTF-8 | 907 | 2.640625 | 3 | [] | no_license | //
// Created by Simone on 22/02/2016.
//
#ifndef JOBSSCHEDULER_RESOURCE_H
#define JOBSSCHEDULER_RESOURCE_H
#include <unordered_map>
using namespace std;
class Resource {
private:
int availability;
unordered_map<int, int> usedResources;
public:
Resource(int availability);
int findStartTimeAvailableResource(int readyTime, int processingTime, int requiredResources);
bool useResources(int start, int processingTime, int quantity);
void releaseResources(int start, int processingTime, int quantity);
bool isAvailable(int t, int quantity);
int getAvailabilityAtTime(int t);
void reset();
};
class ResourceRequest {
private:
int resourceId;
int quantity;
public:
ResourceRequest(int r, int q): resourceId(r), quantity(q) {}
int getResourceId() { return resourceId; }
int getQuantity() { return quantity; }
};
#endif //JOBSSCHEDULER_RESOURCE_H
| true |
02ee6c53cd3ce5395d387eaf532d51f706835279 | C++ | wwildey/voxel | /src/game/Item.h | UTF-8 | 555 | 2.796875 | 3 | [] | no_license | /**
* Voxel Engine
*
* (c) Joshua Farr <j.wgasa@gmail.com>
*
*/
#pragma once
/**
* A game item
*/
class Item
{
public:
typedef enum
{
WEARABLE_TYPE_FEET,
WEARABLE_TYPE_LEGS,
WEARABLE_TYPE_HEAD,
WEARABLE_TYPE_CHEST
} WearableType;
typedef enum
{
ITEM_TYPE_ORE,
ITEM_TYPE_PLANT,
ITEM_TYPE_FOOD,
ITEM_TYPE_WEAPON,
ITEM_TYPE_TOOL,
ITEM_TYPE_WEARABLE,
ITEM_TYPE_UTILITY
} ItemType;
Item();
bool equipped() const;
void equip();
bool equipable() const;
bool wearable() const;
private:
bool equipped_;
};
| true |
1c731f9f44a4c70df056921e3b039e3884d6ecc5 | C++ | CristianERAU/PSP | /ethernetswitch.hpp | UTF-8 | 1,613 | 2.625 | 3 | [] | no_license | ///////////////////////////////
// CS225 Spring 2016 //////////
// Cristian Garcia ////////////
///////////////////////////////
///////////////////////////////
#ifndef ETHERNETSWITCH_HPP_
#define ETHERNETSWITCH_HPP_
// Include Directives /////////
#include <iostream>
#include <string>
#include "packetswitch.hpp"
using std::ostream;
// Decleration Section: //////////////////////////////////////////////////////////////
class EthernetSwitch:public PacketSwitch
{
private:
// Data Hiding //////////////////////////////////////////////////////////////////
static int num_alive;
int packet_size;
int rating;
public:
// Constructor //////////////////////////////////////////////////////////////////
EthernetSwitch();
/////////////////////////////////////////////////////////////////////////////////
EthernetSwitch(int, int);
// Destructor ///////////////////////////////////////////////////////////////////
~EthernetSwitch();
// Mutators ////////////////////////////////////////////
int set_packet_size(int);
int set_rating(int);
double compute_packetspersec();
int set_blank();
// Accessors ///////////////////////////////////////////
static int get_num_alive();
int get_packet_size()const{return packet_size;}//;
int get_rating()const{return rating;}//;
// Helpers //////////////////////////////////////////////////////////////////////
int isempty();
int display_mem_usage();
int toCout() const;
friend ostream& operator<< (ostream &output, const EthernetSwitch& Es);
};
#endif | true |
e88a2a62e4eac972c60907484d63797a6de04bd0 | C++ | epitacioneto/UFPB | /LP1/roteiro6/questao1/Relogio.cpp | UTF-8 | 1,282 | 2.90625 | 3 | [] | no_license | //
// Created by epitacio on 19/09/17.
//
#include "Relogio.h"
Relogio::Relogio() {
}
Relogio::~Relogio() {
}
void Relogio::setHorario(int hora, int minuto, int segundo) {
this->hora = hora;
this->minuto = minuto;
this->segundo = segundo;
}
int Relogio::getHora() {
return hora;
}
int Relogio::getMinuto() {
return minuto;
}
int Relogio::getSegundo() {
return segundo;
}
void Relogio::avancarHorario(int hora, int minuto, int segundo) {
bool horarioCorreto;
horarioCorreto = checaHorario(hora, minuto, segundo+1);
if(horarioCorreto) {
segundo += 1;
this->segundo = segundo;
}else {
while (1) {
if (minuto >= 60) {
hora += 1;
minuto -= 60;
this->hora = hora;
this->minuto = minuto;
continue;
}
if (segundo >= 60) {
minuto += 1;
segundo -= 60;
this->minuto = minuto;
this->segundo = segundo;
continue;
}
break;
}
}
}
bool Relogio::checaHorario(int hora, int minuto, int segundo) {
if(hora > 24 || minuto >= 60 || segundo >= 60) {
return false;
}
return true;
} | true |
b524b6341faea69a1ce619b758e425bbeb893d14 | C++ | parinphatw/CPlusPlus | /Grader/ds01_most/ds01_most/main.cpp | UTF-8 | 650 | 2.921875 | 3 | [] | no_license | //
// main.cpp
// ds01_most
//
// Created by Ryu Lunoz on 29/8/2562 BE.
// Copyright © 2562 Ryu Lunoz. All rights reserved.
//
#include <iostream>
#include <map>
using namespace std;
int main() {
// insert code here...
int num;
cin >> num;
map<string, int> container;
for (int i = 0; i < num; i++) {
string s;
cin >> s;
container[s]++;
}
string mostName;
int max = 0;
for (auto it = container.begin(); it != container.end(); it++) {
if (it->second >= max) {
mostName = it->first;
max = it->second;
}
}
cout << mostName << " " << max;
}
| true |
a73d99ad8f5545d2350c9792e557c2646e97026b | C++ | feiqiu/repository-of-projects | /Win32/typename/main.cpp | UTF-8 | 1,150 | 2.640625 | 3 | [] | no_license |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <crtdbg.h>
inline void EnableMemLeakCheck()
{
_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
}
template<typename T>
class Typename{
public:
static const char* get(){ return T::getTypeName(); }
};
typedef int s32;
// add more specialisations for the build-in types
template<> const char* Typename<s32>::get() { static const char* p="int"; return p; }
template<> const char* Typename<s32*>::get() { static const char* p="int*"; return p; }
template<typename T>
class Test{
T t;
public:
static const char* getTypeName(){
static std::string p=std::string("Test<")+Typename<T>::get()+">";
return p.c_str();
}
};
class Object{
public:
static const char* getTypeName(){
static const char* p="Object";
return p;
}
};
int main(int argc, char* argv[])
{
EnableMemLeakCheck();
Test<int> i;
printf("%s\r\n",i.getTypeName());
Test<int*> ip;
printf("%s\r\n",ip.getTypeName());
Test<Object> o;
printf("%s\r\n",o.getTypeName());
system("pause");
return 0;
} | true |
2b38f513890d2fd625ae3024b3b73f59735cfed8 | C++ | picasso250/leetcode | /4.Median of Two Sorted Arrays.cpp | UTF-8 | 684 | 3.25 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <array>
#include <string>
using namespace std;
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
long s=0;
int c=0;
for (int i : nums1) {
s += i;
c++;
}
for (int i : nums2) {
s += i;
c++;
}
return s * 1.0 / c;
}
};
int main(int argc, char const *argv[])
{
Solution s;
vector<int> nums1={};
vector<int> nums2={2,3};
cout<<s.findMedianSortedArrays(nums1,nums2)<<endl;
vector<int> nums1_={4,5,6,8,9};
vector<int> nums2_={};
cout<<s.findMedianSortedArrays(nums1_,nums2_)<<endl;
return 0;
}
| true |
0d66fb8942fc988494918c630076ee6af835639a | C++ | BamdaXP/SimpleRaytracing | /SimpleRaytracing/src/Random.hpp | UTF-8 | 384 | 2.71875 | 3 | [] | no_license | #pragma once
#include <random>
class Random
{
public:
static float FRandom();
static float FRandom(float a, float b);
static int IRandom();
static int IRandom(int a,int b);
static void SetSeed(uint32_t seed);
private:
static std::default_random_engine s_Engine;
static std::uniform_int_distribution<int> s_IntDist;
static std::uniform_real_distribution<float> s_FloatDist;
}; | true |
2328be1f257f17b029bf3e09683c2542bd3b5f79 | C++ | hongwei7/LeetcodePractice | /129.求根到叶子节点数字之和.cpp | UTF-8 | 993 | 3 | 3 | [] | no_license | // @before-stub-for-debug-begin
#include <vector>
#include <string>
#include "commoncppproblem129.h"
using namespace std;
// @before-stub-for-debug-end
/*
* @lc app=leetcode.cn id=129 lang=cpp
*
* [129] 求根到叶子节点数字之和
*/
// @lc code=start
/**
* 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 {
public:
void traverse(TreeNode* root, int& sum, int& q){
if(root == nullptr){
return;
}
q = 10 * q + root->val;
if (root->left == nullptr && root->right == nullptr)
{
sum += q;
}
traverse(root->left, sum, q);
traverse(root->right, sum, q);
q = (q - root->val) / 10;
}
int sumNumbers(TreeNode* root) {
int sum = 0, q = 0;
traverse(root, sum, q);
return sum;
}
};
// @lc code=end
| true |
f2c41058db6c679af36426865172e067f77928b9 | C++ | himchawla/networkingSide | /spaceInvaders/level.cpp | UTF-8 | 2,521 | 2.640625 | 3 | [] | no_license | //
// Bachelor of Software Engineering
// Media Design School
// Auckland
// New Zealand
//
// (c) 2019 Media Design School
//
// File Name : level.cpp
// Description : Implemntation for level class
// Author : Himanshu Chawla
// Mail : Himanshu.Cha8420@mediadesign.mail.nz
//
// Implementation
#include "level.h"
level::level(int platNum, int checkNum)
{
checks = new platform[checkNum];
plats = new platform[platNum];
chec = checkNum;
plat = platNum;
spawnPoints = sf::Vector2f(0, 0);
}
void level::placePlats(int ch)
{
if (ch == 1)
{
spawnPoints = sf::Vector2f(400.0f, 800.0f);
for (int i = 0; i < 4; i++)
{
plats[i].setTexture("Assets/Grass block.png");
plats[i].sp.setScale(10, 1);
plats[i].x = 700 * i + 150;
plats[i].y = 900 - i * 200;
plats[i].sp.setPosition(plats[i].x, plats[i].y);
}
plats[4].setLocation(700 * 3 + 450, 900 - 3 * 200);
plats[4].setTexture("Assets/Grass block.png");
plats[4].sp.setScale(10, 1);
portal.setTexture("Assets/portal.png");
portal.setLocation(720, 200);
for (int i = 5; i < plat; i++)
{
plats[i].setTexture("Assets/Grass block.png");
plats[i].sp.setScale(10, 1);
plats[i].x = 1700 - i * 150;
plats[i].y = 900 - 3 * 200;
plats[i].sp.setPosition(plats[i].x, plats[i].y);
}
plats[0].sp.setScale(20, 1);
checks[0].setLocation(plats[3].sp.getPosition().x + 320, plats[3].sp.getPosition().y - 64);
checks[0].setTexture("Assets/trigger.png");
spawnPoints.x = 950;
spawnPoints.y = 500;
}
if (ch == 2)
{
trigger.setTexture("Assets/trigger.png");
for (int i = 0; i < plat; i++)
{
plats[i].setTexture("Assets/Grass block.png");
plats[i].sp.setScale(10, 1);
}
spawnPoints.x = 750;
spawnPoints.y = 600;
plats[0].sp.setScale(20, 1);
plats[0].setLocation(10, 900);
plats[1].sp.setScale(10, 1);
plats[1].setLocation(1500, 20);
plats[1].sp.setOrigin(35, 0.5);
trigger.setLocation(1250, 837);
portal.setTexture("Assets/portal.png");
portal.setLocation(1900, 500);
plats[1].sp.setOrigin(0.5, 0.5);
}
if (ch == 3)
{
portal.setLocation(2200, 400);
trigger.setTexture("Assets/leverStraight.png");
for (int i = 0; i < plat; i++)
{
plats[i].setTexture("Assets/Grass block.png");
plats[i].sp.setScale(10, 1);
}
plats[0].sp.setScale(10, 1);
plats[0].setLocation(100, 700);
plats[1].sp.setScale(15, 1);
plats[1].setLocation(650, 600);
trigger.setLocation(1000, 500);
trigger.sp.setScale(4, 4);
spawnPoints.x = 550;
spawnPoints.y = 250;
}
} | true |
cc74e8bce2a8ff579b052686bb9b62e75aa74568 | C++ | MasonSu/leetcode | /swordCode/05_PrintListFromTailToHead.cpp | UTF-8 | 1,064 | 3.890625 | 4 | [] | no_license | /**
*
* 输入一个链表,从尾到头打印链表每个节点的值。
*
*/
#include <iostream>
#include <vector>
#include <stack>
using std::vector;
using std::stack;
struct ListNode {
int val;
ListNode *next;
ListNode(int x): val(x), next(nullptr) {}
};
/* 如果不能修改输入的话,就不能翻转链表 */
/*class Solution {
public:
vector<int> printListFromTailToHead(ListNode *head) {
if (head == nullptr)
return {};
stack<int> node;
while(head) {
node.push(head->val);
head = head->next;
}
vector<int> result;
while (!node.empty()) {
result.push_back(node.top());
node.pop();
}
return result;
}
};*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode *head) {
vector<int> result;
printFromTailToHead(head, result);
return result;
}
private:
void printFromTailToHead(ListNode *head, vector<int>& result) {
if (head == NULL)
return;
printFromTailToHead(head->next, result);
result.push_back(head->val);
}
}; | true |
9ee55a8467cff3dcf49c01f6320f0184dd705bca | C++ | maurime2/Buckey-C-Tutorials | /C++/Buckey Tutorials/45. Buckey - Member Initializers/Sally.cpp | UTF-8 | 427 | 2.890625 | 3 | [] | no_license | /*
* File: Sally.cpp
* Author: Dell
*
* Created on August 31, 2015, 9:04 AM
*/
#include "Sally.h"
#include <iostream>
using namespace std;
Sally::Sally(int a, int b)
: regVar(a), //List for Member Initializers
constVar(b) //For Constant Variables.
{
}
void Sally::print(){
cout<<"Regular var is: "<<regVar<<", const variable is: "<<constVar<<endl;
}
Sally::~Sally() {
}
| true |
91b300280c67fb30841ed842b813f200110f946f | C++ | zmdyemwp/w10 | /legecy_tools/BitFontCreatorX/BitFontCreatorX/BoldNumFont/backup/BoldNumUtil.cpp | UTF-8 | 2,010 | 2.828125 | 3 | [] | no_license |
#include <stdio.h>
#include <string.h>
#include <math.h>
#include "BoldNumTable.h"
const static int space_width = 6;
/*
letter set: 0x21 - 0x3f (from "!" to "?")
For the bold numbers with height 10: set the value of parameter "size": 0
For the bold numbers with height 17: set the value of parameter "size": 1
For the bold numbers with height 34: set the value of parameter "size": 2
For the bold numbers with height 08: set the value of parameter "size": 3
*/
extern void dmsg(TCHAR,DWORD=1);
int GetBoldNumIndex(char c, int size) {
int result = 0;
if(0x20 > c || 0x40 < c) {
result = -2;
}
else if(0x20 == c) {
result = -1;
}
else {
result = c - 0x21;
}
if(0 > size || 3 < size) {
size = 0;
}
result += (0x3f - 0x20) * size;
return result;
}
int GDI_GetBoldNumWidth(char * str, int size) {
int index = 0;
int result = 0;
size_t i = 0;
for(i = 0; i < strlen(str); i++) {
index = GetBoldNumIndex(str[i], size);
if(-1 == index) {
result += space_width;
}
if(0 <= index) {
result += bold_num_font_width_table[index];
}
else {
continue;
}
}
return result;
}
extern void GDI_PaintBuffer(int, int, int, int, unsigned char *, bool);
void GDI_PaintBoldNum(int x, int y, char * str, int alignment, int highlight, int fontsize) {
int wsum = GDI_GetBoldNumWidth(str, fontsize);
int X = 0;
int Y = y;
size_t i = 0;
int height = 0;
int index = 0;
if(0 > alignment) {
X = x;
}
else if(0 == alignment) {
X = x - wsum/2;
}
else {
X = x - wsum;
}
for(i = 0; i < strlen(str); i++) {
index = GetBoldNumIndex(str[i], fontsize);
if(-1 == index) {
X += space_width;
continue;
}
else if(0 > index) {
continue;
}
else {
wsum = bold_num_font_width_table[index];
}
height = (int)((bold_num_font_offset_table[index+1] - bold_num_font_offset_table[index])/ceil((double)wsum/8));
GDI_PaintBuffer(X, Y, wsum, height, (unsigned char *)bold_num_font_data_table + bold_num_font_offset_table[index], highlight);
X += wsum;
}
}
| true |
0863379253d67907e7c6fc3d6524fe134b2a474d | C++ | LauraDiosan-CS/lab8-11-polimorfism-JacquelineK01 | /Lab08-10-live+tema/Lab08/RepositoryFileTxt.cpp | UTF-8 | 2,854 | 2.515625 | 3 | [] | no_license | #include "RepositoryFileTxt.h"
/*
RepositoryFileTxt::RepositoryFileTxt()
{
strcpy(this->airplaneTripsFileName, " ");
strcpy(this->busTripsFileName, " ");
strcpy(this->writeFileName, " ");
this->textOrCSV = 0;
}
RepositoryFileTxt::~RepositoryFileTxt()
{
}
void RepositoryFileTxt::loadBusTripsFromFile()
{
this->calatoriiAutobuz = {};
CalatorieAutobuz calatorie;
int cod;
char localitate_plecare[100];
char localitate_destinatie[100];
char data_plecarii[100];
int nr_loc_totale;
int nr_loc_rezervate;
int nr_zile;
std::ifstream fin(busTripsFileName);
while (!fin.eof()) {
fin >> cod >> localitate_plecare >> localitate_destinatie >> data_plecarii >> nr_zile >> nr_loc_totale >> nr_loc_rezervate;
calatorie = CalatorieAutobuz{ cod, localitate_plecare, localitate_destinatie, data_plecarii, nr_zile, nr_loc_totale, nr_loc_rezervate };
calatoriiAutobuz.push_back(calatorie);
}
fin.close();
}
void RepositoryFileTxt::loadAirplaneTripsFromFile()
{
this->calatoriiAvion = {};
CalatorieAvion calatorie;
int cod;
char localitate_plecare[100];
char localitate_destinatie[100];
char data_plecarii[100];
int nr_loc_totale;
int nr_loc_rezervate;
bool escala;
std::ifstream fin(airplaneTripsFileName);
while (!fin.eof()) {
fin >> cod >> localitate_plecare >> localitate_destinatie >> data_plecarii >> escala >> nr_loc_totale >> nr_loc_rezervate;
calatorie = CalatorieAvion{ cod, localitate_plecare, localitate_destinatie, data_plecarii, escala, nr_loc_totale, nr_loc_rezervate };
calatoriiAvion.push_back(calatorie);
}
fin.close();
}
void RepositoryFileTxt::writeTripsToFile(std::vector<CalatorieAutobuz> calatoriiAutobuz, std::vector<CalatorieAvion> calatoriiAvion)
{
std::ofstream fout(writeFileName);
for (int i = 0; i < calatoriiAutobuz.size(); ++i)
fout << "Cod: " << calatoriiAutobuz[i].getCod() << " Plecare: " << calatoriiAutobuz[i].getLocalitatePlecare() << " Destinatie: " << calatoriiAutobuz[i].getLocalitateDestinatie() << " Data: " << calatoriiAutobuz[i].getDataPlecarii() << " Durata(zile): " << calatoriiAutobuz[i].getNrZileDurata() << " Nr.Locuri Totale:" << calatoriiAutobuz[i].getNrLocTotale() << " Nr.Locuri Rezervate: " << calatoriiAutobuz[i].getNrLocRezervate() << '\n';
for (int i = 0; i < calatoriiAvion.size(); ++i)
{
fout << "Cod: " << calatoriiAvion[i].getCod() << " Plecare: " << calatoriiAvion[i].getLocalitatePlecare() << " Destinatie: " << calatoriiAvion[i].getLocalitateDestinatie() << " Data: " << calatoriiAvion[i].getDataPlecarii() << " Escala: ";
if (calatoriiAvion[i].getEscala() == true)
fout << "DA";
else
fout << "NU";
fout << " Nr.Locuri Totale:" << calatoriiAvion[i].getNrLocTotale() << " Nr.Locuri Rezervate: " << calatoriiAvion[i].getNrLocRezervate() << '\n';
}
}
*/ | true |
d87f9e5a4ef8ae0c68b648790c04b2c9447203ad | C++ | johnnydevriese/wsu_comp_sci | /cpts_122/pa6_VS/pa6_VS/main.cpp | UTF-8 | 3,634 | 3.15625 | 3 | [
"MIT"
] | permissive | /*******************************************************************************************
* Programmer: Johnny Minor *
* Class: CptS 122, Spring 2015; Lab Section 04 *
* Programming Assignment: Programming Assignment 6 *
* Date: March 30th, 2015 *
* Description: This program is supposed to read in the csv file and then manipulate it and have various outfiles that print students.
* Unfortunately it's all screwed up and doesn't work how I intended and I don't know why...
* Although my best guess would be that I have scoping issues, but idk how the hell to fix them.
*******************************************************************************************/
#include<iostream>
#include<fstream>
#include<string>
#include"LinkedList.hpp"
#pragma once
//string stream
//just some miscellaneous notes below...
//include<vector>
//using std::vector
//vector <string> abs
//abs.push_back
/*
how to iterate through a vector
for(int i = 0; i < vector.size(); i++)
{
would start at the beginning
vector[i];
}
*/
//will probably get in trouble for doing this...
//using namespace std;
using std::cout;
using std::cin;
using std::ifstream;
using std::ofstream;
using std::getline;
using std::endl;
using std::cin;
int main(void)
{
List MasterList;
List * list;
int flag = 0;
int flagGenerate = 0;
do{
system("cls");
cout << "what would you like to do?" << endl;
cout << "1. Import course list." << endl;
cout << "2. Load master list" << endl;
cout << "3. Store master list" << endl;
cout << "4. Mark absences" << endl;
cout << "5. Edit absences" << endl;
cout << "6. Generate report" << endl;
cout << "7. Exit" << endl;
cin >> flag ;
system("pause");
if(flag == 1)
{
//import course list into linked list
list = MasterList.importCourse();
system("pause");
}
else if(flag == 2)
{
//load master list
MasterList.loadMasterList();
}
else if(flag == 3)
{
cout << list->pHead->nodeName << endl;
system("pause");
//store master list
//MasterList.storeMasterList();
}
else if(flag == 4)
{
//mark absences
MasterList.markAbsences();
}
else if(flag == 5)
{
//edit absences
MasterList.editAbsences();
}
else if(flag == 6)
{
system("cls");
cout << "Which type of report would you like to generate?" << endl;
cout << "1. Generate report for all student." << endl;
cout << "2. Report for students with a number of absences greater or less than ___" << endl;
cout << "3.Report with all of today's absences." << endl;
cin >> flagGenerate;
if(flagGenerate == 1)
{
//report for all students.
MasterList.generateAll();
}
else if(flagGenerate == 2)
{
cout << "How many absences would you like to search for" << endl;
string searchflag;
cin >> searchflag;
//some function that will search for that flag value and then output to a file.
//();
MasterList.generateSearchAbsent();
}
else if(flagGenerate == 3)
{
//Report with all of todays absences.
MasterList.generateDate();
}
//Generate report
}
}while(flag != 7); //leaving the program
return 0;
} | true |
3082ce3779e212db29bea7ee3a10d4741b83f7bb | C++ | nya3jp/icpc | /camp/2008russia/src/upsolving/journey.cpp | UTF-8 | 1,962 | 2.8125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <complex>
#include <cstdio>
#include <cmath>
using namespace std;
#define REP(i,n) for(int i = 0; i < (int)(n); i++)
#define ALLOF(c) (c).begin(), (c).end()
#define PROBLEM_NAME "journey"
#define MOD 1000000009
typedef int** matrix_t;
matrix_t new_matrix(int n) {
matrix_t a = new int*[n];
REP(i, n) {
a[i] = new int[n];
REP(j, n)
a[i][j] = 0;
}
return a;
}
matrix_t multiply(matrix_t a, matrix_t b, int n) {
matrix_t c = new_matrix(n);
REP(i, n) REP(j, n) REP(k, n)
c[i][k] = (int)((c[i][k] + (long long)a[i][j] * b[j][k]) % MOD);
return c;
}
matrix_t pow(matrix_t a, int n, int p) {
matrix_t b = new_matrix(n);
REP(i, n) REP(j, n)
b[i][j] = (p%2 == 0 ? (i == j ? 1 : 0) : a[i][j]);
if (p >= 2)
b = multiply(b, pow(multiply(a, a, n), n, p/2), n);
return b;
}
int go(bool** g, int n, int d, int p) {
matrix_t a = new_matrix(n);
REP(i, n) REP(j, n)
if (g[i][j] && (p & (1<<i)) == 0 && (p & (1<<j)) == 0)
a[i][j] = 1;
matrix_t b = pow(a, n, d-1);
int res = 0;
REP(i, n) REP(j, n)
if ((p & (1<<j)) == 0)
res = (res + b[i][j]) % MOD;
return res;
}
int main() {
if (!freopen(PROBLEM_NAME ".in", "r", stdin))
abort();
if (!freopen(PROBLEM_NAME ".out", "w", stdout))
abort();
int n, m, k, d;
cin >> n >> m >> k >> d;
bool** g = new bool*[n];
REP(i, n) {
g[i] = new bool[n];
REP(j, n)
g[i][j] = false;
}
REP(i, m) {
int a, b;
cin >> a >> b;
a--; b--;
g[a][b] = g[b][a] = true;
}
int res = 0;
REP(p, 1<<k) {
int lo = go(g, n, d, p);
if (__builtin_popcount(p) % 2 == 0)
res = (res + lo) % MOD;
else
res = (res - lo + MOD) % MOD;
}
cout << res << endl;
return 0;
}
| true |
08a122df86db9a124c43248b0249dee24d7fcb1e | C++ | tl3shi/cpp_hello_world | /morethan1address.cpp | UTF-8 | 363 | 3.0625 | 3 | [] | no_license | #include <iostream>
#include <stdio.h>
using namespace std;
class Base
{
public:
int a;
double x;
char xx;
};
class Derived: public Base
{
public:
int b;
};
int main()
{
Derived d;
d.b = 1;
Base* b = &d;
Derived* d2 = &d;
cout << b << endl;
cout << d2 << endl;
printf("%p", b);
printf("%p", d2);
return 0;
}
| true |
0191769457bd1774ee665ffc80510a6e1aca5c39 | C++ | MartinChan3/CyComputerNote | /LeetCode/001TwoSum.cpp | GB18030 | 1,131 | 3.375 | 3 | [] | no_license | #include <vector>
#include <unordered_map>
#include <iostream>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> m; //ʹmapҪԭΪʱΪO(n)
vector<int> res;
for (int i = 0; i < nums.size(); ++i) {
m[nums[i]] = i; //ֵ-ֵķʽ
}
for (int i = 0; i < nums.size(); ++i) {
int t = target - nums[i];
if (m.count(t) && m[t] != i) { //mapеcount()ʽΪѰҶӦļֵ
res.push_back(i);
res.push_back(m[t]);
break;
}
}
return res;
}
vector<int> twoSum2(vector<int>& nums, int target) { //ϲΪһѭ
unordered_map<int, int> m;
for (int i = 0; i < nums.size(); ++i) {
if (m.count(target - nums[i])) { //Ľ֮һģһд
return{ i, m[target - nums[i]] };
}
m[nums[i]] = i;
}
return{};
}
};
void main()
{
vector<int> nums;
nums.push_back(2);
nums.push_back(7);
nums.push_back(11);
nums.push_back(13);
int target = 9;
Solution solution;
solution.twoSum2(nums, target);
} | true |
cdb4924eb24181c0a2a4594476e49ef40d0a4061 | C++ | matthiasds/sdl_racegame | /components/SdlDebugComponent.h | UTF-8 | 1,250 | 2.578125 | 3 | [] | no_license | /*
* SdlDebugComponent.h
*
* Created on: 10-may.-2015
* Author: Matthias
*/
#ifndef SDLDEBUGCOMPONENT_H_
#define SDLDEBUGCOMPONENT_H_
#include <iostream>
class SdlDebugComponent : public IComponent {
public:
SdlDebugComponent(Au_2Drenderer::Renderer* renderer, std::string fontPath, int fontSize) {
size = fontSize;
color = Color(0,0,255);
this->fontPath=fontPath;
loadFont();
this->renderer = renderer;
}
void loadFont()
{
font = TTF_OpenFont( fontPath.c_str(), size );
if( font == NULL )
{
std::cerr << "Failed to load font " << fontPath << ", Error: " << TTF_GetError() << std::endl;
}
}
void setSize(int size) {
this->size = size;
loadFont();
}
TTF_Font* getFont() {
return font;
}
void setColor(uint8_t r, uint8_t g, uint8_t b ) {
color = Color(r, g, b);
}
Color getColor() {
return color;
}
virtual ~SdlDebugComponent() {
}
Au_2Drenderer::Renderer* getRenderer() {
return renderer;
}
private:
std::vector<Au_2Drenderer::Sprite*> sprites;
TTF_Font * font;
Color color;
int size;
std::string fontPath;
Au_2Drenderer::Renderer* renderer;
};
#endif /* SDLDEBUGCOMPONENT_H_ */
| true |
7fbae9a83d7b226183c15ee3bcf7cc583c0031c6 | C++ | abhisehekkumr/DP | /coinChangeProblem.cpp | UTF-8 | 1,187 | 3.546875 | 4 | [] | no_license | /*
You are given an infinite supply of coins of each of denominations D = {D0, D1, D2, D3, ...... Dn-1}.
You need to figure out the total number of ways W, in which you can make change for Value V using coins of denominations D.
Note : Return 0, if change isn't possible.
*/
#include<bits/stdc++.h>
using namespace std;
const int MAX = 15;
int coinChange(int denominations[], int size, int n, int output[][MAX]){
if(n == 0)
return 1;
if(n < 0)
return 0;
if(size == 0)
return 0;
if(output[n][size] > -1)
return output[n][size];
int first = coinChange(denominations, size, n - denominations[0], output);
int second = coinChange(denominations + 1, size - 1,n, output);
output[n][size] = first + second;
return first + second;
}
int main(){
int d;
cin >> d;
int denominations[d];
for(int i = 0; i < d; i++)
cin >> denominations[i];
int n;
cin >> n;
int output[n + 1][MAX];
for(int i = 0; i <= n; i++){
for(int j = 0; j < MAX; j++)
output[i][j] = -1;
}
std::cout << coinChange(denominations,d,n,output) << '\n';
}
| true |
1f3a579c2be486a16ed840e166b116e129e79567 | C++ | ama0115/Hw06 | /untitled1/src/main/cpp/Queue.h | UTF-8 | 595 | 2.90625 | 3 | [] | no_license | /**
*CSC232 Data Structures
*Missouri State University
*
**@file Queue.hp
* @author Austin Alvidrez<ama0115@live.missouristate.edu>
* @brief Header of Queue
*/
#ifndef HW06_QUEUE_H
#define HW06_QUEUE_H
#include "Node.h"
template <class ItemType>
class Queue {
private:
int startPos;
int endPos;
Event<ItemType>* queueData;
public:
Queue();
~Queue();
bool isEmpty() const;
bool enqueue(const Event<ItemType>& newData);
bool dequeue();
Event<ItemType> peekFront() const;
};
#endif //HW06_QUEUE_H
| true |
21ef831936dcd349e35fa66c4d890f33c2881779 | C++ | MoritzD/LegoLab | /uart.cpp | ISO-8859-3 | 1,879 | 2.703125 | 3 | [] | no_license | /*
* uart.cpp
*
* Created on: 01.06.2016
* Author: Berkay
*/
//#include "uart.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
int main() {
int uart0_filestream = -1;
uart0_filestream = open("/dev/ttyAMA0", O_RDWR | O_NOCTTY | O_NDELAY); //Initialisierung der UART
if (uart0_filestream == -1) {
printf("[ERROR] UART open()\n");
}
struct termios options;
tcgetattr(uart0_filestream, &options);
options.c_cflag = B115200 | CS8 | CLOCAL | CREAD;
options.c_iflag = IGNPAR;
options.c_oflag = 0;
options.c_lflag = 0;
tcflush(uart0_filestream, TCIFLUSH);
tcsetattr(uart0_filestream, TCSANOW, &options);
// sendung bytes ber tx-pin
unsigned char BUF_TX[7];
unsigned char *TX;
TX = &BUF_TX[0];
*TX++ = 'H';
*TX++ = 'e';
*TX++ = 'l';
*TX++ = 'l';
*TX++ = 'o';
*TX++ = '\n';
*TX++ = '\r';
if (uart0_filestream != -1) {
int out = 0;
out = write(uart0_filestream, &BUF_TX[0], (TX - &BUF_TX[0])); //macht das Senden, out zaehlt die geschriebene bytes
if (out < 0) {
printf("[ERROR] UART TX\n");
} else {
printf("[STATUS: TX %i Bytes] %s\n", out, BUF_TX);
}
} // if uart0
sleep(1);
// Bytes empfangen
if (uart0_filestream != -1) {
unsigned char BUF_RX[50];
int rx_length = 0;
while(rx_length <= 0){
rx_length = read(uart0_filestream, (void*)BUF_RX, 50); //rx_length zaehlt ankommenden bytes
}
//UBERPRueFUNG, 0'dan kucukse bir hata var, 0'dan buyukse daha fayla bytes gelemiyor
if (rx_length < 0) {
printf("[ERROR] UART RX\n");
} else if (rx_length == 0) {
printf("[ERROR] UART RX - no data\n");
} else {
BUF_RX[rx_length] = '\0';
printf("[STATUS: RX %i Bytes] %s\n", rx_length, BUF_RX);
} //rx_length check
} //if uart0
close(uart0_filestream);
return 0;
}
| true |
9b1e03645cdd713adf4244db2bac2cc13b641e4e | C++ | tinwoon/baekjoon_algorithm | /Algorithm_code/2580_x.cpp | UHC | 3,284 | 3.375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
std::vector< std::vector<int> >map(9,std::vector<int>(9));
std::vector< std::vector<int> >blank_data;
//Ʈŷ
//dfs ߴٴ ǹ̰ ùٸ .
std::vector<int> Enable_num(std::vector<int> v) {//, , 簢 ȿ ش ǥ
std::vector<int> number = { 1,2,3,4,5,6,7,8,9 };
for (int a = 0; a < 9; a++) {
for (int b = 0; b < number.size(); b++) {
if (v[a] == number[b]) {
number.erase(number.begin()+b);
}
}
}
return number;
}
std::vector<int> Initialize_square(int i,int j) {//ش ǥ 3*3ľȿ
std::vector<int> square;
for (int a = (i / 3) * 3; a < ((i / 3) * 3) + 3; a++) {
for (int b = (j / 3) * 3; b < ((j / 3) * 3) + 3; b++) {
square.push_back(map[a][b]);
}
}
return Enable_num(square);
}
std::vector<int> Initialize_row(int i, int j) {//ش ǥ
std::vector<int> row;
for (int k = 0; k < 9; k++) {
row.push_back(map[i][k]);
}
return Enable_num(row);
}
std::vector<int> Initialize_column(int i, int j) {//ش ǥ
std::vector<int> column;
for (int k = 0; k < 9; k++) {
column.push_back(map[k][j]);
}
return Enable_num(column);
}
void calculate(int i, int j,int stack) {
//row, column, square ؼ ش i,jǥ ص.
std::vector<int> row = Initialize_row(i, j);
std::vector<int> column = Initialize_column(i, j);
std::vector<int> square = Initialize_square(i, j);
std::vector<int> value(9);// ش i,jǥ ִ ص
std::vector<int>::iterator itr = std::set_intersection(row.begin(), row.end(), column.begin(), column.end(),value.begin());// row, column, square value
value.resize(itr - value.begin());
itr = std::set_intersection(value.begin(), value.end(), square.begin(), square.end(), value.begin());
value.resize(itr - value.begin());
if (value.empty()) {
return;
}
for (int x = 0; x < value.size(); x++) {//value ش i,jǥ Ǿ dfs value ϳ 鼭 Ȯ
map[i][j] = value[x];
if ((i == blank_data[blank_data.size() - 1][0]) && (j== blank_data[blank_data.size() - 1][1])) {
for (int a = 0; a < 9; a++) {
for (int b = 0; b < 9; b++) {
printf("%d ", map[a][b]);
}
printf("\n");
}exit(0);
}
std::vector< std::vector<int> >blank_data_x = blank_data;
std::vector< std::vector<int> >map_x = map;
calculate(blank_data[stack + 1][0], blank_data[stack + 1][1], stack + 1);
}
}
int main() {
std::vector<int> data;
int stack=0;
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
scanf("%d", &map[i][j]);
if (map[i][j] == 0) {
data.push_back(i);
data.push_back(j);
blank_data.push_back(data);
data.clear();
}
}
}
std::vector< std::vector<int> >blank_data_x = blank_data;
std::vector< std::vector<int> >map_x = map;
calculate(blank_data[stack][0], blank_data[stack][1],stack);
}
| true |
8e7f68e2f32eccf02216a46f5e283a0601277699 | C++ | GaryZ700/CPSC350_Assignment5 | /student_record.h | UTF-8 | 655 | 2.875 | 3 | [] | no_license | /* Gary Zeri
ID: 2321569
zeri@chapman.edu
CPSC 250-02
Assignment 5: Building a Database with Binary Search Trees
*/
#ifndef STUDENT_RECORD_H_
#define STUDENT_RECORD_H_
#include "serialization_helper.h"
#include "database_record.h"
using namespace std;
class StudentRecord : DatabaseRecord{
friend class Database;
friend class UniversityDB;
public:
StudentRecord();
StudentRecord(int id, string name, string level, string major, double gpa, int advisor);
void Serialize(fstream &outputFile) const;
void Deserialize(fstream &inputFile);
void Display() const;
private:
string major;
double gpa;
int advisor;
};
#endif //STUDENT_RECORD_H_
| true |
c2654bb792ce7c37441e6e9ee2b0b8a5ac2bd5f9 | C++ | RyanMoss96/Generic-Linked-List | /Templates/Templates.cpp | UTF-8 | 616 | 3.0625 | 3 | [] | no_license | // Templates.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "LinkedList.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
LinkedList<string>* myList = new LinkedList<string>;
myList->pushFront("a");
myList->pushFront("b");
myList->pushFront("c");
myList->pushFront("b");
myList->display();
cout << "first item on the list: " << myList->getFront() << endl;
myList->popFront();
myList->display();
cout << "the next item on the list: " << myList->getFront() << endl;
myList->popFront();
delete myList;
system("pause");
}
| true |
8f2c0db689b7e21820a49ad40b7370a469aaf08a | C++ | qls152/CPP-design-parttern | /command-pattern/remote_control_test.cc | UTF-8 | 1,275 | 2.578125 | 3 | [] | no_license | #include "command/garge_door_command.h"
#include "command/garge_door_off_command.h"
#include "command/light_command.h"
#include "command/lightoff_command.h"
#include "slot/normal_garge_door.h"
#include "slot/normal_light.h"
#include "control/remote_control.h"
int main() {
RemoteControl remote_control;
auto garge_door = std::make_shared<NormalGargeDoor>();
auto light = std::make_shared<NormalLight>();
// 创建所需要的命令对象
// 此处并未全部实现HeadFirst中所有命令对象,只是因为创建过程均类似,所以两个足以起练习作用
auto light_on_command = std::make_shared<LightCommand>(light);
auto light_off_command = std::make_shared<LightOffCommand>(light);
auto garge_door_down = std::make_shared<GargeDoorCommand>(garge_door);
auto garge_door_up = std::make_shared<GargeDoorOffCommand>(garge_door);
// 将相应的命令对象加载到相应的槽中
remote_control.setCommand(0, light_on_command, light_off_command);
remote_control.setCommand(1, garge_door_down, garge_door_up);
// 一切准备就绪,按下相应按钮
remote_control.onButtonWasPressed(0);
remote_control.onButtonWasPressed(1);
remote_control.offButtonWasPressed(0);
remote_control.offButtonWasPressed(1);
return 0;
} | true |
f17245f7c4de96acac4ed5ddb0ada8bd945aab6f | C++ | sungindra/codingame-solutions | /multiplayer/coders_strike_back/wood_1_league.cpp | UTF-8 | 1,106 | 3.046875 | 3 | [] | no_license | #include <cstdlib>
#include <cstdio>
#include <cstring>
int main() {
// game loop
while (1) {
int x;
int y;
int nextCheckpointX; // x position of the next check point
int nextCheckpointY; // y position of the next check point
int nextCheckpointDist; // distance to the next checkpoint
int nextCheckpointAngle; // angle between your pod orientation and the direction of the next checkpoint
scanf("%d %d %d %d %d %d", &x, &y, &nextCheckpointX, &nextCheckpointY, &nextCheckpointDist, &nextCheckpointAngle);
int opponentX;
int opponentY;
scanf("%d%d", &opponentX, &opponentY);
int power = 0;
if(nextCheckpointAngle >= 90 || nextCheckpointAngle <= -90) {
power = 10;
} else {
if(power < 50) {
//BOOST
printf("%d %d BOOST\n", nextCheckpointX, nextCheckpointY);
continue;
} else {
power = 100;
}
}
printf("%d %d %d\n", nextCheckpointX, nextCheckpointY, power);
}
} | true |
f121debdd0536e6f862b03883509fa26611dd55e | C++ | Markay12/cardCounting | /src/Cards.cpp | UTF-8 | 1,184 | 3.46875 | 3 | [] | no_license | #include "Cards.h"
#include <cstddef>
#include <cstdlib>
#include <ctime>
//give random card value
Cards::Cards()
{
srand(time(NULL));
this->val = rand() % 13 + 1;
this->suit = rand() % 4 + 1;
}
//give card new values
void Cards::setCard()
{
this->val = rand() % 13 + 1;
this->suit = rand() % 4 + 1;
}
char Cards::getCardVal()
{
//Ace card if value is 1
if(this->val == 1)
{
return 'A';
}
//other face card values
else if (this->val == 10)
{
return 'J';
}
else if (this->val == 11)
{
return 'Q';
}
else if (this->val == 12)
{
return 'K';
}
//if none of these we just return the value of the card
else if (this->val == 2)
{
return '2';
}
else if (this->val == 3)
{
return '3';
}
else if (this->val == 4)
{
return '4';
}
else if (this->val == 5)
{
return '5';
}
else if (this->val == 6)
{
return '6';
}
else if (this->val == 7)
{
return '7';
}
else if (this->val == 8)
{
return '8';
}
else
{
return '9';
}
}
char Cards::getCardSuit()
{
if (this->suit == 1)
{
return 'H';
}
else if (this->suit == 2)
{
return 'D';
}
else if (this->suit == 3)
{
return 'S';
}
else
{
return 'C';
}
}
| true |
fd6822e526c0d1083057fd0abc482e20176fb891 | C++ | Subzero-10/leetcode | /130.surrounded-regions.cpp | UTF-8 | 2,007 | 2.90625 | 3 | [] | no_license | /*
* @lc app=leetcode id=130 lang=cpp
*
* [130] Surrounded Regions
*/
// @lc code=start
class Solution {
public:
void solve(vector<vector<char>>& board) {
int rlen = board.size();
if (rlen == 0)
{
return;
}
int clen = board[0].size();
if (clen == 0)
{
return;
}
vector<char> tem(clen,'X');
vector<vector<char>> m(rlen, tem);
for (int i = 0; i < clen; i++)
{
if (board[0][i] == 'O')
{
if (m[0][i] == 'X')
{
helper(0, i, board, m);
}
}
}
for (int i = 1; i < rlen; i++)
{
if (board[i][0] == 'O')
{
if (m[i][0] == 'X')
{
helper(i, 0, board, m);
}
}
}
for (int i = 1; i < rlen; i++)
{
if (board[i][clen-1] == 'O')
{
if (m[i][clen-1] == 'X')
{
helper(i, clen-1, board, m);
}
}
}
for (int i = 1; i < clen-1; i++)
{
if (board[rlen-1][i] == 'O')
{
if (m[rlen-1][i] == 'X')
{
helper(rlen-1, i, board, m);
}
}
}
board.assign(m.begin(), m.end());
}
void helper(int r, int c, vector<vector<char>>& board, vector<vector<char>>& m){
if (r==(int)m.size() || c==(int)m[0].size() || r==-1 || c==-1)
{
return;
}
if (board[r][c] == 'O')
{
if (m[r][c] == 'X')
{
m[r][c] = 'O';
helper(r+1, c, board, m);
helper(r-1, c, board, m);
helper(r, c+1, board, m);
helper(r, c-1, board, m);
}
}
}
};
// @lc code=end
| true |