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
707ab45c9e325d136ed2ea56a59e63b4b4b66aed
C++
InitToZero/Oregon-State-University-2015-19
/CS 162 - Intro to Computer Science 2/Assignment1/state_facts.cpp
UTF-8
14,189
3.859375
4
[]
no_license
/*************************************************************** * Program: state_facts.cpp * Author: Jonathan Ropp * Date: 4/10/2016 * Input: txt file with state/county information, given by user * Output: ***************************************************************/ #include <iostream> #include <string> #include <cstdlib> #include <fstream> using namespace std; #include "./state_facts.h" /************************************************************************************* * Function : is_valid_arguments * Description : Checks input arguments to see if good * Parameters : char **argv, int argc * Pre-conditions : None * Post-conditions : Will return bool for if args are good * ***********************************************************************************/ bool is_valid_arguments(char **argv, int argc){ int s = -1, f = -1; //If there are not 5 arguments, error msg and end program if(argc != 5){ cout<<"You did not enter the right number of arguments"<<endl; return false; } //If user did not supply -s and -f, error msg and end program for(int i=1; i<argc; i+=2){ if(argv[i][0] == '-' && argv[i][1] == 's'){ if(s == 1){ cout<<"Usage error"<<endl; return false; } s = 1; } else if(argv[i][0] == '-' && argv[i][1] == 'f'){ if(f == 1){ cout<<"Usage error"<<endl; return false; } f = 1; } else{ cout<<"Usage error"<<endl; return false; } } //If input arguments are good, return true return true; } /************************************************************************************* * Function : create_states * Description : Dynamically create a 1-d array on the heap for state info * Parameters : int num * Pre-conditions : Paramters are good * Post-conditions : Will return the array made * ***********************************************************************************/ state * create_states(int num){ //Make 1-d array on heap state *t; t = new state[num]; //Return array return t; } /************************************************************************************* * Function : get_state_data * Description : Will read in state data and create county arrays based on input * Parameters : state *s, int num_state, ifstream &input * Pre-conditions : Paramters are good * Post-conditions : After funciton, state will have all info needed * ***********************************************************************************/ void get_state_data(state *s, int num_state, ifstream &input){ //Input data for state struct input >> s[num_state].name; input >> s[num_state].population; input >> s[num_state].counties; //Create county array s[num_state].c = create_counties(s[num_state].counties); //Fill county array with data for(int i=0; i<s[num_state].counties; i++){ get_county_data(s[num_state].c, i, input); } } /************************************************************************************* * Function : create_counties * Description : Will dynamically create a 1-d array on the heap for county info * Parameters : int num * Pre-conditions : Paramters are good * Post-conditions : Will return array made * ***********************************************************************************/ county * create_counties(int num){ //Create 1-d array county *o; o = new county[num]; //Return array return o; } /************************************************************************************* * Function : get_county_data * Description : Will fill the county array and city string with data read in from file * Parameters : county *o, int num, ifstream & input * Pre-conditions : Paramters are good * Post-conditions : After this, city and county info will be done for this state * ***********************************************************************************/ void get_county_data(county *o, int num, ifstream & input){ //Input data for county struct input >> o[num]. name; input >> o[num]. population; input >> o[num]. avg_income; input >> o[num]. avg_house; input >> o[num]. cities; //Create city array o[num].city=new string[o[num].cities]; //Fill city array with data for(int j=0; j<(o[num].cities); j++){ input >> o[num].city[j]; } } /************************************************************************************* * Function : delete_info * Description : Will delete allocated memory from heap * Parameters : state *s, int num * Pre-conditions : Paramters are good * Post-conditions : All memory should be freed * ***********************************************************************************/ void delete_info(state *s, int num){ //Delete each city array for(int i=0; i<num; i++){ for(int j=0; j<s[i].counties; j++){ delete []s[i].c[j].city; } } //Delete each county array for(int i=0; i<num; i++){ delete []s[i].c; } //Delete state array delete []s; } /************************************************************************************* * Function : menu * Description : This prints menu and gets user input with error handling * Parameters : None * Pre-conditions : None * Post-conditions : Returns user choice for menu * ***********************************************************************************/ int menu(){ int num; bool good=false; string input; //While the user wants to use the menu while(good == false){ cout<<"What would you like to see?"<<endl; cout<<"(1) State with largest population"<<endl <<"(2) County with largest population"<<endl <<"(3) County with income above ___"<<endl <<"(4) Average household income for all counties in each state"<<endl <<"(5) States ordered by name"<<endl <<"(6) States ordered by population"<<endl <<"(7) Counties within states sorted by population"<<endl <<"(8) Counties within states sorted by name"<<endl; //Gets user input and makes sure it is a valid int; if not, print error and ask again cin >> input; for(int i=0; i<input.length();i++){ if(!(input.at(i)>='1'&&input.at(i)<='8')){ cout << "Please enter a valid number. : "; cin >> input; i=-1; } } num = atoi(input.c_str()); while (num > 8 || num < 1){ cout << "Please enter a valid number. : "; cin >> num; } //Return the valid int to main return num; } } /************************************************************************************* * Function : op1 * Description : Will dispay the state with the largest population * Parameters : state *s, int num * Pre-conditions : Paramters are good * Post-conditions : Parameters are still good * ***********************************************************************************/ void op1(state *s, int num){ int big_pop = s[0].population; int name_place = 0; //Cycle through states to find one with largest pop for(int i=1; i<num; i++){ if(s[i].population>big_pop){ big_pop = s[i].population; } name_place = i-1; } cout<<s[name_place].name<<" has the largest population: "<<big_pop<<endl; } /************************************************************************************* * Function : op2 * Description : Will display county with largest population * Parameters : state *s, int num * Pre-conditions : Paramters are good * Post-conditions : Parameters are still good * ***********************************************************************************/ void op2(state *s, int num){ int big_pop = s[0].c[0].population; int s_name_place = 0, c_name_place = 0; //Cycle through counties to find largest pop for(int i=0; i<num; i++){ for(int j=0; j<num; j++){ if(s[i].c[j].population>big_pop){ big_pop = s[i].c[j].population; s_name_place = i; c_name_place = j; } } } cout<<s[s_name_place].c[c_name_place].name<<" county in "<<s[s_name_place].name<< " has the largest population: "<<big_pop<<endl; } /************************************************************************************* * Function : op3 * Description : Displays counties with income above user input * Parameters : state *s, int num * Pre-conditions : Paramters are good * Post-conditions : Parameters are still good * ***********************************************************************************/ void op3(state *s, int num){ string income; //Get input for income level cout<<"What income level would you like to set?"<<endl; cin >> income; //Make sure number is good for(int i=0; i<income.length();i++){ if(!(income.at(i)>='0'&&income.at(i)<='9')){ cout << "Please enter a valid number. : "; cin >> income; i=-1; } } int v_num = atoi(income.c_str()); while (v_num > 10000000 || v_num < 0){ cout<<"Please enter a valid number: "; cin >> income; } for(int i=0; i<num; i++){ for(int j=0; j<s[i].counties; j++){ if(s[i].c[j].avg_income > v_num){ //Print counties with income above set level cout<<s[i].c[j].name<<" with income of "<<s[i].c[j].avg_income<<endl; } } } } /************************************************************************************* * Function : op4 * Description : Displays average houshold cost for all counties * Parameters : state *s, int num * Pre-conditions : Paramters are good * Post-conditions : Parameters are still good * ***********************************************************************************/ void op4(state *s, int num){ cout<<"Average houseshould costs: "<<endl<<endl; for(int i=0; i<num; i++){ cout<<"State: "<<s[i].name<<endl<<endl; for(int j=0; j<s[i].counties; j++){ cout<<s[i].c[j].name<<": "<<s[i].c[j].avg_house<<endl; } cout<<endl<<endl; } } /************************************************************************************* * Function : op5 * Description : This function sorts and prints the states by name * Parameters : state *s, int num * Pre-conditions : Paramters are good * Post-conditions : Parameters are still good * ***********************************************************************************/ void op5(state *s, int num){ string temp; for(int i=0; i<num; i++){ for (int j=0; j<num-1-i; j++){ if(s[j].name > s[j+1].name){ temp = s[j].name; s[j].name = s[j+1].name; s[j+1].name = temp; } } } for(int k=0; k<num; k++){ cout<<s[k].name<<endl; } } /************************************************************************************* * Function : op6 * Description : This function sorts and prints the states by population * Parameters : state *s, int num * Pre-conditions : Paramters are good * Post-conditions : Parameters are still good * ***********************************************************************************/ void op6(state *s, int num){ int temp_i; string temp_s; for (int i=0; i<num; i++){ for (int j=0; j<num-1-i; j++){ if(s[j].population<s[j+1].population){ temp_i = s[j].population; s[j].population = s[j+1].population; s[j+1].population = temp_i; temp_s = s[j].name; s[j].name = s[j+1].name; s[j+1].name = temp_s; } } } for(int k=0; k<num; k++){ cout<<s[k].name<<": "<<s[k].population<<endl; } } /************************************************************************************* * Function : op7 * Description : This function sorts and prints the counties by population * Parameters : state *s, int num * Pre-conditions : Paramters are good * Post-conditions : Parameters are still good * ***********************************************************************************/ void op7(state *s, int num){ /****NOT CORRECT******/ int total_p =0; for(int i=0; i<num; i++){ total_p = total_p + s[i].counties; } float temp; float pop[total_p]; int k = 0; while(k<total_p){ for(int i=0; i<num; i++){ for(int j=0; j<s[i].counties; j++){ pop[k] = s[i].c[j].population; k++; } } } for(int y=0; y<total_p; y++){ if(pop[y]>pop[y+1]){ temp = pop[y]; pop[y] = pop[y+1]; pop[y+1] = temp; y--; } } for(int z=0; z<total_p; z++){ cout<<pop[z]<<" "<<z<<endl; } } /************************************************************************************* * Function : op8 * Description : This function sorts and prints the counties by name * Parameters : state *s, int num * Pre-conditions : Paramters are good * Post-conditions : Parameters are still good * ***********************************************************************************/ void op8(state *s, int num){ /**********NOT CORRECT***********/ int total_c =0; for(int i=0; i<num; i++){ total_c = total_c + s[i].counties; } string temp; string counties[total_c]; int k = 0; while(k<total_c){ for(int i=0; i<num; i++){ for(int j=0; j<s[i].counties; j++){ counties[k] = s[i].c[j].name; k++; } } } for(int y=0; y<total_c; y++){ if(counties[y]>counties[y+1]){ temp = counties[y]; counties[y] = counties[y+1]; counties[y+1] = temp; y--; } } for(int z=0; z<total_c; z++){ cout<<counties[z]<<endl; } } /************************************************************************************* * Function : run_again * Description : Asks user if they want to run through menu again * Parameters : none * Pre-conditions : none * Post-conditions : Parameters are still good * ***********************************************************************************/ bool run_again(){ bool good = false; cout<<"Would you like to run again? Yes(1) or no(2): "; //While the input is bad, keep asking while(good == false){ string input; int num; cin >> input; //If user did not input a 1 or 2, try again for(int i=0; i<input.length();i++){ if(!(input.at(i)>='1'&&input.at(i)<='2')){ cout << "Please enter a valid number : "; cin >> input; i=-1; } } //Translate input to int num = atoi(input.c_str()); //return true(1) or false(2) if(num == 1){ return true; } else if(num == 2){ return false; } } }
true
63009b706e0d1db8c13325114d4202b29af57352
C++
cocoa0409/LeetCodeSolutions
/leetcode解答/位运算-异或-只出现1次的数字-136.cpp
UTF-8
318
2.734375
3
[]
no_license
// // 位运算-异或-只出现1次的数组-136.cpp // LeetCodePlayground // // Created by 兆吉 王 on 2020/4/21. // Copyright © 2020 兆吉 王. All rights reserved. // int singleNumber(vector<int>& nums) { int res=0; for(auto it=nums.begin();it!=nums.end();it++){ res^=*it; } return res; }
true
1a76764b72c1eb07edc87fd4b54c3e21267b0987
C++
castillo098/TrabajoGrupalBimestre_ArduinoConfigBluetooth
/ArduinoConfigBluetooth.ino
UTF-8
1,242
2.75
3
[]
no_license
#include <SoftwareSerial.h> SoftwareSerial blue(2, 3); //Crea conexion al bluetooth-PIN 2 a tx y PIN 3 a RX char NOMBRE[21] = "UserHC-06"; //Nombre de 20 caracteres maximo char BPS = '4'; //1=1200, 2=2400, 3=4800 4= 9600, 5=19200, 6=38400, 7=57600, 8=115200 char PASS [5] = "1234"; //PIN O CLAVE de 4 caracteres numericos void setup() { blue.begin(9600); //Se inicia la comuniacion serial a 9600 baudios(definida como velocidad de fabrica) pinMode(13, OUTPUT); digitalWrite(13,HIGH); //Enciende el LED 13 durante 4s antes de configurar el bluetooth delay(4000); digitalWrite(13,LOW); //Apaga el LED 13 para iniciar la programacion blue.print("AT"); //Inicializa comando AT delay(1000); //Realiza durante un segundo blue.print("AT+NAME"); //Configura el nuevo nombre blue.print(NOMBRE); delay(1000); //espera 1 segundo blue.print("AT+BAUD"); //Configura la nueva velocidad blue.print(BPS); delay(1000); blue.print("AT+PIN"); //Configura el nuevo pin blue.print(PASS); delay(1000); //Espera 1 segundo } void loop() { digitalWrite(13, !digitalRead(13)); //Cuando termina de configurar el Bluetooth que en el LED 13 delay(300); }
true
f7feddda019c9dbc7e72cf1be5f288cab5e2b5b4
C++
dquadros/ATmegaDetonator
/LeFuses/LeFuses.ino
UTF-8
4,158
2.75
3
[ "MIT" ]
permissive
#include "ATmegaDetonator.h" #include <Wire.h> /* * ATmegaDetonator * Teste de leitura dos "fuses" do ATmega * * (C) 2020, Daniel Quadros */ // pinos de saída int pinOut[] = { pinVcc, pin12V, pinOE, pinWR, pinBS1, pinBS2, pinXA0, pinXA1, pinPAGEL, pinXTAL1, 0 }; // comandos de programação const byte CMD_LEID = 0x08; const byte CMD_LEFUSES = 0x04; // Iniciação void setup() { for (int i = 0; pinOut[i] != 0; i++) { pinMode(pinOut[i], OUTPUT); digitalWrite(pinOut[i], LOW); } pinMode (pinRdy, INPUT); Wire.begin(); PCF8574_Write(0); Serial.begin(115200); Serial.println("Leitura dos Fuses"); } void loop() { byte fuses[4]; Serial.println(); Serial.println("Digite [ENTER]"); espera(); ATmega_ModoPgm(); ATmega_LeFuses(fuses); ATmega_Desliga(); Serial.print (fuses[0], HEX); Serial.print ("."); Serial.print (fuses[1], HEX); Serial.print ("."); Serial.print (fuses[2], HEX); Serial.print ("."); Serial.print (fuses[3], HEX); Serial.println(); } // Le os quatro bytes de "fuses" do ATmega void ATmega_LeFuses(byte *fuses) { ATmega_SendCmd (CMD_LEFUSES); fuses[0] = ATmega_Read (LOW, LOW); // LFUSE fuses[1] = ATmega_Read (HIGH, HIGH); // HFUSE fuses[2] = ATmega_Read (LOW, HIGH); // EFUSE fuses[3] = ATmega_Read (HIGH, LOW); // LOCK } // Coloca ATmega no modo programação paralela void ATmega_ModoPgm() { Serial.println ("Colocando no modo de programacao paralela"); // Garantir que está sem alimentação e reset digitalWrite (pinVcc, LOW); digitalWrite (pin12V, LOW); // Condição de entrada no modo programação paralela digitalWrite (pinPAGEL, LOW); digitalWrite (pinXA0, LOW); digitalWrite (pinXA1, LOW); digitalWrite (pinBS1, LOW); // Ligar a alimentação digitalWrite (pinVcc, HIGH); // Estes sinais devem ficar normalmente em nível alto digitalWrite (pinOE, HIGH); digitalWrite (pinWR, HIGH); // Aguardar e colocar 12V no reset delayMicroseconds(40); digitalWrite (pin12V, HIGH); // Aguardar a entrada delayMicroseconds(400); if (digitalRead(pinRdy) == HIGH) { Serial.println ("Sucesso!"); } else { Serial.println ("Nao acionou sinal RDY..."); } } // Retira o ATmega do modo programação e o desliga void ATmega_Desliga() { // Desliga os 12V para sair do modo programação digitalWrite (pin12V, LOW); // Dá um tempo e desliga delayMicroseconds(300); digitalWrite (pinVcc, LOW); // Vamos deixar todos os pinos em nível LOW // Para poder tirar o chip for (int i = 0; pinOut[i] != 0; i++) { digitalWrite(pinOut[i], LOW); } PCF8574_Write(0); } // Envia um comando para o ATmega void ATmega_SendCmd (byte cmd) { // indica que vai enviar um comando digitalWrite (pinXA0, LOW); digitalWrite (pinXA1, HIGH); digitalWrite (pinBS1, LOW); // Coloca o comando na via de dados PCF8574_Write(cmd); // Pulsa XTAL1 para registrar o comando pulsaXTAL1(); } // Envia um byte de endereço para o ATmega void ATmega_SendAddr (byte ordem, byte addr) { // indica que vai enviar um endereço digitalWrite (pinXA0, LOW); digitalWrite (pinXA1, LOW); // indica se é o byte LOW ou HIGH digitalWrite (pinBS1, ordem); // Coloca o endereço na via de dados PCF8574_Write(addr); // Pulsa XTAL1 para registrar o endereço pulsaXTAL1(); } // Lê um byte do ATmega byte ATmega_Read (int bs1, int bs2) { byte dado; // Libera a via de dados PCF8574_Release(); delayMicroseconds(1); // seleciona o byte a ler digitalWrite (pinBS1, bs1); digitalWrite (pinBS2, bs2); // Habilita a saída do byte digitalWrite (pinOE, LOW); delayMicroseconds(1); // Lê o byte dado = PCF8574_Read(); // Faz o ATMega soltar a via de dados digitalWrite (pinOE, HIGH); // Volta os sinais para o default digitalWrite (pinBS1, LOW); digitalWrite (pinBS2, LOW); return dado; } // Gera um pulso em XTAL1 void pulsaXTAL1() { delayMicroseconds(1); digitalWrite (pinXTAL1, HIGH); delayMicroseconds(1); digitalWrite (pinXTAL1, LOW); delayMicroseconds(1); } // Espera digitar ENTER void espera() { while (Serial.read() != '\r') { delay (100); } }
true
371c24ce94892526deb432b05ff369b255cadd61
C++
Vincentsummer/Typora
/C++/vPackage/vThread/vSycnTest.cpp
UTF-8
3,226
3
3
[]
no_license
// // Created by vincent on 20-2-14. // #include <iostream> #include "vSyncTest.h" namespace vincent { void ZeroEvenOdd1::zero(function<void(int)> printNumber) { for (int i = 1; i <= n; ++i){ unique_lock<mutex> lck(mutex_); cond_.wait(lck, [=](){return count == 0 || count == 2;}); printNumber(0); count = count == 0 ? 1 : 3; cond_.notify_all(); } } void ZeroEvenOdd1::odd(function<void(int)> printNumber) { for (int i = 2; i <= n; i += 2){ unique_lock<mutex> lck(mutex_); cond_.wait(lck, [=](){return count == 3;}); printNumber(i); count = 0; cond_.notify_all(); } } void ZeroEvenOdd1::even(function<void(int)> printNumber) { for (int i = 1; i <= n; i += 2){ unique_lock<mutex> lck(mutex_); cond_.wait(lck, [=](){return count == 1;}); printNumber(i); count = 2; cond_.notify_all(); } } ZeroEvenOdd2::ZeroEvenOdd2(int n) { this->n = n; odd_.test_and_set(); even_.test_and_set(); } void ZeroEvenOdd2::zero(function<void(int)> printNumber) { for (int i = 1; i <= n; ++i){ while (zero_.test_and_set()); printNumber(0); if (i % 2 != 0) odd_.clear(); else even_.clear(); } } void ZeroEvenOdd2::odd(function<void(int)> printNumber) { for (int i = 1; i <= n; i += 2){ while (odd_.test_and_set()); printNumber(i); zero_.clear(); } } void ZeroEvenOdd2::even(function<void(int)> printNumber) { for (int i = 2; i <= n; i += 2){ while (even_.test_and_set()); printNumber(i); zero_.clear(); } } ZeroEvenOdd3::ZeroEvenOdd3(int n) : count_(1) { this->n = n; st.store(State::ZERO_ODD, memory_order_relaxed); } void ZeroEvenOdd3::zero(function<void(int)> printNumber) { while(count_ <= n){ State s = st.load(memory_order_relaxed); if (s == State::ZERO_ODD || s == State::ZERO_EVEN) { printNumber(0); cout << count_ << endl; if (s == State::ZERO_ODD) st.store(ODD, memory_order_relaxed); else st.store(EVEN, memory_order_relaxed); } this_thread::yield(); } } void ZeroEvenOdd3::odd(function<void(int)> printNumber) { while (count_ <= n){ if (st.load(memory_order_relaxed) == State::ODD){ printNumber(count_++); st.store(ZERO_EVEN, memory_order_relaxed); } this_thread::yield(); } } void ZeroEvenOdd3::even(function<void(int)> printNumber) { while (count_ <= n){ if (st.load(memory_order_relaxed) == State::EVEN){ printNumber(count_++); st.store(ZERO_ODD, memory_order_relaxed); } this_thread::yield(); } } } // namespace vincent
true
9da4bf5674133d7b7f57cce5c84cbae5208cb1b2
C++
iridium-browser/iridium-browser
/buildtools/third_party/libc++/trunk/test/std/containers/sequences/vector/access.pass.cpp
UTF-8
3,656
2.859375
3
[ "NCSA", "LLVM-exception", "MIT", "Apache-2.0", "BSD-3-Clause" ]
permissive
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // <vector> // reference operator[](size_type __i); // const_reference operator[](size_type __i) const; // // reference at(size_type __i); // const_reference at(size_type __i) const; // // reference front(); // const_reference front() const; // // reference back(); // const_reference back() const; // libc++ marks these as 'noexcept' (except 'at') #include <vector> #include <cassert> #include <stdexcept> #include "min_allocator.h" #include "test_macros.h" template <class C> TEST_CONSTEXPR_CXX20 C make(int size, int start) { C c; for (int i = 0; i < size; ++i) c.push_back(start + i); return c; } template <class Vector> TEST_CONSTEXPR_CXX20 void test_get_basic(Vector& c, int start_value) { const int n = static_cast<int>(c.size()); for (int i = 0; i < n; ++i) assert(c[i] == start_value + i); for (int i = 0; i < n; ++i) assert(c.at(i) == start_value + i); #ifndef TEST_HAS_NO_EXCEPTIONS if (!TEST_IS_CONSTANT_EVALUATED) { try { TEST_IGNORE_NODISCARD c.at(n); assert(false); } catch (const std::out_of_range&) {} } #endif assert(c.front() == start_value); assert(c.back() == start_value + n - 1); } template <class Vector> TEST_CONSTEXPR_CXX20 void test_get() { int start_value = 35; Vector c = make<Vector>(10, start_value); const Vector& cc = c; test_get_basic(c, start_value); test_get_basic(cc, start_value); } template <class Vector> TEST_CONSTEXPR_CXX20 void test_set() { int start_value = 35; const int n = 10; Vector c = make<Vector>(n, start_value); for (int i = 0; i < n; ++i) { assert(c[i] == start_value + i); c[i] = start_value + i + 1; assert(c[i] == start_value + i + 1); } for (int i = 0; i < n; ++i) { assert(c.at(i) == start_value + i + 1); c.at(i) = start_value + i + 2; assert(c.at(i) == start_value + i + 2); } assert(c.front() == start_value + 2); c.front() = start_value + 3; assert(c.front() == start_value + 3); assert(c.back() == start_value + n + 1); c.back() = start_value + n + 2; assert(c.back() == start_value + n + 2); } template <class Vector> TEST_CONSTEXPR_CXX20 void test() { test_get<Vector>(); test_set<Vector>(); Vector c; const Vector& cc = c; ASSERT_SAME_TYPE(typename Vector::reference, decltype(c[0])); ASSERT_SAME_TYPE(typename Vector::const_reference, decltype(cc[0])); ASSERT_SAME_TYPE(typename Vector::reference, decltype(c.at(0))); ASSERT_SAME_TYPE(typename Vector::const_reference, decltype(cc.at(0))); ASSERT_SAME_TYPE(typename Vector::reference, decltype(c.front())); ASSERT_SAME_TYPE(typename Vector::const_reference, decltype(cc.front())); ASSERT_SAME_TYPE(typename Vector::reference, decltype(c.back())); ASSERT_SAME_TYPE(typename Vector::const_reference, decltype(cc.back())); } TEST_CONSTEXPR_CXX20 bool tests() { test<std::vector<int> >(); #if TEST_STD_VER >= 11 test<std::vector<int, min_allocator<int> > >(); test<std::vector<int, safe_allocator<int> > >(); #endif return true; } int main(int, char**) { tests(); #if TEST_STD_VER > 17 static_assert(tests()); #endif return 0; }
true
c22d8e68d9b7bf65978f77a6f9356f4e3ecd0197
C++
MuhammadFareed/C-Language-Programs
/Frequency of characters.cpp
UTF-8
329
2.6875
3
[]
no_license
#include<stdio.h> #include<conio.h> #include<string.h> int main() { int i,l,k,j=0,count=1; char s[20]; puts("Enter a word : "); gets(s); l=strlen(s); for(i=0;i<l;i++) { for(k=1;k<l;k++) { if(s[i]==s[k]) { count=count+1; } } printf("\nFreqency of %c is %d",s[i],count); j++; count=0; } getch(); }
true
14b135ea58f634234fa7ca0ad73d722dd54faabb
C++
SLIIT-FacultyOfComputing/tutorial-03b-IT21044786-1
/exercise01.cpp
UTF-8
418
3.15625
3
[]
no_license
#include<iostream> #include<iomanip> using namespace std; int main() { float marks[] ={78.4,90.6,45.9,72.2,54.4 }; char names[][20] = { "Ajith","Wimal","Kanthi","Suranji","Kushmitha" }; cout<<setw(5)<<"No"<<setw(15)<<"Name"<<setw(10)<<"Marks"<< endl; for (int r = 0; r < 5; r++) { cout<<setw(5)<<r + 1 << setw(15)<<names[r] << setw(10)<<marks[r] << endl; } }
true
63c68d3a4b99a2ad5274ab5287404c08b61a6e12
C++
htaozhang/cpp_common
/common/generic_time.h
UTF-8
3,237
2.703125
3
[]
no_license
// Copyright(c) 2017 macrozhang // All rights reserved. // // #ifndef __GENERIC_TIME_H__ #define __GENERIC_TIME_H__ #include "utils.h" #include <ctime> #if defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__) #include <iostream> #include <sstream> #include <iomanip> // std::get_time #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <winsock2.h> // struct timeval inline int gettimeofday(struct timeval * tp, struct timezone * tzp) { // Note: some broken versions only have 8 trailing zero's, the correct epoch has 9 trailing zero's // This magic number is the number of 100 nanosecond intervals since January 1, 1601 (UTC) // until 00:00:00 January 1, 1970 static const uint64_t EPOCH = ((uint64_t)116444736000000000ULL); SYSTEMTIME system_time; FILETIME file_time; uint64_t time; GetSystemTime(&system_time); SystemTimeToFileTime(&system_time, &file_time); time = ((uint64_t)file_time.dwLowDateTime); time += ((uint64_t)file_time.dwHighDateTime) << 32; tp->tv_sec = (long)((time - EPOCH) / 10000000L); tp->tv_usec = (long)(system_time.wMilliseconds * 1000); return 0; } inline char *strptime(const char *s, const char *format, struct tm *tm) { std::istringstream ss(s); ss.imbue(std::locale(setlocale(LC_ALL, NULL))); ss >> std::get_time(tm, format); return (ss.fail() ? NULL : const_cast<char*>(s + static_cast<int>(ss.tellg()))); } #define timegm _mkgmtime #define usleep(x) Sleep((x) / 1000) #else #include <sys/time.h> #endif inline utils::Null<> localtime_r(...) { return utils::Null<>(); } inline utils::Null<> localtime_s(...) { return utils::Null<>(); } inline utils::Null<> gmtime_r(...) { return utils::Null<>(); } inline utils::Null<> gmtime_s(...) { return utils::Null<>(); } inline std::tm localtime(std::time_t time) { struct LocalTime { std::time_t time_; std::tm tm_; LocalTime(std::time_t t) : time_(t) {} bool run() { return handle(localtime_r(&time_, &tm_)); } bool handle(std::tm *tm) { return tm != NULL; } bool handle(utils::Null<>) { return fallback(localtime_s(&tm_, &time_)); } bool fallback(int res) { return res == 0; } bool fallback(utils::Null<>){ std::tm *tm = std::localtime(&time_); return tm == NULL ? false : (tm_ = *tm, true); } }; LocalTime lt(time); return lt.run() ? lt.tm_ : std::tm(); } inline std::tm gmtime(std::time_t time) { struct GMTime { std::time_t time_; std::tm tm_; GMTime(std::time_t t) : time_(t) {} bool run() { return handle(gmtime_r(&time_, &tm_)); } bool handle(std::tm *tm) { return tm != NULL; } bool handle(utils::Null<>) { return fallback(gmtime_s(&tm_, &time_)); } bool fallback(int res) { return res == 0; } bool fallback(utils::Null<>){ std::tm *tm = std::gmtime(&time_); return tm == NULL ? false : (tm_ = *tm, true); } }; GMTime gt(time); return gt.run() ? gt.tm_ : std::tm(); } #endif /* __GENERIC_TIME_H__ */
true
b6ca6fb9cfb861fa27f47b4ec4d0184310896d83
C++
Totomosic/Anarchy
/Anarchy-Client/src/World/TilemapRenderer.cpp
UTF-8
2,260
2.5625
3
[]
no_license
#include "clientpch.h" #include "TilemapRenderer.h" #include "Tilemap.h" namespace Anarchy { TilemapRenderer::TilemapRenderer(Layer* layer, float tileWidth, float tileHeight) : m_Layer(layer), m_TileWidth(tileWidth), m_TileHeight(tileHeight), m_Chunks() { } float TilemapRenderer::GetTileWidth() const { return m_TileWidth; } float TilemapRenderer::GetTileHeight() const { return m_TileHeight; } void TilemapRenderer::SetTileWidth(float width) { m_TileWidth = width; Invalidate(); } void TilemapRenderer::SetTileHeight(float height) { m_TileHeight = height; Invalidate(); } void TilemapRenderer::DrawChunk(const Vector2i& chunkIndex, const TileChunk* chunk) { Mesh mesh; std::unordered_map<Color, int> materialIndices; for (int x = 0; x < chunk->GetWidth(); x++) { for (int y = 0; y < chunk->GetHeight(); y++) { int index = x + y * chunk->GetWidth(); TileType tile = chunk->GetTiles()[index]; Color c; switch (tile) { case TileType::Grass: c = Color(20, 160, 25); break; case TileType::Sand: c = Color(255, 225, 50); break; case TileType::Water: c = Color(0, 20, 150); break; default: c = Color::Black; break; } int materialIndex = 0; if (materialIndices.find(c) != materialIndices.end()) { materialIndex = materialIndices[c]; } else { materialIndex = mesh.Materials.size(); mesh.Materials.push_back(ResourceManager::Get().Materials().Default(c)); materialIndices[c] = materialIndex; } mesh.Models.push_back({ ResourceManager::Get().Models().Square(), Matrix4f::Translation(x, y, 0), { materialIndex } }); } } float xoffset = (chunk->GetX());// *GetTileWidth(); float yoffset = (chunk->GetY());// *GetTileHeight(); EntityHandle entity = m_Layer->GetFactory().CreateMesh(std::move(mesh), Transform({ xoffset, yoffset, 0.0f })); m_Chunks[chunkIndex] = { chunk, entity }; } void TilemapRenderer::DestroyChunk(const Vector2i& chunk) { if (m_Chunks.find(chunk) != m_Chunks.end()) { EntityHandle entity = m_Chunks[chunk].Entity; if (entity) { entity.Destroy(); } m_Chunks.erase(chunk); } } void TilemapRenderer::Invalidate() { } }
true
a4e5e10003b883aa855fd6e4791e11b76bbc79ce
C++
FaridaSolimann/313Project-1
/solving_root_methods.h
UTF-8
21,162
2.96875
3
[]
no_license
#ifndef INC_313PROJECT_1_SOLVING_ROOT_METHODS_H #define INC_313PROJECT_1_SOLVING_ROOT_METHODS_H #include <iostream> #include <math.h> void bisection(int EQ_i, int iters, float percent, int stopping_cond); void false_position(int EQ_i, int iters, double percent, int stopping_condition); void secant(int EQ_i, int iters, double percent, int stopping_condition); void newton_raphson(int EQ_i, int iters, double percent, int stopping_condition); void bisection(int equation, int iterations, float percent, int stopping_cond) { double f_upper, f_lower, xr, fr; double x_upper, x_lower; long double error = 100; double xr_old; int i = 0; long double _6_func_xl, _6_func_xu, _6_func_xr, _6_xr = 0.0, _6_xr_old = 0.0, _6_xu, _6_xl; double long y; std::cout << "Enter X lower value: "; std::cin >> x_lower; std::cout << "Enter X upper value: "; std::cin >> x_upper; switch (equation) { case 1: while ((stopping_cond == 1 && i < iterations) || (stopping_cond == 2 && error > percent)) { f_upper = pow(x_upper, 3) - 8 * pow(x_upper, 2) + 12 * x_upper - 4; f_lower = pow(x_lower, 3) - 8 * pow(x_lower, 2) + 12 * x_lower - 4; if (f_lower * f_upper > 0) { std::cout << "initial upper and lower limits are incorrect" << std::endl; return; ///CHANGE? } if (i > 0) xr_old = xr; xr = (x_upper + x_lower) / 2; fr = pow(xr, 3) - 8 * pow(xr, 2) + 12 * xr - 4; if (f_lower * fr < 0) x_upper = xr; else x_lower = xr; if (i > 0) error = fabs((xr - xr_old) / xr) * 100; i++; } printf("[Bisection] Method -> Xr: %f | iterations: %d | relative error: %Lf%% \n", xr, i, error); break; case 2: //"2. f(x) = -12 -21x +18x^2 - 2.75x^3 " while ((stopping_cond == 1 && i < iterations) || (stopping_cond == 2 && error > percent)) { f_upper = -12 - 21 * x_upper + 18 * pow(x_upper, 2) - 2.75 * pow(x_upper, 3); f_lower = -12 - 21 * x_lower + 18 * pow(x_lower, 2) - 2.75 * pow(x_lower, 3); if (f_lower * f_upper > 0) { std::cout << "initial upper and lower limits are incorrect" << std::endl; return; ///CHANGE? } if (i > 0) xr_old = xr; xr = (x_upper + x_lower) / 2; fr = -12 - 21 * xr + 18 * pow(xr, 2) - 2.75 * pow(xr, 3); if (f_lower * fr < 0) x_upper = xr; else x_lower = xr; if (i > 0) error = fabs((xr - xr_old) / xr) * 100; i++; } printf("[Bisection] Method -> Xr: %f | iterations: %d | relative error: %Lf%% \n", xr, i, error); break; case 3: //"3. f(x) = 6x -4x^2 + 0.5x^3 -2 " while ((stopping_cond == 1 && i < iterations) || (stopping_cond == 2 && error > percent)) { f_upper = 6 * x_upper - 4 * pow(x_upper, 2) + 0.5 * pow(x_upper, 3) - 2; f_lower = 6 * x_lower - 4 * pow(x_lower, 2) + 0.5 * pow(x_lower, 3) - 2; if (f_lower * f_upper > 0) { std::cout << "initial upper and lower limits are incorrect" << std::endl; return; ///CHANGE? } if (i > 0) xr_old = xr; xr = (x_upper + x_lower) / 2; fr = 6 * xr - 4 * pow(xr, 2) + 0.5 * pow(xr, 3) - 2; if (f_lower * fr < 0) x_upper = xr; else x_lower = xr; if (i > 0) error = fabs((xr - xr_old) / xr) * 100; i++; } printf("[Bisection] Method -> Xr: %f | iterations: %d | relative error: %Lf%% \n", xr, i, error); break; case 4: while ((stopping_cond == 1 && i < iterations) || (stopping_cond == 2 && error > percent)) { f_upper = log(pow(x_upper, 4)) - 0.7; f_lower = log(pow(x_lower, 4)) - 0.7; if (f_lower * f_upper > 0) { std::cout << "initial upper and lower limits are incorrect" << std::endl; return; ///CHANGE? } if (i > 0) xr_old = xr; xr = (x_upper + x_lower) / 2; fr = log(pow(xr, 4)) - 0.7; if (f_lower * fr < 0) x_upper = xr; else x_lower = xr; if (i > 0) error = fabs((xr - xr_old) / xr) * 100; i++; } printf("[Bisection] Method -> Xr: %f | iterations: %d | relative error: %Lf%% \n", xr, i, error); break; case 6: //dy/dx = (-5/216000x^4 + x^2 - 60000) _6_xu = x_upper; _6_xl = x_lower; while ((stopping_cond == 1 && i < iterations) || (stopping_cond == 2 && error > percent)) { _6_func_xl = (-5.0 / 2160000) * powl(_6_xl, 4) + powl(_6_xl, 2) - (60000); _6_func_xu = (-5.0 / 2160000) * powl(_6_xu, 4) + powl(_6_xu, 2) - (60000); if (_6_func_xl * _6_func_xu > 0) { std::cout << "initial upper and lower limits are incorrect" << std::endl; return; ///CHANGE? } if (i > 0) _6_xr_old = _6_xr; _6_xr = (_6_xu + _6_xl) / 2.0; _6_func_xr = (-5.0 / 2160000) * powl(_6_xr, 4) + powl(_6_xr, 2) - (60000); if (_6_func_xl * _6_func_xr < 0.0) _6_xu = _6_xr; else _6_xl = _6_xr; if (i > 0) error = fabsl((_6_xr - _6_xr_old) / _6_xr) * 100.0; i++; } // y = (Wo/120EIL)(-x^5 + 2L^2x^3 - L^4x) y = ((2.5) / (50000 * 30000 * 600 * 120)) * ((-1.0 / 720000) * powl(_6_xr, 5) + powl(_6_xr, 3) - (180000 * _6_xr)); printf("[Bisection] Method -> Xr: %Lf | iterations: %d | relative error: %Lf%% \n", _6_xr, i, error); break; default: //"5. 7 sin(x) = e^x " while ((stopping_cond == 1 && i < iterations) || (stopping_cond == 2 && error > percent)) { f_upper = 7 * sin(x_upper) - exp(x_upper); f_lower = 7 * sin(x_lower) - exp(x_lower); if (f_lower * f_upper > 0) { std::cout << "initial upper and lower limits are incorrect" << std::endl; return; ///CHANGE? } if (i > 0) xr_old = xr; xr = (x_upper + x_lower) / 2; fr = 7 * sin(xr) - exp(xr); if (f_lower * fr < 0) x_upper = xr; else x_lower = xr; if (i > 0) error = fabs((xr - xr_old) / xr) * 100; i++; } printf("[Bisection] Method -> Xr: %f | iterations: %d | relative error: %Lf%% \n", xr, i, error); break; } } void false_position(int EQ_i, int iters, double percent, int stopping_condition) { int i = 0; double x_l, x_u; double func_xl, func_xu, func_xr, xr = 0.0, xr_old = 0.0; long double root_error = 100.0; std::cout << "Enter X lower value: "; std::cin >> x_l; std::cout << "Enter X upper value: "; std::cin >> x_u; switch (EQ_i) { case 1: //f(x) = X^3 - 8X^2 + 12X - 4 while ((i < iters and stopping_condition == 1) or (root_error > percent and stopping_condition == 2)) { //False-Position equation. func_xl = pow(x_l, 3) - 8 * pow(x_l, 2) + 12 * x_l - 4; func_xu = pow(x_u, 3) - 8 * pow(x_u, 2) + 12 * x_u - 4; xr = x_u - ((func_xu * (x_l - x_u))) / (func_xl - func_xu); func_xr = pow(xr, 3) - 8 * pow(xr, 2) + 12 * xr - 4; // Check region where root lies. f(xl)f(xr) < 0 then xu = xr func_xl * func_xr < 0.0 ? x_u = xr : x_l = xr; if (i > 0) root_error = fabs(((xr - xr_old) / xr) * 100); xr_old = xr; i++; } printf("[False Position] Method -> Xr: %f | iterations: %d | relative error: %Lf%% \n", xr, i, root_error); break; case 2: //f(x) = -12 -21x +18x^2 - 2.75x^3 while ((i < iters and stopping_condition == 1) or (root_error > percent and stopping_condition == 2)) { //False-Position equation. func_xl = -12 - 21 * x_l + 18 * pow(x_l, 2) - 2.75 * pow(x_l, 3); func_xu = -12 - 21 * x_u + 18 * pow(x_u, 2) - 2.75 * pow(x_u, 3); xr = x_u - ((func_xu * (x_l - x_u))) / (func_xl - func_xu); func_xr = -12 - 21 * xr + 18 * pow(xr, 2) - 2.75 * pow(xr, 3); // Check region where root lies. f(xl)f(xr) < 0 then xu = xr func_xl * func_xr < 0.0 ? x_u = xr : x_l = xr; if (i > 0) root_error = fabs(((xr - xr_old) / xr) * 100); xr_old = xr; i++; } printf("[False Position] Method -> Xr: %f | iterations: %d | relative error: %Lf%% \n", xr, i, root_error); break; case 3: //f(x) = 6x -4x^2 + 0.5x^3 -2 while ((i < iters and stopping_condition == 1) or (root_error > percent and stopping_condition == 2)) { //False-Position equation. func_xl = 6 * x_l - 4 * pow(x_l, 2) + 0.5 * pow(x_l, 3) - 2; func_xu = 6 * x_u - 4 * pow(x_u, 2) + 0.5 * pow(x_u, 3) - 2; xr = x_u - ((func_xu * (x_l - x_u))) / (func_xl - func_xu); func_xr = 6 * xr - 4 * pow(xr, 2) + 0.5 * pow(xr, 3) - 2; // Check region where root lies. f(xl)f(xr) < 0 then xu = xr func_xl * func_xr < 0.0 ? x_u = xr : x_l = xr; if (i > 0) root_error = fabs(((xr - xr_old) / xr) * 100); xr_old = xr; i++; } printf("[False Position] Method -> Xr: %f | iterations: %d | relative error: %Lf%% \n", xr, i, root_error); break; case 4: //ln(x^4) = 0.7 while ((i < iters and stopping_condition == 1) or (root_error > percent and stopping_condition == 2)) { //False-Position equation. func_xl = log(pow(x_l, 4)) - 0.7; func_xu = log(pow(x_u, 4)) - 0.7; xr = x_u - ((func_xu * (x_l - x_u))) / (func_xl - func_xu); func_xr = log(pow(xr, 4)) - 0.7; // Check region where root lies. f(xl)f(xr) < 0 then xu = xr func_xl * func_xr < 0.0 ? x_u = xr : x_l = xr; if (i > 0) root_error = fabs(((xr - xr_old) / xr) * 100); xr_old = xr; i++; } printf("[False Position] Method -> Xr: %f | iterations: %d | relative error: %Lf%% \n", xr, i, root_error); break; case 5: //7sin(x) = e^x while ((i < iters and stopping_condition == 1) or (root_error > percent and stopping_condition == 2)) { //False-Position equation. func_xl = 7 * sin(x_l) - exp(x_l); func_xu = 7 * sin(x_u) - exp(x_u); xr = x_u - ((func_xu * (x_l - x_u))) / (func_xl - func_xu); func_xr = 7 * sin(xr) - exp(xr); // Check region where root lies. f(xl)f(xr) < 0 then xu = xr func_xl * func_xr < 0.0 ? x_u = xr : x_l = xr; if (i > 0) root_error = fabs(((xr - xr_old) / xr) * 100); xr_old = xr; i++; } printf("[False Position] Method -> Xr: %f | iterations: %d | relative error: %Lf%% \n", xr, i, root_error); break; default: std::cout << "Default" << std::endl; break; } } void secant(int EQ_i, int iters, double percent, int stopping_condition) { int i = 0; double x_i_0, x_i_1; double func_xi0, func_xi1, x_i_2 = 0.0; long double root_error = 100.0; std::cout << "Enter first initial guess (Xo): "; std::cin >> x_i_0; std::cout << "Enter second initial guess (x1): "; std::cin >> x_i_1; switch (EQ_i) { case 1: //f(x) = X^3 - 8X^2 + 12X - 4 while ((i < iters and stopping_condition == 1) or (root_error > percent and stopping_condition == 2)) { func_xi0 = pow(x_i_0, 3) - 8 * pow(x_i_0, 2) + 12 * x_i_0 - 4; func_xi1 = pow(x_i_1, 3) - 8 * pow(x_i_1, 2) + 12 * x_i_1 - 4; //Secant equation. x_i_2 = x_i_1 - ((func_xi1 * (x_i_0 - x_i_1))) / (func_xi0 - func_xi1); root_error = fabs(((x_i_2 - x_i_1) / x_i_2) * 100); x_i_0 = x_i_1; x_i_1 = x_i_2; i++; } printf("[Secant] Method -> Xi2: %f | iterations: %d | relative error: %Lf%% \n", x_i_2, i, root_error); break; case 2: //f(x) = -12 -21x +18x^2 - 2.75x^3 while ((i < iters and stopping_condition == 1) or (root_error > percent and stopping_condition == 2)) { func_xi0 = -12 - 21 * x_i_0 + 18 * pow(x_i_0, 2) - 2.75 * pow(x_i_0, 3); func_xi1 = -12 - 21 * x_i_1 + 18 * pow(x_i_1, 2) - 2.75 * pow(x_i_1, 3); //Secant equation. x_i_2 = x_i_1 - ((func_xi1 * (x_i_0 - x_i_1))) / (func_xi0 - func_xi1); root_error = fabs(((x_i_2 - x_i_1) / x_i_2) * 100); x_i_0 = x_i_1; x_i_1 = x_i_2; i++; } printf("[Secant] Method -> Xi2: %f | iterations: %d | relative error: %Lf%% \n", x_i_2, i, root_error); break; case 3: //f(x) = 6x -4x^2 + 0.5x^3 -2 while ((i < iters and stopping_condition == 1) or (root_error > percent and stopping_condition == 2)) { func_xi0 = 6 * x_i_0 - 4 * pow(x_i_0, 2) + 0.5 * pow(x_i_0, 3) - 2; func_xi1 = 6 * x_i_1 - 4 * pow(x_i_1, 2) + 0.5 * pow(x_i_1, 3) - 2; //Secant equation. x_i_2 = x_i_1 - ((func_xi1 * (x_i_0 - x_i_1))) / (func_xi0 - func_xi1); root_error = fabs(((x_i_2 - x_i_1) / x_i_2) * 100); x_i_0 = x_i_1; x_i_1 = x_i_2; i++; } printf("[Secant] Method -> Xi2: %f | iterations: %d | relative error: %Lf%% \n", x_i_2, i, root_error); break; case 4: //ln(x^4) = 0.7 while ((i < iters and stopping_condition == 1) or (root_error > percent and stopping_condition == 2)) { func_xi0 = log(pow(x_i_0, 4)) - 0.7; func_xi1 = log(pow(x_i_1, 4)) - 0.7; //Secant equation. x_i_2 = x_i_1 - ((func_xi1 * (x_i_0 - x_i_1))) / (func_xi0 - func_xi1); root_error = fabs(((x_i_2 - x_i_1) / x_i_2) * 100); x_i_0 = x_i_1; x_i_1 = x_i_2; i++; } printf("[Secant] Method -> Xi2: %f | iterations: %d | relative error: %Lf%% \n", x_i_2, i, root_error); break; case 5: //7sin(x) = e^x while ((i < iters and stopping_condition == 1) or (root_error > percent and stopping_condition == 2)) { func_xi0 = 7 * sin(x_i_0) - exp(x_i_0); func_xi1 = 7 * sin(x_i_1) - exp(x_i_1); //Secant equation. x_i_2 = x_i_1 - ((func_xi1 * (x_i_0 - x_i_1))) / (func_xi0 - func_xi1); root_error = fabs(((x_i_2 - x_i_1) / x_i_2) * 100); x_i_0 = x_i_1; x_i_1 = x_i_2; i++; } printf("[Secant] Method -> Xi2: %f | iterations: %d | relative error: %Lf%% \n", x_i_2, i, root_error); break; default: std::cout << "Default" << std::endl; break; } } void newton_raphson(int EQ_i, int iters, double percent, int stopping_condition) { int i = 0; double x_i_1; double func_xi1, dx_func_xi1, x_i_2 = 0.0; long double root_error = 100.0; std::cout << "Enter initial guess: "; std::cin >> x_i_1; switch (EQ_i) { case 1: // f(x) = X^3 - 8X^2 + 12X - 4 // f'(x) = 3X^2 - 16X + 12 while ((i < iters and stopping_condition == 1) or (root_error > percent and stopping_condition == 2)) { func_xi1 = (pow(x_i_1, 3)) - (8 * pow(x_i_1, 2)) + (12 * x_i_1) - 4; dx_func_xi1 = (3 * pow(x_i_1, 2)) - (16 * x_i_1) + 12; //Newton-Raphson equation. x_i_2 = x_i_1 - (func_xi1 / dx_func_xi1); root_error = fabs(((x_i_2 - x_i_1) / x_i_2) * 100); x_i_1 = x_i_2; i++; } printf("[Newton-Raphson] Method -> Xi2: %f | iterations: %d | relative error: %Lf%% \n", x_i_2, i, root_error); break; case 2: // f(x) = -12 -21x +18x^2 - 2.75x^3 // f'(x) = -21 + 36x - 8.25x^2 while ((i < iters and stopping_condition == 1) or (root_error > percent and stopping_condition == 2)) { func_xi1 = -12 - 21 * x_i_1 + 18 * pow(x_i_1, 2) - 2.75 * pow(x_i_1, 3); dx_func_xi1 = -21 + 36 * x_i_1 - 8.25 * pow(x_i_1, 2); //Newton-Raphson equation. x_i_2 = x_i_1 - (func_xi1 / dx_func_xi1); root_error = fabs(((x_i_2 - x_i_1) / x_i_2) * 100); x_i_1 = x_i_2; i++; } printf("[Newton-Raphson] Method -> Xi2: %f | iterations: %d | relative error: %Lf%% \n", x_i_2, i, root_error); break; case 3: // f(x) = 6x -4x^2 + 0.5x^3 -2 // f'(x) = 6 - 8x + 1.5x^2 while ((i < iters and stopping_condition == 1) or (root_error > percent and stopping_condition == 2)) { func_xi1 = 6 * x_i_1 - 4 * pow(x_i_1, 2) + 0.5 * pow(x_i_1, 3) - 2; dx_func_xi1 = 6 - 8 * x_i_1 + 1.5 * pow(x_i_1, 2); //Newton-Raphson equation. x_i_2 = x_i_1 - (func_xi1 / dx_func_xi1); root_error = fabs(((x_i_2 - x_i_1) / x_i_2) * 100); x_i_1 = x_i_2; i++; } printf("[Newton-Raphson] Method -> Xi2: %f | iterations: %d | relative error: %Lf%% \n", x_i_2, i, root_error); break; case 4: // f(x) = ln(x^4) - 0.7 // f'(x) = 4/x; while ((i < iters and stopping_condition == 1) or (root_error > percent and stopping_condition == 2)) { func_xi1 = log(pow(x_i_1, 4)) - 0.7; dx_func_xi1 = 4.0 / x_i_1; //Newton-Raphson equation. x_i_2 = x_i_1 - (func_xi1 / dx_func_xi1); root_error = fabs(((x_i_2 - x_i_1) / x_i_2) * 100); x_i_1 = x_i_2; i++; } printf("[Newton-Raphson] Method -> Xi2: %f | iterations: %d | relative error: %Lf%% \n", x_i_2, i, root_error); break; case 5: // f(x) = 7sin(x) - e^x // f'(x) = 7cos(x) - e^x while ((i < iters and stopping_condition == 1) or (root_error > percent and stopping_condition == 2)) { func_xi1 = 7 * sin(x_i_1) - exp(x_i_1); dx_func_xi1 = 7 * cos(x_i_1) - exp(x_i_1); //Newton-Raphson equation. x_i_2 = x_i_1 - (func_xi1 / dx_func_xi1); root_error = fabs(((x_i_2 - x_i_1) / x_i_2) * 100); x_i_1 = x_i_2; i++; } printf("[Newton-Raphson] Method -> Xi2: %f | iterations: %d | relative error: %Lf%% \n", x_i_2, i, root_error); break; default: std::cout << "Default" << std::endl; break; } } #endif //INC_313PROJECT_1_SOLVING_ROOT_METHODS_H
true
e8f9b4f4f4299b2878de428ffc4f9827eb9ddc88
C++
Lazymonter/LeetCode
/231-2的幂.cpp
UTF-8
393
3.6875
4
[]
no_license
/* 2的幂的二进制表示中只有一个1 */ #include <iostream> using namespace std; bool isPowerOfTwo(int n) { return n > 0 && (n & (n - 1)) == 0; } int main() { cout << isPowerOfTwo(1) << endl; cout << isPowerOfTwo(2) << endl; cout << isPowerOfTwo(3) << endl; cout << isPowerOfTwo(5) << endl; cout << isPowerOfTwo(-1) << endl; return 0; }
true
ef0390681575c85aa291754e0dbedb99c51c2d9b
C++
Dev-DarkWolf/Custom-Library
/Custom Library/Containers/ObjectPool.h
UTF-8
4,098
3.015625
3
[]
no_license
//---------------------------------------- //File Name: ObjectPool.h //Author: Trent Manks //------------------------------------------ //Copyright 2017 - DarkWolf Interactive //------------------------------------------ //------------------------------------------ // OBJECT POOLING // Holds Objects To Be Reused When Drawing // And Using In-Game. Prevents The 'new' & // 'delete' Function Being Called While // Player Is In Game. //------------------------------------------ // OffScreen // --- * // | * // | * // | * // Reuse | * <--- Objects/BUllets // | * // | * // --- * // <T> <--- Ship/Gun // //------------------------------------------ // http://best-practice-software-engineering.ifs.tuwien.ac.at/patterns/objectpool.html //------------------------------------------ #pragma once #include "DynamicArray.h" namespace wolf { //-------------------------------------------------- //----------Remove Template Pointer - STRUCT-------- //-------------------------------------------------- template <typename T> struct remove_pointer { typedef T type; }; template <typename T> struct remove_pointer<T*> { typedef T type; }; //-------------------------------------------------- //---------------ObjectPool - CLASS----------------- //-------------------------------------------------- template <typename T> class ObjectPool { public: //-------------------------------------------------- // --- Constructor --- //-------------------------------------------------- // Set 'm_nPoolSize' As 'nPoolSize' // Create Two Dynamic Arrays For Storing Objetcs // 'm_availablePool' = Objects That Aren't Being Used // 'm_used' = Objects That Are Being Used // // Loop Though For The Size Of 'nPoolSize' // Create 'new' Templated Object // 'Push' That Object Into 'm_avaliable' Array //-------------------------------------------------- ObjectPool(int nPoolSize) { m_nPoolSize = nPoolSize; m_availablePool = new wolf::DynamicArray(nPoolSize); m_usedPool = new wolf::DynamicArray(nPoolSize); for (int i = 0; i < nPoolSize; i++) { typedef typename remove_pointer<T>::type type; T object = new type; m_availablePool->Push(object); } } //-------------------------------------------------- // --- Deconstructor --- //-------------------------------------------------- // For Each Object In 'm_avaliable' // 'delete' Object // For Each Object In 'm_used' // 'delete' Object //-------------------------------------------------- ~ObjectPool() { for (int i = 0; i < m_availablePool->Size(); i++) { delete m_availablePool[i]; } for (int i = 0; i < m_usedPool->Size(); i++) { delete m_usedPool[i]; } } //-------------------------------------------------- // --- Use To Return Object In Pool To Use --- //-------------------------------------------------- // Define 'Allocate' // Set 'object' As Popped Object In 'm_availablePool' // Push 'object' Into 'm_usedPool' // Return 'object' //-------------------------------------------------- T Allocate() { T object = m_availablePool->Pop(); m_usedPool->Push(object); return object; } //-------------------------------------------------- // --- Use To Return Object In Pool To Use --- //-------------------------------------------------- // Define 'DeAllocate(T objectToFind)' // FindAndDestroy 'objectToFind' In 'm_usedPool' // Push 'objectToFind' Into 'm_availiablePool' //-------------------------------------------------- void DeAllocate(T objectToFind) { m_usedPool->FindAndDestroy(objectToFind); m_availablePool->Push(objectToFind) } int Size() { return m_nPoolSize; } private: wolf::DynamicArray<T>* m_availablePool; wolf::DynamicArray<T>* m_usedPool; int m_nPoolSize; }; }//END NAMESPACE
true
b058fc55106d0001dec7cd216c480ae916ffbb05
C++
bigfatwhale/orderbook
/cpp/OrderBookPythonAPI.cpp
UTF-8
1,751
2.53125
3
[]
no_license
#include "Python.h" #include "Order.h" #include "OrderBook.hpp" #include "PriceBucket.h" #include <ostream> #include <string> #include <boost/python.hpp> using namespace boost::python; void export_orderbook() { class_< LimitOrderBook<>, boost::noncopyable >("LimitOrderBook") .def(init<>()) .def("addOrder", &LimitOrderBook<>::addOrder ) .def("removeOrder", &LimitOrderBook<>::removeOrder ) .def("volumeForPricePoint", &LimitOrderBook<>::volumeForPricePoint ) .def("bestBid", &LimitOrderBook<>::bestBid ) .def("bestAsk", &LimitOrderBook<>::bestAsk ) .add_property("bids", range(&LimitOrderBook<>::bids_begin, &LimitOrderBook<>::bids_end)) .add_property("asks", range(&LimitOrderBook<>::asks_begin, &LimitOrderBook<>::asks_end)) ; } void export_booktype() { enum_<BookType>("BookType") .value("BUY", BookType::BUY) .value("SELL", BookType::SELL) ; } void export_price_bucket() { class_<PriceBucket>("PriceBucket") .def(init<>()) .def(init<uint64_t>()) .def("__iter__", range(&PriceBucket::begin, &PriceBucket::end)) .def_readwrite("pricePoint", &PriceBucket::m_pricePoint) ; } void export_order() { class_<Order>("Order") .def(init<>()) .def(init<uint64_t, uint64_t, uint32_t, BookType, uint32_t>()) .def_readwrite("orderId", &Order::orderId) .def_readwrite("price", &Order::price) .def_readwrite("volume", &Order::volume) .def_readwrite("side", &Order::side) .def_readwrite("partId", &Order::partId) ; } BOOST_PYTHON_MODULE(orderbook_api) { PyEval_InitThreads(); // need this to mess around with GIL export_orderbook(); export_order(); export_booktype(); export_price_bucket(); }
true
8c6a9641c25e831996431ae936da03816ecc099b
C++
grain1101/LeetCode
/C++/237_DeleteNodeInALinkedList.cpp
UTF-8
379
2.59375
3
[]
no_license
#include "leetcode.h" class Solution { public: // 237. Delete Node in a Linked List void deleteNode(ListNode* node) { node->val = node->next->val; node->next = node->next->next; } }; int main() { Solution s1; int n = 3; auto ans = s1.isPalindrome(nullptr); cout << ans << endl; //showV(ans); //show(ans); //showV(ans); }
true
2fcd493267b826aaa7e3620bb6f2b2c84ae30b48
C++
hjung3113/multicore
/project3/serial.cpp
UTF-8
3,489
2.59375
3
[]
no_license
#include <cstdlib> #include <cstdio> #include <iostream> #include <unistd.h> #include <fstream> #include <string> #include <sstream> #include <vector> #include <queue> #define BUFSIZE 100 using namespace std; bool **board; int NumGenerate; int lx, ly; char buf[100]; queue <pair<int, int>> lives; void printboard(){ /* for(int i=1;i<=ly;i++){ for(int j=1; j<=lx; j++){ if(board[j][i] == false) printf(". "); else printf("0 "); } printf("\n"); }*/ printf("\n"); for(int i=1; i<=ly; i++){ for(int j=1; j<=lx;j++){ if(board[j][i] == false) continue; else printf("%d %d\n", j-1,i-1); } } } void updateboard(){ bool backup[lx+2][ly+2] = {}; bool visit[lx+2][ly+2] = {}; for(int i=1;i<ly+1;i++){ for(int j=1; j<lx+1; j++){ if(board[j][i] == true) backup[j][i] = true; } } // for(int i=1;i<ly+1;i++){ // for(int j=1; j<lx+1; j++){ // } // } int nlives = lives.size(); while(nlives--){ pair<int, int> cur = lives.front(); lives.pop(); int x,y; x=cur.first; y=cur.second; // printf("out x: %d, y:%d\n", x, y); for(int a=y-1; a<=y+1; a++){ if(a<1 || a>ly) continue; for(int b=x-1; b<=x+1; b++){ if(b<1 || b>lx) continue; if(visit[b][a] == true) continue; visit[b][a] = true; int alive = 0; for(int c=-1; c<=1; c++){ for(int d=-1; d<=1; d++){ if(c==0 && d==0) continue; if(backup[b+d][a+c] == true) alive++; } } // printf("x : %d, y : %d, alive : %d\n", b, a, alive); if(backup[b][a] == true){ if(alive < 2) board[b][a] = false; if(alive > 3) board[b][a] = false; else{ lives.push(make_pair(b,a)); } }else{ if(alive == 3) { board[b][a] = true; lives.push(make_pair(b,a)); } } } } } } int main(int argc, char* argv[]) { if(argc != 5){ fprintf(stderr, "usage : exe file ng limit_x limity\n"); exit(1); } string filename(argv[1]); NumGenerate = atoi(argv[2]); int iter = NumGenerate; lx = atoi(argv[3]); ly = atoi(argv[4]); // bool board[lx+2][ly+2] = {}; board = (bool **)calloc(sizeof(bool*), lx+2); for(int i=0;i<lx+2;i++){ board[i] = (bool*)calloc(sizeof(bool), ly+2); } // printf("%d %d\n", lx, ly); ifstream readfile(filename); if(readfile.is_open()){ string line, _x, _y; while(getline(readfile, line)){ int x,y; stringstream _s(line); getline(_s, _x, ' '); getline(_s, _y, ' '); x = stoi(_x); y = stoi(_y); board[x+1][y+1] = true; // printf("in x: %d, y: %d\n", x+1, y+1); lives.push(make_pair(x+1,y+1)); } }else { fprintf(stderr, "err : nofile\n"); exit(1); } while(iter--){ // printboard(); updateboard(); usleep(200000); } printboard(); for(int i=0;i<lx+2;i++) free(board[i]); free(board); return 0; }
true
bc5e5fe1b9b3a560320e1e66ce8b4c4e2fc71947
C++
mungowz/MaximumGraphPath
/Island.hpp
UTF-8
2,739
3.234375
3
[ "MIT" ]
permissive
/* La classe Island produrrà il grafo in base agli input forniti dal file e permetterà l'interazione utente programma. La classe Island ha un rapporto di tipo HAS A con la classe Graph, tra gli attributi privati è istanziata una variabile di tipo Graph , che rappresenta il grafo letto in input. La lettura del file avviene il costruttore della classe Island, a questo viene passato il nome del file da leggere sotto forma di stringa. Tramite il parametro in di tipo ifstream apre il file mediante il metodo open, verificherà inoltre se la sua apertura avviene in modo corretto mediante il metodo fail. In caso di errore viene prodotto dal programma un messaggio diagnostico di errore. I primi due numeri interi del file corrispondono al numero di nodi ed al numero di archi del grafo. Tramite l'operatore di flusso >> questi passano da in per essere memorizzati in numVertex e numEdges. Vengono aggiunti poi i nodi con chiave da 0 ad N-1 (NumVertex-1), sapendo il numero totale di vertici, come espresso dalla traccia, questi saranno identificati dalle chiavi che vanno da 0 ad N-1. Ogni riga dopo la prima contiene tre numeri interi che corrispondono rispettivamente a: il nodo di partenza, il nodo di arrivo, e il peso. Questi vengono salvati nelle varibili node, adj e weight. Tramite al metodo setItemNode assegneremo al nodo in posizione node, l'adiacenza del nodo adj con un peso weight. Viene scelto di usare una classe ulteriore specifica per il problema in modo da garantire la massima "sicurezza" alla struttura del grafo letto in input, in questo modo infatti l'utente non potra modificarla, ma potrà solamente interagire con essa tramite i metodi che la classe Island richiama sul grafo letto in input. */ #ifndef Island_hpp #define Island_hpp #include <fstream> #include <string> #include <stack> #include "Graph.cpp" class Island { private: ifstream in; Graph graph; public: /* Costruttore della classe Island. */ Island(string nameFile); /* Distruttore della classe Island */ ~Island(){}; /* Metodo che richiamando il metodo get_numVertex del grafo valorizza il numero di vertici. */ int getNumVertex(){graph.get_numVertex();}; /* Metodo che richiamando il metodo get_numEdges del grafo valorizza il numero di archi. */ int getNumEdges(){graph.get_numEdges();}; /* Metodo che richiamando il metodo MaxWeightPath del grafo calcolando il cammino massimo. */ void maxWay(int i){this->graph.MaxWeightPath(i);}; }; #endif /* Island_hpp */
true
1385984e136f641891009ec6e435db758e929b32
C++
Isa-rentacs/AOJ
/0212.cpp
UTF-8
1,710
2.796875
3
[]
no_license
#include <iostream> #include <queue> #include <algorithm> #include <cstring> #include <vector> #define INF 1 << 29 using namespace std; int c,n,m,s,d; int cost[101][101]; class S{ public: int node; int tick; int cost; S(int node,int tick,int cost): node(node),tick(tick),cost(cost){} S(){} bool operator <(const S arg) const{ return cost > arg.cost; } }; int dijkstra(int src,int dst){ priority_queue<S> q; int memo[n+1][c+1]; S tmp; fill((int *)memo, (int *)memo+(n+1)*(c+1), INF); memo[src][c] = 0; q.push(S(src,c,0)); while(!q.empty()){ tmp = q.top(); q.pop(); for(int i=0;i<=n;i++){ if(cost[tmp.node][i] != INF){ if(cost[tmp.node][i] + tmp.cost < memo[i][tmp.tick]){ q.push(S(i,tmp.tick,cost[tmp.node][i] + tmp.cost)); memo[i][tmp.tick] = cost[tmp.node][i] + tmp.cost; } if(tmp.tick && cost[tmp.node][i]/2 + tmp.cost < memo[i][tmp.tick-1]){ q.push(S(i,tmp.tick-1,cost[tmp.node][i]/2 + tmp.cost)); memo[i][tmp.tick-1] = cost[tmp.node][i]/2 + tmp.cost; } } } } int ret = 1<<29; for(int i=0;i<=c;i++){ ret = min(ret, memo[dst][i]); } return ret; } int main(){ while(cin >> c >> n >> m >> s >> d){ if((c|n|m|s|d) == 0) break; int src,dst,c; fill((int *)cost, (int *)cost+101*101, INF); for(int i=0;i<m;i++){ cin >> src >> dst >> c; cost[src][dst] = c; cost[dst][src] = c; } cout << dijkstra(s,d) << endl; } }
true
e6edf9688e56d8ec8e7589ab79153ff4c577ec4b
C++
lihzzz/leetcode-C
/LeetCode/second-Leetcode/2.cpp
UTF-8
700
2.984375
3
[]
no_license
// // Created by lh on 2018/3/31. // #include "../DataStruct.h" #include <stack> using namespace std; class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { if(!l1 || !l2){ return NULL; } stack<int> s1,s2; while (l1){ s1.push(l1->val); l1 = l1->next; } while (l2){ s2.push(l2->val); l2 = l2->next; } ListNode* head; while (!s1.empty() && !s2.empty()){ ListNode* tmp = new ListNode(s1.top()+s2.top()); head->next = tmp; tmp->val = s1.top() + s2.top(); head = head->next; } } };
true
3846329da74812cf054d861bbf5d098cfe2de936
C++
jwolf02/CLAHE
/src/common.hpp
UTF-8
10,017
3.390625
3
[ "MIT" ]
permissive
#ifndef __UTIL_HPP #define __UTIL_HPP #include <vector> #include <string> #include <type_traits> #include <stdexcept> #include <algorithm> #include <iostream> #include <functional> #include <unordered_map> #include <map> #include <set> #include <unordered_set> #include <fcntl.h> #include <unistd.h> #include <random> namespace string { /*** * split string by the specified delimiter, if delim is the empty string * then a vector of chars is returned * @param str the string to split * @param delim the delimiter, by default a single space * @return a vector of strings */ inline std::vector<std::string> split(const std::string &str, const std::string &delim = " ") { if (delim.empty()) { throw std::runtime_error("empty delimiter"); } std::vector<std::string> tokens; size_t last = 0; size_t next = 0; while ((next = str.find(delim, last)) != std::string::npos) { tokens.emplace_back(str.substr(last, next - last)); last = next + 1; } tokens.emplace_back(str.substr(last)); return tokens; } /*** * check if str1 starts with str2 * @param str1 * @param str2 * @return */ inline bool starts_with(const std::string &str1, const std::string &str2) { return str1.size() >= str2.size() && std::equal(str1.begin(), str1.begin() + str2.size(), str2.begin()); } /*** * check if str1 end with str2 * @param str1 * @param str2 * @return */ inline bool ends_with(const std::string &str1, const std::string &str2) { return str1.size() >= str2.size() && std::equal(str1.end() - str2.size(), str1.end(), str2.begin()); } /*** * equals ignore case * @param str1 * @param str2 * @return */ inline bool iequals(const std::string &str1, const std::string &str2) { return str1.size() == str2.size() && std::equal(str1.begin(), str1.end(), str2.begin(), [](char a, char b) -> bool { return std::tolower(a) == std::tolower(b); }); } inline bool contains(const std::string &str1, const std::string &str2) { return str1.size() <= str2.size() && str1.find_first_of(str2, 0) != std::string::npos; } /*** * cast string to arithmetic type specified by the template argument * @tparam T type to case to * @param str string to be casted * @return arithmetic type */ template<typename T> T to(const std::string &str) { static_assert(std::is_fundamental<T>::value && (std::is_arithmetic<T>::value || std::is_same<T, bool>::value), "cannot convert std::string to non-arithmetic type"); // signed types if (std::is_same<T, char>::value || std::is_same<T, short>::value || std::is_same<T, int>::value || std::is_same<T, long>::value || std::is_same<T, long long>::value) { return (T) std::strtoll(str.c_str(), nullptr, 10); } // unsigned types else if (std::is_same<T, unsigned char>::value || std::is_same<T, unsigned short>::value || std::is_same<T, unsigned int>::value || std::is_same<T, unsigned long>::value || std::is_same<T, unsigned long long>::value) { return (T) std::strtoull(str.c_str(), nullptr, 10); } // double else if (std::is_same<T, double>::value) { return std::strtod(str.c_str(), nullptr); } // float else if (std::is_same<T, float>::value) { return std::strtof(str.c_str(), nullptr); } // long double else if (std::is_same<T, long double>::value) { return std::strtold(str.c_str(), nullptr); } // bool else if (std::is_same<T, bool>::value) { if (str == "true" || str == "1" || str == "True" || str == "TRUE") return true; else if (str == "false" || str == "0" || str == "False" || str == "FALSE") return false; else throw std::runtime_error("cannot cast std::string '" + str + "' to bool"); } else { throw std::domain_error("cannot convert std::string to specified type"); } } /*** * remove leading and trailing whitespace characters (can be any characters) from string * @param str * @param whitespace * @return */ inline std::string trim(const std::string &str, const std::string &whitespace = " \t\n\r") { const size_t begin = str.find_first_not_of(whitespace); const size_t end = str.find_last_not_of(whitespace); return str.substr(begin, end - begin + 1); } /*** * convert string to upper case * @param str * @return */ inline std::string to_upper(const std::string &str) { std::string up = str; std::transform(str.begin(), str.end(), up.begin(), ::toupper); return up; } /*** * convert string to lower case * @param str * @return */ inline std::string to_lower(const std::string &str) { std::string lo = str; std::transform(str.begin(), str.end(), lo.begin(), ::tolower); return lo; } } namespace seq { template<typename iterator> inline decltype(iterator::operator*) min(iterator begin, iterator end) { if (end - begin == 0) { throw std::length_error("empty sequence"); } iterator min = begin; for (auto it = begin; it != end; ++it) { min = *it < *min ? it : min; } return *min; } template<typename iterator> inline decltype(iterator::operator*) max(iterator begin, iterator end) { if (end - begin == 0) { throw std::length_error("empty sequence"); } iterator max = begin; for (auto it = begin; it != end; ++it) { max = *it > *max ? it : max; } return *max; } template<typename iterator> inline uint64_t argmin(iterator begin, iterator end) { if (end - begin == 0) { throw std::length_error("empty sequence"); } iterator min = begin; for (auto it = begin; it != end; ++it) { min = *it < *min ? it : min; } return min - begin; } template<typename iterator> inline uint64_t argmax(iterator begin, iterator end) { if (end - begin == 0) { throw std::length_error("empty sequence"); } iterator max = begin; for (auto it = begin; it != end; ++it) { max = *it > *max ? it : max; } return max - begin; } } namespace io { /*** * generalized STL-like print function * @tparam iterator * @param os * @param begin * @param end * @param b * @param e * @param print_func */ template <typename iterator> inline void print(std::ostream &os, iterator begin, iterator end, char b, char e, std::function<void (std::ostream &os, iterator it)> &print_func){ auto it = begin; os << b; while (it != end) { print_func(os, it); auto _it = it; if (++_it != end) { os << ", "; } } os << e; } template <typename iterator> inline void print(std::ostream &os, iterator begin, iterator end, char b='(', char e=')'){ auto it = begin; os << b; while (it != end) { os << *it; auto _it = it; if (++_it != end) { os << ", "; } ++it; } os << e; } } template <typename T> inline std::ostream& operator<<(std::ostream &os, const std::vector<T> &vec) { io::print(os, vec.begin(), vec.end(), '[', ']'); return os; } template <typename T, size_t N> inline std::ostream& operator<<(std::ostream &os, const std::array<T, N> &array) { io::print(os, array.begin(), array.end(), '[', ']'); return os; } template <typename T> inline std::ostream& operator<<(std::ostream &os, const std::set<T> &set) { io::print(os, set.begin(), set.end(), '{', '}'); return os; } template <typename T> inline std::ostream& operator<<(std::ostream &os, const std::unordered_set<T> &set) { io::print(os, set.begin(), set.end(), '{', '}'); return os; } template <typename K, typename V> inline std::ostream& operator<<(std::ostream &os, const std::unordered_map<K, V> &map) { io::print(os, map.begin(), map.end(), '{', '}', [](std::ostream &os, decltype(map.begin()) it) { os << it->first << ": " << it->second; }); return os; } template <typename K, typename V> inline std::ostream& operator<<(std::ostream &os, const std::map<K, V> &map) { io::print(os, map.begin(), map.end(), '{', '}', [](std::ostream &os, decltype(map.begin()) it) { os << it->first << ": " << it->second; }); return os; } /*** * byte swap using gcc built-ins for various interger types * @tparam T integer type * @param x value to byte swap * @return */ template<typename T> inline T bswap(T x) { if (std::is_same<T, int8_t>::value || std::is_same<T, uint8_t>::value) { return (T) x; } else if (std::is_same<T, int16_t>::value || std::is_same<T, uint16_t>::value) { return (T) __bswap_16((uint16_t) x); } else if (std::is_same<T, int32_t>::value || std::is_same<T, uint32_t>::value) { return (T) __bswap_32((uint32_t) x); } else if (std::is_same<T, int64_t>::value || std::is_same<T, uint64_t>::value) { return (T) __bswap_64((uint64_t) x); } else { return (T) x; } } /*** * convert data type to network byte order and back * @tparam T * @param x * @return */ template <typename T> inline T inet_bswap(T x) { #if BYTE_ORDER == LITTLE_ENDIAN return bswap<T>(x); #else return (T) x; #endif } inline bool exists(const std::string& fname) { return (access(fname.c_str(), F_OK ) != -1); } #endif // __UTIL_HPP
true
0470daeed642165a7434aea222bd6d0de4772440
C++
delhivery/Re-bar
/fletcher/weld.hpp
UTF-8
2,623
3.453125
3
[]
no_license
/** @file weld.hpp * @brief Defines a class to map string commands to solver functions */ #include <experimental/any> #include <experimental/string_view> #include <functional> #include <future> #include <map> #include <vector> #include <jeayeson/jeayeson.hpp> using namespace std; using std::experimental::any; using std::experimental::string_view; /** * @brief Class to handle command -> function mapping * @details Stores command -> function mapping and invokes appropriate commands against solvers and returns their output. * Requires a template parameter to specify the type of supported solvers */ template <typename T> class Weld { private: /** * @brief Vector to maintain a list of solvers */ vector<shared_ptr<T> > solvers; /** * @brief Map mapping a command to executable function against the solver */ static map<string, function<json_map(shared_ptr<T>, const map<string, any>&)> > welder; public: /** * @brief Default constructs a Weld instance */ Weld() { } /** * @brief Adds solvers to be used for commands * @param[in] solver: Shared pointer to a solver */ void add_solver(const shared_ptr<T>& solver) { solvers.push_back(solver); } /** * @brief Executes a command against solvers asynchronously, fetches the results and returns the mode appropriate solution * @param[in] mode: Solver mode * @param[in] command: Command to execute * @param[in] kwargs: Named arguments for command * @return A json response as generated by command */ json_map operator() (int mode, string_view command, const map<string, any>& kwargs) { vector<json_map> data; vector<future<json_map> > responses; for (const auto& solver: solvers) { responses.push_back( async( [this, &command, &solver, &kwargs]() { return welder.at(command.to_string())(solver, kwargs); } ) ); } for (auto& response: responses) { data.push_back(response.get()); } return data[mode]; } }; template <typename T> map<string, function<json_map(shared_ptr<T>, const map<string, any>&)> > Weld<T>::welder = { {"ADDV", T::addv}, {"ADDE", T::adde}, {"ADDC", T::addc}, {"LOOK", T::look}, {"FIND", T::find}, {"MODC", T::modc} };
true
b0ce9c50daccbf676865df3f3f8ed3c3683def42
C++
shivikasaggar/june_leetcode
/validate IP address.cpp
UTF-8
2,308
3.40625
3
[]
no_license
//Write a function to check whether an input string is a valid IPv4 address or IPv6 address or neither. #include<bits/stdc++.h> using namespace std; bool isHexAlpha(char ch) { return ('a' <= ch && ch <= 'f') || ('A' <= ch && ch <= 'F'); } bool isNum(char ch) { return ('0' <= ch && ch <= '9'); } bool isHexAlphaNum(char ch) { return isHexAlpha(ch) || isNum(ch); } bool isip6(string IP){ string tstr; int tmp_int; // IP.push_back(':'); for (int i=0;i< IP.length();i++) { if (isHexAlphaNum(IP[i])) { tstr.push_back(IP[i]); } else if (IP[i] == ':') { if (tstr.empty()) return false; cout<<tstr.size()<<endl; if (tstr.size() >= 5) return false; tstr = ""; } else { // invalid char return false; } } return true; } bool isip4(string IP){ string tstr; int tmp_int; // IP.push_back('.'); for (int i=0;i<IP.length();i++) { if (isNum(IP[i])) { tstr.push_back(IP[i]); } else if (IP[i] == '.') { if (tstr.empty()) return false; if (tstr.size() >3) return false; //if (tstr[0] == '0' && tstr.size() > 1) return false; //tmp_int = stoi(tstr); if (tmp_int < 0 || tmp_int > 255) return false; tstr = ""; } else { return false; } } return true; } string validIPAddress(string IP) { int n=IP.length(); int ip4=0; int ip6=0; for(int i=0;i<n;i++){ if(IP[i]=='.'){ ip4++; } else if(IP[i]==':'){ ip6++; } else if (!isHexAlphaNum(IP[i])) { //cout<<IP[i]<<endl; return "Neither"; } } if (ip4 == 3 && ip6 == 0) return (isip4(IP)? "IPv4": "Neither"); if (ip4 == 0 && ip6 == 7) return (isip6(IP)? "IPv6":"Neither"); return "Neither"; } int main(){ cout<<validIPAddress("2001:0db8:85a3:0:0:8A2E:0370:73341"); }
true
8edd46bdb5017ae66e6dad47d216751096f5b7c6
C++
npj6/PL-2020-C
/p5/MemoryManager.h
UTF-8
511
2.640625
3
[]
no_license
#ifndef _MemoryManager_ #define _MemoryManager_ #include <stdexcept> using namespace std; class no_memory_left : public logic_error { public: no_memory_left(const char* what) : logic_error(what) {} }; class MemoryManager { private: unsigned varMem; unsigned nextVar; unsigned tempMem; unsigned nextTemp; public: MemoryManager(unsigned varMem, unsigned tempMem); unsigned getVarDir(unsigned varSize); unsigned getTempDir(unsigned tempSize); void resetTempDir(); }; #endif
true
5978f56e92fe41b61ad0efdd9010c6e6859e27fa
C++
philou/philou
/opengl/isiviewerCpp/operators.cpp
UTF-8
623
3.109375
3
[]
no_license
#include "operators.h" #include <math.h> glm::vec3 produitVectoriel(const glm::vec3& u, const glm::vec3& v) { return glm::vec3( u.y*v.z - u.z*v.y , u.x*v.z - u.z*v.x , u.x*v.y - u.y*v.x); } float length(const glm::vec3& v) { if ( v.x == 0 && v.y ==0 && v.z == 0) return 0; return sqrt( v.x*v.x + v.y*v.y + v.z*v.z); } glm::vec3 normalized(const glm::vec3& v) { if (length(v) == 0) return v; return v / length(v); } std::ostream& operator << (std::ostream& output, const glm::vec3& v) { output << "(x=" << v.x << ",y=" << v.y << ",z=" << v.z << ")"; return output; }
true
76037941ca05cdd241ccee3502f4c89cbcf9ff9c
C++
itohdak/AtCoder
/samples/trie.cpp
UTF-8
1,385
3.109375
3
[]
no_license
#include "header.hpp" template<int char_size, int base> struct Trie { struct Node { vector<int> next; vector<int> accept; int c; int common; Node(int c_) : c(c_), common(0) { next.assign(char_size, -1); } }; vector<Node> nodes; int root; Trie() : root(0) { nodes.push_back(Node(root)); } void insert(const string& word, int word_id) { int node_id = 0; for(int i=0; i<(int)word.size(); i++) { int c = (int)(word[i] - base); int& next_id = nodes[node_id].next[c]; if(next_id == -1) { next_id = (int)nodes.size(); nodes.push_back(Node(c)); } ++nodes[node_id].common; node_id = next_id; } ++nodes[node_id].common; nodes[node_id].accept.push_back(word_id); } void insert(const string& word) { insert(word, nodes[0].common); } bool search(const string& word, bool prefix=false) { int node_id = 0; for(int i=0; i<(int)word.size(); i++) { int c = (int)(word[i] - base); int& next_id = nodes[node_id].next[c]; if(next_id == -1) return false; node_id = next_id; } return (prefix ? true : nodes[node_id].accept.size() > 0); } bool start_with(const string& word) { return search(word, true); } int count() const { return (nodes[0].common); } int size () const { return ((int)nodes.size()); } };
true
d5bf6fafd2171892c9ff0efac6009803b2622569
C++
CCatherineeee/DataStructureDesign
/排课软件/Queue.h
GB18030
481
2.96875
3
[]
no_license
#pragma once #include"DEFINE.h" typedef int ElemType; // class sqQueue { private: int rear, front; //ͷβָ ElemType* elements; // int maxsize; //е public: //캯 nΪе sqQueue(int n); // ~sqQueue(); //n Status enQueue(ElemType n); //Ӳݵn Status deQueue(ElemType& n); };
true
4c4104e3c4074acd9d48ae4f9db5f4c936c57afe
C++
emifervi/ProyectoFinalPoo
/Fisico.h
UTF-8
1,511
3.46875
3
[]
no_license
#ifndef FISICO_H_INCLUDED #define FISICO_H_INCLUDED #include "Servicio.h" class Fisico : public Servicio{ private: double ctoX30Min; public: // Constructores Fisico(); Fisico(string servicio, string detalle, char clase, double tarifa); // Metodos de acceso y modificacion void setCtoX30Min(double tarifa); double getCtoX30Min(); // Metodos funcionales void muestra(); double calculaCosto(int tiempo); }; /* * Constructor default */ Fisico::Fisico() : Servicio(){ ctoX30Min = 0; } /* * Constructor con parametros */ Fisico::Fisico(string servicio, string detalle, char clase, double tarifa) : Servicio(servicio, detalle, clase){ ctoX30Min = tarifa; } /* * Metodo de modificacion de ctoX30Min */ void Fisico::setCtoX30Min(double tarifa){ ctoX30Min = tarifa; } /* * Metodo de acceso de ctoX30Min */ double Fisico::getCtoX30Min(){ return ctoX30Min; } /* * Metodo de calcula costo * Arguemntos: tiempo total en minutos; * Retornos: costo total del servicio */ double Fisico::calculaCosto(int tiempo){; return (ctoX30Min/30.0 )* tiempo; } /* * Metodo muestra */ void Fisico::muestra(){ cout << "Servicio: " << cveServicio << endl; cout << "Tipo: " << tipo << endl; cout << "Descripcion: " << descripcion << endl; cout << "Tarifa: " << ctoX30Min << endl; //cout << "Costo total: " << calculaCosto(int mins) << endl; } #endif // FISICO_H_INCLUDED
true
a8b76b7337c27d65b022073866211d01b391af79
C++
EdinsonPedroza/POO2021-1ESPB
/POSGSOFT/Jurado.cpp
UTF-8
2,875
3.1875
3
[]
no_license
#include "Jurado.h" Jurado::Jurado() { } Jurado::Jurado(string nombre, string id): Persona(nombre,id) { this->vectorNombreJurado.push_back(nombre); this->vectorIdJurado.push_back(id); } void Jurado::calificarCriterios(vector<string> criterios) { int i; for (i=0;i<16;i++){ if(i<8){ cout<<criterios[i]; cout<<"Jurado 1:"; cout<<"Ingrese la nota del criterio #"<<i+1<<": "; cin>>this->nota; this->vectorCriterioJ1.push_back(this->nota); cin.ignore(); cout<<"Ingrese su comentario del criterio #"<<i+1<<":\n"; getline(cin, this->comentJ1); this->vectorComentJ1.push_back(this->comentJ1); }else{ cout<<criterios[i-8]; cout<<"Jurado 2:"; cout<<"Ingrese la nota del criterio #"<<i-7<<": "; cin>>this->nota; this->vectorCriterioJ2.push_back(this->nota); cin.ignore(); cout<<"Ingrese su comentario del criterio # "<<i-7<<":\n"; getline(cin,this->comentJ2); this->vectorComentJ2.push_back(this->comentJ2); } } Criterio mandarCriterios; mandarCriterios.recibirCriterios(this->vectorCriterioJ1, this->vectorCriterioJ2, this->vectorComentJ1, this->vectorComentJ2); mandarCriterios.mostrarCalificacionesCriterios(); mandarCriterios.crearPonderado(); mandarCriterios.generarEstadoActa(); mandarCriterios.mostrarComentarios(); ingresarComentariosAdicionales(); } void Jurado::ingresarComentariosAdicionales() { int i=0, respuesta; string comentarioJ1,comentarioJ2; switch (i) { case 0: cout << "Jurado 1" << endl; cout << "Desea realizar comentarios adicionales?" << endl; cout << "0. No\n 1. Si" << endl; cin >> respuesta; if (respuesta == 1) { cin.ignore(); cout << "Ingrese su comentario adicional:\n"; getline(cin, comentarioJ1); } else { comentarioJ1="N/A"; } case 1: cout << "Jurado 2" << endl; cout << "Desea realizar comentarios adicionales?" << endl; cout << "0. No\n 1. Si" << endl; cin >> respuesta; if (respuesta == 1) { cin.ignore(); cout << "Ingrese su comentario adicional:\n"; getline(cin, comentarioJ2); }else{ comentarioJ2="N/A"; } } Acta acta; acta.recibirCalificaciones(this->vectorCriterioJ1, this->vectorCriterioJ2, this->vectorComentJ1, this->vectorComentJ2); acta.recibirComentariosAdicionales(comentarioJ1,comentarioJ2); acta.mostrarComentariosAdicionales(); }
true
b593b97734417d91d4ecd82690ab8dd3a17cbff7
C++
whime/dataStructure-algorithm
/剑指offer/跳台阶.cpp
UTF-8
915
3.921875
4
[]
no_license
/* 一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法 (先后次序不同算不同的结果)。 */ //看来我还是只会递归啊 class Solution { public: int jumpFloor(int number) { if(number==1) return 1; else if(number==2) return 2; else { return jumpFloor(number-1)+jumpFloor(number-2); } } }; //类似Fabonacci数列的方法 class Solution { public: int jumpFloor(int number) { if(number<0) return 0; else if(number==1||number==2) return number; else { int f1=1,f2=2,tmp; for(int i=2;i<number;++i) { tmp=f1+f2; f1=f2; f2=tmp; } return f2; } } };
true
b8866521a16259b7c0dd070ac0d9e78650e353f3
C++
Costath/Ordered-List
/main.cpp
ISO-8859-1
2,573
3.109375
3
[]
no_license
/* Autor: Thales Costa Disciplina: ED1 Professor: Irineu Maio/2017 */ #include "lista_ordenada.h" int main() { setlocale(LC_ALL, ""); system("title Lista ordenada"); int funcao; char elemento; bool found; Lista* L; L = inicializa(); menu: printf("==Lista ordenada==\n\n"); printf("Selecione a funo desejada:\n"); printf("1 - Inserir elemento\n"); printf("2 - Remover elemento\n"); printf("3 - Buscar elemento\n"); printf("4 - Mostrar todos\n"); printf("0 - Sair\n\n"); scanf("%d", &funcao); switch(funcao){ //Direciona para a funo requisitada no menu acima. case(1): //Insere na lista o elemento informado. printf("\nInforme a letra a ser inserida: "); getchar(); scanf("%c", &elemento); L = insere(L, elemento); system("cls"); break; case(2): //Retira determinado elemento da lista. if(L != NULL){ printf("\n\nInforme a letra a ser retirada: "); getchar(); scanf("%c", &elemento); found = false; L = remove(L, elemento, &found); if(found){ printf("\nA letra foi removida com sucesso.\n"); }else{ printf("\nA letra no foi encontrada na lista.\n"); } system("pause"); system("cls"); }else{ printf("\nA lista est vazia.\n"); system("pause"); system("cls"); } break; case(3): //Informa se determinado elemento est na lista. if(L != NULL){ printf("\nInforme a letra a ser buscada: "); getchar(); scanf("%c", &elemento); int position = busca(L, elemento); if(position != -1){ printf("\nA letra est presente na posio %d.\n", position); }else{ printf("\nA letra no est presente na lista.\n"); } }else{ printf("\nA lista est vazia. No possvel realizar buscas.\n"); } system("pause"); system("cls"); break; case(4): //Mostra os elementos da lista. if(L != NULL){ printf("\nLista:\n\n"); mostra(L); }else{ printf("\nA lista est vazia.\n"); } system("pause"); system("cls"); break; case(0): //Libera a memria alocada, caso tenha alguma, e encerra o programa. libera(L); printf("\nObrigado!\n"); return 0; break; default: printf("Opo no existente.\n\n"); system("pause"); system("cls"); } goto menu; //Mantm no menu enquanto no for selecionada a opo "sair". }
true
15f1519d2da9c90e7f6d65ab262eba9d8e781240
C++
Attyuttam/CompetitiveProgramming
/Misc/printingAllStringsOfLengthN.cpp
UTF-8
612
3.265625
3
[]
no_license
#include<bits/stdc++.h> #include<chrono> using namespace std; using namespace std::chrono; void generateAllOfLengthN(int N,string toPrint){ if(N!=0){ generateAllOfLengthN(N-1,toPrint+"a"); generateAllOfLengthN(N-1,toPrint+"b"); }else{ cout<<toPrint<<endl; } } int main(){ int N; for(int i=3;i<=3;i++){ auto start = chrono::high_resolution_clock::now(); generateAllOfLengthN(i,""); auto stop = chrono::high_resolution_clock::now(); auto duration = duration_cast<microseconds>(stop - start); cout << "TIME TAKEN TO GENERATE STRING OF LENGTH "<<i<<": "<<duration.count() << endl; } }
true
8144f1309d6ff0dbc0798cae848e279bfaffa2dd
C++
atenpas/gpd
/src/gpd/util/point_list.cpp
UTF-8
1,786
2.5625
3
[ "BSD-2-Clause" ]
permissive
#include <gpd/util/point_list.h> namespace gpd { namespace util { PointList::PointList(int size, int num_cams) { points_.resize(3, size); normals_.resize(3, size); cam_source_.resize(num_cams, size); view_points_.resize(3, num_cams); } PointList PointList::slice(const std::vector<int> &indices) const { Eigen::Matrix3Xd points_out = EigenUtils::sliceMatrix(points_, indices); Eigen::Matrix3Xd normals_out = EigenUtils::sliceMatrix(normals_, indices); Eigen::MatrixXi cam_source_out = EigenUtils::sliceMatrix(cam_source_, indices); return PointList(points_out, normals_out, cam_source_out, view_points_); } PointList PointList::transformToHandFrame( const Eigen::Vector3d &centroid, const Eigen::Matrix3d &rotation) const { // Eigen::Matrix3Xd points_centered = points_ - centroid.replicate(1, // size()); Eigen::Matrix3Xd points_centered = points_; points_centered.colwise() -= centroid; points_centered = rotation * points_centered; Eigen::Matrix3Xd normals(3, points_centered.cols()); normals = rotation * normals_; return PointList(points_centered, normals, cam_source_, view_points_); } PointList PointList::rotatePointList(const Eigen::Matrix3d &rotation) const { Eigen::Matrix3Xd points(3, points_.cols()); Eigen::Matrix3Xd normals(3, points_.cols()); points = rotation * points_; normals = rotation * normals_; return PointList(points, normals, cam_source_, view_points_); } PointList PointList::cropByHandHeight(double height, int dim) const { std::vector<int> indices(size()); int k = 0; for (int i = 0; i < size(); i++) { if (points_(dim, i) > -1.0 * height && points_(dim, i) < height) { indices[k] = i; k++; } } return slice(indices); } } // namespace util } // namespace gpd
true
4b1a480d2652363bc5412e99d38120c93f7653bb
C++
DSchana/Misc
/School stuff/CS254/assign4/_Graph.cpp
UTF-8
1,425
3.59375
4
[]
no_license
#include <algorithm> #include "_Graph.h" using namespace std; Graph::Graph(int s) { for (int i = 0; i < s; i++) { Node* n; nodes.push_back(n); nodes[i]->id = i; } } /* * Description: Connect two nodes by adding them into * each other's adjacency list * Parameters: Integer n1: ID of node 1 * Integer n2: ID of node 2 * Returns: void **/ void Graph::connect(int n1, int n2) { printf("Connecting\n"); printf("ID: %d ", nodes[n2]->id); nodes[n1]->adj.push_back(nodes[n2]); nodes[n2]->adj.push_back(nodes[n2]); printf("ID: %d\n", nodes[n1]->id); } /* * Description: Get a list of all nodes adjacent to * and indicated node * Parameters: Integer n: ID of node to get adjacency of * Returns: List of Nodes: List of all nodes adjacent * to Node with ID n **/ vector<Node*> Graph::getAdjacency(int n) { return nodes[n]->adj; } /* * Description: Get pointer to node pf specified ID * Parameters: Integer id: ID of node to return * Returns: Pointer to node with ID id **/ Node* Graph::getNode(int id) { return nodes[id]; for (int i = 0; i < nodes.size(); i++) { //printf("ID: %d\n", nodes[i]->id); if (nodes[i]->id == id) { return nodes[i]; } } return nullptr; } Node* Graph::operator[](int id) { return getNode(id); } /* * Description: Get number of nodes in graph * Parameters: void * Returns: Integer: Number of nodes in graph **/ int Graph::size() { return nodes.size(); }
true
2c89da90d36b60a957fc0473f95380a9cce712f3
C++
ATTPC/libattpc-cleaning
/src/Cluster.cpp
UTF-8
1,865
2.921875
3
[]
no_license
#include "Cluster.h" #include <fstream> #include <limits> #include <cctype> #include <boost/algorithm/string/replace.hpp> namespace attpc { namespace clustering { void Cluster::calculateRelationshipMatrixIfNecessary() const { if (this->relationshipMatrix.size() == 0) { this->relationshipMatrix = Eigen::ArrayXXi(this->pointIndexCount, this->pointIndexCount); this->relationshipMatrix.fill(0); for (pcl::PointIndicesConstPtr const& cluster : this->getClusters()) { std::vector<int> const& indices = cluster->indices; size_t indicesSize = indices.size(); for (size_t i = 0; i < indicesSize; ++i) { int indexI = indices[i]; ++this->relationshipMatrix(indexI, indexI); for (size_t j = i + 1; j < indicesSize; ++j) { int indexJ = indices[j]; if (indexI < indexJ) ++this->relationshipMatrix(indexI, indexJ); else ++this->relationshipMatrix(indexJ, indexI); } } } } } Cluster::Cluster(std::vector<pcl::PointIndicesPtr> const& clusters, size_t pointIndexCount) { this->clusters = clusters; this->pointIndexCount = pointIndexCount; } std::vector<pcl::PointIndicesPtr> const& Cluster::getClusters() const { return this->clusters; } size_t Cluster::getPointIndexCount() const { return this->pointIndexCount; } int Cluster::operator-(Cluster const& rhs) const { if (this->getPointIndexCount() != rhs.getPointIndexCount()) throw std::runtime_error("pointIndexCount has to be identical!"); this->calculateRelationshipMatrixIfNecessary(); rhs.calculateRelationshipMatrixIfNecessary(); return (this->relationshipMatrix - rhs.relationshipMatrix).abs().sum(); } } }
true
090be4ad951f052ac13d2c806d1c60214cf7af9e
C++
KarolisZeimantas/1-uzd
/1 Uzd.cpp
UTF-8
1,029
3.28125
3
[]
no_license
#include<iostream> #include <vector> using namespace std; bool gender(string name){ return (name== "s") ? true : false; } void createStars(string name,int plotis){ vector<char> message; string temp = &name[name.length()-1]; string welcome = (gender(temp)) ? "* Sveikas, " : "* Sveika, "; welcome+= name+ " *"; for (int i = 0; i <welcome.size(); i++) { message.push_back(welcome[i]); } for(int j =0;j<plotis;j++) { for (int i = 0; i < message.size(); i++) { if(j==0||j==plotis-1) cout<<"*"; else if(j==plotis/2) cout<<message[i]; else if(i==0||i==message.size()-1) cout<<"*"; else cout<<" "; } cout<<endl; } } int main(){ string name; int plotis; cout<<"prasome ivesti savo varda: "; cin>>name; cout<<"prasome ivesti ploti: "; cin>>plotis; createStars(name,plotis); }
true
4796d63dcb6dfa6ad7cbfd7c57c6aa92c3efa4fa
C++
pinkogeneral/AlgorithmStudy
/03.Sort/selectsort.cpp
ISO-8859-7
417
3.265625
3
[]
no_license
#include<iostream> int main() { int arr[10]{ 1, 10, 9, 5, 4, 3, 6, 8, 7, 2 }; // int i, j, min , temp, index; for (i = 0; i < 10; i++) { min = 999; for (j = i; j < 10; j++) { if (min > arr[j]) { min = arr[j]; index = j; } } temp = arr[i]; arr[i] = arr[index]; arr[index] = temp; } for (int k = 0; k < 10; ++k) { std::cout << arr[k] << " "; } }
true
ecc41bb4f40c59db87f7d2b9b741fd4ad10cbe2f
C++
theater/ArduinoMega
/Library/Room/Mode.cpp
UTF-8
845
2.625
3
[ "Apache-2.0" ]
permissive
/* * Mode.cpp * * Created on: Mar 15, 2018 * Author: theater */ #include <Mode.h> #include <MqttUtil.h> Mode::Mode(ModeType mode) : Mode(mode, NULL) { } Mode::Mode(ModeType mode, char * id ) { this->id = id; this->mode = mode; this->callbackTopic = createCallbackTopic(id); MqttUtil::subscribe(id); } void Mode::updateValue(const char* id, const char* value) { if (!strcmp(id, this->id)) { if (!strcmp(value, "ALL_OFF")) { setMode(ALL_OFF); } else if (!strcmp(value, "MANUAL")) { setMode(MANUAL); } else { setMode(AUTO); } logDebug("Updated MODE " + String(id) + " to value: " + String(value)); } } Mode::~Mode() { } char* Mode::getId() { return id; } ModeType Mode::getMode() { return mode; } void Mode::setMode(ModeType mode) { this->mode = mode; }
true
76474521928b9cca08afde58dccc97c1b4ef4112
C++
onBinHe/C-C-
/nowcoder_studycode/P3_judgeMultiple2_5_11_13/judgeMultiple/judgeMultiple/judgeMultiple.cpp
UTF-8
3,934
3.375
3
[]
no_license
/* ----------------------------------------------------------------------- 题目: 给出一个数n,求1到n中,有多少个数不是2 5 11 13的倍数。 本题有多组输入,每行一个数n,1<=n<=10^18。 每行输出输出不是2 5 11 13的倍数的数共有多少。 如:输入“15”,输出“4”,说明“1 3 7 9” 思路: 从1-n中的所有数,从小到大依次取出;对2 5 11 13做取余运算,如果是 相应的倍数,取余结果为0. 注意点:1)如数据i对2 5 11 13取余,只要有一个取余结果为0,则说明i为其倍数 ,后续则不用对其他取余了; 2)如数据i对2 5 11 13而言,需要同时对4个都不是倍数,那么需要注意不要 将该数据重复添加到数据流中。 ------------------------------------------------------------------------ */ // judgeMultiple.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 // //由于 1<=n<=10^18,且n为整数 // 2^0 = 1 <= n <= 10^18 < 2^64 = 8字节 // 因此,采用的数据类型为:long long类型 #include "stdio.h" #include "iostream" #include "vector" using namespace std; //------------------ 定义一个结构体分别记录不是2 5 11 13的倍数的数的个数 typedef struct NotMultiple { long long isnotall; //总数 vector<long long> datastream;//说明:数据流 }isnot_multiple; isnot_multiple isnot_mult_data; //用于缓存一次判断结果 //------------------ 处理函数 void judgeMultipleFuction(long long num) { for (long long i = 1; i < num + 1; i++) { if ( (0 != (i % 2)) && (0 != (i % 5)) && (0 != (i % 11)) && (0 != (i % 13))) { isnot_mult_data.isnotall ++; isnot_mult_data.datastream.push_back(i); } } } int main(int argc, char* argv[]) { long long n = 0; isnot_multiple result; do { isnot_mult_data.isnotall = 0; isnot_mult_data.datastream.clear();//擦除数据 cout << "请键入n的值..." << endl; cin >> n; if (0 == n) {//如果键入“0”,则退出 cout << "键入“0”,退出程序!" << endl; break; } else // 键入1-10^18的数据,则筛选数据 { cout << "键入的n的值为: " << n << endl; judgeMultipleFuction(n); cout << isnot_mult_data.isnotall << endl; // 1)打印总个数 for (long long i = 0; i < (isnot_mult_data.datastream.size()); i++) { cout << isnot_mult_data.datastream[i] << " "; } cout << endl; // 2)不换行打印数据 } } while (n); return 0; } //#include<stdio.h> //#include "iostream" //using namespace std; //#define ll long long //int main() //{ // ll n; // while ((cin>>n)) // { // ll ans1 = n / 2 + n / 5 + n / 11 + n / 13; // ll ans2 = n / 10 + n / 55 + n / 22 + n / 26 + n / 65 + n / 143; // ll ans3 = n / 110 + n / 130 + n / 286 + n / 715; // ll ans4 = n / 1430; // ll ans = ans1 - ans2 + ans3 - ans4; // ll ANS = n - ans; // printf("%lld\n", ANS); // // } // return 0; //} // 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单 // 调试程序: F5 或调试 >“开始调试”菜单 // 入门使用技巧: // 1. 使用解决方案资源管理器窗口添加/管理文件 // 2. 使用团队资源管理器窗口连接到源代码管理 // 3. 使用输出窗口查看生成输出和其他消息 // 4. 使用错误列表窗口查看错误 // 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目 // 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
true
96685c624f5bcc42b71db8d2a1966bc888e79e41
C++
TopBrussels/TopTreeAnalysisBase
/Selection/src/ElectronSelection.cc
UTF-8
30,325
2.78125
3
[]
no_license
#include "../interface/ElectronSelection.h" //____CONSTRUCTORS______________________________________________________// ElectronSelection::ElectronSelection() { rho_ = 0; elecIsoCorrType_ = 2; // 0: no corr, 1: rho corr, 2: dB corr. } ElectronSelection::ElectronSelection(const std::vector<TRootElectron*>& electrons_) { rho_ = 0; elecIsoCorrType_ = 2; // 0: no corr, 1: rho corr, 2: dB corr. for(unsigned int i=0; i<electrons_.size(); i++) electrons.push_back(electrons_[i]); } ElectronSelection::ElectronSelection(const std::vector<TRootElectron*>& electrons_, float rho) { rho_ = rho; elecIsoCorrType_ = 1; // 0: no corr, 1: rho corr, 2: dB corr. for(unsigned int i=0; i<electrons_.size(); i++) electrons.push_back(electrons_[i]); } ElectronSelection::ElectronSelection(const ElectronSelection& s) { // copy the objects rho_ = s.rho_; elecIsoCorrType_ = s.elecIsoCorrType_; // 0: no corr, 1: rho corr, 2: dB corr. electrons = s.electrons; } //______________________________________________________________________// //____DESTRUCTOR________________________________________________________// ElectronSelection::~ElectronSelection() { electrons.clear(); } //______________________________________________________________________// //______________________________________________________________________// //__EXTRA METHODS_______________________________________________________// //______________________________________________________________________// //____SELECTION GETTERS_________________________________________________// // ______________ELECTRONS____________________________________________// bool ElectronSelection::foundZCandidate(TRootElectron* electron, std::vector<TRootElectron*>& vetoElectrons, float windowsize) { bool foundZ = false; for(unsigned int i=0; i<vetoElectrons.size(); i++) { TRootElectron* el = (TRootElectron*) vetoElectrons[i]; if( fabs(el->Pt() - electron->Pt()) > 0.001 && fabs(el->Eta() - electron->Eta()) > 0.001 ) { double zMass = (*electron + *el).M(); if( zMass >= (91.-windowsize) && zMass <= (91.+windowsize) ) { foundZ = true; // cout << "Found Z with mass: " << zMass << " El1: " << el->Pt() << " " << el->Eta() << " | El2: " << electron->Pt() << " " << electron->Eta() << endl; } } } return foundZ; } bool ElectronSelection::foundZCandidate(std::vector<TRootElectron*>& electrons1, std::vector<TRootElectron*>& electrons2, float windowsize) { bool foundZ = false; for(unsigned int j=0; j<electrons1.size(); j++) { for(unsigned int i=0; i<electrons2.size(); i++) { TRootElectron* el1 = (TRootElectron*) electrons1[j]; TRootElectron* el2 = (TRootElectron*) electrons2[i]; if( fabs(el2->Pt() - el1->Pt()) > 0.001 && fabs(el2->Eta() - el1->Eta()) > 0.001 ) { double zMass = (*el1 + *el2).M(); if( zMass >= (91.-windowsize) && zMass <= (91.+windowsize) ) { foundZ = true; // cout << "Found Z with mass: " << zMass << " El1: " << el->Pt() << " " << el->Eta() << " | El2: " << electron->Pt() << " " << electron->Eta() << endl; } } } } return foundZ; } // ______________ELECTRONS______________________________________________// float ElectronSelection::GetElectronIsoCorrType(TRootElectron *el) const { double EffectiveArea = 0.; // Updated to Spring 2016 EA from slide7: https://indico.cern.ch/event/482673/contributions/2187022/attachments/1282446/1905912/talk_electron_ID_spring16.pdf if (fabs(el->superClusterEta()) >= 0.0 && fabs(el->superClusterEta()) < 1.0 ) EffectiveArea = 0.1703; if (fabs(el->superClusterEta()) >= 1.0 && fabs(el->superClusterEta()) < 1.479 ) EffectiveArea = 0.1715; if (fabs(el->superClusterEta()) >= 1.479 && fabs(el->superClusterEta()) < 2.0 ) EffectiveArea = 0.1213; if (fabs(el->superClusterEta()) >= 2.0 && fabs(el->superClusterEta()) < 2.2 ) EffectiveArea = 0.1230; if (fabs(el->superClusterEta()) >= 2.2 && fabs(el->superClusterEta()) < 2.3 ) EffectiveArea = 0.1635; if (fabs(el->superClusterEta()) >= 2.3 && fabs(el->superClusterEta()) < 2.4 ) EffectiveArea = 0.1937; if (fabs(el->superClusterEta()) >= 2.4 && fabs(el->superClusterEta()) < 5. ) EffectiveArea = 0.2393; if (fabs(el->superClusterEta()) >= 5.) EffectiveArea = -9999; double isocorr = 0; if(elecIsoCorrType_ == 1) // rho correction (default corr) isocorr = rho_*EffectiveArea; else if(elecIsoCorrType_ == 2) // dB correction isocorr = 0.5*el->puChargedHadronIso(3); else if (elecIsoCorrType_ == 0) // no correction isocorr = 0.; else { cerr << "Please, specify the correction type to be applied for the calculation of the electron relative isolation" << endl; cerr << " - Use setElectronIsoCorrType(int) method: " << endl; cerr << " -- 0: no correction, 1: rho correction (default), 2: dB correction" << endl; exit(1); } return isocorr; } float ElectronSelection::pfElectronIso(TRootElectron *el) const { float isoCorr = (el->neutralHadronIso(3) + el->photonIso(3) - GetElectronIsoCorrType(el)); float isolation = (el->chargedHadronIso(3) + (isoCorr > 0.0 ? isoCorr : 0.0))/(el->Pt()); return isolation; } std::vector<TRootElectron*> ElectronSelection::GetSelectedElectrons() const { return GetSelectedElectrons(30,2.5,"Tight","Spring16_80X",true,true); } std::vector<TRootElectron*> ElectronSelection::GetSelectedElectrons(string WorkingPoint, string ProductionCampaign, bool CutsBased) const { return GetSelectedElectrons(30,2.5,WorkingPoint,ProductionCampaign,CutsBased,true); } std::vector<TRootElectron*> ElectronSelection::GetSelectedElectrons(float PtThr, float etaThr, string WorkingPoint) const { return GetSelectedElectrons(PtThr,etaThr,WorkingPoint,"Spring16_80X",true,true); } std::vector<TRootElectron*> ElectronSelection::GetSelectedElectrons(float PtThr, float etaThr, string WorkingPoint, string ProductionCampaign, bool CutsBased, bool applyVID) const { // cout << "Get selected electrons " << endl; // cout << "PtThr " << PtThr << " etaThr " << etaThr << " WorkingPoint " << WorkingPoint << " ProductionCampaign " << ProductionCampaign << " CutsBased " << CutsBased << " applyVID " << applyVID << endl; std::vector<TRootElectron* > ElectronCollection; if (CutsBased == true && applyVID == false) { if (ProductionCampaign == "Spring16_80X" && WorkingPoint == "Tight") { ElectronCollection = GetSelectedTightElectronsCutsBasedSpring16_80X(PtThr, etaThr); } else if (ProductionCampaign == "Spring16_80X" && WorkingPoint == "Medium") { ElectronCollection = GetSelectedMediumElectronsCutsBasedSpring16_80X(PtThr, etaThr); } else if (ProductionCampaign == "Spring16_80X" && WorkingPoint == "Loose") { ElectronCollection = GetSelectedLooseElectronsCutsBasedSpring16_80X(PtThr, etaThr); } else if (ProductionCampaign == "Spring16_80X" && WorkingPoint == "Veto") { ElectronCollection = GetSelectedVetoElectronsCutsBasedSpring16_80X(PtThr, etaThr); } else if (ProductionCampaign == "Spring16_80X" && WorkingPoint == "FakeLoose") { ElectronCollection = GetSelectedFakeLooseElectronsCutsBasedSpring16_80X(PtThr, etaThr); } else if (ProductionCampaign == "Spring16_80X" && WorkingPoint == "FakeTight") { ElectronCollection = GetSelectedFakeTightElectronsCutsBasedSpring16_80X(PtThr, etaThr); } else { string printboolval="Cutbased=true, applyVID=false"; throw std::invalid_argument( "received incorrect args to GetSelectedElectrons, requested: "+WorkingPoint+", "+ProductionCampaign+" "+printboolval); } } else if (CutsBased == true && applyVID == true) { if (ProductionCampaign == "Spring16_80X" && WorkingPoint == "Heep") { ElectronCollection = GetSelectedHeepElectronsCutsBasedSpring16_80X_VID(PtThr, etaThr); } if (ProductionCampaign == "Spring16_80X" && WorkingPoint == "Tight") { ElectronCollection = GetSelectedTightElectronsCutsBasedSpring16_80X_VID(PtThr, etaThr); } else if (ProductionCampaign == "Spring16_80X" && WorkingPoint == "Medium") { ElectronCollection = GetSelectedMediumElectronsCutsBasedSpring16_80X_VID(PtThr, etaThr); } else if (ProductionCampaign == "Spring16_80X" && WorkingPoint == "Loose") { ElectronCollection = GetSelectedLooseElectronsCutsBasedSpring16_80X_VID(PtThr, etaThr); } else if (ProductionCampaign == "Spring16_80X" && WorkingPoint == "Veto") { ElectronCollection = GetSelectedVetoElectronsCutsBasedSpring16_80X_VID(PtThr, etaThr); } else { string printboolval="Cutbased=true, applyVID=true"; throw std::invalid_argument( "received incorrect args to GetSelectedElectrons, requested: "+WorkingPoint+", "+ProductionCampaign+" "+printboolval); } } else if (CutsBased == false && applyVID == true) { if (ProductionCampaign == "Spring16_80X" && WorkingPoint == "Tight") { ElectronCollection = GetSelectedTightElectronsMVABasedSpring16_80X_VID(PtThr, etaThr); } else if (ProductionCampaign == "Spring16_80X" && WorkingPoint == "Medium") { ElectronCollection = GetSelectedMediumElectronsMVABasedSpring16_80X_VID(PtThr, etaThr); } else if (ProductionCampaign == "Spring16_80X" && WorkingPoint == "Loose") { ElectronCollection = GetSelectedLooseElectronsMVABasedSpring16_80X_VID(PtThr, etaThr); } else { string printboolval="Cutbased=false, applyVID=true"; throw std::invalid_argument( "received incorrect args to GetSelectedElectrons, requested: "+WorkingPoint+", "+ProductionCampaign+" "+printboolval); } } else { string printboolval="Cutbased=false, applyVID=false"; throw std::invalid_argument( "received incorrect args to GetSelectedElectrons, requested: "+WorkingPoint+", "+ProductionCampaign+" "+printboolval); } return ElectronCollection; } //VID electrons std::vector<TRootElectron*> ElectronSelection::GetSelectedHeepElectronsCutsBasedSpring16_80X_VID(float PtThr, float EtaThr) const { std::vector<TRootElectron*> selectedElectrons; for(unsigned int i=0; i<electrons.size(); i++) { TRootElectron* el = (TRootElectron*) electrons[i]; if(el->isCB_HeepID() && el->Pt() > PtThr && fabs(el->Eta()) < EtaThr) selectedElectrons.push_back(electrons[i]); } return selectedElectrons; } std::vector<TRootElectron*> ElectronSelection::GetSelectedTightElectronsCutsBasedSpring16_80X_VID(float PtThr, float EtaThr) const { // cout << "GetSelectedTightElectronsCutsBasedSpring16_80X_VID " << PtThr << " " << EtaThr << endl; // cout << "initial collection size " << electrons.size() << endl; std::vector<TRootElectron*> selectedElectrons; for(unsigned int i=0; i<electrons.size(); i++) { TRootElectron* el = (TRootElectron*) electrons[i]; // cout << "electron " << i << " isCB_TightID() " << el->isCB_TightID() << " pt " << el->Pt() << " eta " << el->Eta() << endl; if(el->isCB_TightID() && el->Pt() > PtThr && fabs(el->Eta()) < EtaThr){ selectedElectrons.push_back(electrons[i]); //cout << "pushing back " << endl; } } //cout << "selected collection size " << selectedElectrons.size() << endl; return selectedElectrons; } std::vector<TRootElectron*> ElectronSelection::GetSelectedMediumElectronsCutsBasedSpring16_80X_VID(float PtThr, float EtaThr) const { std::vector<TRootElectron*> selectedElectrons; for(unsigned int i=0; i<electrons.size(); i++) { TRootElectron* el = (TRootElectron*) electrons[i]; if(el->isCB_MediumID() && el->Pt() > PtThr && fabs(el->Eta()) < EtaThr) selectedElectrons.push_back(electrons[i]); } return selectedElectrons; } std::vector<TRootElectron*> ElectronSelection::GetSelectedLooseElectronsCutsBasedSpring16_80X_VID(float PtThr, float EtaThr) const { std::vector<TRootElectron*> selectedElectrons; for(unsigned int i=0; i<electrons.size(); i++) { TRootElectron* el = (TRootElectron*) electrons[i]; if(el->isCB_LooseID() && el->Pt() > PtThr && fabs(el->Eta()) < EtaThr) selectedElectrons.push_back(electrons[i]); } return selectedElectrons; } std::vector<TRootElectron*> ElectronSelection::GetSelectedVetoElectronsCutsBasedSpring16_80X_VID(float PtThr, float EtaThr) const { std::vector<TRootElectron*> selectedElectrons; for(unsigned int i=0; i<electrons.size(); i++) { TRootElectron* el = (TRootElectron*) electrons[i]; if(el->isCB_VetoID() && el->Pt() > PtThr && fabs(el->Eta()) < EtaThr) selectedElectrons.push_back(electrons[i]); } return selectedElectrons; } std::vector<TRootElectron*> ElectronSelection::GetSelectedTightElectronsMVABasedSpring16_80X_VID(float PtThr, float EtaThr) const { std::vector<TRootElectron*> selectedElectrons; for(unsigned int i=0; i<electrons.size(); i++) { TRootElectron* el = (TRootElectron*) electrons[i]; if(el->isMVA_TightID() && el->Pt() > PtThr && fabs(el->Eta()) < EtaThr) selectedElectrons.push_back(electrons[i]); } return selectedElectrons; } std::vector<TRootElectron*> ElectronSelection::GetSelectedMediumElectronsMVABasedSpring16_80X_VID(float PtThr, float EtaThr) const { std::vector<TRootElectron*> selectedElectrons; for(unsigned int i=0; i<electrons.size(); i++) { TRootElectron* el = (TRootElectron*) electrons[i]; if(el->isMVA_MediumID() && el->Pt() > PtThr && fabs(el->Eta()) < EtaThr) selectedElectrons.push_back(electrons[i]); } return selectedElectrons; } std::vector<TRootElectron*> ElectronSelection::GetSelectedLooseElectronsMVABasedSpring16_80X_VID(float PtThr, float EtaThr) const { std::vector<TRootElectron*> selectedElectrons; for(unsigned int i=0; i<electrons.size(); i++) { TRootElectron* el = (TRootElectron*) electrons[i]; if(el->isMVA_LooseID() && el->Pt() > PtThr && fabs(el->Eta()) < EtaThr) selectedElectrons.push_back(electrons[i]); } return selectedElectrons; } // displaced electrons std::vector<TRootElectron*> ElectronSelection::GetSelectedDisplacedElectrons(float PtThr, float EtaThr, float relIsoB, float relIsoEC, bool applyIso, bool applyId) const { // use tight electron ID (cut-based) for now, but without cuts on d0 dz . This ID can be in flux, and for now is hard-coded here: //These quality cuts reflect the recommended Tight cut-based electron ID as provided by the EGM POG. Last updated: 2 december 2015 // as these are still in flux, it is probably useful to check them here: https://twiki.cern.ch/twiki/bin/viewauth/CMS/CutBasedElectronIdentificationRun2#Spring15_selection_25ns (revision 27) std::vector<TRootElectron*> selectedElectrons; bool saveit=false; for(unsigned int i=0; i<electrons.size(); i++) { saveit=false; TRootElectron* el = (TRootElectron*) electrons[i]; if(el->Pt() > PtThr && fabs(el->Eta())< EtaThr && !el->isEBEEGap()) { // no id no iso if (!applyIso && !applyId) { // cout << "no id and no iso" << endl; saveit = true; } // apply iso only if(applyIso && isolationDisplacedElectron(el, relIsoB, relIsoEC) && !applyId){ // cout << "iso cut required and passed" <<endl; saveit=true; } // apply id only if( !applyIso && applyId && identificationDisplacedElectron(el)){ // cout << "id cut required and passed" <<endl saveit=true; } // apply both if( applyIso && isolationDisplacedElectron(el, relIsoB, relIsoEC) && applyId && identificationDisplacedElectron(el)){ // cout << "id and iso cut required and passed" <<endl saveit=true; } if(saveit) selectedElectrons.push_back(electrons[i]); } } // std::sort(selectedElectrons.begin(),selectedElectrons.end(),HighestPt()); return selectedElectrons; } std::vector<TRootElectron*> ElectronSelection::GetSelectedDisplacedElectrons() const{ return GetSelectedDisplacedElectrons(42.0, 2.4, 0.0354, 0.0646, true, true); } std::vector<TRootElectron*> ElectronSelection::GetSelectedTightElectronsCutsBasedSpring16_80X(float PtThr, float EtaThr) const { // (PLEASE UPDATE IF YOU CHANGE THIS CODE) //These quality cuts reflect the recommended Tight cut-based electron ID as provided by the EGM POG. Last updated: 26 October 2016 // as these are still in flux, it is probably useful to check them here: https://twiki.cern.ch/twiki/bin/viewauth/CMS/CutBasedElectronIdentificationRun2#Working_points_for_2016_data_for (revision 37) std::vector<TRootElectron*> selectedElectrons; for(unsigned int i=0; i<electrons.size(); i++) { TRootElectron* el = (TRootElectron*) electrons[i]; //cout << "electron " << i << " fabs(el->deltaEtaIn()) " << fabs(el->deltaEtaIn()) << "< 0.00308 "<< " fabs(el->deltaPhiIn()) " << fabs(el->deltaPhiIn()) << "< 0.0816" << " el->sigmaIEtaIEta_full5x5() " << el->sigmaIEtaIEta_full5x5() << "<0.00998 " << " el->hadronicOverEm() " << el->hadronicOverEm() << "<0.0414 " << " el->ioEmIoP() " << el->ioEmIoP() << "<0.0129 " << " pfElectronIso(el) " << pfElectronIso(el) << "<0.0588 " << " el->missingHits() " << el->missingHits() << "<=1 " << " el->passConversion() " << endl; // Using cut-based, BARREL: if(el->Pt() > PtThr && fabs(el->Eta())< EtaThr) { if( fabs(el->superClusterEta()) <= 1.479) { if( fabs(el->deltaEtaIn()) < 0.00308 && fabs(el->deltaPhiIn()) < 0.0816 && el->sigmaIEtaIEta_full5x5() < 0.00998 && el->hadronicOverEm() < 0.0414 && el->ioEmIoP() < 0.0129 && pfElectronIso(el) < 0.0588 && el->missingHits() <= 1 && el->passConversion()) { selectedElectrons.push_back(electrons[i]); } } // using cut-based, ENDCAP: else { if( fabs(el->deltaEtaIn()) < 0.00605 && fabs(el->deltaPhiIn()) < 0.0394 && el->sigmaIEtaIEta_full5x5() < 0.0292 && (el->hadronicOverEm() < 0.0641) && el->ioEmIoP() < 0.0129 && pfElectronIso(el) < 0.0571 && el->missingHits() <= 1 && el->passConversion()) { selectedElectrons.push_back(electrons[i]); } } } } std::sort(selectedElectrons.begin(),selectedElectrons.end(),HighestElectronPt()); return selectedElectrons; } std::vector<TRootElectron*> ElectronSelection::GetSelectedMediumElectronsCutsBasedSpring16_80X(float PtThr, float EtaThr) const { // (PLEASE UPDATE IF YOU CHANGE THIS CODE) //These quality cuts reflect the recommended Tight cut-based electron ID as provided by the EGM POG. Last updated: 7 October 2016 // as these are still in flux, it is probably useful to check them here: https://twiki.cern.ch/twiki/bin/viewauth/CMS/CutBasedElectronIdentificationRun2#Working_points_for_2016_data_for (revision 37) std::vector<TRootElectron*> selectedElectrons; for(unsigned int i=0; i<electrons.size(); i++) { TRootElectron* el = (TRootElectron*) electrons[i]; // Using cut-based, BARREL: if(el->Pt() > PtThr && fabs(el->Eta())< EtaThr) { if( fabs(el->superClusterEta()) <= 1.479) { if( fabs(el->deltaEtaIn()) < 0.00311 && fabs(el->deltaPhiIn()) < 0.103 && el->sigmaIEtaIEta_full5x5() < 0.00998 && el->hadronicOverEm() < 0.253 && el->ioEmIoP() < 0.134 && pfElectronIso(el) < 0.0695 && el->missingHits() <= 1 && el->passConversion()) { selectedElectrons.push_back(electrons[i]); } } // using cut-based, ENDCAP: else { if( fabs(el->deltaEtaIn()) < 0.00609 && fabs(el->deltaPhiIn()) < 0.045 && el->sigmaIEtaIEta_full5x5() < 0.0298 && (el->hadronicOverEm() < 0.0878) && el->ioEmIoP() < 0.13 && pfElectronIso(el) < 0.0821 && el->missingHits() <= 1 && el->passConversion()) { selectedElectrons.push_back(electrons[i]); } } } } std::sort(selectedElectrons.begin(),selectedElectrons.end(),HighestElectronPt()); return selectedElectrons; } std::vector<TRootElectron*> ElectronSelection::GetSelectedLooseElectronsCutsBasedSpring16_80X(float PtThr, float EtaThr) const { // (PLEASE UPDATE IF YOU CHANGE THIS CODE) //These quality cuts reflect the recommended Tight cut-based electron ID as provided by the EGM POG. Last updated: 7 October 2016 // as these are still in flux, it is probably useful to check them here: https://twiki.cern.ch/twiki/bin/viewauth/CMS/CutBasedElectronIdentificationRun2#Working_points_for_2016_data_for (revision 37) std::vector<TRootElectron*> selectedElectrons; for(unsigned int i=0; i<electrons.size(); i++) { TRootElectron* el = (TRootElectron*) electrons[i]; // Using cut-based, BARREL: if(el->Pt() > PtThr && fabs(el->Eta())< EtaThr) { if( fabs(el->superClusterEta()) <= 1.479) { if( fabs(el->deltaEtaIn()) < 0.00477 && fabs(el->deltaPhiIn()) < 0.222 && el->sigmaIEtaIEta_full5x5() < 0.011 && el->hadronicOverEm() < 0.298 && el->ioEmIoP() < 0.241 && pfElectronIso(el) < 0.0994 && el->missingHits() <= 1 && el->passConversion()) { selectedElectrons.push_back(electrons[i]); } } // using cut-based, ENDCAP: else { if( fabs(el->deltaEtaIn()) < 0.00868 && fabs(el->deltaPhiIn()) < 0.213 && el->sigmaIEtaIEta_full5x5() < 0.0314 && (el->hadronicOverEm() < 0.101) && el->ioEmIoP() < 0.14 && pfElectronIso(el) < 0.107 && el->missingHits() <= 1 && el->passConversion()) { selectedElectrons.push_back(electrons[i]); } } } } std::sort(selectedElectrons.begin(),selectedElectrons.end(),HighestElectronPt()); return selectedElectrons; } std::vector<TRootElectron*> ElectronSelection::GetSelectedFakeLooseElectronsCutsBasedSpring16_80X(float PtThr, float EtaThr) const { // (PLEASE UPDATE IF YOU CHANGE THIS CODE) //These quality cuts reflect the recommended Tight cut-based electron ID as provided by the EGM POG. Last updated: 7 October 2016 // as these are still in flux, it is probably useful to check them here: https://twiki.cern.ch/twiki/bin/viewauth/CMS/CutBasedElectronIdentificationRun2#Working_points_for_2016_data_for (revision 37) std::vector<TRootElectron*> selectedElectrons; for(unsigned int i=0; i<electrons.size(); i++) { TRootElectron* el = (TRootElectron*) electrons[i]; // Using cut-based, BARREL: if(el->Pt() > PtThr && fabs(el->Eta())< EtaThr) { if( fabs(el->superClusterEta()) <= 1.479) { if( fabs(el->deltaEtaIn()) < 0.00477 && fabs(el->deltaPhiIn()) < 0.222 && el->sigmaIEtaIEta_full5x5() < 0.011 && el->hadronicOverEm() < 0.298 && el->ioEmIoP() < 0.0129 // like tight id && pfElectronIso(el) >= 0.0994 // invert iso && pfElectronIso(el) < 1 // extra cut on iso && el->missingHits() <= 1 && el->passConversion()) { selectedElectrons.push_back(electrons[i]); } } // using cut-based, ENDCAP: else { if( fabs(el->deltaEtaIn()) < 0.00868 && fabs(el->deltaPhiIn()) < 0.213 && el->sigmaIEtaIEta_full5x5() < 0.0314 && (el->hadronicOverEm() < 0.101) && el->ioEmIoP() < 0.0129 // like tight && pfElectronIso(el) >= 0.107 // invert iso && pfElectronIso(el) < 1 && el->missingHits() <= 1 && el->passConversion()) { selectedElectrons.push_back(electrons[i]); } } } } std::sort(selectedElectrons.begin(),selectedElectrons.end(),HighestElectronPt()); return selectedElectrons; } std::vector<TRootElectron*> ElectronSelection::GetSelectedFakeTightElectronsCutsBasedSpring16_80X(float PtThr, float EtaThr) const { // (PLEASE UPDATE IF YOU CHANGE THIS CODE) //These quality cuts reflect the recommended Tight cut-based electron ID as provided by the EGM POG. Last updated: 7 October 2016 // as these are still in flux, it is probably useful to check them here: https://twiki.cern.ch/twiki/bin/viewauth/CMS/CutBasedElectronIdentificationRun2#Working_points_for_2016_data_for (revision 37) std::vector<TRootElectron*> selectedElectrons; for(unsigned int i=0; i<electrons.size(); i++) { TRootElectron* el = (TRootElectron*) electrons[i]; // Using cut-based, BARREL: if(el->Pt() > PtThr && fabs(el->Eta())< EtaThr) { if( fabs(el->superClusterEta()) <= 1.479) { if( fabs(el->deltaEtaIn()) < 0.00477 && fabs(el->deltaPhiIn()) < 0.222 && el->sigmaIEtaIEta_full5x5() < 0.011 && el->hadronicOverEm() < 0.298 && el->ioEmIoP() < 0.0129 // like tight id && pfElectronIso(el) >= 0.0588 // invert iso && pfElectronIso(el) < 1 // extra cut on iso && el->missingHits() <= 1 && el->passConversion()) { selectedElectrons.push_back(electrons[i]); } } // using cut-based, ENDCAP: else { if( fabs(el->deltaEtaIn()) < 0.00868 && fabs(el->deltaPhiIn()) < 0.213 && el->sigmaIEtaIEta_full5x5() < 0.0314 && (el->hadronicOverEm() < 0.101) && el->ioEmIoP() < 0.0129 // like tight && pfElectronIso(el) >= 0.0571// invert iso && pfElectronIso(el) < 1 && el->missingHits() <= 1 && el->passConversion()) { selectedElectrons.push_back(electrons[i]); } } } } std::sort(selectedElectrons.begin(),selectedElectrons.end(),HighestElectronPt()); return selectedElectrons; } std::vector<TRootElectron*> ElectronSelection::GetSelectedVetoElectronsCutsBasedSpring16_80X(float PtThr, float EtaThr) const { // (PLEASE UPDATE IF YOU CHANGE THIS CODE) //These quality cuts reflect the recommended Tight cut-based electron ID as provided by the EGM POG. Last updated: 7 October 2016 // as these are still in flux, it is probably useful to check them here: https://twiki.cern.ch/twiki/bin/viewauth/CMS/CutBasedElectronIdentificationRun2#Working_points_for_2016_data_for (revision 37) std::vector<TRootElectron*> selectedElectrons; for(unsigned int i=0; i<electrons.size(); i++) { TRootElectron* el = (TRootElectron*) electrons[i]; // Using cut-based, BARREL: if(el->Pt() > PtThr && fabs(el->Eta())< EtaThr) { if( fabs(el->superClusterEta()) <= 1.479) { if( fabs(el->deltaEtaIn()) < 0.00749 && fabs(el->deltaPhiIn()) < 0.228 && el->sigmaIEtaIEta_full5x5() < 0.0115 && el->hadronicOverEm() < 0.356 && el->ioEmIoP() < 0.299 && pfElectronIso(el) < 0.175 && el->missingHits() <= 2 && el->passConversion()) { selectedElectrons.push_back(electrons[i]); } } // using cut-based, ENDCAP: else { if( fabs(el->deltaEtaIn()) < 0.00895 && fabs(el->deltaPhiIn()) < 0.213 && el->sigmaIEtaIEta_full5x5() < 0.037 && (el->hadronicOverEm() < 0.211) && el->ioEmIoP() < 0.15 && pfElectronIso(el) < 0.159 && el->missingHits() <= 3 && el->passConversion()) { selectedElectrons.push_back(electrons[i]); } } } } std::sort(selectedElectrons.begin(),selectedElectrons.end(),HighestElectronPt()); return selectedElectrons; } //____________IS SELECTED_______________________________________________// bool ElectronSelection::isPVSelected(const std::vector<TRootVertex*>& vertex, int NdofCut, float Zcut, float RhoCut) { if(vertex.size()==0) return false; float Rho = sqrt(vertex[0]->x()*vertex[0]->x()+vertex[0]->y()*vertex[0]->y()); if(!vertex[0]->isFake() && vertex[0]->ndof()>NdofCut && abs(vertex[0]->z())<Zcut && Rho<RhoCut) return true; return false; } //______________________________________________________________________// //---- selection functions for displaced electrons and muons. factorising ID and isolation. bool ElectronSelection::isolationDisplacedElectron(TRootElectron* el, float relIsoB, float relIsoEC) const{ if( fabs(el->superClusterEta()) <= 1.479){ // if(pfElectronIso(el) < 0.0354) if(pfElectronIso(el) < relIsoB) // using the 25ns Effective Area return true; else return false; } // For the endcap else if (fabs(el->superClusterEta()) < 2.5){ // if(pfElectronIso(el) < 0.0646) if(pfElectronIso(el) < relIsoEC) // using the 25ns Effective Area return true; else return false; } return false; } bool ElectronSelection::identificationDisplacedElectron(const TRootElectron* el) const{ // cout << "entering the displaced Id electron" << endl; if( fabs(el->superClusterEta()) <= 1.479){ if ( el->sigmaIEtaIEta() < 0.0101 && fabs(el->deltaEtaIn()) < 0.00926 && fabs(el->deltaPhiIn()) < 0.0336 && el->hadronicOverEm() < 0.0597 && el->ioEmIoP() < 0.012 && el->missingHits() <= 2 // check wrt to expectedMissingInnerHits && el->passConversion()) { // cout << "the displaced Id electron is true" << endl; return true; } } // For the endcap else if (fabs(el->superClusterEta()) < 2.5) { if ( el->sigmaIEtaIEta() < 0.0279 && fabs(el->deltaEtaIn()) < 0.00724 && fabs(el->deltaPhiIn()) < 0.0918 && el->hadronicOverEm() < 0.0615 && el->ioEmIoP() < 0.00999 && el->missingHits() <= 1 // check wrt to expectedMissingInnerHits && el->passConversion()) { // cout << "the displaced Id electron is true" << endl; return true; } } return false; }
true
4fa37e29adc99c4491f00ebb1d22d3ace1e25cc1
C++
muthubro/Amber
/Amber/src/Amber/Math/Frustum.h
UTF-8
621
2.546875
3
[ "Apache-2.0" ]
permissive
#pragma once #include <glm/glm.hpp> namespace Amber { namespace Math { struct Frustum { glm::vec3 Focus; glm::vec3 Front, Up; float NearPlane, FarPlane; float HorizontalFOV, VerticalFOV; Frustum(); Frustum(const glm::vec3& focus, const glm::vec3& front, const glm::vec3 up, float nearPlane, float farPlane, float horizontalFOV, float verticalFOV); Frustum(const glm::mat4& transform, float verticalFOV, float nearClip, float farClip, float aspectRatio); glm::vec3 Right() const; std::array<glm::vec3, 8> GetCornerPoints() const; }; } // Math } // Amber
true
8139a158bba1d0878c0287fdf1350358da0534fe
C++
zhjc/HeuristicOptimization
/src/common/ho_logger.cpp
UTF-8
770
2.625
3
[]
no_license
#include "common/ho_logger.h" #include <iostream> using namespace std; HO_NAMESPACE_BEGIN(utility) HoLogger::HoLogger(const string& strLogName) { if (strLogName != "") { m_logFile.open(strLogName); if (!m_logFile.is_open()) { // error int m = -1; } m_logType = hoLog2File; } else { m_logType = hoLog2Std; } } void HoLogger::LogInfo(const std::string& strMsg) { if (!m_logFile.is_open()) { return; } if (m_logType == hoLog2File) { m_logFile << strMsg << endl; } else { cout << strMsg << endl; } } HoLogger::~HoLogger() { if (m_logFile.is_open()) { m_logFile.close(); } } HO_NAMESPACE_END
true
5691f5c6d35adddf951c0c92b22159a291df7be7
C++
15831944/applesales
/OneWorld/Include/owScene/TerrainTileFactory.h
GB18030
1,801
2.796875
3
[]
no_license
#ifndef OWSCENE_TILEFACTORY_H_ #define OWSCENE_TILEFACTORY_H_ #include <owScene/export.h> #include <osg/Referenced> #include <osg/Geode> #include <owScene/TerrainTile.h> #include <owScene/TileKey.h> #include <owScene/Terrain.h> namespace owScene { /** 鹤ࣺݡTilePagedLodҪֽ£TerrainTileReadWriter * лTerrainйcreateTilecreateTileᴴӦĿڵ㷵TerrainTileReadWriter * ռ뵽ȾcreateTileTerrainTileŵTerrain黺Уby the wayӻɾ * TilePagedLodĹ޳ * ⣺TerrainжԲвʱùӦupdate***¿ݡ */ class OWSCENE_EXPORT TerrainTileFactory : public osg::Referenced { friend class Terrain; public: TerrainTileFactory(Terrain* terrain); /** һ*/ osg::Node* createTile(const TileKey& tilekey); /** εĸڵ*/ osg::Group* createRoot(); private: ~TerrainTileFactory(){} //ӿ飬createTileʵǴĿӿ TerrainTile* createSubTile(const TileKey& tilekey); // TilekeyTerrainϵĵΧ SpatialProperty* calculateSpatialProperty(const TileKey& tilekey); // TerrainΧøڵϵķֿTileKey void getRootKeys(std::vector<TileKey>& keys); // TerrainΧijһοĵΧ void getTileDimensions(unsigned int lod, double& out_width, double& out_height); private: Terrain* _terrain; }; } #endif //OWSCENE_TILEFACTORY_H_
true
821d85f36f2d2bb32fd13ffbd8883f1feb366fb6
C++
Zathom/CarbonFootprintCalculator
/CarbonFootprintCalculator/CarbonFootprint.cpp
UTF-8
7,041
3.4375
3
[]
no_license
#include"CarbonFootprint.h" #include<iostream> using namespace std; //-----------CARBON FOOTPRINT FUNCTIONS---------- //-----------BUILDING FUNCTIONS---------- Building::Building() // DEFAULT CONSTRUCTOR. { cout << "Default building constructor executed...." << endl; } Building::Building(string bldType, double fuelQuan, double fuelInten)//OVERLOADED CONSTRUCTOR { cout << "Creating building object." << endl; buildingType = bldType; emissionsIntense = fuelInten; therms = fuelQuan; } string Building::getBuildingType() { return buildingType; } string Building::setBuildingType() { cout << "Enter building type: "; getline(cin, buildingType); return buildingType; } void Building::output() { cout << "Building type: " << getBuildingType() << endl; cout << "\tTons of fuel used: " << getTherms() << endl; cout << "\t Emissions intensity: " << "*** " << getEmisisonsIntensity() << " ***" << endl; } //BUILDING CLASS FUNCTIONS---------- double Building::getCarbonFootprint(double fuelQuantity, double emissionsIntensity) { cout << "*************************************************************************************" << endl; cout << "Class Building: Method: overloaded getCarbonFootprint: datatype: double. Executed..." << endl; cout << "*************************************************************************************" << endl; double carbonFootprint = fuelQuantity * emissionsIntensity; return carbonFootprint; } int Building::getCarbonFootprint(int fuelQuantity, int emissionsIntensity) { cout << "*************************************************************************************" << endl; cout << "Class Building: Method: overloaded getCarbonFootprint: datatype: Int. Executed..." << endl; cout << "*************************************************************************************" << endl; int carbonFootprint = fuelQuantity * emissionsIntensity; return carbonFootprint; } double Building::getTherms() { return therms; } double Building::setTherms() { cout << "Enter amount of fuel building consumes: "; cin >> therms; return therms; } double Building::getEmisisonsIntensity() { return emissionsIntense; } double Building::setEmissionsIntensity() { cout << "Enter building emissions intensity: "; cin >> emissionsIntense; return emissionsIntense; } //======================================================================= //-----------BICYCLE---------- double Bicycle::getCarbonFootprint(double breathRate, double emissionsIntensity) { cout << "*************************************************************************************" << endl; cout << "Class Bicycle: Method: overloaded getCarbonFootprint: datatype: double. Executed..." << endl; cout << "*************************************************************************************" << endl; double carbonFootprint = breathRate * emissionsIntensity; return carbonFootprint; } int Bicycle::getCarbonFootprint(int breathRate, int emissionsIntensity) { cout << "*************************************************************************************" << endl; cout << "Class Bicycle: Method: overloaded getCarbonFootprint: datatype: Int. Executed..." << endl; cout << "*************************************************************************************" << endl; int carbonFootprint = breathRate * emissionsIntensity; return carbonFootprint; } void Bicycle::output() { cout << "Bicycle type: " << getBikeMake() << endl; cout << "\tUser breath rate: " << getBreathRate() << "/sec.5" << endl; cout << "\t Emissions on use: " << "*** " << getInitialEmissions() << " ***" << endl; } Bicycle::Bicycle()//DEFAULT CONSTRUCTOR. { cout << "Default bicycle constructor executed....." << endl; } Bicycle::Bicycle(string bikeType, double bRate, double iEmm)//OVERLOADED CONSTRUCTOR { cout << "Creating bicycle object." << endl; bicycleType = bikeType; breathRate = bRate; initialEmission = iEmm; } string Bicycle::getBikeMake() { return bicycleType; } double Bicycle::getBreathRate() { return breathRate; } double Bicycle::getInitialEmissions() { return initialEmission; } string Bicycle::setBikeMake() { cout << "Enter bike manufacturor/make: "; getline(cin, bicycleType); return bicycleType; } double Bicycle::setBreathRate() { cout << "Enter the breathrate of the rider as they pedal: "; cin >> breathRate; return breathRate; } double Bicycle::setInitialEmissions() { cout << "Enter emissions of use: "; cin >> initialEmission; return initialEmission; } //-----------CAR----------- void Car::output() { cout << "Fuel type: " << getFuelType() << endl; cout << "\t Mileage: " << getMilesDriven() << " miles." << endl; cout << "\t fuel tank/charge volume: " << getTankVolume() << " gallons/watts" << endl; cout << "\t Co2 emitted per mile: " << getFuelEmittedPerMile() << "/mile." << endl; } Car::Car()//DEFAULT CONSTRUCTOR { cout << "Car default constructor executed." << endl; } Car::Car(string fT, double mD, double tV, double fPm)//OVERLOADED CONSTRUCTOR { cout << "Creating car object." << endl; fuel = fT; milesDriven = mD; tankVolume = tV; fuelEmittedPerMile = fPm; } double Car::getCarbonFootprint(double fuelEfficiency, double fuelPerMile) { cout << "*************************************************************************************" << endl; cout << "Class Car: Method: overloaded getCarbonFootprint: datatype: double. Executed..." << endl; cout << "*************************************************************************************" << endl; double carbonFootprint = fuelEfficiency - fuelPerMile; //Fuel efficiency (MilesTraveled/TankVolume) - Carbon expelled per mile. return carbonFootprint; } int Car::getCarbonFootprint(int fuelEfficiency, int fuelPerMile) { cout << "*************************************************************************************" << endl; cout << "Class Car: Method: overloaded getCarbonFootprint: datatype: Int. Executed..." << endl; cout << "*************************************************************************************" << endl; int carbonFootprint = fuelEfficiency - fuelPerMile; return carbonFootprint; } string Car::getFuelType() { return fuel; } double Car::getMilesDriven() { return milesDriven; } double Car::getTankVolume() { return tankVolume; } double Car::getFuelEfficiency(double mT, double fT) { fuelEfficiency = mT / fT; return fuelEfficiency; } double Car::getFuelEmittedPerMile() { return fuelEmittedPerMile; } string Car::setFuelType() { cout << "Enter fuel type: "; cin >> fuel; return fuel; } double Car::setMilesDriven() { cout << "Enter total vehicle mileage: "; cin >> milesDriven; return milesDriven; } double Car::setTankVolume() { cout << "Enter total fuel tank volume: "; cin >> tankVolume; return tankVolume; } double Car::setFuelEfficiency() { cout << "Enter fuel efficiency: "; cin >> fuelEfficiency; return fuelEfficiency; } double Car::setFuelEmittedPerMile() { cout << "Enter fuel emitted per mile: "; cin >> fuelEmittedPerMile; return fuelEmittedPerMile; }
true
7094e2ffc13b0d688a84b66d3bc781fb086015d2
C++
imane0897/PAT
/1052.cpp
UTF-8
996
2.59375
3
[]
no_license
#include <iostream> #include <stdio.h> #include <algorithm> using namespace std; const int MAXN = 100010; struct num { int add; int val; int next; } ; bool cmp (num a, num b) { return a.val < b.val; } int main(void) { int n, m, i, head_add, b[MAXN] = {0}, c[MAXN] = {0}; num a[MAXN]; cin >> n >> head_add; for (i = 0; i < n; i++) { cin >> a[i].add >> a[i].val >> a[i].next; b[a[i].add] = a[i].next; } while (head_add != -1) { c[head_add] = 1; head_add = b[head_add]; } m = 0; for (i = 0; i < MAXN; i++) { if (c[i]) { m++; } } sort(a, a+n, cmp); cout << m; for (i = 0; i < n; i++) { if (c[a[i].add]) { string res_add = to_string(a[i].add); while (res_add.size() < 5) res_add = "0" + res_add; cout << ' ' << res_add << '\n' << res_add << ' ' << a[i].val; } } cout << " -1" << endl; return 0; }
true
cdd19e10b7cc0c1d70088b790563fafb92933ddf
C++
BITXUJI/C---primer--code-note
/pointerassignment-p49.cpp
UTF-8
436
3.125
3
[]
no_license
#include <iostream> int main(int argc, const char **argv) { int i = 42; int *pi = 0; //int &ri = 0 ; is error int *pi2 = &i; //int &ri2 = i; is ok int *pi3; // int &ri3; is error pi3 = pi2; pi2 = 0; int ival; pi = &ival; *pi = 0; std::cout << ival << " " << *pi << std::endl; pi = 0; if (!pi) { std::cout << "Pointer pi is nullptr" << std::endl; } return 0; }
true
0a4642a6ffabe67cee3cb89bd90437a9095af329
C++
IslamAdam/SPOT_extra_features_added
/Actions/Action.h
UTF-8
368
2.515625
3
[]
no_license
#pragma once #include"..//GUI/Drawable.h" class Registrar; //forward class declaration //Base class for all possible actions (abstract class) class Action { protected: Registrar* pReg; public: Action(Registrar* p) { pReg = p; }; //Execute action (code depends on action type) bool virtual Execute() = 0; //pure virtual virtual ~Action() {} };
true
4f4b129ed8cce7b71f0b86042f771898871d34bb
C++
muneebarshad/Board-Game-40Thieves
/implementation/src/GameBoard.cpp
UTF-8
6,144
3.25
3
[]
no_license
#include <iostream> #include <vector> #include "../include/GameBoard.h" #include "../include/CardStack.h" #include "../include/CardTypes.h" #include <stdexcept> using namespace std; BoardT::BoardT(vector<CardT> deck){ int count=0; vector<CardT> null {}; for(unsigned int i =0 ; i < deck.size(); i++){ for(unsigned int j=0; j < deck.size(); j++){ if((i != j ) && (deck[i].r == deck[j].r) && (deck[i].s == deck[j].s)){ count = count + 1; } } } if (count == 104){ for (int i =0; i < 10; i++){ CardStackT new_stack; for (int j=0; j<4; j++){ new_stack = new_stack.push(deck[(4*i) + j]); } this->Tableau.push_back(new_stack); } for (int i = 0; i < 8; i++){ CardStackT new_stack; this->Foundation.push_back(new_stack); } this->deck = CardStackT(null); for (int i =40; i < 104; i++){ this->deck = this->deck.push(deck[i]); } this->waste = CardStackT(null); } else{ throw std::invalid_argument("No two decks"); } }; CardStackT BoardT::get_tab(int index){ if (0 <= index && index <10){ std::vector<CardStackT> seq; seq = this->Tableau; return seq[index]; } else { throw std::out_of_range("Tableau out of range"); } } CardStackT BoardT::get_foundation(int index){ if (0 <= index && index <8){ return this->Foundation[index]; } else { throw std::out_of_range("Foundation out of range"); } } CardStackT BoardT::get_deck(){ return this->deck; } CardStackT BoardT::get_waste(){ return this->waste; } bool BoardT::is_valid_tab_mv(CategoryT c, int n_0 , int n_1){ if (c == 0){ if (is_valid_pos(static_cast<CategoryT>(0),n_0) && is_valid_pos(static_cast<CategoryT>(0),n_1)){ return valid_tab_tab(n_0,n_1); } else{ throw std::out_of_range("Tableau out of range"); } } else if ( c == 1){ if (is_valid_pos(static_cast<CategoryT>(0),n_0) && is_valid_pos(static_cast<CategoryT>(1),n_1)){ return valid_tab_foundation(n_0,n_1); } else{ throw std::out_of_range("Tableau or Foundation out of range"); } } else{ return false; } } bool BoardT::valid_tab_tab(int n_0 , int n_1){ if (this->Tableau[n_0].size() > 0){ if (this->Tableau[n_1].size() > 0){ return tab_placeable(this->Tableau[n_0].top() , this->Tableau[n_1].top()); } else{ return true; } } else{ return false; } } bool BoardT::valid_tab_foundation(int n_0, int n_1){ if( this->Tableau[n_0].size() > 0){ if ( this->Foundation[n_1].size() > 0){ return foundation_placeable(this->Tableau[n_0].top() , this->Foundation[n_1].top()); } else{ if (this->Tableau[n_0].top().r == ACE ){ return true; } else{ return false; } } } else{ return false; } } bool BoardT::tab_placeable(CardT card1 , CardT card2){ if ((card1.s == card2.s) && (card1.r == card2.r - 1) ){ return true; } else{ return false; } } bool BoardT::foundation_placeable(CardT card1 , CardT card2){ if ((card1.s == card2.s) && (card1.r == card2.r + 1) ){ return true; } else{ return false; } } bool BoardT::is_valid_waste_mv(CategoryT c , int n){ if(this->waste.size() == 0){ throw std::invalid_argument("Waste empty"); } if ( c ==0){ if(is_valid_pos(static_cast<CategoryT>(0),n)){ return valid_waste_tab(n); } else{ throw std::out_of_range("Tableau out of range"); } } else if (c == 1){ if(is_valid_pos(static_cast<CategoryT>(1),n)){ return valid_waste_foundation(n); } else{ throw std::out_of_range("Tableau out of range"); } } else{ return false; } } bool BoardT::valid_waste_tab(int n){ if (this->Tableau[n].size() > 0){ return tab_placeable(this->waste.top(),this->Tableau[n].top()); } else{ return true; } } bool BoardT::valid_waste_foundation(int n){ if (this->Foundation[n].size() > 0){ return foundation_placeable(this->waste.top(),this->Foundation[n].top()); } else{ return (this->waste.top().r == ACE); } } bool BoardT::is_valid_deck_mv(){ return this->deck.size() > 0; } void BoardT::tab_mv(CategoryT c , int n_0, int n_1){ if (is_valid_tab_mv(c,n_0 , n_1)){ if (c ==0){ CardT mov = this->Tableau[n_0].top(); this->Tableau[n_1] = this->Tableau[n_1].push(mov); this->Tableau[n_0] = this->Tableau[n_0].pop(); //cout << "Card moved from Tab to a different Tab" << endl; } else{ CardT mov = this->Tableau[n_0].top(); this->Foundation[n_1] = this->Foundation[n_1].push(mov); this->Tableau[n_0] = this->Tableau[n_0].pop(); //cout << "Card moved from Tab to foundation" << endl; } } else{ throw std::invalid_argument("Tab move not valid"); } } void BoardT::waste_mv(CategoryT c , int n){ if (is_valid_waste_mv(c,n) == 1){ if ( c == 0){ CardT mov = this->waste.top(); this->Tableau[n] = this->Tableau[n].push(mov); this->waste = this->waste.pop(); } else{ CardT mov = this->waste.top(); this->Foundation[n] = this->Foundation[n].push(mov); this->waste = this->waste.pop(); } } else{ throw std::invalid_argument("Waste move not valid"); } } void BoardT::deck_mv(){ if (is_valid_deck_mv() == 1){ CardT mov = deck.top(); this->deck = this->deck.pop(); this->waste = this->waste.push(mov); } else{ throw std::invalid_argument("Move from Deck to Waste not valid"); } } bool BoardT::valid_mv_exists(){ if(is_valid_deck_mv()){ return true; } int validMv = 0; CategoryT c; for (int i =0; i<2; i++){ c = static_cast<CategoryT>(i); for(int n_0 = 0; n_0<10; n_0++){ for (int n_1 =0; n_1 < 10; n_1++){ if(!((i==0) && (n_0 == n_1))){ if((is_valid_pos(static_cast<CategoryT>(0),n_0)) && (is_valid_pos(c,n_1))){ validMv = validMv || is_valid_tab_mv(c,n_0,n_1) || is_valid_waste_mv(c,n_1); } } } } } return validMv; } bool BoardT::is_win_state(){ bool win = 1; for (int i=0; i <8; i++){ win = win && ((this->Foundation[i].size() > 0) && this->Foundation[i].top().r == 13); } return win; } bool BoardT::is_valid_pos(CategoryT c , int n){ if (c ==0){ return n < 10; } else if(c ==1){ return n < 8; } else{ return false; } }
true
b0dbdcc44e33bf522a42be524ebe44f28b386216
C++
AMazur2/UXP-Linda-Potoki
/src/data.cpp
UTF-8
1,521
3.265625
3
[]
no_license
#include<iostream> #include<sstream> #include<cstdarg> #include"data.hpp" Data::Data() = default; Data::Data(const char* fmt...) { va_list args; va_start(args, fmt); std::string format = fmt; for (int i = 0; i < 100 && i < format.size() && *fmt != '\0'; ++i, ++fmt) { if (*fmt == 's') { values.emplace_back(std::string(va_arg(args, char*))); } else if (*fmt == 'i') { values.emplace_back(va_arg(args, int)); } else if (*fmt == 'f') { values.emplace_back(va_arg(args, double)); } } va_end(args); } Data::Data(const std::vector<DataElement>& elements) { for (auto & element : elements) { values.push_back(element); } } const DataElement& Data::operator[](std::size_t idx) const { return values[idx]; } Data::Data(const std::vector<DataElement>& elements) { for (auto & element : elements) { values.push_back(element); } } bool Data::compare(const DataPattern& pattern) const { if (values.size() != pattern.size()) return false; for (int i = 0; i < values.size(); i++) { if (!values[i].compare(pattern[i])) { return false; } } return true; } std::string Data::to_string() { std::stringstream ss; ss << *this; return ss.str(); } std::ostream &operator<< (std::ostream &os, const Data& data) { os << "("; for (const auto & value : data.values) { os << value << ", "; } os << ")"; return os; }
true
5335f660dbd44deb3c96511824bc539f4e3f071e
C++
apoorv-gupta/topcoder
/M/MathContest.cpp
UTF-8
3,435
2.796875
3
[]
no_license
#include <vector> #include <list> #include <map> #include <set> #include <queue> #include <deque> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime> using namespace std; class MathContest { public: int countBlack(string b, int repetitions) { vector < char > balls; while(repetitions--) for(int i=0;i<b.size();++i) balls.push_back(b[i]); vector < char > ::iterator f=balls.begin(); vector < char > ::reverse_iterator e = balls.rbegin(); int ans =0; int done=0; int n = balls.size(); int dir=0; int change=0; while(done<n){ char val; if(dir==0) val = *f++; else val = *e++; if(val=='B') val = 0; else val = 1; if(change) val^=1; if(val==0){//it was black ans++; change^=1; } else dir^=1; done++; } return ans; } }; // BEGIN KAWIGIEDIT TESTING // Generated by KawigiEdit 2.1.4 (beta) modified by pivanof bool KawigiEdit_RunTest(int testNum, string p0, int p1, bool hasAnswer, int p2) { cout << "Test " << testNum << ": [" << "\"" << p0 << "\"" << "," << p1; cout << "]" << endl; MathContest *obj; int answer; obj = new MathContest(); clock_t startTime = clock(); answer = obj->countBlack(p0, p1); clock_t endTime = clock(); delete obj; bool res; res = true; cout << "Time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " seconds" << endl; if (hasAnswer) { cout << "Desired answer:" << endl; cout << "\t" << p2 << endl; } cout << "Your answer:" << endl; cout << "\t" << answer << endl; if (hasAnswer) { res = answer == p2; } if (!res) { cout << "DOESN'T MATCH!!!!" << endl; } else if (double(endTime - startTime) / CLOCKS_PER_SEC >= 2) { cout << "FAIL the timeout" << endl; res = false; } else if (hasAnswer) { cout << "Match :-)" << endl; } else { cout << "OK, but is it right?" << endl; } cout << "" << endl; return res; } int main() { bool all_right; all_right = true; string p0; int p1; int p2; { // ----- test 0 ----- p0 = "BBWWB"; p1 = 1; p2 = 2; all_right = KawigiEdit_RunTest(0, p0, p1, true, p2) && all_right; // ------------------ } { // ----- test 1 ----- p0 = "BBB"; p1 = 10; p2 = 1; all_right = KawigiEdit_RunTest(1, p0, p1, true, p2) && all_right; // ------------------ } { // ----- test 2 ----- p0 = "BW"; p1 = 10; p2 = 20; all_right = KawigiEdit_RunTest(2, p0, p1, true, p2) && all_right; // ------------------ } { // ----- test 3 ----- p0 = "WWWWWWWBWWWWWWWWWWWWWW"; p1 = 1; p2 = 2; all_right = KawigiEdit_RunTest(3, p0, p1, true, p2) && all_right; // ------------------ } if (all_right) { cout << "You're a stud (at least on the example cases)!" << endl; } else { cout << "Some of the test cases had errors." << endl; } return 0; } // END KAWIGIEDIT TESTING //Powered by KawigiEdit 2.1.4 (beta) modified by pivanof!
true
5b1e9a706143f9c623605890a3e8c0013737d721
C++
jinzhu6/line-follower
/read-sensor.cc
UTF-8
2,401
2.53125
3
[]
no_license
#include "robot.h" int param; int left_ir = 0x01; // bit 0: ’0000 0001’ int mid_ir = 0x02; // bit 1: ’0000 0010’ int right_ir = 0x04; // bit 2: ’0000 0100’ int shirt_bit5 = 0x20; // bit 5: '0010 0000' int shirt_bit6 = 0x40; // bit 6: '0100 0000' int read_line() { int result = 0; param = rlink.request(READ_PORT_1); if (param bitand left_ir) { result += 100; } if (param bitand mid_ir) { result += 10; } if (param bitand right_ir) { result += 1; } return result; // binary representation of IR sensor readings: left, mid, right } int read_LDR() { int param = rlink.request(ADC1); return param; } int shirt_colour() { int bucket_white = 0; int bucket_yellow = 0; int bucket_green = 0; int bucket_none = 0; for(int i=0;i<100;i++) { int v = rlink.request (ADC3); cout << v << endl; if(v >= 95 && v <= 105) { bucket_white++; } else if(v >= 65 && v <= 70) { bucket_green++; } else if(v >= 72 && v <= 77) { bucket_yellow++; } else if(v >= 155) { bucket_none++; } delay(10); } #ifdef DEBUG cout << bucket_yellow << " yellow" << endl; cout << bucket_green << " green" << endl; cout << bucket_white << " white" << endl; cout << bucket_none << " none" << endl; #endif int shirt = SHIRT_NONE; if(bucket_white >= bucket_yellow && bucket_white >= bucket_green && bucket_white >= bucket_none) { shirt = SHIRT_WHITE; cout << "Shirt: white (11)" << endl; } else if(bucket_yellow >= bucket_white && bucket_yellow >= bucket_green && bucket_yellow >= bucket_none) { shirt = SHIRT_YELLOW; cout << "Shirt: yellow (01)" << endl; } else if(bucket_green >= bucket_yellow && bucket_green >= bucket_white && bucket_green >= bucket_none) { shirt = SHIRT_GREEN; cout << "Shirt: green (10)" << endl; } else { shirt = SHIRT_NONE; cout << "Shirt: none (00)" << endl; } current_shirt = shirt; update_IO(); return shirt; } void update_IO() { int line_param = left_ir bitor mid_ir bitor right_ir; int grabber_param = 0x00; if(grabber_on == 0) { grabber_param = grabber_bit; } int shirt_param = shirt_bit5 bitor shirt_bit6; if(current_shirt == SHIRT_WHITE) { shirt_param = 0x00; } else if(current_shirt == SHIRT_YELLOW) { shirt_param = shirt_bit5; } else if(current_shirt == SHIRT_GREEN) { shirt_param = shirt_bit6; } param = line_param bitor grabber_param bitor shirt_param; rlink.command (WRITE_PORT_1, param); }
true
ed02884ef17b06cf21ab9bab64e6f161cb5ac271
C++
ckormanyos/real-time-cpp
/examples/chapter16_08/src/util/utility/util_numeric_cast.h
UTF-8
1,649
2.6875
3
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference", "LGPL-3.0-only" ]
permissive
/////////////////////////////////////////////////////////////////// // Copyright Christopher Kormanyos 2009 - 2021. // // Distributed under the Boost Software License, // // Version 1.0. (See accompanying file LICENSE_1_0.txt // // or copy at http://www.boost.org/LICENSE_1_0.txt) // /////////////////////////////////////////////////////////////////// #ifndef UTIL_NUMERIC_CAST_2009_11_24_H_ #define UTIL_NUMERIC_CAST_2009_11_24_H_ #include <sstream> #include <string> #include <type_traits> namespace Util { template<typename T> inline T numeric_cast(const std::string& str) { constexpr bool numeric_cast_is_signed = (std::numeric_limits<T>::is_signed == true); constexpr bool numeric_cast_is_small_type = ( ((numeric_cast_is_signed == true) && (std::numeric_limits<T>::digits <= 31)) || ((numeric_cast_is_signed == false) && (std::numeric_limits<T>::digits <= 32))); using value_type = typename std::conditional<(numeric_cast_is_small_type == true), typename std::conditional<(numeric_cast_is_signed == true), std::int32_t, std::uint32_t>::type, T >::type; // This could be done with a variation of "baselexical_cast". std::stringstream ss; ss << str; value_type t; ss >> t; return (T) t; } } #endif // UTIL_NUMERIC_CAST_2009_11_24_H_
true
21cfc0ed94f26828b1091573cf6ff52449b587a4
C++
VDoring/CPP-My-Study-Functions
/초보자를 위한 C++ 200제/146.cpp
UHC
1,214
3.5625
4
[]
no_license
//146 //tuple ϱ(make tuple, get) #include <iostream> #include <tuple> #include <string> using namespace std; int main() { typedef tuple<string, int, double>Data; //typedef ̿ Ʃ Ѵ. Data Ʃ string, int, double 3 ڷ ִ. Data data1("ڿ", 10, 1.2); //Ʃ Data ü ʱȭѴ. auto data2 = make_tuple("ڿ", 10, 1.2); //( ε ٰ ) cout << get<0>(data1) << ", " << get<1>(data1) << ", " << get<2>(data1) << endl; //Ʃÿ ִ ʹ get ̿ ִ. get ڿ <> ε ȣ ְ, () ȿ Ʃ ü ̸ Ѵ. return 0; } /* ϳ ̳, ϳ ϳ ڷ ־ ߴ. tuple ̿ϸ ڷ ٷ ִ. ܼ ڷḦ ϰų ڷ ̿ پ ڷ ü Ѳ ٷ Ҿ ϰ Ȱ ִ. */
true
be6526eadfaace0c91a258a8091947340456b09c
C++
tabvn/ued
/finalExam2018/part1/max3so.cpp
UTF-8
201
2.546875
3
[]
no_license
#include <iostream> using namespace std; int main(){ long long a,b,c; cin >> a >> b >> c; long long max = a; if(b > max){ max = b; } if(c > max){ max = c; } cout << max; return 0; }
true
965cc7163f2c76fca4f90b0ecf41d1e76bc325e5
C++
CJT-Jackton/The-Color-of-Tea
/Textures.cpp
UTF-8
6,090
2.65625
3
[ "BSD-2-Clause" ]
permissive
// // Textures // // Created by Warren R. Carithers 2016/11/22. // Based on code created by Joe Geigel on 1/23/13. // Copyright 2016 Rochester Institute of Technology. All rights reserved. // // Contributor: Jietong Chen // // Simple class for setting up texture mapping parameters. // // This code can be compiled as either C or C++. // #ifdef __cplusplus #include <iostream> #else #include <stdio.h> #endif #include "Textures.h" // this is here in case you are using SOIL; // if you're not, it can be deleted. #include <SOIL.h> #include <cstdio> #ifdef __cplusplus using namespace std; #endif // the texture handle of cup GLuint Texture::cup; // the texture handle of foliage GLuint Texture::foliage1; GLuint Texture::foliage2; GLuint Texture::foliage3; GLuint Texture::foliage4; /// // This function loads texture data for the GPU. /// void loadTexture() { // load the cup image by SOIL Texture::cup = SOIL_load_OGL_texture( "texture/blueberry.png", SOIL_LOAD_AUTO, SOIL_CREATE_NEW_ID, SOIL_FLAG_MIPMAPS | SOIL_FLAG_INVERT_Y | SOIL_FLAG_NTSC_SAFE_RGB | SOIL_FLAG_COMPRESS_TO_DXT ); if( Texture::cup == 0 ) { printf( "SOIL loading error: '%s'\n", SOIL_last_result() ); } // set up the texture parameters glBindTexture( GL_TEXTURE_2D, Texture::cup ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); // load the first foliage image by SOIL Texture::foliage1 = SOIL_load_OGL_texture( "texture/foliage1.png", SOIL_LOAD_AUTO, SOIL_CREATE_NEW_ID, SOIL_FLAG_MIPMAPS | SOIL_FLAG_INVERT_Y | SOIL_FLAG_NTSC_SAFE_RGB | SOIL_FLAG_COMPRESS_TO_DXT ); if( Texture::foliage1 == 0 ) { printf( "SOIL loading error: '%s'\n", SOIL_last_result() ); } // set up the texture parameters glBindTexture( GL_TEXTURE_2D, Texture::foliage1 ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); // load the second foliage image by SOIL Texture::foliage2 = SOIL_load_OGL_texture( "texture/foliage2.png", SOIL_LOAD_AUTO, SOIL_CREATE_NEW_ID, SOIL_FLAG_MIPMAPS | SOIL_FLAG_INVERT_Y | SOIL_FLAG_NTSC_SAFE_RGB | SOIL_FLAG_COMPRESS_TO_DXT ); if( Texture::foliage2 == 0 ) { printf( "SOIL loading error: '%s'\n", SOIL_last_result() ); } // set up the texture parameters glBindTexture( GL_TEXTURE_2D, Texture::foliage2 ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); // load the third foliage image by SOIL Texture::foliage3 = SOIL_load_OGL_texture( "texture/foliage3.png", SOIL_LOAD_AUTO, SOIL_CREATE_NEW_ID, SOIL_FLAG_MIPMAPS | SOIL_FLAG_INVERT_Y | SOIL_FLAG_NTSC_SAFE_RGB | SOIL_FLAG_COMPRESS_TO_DXT ); if( Texture::foliage3 == 0 ) { printf( "SOIL loading error: '%s'\n", SOIL_last_result() ); } // set up the texture parameters glBindTexture( GL_TEXTURE_2D, Texture::foliage3 ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); // load the fourth foliage image by SOIL Texture::foliage4 = SOIL_load_OGL_texture( "texture/foliage4.png", SOIL_LOAD_AUTO, SOIL_CREATE_NEW_ID, SOIL_FLAG_MIPMAPS | SOIL_FLAG_INVERT_Y | SOIL_FLAG_NTSC_SAFE_RGB | SOIL_FLAG_COMPRESS_TO_DXT ); if( Texture::foliage4 == 0 ) { printf( "SOIL loading error: '%s'\n", SOIL_last_result() ); } // set up the texture parameters glBindTexture( GL_TEXTURE_2D, Texture::foliage4 ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); } /// // This function sets up the parameters for texture use. // // @param texture - The OpenGL texture handle of the texture to use /// void setUpTexture( GLuint texture ) { glBindTexture( GL_TEXTURE_2D, texture ); }
true
e1169804720151aa0811b559e44dcc8707a7f0e8
C++
a8a3/algorithms
/strings/include/fsm.hpp
UTF-8
1,463
3.15625
3
[]
no_license
#pragma once #include <string> #include <vector> namespace fsm { using table = std::vector<std::vector<int>>; // ------------------------------------------------------------------ std::string left(const std::string& s, size_t idx) { return s.substr(0, idx); } // ------------------------------------------------------------------ std::string right(const std::string& s, size_t idx) { const auto len = s.length(); return s.substr(len-idx); } // ------------------------------------------------------------------ table build_table(const std::string& pattern) { constexpr auto alphabet_len = 2; // AB const int p_len = pattern.length(); table t; for (int p = 0; p < p_len; ++p) { t.emplace_back(alphabet_len); for (char a = 'A'; a <= 'B'; ++a) { const auto candidate = left(pattern, p) + a; int len = p + 1; while (left(pattern, len) != right(candidate, len)) { --len; } t[p][a-'A'] = len; } } return t; } // ABAAABAB // ABAB // ------------------------------------------------------------------ int search(const std::string& text, const std::string& pattern) { const auto table = build_table(pattern); int p_len = pattern.length(); int state = 0; for(int i = 0, len = text.length(); i < len; ++i) { state = table[state][text[i]-'A']; if (state == p_len) { return i - (p_len-1); } } return -1; } } // fsm
true
f6dd08a60f45dc0b9d9df8506504e5cfbbaf3e5d
C++
roystjohn/challenges
/unfairness/unfairness/main.cpp
UTF-8
1,464
3.71875
4
[]
no_license
// // main.cpp // unfairness // // Created by Roy St. John on 3/7/15. // Copyright (c) 2015 Roy St. John. All rights reserved. // // From an entry of N integers, group K integers in a // way that minimizes unfairness, where unfairness is // the max of the group of integers minus the minimum // of the group of integers. #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int minMax(int *candies, int N, int K) { int minimum_value; minimum_value = candies[K-1] - candies[0]; for(int x = K; x < N; x++) { if(minimum_value > candies[x] - candies[x-K+1]) { minimum_value = candies[x] - candies[x-K+1]; } } return minimum_value; } // It is NOT mandatory to use the provided template. You can handle the IO section differently. int main() { /* The code required to enter n,k, candies is provided*/ int N, K, unfairness; cin >> N >> K; int candies[N]; for (int i=0; i<N; i++) { cin >> candies[i]; for(int z = i; z > 0 && candies[z - 1] > candies[z]; z--) { int temp = candies[z]; candies[z] = candies[z - 1]; candies[z - 1] = temp; } } /** Write the solution code here. Compute the result, store in the variable unfairness -- and output it**/ unfairness = minMax(candies, N, K); cout << unfairness << "\n"; return 0; }
true
531acb01e76ed9f7af39945cec7d1fc698f44978
C++
ryanpflynn/network-file-client
/main1.cpp
UTF-8
5,350
3.328125
3
[]
no_license
/************************* * Ryan Flynn * Network File Transfer Client **************************/ #include <iostream> #include <string> #include <cstdlib> #include "Winsock2.h" #include "Socket1.h" using namespace std; bool checkName(string, string); char* stringToCharArray(string); bool checkCommand (string, Socket&); void receiveDir(Socket&); void receiveFile(Socket&); int main() { //Variables definitions: string ipAddress; int port = 54321; char recMessage[STRLEN]; string userId; string command; cout << "Enter the Server's ip address: "; cin >> ipAddress; ClientSocket sockClient; sockClient.ConnectToServer(ipAddress.c_str(), port); sockClient.RecvData( recMessage, STRLEN ); if (checkName("LOGIN", recMessage)== false) { sockClient.CloseConnection(); }else{ cout << "Please enter the user-identifier: "; cin >> userId; sockClient.SendData(stringToCharArray(userId)); cin.clear(); cin.ignore(1000, '\n'); //Removing the /n character for the next getline. } sockClient.RecvData( recMessage, STRLEN ); if (checkName("WELCOME", recMessage)== false) { sockClient.CloseConnection(); return 0; }else{ while(true) { cout << "Please enter the command: "; getline(cin, command); sockClient.SendData(stringToCharArray(command)); if (checkCommand(command, sockClient) == false) break; } } return 0; } /******************** * Name: checkName * Purpose: Verify the server keywords "LOGIN" and "WELCOME". * Arguments: required keyword, keyword send by the server. * Returns: true if matched, false otherwise ********************/ bool checkName(string keyword, string message){ if(keyword == message) { return true; }else{ return false; } } /******************** * Name: stringToCharArray * Purpose: Converts a string in a character array to send via the socket. * Arguments: String to be converted * Returns: New C-style string. ********************/ char* stringToCharArray(string oldStr){ char *newCStr = new char[oldStr.size()+1]; strcpy(newCStr, oldStr.c_str()); return newCStr; } /******************** * Name: checkCommand * Purpose: Verify the command sent to the server to be prepare for the response. * Arguments: Command send to the server. Socket to receive data. * Returns: true to exit keep the client running. False to finish the program. ********************/ bool checkCommand (string command, Socket& sockClient){ const int STRLEN = 256; char recMessage[STRLEN]; if (command.substr(0,4) == "LIST") { receiveDir(sockClient); return true; } else if (command.substr(0,4) == "SEND") { receiveFile(sockClient); return true; } else if (command.substr(0,4) == "QUIT") { sockClient.CloseConnection(); cout << "Connection close by the server. Exiting the program" << endl; return false; } else { sockClient.RecvData( recMessage, STRLEN ); if (checkName("ERROR", recMessage)== true) { cout << "Command not found" << endl; return true; } } } /******************** * Name: receiveDir * Purpose: Receive the contents of the server's current directory. * Arguments: Socket to receive data. * Returns: Nothing. ********************/ void receiveDir(Socket& sockClient){ char recMessage[STRLEN]; string output; sockClient.RecvData( recMessage, STRLEN ); //if (recMessage[0]!=1){ //string format(recMessage); //output=format.substr(1); //Eliminates character at the beginning of the string. //cout << output; //}else{ cout << recMessage; //} } /******************** * Name: receiveFile * Purpose: Receive requested file from the server. * Arguments: Socket to receive data. * Returns: Nothing. ********************/ void receiveFile(Socket& sockClient){ char filename[256]; char recMessage[256]; //If receive file fails, exit the function if(sockClient.ReceiveFile(filename)==false) { return; } //Get EOF message sockClient.RecvData( recMessage, STRLEN ); if (checkName("EOFEOFEOFEOFEOFEOF", recMessage)== false) { sockClient.CloseConnection(); }else{ sockClient.SendData(stringToCharArray("EOF OK")); sockClient.RecvData( recMessage, STRLEN ); cout << "---File Transferred Successfully---\n" << endl; if (checkName("OK", recMessage)== false) sockClient.CloseConnection(); } }
true
f22348ddf0fe1d0debc22fb7eb8344aabe408521
C++
skypjack/uvw
/src/uvw/idle.h
UTF-8
1,415
2.625
3
[ "MIT", "CC-BY-SA-4.0" ]
permissive
#ifndef UVW_IDLE_INCLUDE_H #define UVW_IDLE_INCLUDE_H #include <uv.h> #include "handle.hpp" #include "loop.h" namespace uvw { /*! @brief Idle event. */ struct idle_event {}; /** * @brief The idle handle. * * Idle handles will emit a idle event once per loop iteration, right before the * prepare handles. * * The notable difference with prepare handles is that when there are active * idle handles, the loop will perform a zero timeout poll instead of blocking * for I/O. * * @note * Despite the name, idle handles will emit events on every loop iteration, not * when the loop is actually _idle_. * * To create an `idle_handle` through a `loop`, no arguments are required. */ class idle_handle final: public handle<idle_handle, uv_idle_t, idle_event> { static void start_callback(uv_idle_t *hndl); public: using handle::handle; /** * @brief Initializes the handle. * @return Underlying return value. */ int init(); /** * @brief Starts the handle. * * An idle event will be emitted once per loop iteration, right before * polling the prepare handles. * * @return Underlying return value. */ int start(); /** * @brief Stops the handle. * * @return Underlying return value. */ int stop(); }; } // namespace uvw #ifndef UVW_AS_LIB # include "idle.cpp" #endif #endif // UVW_IDLE_INCLUDE_H
true
8b85df22126c5a516b6f51c9591aa0996ea5c7ef
C++
pvsmpraveen/MissionRnd
/Advanced C/C-MRND2017_WinterCamp/spec/P1_ZerosOnesSpec.cpp
UTF-8
3,846
3.390625
3
[]
no_license
#include "stdafx.h" #include "../src/P1_ZerosOnes.cpp" using namespace System; using namespace System::Text; using namespace System::Collections::Generic; using namespace Microsoft::VisualStudio::TestTools::UnitTesting; namespace spec { [TestClass] public ref class P1_ZerosOnesSpec { private: TestContext^ testContextInstance; public: /// <summary> ///Gets or sets the test context which provides ///information about and functionality for the current test run. ///</summary> property Microsoft::VisualStudio::TestTools::UnitTesting::TestContext^ TestContext { Microsoft::VisualStudio::TestTools::UnitTesting::TestContext^ get() { return testContextInstance; } System::Void set(Microsoft::VisualStudio::TestTools::UnitTesting::TestContext^ value) { testContextInstance = value; } }; #pragma region Additional test attributes // //You can use the following additional attributes as you write your tests: // //Use ClassInitialize to run code before running the first test in the class //[ClassInitialize()] //static void MyClassInitialize(TestContext^ testContext) {}; // //Use ClassCleanup to run code after all tests in a class have run //[ClassCleanup()] //static void MyClassCleanup() {}; // //Use TestInitialize to run code before running each test //[TestInitialize()] //void MyTestInitialize() {}; // //Use TestCleanup to run code after each test has run //[TestCleanup()] //void MyTestCleanup() {}; // #pragma endregion [TestMethod, Timeout(1000)] void Problem1_Testcase1() { int array[3] = { 1, 1, 1 }; sortZerosnOnes(array, 3); Assert::AreEqual(1, array[0], L"Failed for value at index 0", 1, 2); Assert::AreEqual(1, array[1], L"Failed for value at index 1", 1, 2); Assert::AreEqual(1, array[2], L"Failed for value at index 2", 1, 2); }; [TestMethod, Timeout(1000)] void Problem1_Testcase2() { int array[3] = { 0, 0, 0 }; sortZerosnOnes(array, 3); Assert::AreEqual(0, array[0], L"Failed for value at index 0", 1, 2); Assert::AreEqual(0, array[1], L"Failed for value at index 1", 1, 2); Assert::AreEqual(0, array[2], L"Failed for value at index 2", 1, 2); }; [TestMethod, Timeout(1000)] void Problem1_Testcase3() { int array[7] = { 1, 1, 1, 1, 0, 0, 0 }; sortZerosnOnes(array, 7); Assert::AreEqual(0, array[0], L"Failed for value at index 0", 1, 2); Assert::AreEqual(0, array[1], L"Failed for value at index 1", 1, 2); Assert::AreEqual(0, array[2], L"Failed for value at index 2", 1, 2); Assert::AreEqual(1, array[3], L"Failed for value at index 2", 1, 2); Assert::AreEqual(1, array[4], L"Failed for value at index 2", 1, 2); Assert::AreEqual(1, array[5], L"Failed for value at index 2", 1, 2); Assert::AreEqual(1, array[6], L"Failed for value at index 2", 1, 2); }; [TestMethod, Timeout(1000)] void Problem1_Testcase4() { int array[2] = { 1, 0 }; sortZerosnOnes(array, 2); Assert::AreEqual(0, array[0], L"Failed for value at index 0", 1, 2); Assert::AreEqual(1, array[1], L"Failed for value at index 1", 1, 2); }; [TestMethod, Timeout(1000)] void Problem1_Testcase5() { int array[8] = { 1, 0, 1, 0, 1, 0, 1, 0 }; sortZerosnOnes(array, 8); Assert::AreEqual(0, array[0], L"Failed for value at index 0", 1, 2); Assert::AreEqual(0, array[1], L"Failed for value at index 1", 1, 2); Assert::AreEqual(0, array[2], L"Failed for value at index 1", 1, 2); Assert::AreEqual(0, array[3], L"Failed for value at index 1", 1, 2); Assert::AreEqual(1, array[4], L"Failed for value at index 1", 1, 2); Assert::AreEqual(1, array[5], L"Failed for value at index 1", 1, 2); Assert::AreEqual(1, array[6], L"Failed for value at index 1", 1, 2); Assert::AreEqual(1, array[7], L"Failed for value at index 1", 1, 2); }; }; }
true
469a7120ded443851103e2f09b5867601c18f1bf
C++
ghostec/WhiteOld
/Physics/src/Helpers/XMLPhysics.cpp
UTF-8
1,095
2.5625
3
[]
no_license
#include "Physics/Helpers/XMLPhysics.h" namespace XMLHelper { void createBody( tinyxml2::XMLElement* el, std::shared_ptr<SceneGraph> scene_graph, std::shared_ptr<PhysicsManager> physics_manager ) { const char* sg_node_name = el->FirstChildElement( "sg_node" )->GetText(); std::shared_ptr<SGNode> sg_node = scene_graph->findSGNode( sg_node_name ); std::shared_ptr<Body> body; if( strcmp( sg_node_name, "plane" ) != 0 ) body.reset( new Body( sg_node ) ); else { body.reset( new Body( sg_node, true ) ); } physics_manager->addBody( body ); } void importPhysics( std::string file_name, std::shared_ptr<SceneGraph> scene_graph, std::shared_ptr<PhysicsManager> physics_manager ) { tinyxml2::XMLDocument doc; file_name = "../assets/xml/" + file_name + ".xml"; doc.LoadFile( file_name.c_str( ) ); tinyxml2::XMLElement* el = doc.RootElement(); while( el ) { if( strcmp( el->Name(), "body" ) == 0 ) createBody( el, scene_graph, physics_manager ); el = el->NextSiblingElement( ); } } }
true
ebf3c9fcec625b21a46d91cbc3060b8816e21e57
C++
Error323/wordclock
/LightSensor.cpp
UTF-8
384
2.671875
3
[]
no_license
#include "LightSensor.h" #include <Arduino.h> LightSensor::LightSensor(const uint8_t pin): mPin(pin) { for (uint8_t i = 0; i < BUFFER_SIZE; i++) Update(); } void LightSensor::Update() { mRingBuffer.Add(analogRead(mPin)); } uint8_t LightSensor::Brightness() { uint8_t brightness = map(mRingBuffer.Mean(), 0, 1023, MIN, MAX); return constrain(brightness, MIN, MAX); }
true
15c008eae90ddf30d461899222c01624ee8b65ab
C++
totorodev0032/Data-Structure-and-algorithms-For-Interview-Preparation
/Arrays/kth_distinct_largest_element.cpp
UTF-8
604
3.40625
3
[]
no_license
// kth largest distinct element. #include <bits/stdc++.h> using namespace std; int main() { int arr[] = {3,2,3,1,2,4,5,5,6}; int size = sizeof(arr)/sizeof(int); sort(arr, arr + size, greater<int>()); for(int i = 0; i<size; i++) { cout<< arr[i] << endl; } // kth largest element int k = 4; int count = 0; int pos = 0; if(k >= size) { return 1; } for(int i = 0; i < size; i++){ pos = i; if(arr[i]!=arr[i+1] ) { count ++; } if(count == k) break; } cout << "kth largest number is" << " " << arr[pos] ; return 0; }
true
97eba756f5abf042856a24e741344919b51766c7
C++
MrClam1/My-works
/Lab 5.cpp
UTF-8
4,005
3.109375
3
[]
no_license
#include <stdio.h> #include <Windows.h> #include <iostream> #include <string.h> #include <fstream> #include <locale.h> using namespace std; struct Country { char name[20]; char capital[20]; char language[50]; int people; int square; char money[10]; char government[100]; }; struct Countries { Country countries[5]; }; void File() { int size; char text[1000]; FILE* file; errno_t Error; Error = fopen_s(&file, "file.txt", "a"); if (Error == 0) { while (strcmp(text, "Stop\n") != 0) { cout << "Enter information about countries: \n"; cin.ignore(); cin.get(text, 1000); size = strlen(text); text[size] = '\n'; text[size + 1] = '\0'; if (strcmp(text, "Stop\n") != 0) { fputs(text, file); } } fclose(file); } else { printf("File not opened! \n"); } } int main() { string enter1; cout << "Do you want to add information about countries: Yes or No?" << endl; cin >> enter1; if (enter1 == "Yes") { File(); } else { cout << "Okey" << endl; } Countries Group = {}; char name[20], capital[20], language[50], money[10], government[100]; int people, square; FILE* file; int count = 0; errno_t Error; Error = fopen_s(&file, "file.txt", "r"); if (Error == 0) { while (!feof(file)) { if (fgetc(file) == '\n') { count++; } } fseek(file, 0L, SEEK_SET); if (file != NULL) { for (int i = 0; i <= count; i++) { fscanf_s(file, "%s %s %s %i, %i, %s %100[^\n]", name, 20, capital, 20, language, 50, &people, &square, money, 10, government, 100); Country country = {}; for (int i = 0; i < 20; i++) { if (name[i] == ',') { name[i] = '\0'; } } strcpy_s(country.name, name); strcpy_s(country.capital, capital); strcpy_s(country.language, language); country.people = people; country.square = square; strcpy_s(country.money, money); strcpy_s(country.government, government); Group.countries[i] = country; } } fclose(file); } else { printf("File not opened! \n"); } int enter2, a; cout << "What would you like to find? Choose a number: " << endl; cout << "1. Capital of country" << endl; cout << "2. Language of country" << endl; cout << "3. Population of country" << endl; cout << "4. Square of country" << endl; cout << "5. Currency of country" << endl; cout << "6. Political system of country" << endl; cin >> enter2; cout << "What country would you like to find about information? Choose a number : " << endl; cout << "1. France" << endl; cout << "2. USA" << endl; cout << "3. Russia" << endl; cout << "4. UK" << endl; cout << "5. Japan" << endl; cin >> a; switch (enter2) { case 1: cout << "The capital of " << Group.countries[a - 1].name << " is" << Group.countries[a - 1].capital << endl; break; case 2: cout << "The official language of " << Group.countries[a - 1].name << " is" << Group.countries[a - 1].language << " language" << endl; break; case 3: cout << "The population of " << Group.countries[a - 1].name << " is " << Group.countries[a - 1].people << endl; break; case 4: cout << "The square of " << Group.countries[a - 1].name << " is " << Group.countries[a - 1].square << endl; break; case 5: cout << "The currence of " << Group.countries[a - 1].name << " is " << Group.countries[a - 1].money << endl; break; case 6: cout << "The political system of " << Group.countries[a - 1].name << " is " << Group.countries[a - 1].government << endl; break; default: cout << "Wrong number!" << endl; break; } cout << "=== [. . .] ===" << endl; Country Massive{ }; for (int i = count - 1; i >= 0; i--) { for (int j = 0; j < i; j++) { if (Group.countries[j].people > Group.countries[j + 1].people) { Massive = Group.countries[j]; Group.countries[j] = Group.countries[j + 1]; Group.countries[j + 1] = Massive; } } } for (int i = 0; i < count; i++) { cout << Group.countries[i].name << ". Population of this country is: " << Group.countries[i].people << endl; } return 0; }
true
23159f5980f70b47b8a42b7e5cbd26b415092155
C++
saphere9/InterviewPrep
/Topic/Solution/Graph2.cpp
UTF-8
1,548
2.8125
3
[]
no_license
class Solution { public: vector<int> eventualSafeNodes(vector<vector<int>>& graph) { queue<int> q; int n = graph.size(); int in[10001]; fill( in , in + n+1,0); vector< vector<int> > edges(n); for ( int i = 0 ; i < n ; i++){ for ( int x : graph[i]) { edges[x].push_back(i); in[i]++; } } for ( int i = 0 ; i < n; i++){ if (in[i] == 0) { // cout << i << "\n"; q.push(i); } } vector<int> ans; while(!q.empty()){ int top = q.front();q.pop(); ans.push_back(top); for ( int ne : edges[top]){ in[ne]--; if ( in[ne] == 0 )q.push(ne); } } sort( ans.begin(), ans.end()); return ans; } }; /* Alternate solution : Graph colouring */ class Solution(object): def eventualSafeNodes(self, graph): WHITE, GRAY, BLACK = 0, 1, 2 color = collections.defaultdict(int) def dfs(node): if color[node] != white: return color[node] == BLACK color[node] = GRAY for nei in graph[node]: if color[nei] == BLACK: continue if color[nei] == GRAY or not dfs(nei): return False color[node] = BLACK return True return filter(dfs, range(len(graph)))
true
5a99d83556bb4563e46ee18df95e806883bc634f
C++
zzhuazi/c-primer-plus
/第五章/T5-2/T5-2/T5-2.cpp
GB18030
302
3.203125
3
[]
no_license
/* ʹarray󣬺long double±д嵥5.4100ֵ */ #include <iostream> #include <array> using namespace std; int main() { array<long double, 100> a; a[1] = a[0] = 1; for (int i = 2; i < 100; i++) { a[i] = i* a[i - 1]; } cout << a[98] << endl << a[99]; }
true
76c8e04e96aa60a96801d738998f2d2171eccc31
C++
IvanaGyro/ZeroJudge-Answers
/a065/a095.cpp
UTF-8
164
2.53125
3
[]
no_license
#include <iostream> using namespace std; int main(){ int m, n; while (cin >> n){ cin >> m; if (m == n) cout << m << endl; else cout << m + 1 << endl; } }
true
a368f85fd702a5e81f7d2cba470a2c528f4cbe82
C++
taihangy/hackerrank
/binarytree.cpp
UTF-8
1,500
3.515625
4
[]
no_license
#include <stdio.h> #include <stdlib.h> #define LEFT 0 #define RIGHT 1 struct BTNode { int key; struct BTNode* nodes[2]; }; struct BTNode* newNode(int key) { struct BTNode* node = (struct BTNode*) malloc(sizeof(*node)); node->key = key; node->nodes[LEFT] = NULL; node->nodes[RIGHT] = NULL; return node; } int maxInBTree(struct BTNode *node) { int maxLT, maxRT; if (node == NULL) { return 0; } maxLT = maxInBTree(node->nodes[LEFT]); maxRT = maxInBTree(node->nodes[RIGHT]); return maxLT > node->key ? (maxLT > maxRT ? maxLT : maxRT) : (node->key > maxRT ? node->key : maxRT); } struct BTNode* insert(struct BTNode* node, int key) { if (node == NULL) { return newNode(key); } else { struct BTNode *temp; int f = rand() % 2 != 0; if (f) { temp = insert(node->nodes[LEFT], key); node->nodes[LEFT] = temp; } else { temp = insert(node->nodes[RIGHT], key); node->nodes[RIGHT] = temp; } return node; } } void inordertrav(struct BTNode *node) { if (node == NULL) { return; } inordertrav(node->nodes[LEFT]); printf("%d\n", node->key); inordertrav(node->nodes[RIGHT]); } int main(void) { struct BTNode* root = NULL; int arr[] = {20, 8, 22, 4, 12, 10, 14, 45}; for (unsigned int i = 0; i < sizeof(arr)/sizeof(arr[0]); i++) { root = insert(root, arr[i]); } inordertrav(root); printf("Max is %d\n", maxInBTree(root)); return 0; }
true
75fec3c18b6db21b07e6bb0c37a6f312e5719b81
C++
ivan-uskov/computer-graphics-labs
/tiny_renderer/renderer/frametile.cpp
UTF-8
1,097
2.953125
3
[ "MIT" ]
permissive
#include "frametile.h" #include "tgaimage.h" #include <string.h> FrameTile::FrameTile(Vec2i origin, Vec2i size) : m_origin(origin) , m_size(size) { } void FrameTile::init(TGAImage & image, float * zbuffer) { m_imageSize = image.get_size(); m_data = image.buffer(); m_bytespp = image.get_bytespp(); m_zbuffer = zbuffer; } TGAColor FrameTile::get(int x, int y) const { return TGAColor(m_data + m_bytespp * index(x, y), m_bytespp); } void FrameTile::set(int x, int y, TGAColor const& c) { memcpy(m_data + m_bytespp * index(x, y), c.bgra, m_bytespp); } int FrameTile::get_top() const { return m_origin.y; } int FrameTile::get_left() const { return m_origin.x; } int FrameTile::get_right() const { return m_origin.x + m_size.x; } int FrameTile::get_bottom() const { return m_origin.y + m_size.y; } float FrameTile::get_z(int x, int y) const { return m_zbuffer[index(x, y)]; } void FrameTile::set_z(int x, int y, float z) { m_zbuffer[index(x, y)] = z; } size_t FrameTile::index(int x, int y) const { return x + y * m_imageSize.x; }
true
2667fd54aa35c11e763b1465f670ccb1bbfbd0c4
C++
haiki/OJcode
/18SpecialMultiplication1083.cpp
UTF-8
858
3.140625
3
[]
no_license
#include<iostream> using namespace std; /*int main() { int a,b; int buff1[11]={0},buff2[11]={0}; while(cin>>a>>b) { int si1=0,si2=0; int result=0; while(a!=0) { buff1[si1++]=a%10; a=a/10; } while(b!=0) { buff2[si2++]=b%10; b=b/10; } for(int i=0;i<si1;i++) { for(int j=0;j<si2;j++) { result+=buff1[i]*buff2[j]; } } cout<<result<<endl; } return 0; } */ int main() { char buff1[11],buff2[11]; int result=0; while(cin>>buff1>>buff2) { for(int i=0;buff1[i]!='\0';i++) for(int j=0;buff2[j]!='\0';j++) result+=(buff1[i]-'0')*(buff2[j]-'0'); cout<<result<<endl; } return 0; }
true
a1071be496ecc9f8f428b4a5d7ab30b056aa317d
C++
Vory7/sibsutis
/3 семестр/СиАОД/Лабораторные работы/lab_3 (Удаление из СДП)/treecreate.cpp
UTF-8
2,604
3.46875
3
[]
no_license
#include "treecreate.hpp" #include <iostream> #include <ctime> #include <conio.h> /* Рандомайзер без повторов */ void FillRand(int *A, int n) { bool table[MAX_RAND] = {false}; int x; for (int i = 0; i < n; i++) { while (table[x = rand() % MAX_RAND]) ; table[x] = true; A[i] = x; } } void InsertSort(int *A, int n) { int temp, i, j; for (i = 1; i < n; i++) { temp = A[i]; j = i - 1; while (j >= 0 && temp < A[j]) { A[j + 1] = A[j]; j = j - 1; } A[j + 1] = temp; } } /* Perfectly balanced search tree */ /* Идеально сбалансированное дерево поиска */ tree *PBST(int left, int right, int *A) { if (left > right) return NULL; else { int m = ((left + right) / 2); tree *p = new tree; p->data = A[m]; p->L = PBST(left, m - 1, A); p->R = PBST(m + 1, right, A); return p; } } tree *createPBST(int n) { int *Arr = new int[n]; FillRand(Arr, n); InsertSort(Arr, n); return PBST(0, n - 1, Arr); } /* Добавление элемента в случайное дерево поиска (двойная косвенность (double * indirection)) */ bool addRST_DI(tree *&p, int data) { tree **q = &p; while (*q != NULL) { if (data < (*q)->data) q = &((*q)->L); else if (data > (*q)->data) q = &((*q)->R); else { return false; } } if (*q == NULL) { *q = new tree; (*q)->data = data; } return true; } tree *createRST_DI(int n, bool log) { tree *root = NULL; int i = 0; while (i < n) { int data = rand() % MAX_RAND; if (addRST_DI(root, data)) i++; else if (log) std::cout << "\t\t /* Данные с ключом \"" << data << "\" уже есть в дереве */" << std::endl; } return root; } /* Добавление элемента в случайное дерево поиска (рекурсия (recursive)) */ bool addRST_R(tree *&p, int data) { bool lol = true; if (p == NULL) { p = new tree; p->data = data; } else if (data < p->data) lol = addRST_R(p->L, data); else if (data > p->data) lol = addRST_R(p->R, data); else lol = false; return lol; } tree *createRST_R(int n, bool log) { tree *root = NULL; int i = 0; while (i < n) { int data = rand() % MAX_RAND; if (addRST_R(root, data)) i++; else if (log) std::cout << "\t\t /* Данные с ключом \"" << data << "\" уже есть в дереве */" << std::endl; } return root; }
true
fa882e559e225942a1f192eb4d940e336772dd54
C++
igorracca/UVa-solutions
/fb.cpp
UTF-8
3,191
3.90625
4
[]
no_license
/* ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ author: Igor Racca ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ Problem: Given a sequence of positive integers A and an integer T, return whether there is a *continuous sequence* of A that sums up to exactly T Example [23, 5, 4, 7, 2, 11], 20. Return True because 7 + 2 + 11 = 20 [1, 3, 5, 23, 2], 8. Return True because 3 + 5 = 8 [1, 3, 5, 23, 2], 7 Return False because no sequence in this array adds up to 7 Note: We are looking for an O(N) solution. There is an obvious O(N^2) solution which is a good starting point but is not the final solution we are looking for. The solution is actually quite simple and straightforward. It does not require using any fancy recursion, algorithms or data structures. Just think how you'd solve it in O(N) on paper then write that code. ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ Input: A (number of positive integers) x1 x2 ... xA (positive integers) T (target) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ Output: True because xk + xk+1 + ... + xk+n = T (if the continuous sequence exists) or False because no sequence in this array adds up to T (if the continuous sequence does not exist) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ */ #include <iostream> using namespace std; void printSol(bool sol, int v[], int t, int b, int e) { if(sol == false) { cout << "False because no sequence in this array adds up to " << t << endl; return; } cout << "True because"; for(int i=b; i<=e; i++) { cout << " " << v[i]; if(i!=e) { cout << " +"; } } cout << " = " << t; } int main() { int *A; int a, target; cout << "How many numbers in the sequence?" << endl; cin >> a; A = new int[a]; cout << "Inform the " << a << " numbers separeted by spaces: " << endl; for(int i=0; i<a; i++) { cin >> A[i]; } cout << "Inform the target: "; cin >> target; int begin=0, end=1, sol=false; if(a == 1) { if(A[0] == target) { begin = end = 0; sol=true; } } else { int sum = A[begin]; while(end < a) { if(begin == end) { sum = A[begin]; end++; } if((sum + A[end]) == target) { sol=true; break; } else if((sum + A[end]) < target) { sum += A[end]; end++; } else { sum -= A[begin]; begin++; } } } printSol(sol, A, target, begin, end); return 0; }
true
063f86bf8b21b08a627bd7120d106bd095b90aca
C++
kalyanghosh/A-Tour-of-Cpp
/Pointers_Structures/memory_allocation_in_heap.cpp
UTF-8
232
2.796875
3
[]
no_license
#include<iostream> using namespace std; int main() { int * A; cout<<"Enter the number of students:\n"; int numStudents; cin>>numStudents; A=new int[numStudents]; if(A!=NULL) { A[0]=10; A[1]=15; } return 0; }
true
9e08fd5ab7d3250a2d0d5e937a077ceed277e2e6
C++
davidmueller13/vexx
/experimental/database/src/fieldManager.cpp
UTF-8
1,704
2.671875
3
[]
no_license
#include "fieldManager.h" #include "iostream" namespace db { void fieldManager::ensureRegisteredType( field *in, std::string nN ) { if( typeid( *in ) != typeid( field ) ) { if( !isRegistered( in ) ) { fieldRecord temp; temp.type = in->copy( 0 ); temp.niceName = nN; types.push_back( temp ); } } } bool fieldManager::isRegistered( field *in ) { for( unsigned int x=0; x<types.size(); x++ ) { if( typeid( *types[x].type ) == typeid( *in ) ) { return true; } } return false; } field *fieldManager::getField( std::string name ) { field *orig = getOriginal( name ); if( orig ) { return reinterpret_cast<field *>(orig->copy( 0 )); } return 0; } std::string fieldManager::getName( field *in ) { for( unsigned int x=0; x<types.size(); x++ ) { if( typeid( *(types[x].type) ) == typeid( *in ) && types[x].niceName != "" ) { return types[x].niceName; } } return typeid( *in ).name(); } field *fieldManager::getOriginal( std::string in ) { for( unsigned int x=0; x<types.size(); x++ ) { if( typeid( *(types[x].type) ).name() == in || types[x].niceName == in ) { return types[x].type; } } return 0; } fieldManager *fieldManager::instance( bool force ) { static bool beenCalled = false; static fieldManager *me; if( !beenCalled || force ) { beenCalled = true; me = new fieldManager(); } return me; } void fieldManager::empty() { delete instance(); } fieldManager::fieldManager() { } fieldManager::fieldManager( const fieldManager & ) { } fieldManager::~fieldManager() { for( unsigned int x=0; x<types.size(); x++ ) { delete types[x].type; } } }
true
da30faa8c66baa4b867d2c133be20fc40fdd44c0
C++
ash/cpp-tut
/012.cpp
UTF-8
171
2.65625
3
[]
no_license
#include <iostream> using namespace std; int f() { static int c = 0; return c++; } int main() { for (int i = 0; i < 10; i++) cout << f() << "\n"; }
true
bc4598ce909940f3ba4a78e5356138966c5dc21f
C++
aiiselo/HSE-software-engineering
/2nd course/Algorithms and Data Structures/Disjoint Sets/header.cpp
UTF-8
7,011
2.984375
3
[]
no_license
#include "header.hpp" #include <iostream> #include <stdio.h> #include <vector> using namespace std; void DSArray::Create (int x){ index++; array[x] = index; } void DSArray::Union (int x, int y){ for (int i=0; i<array.size(); i++){ if (array[i] == array[x]){ array[x] = array[y]; } } } int DSArray::Find (int x){ return array[x]; } void DSTree::Create (int x){ tree[x]=x; } int DSTree::Find (int x){ while (tree[x]!=x){ x = tree[x]; } return tree[x]; } void DSTree::Union (int x, int y){ x = Find(x); y = Find(y); if (x==y) return; tree[x]=y; } void DSTreeRanked::Create(int x){ treeRElements[x]=x; treeHeight[x]=0; } void DSTreeRanked::Union(int x, int y){ x = Find(x); y = Find(y); if (x == y) return; if (treeHeight[x]<treeHeight[y]) treeRElements[x]=y; else { if (treeHeight[x]>treeHeight[y]) treeRElements[y]=x; else { treeRElements[x] = y; treeHeight[y]++; } } } int DSTreeRanked::Find(int x){ while (treeRElements[x]!=x){ x = treeRElements[x]; } return treeRElements[x]; } void DSTreeRCompr::Create(int x){ treeRCElements[x] = x; treeRank[x] = 0; } void DSTreeRCompr::Union(int x, int y){ x = Find(x); y = Find(y); if (x == y) return; if (treeRank[x]<treeRank[y]) treeRCElements[x]=y; else { if (treeRank[x]>treeRank[y]) treeRCElements[y]=x; else { treeRCElements[x] = y; treeRank[y]++; } } } int DSTreeRCompr::Find(int x){ int z = x; while (treeRCElements[x]!=x){ x = treeRCElements[x]; } int y = x; while (treeRCElements[z]!=z){ int key = z; z = treeRCElements[z]; treeRCElements[key] = y; } return x; } void fullQueue(std::vector<int> &procedure, int size) { procedure.clear(); int F = size - 1; // 0 int U = size - 1; // 1 while ((F>0) || (U>0)){ if ((rand() % 2 == 0) && (F>0)){ procedure.push_back(0); F--; } else if (U>0) { procedure.push_back(1); U--; } } } void arrayTime(int size){ double totalTime = 0; for (int k = 0; k<50; k++){ srand((int)time(0)); double startTime = 0; DSArray *array = new DSArray(size); startTime = clock(); for (int i=0; i<size; i++){ array->Create(i); } std::vector<int> procedure; fullQueue(procedure, size); for (int i = 0; i < 2*size - 2; i++){ if (procedure[i]==0) array->Find(rand()%size); if (procedure[i]==1) array->Union(rand()%size, rand()%size); } delete array; double endTime = clock() - startTime; totalTime +=endTime; //cout<<"Time of iteration №"<<k+1<<" is "<<endTime/CLOCKS_PER_SEC<<endl; //cout<<endTime/CLOCKS_PER_SEC<<endl; //раскомментируйте, чтобы увидеть время каждой итерации } cout<<"\n"<<endl; cout<<"Total time for array of "<<size<<" elements is "<<totalTime/CLOCKS_PER_SEC<<endl; cout<<"Average time for array of "<<size<<" elements is "<<totalTime/(CLOCKS_PER_SEC*50)<<endl; cout<<"\n"<<endl; } void treeTime(int size){ double totalTime = 0; for (int k = 0; k<50; k++){ srand((int)time(0)); double startTime = 0; DSTree *tree = new DSTree(size); startTime = clock(); for (int i=0; i<size; i++){ tree->Create(i); } std::vector<int> procedure; fullQueue(procedure, size); for (int i = 0; i < 2*size - 2; i++){ if (procedure[i]==0) tree->Find(rand()%size); if (procedure[i]==1) tree->Union(rand()%size, rand()%size); } delete tree; double endTime = clock() - startTime; totalTime +=endTime; //cout<<"Time of iteration №"<<k+1<<" is "<<endTime/CLOCKS_PER_SEC<<endl; //cout<<endTime/CLOCKS_PER_SEC<<endl; //раскомментируйте, чтобы увидеть время каждой итерации } cout<<"\n"<<endl; cout<<"Total time for usual tree of "<<size<<" elements is "<<totalTime/CLOCKS_PER_SEC<<endl; cout<<"Average time for usual tree of "<<size<<" elements is "<<totalTime/(CLOCKS_PER_SEC*50)<<endl; cout<<"\n"<<endl; } void treeRTime(int size){ double totalTime = 0; for (int k = 0; k<50; k++){ srand((int)time(0)); double startTime = 0; DSTreeRanked *rankedTree = new DSTreeRanked(size); startTime = clock(); for (int i=0; i<size; i++){ rankedTree->Create(i); } std::vector<int> procedure; fullQueue(procedure, size); for (int i = 0; i < 2*size - 2; i++){ if (procedure[i]==0) rankedTree->Find(rand()%size); if (procedure[i]==1) rankedTree->Union(rand()%size, rand()%size); } delete rankedTree; double endTime = clock() - startTime; totalTime +=endTime; //cout<<"Time of iteration №"<<k+1<<" is "<<endTime/CLOCKS_PER_SEC<<endl; //cout<<endTime/CLOCKS_PER_SEC<<endl; //раскомментируйте, чтобы увидеть время каждой итерации } cout<<"\n"<<endl; cout<<"Total time for ranked tree of "<<size<<" elements is "<<totalTime/CLOCKS_PER_SEC<<endl; cout<<"Average time for ranked tree of "<<size<<" elements is "<<totalTime/(CLOCKS_PER_SEC*50)<<endl; cout<<"\n"<<endl; } void treeRCTime(int size){ double totalTime = 0; for (int k = 0; k<50; k++){ srand((int)time(0)); double startTime = 0; DSTreeRCompr *rcTree = new DSTreeRCompr(size); startTime = clock(); for (int i=0; i<size; i++){ rcTree->Create(i); } std::vector<int> procedure; fullQueue(procedure, size); for (int i = 0; i < 2*size - 2; i++){ if (procedure[i]==0) rcTree->Find(rand()%size); if (procedure[i]==1) rcTree->Union(rand()%size, rand()%size); } delete rcTree; double endTime = clock() - startTime; totalTime +=endTime; //cout<<"Time of iteration №"<<k+1<<" is "<<endTime/CLOCKS_PER_SEC<<endl; //cout<<endTime/CLOCKS_PER_SEC<<endl;//раскомментируйте, чтобы увидеть время каждой итерации } cout<<"\n"<<endl; cout<<"Total time for ranked tree of "<<size<<" elements is "<<totalTime/CLOCKS_PER_SEC<<endl; cout<<"Average time for ranked tree of "<<size<<" elements is "<<totalTime/(CLOCKS_PER_SEC*50)<<endl; cout<<"\n"<<endl; }
true
aa61f81486f21cca7e7457ee7e5df49cf391877a
C++
JaimeRamosMiranda/C-plus-plus-1st-repository-2018
/practica2/tabla.cpp
UTF-8
460
2.671875
3
[]
no_license
/* Tabla de multiplicar */ #include<iostream> #include<conio.h> using namespace std; int main() {int n,f,c; int op; for(;;) { do {cout<<"Ingrese >0 y <= 10 :"; cin>>n; }while(n<0||n>10); for(f=1;f<=n;f++) { for(c=1;c<=n;c++) cout<<f*c<<"\t"; cout<<endl; } getche(); cout<<"Desea continuar Si 1 No 0"<<endl; cin>>op; if(op==0)break; } system("cls"); cout<<"fin proceso"<<endl; getche(); return 0; }
true
89e4d01e2a89248110fdd693533bd8f510c537c3
C++
finegs/Test01
/pjt02/rpi01.cpp
UTF-8
3,035
2.796875
3
[]
no_license
/* * https://fishpoint.tistory.com/2235?utm_source=dable * dht22.c: * Simple test program to test the wiringPi functions * Based on the existing dht11.c * Amended by technion@lolware.net */ #include <wiringPi.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <sys/types.h> #include <unistd.h> #define MAXTIMINGS 85 static int DHTPIN = 11; static int dht22_dat[5] = {0,0,0,0,0}; static uint8_t sizecvt(const int read) { /* digitalRead() and friends from wiringpi are defined as returning a value < 256. However, they are returned as int() types. This is a safety function */ if (read > 255 || read < 0) { printf("Invalid data from wiringPi library\n"); exit(EXIT_FAILURE); } return (uint8_t)read; } static int read_dht22_dat() { uint8_t laststate = HIGH; uint8_t counter = 0; uint8_t j = 0, i; dht22_dat[0] = dht22_dat[1] = dht22_dat[2] = dht22_dat[3] = dht22_dat[4] = 0; // pull pin down for 18 milliseconds pinMode(DHTPIN, OUTPUT); digitalWrite(DHTPIN, HIGH); delay(10); digitalWrite(DHTPIN, LOW); delay(18); // then pull it up for 40 microseconds digitalWrite(DHTPIN, HIGH); delayMicroseconds(40); // prepare to read the pin pinMode(DHTPIN, INPUT); // detect change and read data for ( i=0; i< MAXTIMINGS; i++) { counter = 0; while (sizecvt(digitalRead(DHTPIN)) == laststate) { counter++; delayMicroseconds(1); if (counter == 255) { break; } }//end wile laststate = sizecvt(digitalRead(DHTPIN)); if (counter == 255) break; // ignore first 3 transitions if ((i >= 4) && (i%2 == 0)) { // shove each bit into the storage bytes dht22_dat[j/8] <<= 1; if (counter > 16) dht22_dat[j/8] |= 1; j++; } }//end for // check we read 40 bits (8bit x 5 ) + verify checksum in the last byte // print it out if data is good if ((j >= 40) && (dht22_dat[4] == ((dht22_dat[0] + dht22_dat[1] + dht22_dat[2] + dht22_dat[3]) & 0xFF)) ) { float t, h; h = (float)dht22_dat[0] * 256 + (float)dht22_dat[1]; h /= 10; t = (float)(dht22_dat[2] & 0x7F)* 256 + (float)dht22_dat[3]; t /= 10.0; if ((dht22_dat[2] & 0x80) != 0) t *= -1; printf("Humidity = %.2f %% Temperature = %.2f *C \n", h, t ); return 1; } else { printf("Data not good, skip\n"); return 0; } } //int main (int argc, char *argv[]) int main (void) { //여기에서 온도와 습도를 읽어옵니다. if (wiringPiSetup() == -1) exit(EXIT_FAILURE) ; if (setuid(getuid()) < 0) { perror("Dropping privileges failed\n"); exit(EXIT_FAILURE); } while(1){ while (read_dht22_dat() == 0) { delay(1000); // wait 1sec to refresh 1초간 기다립니다. } } return 0 ; }
true
da9359758969f1d9c360daf279c144c0c4130905
C++
heyang5188/LeetCode
/tree/144.二叉树的前序遍历.cc
UTF-8
879
3.0625
3
[]
no_license
// Author Herb // Time : 2019-01-30 21:01:33 #include <iostream> #include <string> #include <map> #include <unordered_map> #include <vector> #include <queue> #include <stack> using namespace std; struct ListNode { int val; ListNode* next; ListNode(int x): val(x),next(NULL){}}; struct TreeNode {int val;TreeNode* left;TreeNode* right;TreeNode(int x): val(x), left(nullptr), right(nullptr){}}; class Solution { public: vector<int> preorderTraversal(TreeNode* root) { stack<TreeNode*> stk; vector<int> ans; while(root||!stk.empty()) { if(root) { ans.push_back(root->val); stk.push(root); root = root->left; } else { root = stk.top()->right; stk.pop(); } } return ans; } };
true
fff6b56214a2a55e69943c00a9f13429106d215e
C++
ingyeoking13/algorithm
/cf/problemsetOldVersion/1138B.cc
UTF-8
1,079
2.5625
3
[]
no_license
#include <stdio.h> #include <vector> using namespace std; vector<int> ans; vector<int> zero; vector<int> rep; char a[(int)5e3+1]; char b[(int)5e3+1]; int main() { int n; scanf("%d", &n); scanf("%s", a); scanf("%s", b); int acnt = 0, bcnt=0; int zerocnt = 0; int stat = 1; for (int i=0; i<n; i++) { if ( a[i] == '0' && b[i] == '0') { if ( stat == 1 ) zero.push_back(i+1); stat = 3-stat; zerocnt ++; continue; } if ( a[i] == '1' && b[i] == '1' ) rep.push_back(i+1); else if ( a[i] == '1' ) ans.push_back(i+1); else bcnt++; } if ( zero.size()*2 != zerocnt ) return !printf("-1\n"); while ( ans.size() < bcnt ) { ans.push_back( rep.back() ); rep.pop_back(); } while ( bcnt < ans.size() ) { rep.pop_back(); bcnt++; } if ( rep.size() % 2 == 1 ) return !printf("-1\n"); for (int i=0; i<zero.size(); i++ ) printf("%d ", zero[i]); for ( int i=0; i<ans.size(); i++) printf("%d ", ans[i]); for ( int i=0; i<rep.size()/2; i++) printf("%d ", rep[i]); printf("\n"); }
true
c1e2054fded7a969abc4522c7ca0912e6905c5a2
C++
vimday/PlayWithLeetCode
/每日一题 11 月/Day1105_word-ladder.cpp
UTF-8
2,935
2.84375
3
[]
no_license
/* * @Author :vimday * @Desc : * @Url : * @File Name :Day1105_word-ladder.cpp * @Created Time:2020-11-05 16:21:01 * @E-mail :lwftx@outlook.com * @GitHub :https://github.com/vimday */ #include <bits/stdc++.h> using namespace std; void debug() { #ifdef LOCAL freopen("E:\\Cpp\\in.txt", "r", stdin); freopen("E:\\Cpp\\out.txt", "w", stdout); #endif } class Solution { public: int ladderLength(string beginWord, string endWord, vector<string>& wordList) { unordered_set<string> wordDict(wordList.begin(), wordList.end()); if (wordDict.find(endWord) == wordDict.end()) { return 0; //Not FOUND 404 } unordered_set<string> beginSet{beginWord}; unordered_set<string> endSet{endWord}; int step = 1; for (; !beginSet.empty();) { unordered_set<string> tempSet; ++step; for (auto s : beginSet) { wordDict.erase(s); } for (auto s : beginSet) { for (int i = 0; i < s.size(); ++i) { string str = s; for (char c = 'a'; c <= 'z'; ++c) { str[i] = c; if (wordDict.find(str) == wordDict.end()) { continue; } if (endSet.find(str) != endSet.end()) { return step; } tempSet.insert(str); } } } if (tempSet.size() < endSet.size()) { beginSet = tempSet; } else { beginSet = endSet; endSet = tempSet; } } return 0; } }; class Solution { public: int ladderLength(string beginWord, string endWord, vector<string>& wordList) { unordered_set<string> wordSet(wordList.begin(), wordList.end()); if (wordSet.count(endWord) == 0) return 0; unordered_set<string> from({beginWord}); unordered_set<string> to({endWord}); int ans = 2; while (!from.empty()) { unordered_set<string> next; for (auto& word : from) { wordSet.erase(word); } for (auto& word : from) { for (int i = 0; i < word.size(); i++) { string s = word; for (char c = 'a'; c <= 'z'; c++) { s[i] = c; if (wordSet.count(s) == 0) continue; next.insert(s); if (to.count(s) == 0) continue; return ans; } } } from = next; if (from.size() > to.size()) { swap(from, to); } ans++; } return 0; } };
true
eb47ddff9603315189b6ccf68f49b217546c6441
C++
hshshv/Glove-for-blind-code
/glove.ino
UTF-8
680
2.53125
3
[]
no_license
#include "UltrasonicSensor.h" #define num_of_engines 3 #define Minimum_voltag_per_engine 70 UltrasonicSensor Dsensor(7,8);//trig, echo short engines[] = {5,10,11}; //must be PWM pin float Distance; short TurnedOnEngine; void setup() { TurnOff(); } void loop() { Distance = Dsensor.GetAvg(); if(!(TurnedOnEngine = map(Distance, 4, 150, 0, num_of_engines))) { TurnOff(); TurnedOnEngine = map(Distance, 4, 150, 0, num_of_engines); } analogWrite(TurnedOnEngine, map(Distance, 4, 150, 0, Minimum_voltag_per_engine)); } void TurnOff() { for(short i = 0; i < num_of_engines; ++i) { digitalWrite(engines[i], LOW); } }
true
5f40b74b2002963617b1bbe2c0dc332b92600a76
C++
rfccambridge/robocup-ee
/firmware/gen3/SPILib/SPISlave.h
UTF-8
1,101
2.9375
3
[]
no_license
/* * SPISlave.h * * Created: 3/24/2015 1:24:46 PM * Author: David */ #ifndef __SPISLAVE_H__ #define __SPISLAVE_H__ #include "Command.h" class SPISlave { private: // state: 0 waiting; 1-5 number of bytes received (start, command, arg1, arg2, checksum); 6 given data to GetCommand; 7 reply ready (sending start byte); 8-10 sending response bytes (checksumEcho, reply, checksum) char m_state; char m_command; char m_arg1; char m_arg2; char m_arg3; char m_arg4; char m_checksum; char m_reply; public: SPISlave(); // should be called every iteration of main loop to handle periodic tasks void ReceiveSPI(); // get a command if one was sent // does not wait for one // returns false if no command bool GetCommand(Command &command); // gets a simple byte for debugging char getChar(); // after getting a command, this function should be called so that a response is sent acknowledging the command // the reply argument can be used to send back info (could be errors, or could be used to make commands that ask for data) void SetReply(char reply); }; #endif //__SPISLAVE_H__
true
0cfff3f79ff12d2172ab0455a24a27b1a33ac7f7
C++
bugy15/ZPG
/ZPG/Object.h
UTF-8
747
2.703125
3
[]
no_license
#pragma once #include <map> #include<glm/gtc/matrix_transform.hpp> #include "Model.h" #include "Direction.h" class Object { private: Model * model; GLsizei vao; GLsizei count; GLuint ID; string nameOfShader; mat4 ModelMatrix; vec4 color; vec3 multipler; public: Object(GLuint ID, string nameOfShader, Model * model, vec4 color, vec3 position, vec3 scale, vec3 rotate, float angle); GLsizei getVao(); GLsizei getCount(); string getNameOfShader(); mat4 getModelMatrix(); vec4 getColor(); vec3 getPosition(); GLuint getId(); void setColor(vec4 color); void setNameOfShader(string nameOfShader); void setPosition(vec3 position); void move(direction dir, vec3 center, vec3 up); ~Object(); };
true
987cd6b84b4af984edb7b7e4f96184166e744c49
C++
shingie11/MobileRobotNavigation
/AMR-workshops/src/planner/include/planner/node_xy.h
UTF-8
1,195
2.640625
3
[]
no_license
// // node_xy.h // Heuristic Search // // Created by Shingie on 3/25/20. // Copyright © 2020 Shingie. All rights reserved. //prototype for a node/intersection in the path of the mobile robot #ifndef node_xy_h #define node_xy_h #include <stdio.h> #include <iostream> #include <string.h> #include <vector> class NodeXY { public: NodeXY(double x, double y, double goalx, double goaly, double prevx, double prevy, std::string previ, double prevCost); NodeXY(); ~NodeXY(); bool wasVisited(); void setVisited(bool status); double getLongi(); double getLati(); std::string getID(); std::string getPrev(); double gettotalCost(); double totalCost; double heuristic; double lati; double longi; bool visited; std::string ID; double cost; double getCost(); void setCost(double c); std::string prev; void setPrev(std::string p); std::string calcID(double x, double y); friend bool operator== ( const NodeXY &n1, const NodeXY &n2); }; #endif /* node_xy_h */
true
75b4e6047ced22f18dcf0875f6f48514d64b95ee
C++
cheerayhuang/Garner
/c++_primer_ex/ex13_27.cc
UTF-8
1,388
3.1875
3
[]
no_license
/************************************************************************** * * Copyright (c) 2015 Cheeray Huang. All Rights Reserved * * @file: ex13_27.cc * @author: Huang Qiyu * @email: cheeray.huang@gmail.com * @date: 07-04-2016 00:04:08 * @version $Revision$ * **************************************************************************/ #include <iostream> #include <string> using namespace std; class HasPtr { public: HasPtr(const string &s = string()): ps(new string(s)), i(0), use(new size_t(1)) {} HasPtr(const HasPtr& h); HasPtr & operator=(const HasPtr&); ~HasPtr(); //private: public: string *ps; int i; size_t *use; }; HasPtr::HasPtr(const HasPtr& h) { i = h.i; ps = h.ps; use = h.use; ++*use; cout << "copy construct" << endl; } HasPtr& HasPtr::operator=(const HasPtr& h) { ++*h.use; if (--*use == 0) { delete ps; delete use; } i = h.i; ps = h.ps; use = h.use; cout << "copy operator =" << endl; } HasPtr::~HasPtr() { if (--*use == 0) { delete ps; delete use; } } int main() { HasPtr h1("hello"); HasPtr h2 = h1; HasPtr h3(h1); cout << *(h2.ps) << endl; cout << *(h3.ps) << endl; HasPtr h4; h4 = h2; cout << *(h4.ps) << endl; cout << hex << h2.ps << endl; cout << hex << h4.ps << endl; return 0; }
true
883604f494ab969097e5f975ac038968cc60c83d
C++
sizilium/FlexChess
/EasyFramework3d/base/cont/StringList.hpp
UTF-8
36,765
3.125
3
[ "MIT" ]
permissive
/** * @file StringList.hpp * @author sizilium * @date 01.06.2007 * @brief This file is part of the Vision Synthesis Easy Framework.\n * This file has no copyright; you can change everything. * Visit www.vision-synthesis.de or www.easy-framework.de for further informations.\n * If there is a bug please send a mail to bug@vision-synthesis.de. No warranty is given! */ #ifndef STRING_LIST_H #define STRING_LIST_H // includes #include <vs/Build.hpp> #include <string> #include <iostream> #include <assert.h> #include <stdio.h> #include <iterator> #include <vs/base/cont/JavaStyleIterator.hpp> #include <vs/base/cont/JavaStyleContainer.hpp> #include <vs/base/cont/NullIterator.hpp> #include <vs/base/cont/SmartIterator.hpp> namespace vs { namespace base { namespace cont { // predeclarations //template <class T> class SmartIterator; template <class T> class StringListNode; template <class T> class StringList; using namespace std; /** * Global function wich swappes two StringList's. * @code // Example * StringList<MyClass *> list_1, list_2; * ... * swap(list_1, list_2); // swapping by global function * list_1.swap(list_2); // swapping by StringList method * * @endcode * @param list_1 Pass the first list (reference). * @param list_2 Pass the second list (reference). */ template<class T> VS_EXPORT void swap(StringList<T> &list_1, StringList<T> &list_2) { StringListNode<T> *tmp; tmp = list_1.head; list_1.head = list_2.head; list_2.head = tmp; tmp = list_1.tail; list_1.tail = list_2.tail; list_2.tail = tmp; } /** @class StringList * A vision-synthesis template container like the stl list pattern. But StringList can * contain pointers (it's safe) and the members can searched by a string name (optional). \n * StringList supports an iterator who can both: Java and STL styled access. \n * It is a double linked list. There are many assertions to catch some errors. If you want * to disable it (for more performance) write \#define NDEBUG in this header. \n * The container is tested regularly with several CppUnit "http://sourceforge.net/projects/cppunit" * test but notice that no warranty is given. */ template <class T> class VS_EXPORT StringList : public JavaStyleContainer<T> { public: /** * After initialization the container is empty. */ StringList() { head = new StringListNode<T>(); tail = new StringListNode<T>(); head->next = tail; head->previous = NULL; tail->next = NULL; tail->previous = head; } StringList(const StringList<T> &list) { this->addAll(&list); } /** * All entrys will be cleared. * @see clear */ virtual ~StringList() { clear(); delete head; head = NULL; delete tail; tail = NULL; } /** * Copies the list. */ StringList<T>& operator=(const StringList<T> &op2) { if (this != &op2) { this->addAll(&op2); } return *this; } /** * Checks if two list pointers are directed to the same list. Complexity is only O(1). * @return True if it != op2 */ bool operator== (const StringList<T> &op2) const { if (head == op2.head) return true; else return false; } /** * The opposite of '==' operator. Checks if two list pointers are directed to * different lists. * @return True if it != op2 */ bool operator!= (const StringList<T> &op2) const { return !(*this == op2); } /** * This is the iterator for StringList. It implements JavaStyleIterator, means that * the common methods hasNext, next and remove available. STL style operation are * possible too, like ++, --, = and * operations.\n * A special feature of the StringList::iterator is the name() method, who returns the * name of an entry.\n * If you try to use an uninitialized iterator an assert will occure.\n * Note: EasyFramework use strictly name conventions: Classes are all upper case * and also the Iterator class. * * @code // Usage-Exampe: * StringList<short> stringList; * stringList.push_front(15, "fifteen"); * stringList.push_front(10, "ten"); * stringList.push_front(5, "five"); * * //Java style: * StringList<short>::Iterator it(stringList); * while (it.hasNext()) * cout << it.next() << " "; // output is: 5 10 15 * // {cout << it.name() << " "; it.next();} // output: five ten fifteen * * // STL style: * StringList<short>::Iterator itc = stringList.begin(); * while (itc != stringList.end()) * { * cout << *itc << " "; // output is: 5 10 15 * itc++; * } * @endcode */ class VS_EXPORT Iterator : public JavaStyleIterator<T>, public std::iterator<std::bidirectional_iterator_tag, T> { public: // typedefs typedef T value_type; typedef T& reference; typedef T* pointer; typedef int difference_type; typedef std::bidirectional_iterator_tag iterator_category; friend class StringList<T>; /** * You need no parameters for an iterator, but before the first use the iterator * must be initialized (with '=' operator for example). * @param node Optional parameter to direct the iterator to an ListNode. * Only for internal use. */ Iterator(StringListNode<T> *node = NULL) :currentNode(node) {} /** * A useful iterator initialization. Pass a list to the constructor parameter to * direct the iterator to the first entry of the list. * @param list The target list for the iterator */ Iterator(StringList<T> &list) { *this = list.begin(); } /** * Copyconstructor. * @param it Iterator to copy. */ Iterator(const Iterator &it) :currentNode(it.currentNode) {} /** * Java style method. Checks if the list has a next entry, dependent of the * iterator position. * @return True if the list still has a next entry from the iterator position. */ bool hasNext() const { assert("first you must inizialize the iterator!" && currentNode != NULL); if (currentNode->next != NULL) return true; return false; } /** * Returns the current entry without iterater shifting (additional vs method, no java * style but useful). * @return The current entry. */ T current() const { assert ("first you must inizialize the iterator!" && currentNode != NULL); return currentNode->value; } /** * Java style method. Returns the current entry and set the iterator to the next.\n * First check if the list has a next entry with hasNext()! Otherwise an assert * will occure. * @return The current entry. */ T next() { assert ("first you must inizialize the iterator!" && currentNode != NULL); T tmp = currentNode->value; assert ("there are no more entrys in the StringList, call hasNext() first!" && currentNode->next != NULL); currentNode = currentNode->next; return tmp; } /** * Removes the current entry and push the iterator to the next entry. */ void remove() { assert ("first you must inizialize the iterator!" && currentNode != NULL); StringListNode<T> *tmp = currentNode->next; currentNode->previous->next = currentNode->next; currentNode->next->previous = currentNode->previous; delete currentNode; currentNode = tmp; } /** * Special feature of StringList: The entries are named.\n * Returns the name of the entry dependent of the actual iterator position. * @return The entries name. */ string& name() const { assert ("first you must inizialize the iterator!" && currentNode != NULL); return currentNode->name; } operator bool() const { return bool (currentNode); } /** * Returns the value of the entry dependent of the actual iterator position. * @return The entries value. */ reference operator*() const { assert ("first you must inizialize the iterator!" && currentNode != NULL); return currentNode->value; } /** * Returns the value of the entry dependent of the actual iterator position. * return The entries value. */ pointer operator->() const { return &(operator*()); } /** * The ++it prefix operator shifts the iterator to the next entry and returns it * then. * @return Iterator to the new position. */ Iterator& operator++() { assert ("first you must inizialize the iterator!" && currentNode != NULL); assert ("there are no more entrys in the StringList, call if (it==list.end()) first!" && currentNode->next != NULL); currentNode = currentNode->next; return *this; } /** * The --it prefix operator shifts the iterator to the previous entry and returns * it then. * @return Iterator to the new position. */ Iterator& operator--() { assert ("first you must inizialize the iterator!" && currentNode != NULL); assert ("there are no more entrys in the StringList, call if (it==list.begin()) first!" && currentNode->previous != NULL); currentNode = currentNode->previous; return *this; } /** * The it++ postfix operator returns the iterator first and then shifts it * to the next entry. * @return Iterator to the new position. */ Iterator operator++(int) { assert ("first you must inizialize the iterator!" && currentNode != NULL); assert ("there are no more entrys in the StringList, call if (it==list.end()) first!" && currentNode->next != NULL); Iterator tmp = *this; currentNode = currentNode->next; return tmp; } /** * The it-- postfix operator first returns the iterator and then shifts it * to the previous entry. * @return Iterator to the new position. */ Iterator operator--(int) { assert ("first you must inizialize the iterator!" && currentNode != NULL); assert ("there are no more entrys in the StringList, call if (it==list.begin()) first!" && currentNode->previous != NULL); Iterator tmp = *this; currentNode = currentNode->previous; return tmp; } /** * The '==' operator checks if two iterators are directed to the same * StringListNode, say to the same entry of a list. * @return True if it == op2 */ bool operator== (const Iterator& op2) const { if (currentNode == op2.currentNode) return true; else return false; } /** * The opposite of '==' operator. Checks if two iterators not directed to the * same entry of a list. * @return True if it != op2 */ bool operator!= (const Iterator &op2) const { return !(*this == op2); } private: StringListNode<T> *currentNode; }; /** * This is the Const_Iterator for StringList. It implements JavaStyleIterator, means that * the common methods hasNext, next and remove available. STL style operation are * possible too, like ++, --, = and * operations. STL algorithm are also possible * (this is an STL bidirectional_iterator).\n * If you try to use an uninitialized Const_Iterator an assert will occure.\n * Note: EasyFramework use strictly name conventions: Classes are all upper case * and also the iterator class.\n * The const iterator can not change the container! */ class VS_EXPORT Const_Iterator : public JavaStyleIterator<T>, public std::iterator<std::bidirectional_iterator_tag, const T> { public: // typedefs typedef const T value_type; typedef const T& reference; typedef const T* pointer; typedef int difference_type; typedef std::bidirectional_iterator_tag iterator_category; friend class StringList<T>; /** * You need no parameters for an iterator, but before the first use the iterator * must be initialized (with '=' operator for example). * @param node Optional parameter to direct the iterator to an ListNode. * Only for internal use. */ Const_Iterator(const StringListNode<T> *node = NULL) :currentNode(node) {} /** * Overloaded constructor for more const compability (Const_Iterator must be able * to direct to an const StringListNode and a StringListNode). */ Const_Iterator(StringListNode<T> *node) :currentNode(const_cast<const StringListNode<T>*> (node) ) {} /** * A useful iterator initialization. Pass a list to the constructor parameter to * direct the iterator to the first entry of the list. * @param list The target list for the iterator */ Const_Iterator(const StringList<T> &list) { *this = list.begin(); } /** * Copyconstructor. * @param it iterator to copy. */ Const_Iterator(const Const_Iterator &it) :currentNode(it.currentNode) {} /** * Java style method. Checks if the list has a next entry, dependent of the * iterator position. * @return True if the list still has a next entry from the iterator position. */ bool hasNext() const { assert("first you must inizialize the Const_Iterator!" && currentNode != NULL); if (currentNode->next != NULL) return true; return false; } /** * Returns the current entry without iterater shifting (additional vs method, no java * style but useful). * @return The current entry. */ T current() const { assert ("first you must inizialize the iterator!" && currentNode != NULL); return currentNode->value; } /** * Java style method. Returns the current entry and set the iterator to the next.\n * First check if the list has a next entry with hasNext()! Otherwise an assert * will occure. * @return The current entry. */ T next() { assert ("first you must inizialize the Const_Iterator!" && currentNode != NULL); T tmp = currentNode->value; assert ("there are no more entrys in the StringList, call hasNext() first!" && currentNode->next != NULL); currentNode = currentNode->next; return tmp; } /** * Removes the current entry and push the iterator to the next entry. */ void remove() { assert ("first you must inizialize the Const_Iterator!" && currentNode != NULL); StringListNode<T> *tmp = currentNode->next; currentNode->previous->next = currentNode->next; currentNode->next->previous = currentNode->previous; delete currentNode; currentNode = tmp; } /** * Returns the value of the entry dependent of the actual iterator position. * @return The entries value. */ reference operator*() const { assert ("first you must inizialize the Const_Iterator!" && currentNode != NULL); return currentNode->value; } /** * Returns the value of the entry dependent of the actual iterator position. * return The entries value. */ pointer operator->() const { return &(operator*()); } /** * The ++it prefix operator shifts the iterator to the next entry and returns it * then. * @return iterator to the new position. */ Const_Iterator& operator++() { assert ("first you must inizialize the Const_Iterator!" && currentNode != NULL); assert ("there are no more entrys in the StringList, call if (it==list.end()) first!" && currentNode->next != NULL); currentNode = currentNode->next; return *this; } /** * The --it prefix operator shifts the iterator to the previous entry and returns * it then. * @return iterator to the new position. */ Const_Iterator& operator--() { assert ("first you must inizialize the Const_Iterator!" && currentNode != NULL); assert ("there are no more entrys in the StringList, call if (it==list.begin()) first!" && currentNode->previous != NULL); currentNode = currentNode->previous; return *this; } /** * The it++ postfix operator returns the iterator first and then shifts it * to the next entry. * @return Const_Iterator to the new position. */ Const_Iterator operator++(int) { assert ("first you must inizialize the Const_Iterator!" && currentNode != NULL); assert ("there are no more entrys in the StringList, call if (it==list.end()) first!" && currentNode->next != NULL); Const_Iterator tmp = *this; currentNode = currentNode->next; return tmp; } /** * The it-- postfix operator first returns the iterator and then shifts it * to the previous entry. * @return iterator to the new position. */ Const_Iterator operator--(int) { assert ("first you must inizialize the Const_Iterator!" && currentNode != NULL); assert ("there are no more entrys in the StringList, call if (it==list.begin()) first!" && currentNode->previous != NULL); Const_Iterator tmp = *this; currentNode = currentNode->previous; return tmp; } /** * The '==' operator checks if two iterators are directed to the same * StringListNode, say to the same entry of a list. * @return True if it == op2 */ bool operator== (const Const_Iterator& op2) const { if (currentNode == op2.currentNode) return true; else return false; } /** * The opposite of '==' operator. Checks if two iterators not directed to the * same entry of a list. * @return True if it != op2 */ bool operator!= (const Const_Iterator &op2) const { return !(*this == op2); } private: // this is const! const StringListNode<T> *currentNode; }; // -------------- Java section ------------------ /** * This method implements the JavaStyleContainer interfaces an returns an iterator * pointer with JavaStyleIterator type. * @return Look out for Iterator pattern for further informations. * @see JavaStyleContainer, JavaStyleIterator */ SmartIterator<T> iterator() const { if (empty()) return SmartIterator<T> (new NullIterator<T>); else return SmartIterator<T> (new Iterator(head->next)); } void add(const T element) { push_back(element); } void add(const T element, string name) { push_back(element, name); } /** * Removes all entries by a given name. If there is no entry with this name, * nothing happens. * @param name All entries with this values will be removed */ bool remove(const string &name) { bool changed = false; Iterator it = this->begin(); while (it != this->end()) { if (it.name() == name) { erase(it); changed = true; } else ++it; } return changed; } /** * Removes all entries by a given value. If there is no entry whis this value, * nothing happens. * @param value All entries with this value will be removed. */ bool remove(const T value) { bool changed = false; Iterator it = this->begin(); while (it != this->end()) { if (*it == value) { erase(it); changed = true; } else ++it; } return changed; } // ----------- Java section end ---------------- /** * Returns an iterator wich is directed to the beginning of the StringList (head->next). If the list * is empty, the iterator will directed to the tail of the list (no error).\n * Note: Check with empty() if there is an entry first! * @return An iterator to the first entry. */ Iterator begin() { return Iterator(head->next); } /** * Returns an iterator wich is directed the end of the StringList (tail). */ Iterator end() { return Iterator(tail); } /** * Returns an const iterator wich is directed to the beginning of the List (head->next). If the list * is empty, the iterator will directed to the tail of the list (no error).\n * Note: Check with empty() if there is an entry first!\n * The const iterator can not change the container. * @return An iterator to the first entry. */ Const_Iterator begin() const { return Const_Iterator(head->next); } /** * Returns an const iterator wich is directed the end of the List (tail). */ Const_Iterator end() const { return Const_Iterator(tail); } /** * Pushes an (named) entry at the front of the list. * @param value Pass the value you have determined at the template specifier \<T\>. * @param name A special feature of StringList: You can name the entrys (optional). * The default name is "". */ void push_front(T value, string name = "") { StringListNode<T> *tmp = new StringListNode<T>(value, name); tmp->next = head->next; tmp->previous = head; head->next->previous = tmp; head->next = tmp; } /** * The front entry of the list will removed, if the list isn't empty. * If the list is empty nothing happens. */ void pop_front() { if (!empty()) { StringListNode<T> *tmp = head->next->next; delete head->next; head->next = tmp; tmp->previous = head; } } /** * Getter for the front entry of the list. Note: If there is no entry, an assert * will occure! First check with isEmpty() if there is an entry at all. * @return The front entry value of the list. */ T front() const { if (!empty()) return head->next->value; else { assert("StringList is empty! front() is forbidden!"); return 0; } } /** * Special feature of StringList: Returns the front entrys name of the list. * Note: If there is no entry, an assert will occure! First check with isEmpty() if * there is an entry at all. * @return The name of the front entry as std::string. */ string frontName() const { if (!empty()) return head->next->name; else { assert("StringList is empty! frontName() is forbidden!"); return 0; } } /** * Pushes an (named) entry at back of the list. * @param value Pass the value you have determined at the template specifier \<T\>. * @param name A special feature of StringList: You can name the entrys (optional). * The default name is "". */ void push_back(T value, string name = "") { StringListNode<T> *tmp = new StringListNode<T>(value, name); tmp->next = tail; tmp->previous = tail->previous; tail->previous->next = tmp; tail->previous = tmp; } /** * The back entry of the list will removed, if the list isn't empty. * If the list is empty nothing happens. */ void pop_back() { if (!empty()) { StringListNode<T> *tmp = tail->previous->previous; delete tail->previous; tail->previous = tmp; tmp->next = tail; } } /** * Getter for the back entry of the list. Note: If there is no entry, an assert * will occure! First check with isEmpty() if there is an entry at all. * @return The back entry value of the list. */ T back() const { if(!empty()) return tail->previous->value; else { assert("StringList is empty! back() is forbidden!"); return 0; } } /** * Special feature of StringList: Returns the back entrys name of the list. * Note: If there is no entry, an assert will occure! First check with isEmpty() if * there is an entry at all. * @return The name of the back entry as std::string. */ string backName() const { if(!empty()) return tail->previous->name; else { assert("StringList is empty! backName() is forbidden!"); return 0; } } /** * Transferes the complete sourceStringList to an appointed place in this list (one * entry before the iterator position). After this operation the sourceStringList will be empty. * It's a efficiently operation: O(1). * @param position Specifies the position in this list the copy will paste. After the * insertion the iterator shows the next entry after insertion. * @param sourceStringList The source list wich entrys will completely shifted to this list. */ void splice(Iterator &position, StringList<T> &sourceStringList) { assert("source list should not be the list itself" && sourceStringList != *this); StringListNode<T> *insert = position.currentNode; insert->previous->next = sourceStringList.head->next; sourceStringList.head->next->previous = insert->previous; sourceStringList.tail->previous->next = insert; insert->previous = sourceStringList.tail->previous; sourceStringList.head->next = sourceStringList.tail; sourceStringList.tail->previous = sourceStringList.head; } /** * Transferes a single entry from sourceStringList to an appointed place in this list * (one entry before the iterator position).\n * The entry will removed from sourceStringList and added in sourceStringList. * It's a efficiently operation: O(1). * @param position Specifies the position in this list the copy will paste. After the * insertion the iterator shows the next entry after insertion. * @param sourceStringList The source list wich entry will shifted to this list. * @param sourceElement The place of the entry in source list who will be moved. * After the operation the iterator shows the entry after the removed. */ void splice(Iterator &position, StringList<T> &sourceStringList, Iterator &sourceElement) { assert("source list should not be the list itself" && sourceStringList != *this); StringListNode<T> *insert = position.currentNode; StringListNode<T> *element = sourceElement.currentNode; ++sourceElement; element->previous->next = element->next; element->next->previous = element->previous; insert->previous->next = element; element->previous = insert->previous; element->next = insert; insert->previous = element; } /** * Transferes a range (start to end iterator) of entries from sourceStringList to * an appointed place in this list (one entry before the iterator position).\n * The entries will removed from sourceStringList and added in sourceStringList.\n * Note: The start and end iterators must directed to sourceStringList.\n * If the end iterator isn't linked to sourceStringList, the transfer stops on the * end of sourceStringList. * It's a efficiently operation: O(1). * @param position Specifies the position in this list the copy will paste. After the * insertion the iterator shows the next entry after insertion. * @param sourceStringList The source list wich entries will shifted to this list. * @param start The start marker (iterator) of the range in source list. After the * operation the iterator shows the entry in source list after the end iterator. * @param end The end marker (iterator) of the range in source list. */ void splice(Iterator &position, StringList<T> &sourceStringList, Iterator &start, Iterator &end) { assert("source list should not be the list itself" && sourceStringList != *this); StringListNode<T> *insert = position.currentNode; StringListNode<T> *s = start.currentNode; StringListNode<T> *e = end.currentNode; s->previous->next = e->next; e->next->previous = s->previous; insert->previous->next = s; s->previous = insert->previous; e->next = insert; insert->previous = e; } /** * Swaps another list with this one in constant time. * @param list The other list, this list will swapped with. */ void swap(StringList<T> &list) { vs::base::cont::swap(*this, list); } /** * Deletes an entry in the StringList with an iterator. * @param position An iterator shows the position in StringList to delete an entry.\n * Note: After a deletion the iterator shows to the next entry! * @return Iterator to the new position (after deletion). */ Iterator erase(Iterator &position) { assert ("first you must inizialize the iterator!" && position.currentNode != NULL); assert ("iterator is directed to a wrong entry. Can't erase this!" && position.currentNode != head && position.currentNode != tail); StringListNode<T> *tmp = position.currentNode->next; position.currentNode->previous->next = position.currentNode->next; position.currentNode->next->previous = position.currentNode->previous; delete position.currentNode; position.currentNode = tmp; return position; } /** * Deletes several entries in the StringList with two iterators. * @param first The start position in StringList of the entries to delete. * @param last The last position in StringList of the entries to delete. * @return Iterator to the new position (after deletion). */ Iterator erase(Iterator &first, Iterator &last) { assert ("first you must inizialize the two iterators!" && first.currentNode != NULL && last.currentNode != NULL); assert ("first iterator is directed to a wrong entry. Can't erase this!" && first.currentNode != head && first.currentNode != tail); assert ("last iterator is directed to a wrong entry. Can't erase this!" && last.currentNode != head && last.currentNode != tail); StringListNode<T> *tmp = first.currentNode; first.currentNode = first.currentNode->previous; last.currentNode = last.currentNode->next; while(tmp != last.currentNode) { tmp = tmp->next; delete tmp->previous; } first.currentNode->next = last.currentNode; last.currentNode->previous = first.currentNode; first.currentNode = last.currentNode; return first; } /** * Inserts an entry in the StringList with an iterator. The entry will be added before * the iteratiors indication. * @param position An entry will be added before this position. * @param value The entry value who will insert before the position. * @param name The name of the new entry value (optional). The default name is "". * @return Iterator to the new entry. */ Iterator insert(Iterator &position, const T value, string name = "") { assert ("first you must inizialize the iterator!" && position.currentNode != NULL); assert("iterator is directed to a wrong entry. Can't insert entry there!" && position.currentNode != head); StringListNode<T> *tmp = new StringListNode<T>(value, name); position.currentNode->previous->next = tmp; tmp->previous = position.currentNode->previous; position.currentNode->previous = tmp; tmp->next = position.currentNode; position.currentNode = tmp; return tmp; } /** * Search an entry by name and checks if the entry exist.\n * Note: If there are several entrys with the same name, the first match will * returned! The items must be names useful. * @code // Usage example * StringList<int> ids; * ids.push_front(55, "glHouse"); * ids.push_front(46, "glTree"); * ... * int id; * if (ids.byName("glTree", id)) * cout << "the glTree id is: " << id << endl; * else * cout << "there is no glTree id!" << endl; * @endcode * * @param name The name of the searched entry. * @param value If the entry was found, it will returned by the value reference. * If the entry was not found, the value will be -1. * @return Check if the entry was found (true) or not exist (false). */ bool byName(const string &name, T &value) const { // todo: optimierungen, z.b. cache ... StringListNode<T> *tmp = head; while (tmp->next != tail) { if (tmp->next->name == name) { value = tmp->next->value; return true; } tmp = tmp->next; } return false; } /** * Search an entry by name and checks if the entry exist.\n * Note: If there are several entrys with the same name, the first match will * returned! The items must be names useful. * @param name The name of the searched entry. * @param it If the entry was found, an iterator wich is directed to it will returned. * @return Check if the entry was found (true) or not exist (false). */ bool byName(const string &name, Iterator &it) const { // todo: optimierungen, z.b. cache ... StringListNode<T> *tmp = head; while (tmp->next != tail) { if (tmp->next->name == name) { it = Iterator(tmp->next); return true; } tmp = tmp->next; } return false; } /** * Search an entry by name and checks if the entry exist.\n * Note: If there are several entrys with the same name, the first match will * returned! The items must be names useful.\n * The advantage of using JavaStryleIterator is thas you can programming with an * abstract iterator and its save! When the entry is not found, a NullIterarot will * returned. * @param name The name of the searched entry. * @param it If the entry was found, an iterator wich is directed to it will returned. * @return Check if the entry was found (true) or not exist (false). * @see JavaStyleIterator, NullIterator */ bool byName(const string &name, SmartIterator<T> &it) const { // todo: speicherleiche entfernen StringListNode<T> *tmp = head; while (tmp->next != tail) { if (tmp->next->name == name) { it = SmartIterator<T>(new Iterator(tmp->next)); return true; } tmp = tmp->next; } it = SmartIterator<T>(new NullIterator<T>()); return false; } /** * Special feature of StringList.\n * Search an entry by name and returns an iterator on it. If the searched name does * not exist, the iterator on the end of the list will be returned. Check this with * @code // Example * StringList<char *>::iterator it; * it = myList.findByName("Adress"); * if (it != myList.end()) * printf("%s\n", *it); // output: 78357 Stockach (for example) * @endcode * * @param name The name of the searched entry. * @return Iterator to the first found found entry (if exists) or to the end of the list. */ Iterator findByName(const string name) { StringListNode<T> *tmp = head; while (tmp->next != tail) { if (tmp->next->name == name) { return Iterator(tmp->next); } tmp = tmp->next; } return Iterator(tail); } /** * A search method in STL style.\n * Search an entry by value and returns an iterator on it. If the searched name does * not exist, the iterator on the end of the list will be returned. Check this with * @code // Example * StringList<char *>::iterator it; * it = myList.find(55); * if (it != myList.end()) * printf("%d\n", *it); // output: 55 * @endcode * * @return Iterator to the first found entry (if exists) or to the end of the list. */ Iterator find(const T value) { StringListNode<T> *tmp = head; while (tmp->next != tail) { if (tmp->next->value == value) { return Iterator(tmp->next); } tmp = tmp->next; } return Iterator(tail); } /** * All entrys will be cleared. After this operation the container is empty. * Of course you can refill it. */ void clear() { StringListNode<T> *tmp; while (head->next != tail) { tmp = head->next->next; delete head->next; head->next = tmp; } tail->previous = head; } /** * Count the number of all entrys in the list and returns it. Optional you can count the * entries by name. * @param name Count the number of entries named with "name". If you don't pass an * argument, all entries will count (like size()). * @return The number of entries. */ int count(const string &name = "") const { if (name == "") return size(); else { int num = 0; if (empty()) return 0; StringListNode<T> *tmp = head->next; while(tmp->next != tail) { if (name == tmp->name) ++num; tmp = tmp->next; } if (name == tmp->name) ++num; return num; } } /** * Count the number of values in the list and return it. Overloaded method. * @param value The value the method will searched with. * @return The number of entries. */ int count(const T value) const { if (empty()) return 0; int num = 0; StringListNode<T> *tmp = head->next; while (tmp->next != tail) { if (value == tmp->value) ++num; tmp = tmp->next; } if (value == tmp->value) ++num; return num; } /** * Count the number of all entrys in the list and returns it. * @return The number of entrys. */ int size() const { if (empty()) return 0; else { int num = 1; StringListNode<T> *tmp = head->next; while(tmp->next != tail) { ++num; tmp = tmp->next; } return num; } } /** * Check if there is a entry or not. * @return If there is no entry it returns true. */ bool empty() const { if (head->next == tail) return true; else return false; } /** * Cout all entries names to the std console. Useful for debugging. Note that * only the name will be printed! */ void coutNames() const { StringListNode<T> *tmp = head; while (tmp->next != tail) { tmp = tmp->next; cout << tmp->name << endl; } } // global swap for StringList friend void vs::base::cont::swap<T>(StringList<T> &list_1, StringList<T> &list_2); private: StringListNode<T> *head; StringListNode<T> *tail; }; /** * An entry node used by the StringList class. It contains a name and a template value.\n * Note: You don't must touch this! * @see StringList */ template <class T> class VS_EXPORT StringListNode { public: StringListNode(T value, string name = "") :name(name), value(value) { this->next = NULL; this->previous = NULL; } StringListNode(string name = "") :name(name) { this->next = NULL; this->previous = NULL; } friend class StringList<T>; friend class StringList<T>::Iterator; friend class StringList<T>::Const_Iterator; private: string name; StringListNode<T> *next; StringListNode<T> *previous; T value; }; } // cont } // base } // vs #endif // STRING_LIST_H
true
c103c4dcc74caf3e2a8b27e4bac2be30d5182766
C++
huang7017/pccu_cpp_practice
/practice_11/11-統計各組距人數.cpp
BIG5
665
3.453125
3
[]
no_license
/* main禡wJYZ{]pҸզZܰ}CscoreA мg禡distributionHέpUնZ(0-9, 10-19, K,90-99, 100)HơA ȩ̀(ۤƧCܰ)LXέpGC Фŧmain禡C */ #include <iostream> #include <iomanip> using namespace std; void distribution(int name[],int size); int main(){ const int arraySize=100; int score[arraySize]; for(int i=0;i<arraySize;i++){ cin>>score[i]; } distribution(score, arraySize); } void distribution(int name[],int size){ int total[11] = {}; for(int i = 0;i < size;i++){ total[name[i]/10]++; } for(int i = 0;i < 11;i++){ cout << total[i] << " "; } }
true
dadf6a205397f1f5b9796d04239be7c048454bfd
C++
vectormars/CPP
/Design pattern/Builder Pattern/Builder Pattern Meal/Meal.cpp
UTF-8
348
3.21875
3
[]
no_license
#include "Meal.h" Meal::Meal() { //ctor } Meal::~Meal() { //dtor } void Meal::setMealItem(string mealItem) { mMeal.push(mealItem); } void Meal::serveMeal() { int i = 1; while(!mMeal.empty()) { cout << " Serve item " << i++ << ":" << mMeal.front() << endl ; mMeal.pop(); } }
true
839c74af127e63eadbb2de0d5f3b9a7dcbda16a2
C++
battleofdie/interview
/leetcode/Length-of-Last-Word.cpp
UTF-8
545
2.84375
3
[]
no_license
class Solution { public: int lengthOfLastWord(const char *s) { // Note: The Solution object is instantiated only once and is reused by each test case. if(s == NULL) return 0; int p = 0, r = 0; while(*s) { if(*s == ' ') { p = r; r = 0; while(*s == ' ') s++; } else { r++; s++; } } return (r == 0 ? p : r); } };
true
edb15cca5622c2ee997ccc2f9c24e7e7b6650ac9
C++
aallbrig/arduino-glob
/motion_activate_LED_1/motion_activate_LED_1.ino
UTF-8
2,824
2.984375
3
[]
no_license
// Motion Sensor const int motionSensor = 1; // LED lights (6 total) const int greenLed = 9; const int yellowLed = 10; const int redLed1 = 11; const int redLed2 = 12; const int redLed3 = 13; const int waitTime = 3000; const int quickWait = 500; // Servo #include <Servo.h> Servo servo; const int servoPin = 2; int pos = 0; const int servoStartDegree = 50; const int servoEndDegree = 90; // LCD Display #include <LiquidCrystal.h> LiquidCrystal lcd(8, 9, 4, 5, 6, 7); void setup(){ // Servo setup servo.attach(servoPin); servo.write(servoStartDegree); // LED setup pinMode(motionSensor, INPUT); pinMode(greenLed, OUTPUT); pinMode(yellowLed, OUTPUT); pinMode(redLed1, OUTPUT); pinMode(redLed2, OUTPUT); pinMode(redLed3, OUTPUT); // Define LCD Display lcd.begin(16, 2); // any one-time tests /*testLcdDisplay();*/ } void testServo(){ for(pos = 0; pos < 180; pos += 1){ servo.write(pos); delay(15); } servo.write(0); delay(10000); } void testLeds(){ // Test LED lights digitalWrite(greenLed, HIGH); digitalWrite(yellowLed, HIGH); digitalWrite(redLed1, HIGH); resetLeds(); } void testLcdDisplay(){ // set up the LCD's number of columns and rows: lcd.clear(); lcd.home(); // Print a message to the LCD. lcd.setCursor(4, 0); lcd.print("Hello,"); lcd.setCursor(5, 1); lcd.print("Dave..."); delay(waitTime); } void resetLeds(){ digitalWrite(redLed1, LOW); digitalWrite(redLed2, LOW); digitalWrite(redLed3, LOW); digitalWrite(yellowLed, LOW); digitalWrite(greenLed, LOW); } void onMotionSense(){ /* light pattern */ resetLeds(); servo.write(servoEndDegree); lcd.home(); lcd.clear(); lcd.home(); // Print a message to the LCD. lcd.setCursor(4, 0); lcd.print("Hello,"); lcd.setCursor(5, 1); lcd.print("Dave..."); digitalWrite(redLed1, HIGH); digitalWrite(greenLed, LOW); delay(waitTime/3); digitalWrite(yellowLed, HIGH); delay(50); digitalWrite(yellowLed, LOW); delay(50); digitalWrite(yellowLed, HIGH); delay(50); digitalWrite(yellowLed, LOW); delay(50); digitalWrite(yellowLed, HIGH); delay(50); digitalWrite(yellowLed, LOW); delay(waitTime); digitalWrite(greenLed, HIGH); delay(waitTime); digitalWrite(redLed1, LOW); servo.write(servoStartDegree); lcd.clear(); } void onIdle(){ digitalWrite(redLed1, LOW); digitalWrite(redLed2, LOW); digitalWrite(redLed3, HIGH); digitalWrite(yellowLed, LOW); digitalWrite(greenLed, HIGH); delay(quickWait); digitalWrite(redLed3, LOW); digitalWrite(redLed2, HIGH); delay(quickWait); } void loop(){ int value = digitalRead(motionSensor); if (value == HIGH) { onMotionSense(); } else { onIdle(); } /*testServo();*/ /*testLeds();*/ /*testLcdDisplay();*/ }
true
326c2c03a7d4b2f9a48a726f032a75ae597e2116
C++
xchrdw/voxellancer
/src/equipment/equipmentslot.h
UTF-8
808
2.75
3
[]
no_license
#pragma once #include <map> #include <list> #include <string> #include "utils/observable.h" class WorldObjectComponents; /** * Base class for everything on a worldobject that behaves like a slot * that can be (or cannot) be equipped with equipment */ class EquipmentSlot : public Observable { public: EquipmentSlot(WorldObjectComponents* components, int group); virtual ~EquipmentSlot(); std::list<std::string> mountables() const; bool mountable(const std::string& name) const; void setMountable(const std::string& name, bool mountable); WorldObjectComponents* components(); const WorldObjectComponents* components() const; int group() const; protected: WorldObjectComponents* m_components; std::map<std::string, bool> m_mountables; int m_group; };
true
e6bd262c21c5abd055405e3daefcf95b9c14fb13
C++
Gdansk-Embedded-Meetup/slajdy
/Spotkanie #14 2023-05-09/kody/unique_ptr_deleter.cpp
UTF-8
369
3.078125
3
[]
no_license
#include <cstdio> #include <memory> using FilePtr = std::unique_ptr<FILE, decltype([](FILE* f) { std::fclose(f); })>; void print_content(const char* file_path) { FilePtr file{std::fopen(file_path, "r")}; int c; while ((c = std::fgetc(file.get())) != EOF) { std::putchar(c); } } int main() { print_content("example.txt"); return 0; }
true
76f702a71a30ff119d0db0f864517484df0e1be1
C++
ruthvikb14/MagOD
/src/screen/screen_RA8875.cpp
UTF-8
10,737
2.546875
3
[]
no_license
/* screen_8875.cpp MagOD2 libary Mar 2019 Definition of screen layout and screen update functions for TFT050 screen (MAGOD2 system has that one) Tijmen Hageman, Jordi Hendrix, Hans Keizer, Leon Abelmann */ #include "Arduino.h" //Avoid that Arduino IDE compiles this file when not MagOD2 #include "../../MagOD.h" //MagOD version is defined in MagOD.h #if defined(_MAGOD2) #include <SPI.h> #include "screen_RA8875.h" screen::screen(void) { } void screen::updateGraph(double value, int led) { //Needs a serious upgrade, became too complicated. LEON //Plot measurement point and correct for out-of-bounds double val_conv = (value-g_minVal)/(g_maxVal-g_minVal); if(val_conv<0){val_conv=0;} if(val_conv>1){val_conv=1;} val_conv = val_conv*(g_h-3);//scale value on height of graph val_conv = round(g_y+g_h-val_conv-2);//plot it upside down???LEON int pixelcolor = TFTCOLOR_GRAY; /* init to grey, to indicate error */ // Pixel color is determined by led color switch (led) { case RED: pixelcolor = TFTCOLOR_RED; break; case GREEN: pixelcolor = TFTCOLOR_GREEN; break; case BLUE: pixelcolor = TFTCOLOR_BLUE; break; } tft.graphicsMode(); tft.drawPixel(g_xCursor, val_conv, pixelcolor); tft.drawLine(g_xCursor_prev, g_value_prev, g_xCursor, val_conv, pixelcolor);//Why isn't drawing the line sufficient, why also pixel? //store min and max value of a a cycle if (value < value_min) { value_min = value; } if (value > value_max) { value_max = value; } //Update counter g_xCursor_prev = g_xCursor; g_value_prev = val_conv; g_xCursor++; //rescaling of the screengraph if(g_xCursor>=g_x+g_w-1) { g_xCursor=g_x+1; g_xCursor_prev=g_xCursor; g_maxVal = value_max *1.004+0.002; g_minVal = value_min /1.004-0.002; value_max = value; value_min = value; //Erase place for labels tft.fillRect(0,g_y,g_x,g_y+g_h,TFTCOLOR_BLACK); } //Insert empty space //tft.graphicsMode(); tft.drawFastVLine(g_xCursor, g_y+1, g_h-3, TFTCOLOR_BLACK); // Write scale, does not have to be done every run! LEON tft.textMode();/*Go back to default textMode */ tft.textTransparent(TFTCOLOR_YELLOW); char string[15]; //Write min value bottom left tft.textSetCursor(0,g_y+g_h-locText_vSpace); dtostrf(g_minVal, 5, 3, string); tft.textWrite(string,5); //Write max value top left tft.textSetCursor(0,g_y); dtostrf(g_maxVal, 5, 3, string); tft.textWrite(string,5); } //sets button to indicate whether the program is running void screen::setRecButton(bool active) { #if defined(_MAGOD1) uint8_t buttonSize = 5; if(active) { tft.fillCircle(screenSiz_x-buttonSize-1, buttonSize, buttonSize, TFTCOLOR_RED); } else { tft.fillCircle(screenSiz_x-buttonSize-1, buttonSize, buttonSize, TFTCOLOR_GRAY); } #elif defined(_MAGOD2) if(active) { /* Change color and label on start/stop button */ mybuttons.showButtonArea(1, (char *)"Stop", TFTCOLOR_RED, TFTCOLOR_BLACK); } else { /* Change color and label on start/stop button */ mybuttons.showButtonArea(1, (char *)"Start", TFTCOLOR_GREEN, TFTCOLOR_BLACK); } #endif } //setup of text on the screen void screen::setupScreen() { screenSiz_x=SCRN_HOR, screenSiz_h=SCRN_VERT; //Text area locText_x=0, locText_y=0; //Top left of text area locText_hSpace = 40, locText_vSpace=12;//Size of each line column_space = 140; //Space between the two columns of text data //Graph display g_x=40,g_y=88; // Top left of graph g_w=SCRN_HOR-g_x-1,g_h=SCRN_VERT-g_y-2; g_xCursor=g_x+1; g_minVal=0;//Minimum value on the graph (V) g_maxVal=myadc.adsMaxV0;//Maximum value on the graph (V) g_xCursor_prev=g_x+1; g_value_prev=g_y+g_h-2; value_min = g_maxVal; value_max = 0; //tft.initR(INITR_BLACKTAB); No initR in RA8875, ignore for the moment, Leon Serial.println("Trying to find RA8875 screen..."); /* Initialise the display using 'RA8875_480x272' or 'RA8875_800x480' */ if (!tft.begin(RA8875_480x272)) { Serial.println("RA8875 Not Found!"); while (1); } Serial.println("RA8875 Found"); // Initiliaze display tft.displayOn(true); tft.GPIOX(true); // Enable TFT - display enable tied to GPIOX tft.PWM1config(true, RA8875_PWM_CLK_DIV1024); // PWM output for backlight tft.PWM1out(255); tft.fillScreen(RA8875_WHITE); delay(100); /* Switch to text mode */ Serial.println("Screen in Textmode"); tft.textMode(); tft.textSetCursor(100, 100); tft.textTransparent(RA8875_BLACK); tft.textWrite("MagOD 2"); tft.textSetCursor(100, 124); tft.textWrite("Tijmen Hageman, Jordi Hendrix, Hans Keizer"); tft.textSetCursor(100, 148); tft.textWrite("Marcel Welleweerd, Dave van As, Leon Abelmann"); delay(2000); tft.fillScreen(RA8875_BLACK); /* Color of all text labels */ tft.textTransparent(TFTCOLOR_YELLOW); /* Left column */ //Voltage photodiode tft.textSetCursor(locText_x, locText_y+0*locText_vSpace); tft.textWrite("Vdio:"); //Voltage reference diode tft.textSetCursor(locText_x, locText_y+1*locText_vSpace); tft.textWrite("Vled:"); //Temperature tft.textSetCursor(locText_x, locText_y+2*locText_vSpace); tft.textWrite("Temp:"); //Calculated OD tft.textSetCursor(locText_x, locText_y+3*locText_vSpace); tft.textWrite("OD:"); //Current X tft.textSetCursor(locText_x, locText_y+4*locText_vSpace); tft.textWrite("I_x:"); //Current Y tft.textSetCursor(locText_x, locText_y+5*locText_vSpace); tft.textWrite("I_y:"); //Current Z tft.textSetCursor(locText_x, locText_y+6*locText_vSpace); tft.textWrite("I_z:"); /* Right Column */ //Voltage reference photodiode tft.textSetCursor(column_space, locText_y+0*locText_vSpace); tft.textWrite("Vref:"); //Filename: tft.textSetCursor(column_space, locText_y+1*locText_vSpace); tft.textWrite("FILE:"); //Program: tft.textSetCursor(column_space, locText_y+2*locText_vSpace); tft.textWrite("PRG:"); //Which run in the program: tft.textSetCursor(column_space, locText_y+3*locText_vSpace); tft.textWrite("RUN:"); //Which step in the program: tft.textSetCursor(column_space, locText_y+4*locText_vSpace); tft.textWrite("STP:"); this->updateV(Vdiodes,Vrefs,0,Vfb); this->updateInfo(0,0,0,"MAGOD2"); //Draw rectangle for graph tft.drawRect(g_x, g_y, g_w, g_h, TFTCOLOR_WHITE); //tft.drawRect(g_x+1, g_y+1, g_w-2, g_h-2, TFTCOLOR_RED); //Buttons are loaded in initButton } //filling in the values on the screen void screen::updateV(diodes Vdiodes, references Vref, double OD, feedbacks currents) { /* Debug */ /* Serial.print("V : ");Serial.println(Vdiodes.Vdiode); Serial.print("Vled : ");Serial.println(Vdiodes.Vled); Serial.print("Vref : ");Serial.println(Vref.Vref); Serial.print("OD : ");Serial.println(OD); Serial.print("Temp : ");Serial.println(Temperature_degrees); Serial.print("FB_x : ");Serial.println(currents.x); Serial.print("FB_y : ");Serial.println(currents.y); Serial.print("FB_z : ");Serial.println(currents.z); */ //Clear existing data (x0,y0,x1,y1) //Left column tft.fillRect(locText_x+locText_hSpace, locText_y, column_space-locText_hSpace, 7*locText_vSpace+1, TFTCOLOR_BLACK); //Right column // tft.fillRect(column_space+locText_hSpace, // locText_y, // column_space-locText_hSpace, // 5*locText_vSpace+1, TFTCOLOR_BLACK); // Write measured voltages tft.textTransparent(TFTCOLOR_RED); char string[15]; //Signal photodiode tft.textSetCursor(locText_x+locText_hSpace, locText_y+0*locText_vSpace); dtostrf(Vdiodes.Vdiode, 5, 3, string); tft.textWrite(string,5); //Signal reference diode tft.textSetCursor(locText_x+locText_hSpace, locText_y+1*locText_vSpace); dtostrf(Vdiodes.Vled, 5, 3, string); tft.textWrite(string,5); //Temperature tft.textSetCursor(locText_x+locText_hSpace, locText_y+2*locText_vSpace); dtostrf(Temperature_degrees, 5, 3, string); tft.textWrite(string,5); //OD tft.textSetCursor(locText_x+locText_hSpace, locText_y+3*locText_vSpace); dtostrf(OD, 5, 3, string); tft.textWrite(string,5); //Feedback current X tft.textSetCursor(locText_x+locText_hSpace, locText_y+4*locText_vSpace); dtostrf(currents.x, 5, 3, string); tft.textWrite(string,5); //Feedback current Y tft.textSetCursor(locText_x+locText_hSpace, locText_y+5*locText_vSpace); dtostrf(currents.y, 5, 3, string); tft.textWrite(string,5); //Feedback current Z tft.textSetCursor(locText_x+locText_hSpace, locText_y+6*locText_vSpace); dtostrf(currents.z, 5, 3, string); tft.textWrite(string,5); } //update program settings whenever requested void screen::updateInfo(unsigned int Looppar_1, unsigned int Looppar_2, int16_t program_cnt, const char *filename) { //Clear existing data tft.fillRect(locText_x+locText_hSpace+column_space, locText_y, column_space, 7*locText_vSpace+2, TFTCOLOR_BLACK); tft.textTransparent(TFTCOLOR_RED); char string[5]; char filestring[15]; //Reference signal tft.textSetCursor(column_space+locText_hSpace, locText_y+0*locText_vSpace); dtostrf(Vrefs.Vref, 5, 3, string); tft.textWrite(string,5); //FILE tft.textSetCursor(column_space+locText_hSpace, locText_y+1*locText_vSpace); //strcpy(filestring, filename); /* truncate to length of filestring */ //tft.textWrite(filestring); tft.textWrite(filename); //program number tft.textSetCursor(column_space+locText_hSpace, locText_y+2*locText_vSpace); dtostrf(program_cnt, 2, 0, string); tft.textWrite(string); //Run: Looppar_2, number of cycles tft.textSetCursor(column_space+locText_hSpace, locText_y+3*locText_vSpace); dtostrf(Looppar_2, 2, 0, string); tft.textWrite(string); //Step: Looppar_1, which step in the cycle tft.textSetCursor(column_space+locText_hSpace, locText_y+4*locText_vSpace); dtostrf(Looppar_1, 2, 0, string); tft.textWrite(string); } // Update the filename field in the info column void screen::updateFILE(const char *filename) { /* Loopar_ and program_cnt are globals defined in MagOD.h */ Serial.print("UpdateFile, filename is "); Serial.println(filename); updateInfo(Looppar_1, Looppar_2, program_cnt, filename); } #endif // defined _MAGOD2
true
5fe878517af84e028fc682cd3699baefd0c4a4cd
C++
bamboohiko/problemSolve
/swjtu/e20150426/t2_ph.cpp
UTF-8
515
2.90625
3
[]
no_license
#include<iostream> using namespace std; bool f[26]; void init(){ for(int i=0;i<26;i++) f[i] = false; } int main(){ int n; bool flag; char ch; while(cin>>n){ init(); flag = false; for(int i = 0; i < n; i++){ cin>>ch; if((ch>='A')&&(ch<='Z')) ch+=32; if(!f[ch-97]) f[ch-97] = true; } for(int i = 0; i < 26; i++){ if(f[i] == false){ flag = true; break; } } if(flag) cout<<"NO"<<endl; else cout<<"YES"<<endl; } return 0; }
true
795462251439e50ba6252dabc68fd204d899741c
C++
klingerf2/SmartDME
/raspberrypi/sketchbook/wifly_firmware_update/wifly_firmware_update.ino
UTF-8
4,222
2.59375
3
[ "Unlicense" ]
permissive
/* This script is made for a WiFly connected to a Arduino Leonardo (with the protoshield for example) or the Helios gadget ( http://www.heliosgadget.nl/ ) This script will update your WiFly to the following firmware files wifly7-400.img wifly7-400.mif Please change those file names in case there is new firmware available. http://www.rovingnetworks.com/Current_Firmware */ #include "WiFly_communicator.h" #define SSID "smartDME" #define KEY "Smart-DME" // WIFLY_AUTH_OPEN / WIFLY_AUTH_WPA1 / WIFLY_AUTH_WPA1_2 / WIFLY_AUTH_WPA2_PSK #define AUTH WIFLY_AUTH_WPA1_2 //#include <WiFlyHQ.h> //wiFly //#include <TinyGPS.h> //GPS #include <SoftwareSerial.h> /* initialize objects */ //TinyGPS gps; WiFly wifly; /* Setup serial connections */ SoftwareSerial Serial1(7,8); boolean firmwareUpdated = false; // set to true when firmware is updated, next boot sequence the .mif files are done void setup() { Serial.begin(115200); // Serial monitor // don't do anything until the serial monitor is opened while (!Serial) { ; // wait for serial port to connect. } Serial.println("starting..."); delay(200); // give WiFly some time to power up // for debugging this script we can reset the firmware again //Serial1.begin(9600); // Wifly //delay(50); //wifly.sendCommand("boot image 2\r", "=OK"); //wifly.sendCommand("save\r", "Storing"); //wifly.reboot(); // run factory reset otherwise ftp connection doesn't work sometimes Serial1.begin(9600); wifly.reset(); // factory reset in case settings where changed wifly.sendCommand("save\r", "Storing"); // save wifly.reboot(); delay(200); Serial1.flush(); Serial1.end(); initWifly(); } void initWifly() { delay(200); Serial1.begin(9600); // rx/tx WiFly Serial1.flush(); // errors without doing this wifly.clear(); // errors without doing this wifly.dataMode(); // errors without doing this delay(200); wifly.sendCommand("set i d 1\r", "AOK"); wifly.sendCommand("set w j 0\r", "AOK"); wifly.sendCommand("set o j 2000\r", "AOK"); wifly.sendCommand("save\r", "Storing"); while (1) { Serial.println("Try to join " SSID ); if (wifly.join(SSID, KEY, AUTH)) { Serial.println("Succeed to join " SSID); wifly.clear(); updateFirmware(); break; } else { Serial.println("Failed to join " SSID); Serial.println("Wait 3 second and try again..."); delay(3000); } } } void updateFirmware() { wifly.sendCommand("set ftp address 0\r", "AOK"); wifly.sendCommand("set dns name rn.microchip.com\r", "AOK"); wifly.sendCommand("save\r", "Storing"); if(firmwareUpdated != true) { // first update the firmware img Serial.println("Starting firmware update from ftp, feedback is not visible, this can take a some seconds."); if(wifly.sendCommand("ftp update wifly7-400.img\r", "UPDATE OK", 30000) == true) { Serial.println("Firmware update succeeded!"); firmwareUpdated = true; wifly.sendCommand("factory RESET\r", "Defaults", 2000); wifly.reboot(); delay(500); initWifly(); } else Serial.println("Firmware update failed. Please retry by reseting the board."); } else { // then update the additional files .mif Serial.println("Starting additional files update from ftp, feedback is not visible, this can take a some seconds."); if(wifly.sendCommand("ftp update wifly7-400.mif\r", "UPDATE OK", 60000)) { Serial.println("Additional files update succeeded!"); } else Serial.println("Additional files update failed. Please retry by reseting the board."); } } void loop() { while(wifly.available()) { /* if(wifly.peek() == '*') { if(wifly.find("*Reboot*�")) { if(reInitOnReboot == true) { Serial.println("re-init"); initWifly(); } } } */ Serial.write(wifly.read()); } if (Serial.available()) { wifly.write(Serial.read()); } }
true
b6186ce74c8ec61ca31a6aa083e6b8793ce06b13
C++
vabalcar/Todolister
/Todolister/TOIIO.h
UTF-8
375
2.5625
3
[ "MIT" ]
permissive
#pragma once #include "TOIParser.h" #include "TOIPrinter.h" class TOIIO { public: TOIIO(toiParserPtr parser, toiPrinterPtr printer) : parser_(move(parser)), printer_(move(printer)) {} TOIParser& getParser() { return *parser_; } TOIPrinter& getPrinter() { return *printer_; } private: toiParserPtr parser_; toiPrinterPtr printer_; }; typedef unique_ptr<TOIIO> toiIOPtr;
true
e760a71e093ddd306be758e28f227888b706bb5c
C++
EricRobertBrewer/SonomaState
/cs450/Project2/shell.cpp
UTF-8
5,352
2.84375
3
[]
no_license
/* shell.cpp Eric Brewer 12/6/10 Kooshesh CS450 - Operating Systems Shell program; main function - */ #include <iostream> #include <string> #include <cstring> using namespace std; #include <unistd.h> #include <wait.h> #include <stdlib.h> #include <fcntl.h> #include "Parser.hpp" #define DEBUG 0 #define debug if( DEBUG ) cout #define MAX_LINE 1024 #define MAX_PIPES 15 #define MAX_LEXEMES 271 #define MAX_COMMANDS 16 #define MAX_ARGS 16 #define MAX_STR_LENGTH 256 enum DIRECTION{ READ = 0, WRITE }; int main( int argc, char *argv[] ){ Parser parser; string line; string lexemes[MAX_LEXEMES]; string commands[MAX_COMMANDS][MAX_ARGS]; char*** c_commands = new char**[MAX_COMMANDS]; for( int i = 0; i < MAX_COMMANDS; i++ ){ c_commands[i] = new char*[MAX_ARGS]; for( int j = 0; j < MAX_ARGS; j++ ) c_commands[i][j] = new char[MAX_STR_LENGTH]; } // Needed to prevent Seg. Faults after a c-string is set to NULL // to appease execvp(). char*** null_backup = new char**[MAX_COMMANDS]; null_backup = c_commands; for( int i = 0; i < MAX_COMMANDS; i++ ){ null_backup[i] = new char*[MAX_ARGS]; null_backup[i] = c_commands[i]; for( int j = 0; j < MAX_ARGS; j++ ){ null_backup[i][j] = new char[MAX_STR_LENGTH]; null_backup[i][j] = c_commands[i][j]; } } int pipefds[MAX_PIPES][2]; int num_pipes, lindex, num_commands, pindex; int num_args[MAX_COMMANDS]; int redirect[2]; while( true ){ // Initialization num_pipes = 0; num_commands = 0; for( int i = 0; i < MAX_COMMANDS; i++ ) num_args[i] = 0; redirect[READ] = 0; redirect[WRITE] = 1; // Grab the entire line cout << "[SHELL]$ "; getline( cin, line ); parser.setLine( line ); // Throw each word of the line into lexemes[]. Count number of pipes for( lindex = 0; !parser.eol(); lindex++ ){ if( ( lexemes[lindex] = parser.getNextLexeme() ) == "|" ) num_pipes++; } // Debug debug << "lindex: " << lindex << endl; debug << "num_pipes: " << num_pipes << endl; // Create the 'string commands[][]' structure // For example: // sort -n aFile | uniq -c | sort -nr // becomes: // 0 1 2 // 0 sort -n aFile // 1 uniq -c // 2 sort -nr for( int i = 0; i < lindex; i++ ){ if( lexemes[i] == "|" ){ num_commands++; num_args[num_commands] = 0; } else{ commands[num_commands][num_args[num_commands]] = lexemes[i]; num_args[num_commands]++; } } num_commands++; // Copy C++ strings into associated c-strings in identical structure for( int i = 0; i < num_commands; i++ ){ for( int j = 0; j < num_args[i]; j++ ) strcpy( c_commands[i][j], commands[i][j].c_str() ); // set to NULL because execvp takes an array of c-strings terminated by a null string // char*** null_backup has the original pointer saved c_commands[i][num_args[i]] = 0; } // More debug debug << "C++ strings: " << endl; for( int i = 0; i < num_commands; i++ ){ for( int j = 0; j < num_args[i]; j++ ){ debug << commands[i][j] << ' '; } debug << endl; } debug << "c-strings: " << endl; for( int i = 0; i < num_commands; i++ ){ for( int j = 0; j < num_args[i]; j++ ){ debug << c_commands[i][j] << ' '; } debug << endl; } // After we create the c_commands[][] structure, we can execute //pipefds[0][READ] = redirect[READ]; //debug << "pipefds[0][READ]: " << pipefds[0][READ] << endl; for( pindex = 1; pindex <= num_pipes; pindex++ ){ if( pindex != 1 ) close( pipefds[pindex-1][WRITE] ); pipe( pipefds[pindex] ); debug << "c_commands[" << pindex-1 << "][0]: " << c_commands[pindex-1][0] << endl; debug << "pipefds[" << pindex << "][READ]: " << pipefds[pindex][READ] << endl; debug << "pipefds[" << pindex << "][WRITE]: " << pipefds[pindex][WRITE] << endl; // Child process if( fork() == 0 ){ dup2( pipefds[pindex-1][READ], 0 ); close( pipefds[pindex-1][READ] ); dup2( pipefds[pindex][WRITE], 1 ); close( pipefds[pindex][WRITE] ); close( pipefds[pindex][READ] ); execvp( c_commands[pindex-1][0], c_commands[pindex-1] ); } if( pindex != 1 ) close( pipefds[pindex-1][READ] ); } // Once there are no more pipes, repeat //pipefds[num_pipes+1][WRITE] = redirect[WRITE]; //debug << "pipefds[" << num_pipes+1 << "][WRITE]: " << pipefds[num_pipes+1][WRITE] << endl; if( pindex != 1 ) close( pipefds[pindex-1][WRITE] ); debug << "c_commands[" << pindex-1 << "][0]: " << c_commands[pindex-1][0] << endl; debug << "pipefds[" << pindex << "][READ]: " << pipefds[pindex][READ] << endl; debug << "pipefds[" << pindex << "][WRITE]: " << pipefds[pindex][WRITE] << endl; // Child process if( fork() == 0 ){ dup2( pipefds[pindex-1][READ], 0 ); close( pipefds[pindex-1][READ] ); close( pipefds[pindex][READ] ); execvp( c_commands[pindex-1][0], c_commands[pindex-1] ); } if( pindex != 1 ) close( pipefds[pindex-1][READ] ); while( wait( NULL ) != -1 ); // Restore those null c-strings used as last arguments to execvp for( int i = 0; i < num_commands; i++ ) c_commands[i][num_args[i]] = null_backup[i][num_args[i]]; } return 0; }
true
bfd659bc76fdc7f0d3c794a5bcb019f5d322cccd
C++
Drewblue78/C-Plus
/Chapters/Chapter4/Ex7.cpp
UTF-8
876
3.265625
3
[]
no_license
#include <cmath> #include <iostream> using namespace std; double gravitational_force(double m1, double m2, double d); char ans; const double G = 6.673 * pow(10.0, -8.0); double mass1, mass2, distance, gravity; int main() { do { double mass1, mass2, distance; cout << "Enter the mass of the first body (in grams): "; cin >> mass1; cout << "Enter the mass of the second body (in grams): "; cin >> mass2; cout << "Enter the (nonzero) distance between them (in cm): "; cin >> distance; cout << "The gravitational force between the two objects is " << gravitational_force(mass1, mass2, distance) << " dynes.\n"; return 0; { return gravity = (G * mass1 * mass2) / pow(distance, 2.0); } cout << "Do you want to begin again?"; cin >> ans; } while (ans == 'y' || ans == 'Y'); cout << "Have a nice day. \n"; return 0; }
true
5c4a2a970bef065df67bfe70176f634481af8360
C++
n-donnelly/TDE-GameEngine
/TDE Engine/TDE Engine/TDE_Animation.h
UTF-8
1,343
2.78125
3
[]
no_license
#ifndef TDE_ANIMATION #define TDE_ANIMATION #include "Includes.h" #include "TextureManager.h" namespace TDE { class TDEGraphics; class TDE_Animation { public: TDE_Animation(void); TDE_Animation(std::string name, TDEImage* im, Texture* tex, int cellWidth, int cellHeight, int numCells); TDE_Animation(std::string name, TDEImage* cells[], int numCells); ~TDE_Animation(void); void Update(); void Play(int loopTime, int startCell, int numRepeats); void Pause(); void Resume(); void Stop(); void Reset(); void JumpToCell(int i); int GetCurrentCellIndex(); bool isPlaying(); bool isPaused(); bool IsFinished(); int GetCellWidth(); int GetCellHeight(); int GetLoopTime(); int GetNumCells(); string GetName(); void Delete(); TDEImage* GetCurrentCell(); TDEImage* GetCell(int i); private: bool DecomposeImage(Texture* t, TDEImage* im, int cellWidth, int cellHeight, int numCells); void PopulateVector(TDEImage* cells[], int numCells); std::vector<TDEImage> mCells; std::string mName; int mNumCells; int mCellWidth; int mCellHeight; int mCurrentCell; int mLoopTime; int mCellPerSec; bool mPlaying; bool mPaused; bool mFinished; int mRepeats; int mLastUpdate; int mPauseTime; }; } #endif
true
6eda3b492fea5682b6c186fd2e4f8d37c79e0076
C++
chianghonbin/AlphaNet
/include/net/TcpAcceptor.h
UTF-8
871
2.703125
3
[]
no_license
#ifndef TCP_ACCEPTOR_H__ #define TCP_ACCEPTOR_H__ #include <memory> #include <functional> #include <atomic> #include "net/InternetAddress.h" #include "net/Socket.h" #include "net/Channel.h" namespace Net { class TcpStream; class EventLoop; class Channel; class TcpAcceptor { using NewConnectionCallback = std::function<void(int sockfd, const InternetAddress&)> ; public: explicit TcpAcceptor(EventLoop* loop, const InternetAddress& listenAddress); void Listen(); bool IsListening() const { return listening_.load(); } void SetNewConnectionCallBack(const NewConnectionCallback& cb) { newConnCallBack_ = cb; } private: void HandleRead(); private: const InternetAddress& inetAddr_; Socket listenSocket_; Channel acceptChannel_; NewConnectionCallback newConnCallBack_; EventLoop* loop_; std::atomic<bool> listening_; }; } #endif
true