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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
5e55351d87e7b9bab1d0c61af243f5d1a3eee9f9 | C++ | alanennis/arduino_old | /sloeber workspace/heating/heating.ino | UTF-8 | 3,263 | 2.5625 | 3 | [] | no_license |
#define BLYNK_PRINT Serial
#include <SPI.h>
#include <Ethernet.h>
#include <BlynkSimpleEthernet.h>
#include <RBD_Timer.h> // https://github.com/alextaujenis/RBD_Timer
//http://robotsbigdata.com/docs-arduino-timer.html
int Countdown; // Global variable used in Slider widget and runEveryMinute()
int TimeChoice;
byte control_pin = 22;
bool heat_state = false;
int state;
int heating_run_timer;
char auth[] = "a8483d62fa0c4e3f96b906e722d4d3ca";
WidgetLCD lcd(V2);
RBD::Timer heating_timer;
RBD::Timer status_timer;
void LCDUpdate(String lcd_message) { // update the lcd and add new messages
lcd.print(0,0, lcd_message);
}
BLYNK_WRITE(V0){ // add a slider to your project on V0 range 0 to 30 (minutes)
Countdown = param.asInt(); // set variable as Slider value
Serial.println(Countdown);
}
BLYNK_WRITE(V1){ // Get index of timer choice
switch (param.asInt())
{
case 1: { // Item 1
Serial.println("30 minutes heating selected");
heat_action(30000, 1);
break;
}
case 2: { // Item 2
Serial.println("45 minutes heating selected");
heat_action(45000, 1);
break;
}
case 3: { // Item 2
Serial.println("60 minutes heating selected");
heat_action(60000, 1);
break;
}
case 4: { // Item 2
Serial.println("90 minutes heating selected");
heat_action(90000, 1);
break;
}
case 5: { // Item 2
Serial.println("120 minutes heating selected");
heat_action(120000, 1);
break;
}
}
}
void heat_action(unsigned long duration, int action) { //duration in ms; action 0 = off, 1 = on
switch (action)
{
case 0: { // heating off
digitalWrite (control_pin, LOW); //physically turn the pin off
Serial.println("Heating off");
heating_timer.stop();
Serial.println("Timer off");
heat_state = false;
break;
}
case 1: { // heating on for duration
Serial.println("heat action on");
heating_timer.setTimeout(duration);
heating_timer.restart();
digitalWrite(control_pin, HIGH);
heat_state = true;
break;
}
}
}
int get_time_left(){
unsigned long seconds_remaining;
unsigned int minutes_remaining;
seconds_remaining = heating_timer.getInverseValue() / 1000;
//minutes_remaining = seconds_remaining / 60;
return seconds_remaining;
}
void show_heat_state () { //display state in LCD
unsigned long seconds_remaining;
unsigned int minutes_remaining;
state = digitalRead(control_pin);
lcd.clear();
if (state == 0){
lcd.print(0,0, "Heating off");
heating_timer.stop();
}
if (state == 1) {
if (heating_timer.isActive()) {
minutes_remaining = get_time_left();
}
else {
minutes_remaining = 0;
}
lcd.print(0,0, "Heating on");
lcd.print(0,1, minutes_remaining);
lcd.print(3,1, "Minutes left");
}
}
void heat_off() {
heat_action(0,0);
}
void setup()
{
pinMode(control_pin, OUTPUT);
Serial.begin(9600);
Blynk.begin(auth);
lcd.clear();
status_timer.setTimeout(5000);
}
void loop()
{
Blynk.run();
if(heating_timer.onRestart()) { heat_off(); }
if(status_timer.onRestart()) { show_heat_state(); }
}
| true |
ff7a5a4ea583f2201f6603a389b42038daf29617 | C++ | barryntklc/ics212f14 | /Project 2/ABook.cpp | UTF-8 | 15,885 | 3.015625 | 3 | [] | no_license | /******************************************************************************************
*
* NAME: Barryn Chun
*
* HOMEWORK: Project 2
*
* CLASS: ICS 212
*
* INSTRUCTOR: Ravi Narayan
*
* DATE: November 27, 2014
*
* FILE: TempConverter.cpp
*
* DESCRIPTION: C++ rework of ABook
*
*****************************************************************************************/
#include <iostream>
#include <iomanip>
#include <ios>
#include <string>
#include "llist.h"
llist mylist;
char version_no[] = "2.0";
void print_menu(std::string);
void print_usage();
int main_menu();
void option1();
void option2();
void option3();
void option4();
void option5();
void option6();
int getint(std::string, int);
std::string getlines(std::string);
char * convert_string(std::string);
/******************************************************************************************
*
* Function name: main
*
* DESCRIPTION: the main function
*
* Parameters: argc the number of arguments
* argv a character array of arguments
*
* Return values: returnval true if the program runs
* false if arguments are incorrect
*
*****************************************************************************************/
int main(int argc, const char * argv[])
{
#ifdef DEBUG
std::cout << "\n";
std::cout << "[DEBUG] main called\n";
std::cout << "\n";
#endif
int returnval = false;
if (argc == 1)
{
main_menu();
returnval = true;
}
else
{
print_usage();
returnval = false;
}
return returnval;
}
/******************************************************************************************
*
* Function name: print_menu
*
* DESCRIPTION: prints the menu of ABook, with an inserted message
*
* Parameters: message - a message string
*
* Return values: none
*
*****************************************************************************************/
void print_menu(std::string message)
{
#ifdef DEBUG
std::cout << "\n";
std::cout << "[DEBUG] print_menu called\n";
std::cout << "message:\n" << message << "\n";
std::cout << "\n";
#else
system("clear");
#endif
std::cout << "---------------------------------------------------------------------------" << '\n';
std::cout << "[AddressBook] version " << version_no << "\n";
std::cout << "\n";
std::cout << message << "\n";
std::cout << "\n";
std::cout << "\t(1) Add a Contact\n";
std::cout << "\t(2) Delete a Contact\n";
std::cout << "\t(3) Edit a Contact\n";
std::cout << "\t(4) View a Contact's Info\n";
std::cout << "\t(5) List All Contacts\n";
std::cout << "\t(6) Reverse Contact List\n";
std::cout << "\t(7) Exit\n";
std::cout << "\n";
std::cout << "Select any one of the options above by entering the number next to it.\n";
}
/******************************************************************************************
*
* Function name: print_usage
*
* DESCRIPTION: prints the usage errors for ABook if arguments are invalid
*
* Parameters: none
*
* Return values: none
*
*****************************************************************************************/
void print_usage()
{
#ifdef DEBUG
std::cout << "\n";
std::cout << "[DEBUG] print_usage called\n";
std::cout << "\n";
#endif
std::cout << "usage:\t./ABook\n";
std::cout << " \t./ABook debug\n";
}
/******************************************************************************************
*
* Function name: main_menu
*
* DESCRIPTION: runs the main menu in a loop, collects the user's choices,
* and selects an option accordingly
*
* Parameters: none
*
* Return values: 1 (TRUE), indicating that the function has executed
*
*****************************************************************************************/
int main_menu()
{
int exit_status = false;
#ifdef DEBUG
std::cout << "\n";
std::cout << "[DEBUG] main_menu called\n";
std::cout << "\n";
print_menu("Welcome! Debug Mode active.");
#else
print_menu("Welcome!");
#endif
int input = 0;
while(exit_status == false)
{
input = getint(": ", 1); //REMOVE COLON
if (input == 7) //exit
{
#ifndef DEBUG
system("clear");
#endif
exit_status = true;
}
else if (input == 6) //reverse
{
option6();
}
else if (input == 5) //listall
{
option5();
}
else if (input == 4) //view
{
option4();
}
else if (input == 3) //edit
{
option3();
}
else if (input == 2) //delete
{
option2();
}
else if (input == 1) //add
{
option1();
}
else
{
print_menu("[ERROR]: Invalid command. Please choose from options 1-6.");
}
}
return true;
}
/******************************************************************************************
*
* Function name: option1
*
* DESCRIPTION: data collection for option 1 (add)
*
* Parameters: none
*
* Return values: none
*
*****************************************************************************************/
void option1()//add
{
#ifdef DEBUG
std::cout << "\n";
std::cout << "[DEBUG] option1 called\n";
std::cout << "\n";
#endif
#ifndef DEBUG
system("clear");
#endif
std::string name;
std::string address;
int yob;
std::string telno;
std::cout << "[Adding new contact...]----------------------------------------------------" << '\n';
std::cout << "Enter NAME: " << '\n' << ": ";
std::getline(std::cin, name);
std::cout << "Enter ADDRESS (press enter twice to continue): " << '\n';
address = getlines(": ");
std::cout << "Enter BIRTH YEAR: " << '\n'; //move colon to check valid input
yob = getint(": ", 0);
std::cout << "Enter PHONE #: " << '\n' << ": ";
std::getline(std::cin, telno);
mylist.addRecord(convert_string(name), convert_string(address), yob, convert_string(telno));
print_menu("Contact added."); //TODO CHANGE
}
/******************************************************************************************
*
* Function name: option2
*
* DESCRIPTION: data collection for option 2 (delete)
*
* Parameters: none
*
* Return values: none
*
*****************************************************************************************/
void option2()//delete
{
#ifdef DEBUG
std::cout << "\n";
std::cout << "[DEBUG] option2 called\n";
std::cout << "\n";
#endif
#ifndef DEBUG
system("clear");
#endif
if (mylist.isEmpty() == true)
{
print_menu("You have no contacts to delete!"); //TODO CHANGE
}
else
{
std::string name;
int found = false;
std::cout << "[Deleting a contact...]------------------------------------------------" << '\n';
std::cout << "Enter NAME to delete: ";
std::getline(std::cin, name);
found = mylist.deleteRecord(convert_string(name)); //DOES NOT DETECT NAME? wait, remove the return space.
if (found == true)
{
print_menu("Contact(s) deleted.");
}
else
{
print_menu("No such contact found, no contacts deleted.");
}
}
}
/******************************************************************************************
*
* Function name: option3
*
* DESCRIPTION: data collection for option 3 (edit)
*
* Parameters: none
*
* Return values: none
*
*****************************************************************************************/
void option3()//edit
{
#ifdef DEBUG
std::cout << "\n";
std::cout << "[DEBUG] option3 called\n";
std::cout << "\n";
#endif
#ifndef DEBUG
system("clear");
#endif
if (mylist.isEmpty() == true)
{
print_menu("You have no contacts to edit!"); //TODO CHANGE
}
else
{
std::string name;
std::string address;
std::string telno;
int found = false;
std::cout << "[Editing a contact...]-----------------------------------------------------" << '\n';
std::cout << "Enter NAME: " << '\n' << ": ";
std::getline(std::cin, name);
std::cout << "Enter ADDRESS (press enter twice to continue): " << '\n';
address = getlines(": ");
std::cout << "Enter PHONE #: " << '\n' << ": ";
std::getline(std::cin, telno);
found = mylist.modifyRecord(convert_string(name), convert_string(address), convert_string(telno));
if (found == true)
{
print_menu("Info of contact(s) edited.");
}
else
{
print_menu("No matching contacts found, no contacts edited.");
}
}
}
/******************************************************************************************
*
* Function name: option4
*
* DESCRIPTION: data collection for option 4 (print)
*
* Parameters: none
*
* Return values: none
*
*****************************************************************************************/
void option4()//print
{
#ifdef DEBUG
std::cout << "\n";
std::cout << "[DEBUG] option4 called\n";
std::cout << "\n";
#endif
#ifndef DEBUG
system("clear");
#endif
if (mylist.isEmpty() == true)
{
print_menu("You have no contacts to look for!"); //TODO CHANGE
}
else
{
std::string name;
int found = false;
std::cout << "[Looking for a contact...]-------------------------------------------------" << '\n';
std::cout << "Enter NAME to search for: ";
std::getline(std::cin, name);
found = mylist.printRecord(convert_string(name));
getlines(": ");
print_menu("");
}
}
/******************************************************************************************
*
* Function name: option5
*
* DESCRIPTION: operations for option 5 (print all)
*
* Parameters: none
*
* Return values: none
*
*****************************************************************************************/
void option5()//printAll
{
#ifdef DEBUG
std::cout << "\n";
std::cout << "[DEBUG] option5 called\n";
std::cout << "\n";
#endif
#ifndef DEBUG
system("clear");
#endif
if (mylist.isEmpty() == true)
{
print_menu("You have no contacts to show!");
}
else
{
std::cout << mylist;
getlines(": ");
print_menu("");
}
}
/******************************************************************************************
*
* Function name: option6
*
* DESCRIPTION: operations for option 6 (reverse)
*
* Parameters: none
*
* Return values: none
*
*****************************************************************************************/
void option6()//reverse
{
#ifdef DEBUG
std::cout << "\n";
std::cout << "[DEBUG] option6 called\n";
std::cout << "\n";
#endif
#ifndef DEBUG
system("clear");
#endif
if (mylist.isEmpty() == true)
{
print_menu("You have no contacts to reorder!");
}
else
{
mylist.reverse();
print_menu("Contact list reversed.");
}
}
/******************************************************************************************
*
* Function name: getint
*
* DESCRIPTION: gets a valid integer for input
*
* Parameters: msg - an input message
* usage - what getint is to be used for (input mode)
* 0 - for getting a valid int in general
* 1 - for getting a valid int for a menu option
*
* Return values: input - a validated integer
*
*****************************************************************************************/
int getint(std::string msg, int usage)
{
#ifdef DEBUG
std::cout << "\n";
std::cout << "[DEBUG] getint called\n";
std::cout << "msg: " << msg << "\n";
std::cout << "usage: " << usage << "\n";
std::cout << "\n";
#endif
int input = 0;
int validNumber = false;
while (validNumber == false)
{
std::cout << msg;
std::cin >> input;
if (!std::cin)
{
if (usage == 0)
{
std::cout << "[ERROR]: Please enter a valid number." << '\n';
}
else if (usage == 1)
{
print_menu("[ERROR]: Invalid command. Please choose from options 1-7.");
}
std::cin.clear();
std::cin.ignore(INT_MAX, '\n');
}
else
{
std::cin.ignore(INT_MAX, '\n');
if (input > 0) {
validNumber = true;
}
else
{
if (usage == 0)
{
std::cout << "[ERROR]: Please provide a number greater than zero." << '\n';
}
else if (usage == 1)
{
print_menu("[ERROR]: Invalid command. Please choose from options 1-7.");
}
}
}
}
return input;
}
/******************************************************************************************
*
* Function name: getlines
*
* DESCRIPTION: gets multiple lines of user input
*
* Parameters: msg - a message printed before user input
*
* Return values: buffer - a string buffer containing total user input
*
*****************************************************************************************/
std::string getlines(std::string msg)
{
#ifdef DEBUG
std::cout << "\n";
std::cout << "[DEBUG] getlines called\n";
std::cout << "msg: " << msg << "\n";
std::cout << "\n";
#endif
std::string input = "";
std::string buffer = "";
int exit_status = false;
while (exit_status == false)
{
std::cout << msg;
std::getline(std::cin, input);
if (input != "")
{
buffer.append(input);
buffer.append("\n");
}
else
{
if (buffer != "")
{
buffer.erase(buffer.end() - 1);
}
exit_status = true;
}
}
return buffer;
}
/******************************************************************************************
*
* Function name: convert_string
*
* DESCRIPTION: converts a string to a (character *) or (character[])
*
* Parameters: string - a string object
*
* Return values: chararray - a char pointer
*
*****************************************************************************************/
char * convert_string(std::string string)
{
#ifdef DEBUG
std::cout << "\n";
std::cout << "[DEBUG] convert_string called\n";
std::cout << "string: " << string << "\n";
std::cout << "\n";
#endif
char * chararray = new char[string.size() + 1];
std::copy(string.begin(), string.end(), chararray);
chararray[string.size()] = '\0';
return chararray;
}
| true |
b42cc7e065c75c583f684eea59c57a4b7615c640 | C++ | AntonShalgachev/AmbientBacklight | /Color.cpp | UTF-8 | 902 | 3.359375 | 3 | [] | no_license | #include "Color.h"
Color::Color()
{
SetColor(0, 0, 0);
}
Color::Color(uint8_t _r, uint8_t _g, uint8_t _b) : r(_r), g(_g), b(_b)
{
SetColor(_r, _g, _b);
}
Color::Color(uint32_t color)
{
SetColor(color);
}
Color::Color(const Color& color)
{
SetColor(color);
}
void Color::SetColor(uint8_t _r, uint8_t _g, uint8_t _b)
{
r = _r;
g = _g;
b = _b;
}
void Color::SetColor(uint32_t color)
{
SetColor((color >> 16) & 0xFF, (color >> 8) & 0xFF, (color)& 0xFF);
}
void Color::SetColor(const Color& color)
{
SetColor(color.r, color.g, color.b);
}
const Color Color::Red = Color(0xFF0000);
const Color Color::Green = Color(0x00FF00);
const Color Color::Blue = Color(0x0000FF);
const Color Color::White = Color(0xFFFFFF);
const Color Color::Black = Color(0x000000);
const Color Color::Magenta = Color(0xFF00FF);
const Color Color::Cyan = Color(0x00FFFF);
const Color Color::Yellow = Color(0xFFFF00);
| true |
9c7c91c1705287d0b1067111fd43f9cc455fff88 | C++ | leandroniebles/code-compilation-component | /pseint-code/pseint/Ejecutar.cpp | ISO-8859-1 | 28,005 | 2.59375 | 3 | [
"GPL-1.0-or-later",
"GPL-2.0-only",
"MIT"
] | permissive | #include "Ejecutar.h"
#include <string>
#include "global.h"
#include "intercambio.h"
#include "utils.h"
#include <iostream>
#include "new_evaluar.h"
#include "new_memoria.h"
#include "zcurlib.h"
#include "new_programa.h"
#include "new_funciones.h"
using namespace std;
// ********************* Ejecutar un Bloque de Instrucciones **************************
// Ejecuta desde linestart+1 hasta lineend inclusive, o hasta finproceso/finsubproceso si lineend es -1.
// Las variables aux?, tmp? y tipo quedaron del cdigo viejo, se reutilizan para diferentes
// cosas, por lo que habra que analizarlas y cambiarlas por varias otras variables con scope y
// nombres mas claros... por ahora cambie las obvias y reduje el scope de las que quedaron, pero falta...
void Ejecutar(int LineStart, int LineEnd) {
// variables auxiliares
string cadena;
// Ejecutar el bloque
int line=LineStart-1;
while (true) {
line++;
if (LineEnd!=-1 && line>LineEnd) break;
cadena=programa[line].instruccion;
InstructionType instruction_type=programa[line].type;
//cout << LineStart+1 << ":"<<LineEnd+1<< " " << cadena << endl; // debug
if (instruction_type==IT_FINPROCESO || instruction_type==IT_FINSUBPROCESO) {
_pos(line);
if (instruction_type==IT_FINSUBPROCESO) {
_sub(line,string("Se sale del subproceso ")+cadena);
Inter.OnFunctionOut();
} else {
_sub(line,"Finaliza el algoritmo");
}
break;
}
if (instruction_type==IT_PROCESO || instruction_type==IT_SUBPROCESO) {
bool es_proc=instruction_type==IT_PROCESO;
size_t p=cadena.find(' '); cadena=cadena.substr(p);
p=cadena.find('<'); if (p==string::npos) p=cadena.find('='); else p++;
if (p==string::npos) p=0; else p++; cadena=cadena.substr(p);
p=cadena.find('('); if (p!=string::npos) cadena=cadena.substr(0,p);
Inter.OnFunctionIn(cadena);
_pos(line);
_sub(line,string(es_proc?"El algoritmo comienza con el proceso ":"Se ingresa en el subproceso ")+cadena);
continue;
}
if (cadena[cadena.size()-1]==';') { // Si es una accion secuencial
_pos(line);
if (instruction_type==IT_BORRARPANTALLA) {
if (for_test) cout<<"***LimpiarPantalla***"<<endl; else { clrscr(); gotoXY(1,1); }
_sub(line,"Se borra la pantalla");
} else if (instruction_type==IT_ESPERARTECLA) {
_sub_msg(line,"Se espera a que el usuario presione una tecla.");
_sub_raise();
if (for_test) cout<<"***EsperarTecla***"<<endl; else getKey();
_sub_wait();
} else if (instruction_type==IT_INVOCAR) {
string llamada=cadena.substr(8); llamada.erase(llamada.length()-1,1); // cortar el "invocar" y el ";"
tipo_var tipo=vt_desconocido; size_t p=llamada.find('(',0);
_sub(line,string("Se va a invocar al subproceso")+llamada.substr(0,p));
if (p==string::npos)
EvaluarFuncion(EsFuncion(llamada),"()",tipo,false);
else
EvaluarFuncion(EsFuncion(llamada.substr(0,p)),llamada.substr(p),tipo,false);
// ----------- ESCRIBIR ------------ //
} else if (instruction_type==IT_ESCRIBIR || instruction_type==IT_ESCRIBIRNL) {
bool saltar=instruction_type==IT_ESCRIBIR;
cadena.erase(0,9);
cadena.erase(cadena.size()-1,1);
// Separar parametros
for(size_t i=0, arg_num=1;i<cadena.size();++arg_num) {
for(int par_level = 0; i<(int)cadena.size() && !(par_level==0 && cadena[i]==',');++i) {
if (cadena[i]=='\'') while (cadena[++i]!='\'');
else if (cadena[i]=='(') par_level++;
else if (cadena[i]==')') par_level--;
}
string aux1 = cadena;
aux1.erase(i,aux1.size()-i);
i -= aux1.size();
cadena.erase(0,aux1.size()+1);
if (colored_output) setForeColor(COLOR_OUTPUT);
if (with_io_references) Inter.SendIOPositionToTerminal(arg_num);
_sub(line,string("Se evala la expresion: ")+aux1);
DataValue res = Evaluar(aux1);
if (res.IsOk()) {
string ans = res.GetForUser(); fixwincharset(ans);
cout<< ans <<flush; // Si es variable, muestra el contenido
_sub(line,string("Se muestra en pantalla el resultado: ")+res.GetForUser());
}
}
if (saltar) cout<<endl; else cout<<flush;
} else
// ------------- LEER --------------- //
if (instruction_type==IT_LEER) {
cadena.erase(0,5);
cadena.erase(cadena.size()-1,1);
for(size_t i=0, arg_num=1; i<cadena.size();++arg_num) {
for(int par_level=0;i<(int)cadena.size() && !(par_level==0 && cadena[i]==',');++i) {
if (cadena[i]=='\'') while(cadena[++i]!='\'');
else if (cadena[i]=='(') par_level++;
else if (cadena[i]==')') par_level--;
}
// Cortar el nombre de la variable a leer
string aux2=cadena;
aux2.erase(i,cadena.size()-i);
cadena.erase(0,aux2.size()+1);
i-=aux2.size();
if (lang[LS_FORCE_DEFINE_VARS] && !memoria->EstaDefinida(aux2)) {
ExeError(208,"Variable no definida ("+aux2+").");
}
tipo_var tipo=memoria->LeerTipo(aux2);
const int *dims=memoria->LeerDims(aux2);
size_t pp=aux2.find("(");
if (dims && pp==string::npos)
ExeError(200,"Faltan subindices para el arreglo ("+aux2+").");
else if (!dims && pp!=string::npos)
ExeError(201,"La variable ("+aux2.substr(0,pp)+") no es un arreglo.");
if (dims) {
_sub(line,string("Se analizan las dimensiones de ")+aux2);
CheckDims(aux2);
_sub(line,string("El resultado es ")+aux2);
}
if (with_io_references) Inter.SendIOPositionToTerminal(arg_num);
if (colored_output) setForeColor(COLOR_INFO);
cout<<flush;
if (colored_output) setForeColor(COLOR_INPUT);
// Leer dato
_sub_msg(line,"Se espera a que el usuario ingrese un valor y presiones enter."); // tipo?
_sub_raise();
string aux1;
if (!predef_input.empty() || noinput) {
if (predef_input.empty()) ExeError(214,"Sin entradas disponibles.");
aux1=predef_input.front(); predef_input.pop(); cout<<aux1<<endl;
_sub_wait();
} else {
aux1=getLine();
if (for_eval) cout<<aux1<<endl; // la entrada en psEval es un stream separado de la salida, entonces la reproducimos alli para que la salida contenga todo el "dialogo"
}
fixwincharset(aux1,true); // "descorrige" para que al corregir no traiga problemas
string auxup=ToUpper(aux1);
if (auxup=="VERDADERO" || auxup=="FALSO") aux1=auxup;
if (tipo==vt_logica && aux1.size()==1 && (toupper(aux1[0])=='F'||aux1[0]=='0')) aux1=FALSO;
if (tipo==vt_logica && aux1.size()==1 && (toupper(aux1[0])=='V'||aux1[0]=='1')) aux1=VERDADERO;
tipo_var tipo2 = GuestTipo(aux1);
if (!tipo.set(tipo2))
ExeError(120,string("No coinciden los tipos (")+aux2+").");
else if (tipo==vt_numerica_entera && tipo.rounded && aux1.find(".",0)!=string::npos)
ExeError(313,string("No coinciden los tipos (")+aux2+"), el valor ingresado debe ser un entero.");
_sub(line,string("El valor ingresado se almacena en ")+aux2); // tipo?
memoria->DefinirTipo(aux2,tipo);
memoria->EscribirValor(aux2,DataValue(tipo,aux1));
}
} else
// ------------- DIMENSION --------------- //
if (instruction_type==IT_DIMENSION) {
do {
string otro=""; // por si hay mas de un arreglo
cadena.erase(0,10);
int pos_par = cadena.find("(",0); // Cortar nombre del arreglo
string name=cadena; name.erase(pos_par,name.size()-pos_par);
string aux2=cadena; // cortar indices
aux2.erase(0,name.size()+1); aux2.erase(aux2.size()-2,2);
// Separar indices
int anid_parent=0, cant_dims=0;
for(size_t i=0;i<aux2.size();i++) {
while (i<aux2.size() && !(anid_parent==0 && (aux2[i]==','||aux2[i]==')'))) {
if (aux2[i]=='(') anid_parent++;
else if (aux2[i]==')') anid_parent--;
i++;
}
if (aux2[i]==')') {
otro=aux2;
otro.erase(0,i+2);
otro="DIMENSION "+otro+");";
aux2.erase(i,aux2.size()-i);
aux2=aux2+",";
cant_dims++;
break;
}
cant_dims++;
}
int *dim = new int[cant_dims+1]; dim[0]=cant_dims; // arreglo para las dimensiones
int last=0, num_idx=0; anid_parent = 0;
if (lang[LS_ALLOW_DINAMYC_DIMENSIONS]) { _sub(line,string("Se evalan las expresiones para cada dimensin del arreglo ")+name); }
for(size_t i=0;i<aux2.size();i++) {
while (i<aux2.size() && !(anid_parent==0 && aux2[i]==',')) {
if (aux2[i]=='(') anid_parent++;
else if (aux2[i]==')') anid_parent--;
i++;
}
cadena=aux2; // Cortar la expresion indice
cadena.erase(i,cadena.size()-i); cadena.erase(0,last);
DataValue index = Evaluar(cadena);
if (!index.CanBeReal()) ExeError(122,"No coinciden los tipos.");
dim[++num_idx] = index.GetAsInt();
if (dim[num_idx]<=0) {
ExeError(274,"Las dimensiones deben ser mayores a 0.");
}
last=i+1;
}
if (Inter.subtitles_on) {
string tamanio;
for(int i=1;i<=dim[0];i++) tamanio+="x"+IntToStr(dim[i]);
tamanio[0]=' ';
_sub(line,string("Se crea el arreglo ")+name+" de"+tamanio+" elementos");
}
if (memoria->HaSidoUsada(name)||memoria->LeerDims(name))
ExeError(123,"Identificador en uso.");
if (dim!=0) memoria->AgregarArreglo(name, dim);
if (otro!="") cadena=otro; else cadena="";
} while (cadena.size());
} else
// ------------- DEFINICION --------------- //
if (instruction_type==IT_DEFINIR) {
string aux1, aux2; tipo_var tipo;
int tmp1=0, tmp2=0; cadena.erase(0,8); bool rounded=false;
if (RightCompare(cadena," COMO LOGICO;")) { tipo=vt_logica; aux1="FALSO"; cadena.erase(cadena.size()-13,13); }
else if (RightCompare(cadena," COMO REAL;")) { tipo=vt_numerica; aux1="0"; cadena.erase(cadena.size()-11,11); }
else if (RightCompare(cadena," COMO ENTERO;")) { tipo=vt_numerica; aux1="0"; cadena.erase(cadena.size()-13,13); rounded=true; }
else if (RightCompare(cadena," COMO CARACTER;")) { tipo=vt_caracter; aux1=""; cadena.erase(cadena.size()-15,15); }
while (tmp2<(int)cadena.size()) {
while (tmp2<(int)cadena.size() && !(tmp1==0 && cadena[tmp2]==',')) {
tmp2++;
if (cadena[tmp2]=='(') tmp1++;
if (cadena[tmp2]==')') tmp1--;
}
// Cortar el nombre de la variable a leer
aux2=cadena;
aux2.erase(tmp2,cadena.size()-tmp2);
cadena.erase(0,aux2.size()+1);
tmp2-=aux2.size();
if (memoria->EstaDefinida(aux2) || memoria->EstaInicializada(aux2))
ExeError(124,string("La variable (")+aux2+") ya estaba definida.");
memoria->DefinirTipo(aux2,tipo,rounded);
if (tipo==vt_numerica) {
if (rounded) {
_sub(line,string("Se define el tipo de la variable \"")+aux2+"\" como Numrico(Entero).");
} else {
_sub(line,string("Se define el tipo de la variable \"")+aux2+"\" como Numrico(Real).");
}
} else if (tipo==vt_caracter) {
_sub(line,string("Se define el tipo de la variable \"")+aux2+"\" como Caracter/Cadena de Caracteres.");
} else if (tipo==vt_logica) {
_sub(line,string("Se define el tipo de la variable \"")+aux2+"\" como Lgico.");
}
}
} else
// ------------- ESPERAR un tiempo --------------- //
if (instruction_type==IT_ESPERAR) {
string aux2=cadena.substr(8);
int factor=1;
if (RightCompare(aux2," SEGUNDO;")) { factor=1000; aux2.erase(aux2.size()-9); }
else if (RightCompare(aux2," SEGUNDOS;")) { factor=1000; aux2.erase(aux2.size()-10); }
if (RightCompare(aux2," MILISEGUNDO;")) { factor=1; aux2.erase(aux2.size()-13); }
else if (RightCompare(aux2," MILISEGUNDOS;")) { factor=1; aux2.erase(aux2.size()-14); }
_sub(line,string("Se evala la cantidad de tiempo: ")+aux2);
DataValue time = Evaluar(aux2);
if (!time.CanBeReal()) ExeError(219,string("La longitud del intervalo debe ser numrica."));
else {
_sub(line,string("Se esperan ")+time.GetForUser()+(factor==1?" milisengudos":" segundos"));
if (for_test) cout<<"***Esperar"<<time.GetAsInt()*factor<<"***"<<endl;
else if (!Inter.subtitles_on) Sleep(time.GetAsInt()*factor);
}
} else
// ------------- ASIGNACION --------------- //
if (instruction_type==IT_ASIGNAR) {
// separar variable y expresion en aux1 y aux2
int tmp1=cadena.find("<-",0);
string aux1=cadena.substr(0,tmp1);
string aux2=cadena.substr(tmp1+3,cadena.size()-tmp1-5); // ignorar flecha, punto y como y parentesis extras
if (lang[LS_FORCE_DEFINE_VARS] && !memoria->EstaDefinida(aux1)) {
ExeError(211,string("La variable (")+aux1+") no esta definida.");
}
// verificar indices si es arreglo
if (memoria->LeerDims(aux1)) {
if (aux1.find("(",0)==string::npos)
ExeError(200,"Faltan subindices para el arreglo ("+aux1+").");
else
CheckDims(aux1);
} else if (aux1.find("(",0)!=string::npos) {
ExeError(201,"La variable ("+aux1.substr(0,aux1.find("(",0))+") no es un arreglo.");
}
// evaluar expresion
_sub(line,string("Se evala la expresion a asignar: ")+aux2);
DataValue result = Evaluar(aux2);
// comprobar tipos
tipo_var tipo_aux1 = memoria->LeerTipo(aux1);
if (!tipo_aux1.can_be(result.type))
ExeError(125,"No coinciden los tipos.");
else if (tipo_aux1==vt_numerica_entera && tipo_aux1.rounded && result.GetAsInt()!=result.GetAsReal())
ExeError(314,"No coinciden los tipos, el valor a asignar debe ser un entero.");
_sub(line,string("El resultado es: ")+result.GetForUser());
// escribir en memoria
_sub(line,string("El resultado se guarda en ")+aux1);
result.type.rounded=false; // no forzar a entera la variable en la que se asigna
memoria->DefinirTipo(aux1,result.type);
memoria->EscribirValor(aux1,result);
} // ya deberamos haber cubierto todas las opciones
else {
ExeError(0,"Ha ocurrido un error interno en PSeInt.");
}
} else { // Si no es secuencial
// ---------------- SI ------------------ //
if (instruction_type==IT_SI) {
cadena.erase(0,3);
_pos(line);
_sub(line,string("Se evala la condicin para Si-Entonces: ")+cadena);
tipo_var tipo;
bool condition_is_true = Evaluar(cadena,vt_logica).GetAsBool();
if (tipo!=vt_error) {
// Buscar hasta donde llega el bucle
int anidamiento=0, line_sino=-1,line_finsi=line+1;
while (!(anidamiento==0 && programa[line_finsi]==IT_FINSI)) {
// Saltear bucles anidados
if (anidamiento==0 && programa[line_finsi]==IT_SINO) line_sino=line_finsi;
else if (programa[line_finsi]==IT_SI) anidamiento++;
else if (programa[line_finsi]==IT_FINSI) anidamiento--;
line_finsi++;
}
// ejecutar lo que corresponda
if (condition_is_true) {
_sub(line+1,"El resultado es Verdadero, se sigue por la rama del Entonces");
if (line_sino==-1) line_sino=line_finsi;
Ejecutar(line+2,line_sino-1); // ejecutar salida por verdadero
} else {
if (line_sino!=-1) {
line = line_sino;
_pos(line);
_sub(line,"El resultado es Falso, se sigue por la rama del SiNo");
Ejecutar(line+1,line_finsi-1); // ejecutar salida por falso
} else {
_sub(line,"El resultado es Falso, no se hace nada");
}
}
// marcar la salida
line=line_finsi;
_pos(line);
_sub(line,"Se sale de la estructura Si-Entonces");
} else {
ExeError(275,"No coinciden los tipos.");
}
} else
// ---------------- MIENTRAS ------------------ //
if (instruction_type==IT_MIENTRAS) {
cadena.erase(0,9);
cadena.erase(cadena.size()-6,6);
_pos(line);
_sub(line,string("Se evala la condicin para Mientras: ")+cadena);
tipo_var tipo;
bool condition_is_true = Evaluar(cadena,vt_logica).GetAsBool();
if (tipo!=vt_error) {
int line_finmientras = line+1, anidamiento=0; // Buscar hasta donde llega el bucle
while (!(anidamiento==0 && programa[line_finmientras]==IT_FINMIENTRAS)) {
// Saltear bucles anidados
if (programa[line_finmientras]==IT_MIENTRAS) anidamiento++;
else if (programa[line_finmientras]==IT_FINMIENTRAS) anidamiento--;
line_finmientras++;
}
while (condition_is_true) {
_sub(line,"La condicin es Verdadera, se iniciar una iteracin.");
Ejecutar(line+1,line_finmientras-1);
_pos(line);
_sub(line,string("Se evala nuevamente la condicin: ")+cadena);
condition_is_true = Evaluar(cadena,vt_logica).GetAsBool();
}
line=line_finmientras;
_pos(line);
_sub(line,"La condicin es Falsa, se sale de la estructura Mientras.");
}
} else
// ---------------- REPETIR HASTA QUE ------------------ //
if (instruction_type==IT_REPETIR) {
_pos(line);
int line_hastaque=line+1, anidamiento=0; // Buscar hasta donde llega el bucle
while (!(anidamiento==0 && (programa[line_hastaque]==IT_HASTAQUE||programa[line_hastaque]==IT_MIENTRASQUE))) {
// Saltear bucles anidados
if (programa[line_hastaque]==IT_REPETIR) anidamiento++;
else if (programa[line_hastaque]==IT_HASTAQUE || programa[line_hastaque]==IT_MIENTRASQUE) anidamiento--;
line_hastaque++;
}
// cortar condicion de cierre
cadena=programa[line_hastaque];
instruction_type=programa[line_hastaque].type;
bool valor_verdad;
if (instruction_type==IT_HASTAQUE){
cadena.erase(0,10);
valor_verdad=false;
} else {
cadena.erase(0,13);
valor_verdad=true;
}
_sub(line,"Se ejecutarn las acciones contenidas en la estructura Repetir");
tipo_var tipo;
bool should_continue_iterating=true;
while (should_continue_iterating) {
Ejecutar(line+1,line_hastaque-1);
// evaluar condicion y seguir
_pos(line_hastaque);
_sub(line_hastaque,string("Se evala la condicin: ")+cadena);
should_continue_iterating = Evaluar(cadena,vt_logica).GetAsBool()==valor_verdad;
if (should_continue_iterating)
_sub(line_hastaque,string("La condicin es ")+(valor_verdad?VERDADERO:FALSO)+", se contia iterando.");
} while (should_continue_iterating);
line=line_hastaque;
_sub(line_hastaque,string("La condicin es ")+(valor_verdad?FALSO:VERDADERO)+", se sale de la estructura Repetir.");
} else
// ------------------- PARA --------------------- //
if (instruction_type==IT_PARA) {
_pos(line);
bool positivo; // para saber si es positivo o negativo
cadena.erase(0,5); // saca "PARA "
cadena.erase(cadena.size()-6,6); // saca " HACER"
// corta condicion
int tmp1=cadena.find(" HASTA ");
string aux1=cadena.substr(0,tmp1);
cadena.erase(0,tmp1+7); // saca la asignacion inicial
tmp1=aux1.find("<-",0);
string contador = aux1.substr(0,tmp1); // variable del para
memoria->DefinirTipo(aux1,vt_numerica);
string expr_ini = aux1.substr(tmp1+2); // valor inicial
_sub(line,string("Se evala la expresion para el valor inicial: ")+expr_ini);
DataValue res_ini = Evaluar(expr_ini,vt_numerica), res_paso(vt_numerica,"1"), res_fin;
if (!res_ini.CanBeReal()) ExeError(126,"No coinciden los tipos."); /// @todo: parece que esto no es posible, salta antes adentro del evaluar
size_t pos_paso=cadena.find(" CON PASO ",0); // busca el paso
if (pos_paso!=string::npos) { // si hay paso tomar ese
string expr_fin = cadena.substr(0,pos_paso);
if (RightCompare(expr_fin," HACER")) // por si ponen "...HASTA 5 HACER CON PASO 3 HACER" (2 HACER)
expr_fin = expr_fin.substr(0,expr_fin.size()-6);
res_fin = Evaluar(expr_fin,vt_numerica);
string expr_paso = cadena.substr(pos_paso+10);
_sub(line,string("Se evala la expresion para el paso: ")+expr_paso);
res_paso = Evaluar(expr_paso,vt_numerica);
positivo = res_paso.GetAsReal()>=0;
} else { // si no hay paso adivinar
res_fin = Evaluar(cadena,vt_numerica);
if (lang[LS_DEDUCE_NEGATIVE_FOR_STEP] && res_ini.GetAsReal()>res_fin.GetAsReal()) {
_sub(line,"Se determina que el paso ser -1.");
positivo=false; res_paso.SetFromInt(-1);
} else {
_sub(line,"Se determina que el paso ser +1.");
positivo=true; res_paso.SetFromInt(1);
}
}
// Buscar hasta donde llega el bucle
int line_finpara=line+1, anidamiento=0;
while (!(anidamiento==0 && programa[line_finpara]==IT_FINPARA)) {
// Saltear bucles anidados
if (programa[line_finpara]==IT_PARA||programa[line_finpara]==IT_PARACADA) anidamiento++;
else if (programa[line_finpara]==IT_FINPARA) anidamiento--;
line_finpara++;
}
_sub(line,string("Se inicializar el contador ")+contador+" en "+res_ini.GetForUser());
memoria->EscribirValor(contador,res_ini); // inicializa el contador
string comp=positivo?"<=":">=";
do {
/// @todo: cuando memoria maneje DataValues usar el valor del contador directamente desde ahi en lugar de evaluar
_sub(line,string("Se compara el contador con el valor final: ")+contador+"<="+res_fin.GetForUser());
DataValue res_cont = Evaluar(contador,vt_numerica);
if ( positivo ? (res_cont.GetAsReal()>res_fin.GetAsReal()) : (res_cont.GetAsReal()<res_fin.GetAsReal()) ) break;
_sub(line,"La expresin fue Verdadera, se iniciar una iteracin.");
Ejecutar(line+1,line_finpara-1);
_pos(line);
res_cont = Evaluar(contador,vt_numerica); // pueden haber cambiado a para el contador!!!
memoria->EscribirValor(contador,DataValue::MakeReal(res_cont.GetAsReal()+res_paso.GetAsReal()));
_sub(line,string("Se actualiza el contador, ahora ")+contador+" vale "+aux1+".");
} while(true);
memoria->Desinicializar(contador);
line=line_finpara;
_pos(line);
_sub(line,"Se sale de la estructura repetitiva Para.");
} else
// ------------------- PARA CADA --------------------- //
if (instruction_type==IT_PARACADA) {
bool primer_iteracion=true; _pos(line);
cadena.erase(0,9); // borrar "PARACADA "
cadena.erase(cadena.size()-6,6); // borrar " HACER"
int tmp1=cadena.find(" ");
int tmp2=cadena.find(" ",tmp1+4);
string aux1=cadena.substr(0,tmp1); // indetificador para el elemento
string aux2=cadena.substr(tmp1+4,tmp2-tmp1-3); // identificador del arreglo
int line_finpara=line+1, anidamiento=0; // Buscar hasta donde llega el bucle
while (!(anidamiento==0 && programa[line_finpara]==IT_FINPARA)) {
// Saltear bucles anidados
if (programa[line_finpara]==IT_PARA||programa[line_finpara]==IT_PARACADA) anidamiento++;
else if (programa[line_finpara]==IT_FINPARA) anidamiento--;
line_finpara++;
}
const int *dims=memoria->LeerDims(aux2);
if (!dims) ExeError(276,"La variable ("+aux2+") no es un arreglo.");
int nelems=1; // cantidad total de iteraciones
for (int i=1;i<=dims[0];i++) nelems*=dims[i];
// bucle posta
_sub(line,string("El arreglo \"")+aux2+"\" contiene "+IntToStr(nelems)+" elementos. Se comienza a iterar por ellos.");
for (int i=0;i<nelems;i++) {
// armar expresion del elemento (ej: A[1])
string elemento=")";
int naux=1;
for (int j=dims[0];j>0;j--) {
elemento=string(",")+IntToStr((lang[LS_BASE_ZERO_ARRAYS]?0:1)+((i/naux)%dims[j]))+elemento;
naux*=dims[j];
}
elemento=aux2+"("+elemento.substr(1);
// asignar el elemento en la variable del bucle
if (primer_iteracion) primer_iteracion=false; else { _pos(line); }
_sub(line,aux1+" ser equivalente a "+elemento+" en esta iteracin.");
if (!memoria->DefinirTipo(aux1,memoria->LeerTipo(elemento)))
ExeError(277,"No coinciden los tipos.");
memoria->EscribirValor(aux1,memoria->LeerValor(elemento));
// ejecutar la iteracion
Ejecutar(line+1,line_finpara-1);
// asignar la variable del bucle en el elemento
memoria->DefinirTipo(elemento,memoria->LeerTipo(aux1));
memoria->EscribirValor(elemento,memoria->LeerValor(aux1));
}
memoria->Desinicializar(aux1);
line=line_finpara; // linea del finpara
_pos(line);
_sub(line,"Se sale de la estructura repetitiva Para Cada.");
} else
// ------------------- SEGUN --------------------- //
if (instruction_type==IT_SEGUN) {
string expr_control = cadena.substr(6,cadena.size()-12); // Cortar la variable (sacar SEGUN y HACER)
tipo_var tipo_master=vt_caracter_o_numerica;
_pos(line);
_sub(line,string("Se evala la expresion: ")+expr_control);
DataValue val_control = Evaluar(expr_control,tipo_master); // evaluar para verificar el tipo
if (!val_control.CanBeReal()&&(lang[LS_INTEGER_ONLY_SWITCH]||!val_control.CanBeString())) {
if (!lang[LS_INTEGER_ONLY_SWITCH])
ExeError(205,"La expresin del SEGUN debe ser de tipo numerica o caracter.");
else
ExeError(206,"La expresin del SEGUN debe ser numerica.");
}
_sub(line,string("El resultado es: ")+val_control.GetForUser());
int line_finsegun=line+1, anidamiento=0; // Buscar hasta donde llega el bucle
while (!(anidamiento==0 && LeftCompare(programa[line_finsegun],"FINSEGUN"))) {
// Saltear bucles anidados
if (programa[line_finsegun]==IT_SEGUN) anidamiento++;
else if (programa[line_finsegun]==IT_FINSEGUN) anidamiento--;
line_finsegun++;
}
int line_opcion=line; bool encontrado=false; anidamiento=0;
while (!encontrado && ++line_opcion<line_finsegun) {
instruction_type=programa[line_opcion].type;
if (instruction_type==IT_SEGUN) anidamiento++;
else if (instruction_type==IT_FINSEGUN) anidamiento--;
else if ((instruction_type==IT_OPCION||instruction_type==IT_DEOTROMODO) && anidamiento==0) {
if (instruction_type==IT_DEOTROMODO) {
_pos(line_opcion);
_sub(line_opcion,"Se ingresar en la opcin De Otro Modo");
encontrado=true; break;
}
else {
string posibles_valores = programa[line_opcion];
posibles_valores[posibles_valores.size()-1]=',';
size_t pos_fin_valor = posibles_valores.find(",",0);
while (pos_fin_valor!=string::npos) {
// evaluar el parametro para verificar el tipo
string expr_opcion=posibles_valores.substr(0,pos_fin_valor);
posibles_valores.erase(0,expr_opcion.size()+1);
_pos(line_opcion);
_sub(line_opcion,string("Se evala la opcion: ")+expr_opcion);
DataValue val_opcion = Evaluar(expr_opcion,tipo_master);
if (!val_opcion.CanBeReal()&&(lang[LS_INTEGER_ONLY_SWITCH]||!val_opcion.CanBeString())) ExeError(127,"No coinciden los tipos.");
// evaluar la condicion (se pone como estaban y no los resultados de la evaluaciones de antes porque sino las variables indefinida pueden no tomar el valor que corresponde
if (Evaluar(string("(")+expr_control+")=("+expr_opcion+")").GetAsBool()) {
_sub(line_opcion,"El resultado coincide, se ingresar en esta opcin.");
encontrado=true; break;
} else {
_sub(line_opcion,string("El resultado no coincide: ")+val_opcion.GetForUser());
}
// if (tipo==vt_error) ExeError(127,"No coinciden los tipos."); // no parece hacer falta
pos_fin_valor=posibles_valores.find(",",0);
}
}
}
}
if (encontrado) { // si coincide, buscar el final del bucle
int line_finopcion=line_opcion+1; anidamiento=0; // Buscar hasta donde llega ese caso
while (!(anidamiento==0 && ((programa[line_finopcion]==IT_FINSEGUN) || (programa[line_finopcion]==IT_OPCION||programa[line_finopcion]==IT_DEOTROMODO)) )) {
// Saltear bucles anidados
if (programa[line_finopcion]==IT_SEGUN) anidamiento++;
else if (programa[line_finopcion]==IT_FINSEGUN) anidamiento--;
line_finopcion++;
}
Ejecutar(line_opcion+1,line_finopcion-1);
}
line=line_finsegun;
_pos(line);
_sub(line,"Se sale de la estructura Segun. ");
} // ya deberamos haber cubierto todas las opciones
else {
ExeError(0,"Ha ocurrido un error interno en PSeInt.");
}
}
}
}
| true |
a55edfb02cc9d38337c58602a3d5544bf8232b7b | C++ | Frank-Skywalker/MIT_-ComputerGraphics | /Assignment9_ParticleSystems/forcefield.h | UTF-8 | 1,937 | 3.015625 | 3 | [] | no_license | #ifndef _FORCEFIELD_H_
#define _FORCEFIELD_H_
#include "vectors.h"
#define G 9.8
class ForceField
{
public:
virtual Vec3f getAcceleration(const Vec3f& position, float mass, float t) const = 0;
};
class GravityForceField : public ForceField
{
public:
GravityForceField(Vec3f gravity):gravity(gravity)
{
}
virtual Vec3f getAcceleration(const Vec3f& position, float mass, float t) const
{
return gravity;
}
private:
Vec3f gravity;
};
class ConstantForceField : public ForceField
{
public:
ConstantForceField(Vec3f force):force(force)
{
}
virtual Vec3f getAcceleration(const Vec3f& position, float mass, float t) const
{
return (1.0f / mass)* force;
}
private:
Vec3f force;
};
class RadialForceField : public ForceField
{
public:
RadialForceField(float magnitude):magnitude(magnitude)
{
}
virtual Vec3f getAcceleration(const Vec3f& position, float mass, float t) const
{
Vec3f direction = -1*position;
direction.Normalize();
float distance = position.Length();
return magnitude * distance * (1.0f / mass)*direction;
}
private:
float magnitude;
};
class VerticalForceField : public ForceField
{
public:
VerticalForceField(float magnitude) :magnitude(magnitude)
{
}
virtual Vec3f getAcceleration(const Vec3f& position, float mass, float t) const
{
Vec3f direction(0, -position.y(), 0);
direction.Normalize();
float distance = fabs(position.y());
return magnitude * distance * (1.0f / mass) * direction;
}
private:
float magnitude;
};
//not implemented
class WindForceField :public ForceField
{
public:
WindForceField(float magnitude) : magnitude(magnitude)
{
}
virtual Vec3f getAcceleration(const Vec3f& position, float mass, float t) const
{
Vec3f direction(0, -position.y(), 0);
direction.Normalize();
float distance = fabs(position.y());
return magnitude * distance * (1.0f / mass) * direction;
}
private:
float magnitude;
};
#endif | true |
f260706f04454bb4761d77765cd1c67794222878 | C++ | orlinhristov/cportlib | /cport/util/thread_group.hpp | UTF-8 | 2,805 | 3.453125 | 3 | [] | no_license | #ifndef __THREAD_GROUP_HPP__
#define __THREAD_GROUP_HPP__
//
// thread_group.hpp
//
// Copyright (c) 2014-2016 Orlin Hristov (orlin dot hristov at gmail dot com)
//
// Distributed under the Apache License, Version 2.0
// visit http://www.apache.org/licenses/ for more information.
//
#include <algorithm>
#include <thread>
#include <vector>
#include <utility>
namespace cport {
namespace util {
/// Provides a mechanism to manage the lifecycle of a group of threads.
/**
* Defines an interface similar to the one, that the standart library defines,
* for a singe thread of execution.
*/
class thread_group {
public:
/// Construct an empty group.
thread_group()
{
}
/// Construct a group of threads.
/**
* @param f A callable object to be run in all threads created by the constructor.
*
* @param count The number of threads to be created. If this parameter is not specified,
* the object will starta a number of threads, equal to concurrent threads,
* supported by the system.
*/
template <typename Fn>
explicit thread_group(Fn f, std::size_t count = std::thread::hardware_concurrency())
{
threads_.reserve(count);
for (std::size_t i = 0; i < count; ++i)
{
add(f);
}
}
/// Delete copy constructor.
thread_group(const thread_group& tg) = delete;
/// Construct an object acquiring the threads running in tg.
thread_group(thread_group&& tg)
: threads_(std::move(tg.threads_))
{
}
/// Delete assigment operator.
thread_group& operator=(const thread_group& tg) = delete;
/// Acquire the threads running in tg.
thread_group& operator=(thread_group&& tg)
{
if (this != &tg)
{
threads_.swap(tg.threads_);
}
return *this;
}
/// Destruct the group.
/**
* Will wait for all threads in the group to finish.
*/
~thread_group()
{
join();
}
/// Add new thread to the group.
/**
* @param f A callable object to be run in the newly created thread.
*/
template <typename Fn>
void add(Fn&& f)
{
add(std::thread(std::forward<Fn>(f)));
}
/// Add an existing thread to the group.
/**
* @param t The thread to be added.
*/
void add(std::thread&& t)
{
threads_.push_back(std::move(t));
}
/// Wait for all running threads in this group to finish.
void join()
{
for (std::thread &t : threads_)
{
if (t.joinable())
{
t.join();
}
}
threads_.clear();
}
private:
std::vector<std::thread> threads_;
};
} // namespace util
} // namespace cport
#endif //__THREAD_GROUP_HPP__
| true |
00e126475fa3a990f7dd9f807f7869a00ddb1d56 | C++ | mikekutzma/compPhys | /Oscillations/shm.cpp | UTF-8 | 1,401 | 2.890625 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <cmath>
using namespace std;
#define NPOINTSMAX 100000
#define PI 3.141592653
double step(double, double, double);
double wstep(double, double, double, double,double, double, double, double);
int main(int argc, char* argv[]){
double w0,theta0,l,dt,q,fd,wd;
int N;
string filename;
w0 = atof(argv[1]);
theta0 = atof(argv[2]);
l = 9.81;
dt = atof(argv[3]);
N = atoi(argv[4]);
filename = argv[5];
q = 0.5;
fd = atof(argv[6]);
wd = 2.0/3.0;
double thetat,wt,theta[NPOINTSMAX],w[NPOINTSMAX],t;
theta[0] = theta0;
w[0] = w0;
for(int i=1;i<N;i++){
w[i] = wstep(w[i-1],theta[i-1],l,dt,q,fd,wd,i*dt);
theta[i] = step(theta[i-1],w[i],dt);
}
ofstream fout(filename);
for(int i=0;i<N;i++){
fout << left << setw(12) << i*dt << "\t";
fout << left << setw(12) << theta[i] << "\t";
fout << left << setw(12) << w[i] << endl;
}
}
double step(double theta, double w,double dt){
double a = theta + (w*dt);
if(a > PI){
a = a - (2*PI);
}else if(a<-PI){
a = a + (2*PI);
}
return a;
}
double wstep(double w,double theta,double l, double dt,double q, double fd, double wd, double t){
const double g = 9.81;
return w - (g*sin(theta)*dt/l) - (q*w*dt) - (fd*sin(wd*t)*dt);
}
| true |
eccbe89940bbd59f53eac6c190edf6eb122dfea4 | C++ | bimoanggito/LatihanFinanceCplusplus | /Finance.cpp | UTF-8 | 4,230 | 2.9375 | 3 | [] | no_license | #include <iostream>
#include <iomanip>
#include <conio.h>
#include <math.h>
#include <stdio.h>
using namespace std;
extern "C"{
//Natural Log Base
#define LN_BASE 2.718281828459
}
class Finance
{
public:
double p_2_f (double i, int n);
double f_2_p (double i, int n);
double f_2_a (double i, int n);
double p_2_a (double i, int n);
double a_2_f (double i, int n);
double a_2_p (double i, int n);
double p_2_f_c (double i, int n);
double f_2_p_c (double r, int n);
double f_2_a_c (double r, int n);
double p_2_a_c (double r, int n);
double a_2_f_c (double r, int n);
double a_2_p_c (double r, int n);
};
inline double Finance::p_2_f(double i, int n){
return (pow(1+i, n) );
}
inline double Finance::f_2_p(double i, int n){
return (1.0 / p_2_f(i, n) );
}
inline double Finance::f_2_a(double i, int n){
return (1.0 / a_2_f(i, n) );
}
inline double Finance::p_2_a(double i, int n){
return ( p_2_f(i, n) / a_2_f(i, n) );
}
inline double Finance::a_2_f(double i, int n){
return ( p_2_f(i, n) - 1.0 / i );
}
inline double Finance::a_2_p(double i, int n){
return ( a_2_f(i, n) / p_2_f(i, n) );
}
inline double Finance::p_2_f_c (double r, int n){
return (pow(LN_BASE, r * n) );
}
inline double Finance::f_2_p_c(double r, int n){
return ( 1.0 / p_2_f_c(r,n) );
}
inline double Finance::f_2_a_c(double r, int n){
return ( 1.0 / a_2_f_c(r,n) );
}
inline double Finance::p_2_a_c(double r, int n){
return ( p_2_f_c(r,n) / a_2_f_c(r,n) );
}
inline double Finance::a_2_f_c(double r, int n){
return ( (p_2_f_c(r,n)- 1.0) / (pow(LN_BASE, r) - 1.0) );
}
inline double Finance::a_2_p_c(double r, int n){
return ( a_2_f_c(r,n) / p_2_f_c(r,n) );
}
int main()
{
Finance findat;
double hasil;
double pv;
double fv;
double i;
double a;
int n;
system("CLS");
cout<<endl<<"Tanpa anuity"<<endl;
pv = 10000.00; // Present Value(Nilai Sekarang)
fv = 0; // ? Future Value(Nilai Kemudian)
i = 0.08; // Tingkat Bunga 8%
n = 5; // Periode 5 Tahun
hasil = findat.p_2_f (i,n);
fv = pv * hasil;
cout<<endl<<"Future Value = Present Value * FVIF";
cout<<endl<<"Present Value : "<<pv;
cout<<endl<<"Tingkat Bunga(i) : "<<i*100<<" %";
cout<<endl<<"Periode(n) : "<<n;
cout<<endl<<"FVIF(i, n) : "<<hasil;
cout<<endl<<"Future Value : "<<fv;
cout<<endl;
pv = 0; // Present Value(Nilai Sekarang)
fv = 15000.00; // ? Future Value(Nilai Kemudian)
i = 0.08; // Tingkat Bunga 8%
n = 5; // Periode 5 Tahun
hasil = findat.f_2_p (i,n);
pv = fv * hasil;
cout<<endl<<"Present Value = Future Value * PVIF";
cout<<endl<<"Future Value : "<<fv;
cout<<endl<<"Tingkat Bunga(i) : "<<i*100<<" %";
cout<<endl<<"Periode(n) : "<<n;
cout<<endl<<"PVIF(i, n) : "<<hasil;
cout<<endl<<"Present Value : "<<pv;
cout<<endl;
getche();
cout<<endl<<"Dengan anuity"<<endl;
a = 10000; // Annuity
fv = 0; // ? Future Value(Nilai Kemudian)
i = 0.08; // Tingkat Bunga 8%
n = 3; // Periode 5 Tahun
hasil = findat.a_2_f (i,n);
fv = a * hasil;
cout<<endl<<"Future Value Annuity = Annuity * FVIFA";
cout<<endl<<"Annuity : "<<a;
cout<<endl<<"Tingkat Bunga(i) : "<<i*100<<" %";
cout<<endl<<"Periode(n) : "<<n;
cout<<endl<<"FVIFA(i, n) : "<<hasil;
cout<<endl<<"Future Value Annuity : "<<fv;
cout<<endl;
a = 10000; // Annuity
fv = 0; // ? Future Value(Nilai Kemudian)
i = 0.08; // Tingkat Bunga 8%
n = 3; // Periode 5 Tahun
hasil = findat.a_2_p (i,n);
fv = a * hasil;
cout<<endl<<"Present Value Annuity = Annuity * PVIFA";
cout<<endl<<"Annuity : "<<a;
cout<<endl<<"Tingkat Bunga(i) : "<<i*100<<" %";
cout<<endl<<"Periode(n) : "<<n;
cout<<endl<<"PVIFA(i, n) : "<<hasil;
cout<<endl<<"Present Value Annuity : "<<fv;
cout<<endl;
}
| true |
9fb1e487af261f46e38ee54eccb7eb70ac4d37c2 | C++ | xeon2007/CommonUtilities | /CharacterLookup.cpp | WINDOWS-1252 | 4,472 | 2.578125 | 3 | [] | no_license | #include "CharacterLookup.h"
namespace CommonUtilities
{
CharacterLookup::CharacterLookup()
{
myCharacterLookup[eKeyboardKeys::KEY_0] = '0';
myCharacterLookup[eKeyboardKeys::KEY_1] = '1';
myCharacterLookup[eKeyboardKeys::KEY_2] = '2';
myCharacterLookup[eKeyboardKeys::KEY_3] = '3';
myCharacterLookup[eKeyboardKeys::KEY_4] = '4';
myCharacterLookup[eKeyboardKeys::KEY_5] = '5';
myCharacterLookup[eKeyboardKeys::KEY_6] = '6';
myCharacterLookup[eKeyboardKeys::KEY_7] = '7';
myCharacterLookup[eKeyboardKeys::KEY_8] = '8';
myCharacterLookup[eKeyboardKeys::KEY_9] = '9';
myCharacterLookup[eKeyboardKeys::KEY_A] = 'a';
myCharacterLookup[eKeyboardKeys::KEY_B] = 'b';
myCharacterLookup[eKeyboardKeys::KEY_C] = 'c';
myCharacterLookup[eKeyboardKeys::KEY_D] = 'd';
myCharacterLookup[eKeyboardKeys::KEY_E] = 'e';
myCharacterLookup[eKeyboardKeys::KEY_F] = 'f';
myCharacterLookup[eKeyboardKeys::KEY_G] = 'g';
myCharacterLookup[eKeyboardKeys::KEY_H] = 'h';
myCharacterLookup[eKeyboardKeys::KEY_I] = 'i';
myCharacterLookup[eKeyboardKeys::KEY_J] = 'j';
myCharacterLookup[eKeyboardKeys::KEY_K] = 'k';
myCharacterLookup[eKeyboardKeys::KEY_L] = 'l';
myCharacterLookup[eKeyboardKeys::KEY_M] = 'm';
myCharacterLookup[eKeyboardKeys::KEY_N] = 'n';
myCharacterLookup[eKeyboardKeys::KEY_O] = 'o';
myCharacterLookup[eKeyboardKeys::KEY_P] = 'p';
myCharacterLookup[eKeyboardKeys::KEY_Q] = 'q';
myCharacterLookup[eKeyboardKeys::KEY_R] = 'r';
myCharacterLookup[eKeyboardKeys::KEY_S] = 's';
myCharacterLookup[eKeyboardKeys::KEY_T] = 't';
myCharacterLookup[eKeyboardKeys::KEY_U] = 'u';
myCharacterLookup[eKeyboardKeys::KEY_V] = 'v';
myCharacterLookup[eKeyboardKeys::KEY_X] = 'x';
myCharacterLookup[eKeyboardKeys::KEY_Y] = 'y';
myCharacterLookup[eKeyboardKeys::KEY_Z] = 'z';
myCharacterLookup[eKeyboardKeys::KEY_SPACE] = ' ';
myCharacterLookup[eKeyboardKeys::KEY_COMMA] = ',';
myCharacterLookup[eKeyboardKeys::KEY_PERIOD] = '.';
//ShiftChars
myShiftCharacterLookup[eKeyboardKeys::KEY_0] = '=';
myShiftCharacterLookup[eKeyboardKeys::KEY_1] = '!';
myShiftCharacterLookup[eKeyboardKeys::KEY_2] = '\"';
myShiftCharacterLookup[eKeyboardKeys::KEY_3] = '#';
myShiftCharacterLookup[eKeyboardKeys::KEY_4] = static_cast<unsigned char>('');
myShiftCharacterLookup[eKeyboardKeys::KEY_5] = '%';
myShiftCharacterLookup[eKeyboardKeys::KEY_6] = '&';
myShiftCharacterLookup[eKeyboardKeys::KEY_7] = '/';
myShiftCharacterLookup[eKeyboardKeys::KEY_8] = '(';
myShiftCharacterLookup[eKeyboardKeys::KEY_9] = ')';
myShiftCharacterLookup[eKeyboardKeys::KEY_A] = 'A';
myShiftCharacterLookup[eKeyboardKeys::KEY_B] = 'B';
myShiftCharacterLookup[eKeyboardKeys::KEY_C] = 'C';
myShiftCharacterLookup[eKeyboardKeys::KEY_D] = 'D';
myShiftCharacterLookup[eKeyboardKeys::KEY_E] = 'E';
myShiftCharacterLookup[eKeyboardKeys::KEY_F] = 'F';
myShiftCharacterLookup[eKeyboardKeys::KEY_G] = 'G';
myShiftCharacterLookup[eKeyboardKeys::KEY_H] = 'H';
myShiftCharacterLookup[eKeyboardKeys::KEY_I] = 'I';
myShiftCharacterLookup[eKeyboardKeys::KEY_J] = 'J';
myShiftCharacterLookup[eKeyboardKeys::KEY_K] = 'K';
myShiftCharacterLookup[eKeyboardKeys::KEY_L] = 'L';
myShiftCharacterLookup[eKeyboardKeys::KEY_M] = 'M';
myShiftCharacterLookup[eKeyboardKeys::KEY_N] = 'N';
myShiftCharacterLookup[eKeyboardKeys::KEY_O] = 'O';
myShiftCharacterLookup[eKeyboardKeys::KEY_P] = 'P';
myShiftCharacterLookup[eKeyboardKeys::KEY_Q] = 'Q';
myShiftCharacterLookup[eKeyboardKeys::KEY_R] = 'R';
myShiftCharacterLookup[eKeyboardKeys::KEY_S] = 'S';
myShiftCharacterLookup[eKeyboardKeys::KEY_T] = 'T';
myShiftCharacterLookup[eKeyboardKeys::KEY_U] = 'U';
myShiftCharacterLookup[eKeyboardKeys::KEY_V] = 'V';
myShiftCharacterLookup[eKeyboardKeys::KEY_X] = 'X';
myShiftCharacterLookup[eKeyboardKeys::KEY_Y] = 'Y';
myShiftCharacterLookup[eKeyboardKeys::KEY_Z] = 'Z';
//Alt Keys
myAltCharacterLookup[eKeyboardKeys::KEY_EQUALS] = '\\';
myAltCharacterLookup[eKeyboardKeys::KEY_2] = '@';
}
CharacterLookup::~CharacterLookup()
{
}
unsigned char CharacterLookup::GetChar(const eKeyboardKeys aKeyboardKey)
{
return myCharacterLookup[aKeyboardKey];
}
unsigned char CharacterLookup::GetShiftChar(const eKeyboardKeys aKeyboardKey)
{
return myShiftCharacterLookup[aKeyboardKey];
}
unsigned char CharacterLookup::GetAltChar(const eKeyboardKeys aKeyboardKey)
{
return myAltCharacterLookup[aKeyboardKey];
}
}
| true |
f064aa3c8d07d2cf33c08d015a62ef6fec15a900 | C++ | MeushRoman/pointers_HT | /ConsoleApplication24/ConsoleApplication24.cpp | UTF-8 | 4,279 | 3.5 | 4 | [] | no_license | // ConsoleApplication24.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <time.h>
using namespace std;
int main()
{
srand(time(NULL));
const int size = 10;
int a[size];
int *p = a;
//1. Создать массив из 10 целых чисел. Заполнить массив случайным образом в диапазоне от -45 до 45. Пользуясь указателем(и) на массив целых чисел, посчитать процент положительных и отрицательных элементов массива.
int pol = 0, otr = 0, res;
for (p = a; p < a + size; p++)
{
*p = -45 + rand() % 90;
(*p < 0) ? otr++ : pol++;
}
for (p = a; p < a + size; p++)
{
cout << *p << " ";
}
cout << endl;
cout << "1. otricatel'nyh = " << (float)otr / size * 100 << " %\tpolojitel'nyh = " << (float)pol / size * 100 << " %" << endl;
cout << endl;
//2. *Создать массив из 10 целых чисел. Заполнить массив случайным образом. Пользуясь указателем на массив целых чисел, посчитать сумму элементов массива с четными номерами
//3. *Создать массив из 10 целых чисел. Заполнить массив случайным образом. Пользуясь указателем на массив целых чисел, посчитать сумму элементов массива с нечетными номерами.
//4. *Создать массив из 10 целых чисел. Заполнить массив случайным образом. Пользуясь указателем на массив целых чисел, посчитать сумму элементов массива с номерами кратными трем
//5. *Создать массив из 10 целых чисел.Заполнить массив случайным образом.Пользуясь указателем на массив целых чисел, посчитать сумму элементов массива с номерами кратными 7.
int sum1 = 0, sum2 = 0, sum3 = 0, sum4 = 0;
for (p = a; p < a + size; p++)
{
*p = 1 + rand() % 30;
//2, 3
((p - a) % 2 == 0) ? sum1 += *p : sum2 += *p;
//4.
if ((p - a) % 3 == 0) sum3 += *p;
//5.
if ((p - a) % 7 == 0) sum4 += *p;
}
for (p = a; p < a + size; p++)
{
cout << *p << " ";
}
cout << endl << endl;
cout << "2. sum (4et) \t= " << sum1 << endl;
cout << "3. sum (ne 4et) = " << sum2 << endl;
cout << "4. sum (krat 3) = " << sum3 << endl;
cout << "5. sum (krat 7) = " << sum4 << endl;
cout << endl;
//6. Создать массив из 20 целых чисел. Заполнить массив случайным образом в диапазоне от 1 до 12. Каждое число это оценка по 12 бальной системе. Пользуясь указателем на массив целых чисел, посчитать процент двоек, троек, четверок и пятерок. Двойка от 1 до 3 включительно, тройка от 4 до 6, четверка от 7 до 9, пятерка от 10 до 12.
cout << "6. " << endl;
const int size2 = 20;
int b[size2];
int *p2 = a;
float dvoek = 0, troek = 0, chetverok = 0, pyaterok = 0;
for (p2 = b; p2 < b + size2; p2++)
{
*p2 = 1 + rand() % 12;
}
for (p2 = b; p2 < b + size2; p2++)
{
cout << *p2 << " ";
switch (*p2)
{
case 1:
case 2:
case 3: dvoek++;
break;
case 4:
case 5:
case 6: troek++;
break;
case 7:
case 8:
case 9: chetverok++;
break;
case 10:
case 11:
case 12: pyaterok++;
break;
}
}
cout << endl << endl;
cout << "dvoek = " << dvoek << " = " << (float)dvoek / size2 * 100 << " %" << endl;
cout << "troek = " << troek << " = " << (float)troek / size2 * 100 << " %" << endl;
cout << "4etverok = " << chetverok << " = " << (float) chetverok/size2 * 100 << " %" << endl;
cout << "pyaterok = " << pyaterok << " = " << (float)pyaterok/size2 * 100 << " %" << endl;
cout << endl;
return 0;
}
| true |
3f344542fb5c399ba42f12c40becfaa8af62752f | C++ | eaasna/low-memory-prefilter | /hashmap/lib/seqan3/include/seqan3/range/views/move.hpp | UTF-8 | 4,549 | 2.671875 | 3 | [
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-public-domain",
"CC0-1.0",
"CC-BY-4.0",
"MIT"
] | permissive | // -----------------------------------------------------------------------------------------------------
// Copyright (c) 2006-2020, Knut Reinert & Freie Universität Berlin
// Copyright (c) 2016-2020, Knut Reinert & MPI für molekulare Genetik
// This file may be used, modified and/or redistributed under the terms of the 3-clause BSD-License
// shipped with this file and also available at: https://github.com/seqan/seqan3/blob/master/LICENSE.md
// -----------------------------------------------------------------------------------------------------
/*!\file
* \author Hannes Hauswedell <hannes.hauswedell AT fu-berlin.de>
* \brief Provides seqan3::views::move.
*/
#pragma once
#include <seqan3/std/ranges>
#include <seqan3/std/type_traits>
#include <seqan3/utility/detail/multi_invocable.hpp>
namespace seqan3::views
{
/*!\name General purpose views
* \{
*/
/*!\brief A view that turns lvalue-references into rvalue-references.
* \tparam urng_t The type of the range being processed. See below for requirements. [template parameter is
* omitted in pipe notation]
* \param[in] urange The range being processed. [parameter is omitted in pipe notation]
* \returns A range whose elements will be moved from.
* \ingroup views
*
* \details
*
* \header_file{seqan3/range/views/move.hpp}
*
* ### View properties
*
*
* | Concepts and traits | `urng_t` (underlying range type) | `rrng_t` (returned range type) |
* |----------------------------------|:-------------------------------------:|:--------------------------------------------------:|
* | std::ranges::input_range | *required* | *preserved* |
* | std::ranges::forward_range | | *preserved* |
* | std::ranges::bidirectional_range | | *preserved* |
* | std::ranges::random_access_range | | *preserved* |
* | std::ranges::contiguous_range | | *preserved* |
* | | | |
* | std::ranges::viewable_range | *required* | *guaranteed* |
* | std::ranges::view | | *guaranteed* |
* | std::ranges::sized_range | | *preserved* |
* | std::ranges::common_range | | *preserved* |
* | std::ranges::output_range | | *lost* |
* | seqan3::const_iterable_range | | *preserved* |
* | std::semiregular | | *preserved* |
* | | | |
* | std::ranges::range_reference_t | | `t &` -> `t &&` but `t` -> `t` |
*
* See the \link views views submodule documentation \endlink for detailed descriptions of the view properties.
*
* ### Example
*
* This is a slightly more verbose version of calling `std::ranges::move` on the range.
*
* \include test/snippet/range/views/move.cpp
*
* A more useful example can be found in \link sequence_file_section_fun_with_ranges the tutorial \endlink.
* \hideinitializer
* \deprecated Use the std::ranges::move algorithm, std::[cpp20::]move_iterator or an explicit for loop where you move
* the value.
*/
#ifdef SEQAN3_DEPRECATED_310
SEQAN3_DEPRECATED_310 inline auto const move = std::views::transform(detail::multi_invocable
{
[] (auto && arg) -> std::remove_cvref_t<decltype(arg)> { return std::move(arg); },
[] (auto & arg) -> decltype(auto) { return std::move(arg); }
});
#endif // SEQAN3_DEPRECATED_310
//!\}
} // namespace seqan3::views
| true |
39d46d1c76fb7fb537ffba038753245221858734 | C++ | marcelozeballos/SPOJ---OBI | /Zig Zag/main.cpp | UTF-8 | 746 | 2.96875 | 3 | [] | no_license | #include <cstdio>
#include <iostream>
using namespace std;
int main()
{
int rows, col; fscanf(stdin, "%d %d", &rows, &col);
int grid[rows][col];
for(int i = 0; i < rows; i++)
for(int j = 0; j < col; j++)
cin >> grid[i][j];
bool zigzag = true;
bool increase = true;
int x = 0, y =0;
while(y < col)
{
if(grid[x][y] == 0){
zigzag = false;
break;
}
if(x == (rows-1))
increase = false;
else if(x == 0)
increase = true;
if(increase)
x++;
else if(!increase)
x--;
y++;
}
if(zigzag)
fprintf(stdout, "YES\n");
else
fprintf(stdout, "NO\n");
}
| true |
f7f20e749d62e58e75604b55c4da1d17ab1ab7a5 | C++ | maxytakano/RayTracer | /FINALPHOENIX/MotionObject.h | UTF-8 | 1,946 | 2.859375 | 3 | [] | no_license | ////////////////////////////////////////
// MotionObject.h
////////////////////////////////////////
#ifndef CSE168_MOTIONOBJECT_H
#define CSE168_MOTIONOBJECT_H
#include "Object.h"
#include "Matrix34.h"
////////////////////////////////////////////////////////////////////////////////
class MotionObject:public Object {
public:
MotionObject() {}
MotionObject(Object &obj) {
Child = &obj;
Mtl = NULL;
}
bool Intersect(const Ray &ray, Intersection &hit) {
Matrix34 Matrix; // Lerp over each component of matrix
Matrix.a = InitialMatrix.a + ray.time*(FinalMatrix.a - InitialMatrix.a);
Matrix.b = InitialMatrix.b + ray.time*(FinalMatrix.b - InitialMatrix.b);
Matrix.c = InitialMatrix.c + ray.time*(FinalMatrix.c - InitialMatrix.c);
Matrix.d = InitialMatrix.d + ray.time*(FinalMatrix.d - InitialMatrix.d);
Matrix34 Inverse; // Get the inverse matrix on the fly
Inverse = Matrix;
Inverse.Inverse();
Ray ray2;
Inverse.Transform(ray.Origin, ray2.Origin);
Inverse.Transform3x3(ray.Direction, ray2.Direction);
if(Child->Intersect(ray2, hit)==false) return false;
Matrix.Transform(hit.Position, hit.Position);
Matrix.Transform3x3(hit.Normal, hit.Normal);
hit.HitDistance=ray.Origin.Distance(hit.Position); // Correct for any scaling
if (Mtl != NULL) {
hit.Mtl = Mtl;
}
return true;
}
void SetChild(Object &obj) {
Child = &obj;
}
void SetInitialMatrix(Matrix34 &mtx) {
InitialMatrix = mtx;
//InitialInverse = mtx;
//InitialInverse.Inverse();
}
void SetFinalMatrix(Matrix34 &mtx) {
FinalMatrix = mtx;
//FinalInverse = mtx;
//FinalInverse.Inverse();
}
void SetMaterial(Material *m) {
Mtl = m;
}
private:
Material *Mtl;
Matrix34 InitialMatrix, FinalMatrix;
Matrix34 InitialInverse, FinalInverse; // Pre-computed inverse of Matrix
Object *Child;
};
////////////////////////////////////////////////////////////////////////////////
#endif
| true |
b8566c29415ed8c0e84661068c0f4eeb941c5c9d | C++ | rishup132/Codeforces-Solutions | /Practice/C.cpp | UTF-8 | 1,172 | 2.890625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main()
{
double n,a,b,c,d;
cin >> n >> a >> b >> c >> d;
double dis = sqrt((a-c)*(a-c)+(b-d)*(b-d));
if(dis >= n)
{
printf("%0.9f %0.9f %0.9f\n",a,b,n);
return 0;
}
if(dis == 0)
{
printf("%0.9f %0.9f %0.9f\n",a+n/2,b,n/2);
return 0;
}
double temp1,temp2,temp3,temp4,temp5;
double m,k;
temp4 = a-c;
temp5 = b-d;
k = b-m*a;
//cout << m << " " << k << endl;
temp1 = 1+m*m;
temp2 = 2*(m*(k-b)-a);
temp3 = a*a + (k-b)*(k-b) - n*n;
//cout << temp1 << " " << temp2 << " " << temp3 << endl;
temp3 = sqrt(temp2*temp2 - 4*temp1*temp3);
temp4 = (temp2 + temp3)/(2*temp1);
temp5 = (temp2 - temp3)/(2*temp1);
//cout << temp3 << " " << temp4 << " " << temp5 << endl;
temp1 = m*temp4 + k;
temp2 = m*temp5 + k;
//cout << temp1 << " " << temp2 << endl;
double dis1,dis2;
dis1 = sqrt((temp4-c)*(temp4-c)+(temp1-d)*(temp1-d));
dis2 = sqrt((temp5-c)*(temp5-c)+(temp2-d)*(temp2-d));
//cout << dis1 << " " << dis2 << endl;
if(dis1 > dis2)
printf("%0.9f %0.9f %0.9f\n",(temp4-c)/2,(temp1-d)/2,(n+dis)/2);
else
printf("%0.9f %0.9f %0.9f\n",(c-temp5)/2,(d-temp2)/2,(n+dis)/2);
} | true |
60f30887443c76b38e66d45adab36697f38b9613 | C++ | kaushikacharya/cpp_practise | /online_judge/hackerrank/zartan_roads.cpp | UTF-8 | 3,358 | 3.03125 | 3 | [] | no_license | // https://www.hackerrank.com/contests/startatastartup/challenges/zartan-roads
#include <iostream>
#include <vector>
#include <fstream>
const bool READ_FROM_FILE = false;
template<typename T>
class Zartan
{
public:
Zartan(T nJunction, T nRoad);
~Zartan();
public:
void read_input(std::fstream& pFile);
bool process();
private:
T nJunction_;
T nRoad_;
private:
std::vector<T> vecVisited_;
std::vector<std::vector<T> > adjList_;
std::vector<T> vecVisitIteration_;
std::vector<T> vecInEdgeCount_;
};
//---
template<typename T>
Zartan<T>::Zartan(T nJunction, T nRoad)
: nJunction_(nJunction)
, nRoad_(nRoad)
{
vecVisited_.reserve(nJunction_);
adjList_.reserve(nJunction_);
vecVisitIteration_.reserve(nJunction_);
vecInEdgeCount_.reserve(nJunction_);
for (T junc_i = 0; junc_i != nJunction_; ++junc_i)
{
vecVisited_.push_back(false);
adjList_.push_back(std::vector<T>());
vecVisitIteration_.push_back(0);
vecInEdgeCount_.push_back(0);
}
}
template<typename T>
Zartan<T>::~Zartan()
{
}
template<typename T>
void Zartan<T>::read_input(std::fstream &pFile)
{
T source_junction, target_junction;
for (T road_i = 0; road_i != nRoad_; ++road_i)
{
if (READ_FROM_FILE)
{
pFile >> source_junction >> target_junction;
}
else
{
std::cin >> source_junction >> target_junction;
}
adjList_[source_junction].push_back(target_junction);
++vecInEdgeCount_[target_junction];
}
}
template<typename T>
bool Zartan<T>::process()
{
bool flag_cycle_present = false;
T iter = 0;
for (T junc_i = 0; junc_i != nJunction_; ++junc_i)
{
if (vecVisited_[junc_i])
{
continue;
}
++iter;
T curJunction = junc_i;
while (true)
{
if (vecVisited_[curJunction])
{
if (vecVisitIteration_[curJunction] == iter)
{
flag_cycle_present = true;
}
else
{
//we had visited curJunction in a previous iteration
}
break;
}
else
{
vecVisited_[curJunction] = true;
vecVisitIteration_[curJunction] = iter;
// In this problem there's atmost a single exit from a junction
if (adjList_[curJunction].empty() || (adjList_[curJunction].front() == curJunction))
{
break;
}
else
{
curJunction = adjList_[curJunction].front();
}
}
}
/*
if (vecInEdgeCount_[junc_i] > 0)
{
continue;
}
T curJunction = junc_i;
bool flag_next_present = true;
while (flag_next_present)
{
if (vecVisited_[curJunction])
{
flag_cycle_present = true;
break;
}
vecVisited_[curJunction] = true;
// In this problem there's atmost a single exit from a junction
if (adjList_[curJunction].empty() || (adjList_[curJunction].front() == curJunction))
{
flag_next_present = false;
}
else
{
curJunction = adjList_[curJunction].front();
}
}
*/
if (flag_cycle_present)
{
break;
}
}
return flag_cycle_present;
}
//---
int main(int argc, char* argv[])
{
unsigned int N,R;
std::fstream pFile;
if (READ_FROM_FILE)
{
pFile.open("D:/cpp_practise/online_judge/hackerrank/zartan_roads_input.txt",std::ios::in);
pFile >> N >> R;
}
else
{
std::cin >> N >> R;
}
Zartan<unsigned int> zartan(N,R);
zartan.read_input(pFile);
bool cycle_present = zartan.process();
if (cycle_present)
{
std::cout << "YES" << std::endl;
}
else
{
std::cout << "NO" << std::endl;
}
return 0;
} | true |
2cfc98c2b8aa321b320b81357c26c470576f90a7 | C++ | Krishanadave671/sem4-assignments | /Analysis of Algorithms (AOA)/10. KMP Algorithm.cpp | UTF-8 | 1,447 | 3.265625 | 3 | [] | no_license | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
void KMP(char *str, char *word, int *ptr)
{
int i = 0, j = 0;
while ((i + j) < strlen(str))
{
if (word[j] == str[i + j])
{
if (j == (strlen(word) - 1))
{
printf("%s located at the index %d\n", word, i);
return;
}
j = j + 1;
}
else
{
i = i + j - ptr[j];
if (ptr[j] > -1)
{
j = ptr[j];
}
else
{
j = 0;
}
}
}
}
void findOverlap(char *word, int *ptr)
{
int i = 2, j = 0, len = strlen(word);
ptr[0] = -1;
ptr[1] = 0;
while (i < len)
{
if (word[i - 1] == word[j])
{
j = j + 1;
ptr[i] = j;
i = i + 1;
}
else if (j > 0)
{
j = ptr[j];
}
else
{
ptr[i] = 0;
i = i + 1;
}
}
return;
}
int main()
{
char word[256], str[1024];
int *ptr, i;
printf("Enter Text :--> ");
fgets(str, 1024, stdin);
str[strlen(str) - 1] = '\0';
printf("Enter Pattern :--> ");
fgets(word, 256, stdin);
word[strlen(word) - 1] = '\0';
ptr = (int *)calloc(1, sizeof(int) * (strlen(word)));
findOverlap(word, ptr);
KMP(str, word, ptr);
return 0;
}
| true |
6478ff14dffb417043c303f74b0d27b6bdcd17d4 | C++ | lisher/whats_new_cpp | /variadic/va_list/positive.cpp | UTF-8 | 1,928 | 3.53125 | 4 | [] | no_license | /*
*
* What's new in C++
* Variadic functions
*
*/
/*
* Change the value of STEP identifier to enable different scenarios.
* Some include code from previous steps, other are completely separate.
*
* STEP 0 - calculating average
* STEP 1 - negative case - no type control
* STEP 2 - printf - positive
* STEP 3 - printf - incorrect types marks
* STEP 4 - no counter provided
*/
#define STEP 4
#include <stdarg.h>
#include <stdio.h>
#include <cstring>
#include <string>
#include <iostream>
double average(int count, ...)
{
va_list ap;
double sum = 0;
va_start(ap, count);
for (int i = 0 ; i < count ; ++i)
{
sum += va_arg(ap, int);
}
va_end(ap);
return sum / count;
}
#if STEP >= 4
// at least one argument must be provided
std::string combine(const char * first, ...)
{
const char * str = first;
va_list ap;
std::string result;
va_start(ap, first);
while (strcmp(str, ""))
{
result += str;
str = va_arg(ap, const char *);
}
return result;
}
#endif // STEP 4
int main()
{
printf("%f\n", average(4, 1, 2, 3, 4));
// access less parameters than provided
printf("%f\n", average(3, 1, 2, 3, 4));
// negative scenario
// access more parameters than provided
printf("%f\n", average(10, 1, 2, 3, 4));
#if STEP >= 1
// negative scenario 2
// no type control in compilation time
printf("%f\n", average(4, "alpha", 3, -1.5, 'z'));
#endif // STEP 1
#if STEP >= 2
// classic use - printf
// positive example
unsigned u = 4;
float f = 1.2;
char c = 'r';
printf(" unsigned %u, float %f, character %c\n", u, f, c);
#endif // STEP 2
#if STEP == 3
// compiler supports check of parameters in printf functions (-Wformat)
printf(" unsigned %u, float %f, character %c\n", f, c, u);
#endif // STEP 3
#if STEP >= 4
std::cout << "\"" << combine("there ", "is ", "no ", "spoon", "") << "\"" << std::endl;
#endif // STEP 4
return 0;
}
| true |
8a6556bdc5e3795e808e0505a75527e35bf570c1 | C++ | rafael-431/LAb06_1225419 | /DoubleLinkedList.h | UTF-8 | 554 | 3.546875 | 4 | [] | no_license | #pragma once
#include "Node.h";
template <typename T>
class DoubleLinkedList
{
public:
Node<T>* start;
Node<T>* end;
int count;
DoubleLinkedList() {
start = nullptr;
end = nullptr;
count = 0;
};
~DoubleLinkedList() {};
bool IsEmpty() {
return count == 0;
}
void InsertAtEnd(T new_value) {
Node<T>* new_node = new Node<T>();
new_node->value = new_value;
if (IsEmpty()) {
start = new_node;
end = new_node;
}
else {
end->next = new_node;
new_node->prev = end;
end = new_node;
}
count++;
return;
}
};
| true |
453c27676bff54f03a95a1ab615dcfe4c4f3b811 | C++ | jackyluk/novelCL | /device/core.cpp | UTF-8 | 825 | 2.75 | 3 | [] | no_license | /*!****************************************************************************
* @file core.cpp Entry file
* @author Jacky H T Luk 2013
*****************************************************************************/
#include "Device.hpp"
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
/*! Prototypes */
void usage(char *name);
int main(int argc, char *argv[])
{
if(argc < 2){
usage(argv[0]);
return -1;
}
int port = atoi(argv[1]);
Device device(port);
/* start processing thread */
try{
while(1){
device.start();
//pthread_join(proc_thread, NULL);
device.join();
}
}
catch(...){
printf("Error starting device.\n");
}
return 0;
}
void usage(char *name){
printf("%s <port>\n", name);
} | true |
53667934e8b715161bd8a4360d1cd3c26fcf58ae | C++ | andriimokii/Cpp_Ess_KI3 | /C++_Ess_KI3/Chapter_2/2.9-Labs/Project-2.cpp | UTF-8 | 759 | 3.1875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main( void ) {
unsigned short sum = 0;
unsigned short banknotes[5] = {0, 0, 0, 0, 0};
cin >> sum;
do {
if( sum >= 50 ) {
sum-=50;
banknotes[0]++;
}
else if( sum >= 20 ) {
sum-=20;
banknotes[1]++;
}
else if( sum >= 10 ) {
sum-=10;
banknotes[2]++;
}
else if( sum >= 5 ) {
sum-=5;
banknotes[3]++;
}
else if( sum >= 1 ) {
sum--;
banknotes[4]++;
}
}
while( sum );
for( int c = 0 ; c < 5 ; c++ ) {
while( banknotes[c] ) {
switch( c ) {
case 0: cout << "50 "; break;
case 1: cout << "20 "; break;
case 2: cout << "10 "; break;
case 3: cout << "5 "; break;
case 4: cout << "1 ";
}
banknotes[c]--;
}
}
cout << endl;
return 0;
}
| true |
e1d78f4edb1abcade93f6762394d3da001363c7a | C++ | caizhixiang/zikao | /C++/程序第2-5章/3.3 内联函数.cpp | GB18030 | 248 | 3.4375 | 3 | [
"MIT"
] | permissive | #include <iostream>
using namespace std;
int isnumber(char c)
{return (c>='0'&&c<='9')?1:0;}
void main( )
{
char c;
cin>>c;
if(isnumber( c ))
cout<<"һ";
else
cout<<"IJһ";
} | true |
26f0628c67c0badee8cb9e25862219a1fa99adfc | C++ | Lukas-PSS/-Programming_Logic | /Curso Logica de Programação Neri Neitzke/Algoritmos em C/avaliacao_if2.cpp | ISO-8859-1 | 1,254 | 3.1875 | 3 | [] | no_license | // Prof Neri Aldoir Neitzke
// www.INFORMATICON.com.br - videoaulasneri@gmail.com
/* Problema: O sistema de avaliao de determinada disciplina, composto
por trs provas. A primeira prova tem peso 2, a Segunda tem peso 3 e
a terceira prova tem peso 5. Faa um algoritmo para calcular a mdia
final de um aluno desta disciplina. Caso a media seja maior ou igual
a 6 mostre APROVADO, se a media for entre 4 e 6, mostre em RECUPERAO,
e se for menor do que 4 mostre REPROVADO.
*/
#include <conio.h>
#include <stdio.h>
main()
{
float prova1, prova2, prova3, media;
printf("Digite a nota da prova 1.: ");
scanf("%f",&prova1);//
printf("Digite a nota da prova 2.: ");
scanf("%f",&prova2);//
printf("Digite a nota da prova 3.: ");
scanf("%f",&prova3);//
//prova1 := 6;
//prova2 := 8;
//prova3 := 4;
prova1 = prova1 * 2 /10;
prova2 = prova2 * 3 /10;
prova3 = prova3 * 5 /10;
media = (prova1 + prova2 + prova3);
if (media >= 6)
printf("Aprovado com media %f'",media);
else if (media >= 4)
printf("Recuperacao com media %f",media);
else
printf("Reprovado com media %f",media);
printf("\n\n\\n.................FIM..................");
getch(); // esperar uma tecla
}
| true |
153c06c1cb1d7ae03ddd7bb413bc2cebada72806 | C++ | Mammux/kraftverk | /Arduino/make55Hz/make55Hz.ino | UTF-8 | 1,788 | 2.5625 | 3 | [] | no_license | #include <CmdMessenger.h> // CmdMessenger
CmdMessenger cmdMessenger = CmdMessenger(Serial);
int hz = 50;
boolean toggle1 = 0;
// Commands
enum
{
relay_on,
relay_off,
set_hz,
error,
};
void attachCommandCallbacks()
{
cmdMessenger.attach(set_hz, OnSetHz);
cmdMessenger.attach(error, OnError);
}
void OnSetHz()
{
hz = cmdMessenger.readBinArg<int>();
updateFreq(hz);
}
void OnError()
{
// nop
}
void updateFreq(int freq) {
cli();//stop interrupts
//set timer1 interrupt at 1Hz
TCCR1A = 0;// set entire TCCR1A register to 0
TCCR1B = 0;// same for TCCR1B
TCNT1 = 0;//initialize counter value to 0
// set compare match register for 1hz increments
OCR1A = int(15624 / (hz*2));// = (16*10^6) / (1*1024) - 1 (must be <65536)
// turn on CTC mode
TCCR1B |= (1 << WGM12);
// Set CS12 and CS10 bits for 1024 prescaler
TCCR1B |= (1 << CS12) | (1 << CS10);
// enable timer compare interrupt
TIMSK1 |= (1 << OCIE1A);
sei();//allow interrupts
}
void setup() {
pinMode(7, OUTPUT);
updateFreq(hz);
// Listen on serial connection for messages from the PC
// 115200 is the max speed on Arduino Uno, Mega, with AT8u2 USB
// Use 57600 for the Arduino Duemilanove and others with FTDI Serial
Serial.begin(57600);
// Attach my application's user-defined callback methods
attachCommandCallbacks();
}
ISR(TIMER1_COMPA_vect){//timer1 interrupt 1Hz toggles pin 13 (LED)
//generates pulse wave of frequency 1Hz/2 = 0.5kHz (takes two cycles for full wave- toggle high then toggle low)
if (toggle1){
digitalWrite(7,HIGH);
toggle1 = 0;
}
else{
digitalWrite(7,LOW);
toggle1 = 1;
}
}
void loop() {
// put your main code here, to run repeatedly:
cmdMessenger.feedinSerialData();
// tone(7, hz, 10);
}
| true |
47bf726404f77e6c899553924277f0df484a7ba8 | C++ | rh17983/swarmtemp | /src/core/simulator/entity/embodied_entity.cpp | UTF-8 | 17,338 | 2.609375 | 3 | [
"MIT"
] | permissive |
/**
* @file <argos3/core/simulator/entity/embodied_entity.cpp>
*
* @author Carlo Pinciroli <ilpincy@gmail.com>
*/
#include "embodied_entity.h"
#include "composable_entity.h"
#include <argos3/core/simulator/space/space.h>
#include <argos3/core/simulator/simulator.h>
#include <argos3/core/utility/string_utilities.h>
#include <argos3/core/utility/math/matrix/rotationmatrix3.h>
namespace argos {
/****************************************/
/****************************************/
CEmbodiedEntity::CEmbodiedEntity(CComposableEntity* pc_parent) :
CPositionalEntity(pc_parent),
m_bMovable(true),
m_sBoundingBox(NULL) {}
/****************************************/
/****************************************/
CEmbodiedEntity::CEmbodiedEntity(CComposableEntity* pc_parent,
const std::string& str_id,
const CVector3& c_position,
const CQuaternion& c_orientation,
bool b_movable) :
CPositionalEntity(pc_parent,
str_id,
c_position,
c_orientation),
m_bMovable(b_movable),
m_sBoundingBox(NULL) {}
/****************************************/
/****************************************/
CEmbodiedEntity::~CEmbodiedEntity() {
if(!m_bMovable && m_sBoundingBox != NULL) {
delete m_sBoundingBox;
}
}
/****************************************/
/****************************************/
void CEmbodiedEntity::Init(TConfigurationNode& t_tree) {
try {
CPositionalEntity::Init(t_tree);
m_bMovable = true;
}
catch(CARGoSException& ex) {
THROW_ARGOSEXCEPTION_NESTED("Failed to initialize embodied entity \"" << GetId() << "\".", ex);
}
}
/****************************************/
/****************************************/
const SBoundingBox& CEmbodiedEntity::GetBoundingBox() const {
if(GetPhysicsModelsNum() == 0) {
/* No engine associated to this entity */
THROW_ARGOSEXCEPTION("CEmbodiedEntity::GetBoundingBox() : entity \"" << GetId() << "\" is not associated to any engine");
}
return *m_sBoundingBox;
}
/****************************************/
/****************************************/
UInt32 CEmbodiedEntity::GetPhysicsModelsNum() const {
return m_tPhysicsModelVector.size();
}
/****************************************/
/****************************************/
void CEmbodiedEntity::AddPhysicsModel(const std::string& str_engine_id,
CPhysicsModel& c_physics_model) {
if(m_bMovable && GetPhysicsModelsNum() > 0) {
THROW_ARGOSEXCEPTION(GetId() << " is movable embodied entity and can't have more than 1 physics engine entity associated");
}
m_tPhysicsModelMap[str_engine_id] = &c_physics_model;
m_tPhysicsModelVector.push_back(&c_physics_model);
CalculateBoundingBox();
}
/****************************************/
/****************************************/
void CEmbodiedEntity::RemovePhysicsModel(const std::string& str_engine_id) {
CPhysicsModel::TMap::iterator itMap = m_tPhysicsModelMap.find(str_engine_id);
if(itMap == m_tPhysicsModelMap.end()) {
THROW_ARGOSEXCEPTION("Entity \"" << GetId() << "\" has no associated entity in physics engine " << str_engine_id);
}
CPhysicsModel::TVector::iterator itVec = std::find(m_tPhysicsModelVector.begin(),
m_tPhysicsModelVector.end(),
itMap->second);
m_tPhysicsModelMap.erase(itMap);
m_tPhysicsModelVector.erase(itVec);
CalculateBoundingBox();
}
/****************************************/
/****************************************/
const CPhysicsModel& CEmbodiedEntity::GetPhysicsModel(size_t un_idx) const {
if(un_idx > m_tPhysicsModelVector.size()) {
THROW_ARGOSEXCEPTION("CEmbodiedEntity::GetPhysicsModel: entity \"" << GetId() << "\": the passed index " << un_idx << " is out of bounds, the max allowed is " << m_tPhysicsModelVector.size());
}
return *m_tPhysicsModelVector[un_idx];
}
/****************************************/
/****************************************/
CPhysicsModel& CEmbodiedEntity::GetPhysicsModel(size_t un_idx) {
if(un_idx > m_tPhysicsModelVector.size()) {
THROW_ARGOSEXCEPTION("CEmbodiedEntity::GetPhysicsModel: entity \"" << GetId() << "\": the passed index " << un_idx << " is out of bounds, the max allowed is " << m_tPhysicsModelVector.size());
}
return *m_tPhysicsModelVector[un_idx];
}
/****************************************/
/****************************************/
const CPhysicsModel& CEmbodiedEntity::GetPhysicsModel(const std::string& str_engine_id) const {
CPhysicsModel::TMap::const_iterator it = m_tPhysicsModelMap.find(str_engine_id);
if(it == m_tPhysicsModelMap.end()) {
THROW_ARGOSEXCEPTION("Entity \"" << GetId() << "\" has no associated entity in physics engine \"" << str_engine_id << "\"");
}
return *(it->second);
}
/****************************************/
/****************************************/
CPhysicsModel& CEmbodiedEntity::GetPhysicsModel(const std::string& str_engine_id) {
CPhysicsModel::TMap::iterator it = m_tPhysicsModelMap.find(str_engine_id);
if(it == m_tPhysicsModelMap.end()) {
THROW_ARGOSEXCEPTION("Entity \"" << GetId() << "\" has no associated entity in physics engine \"" << str_engine_id << "\"");
}
return *(it->second);
}
/****************************************/
/****************************************/
bool CEmbodiedEntity::MoveTo(const CVector3& c_position,
const CQuaternion& c_orientation,
bool b_check_only) {
bool bNoCollision = true;
for(CPhysicsModel::TVector::const_iterator it = m_tPhysicsModelVector.begin();
it != m_tPhysicsModelVector.end() && bNoCollision; ++it) {
if(! (*it)->MoveTo(c_position, c_orientation, b_check_only)) {
bNoCollision = false;
}
}
if(bNoCollision && !b_check_only) {
/* Update space position */
SetPosition(c_position);
SetOrientation(c_orientation);
if( HasParent() ) {
CComposableEntity* pcEntity = dynamic_cast<CComposableEntity*>(&GetParent());
if( pcEntity != NULL ) {
pcEntity->Update();
}
}
return true;
}
else {
/* No Collision or check only, undo changes */
for(CPhysicsModel::TVector::const_iterator it = m_tPhysicsModelVector.begin();
it != m_tPhysicsModelVector.end(); ++it) {
(*it)->MoveTo(GetPosition(), GetOrientation());
}
if(!bNoCollision) {
/* Collision */
return false;
}
else {
/* No collision, it was a check-only */
return true;
}
}
}
/****************************************/
/****************************************/
#define CHECK_CORNER(MINMAX, COORD, OP) \
if(m_sBoundingBox->MINMAX ## Corner.Get ## COORD() OP sBBox.MINMAX ## Corner.Get ## COORD()) { \
m_sBoundingBox->MINMAX ## Corner.Set ## COORD(sBBox.MINMAX ## Corner.Get ## COORD()); \
}
void CEmbodiedEntity::CalculateBoundingBox() {
if(GetPhysicsModelsNum() > 0) {
/*
* There is at least one physics engine entity associated
*/
if(m_bMovable) {
/* The bounding box points directly to the associated model bounding box */
m_sBoundingBox = &m_tPhysicsModelVector[0]->GetBoundingBox();
}
else {
/* The bounding box is obtained taking the extrema of all the bboxes of all the engines */
if(m_sBoundingBox == NULL) {
m_sBoundingBox = new SBoundingBox();
}
*m_sBoundingBox = m_tPhysicsModelVector[0]->GetBoundingBox();
for(size_t i = 1; i < GetPhysicsModelsNum(); ++i) {
const SBoundingBox& sBBox = m_tPhysicsModelVector[0]->GetBoundingBox();
CHECK_CORNER(Min, X, >);
CHECK_CORNER(Min, Y, >);
CHECK_CORNER(Min, Z, >);
CHECK_CORNER(Max, X, <);
CHECK_CORNER(Max, Y, <);
CHECK_CORNER(Max, Z, <);
}
}
}
else {
/*
* No physics engine entity associated
*/
if(! m_bMovable && m_sBoundingBox != NULL) {
/* A non-movable entity has its own bounding box, delete it */
delete m_sBoundingBox;
}
m_sBoundingBox = NULL;
}
}
/****************************************/
/****************************************/
bool CEmbodiedEntity::IsCollidingWithSomething() const {
/* If no model is associated, you can't call this function */
if(m_tPhysicsModelVector.empty()) {
THROW_ARGOSEXCEPTION("CEmbodiedEntity::IsCollidingWithSomething() called on entity \"" << GetId() << "\", but this entity has not been added to any physics engine.");
}
/* Special case: if there is only one model, check that directly */
if(m_tPhysicsModelVector.size() == 1) {
return m_tPhysicsModelVector[0]->IsCollidingWithSomething();
}
/* Multiple associations, go through them */
else {
/* Return true at the first detected collision */
for(size_t i = 0; i < m_tPhysicsModelVector.size(); ++i) {
if(m_tPhysicsModelVector[i]->IsCollidingWithSomething()) {
return true;
}
}
/* If you get here it's because there are collisions */
return false;
}
}
/****************************************/
/****************************************/
void CEmbodiedEntitySpaceHashUpdater::operator()(CAbstractSpaceHash<CEmbodiedEntity>& c_space_hash,
CEmbodiedEntity& c_element) {
/* Translate the min corner of the bounding box into the map's coordinate */
c_space_hash.SpaceToHashTable(m_nMinX, m_nMinY, m_nMinZ, c_element.GetBoundingBox().MinCorner);
/* Translate the max corner of the bounding box into the map's coordinate */
c_space_hash.SpaceToHashTable(m_nMaxX, m_nMaxY, m_nMaxZ, c_element.GetBoundingBox().MaxCorner);
/* Finally, go through the affected cells and update them */
for(SInt32 nK = m_nMinZ; nK <= m_nMaxZ; ++nK) {
for(SInt32 nJ = m_nMinY; nJ <= m_nMaxY; ++nJ) {
for(SInt32 nI = m_nMinX; nI <= m_nMaxX; ++nI) {
c_space_hash.UpdateCell(nI, nJ, nK, c_element);
}
}
}
}
/****************************************/
/****************************************/
CEmbodiedEntityGridUpdater::CEmbodiedEntityGridUpdater(CGrid<CEmbodiedEntity>& c_grid) :
m_cGrid(c_grid) {}
bool CEmbodiedEntityGridUpdater::operator()(CEmbodiedEntity& c_entity) {
try {
/* Get cell of bb min corner, clamping it if is out of bounds */
m_cGrid.PositionToCell(m_nMinI, m_nMinJ, m_nMinK, c_entity.GetBoundingBox().MinCorner);
m_cGrid.ClampCoordinates(m_nMinI, m_nMinJ, m_nMinK);
/* Get cell of bb max corner, clamping it if is out of bounds */
m_cGrid.PositionToCell(m_nMaxI, m_nMaxJ, m_nMaxK, c_entity.GetBoundingBox().MaxCorner);
m_cGrid.ClampCoordinates(m_nMaxI, m_nMaxJ, m_nMaxK);
/* Go through cells */
for(SInt32 m_nK = m_nMinK; m_nK <= m_nMaxK; ++m_nK) {
for(SInt32 m_nJ = m_nMinJ; m_nJ <= m_nMaxJ; ++m_nJ) {
for(SInt32 m_nI = m_nMinI; m_nI <= m_nMaxI; ++m_nI) {
m_cGrid.UpdateCell(m_nI, m_nJ, m_nK, c_entity);
}
}
}
/* Continue with the other entities */
return true;
}
catch(CARGoSException& ex) {
THROW_ARGOSEXCEPTION_NESTED("While updating the embodied entity grid for embodied entity \"" << c_entity.GetContext() << c_entity.GetId() << "\"", ex);
}
}
/****************************************/
/****************************************/
/**
* @cond HIDDEN_SYMBOLS
*/
class CSpaceOperationAddEmbodiedEntity : public CSpaceOperationAddEntity {
public:
void ApplyTo(CSpace& c_space, CEmbodiedEntity& c_entity) {
/* Add entity to space */
c_space.AddEntity(c_entity);
/* Try to add entity to physics engine(s) */
c_space.AddEntityToPhysicsEngine(c_entity);
}
};
REGISTER_SPACE_OPERATION(CSpaceOperationAddEntity, CSpaceOperationAddEmbodiedEntity, CEmbodiedEntity);
class CSpaceOperationRemoveEmbodiedEntity : public CSpaceOperationRemoveEntity {
public:
void ApplyTo(CSpace& c_space, CEmbodiedEntity& c_entity) {
/* Get a reference to the root entity */
CEntity* pcRoot = &c_entity;
while(pcRoot->HasParent()) {
pcRoot = &pcRoot->GetParent();
}
/* Remove entity from all physics engines */
try {
while(c_entity.GetPhysicsModelsNum() > 0) {
c_entity.GetPhysicsModel(0).GetEngine().RemoveEntity(*pcRoot);
}
}
catch(CARGoSException& ex) {
/*
* It is safe to ignore errors because they happen only when an entity
* is completely removed from the space. In this case, the body is
* first removed from the composable entity, and then the embodied entity
* is asked to clear up the physics models. In turn, this last operation
* searches for the body component, which is not there anymore.
*
* It is anyway useful to search for the body component because, when robots
* are transferred from an engine to another, only the physics model is to be
* removed.
*/
}
/* Remove entity from space */
c_space.RemoveEntity(c_entity);
}
};
REGISTER_SPACE_OPERATION(CSpaceOperationRemoveEntity, CSpaceOperationRemoveEmbodiedEntity, CEmbodiedEntity);
/**
* @endcond
*/
/****************************************/
/****************************************/
bool GetClosestEmbodiedEntityIntersectedByRay(SEmbodiedEntityIntersectionItem& s_item,
const CRay3& c_ray) {
/* This variable is instantiated at the first call of this function, once and forever */
static CSimulator& cSimulator = CSimulator::GetInstance();
/* Initialize s_item */
s_item.IntersectedEntity = NULL;
s_item.TOnRay = 1.0f;
/* Create a reference to the vector of physics engines */
CPhysicsEngine::TVector& vecEngines = cSimulator.GetPhysicsEngines();
/* Ask each engine to perform the ray query, keeping the closest intersection */
Real fTOnRay;
CEmbodiedEntity* pcEntity;
for(size_t i = 0; i < vecEngines.size(); ++i) {
pcEntity = vecEngines[i]->CheckIntersectionWithRay(fTOnRay, c_ray);
if(pcEntity != NULL) {
if(s_item.TOnRay > fTOnRay) {
s_item.TOnRay = fTOnRay;
s_item.IntersectedEntity = pcEntity;
}
}
}
/* Return true if an intersection was found */
return (s_item.IntersectedEntity != NULL);
}
/****************************************/
/****************************************/
bool GetClosestEmbodiedEntityIntersectedByRay(SEmbodiedEntityIntersectionItem& s_item,
const CRay3& c_ray,
CEmbodiedEntity& c_entity) {
/* This variable is instantiated at the first call of this function, once and forever */
static CSimulator& cSimulator = CSimulator::GetInstance();
/* Initialize s_item */
s_item.IntersectedEntity = NULL;
s_item.TOnRay = 1.0f;
/* Create a reference to the vector of physics engines */
CPhysicsEngine::TVector& vecEngines = cSimulator.GetPhysicsEngines();
/* Ask each engine to perform the ray query, keeping the closest intersection
that does not involve the entity to discard */
Real fTOnRay;
CEmbodiedEntity* pcEntity;
for(size_t i = 0; i < vecEngines.size(); ++i) {
pcEntity = vecEngines[i]->CheckIntersectionWithRay(fTOnRay, c_ray);
if((pcEntity != NULL) &&
(pcEntity != &c_entity)){
if(s_item.TOnRay > fTOnRay) {
s_item.TOnRay = fTOnRay;
s_item.IntersectedEntity = pcEntity;
}
}
}
/* Return true if an intersection was found */
return (s_item.IntersectedEntity != NULL);
}
/****************************************/
/****************************************/
}
| true |
633dfc87b03e710426028c278bee0ae0b0e1e4bb | C++ | nuramkin/Portfolio | /C++ Projects/To Do List Application (Programming III Assignment)/programmingassignment3/main.cpp | UTF-8 | 1,872 | 3.484375 | 3 | [] | no_license | /* Nicholas Uramkin
Programming Assignment 3
COSC 2436
3/30/2018
4:30pm Mon/Wed
main.cpp */
#include <iostream>
#include <fstream>
#include <string>
#include "todolist.h"
using namespace std;
int main()
{
string fileName = "";//empty string tells save method to make new file
bool filter = false;//filter is basically an on/off switch for filtering out completed tasks
ToDoList tdl;//instantiating ToDoList class to access its methods
char choice;
while(true)
{
//print title and list of tasks(if any)
cout << "-------- TO DO LIST --------\n";
tdl.printTasks(filter);
//print menu
cout << "\n----- TO DO LIST MENU -----\n"
<< " 1. Add a new task\n"
<< " 2. Modify a task\n"
<< " 3. Remove a task\n"
<< " 4. Display tasks by priority\n"
<< " 5. Display tasks by due date\n"
<< " 6. Filter/Unfilter complete tasks\n"
<< " 7. Save To Do List\n"
<< " 8. Load To Do List\n"
<< " 9. Quit Program\n";
cin >> choice;
cout << endl << endl;
switch (choice)
{
case '1':
tdl.addTaskToList();
break;
case '2':
tdl.modifyTaskInList();
break;
case '3':
tdl.removeTaskFromList();
break;
case '4':
tdl.sortTasksByPriority();
break;
case '5':
tdl.sortTasksByDate();
break;
case '6':
filter = tdl.filterTasks(filter);//passes filter in to be turned on or off
break; //returns filter to be passed into printTasks
case '7':
fileName = tdl.saveList(fileName);
break;
case '8':
fileName = tdl.loadList(fileName);
break;
case '9':
return false;
break;
default :
cout << "\nERROR: Please enter a number between 1 and 9\n\n";
system("pause");
}
system("CLS");
}
return 0;
}
| true |
0e8aaf75e5d2afe1d28e7dd0a7e09d4bc8f0a49b | C++ | mathijsromans/trafel | /button.cpp | UTF-8 | 560 | 2.53125 | 3 | [] | no_license | #include "button.h"
#include <QDebug>
#include <QPushButton>
Button::Button(const std::string& text)
: QGraphicsProxyWidget(),
m_pushButton(0)
{
m_pushButton = new QPushButton(QString::fromStdString(text));
QFontMetrics metrics(m_pushButton->font());
QRect textBox = metrics.boundingRect(m_pushButton->text()+ " ");
int width = std::max<int>( 1.5 *textBox.height(), 1.5 * textBox.width() );
m_pushButton->setMaximumWidth( width );
setWidget(m_pushButton);
}
void Button::eventClick(const PointerEvent::CPoint& /*p*/)
{
emit pressed();
}
| true |
089db21dda34d3a58ec2227132212dfa7dc56ad9 | C++ | toniou/liam-esp | /src/scheduler/scheduler.h | UTF-8 | 620 | 2.5625 | 3 | [
"MIT"
] | permissive | #ifndef _scheduler_util_h
#define _scheduler_util_h
#include <functional>
#include <list>
struct scheduled_fn_t
{
bool repeat;
uint16_t id;
uint16_t delay;
uint32_t startMillis;
std::function<void(void)> func;
};
class Scheduler {
public:
Scheduler(bool inSeries = false);
uint16_t schedule(const std::function<void(void)> fn, uint32_t time, bool repeat = false);
void unschedule(uint16_t id);
bool isEmpty();
void clear();
void process();
private:
std::list<scheduled_fn_t> scheduled_fn_list;
uint16_t task_counter = 0;
bool in_series = false;
};
#endif
| true |
6e3d44c7802077caa258584773b889427c44fce3 | C++ | Kullsno2/C-Cpp-Programs | /PLANKET.cpp | UTF-8 | 456 | 2.9375 | 3 | [] | no_license | #include<iostream>
#include<math.h>
using namespace std;
int main()
{
long int b,r;
cin>>b>>r;
int val = b+r;
int sq = (int)sqrt(val);
for(long int i=1 ; i<=sq ; i++){
if(val % i == 0){
long int fac1 = i;
long int fac2 = val/i;
long int row,col;
if(fac1 > fac2){
row = fac1;
col = fac2;
}
else{
row = fac2;
col = fac1;
}
if(((2*col) + ((row-2) * 2))==b ){
cout<<row<<" "<<col;
break;
}
}
}
}
| true |
3795d77925874c26f5af08c98c7100f356d22aaa | C++ | yielding/code | /cpp.range-v3/action.join/action.join.cpp | UTF-8 | 516 | 2.703125 | 3 | [] | no_license | #include <iostream>
#include <ranges>
#include <string_view>
#include <vector>
//
// NOTICE pure c++20 (without range-v3 github)
//
using namespace std;
using namespace literals;
int main()
{
auto bits = { "https:"sv, "//"sv, "cppreference"sv, "."sv, "com"sv };
for (auto c : bits | views::join)
cout << c << " ";
cout << '\n';
vector<vector<int>> v{ {1,2}, {3,4,5}, {6}, {7,8,9} };
auto jv = ranges::join_view(v);
for (int const e : jv)
cout << e << ' ';
cout << '\n';
return 0;
}
| true |
462946aab1296618b6638ee8f5428e8ab22558ea | C++ | acyclics/ENGG1340_Group98 | /simulator.cpp | UTF-8 | 7,269 | 3.453125 | 3 | [] | no_license | /*
File: simulator.cpp
Purpose: Simulates the checkout procedure of a grocery store
*/
#include <queue>
#include <iostream>
#include "simulator.h"
#include "testcase_generator.h"
/*
Struct: Customer
Description: Stores the time a customer needs during checkout.
Also stores the time when the customer first entered queue.
*/
struct Customer {
int checkoutTimeNeeded = 0;
int timeCustomerEnteredQueue = 0;
};
/*
Class: Cashier
Description: Stores the time a customer is spending at the cashier.
For this Class, we won't divide it into header and source file
as the functions and class is only used by the simulator.
There is no reason for keeping it modular.
*/
class Cashier {
Customer checkingOut;
public:
std::queue<Customer> line;
int timeCashierIsOcuppiedUntil = 0;
/*
Function: process
Description: This simulates a cashier within the grocery store.
Return: Returns 1 if a customer has checked-out. Return 0 otherwise.
*/
int process(int current_time) {
Customer current;
if (!line.empty())
current = line.front();
if (checkingOut.checkoutTimeNeeded == 0 && !line.empty()) { // If a customer has 0 checkout time, it means the current customer checking-out is not a real customer
checkingOut = current; // Hence, we assign the customer in front of the queue for this cashier to checkout at this cashier
timeCashierIsOcuppiedUntil = current_time + checkingOut.checkoutTimeNeeded;
line.pop();
if (!line.empty())
current = line.front();
}
while (current.checkoutTimeNeeded != 0 && current_time - current.timeCustomerEnteredQueue >= 15 * 60 && !line.empty()) { // 15 minutes has passed. Customers in line has already left.
line.pop(); // So, we remove them from the queue
current = line.front();
}
if (checkingOut.checkoutTimeNeeded != 0 && current_time == timeCashierIsOcuppiedUntil) {
Customer emptyCashier; // Customer has checked-out. Cashier is now empty
checkingOut = emptyCashier;
timeCashierIsOcuppiedUntil = 0;
return 1; // Return 1 as one customer has been served
}
else {
return 0; // Return 0 as customer at cashier is still checking-out
}
}
};
/*
Function: simulate
Description: This is the core of the simulation. Each call to this simulation
simulates one day at a grocery store
Return: Total customers served during the simulation of a day at a grocery store.
*/
long long simulate(int numberOfCashiers, int numberOfCustomers, testcase::tcGenerator testcases) {
using namespace testcase;
using namespace std;
int current_time = 0; // current_time is to simulate a day. ++current_time = plus one second.
Cashier *cashiers = new Cashier[numberOfCashiers]; // dynamically allocate cashiers
matrix time_customers = testcases.returnTestcases() * testcases.returnTimeConstants();
/*
Explanation of above line:
- "testcases.returnTestcases()" and "testcases.returnTimeConstants()" each is a matrix.
- So let A = "testcases.returnTestcases()" and B = "testcases.returnTimeConstants()".
- A is a "numberOfCustomers" by 2 matrix.
- B is a 2 x 1 matrix.
- AB is a matrix multiplication (operator "*" is overloaded so that this is feasible).
- AB is a "numberOfCustomers" by 1 matrix, a.k.a vector, where entry "i" stores the
total amount of time customer "i" needs to checkout at a cashier.
*/
queue<Customer> line;
for (int cus(0); cus < numberOfCustomers; ++cus) { // we put the time each customer needs for checkout into the data structure queue
Customer tmp;
tmp.checkoutTimeNeeded = time_customers.valueAt(cus, 0);
line.push(tmp); // queue creates copies so we don't have to be afraid of tmp being out of scope after for loop ends
}
int current_cashier = 0; // variables to handle the distribution of customer to each cashier
double mean = (double)numberOfCustomers / 86400.0; // on average around one customer arrives to the checkout per second
double standard_deviation = 0.0005;
double probability = 0;
long long total_customers_served = 0;
while (current_time != 86400) { // Simulation / while loop ends when 86400 seconds past
double probabilityOfCustomer = max(0.0, numGenerator::NDG(mean, standard_deviation)); // Determine number of customers to be distributed in this time frame
probability += probabilityOfCustomer;
int new_customers = probability; // Customers are discrete, so once the probabilty of having a customer is equal to or greater than 1, new_customer will equal 1 as the double probability will truncate
if (new_customers >= 1) probability = 0; // Event (customer's arrival) occurred. So we reset the probability of a customer's arrival
for (;current_cashier < numberOfCashiers && !line.empty() && new_customers--; current_cashier = ++current_cashier % numberOfCashiers) {
Customer front_of_line = line.front(); // We evenly distribute customers to each cashier as this is the optimal strategy for all customers
front_of_line.timeCustomerEnteredQueue = current_time;
line.pop();
cashiers[current_cashier].line.push(front_of_line); // Here, customers are added to the queue for each cashier
}
for (int cshr(0); cshr < numberOfCashiers; ++cshr) {
total_customers_served += cashiers[cshr].process(current_time); // We distributed customers to cashier, now we simulate the operations at each cashier
}
++current_time; // Increase time by one second
}
delete[] cashiers;
return total_customers_served;
}
| true |
7cb8b6274a01af5f9eec01e165970eac86599bbc | C++ | pasindubawantha/sherlock-framework | /src/AnomalyDetectionModule/AnomalyDetectors/ConfidenceInterval/ConfidenceIntervalAnomalyDetector.cpp | UTF-8 | 2,432 | 3.03125 | 3 | [
"Apache-2.0"
] | permissive | #include "ConfidenceIntervalAnomalyDetector.h"
#include <iostream>
// Constructors
ConfidenceIntervalAnomalyDetector::ConfidenceIntervalAnomalyDetector(std::string identifyer)
{
this->identifyer = identifyer;
std::cout << "[ConfidenceIntervalAnomalyDetector] Constructing {" << identifyer << "}" << std::endl;
}
// Destroying
ConfidenceIntervalAnomalyDetector::~ConfidenceIntervalAnomalyDetector()
{
std::cout << "[ConfidenceIntervalAnomalyDetector] Destroying {" << identifyer << "}" << std::endl;
}
void ConfidenceIntervalAnomalyDetector::init()
{
std::cout << "[ConfidenceIntervalAnomalyDetector] Initializing {" << identifyer << "}" << std::endl;
windowSize = sharedMemory->anomalyDetector->distance->size - 1;
std::cout << "[ConfidenceIntervalAnomalyDetector] Done initializing {" << identifyer << "}" << std::endl;
}
double ConfidenceIntervalAnomalyDetector::calculateMean()
{
// calculates Mean for distance [0 n-1 , n] 1 to n, 0 is left out
double mean = 0;
for(int i=0; i < this->windowSize; i++){
mean += sharedMemory->anomalyDetector->distance->data[sharedMemory->anomalyDetector->distance->size -1 -i];
}
mean = mean/this->windowSize;
return mean;
};
double ConfidenceIntervalAnomalyDetector::calculateSD(double mean)
{
// calculates Standard deviation for distance [0 n-1 , n] 1 to n, 0 is left out
double finalSD = 0;
double SD;
for(int i=0; i < this->windowSize; i++){
SD += sharedMemory->anomalyDetector->distance->data[sharedMemory->anomalyDetector->distance->size -1 -i];
SD = mean - SD;
if(SD < 0){
SD = 0 - SD;
}
finalSD += SD;
}
finalSD = finalSD/this->windowSize;
return finalSD;
};
bool ConfidenceIntervalAnomalyDetector::detectWarnning()
{
double mean = this->calculateMean();
double SD = this->calculateSD(mean);
double metric = mean + SD;
bool result = false;
if(metric >= sharedMemory->anomalyDetector->thresholdWarning){
// Warnning
result = true;
}
return result;
}
bool ConfidenceIntervalAnomalyDetector::detectAlarm()
{
double mean = this->calculateMean();
double SD = this->calculateSD(mean);
double metric = mean + SD;
bool result = false;
if(metric >= sharedMemory->anomalyDetector->thresholdAlram){
// Alarm
result = true;
}
return result;
}
| true |
399ba4027d28812f18f6bc099b4adfeeed781ffd | C++ | sagnik2911/Data-Structure-Practices- | /FACTORIA.CPP | UTF-8 | 225 | 2.84375 | 3 | [] | no_license | #include<stdio.h>
#include<conio.h>
void main()
{
int i,j=1,n;
printf("please input the number:: ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
j=i*j;
}
printf("factorial is :%d",j);
getch();
}
| true |
24fc4fd6bd9591c172e124093fd46cb2f9b2e936 | C++ | juggernaut15/gilgil_vendingMachine | /widget.cpp | UTF-8 | 1,952 | 2.609375 | 3 | [] | no_license | #include "widget.h"
#include "ui_widget.h"
#include <QMessageBox>
#include <QString>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
checkMoney();
}
Widget::~Widget()
{
delete ui;
}
void Widget::checkMoney(){
if(money >= 200){
ui->pbCoke->setEnabled(true);
ui->pbTea->setEnabled(true);
ui->pbCoffee->setEnabled(true);
}
else if(money >= 150){
ui->pbCoke->setEnabled(false);
ui->pbTea->setEnabled(true);
ui->pbCoffee->setEnabled(true);
}
else if(money >= 100){
ui->pbCoke->setEnabled(false);
ui->pbTea->setEnabled(false);
ui->pbCoffee->setEnabled(true);
}
else {
ui->pbCoke->setEnabled(false);
ui->pbTea->setEnabled(false);
ui->pbCoffee->setEnabled(false);
}
}
void Widget::changeMoney(int n){
money += n;
ui ->lcdNumber->display(money);
checkMoney();
}
void Widget::on_pb10_clicked()
{
changeMoney(10);
}
void Widget::on_pb50_clicked()
{
changeMoney(50);
}
void Widget::on_pb100_clicked()
{
changeMoney(100);
}
void Widget::on_pb500_clicked()
{
changeMoney(500);
}
void Widget::on_pbCoffee_clicked()
{
changeMoney(-100);
}
void Widget::on_pbTea_clicked()
{
changeMoney(-150);
}
void Widget::on_pbCoke_clicked()
{
changeMoney(-200);
}
void Widget::on_pbReset_clicked()
{
QMessageBox msg;
QString reset;
int num10=0, num50=0, num100=0, num500=0;
int m = money;
money = 0;
changeMoney(0);
while(m / 500 != 0){
num500++;
m -= 500;
}
while(m / 100 != 0){
num100++;
m -= 100;
}
while(m / 50 != 0){
num50++;
m -= 50;
}
while(m / 10 != 0){
num10++;
m -= 10;
}
reset.sprintf("500 : %d\n100 : %d\n50 : %d\n10 : %d",num500, num100, num50, num10);
msg.information(nullptr, "reset", reset);
}
| true |
d3afbfe2b1bfa4848beea4e170539aaf0884d0e0 | C++ | siagung/stoneaero | /trunsmeetur/include/IdleSwitch.h | UTF-8 | 455 | 2.828125 | 3 | [] | no_license | #ifndef __IDLESWITCH_H__
#define __IDLESWITCH_H__
#include<Arduino.h>
typedef enum
{
IS_N = 0, IS_0 = 1, IS_1 = 2
} IdleSwitchState;
class IdleSwitch
{
public:
IdleSwitch(int pin1, int pinN);
IdleSwitch(int pin1, int pinN, IdleSwitchState* state);
IdleSwitchState get( void );
void registerState( IdleSwitchState* state);
void update( void );
private:
int pin1;
int pinN;
IdleSwitchState* state = NULL;
};
#endif
| true |
14a7ad2c842d4afdc5beb672a4a67aeb355dff35 | C++ | rahulkr007/sageCore | /trunk/src/c++/include/util/TypeInfo.h | UTF-8 | 2,561 | 3.453125 | 3 | [] | no_license | #ifndef UTIL_TYPEINFO_H
#define UTIL_TYPEINFO_H
#include <typeinfo>
#include <string>
namespace SAGE {
namespace UTIL {
class TypeInfo
{
public:
template<typename T>
struct TypeWrapper
{
typedef T type;
};
/// @name Constructors / destructors
//@{
///
/// Constructor.
TypeInfo() { my_info = 0; }
///
/// Constructor #2.
TypeInfo(const std::type_info & info) { my_info = &info; }
///
/// Constructor #3.
TypeInfo(const std::type_info * info) { my_info = info; }
template<typename T> static TypeInfo create() { return TypeInfo(typeid(T)); }
///
/// Copy constructor.
TypeInfo(const TypeInfo & other) { my_info = other.my_info; }
//@}
/// @name Operators
//@{
TypeInfo& operator=(const TypeInfo & other) { my_info = other.my_info; return *this; }
bool operator== (const TypeInfo & other) const { return my_info && other.my_info ? my_info->operator==(*other.my_info) : false; }
bool operator!= (const TypeInfo & other) const { return !operator==(other); }
bool operator< (const TypeInfo & other) const { return before(other); }
bool operator<= (const TypeInfo & other) const { return before(other) || operator==(other); }
bool operator> (const TypeInfo & other) const { return !before(other); }
bool operator>= (const TypeInfo & other) const { return !before(other) || operator==(other); }
//@}
/// Misc.
//@{
// Compatibility functions
bool before(const TypeInfo & other) const { return my_info && other.my_info ? my_info->before(*other.my_info) : false; }
///
/// Returns the name of the type, or an empty string
/// if no type has been given yet.
std::string getName() const { return my_info ? my_info->name() : ""; }
//@}
private:
const std::type_info * my_info;
};
// Comparison operators
inline bool operator== (const std::type_info * a1, const TypeInfo & a2) { return TypeInfo(a1) == a2; }
inline bool operator!= (const std::type_info * a1, const TypeInfo & a2) { return TypeInfo(a1) != a2; }
inline bool operator< (const std::type_info * a1, const TypeInfo & a2) { return TypeInfo(a1) < a2; }
inline bool operator<= (const std::type_info * a1, const TypeInfo & a2) { return TypeInfo(a1) <= a2; }
inline bool operator> (const std::type_info * a1, const TypeInfo & a2) { return TypeInfo(a1) > a2; }
inline bool operator>= (const std::type_info * a1, const TypeInfo & a2) { return TypeInfo(a1) >= a2; }
} // end namespace UTIL
} // end namespace SAGE
#endif
| true |
c74f0dd3fb679cbe7c85630bbe582af8a4632ed9 | C++ | sgosiaco/ecs60p5 | /braincell.cpp | UTF-8 | 704 | 2.734375 | 3 | [] | no_license | #include <iostream>
#include "braincell.h"
#include <cstring>
using namespace std;
BrainCell::BrainCell()
{
fed = 0;
outgoing = 0;
ID = 0;
inPath = outPath = NULL;
inLength = outLength = 0;
visited = 0;
source = 0;
}
void BrainCell::create(Vessel2 in[], int count, int ID)
{
fed = 0;
visited = 0;
source = 0;
inLength = outLength = 0;
inPath = outPath = NULL;
this->ID = ID;
outgoing = count;
out = new Vessel2[count];
memcpy(out, in, sizeof(Vessel2)*count);
/*
for(int i = 0; i < count; i++)
{
out[i] = in[i];
}
*/
}
void Vessel2::copy(Vessel in, int count)
{
src = in.src;
dest = in.dest;
capacity = in.capacity;
ID = count;
carrying = 0;
}
| true |
8f4d02441ef45ee62c6e052eefff4af691b09acd | C++ | Illia1F/data-structures | /ChainedHashTable with bst/main.cpp | UTF-8 | 415 | 3.640625 | 4 | [] | no_license | #include "hashTable.h"
#include <iostream>
using namespace std;
int main()
{
// create the hash table with a size of 5
HashTable t(5);
// insert to the hash table 30 elements
for(int i=0; i<30; i++)
t.Insert(i+1);
// and try to delete some elements
t.Delete(2);
t.Delete(12);
// and then find some of them
cout << t.Find(22) << endl;
return 0;
}
| true |
168c78fdf05c419ae8f17a9b92add769d24e5b6d | C++ | fidelitousone/xor-decryptor | /src/XorDecryptor.cpp | UTF-8 | 1,623 | 3.1875 | 3 | [] | no_license | // PROJECT EULER
// PROBLEM 59
// XOR Decryption
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include <vector>
using namespace std;
char * keygen() {
static char randkey[3];
char alphabet [26] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y', 'z'};
for (int i = 0; i < sizeof(randkey); i++) {
randkey[i] = alphabet[rand() % 26];
}
return randkey;
}
int main(int argc, char *argv[]) {
string line;
ifstream file (argv[1]);
vector<int> vect;
vector<int> decrypt;
char key [3] = {'a', 'b', 'c' };
string almostkey = argv[2];
cout << keygen();
if (file.is_open()) {
while (getline(file,line)) {
//TODO: Code goes for decipher goes
//here
stringstream ss(line);
int i;
while(ss >> i) {
vect.push_back(i);
if (ss.peek() == ',') {
ss.ignore();
}
}
for (i = 0; i < vect.size(); i++) {
decrypt.push_back(i ^ almostkey[0]);
for (int k = 1; k < 2; k++) {
decrypt.push_back(i ^ almostkey[k]);
i++;
}
}
}
file.close();
} else {
cout << "can't open file";
}
for (int i = 0; i < decrypt.size(); i++) {
cout << (char) decrypt.at(i) << endl;
}
return 0;
}
| true |
f434f5ad4cf0a9064f307bc1e25f9b3dcd591957 | C++ | MarcoLotto/ScaenaFramework | /Graphics/include/DepthTexture.h | UTF-8 | 794 | 2.859375 | 3 | [
"MIT"
] | permissive | /**********************************
* SCAENA FRAMEWORK
* Author: Marco Andrés Lotto
* License: MIT - 2016
**********************************/
#pragma once
#include "MemoryTexture.h"
class DepthTexture : public MemoryTexture{
protected:
void deleteTextureFromMemory();
void generate(vec2 size);
void assignTextureIdForClone(DepthTexture* originalToClone);
public:
// Dados los parametros de la textura, genera una nueva (con nuevos recursos)
DepthTexture(vec2 size);
// Dada una apiTexture, copiaremos sus carateristicas y apuntaremos a sus mismos recursos (no genero nuevos recursos)
DepthTexture(DepthTexture* textureToClone);
virtual ~DepthTexture();
// Devuelve un clon de esta textura, manteniendo los mismos recursos (es decir, sin crear recursos nuevos)
virtual Texture* clone();
}; | true |
45a3d26c2e7ef67ee3da59374873496fdce2f0cb | C++ | zhaohuanzhendl/algorithm | /leetcode/string/Lenth_of_Last_Word.cc | UTF-8 | 985 | 3.3125 | 3 | [] | no_license | /*
* Filename Lenth_of_Last_Word.cc
* CreateTime 2017-03-05 07:05:40
*
* Copyright (C) Zhao Huanzhen
* Copyright (C) zhzcsp@gmail.com
*/
#include <iostream>
#include <algorithm>
#include <functional>
#include <string>
using namespace std;
class Solution {
public:
int lengthOLW(const char *s)
{
const string str(s);
auto first = find_if(str.rbegin(), str.rend(), ::isalpha);
auto last = find_if_not(first, str.rend(), ::isalpha);
return distance(first, last);
}
};
class Solution_B {
public:
int lengthOLW(const char *s)
{
int len = 0;
while (*s) {
if (*(s++) != ' ') {
++len;
} else if (*s && *s != ' ') {
len = 0;
}
}
return len;
}
};
//unit test
int main()
{
char *s = "Hello World";
//string s = "Hello World";
//Solution S;
Solution_B S;
cout << "res: " << S.lengthOLW(s) << endl;
return 0;
}
| true |
4f43108c6b0cc643fa2d15e81ff2401b2e89da21 | C++ | dendibakh/Network-programming | /StatServer/StatServer/StatServer.cpp | UTF-8 | 4,363 | 2.734375 | 3 | [] | no_license | #include <iostream>
#include <winsock2.h>
#include <mysql.h>
#include <boost/asio.hpp>
#include <boost/array.hpp>
#include <boost/tokenizer.hpp>
#include <boost/lexical_cast.hpp>
#include "util.h"
using namespace boost::asio;
using namespace std;
namespace
{
MYSQL *connection = nullptr;
class commandParser
{
typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
void processQuit()
{
answer.assign("[S] > OK");
//mustCloseCon = true;
}
void processData(tokenizer::iterator& tok_iter, const tokenizer::iterator& end_iter)
{
++tok_iter;
if (tok_iter == end_iter)
{
answer.assign("[S] > ERR (Address is not specified)");
return;
}
boost::system::error_code error;
string IPadrr = removeEndLSymbol(*tok_iter);
ip::address_v4 addr = ip::address_v4::from_string(IPadrr, error);
if (error)
{
answer.assign("[S] > ERR (Wrong IP-address)");
return;
}
++tok_iter;
if (tok_iter == end_iter)
{
answer.assign("[S] > ERR (Amount of bytes is not specified)");
return;
}
size_t bytesAmount = 0;
try
{
bytesAmount = boost::lexical_cast<size_t>(removeEndLSymbol(*tok_iter));
}
catch(boost::bad_lexical_cast&)
{
answer.assign("[S] > ERR (Illegal amount of bytes specified)");
return;
}
string querry("insert into stat values (" + boost::lexical_cast<string>(addr.to_ulong()) + ", " + boost::lexical_cast<string>(bytesAmount) + ");");
int query_state = mysql_query(connection, querry.c_str());
if (query_state !=0)
{
answer.assign("[S] > ERR " + string(mysql_error(connection)));
return;
}
answer.assign("[S] > OK");
}
void processStat()
{
int query_state = mysql_query(connection, "select * from stat;");
if (query_state !=0)
{
answer.assign("[S] > ERR " + string(mysql_error(connection)));
return;
}
answer += "[S] > OK";
answer += '\n';
MYSQL_RES *result = mysql_store_result(connection);
MYSQL_ROW row;
while (( row = mysql_fetch_row(result)) != NULL)
{
answer += "[S] > ";
answer += string(row[0]);
answer += ' ';
answer += string(row[1]);
answer += '\n';
}
answer += "[S] > END";
answer += '\n';
mysql_free_result(result);
}
public:
commandParser(boost::asio::streambuf& command) //: mustCloseCon(false)
{
string strCommand = to_string(command);
boost::char_separator<char> sepSpace(" ");
tokenizer tokens(strCommand, sepSpace);
auto tok_iter = tokens.begin();
if (tok_iter == tokens.end())
{
answer.assign("[S] > ERR (No command)");
}
else
{
if (equalCommands(QuitCommand, *tok_iter))
processQuit();
else if (equalCommands(DataCommand, *tok_iter))
processData(tok_iter, tokens.end());
else if (equalCommands(StatCommand, *tok_iter))
processStat();
else
answer.assign("[S] > ERR (Unknown command)");
}
answer.resize(answer.size() + 1);
}
bool mustCloseConnectiont()
{
return false;//mustCloseCon;
}
string getAnswer()
{
return answer;
}
private:
//bool mustCloseCon;
string answer;
};
}
int main()
{
MYSQL mysql;
mysql_init(&mysql);
connection = mysql_real_connect(&mysql, "localhost", "root", "dendi", "StatServer", 3306, 0, 0);
if (connection == NULL)
{
std::cout << mysql_error(&mysql) << std::endl;
return 1;
}
try
{
std::cout << "Initiating server..." << std::endl;
boost::asio::io_service io;
ip::tcp::acceptor acceptor (io, ip::tcp::endpoint(ip::tcp::v4(), 9999));
ip::tcp::socket socket (io);
acceptor.accept(socket);
while (true)
{
boost::asio::streambuf buffer;
size_t len = read_until(socket, buffer, '\0');
if (len)
{
/*std::cout << " Receive message: ";
std::cout.write(buffer.data(), len) << std::endl;
std::cout << " Send message: OK" << std::endl;*/
commandParser parser(buffer);
string answer = parser.getAnswer();
socket.write_some(boost::asio::buffer(answer));
/*
if (parser.mustCloseConnectiont())
break;
*/
//write(socket, buffer);
}
}
}
catch (std::exception & e)
{
std::cerr << e.what() << std::endl;
}
mysql_close(connection);
return 0;
} | true |
fbb78ae7f1b6b0a0e993927817597cf32f03d655 | C++ | jammer312/cpp_random_code_without_context | /cmc_complex_eval.h | UTF-8 | 2,010 | 2.96875 | 3 | [] | no_license | #include <vector>
#include <string>
#include <map>
#include <functional>
namespace numbers
{
complex eval(const std::vector<std::string> &args, const complex &z) {
static std::map<std::string, std::function<void (complex_stack &)> > op_map{
{"+", [] (complex_stack &stack) {
complex tmp = +stack;
stack = ~stack;
tmp = +stack + tmp;
stack = ~stack << tmp;
}},
{"-", [] (complex_stack &stack) {
complex tmp = +stack;
stack = ~stack;
tmp = +stack - tmp;
stack = ~stack << tmp;
}},
{"*", [] (complex_stack &stack) {
complex tmp = +stack;
stack = ~stack;
tmp = +stack * tmp;
stack = ~stack << tmp;
}},
{"/", [] (complex_stack &stack) {
complex tmp = +stack;
stack = ~stack;
tmp = +stack / tmp;
stack = ~stack << tmp;
}},
{"!", [] (complex_stack &stack) {
stack = stack << +stack;
}},
{";", [] (complex_stack &stack) {
stack = ~stack;
}},
{"~", [] (complex_stack &stack) {
stack = ~stack << ~+stack;
}},
{"#", [] (complex_stack &stack) {
stack = ~stack << -+stack;
}},
};
complex_stack stack;
for (auto i : args) {
switch (i[0]) {
case 'z':
stack = stack << z;
break;
case '(':
stack = stack << complex(i);
break;
default:
if (op_map.find(i) != op_map.end()) {
op_map[i](stack);
}
break;
}
}
return +stack;
}
} | true |
08b1bcafcf9098d23bbb833e844898e88dc35828 | C++ | SureD/Practice | /negetive2nums.cpp | UTF-8 | 1,878 | 3.71875 | 4 | [] | no_license | /*
* 负二进制的转换及加法计算
* 利用了取余法求取当前位置上的数
*================================================
*
* 2---->n n+1 3
* -2|—————— -2|--------
* | -5 ====> | -5
* -------- ---------
* -1 ---->m m+2 1
*/
#include<iostream>
#include<string>
#include<cassert>
using namespace std;
string num2neg(int n){
string c;
while(n!=0){
int m;
m = n%2; //余数
n = n/(-2);//除数
if(m<0) //余数小于0
{
m+=2; //将余数+2相当于把除数加了1
n++;
}
c = char(m+'0')+c;
}
return c;
}
string negsum(string &a,string &b)
{
string c;
int la,lb,f;
la = a.length()-1;
lb = b.length()-1;
f = 0;
int ts;
while(la>=0||lb>=0||f){
int pa = la>=0?a[la]-'0':0;
int pb = lb>=0?b[lb]-'0':0;
ts = pa+pb+f;
switch(ts){
case -1:{
f = 1;
c = "1" + c;
};break;
case 0: case 1:{
f = 0;
c = char(ts+'0')+c;
};break;
case 2: case 3:{
f = -1;
c = char(ts-2+'0')+c;
};break;
default:
// error("Error");
exit(-1);
break;
}
la--;
lb--;
}
return c;
}
//进位例如若11与11相加,那么1+1=2 相当于 (-2)^i+(-2)^i=(-1)*(-2)^(i+1)相当于向高位进-1
//case为-1时如(01+01),相当于将当前位置为1并且向前进位,相当于(-2)^i*2 = (-2)^(i+1)+(-2)^(i+2);
int main()
{
string a;
a = num2neg(-2);
cout<<a<<endl;
return 0;
}
| true |
0ccfb897365e8fe67cd2f62a5ad4a69a171895b0 | C++ | pz1971/Online-Judge-Solutions | /SPOJ/PALIN.cpp | UTF-8 | 1,629 | 2.546875 | 3 | [] | no_license | #include <bits/stdc++.h>
#define vi vector<int>
typedef unsigned int ui;
typedef long int li;
typedef unsigned long lu;
typedef long long ll;
typedef unsigned long long llu;
using namespace std;
int main()
{
int t{};
cin>> t;
getchar();
while(t--)
{
vi d;
char ch{};
while(1)
{
ch = getchar();
if(isdigit(ch))
{
d.push_back(ch - '0');
}
else
break;
}
int l{d.size()};
bool done{false};
int m{l/2};
for(int i=0; i<m; i++)
{
if(d.at(i)!=d.at(l-i-1))
{
if(d.at(i)>d.at(l-i-1))
done = true;
else
done = false;
d.at(l-i-1) = d.at(i);
}
}
if(!done)
{
bool carry{false};
if(m*2==l)
m--;
while(m>=0)
{
if(d.at(m)==9)
{
d.at(m) = d.at(l-m-1) = 0;
carry = true;
}
else
{
d.at(m)++;
if(m!=l-m-1)
d.at(l-m-1)++;
carry = false;
break;
}
m--;
}
if(carry)
{
cout<< "1";
d.at(l-1) = 1;
}
}
///
for(auto i: d)
cout<< i;
cout<< endl;
}
return 0;
} | true |
8388d0f0753216e2a202fb6a8997917ce04bcab4 | C++ | asieraguado/skeletonml | /kinect_postures/src/exceptions.h | UTF-8 | 547 | 2.546875 | 3 | [
"MIT"
] | permissive | #ifndef EXCEPTIONS_H
#define EXCEPTIONS_H
class NoTrackerDataException: public std::exception
{
public:
virtual const char* what() const throw()
{
return "Insufficient data from OpenNI tracker. Sensor is not ready or user1 is not calibrated yet.";
}
};
class LoadModelFileException: public std::exception
{
public:
virtual const char* what() const throw()
{
return "Error loading classifier from file. Check if 'models' folder is in the program running directory (usually ROS home).";
}
};
#endif /* EXCEPTIONS_H */
| true |
9f3d90822626f029fce7ea4147f4d863190d49d6 | C++ | michaelrk02/interpolator | /src/NewtonPolynomial.cpp | UTF-8 | 3,511 | 2.875 | 3 | [] | no_license | #include <algorithm>
#include <cstdlib>
#include <iostream>
#include <debug.h>
#include <NewtonPolynomial.h>
NewtonPolynomial::NewtonPolynomial(void) {
this->degree = 0;
}
NewtonPolynomial::~NewtonPolynomial(void) {
}
void NewtonPolynomial::initializeData(std::istream &input, float scaleX, float scaleY) {
this->data.clear();
TRACE("data initializing");
while (true) {
std::pair<float, float> p;
input >> p.first >> p.second;
if (input.good()) {
p.first = p.first * scaleX;
p.second = p.second * scaleY;
this->data.push_back(p);
} else {
break;
}
}
std::sort(this->data.begin(), this->data.end());
TRACE("data initialized");
}
unsigned int NewtonPolynomial::getDegree(void) const {
return this->degree;
}
void NewtonPolynomial::setDegree(unsigned int degree) {
this->degree = degree;
this->samples.clear();
if (degree > 0) {
this->samples.push_back(this->data[0]);
if (degree > 1) {
int additional = (this->data.size() - 2) / (degree - 1);
int remainder = (this->data.size() - 2) % (degree - 1);
int start = 1;
for (int i = 0; i < degree - 1; i++) {
float total = 0.0f;
int count = additional + (remainder > 0 ? 1 : 0);
for (int j = start; j < start + count; j++) {
total = total + this->data[j].second;
}
float average = total / (float)count;
int select = start;
for (int j = start; j < start + count; j++) {
float d = std::abs(this->data[j].second - average);
if (d < std::abs(this->data[select].second - average)) {
select = j;
}
}
DUMP(average);
DUMP(this->data[select].first);
this->samples.push_back(this->data[select]);
start = start + count;
remainder--;
}
}
this->samples.push_back(this->data[this->data.size() - 1]);
}
this->dd.destroy();
this->dd.initialize(degree + 1, degree + 1);
for (int j = 0; j <= degree; j++) {
for (int i = 0; i <= degree - j; i++) {
if (j == 0) {
this->dd.at(i, 0) = this->samples[i].second;
DUMP(this->dd.at(i, 0));
} else {
float f1 = this->dd.at(i + 1, j - 1);
float f0 = this->dd.at(i, j - 1);
float x1 = this->samples[i + j].first;
float x0 = this->samples[i].first;
TRACE("===");
DUMP(f1);
DUMP(f0);
DUMP(x1);
DUMP(x0);
this->dd.at(i, j) = (f1 - f0) / (x1 - x0);
DUMP(this->dd.at(i, j));
}
}
}
}
float NewtonPolynomial::interpolate(float x) const {
float result = 0.0f;
float *xCalc = new float[this->degree];
for (int i = 0; i < this->degree; i++) {
xCalc[i] = (x - this->samples[i].first);
if (i > 0) {
xCalc[i] = xCalc[i] * xCalc[i - 1];
}
}
for (int i = 0; i <= this->degree; i++) {
float term = this->dd.at(0, i);
if (i > 0) {
term = term * xCalc[i - 1];
}
result = result + term;
}
delete[] xCalc;
return result;
}
| true |
3da56cade4522f93d536c0e98d41d3eb0955e741 | C++ | nagyistoce/VideoCollage | /inc/vtl/img/Img_Ip.h | UTF-8 | 21,986 | 2.703125 | 3 | [] | no_license | /*************************************************************************\
Microsoft Research Asia
Copyright (c) 2003 Microsoft Corporation
Module Name:
Vis Lib Image Processing
Abstract:
A group of image processing functions.
Notes:
TODO:
/// Apply the callback function on each pixel
/// typedef void (*Function) (T&);
template<class T, class Function>
HRESULT ForEachPixel(img::CImage<T>& imDst, Function function);
/// Apply the callback function to transform from one to the other image
/// typedef void (*Function) (T&, const S&);
template<class T, class S, class Function>
HRESULT ForEachPixel(img::CImage<T>& imDst, const img::CImage<S>& imSrc, Function function);
Usage:
History:
Created on 2003 Aug. 16 by oliver_liyin
\*************************************************************************/
#pragma once
#include "Img_Image.h"
#include "Img_ConvHV.hpp"
namespace img
{
/// blend colors as: r = alpha * s + beta * t
template<class R, class S, class T>
void BlendPixel(R& r, const S& s, const T& t, float alpha, float beta);
/// [Compute the guassian blur image].
template<class IMAGE>
HRESULT ImageBlurGaussian(IMAGE& imDst,
const IMAGE& imSrc, float sigma, xtl::IProgress* progress = NULL);
/// [Compute the guassian blur image, sigma = 0.717f].
template<class IMAGE>
HRESULT ImageBlurFixed121(IMAGE& imDst,
const IMAGE& imSrc, xtl::IProgress* progress = NULL)
{
img::FixedKernel_121<ConvolutionDefault> K;
return img::ConvolveImageHV(imDst, imSrc, K, K, progress);
}
/// [Compute the guassian blur image, sigma = 1f].
template<class IMAGE>
HRESULT ImageBlurFixed14641(IMAGE& imDst,
const IMAGE& imSrc, xtl::IProgress* progress = NULL)
{
img::FixedKernel_14641<ConvolutionDefault> K;
return img::ConvolveImageHV(imDst, imSrc, K, K, progress);
}
/// Blur and down sample image by integer facter
template<class IMAGE>
HRESULT ImageDecimate(IMAGE& imDst, const IMAGE& imSrc, INT xScale, INT yScale);
/// [To compute the gradient component on X, and Y].
template<class ImageGradientType>
HRESULT ComputeGradientXY(
ImageGradientType& imGx, ImageGradientType& imGy, const CImageArgb& imSrc);
/// [composite gradient magnitude by x, y components.
template<class G, class T>
HRESULT CompositeGradient(CImage<G>& imG, const CImage<T>& imX, const CImage<T>& imY);
/// Compute the inverse of given image
template<class IMAGE>
HRESULT InvertImageColor(IMAGE& imDst, const IMAGE& imSrc);
/// Normalize the image to given min max value range
/// If no min max is given, use default Black and White color of given pixel type
template <class T>
void NormalizeMinMax(CImage<T>& image,
T min_val = PixelTraits<T>::Black,
T max_val = PixelTraits<T>::White);
/// convert label image to Psuedo
HRESULT ImageLabelToPsuedo(
CImageArgb& imPsuedo, const CImageInt& imLabel, UINT number_of_colors = 1024);
/// Morphologic filter
template<class DilateKernel, class ErosionKernel>
class MorphologicalFilter
{
public:
MorphologicalFilter(size_t scale) : m_Dilation(scale), m_Erosion(scale)
{
}
template<class ImageType>
HRESULT Dilate(ImageType& imOut, const ImageType& imIn)
{
return ConvolveImageHV(imOut, imIn, m_Dilation, m_Dilation);
}
template<class ImageType>
HRESULT Erode(ImageType& imOut, const ImageType& imIn)
{
return ConvolveImageHV(imOut, imIn, m_Erosion, m_Erosion);
}
template<class ImageType>
HRESULT Open(ImageType& imOut, const ImageType& imIn)
{
HRESULT hr = Erode(imOut, imIn);
if (FAILED(hr)) return hr;
return Dilate(imOut, imOut);
}
template<class ImageType>
HRESULT Close(ImageType& imOut, const ImageType& imIn)
{
HRESULT hr = Dilate(imOut, imIn);
if (FAILED(hr)) return hr;
return Erode(imOut, imOut);
}
template<class ImageType>
HRESULT Smooth(ImageType& imOut, const ImageType& imIn)
{
HRESULT hr = Open(imOut, imIn);
if (FAILED(hr)) return hr;
return Close(imOut, imOut);
}
private:
DilateKernel m_Dilation;
ErosionKernel m_Erosion;
private:
MorphologicalFilter();
MorphologicalFilter(MorphologicalFilter&);
MorphologicalFilter& operator= (MorphologicalFilter&);
};
inline HRESULT BinaryImageErode(CImageByte& imSrcDst, size_t scale)
{
typedef BinaryMorphologicalKernel<Erosion, ConvolutionDefault> Kernel;
Kernel kernel(scale);
return ConvolveImageHV(imSrcDst, imSrcDst, kernel, kernel);
}
inline HRESULT BinaryImageDilate(CImageByte& imSrcDst, size_t scale)
{
typedef BinaryMorphologicalKernel<Dilation, ConvolutionDefault> Kernel;
Kernel kernel(scale);
return ConvolveImageHV(imSrcDst, imSrcDst, kernel, kernel);
}
inline HRESULT BinaryImageErode(
CImageByte& imDst, const CImageByte& imSrc, size_t scale)
{
imDst.Copy(imSrc);
return BinaryImageErode(imDst, scale);
}
inline HRESULT BinaryImageDilate(
CImageByte& imDst, const CImageByte& imSrc, size_t scale)
{
imDst.Copy(imSrc);
return BinaryImageDilate(imDst, scale);
}
#pragma region template implementations
template<class IMAGE>
HRESULT ImageBlurGaussian(
IMAGE& imDst,
const IMAGE& imSrc,
float sigma,
xtl::IProgress* progress)
{
if (imSrc.IsEmpty()) return E_INVALIDARG;
if (sigma < 0) return E_INVALIDARG;
if (sigma == 0)
{
return imDst.Copy(imSrc);
}
else
{
img::ConvolutionKernel<float, ConvolutionDefault> K;
HRESULT hr = BuildGaussianKernel(K, sigma);
if (FAILED(hr)) return hr;
return img::ConvolveImageHV(imDst, imSrc, K, K, progress);
}
}
template<class IMAGE>
HRESULT InvertImageColor(IMAGE& imDst, const IMAGE& imSrc)
{
if(imSrc.IsEmpty()) return E_INVALIDARG;
if(imDst != imSrc) imDst.Allocate(imSrc);
typedef typename IMAGE::PixelType PixelType;
const int cx = imSrc.Width();
const int cy = imSrc.Height();
for(int y = 0; y < cy; y ++)
{
PixelType* pDst = imDst.RowPtr(y);
const PixelType* pSrc = imSrc.RowPtr(y);
for(int x = 0; x < cx; x ++)
{
PixelInvert(pDst[x], pSrc[x]);
}
}
return S_OK;
}
template<class IMAGE>
HRESULT ImageDecimate(IMAGE& imDst, const IMAGE& imSrc, INT xScale, INT yScale)
{
if (imDst == imSrc) return E_INVALIDARG;
if (xScale <= 0 || yScale <= 0) return E_INVALIDARG;
/// if decimate scale is 1, copy image
if (xScale == 1 && yScale == 1)
{
imDst.Copy(imSrc);
return S_OK;
}
const int cx = imSrc.Width() / xScale;
const int cy = imSrc.Height() / yScale;
imDst.Allocate(cx, cy);
typedef typename IMAGE::PixelType PixelType;
for (int y = 0; y < cy; y ++)
{
const PixelType* pSrc = imSrc.RowPtr(y * yScale);
PixelType* pDst = imDst.RowPtr(y);
for (int xDst = 0, xSrc = 0; xDst < cx; xDst ++, xSrc += xScale)
{
pDst[xDst] = pSrc[xSrc];
}
}
return S_OK;
}
template <class T>
void NormalizeMinMax(CImage<T>& image, T min_val, T max_val)
{
if (image.IsEmpty()) return;
if (min_val > max_val) std::swap(min_val, max_val);
/// first, estimate min max value
T _maxv = image(0, 0);
T _minv = image(0, 0);
for (int y = 0; y < image.Height(); y ++)
{
T* p = image.RowPtr(y);
for (int x = 0; x < image.Width(); x ++)
{
if (_minv >(*p)) _minv =(*p);
if (_maxv <(*p)) _maxv =(*p);
++p;
}
}
const T diff = _maxv - _minv;
if (diff > xtl::Limits<T>::denorm_min())
{
const T denorminator =(max_val - min_val) / diff;
for (int y = 0; y < image.Height(); y ++)
{
T* p = image.RowPtr(y);
for (int x = 0; x < image.Width(); x ++)
{
(*p) = ((*p) - _minv) * denorminator + min_val;
++p;
}
}
}
else
{
/// uniform image
image.FillPixels(0);
}
}
/// morphological operations
namespace impl
{
template<class S> struct ColorDifference;
template<>
struct ColorDifference<BYTE>
{
BYTE operator() (const PixelArgb& p, const PixelArgb& q) const
{
const int dr = int(p.r) - int(q.r);
const int dg = int(p.g) - int(q.g);
const int db = int(p.b) - int(q.b);
//const float result = sqrtf(float(dr*dr + dg*dg + db*db) / 3.f);
const int result = (abs(dr) + abs(dg) + abs(db)) / 3;
assert(result >= 0 && result <= 255);
return static_cast<BYTE>(result);
};
BYTE operator() (const BYTE p, const BYTE q) const
{
return static_cast<BYTE>(abs(int(p) - int(q)));
};
BYTE operator() (const float p, const float q) const
{
return static_cast<BYTE>(fabs(p - q) * 255);
};
};
template<>
struct ColorDifference<float>
{
float operator()(const PixelArgb& p, const PixelArgb& q) const
{
const int dr = int(p.r) - int(q.r);
const int dg = int(p.g) - int(q.g);
const int db = int(p.b) - int(q.b);
//const float result = sqrtf(float(dr*dr + dg*dg + db*db) / 3.f);
const int result = (abs(dr) + abs(dg) + abs(db)) / 3;
assert(result >= 0 && result <= 255);
return static_cast<float>(result / 255.f);
};
float operator() (const BYTE p, const BYTE q) const
{
return static_cast<float>(abs(int(p) - int(q)) / 255.f);
};
float operator() (const float p, const float q) const
{
return fabs(p - q);
};
};
/// Compute gradient using average of foreward and backward difference
template<class T>
struct ComputeGradientXY_On_Scanline
{
ColorDifference<T> color_diff;
void operator() (
T* pDstX,
T* pDstY,
int cx,
const PixelArgb* pSrcP, /// upper scanline, y - 1
const PixelArgb* pSrc0, /// current scanline, y
const PixelArgb* pSrcQ) /// lower scanline, y + 1
{
for(int x = 1; x < cx-1; x ++)
{
pDstX[x] = color_diff(pSrc0[x+1], pSrc0[x-1]);
pDstY[x] = color_diff(pSrcP[x], pSrcQ[x]);
}
/// reflect at left and right boundary
pDstX[0] = color_diff(pSrc0[0], pSrc0[1]);
pDstY[0] = color_diff(pSrcP[0], pSrcQ[0]);
pDstX[cx-1] = color_diff(pSrc0[cx-1], pSrc0[cx-2]);
pDstY[cx-1] = color_diff(pSrcP[cx-1], pSrcQ[cx-1]);
}
};
} /// namespace impl
template<class ImageGradientType>
HRESULT ComputeGradientXY(
ImageGradientType& imGx,
ImageGradientType& imGy,
const CImageArgb& imSrc)
{
typedef ImageGradientType::PixelType T;
if (imSrc.IsEmpty()) return E_INVALIDARG;
const int cx = imSrc.Width();
const int cy = imSrc.Height();
imGx.Allocate(cx, cy);
imGy.Allocate(cx, cy);
/// If image size is too small, gradient is zero
if (cx == 1 || cy == 1)
{
imGx.ClearPixels();
imGy.ClearPixels();
return S_OK;
}
impl::ComputeGradientXY_On_Scanline<T> _InnerFunction;
/// reflect at top and bottom
_InnerFunction(imGx.RowPtr(0), imGy.RowPtr(0), cx,
imSrc.RowPtr(0), imSrc.RowPtr(0), imSrc.RowPtr(1));
for(int y = 1; y < cy-1; y ++)
{
_InnerFunction(imGx.RowPtr(y), imGy.RowPtr(y), cx,
imSrc.RowPtr(y-1), imSrc.RowPtr(y), imSrc.RowPtr(y+1));
}
_InnerFunction(imGx.RowPtr(cy-1), imGy.RowPtr(cy-1), cx,
imSrc.RowPtr(cy-2), imSrc.RowPtr(cy-1), imSrc.RowPtr(cy-1));
return S_OK;
}
template<class G, class T>
HRESULT CompositeGradient(CImage<G>& imG, const CImage<T>& imX, const CImage<T>& imY)
{
typedef CImage<G> Image_G;
typedef CImage<T> Image_XY;
assert(imX.Width() == imY.Width() && imX.Height() == imY.Height());
if (imX.IsEmpty() || imY.IsEmpty()) return E_INVALIDARG;
const int cx = imX.Width();
const int cy = imX.Height();
imG.Allocate(cx, cy);
if (imG.IsEmpty()) return E_OUTOFMEMORY;
for (int y = 0; y < cy; y ++)
{
const Image_XY::PixelType* px = imX.RowPtr(y);
const Image_XY::PixelType* py = imY.RowPtr(y);
Image_G::PixelType* pg = imG.RowPtr(y);
for (int x = 0; x < cx; x ++)
{
typedef Image_XY::PixelType T;
typedef xtl::TypeTraits<T>::AccumType AccumType;
//*/// use L2 norm
const AccumType xx = vtl::Square(px[x]);
const AccumType yy = vtl::Square(py[x]);
pg[x] = xtl::RealCast<Image_G::PixelType>(vtl::Sqrt((xx + yy) / 2.));
/*/// use L1 norm
pg[x] = xtl::RealCast<Image_G::PixelType>((abs(px[x]) + abs(py[x])) / 2);
//*/
}
}
return S_OK;
}
/// BlendPixel two pixels into one using given alpha, beta
/// r = s * alpha + t * beta
template<class R, class S, class T>
void BlendPixel(R& r, const S& s, const T& t, float alpha, float beta)
{
typedef PixelTraits<R> TraitsR;
typedef PixelTraits<S> TraitsS;
typedef PixelTraits<T> TraitsT;
COMPILE_TIME_ASSERT(TraitsR::ColorChannelNum == TraitsS::ColorChannelNum);
COMPILE_TIME_ASSERT(TraitsR::ColorChannelNum == TraitsT::ColorChannelNum);
TraitsR::ChannelType* pr = (TraitsR::ChannelType*) &r;
const TraitsS::ChannelType* ps = (const TraitsS::ChannelType*) &s;
const TraitsT::ChannelType* pt = (const TraitsT::ChannelType*) &t;
for(size_t i = 0; i < TraitsR::ColorChannelNum; i ++)
{
pr[i] = xtl::RealCast<TraitsR::ChannelType>(alpha * ps[i] + beta * pt[i]);
}
}
#pragma endregion
/// The context to fill in Byte image with given value
/// It's usually used as hint of FillImageMethod
template<class T>
struct FillImageContext
{
img::CImage<T>* pimTarget;
T value;
};
/// A general call back function to fill a Byte image with value
/// For example:
/// FillImageContext<BYTE> context = { &m_imMask, value};
/// ScanConvertPolygon(pts, count, rc, &img::FillImageMethod<BYTE>, (INT_PTR) &context);
template<class T>
bool FillImageMethod(int y, int x0, int x1, INT_PTR hint)
{
FillImageContext<T>* context = (FillImageContext<T>*) hint;
assert(y >= 0 && y < context->pimTarget->Height());
assert(x0 >=0 && x0 < context->pimTarget->Width());
assert(x1 >=0 && x1 <= context->pimTarget->Width());
assert(x0 < x1);
T* pRow = context->pimTarget->RowPtr(y);
for(int x = x0; x < x1; x ++)
{
pRow[x] = context->value;
}
return true;
}
/// Fill in the image with value inside polygon pts[0..count)
template<class T, class S>
HRESULT FillImage(CImage<T>& imTarget,
const Gdiplus::PointF* pts, size_t count, const Gdiplus::Rect& rcClip, const S& value)
{
FillImageContext<T> context = { &imTarget, (T) value};
return img::ScanConvertPolygon(
pts, count, rcClip, &FillImageMethod<T>, (INT_PTR) &context);
}
/// Fill in the given graphics path
/// the path must contains only polygons
/// Therefore, you should Flatten the path beforehand.
template<class T, class S>
HRESULT FillGraphicsPath(CImage<T>& imTarget,
Gdiplus::GraphicsPath& path, const Gdiplus::Rect& rcClip, const S& value)
{
using namespace Gdiplus;
FillImageContext<T> context = { &imTarget, (T) value};
/// read the path data
PathData data;
path.GetPathData(&data);
/// analysis path data, get each segment of polygon
INT start = 0;
for(INT k = 0; k < data.Count; k ++)
{
if(data.Types[k] == PathPointTypeStart)
{
start = k;
}
else if((data.Types[k] & PathPointTypeCloseSubpath) != 0)
{
/// If polygon is found, scan convert it
img::ScanConvertPolygon(
data.Points + start, k - start + 1, rcClip,
&FillImageMethod<T>, (INT_PTR) &context);
}
else
{
/// Assume after flatten, all data are line data
assert(data.Types[k] == PathPointTypeLine);
}
}
return S_OK;
}
/// Copy channel iSrc of imSrc, to the channel iDst to imDst
template<class T, class S>
HRESULT CopyChannel(
CImage<T>& imDst, const CImage<S>& imSrc,
ChannelIndex iDst, ChannelIndex iSrc)
{
typedef PixelTraits<T>::ChannelType DstChannelType;
typedef PixelTraits<S>::ChannelType SrcChannelType;
if (iDst < 0 || iSrc < 0) return E_INVALIDARG;
if (iDst >= PixelTraits<T>::ChannelNum) return E_INVALIDARG;
if (iSrc >= PixelTraits<S>::ChannelNum) return E_INVALIDARG;
const int cx = imSrc.Width();
const int cy = imSrc.Height();
if(imDst.Width() != cx || imDst.Height() != cy) return E_INVALIDARG;
for (int y = 0; y < cy; y ++)
{
T* pDst = imDst.RowPtr(y);
const S* pSrc = imSrc.RowPtr(y);
for (int x = 0; x < cx; x ++)
{
DstChannelType* cpDst = (DstChannelType*) &pDst[x];
const SrcChannelType* cpSrc = (const SrcChannelType*) &pSrc[x];
cpDst[iDst] = xtl::RealCast<DstChannelType>(cpSrc[iSrc]);
}
}
imDst.ResetDisplayImage();
return S_OK;
}
/// Copy image pixels, and clamp source pixel values in boundary
/// imDst and imSrc must be allocated and same size before calling
template<typename T, typename S>
HRESULT CopyPixelsWithClamp(
img::CImage<T>& imDst, const img::CImage<S>& imSrc,
typename img::PixelTraits<S>::ChannelType minValue = img::PixelTraits<typename img::PixelTraits<S>::ChannelType>::Black,
typename img::PixelTraits<S>::ChannelType maxValue = img::PixelTraits<typename img::PixelTraits<S>::ChannelType>::White)
{
if (imDst.IsEmpty() || imSrc.IsEmpty()) return E_INVALIDARG;
if (imDst.GetSize() != imSrc.GetSize()) return E_INVALIDARG;
typedef img::PixelTraits<T> DstTraits;
typedef img::PixelTraits<S> SrcTraits;
if (DstTraits::ColorChannelNum != SrcTraits::ColorChannelNum) return E_INVALIDARG;
const size_t ColorChannelNum = DstTraits::ColorChannelNum;
typedef DstTraits::PixelType DstPixelType;
typedef DstTraits::ChannelType DstChannelType;
typedef SrcTraits::PixelType SrcPixelType;
typedef SrcTraits::ChannelType SrcChannelType;
const int width = imDst.Width();
const int height = imDst.Height();
for (int y = 0; y < height; y ++)
{
DstPixelType* ptrDst = imDst.RowPtr(y);
const SrcPixelType* ptrSrc = imSrc.RowPtr(y);
for (int x = 0; x < width; x ++)
{
DstChannelType* pixDst = (DstChannelType*)(&ptrDst[x]);
const SrcChannelType* pixSrc = (const SrcChannelType*)(&ptrSrc[x]);
for (int k = 0; k < ColorChannelNum; k ++)
{
SrcChannelType src = pixSrc[k];
if (src < minValue) src = minValue;
if (src > maxValue) src = maxValue;
pixDst[k] = xtl::RealCast<DstChannelType>(src);
}
}
}
return S_OK;
}
} /// namespace img | true |
367456784296ff5313abc03ba21711e0acd49c8e | C++ | maleRjc/GPU_VIDEO | /Video_codec_demo/src/Mux_decode_thread/Demux_queue.cpp | UTF-8 | 7,110 | 2.828125 | 3 | [] | no_license | #include "Demux_queue.h"
#include <glog/logging.h>
#include <cstring>
namespace Demux
{
Demux_queue::Demux_queue():m_write_position(0), m_read_position(0), m_used_queue_size(0), m_enqueue_sta(true), m_dequeue_sta(true), m_clear_cache(false)
{
pthread_mutex_init(&m_lock, NULL);
pthread_cond_init(&m_cond_empty, NULL);
pthread_cond_init(&m_cond_full, NULL);
Demuxframes_cache.clear();
}
int Demux_queue::enqueue(const FFmpeg::Demuxframe & item)
{
pthread_mutex_lock(&m_lock);
#ifdef DISPLAY_INFO
if(m_enqueue_sta)
{
LOG(INFO) << "enqueue have the lock ";
m_enqueue_sta = false;
m_dequeue_sta = true;
}
#endif
//入队列前先判断队列是否已满(一定要先判断,否则会导致解除阻塞后丢失当前数据)(用while判断条件避免错误唤醒)
while(m_used_queue_size == QUEUE_SIZE)
{
LOG(WARNING) << "Demux_queue is full";
pthread_cond_wait(&m_cond_full, &m_lock);
}
//队列未满
m_queue[m_write_position % QUEUE_SIZE] = item;
m_write_position++;
m_used_queue_size++;
#ifdef DISPLAY_INFO
LOG(INFO) << " enqueue:" << (m_write_position - 1) % QUEUE_SIZE << " size:" << m_used_queue_size << " item.nVideoBytes: "<< item.size();
#endif
pthread_mutex_unlock(&m_lock);
if(m_used_queue_size == ACTIVE_DEQUEUE_SIZE || item.size() == -1) //解决最后写队列写的数量不够激活读队列线程的时候
pthread_cond_signal(&m_cond_empty);
return (m_write_position - 1) % QUEUE_SIZE;
}
uint64_t Demux_queue::enqueue_non_blocking(const FFmpeg::Demuxframe & item)
{
uint64_t cache_size = input_cahce(item);
cache_size = enqueue_cache();
return cache_size;
}
//返回cache中的数据大小
uint64_t Demux_queue::input_cahce(const FFmpeg::Demuxframe & item)
{
Demuxframes_cache.push_back(item);
#ifdef DISPLAY_INFO
LOG(INFO) << " input cache:" << " cahce size:" << Demuxframes_cache.size() << " item.nVideoBytes: "<< item.size();
#endif
return Demuxframes_cache.size();
}
//返回cache中还剩多少数据未写入队列
uint64_t Demux_queue::enqueue_cache()
{
int lock_sta = pthread_mutex_trylock(&m_lock);
//获得锁,将缓存数据写入队列
if(lock_sta == 0)
{
#ifdef DISPLAY_INFO
if(m_enqueue_sta)
{
LOG(INFO) << "enqueue have the lock ";
m_enqueue_sta = false;
m_dequeue_sta = true;
}
#endif
//入队列前先判断队列是否已满,满了就先写入缓存
if(m_used_queue_size < QUEUE_SIZE)
{
int i = 0;
for(i = 0; i < Demuxframes_cache.size(); i++)
{
if(m_used_queue_size < QUEUE_SIZE)
{
if(m_write_position % QUEUE_SIZE == 0)
{
LOG(WARNING) << "From Demux queue start and now cache size:" << Demuxframes_cache.size();
}
m_queue[m_write_position % QUEUE_SIZE] = Demuxframes_cache[i];
m_write_position++;
m_used_queue_size++;
#ifdef DISPLAY_INFO
LOG(INFO) << " enqueue:" << (m_write_position - 1) % QUEUE_SIZE << " size:" << m_used_queue_size << " item.nVideoBytes: "<< Demuxframes_cache[i].size();
#endif
}
else
break;
}
Demuxframes_cache.erase(Demuxframes_cache.begin(), Demuxframes_cache.begin() + i);
}
else if(m_used_queue_size == QUEUE_SIZE)
{
//LOG(WARNING) << "Demux_queue is full";
}
pthread_mutex_unlock(&m_lock);
if(m_used_queue_size == ACTIVE_DEQUEUE_SIZE || m_clear_cache) //解决最后写队列写的数量不够激活的时候
{
pthread_cond_signal(&m_cond_empty);
}
}
return Demuxframes_cache.size();
}
int Demux_queue::dequeue(FFmpeg::Demuxframe &item)
{
pthread_mutex_lock(&m_lock);
#ifdef DISPLAY_INFO
if(m_dequeue_sta)
{
LOG(INFO) << "dequeue have the lock ";
m_dequeue_sta = false;
m_enqueue_sta = true;
}
#endif
while(m_used_queue_size == 0)
{
LOG(WARNING) << "Demux_queue is empty";
pthread_cond_wait(&m_cond_empty, &m_lock);
}
item = m_queue[m_read_position % QUEUE_SIZE];
m_read_position++;
m_used_queue_size--;
#ifdef DISPLAY_INFO
LOG(INFO) << " dequeue:" << (m_read_position - 1) % QUEUE_SIZE << " size:" << m_used_queue_size << " item.nVideoBytes: " << item.size();
#endif
pthread_mutex_unlock(&m_lock);
if(m_used_queue_size == QUEUE_SIZE - ACTIVE_ENQUEUE_SIZE)
pthread_cond_signal(&m_cond_full);
return (m_read_position - 1) % QUEUE_SIZE;
}
uint64_t Demux_queue::dequeue_batch(std::vector<FFmpeg::Demuxframe> &Demuxframes)
{
FFmpeg::Demuxframe item;
int dequeue_num = 0;
int old_read_position = m_read_position;
Demuxframes.clear();
pthread_mutex_lock(&m_lock);
#ifdef DISPLAY_INFO
if(m_dequeue_sta)
{
LOG(INFO) << "dequeue have the lock ";
m_dequeue_sta = false;
m_enqueue_sta = true;
}
#endif
while(m_used_queue_size == 0)
{
LOG(WARNING) << "Demux_queue is empty";
pthread_cond_wait(&m_cond_empty, &m_lock);
}
if(m_used_queue_size < BATCH_SIZE)
dequeue_num = m_used_queue_size;
else
dequeue_num = BATCH_SIZE;
if(m_read_position < m_write_position)
{
for(int i = 0; i < dequeue_num; i++)
{
Demuxframes.push_back(m_queue[m_read_position % QUEUE_SIZE]);
m_queue[m_read_position % QUEUE_SIZE].clear_data();
m_read_position++;
m_used_queue_size--;
}
}
#ifdef DISPLAY_INFO
LOG(INFO) << "dequeue:" << old_read_position % QUEUE_SIZE << " -> " << m_read_position % QUEUE_SIZE << " dequeue size:" << dequeue_num
<< " res size:" << m_used_queue_size << " Demuxframes size:" << Demuxframes.size();
#endif
pthread_mutex_unlock(&m_lock);
if(m_used_queue_size <= QUEUE_SIZE - ACTIVE_ENQUEUE_SIZE)
pthread_cond_signal(&m_cond_full);
return m_used_queue_size;
}
int Demux_queue::query_used_queue_size(void)
{
return m_used_queue_size;
}
} | true |
b1cb1100c85e9d26602ba7d1117bba95a7e8eccf | C++ | martymcflywa/ScrabbleDictionary | /test/DictionaryExtractorTests.cpp | UTF-8 | 4,683 | 3.0625 | 3 | [] | no_license | #include "stdafx.h"
#include "catch.hpp"
#include <string>
#include "TestHelpers.h"
#include "TestReader.h"
#include "../lib/DefinitionFormatter.h"
#include "../lib/DefinitionPrinter.h"
#include "../lib/DictionaryExtractor.h"
#include "../lib/DictionaryTask.h"
#include "../lib/EmptyStringException.h"
#include "../lib/WordFactory.h"
using namespace std;
using namespace lib;
namespace dictionaryExtractorTests
{
auto formatter = DefinitionFormatter();
auto printer = DefinitionPrinter(formatter);
auto task = DictionaryTask();
auto extractor = DictionaryExtractor(printer, task);
SCENARIO("Dictionary extractor reads valid file")
{
GIVEN("A file containing valid dictionary entries")
{
const string testFile = "first [adj]\nThis is the first definition.\n\nsecond [adv]\nThis is the second definition.\n";
WHEN("The extractor reads the file")
{
auto reader = TestReader();
reader.setTestFile(testFile);
auto& content = reader.read();
auto actual = extractor.extract(content);
THEN("A corresponding collection of Words is created")
{
auto expected = unordered_map<string, shared_ptr<Word>>
{
{ "first", make_shared<Word>(WordFactory::build("first", "adj", "This is the first definition.", printer)) },
{ "second", make_shared<Word>(WordFactory::build("second", "adv", "This is the second definition.", printer)) }
};
for(auto expectedIt = expected.begin(), actualIt = actual.begin();
expectedIt != expected.end() || actualIt != actual.end();
++expectedIt, ++actualIt)
{
REQUIRE(expectedIt->first == actualIt->first);
REQUIRE(TestHelpers::isSmartPtrEqual(expectedIt->second, actualIt->second));
}
}
}
}
}
SCENARIO("Dictionary extractor reads file with missing word")
{
GIVEN("A file containing a dictionary entry with missing word")
{
const string testFile = "[adj]\nThis is the first definition.\n\n";
WHEN("The extracor reads the file")
{
auto reader = TestReader();
reader.setTestFile(testFile);
auto& content = reader.read();
unordered_map<string, shared_ptr<Word>> actual;
try
{
actual = extractor.extract(content);
}
catch (EmptyStringException&) {}
THEN("Nothing is extracted")
{
REQUIRE(actual.empty());
}
}
}
}
SCENARIO("Dictionary extractor reads file with missing type")
{
GIVEN("A file containing a dictionary entry with missing type")
{
const string testFile = "first []\nThis is the first definition.\n\n";
WHEN("The extractor reads the file")
{
auto reader = TestReader();
reader.setTestFile(testFile);
auto& content = reader.read();
unordered_map<string, shared_ptr<Word>> actual;
try
{
actual = extractor.extract(content);
}
catch (EmptyStringException&) {}
THEN("Nothing is extracted")
{
REQUIRE(actual.empty());
}
}
}
}
SCENARIO("Dictionary extractor reads file with missing definition")
{
GIVEN("A file containing a dictionary entry with missing definition")
{
const string testFile = "first [adj]\n\n\n";
WHEN("The extractor reads the file")
{
auto reader = TestReader();
reader.setTestFile(testFile);
auto& content = reader.read();
unordered_map<string, shared_ptr<Word>> actual;
try
{
actual = extractor.extract(content);
}
catch (EmptyStringException&) {}
THEN("Nothing is extracted")
{
REQUIRE(actual.empty());
}
}
}
}
}
| true |
d270fccafcaca7d24d66d1ac47cdc071efca32d5 | C++ | boutboutnico/game | /tic_tac_toe/src/print.cpp | UTF-8 | 1,134 | 2.75 | 3 | [] | no_license | ///
/// \file print.cpp
/// \brief
/// \date 9 juil. 2015
/// \author nboutin
///
#include "print.hpp"
/// === Includes ================================================================================
#include <iostream>
#include "engine/engine.hpp"
/// === Namespaces ================================================================================
using namespace std;
using namespace tic_tac_toe;
namespace print
{
/// === Public Definitions ========================================================================
void print_grid(const Engine& engine)
{
auto& grid = engine.get_grid();
for (auto& line : grid)
{
for (auto& cell : line)
{
auto str = (cell == e_pawn::circle) ? "() " : (cell == e_pawn::cross) ? ">< " : "-- ";
cout << str;
}
cout << endl;
}
cout << "____________________" << endl;
}
/// === Private Definitions ========================================================================
/// ------------------------------------------------------------------------------------------------
}
/// === END OF FILES ============================================================================
| true |
45014f78bd4b2cb1257e309acdabf7099014ed04 | C++ | zahramo/Usart-Sensor | /mainBoard/src/main.cpp | UTF-8 | 1,910 | 2.8125 | 3 | [] | no_license | #include <Arduino.h>
#include <Wire.h>
#include <LiquidCrystal.h>
#include <AltSoftSerial.h>
#define RXPIN 9
#define TXPIN 8
float datas[2];
AltSoftSerial altSerial;
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
typedef union{
float fp;
byte bin[4];
} FloatBytes;
FloatBytes humidity;
FloatBytes temp;
float getDataFromLightBoard(){
float lux = 0;
if (Serial.available() >= 4) {
lux = Serial.parseFloat();
}
return lux;
}
void getDataFromThBoard(){
char c;
int i = 0;
int status = 0; // 0: initial, 1: humidity, 2: temperature
if (altSerial.available() >= 11) {
while (1){
c = altSerial.read();
if (c == '#') {
status = 1;
i = 0;
continue;
}
else if (c == '*'){
status = 2;
i = 0;
continue;
}
else if (c == '@')
break;
if (status == 1) {
humidity.bin[i++] = c;
}
else if (status == 2){
temp.bin[i++] = c;
}
}
}
}
void printResponseInLcd(float humidity, float temp, float lux) {
if (humidity > 80) {
lcd.print("no watering");
}
else if (humidity > 50){
if (temp <= 25) {
if (lux < 600)
lcd.print("10 drop/min");
else if (lux >= 600)
lcd.print("5 drop/min");
}
else {
lcd.print("10 drop/min");
}
}
else {
lcd.print("15 cc/min");
}
}
void setup() {
pinMode(RXPIN, INPUT);
pinMode(TXPIN, OUTPUT);
lcd.begin(16,4);
Serial.begin(9600);
altSerial.begin(9600);
}
void loop() {
float lux = getDataFromLightBoard();
getDataFromThBoard();
lcd.setCursor(0, 0);
lcd.print("hum: ");
lcd.print(humidity.fp);
lcd.setCursor(0, 1);
lcd.print("tmp: ");
lcd.print(temp.fp);
lcd.setCursor(0, 2);
lcd.print("lux: ");
lcd.print(lux);
lcd.setCursor(0, 3);
lcd.print("** ");
printResponseInLcd(humidity.fp, temp.fp, lux);
delay(300);
lcd.clear();
} | true |
7b540bebacc5ea4889aacd952b782d8f6e3612c8 | C++ | dtbinh/Game-Engine | /ResourceManager.cpp | UTF-8 | 6,255 | 2.671875 | 3 | [] | no_license | #include "ResourceManager.h"
#include "GameManager.h"
#include "MeshResource.h"
#include "PathResource.h"
#include "TinyXML.h"
std::string ResourceManager::getCurrentGroupName()
{
return current_group;
}
ResourceManager::ResourceManager(GameManager* gm)
{
game_manager = gm;
current_group = "";
all_resources = new TableAVL<KeyedListArray<GameResource>, string >(&KeyedListArray<GameResource>::compare_items, &KeyedListArray<GameResource>::compare_keys);
}
ResourceManager::~ResourceManager()
{
AVLTreeIterator<KeyedListArray<GameResource> >* all_lists_iter = all_resources->tableIterator();
while(all_lists_iter->hasNext())
{
KeyedListArray<GameResource>* list = all_lists_iter->next();
ListArrayIterator<GameResource>* list_iter = list->iterator();
while(list_iter->hasNext())
{
GameResource* resource = list_iter->next();
delete resource;
}
delete list_iter;
delete list;
}
delete all_lists_iter;
delete all_resources;
}
void ResourceManager::loadResources(std::string group_name)
{
if (current_group == group_name) return;
if (current_group != "") unloadResources();
KeyedListArray<GameResource>* list = all_resources->tableRetrieve(&group_name);
//make sure that the PATHs are all loaded first
ListArrayIterator<GameResource>* iter = list->iterator();
while(iter->hasNext())
{
GameResource* resource = iter->next();
if (resource->getResourceType() == PATH)
{
resource->load();
}
}
delete iter;
//load the rest
iter = list->iterator();
while(iter->hasNext())
{
GameResource* resource = iter->next();
GameResourceType grt = resource->getResourceType();
if (grt != PATH)
{
resource->load();
}
}
delete iter;
//initialize and load the Ogre group
game_manager->initialiseRenderResourceGroup(group_name);
game_manager->loadRenderResourceGroup(group_name);
cout << "meshes should all be loaded" << endl;
current_group = group_name;
}
void ResourceManager::unloadResources()
{
std::string group_name = current_group;
KeyedListArray<GameResource>* list = all_resources->tableRetrieve(&group_name); //old scope
ListArrayIterator<GameResource>* iter = list->iterator();
while(iter->hasNext())
{
GameResource* resource = iter->next();
resource->unload();
}
delete iter;
game_manager->unloadRenderResourceGroup(group_name);
current_group = "";
}
std::string ResourceManager::getConfigFilePath()
{
GameResource* gr = findResourceByID(1);
return gr->getResourceFileName();
}
//id 1 will be the config file path for the current resource group
GameResource* ResourceManager::findResourceByID(unsigned int resource_id)
{
if (current_group == "") return NULL;
KeyedListArray<GameResource>* current_list = all_resources->tableRetrieve(¤t_group);
ListArrayIterator<GameResource>* current_list_iter = current_list->iterator();
while(current_list_iter->hasNext())
{
GameResource* game_resource = current_list_iter->next();
int test_resource_id = game_resource->getResourceID();
if (test_resource_id == resource_id)
{
delete current_list_iter;
return game_resource;
}
}
delete current_list_iter;
return NULL; //the requested resource_id was not found
}
void ResourceManager::loadFromXMLFile(std::string file_name)
{
int resource_count = 1;
TiXmlDocument doc(file_name.c_str());
if (doc.LoadFile())
{
TiXmlNode* resource_tree = doc.FirstChild("resources");
if (resource_tree)
{
//Enumerate resource objects (eventually, child will be false and loop will terminate)
for(TiXmlNode* child = resource_tree->FirstChild(); child; child = child->NextSibling())
{
TiXmlElement* resource_element = child->ToElement();
if(resource_element)
{
GameResource* game_resource = NULL;
TiXmlElement* uid_element = (TiXmlElement*) resource_element->FirstChild("uid");
unsigned int uid = atoi(uid_element->GetText());
TiXmlElement* type_element = (TiXmlElement*) resource_element->FirstChild("resource_type");
std::string resource_type = type_element->GetText();
TiXmlElement* filename_element = (TiXmlElement*) resource_element->FirstChild("file_name");
std::string file_name = filename_element->GetText();
TiXmlElement* scope_element = (TiXmlElement*) resource_element->FirstChild("scope");
std::string scope = scope_element->GetText();
if (resource_type == "path")
{
game_resource = new PathResource(uid, scope, file_name, PATH, game_manager);
}
else if (resource_type == "mesh")
{
game_resource = new MeshResource(uid, scope, file_name, MESH, game_manager);
}
if (game_resource)
{
KeyedListArray<GameResource>* list = all_resources->tableRetrieve(&scope); //place in the appropriate list
if (list)
{
list->add(game_resource);
}
else
{
list = new KeyedListArray<GameResource>(scope);
list->add(game_resource);
all_resources->tableInsert(list);
}
resource_count++;
}
} //individual resource element
else
{
std::string str = "Resource manager failed to load resource meta data ";
str.append("" + resource_count);
str.append(".");
//game_manager->logException(str);
}
} //resource elements for loop
} //resource tree
else
{
//THROW_EXCEPTION(1, "Resource manager failed to load any resources.");
}
} //document
else
{
//THROW_EXCEPTION(1, "Resource manager failed to find the resource metadata file.");
}
}
| true |
2e1c913049c9e913997d256194713b23a108e432 | C++ | BekzhanKassenov/olymp | /codeforces.com/Contests/Other contests/Good Bye/2015/A/A.cpp | UTF-8 | 1,487 | 2.609375 | 3 | [] | no_license | /****************************************
** Solution by Bekzhan Kassenov **
****************************************/
#include <bits/stdc++.h>
using namespace std;
#define F first
#define S second
#define MP make_pair
#define all(x) (x).begin(), (x).end()
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
const double EPS = 1e-9;
const double PI = acos(-1.0);
const int MOD = 1000 * 1000 * 1000 + 7;
const int INF = 2000 * 1000 * 1000;
template <typename T>
inline T sqr(T n) {
return n * n;
}
int months[] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int n;
string s;
struct Date {
int day, month;
int weekday;
Date() :
day(0),
month(0),
weekday(4) { }
bool next() {
day++;
if (day == months[month]) {
day = 0;
month++;
}
weekday++;
weekday %= 7;
return month != 12;
}
};
int main() {
#ifndef ONLINE_JUDGE
freopen("in", "r", stdin);
#endif
cin >> n;
getline(cin, s);
if (s == " of week") {
n--;
Date d;
int ans = 0;
do {
if (d.weekday == n) {
ans++;
}
} while (d.next());
cout << ans << endl;
} else {
int ans = 0;
for (int i = 0; i < 12; i++) {
if (months[i] >= n) {
ans++;
}
}
cout << ans << endl;
}
return 0;
}
| true |
de8e543ca1c74602f2f7e47e113f3ae062e76120 | C++ | OkayFly/Learn | /C/Client/example_client.cpp | UTF-8 | 665 | 2.734375 | 3 | [] | no_license | // 定时器,每2分钟发送 helloword 到服务器
#include <iostream>
#include <stdio.h>
#include "tcpclient.h"
void onRead(const char *data, int len)
{
std::cout << "Receive:"<<data << "len:"<<len<<std::endl;
}
void onConnect()
{
std::cout << "client connect "<<std::endl;
}
void onDisconnect()
{
std::cout<<"client disconnect" << std::endl;
}
int main(int argc, char** argv)
{
if(argc !=3)
{
printf("usage: %s <port> <ip>", argv[0]);
exit(1);
}
TCPClient* tcp_client = new TCPClient("127.0.0.1", 21, onRead, onConnect, onDisconnect);
tcp_client->connect();
tcp_client->join();
return 0;
} | true |
d494d0a249db5cc84d02dda1bd173d2db87b7152 | C++ | gxmc/TerrainGeneration | /vec.h | UTF-8 | 2,160 | 3.296875 | 3 | [] | no_license | #pragma once
#include <iostream>
#include <QTextStream>
using namespace std;
/**
* @brief Classe abstraite de vecteur.
*/
class Vec {
public:
/**
* @brief Calcule la norme du vecteur.
*/
virtual double length() const = 0;
};
class Vec2;
class Vec3;
/**
* @brief Vecteur à 2 dimensions.
*/
class Vec2 : public Vec {
public:
Vec2();
Vec2(double x, double y);
Vec2(const Vec2& v);
Vec2(const Vec3& v);
double length() const;
double x, y;
};
/**
* @brief Vecteur à 3 dimensions.
*/
class Vec3 : public Vec {
public:
Vec3();
Vec3(double x, double y, double z);
Vec3(const Vec2& v, double z);
Vec3(const Vec3& v);
double length() const;
double x, y, z;
};
Vec2 operator+ (const Vec2& v1, const Vec2& v2);
Vec2 operator- (const Vec2& v1, const Vec2& v2);
Vec2 operator* (const Vec2& v, double d);
Vec2 operator* (double d, const Vec2& v);
Vec2 operator/ (const Vec2& v, double d);
Vec3 operator+ (const Vec3& v1, const Vec3& v2);
Vec3 operator- (const Vec3& v1, const Vec3& v2);
Vec3 operator* (const Vec3& v, double d);
Vec3 operator* (double d, const Vec3& v);
Vec3 operator/ (const Vec3& v, double d);
bool operator== (const Vec2& v1, const Vec2& v2);
bool operator== (const Vec3& v1, const Vec3& v2);
inline ostream& operator<<(ostream& os, const Vec2& v)
{
os << "(" << v.x << ';' << v.y << ")";
return os;
}
inline ostream& operator<<(ostream& os, const Vec3& v)
{
os << "(" << v.x << ';' << v.y << ';' << v.z << ")";
return os;
}
inline QTextStream& operator<<(QTextStream& os, const Vec3& v)
{
os << v.x << ' ' << v.y << ' ' << v.z;
return os;
}
double dot(const Vec3& va, const Vec3& vb);
Vec3 cross(const Vec3& va, const Vec3& vb);
Vec2 normalize(const Vec2& v);
Vec3 normalize(const Vec3& v);
/**
* @brief Opérateur de comparaison de deux vecteurs. La comparaison se fait uniquement sur la composante z.
*/
bool operator< (const Vec3& v1, const Vec3& v2);
/**
* @brief Génère un vecteur 2D de coordonnées x entre minX et maxX et y entre minY et maxY.
*/
Vec2 randVec2(double minX = 0.0, double minY = 0.0,
double maxX = 1.0, double maxY = 1.0);
| true |
6913b36c35b665795079edae083f27b113ea887f | C++ | honorpeter/FPGA | /CNN/Tensor.h | UTF-8 | 948 | 2.703125 | 3 | [] | no_license | #include <vector>
#include <assert.h>
struct point_t
{
int x, y, z;
};
struct hyperparam
{
int stride;
int pad;
};
typedef ap_fixed<16,8> fixedAP;
//typedef float fixedAP;
template< int x, int y, int z>
struct tensor_t
{
fixedAP data[x * y * z];
#pragma data
//fixedAP * data_p;
point_t size;
/*Define size of tensor */
tensor_t( )
{
//data_p = &data[0];//data_p = &data[0][0][0];
size.x = x;
size.y = y;
size.z = z;
}
void set_all( fixedAP value )
{
for (int Nz = 0; Nz < size.z; ++Nz)
{
for (int Ny = 0; Ny < size.y; ++Ny)
{
for (int Nx = 0; Nx < size.x; ++Nx)
{
data[Nz * (size.x * size.y) + Ny * (size.x) + Nx] = value;
}
}
}
}
fixedAP& operator()( int _x, int _y, int _z )
{
return this->get( _x, _y, _z );
}
fixedAP& get(int _x, int _y, int _z)
{
return data [_z * (x * y) + _y * (x) +_x];// return data[_z][_y][_x];
}
};
/*Print all data in tensor*/
| true |
2c2e8164293262aa2279e4379b6232932343eaa0 | C++ | yanyan2060/Decision-Tree-Induction-algorithm | /newtable.cpp | UTF-8 | 1,431 | 2.90625 | 3 | [] | no_license | #include "newtable.h"
#include "MyCell.h"
using namespace std;
vector<MyCell> newtable(int num, string dsname,vector<MyCell>&original,vector<vector<string>> &ds)
{
vector<MyCell> newdata;
vector<int> index;
newdata.push_back(original[0]);
for (size_t r = 0; r < original.size();r++)
{
string temp3 = dsname;
if (original[r].attriValue[num]== temp3)
{
MyCell* cell = new MyCell();
cell->attriValue=original[r].attriValue;
cell->attriNum = original[r].attriValue.size();
newdata.push_back(*cell);
delete cell;
}
}
for (size_t row = 0; row < newdata.size(); row++)
{
newdata[row].attriValue.erase( newdata[row].attriValue.begin() + (num));
}
return newdata;
}
vector<MyCell> newtable3(int num, vector<vector<string>> &sub, vector<MyCell>&original, vector<vector<string>> &ds)
{
vector<MyCell> newdata;
vector<int> index;
newdata.push_back(original[0]);
for (size_t r = 0; r < original.size(); r++)
{
for (size_t i = 0; i < sub[0].size(); i++)
{
string temp3 = sub[0][i];
if (original[r].attriValue[num] == temp3)
{
MyCell* cell = new MyCell();
cell->attriValue = original[r].attriValue;
cell->attriNum = original[r].attriValue.size();
newdata.push_back(*cell);
delete cell;
}
}
}
for (size_t row = 0; row < newdata.size(); row++)
{
newdata[row].attriValue.erase(newdata[row].attriValue.begin() + (num));
}
return newdata;
} | true |
d3a2399b39f8d0aec10c34939d6fc583a8b6e05f | C++ | saif86/CPP-Default-Arguments | /Example.cpp | UTF-8 | 923 | 3.921875 | 4 | [] | no_license | /**
* @file Example.cpp
*
* @brief C++ Program to demonstrate working of default argument.
*
* @author Saif Ullah Ijaz
*
*/
#include <iostream>
using namespace std;
// FUNCTION PROTOTYPE (DECLARATION)
/** function that prints a character multiple times.
*
* @param c The input character to be printed.
* @param n The no. of times to be printed.
*
* @return void.
*/
void display(char = '*', int = 1);
// function main begins program execution
int main() {
cout << "No argument passed:\n";
display();
cout << "\n\nFirst argument passed:\n";
display('#');
cout << "\n\nBoth argument passed:\n";
display('$', 5);
system("pause");
return 0;
}
// end main
// FUNCTION DEFINITION
// function that displays the input character desired no. of times
void display(char c, int n) {
for (int i = 1; i <= n; ++i) {
cout << c;
}
cout << endl;
}
// end function display
| true |
92fd3f91d1223c72f50b356e2d451b58b11b2f57 | C++ | alexOarga/PSConcurrentesDistribuidos16 | /practica1/tar/ejercicio_4.cpp | UTF-8 | 1,699 | 3.359375 | 3 | [] | no_license | #include <iostream>
#include <thread>
#include <string>
#include <chrono>
#include <stdlib.h>
#include <time.h>
#include <math.h>
using namespace std;
//Esribe en media la media de los reales de la tabla T
void media(double T[], int i, double* media) {
*media = 0.0;
for(int j = 0; j<i; j++){
*media = *media + T[j];
}
}
//Escribe en menor el menor dato de la tabla T
void menor(double T[], int i, double* menor) {
*menor = T[0];
for(int j=1; j<i; j++){
if(*menor>T[j]){
*menor=T[j];
}
}
}
//Escribe en mayor el mayor real de la tabla T
void mayor(double T[], int i, double* mayor) {
*mayor = T[0];
for(int j=1; j<i; j++){
if(*mayor<T[j]){
*mayor=T[j];
}
}
}
//Asigna a la variable des la desviacion tipica de los i datos de la tabla T
void desviacion(double T[], int i, double* des, int media) {
double suma = 0.0;
for(int j=0; j<i ; j++){
suma = suma + ((T[j]-media)*(T[j]-media));
}
suma = suma/i;
*des=sqrt(suma);
}
int main() {
srand(time(NULL));
double T[100];
for(int i=0; i<100; i++){
T[i]=rand();
}
double varMedia;
thread t1(&media, T, 100, &varMedia);
double varMayor = 0.0;
thread t2(&mayor, T, 100, &varMayor);
double varMenor = 0.0;
thread t3(&menor, T, 100, &varMenor);
t1.join();
t2.join();
t3.join();
double varDes = 0.0;
thread t4(&desviacion, T, 100, &varDes, varMedia);
t4.join();
cout << "#datos: " << 100 << endl;
cout << "media: " << varMedia << endl;
cout << "max: " << varMayor << endl;
cout << "min: " << varMenor << endl;
cout << "sigma: " << varDes << endl;
return 0;
}
| true |
fc48f096e4f550488b63b3258b2826907c7907a3 | C++ | vbabenk/Course-work | /Kursa4/Kursa4/Program.cpp | UTF-8 | 1,895 | 3.421875 | 3 | [] | no_license | #include "Program.h"
#include "Array.h"
Program::Program()
{
}
Program::~Program()
{
}
void Program::Run()
{
int i;
char s[10];
do
{
system("cls");
cout << "-------------- MENU --------------" << endl;
cout << "<1>.Create student's object" << endl;
cout << "<2>.Create teacher's object" << endl;
cout << "<3>.Show smth" << endl;
cout << "<4>.Remove smth" << endl;
cout << "<5>.Save to the file" << endl;
cout << "<6>.Load from the file" << endl;
cout << "<7>.Sort objects" << endl;
cout << "<8>.Do request" << endl;
cout << "<9>.Leave the program" << endl << endl;
cin.getline(s, 10);
i = atoi(s);
switch (i)
{
case 1:
{
system("cls");
create_student();
system("pause");
break;
}
case 2:
{
system("cls");
create_teacher();
system("pause");
break;
}
case 3:
{
system("cls");
show();
system("pause");
break;
}
case 4:
{
system("cls");
remove();
system("pause");
break;
}
case 5:
{
system("cls");
save_file();
system("pause");
break;
}
case 6:
{
system("cls");
load_file();
system("pause");
break;
}
case 7:
{
system("cls");
sort();
system("pause");
break;
}
case 8:
{
system("cls");
do_request();
system("pause");
break;
}
default:
{
if (i > 9 || i < 0)
{
cout << "Your choice is not correct..." << endl;
system("pause");
}
break;
}
}
}
while (i != 9);
}
void Program::create_student()
{
}
void Program::create_teacher()
{
}
void Program::show()
{
}
void Program::remove()
{
}
void Program::save_file()
{
}
void Program::load_file()
{
}
void Program::sort()
{
}
void Program::do_request()
{
} | true |
3acc12406413ae2c711f0d8afb4b6e1fbefca6cd | C++ | WhiZTiM/coliru | /Archive2/3e/0c2e6a4c969ed8/main.cpp | UTF-8 | 5,581 | 3.203125 | 3 | [] | no_license | #include <iostream>
#ifndef ANALOGLITERALS_HPP
#define ANALOGLITERALS_HPP
namespace analog_literals {
typedef unsigned int uint;
// Symbols
enum line_end { o, I };
enum Lsymbol { L };
// Intermediary types used during construction
struct eLsymbol {};
eLsymbol operator! (Lsymbol) { return eLsymbol(); }
struct gen { template <typename T> operator T () const { return T(); } };
template <typename T, uint n> struct excls { excls<T, n + 1> operator! () const { return gen(); } };
template <typename T, uint n> struct dashes: excls<dashes<T, n>, 0>
{ dashes<T, n + 1> operator-- (int) const { return gen(); } };
template <typename, uint> struct L_symbols {}; // represents a L|L|L|.. series
template <typename T, uint n> L_symbols<T, n + 1> operator| (L_symbols<T, n>, Lsymbol) { return gen(); }
template <typename, uint> struct eL_symbols {}; // represents a !L|!L|!L|.. series
template <typename T, uint n> eL_symbols<T, n + 1> operator| (eL_symbols<T, n>, eLsymbol) { return gen(); }
dashes<line_end, 1> operator-- (line_end, int) { return gen(); }
excls<line_end, 1> operator! (line_end) { return gen(); }
// Result types
template <uint len> struct line: L_symbols<line<len>, 0>
{ static uint const length; operator uint () const { return len; } };
template <uint x, uint y> struct rectangle { static uint const width, height, area; };
template <uint x, uint y, uint z> struct cuboid { static uint const width, height, depth, volume; };
// Static members
template <uint len> uint const line<len>::length = len;
template <uint x, uint y> uint const rectangle<x, y>::width = x;
template <uint x, uint y> uint const rectangle<x, y>::height = y;
template <uint x, uint y> uint const rectangle<x, y>::area = x * y;
template <uint x, uint y, uint z> uint const cuboid<x, y, z>::width = x;
template <uint x, uint y, uint z> uint const cuboid<x, y, z>::height = y;
template <uint x, uint y, uint z> uint const cuboid<x, y, z>::depth = z;
template <uint x, uint y, uint z> uint const cuboid<x, y, z>::volume = x * y * z;
template <uint x, uint y, uint z> rectangle<x, y> front (cuboid<x, y, z>) { return gen(); }
template <uint x, uint y, uint z> rectangle<z, y> side (cuboid<x, y, z>) { return gen(); }
template <uint x, uint y, uint z> rectangle<x, z> top (cuboid<x, y, z>) { return gen(); }
// Equality
template <uint ax, uint bx> bool operator== (line<ax>, line<bx>) { return ax == bx; }
template <uint ax, uint ay, uint bx, uint by> bool operator== (rectangle<ax, ay>, rectangle<bx, by>)
{ return ax == bx && ay == by; }
template <uint ax, uint ay, uint az, uint bx, uint by, uint bz>
bool operator== (cuboid<ax, ay, az>, cuboid<bx, by, bz>) { return ax == bx && ay == by && az == bz; }
// Construction
// line
line<0> operator- (line_end, line_end) { return gen(); }
template <uint x> line<x> operator- (dashes<line_end, x>, line_end) { return gen(); }
// rectangle
template <uint x, uint y> struct lower_rectangle {}; // with lower right corner
template <uint excl_marks, uint x>
lower_rectangle<x, (excl_marks + 1) / 2> operator- (excls<dashes<line_end, x>, excl_marks>, line_end)
{ return gen(); }
template <uint x, uint y> rectangle<x, y> operator| (line<x>, lower_rectangle<x, y>) { return gen(); }
// cuboid
template <uint x, uint y, uint z> struct cuboid_top {};
template <uint x, uint y, uint z> struct half_cuboid {};
// dimensions of complete cuboid known, rest is for show
template <uint x, uint n>
cuboid_top<x, n + 1, n> operator| (L_symbols<line<x>, n>, line<x>) { return gen(); }
template <uint x, uint y, uint z, uint n>
eL_symbols<half_cuboid<x, y + (n + 1) / 3, z>, 0> // todo: assert: n%3=2
operator| (cuboid_top<x, y, z>, excls<line_end, n>) { return gen(); }
template <uint x, uint y, uint z>
cuboid<x, y, z> operator| (eL_symbols<half_cuboid<x, y, z>, z>, lower_rectangle<x, 1>) { return gen(); }
// Convenience namespaces that can be "using namespace"'d:
namespace symbols
{
using analog_literals::o;
using analog_literals::I;
using analog_literals::L;
}
namespace shapes
{
using analog_literals::line;
using analog_literals::rectangle;
using analog_literals::cuboid;
}
} // analog_literals
#endif // header guard
int main ()
{
using namespace analog_literals::symbols;
using namespace analog_literals::shapes;
line<3>(I-------I);
rectangle<2, 3> a =(o-----o
| !
! !
! !
o-----o);
cuboid<6, 6, 3> b =(o-------------o
|L \
| L \
| L \
| o-------------o
| ! !
! ! !
o | !
L | !
L | !
L| !
o-------------o );
cuboid<3, 4, 2> c =(o-------o
|L \
| L \
| o-------o
| ! !
o | !
L | !
L| !
o-------o);
std::cout<<a.area <<std::endl;
std::cout<<b.volume <<std::endl;
}
| true |
8f70643ac945a15035c09423110e29d64a80e269 | C++ | munsingh/Downloader | /src/main.cpp | UTF-8 | 2,830 | 2.875 | 3 | [] | no_license |
//boost includes
#include "boost/any.hpp"
#include "boost/program_options.hpp"
//Project Includes
#include "Globals.h"
#include "DownloadManager.h"
#include "URL.h"
//C++ includes
#include <vector>
#include <iostream>
namespace po = boost::program_options;
struct Directory {
public:
Directory( const std::string& strDirectory ) : m_strDirectory( strDirectory ) {}
std::string m_strDirectory;
};
void validate( boost::any& v, std::vector< std::string > const& values, Directory*, int ) {
// Make sure no previous assignment to 'v' was made.
po::validators::check_first_occurrence( v );
//Extract the first string from 'values'. If there is more than one string,
//it's an error, and exception will be thrown.
std::string const& s = po::validators::get_single_string( values );
//check the validity of the
//TODO::
v = boost::any( Directory( s ) );
}
int wmain( int argc, const wchar_t** argv ) {
int nRetval = 0;
try {
//Setup boost program options, to handle command line switches passed
//
std::string strDownloadFolderA;
bool bRetval = Globals::GetDownloadsFolder( strDownloadFolderA );
if( !bRetval ) {
return 1;
}
po::options_description desc( "This application can be used to download one ore more files from the internet.\nIt supports downloading from various protocols http, ftp, sftp and so on.\nUsage: Downloaders.exe --dir <DirectoryName> URL1 URL2" );
desc.add_options()
( "help,h", "Displays this help" )
( "dir,d", po::value< Directory >(), "Directory where the files will be downloaded and kept.\nIf not specified, it defaults to the Systems Download directory.\nIf exact path is not specified, then this path will be created under the default folder." )
( "url,u", po::value< std::vector< Helper::URL > >(), "URLs to download from space separated" );
//all positional arguments will be treated as URLs
po::positional_options_description p;
p.add( "url", -1 );
po::variables_map vm;
po::store( po::wcommand_line_parser( argc, argv ).options( desc ).positional( p ).run(), vm );
po::notify( vm );
if( vm.count( "help" ) || vm.empty() ) {
std::cout << desc << std::endl;
nRetval = 0;
}
else {
//Max Concurrent Downloads is automatically stored in the variable uMaxConcurentDownloads
//Retrive the download directory
if( vm.count( "dir" ) ) {
//directory specified,
strDownloadFolderA = vm[ "dir" ].as< Directory >().m_strDirectory;
}
if( vm.count( "url" ) ) {
Helper::DownloadManager oDLManager( vm[ "url" ].as< std::vector<Helper::URL>>(),
strDownloadFolderA );
oDLManager.Start();
}
else {
std::cout << "You need to specify the URLs to download.";
nRetval = 1;
}
}
}
catch( std::runtime_error& ) {
//TODO::
}
catch( ... ) {
//TODO::
}
return nRetval;
} | true |
cb89818790cce6b54ca4952551643b845d6ee51a | C++ | OmerBhatti/Cpp-Classes | /Custom Classes/BitArray.cpp | UTF-8 | 2,915 | 3.359375 | 3 | [] | no_license | #include "BitArray.h"
#include <iostream>
#include <cmath>
using namespace std;
int BitArray::getCapacity()const
{
return capacity;
}
BitArray::BitArray(int n)
{
capacity = n;
int s = (int)ceil((float)capacity / 8);
data = new unsigned char[s];
for (int i = 0; i < s; i++)
{
//initialize with zeroes
data[i] = data[i] & 0;
}
}
BitArray::BitArray(const BitArray& ref)
{
if (ref.data == nullptr)
{
data = nullptr;
capacity = 0;
return;
}
int s = (int)ceil((float)(ref.capacity / 8));
capacity = ref.capacity;
data = new unsigned char[s];
for (int i = 0; i < s; i++)
{
data[i] = ref.data[i];
}
}
void BitArray::on(int bitNo)
{
if (isValidBit(bitNo))
{
int block = bitNo / 8;
int bit = bitNo % 8;
unsigned char mask = (1 << (bit));
data[block] = data[block] | mask;
}
}
void BitArray::off(int bitNo)
{
if (isValidBit(bitNo))
{
int block = bitNo / 8;
int bit = bitNo % 8;
unsigned char mask = (1 << (bit));
data[block] = data[block] & ~mask;
}
}
bool BitArray::checkBitStatus(int bitNo)
{
if (isValidBit(bitNo))
{
int block = bitNo / 8;
int bit = bitNo % 8;
unsigned char x = data[block];
return x & (1 << bit);
}
}
void BitArray::invert(int bitNo)
{
if (isValidBit(bitNo))
{
int block = bitNo / 8;
int bit = bitNo % 8;
unsigned char mask = (1 << (bit));
data[block] = data[block] ^ mask;
}
}
void BitArray::dump()
{
for (int i = capacity - 1; i >= 0; i--)
{
if (i % 8 == 0)
{
cout << checkBitStatus(i) << " ";
}
else
{
cout << checkBitStatus(i);
}
}
cout << "\n";
}
BitArray BitArray::AND(BitArray & arr2)
{
BitArray arr(capacity);
int s = (int)ceil((float)capacity / 8);
for (int i = 0; i < s; i++)
{
arr.data[i] = data[i] & arr2.data[i];
}
return arr;
}
BitArray BitArray::OR(BitArray & arr2)
{
BitArray arr(arr2);
int s = (int)ceil((float)capacity / 8);
for (int i = 0; i < s; i++)
{
arr.data[i] = data[i] | arr2.data[i];
}
return arr;
}
void BitArray::shiftLeft(int count)
{
setIntegralValue(getUnsignedIntegeralValue() * pow(2, count));
}
void BitArray::shiftRight(int count)
{
setIntegralValue(getUnsignedIntegeralValue() / pow(2, count));
}
unsigned long long BitArray::getUnsignedIntegeralValue()
{
unsigned long long value = 0;
for (int i = 0; i < capacity; i++)
{
//1101 = 1*2^0 + 1*2^1 + 0*2^2 + 1*2^3 = 1+2+0+8 = 11
value = value + checkBitStatus(i) * pow(2, i);
}
return value;
}
void BitArray::setIntegralValue(unsigned long long value)
{
int max = pow(2, capacity);
if (value < max)
{
int s = (int)ceil((float)capacity / 8);
for (int i = 0; i < s; i++)
{
//reset array
data[i] = data[i] & 0;
}
for (int i = 0; value; i++)
{
if (value % 2 == 0)
{
off(i);
}
else if(value % 2 == 1)
{
on(i);
}
value = value / 2;
}
}
}
BitArray::~BitArray()
{
if (data == nullptr)
{
capacity = 0;
return;
}
delete[]data;
capacity = 0;
} | true |
e42ad5dbf19225455d5699bab430990fb55910f1 | C++ | jdefaye/local_TSP | /solution.cpp | UTF-8 | 543 | 2.671875 | 3 | [] | no_license | #include "solution.h"
Solution::Solution() {}
Solution::Solution(const std::pair< float, float >& evaluation, const std::vector< int >& conf): eval(evaluation), configuration(conf)
{}
std::pair< float, float > Solution::get_eval() const
{
return eval;
}
void Solution::set_eval(const std::pair< float, float >& evaluation)
{
eval = evaluation;
}
std::vector< int > Solution::get_configuration() const
{
return configuration;
}
void Solution::set_configuration(const std::vector< int >& conf)
{
configuration = conf;
}
| true |
2f4f10bf1e0a19b5d72f32d88a790560a97dcd50 | C++ | kartoshhka/urs_laba2 | /bagulina_ms_13345_2_2/src/get_week_day_client.cpp | UTF-8 | 784 | 2.78125 | 3 | [] | no_license | #include "ros/ros.h"
#include "bagulina_ms_13345_2_2/GetDay.h"
#include <cstdlib>
int main(int argc, char **argv)
{
ros::init(argc, argv, "get_week_day_client");
ros::NodeHandle n;
ros::ServiceClient client = n.serviceClient<bagulina_ms_13345_2_2::GetDay>("get_week_day");
bagulina_ms_13345_2_2::GetDay srv;
while (ros::ok())
{
int day;
int month;
ROS_INFO_STREAM("Input the number of the day and month: ");
std::cin >> day;
std::cin >> month;
srv.request.a = day;
srv.request.b = month;
if (client.call(srv))
{
ROS_INFO_STREAM("The day is: " << srv.response.day);
}
else
{
ROS_ERROR_STREAM("Failed to call service get_week_day or wrong data input");
}
}
return 0;
}
| true |
14e4fd871b6a488756d4ad102de2698df2c5be01 | C++ | Algoraphics/VisualStudioStuff | /Lab3/Producer/Connection.cpp | UTF-8 | 2,890 | 3.09375 | 3 | [] | no_license | // Gabriel Hope, ghope@wustl.edu
// Kevin Kieselbach, kevin.kieselbach@wustl.edu
// Ethan Rabb, ethanrabb@go.wustl.edu
//
// Connection class definition.
//
#include "stdafx.h"
#include "Connection.h"
#include "Producer.h"
using namespace std;
Connection::Connection(Producer & producer_) :
receivingPlays(true),
producer(producer_),
directorId(-1)
{
}
/*
* Parses an input command from the stream and follows our communication protocal after determining
* the type of token that has been input. Initially it is assumed that we will receive a play name.
* Any characters not in our list of special tokens will be concatenated as part of the play name.
*/
int Connection::handle_input(ACE_HANDLE h)
{
char buffer;
ACE_Time_Value timeout(5);
while (this->stream.recv_n(&buffer, 1, &timeout) > 0)
{
if (buffer == END_OF_PLAYS_TOKEN)
{
if (!this->receivingPlays)
{
cerr << "Invalid END_OF_PLAYS_TOKEN" << endl;
return 0;
}
// Add the director's list of plays to the producer
this->producer.setRepertoire(this->directorId, this->playNames);
this->playNames.clear();
receivingPlays = false;
return 0;
}
else if (buffer == PLAY_ENDED_TOKEN)
{
if (this->receivingPlays)
{
cerr << "Invalid message received while reading play names" << endl;
return 0;
}
// Inform the producer that the director is ready to perform another play
this->producer.directorReady(this->directorId);
return 0;
}
else if (buffer == PLAY_STARTED_TOKEN)
{
if (this->receivingPlays)
{
cerr << "Invalid message received while reading play names" << endl;
return 0;
}
// Inform the producer that the director has started the play
this->producer.directorStarted(this->directorId);
return 0;
}
else if (buffer == DIRECTOR_TERMINATED_TOKEN)
{
if (this->receivingPlays)
{
cerr << "Invalid message received while reading play names" << endl;
return 0;
}
// Inform the producer that the director has terminated
this->producer.removeDirector(this->directorId);
return 0;
}
else if (this->receivingPlays)
{
if (buffer == ' ')
{
this->playNames.push_back(this->curPlayName);
this->curPlayName = "";
}
else
{
// Concatenates the current character to the play name we are saving
this->curPlayName += buffer;
}
}
else
{
cerr << "Token: " << buffer << " undefined" << endl;
}
}
// If recv fails, fire the director for incompetence.
if (this->directorId != -1)
{
this->producer.removeDirector(this->directorId);
this->directorId = -1;
}
return 0;
}
/*
* Get access to the stream object
*/
ACE_SOCK_Stream& Connection::getStream()
{
return this->stream;
}
/*
* Setter for the director ID
*/
void Connection::setDirectorId(int directorId)
{
if (this->directorId == -1)
{
this->directorId = directorId;
}
else
{
cerr << "This connection already has a director" << endl;
}
} | true |
c2a8476665d786d085a805ef4d42fa2fa8cd5f4b | C++ | sjtuchp/C-PrimerPlus-Learning-Note | /chapter8/practice/5.cpp | UTF-8 | 392 | 3.828125 | 4 | [] | no_license | #include <iostream>
template <typename T>
T max5(T *);
int main(){
using std :: cout;
using std :: endl;
int arr1[] = {1,2,3,4,5};
double arr2[] = {1.0,2.2,3.3,5.5,2};
cout << max5(arr1) << endl;
cout << max5(arr2) << endl;
}
template <typename T>
T max5 (T *arr){
T result = *arr;
for (int i=1;i<5;i++)
if (arr[i]>result)
result = arr[i];
return result;
}
| true |
68d503a222c98290bf92422b173761d1fbb890ca | C++ | anshumanvarshney/CODE | /Basic Implementation/tree/binarysearchtree.cpp | UTF-8 | 2,744 | 3.828125 | 4 | [] | no_license | /*
traversal of binary tree
1-Depth order(inorder, preorder, postorder)
2-Level order (level by level)
*/
#include<bits/stdc++.h>
using namespace std;
class btree
{
private :
struct node //building a binary search tree
{
node *left;
int data;
node *right;
}*root; //root of a binary tree
public:
btree();
void buildtree(int num);
void insert(node **sr,int num);
int height(node *sr);
void traversal();
void inorder(node *sr);
void preorder(node *sr);
void postorder(node *sr);
void levelorder(node *sr);
void del(node *sr);
~btree();
};
btree::btree()
{
root=NULL;
}
void btree::buildtree(int num)
{
insert(&root,num);
}
void btree::insert(node **sr,int num)
{
if(*sr==NULL)// making of 'root node' in every recursion
{
*sr=new node;
(*sr)->left=NULL;
(*sr)->data=num;
(*sr)->right=NULL;
}
else
{
if(num<(*sr)->data)
{
insert(&((*sr)->left),num);
}
else
{
insert(&((*sr)->right),num);
}
}
}
int btree :: height (node *sr)
{
int l,r;
if(sr==NULL)
{
return 0;
}
else
{
l=height (sr->left); //recursive call
r=height (sr->right);
if(l>r)
return (l+1);
else return (r+1);
}
}
void btree::traversal()
{
cout<<"\nHeight :";
int t=height(root);
cout<<t;
cout<<"\nIno-rder Traversal :";
inorder(root);
cout<<"\nPre-order Traversal :";
preorder(root);
cout<<"\nPostorder Traversal :";
postorder(root);
cout<<"\nLevel Traversal :";
levelorder(root);
}
void btree :: inorder (node *sr)//because BST is recursive in nature
{
if(sr!=NULL)
{
inorder(sr->left);
cout<<(sr->data)<<" ";
inorder(sr->right);
}
}
void btree :: preorder (node *sr)
{
if(sr!=NULL)
{
cout<<(sr->data)<<" ";
preorder(sr->left);
preorder(sr->right);
}
}
void btree :: postorder (node *sr)
{
if(sr!=NULL)
{
postorder(sr->left);
postorder(sr->right);
cout<<(sr->data)<<" ";
}
}
void btree::levelorder(node *root)
{
if(root==NULL) return;
queue<node *> q;//queue of node i.e tree
q.push(root);
while(!q.empty())
{
root=q.front();
q.pop();
cout<< root->data <<" ";
if(root->left!=NULL)
q.push(root->left);
if(root->right!=NULL)
q.push(root->right);
}
}
btree :: ~btree() // deallocate memory
{
del(root);
}
void btree::del(node *sr)
{
if(sr!=NULL)
{
del(sr->left);
del(sr->right);
}
delete sr;
}
int main()
{
btree bt;
int req,i=0,num;
cout<<"Specify the number of items to be inserted :";
cin>>req;
while(++i<=req)
{
cout<<"\nEnter data :";
cin>>num;
bt.buildtree(num);
}
bt.traversal();
return 0;
}
| true |
72c31b1281ae6d155842e6f61b0c2c07b091d6cf | C++ | InfiniBrains/mobagen | /examples/maze/Node.h | UTF-8 | 1,018 | 3.09375 | 3 | [
"Apache-2.0"
] | permissive | #ifndef MOBAGEN_NODE_H
#define MOBAGEN_NODE_H
#include <iostream>
#include <vector>
// the goal of this data structure is to interface with the world
struct Node {
public:
Node() = default;
Node(bool north, bool east, bool south, bool west) {
data = ((uint8_t)north) | ((uint8_t)east << 1U) | ((uint8_t)south << 2U) | ((uint8_t)west << 3U);
}
private:
uint8_t data;
public:
// todo: can you improve this?
bool inline GetNorth() const { return data & 1U; };
bool inline GetEast() const { return data >> 1U & 1U; };
bool inline GetSouth() const { return data >> 2U & 1U; };
bool inline GetWest() const { return data >> 3U & 1U; };
// todo set
// todo: can you improve this?
void inline SetNorth(bool x) { data = (data & ~(1 << 0)) | x << 0; };
void inline SetEast(bool x) { data = (data & ~(1 << 1)) | x << 1; };
void inline SetSouth(bool x) { data = (data & ~(1 << 2)) | x << 2; };
void inline SetWest(bool x) { data = (data & ~(1 << 3)) | x << 3; };
};
#endif // MOBAGEN_NODE_H
| true |
f71cd496903a3fed0fd8fdcfa83fccc1df611cf1 | C++ | ClarePhang/avs-device-sdk-intel-speech-enabling-kit | /CapabilityAgents/Alerts/include/Alerts/Reminder.h | UTF-8 | 2,804 | 2.53125 | 3 | [
"Apache-2.0"
] | permissive | /*
* Reminder.h
*
* Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#ifndef ALEXA_CLIENT_SDK_CAPABILITY_AGENTS_ALERTS_INCLUDE_ALERTS_REMINDER_H_
#define ALEXA_CLIENT_SDK_CAPABILITY_AGENTS_ALERTS_INCLUDE_ALERTS_REMINDER_H_
#include "Alerts/Alert.h"
namespace alexaClientSDK {
namespace capabilityAgents {
namespace alerts {
/**
* A reminder class. This represents an alert which the user wishes to activate at a specific point in time,
* which they specify as that absolute time point, rather than an offset from the current time.
*
* The user expectation is that the activation of the reminder will include custom assets (if the device is connected
* to the internet), such as Alexa telling the user something specific with respect to the reminder being set.
*
* Usage example:
* "Alexa, remind me to walk the dog at 10am".
* 10am : Alexa will say "This is your 10am reminder to walk the dog."
*/
class Reminder : public Alert {
public:
/// String representation of this type.
static const std::string TYPE_NAME;
/**
* A static function to set the default audio file path for this type of alert.
*
* @note This function should only be called at initialization, before any objects have been instantiated.
*
* @param filePath The path to the audio file.
*/
static void setDefaultAudioFilePath(const std::string& filePath);
/**
* A static function to set the short audio file path for this type of alert.
*
* @note This function should only be called at initialization, before any objects have been instantiated.
*
* @param filePath The path to the audio file.
*/
static void setDefaultShortAudioFilePath(const std::string& filePath);
std::string getDefaultAudioFilePath() const override;
std::string getDefaultShortAudioFilePath() const override;
std::string getTypeName() const override;
private:
/// The class-level audio file path.
static std::string m_defaultAudioFilePath;
/// The class-level short audio file path.
static std::string m_defaultShortAudioFilePath;
};
} // namespace alerts
} // namespace capabilityAgents
} // namespace alexaClientSDK
#endif // ALEXA_CLIENT_SDK_CAPABILITY_AGENTS_ALERTS_INCLUDE_ALERTS_REMINDER_H_ | true |
2a79f74a97f3ed9b2cd530c243ad9560e943c66d | C++ | NathanZaldivar/Cpp_codecademy | /LOGICAL OPERATORS/Leap_year.cpp | UTF-8 | 354 | 3.265625 | 3 | [] | no_license | #include <iostream>
int main() {
int year;
std::cout << "Enter current year: ";
std::cin >> year;
if (year < 9999 && year > 1000) {
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
std::cout << "Leap year!\n";
} else {
std::cout << "Not a leap year!\n";
}
} else {
std::cout << "Invalid year\n";
}
}
| true |
2f1c528703f30b9d96da2df963055370df77d63b | C++ | alexclapou/oop | /exam/domain.h | UTF-8 | 833 | 3.234375 | 3 | [] | no_license | #include <string>
class Astronomer{
private:
std::string name;
std::string constellation;
public:
Astronomer(std::string _n, std::string _c):name{_n}, constellation{_c}{}
std::string get_name();
std::string get_constellation();
};
class Star{
private:
std::string name;
std::string constellation;
int ra;
int dec;
int diameter;
public:
Star(std::string _n, std::string _c, int _r, int _d, int _di):name{_n}, constellation{_c}, ra{_r}, dec{_d}, diameter{_di}{}
std::string get_name();
std::string get_constellation();
int get_ra();
int get_dec();
int get_diameter(){
return diameter;
}
friend std::ostream& operator<<(std::ostream& os, Star& star_to_add);
};
| true |
99718b49cbdda49eaa4f08c7e509bdfda234027d | C++ | quanghm/UVA-online-judge | /151.cpp | UTF-8 | 644 | 2.6875 | 3 | [] | no_license | /*
* uva151.cpp
*
* Created on: May 4, 2015
* Author: qhoang
*/
#include<iostream>
using namespace std;
int main() {
int n, m,s;
while (cin >> n && n) {
if (n == 13) {
cout<<"1\n";
} else {
m=2;
while (m++){
// int a[100] = { }; // a[i]: last person in an (i+1)-queue
// a[0] = 0;
// a[1] = 1;
// for (int i = 2; i < n; i++) { //a[0]=0
// a[i] = (a[i - 1] + m) % (i);
// if (a[i] == 0) {
// a[i] = i;
// }
// }
s=1; //two zones
for (int i=2;i<n;i++){
s=(s+m)%i;
if (s==0){
s=i;
}
}
if (s==12){
cout<<m<<"\n";
break;
}
}
}
}
}
| true |
afcd4f56dbe07177f91693d777d1511851cc6841 | C++ | tobias93/sort-algorithms | /Sortierverfahren/MergeSorter.cpp | UTF-8 | 2,400 | 3.09375 | 3 | [
"MIT"
] | permissive | #include "stdafx.h"
#include "MergeSorter.h"
template<class sortType>
MergeSorter<sortType>::MergeSorter()
{
}
template<class sortType>
MergeSorter<sortType>::~MergeSorter()
{
}
template<class sortType>
void MergeSorter<sortType>::sort(DataArray<sortType>& data)
{
this->resetPerformenceCounters();
this->sortRecursive(data.getData(), data.getLength());
}
template<class sortType>
void MergeSorter<sortType>::sortRecursive(sortType* data, unsigned int len)
{
/*
Laufzeitverhalten:
Vergleiche:
O(n * log(n))
Schreibzugriffe:
Best case = average case = worst case:
2n * log(n)
*/
if (len <= 1)
{
return;
}
//split data[] into 2 segments and use mergesort to sort each segment recursively
unsigned int len_1st_half = len / 2;
unsigned int len_2nd_half = len - len_1st_half;
this->sortRecursive(data, len_1st_half);
this->sortRecursive(&data[len_1st_half], len_2nd_half);
//merge the sorted segments
// copy the segments to their own arrays
sortType* data_1st_half = (sortType*)malloc(sizeof(sortType) * len_1st_half);
sortType* data_2nd_half = (sortType*)malloc(sizeof(sortType) * len_2nd_half);
memcpy(data_1st_half, data, sizeof(sortType) * len_1st_half);
memcpy(data_2nd_half, &data[len_1st_half], sizeof(sortType) * len_2nd_half);
this->countWrites(len);
// merge them back to the data array
unsigned int position_1st_half = 0;
unsigned int position_2nd_half = 0;
unsigned int position = 0;
while (position_1st_half < len_1st_half && position_2nd_half < len_2nd_half)
{
this->countCompares(1);
if (data_1st_half[position_1st_half] <= data_2nd_half[position_2nd_half])
{
data[position] = data_1st_half[position_1st_half];
position_1st_half++;
}
else
{
data[position] = data_2nd_half[position_2nd_half];
position_2nd_half++;
}
position++;
this->countWrites(1);
}
// copy back what is left over
if (position_1st_half < len_1st_half)
{
memcpy(&data[position], &data_1st_half[position_1st_half], sizeof(sortType) * (len_1st_half - position_1st_half));
this->countWrites(len_1st_half - position_1st_half);
}
else if (position_2nd_half < len_2nd_half)
{
memcpy(&data[position], &data_2nd_half[position_2nd_half], sizeof(sortType) * (len_2nd_half - position_2nd_half));
this->countWrites(len_2nd_half - position_2nd_half);
}
//free memory
delete(data_1st_half);
delete(data_2nd_half);
} | true |
4d1d0acbb42cfb48804445ff7120146c7bde262d | C++ | Bab95/Programs | /LeetCode/Problems/14.Longest_Common_Prefix.cpp | UTF-8 | 2,055 | 3.171875 | 3 | [] | no_license | class Solution {
public:
struct node{
bool isEnd;
int count;
struct node* children[26];
};
struct node* getnode(){
struct node* tmp = new node;
tmp->isEnd = false;
tmp->count = 0;
for(int i=0;i<26;i++){
tmp->children[i] = NULL;
}
return tmp;
}
void insertTrie(struct node* root,string &s){
struct node* pcrawl = root;
for(int i=0;i<s.length();i++){
int index = (int)s[i]-97;
if(pcrawl->children[index]==NULL){
pcrawl->children[index] = getnode();
}
pcrawl->children[index]->count+=1;
pcrawl = pcrawl->children[index];
}
pcrawl->isEnd = true;
cout<<"insertion Complete:"<<s<<endl;
}
int countChild(int *index,struct node* pcrawl){
int res = 0;
for(int i=0;i<26;i++){
if(pcrawl->children[i]!=NULL){
res++;
*index = i;
}
}
return res;
}
void printTrie(struct node *root){
for(int i=0;i<26;i++){
cout<<"level: "<<i+1<<" ";
if(root->children[i]!=NULL){
char c = (char)(i+97);
cout<<c<<" ";
root = root->children[i];
}
cout<<endl;
}
}
string longestCommonPrefix(vector<string>& strs) {
struct node* root = getnode();
for(int i=0;i<strs.size();i++){
insertTrie(root,strs[i]);
}
printTrie(root);
struct node* pcrawl = root;
string res;
int index = -1;
while(pcrawl!=NULL&&pcrawl->isEnd!=true){
int child = countChild(&index,pcrawl);
if(child>1){
break;
}else if(child==1){
char c = (char)(index+97);
res.push_back(c);
}else{
break;
}
pcrawl = pcrawl->children[index];
}
return res;
}
};
| true |
dca34b7c82fe1026935f24217d65a97cac6c4bed | C++ | Thunradee/CPP | /BSTMorse/main.cpp | UTF-8 | 2,357 | 3.171875 | 3 | [] | no_license | /*************************************************************************************************************
* Programmer: Thunradee Tangsupakij *
* Class: CptS 122, Spring, 2019; Lab Section 2 *
* Programming Assignment 6: Morse Code Lookup BST *
* Date: March 21, 2019 *
* Description: This program creates a morse lookup BST, reads messages from a file, converts to morse codes *
* and displays to the screen *
*************************************************************************************************************/
#include <iostream>
#include <fstream>
#include <string>
#include <ctype.h>
#include "BST.h"
int main(void) {
BST<char, string> tree;
cout << "************** Morse Code Alphabet **************" << endl;
tree.printInOrderRecur(tree.getRoot());
fstream in;
in.open("Convert.txt");
if (in.is_open()) {
// file is opened successfully
char temp;
string line, morse, morseMessage;
bool isFound = false;
cout << endl;
cout << endl;
cout << "Morse Message::" << endl;
while (!in.eof()) {
getline(in, line);
line += "\n";
for (int i = 0; i < line.length(); ++i) {
temp = line[i];
if (temp == '\n') {
morseMessage += "\n";
cout << endl;
}
else if (temp == ' ') {
morseMessage += " ";
cout << " ";
}
else {
if (isalpha(temp)) {
temp = toupper(temp);
}
isFound = tree.searchRecur(tree.getRoot(), temp, morse);
if (isFound) {
morseMessage += morse;
morseMessage += " ";
cout << morse << " ";
}
}
}
}
in.close();
/*string file = "- .... .. ... .. ... .- - . ... - --- ..-. - .... . -.-. .--. - ... .---- ..--- ..--- \n-- --- .-. ... . -.-. --- -.. . -.-. --- -. ...- . .-. ... .. --- -. - --- --- .-.. .-.-.- \n";
cout << file;
if (file == morseMessage) {
cout << "correct" << endl;
}
else {
cout << "not correct" << endl;
}*/
}
return 0;
} | true |
8e0db7b435fbc1b28c23efa1a56d6db07af4866c | C++ | workOnCarrier/AccGrind | /plugins/textEcho/specialTextTask.cpp | UTF-8 | 607 | 2.609375 | 3 | [] | no_license | #include <iostream>
#include "specialTextTask.h"
namespace AccGrindPlugin{
SpecialTextTask::SpecialTextTask( std::string const &textVal)
:m_textValue(textVal) { }
void SpecialTextTask::execute()
{
std::cout << " value of string in SPECIAL task is ::" << m_textValue << std::endl;
}
std::string SpecialTextOption:: getOptionString ( )const {
return "echo fun string";
}
Task SpecialTextOption:: getTask ( std::string const& textString) const {
return std::make_shared<SpecialTextTask>(SpecialTextTask(textString));
}
}
| true |
ad571cc1a3d3d248e51089e5a88e10b5fe2c4356 | C++ | Kpolatajko/PAMSI | /Projekt_1/src/main.cpp | UTF-8 | 13,731 | 3.671875 | 4 | [] | no_license | #include "list.hh"
#include "map.hh"
#include "stack.hh"
#include "queue.hh"
#include "priorityqueue.hh"
#include <iostream>
//---Biblioteki STL---
#include <queue>
#include <stack>
#include <list>
#include <iterator>
#include <map>
//---Funkcja wyswietlajaca liste STL
void display_list(std::list<int> tlist){
std::list<int>::iterator I;
for(I = tlist.begin(); I != tlist.end(); ++I)
std::cout<<*I<<" ";
std::cout<<std::endl;
}
//---Funkcja wyswietlajaca stos STL
void display_stack(std::stack<int> tym){
while(!tym.empty()){
std::cout<<tym.top()<<"\n";
tym.pop();
}
}
//---Funkcja wyswietlajaca kolejke STL
void display_queue(std::queue<int> temp){
while(!temp.empty()){
std::cout<<temp.front()<<" ";
temp.pop();
}
std::cout<<std::endl;
}
//---Funkcja wyswietlajaca kolejke priorytetowa STL
void display_priority_queue(std::priority_queue<int> ptemp){
while(!ptemp.empty()){
std::cout<<ptemp.top()<<" ";
ptemp.pop();
}
std::cout<<std::endl;
}
//---Funkcja wyswietlajaca hashmape STL
void display_map(std::map<std::string, int> mapSTL){
for (auto itr = mapSTL.begin(); itr != mapSTL.end(); ++itr){
std::cout<<"Klucz: "<<itr->first<<std::endl;
std::cout<<"Wartosc: "<<itr->second<<std::endl;
std::cout<<std::endl;
}
}
int main(){
std::cout<<"\n=================================\n";
//===Lista - projekt===
List<int> list;
std::cout<<"=====Lista - projekt:=====\n";
list.pushBack(1);
std::cout<<"--------------------------\n";
std::cout<<"---Funkcja pushBack(1)----\n";
std::cout<<"--------------------------\n";
std::cout<<list[0]<<std::endl;
list.pushBack(12);
std::cout<<"--------------------------\n";
std::cout<<"---Funkcja pushBack(12)---\n";
std::cout<<"--------------------------\n";
std::cout<<list[0]<<" "<<list[1]<<std::endl;
list.pushFront(3);
std::cout<<"--------------------------\n";
std::cout<<"---Funkcja pushFront(3)---\n";
std::cout<<"--------------------------\n";
std::cout<<list[0]<<" "<<list[1]<<" "<<list[2]<<std::endl;
list.pushFront(9);
std::cout<<"--------------------------\n";
std::cout<<"---Funkcja pushFront(9)---\n";
std::cout<<"--------------------------\n";
std::cout<<list[0]<<" "<<list[1]<<" "<<list[2]<<" "<<list[3]<<std::endl;
list.insert(2,2);
std::cout<<"--------------------------\n";
std::cout<<"---Funkcja insert(2,2)----\n";
std::cout<<"--------------------------\n";
std::cout<<list[0]<<" "<<list[1]<<" "<<list[2]<<" "<<list[3]<<" "<<list[4]<<std::endl;
list.remove(1);
std::cout<<"--------------------------\n";
std::cout<<"----Funkcja remove(1)-----\n";
std::cout<<"--------------------------\n";
std::cout<<list[0]<<" "<<list[1]<<" "<<list[2]<<" "<<list[3]<<std::endl<<std::endl<<std::endl;
//===Lista - STL===
std::list<int> listSTL;
std::cout<<"=======Lista - STL:=======\n";
listSTL.push_back(1);
std::cout<<"--------------------------\n";
std::cout<<"---Funkcja pushBack(1)----\n";
std::cout<<"--------------------------\n";
display_list(listSTL);
listSTL.push_back(12);
std::cout<<"--------------------------\n";
std::cout<<"---Funkcja pushBack(12)---\n";
std::cout<<"--------------------------\n";
display_list(listSTL);
listSTL.push_front(3);
std::cout<<"--------------------------\n";
std::cout<<"---Funkcja pushFront(3)---\n";
std::cout<<"--------------------------\n";
display_list(listSTL);
listSTL.push_front(9);
std::cout<<"--------------------------\n";
std::cout<<"---Funkcja pushFront(9)---\n";
std::cout<<"--------------------------\n";
display_list(listSTL);
std::list<int>::iterator it;
it = listSTL.begin();
++it;
++it;
listSTL.insert(it,2);
std::cout<<"--------------------------\n";
std::cout<<"---Funkcja insert(2,2)----\n";
std::cout<<"--------------------------\n";
display_list(listSTL);
listSTL.remove(3);
std::cout<<"--------------------------\n";
std::cout<<"----Funkcja remove(3)-----\n";
std::cout<<"--------------------------\n";
display_list(listSTL);
std::cout<<std::endl;
std::cout<<std::endl;
std::cout<<"=================================\n";
//===Kolejka - projekt===
Queue<int> que;
std::cout<<"====Kolejka - projekt:====\n";
std::cout<<"--------------------------\n";
std::cout<<"----Funkcja dequeue()-----\n";
std::cout<<"--------------------------\n";
que.dequeue();
que.display();
que.enqueue(1);
std::cout<<"--------------------------\n";
std::cout<<"----Funkcja enqueue(1)----\n";
std::cout<<"--------------------------\n";
que.display();
que.enqueue(49);
std::cout<<"--------------------------\n";
std::cout<<"----Funkcja enqueue(49)---\n";
std::cout<<"--------------------------\n";
que.display();
que.enqueue(2);
std::cout<<"--------------------------\n";
std::cout<<"----Funkcja enqueue(2)----\n";
std::cout<<"--------------------------\n";
que.display();
que.dequeue();
std::cout<<"--------------------------\n";
std::cout<<"----Funkcja dequeue()-----\n";
std::cout<<"--------------------------\n";
que.display();
que.dequeue();
std::cout<<"--------------------------\n";
std::cout<<"----Funkcja dequeue()-----\n";
std::cout<<"--------------------------\n";
que.display();
que.enqueue(15);
std::cout<<"--------------------------\n";
std::cout<<"----Funkcja enqueue(15)---\n";
std::cout<<"--------------------------\n";
que.display();
que.enqueue(8);
std::cout<<"--------------------------\n";
std::cout<<"----Funkcja enqueue(8)----\n";
std::cout<<"--------------------------\n";
que.display();
std::cout<<std::endl<<std::endl;
//===Kolejka - STL===
std::queue<int> queSTL;
std::cout<<"======Kolejka - STL:======\n";
queSTL.push(1);
std::cout<<"--------------------------\n";
std::cout<<"----Funkcja enqueue(1)----\n";
std::cout<<"--------------------------\n";
display_queue(queSTL);
queSTL.push(49);
std::cout<<"--------------------------\n";
std::cout<<"----Funkcja enqueue(49)---\n";
std::cout<<"--------------------------\n";
display_queue(queSTL);
queSTL.push(2);
std::cout<<"--------------------------\n";
std::cout<<"----Funkcja enqueue(2)----\n";
std::cout<<"--------------------------\n";
display_queue(queSTL);
queSTL.pop();
std::cout<<"--------------------------\n";
std::cout<<"----Funkcja dequeue()-----\n";
std::cout<<"--------------------------\n";
display_queue(queSTL);
queSTL.pop();
std::cout<<"--------------------------\n";
std::cout<<"----Funkcja dequeue()-----\n";
std::cout<<"--------------------------\n";
display_queue(queSTL);
queSTL.push(15);
std::cout<<"--------------------------\n";
std::cout<<"----Funkcja enqueue(15)---\n";
std::cout<<"--------------------------\n";
display_queue(queSTL);
queSTL.push(8);
std::cout<<"--------------------------\n";
std::cout<<"----Funkcja enqueue(8)----\n";
std::cout<<"--------------------------\n";
display_queue(queSTL);
std::cout<<std::endl<<std::endl;
std::cout<<"=================================\n";
//===Kolejka priopytetowa - proj===
PriorityQueue<int> quep;
std::cout<<"==Kolejka (prio) - proj:==\n";
std::cout<<"--------------------------\n";
std::cout<<"---Funkcja dequeue()------\n";
std::cout<<"--------------------------\n";
quep.dequeue();
quep.display();
std::cout<<"--------------------------\n";
std::cout<<"---Funkcja enqueue(6,2)---\n";
std::cout<<"--------------------------\n";
quep.enqueue(6,2);
quep.display();
std::cout<<"--------------------------\n";
std::cout<<"---Funkcja enqueue(1,7)---\n";
std::cout<<"--------------------------\n";
quep.enqueue(1,7);
quep.display();
std::cout<<"--------------------------\n";
std::cout<<"---Funkcja enqueue(10,4)--\n";
std::cout<<"--------------------------\n";
quep.enqueue(10,4);
quep.display();
std::cout<<"--------------------------\n";
std::cout<<"---Funkcja dequeue()------\n";
std::cout<<"--------------------------\n";
quep.dequeue();
quep.display();
std::cout<<"--------------------------\n";
std::cout<<"---Funkcja dequeue()------\n";
std::cout<<"--------------------------\n";
quep.dequeue();
quep.display();
std::cout<<std::endl<<std::endl;
//===Kolejka priopytetowa - STL===
std::priority_queue<int> quepSTL;
std::cout<<"==Kolejka (prio) - STL:===\n";
std::cout<<"--------------------------\n";
std::cout<<"----Funkcja enqueue(6)----\n";
std::cout<<"--------------------------\n";
quepSTL.push(6);
display_priority_queue(quepSTL);
std::cout<<"--------------------------\n";
std::cout<<"----Funkcja enqueue(1)----\n";
std::cout<<"--------------------------\n";
quepSTL.push(1);
display_priority_queue(quepSTL);
std::cout<<"--------------------------\n";
std::cout<<"----Funkcja enqueue(10)---\n";
std::cout<<"--------------------------\n";
quepSTL.push(10);
display_priority_queue(quepSTL);
std::cout<<"--------------------------\n";
std::cout<<"----Funkcja dequeue()-----\n";
std::cout<<"--------------------------\n";
quepSTL.pop();
display_priority_queue(quepSTL);
std::cout<<"--------------------------\n";
std::cout<<"----Funkcja dequeue()-----\n";
std::cout<<"--------------------------\n";
quepSTL.pop();
display_priority_queue(quepSTL);
std::cout<<std::endl<<std::endl;
std::cout<<"=================================\n";
//===Stos - projekt===
Stack<int> stos;
std::cout<<"======Stos - projekt:=====\n";
std::cout<<"--------------------------\n";
std::cout<<"------Funkcja pop()-------\n";
std::cout<<"--------------------------\n";
stos.pop();
stos.display();
stos.push(1);
std::cout<<"--------------------------\n";
std::cout<<"------Funkcja push(1)-----\n";
std::cout<<"--------------------------\n";
stos.display();
stos.push(10);
std::cout<<"--------------------------\n";
std::cout<<"------Funkcja push(10)----\n";
std::cout<<"--------------------------\n";
stos.display();
stos.push(100);
std::cout<<"--------------------------\n";
std::cout<<"------Funkcja push(100)---\n";
std::cout<<"--------------------------\n";
stos.display();
stos.pop();
std::cout<<"--------------------------\n";
std::cout<<"------Funkcja pop()-------\n";
std::cout<<"--------------------------\n";
stos.display();
std::cout<<std::endl<<std::endl;
//===Stos - STL===
std::stack<int> stosSTL;
std::cout<<"========Stos - STL:=======\n";
stosSTL.push(1);
std::cout<<"--------------------------\n";
std::cout<<"------Funkcja push(1)-----\n";
std::cout<<"--------------------------\n";
display_stack(stosSTL);
stosSTL.push(10);
std::cout<<"--------------------------\n";
std::cout<<"------Funkcja push(10)----\n";
std::cout<<"--------------------------\n";
display_stack(stosSTL);
stosSTL.push(100);
std::cout<<"--------------------------\n";
std::cout<<"------Funkcja push(100)---\n";
std::cout<<"--------------------------\n";
display_stack(stosSTL);
stosSTL.pop();
std::cout<<"--------------------------\n";
std::cout<<"------Funkcja pop()-------\n";
std::cout<<"--------------------------\n";
display_stack(stosSTL);
std::cout<<std::endl<<std::endl;
std::cout<<"=================================\n";
//===Hashmapa - projekt===
Map<std::string,int> map;
std::cout<<"====Hashmapa - projekt:===\n";
map.insert("kot",5);
std::cout<<"--------------------------\n";
std::cout<<"--Funkcja insert(kot, 5)--\n";
std::cout<<"--------------------------\n";
std::cout<<"Klucz: kot\n";
map.display("kot");
map.insert("pies",15);
std::cout<<"--------------------------\n";
std::cout<<"-Funkcja insert(pies, 15)-\n";
std::cout<<"--------------------------\n";
std::cout<<"Klucz: pies\n";
map.display("pies");
std::cout<<"--------------------------\n";
std::cout<<"---Biezacy stan Hashmapy--\n";
std::cout<<"--------------------------\n";
std::cout<<map["kot"]<<" "<<map["pies"]<<std::endl;
map.remove("pies");
std::cout<<"--------------------------\n";
std::cout<<"---Funkcja remove(pies)---\n";
std::cout<<"--------------------------\n";
std::cout<<map["kot"]<<" "<<map["pies"]<<std::endl;
std::cout<<std::endl<<std::endl;
//===Hashmapa - projekt===
std::map<std::string,int> mapSTL;
std::cout<<"====Hashmapa - projekt:===\n";
mapSTL.insert(std::pair<std::string,int>("kot", 5));
std::cout<<"--------------------------\n";
std::cout<<"--Funkcja insert(kot, 5)--\n";
std::cout<<"--------------------------\n";
display_map(mapSTL);
mapSTL.insert(std::pair<std::string,int>("pies", 15));
std::cout<<"--------------------------\n";
std::cout<<"-Funkcja insert(pies, 15)-\n";
std::cout<<"--------------------------\n";
display_map(mapSTL);
std::cout<<"--------------------------\n";
std::cout<<"---Biezacy stan Hashmapy--\n";
std::cout<<"--------------------------\n";
display_map(mapSTL);
mapSTL.erase("pies");
std::cout<<"--------------------------\n";
std::cout<<"---Funkcja erase(pies)---\n";
std::cout<<"--------------------------\n";
display_map(mapSTL);
std::cout<<std::endl<<std::endl;
std::cout<<"=================================\n";
return 0;
}
| true |
8d636285127905e8ffa55d13c058a21fa4fc67fb | C++ | hyemmie/algorithm_study | /Backjoon/DevideConquer/12846.cpp | UTF-8 | 1,757 | 3.3125 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <vector>
#include <cmath>
#include <utility>
#include <cstdlib>
using namespace std;
vector<long> dailyProfit(0,0);
// int로 하면 메모리 초과
long maximumProfit(long start, long end) {
// 기저 사례
if (start == end) {
return dailyProfit[start];
}
long mid = (start + end) / 2;
// 반으로 나눠서 각개격파
long area = max(maximumProfit(start, mid), maximumProfit(mid + 1, end));
// 가운데에 걸친 경우
long left = mid;
long right = mid + 1;
long currentHeight = min(dailyProfit[left], dailyProfit[right]);
// 확장 전 가운데 걸린 두 칸짜리 사각형을 후보에!
area = max(area, currentHeight * 2);
while(start < left || right < end) {
// 오른쪽으로 확장하는 경우 : 왼쪽 끝까지 이미 확장했거나 오른쪽이 왼쪽보다 클 때
if(right < end && (start == left || dailyProfit[left-1] < dailyProfit[right+1])) {
++right;
currentHeight = min(currentHeight, dailyProfit[right]);
}
// 왼쪽으로 확장하는 경우 : 오른쪽 끝까지 이미 확장했거나 왼쪽이 오른쪽보다 클 때
else {
--left;
currentHeight = min(currentHeight, dailyProfit[left]);
}
// 양쪽에서 구한 넓이, 확장되면서 변하는 넓이들 중에서 가장 큰 값으로 업데이트
area = max(area, currentHeight * (right - left + 1));
}
return area;
}
int main() {
long n;
cin >> n;
for (long i = 0; i < n; i++) {
long input;
cin >> input;
dailyProfit.push_back(input);
}
cout << maximumProfit(0, n - 1) << endl;
}
| true |
c5acb2a41c451998d67a3bea2da97b8b8623bfc0 | C++ | bogdan-ivan/quantumcity | /hightrafficdetector/hightrafficdetector.ino | UTF-8 | 2,212 | 2.75 | 3 | [] | no_license | // LCD
#include <LiquidCrystal.h>
const int rs = 1, en = 2, d4 = 4, d5 = 5, d6 = 6, d7 = 7;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
// LEDs
int redLed = 33;
int yellowLed = 32;
int greenLed = 30;
// movement
const int sensor = 50;
// proximity
const int trigPin = 51;
const int echoPin = 52;
long duration;
int distance;
int threshold1 = 0;
int threshold2 = 5;
int threshold3 = 10;
int counter = 0;
int busy = 0;
void setup()
{
// lcd
lcd.begin(16,2);
// Leds
pinMode(redLed, OUTPUT);
pinMode(yellowLed, OUTPUT);
pinMode(greenLed, OUTPUT);
// movement
pinMode(sensor, INPUT);
// proximity
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop()
{
// digitalWrite(trigPin, LOW);
// delayMicroseconds(2);
// digitalWrite(trigPin, HIGH);
// delayMicroseconds(10);
// digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance= duration*0.034/2;
// lcd.print("Distance: ");
// lcd.print(distance);
// lcd.print("cm");
// delay(2000);
// lcd.clear();
lcd.print("Looking for cars...");
if(counter < 6)
{
digitalWrite(greenLed,LOW);
digitalWrite(redLed,HIGH);
digitalWrite(yellowLed,LOW);
}
if(counter < 4)
{
digitalWrite(greenLed,LOW);
digitalWrite(redLed,LOW);
digitalWrite(yellowLed,HIGH);
}
if(counter < 2)
{
digitalWrite(greenLed,HIGH);
digitalWrite(redLed,LOW);
digitalWrite(yellowLed,LOW);
}
bool Detection = digitalRead(sensor);
if(Detection==HIGH)
{
lcd.clear();
lcd.print("Car detected ");
lcd.print(counter);
delay(500);
counter = counter + 1;
}
if(Detection==LOW)
{
delay(500);
counter = counter - 1;
}
if(counter > threshold1)
{
busy = 0;
}
if (counter > threshold2)
{
busy = 1;
}
if (counter > threshold2)
{
busy = 2;
}
delay(1000);
lcd.clear();
// lcd.print("Hackathon 2019");
// delay(3000);
//
// lcd.setCursor(2,1);
// lcd.print("Quantum team");
// delay(3000);
//
// lcd.clear();
//
// lcd.blink();
// delay(3000);
// lcd.setCursor(7,1);
// delay(3000);
// lcd.noBlink();
//
// lcd.cursor();
// delay(3000);
// lcd.noCursor();
//
// lcd.clear();
}
| true |
dc25dbc40e721cba5ecbe5e43e23be52d0ad2065 | C++ | martin-carrasco/online-judge-solutions | /CSES/1163.cpp | UTF-8 | 648 | 2.515625 | 3 | [] | no_license | #include "bits/stdc++.h"
using namespace std;
using ii = pair<int, int>;
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
set<int> intervals;
multiset<int> lengths;
int x, n;
cin >> x >> n;
intervals.insert(0);
intervals.insert(x);
lengths.insert(x);
for(int i = 0;i < n;i++){
int split;
cin >> split;
auto it = intervals.upper_bound(split);
int up = *it;
--it;
int down = *it;
lengths.erase(lengths.find(up-down));
intervals.insert(split);
lengths.insert(abs(down - split));
lengths.insert(abs(up - split));
auto res = lengths.end();
--res;
cout << *res << " ";
}
cout << "\n";
return 0;
}
| true |
39c7f6fd3823965474e83c6b50003f2c9f5dbc46 | C++ | GH2005/myLeetcodeSolutions | /289. Game of Life.cpp | UTF-8 | 984 | 3.03125 | 3 | [] | no_license | // idea by Stefan Pochmann
class Solution {
public:
void gameOfLife(vector<vector<int>>& board) {
int height = board.size(), width = height > 0 ? board[0].size() : 0;
if (height == 0 || width == 0) return;
// update the state using the second bit
for (int centerY = 0; centerY < height; centerY++)
for (int centerX = 0; centerX < width; centerX++) {
int count = - board[centerY][centerX];
for (int y = max(0, centerY-1); y < min(height, centerY+2); y++)
for (int x = max(0, centerX-1); x < min(width, centerX+2); x++)
count += board[y][x] & 1;
if ((count | board[centerY][centerX]) == 3)
board[centerY][centerX] |= 2;
}
// right shift to let the new state take effect
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
board[y][x] >>= 1;
return;
}
};
| true |
f859c302a2e119040e9a56a0baf5a337ed911e71 | C++ | cskilbeck/SearchClip | /SearchClip/Util.cpp | UTF-8 | 3,773 | 2.953125 | 3 | [
"MIT"
] | permissive | //////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include <algorithm>
#include <functional>
#include <cctype>
#include <locale>
//////////////////////////////////////////////////////////////////////
wstring GString(DWORD id)
{
WCHAR str[MAX_LOADSTRING];
LoadString(GetModuleHandle(NULL), id, str, MAX_LOADSTRING);
return str;
}
//////////////////////////////////////////////////////////////////////
wstring Format(WCHAR const *fmt, ...)
{
va_list v;
va_start(v, fmt);
WCHAR buffer[8192];
_vsnwprintf_s(buffer, ARRAYSIZE(buffer) - 1, fmt, v);
return buffer;
}
//////////////////////////////////////////////////////////////////////
wstring Format(wstring const &str, ...)
{
va_list v;
wstring t(str);
va_start(v, t);
WCHAR buffer[8192];
_vsnwprintf_s(buffer, ARRAYSIZE(buffer) - 1, str.c_str(), v);
return buffer;
}
//////////////////////////////////////////////////////////////////////
wstring Replace(wstring const &str, wstring const &from, wstring const &to)
{
size_t start_pos = 0;
wstring newStr = str;
size_t len = to.size();
while((start_pos = newStr.find(from, start_pos)) != wstring::npos) {
newStr.replace(start_pos, from.size(), to);
start_pos += len;
}
return newStr;
}
//////////////////////////////////////////////////////////////////////
wstring GetExecutableFilename()
{
WCHAR filename[32768];
filename[0] = 0;
filename[ARRAYSIZE(filename) - 1] = 0;
GetModuleFileName(GetModuleHandle(NULL), filename, ARRAYSIZE(filename) - 1);
return filename;
}
//////////////////////////////////////////////////////////////////////
wstring UpperCase(wstring const &str)
{
wstring upr(str);
std::transform(upr.begin(), upr.end(), upr.begin(), ::toupper);
return upr;
}
//////////////////////////////////////////////////////////////////////
// trim from start
wstring ltrim(wstring const &str)
{
wstring s(str);
s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
return s;
}
//////////////////////////////////////////////////////////////////////
// trim from end
wstring rtrim(wstring const &str)
{
wstring s(str);
s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
return s;
}
//////////////////////////////////////////////////////////////////////
// trim from both ends
wstring trim(wstring const &str)
{
return ltrim(rtrim(str));
}
//////////////////////////////////////////////////////////////////////
bool GetClipboardAsString(wstring &str)
{
bool gotIt = false;
OpenClipboard(NULL);
HANDLE clip = GetClipboardData(CF_UNICODETEXT);
if(clip != NULL) {
HANDLE h = GlobalLock(clip);
if(h != NULL) {
WCHAR const *c = (WCHAR *)clip;
size_t length = wcsnlen_s(c, 4096);
WCHAR *buffer = new WCHAR[length + 1];
CopyMemory(buffer, c, sizeof(WCHAR) * length);
buffer[length] = (WCHAR)0;
GlobalUnlock(clip);
str = buffer;
gotIt = true;
}
}
CloseClipboard();
return gotIt;
}
//////////////////////////////////////////////////////////////////////
wstring URLSanitize(wstring const &str)
{
wstring OK(TEXT("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~:/?#@!$&'()*,;="));
wstring result;
size_t l = str.size();
for(size_t i = 0; i < l; ++i) {
if(OK.find(str[i]) != wstring::npos) {
result += str[i];
} else {
result += Format(TEXT("%%%02X"), str[i]); // TODO: deal with Unicode properly
}
}
return result;
} | true |
6f6a7d2f69ba4ab44e4556f3a9832ae276d6a5dc | C++ | optimus20/morse | /苏钰迪 开源硬件作业/7月4号第二次作业/qiduanguan.ino | UTF-8 | 1,894 | 3.046875 | 3 | [] | no_license | void setup()
{
pinMode(1, OUTPUT);
pinMode(2, OUTPUT);
pinMode(3, OUTPUT);
pinMode(4, OUTPUT);
Serial.begin(9600);
}
int income=0;
void loop()
{
if(Serial.available()>0)
{
income=Serial.read();
switch(income)
{
case'0':
show0();
break;
case'1':
show1();
break;
case'2':
show2();
break;
case'3':
show3();
break;
case'4':
show4();
break;
case'5':
show5();
break;
case'6':
show6();
break;
case'7':
show7();
break;
case'8':
show8();
break;
case'9':
show9();
break;
}
}
}
void show0()
{
digitalWrite(1,LOW);
digitalWrite(2,LOW);
digitalWrite(3,LOW);
digitalWrite(4,LOW);
delay(10);
}
void show1()
{
digitalWrite(1,HIGH);
digitalWrite(2,LOW);
digitalWrite(3,LOW);
digitalWrite(4,LOW);
delay(10);
}
void show2()
{
digitalWrite(1,LOW);
digitalWrite(2,HIGH);
digitalWrite(3,LOW);
digitalWrite(4,LOW);
delay(10);
}
void show3()
{
digitalWrite(1,HIGH);
digitalWrite(2,HIGH);
digitalWrite(3,LOW);
digitalWrite(4,LOW);
delay(10);
}
void show4()
{
digitalWrite(1,LOW);
digitalWrite(2,LOW);
digitalWrite(3,HIGH);
digitalWrite(4,LOW);
delay(10);
}
void show5()
{
digitalWrite(1,HIGH);
digitalWrite(2,LOW);
digitalWrite(3,HIGH);
digitalWrite(4,LOW);
delay(10);
}
void show6()
{
digitalWrite(1,LOW);
digitalWrite(2,HIGH);
digitalWrite(3,HIGH);
digitalWrite(4,LOW);
delay(10);
}
void show7()
{
digitalWrite(1,HIGH);
digitalWrite(2,HIGH);
digitalWrite(3,HIGH);
digitalWrite(4,LOW);
delay(10);
}
void show8()
{
digitalWrite(1,LOW);
digitalWrite(2,LOW);
digitalWrite(3,LOW);
digitalWrite(4,HIGH);
delay(10);
}
void show9()
{
digitalWrite(1,HIGH);
digitalWrite(2,LOW);
digitalWrite(3,LOW);
digitalWrite(4,HIGH);
delay(10);
} | true |
4d280d0b66c79be62456cc4c2b2dbac200c24468 | C++ | james-sungjae-lee/2018_CPP | /STUDY/Study0531/find.cpp | UTF-8 | 478 | 3.140625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
using namespace std;
int main(int argc, char const *argv[]) {
string fruits[5] = {"사과", "토마토", "배", "수박", "키위"};
std::vector<string> vec(&fruits[0], &fruits[5]);
std::vector<string>::iterator it;
it = find(vec.begin(), vec.end(), "수박");
if(it != vec.end()){
cout << "수박이 " << distance(vec.begin(), it )+1 << "번째 에 있습니다.";
}
return 0;
}
| true |
e32004c48a51b3a19988d660a78dafcedf148c59 | C++ | busebd12/InterviewPreparation | /LeetCode/C++/General/Easy/ComplimentOfABase10Integer/main.cpp | UTF-8 | 1,425 | 3.859375 | 4 | [
"MIT"
] | permissive | #include <algorithm>
#include <iostream>
#include <string>
using namespace std;
/*
* Approach: we convert the input number to a string representation of its bits.
* Then, for each bit, if the bit is a one, we make it a zero and vice versa.
* Finally, we convert the string back into a decimal number and return that number.
*
* Time complexity: O(b) [where b is the number of bits in the input number]
* Space complexity: O(b)
*/
int binaryToDecimal(string complimentString)
{
int decimal=0;
int n=int(complimentString.size());
int power=0;
for(int i=0;i<n;++i)
{
if(complimentString[i]=='0')
{
complimentString[i]='1';
}
else
{
complimentString[i]='0';
}
}
for(int i=n-1;i>=0;--i)
{
if(complimentString[i]=='1')
{
int value=1;
for(int count=0;count<power;++count)
{
value*=2;
}
decimal+=value;
}
power++;
}
return decimal;
}
int bitwiseComplement(int N)
{
if(N==0)
{
return 1;
}
string complimentString{};
while(N)
{
int digit=N & 1;
complimentString+=(digit + '0');
N >>= 1;
}
reverse(complimentString.begin(), complimentString.end());
int compliment=binaryToDecimal(complimentString);
return compliment;
} | true |
328d34eb3e2eeba148b65985020ccfb6566ef0a9 | C++ | lior035/CPP-WorkoutGym | /healthClub.cpp | UTF-8 | 10,374 | 3.40625 | 3 | [] | no_license | #include <iostream>
using namespace std;
#include <string.h>
#include <typeinfo.h>
#include "healthClub.h"
#include "healthClubException.h"
HealthClub::HealthClub(char* name): devices(0) //constructor
{
if (name!=NULL)
this->setName(name);
trainers = NULL;
iTrainer = 0;
}
HealthClub::HealthClub(ifstream & inFile)//constructor by file
{
//assumption - the file is open and set to be readen
//Part 1- reading the club name and length
this->readClubName (inFile);
//Part 2 - reading and creating the trainer array from the file
this->readTrainer (inFile);
//Part 3 - reading and creating the device array from the file
this->readDevice (inFile);
}
void HealthClub:: readClubName (ifstream & inFile) // private function
{
//assumption - the file is open to be readen
int length;
inFile.read((char*)&length,sizeof(length)); //reading the length of the club's name
char* name = new char [length+1]; // allocating name string
inFile.read((char*)name, length);//read the name of the club from the file
name[length] = '\0';
this->setName(name);
delete [] name;
}
void HealthClub:: readTrainer (ifstream & inFile)
{
//assumption - the file is open and set on the right place
int i;
int totalTrainer;
inFile.read((char*)&totalTrainer, sizeof(totalTrainer)); // reading the total amount of trainers in the club
this->iTrainer = totalTrainer;
this->trainers = new Trainer* [iTrainer]; //allocating trainer * array
//creating the trainers according the info in the file
for (i = 0; i<iTrainer; i++)
*(this->trainers+i) = new Trainer (inFile);
}
void HealthClub::readDevice (ifstream & inFile)
{
//assumption - the file is open and set on the right place
int i;
int Serial;
inFile.read((char*)&Serial, sizeof(Serial));//reading the serial number of device
Device::SetSerialNum(Serial);
int totalDevice;
inFile.read((char*)&totalDevice, sizeof(totalDevice)); //reading the total amount of devices in the club
this->devices.setLogicSize(totalDevice); //allocating device* array
this->devices.getArray() = new Device*[totalDevice];
//creating the devices according the info in the file
for (i = 0; i<this->devices.getLogicSize(); i++)
{
int length = 3;
char* type = new char [length+1]; //indicate the type of the current device
inFile.read((char*)type,length); // read the type of current device from the file
type[length]= '\0';
if (strncmp(type,typeid(AerobicDevice).name()+6, length) == 0)
{
Device* d = new AerobicDevice (inFile); // create from the file new aerobic device
this->devices.replaceCell(i,d);
}
else if (strncmp(type,typeid(PowerDevice).name()+6,length) == 0)
{
Device* d = new PowerDevice (inFile); // create from the file new Power device
this->devices.replaceCell(i,d);
}
}
}
HealthClub:: HealthClub(const HealthClub& clubToCopy): devices(clubToCopy.devices.getLogicSize()), trainers(NULL)//copy constructor
{
*this = clubToCopy;
}
//operator = overload for private use only
HealthClub& HealthClub:: operator= (const HealthClub & h)
{
//assumption - devices and trainers will always be NULL at this point - since the operator =
//is being used only in the copy onstructor
int i;
this->iTrainer = h.iTrainer;
this->trainers = new Trainer * [iTrainer];
for (i = 0; i<devices.getLogicSize(); i++)
{
Device * d = h.devices[i]->clone();
this->devices.replaceCell(i,d);
}
for (i = 0; i<iTrainer; i++)
this->trainers[i] = new Trainer (*(h.trainers[i]));
this->setName(h.getClubName());
return *this;
}
//sets
void HealthClub:: setName (const char * name)
{
strncpy (clubName, name,LengthTotal);
clubName[LengthTotal] = '\0';
}
//gets
const char* HealthClub:: getClubName () const
{
return clubName;
}
int HealthClub:: getTotalTrainerCount () const
{
return iTrainer;
}
int HealthClub:: getTotalDeviceCount () const
{
return devices.getLogicSize();
}
//2 ways for getting pointer for a specific trainer:
Trainer* HealthClub:: getTrainer (const char* tName) const
{
int i;
if (iTrainer == 0)
{
cout<<"There are no trainers at all in the club"<<endl;
return NULL;
}
for (i = 0; i<iTrainer; i++)
{
if (strcmp(trainers[i]->getName(), tName) == 1)
return trainers[i];
}
cout<<"No trainer with that name"<<endl;
return NULL;
}
Trainer* HealthClub:: getTrainer (int index) const throw(HealthClubException*)
{
if (index>=iTrainer)
{
HealthClubException * hce = new HealthClubException(NULL,INDEX_OUT_OF_BOUNDRIES);
throw hce;
}
return trainers[index];
}
//2 ways for getting pointer for a specific device:
Device* HealthClub:: getDevice (const char* dName) const
{
int i;
if (devices.getLogicSize() == 0)
{
cout<<"There are no devices at all in the club"<<endl;
return NULL;
}
for (i=0; i<devices.getLogicSize(); i++)
{
if (strcmp(devices[i]->getName(),dName) == 1)
return devices[i];
}
cout<<"No device with that name"<<endl;
return NULL;
}
Device* HealthClub:: getDevice (int index) const
{
//see comment 6 (-2)
if (index>=devices.getLogicSize())
return NULL;
return devices[index];
}
//add
int HealthClub:: addTrainer (char* newTrainerName)throw(HealthClubException* )
{
if (iTrainer>=100)
{
HealthClubException* hce = new HealthClubException(newTrainerName,REGISTER_FAILED_CLUB_IS_FULL) ;
throw hce;
}
else if (trainerIsAlreadyIn(this->trainers, this->iTrainer, newTrainerName))
{
HealthClubException* hce = new HealthClubException (newTrainerName, REGISTER_FAILED_CANNOT_DUPLICATE_TRAINER);
throw hce;
}
else
{
(*this).extandTrainersArrey(newTrainerName);
return REGISTER_SUCCEED;
}
}
//2 private sub method for addTrainer to use:
bool HealthClub:: trainerIsAlreadyIn(Trainer** trainers, int iTrainer, const char* trainerName)const
{
int i =0;
if (iTrainer == 0) //Means that there are not any trainers (now - trainers points to NULL)
return false;
for (i=0; i<iTrainer; i++)
{
if (strcmp(trainerName, trainers[i]->getName())==0)
return true;
}
return false;
}
void HealthClub:: extandTrainersArrey(char* newTrainerName)
{
//see comment 12 (-2)
//see comment 19 (-3)
int i = 0;
Trainer ** newArr;
this->iTrainer++;
newArr = new Trainer * [this->iTrainer];
for (i=0; i<this->iTrainer-1; i++)
{
newArr[i] = new Trainer;
newArr[i]->setName(this->trainers[i]->getName());
newArr[i]->getProgram() = this->trainers[i]->getProgram();
}
newArr[i] = new Trainer;
newArr[i]->setName(newTrainerName);
newArr[i]->setProgram();
for (i=0; i<iTrainer-1; i++)
delete this->trainers[i];
delete [] this->trainers;
this->trainers = newArr;
}
bool HealthClub :: addDevice (Device* newDevice)
{
if (newDevice == NULL)
return false;
if (deviceIsAlreadyIn(this->devices, newDevice))
{
cout<<newDevice->getName()<<" is already at our club"<< endl;
return false;
}
else
{
this->extandDevicesArrey(this->devices,newDevice);
return true;
}
}
//2 private sub method for addDevice to use:
bool HealthClub:: deviceIsAlreadyIn(Array<Device>&devices, Device* newDevice) const
{
int i = 0;
if (devices.getLogicSize() == 0) //Means that there are not any devices (now - devices points to NULL)
return false;
for (i = 0; i<devices.getLogicSize(); i++)
{
if (strcmp(newDevice->getName(), devices[i]->getName())==0)
return true;
}
return false;
}
void HealthClub:: extandDevicesArrey(Array<Device>& arr, Device* newDevice)
{
int i = 0;
Device** newArr;
int total = this->devices.getLogicSize();
total++;
newArr = new Device * [total];
for (i=0; i<total-1; i++)
{
newArr[i] = arr[i]->clone();
}
//Device::SetSerialNum(current->iDevice-1, '-');
//not needed - the son make sure that while cloning the SerialNum will not be increased
newArr[i] = newDevice->clone();
for (i=0; i<this->devices.getLogicSize();i++)
delete this->devices[i];
devices.setLogicSize(devices.getLogicSize()+1);
for (i=0; i<total; i++)
arr.replaceCell(i, newArr[i]);
}
//operator << overload by friend function
ostream& operator<< (ostream & os, const HealthClub& h)
{
int i;
os<<"Club name : " <<h.clubName<<endl<<endl;
os<<"Number of trainers in the club : "<<h.iTrainer<<endl;
if (h.iTrainer!=0)
os<<"Trainers : "<<endl;
for (i= 0; i<h.iTrainer; i++)
os<<i+1<<"). "<<*(h.trainers)[i];
os<<endl;
int total = h.devices.getLogicSize();
os<<"Number of devices in the club : "<<total<<endl;
if (total!=0)
os<<"Devices : "<<endl;
for (i= 0; i<total; i++)
os<<i+1<<"). "<<(*(h.devices[i]));
return os;
}
//-----------------------------------------------------------------
void HealthClub:: saveToFile (const HealthClub & hToSave, ofstream & outFile) const
{
//assumption - the file is open and ready to be use
int i, length, totalTrainer, totalDevice;
//writing the club name
length = strlen(hToSave.getClubName());
outFile.write((const char *) &length, sizeof (length)); //writing the length of the club name
outFile.write((const char*)hToSave.getClubName(), length); // writing the name of the club
//writing the trainers detaile (only name):
totalTrainer = hToSave.getTotalTrainerCount();
outFile.write((const char*) &totalTrainer, sizeof (totalTrainer));//writing the amount of trainers
for (i = 0; i<totalTrainer; i++)
{
char * tName = hToSave.getTrainer(i)->getName(); //excption is not needed here since the i is alyays in the boundries
length = strlen(tName);
outFile.write((const char *)&length, sizeof(length));//writing the length of the name of current trainer
outFile.write((const char *)tName, length); //writing the name of current trainer
}
int Serial = Device::GetSerialNum();
outFile.write((const char *)&Serial, sizeof(Serial)); //writing the last serial number
//writing the device detail:
totalDevice = hToSave.devices.getLogicSize();
outFile.write((const char*)&totalDevice, sizeof (totalDevice)); // writing the amount of devices
for (i = 0; i<totalDevice; i++)
{
Device* d = hToSave.devices[i]; // getting the current device to save
d->saveDeviceToFile(outFile); //will save to the file: 1)device type, 2)serial of current device
// 3) device length, 4)device name, 5)extra information according the device type
}
}
//---------------------------------------------------------------------
HealthClub::~HealthClub() // destructor
{
delete [] trainers;
}//here it will enter the Array<T> destructor | true |
a67da6c6fc6a7365fcd6198a4dcca8a0c4782643 | C++ | k1rrra/Laba-2 | /Laba 7.1.cpp | UTF-8 | 1,020 | 3.078125 | 3 | [] | no_license | #include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
int sum(int x, int y)
{
int sum;
sum = x + y;
return sum;
}
void sum(int a1, int a2, int b1, int b2)
{
int sum1, sum2;
sum1 = a1 + b1;
sum2 = a2 + b2;
if (sum2 > 0)
{
cout << sum1<<"+"<<sum2<<"i";
}
else
{
cout << sum1<<sum2<<"i";
}
}
int main(int argc, char** argv) {
setlocale(LC_ALL,"Russian");
setlocale(LC_ALL,"rus");
int a,b,a1,a2,b1,b2;
int c;
cout<<"a+b \n";
cout<<"a = ";
cin>>a;
cout<<"b = ";
cin>>b;
int s1 = sum(a,b);
cout<<"a+b= "<<s1<<"\n";
cout<<"z1 = a1+b1 i, z2 = a2+b2 i \n";
cout<<"a1 = ";
cin>>a1;
cout<<"b1 = ";
cin>>b1;
cout<<"a2 = ";
cin>>a2;
cout<<"b2 = ";
cin>>b2;
cout<<"z1 + z2 = ";
sum(a1,b1,a2,b2);
cin>>c;
return 0;
}
| true |
06ff544237d9906211ff44c31e3e2c8f406f39b6 | C++ | justinjeong5/Implementation | /queue_circularArray.cpp | UTF-8 | 2,172 | 3.65625 | 4 | [] | no_license | /*
* 2019.7.4
* data structure implementation - queue_circularArray
*/
#include <iostream>
#include <string>
using namespace std;
#define endl '\n'
class QueueCirArr {
public:
int q_size, capacity;
int first, last;
int *queue;
QueueCirArr() {
q_size = 0;
capacity = 8;
first = 0;
last = 0;
queue = new int[capacity];
}
~QueueCirArr() {}
void push(int value) {
if (q_size == capacity) {
capacity *= 2;
int *temp = new int[capacity];
for (int i = 0; i < capacity / 2; i++) {
temp[i] = queue[i];
}
queue = temp;
if (last < first)
last = first + q_size - 1;
}
queue[last] = value;
last = (last + 1) % (capacity + 1);
q_size++;
}
int front() {
if (q_size == 0) return -1;
return queue[first];
}
int back() {
if (q_size == 0) return -1;
return queue[(last - 1) % (capacity + 1)];
}
void pop() {
if (q_size == 0) return;
q_size--;
first = (first + 1) % (capacity + 1);
}
bool empty() {
return !q_size;
}
int size() {
return q_size;
}
};
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
QueueCirArr queue;
int a;
cin >> a;
for (int i = 0; i < a; i++) {
string input;
cin >> input;
if (input == "push") {
int a;
cin >> a;
queue.push(a);
} else if (input == "pop") {
if (queue.empty())
cout << -1 << endl;
else cout << queue.front() << endl;
queue.pop();
} else if (input == "size")
cout << queue.size() << endl;
else if (input == "empty") {
if (queue.empty())
cout << 1 << endl;
else
cout << 0 << endl;
} else if (input == "front")
cout << queue.front() << endl;
else if (input == "back")
cout << queue.back() << endl;
}
return 0;
} | true |
84f10fa0aa0969463f57f78dfd258293b07014ef | C++ | YegangWu/Alogirthms | /encoding/node.h | UTF-8 | 375 | 3.15625 | 3 | [] | no_license | #ifndef INCLUDE_NODE_H
#define INCLUDE_NODE_H
class Node
{
public:
char d_c;
int d_freq;
Node* left;
Node* right;
Node(char c, int freq, Node* left, Node* right): d_c(c), d_freq(freq), left(left), right(right) {}
friend struct greater;
};
struct greater
{
bool operator()(const Node* lhs, const Node* rhs)
{
return lhs->d_freq > rhs->d_freq;
}
};
#endif
| true |
1bd72c180d3953d4be08bc300553430570475959 | C++ | tabvn/ued | /c++/part1/bai16.cpp | UTF-8 | 710 | 3.625 | 4 | [] | no_license | #include <iostream>
#include <math.h>
using namespace std;
bool isPrime(int n){
if(n <2){
return false;
}
for (int i = 2; i <= sqrt(n); ++i){
if(n % i == 0){
return false;
}
}
return true;
}
int reverse(int n){
int s;
while(n >0){
s += s*10 + n%10;
n /= 10;
}
return s;
}
void displayCoupleOfNumber(int n){
int b = 0;
int tmp = sqrt(n);
int a = tmp;
while(true){
if(a<=0 || b >= tmp){
break;
}
if(a*a + b*b < n){
cout << "(" << a << ", "<< b<< ")" << endl;
cout << "(" << b << ", "<< a<< ")" << endl;
b++;
}else{
a--;
b = 0;
}
}
}
int main(){
int n;
cin >> n;
//cout << n << " Reverse:" << reverse(n);
displayCoupleOfNumber(n);
return 0;
} | true |
74a0d8cdb083d95e5199be27747f02af7e1f832c | C++ | diegoximenes/icpc | /judges/codeforces/done/332b.cpp | UTF-8 | 1,293 | 2.609375 | 3 | [] | no_license | #include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
#define MAX 300000+10
#define ll long long
int n, k;
ll v, dp[MAX][2], tree[MAX];
bool firstPrint = 1;
void update(int idx , ll val)
{
while (idx <= n)
{
tree[idx] += val;
idx += (idx & -idx);
}
}
ll read(int idx)
{
ll sum = 0;
while (idx > 0)
{
sum += tree[idx];
idx -= (idx & -idx);
}
return sum;
}
ll opt(int i, int count)
{
if(count > 1)
return 0;
if(i > n || i+k-1 > n)
return 0;
if(dp[i][count] != -1)
return dp[i][count];
return dp[i][count] = max(read(i + k - 1) - read(i - 1) + opt(i + k, count + 1), opt(i + 1, count));
}
void printSol(int i, int count)
{
if(i > n || count > 1)
return;
if(dp[i][count] == read(i + k - 1) - read(i - 1) + opt(i + k, count + 1))
{
if(firstPrint)
{
printf("%d", i);
firstPrint = 0;
}
else
printf(" %d", i);
printSol(i + k, count+1);
}
else
printSol(i + 1, count);
}
int main()
{
memset(dp, -1, sizeof(dp));
memset(tree, 0, sizeof(tree));
dp[0][0] = dp[0][1] = 0;
scanf("%d %d", &n, &k);
for(int i=1; i<=n; ++i)
{
cin >> v;
update(i, v);
}
opt(1, 0);
printSol(1, 0);
puts("");
/*for(int i=1; i<=n; ++i)
printf("i= %d, dp= %d, tree= %d\n", i, dp[i], tree[i]);*/
return 0;
}
| true |
050cf192e11a45ce19ddb9f0d7e261b23206e640 | C++ | 1249302623/myWebServer | /LiuServer/base/FileUtil.cpp | UTF-8 | 1,937 | 3.328125 | 3 | [] | no_license | #include "FileUtil.h"
#include <stdio.h>
AppendFile::AppendFile(std::string filename):
fp_(fopen(filename.c_str(),"ae"))//e :O_CLOEXEC 应该表示执行exec()时,之前通过open()打开的文件描述符会自动关闭
{
setbuffer(fp_, buffer_, sizeof buffer_);
//在打开文件流后,读取内容之前,调用setbuffer()可用来设置文件流的缓冲区。参数stream为指定的文件流,参数buf指向自定的缓冲区起始地址,参数size为缓冲区大小
}
AppendFile::~AppendFile(){
fclose(fp_);
}
void AppendFile::append(const char* logline, const size_t len)//不是线程安全的,需要外部加锁
{
size_t n = this->write(logline, len);//fwrite将数据写入写缓冲区,除非缓冲区已满,否则不写入文件。遇换行符或缓冲区满时,将刷新缓冲区;
size_t remain = len - n;
while (remain > 0) {
size_t x = this->write(logline + n, remain);
if (x == 0) {
int err = ferror(fp_);
if (err) fprintf(stderr, "AppendFile::append() failed !\n");
break;
}
n += x;
remain = len - n;
}
}
void AppendFile::flush()
{
fflush(fp_);//清除一个流,即清除文件缓冲区,当文件以写方式打开时,将缓冲区内容写入文件。
}
size_t AppendFile::write(const char* logline, size_t len)
{
return fwrite_unlocked(logline, 1, len, fp_);//size 设置为1,代表一个字节一个字节的写入文件。
}
//size_t fwrite(const void * ptr, size_t size, size_t nmemb, FILE * stream);
//fwrite()用来将数据写入文件流中. 参数stream 为已打开的文件指针, 参数ptr 指向欲写入的数据地址,size是数据块的大小(字节数)
//总共写入的字符数以参数size*nmemb 来决定. Fwrite()会返回实际写入的nmemb 数目
//fwrite_unlocked()与fwrite()相同,只是它不需要是线程安全的,fwrite_unlocked()函数,以不加锁的方式写文件,不线程安全,但是效率高。
| true |
fb0cccaf051cd1a7158ba9b78a4d46efa6a0e89b | C++ | chishaung/CS_570-Artificial-Intelligence- | /2013/CS570/CS_570 A.I./a.cpp | UTF-8 | 772 | 2.84375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
int x = 5;
float f = 8.5;
float a[3] = {1.1, 1.2, 1.3};
float *fp1, *fp2;
fp1 = &f;
cout << "fp1: " << *fp1 << endl;
fp2 = a;
cout << "fp2: " << *fp2 << endl;
cout << "fp2: " << fp2[0] << endl;
cout << "fp2: " << fp2[1] << endl;
cout << "fp2: " << fp2[2] << endl;
*fp1 = 4.4;
cout << "fp1: " << *fp1 << endl;
cout << "f: " << f << endl;
*fp2 = 8.5;
cout << "fp2: " << *fp2 << endl;
cout << "fp2: " << fp2[0] << endl;
cout << "fp2: " << fp2[1] << endl;
cout << "fp2: " << fp2[2] << endl;
cout << "a: " << *a << endl;
cout << "a: " << a[0] << endl;
cout << "a: " << a[1] << endl;
cout << "a: " << a[2] << endl;
fp1 = & fp2[1];
cout << "fp1: " << fp1 << endl;
cout << "fp2: " << fp2 << endl;
return 0;
}
| true |
7a8d7bb736b872654bfaa1886c28e4099576170c | C++ | patrickpclee/codfs | /branch/0.2/src/client/client_storagemodule.cc | UTF-8 | 5,339 | 2.59375 | 3 | [] | no_license | #include <fstream>
#include <math.h>
#include <stdlib.h>
#include <sys/file.h>
#include <thread>
#include <mutex> // added for gcc 4.7.1
#include <unistd.h> // added for gcc 4.7.1
#include "../common/debug.hh"
#include "../common/memorypool.hh"
#include "client_storagemodule.hh"
#include "../config/config.hh"
using namespace std;
/// Config Layer
extern ConfigLayer* configLayer;
// Global Mutex for locking file during read / write
mutex fileMutex;
mutex cacheMutex;
mutex openedFileMutex;
ClientStorageModule::ClientStorageModule() {
// read config value
_objectCache = {};
_objectSize = configLayer->getConfigLong("Storage>ObjectSize") * 1024;
debug("Config Object Size = %" PRIu64 " Bytes\n", _objectSize);
}
uint64_t ClientStorageModule::getFilesize(string filepath) {
ifstream in(filepath, ifstream::in | ifstream::binary);
if (!in) {
debug("%s\n", "ERROR: Cannot open file");
exit(-1);
}
// check filesize
in.seekg(0, std::ifstream::end);
uint64_t filesize = in.tellg();
in.close();
return filesize;
}
uint32_t ClientStorageModule::getObjectCount(string filepath) {
const uint64_t filesize = getFilesize(filepath);
if (filesize == 0) {
return 0;
}
uint32_t objectCount = (uint32_t) ((filesize - 1) / _objectSize + 1);
return objectCount;
}
struct ObjectData ClientStorageModule::readObjectFromFile(string filepath,
uint32_t objectIndex) {
// TODO: now assume that client only do one I/O function at a time
// lock file access function
lock_guard<mutex> lk(fileMutex);
struct ObjectData objectData;
uint32_t byteToRead = 0;
// index starts from 0
const uint64_t offset = objectIndex * _objectSize;
FILE* file = fopen(filepath.c_str(), "rb");
if (file == NULL) { // cannot open file
debug("%s\n", "Cannot open");
exit(-1);
}
// Read Lock
if (flock(fileno(file), LOCK_SH) == -1) {
debug("%s\n", "ERROR: Cannot LOCK_SH");
exit(-1);
}
// check filesize
fseek(file, 0, SEEK_END);
uint64_t filesize = ftell(file);
if (offset >= filesize) {
debug("%s\n", "ERROR: offset exceeds filesize");
exit(-1);
}
if (filesize - offset > _objectSize) {
byteToRead = _objectSize;
} else {
byteToRead = filesize - offset;
}
// Read file contents into buffer
objectData.buf = MemoryPool::getInstance().poolMalloc(byteToRead);
uint32_t byteRead = pread(fileno(file), objectData.buf, byteToRead, offset);
// Release lock
if (flock(fileno(file), LOCK_UN) == -1) {
debug("%s\n", "ERROR: Cannot LOCK_UN");
exit(-1);
}
if (byteRead != byteToRead) {
debug("ERROR: Length = %" PRIu32 ", byteRead = %" PRIu32 "\n",
byteToRead, byteRead);
exit(-1);
}
fclose(file);
// fill in information about object
objectData.info.objectSize = byteToRead;
return objectData;
}
void ClientStorageModule::createObjectCache(uint64_t objectId,
uint32_t length) {
// create cache
struct ObjectTransferCache objectCache;
objectCache.length = length;
objectCache.buf = MemoryPool::getInstance().poolMalloc(length);
// save cache to map
{
lock_guard<mutex> lk(cacheMutex);
_objectCache[objectId] = objectCache;
}
debug("Object created ID = %" PRIu64 " Length = %" PRIu32 "\n",
objectId, length);
}
uint32_t ClientStorageModule::writeObjectCache(uint64_t objectId, char* buf,
uint64_t offsetInObject, uint32_t length) {
char* recvCache;
{
lock_guard<mutex> lk(cacheMutex);
if (!_objectCache.count(objectId)) {
debug("%s\n", "cannot find cache for object");
exit(-1);
}
recvCache = _objectCache[objectId].buf;
}
memcpy(recvCache + offsetInObject, buf, length);
return length;
}
bool ClientStorageModule::locateObjectCache(uint64_t objectId){
return _objectCache.count(objectId);
}
struct ObjectTransferCache ClientStorageModule::getObjectCache(uint64_t objectId) {
lock_guard<mutex> lk(cacheMutex);
if (!_objectCache.count(objectId)) {
debug("object cache not found for %" PRIu64 "\n", objectId);
exit(-1);
}
return _objectCache[objectId];
}
void ClientStorageModule::closeObject(uint64_t objectId) {
// close cache
struct ObjectTransferCache objectCache = getObjectCache(objectId);
MemoryPool::getInstance().poolFree(objectCache.buf);
{
lock_guard<mutex> lk(cacheMutex);
_objectCache.erase(objectId);
}
debug("Object ID = %" PRIu64 " closed\n", objectId);
}
FILE* ClientStorageModule::createAndOpenFile(string filepath) {
// open file for read/write
// create new if not exist
FILE* filePtr;
filePtr = fopen(filepath.c_str(), "wb+");
if (filePtr == NULL) {
debug("%s\n", "Unable to create file!");
return NULL;
}
// set buffer to zero to avoid memory leak
setvbuf(filePtr, NULL, _IONBF, 0);
return filePtr;
}
uint32_t ClientStorageModule::writeFile(FILE* file, string filepath, char* buf,
uint64_t offset, uint32_t length) {
// lock file access function
lock_guard<mutex> lk(fileMutex);
if (file == NULL) { // cannot open file
debug("%s\n", "Cannot write");
exit(-1);
}
// Write file contents from buffer
uint32_t byteWritten = pwrite(fileno(file), buf, length, offset);
if (byteWritten != length) {
debug("ERROR: Length = %d, byteWritten = %d\n", length, byteWritten);
exit(-1);
}
return byteWritten;
}
void ClientStorageModule::closeFile (FILE* filePtr) {
fclose (filePtr);
}
uint64_t ClientStorageModule::getObjectSize() {
return _objectSize;
}
| true |
f6ba752b6df3084acb30f9a3038840f53d3d6581 | C++ | JoshuaWright1197/Vehicle | /main.cpp | UTF-8 | 946 | 2.875 | 3 | [] | no_license | #include<iostream>
#include<vector>
#include<iomanip>
#include"MotorVehicle.hpp"
using namespace std;
using namespace MotorVehicle;
int main()
{
vector<Vehicle::pointer_type> v;
v.push_back(Vehicle::pointer_type(new SuperCar("Ferrari", "488 GTB", "Red", 2016, 250'000, 8, 1'475,2, 3.9, 670, 0)));
v.push_back(Vehicle::pointer_type(new SuperBike("Yamaha", "R1", "Blue/white", 2016,16'500, 4, 4, 414,1, 200, 0)));
for (auto i : v) {
cout << i->to_string();
cout << endl;
}
cout << endl;
cout << setw(25) << left << "Total Vehicle(s):" << Vehicle::Get_Vehicle_Count() << endl;
cout << setw(25) << "Total Car(s):" << Car::Get_Car_Count() << endl;
cout << setw(25) << "Total MotorCycles(s):" << MotorCycle::Get_MotorCycle_Count() << endl;
cout << setw(25) << "Total SuperCar(s):" << SuperCar::Get_SuperCar_Count() << endl;
cout << setw(25) <<"Total SuperBiker(s):" << SuperBike::Get_SuperBike_Count() << endl;
} | true |
988b0a9d3026fc7aeb6706e5b772bc03886a4875 | C++ | lfblue/CornersVisualizer | /src/bridge.cpp | UTF-8 | 1,385 | 2.53125 | 3 | [] | no_license | #include "bridge.h"
#include <QFile>
#include <QDebug>
#include <QVariantMap>
// json include
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QVariant>
#include <QFileDialog>
Bridge::Bridge(QObject *parent) : QObject(parent)
{
m_settings = new QSettings("app.ini",QSettings::IniFormat);
}
Bridge::~Bridge()
{
delete m_settings;
}
QVariantMap Bridge::getJsonFromFile(const QString &path)
{
QFile file(path);
if(!file.open(QIODevice::ReadOnly))
{
qDebug() << "wrong path";
return QVariantMap();
}
QJsonDocument jsonDocument = QJsonDocument::fromJson(file.readAll());
return jsonDocument.toVariant().toMap();
}
void Bridge::setValue(const QString &key, const QVariant &value)
{
m_settings->setValue(key,value);
}
QVariant Bridge::getValue(const QString &key)
{
return m_settings->value(key);
}
void Bridge::setArray(const QString &key, const QVariantList &value)
{
m_settings->setValue(key,value);
}
QVariantList Bridge::getArray(const QString &key)
{
return m_settings->value(key).toList();
}
void Bridge::setObject(const QString &key, const QVariantMap &value)
{
m_settings->setValue(key,value);
}
QVariantMap Bridge::getObject(const QString &key)
{
return m_settings->value(key).toMap();
}
QString Bridge::getFilePath()
{
return QFileDialog::getOpenFileName();
}
| true |
0dea205c968ddba96e8513eed327439f4f2085ed | C++ | swong225/advent-of-code-2017 | /swong/02/part1.cpp | UTF-8 | 490 | 2.984375 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <fstream>
#include <sstream>
#include <climits>
using namespace std;
int main() {
ifstream inputFile("./input.txt");
string currLine;
int sum;
while (getline(inputFile, currLine)) {
istringstream is(currLine);
int currNum;
int min = INT_MAX;
int max = INT_MIN;
while(is >> currNum) {
if (currNum < min) min = currNum;
if (currNum > max) max = currNum;
}
sum += max - min;
}
cout << sum << "\n";
} | true |
34e9f3ed40f1bf9be6db5cac497df99df152157f | C++ | cipherxraytaint/preprocessor | /include/record.h | UTF-8 | 404 | 2.609375 | 3 | [] | no_license | #ifndef RECORD_H_
#define RECORD_H_
#include "node.h"
class Record
{
public:
Record() {};
~Record() {};
bool init_record(std::string rec);
bool is_mark();
void set_index(uint64_t index);
uint64_t get_index();
Node get_src();
Node get_dst();
void print_record();
private:
bool is_mark_ = false;
uint64_t index_ = 0;
Node src_;
Node dst_;
};
#endif | true |
f0feb922fff128d2fbeabf26768ea8766346183c | C++ | fallingfox/piskvorky | /piskvorky/piskvorky.cpp | UTF-8 | 2,993 | 3.078125 | 3 | [] | no_license | #include <algorithm>
#include "piskvorky.hpp"
// Konsturktor
Piskvorky::~Piskvorky() {
delete _board;
std::for_each(_players.cbegin(), _players.cend(), [](Player* player) { delete player; });
_players.clear();
}
// Gettery
Board* Piskvorky::getBoard() const {
return _board;
}
Player** Piskvorky::getPlayers() {
return _players.data();
}
const int Piskvorky::getWinSequence() const {
return _win_sequence;
}
// Settery
void Piskvorky::setBoard(Board* board) {
_board = board;
}
void Piskvorky::setWinSequence(const int seq) {
// TODO kontrola parametru
_win_sequence = seq;
}
// Metody
void Piskvorky::addPlayer(Player* player) {
this->_players.push_back(player);
}
Player* Piskvorky::checkWinner() {
for (int y = 0, h = _board->getHeight(); y < h; y++) {
for (int x = 0, w = _board->getWidth(); x < w; x++) {
Stone* s = _board->getStone(x, y);
if (s == nullptr) continue;
Player* p = s->getPlayer();
int hor = 1, ver = 1, diaL = 1, diaR = 1;
for (int i = 1; i < _win_sequence; i++) { // vertikální
try {
s = _board->getStone(x, y + i);
if (s == nullptr) break;
if (s->getPlayer() != p) break;
ver++;
} catch (char const* error) {
break;
}
}
if (ver >= _win_sequence) return p;
for (int i = 1; i < _win_sequence; i++) { // horizontální
try {
s = _board->getStone(x + i, y);
if (s == nullptr) break;
if (s->getPlayer() != p) break;
hor++;
} catch (char const* error) {
break;
}
}
if (hor >= _win_sequence) return p;
for (int i = 1; i < _win_sequence; i++) { // diagonální vpravo
try {
s = _board->getStone(x + i, y + i);
if (s == nullptr) break;
if (s->getPlayer() != p) break;
diaR++;
} catch (char const* error) {
break;
}
}
if (diaR >= _win_sequence) return p;
for (int i = 1; i < _win_sequence; i++) { // diagonální vlevo
try {
s = _board->getStone(x - i, y + i);
if (s == nullptr) break;
if (s->getPlayer() != p) break;
diaL++;
} catch (char const* error) {
break;
}
}
if (diaL >= _win_sequence) return p;
}
}
return nullptr;
}
Player* Piskvorky::checkWinner(const int last_x, const int last_y) {
// TODO impl
return nullptr;
}
Player* Piskvorky::nextPlayer() {
return _players[_playerIndex++ % 2];
} | true |