text
stringlengths
8
6.88M
class Solution { public: double myPow(double x, int n) { if(n == 0 || x == 1.0) return 1; if(x == 0.0 && n < 0) return x; // 当x是0而n是负数的时候,特殊情况 double res = 1.0; long exp = n; // 必须是long,否则如果n=INT_MIN,-n就会越界 if(n < 0) { x = 1 / x; exp = - exp; } while(exp) { // 快速幂方法(位运算) // 假如n=9,9写成二进制就是1001 // 每当exp & 1 = 1的时候,就执行乘方运算 if(exp & 1) res *= x; x *= x; exp >>= 1; } return res; } };
/** * * @file KondoB3MControlTable.hpp * @brief Kondo B3M device control table * @auther Yasuo Hayashibara * **/ #pragma once #include "../../../Communicator/Protocols/KondoB3M.hpp" namespace IO { namespace Device { namespace Actuator { namespace ServoMotor { namespace B3MSC1170AControlTable { constexpr Communicator::Protocols::KondoB3M::Byte system_id = 0x00, // eeprom start system_baudrate = 0x01, system_position_min = 0x05, system_position_max = 0x07, system_position_center = 0x09, system_mcu_temp_limit = 0x0B, system_mcu_temp_limit_pr = 0x0D, system_motor_temp_limit = 0x0E, system_motor_temp_limit_pr = 0x10, system_current_limit = 0x11, system_current_limit_pr = 0x13, system_lockdetect_time = 0x14, system_lockdetect_outrate = 0x15, system_lockdetect_time_pr = 0x16, system_input_voltage_min = 0x17, system_input_voltage_max = 0x19, system_torque_limit = 0x1B, system_deadband_width = 0x1C, system_motor_cw_ratio = 0x22, system_motor_ccw_ratio = 0x23, servo_servo_option = 0x27, servo_servo_mode = 0x28, servo_torque_on = 0x28, servo_run_mode = 0x29, servo_desired_position = 0x2A, servo_current_position = 0x2C, servo_previous_position = 0x2E, servo_desired_velocity = 0x30, servo_current_velocity = 0x32, servo_previous_velocity = 0x34, servo_desired_time = 0x36, servo_running_time = 0x38, servo_working_time = 0x3A, servo_desired_torque = 0x3C, servo_system_clock = 0x3E, servo_sampling_time = 0x42, servo_mcu_temp = 0x44, servo_motor_temp = 0x46, servo_current = 0x48, servo_input_voltage = 0x4A, servo_pwm_duty = 0x4C, servo_pwm_frequency = 0x4E, servo_encoder_value = 0x50, servo_encoder_count = 0x52, servo_hall_ic_state = 0x56, control_control_law = 0x5C, control_gain_presetno = 0x5C, control_type = 0x5D, control_kp0 = 0x5E, control_kd0 = 0x62, control_ki0 = 0x66, control_static_friction0 = 0x6A, control_dynamic_friction0 = 0x6C, control_kp1 = 0x6E, control_kd1 = 0x72, control_ki1 = 0x76, control_static_friction1 = 0x7A, control_dynamic_friction1 = 0x7C, control_kp2 = 0x7E, control_kd2 = 0x82, control_ki2 = 0x86, control_static_friction2 = 0x8A, control_dynamic_friction2 = 0x8C, status_base_addr = 0x9D, status_system = 0x9E, status_motor = 0x9F, status_uart = 0xA0, status_command = 0xA1, config_model_number = 0xA2, config_model_number_voltage_class = 0xA2, config_model_number_version = 0xA3, config_model_number_torque = 0xA4, config_model_number_case = 0xA5, config_model_type = 0xA6, config_model_type_motor = 0xA8, config_model_type_device = 0xA9, config_fw_version = 0xAA, config_fw_build = 0xAA, config_fw_revision = 0xAB, config_fw_minor = 0xAC, config_fw_major = 0xAD, config_enc_offset_center = 0xAE, config_enc_offset = 0xB0; } } } } }
#include <stdio.h> #include <iostream> #include <assert.h> #include <string.h> #include <queue> #include <vector> #include <sys/time.h> #include <time.h> #include "sample_receiver.h" #include "../shared/protocol.h" #include "log.h" #include "ring_buffer.h" using namespace std; using namespace base; SampleReceiver::SampleReceiver(MessageQueue *queue, RingBuffer *buffer, int trigger) : m_thread(new Thread(this, "sample_receiver")), m_msg_queue(queue), m_running(false), m_buffer(buffer), m_trigger(trigger) { } SampleReceiver::~SampleReceiver() { m_running = false; m_thread->join(); /* 等待线程退出 */ delete m_thread; } void SampleReceiver::start(uint32_t trigger) { assert(! m_running); m_trigger = trigger; m_thread->set_priority(0); m_thread->start(); } void SampleReceiver::stop() { assert(m_running); m_running = false; } void *SampleReceiver::run() { LOG_INFO("sample receiver is running"); m_running = true; while (m_running) { /* 等待 slave 端通知,1s 超时 */ Message *msg = (Message *)m_msg_queue->pop(1000 /* 1 sec */); if (! m_running) { /* 是否现在需要 quit */ if (msg) m_msg_queue->msg_free(msg); break; } if (! msg) { //LOG_TRACE("recv data timeout"); continue; } if (msg->cmd != MSG_CMD_RAW_DATA && msg->cmd != MSG_CMD_FFT_DATA) { LOG_WARN("unexpected message"); m_msg_queue->msg_free(msg); continue; } uint32_t size = sizeof(float) * m_trigger; float *data = (float *)m_buffer->acquired(size); /* 从 ipc ring buffer 读取数据 */ if (data == NULL) LOG_FATAL("failed to acquired data"); vector<float> samples(m_trigger, 0); memcpy(&samples[0], data, sizeof(float) * samples.size()); if (msg->cmd == MSG_CMD_RAW_DATA) /* 时域数据 */ emit raw(samples, samples.size()); else if (msg->cmd == MSG_CMD_FFT_DATA) /* 频域数据 */ emit fft(samples, samples.size()); m_buffer->release(size); m_msg_queue->msg_free(msg); } m_running = false; LOG_INFO("sample receiver is stoped"); return (void *)0; }
#include <iostream> #include <ctime> #include <cstdlib> #include <string> #include <vector> #include "Bote.h" using namespace std; enum TamanioBote { Submarino = 2, Destruidor = 3, Battleship = 4, Carrier = 5 }; void impBorda(int m[][10]); void inMatriz(int m[][10]); void impBordaJuego(int m[][10]); int colFilas(int col, int &fila, int TamanioBote, char d); char obtDir(int d); int comEspa(int m[][10], int c, int r, int s, char d); void editMatriz(int m[][10], int col, int fila, int TamanioBote, char dir); bool conjuntoBote(int m[][10], int TamanioBote, int nombre, vector<Bote> &IistaBotes); void editBoteInfo(int m[][10], int c, int r, int TamanioBote, char d, vector<Bote> &IistaBotes, int nombre); int playGame(int m[][10], vector<Bote> &IistaBotes); int obtEspacio(int m[][10], int fila, int col); /*void impBorda(int m[][10]) //imprime los barcos en sus respectivos lugares { cout << " 0|1|2|3|4|5|6|7|8|9" << endl << endl; for(int i=0; i<10; i++) { for(int j=0; j<10; j++) { if(j==0) { cout << i << " " ; } cout << m[i][j] ; if(j!=9) { cout << "|"; } } cout << endl; } cout << endl; }*/ void inMatriz(int m[][10]) { for(int col=0; col<10; col++) { for(int fila=0; fila<10; fila++) { m[col][fila]=0; } } } void impBordaJuego(int m[][10]) { cout << " 0|1|2|3|4|5|6|7|8|9" << endl << endl; for(int i=0; i<10; i++) { for(int j=0; j<10; j++) { if(j==0) { cout << i << " " ; } if(m[i][j]==1) { cout << 1; } else if(m[i][j]==9) { cout << 9; } else { cout << 0; } if(j!=9) { cout << "|"; } } cout << endl; } cout << endl; } bool conjuntoBote(int m[][10], int TamanioBote, int nombre, vector<Bote> &IistaBotes) //coloca las los botes en la matriz { srand(time(0)); int col=0; int fila=0; char d='v'; bool colocacion=true;//si la colocacion no es correcta char check='v'; int cS=0; d=obtDir(rand()%10); //bote col=colFilas(col, fila, TamanioBote, d); //retorna la columna y fila del bote while(colocacion) { if(d=='h') { cS=comEspa(m, col, fila, TamanioBote, d);//verifica si un bote n se sobrepone en otro bote if(cS==1)//Si el barco se superpone, genere otra columna aleatoria, fila y dirección e inicie el bucle de nuevo { d=obtDir(rand()%10); col=colFilas(col, fila, TamanioBote, d); cS==0; continue; } editMatriz(m, col, fila, TamanioBote, d);//lugar del bote en la matriz editBoteInfo(m, col, fila, TamanioBote, d, IistaBotes, nombre);//crear el bote return 0; }// else if(d=='v') { cS=comEspa(m, col, fila, TamanioBote, d); if(cS==1) { d=obtDir(rand()%10); col=colFilas(col, fila, TamanioBote, d); cS==0; continue; } editMatriz(m, col, fila, TamanioBote, d); editBoteInfo(m, col, fila, TamanioBote, d, IistaBotes, nombre); return 0; } } } char obtDir(int d) { if(d>4) { return 'h'; //selecciona donde poner al azar el barco } else { return 'v'; } } void editMatriz(int m[][10], int col, int fila, int TamanioBote, char dir) //pone los respectivos numers del bot en la atriz { if(dir=='h') { for(int i=0; i<TamanioBote; i++) { m[fila][col]=TamanioBote; col++; cout << endl; } } else if(dir=='v') { for(int i=0; i<TamanioBote; i++) { m[fila][col]=TamanioBote; fila++; cout << endl; } } else { cout << "Error! la direccion se paso" << endl; } //impBorda(m); } int comEspa(int m[][10], int c, int r, int s, char d) //compruba que los botes no se obresalan { int check=0; if(d=='h') { for(int i=c; i<c+s; i++) { check=m[r][i]; if(check!=0) { return 1; } } return 0; } else { for(int i=r; i<r+s; i++) { check=m[i][c]; if(check!=0) { return 1; } } return 0; } } int colFilas(int col, int &fila, int TamanioBote, char d) { switch(TamanioBote) //genera los botes en la columna y fila y confirma ue no se salgan de la brda { case Submarino: if(d=='h') { col=rand()%8; fila=rand()%10; } else { col=rand()%10; fila=rand()%8; } break; case Destruidor: if(d=='h') { col=rand()%7; fila=rand()%10; } else { col=rand()%10; fila=rand()%7; } break; case Battleship: if(d=='h') { col=rand()%6; fila=rand()%10; } else { col=rand()%10; fila=rand()%6; } break; case Carrier: if(d=='h') { col=rand()%5; fila=rand()%10; } else { col=rand()%10; fila=rand()%5; } } return col; } void editBoteInfo(int m[][10], int c, int r, int TamanioBote, char d, vector<Bote> &IistaBotes, int nombre) //crea los botes { switch(nombre) { case 1: if(d=='h') { vector<int> r1 (5); //agrega los datos en las coordenadas se usa el at for (int i=0; i<(int)r1.size(); ++i) { r1.at(i)=r; } vector<int> c1 (5); for (int i=0; i<(int)c1.size(); ++i) { c1.at(i)=c; c++; } //Aircraft Carrier Bote carrierBote('h', 5, r1, c1, 0, "Aircraft Carrier"); IistaBotes.push_back(carrierBote); } else if(d=='v') { vector<int> r1 (5); for (int i=0; i<(int)r1.size(); ++i) { r1.at(i)=r; r++; } vector<int> c1 (5); for (int i=0; i<(int)c1.size(); ++i) { c1.at(i)=c; } //Aircraft Carrier Bote carrierBote('v', 5, r1, c1, 0, "Aircraft Carrier"); IistaBotes.push_back(carrierBote); } break; case 2: if(d=='h') { vector<int> r1 (4); for (int i=0; i<(int)r1.size(); ++i) { r1.at(i)=r; } vector<int> c1 (4); for (int i=0; i<(int)c1.size(); ++i) { c1.at(i)=c; c++; } //Battleship 1 Bote battleship1Bote('h', 4, r1, c1, 0, "Battleship 1"); IistaBotes.push_back(battleship1Bote); } else if(d=='v') { vector<int> r1 (4); for (int i=0; i<(int)r1.size(); ++i) { r1.at(i)=r; r++; } vector<int> c1 (4); for (int i=0; i<(int)c1.size(); ++i) { c1.at(i)=c; } //Battleship 1 Bote battleship1Bote('v', 4, r1, c1, 0, "Battleship 1"); IistaBotes.push_back(battleship1Bote); } break; case 3: if(d=='h') { vector<int> r1 (4); for (int i=0; i<(int)r1.size(); ++i) { r1.at(i)=r; } vector<int> c1 (4); for (int i=0; i<(int)c1.size(); ++i) { c1.at(i)=c; c++; } //Battleship 2 Bote battleship2Bote('h', 4, r1, c1, 0, "Battleship 2"); IistaBotes.push_back(battleship2Bote); } else if(d=='v') { vector<int> r1 (4); for (int i=0; i<(int)r1.size(); ++i) { r1.at(i)=r; r++; } vector<int> c1 (4); for (int i=0; i<(int)c1.size(); ++i) { c1.at(i)=c; } //Battleship 2 Bote battleship2Bote('v', 4, r1, c1, 0, "Battleship 2"); IistaBotes.push_back(battleship2Bote); } break; case 4: if(d=='h') { vector<int> r1 (3); for (int i=0; i<(int)r1.size(); ++i) { r1.at(i)=r; } vector<int> c1 (3); for (int i=0; i<(int)c1.size(); ++i) { c1.at(i)=c; c++; } //Destruidor 1 Bote Destruidor1Bote('h', 3, r1, c1, 0, "Destruidor 1"); IistaBotes.push_back(Destruidor1Bote); } else if(d=='v') { vector<int> r1 (3); for (int i=0; i<(int)r1.size(); ++i) { r1.at(i)=r; r++; } vector<int> c1 (3); for (int i=0; i<(int)c1.size(); ++i) { c1.at(i)=c; } //Destruidor 1 Bote Destruidor1Bote('v', 3, r1, c1, 0, "Destruidor 1"); IistaBotes.push_back(Destruidor1Bote); } break; case 5: if(d=='h') { vector<int> r1 (3); for (int i=0; i<(int)r1.size(); ++i) { r1.at(i)=r; } vector<int> c1 (3); for (int i=0; i<(int)c1.size(); ++i) { c1.at(i)=c; c++; } //Destruidor 2 Bote Destruidor2Bote('h', 3, r1, c1, 0, "Destruidor 2"); IistaBotes.push_back(Destruidor2Bote); } else if(d=='v') { vector<int> r1 (3); for (int i=0; i<(int)r1.size(); ++i) { r1.at(i)=r; r++; } vector<int> c1 (3); for (int i=0; i<(int)c1.size(); ++i) { c1.at(i)=c; } //Destruidor 2 Bote Destruidor2Bote('v', 3, r1, c1, 0, "Destruidor 2"); IistaBotes.push_back(Destruidor2Bote); } break; case 6: if(d=='h') { vector<int> r1 (3); for (int i=0; i<(int)r1.size(); ++i) { r1.at(i)=r; } vector<int> c1 (3); for (int i=0; i<(int)c1.size(); ++i) { c1.at(i)=c; c++; } //Destruidor 3 Bote Destruidor3Bote('h', 3, r1, c1, 0, "Destruidor 3"); IistaBotes.push_back(Destruidor3Bote); } else if(d=='v') { vector<int> r1 (3); for (int i=0; i<(int)r1.size(); ++i) { r1.at(i)=r; r++; } vector<int> c1 (3); for (int i=0; i<(int)c1.size(); ++i) { c1.at(i)=c; } //Destruidor 3 Bote Destruidor3Bote('v', 3, r1, c1, 0, "Destruidor 3"); IistaBotes.push_back(Destruidor3Bote); } break; case 7: if(d=='h') { vector<int> r1 (2); for (int i=0; i<(int)r1.size(); ++i) { r1.at(i)=r; } vector<int> c1 (2); for (int i=0; i<(int)c1.size(); ++i) { c1.at(i)=c; c++; } //Submarino1 Bote Submarino1Bote('h', 2, r1, c1, 0, "Submarino 1"); IistaBotes.push_back(Submarino1Bote); } else if(d=='v') { vector<int> r1 (2); for (int i=0; i<(int)r1.size(); ++i) { r1.at(i)=r; r++; } vector<int> c1 (2); for (int i=0; i<(int)c1.size(); ++i) { c1.at(i)=c; } //Submarino 1 Bote Submarino1Bote('v', 2, r1, c1, 0, "Submarino 1"); IistaBotes.push_back(Submarino1Bote); } break; case 8: if(d=='h') { vector<int> r1 (2); for (int i=0; i<(int)r1.size(); ++i) { r1.at(i)=r; } vector<int> c1 (2); for (int i=0; i<(int)c1.size(); ++i) { c1.at(i)=c; c++; } //Submarino 2 Bote Submarino2Bote('h', 2, r1, c1, 0, "Submarino 2"); IistaBotes.push_back(Submarino2Bote); } else if(d=='v') { vector<int> r1 (2); for (int i=0; i<(int)r1.size(); ++i) { r1.at(i)=r; r++; } vector<int> c1 (2); for (int i=0; i<(int)c1.size(); ++i) { c1.at(i)=c; } //Submarino 2 Bote Submarino2Bote('v', 2, r1, c1, 0, "Submarino 2"); IistaBotes.push_back(Submarino2Bote); } break; case 9: if(d=='h') { vector<int> r1 (2); for (int i=0; i<(int)r1.size(); ++i) { r1.at(i)=r; } vector<int> c1 (2); for (int i=0; i<(int)c1.size(); ++i) { c1.at(i)=c; c++; } //Submarino 3 Bote Submarino3Bote('h', 2, r1, c1, 0, "Submarino 3"); IistaBotes.push_back(Submarino3Bote); } else if(d=='v') { vector<int> r1 (2); for (int i=0; i<(int)r1.size(); ++i) { r1.at(i)=r; r++; } vector<int> c1 (2); for (int i=0; i<(int)c1.size(); ++i) { c1.at(i)=c; } //Submarino 3 Bote Submarino3Bote('v', 2, r1, c1, 0, "Submarino 3"); IistaBotes.push_back(Submarino3Bote); } break; case 10: if(d=='h') { vector<int> r1 (2); for (int i=0; i<(int)r1.size(); ++i) { r1.at(i)=r; } vector<int> c1 (2); for (int i=0; i<(int)c1.size(); ++i) { c1.at(i)=c; c++; } //Submarino 4 Bote Submarino4Bote('h', 2, r1, c1, 0, "Submarino 4"); IistaBotes.push_back(Submarino4Bote); } else if(d=='v') { vector<int> r1 (2); for (int i=0; i<(int)r1.size(); ++i) { r1.at(i)=r; r++; } vector<int> c1 (2); for (int i=0; i<(int)c1.size(); ++i) { c1.at(i)=c; } //Submarino 4 Bote Submarino4Bote('v', 2, r1, c1, 0, "Submarino 4"); IistaBotes.push_back(Submarino4Bote); } break; } } int playGame(int m[][10], vector<Bote> &IistaBotes) { bool gameInProgress=true; int fila=0; int col=0; int adivin=0; int pum=0; int miss=0; int espacio=0; char d='g'; string btnombre=" "; int bomba=0; while(gameInProgress) { impBordaJuego(m); //impBorda(m); cout << "Ingresa la coordinada de la fila: "; cin >> fila; cout << "Ingresa la coordinada de la columna: "; cin >> col; cout << endl; adivin++; espacio=obtEspacio(m, fila, col); switch(espacio) { case 0: cout << "fallaste" << endl; m[fila][col]=9; miss++; break; case 1: cout << "Este espacio ya ha sido bombardeado. ¡Has desperdiciado una bomba!" << endl; break; case 2: m[fila][col]=1; pum++; btnombre=IistaBotes[6].obtBote(fila, col); // if(btnombre=="Submarino 1") { cout << "Has bombardeado" << btnombre << "!" << endl; IistaBotes[6].conjuntoPum(); bomba=IistaBotes[6].checkBomba(Submarino); if(bomba==9) { cout << "Has bombardeado a Submarino 1." << endl; } } else if(btnombre.empty()) { btnombre=IistaBotes[7].obtBote(fila, col); if(btnombre=="Submarino 2") { cout << "Has bombardeado " << btnombre << "!" << endl; IistaBotes[7].conjuntoPum(); bomba=IistaBotes[7].checkBomba(Submarino); if(bomba==9) { cout << "Has bombardeado Submarino 2." << endl; } } else if(btnombre.empty()) { btnombre=IistaBotes[8].obtBote(fila, col); // cout << "Has bombardeado " << btnombre << "!" << endl; IistaBotes[8].conjuntoPum(); bomba=IistaBotes[8].checkBomba(Submarino); if(bomba==9) { cout << "Has bombardeado Submarino 3." << endl; } } else if(btnombre.empty()) { btnombre=IistaBotes[9].obtBote(fila, col); //verifica sies el 4 cout << "Has bombardeado " << btnombre << "!" << endl; IistaBotes[9].conjuntoPum(); bomba=IistaBotes[9].checkBomba(Submarino); if(bomba==9) { cout << "Has bombardeado Submarino 4." << endl; } } } btnombre.clear(); break; case 3: m[fila][col]=1; pum++; btnombre=IistaBotes[3].obtBote(fila, col); //verificar i es destructor 1 if(btnombre=="Destruidor 1") { cout << "Has bombardeado " << btnombre << "!" << endl; IistaBotes[3].conjuntoPum(); bomba=IistaBotes[3].checkBomba(Destruidor); if(bomba==9) { cout << "Has bombardeado Destruidor 1." << endl; } } else if(btnombre.empty()) { btnombre=IistaBotes[4].obtBote(fila, col); if(btnombre=="Destruidor 2") { cout << "Has bombardeado" << btnombre << "!" << endl; IistaBotes[4].conjuntoPum(); bomba=IistaBotes[4].checkBomba(Destruidor); if(bomba==9) { cout << "Has bombardeado Destruidor 2." << endl; } } else if(btnombre.empty()) { btnombre=IistaBotes[5].obtBote(fila, col); cout << "Has bombardeado " << btnombre << "!" << endl; IistaBotes[5].conjuntoPum(); bomba=IistaBotes[5].checkBomba(Destruidor); cout << "bomba es " << bomba << endl; if(bomba==9) { cout << "Has bombardeado Destruidor 3." << endl; } } } btnombre.clear(); break; case 4: m[fila][col]=1; pum++; btnombre=IistaBotes[1].obtBote(fila, col); if(btnombre=="Battleship 1") { cout << "Has bombardeado " << btnombre << "!" << endl; IistaBotes[1].conjuntoPum(); bomba=IistaBotes[1].checkBomba(Battleship); if(bomba==9) { cout << "Has bombardeado Battleship 1." << endl; } } if(btnombre.empty()) { btnombre=IistaBotes[2].obtBote(fila, col); cout << "Has bombardeado" << btnombre << "!" << endl; IistaBotes[2].conjuntoPum(); bomba=IistaBotes[2].checkBomba(Battleship); if(bomba==9) { cout << "Has bombardeado Battleship 2." << endl; } } btnombre.clear(); break; case 5: cout << "Has bombardeado el aircraft carrier! " << endl; m[fila][col]=1; pum++; IistaBotes[0].conjuntoPum(); bomba=IistaBotes[0].checkBomba(Carrier); if(bomba==9) { cout << "Has bombardeado el aircraft carrier." << endl; } break; }//termino del switch if(pum==30) { gameInProgress=false; } }// cout << "¡Gracias por jugar! Usted uso " << adivin << " movimientos!" << endl; }//se termina la funcion int obtEspacio(int m[10][10], int fila, int col) { int espacio=0; espacio=m[fila][col]; return espacio; } int main() { int m[10][10]; vector<Bote> IistaBotes; char play; inMatriz(m); conjuntoBote(m, Carrier, 1, IistaBotes); //conjuntos de botes en la mtatrix conjuntoBote(m, Battleship, 2, IistaBotes); conjuntoBote(m, Battleship, 3, IistaBotes); conjuntoBote(m, Destruidor, 4, IistaBotes); conjuntoBote(m, Destruidor, 5, IistaBotes); conjuntoBote(m, Destruidor, 6, IistaBotes); conjuntoBote(m, Submarino, 7, IistaBotes); conjuntoBote(m, Submarino, 8, IistaBotes); conjuntoBote(m, Submarino, 9, IistaBotes); conjuntoBote(m, Submarino, 10, IistaBotes); cout << "Bienvenido a Batalla naval,presiona j para empezar a jugar" << endl << endl; cout << "el 1 significa que le diste y un nueve que fallaste" << endl << endl; cin >> play; if(play=='j') { playGame(m, IistaBotes); } return 0; }
#include <bits/stdc++.h> using namespace std; int main() { int t; cin>>t; while(t--) { string a; vector<int> b(0); int c[201]={0}; cin>>a; for(int i=0;i<a.length();i++) { int count =0,index ; for(int j=0;j<b.size();j++) { if(a[i] == b[j]) { count = 1; index = j; } } if(count == 0) { b.push_back(a[i]); index = b.size()-1; } c[index]++; } int sum = 0; for(int i=0;i<b.size();i++) { sum += (c[i]/2) + (c[i]%2); } cout<<sum<<endl; } return 0; }
#include <bits/stdc++.h> using namespace std; using ll = long long int; int const N = 55; string g[N]; int row[N][N], col[N][N]; void solve(){ int n; cin >> n; memset(row, 0, sizeof row); memset(col, 0, sizeof col); for(int i = 0; i < n; i++){ cin >> g[i] ; } for(int r = n - 1; r >= 0; r--){ for(int c = n - 1; c >= 0; c--){ if(g[r][c] == '1'){ if(r == n - 1 or g[r + 1][c] == '1' or c == n - 1 or g[r][ c + 1] == '1') continue; cout << "NO\n"; return; } } } cout << "YES\n"; } int main(){ ios::sync_with_stdio(0); cin.tie(0); int t; cin >> t; while(t--){ solve(); } }
#ifndef ENEMY_H #define ENEMY_H #include <QImage> #include <QRect> class enemy { //TEMPLATE ENEMY CLASS public: enemy(); enemy(int, int); ~enemy(); int getXDir(); int getYDir(); // X AND Y GETS AND SETS void setXDir(int); void setYDir(int); void reset(int, int); void setHit(bool); bool getHit(); QImage & getImage(); QRect getRect(); //IMAGE AND RECT GET protected: int y; bool hit; int xdir, ydir; QImage image; QRect rect; }; #endif // ENEMY_H
#include <iostream> #include <queue> #include <set> #include "Graph.h" using namespace std; template <typename T> bool hasLoops(const Graph<T>& g) { for (const T& v : g.vertices()) { if (g.hasEdge(v, v)) { return true; } } return false; } template <typename T> bool isComplete(const Graph<T>& g) { for (const T& v1 : g.vertices()) { for (const T& v2 : g.vertices()) { if (!g.hasEdge(v1, v2)) { return false; } } } return true; } template <typename T> bool isUnordered(const Graph<T>& g) { for (const T& v1 : g.vertices()) { for (const T& v2 : g.successors(v1)) { if (!hasEdge(v2, v1)) { return false; } } } return true; } template <typename T> Graph<T> complement(const Graph<T>& g) { Graph<T> result; for (const Vertex& v : g.vertices()) { result.addVertex(v); } for (const Vertex& v1 : g.vertices()) { for (const Vertex& v2 : g.vertices()) { if (!g.hasEdge(v1, v2)) { result.addEdge(v1, v2); } } } return result; } template <typename T> int propagateSecrets(const T& person, const Graph<T>& friends, T& mostSources) { std::queue<T> bfs; std::set<T> visited; std::unordered_map<T, int> countSources; bfs.push(person); while (!bfs.empty()) { T p = bfs.front(); bfs.pop(); if (visited.count(p) != 0) { // already visited, skip continue; } visited.insert(p); for (const T& fr : friends.successors(p)) { countSources[fr] += 1; if (visited.count(fr) == 0) { bfs.push(fr); } } } // find person with most sources int maxCount = 0; for (auto count : countSources) { if (count.second > maxCount) { maxCount = count.second; mostSources = count.first; } } // how many people know return visited.size(); } int main() { Graph<int> g; g.addEdge(15, 15); g.addEdge(15, 7); g.addEdge(15, 1); g.addEdge(1, 3); g.addEdge(3, 7); g.addEdge(7, 15); g.addEdge(7, 3); cout << "Hello world!" << endl; return 0; }
../../Lib/matrix.cpp
#ifndef PNRD_H #define PNRD_H #include "PetriNet.h" #ifndef MAX_NUM_OF_TAG_HISTORY_ENTRIES #define MAX_NUM_OF_TAG_HISTORY_ENTRIES 10 #endif enum class PetriNetInformation { TOKEN_VECTOR = 0, ADJACENCY_LIST = 1, FIRE_VECTOR = 2, CONDITIONS = 3, TAG_HISTORY = 4, DESIRED_STATE = 5 }; enum class ReadError { NO_ERROR = 0, TAG_NOT_PRESENT = 1, INFORMATION_NOT_PRESENT = 2, DATA_SIZE_NOT_COMPATIBLE = 3, NOT_AUTORIZED = 4, VERSION_NOT_SUPPORTED = 5, ERROR_UNKNOWN = 6 }; enum class WriteError { NO_ERROR = 0, TAG_NOT_PRESENT = 1, INFORMATION_NOT_SAVED = 2, NOT_ENOUGH_SPACE = 3, NOT_AUTORIZED = 4, VERSION_NOT_SUPPORTED = 5, ERROR_UNKNOWN = 6 }; enum class PnrdPolicy { DEFAULT_SETUP = 0, TAG_SETUP = 1 }; struct TagHistoryEntry { uint16_t DeviceId = 0; uint8_t Place = 255; uint16_t Tokens = 0; uint32_t TimeStamp = 0; }; class Reader; class Pnrd : public PetriNet { private: Reader* reader; uint8_t dataInTag; uint32_t tagId; uint32_t deviceId; TagHistoryEntry* tagHistory; uint8_t tagHistoryIndex = 0; bool hasTagHistory; private: void preparePnrdMemoryStack(); void printTagHistoryEntry(TagHistoryEntry entry); void saveTagHistory(); public: Pnrd(Reader* readerPointer, uint8_t num_places, uint8_t num_transitions, uint8_t num_max_of_inputs, uint8_t num_max_of_outputs, bool hasConditions, bool hasTagHistory); Pnrd(Reader* readerPointer, uint8_t num_places, uint8_t num_transitions, uint8_t num_max_of_inputs, uint8_t num_max_of_outputs); Pnrd(Reader* readerPointer, uint8_t num_places, uint8_t num_transitions, bool hasConditions, bool hasTagHistory); Pnrd(Reader* readerPointer, uint8_t num_places, uint8_t num_transitions); ~Pnrd(); void setAsTagInformation(PetriNetInformation info); void setAsDeviceInformation(PetriNetInformation info); void resetAsTagInformation(); bool isTagInformation(PetriNetInformation info); uint8_t* getDataInTag(); ReadError getData(); WriteError saveData(); void setTagId(uint32_t tagId); uint32_t getTagId(); void setDeviceId(uint32_t deviceId); uint32_t getDeviceId(); bool setTagHistory(TagHistoryEntry* vector, uint8_t numberOfEntries); uint8_t getTagHistory(TagHistoryEntry* vector); TagHistoryEntry* getTagHistoryPointer(); uint8_t* getTagHistoryIndexPointer(); void printTagHistory(); void addTagHistoryEntry(TagHistoryEntry entry); void removeLastTagHistoryEntry(); FireError fire(); FireError fire(uint8_t transition); PnrdPolicy setup = PnrdPolicy::DEFAULT_SETUP; }; class Reader { public: virtual ReadError read(Pnrd* pnrd) = 0; virtual WriteError write(Pnrd* pnrd) = 0; }; #endif
/* Copyright (c) 2005-2023, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Oxford nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "AbstractPdeModifier.hpp" #include "VtkMeshWriter.hpp" #include "ReplicatableVector.hpp" #include "AveragedSourceEllipticPde.hpp" #include "AveragedSourceParabolicPde.hpp" template<unsigned DIM> AbstractPdeModifier<DIM>::AbstractPdeModifier(boost::shared_ptr<AbstractLinearPde<DIM,DIM> > pPde, boost::shared_ptr<AbstractBoundaryCondition<DIM> > pBoundaryCondition, bool isNeumannBoundaryCondition, Vec solution) : AbstractCellBasedSimulationModifier<DIM>(), mpPde(pPde), mpBoundaryCondition(pBoundaryCondition), mIsNeumannBoundaryCondition(isNeumannBoundaryCondition), mSolution(nullptr), mOutputDirectory(""), mOutputGradient(false), mOutputSolutionAtPdeNodes(false), mDeleteFeMesh(false) { if (solution) { mSolution = solution; } } template<unsigned DIM> AbstractPdeModifier<DIM>::~AbstractPdeModifier() { if (mDeleteFeMesh and mpFeMesh!=nullptr) { delete mpFeMesh; } if (mSolution) { PetscTools::Destroy(mSolution); } } template<unsigned DIM> boost::shared_ptr<AbstractLinearPde<DIM,DIM> > AbstractPdeModifier<DIM>::GetPde() { return mpPde; } template<unsigned DIM> boost::shared_ptr<AbstractBoundaryCondition<DIM> > AbstractPdeModifier<DIM>::GetBoundaryCondition() { return mpBoundaryCondition; } template<unsigned DIM> bool AbstractPdeModifier<DIM>::IsNeumannBoundaryCondition() { return mIsNeumannBoundaryCondition; } template<unsigned DIM> void AbstractPdeModifier<DIM>::SetDependentVariableName(const std::string& rName) { mDependentVariableName = rName; } template<unsigned DIM> std::string& AbstractPdeModifier<DIM>::rGetDependentVariableName() { return mDependentVariableName; } template<unsigned DIM> bool AbstractPdeModifier<DIM>::HasAveragedSourcePde() { return ((boost::dynamic_pointer_cast<AveragedSourceEllipticPde<DIM> >(mpPde) != nullptr) || (boost::dynamic_pointer_cast<AveragedSourceParabolicPde<DIM> >(mpPde) != nullptr)); } template<unsigned DIM> void AbstractPdeModifier<DIM>::SetUpSourceTermsForAveragedSourcePde(TetrahedralMesh<DIM,DIM>* pMesh, std::map<CellPtr, unsigned>* pCellPdeElementMap) { assert(HasAveragedSourcePde()); if (boost::dynamic_pointer_cast<AveragedSourceEllipticPde<DIM> >(mpPde) != nullptr) { boost::static_pointer_cast<AveragedSourceEllipticPde<DIM> >(mpPde)->SetupSourceTerms(*pMesh, pCellPdeElementMap); } else if (boost::dynamic_pointer_cast<AveragedSourceParabolicPde<DIM> >(mpPde) != nullptr) { boost::static_pointer_cast<AveragedSourceParabolicPde<DIM> >(mpPde)->SetupSourceTerms(*pMesh, pCellPdeElementMap); } } template<unsigned DIM> Vec AbstractPdeModifier<DIM>::GetSolution() { return mSolution; } template<unsigned DIM> Vec AbstractPdeModifier<DIM>::GetSolution() const { return mSolution; } template<unsigned DIM> TetrahedralMesh<DIM,DIM>* AbstractPdeModifier<DIM>::GetFeMesh() const { return mpFeMesh; } template<unsigned DIM> void AbstractPdeModifier<DIM>::SetupSolve(AbstractCellPopulation<DIM,DIM>& rCellPopulation, std::string outputDirectory) { // Cache the output directory this->mOutputDirectory = outputDirectory; if (mOutputSolutionAtPdeNodes) { if (PetscTools::AmMaster()) { OutputFileHandler output_file_handler(outputDirectory+"/", false); mpVizPdeSolutionResultsFile = output_file_handler.OpenOutputFile("results.vizpdesolution"); } } } template<unsigned DIM> void AbstractPdeModifier<DIM>::UpdateAtEndOfOutputTimeStep(AbstractCellPopulation<DIM,DIM>& rCellPopulation) { if (mOutputSolutionAtPdeNodes) { if (PetscTools::AmMaster()) { (*mpVizPdeSolutionResultsFile) << SimulationTime::Instance()->GetTime() << "\t"; assert(mpFeMesh != nullptr); assert(mDependentVariableName != ""); for (unsigned i=0; i<mpFeMesh->GetNumNodes(); i++) { (*mpVizPdeSolutionResultsFile) << i << " "; const c_vector<double,DIM>& r_location = mpFeMesh->GetNode(i)->rGetLocation(); for (unsigned k=0; k<DIM; k++) { (*mpVizPdeSolutionResultsFile) << r_location[k] << " "; } assert(mSolution != nullptr); ReplicatableVector solution_repl(mSolution); (*mpVizPdeSolutionResultsFile) << solution_repl[i] << " "; } (*mpVizPdeSolutionResultsFile) << "\n"; } } #ifdef CHASTE_VTK if (DIM > 1) { std::ostringstream time_string; time_string << SimulationTime::Instance()->GetTimeStepsElapsed(); std::string results_file = "pde_results_" + mDependentVariableName + "_" + time_string.str(); VtkMeshWriter<DIM,DIM>* p_vtk_mesh_writer = new VtkMeshWriter<DIM,DIM>(mOutputDirectory, results_file, false); ReplicatableVector solution_repl(mSolution); std::vector<double> pde_solution; for (unsigned i=0; i<mpFeMesh->GetNumNodes(); i++) { pde_solution.push_back(solution_repl[i]); } p_vtk_mesh_writer->AddPointData(mDependentVariableName, pde_solution); p_vtk_mesh_writer->WriteFilesUsingMesh(*mpFeMesh); delete p_vtk_mesh_writer; } #endif //CHASTE_VTK } template<unsigned DIM> void AbstractPdeModifier<DIM>::UpdateAtEndOfSolve(AbstractCellPopulation<DIM,DIM>& rCellPopulation) { if (mOutputSolutionAtPdeNodes) { if (PetscTools::AmMaster()) { mpVizPdeSolutionResultsFile->close(); } } } template<unsigned DIM> bool AbstractPdeModifier<DIM>::GetOutputGradient() { return mOutputGradient; } template<unsigned DIM> void AbstractPdeModifier<DIM>::SetOutputGradient(bool outputGradient) { mOutputGradient = outputGradient; } template<unsigned DIM> void AbstractPdeModifier<DIM>::SetOutputSolutionAtPdeNodes(bool outputSolutionAtPdeNodes) { mOutputSolutionAtPdeNodes = outputSolutionAtPdeNodes; } template<unsigned DIM> void AbstractPdeModifier<DIM>::OutputSimulationModifierParameters(out_stream& rParamsFile) { // No parameters to output, so just call method on direct parent class AbstractCellBasedSimulationModifier<DIM>::OutputSimulationModifierParameters(rParamsFile); } // Explicit instantiation template class AbstractPdeModifier<1>; template class AbstractPdeModifier<2>; template class AbstractPdeModifier<3>;
#include "Combat.h" #include "Bitmap.h" #include "ScreenMainGame.h" #include "ActionExecutor.h" #include "CombatUI.h" #include "CombatSuccess.h" #include "ResLevelupChain.h" #include "ActionPhysicalAttackAll.h" #include "ActionPhysicalAttackOne.h" #include "SaveLoadStream.h" Combat::Combat() :mIsEnable(false), mIsFighting(false), mIsRandomFight(false) { mRandom = new Random(); mIsWin = false; mPlayerPos[0].set(64 + 12, 52 + 18); mPlayerPos[1].set(96 + 12, 48 + 18); mPlayerPos[2].set(128 + 12, 40 + 18); mIsAutoAttack = false; mFlyPeach = (ResSrs*)DatLib::GetRes(DatLib::RES_SRS, 1, 249); mCombatState = SelectAction; mActionQueue = new HMQueue < Action * > ; mActionExecutor = new ActionExecutor(mActionQueue, this); mCombatUI = CombatUI::getInstance(); mCombatUI->setCurrentPlayerIndex(0); mCombatUI->setCallBack(this); mCombatSuccess = NULL; mCurSelActionPlayerIndex = 0; mTimeCnt = 0; mBackground = NULL; } Combat::~Combat() { delete mFlyPeach; delete mActionExecutor; delete mActionQueue; delete mRandom; } Combat * Combat::getInstance() { static Combat instance; return &instance; } bool Combat::isActive() { return mIsEnable && mIsFighting; } void Combat::fightEnable() { mIsEnable = true; } void Combat::fightDisable() { mIsEnable = false; } void Combat::initFight(vector<int> monstersType, int scrb, int scrl, int scrr) { mIsEnable = true; mIsRandomFight = true; mIsFighting = false; mMonsterType.clear(); for (int i = 0; i < (int)(monstersType.size()); ++i) { if (monstersType[i] > 0) { mMonsterType.push_back(monstersType.at(i)); } } mRoundCnt = 0; mMaxRound = 0; // 回合数无限制 createBackgroundBitmap(scrb, scrl, scrr); } void Combat::enterFight(int roundMax, int monstersType[3], int scr[3], int evtRnds[3], int evts[3], int lossto, int winto) { mIsRandomFight = false; for (int i = 0; i < 3; ++i) { if (monstersType[i] > 0) { Monster *tmp = (Monster*)DatLib::GetRes(DatLib::RES_ARS, 3, monstersType[i]); if (tmp != NULL) { mMonsterList.push_back(tmp); } } } mMaxRound = roundMax; mRoundCnt = 0; prepareForNewCombat(); createBackgroundBitmap(scr[0], scr[1], scr[2]); mEventRound.clear(); mEventNum.clear(); for (int i = 0; i < 3; i++) { mEventRound.push_back(evtRnds[i]); mEventNum.push_back(evts[i]); } mLossAddr = lossto; mWinAddr = winto; } bool Combat::startNewRandomCombat() { if (!mIsEnable || mRandom->nextInt(COMBAT_PROBABILITY) != 0) { mIsFighting = false; return false; } // 打乱怪物类型 for (int i = mMonsterType.size() - 1; i > 1; --i) { int r = mRandom->nextInt(i); int t = mMonsterType[i]; mMonsterType[i] = mMonsterType[r]; mMonsterType[r] = t; } //删除怪物列表 while (!mMonsterList.empty()) { delete mMonsterList.back(); mMonsterList.pop_back(); } // 随机添加怪物 for (int i = mRandom->nextInt(3), j = 0; i >= 0; i--) { Monster *m = (Monster*)DatLib::GetRes(DatLib::RES_ARS, 3, mMonsterType.at(j++)); if (m != NULL) { mMonsterList.push_back(m); } } mRoundCnt = 0; mMaxRound = 0; // 回合不限 prepareForNewCombat(); return true; } void Combat::createBackgroundBitmap(int scrb, int scrl, int scrr) { if (NULL != mBackground) { delete mBackground; } mBackground = Bitmap::createBitmap(160, 96, ARGB_8888); Canvas *canvas = new Canvas(mBackground); ResImage *img; img = (ResImage*)DatLib::GetRes(DatLib::RES_PIC, 4, scrb); if (img != NULL) { img->draw(canvas, 1, 0, 0); // 背景 delete img; } img = (ResImage*)DatLib::GetRes(DatLib::RES_PIC, 4, scrl); if (img != NULL) { img->draw(canvas, 1, 0, 96 - img->getHeight()); // 左下角 delete img; } img = (ResImage*)DatLib::GetRes(DatLib::RES_PIC, 4, scrr); if (img != NULL) { img->draw(canvas, 1, 160 - img->getWidth(), 0); // 右上角 delete img; } delete canvas; mScrb = scrb; mScrl = scrl; mScrR = scrr; } void Combat::prepareForNewCombat() { mIsEnable = true; mIsFighting = true; //删动作物列表 while (!mActionQueue->empty()) { delete mActionQueue->back(); mActionQueue->pop_back(); } mIsAutoAttack = false; mCombatState = SelectAction; mCurSelActionPlayerIndex = 0; mPlayerList.clear(); for (int i = 0; i < (int)(ScreenMainGame::sPlayerList.size());i++) { mPlayerList.push_back(ScreenMainGame::sPlayerList.at(i)); } mCombatUI->reset(); mCombatUI->setCurrentPlayerIndex(0); mCombatUI->setPlayerList(mPlayerList); setOriginalPlayerPos(); setOriginalMonsterPos(); mRoundCnt = 0; mHasEventExed = false; // 检查玩家血量 for (int i = 0; i < (int)(mPlayerList.size()); ++i) { Player *p = mPlayerList.at(i); if (p->getHP() <= 0) { // 确保血量大于0 p->setHP(1); } p->setFrameByState(); } // 怪物血量设置为其最大值 for (int i = 0; i < (int)(mMonsterList.size()); ++i) { Monster *m = mMonsterList.at(i); m->setHP(m->getMaxHP()); } // 计算战斗胜利能获得的金钱和经验 mWinMoney = 0; mWinExp = 0; for (int i = 0; i < (int)(mMonsterList.size()); ++i) { Monster *m = mMonsterList.at(i); mWinMoney += m->getMoney(); mWinExp += m->getExp(); } if (!mIsRandomFight && mMonsterList.size() == 1) { // 剧情战斗,只有一个怪时,怪的位置在中间 Monster *m = mMonsterList.at(0); Monster *n = (Monster*)DatLib::GetRes(DatLib::RES_ARS, m->getType(), m->getIndex()); n->setHP(-1); n->setVisiable(false); vector<Monster *>::iterator iter = mMonsterList.begin(); mMonsterList.insert(iter, n); // 加入一个看不见的怪 ,在0位置 setOriginalMonsterPos(); // 重置位置 } mFlyPeach->startAni(); mFlyPeach->setIteratorNum(5); mCombatUI->setMonsterList(mMonsterList); } void Combat::exitCurrentCombat() { if (!mIsRandomFight) { ScreenMainGame::gotoAddress(mIsWin ? mWinAddr : mLossAddr); ScriptExecutor::goonExecute = true; mIsRandomFight = true; } else { if (!mIsWin) { // 死了,游戏结束 GameView::getInstance()->changeScreen(SCREEN_MENU); } } mIsFighting = false; while (!mActionQueue->empty()) { Action *act = mActionQueue->back(); if (NULL != act) { delete act; } mActionQueue->pop_back(); } mActionExecutor->reset(); mCombatUI->reset(); mIsAutoAttack = false; // 恢复一定的血量 vector<Player*>::const_iterator iter = mPlayerList.begin(); for (; iter != mPlayerList.begin(); ++iter) { Player *p = *iter; if (p->getHP() <= 0) { p->setHP(1); } if (p->getMP() <= 0) { p->setMP(1); } p->setHP(p->getHP() + (p->getMaxHP() - p->getHP()) / 10); p->setMP(p->getMP() + p->getMaxMP() / 5); if (p->getMP() > p->getMaxMP()) { p->setMP(p->getMaxMP()); } } } void Combat::setOriginalPlayerPos() { for (int i = 0; i < (int)(mPlayerList.size()); i++) { mPlayerList.at(i)->setCombatPos(mPlayerPos[i].x, mPlayerPos[i].y); } } void Combat::setOriginalMonsterPos() { for (int i = 0; i < (int)(mMonsterList.size()); i++) { mMonsterList.at(i)->setOriginalCombatPos(i); } } void Combat::generateAutoActionQueue() { Monster *monster = getFirstAliveMonster(); while (!mActionQueue->empty()) { Action *act = mActionQueue->back(); if (NULL != act) { delete act; } mActionQueue->pop_back(); } // 玩家的Action for (int i = 0; i < (int)(mPlayerList.size()); i++) { Player *p = mPlayerList.at(i); if (p->isAlive()) { Action *act = NULL; if (p->hasAtbuff(Player::BUFF_MASK_ALL)) { vector<FightingCharacter *> fc; fc.clear(); while (!mMonsterList.empty()) { fc.push_back(mMonsterList.back()); } act = new ActionPhysicalAttackAll(p, fc); } else { act = new ActionPhysicalAttackOne(p, monster); } mActionQueue->add(act); } } // 怪物的Action generateMonstersActions(); sortActionQueue(); } void Combat::generateMonstersActions() { // TODO according to the monster's intelligence, add some magic attack for (int i = 0; i < (int)(mMonsterList.size()); i++) { Monster *m = mMonsterList.at(i); if (m->isAlive()) { Player *p = getRandomAlivePlayer(); if (p != NULL) { Action *act = NULL; if (p->hasAtbuff(Monster::BUFF_MASK_ALL)) { vector<FightingCharacter *> fc; fc.clear(); while (!mPlayerList.empty()) { fc.push_back(mPlayerList.back()); } act = new ActionPhysicalAttackAll(m, fc); } else { act = new ActionPhysicalAttackOne(m, p); } mActionQueue->add(act); } } } } bool Combat::isAnyPlayerAlive() { for (int i = 0; i < (int)(mPlayerList.size()); i++) { Player *p = mPlayerList.at(i); if (p->getHP() > 0) { return true; } } return false; } bool Combat::isAllMonsterDead() { return getFirstAliveMonster() == NULL; } bool Combat::isPlayerBehindDead(int index) { for (int i = index + 1; i < (int)(mPlayerList.size()); i++) { if (mPlayerList.at(i)->isAlive()) { return false; } } return true; } int Combat::getNextAlivePlayerIndex() { for (int i = mCurSelActionPlayerIndex + 1; i < (int)(mPlayerList.size()); i++) { if (mPlayerList.at(i)->isAlive()) { return i; } } return -1; } int Combat::getPreAlivePlayerIndex() { for (int i = mCurSelActionPlayerIndex - 1; i >= 0; i--) { if (mPlayerList.at(i)->isAlive()) { return i; } } return -1; } int Combat::getFirstAlivePlayerIndex() { for (int i = 0; i < (int)(mPlayerList.size()); i++) { if (mPlayerList.at(i)->isAlive()) { return i; } } return -1; } void Combat::update(long delta) { mTimeCnt += delta; switch (mCombatState) { case SelectAction: if (!mHasEventExed && !mIsRandomFight) { mHasEventExed = true; for (int i = 0; i < (int)(mEventRound.size()); i++) { if (mRoundCnt == mEventRound[i] && mEventNum[i] != 0) { ScreenMainGame::triggerEvent(mEventNum[i]); } } } if (mIsAutoAttack) { // 自动生成动作队列 generateAutoActionQueue(); mCombatState = PerformAction; } else { // 玩家决策 mCombatUI->update(delta); } break; case PerformAction: if (!mActionExecutor->update(delta)) { // 动作执行完毕 if (isAllMonsterDead()) { // 怪物全挂 mTimeCnt = 0; // 计时器清零 mCombatState = Win; Player::sMoney += mWinMoney; // 获得金钱 vector<Player*> lvuplist; lvuplist.clear(); for (int i = 0; i < (int)(mPlayerList.size()); i++) { Player *p = mPlayerList.at(i); // 获得经验 if (p->isAlive()) { if (p->getLevel() >= p->getLevelupChain()->getMaxLevel()) // 满级 break; int nextExp = p->getLevelupChain()->getNextLevelExp(p->getLevel()); int exp = mWinExp + p->getCurrentExp(); if (exp < nextExp) { p->setCurrentExp(exp); } else { // 升级 int cl = p->getLevel(); // 当前等级 ResLevelupChain *c = p->getLevelupChain(); p->setCurrentExp(exp - nextExp); p->setLevel(cl + 1); p->setMaxHP(p->getMaxHP() + c->getMaxHP(cl + 1) - c->getMaxHP(cl)); //p->setHP(p->getMaxHP()); CombatSuccess 中设置 p->setMaxMP(p->getMaxMP() + c->getMaxMP(cl + 1) - c->getMaxMP(cl)); //p->setMP(p->getMaxMP()); CombatSuccess 中设置 p->setAttack(p->getAttack() + c->getAttack(cl + 1) - c->getAttack(cl)); p->setDefend(p->getDefend() + c->getDefend(cl + 1) - c->getDefend(cl)); p->getMagicChain()->setLearnNum(c->getLearnMagicNum(cl + 1)); p->setSpeed(p->getSpeed() + c->getSpeed(cl + 1) - c->getSpeed(cl)); p->setLingli(p->getLingli() + c->getLingli(cl + 1) - c->getLingli(cl)); p->setLuck(p->getLuck() + c->getLuck(cl + 1) - c->getLuck(cl)); lvuplist.push_back(p); } } } // 最大幸运值 int ppt = 10; for (int i = 0; i < (int)(mPlayerList.size()); i++) { Player *p = mPlayerList.at(i); if (p->getLuck() > ppt) { ppt = p->getLuck(); } } ppt -= 10; if (ppt > 100) { ppt = 100; } else if (ppt < 0) { ppt = 10; } // 战利品链表 GoodsManage gm; vector<BaseGoods*> gl; for (int i = 0; i < (int)(mMonsterList.size()); i++) { Monster *m = mMonsterList.at(i); BaseGoods *g = m->getDropGoods(); int lucky = mRandom->nextInt(101); if (g != NULL && lucky < ppt) { // ppt%掉率 gm.addGoods(g->getType(), g->getIndex(), g->getGoodsNum()); Player::sGoodsList->addGoods(g->getType(), g->getIndex(), g->getGoodsNum()); // 添加到物品链表 } if (g != NULL) { delete g; } } gl.clear(); if (!gm.getGoodsList()->empty()) { vector<BaseGoods *>::const_iterator iter = gm.getGoodsList()->begin(); for (; iter != gm.getGoodsList()->end(); ++iter) { BaseGoods *g = *iter; gl.push_back(g); } } if (!gm.getEquipList()->empty()) { vector<BaseGoods *>::const_iterator iter = gm.getEquipList()->begin(); for (; iter != gm.getEquipList()->end(); ++iter) { BaseGoods *g = *iter; gl.push_back(g); } } mCombatSuccess = new CombatSuccess(mWinExp, mWinMoney, gl, lvuplist); // 显示玩家的收获 //删除怪物列表 while (!mMonsterList.empty()) { delete mMonsterList.back(); mMonsterList.pop_back(); } } else { // 还有怪物存活 if (isAnyPlayerAlive()) { // 有玩家角色没挂,继续打怪 ++mRoundCnt; updateFighterState(); mCombatState = SelectAction; mCurSelActionPlayerIndex = getFirstAlivePlayerIndex(); mCombatUI->setCurrentPlayerIndex(mCurSelActionPlayerIndex); for (int i = 0; i < (int)(mPlayerList.size()); i++) { Player *p = mPlayerList.at(i); p->setFrameByState(); } } else { // 玩家角色全挂,战斗失败 mTimeCnt = 0; mCombatState = Loss; } } } break; case Win: // TODO if (winAddr...) // if (mTimeCnt > 1000){ // mCombatState = CombatState.Exit; // } mIsWin = true; if (mCombatSuccess->update(delta)) { delete mCombatSuccess; mCombatSuccess = NULL; mCombatState = Exit; } break; case Loss: // TODO if (lossAddr...) if (mIsRandomFight && mFlyPeach->update(delta)) { } else { mIsWin = false; mCombatState = Exit; } break; case Exit: exitCurrentCombat(); break; } } void Combat::draw(Canvas *canvas) { canvas->drawBitmap(mBackground, 0, 0); // draw the monsters and players for (int i = 0; i < (int)(mMonsterList.size()); i++) { Monster *fc = mMonsterList.at(i); if (fc->isVisiable()) { fc->getFightingSprite()->draw(canvas); } } for (int i = mPlayerList.size() - 1; i >= 0; i--) { FightingSprite *f = mPlayerList.at(i)->getFightingSprite(); f->draw(canvas); } if (mCombatState == SelectAction && !mIsAutoAttack) { mCombatUI->draw(canvas); } else if (mCombatState == PerformAction) { mActionExecutor->draw(canvas); } else if (mCombatState == Win) { TextRender::drawText(canvas, "Win", 20, 40); mCombatSuccess->draw(canvas); } else if (mCombatState == Loss && mIsRandomFight) { TextRender::drawText(canvas, "Loss", 20, 40); mFlyPeach->draw(canvas, 0, 0); } } void Combat::onKeyDown(int key) { if (mCombatState == SelectAction) { if (!mIsAutoAttack) { mCombatUI->onKeyDown(key); } } else if (mCombatState == Win) { mCombatSuccess->onKeyDown(key); } } void Combat::onKeyUp(int key) { if (mCombatState == SelectAction) { if (!mIsAutoAttack) { mCombatUI->onKeyUp(key); } } else if (mCombatState == Win) { mCombatSuccess->onKeyUp(key); } if (mIsAutoAttack && key == KEY_CANCEL) { // 退出“围攻”模式 mIsAutoAttack = false; } } void Combat::sortActionQueue() { struct ActionQueueCompare { bool operator()(Action *lhs, Action *rhs) { return rhs->getPriority() < lhs->getPriority(); } }comp; sort(mActionQueue->begin(), mActionQueue->end(), comp); } Monster * Combat::getFirstAliveMonster() { for (int i = 0; i < (int)(mMonsterList.size()); i++) { Monster *m = mMonsterList.at(i); if (m->isAlive()) { return m; } } return NULL; } Player * Combat::getRandomAlivePlayer() { int cnt = 0; for (int i = 0; i < (int)(mPlayerList.size()); i++) { Player *p = mPlayerList.at(i); if (p->isAlive()) { ++cnt; } } if (cnt == 0) return NULL; // 全死了 vector<Player*> arr; for (int i = 0; i < (int)(mPlayerList.size()); i++) { Player *p = mPlayerList.at(i); if (p->isAlive()) { arr.push_back(p); } } return arr.at(mRandom->nextInt(cnt)); } void Combat::updateFighterState() { // TODO decrease the buff's round count } void Combat::onActionSelected(Action *action) { mActionQueue->add(action); mCombatUI->reset(); // 重置战斗UI if (action->bInstanceof_ActionCoopMagic) { // 只保留合击 while (!mActionQueue->empty()) { Action *act = mActionQueue->back(); if (NULL != act) { delete act; } mActionQueue->pop_back(); } mActionQueue->add(action); generateMonstersActions(); sortActionQueue(); mCombatState = PerformAction; } else if (mCurSelActionPlayerIndex >= (int)(mPlayerList.size()) - 1 || isPlayerBehindDead(mCurSelActionPlayerIndex)) { // 全部玩家角色的动作选择完成 generateMonstersActions(); sortActionQueue(); mCombatState = PerformAction; // 开始执行动作队列 } else { // 选择下一个玩家角色的动作 mCurSelActionPlayerIndex = getNextAlivePlayerIndex(); //if (mPlayerList.get(mCurSelActionPlayerIndex).hasDebuff(0)) TODO 乱眠死不能自己选择action mCombatUI->setCurrentPlayerIndex(mCurSelActionPlayerIndex); } } void Combat::onAutoAttack() { // clear all the actions that has been selected, enter into auto fight mode mCombatUI->reset(); while (!mActionQueue->empty()) { Action *act = mActionQueue->back(); if (NULL != act) { delete act; } mActionQueue->pop_back(); } mIsAutoAttack = true; mCombatState = SelectAction; } void Combat::onFlee() { // TODO add flee action to all the other actor mCombatUI->reset(); // 重置战斗UI for (int i = mCurSelActionPlayerIndex; i < (int)(mPlayerList.size()); i++) { bool bFlee = mRandom->nextbool(); if (mPlayerList.at(i)->isAlive() && bFlee && mIsRandomFight) { class RunnableFlee : public Runnable { private: Combat *_this; public: RunnableFlee(Combat *_this) { this->_this = _this; } virtual void run() { // 逃跑成功后执行 _this->mIsWin = true; _this->mCombatState = Exit; } }; // 50% 逃走 mActionQueue->add(new ActionFlee(mPlayerList.at(i), true, new RunnableFlee(this))); break; } else { // 逃跑失败 mActionQueue->add(new ActionFlee(mPlayerList.at(i), false, NULL)); } } generateMonstersActions(); sortActionQueue(); mCombatState = PerformAction; } void Combat::onCancel() { int i = getPreAlivePlayerIndex(); if (i >= 0) { // 不是第一个角色 // 重选上一个角色的动作 mActionQueue->removeLast(); mCurSelActionPlayerIndex = i; mCombatUI->setCurrentPlayerIndex(mCurSelActionPlayerIndex); mCombatUI->reset(); } } void Combat::read(SaveLoadStream *buff) { mIsEnable = buff->readBoolean(); if (mIsEnable) { vector<int> monsterType; monsterType.clear(); int size = buff->readInt(); for (int i = 0; i < size; i++) { monsterType.push_back(buff->readInt()); } int scrb = buff->readInt(); int scrl = buff->readInt(); int scrr = buff->readInt(); initFight(monsterType, scrb, scrl, scrr); } } void Combat::write(SaveLoadStream *buff) { buff->writeBoolean(mIsEnable); if (mIsEnable) { int size = (int)mMonsterType.size(); buff->writeInt(size); for (int i = 0; i < size; i++) { buff->writeInt(mMonsterType.at(i)); } buff->writeInt(mScrb); buff->writeInt(mScrl); buff->writeInt(mScrR); } }
#include "CEndSuccess.h" #include "CLabel.h" #include "CText.h" #include "CButton.h" #include "CBaseEngine.h" #include "CSubmitScore.h" CEndSuccess::CEndSuccess(): CCenteredWindow(vec2d(500,350),"",65.,false) { addChild(new CLabel(vec2d(20.,20.), vec2d(getW()-40., 60.), "Výborně!", true, CLabel::ALIGN_CENTER)); addChild(new CLabel(vec2d(20.,100.), vec2d(getW()-40., 28.), (format("Váš dosažený čas: %1%") % formatTime(engine->map->getMapTime()) ).str(), true, CLabel::ALIGN_CENTER)); { CText* tmp; addChild(tmp = new CText(vec2d(20.,150.), vec2d(getW()-40., 21.), 21., CLabel::ALIGN_CENTER)); tmp->setText("Pokud chcete čas odeslat na server, stiskněte tlačítko \"Odeslat čas\"."); } CGuiPanel* tmp; addChild(tmp = new CButton(vec2d(getW()-150., getH()-45.), vec2d(130., 25.), "Odeslat čas")); tmp->addListener(makeCListenerMemberFn(0,this,&CEndSuccess::endSuccessAction)); addChild(tmp = new CButton(vec2d(getW()-278., getH()-45.), vec2d(130., 25.), "Opakovat")); tmp->addListener(makeCListenerMemberFn(1,this,&CEndSuccess::endSuccessAction)); addChild(tmp = new CButton(vec2d(getW()-406., getH()-45.), vec2d(130., 25.), "Hlavní menu")); tmp->addListener(makeCListenerMemberFn(2,this,&CEndSuccess::endSuccessAction)); } void CEndSuccess::endSuccessAction(int id){ if(id == 0){ remove(); engine->gui->addElement( new CSubmitScore() ); }else if(id == 1){ remove(); engine->map->reload(); }else if(id == 2){ remove(); engine->gui->showMainMenu(true); } }
// C++ for the Windows Runtime vv1.0.170303.6 // Copyright (c) 2017 Microsoft Corporation. All rights reserved. #pragma once WINRT_EXPORT namespace winrt { namespace ABI::Windows::Security::Authentication::Web::Core { struct IWebAccountEventArgs; struct IWebAccountMonitor; struct IWebAuthenticationCoreManagerStatics; struct IWebAuthenticationCoreManagerStatics2; struct IWebAuthenticationCoreManagerStatics3; struct IWebProviderError; struct IWebProviderErrorFactory; struct IWebTokenRequest; struct IWebTokenRequest2; struct IWebTokenRequest3; struct IWebTokenRequestFactory; struct IWebTokenRequestResult; struct IWebTokenResponse; struct IWebTokenResponseFactory; struct WebAccountEventArgs; struct WebAccountMonitor; struct WebProviderError; struct WebTokenRequest; struct WebTokenRequestResult; struct WebTokenResponse; } namespace Windows::Security::Authentication::Web::Core { struct IWebAccountEventArgs; struct IWebAccountMonitor; struct IWebAuthenticationCoreManagerStatics; struct IWebAuthenticationCoreManagerStatics2; struct IWebAuthenticationCoreManagerStatics3; struct IWebProviderError; struct IWebProviderErrorFactory; struct IWebTokenRequest; struct IWebTokenRequest2; struct IWebTokenRequest3; struct IWebTokenRequestFactory; struct IWebTokenRequestResult; struct IWebTokenResponse; struct IWebTokenResponseFactory; struct WebAccountEventArgs; struct WebAccountMonitor; struct WebAuthenticationCoreManager; struct WebProviderError; struct WebTokenRequest; struct WebTokenRequestResult; struct WebTokenResponse; } namespace Windows::Security::Authentication::Web::Core { template <typename T> struct impl_IWebAccountEventArgs; template <typename T> struct impl_IWebAccountMonitor; template <typename T> struct impl_IWebAuthenticationCoreManagerStatics; template <typename T> struct impl_IWebAuthenticationCoreManagerStatics2; template <typename T> struct impl_IWebAuthenticationCoreManagerStatics3; template <typename T> struct impl_IWebProviderError; template <typename T> struct impl_IWebProviderErrorFactory; template <typename T> struct impl_IWebTokenRequest; template <typename T> struct impl_IWebTokenRequest2; template <typename T> struct impl_IWebTokenRequest3; template <typename T> struct impl_IWebTokenRequestFactory; template <typename T> struct impl_IWebTokenRequestResult; template <typename T> struct impl_IWebTokenResponse; template <typename T> struct impl_IWebTokenResponseFactory; } namespace Windows::Security::Authentication::Web::Core { enum class WebTokenRequestPromptType { Default = 0, ForceAuthentication = 1, }; enum class WebTokenRequestStatus { Success = 0, UserCancel = 1, AccountSwitch = 2, UserInteractionRequired = 3, AccountProviderNotAvailable = 4, ProviderError = 5, }; } }
#ifndef __DailyBonus_H__ #define __DailyBonus_H__ #include "cocos2d.h" #include "LBLibraryBase.h" #include "TipDialog.h" class DailyBonus : public TipDialog { private: bool m_completed; static int checkDays(); static int getDays(); int m_days; static DailyBonus *create(int days); //void show(Node *owner, int zOrder); void setNodeColorAndUsedAble(); void onClickDaySprite(Node *node, WJTouchEvent *event); void onPlayGiftAniTimer(float time); public: DailyBonus(); bool init(int days); static bool showItIfNeed(Node *owner, int zOrder); virtual void onEnterTransitionDidFinish(); }; #endif
// // Compiler/Diagnostics/FileRange.cpp // // Brian T. Kelley <brian@briantkelley.com> // Copyright (c) 2011 Brian T. Kelley // // This software is licensed as described in the file LICENSE, which you should have received as part of this distribution. // #include "Compiler/Diagnostics/FileRange.h" #include <sstream> using namespace Compiler::Diagnostics; const Position Position::Empty = Position(0, 0); const FileRange FileRange::Empty = FileRange("", Position::Empty, Position::Empty); const std::string FileRange::GetDescription() const { std::stringstream description; description << GetFileName(); const Position& startPosition = GetStartPosition(); const Position& endPosition = GetEndPosition(); const bool hasStartPosition = !startPosition.IsEmpty(); const bool hasEndPosition = !endPosition.IsEmpty(); if (hasStartPosition || hasEndPosition) { description.put(':'); if (hasStartPosition && hasEndPosition) { // (line:column - line:column) description.put('('); description << startPosition.GetLineNumber() << ':' << startPosition.GetColumn(); description << " - "; description << endPosition.GetLineNumber() << ':' << endPosition.GetColumn(); description.put(')'); } else { const Position &position = hasStartPosition ? startPosition : endPosition; if (position.GetColumn() == 0) { description << position.GetLineNumber(); } else { description.put('('); description << position.GetLineNumber() << ':' << position.GetColumn(); description.put(')'); } } } return description.str(); }
// This file has been generated by Py++. #include "boost/python.hpp" #include "generators/include/python_CEGUI.h" #include "MouseCursorEventArgs.pypp.hpp" namespace bp = boost::python; struct MouseCursorEventArgs_wrapper : CEGUI::MouseCursorEventArgs, bp::wrapper< CEGUI::MouseCursorEventArgs > { MouseCursorEventArgs_wrapper(CEGUI::MouseCursorEventArgs const & arg ) : CEGUI::MouseCursorEventArgs( arg ) , bp::wrapper< CEGUI::MouseCursorEventArgs >(){ // copy constructor } MouseCursorEventArgs_wrapper(::CEGUI::MouseCursor * cursor ) : CEGUI::MouseCursorEventArgs( boost::python::ptr(cursor) ) , bp::wrapper< CEGUI::MouseCursorEventArgs >(){ // constructor } static ::CEGUI::Image const * get_image(CEGUI::MouseCursorEventArgs const & inst ){ return inst.image; } static void set_image( CEGUI::MouseCursorEventArgs & inst, ::CEGUI::Image const * new_value ){ inst.image = new_value; } static ::CEGUI::MouseCursor * get_mouseCursor(CEGUI::MouseCursorEventArgs const & inst ){ return inst.mouseCursor; } static void set_mouseCursor( CEGUI::MouseCursorEventArgs & inst, ::CEGUI::MouseCursor * new_value ){ inst.mouseCursor = new_value; } }; void register_MouseCursorEventArgs_class(){ { //::CEGUI::MouseCursorEventArgs typedef bp::class_< MouseCursorEventArgs_wrapper, bp::bases< CEGUI::EventArgs > > MouseCursorEventArgs_exposer_t; MouseCursorEventArgs_exposer_t MouseCursorEventArgs_exposer = MouseCursorEventArgs_exposer_t( "MouseCursorEventArgs", "*!\n\ \n\ EventArgs based class that is used for objects passed to input event handlers\n\ concerning mouse cursor events.\n\ *\n", bp::init< CEGUI::MouseCursor * >(( bp::arg("cursor") )) ); bp::scope MouseCursorEventArgs_scope( MouseCursorEventArgs_exposer ); bp::implicitly_convertible< CEGUI::MouseCursor *, CEGUI::MouseCursorEventArgs >(); MouseCursorEventArgs_exposer.add_property( "image" , bp::make_function( (::CEGUI::Image const * (*)( ::CEGUI::MouseCursorEventArgs const & ))(&MouseCursorEventArgs_wrapper::get_image), bp::return_internal_reference< >() ) , bp::make_function( (void (*)( ::CEGUI::MouseCursorEventArgs &,::CEGUI::Image const * ))(&MouseCursorEventArgs_wrapper::set_image), bp::with_custodian_and_ward_postcall< 1, 2 >() ) ); MouseCursorEventArgs_exposer.add_property( "mouseCursor" , bp::make_function( (::CEGUI::MouseCursor * (*)( ::CEGUI::MouseCursorEventArgs const & ))(&MouseCursorEventArgs_wrapper::get_mouseCursor), bp::return_internal_reference< >() ) , bp::make_function( (void (*)( ::CEGUI::MouseCursorEventArgs &,::CEGUI::MouseCursor * ))(&MouseCursorEventArgs_wrapper::set_mouseCursor), bp::with_custodian_and_ward_postcall< 1, 2 >() ) ); } }
/* Copyright (c) 2005-2023, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Oxford nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef CRYPTSIMULATION2D_HPP_ #define CRYPTSIMULATION2D_HPP_ #include "ChasteSerialization.hpp" #include <boost/serialization/base_object.hpp> #include "WntConcentration.hpp" #include "OffLatticeSimulation.hpp" #include "VertexBasedCellPopulation.hpp" #include "CryptSimulationBoundaryCondition.hpp" #include "CryptCentreBasedDivisionRule.hpp" #include "CryptVertexBasedDivisionRule.hpp" /** * A 2D crypt simulation object. For more details on the crypt geometry, see the * papers by van Leeuwen et al (2009) [doi:10.1111/j.1365-2184.2009.00627.x] and * Osborne et al (2010) [doi:10.1098/rsta.2010.0173]. */ class CryptSimulation2d : public OffLatticeSimulation<2> { // Allow tests to access private members, in order to test computation of private functions e.g. DoCellBirth() friend class TestCryptSimulation2dWithMeshBasedCellPopulation; friend class TestCryptSimulation2dWithVertexBasedCellPopulation; protected: /** Needed for serialization. */ friend class boost::serialization::access; /** * Archive the simulation and member variable. * * @param archive the archive * @param version the current version of this class */ template<class Archive> void serialize(Archive & archive, const unsigned int version) { archive & boost::serialization::base_object<OffLatticeSimulation<2> >(*this); SerializableSingleton<WntConcentration<2> >* p_wnt_wrapper = WntConcentration<2>::Instance()->GetSerializationWrapper(); archive & p_wnt_wrapper; } /** * Helper member that stores whether we are using a MeshBasedCellPopulationWithGhostNodes * (if not, then we are assumed to be using a VertexBasedCellPopulation). */ bool mUsingMeshBasedCellPopulation; /** * Overridden SetupSolve() method. * * Write initial beta catenin results to file if required. */ void SetupSolve(); public: /** * Constructor. * * @param rCellPopulation A cell population object * @param deleteCellPopulationInDestructor Whether to delete the cell population on destruction to * free up memory (defaults to false) * @param initialiseCells whether to initialise cells (defaults to true, set to false when loading from an archive) */ CryptSimulation2d(AbstractCellPopulation<2>& rCellPopulation, bool deleteCellPopulationInDestructor=false, bool initialiseCells=true); /** * Destructor. * * This frees the CryptSimulationBoundaryCondition. */ virtual ~CryptSimulation2d(); /** * Set method for mUseJiggledBottomCells. */ void UseJiggledBottomCells(); /** * Sets the Ancestor index of all the cells at the bottom in order, * can be used to trace clonal populations. */ void SetBottomCellAncestors(); /** * Outputs simulation parameters to file * * As this method is pure virtual, it must be overridden * in subclasses. * * @param rParamsFile the file stream to which the parameters are output */ void OutputSimulationParameters(out_stream& rParamsFile); }; // Declare identifier for the serializer #include "SerializationExportWrapper.hpp" CHASTE_CLASS_EXPORT(CryptSimulation2d) namespace boost { namespace serialization { /** * Serialize information required to construct a CryptSimulation2d. */ template<class Archive> inline void save_construct_data( Archive & ar, const CryptSimulation2d * t, const unsigned int file_version) { // Save data required to construct instance const AbstractCellPopulation<2>* p_cell_population = &(t->rGetCellPopulation()); ar & p_cell_population; } /** * De-serialize constructor parameters and initialise a CryptSimulation2d. */ template<class Archive> inline void load_construct_data( Archive & ar, CryptSimulation2d * t, const unsigned int file_version) { // Retrieve data from archive required to construct new instance AbstractCellPopulation<2>* p_cell_population; ar & p_cell_population; // Invoke inplace constructor to initialise instance ::new(t)CryptSimulation2d(*p_cell_population, true, false); } } } // namespace #endif /*CRYPTSIMULATION2D_HPP_*/
// reverse stack #include<iostream> #include<stack> using namespace std; stack<int> reverseStack(stack<int> s1){ stack<int> s2; while(!s1.empty()){ s2.push(s1.top()); s1.pop(); } return s2; } void display(stack<int> s){ while(!s.empty()){ cout<<s.top()<<" "; s.pop(); } cout<<endl; } int main(){ stack<int> s1; s1.push(1); s1.push(2); s1.push(3); s1.push(4); s1.push(5); display(s1); s1 = reverseStack(s1); display(s1); return 0; }
//输入两个字符串,从第一字符串中删除第二个字符串中所有的字符。例如,输入”They are students.”和”aeiou”, //则删除之后的第一个字符串变成”Thy r stdnts.” #if 0 #include<iostream> #include<string> int main() { std::string s1, s2, res; std::getline(std::cin, s1); std::getline(std::cin, s2); int hashtable[256] = { 0 }; for (int i = 0; i < s2.size(); i++) hashtable[s2[i]]++; for (int i = 0; i < s1.size(); i++) { if (hashtable[s1[i]] == 0) res.push_back(s1[i]); } std::cout << res << std::endl; return 0; } #endif
/*********************************************************************** * created: 11/6/2011 * author: Martin Preisler *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #include "CEGUI/Clipboard.h" #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_SUITE(Clipboard) const size_t BUFFER_SIZE = 1024; const CEGUI::String MIME_TYPE = "cegui/regression-test-data"; BOOST_AUTO_TEST_CASE(InternalClipboard) { CEGUI::Clipboard cb; // string set, get cb.setText("TestingContents"); BOOST_CHECK_EQUAL(cb.getText(), "TestingContents"); // raw data set, get std::uint8_t* buffer = new std::uint8_t[BUFFER_SIZE]; for (unsigned int i = 0; i < BUFFER_SIZE; ++i) { // I want to have something in the memory, not just zeroes, // this could avoid false positives in some cases buffer[i] = static_cast<std::uint8_t>(i % std::numeric_limits<std::uint8_t>::max()); } cb.setData(MIME_TYPE, buffer, BUFFER_SIZE); CEGUI::String retrievedMimeType; const void* retrievedBuffer; size_t retrievedBufferSize; cb.getData(retrievedMimeType, retrievedBuffer, retrievedBufferSize); BOOST_CHECK_EQUAL(MIME_TYPE, retrievedMimeType); BOOST_CHECK_EQUAL(BUFFER_SIZE, retrievedBufferSize); BOOST_CHECK(memcmp(buffer, retrievedBuffer, BUFFER_SIZE) == 0); // 0 indicates that both blocks of memory are equal delete[] buffer; } static CEGUI::String g_MimeType = ""; static std::uint8_t* g_ClipboardBuffer = nullptr; static size_t g_ClipboardSize = 0; class TestNativeClipboardProvider : public CEGUI::NativeClipboardProvider { private: std::vector<std::unique_ptr<uint8_t[]>> d_allocatedMemory; public: virtual ~TestNativeClipboardProvider() {} void sendToClipboard(const CEGUI::String& mimeType, void* buffer, size_t size) override { g_MimeType = mimeType; g_ClipboardSize = size; g_ClipboardBuffer = new std::uint8_t[size]; memcpy(g_ClipboardBuffer, buffer, size); d_allocatedMemory.emplace_back(static_cast<std::uint8_t*>(g_ClipboardBuffer)); } void retrieveFromClipboard(CEGUI::String& mimeType, void*& buffer, size_t& size) override { mimeType = g_MimeType; size = g_ClipboardSize; // we have to allocate buffer for the user of the native clipboard provider! buffer = new std::uint8_t[g_ClipboardSize]; memcpy(buffer, g_ClipboardBuffer, g_ClipboardSize); d_allocatedMemory.emplace_back(static_cast<std::uint8_t*>(buffer)); } }; BOOST_AUTO_TEST_CASE(NativeClipboardProvider) { CEGUI::NativeClipboardProvider* provider = new TestNativeClipboardProvider(); CEGUI::Clipboard cb; cb.setNativeProvider(provider); // ASCII string set, get const char* asciiTest = "TestingContents"; cb.setText(asciiTest); BOOST_CHECK_EQUAL(cb.getText(), asciiTest); BOOST_CHECK_EQUAL(g_ClipboardSize, 15); // it only contains characters from ASCII 7bit #if CEGUI_STRING_CLASS != CEGUI_STRING_CLASS_UTF_32 BOOST_CHECK(memcmp(g_ClipboardBuffer, CEGUI::String(asciiTest).c_str(), g_ClipboardSize) == 0); #else BOOST_CHECK(memcmp(g_ClipboardBuffer, CEGUI::String::convertUtf32ToUtf8(CEGUI::String(asciiTest).getString()).c_str(), g_ClipboardSize) == 0); #endif #if CEGUI_STRING_CLASS == CEGUI_STRING_CLASS_UTF_32 || CEGUI_STRING_CLASS == CEGUI_STRING_CLASS_UTF_8 // Unicode string set, get const char* utf8Test = "(・。・;)"; cb.setText(utf8Test); BOOST_CHECK_EQUAL(cb.getText(), utf8Test); # if CEGUI_STRING_CLASS == CEGUI_STRING_CLASS_UTF_8 BOOST_CHECK(memcmp(g_ClipboardBuffer, CEGUI::String(utf8Test).c_str(), g_ClipboardSize) == 0); # endif #endif delete provider; } BOOST_AUTO_TEST_SUITE_END()
#ifndef _INC_RPG2K__AUDIO__AUDIO_2D__HPP #define _INC_RPG2K__AUDIO__AUDIO_2D__HPP #include <SDL_mixer.h> #include <set> #include <map> #include "Material.hpp" namespace rpg2kLib { class Main; namespace structure { class Music; class Sound; } #define PP_allSoundType(func) func(wav) #define PP_allMusicType(func) func(mid) func(wav) func(mp3) class Audio2D { public: #define PP_enumSoundType(name) SND_##name, enum SoundType { PP_allSoundType(PP_enumSoundType) SND_END, }; #undef PP_enumSoundType #define PP_enumMusicType(name) MUS_##name, enum MusicType { PP_allMusicType(PP_enumMusicType) MUS_END, }; #undef PP_enumMusicType private: friend class ::rpg2kLib::Main; Main& owner_; std::map< RPG2kString, Mix_Music* > musicPool_; std::map< RPG2kString, Mix_Chunk* > soundPool_; RPG2kString currentMusic_; // std::set< RPG2kString > playingSound_; std::vector< SystemString > soundExt_; std::vector< SystemString > musicExt_; protected: void gotoTitle(); Mix_Music* getMusic(RPG2kString const& name); Mix_Chunk* getSound(RPG2kString const& name); Mix_Chunk* loadSound(RPG2kString const& name); Mix_Music* loadMusic(RPG2kString const& name); public: Audio2D(Main& m); ~Audio2D(); void stop(); void stopMusic(); void stopSound(); void playSound(structure::Sound const& se); void playMusic(structure::Music const& bgm); }; // class Audio2D } // namespace rpg2kLib #endif
// ---------------------------------------------------------------------- // Filename Compression.cpp // Created by Rakkar Software (rakkar@jenkinssoftware.com) September 25, 2003 // Demonstrates how to use compression with the standard chat example. // The first time you run this you won't have frequency tables, so you must run it twice. // The first time to generate a table, the second time to use the last table generated // ---------------------------------------------------------------------- #include "MessageIdentifiers.h" #include "RakNetworkFactory.h" #include "RakPeerInterface.h" #include "RakNetTypes.h" #include "BitStream.h" #include <assert.h> #include <cstdio> #include <cstring> #include <stdlib.h> #ifdef WIN32 #include "Kbhit.h" #else #include "Kbhit.h" #endif int main(void) { printf("This sample demonstrates RakNet's global compression feature.\n"); printf("When activated, outgoing and incoming data is tracked and saved to a frequency\n"); printf("table. This frequency table is then saved to disk and later loaded to generate\n"); printf("a Huffman encoding tree.\n"); printf("Difficulty: Intermediate\n\n"); // Pointers to the interfaces of our server and client. // Note we can easily have both in the same program FILE *serverToClientFrequencyTableFilePointer, *clientToServerFrequencyTableFilePointer; char serverToClientFrequencyTableFilename[100], clientToServerFrequencyTableFilename[100]; char buff[256]; RakPeerInterface *rakClient=RakNetworkFactory::GetRakPeerInterface(); RakPeerInterface *rakServer=RakNetworkFactory::GetRakPeerInterface(); // Frequency table tracking takes a bit of CPU power under high loads so is off by default. We need to turn it on // So RakNet will track data frequencies which we can then use to create the compression tables rakServer->SetCompileFrequencyTable(true); rakClient->SetCompileFrequencyTable(true); int i = rakServer->GetNumberOfAddresses(); // Just so we can remember where the packet came from bool isServer; // We are generating compression layers for both the client and the server just to demonstrate it // in practice you would only do one or the other depending on whether you wanted to run as a client or as a server // Note that both the client and the server both need both frequency tables and they must be the same puts("Enter the filename holding the server to client frequency table:"); gets(serverToClientFrequencyTableFilename); if (serverToClientFrequencyTableFilename[0]==0) strcpy(serverToClientFrequencyTableFilename, "s2c"); serverToClientFrequencyTableFilePointer = fopen(serverToClientFrequencyTableFilename, "rb"); if (serverToClientFrequencyTableFilePointer==0) { printf("Can't open %s\n", serverToClientFrequencyTableFilename); } else { unsigned int frequencyData[256]; int numRead; numRead=(int)fread(frequencyData, sizeof(unsigned int), 256, serverToClientFrequencyTableFilePointer); if (numRead != 256) puts("Error reading data"); else { rakClient->GenerateCompressionLayer(frequencyData, true); // server to client is input for the client so the last parameter is true rakServer->GenerateCompressionLayer(frequencyData, false); // server to client is output for the server so the last parameter is false puts("Compression layer generated for server to client data"); } fclose(serverToClientFrequencyTableFilePointer); } puts("Enter the filename holding the client to server frequency table:"); gets(clientToServerFrequencyTableFilename); if (clientToServerFrequencyTableFilename[0]==0) strcpy(clientToServerFrequencyTableFilename, "c2s"); clientToServerFrequencyTableFilePointer = fopen(clientToServerFrequencyTableFilename, "rb"); if (clientToServerFrequencyTableFilePointer==0) { printf("Can't open %s\n", clientToServerFrequencyTableFilename); } else { unsigned int frequencyData[256]; int numRead; numRead=(int)fread(frequencyData, sizeof(unsigned int), 256, clientToServerFrequencyTableFilePointer); if (numRead != 256) puts("Error reading data"); else { rakClient->GenerateCompressionLayer(frequencyData, false); // client to server is output for the client so the last parameter is false rakServer->GenerateCompressionLayer(frequencyData, true); // client to server is input for the server so the last parameter is true puts("Compression layer generated for server to client data"); } fclose(clientToServerFrequencyTableFilePointer); } // Crude interface puts("Run as (1) Client or (2) Server ?"); if ( gets(buff)&&(buff[0]=='1') ) { // Holds user data char ip[30], serverPort[30], clientPort[30]; // A client isServer=false; // Get our input puts("Enter the client port to listen on."); gets(clientPort); if (clientPort[0]==0) strcpy(clientPort, "60001"); puts("Enter IP to connect to"); gets(ip); if (ip[0]==0) strcpy(ip, "127.0.0.1"); puts("Enter the port to connect to"); gets(serverPort); if (serverPort[0]==0) strcpy(serverPort, "60000"); // Connecting the client is very simple. 0 means we don't care about // a connectionValidationInteger, and false for low priority threads SocketDescriptor socketDescriptor(atoi(clientPort),0); bool b= rakClient->Startup(1, 30, &socketDescriptor, 1); rakClient->Connect(ip, atoi(serverPort), 0, 0); if (b) puts("Attempting connection"); else { puts("Bad connection attempt. Terminating."); exit(1); } } else { // Holds user data char portstring[30]; // A server isServer=true; puts("Enter the server port to listen on"); gets(portstring); if (portstring[0]==0) strcpy(portstring, "60000"); puts("Starting server."); // Starting the server is very simple. 2 players allowed. // 0 means we don't care about a connectionValidationInteger, and false // for low priority threads SocketDescriptor socketDescriptor(atoi(portstring),0); bool b = rakServer->Startup(2, 30, &socketDescriptor, 1); rakServer->SetMaximumIncomingConnections(2); if (b) puts("Server started, waiting for connections."); else { puts("Server failed to start. Terminating."); exit(1); } } puts("Type 'quit' to quit or type to talk."); char message[400]; // Loop for input while (1) { if (kbhit()) { // Notice what is not here: something to keep our network running. It's // fine to block on gets or anything we want // Because the network engine was painstakingly written using threads. gets(message); if (strcmp(message, "quit")==0) { puts("Quitting."); break; } // Message now holds what we want to broadcast if (isServer) { char message2[420]; // Append Server: to the message so clients know that it ORIGINATED from the server // All messages to all clients come from the server either directly or by being // relayed from other cilents strcpy(message2, "Server: "); strcat(message2, message); // message2 is the data to send // strlen(message2)+1 is to send the null terminator // HIGH_PRIORITY doesn't actually matter here because we don't use any other priority // RELIABLE_ORDERED means make sure the message arrives in the right order // We arbitrarily pick 0 for the ordering stream // UNASSIGNED_SYSTEM_ADDRESS means don't exclude anyone from the broadcast // true means broadcast the message to everyone connected rakServer->Send(message2, (const int)strlen(message2)+1, HIGH_PRIORITY, RELIABLE_ORDERED, 0, UNASSIGNED_SYSTEM_ADDRESS, true); } else { // message is the data to send // strlen(message)+1 is to send the null terminator // HIGH_PRIORITY doesn't actually matter here because we don't use any other priority // RELIABLE_ORDERED means make sure the message arrives in the right order rakClient->Send(message, (const int)strlen(message)+1, HIGH_PRIORITY, RELIABLE_ORDERED, 0, UNASSIGNED_SYSTEM_ADDRESS, true); } } Packet *packet; packet = rakClient->Receive(); if (packet) { if (packet->data[0]>=ID_USER_PACKET_ENUM) { // It's a client, so just show the message printf("%s\n", packet->data); } rakClient->DeallocatePacket(packet); } packet = rakServer->Receive(); if (packet) { if (packet->data[0]>=ID_USER_PACKET_ENUM) { char message[200]; printf("%s\n", packet->data); // Relay the message. We prefix the name for other clients. This demonstrates // That messages can be changed on the server before being broadcast // Sending is the same as before sprintf(message, "%s", packet->data); rakServer->Send(message, (const int)strlen(message)+1, HIGH_PRIORITY, RELIABLE_ORDERED, 0, packet->systemAddress, true); } if (packet->data[0]>=ID_CONNECTION_REQUEST_ACCEPTED) { printf("ID_CONNECTION_REQUEST_ACCEPTED\n"); } rakServer->DeallocatePacket(packet); } } // Output statistics printf("Server: Compression ratio=%f. Decompression ratio=%f\n", rakServer->GetCompressionRatio(), rakServer->GetDecompressionRatio()); printf("Client: Compression ratio=%f. Decompression ratio=%f\n", rakClient->GetCompressionRatio(), rakClient->GetDecompressionRatio()); rakServer->Shutdown(100); rakClient->Shutdown(100); // Output the frequency table generated by this run if (isServer) puts("Enter the filename to use to save the server to client frequency table:"); else puts("Enter the filename to use to save the client to server frequency table:"); scanf("%s", serverToClientFrequencyTableFilename); if (serverToClientFrequencyTableFilename[0]==0) { if (isServer) strcpy(serverToClientFrequencyTableFilename, "s2c"); else strcpy(serverToClientFrequencyTableFilename, "c2s"); } serverToClientFrequencyTableFilePointer = fopen(serverToClientFrequencyTableFilename, "wb"); if (serverToClientFrequencyTableFilePointer==0) { printf("Can't open %s\n", serverToClientFrequencyTableFilename); } else { unsigned int frequencyData[256]; // Get the frequency table generated during the run if (isServer) rakServer->GetOutgoingFrequencyTable(frequencyData); else rakClient->GetOutgoingFrequencyTable(frequencyData); fwrite(frequencyData, sizeof(unsigned int), 256, serverToClientFrequencyTableFilePointer); fclose(serverToClientFrequencyTableFilePointer); } // We're done with the network RakNetworkFactory::DestroyRakPeerInterface(rakServer); RakNetworkFactory::DestroyRakPeerInterface(rakClient); return 0; }
 #pragma once #include <cstddef> namespace Lynx { namespace SmartPtr { template<typename T> class ScopedArr { public: ScopedArr(ScopedArr&) noexcept = delete; ScopedArr(ScopedArr&&) noexcept = delete; ScopedArr(const ScopedArr&) noexcept = delete; ScopedArr(const ScopedArr&&) noexcept = delete; ScopedArr& operator=(ScopedArr&) noexcept = delete; ScopedArr& operator=(ScopedArr&&) noexcept = delete; ScopedArr& operator=(const ScopedArr&) noexcept = delete; ScopedArr& operator=(const ScopedArr&&) noexcept = delete; bool operator==(const ScopedArr&) const noexcept = delete; bool operator!=(const ScopedArr&) const noexcept = delete; public: explicit ScopedArr(T* ptr = nullptr) noexcept : _ptr(ptr) { } virtual ~ScopedArr() noexcept { delete[] _ptr; _ptr = nullptr; } public: void Reset(T* ptr = nullptr) noexcept { delete[] _ptr; _ptr = ptr; } T& operator[](const std::size_t& index) const noexcept { return _ptr[index]; } T* Get() const noexcept { return _ptr; } T* Release() noexcept { T* ptr = _ptr; _ptr = nullptr; return ptr; } explicit operator bool() const noexcept { return static_cast<bool>(_ptr); } void Swap(ScopedArr& sa) noexcept { T* tmp = sa.Release(); sa.Reset(_ptr); _ptr = tmp; } public: using ElementType = T; protected: T* _ptr; }; } //# namespace SmartPtr } //# namespace Lynx namespace Lynx { template<typename T> void Swap(SmartPtr::ScopedArr<T>& a, SmartPtr::ScopedArr<T>& b) noexcept { a.Swap(b); } template<typename T> bool operator==(const SmartPtr::ScopedArr<T>& sp, std::nullptr_t) noexcept { return sp.Get() == nullptr; } template<typename T> bool operator==(std::nullptr_t, const SmartPtr::ScopedArr<T>& sp) noexcept { return sp.Get() == nullptr; } template<typename T> bool operator!=(const SmartPtr::ScopedArr<T>& sp, std::nullptr_t) noexcept { return sp.Get() != nullptr; } template<typename T> bool operator!=(std::nullptr_t, const SmartPtr::ScopedArr<T>& sp) noexcept { return sp.Get() != nullptr; } } //# namespace Lynx
/*========================================================================= Library : packages Module : $RCSfile: shreg.cc,v $ Authors : Daniel Rueckert Copyright : Imperial College, Department of Computing Visual Information Processing (VIP), 2000-2001 Purpose : Date : $Date: 2004/12/17 16:25:37 $ Version : $Revision: 1.7 $ Changes : $Locker: $ $Log: shreg.cc,v $ Revision 1.7 2004/12/17 16:25:37 dp1 Compilation with the new project Revision 1.6 2004/12/16 16:58:47 dr Introduced new transformation class hierachy Revision 1.5 2004/11/15 11:40:03 tp500 Made program give more feedback on the data it is given. Revision 1.3 2004/08/12 10:05:40 dr Added compatibility for VTK 4.4 and higher Revision 1.2 2004/07/22 10:54:12 dr Added #ifdef HAS_VTK Revision 1.1 2004/07/14 16:43:41 dr Imported sources =========================================================================*/ #ifdef HAS_VTK #include <vtkPolyData.h> #include <vtkPolyDataReader.h> #include <vtkCleanPolyData.h> #include <vtkFloatArray.h> #include <vtkPointData.h> #include <vtkImageData.h> #include <vtkFeatureEdges.h> #include <vtkKDTreePointLocator.h> #include <vtkGenericCell.h> #include <vtkBMPReader.h> #include <irtkLocator.h> #include <vtkPolyDataWriter.h> #include <irtkTransformation.h> #include <irtkSurfaceRegistration.h> //some global variables char *_target_name = NULL, *_source_name = NULL; char *dofin_name = NULL, *dofout_name = NULL; char *fov_image_name = NULL; void usage() { cerr << "Usage: shreg [target] [source] [subdivisions] <options> \n" << endl; cerr << "where <options> is one or more of the following:\n" << endl; cerr << "<-locator value> Locator: 0 = cell locator 1 = point locator 2 = kd-tree locator (default = point)" << endl; cerr << "<-dofin name> Name of input file" << endl; cerr << "<-dofout name> Name of output file" << endl; cerr << "<-ignoreedges> Ignores edges in ICP (default OFF)" << endl; cerr << "<-epsilon> Epsilon (default=0.01)" << endl; cerr << "<-numberofsteps> Number of steps (default 5)" << endl; cerr << "<-stepsize> Size of steps (default 5)" << endl; cerr << "<-iterations> Number of iterations (default 100)" << endl; cerr << "<-subdivide> Subdivide" << endl; cerr << "<-surfaces> Number of surfaces in the data"<<endl; cerr << "<-ds> value" << endl; cerr << "<-fovImage> Image to use when finding the fov bounds for dimensions of dofout." << endl; cerr << "<-fovDofin> Use the details of dofin as the dimensions of dofout." << endl; exit(1); } void MarkBoundary(vtkPolyData *polydata) { vtkFloatArray *scalars = vtkFloatArray::New(); vtkFeatureEdges *edges = vtkFeatureEdges::New(); edges->BoundaryEdgesOn(); edges->FeatureEdgesOff(); edges->ManifoldEdgesOff(); edges->NonManifoldEdgesOff(); edges->SetColoring(1); edges->SetInput(polydata); edges->Update(); int size_before_filtering = polydata->GetNumberOfPoints(); int size_after_filtering = edges->GetOutput()->GetNumberOfPoints(); VTKFloat xyz[3]; int closestPoint(0); vtkPointLocator *ploc = vtkPointLocator::New(); ploc->SetDataSet(polydata); ploc->BuildLocator(); scalars->SetNumberOfTuples(size_before_filtering); for (int counter = 0; counter < size_after_filtering; counter++){ edges->GetOutput()->GetPoint(counter, xyz); closestPoint = ploc->FindClosestPoint(xyz); scalars->InsertTuple1(closestPoint, 0); //if edge set scalar for point to zero } for (int c = 0; c < size_before_filtering; c++){ if (scalars->GetValue(c) != 0){ scalars->InsertTuple1(c, 1); } } scalars->SetName("EDGEPOINTS"); polydata->GetPointData()->AddArray(scalars); } int main(int argc, char **argv) { int i, elementsPerBucket, numberOfLevels; int locatorType, iterations; bool ok; float epsilon; double dx, dy, dz; bool ignoreEdges, subdivide; bool multipleSurfaces = false; int surfaces = 0; bool copyDofinDetails = false; irtkGreyImage fovImage; if (argc < 3){ usage(); } // Default parameters iterations = 100; elementsPerBucket = 5; locatorType = 1; epsilon = 0.01; ok = 0; ignoreEdges = false; subdivide = false; // Fix spacing dx = 20; dy = 20; dz = 20; // Parse filenames _target_name = argv[1]; argv++; argc--; _source_name = argv[1]; argv++; argc--; // Target pipeline cout << "Reading target ... " << _target_name; vtkPolyDataReader *target_reader = vtkPolyDataReader::New(); target_reader->SetFileName(_target_name); target_reader->Modified(); vtkPolyData *target = vtkPolyData::New(); target = target_reader->GetOutput(); target->Modified(); target->Update(); cout << " (" << target->GetNumberOfPoints() << " points)" << endl; // Source pipeline cout << "Reading source ... " << _source_name; vtkPolyDataReader *source_reader = vtkPolyDataReader::New(); source_reader->SetFileName(_source_name); source_reader->Modified(); source_reader->Update(); vtkPolyData *source = vtkPolyData::New(); source = source_reader->GetOutput(); source->Modified(); cout << " (" << source->GetNumberOfPoints() << " points)" << endl; // Number of subdivisions numberOfLevels = atoi(argv[1]); argc--; argv++; // Parse remaining parameters while (argc > 1) { ok = false; if ((ok == false) && (strcmp(argv[1], "-iterations") == 0)){ argc--; argv++; iterations = atoi(argv[1]); argc--; argv++; ok = true; } if ((ok == false) && (strcmp(argv[1], "-locator") == 0)){ argc--; argv++; locatorType = atoi(argv[1]); argc--; argv++; ok = true; } if ((ok == false) && (strcmp(argv[1], "-ignoreedges") == 0)){ argc--; argv++; ignoreEdges = true; MarkBoundary(target); ok = true; } if ((ok == false) && (strcmp(argv[1], "-dofout") == 0)){ argc--; argv++; dofout_name = argv[1]; argc--; argv++; ok = true; } if ((ok == false) && (strcmp(argv[1], "-dofin") == 0)){ argc--; argv++; dofin_name = argv[1]; argc--; argv++; ok = true; } if ((ok == false) && (strcmp(argv[1], "-epsilon") == 0)){ argc--; argv++; epsilon = atof(argv[1]); argc--; argv++; ok = true; } if ((ok == false) && (strcmp(argv[1], "-subdivide") == 0)){ argc--; argv++; subdivide = true; ok = true; } if ((ok == false) && (strcmp(argv[1], "-ds") == 0)){ argc--; argv++; dx = atof(argv[1]); dy = atof(argv[1]); dz = atof(argv[1]); argc--; argv++; ok = true; } if ((ok == false) && (strcmp(argv[1], "-surfaces") == 0)){ argc--; argv++; multipleSurfaces = true; ok = true; } if ((ok == false) && (strcmp(argv[1], "-fovImage") == 0)){ argc--; argv++; fov_image_name = argv[1]; argc--; argv++; ok = true; } if ((ok == false) && (strcmp(argv[1], "-fovDofin") == 0)){ argc--; argv++; copyDofinDetails = true; ok = true; } if (ok == false){ cerr << "Can not parse argument " << argv[1] << endl; usage(); } } irtkLocator *locator = new irtkLocator; locator->SelectLocatorType(locatorType); irtkSurfaceSimilarityNDDistanceMetric *metric = new irtkSurfaceSimilarityNDDistanceMetric; if (ignoreEdges) { metric->IgnoreEdges(); } irtkSurfaceAffineRegistration *registration; if ( multipleSurfaces == true){ registration = new irtkMSurfaceFreeFormRegistrationApproximation; } else registration = new irtkSurfaceFreeFormRegistrationApproximation; registration->SetInput(target, source); registration->SetNumberOfIterations(iterations); registration->SetEpsilon(epsilon); registration->SetMetric(metric); registration->SetLocator(locator); // Create initial multi-level free-form deformation irtkMultiLevelBSplineFreeFormTransformation *mffd = NULL; // Read transformation if (dofin_name != NULL){ if (irtkRigidTransformation::CheckHeader(dofin_name) == true){ mffd = new irtkMultiLevelBSplineFreeFormTransformation; mffd->irtkRigidTransformation::Read(dofin_name); } else { if (irtkAffineTransformation::CheckHeader(dofin_name) == true){ mffd = new irtkMultiLevelBSplineFreeFormTransformation; mffd->irtkAffineTransformation::Read(dofin_name); } else { if (irtkMultiLevelFreeFormTransformation::CheckHeader(dofin_name) == true){ mffd = new irtkMultiLevelBSplineFreeFormTransformation(dofin_name); } else { cerr << "Input transformation is not of type rigid, affine " << endl; cerr << "or multi-level free form deformation" << endl; exit(1); } } } } else { // Otherwise use identity transformation to start mffd = new irtkMultiLevelBSplineFreeFormTransformation; } double start_box[3], end_box[3]; VTKFloat *loc; double xaxis[3] = {1, 0, 0}; double yaxis[3] = {0, 1, 0}; if (fov_image_name != NULL){ // Use the image to get a bounding box for the lattice. fovImage.Read(fov_image_name); start_box[0] = 0; start_box[1] = 0; start_box[2] = 0; end_box[0] = fovImage.GetX()-1; end_box[1] = fovImage.GetY()-1; end_box[2] = fovImage.GetZ()-1; fovImage.ImageToWorld(start_box[0], start_box[1], start_box[2]); fovImage.ImageToWorld(end_box[0], end_box[1], end_box[2]); fovImage.GetOrientation(xaxis, yaxis); } else if (copyDofinDetails == true){ // Generate a dof with the dimensions as the dofin. if (dofin_name == NULL){ cout << "No dofin given from which to copy details." << endl; exit(1); } if (mffd->NumberOfLevels() > 1){ cout << "Can only copy details from a single level FFD." << endl; exit(1); } irtkBSplineFreeFormTransformation *ffd = mffd->GetLocalTransformation(0); ffd->BoundingBox(start_box[0], start_box[1], start_box[2], end_box[0], end_box[1], end_box[2]); ffd->GetSpacing(dx, dy, dz); ffd->GetOrientation(xaxis, yaxis); } else { // Get bounding box of data loc = source->GetBounds(); start_box[0] = *loc - dx; start_box[1] = *(loc+2) - dy; start_box[2] = *(loc+4) - dz; end_box[0] = *(loc+1) + dx; end_box[1] = *(loc+3) + dy; end_box[2] = *(loc+5) + dz; } cout << "Source Dimensions -- " << abs(start_box[0]-end_box[0]) << " x " << abs(start_box[1]-end_box[1]) << " x " << abs(start_box[2]-end_box[2]) << endl; cout << "Creating Grid -- " << abs(round((start_box[0]-end_box[0])/dx))+1 << " x " << abs(round((start_box[1]-end_box[1])/dy))+1 << " x " << abs(round((start_box[2]-end_box[2])/dz))+1 << endl; cout << "Grid spacing -- " << dx << "mm" << " " << dy << "mm" << " " << dz << "mm" << endl; // Create transformation irtkBSplineFreeFormTransformation *affd = new irtkBSplineFreeFormTransformation(start_box[0], start_box[1], start_box[2], end_box[0], end_box[1], end_box[2], dx, dy, dz, xaxis, yaxis); // Add ffd mffd->PushLocalTransformation(affd); for (i = 0; i < numberOfLevels-1; i++){ // Set up registration and run registration->SetOutput(mffd); registration->Run(); if (subdivide == false){ // Add transformation dx = dx/2.0; dy = dy/2.0; dz = dz/2.0; irtkBSplineFreeFormTransformation *affd = new irtkBSplineFreeFormTransformation(start_box[0], start_box[1], start_box[2], end_box[0], end_box[1], end_box[2], dx, dy, dz); mffd->PushLocalTransformation(affd); } else { // Extract current transformation level irtkBSplineFreeFormTransformation *affd = (irtkBSplineFreeFormTransformation *)mffd->GetLocalTransformation(0); // Subdivide affd->Subdivide(); } } // Set up registration and run registration->SetOutput(mffd); registration->Run(); // Write rigid transformation if (dofout_name != NULL){ mffd->Write(dofout_name); } } #else #include <irtkImage.h> int main( int argc, char *argv[] ){ cerr << argv[0] << " needs to be compiled with the VTK library " << endl; } #endif
#pragma once #include "viewport.h" namespace GLPlay { class PerspectiveViewport : public Viewport { public: PerspectiveViewport(int width, int height, float fov); virtual void Update(); private: float fov_; }; }
#ifndef BSCHEDULER_DAEMON_FACTORY_SOCKET_HH #define BSCHEDULER_DAEMON_FACTORY_SOCKET_HH #define BSCHEDULER_UNIX_DOMAIN_SOCKET "\0BSCHEDULER" #endif // vim:filetype=cpp
#include "CGame.h" #include "CBaseEngine.h" #include "DescriptorList.h" #include "gui/CEndFailure.h" #include "gui/CEndSuccess.h" void CGame::init(){ isBackground = false; m_time = 0; } void CGame::spawn(){ engine->map->setMapAsBackground(isBackground); CGuiPanel* hud = engine->gui->getHud(); engine->log("Adding label"); hud->addChild(m_startTimerText = new CLabel( vec2d(engine->getScreenWidth()/2., engine->getScreenHeight()/3. ), vec2d(0., engine->getScreenHeight()/6. ),"", true, CLabel::ALIGN_CENTER)); hud->addChild(m_timerText = new CLabel( vec2d(engine->getScreenWidth()-10., 6*engine->getScreenHeight()/7-10. ), vec2d(0., engine->getScreenHeight()/7. ),"0:00.00", true, CLabel::ALIGN_RIGHT)); fireOutput("onGameStart", this); engine->input->setEnabled(false); } void CGame::think(){ if(engine->getTime() < 2.){ }else if(engine->getTime() < 5.){ m_startTimerText->setText((format("%1%") % floor(6. - engine->getTime())).str()); }else if(engine->getTime() < 6.){ m_startTimerText->setText("Běž!"); engine->input->setEnabled(true); }else{ m_startTimerText->setText(""); } if(engine->getTime() >= 5.){ m_time = engine->getTime()-5.; m_timerText->setText(formatTime(m_time)); } } void CGame::endGameSuccess(CBaseEntity* originator){ engine->map->setMapTime(m_time); engine->gui->fadeTo(.9, 1.); CGuiPanel* temp = new CEndSuccess(); temp->setOpacity(0.); temp->fadeTo(1., 1.); engine->setTimeScale(0.); engine->gui->addElement(temp); engine->gui->enableCursor(true); engine->gui->enableEscape(false); } void CGame::endGameFailure(CBaseEntity* originator){ engine->gui->fadeTo(.9, 1.); CGuiPanel* temp = new CEndFailure(); temp->setOpacity(0.); temp->fadeTo(1., 1.); engine->setTimeScale(0.); engine->gui->addElement(temp); engine->gui->enableCursor(true); engine->gui->enableEscape(false); } REGISTER_ENTITY(CGame)
// Copyright (c) 2015, Baidu.com, Inc. All Rights Reserved // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "db/filename.h" #include <ctype.h> #include <limits.h> #include <stdint.h> #include <stdio.h> #include <iostream> #include "db/dbformat.h" #include "leveldb/env.h" #include "util/string_ext.h" namespace leveldb { // A utility routine: write "data" to the named file and Sync() it. extern Status WriteStringToFileSync(Env* env, const Slice& data, const std::string& fname); static std::string MakeFileName(const std::string& name, uint64_t number, const char* suffix) { char buf[100]; snprintf(buf, sizeof(buf), "/%08llu.%s", static_cast<unsigned long long>(number), suffix); return name + buf; } bool ParseDbName(const std::string& dbname, std::string* prefix, uint64_t* tablet, uint64_t* lg) { std::string::size_type pos1, pos2; assert(dbname[dbname.size() - 1] != '/'); pos2 = dbname.find_last_of("/"); assert(pos2 != std::string::npos); if (lg) { Slice lg_str(dbname.data() + pos2 + 1); assert(ConsumeDecimalNumber(&lg_str, lg)); } pos1 = dbname.find_last_of("/", pos2 - 1); assert(pos1 != std::string::npos); if (pos1 + 1 != dbname.find("tablet", pos1)) { if (prefix) { prefix->assign(dbname.substr(0, pos2)); } // have no tablet return false; } else { if (prefix) { prefix->assign(dbname.substr(0, pos1)); } if (tablet) { pos1 += 7; Slice tablet_str(dbname.data() + pos1, pos2 - pos1); assert(ConsumeDecimalNumber(&tablet_str, tablet)); } return true; } } std::string LogFileName(const std::string& name, uint64_t number) { assert(number > 0); return MakeFileName(name, number, "log"); } std::string LogHexFileName(const std::string& name, uint64_t number) { assert(number > 0); return name + std::string("/H") + Uint64ToString(number, 16) + ".log"; } std::string TableFileName(const std::string& name, uint64_t number) { assert(number > 0); if (number < (1ull << 63)) { return MakeFileName(name, number, "sst"); } uint64_t tablet = number >> 32 & 0x7fffffff; std::string dbname = RealDbName(name, tablet); return MakeFileName(dbname, number & 0xffffffff, "sst"); } std::string DescriptorFileName(const std::string& dbname, uint64_t number) { assert(number > 0); char buf[100]; snprintf(buf, sizeof(buf), "/MANIFEST-%06llu", static_cast<unsigned long long>(number)); return dbname + buf; } std::string CurrentFileName(const std::string& dbname) { return dbname + "/CURRENT"; } std::string LockFileName(const std::string& dbname) { return dbname + "/LOCK"; } std::string TempFileName(const std::string& dbname, uint64_t number) { assert(number > 0); return MakeFileName(dbname, number, "dbtmp"); } std::string InfoLogFileName(const std::string& dbname) { return dbname + "/LOG"; } // Return the name of the old info log file for "dbname". std::string OldInfoLogFileName(const std::string& dbname) { return dbname + "/LOG.old"; } // Owned filenames have the form: // dbname/CURRENT // dbname/LOCK // dbname/LOG // dbname/LOG.old // dbname/MANIFEST-[0-9]+ // dbname/[0-9]+.(log|sst) bool ParseFileName(const std::string& fname, uint64_t* number, FileType* type) { Slice rest(fname); if (rest == "CURRENT") { *number = 0; *type = kCurrentFile; } else if (rest == "LOCK") { *number = 0; *type = kDBLockFile; } else if (rest == "LOG" || rest == "LOG.old") { *number = 0; *type = kInfoLogFile; } else if (rest.starts_with("MANIFEST-")) { rest.remove_prefix(strlen("MANIFEST-")); uint64_t num; if (!ConsumeDecimalNumber(&rest, &num)) { return false; } if (!rest.empty()) { return false; } *type = kDescriptorFile; *number = num; } else { // Avoid strtoull() to keep filename format independent of the // current locale uint64_t num; if (!ConsumeDecimalNumber(&rest, &num)) { return false; } Slice suffix = rest; if (suffix == Slice(".log")) { *type = kLogFile; } else if (suffix == Slice(".sst")) { *type = kTableFile; } else if (suffix == Slice(".dbtmp")) { *type = kTempFile; } else { return false; } *number = num; } return true; } Status SetCurrentFile(Env* env, const std::string& dbname, uint64_t descriptor_number) { // Remove leading "dbname/" and add newline to manifest file name std::string manifest = DescriptorFileName(dbname, descriptor_number); Slice contents = manifest; assert(contents.starts_with(dbname + "/")); contents.remove_prefix(dbname.size() + 1); std::string tmp = TempFileName(dbname, descriptor_number); Status s = WriteStringToFileSync(env, contents.ToString() + "\n", tmp); if (s.ok()) { s = env->RenameFile(tmp, CurrentFileName(dbname)); } else { Log("[%s][dfs error] open dbtmp[%s] error, status[%s].\n", dbname.c_str(), tmp.c_str(), s.ToString().c_str()); } if (!s.ok()) { Log("[%s][dfs error] rename CURRENT[%s] error, status[%s].\n", dbname.c_str(), tmp.c_str(), s.ToString().c_str()); env->DeleteFile(tmp); } return s; } const char* FileTypeToString(FileType type) { switch (type) { case kLogFile: return "kLogFile"; case kDBLockFile: return "kDBLockFile"; case kTableFile: return "kTableFile"; case kDescriptorFile: return "kDescriptorFile"; case kCurrentFile: return "kCurrentFile"; case kTempFile: return "kTempFile"; case kInfoLogFile: return "kInfoLogFile"; default:; } return "kUnknown"; } uint64_t BuildFullFileNumber(const std::string& dbname, uint64_t number) { assert(number < UINT_MAX); uint64_t tablet, lg; std::string prefix; if (!ParseDbName(dbname, &prefix, &tablet, &lg)) { // have no tablet return number; } else { return (1UL << 63 | tablet << 32 | number); } } bool ParseFullFileNumber(uint64_t full_number, uint64_t* tablet, uint64_t* file) { if (tablet) { *tablet = (full_number >> 32 & 0x7FFFFFFF); } if (file) { *file = full_number & 0xffffffff; } return true; } std::string BuildTableFilePath(const std::string& prefix, uint64_t lg, uint64_t number) { uint64_t tablet = (number >> 32 & 0x7FFFFFFF); char buf[100]; snprintf(buf, sizeof(buf), "/tablet%08llu/%llu", static_cast<unsigned long long>(tablet), static_cast<unsigned long long>(lg)); std::string dbname = prefix + buf; return MakeFileName(dbname, number & 0xffffffff, "sst"); } std::string RealDbName(const std::string& dbname, uint64_t tablet) { assert(tablet < UINT_MAX); uint64_t tablet_old, lg; std::string prefix; if (!ParseDbName(dbname, &prefix, &tablet_old, &lg)) { return dbname; } char buf[100]; snprintf(buf, sizeof(buf), "/tablet%08llu/%llu", static_cast<unsigned long long>(tablet), static_cast<unsigned long long>(lg)); return prefix + buf; } std::string GetTabletPathFromNum(const std::string& tablename, uint64_t tablet) { assert(tablet > 0); char buf[32]; snprintf(buf, sizeof(buf), "/tablet%08llu", static_cast<unsigned long long>(tablet)); return tablename + buf; } std::string GetChildTabletPath(const std::string& parent_path, uint64_t tablet) { assert(tablet > 0); char buf[32]; snprintf(buf, sizeof(buf), "%08llu", static_cast<unsigned long long>(tablet)); return parent_path.substr(0, parent_path.size() - 8) + buf; } uint64_t GetTabletNumFromPath(const std::string& tabletpath) { Slice path = tabletpath; if (path.size() <= 14) { return 0; } path.remove_prefix(path.size() - 14); if (!path.starts_with("tablet")) { return 0; } path.remove_prefix(6); uint64_t tablet = 0; assert(ConsumeDecimalNumber(&path, &tablet)); return tablet; } bool IsTableFileInherited(uint64_t tablet, uint64_t number) { assert(number > UINT_MAX); uint64_t file_tablet = (number >> 32 & 0x7FFFFFFF); return (tablet == file_tablet) ? false : true; } std::string FileNumberDebugString(uint64_t full_number) { uint64_t tablet = (full_number >> 32 & 0x7FFFFFFF); uint64_t file = full_number & 0xffffffff; char buf[32]; snprintf(buf, sizeof(buf), "[%08llu %08llu.sst]", static_cast<unsigned long long>(tablet), static_cast<unsigned long long>(file)); return std::string(buf, 23); } } // namespace leveldb
#include <vector> using namespace std; class Solution { public: bool valid_num(int val) { int ival = val; while (ival) { int tmp = ival % 10; if (tmp == 0 || val % tmp != 0) return false; ival /= 10; } return true; } vector<int> selfDividingNumbers(int left, int right) { vector<int> res; for (int idx = left; idx <= right; ++idx) { if (valid_num(idx)) res.push_back(idx); } return res; } };
#include <stdio.h> #if defined flagWIN32 && defined flagMSC #include <corecrt_io.h> #endif #ifdef flagPOSIX #include <sys/types.h> #include <dirent.h> #include <unistd.h> #include <sys/types.h> #include <pwd.h> #include <sys/stat.h> #endif #ifdef flagWIN32 #define _WINSOCKAPI_ #include <windows.h> #include <fileapi.h> #include <stdlib.h> #include <string.h> #endif #undef GetFileTitle #include "Com.h" #if defined flagWIN32 typedef struct DIR DIR; struct dirent { char *d_name; }; #ifdef flagUWP typedef ::_finddata64i32_t _finddata_t; #endif DIR *opendir(const char *); int closedir(DIR *); struct dirent *readdir(DIR *); void rewinddir(DIR *); typedef ptrdiff_t handle_type; /* C99's intptr_t not sufficiently portable */ struct DIR { handle_type handle; /* -1 for failed rewind */ _finddata_t info; struct dirent result; /* d_name null iff first time */ String name; /* null-terminated char string */ }; DIR *opendir(const char *name) { DIR *dir = 0; if(name && name[0]) { size_t base_length = strlen(name); const char *all = /* search pattern must end with suitable wildcard */ strchr("/\\", name[base_length - 1]) ? "*" : "/*"; dir = new DIR(); dir->name = name + String(all); if((dir->handle = (handle_type) _findfirst(dir->name.Begin(), &dir->info)) != -1) { dir->result.d_name = 0; } else /* rollback */ { delete (dir); dir = 0; } } else { errno = EINVAL; } return dir; } int closedir(DIR *dir) { int result = -1; if(dir) { if(dir->handle != -1) { result = _findclose(dir->handle); } delete (dir); } if(result == -1) /* map all errors to EBADF */ { errno = EBADF; } return result; } struct dirent *readdir(DIR *dir) { struct dirent *result = 0; if(dir && dir->handle != -1) { if(!dir->result.d_name || _findnext(dir->handle, &dir->info) != -1) { result = &dir->result; result->d_name = dir->info.name; } } else { errno = EBADF; } return result; } void rewinddir(DIR *dir) { if(dir && dir->handle != -1) { _findclose(dir->handle); dir->handle = (handle_type) _findfirst(dir->name.Begin(), &dir->info); dir->result.d_name = 0; } else { errno = EBADF; } } #endif NAMESPACE_COM_BEGIN int Console::Get(char* line, int size) { if (!line || size <= 0) return 0; size_t i; for (i = 0; i < size - 1; ++i) { int ch = fgetc(stdin); if (ch == '\n' || ch == EOF) { break; } line[i] = ch; } line[i] = '\0'; return i; } void Console::Put(const char* msg) { int len = strlen(msg); if (len) fwrite(msg, len, 1, stdout); } NAMESPACE_COM_END #if 0 FileIn cin(stdin); FileOut cout(stdout), cerr(stderr); void Panic(String s) { LOG(" *** Panic: " + s + " ***"); #ifdef PLATFORM_POSIX signal(SIGILL, SIG_DFL); signal(SIGSEGV, SIG_DFL); signal(SIGBUS, SIG_DFL); signal(SIGFPE, SIG_DFL); #endif #ifdef flagDEBUG __BREAK__; #endif abort(); } void Assert(bool b, String s) { if (!b) Panic(s); } void AssertFalse(bool b, String s) { if (b) Panic(s); } String ToUpper(const String& s) { StringStream out; for(int i = 0; i < s.GetCount(); i++) out.Put(ToUpper(s[i])); return out.GetResult(); } String ToLower(const String& s) { StringStream out; for(int i = 0; i < s.GetCount(); i++) out.Put(ToLower(s[i])); return out.GetResult(); } #ifdef __GNUC__ typedef __attribute__((__may_alias__)) size_t WT; #define WS (sizeof(WT)) #endif void MemoryMoveSlow(void* dst, const void* src, int n) { char *d = (char*)dst; const char *s = (const char*)src; if (d==s) return; if ((uintptr_t)s-(uintptr_t)d-n <= -2*n) { MemoryCopySlow(d, s, n); return; } if (d<s) { #ifdef __GNUC__ if ((uintptr_t)s % WS == (uintptr_t)d % WS) { while ((uintptr_t)d % WS) { if (!n--) return; *d++ = *s++; } for (; n>=WS; n-=WS, d+=WS, s+=WS) *(WT *)d = *(WT *)s; } #endif for (; n; n--) *d++ = *s++; } else { #ifdef __GNUC__ if ((uintptr_t)s % WS == (uintptr_t)d % WS) { while ((uintptr_t)(d+n) % WS) { if (!n--) return; d[n] = s[n]; } while (n>=WS) n-=WS, *(WT *)(d+n) = *(WT *)(s+n); } #endif while (n) n--, d[n] = s[n]; } } String Time::ToString() const { char buffer [80]; strftime(buffer, 80, "%A %d.%m.%G %H:%M:%S", &t); return String(buffer); } Time GetSysTime() { time_t rawtime; time(&rawtime); Time time; struct tm tmp; #ifdef flagWIN32 localtime_s(&tmp, &rawtime); #else tmp = *localtime(&rawtime); #endif MemoryCopy(&time.Std(), &tmp, sizeof(struct tm)); return time; } Stream& Log() { static FileOut fout; static StringStream ss; // for early logging if (!fout.IsOpen()) { String exepath = GetExeFilePath(); if (exepath.IsEmpty()) { return ss; } else { String exe_title = GetFileTitle(exepath); String path = ConfigFile(exe_title + ".log"); int r0 = (path.GetString0()->GetRefs()); const char* p = path.Begin(); int r1 = (path.GetString0()->GetRefs()); RealizeDirectory(GetFileDirectory(path)); int r2 = (path.GetString0()->GetRefs()); //cout << path << ENDL; fout.Open(path); int r3 = (path.GetString0()->GetRefs()); fout << " *** " << GetSysTime().ToString() << " ***" << ENDL << " *** " << GetExeFilePath() << " ***" << ENDL; if (ss.GetSize()) fout << ss.GetResult(); fout.Flush(); int r4 = (path.GetString0()->GetRefs()); int s = r0 + r1 + r2 + r3 + r4; } } return fout; } Stream& Cout() { static FileOut fout(stdout); return fout; } Stream& Cin() { static FileOut fout(stderr); return fout; } Stream& Cerr() { static FileOut fout(stdin); return fout; } String exe_path; void SetExeFilePath(String s) { exe_path = s; } String GetExeFilePath() { return exe_path; } String GetHomeDir() { #ifdef flagPOSIX struct passwd *pw = getpwuid(getuid()); const char *homedir = pw->pw_dir; return homedir; #else char homedir[2048]; getenv_s(0, homedir, 2048, "USERPROFILE"); return homedir; #endif } extern String config_path; String ConfigFile(String file_name) { if (config_path.GetCount()) return AppendFileName(config_path, file_name); #ifdef flagWIN32 String dir = GetExeDirFile(""); #else String home_dir = GetHomeDir(); String upp = AppendFileName(home_dir, ".config"); upp = AppendFileName(upp, "u++"); String dir = AppendFileName(upp, GetFileTitle(GetExeFilePath())); #endif return AppendFileName(dir, file_name); } String GetFileName(String path) { int i = path.ReverseFind(DIR_SEPS); if (i >= 0) return path.Mid(i + 1); return path; } String GetFileTitle(String path) { String fname = GetFileName(path); int i = fname.ReverseFind("."); if (i >= 0) return fname.Left(i); return fname; } String GetFileDirectory(String path) { int i = path.ReverseFind("\\"); int j = path.ReverseFind("/"); if (i >= 0 && j >= 0) return path.Left(max(i, j)); if (i >= 0) return path.Left(i); if (j >= 0) return path.Left(j); return ""; } void RealizeDirectory(String dir) { if (dir.IsEmpty()) return; DIR* d = opendir(dir.Begin()); if (d) { closedir(d); } else { RealizeDirectory(GetFileDirectory(dir)); struct stat st = {0}; if (stat(dir.Begin(), &st) == -1) { #ifdef flagWIN32 //CreateDirectoryA(dir.Begin(), NULL); Panic("Not supported in UWP"); #else mkdir(dir.Begin(), 0700); #endif } } } void DeleteFile(String path) { unlink(path.Begin()); } void RenameFile(String oldpath, String newpath) { rename(oldpath.Begin(), newpath.Begin()); } String AppendFileName(String a, String b) { if (b.IsEmpty()) return a; if (a.IsEmpty()) return b; bool a_sep = a.ReverseFind(DIR_SEPS) == a.GetCount()-1; bool b_sep = b.Find(DIR_SEPS) == 0; if (!a_sep) { if (!b_sep) return a + DIR_SEPS + b; else return a + b; } else { if (!b_sep) return a + b; else return a + b.Mid(1); } } String GetParentDirectory(String path, int steps) { path = TrimBoth(path); String last_known_dir = path; for(int i = 0; i < steps; i++) { if (path.IsEmpty()) return last_known_dir; while (path.Right(1) == DIR_SEPS) path = path.Left(path.GetCount()-1); int j = path.ReverseFind(DIR_SEPS); #ifdef flagPOSIX if (!j) return DIR_SEPS; #endif if (j <= 0) return path; path = path.Left(j); last_known_dir = path; } return path; } String GetFileExt(String path) { for(int i = path.GetCount()-1; i >= 0; i--) { int chr = path[i]; if (chr == DIR_SEP) return ""; if (chr == '.') return path.Mid(i); } return ""; } String LoadFile(String path) { FileIn in; if (!in.Open(path)) return ""; int size = in.GetSize(); return in.Get(size); } String EscapeString(String s) { s.Replace("\n", "\\n"); s.Replace("\t", "\\t"); s.Replace("\r", "\\r"); s.Replace("\"", "\\\""); return s; } String EscapeCharacter(String s) { s.Replace("\n", "\\n"); s.Replace("\t", "\\t"); s.Replace("\r", "\\r"); s.Replace("\"", "\\\""); s.Replace("\'", "\\\'"); return s; } void StringParser::PassChar(int chr, bool do_pass_white) { if (!IsChar(chr)) throw Exc("unexpected char"); cursor++; if (do_pass_white) PassWhite(); } bool StringParser::Char(int chr) { int curchr = s[cursor]; if (curchr == chr) { cursor++; PassWhite(); return true; } return false; } int StringParser::ReadInt() { String i; while (IsDigit(s[cursor])) { i.Cat(s[cursor++]); } PassWhite(); return StrInt(i); } String StringParser::ReadId() { String id; while (cursor < s.GetCount()) { int chr = s[cursor]; if (IsSpace(chr)) break; if (chr == '\\') { cursor++; chr = s[cursor]; } if (IsAlpha(chr) || chr == '_' || IsDigit(chr)) { id.Cat(chr); cursor++; } else break; } PassWhite(); return id; } int StringParser::GetChar() { return s[cursor++]; } int StringParser::PeekChar() { return s[cursor]; } bool StringParser::IsChar(int chr) { return s[cursor] == chr; } void StringParser::PassWhite() { while (cursor < s.GetCount()) { int chr = s[cursor]; if (IsSpace(chr)) cursor++; else break; } } void ErrorSource::PrintHeader(String file, int line, int col) { if (src.GetCount()) cout << src << ":"; if (file.GetCount()) cout << file << ":"; else if (error_path.GetCount()) cout << error_path << ":"; if (line >= 0) cout << line << ":"; if (col >= 0) cout << col << ":"; } void ErrorSource::Internal(String msg) { PrintHeader(); cerr << " internal-error: " << msg << endl; } void ErrorSource::InternalWarning(String msg) { PrintHeader(); cerr << " internal-warning: " << msg << endl; } void ErrorSource::Error(String msg, int line, int col) { fail = true; PrintHeader("", line, col); cerr << " error: " << msg << endl; } void ErrorSource::Error(String msg, String file, int line, int col) { fail = true; PrintHeader(file, line, col); cerr << " error: " << msg << endl; } void ErrorSource::Error(String msg) { fail = true; PrintHeader(); cerr << " error: " << msg << endl; } void ErrorSource::Warning(String msg, int line, int col) { PrintHeader("", line, col); cerr << " warning: " << msg << endl; } void ErrorSource::Warning(String msg, String file, int line, int col) { PrintHeader(file, line, col); cerr << " warning: " << msg << endl; } void ErrorSource::Warning(String msg) { PrintHeader(); cerr << " warning: " << msg << endl; } void ErrorSource::Info(String msg) { PrintHeader(); cerr << " info: " << msg << endl; } String Join(const Vector<String>& v, String join_str, bool ignore_empty) { String out; for (const String& s : v) { if (s.IsEmpty() && ignore_empty) continue; if (!out.IsEmpty()) out << join_str; out << s; } return out; } Vector<String> Split(String to_split, String split_str, bool ignore_empty) { Vector<String> v; if (to_split.IsEmpty() || split_str.IsEmpty()) return v; int i = to_split.Find(split_str); if (i == -1) v.Add(to_split); else { int j = 0; while (i >= 0) { String str = to_split.Mid(j, i - j); if (str.GetCount() == 0) { if (!ignore_empty) v.Add(str); } else { v.Add(str); } i += split_str.GetCount(); j = i; i = to_split.Find(split_str, i); } i = to_split.GetCount(); String str = to_split.Mid(j, i - j); if (str.GetCount() == 0) { if (!ignore_empty) v.Add(str); } else { v.Add(str); } } return v; } #endif
#include "kernels/kernel_cpu.hpp" #include "kernels/kernel_v2.hpp" #if OCTORAD_HAVE_CUDA #include "kernels/kernel_gpu.hpp" #endif #include "utils/fx_case.hpp" #include "utils/fx_compare.hpp" #include "utils/scoped_timer.hpp" #include "utils/util.hpp" #include <chrono> #include <cstdio> #include <random> #include <ratio> #include <vector> #define LOAD_RANDOM_CASES 1 #define VERIFY_OUTCOMES 0 constexpr std::size_t CASE_COUNT = OCTORAD_DUMP_COUNT; constexpr std::size_t LOAD_CASE_COUNT = 100; template <typename K> struct case_runner { case_runner() : kernel() { } case_runner(case_runner const& other) = delete; case_runner(case_runner&& other) = delete; void run_case_on_kernel(octotiger::fx_case test_case) { using octotiger::are_ranges_same; octotiger::fx_args& a = test_case.args; kernel(a.opts_eos, a.opts_problem, a.opts_dual_energy_sw1, a.opts_dual_energy_sw2, a.physcon_A, a.physcon_B, a.physcon_c, a.er_i, a.fx_i, a.fy_i, a.fz_i, a.d, a.rho, a.sx, a.sy, a.sz, a.egas, a.tau, a.fgamma, a.U, a.mmw, a.X_spc, a.Z_spc, a.dt, a.clightinv); #if VERIFY_OUTCOMES if (verify_outcome) { bool const success = are_ranges_same(a.egas, test_case.outs.egas, "egas") && are_ranges_same(a.sx, test_case.outs.sx, "sx") && are_ranges_same(a.sy, test_case.outs.sy, "sy") && are_ranges_same(a.sz, test_case.outs.sz, "sz") && are_ranges_same(a.U, test_case.outs.U, "U"); if (!success) { throw octotiger::formatted_exception( "case % code integrity check failed", test_case.index); } } #endif } double operator()(octotiger::fx_case const test_case) { double cpu_kernel_duration{}; { scoped_timer<double, std::micro>{cpu_kernel_duration}; run_case_on_kernel(test_case); } return cpu_kernel_duration; } private: K kernel; }; #if LOAD_RANDOM_CASES std::size_t select_random_case(std::size_t min_val, std::size_t max_val) { static std::random_device rd; static std::mt19937 mt(rd()); static std::uniform_int_distribution<std::size_t> dist(min_val, max_val); return dist(mt); } #endif template <typename K> double run_kernel( std::vector<octotiger::fx_case>& test_cases, std::string const& title) { double overall_et{}; double pure_et{}; { scoped_timer<double> timer(overall_et); std::printf("***** %s *****\n", title.c_str()); case_runner<K> run_cpu_case; for (auto& test_case : test_cases) { pure_et += run_cpu_case(test_case); } } std::printf("total kernel execution time: %gus\n", pure_et); std::printf("overall execution time: %gs\n", overall_et); return pure_et; } int main() { try { std::printf("***** init device *****\n"); double dev_init_et{}; { scoped_timer<double, std::milli> timer(dev_init_et); octotiger::device_init(); } std::printf("initialized device in %gms\n", dev_init_et); std::printf("***** load cases *****\n"); std::vector<octotiger::fx_case> test_cases; double load_et{}; { scoped_timer<double> timer(load_et); test_cases.reserve(LOAD_CASE_COUNT); for (std::size_t i = 0; i < LOAD_CASE_COUNT; ++i) { double const perecent_loaded = 100.0 * static_cast<double>(i) / static_cast<double>(LOAD_CASE_COUNT); std::printf("\rloaded %g%% of the cases\t", perecent_loaded); std::fflush(stdout); #if LOAD_RANDOM_CASES std::size_t case_id = select_random_case(0, LOAD_CASE_COUNT - 1); test_cases.emplace_back(octotiger::import_case(case_id)); #else test_cases.emplace_back(octotiger::import_case(i)); #endif } } std::printf( "\rloaded %zd cases in %gs\t\t\n", test_cases.size(), load_et); // CPU case is the reference execution time double const ref_k_et = run_kernel<octotiger::radiation_cpu_kernel>( test_cases, "cpu kernel (reference)"); std::printf("speedup: %g\n", 1.0); auto v2_k_et = run_kernel<octotiger::radiation_v2_kernel>( test_cases, "cpu kernel (v2)"); std::printf("speedup: %g\n", ref_k_et / v2_k_et); #if OCTORAD_HAVE_CUDA auto gpu_k_et = run_kernel<octotiger::radiation_gpu_kernel>( test_cases, "gpu kernel (ported code)"); std::printf("speedup: %g\n", ref_k_et / gpu_k_et); #endif } catch (std::exception const& e) { std::printf("exception caught: %s\n", e.what()); return 1; } return 0; }
#include "stdafx.h" #include"AktivesVO.h" #include <iostream> #include <list> #include <map> #include <string> #include "ExceptionHandler.h" using namespace std; map <string, AktivesVO*> AktivesVO::mapAllObjects; extern double dGlobaleZeit; int AktivesVO::p_iMaxID = 1; AktivesVO::AktivesVO() : p_sName(""), lokaleZeit(0) { vInitialization(); } AktivesVO::AktivesVO(string namestr) : p_sName(namestr), lokaleZeit(0) { vInitialization(); } istream & AktivesVO::istreamInput(istream & in) { if (this->p_sName != "") { ExceptionHandler(3,"No empty Objects allowed"); } in >> this->p_sName; return in; } AktivesVO * AktivesVO::ptObject(string sName) { if (AktivesVO::NameValidation(sName)) { return AktivesVO::mapAllObjects[sName]; } else { ExceptionHandler(1,sName + "is not existing"); } } void AktivesVO::vAddPtObject(AktivesVO * Object) { if (AktivesVO::NameValidation(Object->p_sName)) { ExceptionHandler(1,"Object " + Object->p_sName + " already existing"); } else { AktivesVO::mapAllObjects[Object->p_sName] = Object; cout << Object->p_sName << " was added" << endl; } } void AktivesVO::vAddPtObjects(list<AktivesVO*> listObjects) { list<AktivesVO*>::iterator it; for (it = listObjects.begin(); it != listObjects.end(); it++) { AktivesVO::vAddPtObject((*it)); } } bool AktivesVO::NameValidation(string name) { if (AktivesVO::mapAllObjects.count(name) > 0) { return true; } else { return false; } } AktivesVO::~AktivesVO() { } void AktivesVO::vostreamAusgabe(ostream & out) { out.precision(2); out << fixed; out << resetiosflags(ios::right); out << setiosflags(ios::left); out << setw(6) << p_iID; out << setw(10) << p_sName; out << setw(5) << ":"; } void AktivesVO::vInitialization() { p_iID = p_iMaxID; p_iMaxID++; } string AktivesVO::returnName() { return p_sName; } ostream& operator <<(ostream& out, AktivesVO& fahrzeug) { fahrzeug.vostreamAusgabe(out); return out; } bool AktivesVO::operator==(const AktivesVO& aVO) { return p_iID == aVO.p_iID; } istream & operator>>(istream & in, AktivesVO & x) { x.istreamInput(in); return in; }
#pragma once #ifdef _WIN32_WCE # error CallStack cannot be used under Windows CE! #endif // includes #include <vector> #ifdef UNICODE #define DBGHELP_TRANSLATE_TCHAR #endif #pragma warning(push) #pragma warning(disable: 4091) // 'typedef ': ignored on left of '' when no variable is declared #include <dbghelp.h> #pragma warning(pop) namespace Debug { // forward references class Symbol; class SymbolManager; /// infos about a function call class FunctionCall { public: FunctionCall(DWORD64 dwIP = 0) :m_dwIP(dwIP) { } // get functions DWORD64 GetIP() const throw() { return m_dwIP; } DWORD64 ModuleBaseAddress() const throw() { return m_dwModuleBaseAddress; } const CString& GetFunctionName() const throw() { return m_cszFunctionName; } DWORD64 GetFunctionDisplacement() const throw() { return m_dwFunctionDisplacement; } const CString& SourceFilename() const throw() { return m_cszSourceFilename; } DWORD SourceLineNumber() const throw() { return m_dwSourceLineNumber; } // set functions void SetSymbol(Symbol& symbol); void SetModuleBaseAddress(DWORD64 dwModuleBaseAddress) { m_dwModuleBaseAddress = dwModuleBaseAddress; } void SetFunctionName(const CString& cszFunctionName) { m_cszFunctionName = cszFunctionName; } void SetSourceFilename(const CString& cszSourceFilename) { m_cszSourceFilename = cszSourceFilename; } void SetSourceLineNumber(DWORD dwSourceLineNumber) { m_dwSourceLineNumber = dwSourceLineNumber; } private: DWORD64 m_dwIP; ///< instruction pointer DWORD64 m_dwModuleBaseAddress; CString m_cszFunctionName; ///< function name DWORD64 m_dwFunctionDisplacement; ///< displacement from function start CString m_cszSourceFilename; DWORD m_dwSourceLineNumber; }; /// represents a call stack from a stack walk class CallStack { public: /// ctor; collects callstack from current function CallStack(); /// ctor; collects callstack from given process and thread CallStack(DWORD dwProcessId, DWORD dwThreadId); /// returns size of call stack size_t GetSize() const { return m_veCallStack.size(); } /// returns function call info const FunctionCall& GetFunctionCall(size_t uiIndex) const { ATLASSERT(uiIndex < GetSize()); return m_veCallStack[uiIndex]; } private: void CollectCallstack(HANDLE hProcess, HANDLE hThread, CONTEXT& context, SymbolManager& symbolManager); bool WalkStack(HANDLE hProcess, HANDLE hThread, DWORD dwMachineType, CONTEXT& context, STACKFRAME64& stackFrame); void AddStackFrame(HANDLE hProcess, const STACKFRAME64& stackFrame, Debug::SymbolManager& symManager); private: std::vector<FunctionCall> m_veCallStack; }; } // namespace Debug
class DisjointSet { // 并查集模板 public: int father[1005]; void init(int n) { for (int i = 0; i < n; i++) { father[i] = i; } } int find(int x) { return x == father[x] ? x : father[x] = find(father[x]); } void union2(int x, int y) { int rootX = find(x); int rootY = find(y); if (rootX != rootY) father[rootX] = rootY; } bool same(int x, int y) { return find(x) == find(y); } }; class Solution { public: vector<int> findRedundantConnection(vector<vector<int>>& edges) { // 本题使用并查集求解,最重要的是要明白什么是冗余连接。 // 冗余连接,通俗的说,就是从树变成环的最后一步。我们需要抛弃这一步,使得树的结构依然成立。 // 明白这一点,我们就知道可以用并查集的方法,在各个边合并之后,看哪个边的两个节点最早处于同一个集合。这个时候输出这条边即可 DisjointSet UnionFind; UnionFind.init(1005); // 初始化 for (int i = 0; i < edges.size(); i++) { if (UnionFind.same(edges[i][0], edges[i][1])) return {edges[i][0], edges[i][1]}; // 找到了冗余连接,输出 else UnionFind.union2(edges[i][0], edges[i][1]); // 不是冗余连接,那么就把两个点合并 } return {}; // 都没有冗余连接,那么输出空值 } }; // reference https://leetcode-cn.com/problems/redundant-connection/solution/684-rong-yu-lian-jie-bing-cha-ji-ji-chu-eartc/ // 最后说明一个可能存在的疑惑:题目中说的是输出最后连接的边,但是代码中是一遇到相同集合的边就输出,这样违背了题目的意思吗? // 其实没有违背。题目所谓的输出最后连接的边,其实就是第一条由树成环的边。我们这里输出的就是这个第一条成环的边,和题意相通,并不违背。
/*========================================================================= Library : packages Module : $RCSfile: volumechange.cc,v $ Authors : Daniel Rueckert Copyright : Imperial College, Department of Computing Visual Information Processing (VIP), 2000-2004 Purpose : Date : $Date: 2004/12/17 16:13:36 $ Version : $Revision: 1.1 $ Changes : $Locker: $ $Log: volumechange.cc,v $ Revision 1.1 2004/12/17 16:13:36 dr Imported sources =========================================================================*/ #include <irtkImage.h> #include <irtkTransformation.h> // Default filenames char *input_name = NULL, *output_name, *dof_name1 = NULL, *dof_name2 = NULL; void usage() { cerr << "Usage: consistency [mask] [mask-value] [dof1] [dof2]\n" << endl; cerr << " dof1 dof2 " << endl; cerr << "mask -----> image Y -----> mask" << endl; exit(1); } int main(int argc, char **argv) { int i, j, k, n, mask_value, xdim, ydim, zdim; double x1, y1, z1, x2, y2, z2, sum, sumsq, dispsq, mean; // Check command line if (argc != 5){ usage(); } // Parse image input_name = argv[1]; argc--; argv++; mask_value = atoi(argv[1]); argc--; argv++; dof_name1 = argv[1]; argc--; argv++; dof_name2 = argv[1]; argc--; argv++; // Read image // cout << "Reading image ... "; cout.flush(); irtkGreyImage *image = new irtkGreyImage(input_name); // cout << "done" << endl; // Read transformation irtkTransformation *transformation1; transformation1->irtkTransformation::Read(dof_name1); // transformation1->Invert(); irtkTransformation *transformation2; transformation2->irtkTransformation::Read(dof_name2); // transformation2->Invert(); n = 0; sum = 0; sumsq = 0; xdim = image->GetX(); ydim = image->GetY(); zdim = image->GetZ(); for (k = 0; k < zdim; k++){ for (j = 0; j < ydim; j++){ for (i = 0; i < xdim; i++){ if (image->Get(i, j, k) == mask_value){ x1 = x2 = i; y1 = y2 = j; z1 = z2 = k; image->ImageToWorld(x1, y1, z1); image->ImageToWorld(x2, y2, z2); transformation2->Transform(x2, y2, z2); transformation1->Transform(x2, y2, z2); x1 -= x2; y1 -= y2; z1 -= z2; dispsq = x1*x1 + y1*y1 + z1*z1; sum += sqrt(dispsq); sumsq += dispsq; n++; } } } } mean = sum / (double) n; cout << mean << "," << (sumsq / (double) n) - (mean * mean) << endl; // cout << "mean displacement: " << mean << endl; // cout << ", variance " << (sumsq / (double) n) - (mean * mean) << endl; }
#include "Benchmark.hpp" #include <algorithm> #include <exception> #include <iomanip> #include <iostream> #include <tuple> using namespace std::chrono; namespace Utils { namespace Timing { /* Static variables */ Benchmark * Benchmark::current = NULL; Benchmark::Benchmark(Benchmark * f, const std::string & n) : father(f), name(n) { #ifndef WIN32 openingTime = steady_clock::now(); #endif isTimerActive = false; } Benchmark * Benchmark::getCurrent() { if (current == NULL) open("Default"); return current; } void Benchmark::open(const std::string& benchmarkName) { Benchmark * newB = new Benchmark(current, benchmarkName); if (current != NULL) { current->children.push_back(namedBenchmark(benchmarkName, newB)); } current = newB; } void Benchmark::close(bool print) { if (current == NULL) throw std::runtime_error("No active benchmark to close"); Benchmark * toClose = current; #ifndef WIN32 toClose->closingTime = steady_clock::now(); #endif current = toClose->father; if (print) toClose->print(); // Suppress Benchmark if the link is lost if (current == NULL) delete(toClose); } double Benchmark::getTime() const { double elapsedTicks = double((closingTime - openingTime).count()); double time = elapsedTicks * steady_clock::period::num / steady_clock::period::den; return time; } double Benchmark::getSubTime() const { double t = 0; for (auto& c : children) { t += c.second->getTime(); } return t; } // Printable data: <name, elapsedTime, link> typedef std::tuple<std::string, double, Benchmark *> printableEntry; int cmp(const printableEntry& a, const printableEntry& b) { return std::get<1>(a) < std::get<1>(b); } void Benchmark::print() { // Formatting specifically int precision = 3; int width = 8; int oldPrecision = std::cout.precision(); std::cout.precision(precision); std::cout.setf(std::ios::fixed, std::ios::floatfield); print(0, width); // Restoring default std::cout.precision(oldPrecision); std::cout.unsetf(std::ios::floatfield); } void Benchmark::print(int depth, int width) { // Build and sort printable data typedef std::tuple<std::string, double, Benchmark *> printableEntry; std::vector<printableEntry> subFields; for(auto& c : children) { subFields.push_back(printableEntry(c.first, c.second->getTime(), c.second)); } // Add Unknown field only if there are other information if (subFields.size() > 0) { subFields.push_back(printableEntry("Unknown", getTime() - getSubTime(), NULL)); } // Ordering std::sort(subFields.begin(), subFields.end(), cmp); // Printing for(auto& f : subFields) { // For Benchmark, print them if (std::get<2>(f) != NULL){ std::get<2>(f)->print(depth + 1, width); } // Print entries else { for (int i = 0; i < depth + 1; i++) std::cout << '\t'; std::cout << std::setw(width) << (std::get<1>(f) * 1000) << " ms : " << std::get<0>(f) << std::endl; } } for (int i = 0; i < depth; i++) std::cout << '\t'; std::cout << std::setw(width) << getTime() * 1000 << " ms : " << name << std::endl; } } }
#ifndef ELEMENT_EXECUTOR_H #define ELEMENT_EXECUTOR_H #include <elements/element.h> /** * @brief Will perform the action on a given element */ class ElementExecutor { public: struct Data { Element::ConstPtr element; }; public: /** * @brief executes the given element * @param data the data required to execute the element * @return true on success, false otherwise */ static bool execute(const Data& data); }; #endif // ELEMENT_EXECUTOR_H
#pragma once #include <vector> class RuleSet { public: int getAmtOfNeighbours(int i, std::vector<bool*> field, int fieldWidth, int fieldHeight); virtual std::vector<bool*> applyRules(std::vector<bool*> field, int fieldWidth, int fieldHeight) = 0; RuleSet(); ~RuleSet(); private: std::vector<int> nrs1; std::vector<int> nrs2; std::vector<int> nrs3; std::vector<int> nrs4; std::vector<int> nrs5; std::vector<int> nrs6; std::vector<int> nrs7; };
/* Author: Градобоева Елизавета Group: СБС-001-о-01 Task#: 9.11 */ #include <iostream> using namespace std; class V_Coss { public: int n; double* p; V_Coss(int i, double x) { n = i; p = new double[n + 1]; p[0] = 1; for (int k = 1; k <= n; k++) p[k] = p[k - 1] * -x * x / (2 * k * (2 * k - 1)); } ~V_Coss() { delete[] p; } }; int main() { setlocale(LC_ALL, "rus"); cout << " Программа вычисляет значение Cos." << endl; int n, i; double x, s = 0; cout << "Введите значение переменной N= "; while (!(cin >> n )) { cin.clear(); while (cin.get() != '\n'); cout << "\nОшибка! Введена буква" << endl; cout << "ВВедите значение переменной N= "; } cout << "Введите значение переменной X = "; while (!(cin >> x )) { cin.clear(); while (cin.get() != '\n'); cout << "\nОшибка! Введена буква" << endl; cout << "ВВедите значение переменной X= "; } V_Coss obj(n, x); for (i = 0; i <= n; i++) s += obj.p[i]; cout << " Cos (" << x << ") = " << s << endl; return 0; }
// // UnitNode.cpp // Boids // // Created by Yanjie Chen on 3/2/15. // // #include "UnitNode.h" #include "../manager/ResourceManager.h" #include "../scene/BattleLayer.h" #include "../manager/AudioManager.h" #include "../ArmatureManager.h" #include "../BoidsMath.h" #include "../AI/Terrain.h" #include "../AI/Path.h" #include "../constant/BoidsConstant.h" #include "../Utils.h" #include "BulletNode.h" #include "JumpText.h" #include "ui/CocosGUI.h" #include "../BoidsMath.h" #include "../data/PlayerInfo.h" #include "../manager/AudioManager.h" #include "../unit/skill/SkillCache.h" #define DEFAULT_SHADOW_RADIUS 30.0 #define DEFAULT_HESITATE_FRAMES 15 #define DEFAULT_CATCH_UP_STOP_DISTANCE 250.0 #define DEFAULT_CATCH_UP_START_DISTANCE 700.0 #define DEFAULT_WANDER_RADIUS 200.0 using namespace cocos2d; UnitNode::UnitNode() : _state( eUnitState::Unknown_Unit_State ), _next_state( eUnitState::Unknown_Unit_State ), _guard_target( nullptr ), _walk_path( nullptr ), _tour_path( nullptr ), _is_charging( false ), _charging_effect( nullptr ), _chasing_target( nullptr ), _weapon( nullptr ), _armor( nullptr ), _boot( nullptr ), _accessory( nullptr ), _hint_node( nullptr ), _formation_pos( 0 ), _weight( 0 ), _is_leader( false ) { } UnitNode::~UnitNode() { CC_SAFE_RELEASE( _guard_target ); CC_SAFE_RELEASE( _walk_path ); CC_SAFE_RELEASE( _tour_path ); CC_SAFE_RELEASE( _chasing_target ); CC_SAFE_RELEASE( _weapon ); CC_SAFE_RELEASE( _armor ); CC_SAFE_RELEASE( _boot ); CC_SAFE_RELEASE( _accessory ); } eTargetCamp UnitNode::getCampByString( const std::string& camp_string ) { if( camp_string == UNIT_CAMP_ENEMY ) { return eTargetCamp::Enemy; } else if( camp_string == UNIT_CAMP_NEUTRAL ) { return eTargetCamp::NPC; } else if( camp_string == UNIT_CAMP_ALLY ) { return eTargetCamp::Ally; } else if( camp_string == UNIT_CAMP_PLAYER ) { return eTargetCamp::Player; } else if( camp_string == UNIT_CAMP_WILD ) { return eTargetCamp::Wild; } else if( camp_string == UNIT_CAMP_OPPONENT ) { return eTargetCamp::Unknown_Camp; } return eTargetCamp::Unknown_Camp; } std::string UnitNode::getStringByCamp( eTargetCamp camp ) { switch( camp ) { case eTargetCamp::Enemy: return UNIT_CAMP_ENEMY; case eTargetCamp::NPC: return UNIT_CAMP_NEUTRAL; case eTargetCamp::Ally: return UNIT_CAMP_ALLY; case eTargetCamp::Player: return UNIT_CAMP_PLAYER; case eTargetCamp::Wild: return UNIT_CAMP_WILD; default: break; } return ""; } UnitNode* UnitNode::create( BattleLayer* battle_layer, const cocos2d::ValueMap& unit_data ) { UnitNode* ret = new UnitNode(); if( ret && ret->init( battle_layer, unit_data ) ) { ret->autorelease(); return ret; } else { CC_SAFE_DELETE( ret ); return nullptr; } } bool UnitNode::init( BattleLayer* battle_layer, const cocos2d::ValueMap& unit_data ) { if( !TargetNode::init( battle_layer ) ) { return false; } ResourceManager* res_manager = ResourceManager::getInstance(); UnitData* target_data = UnitData::create( unit_data ); this->setTargetData( target_data ); _direction = Point::ZERO; _face = eUnitFace::Front; _is_charging = false; this->setConcentrateOnWalk( false ); auto itr = unit_data.find( "unit_camp" ); if( itr != unit_data.end() ) { this->setTargetCamp( UnitNode::getCampByString( itr->second.asString() ) ); } itr = unit_data.find( "tag_string" ); if( itr != unit_data.end() ) { this->setUnitTags( itr->second.asString() ); } itr = unit_data.find( "hold_position" ); if( itr != unit_data.end() ) { //no move behavior } else { //with move behavior } if( target_data->is_double_face ) { std::string resource = res_manager->getPathForResource( target_data->name, eResourceType::Character_Double_Face ); _front = ArmatureManager::getInstance()->createArmature( resource ); _back = nullptr; } else { std::string front_res = res_manager->getPathForResource( target_data->name, eResourceType::Character_Front ); _front = ArmatureManager::getInstance()->createArmature( front_res ); std::string back_res = res_manager->getPathForResource( target_data->name, eResourceType::Character_Back ); _back = ArmatureManager::getInstance()->createArmature( back_res ); } if( _front ) { _front->setScale( target_data->scale ); _desired_unit_scale = target_data->scale; _front->setStartListener( CC_CALLBACK_1( UnitNode::onSkeletonAnimationStart, this ) ); _front->setCompleteListener( CC_CALLBACK_1( UnitNode::onSkeletonAnimationCompleted, this ) ); _front->setEventListener( CC_CALLBACK_2( UnitNode::onSkeletonAnimationEvent, this ) ); this->addChild( _front, eComponentLayer::Object ); Rect bounding_box = _front->getBoundingBox(); this->setContentSize( bounding_box.size ); } if( _back ) { _back->setScale( target_data->scale ); _back->setStartListener( CC_CALLBACK_1( UnitNode::onSkeletonAnimationStart, this ) ); _back->setCompleteListener( CC_CALLBACK_1( UnitNode::onSkeletonAnimationCompleted, this ) ); _back->setEventListener( CC_CALLBACK_2( UnitNode::onSkeletonAnimationEvent, this ) ); this->addChild( _back, eComponentLayer::Object ); } //shadow _shadow = Sprite::createWithSpriteFrameName( "unit_shadow.png" ); _shadow->setScale( target_data->collide / DEFAULT_SHADOW_RADIUS ); this->addChild( _shadow, eComponentLayer::MostBelow ); _same_dir_frame_count = 0; this->setHesitateFrame( DEFAULT_HESITATE_FRAMES ); this->setChasingTarget( nullptr ); this->setShouldCatchUp( false ); //debug // _custom_draw = DrawNode::create(); // _custom_draw->drawLine( Point::ZERO, Point( 100.0, 0 ), Color4F::YELLOW ); // this->addChild( _custom_draw, 10000 ); // // _new_dir_draw = DrawNode::create(); // _new_dir_draw->drawLine( Point::ZERO, Point( 100.0, 0 ), Color4F::BLUE ); // this->addChild( _new_dir_draw, 10001 ); // // _custom_draw->drawCircle( Point::ZERO, target_data->collide, 360, 100, false, Color4F::RED ); //end debug _face = eUnitFace::Back; this->setCurrentSkeleton( _front ); this->changeUnitDirection( Point( 1.0f, 0 ) ); this->setNextUnitState( eUnitState::Unknown_Unit_State ); this->changeUnitState( eUnitState::Idle ); this->setWanderRadius( DEFAULT_WANDER_RADIUS ); _relax_frames = 0; //skill for( auto v : target_data->skills ) { Skill* skill = Skill::create( this, v.asValueMap() ); _skills.pushBack( skill ); } Rect bounding_box = _current_skeleton->getBoundingBox(); float hpbar_width = DEFAULT_HP_BAR_WIDTH; float hpbar_height = DEFAULT_HP_BAR_HEIGHT; _hp_bar = HpBar::create( Size( hpbar_width, hpbar_height ) ); _hp_bar->setPosition( Point( 0, bounding_box.size.height * ( 1.0f - _current_skeleton->getAnchorPoint().y ) + 10.0f ) ); this->addChild( _hp_bar, eComponentLayer::OverObject ); itr = unit_data.find( "is_boss" ); if( itr != unit_data.end() ) { this->setBoss( itr->second.asBool() ); this->hideHP(); } else { this->setBoss( false ); itr = unit_data.find( "show_hp" ); if( itr != unit_data.end() ) { if( itr->second.asBool() ) { this->showHP(); } else { this->hideHP(); } } } _has_hint_node = true; if( this->isBoss() ) { this->setUnitWeight( UNIT_WEIGHT_BOSS ); } return true; } void UnitNode::updateFrame( float delta ) { if( _relax_frames > 0 && _state == eUnitState::Idle ) { --_relax_frames; } ++_same_dir_frame_count; this->updateBuffs( delta ); if( this->isUnderControl() ) { bool under_control = false; for( auto pair : _buffs ) { Buff* buff = pair.second; if( buff->getBuffType() == BUFF_TYPE_STUN || buff->getBuffType() == BUFF_TYPE_PIERCE ) { under_control = true; break; } } if( !under_control ) { this->changeUnitState( eUnitState::Idle, true ); } } TargetNode::updateFrame( delta ); this->updateHintNode( delta ); this->applyUnitState(); this->updateSkills( delta ); this->evaluateCatchUp(); if( this->isAlive() && _is_charging && _charging_effect != nullptr ) { _charging_effect->setPosition( this->getLocalBonePos( "ChargingPoint" ) ); } ElementData* unit_data = this->getTargetData(); unit_data->current_hp = clampf( unit_data->current_hp + unit_data->recover * delta, 0, unit_data->hp ); unit_data->current_mp = clampf( unit_data->current_mp + unit_data->recover * delta, 0, unit_data->mp ); } void UnitNode::onSkeletonAnimationStart( int track_index ) { spTrackEntry* entry = this->getCurrentSkeleton()->getCurrent(); std::string animation_name = std::string( entry->animation->name ); if( animation_name == "Attack" ) { } else if( animation_name == "Cast" || animation_name == "Cast2" ) { } else if( animation_name == "Die" ) { std::string audio_res = this->getUnitData()->name + "/die.mp3"; AudioManager::getInstance()->playEffect( audio_res ); } } void UnitNode::onSkeletonAnimationEnded( int track_index ) { } void UnitNode::onSkeletonAnimationCompleted( int track_index ) { spTrackEntry* entry = this->getCurrentSkeleton()->getCurrent(); std::string animation_name = std::string( entry->animation->name ); if( animation_name == "Attack" ) { this->changeUnitState( eUnitState::Idle ); } else if( animation_name == "Cast_2" || animation_name == "Cast2_2" ) { this->endSkill(); this->changeUnitState( eUnitState::Idle ); } else if( animation_name == "Cast" || animation_name == "Cast2" ) { if( _using_skill_params["multi_action"].asBool() ) { if( _using_skill_params["state"].asString() == "start" ) { this->changeUnitState( eUnitState::Casting, true ); _using_skill_params["state"] = Value( "continue" ); } } else { this->endSkill(); this->changeUnitState( eUnitState::Idle ); } } // else if( animation_name == "Cast_1" || animation_name == "Cast2_1" ) { // if( _using_skill_params["state"].asString() == "end" ) { // _unit_state_changed = true; // this->setNextUnitState( eUnitState::Casting ); // } // } else if( animation_name == "Die" ) { this->changeUnitState( eUnitState::Disappear, true ); } } void UnitNode::onSkeletonAnimationEvent( int track_index, spEvent* event ) { spTrackEntry* entry = this->getCurrentSkeleton()->getCurrent(); std::string animation_name = std::string( entry->animation->name ); std::string event_name = std::string( event->data->name ); if( ( animation_name == "Cast" || animation_name == "Cast2" ) && event_name == "OnCasting" ) { this->onCasting(); int sk_id = _using_skill_params["skill_id"].asInt(); std::string audio_res = this->getUnitData()->name + Utils::stringFormat( "/cast%d.mp3", sk_id + 1 ); AudioManager::getInstance()->playEffect( audio_res ); } else if( animation_name == "Attack" && event_name == "OnAttacking" ) { std::string audio_res = this->getUnitData()->name + "/attack.mp3"; AudioManager::getInstance()->playEffect( audio_res ); this->onAttacking(); } else if( animation_name == "Attack" && event_name == "OnAttackBegan" ) { this->onAttackBegan(); } else if( animation_name == "Cast" && event_name == "OnJuneng" ) { this->onCharging(); } else if( animation_name == "Cast2" && event_name == "OnJuneng" ) { this->onCharging(); } } TargetNode* UnitNode::getChasingTarget() { if( _chasing_target && _chasing_target->isDying() ) { this->setChasingTarget( nullptr ); } return _chasing_target; } void UnitNode::setChasingTarget( TargetNode* target ) { CC_SAFE_RETAIN( target ); CC_SAFE_RELEASE( _chasing_target ); _chasing_target = target; } void UnitNode::changeUnitState( eUnitState new_state, bool force ) { if( ( _state >= eUnitState::Dying && new_state < _state ) || ( _next_state >= eUnitState::Dying && new_state < _next_state ) ) { return; } if( force || ( ( _next_state == eUnitState::Unknown_Unit_State && new_state != _state ) || new_state >= eUnitState::Dying ) ) { if( _next_state == eUnitState::UnderControl && new_state < _next_state ) { return; } _next_state = new_state; _unit_state_changed = true; if( _next_state != _state ) { _current_skeleton->clearTrack(); } if( _next_state == eUnitState::UnderControl ) { SkillCache::getInstance()->removeSkillOfOwner( this ); this->endSkill(); } } } void UnitNode::applyUnitState() { if( _unit_state_changed ) { _unit_state_changed = false; _state = _next_state; _next_state = eUnitState::Unknown_Unit_State; if( _state == eUnitState::Attacking ) { _front->setTimeScale( _target_data->atk_speed ); if( _back ) { _back->setTimeScale( _target_data->atk_speed ); } } else { _front->setTimeScale( 1.0f ); if( _back ) { _back->setTimeScale( 1.0f ); } } switch( _state ) { case eUnitState::Casting: { std::string state = _using_skill_params["state"].asString(); int sk_id = _using_skill_params.at( "skill_id" ).asInt(); if( state == "start" ) { if( sk_id == 0 ) { _current_skeleton->setAnimation( 0, "Cast", false ); } else if( sk_id == 1 ) { if( _current_skeleton->setAnimation( 0, "Cast2", false ) == nullptr ) { _current_skeleton->setAnimation( 0, "Cast", false ); } } } else if( state == "end" ) { if( sk_id == 0 ) { _current_skeleton->setAnimation( 0, "Cast_2", false ); } else if( sk_id == 1 ) { _current_skeleton->setAnimation( 0, "Cast2_2", false ); } } else if( _using_skill_params["multi_action"].asBool() ) { if( sk_id == 0 ) { _current_skeleton->setAnimation( 0, "Cast_1", true ); } else if( sk_id == 1 ) { _current_skeleton->setAnimation( 0, "Cast2_1", true ); } } } break; case eUnitState::Walking: if( _is_charging ) { _current_skeleton->setAnimation( 0, "Walk2", true ); } else { _current_skeleton->setAnimation( 0, "Walk", true ); } break; case eUnitState::Idle: if( _is_charging ) { _current_skeleton->setAnimation( 0, "Idle2", true ); } else { _current_skeleton->setAnimation( 0, "Idle", true ); } break; case eUnitState::Attacking: _current_skeleton->setAnimation( 0, "Attack", false ); break; case eUnitState::Dying: if( _current_skeleton->setAnimation( 0, "Die", false ) == nullptr ) { this->changeUnitState( eUnitState::Disappear, true ); } else { this->onDying(); } break; case eUnitState::Disappear: this->disappear(); break; case eUnitState::UnderControl: _current_skeleton->setAnimation( 0, "Stun", true ); break; case eUnitState::Dead: break; default: break; } } } void UnitNode::changeUnitDirection( const cocos2d::Point& new_dir ) { eUnitFace new_face = new_dir.y > 0 ? eUnitFace::Back : eUnitFace::Front; this->changeFace( new_face ); UnitData* unit_data = dynamic_cast<UnitData*>( _target_data ); int flipped_x = 0; if( new_dir.y > 0 ) { if( new_dir.x > 0 ) { flipped_x = ( unit_data->default_face_dir == 2 || unit_data->default_face_dir == 3 ) ? 1 : 0; } else { flipped_x = ( unit_data->default_face_dir == 0 || unit_data->default_face_dir == 1 ) ? 1 : 0; } } else { if( new_dir.x > 0 ) { flipped_x = ( unit_data->default_face_dir == 1 || unit_data->default_face_dir == 3 ) ? 1 : 0; } else { flipped_x = ( unit_data->default_face_dir == 0 || unit_data->default_face_dir == 2 ) ? 1 : 0; } } if( this->getCurrentSkeleton()->getSkeleton()->flipX != flipped_x ) { _front->getSkeleton()->flipX = flipped_x; if( _back ) { _back->getSkeleton()->flipX = flipped_x; } _same_dir_frame_count = 0; } Point normalized_dir = new_dir; normalized_dir.normalize(); //debug // _custom_draw->setRotation( -new_dir.getAngle() * 180 / M_PI ); //end debug this->setUnitDirection( normalized_dir ); } void UnitNode::changeFace( eUnitFace face ) { UnitData* unit_data = dynamic_cast<UnitData*>( _target_data ); if( !unit_data->is_double_face ) { if( _face != face ) { if( face == eUnitFace::Front ) { _front->setVisible( true ); _back->setVisible( false ); _back->clearTrack(); this->setCurrentSkeleton( _front ); } else { _front->setVisible( false ); _back->setVisible( true ); _front->clearTrack(); this->setCurrentSkeleton( _back ); } _face = face; this->changeUnitState( _state, true ); _same_dir_frame_count = 0; } } } cocos2d::Point UnitNode::getLocalHitPos() { return ArmatureManager::getInstance()->getBonePosition( _current_skeleton, "shen" ); } cocos2d::Point UnitNode::getHitPos() { Point ret = this->getLocalHitPos(); ret = _current_skeleton->convertToWorldSpace( ret ); ret = this->getParent()->convertToNodeSpace( ret ); return ret; } cocos2d::Point UnitNode::getEmitPos() { Point ret = ArmatureManager::getInstance()->getBonePosition( _current_skeleton, "EmitPoint" ); ret = _current_skeleton->convertToWorldSpace( ret ); ret = this->getParent()->convertToNodeSpace( ret ); return ret; } cocos2d::Point UnitNode::getLocalEmitPos() { return ArmatureManager::getInstance()->getBonePosition( _current_skeleton, "EmitPoint" ); } cocos2d::Point UnitNode::getLocalHeadPos() { return ArmatureManager::getInstance()->getBonePosition( _current_skeleton, "tou" ); } cocos2d::Point UnitNode::getBonePos( const std::string& bone_name ) { Point ret = this->getLocalBonePos( bone_name ); ret = _current_skeleton->convertToWorldSpace( ret ); ret = this->getParent()->convertToNodeSpace( ret ); return ret; } cocos2d::Point UnitNode::getLocalBonePos( const std::string& bone_name ) { return ArmatureManager::getInstance()->getBonePosition( _current_skeleton, bone_name ); } void UnitNode::appear() { std::string resource = "effects/unit_appear"; spine::SkeletonAnimation* appear_effect = ArmatureManager::getInstance()->createArmature( resource ); UnitNodeSpineComponent* component = UnitNodeSpineComponent::create( appear_effect, "unit_appear_effect", true ); component->setPosition( this->getLocalHitPos() ); this->addUnitComponent( component, component->getName(), eComponentLayer::OverObject ); component->setAnimation( 0, "animation", false ); } void UnitNode::disappear() { _front->clearTrack(); if( _back ) { _back->clearTrack(); } FadeTo* fadeout = FadeTo::create( 1.2f, 0 ); CallFunc* callback = CallFunc::create( CC_CALLBACK_0( UnitNode::onDisappearEnd, this ) ); Sequence* seq = Sequence::create( fadeout, callback, nullptr ); _current_skeleton->runAction( seq ); } void UnitNode::onDisappearEnd() { this->removeAllUnitComponents(); if( _hint_node ) { _hint_node->removeFromParent(); _hint_node = nullptr; } this->changeUnitState( eUnitState::Dead, true ); } void UnitNode::onDying() { this->removeAllBuffs(); Sprite* blood = Sprite::createWithSpriteFrameName( "unit_deadblood.png" ); UnitNodeFadeoutComponent* component = UnitNodeFadeoutComponent::create( blood, "dead_blood", 3.0f, 0, true ); component->setPosition( Point::ZERO ); this->addUnitComponent( component, component->getName(), eComponentLayer::BelowObject ); } void UnitNode::takeDamage( const cocos2d::ValueMap& result, TargetNode* atker ) { this->takeDamage( result.at( "damage" ).asFloat(), result.at( "cri" ).asBool(), result.at( "miss" ).asBool(), atker ); } void UnitNode::takeDamage( float amount, bool is_cri, bool is_miss, TargetNode* atker ) { if( this->isAlive() ) { UnitData* unit_data = dynamic_cast<UnitData*>( _target_data ); if( this->isAttackable() && unit_data->current_hp > 0 ) { float damage = amount; for( auto itr = _buffs.begin(); itr != _buffs.end(); ++itr ) { damage = itr->second->filterDamage( damage, atker ); } unit_data->current_hp -= damage; //jump damage number std::string jump_text_name = Utils::stringFormat( "damage_number_%d", BulletNode::getNextBulletId() ); this->jumpNumber( damage, "damage", is_cri, jump_text_name ); //update blood bar if( this->isBoss() ) { float percent = 100.0f * _target_data->current_hp / _target_data->hp; if( percent < 0 ) { percent = 0; } _battle_layer->getUIBattleLayer()->setBossHpPercent( percent ); } else if( this->getTargetCamp() == eTargetCamp::Player ) { float percent = _target_data->current_hp / _target_data->hp * 100.0f; if( percent < 0 ) { percent = 0; } _hp_bar->setPercentage( percent ); } //dying if( unit_data->current_hp <= 0 ) { _battle_layer->clearChasingTarget( this ); SkillCache::getInstance()->removeSkillOfOwner( this ); this->endSkill(); this->changeUnitState( eUnitState::Dying, true ); } else if( _chasing_target == nullptr ) { if( atker && atker->isAttackable() && atker->isAlive() ) { this->setChasingTarget( atker ); } } } } } void UnitNode::takeHeal( const cocos2d::ValueMap& result, int source_id ) { this->takeHeal( result.at( "damage" ).asFloat(), result.at( "cri" ).asBool(), source_id ); } void UnitNode::takeHeal( float amount, bool is_cri, int source_id ) { _target_data->current_hp += amount; if( _target_data->current_hp > _target_data->hp ) { _target_data->current_hp = _target_data->hp; } //add heal effect std::string resource = "effects/heal"; std::string component_name = Utils::stringFormat( "heal_effect_%d", BulletNode::getNextBulletId() ); spine::SkeletonAnimation* effect = ArmatureManager::getInstance()->createArmature( resource ); effect->setScale( 0.7f ); UnitNodeSpineComponent* component = UnitNodeSpineComponent::create( effect, component_name, true ); component->setPosition( Point::ZERO ); this->addUnitComponent( component, component_name, eComponentLayer::OverObject ); component->setAnimation( 0, "animation", false ); //update blood bar _hp_bar->setPercentage( _target_data->current_hp / _target_data->hp * 100.0f ); //jump number std::string jump_text_name = Utils::stringFormat( "heal_number_%d", BulletNode::getNextBulletId() ); this->jumpNumber( amount, "heal", is_cri, jump_text_name ); } void UnitNode::setGLProgrameState( const std::string& name ) { GLProgramState* gl_program_state = GLProgramState::getOrCreateWithGLProgramName( name ); if( gl_program_state ) { _front->setGLProgramState( gl_program_state ); if( _back ) { _back->setGLProgramState( gl_program_state ); } } } void UnitNode::showHP() { _show_hp = true; if( _hp_bar ) { _hp_bar->setVisible( true ); } } void UnitNode::hideHP() { _show_hp = false; if( _hp_bar ) { _hp_bar->setVisible( false ); } } void UnitNode::applyCustomChange( const std::string& content_string ) { std::vector<std::string> change_pairs; Utils::split( content_string, change_pairs, ',' ); for( auto str : change_pairs ) { std::vector<std::string> pair; Utils::split( str, pair, ':' ); std::string key = pair.at( 0 ); std::string value = pair.at( 1 ); if( key == "attackable" ) { this->setAttackable( value == "true" ); } else { _target_data->setAttribute( pair.at( 0 ), pair.at( 1 ) ); } _front->setScale( _target_data->scale ); _desired_unit_scale = _target_data->scale; if( _back ) { _back->setScale( _target_data->scale ); } } } void UnitNode::addBuff( const std::string& buff_id, Buff* buff, bool replace ) { if( replace ) { Buff* old_buff = this->getBuffOfType( buff->getBuffType() ); if( old_buff ) { old_buff->end(); } } _buffs.insert( buff_id, buff ); } void UnitNode::removeBuff( const std::string& buff_id ) { auto itr = _buffs.find( buff_id ); if( itr != _buffs.end() ) { _buffs.erase( itr ); } } bool UnitNode::hasBuff( const std::string& buff_id ) { auto itr = _buffs.find( buff_id ); return itr != _buffs.end(); } bool UnitNode::hasBuffOfType( const std::string& buff_type ) { return this->getBuffOfType( buff_type ) != nullptr; } Buff* UnitNode::getBuffOfType( const std::string& buff_type ) { for( auto itr = _buffs.begin(); itr != _buffs.end(); ++itr ) { if( itr->second->getBuffType() == buff_type ) { return itr->second; } } return nullptr; } void UnitNode::removeAllBuffs() { for( auto pair : _buffs ) { pair.second->end(); } _buffs.clear(); } void UnitNode::removeAllDebuffs() { for( auto pair : _buffs ) { Buff* buff = pair.second; if( buff->getBuffGroup() == eBuffGroup::BuffGroupDebuff ) { buff->end(); } } } void UnitNode::clearItems() { _items.clear(); } void UnitNode::addItem( Item* item ) { _items.insert( item->getItemId(), item ); Sprite* item_sprite = Sprite::createWithSpriteFrameName( item->getResource() ); UnitNodeComponent* component = UnitNodeComponent::create( item_sprite, item->getName(), true ); this->addUnitComponent( component, item->getName(), eComponentLayer::OverObject ); Point icon_pos = Point( 0, this->getLocalHeadPos().y + item_sprite->getContentSize().height ); component->setPosition( icon_pos ); this->addUnitTag( item->getName() ); } void UnitNode::removeItem( const std::string& item_name ) { for( auto itr = _items.begin(); itr != _items.end(); ++itr ) { if( itr->second->getName() == item_name ) { itr->second->removeFromUnit( this ); _items.erase( itr ); break; } } } bool UnitNode::hasItem( const std::string& item_name ) { for( auto itr = _items.begin(); itr != _items.end(); ++itr ) { if( itr->second->getName() == item_name ) { return true; } } return false; } void UnitNode::useSkill( int skill_id, const cocos2d::Point& dir, float range_per, float duration ) { if( !this->isDying() && !this->isCasting() && !this->isUnderControl() ) { Point sk_dir = dir; if( sk_dir.x != 0 || sk_dir.y != 0 ) { this->changeUnitDirection( dir ); } else { sk_dir = this->getUnitDirection(); } _using_skill_params.clear(); _using_skill_params["dir_x"] = Value( sk_dir.x ); _using_skill_params["dir_y"] = Value( sk_dir.y ); _using_skill_params["touch_down_duration"] = Value( duration ); _using_skill_params["multi_action"] = Value( _skills.at( skill_id )->shouldContinue() ); _using_skill_params["skill_id"] = Value( skill_id ); _using_skill_params["range_per"] = Value( range_per ); _using_skill_params["state"] = Value( "start" ); _using_skill_params["charging_effect"] = Value( _skills.at( skill_id )->getChargingEffect() ); _using_skill_params["charging_effect_pos"] = Value( _skills.at( skill_id )->getChargingEffectPos() ); this->changeUnitState( eUnitState::Casting, true ); } } void UnitNode::endSkill() { auto itr = _using_skill_params.find( "skill_id" ); if( itr != _using_skill_params.end() ) { int sk_id = _using_skill_params.at( "skill_id" ).asInt(); _skills.at( sk_id )->reload(); } _using_skill_params.clear(); } void UnitNode::endCast() { if( this->isCasting() ) { _using_skill_params["state"] = Value( "end" ); int sk_id = _using_skill_params.at( "skill_id" ).asInt(); _skills.at( sk_id )->setSkillNode( nullptr ); this->changeUnitState( eUnitState::Casting, true ); } } bool UnitNode::getAdvisedNewDir( UnitNode* unit, cocos2d::Vec2 old_dir, cocos2d::Vec2& new_dir, bool visited ) { // Vec2 unit_to_this = this->getPosition() - unit->getPosition(); // Vec2 this_to_unit = unit->getPosition() - this->getPosition(); // Vec2 this_dir = this->getUnitDirection(); // int unit_weight = unit->getUnitWeight(); // float this_collide = _target_data->collide; // float unit_collide = unit->getTargetData()->collide; // if( Math::doesCircleIntersectesCircle( this->getPosition(), this_collide, unit->getPosition(), unit_collide ) ) { // new_dir = this_to_unit; // new_dir.normalize(); // return true; // } // // float this_dir_to_center = this_dir.cross( this_to_unit ); // float unit_dir_to_center = old_dir.cross( unit_to_this ); // // if( _weight == unit_weight ) { // _weight++; // } // if( _weight > unit_weight || !this->isWalking() ) { // if( this_dir_to_center * unit_dir_to_center <= 0 ) { // if( visited ) { // new_dir = Geometry::anticlockwisePerpendicularVecToLine( unit_to_this ); // } // else { // new_dir = Geometry::clockwisePerpendicularVecToLine( unit_to_this ); // } // } // else { // if( unit_dir_to_center > 0 ) { // new_dir = Geometry::clockwisePerpendicularVecToLine( unit_to_this ); // } // else { // new_dir = Geometry::anticlockwisePerpendicularVecToLine( unit_to_this ); // } // } // } // else { // new_dir = old_dir; // } // new_dir.normalize(); Vec2 this_to_unit = unit->getPosition() - this->getPosition(); this_to_unit.normalize(); float this_collide = _target_data->collide; float unit_collide = unit->getTargetData()->collide; if( Math::doesCircleIntersectesCircle( this->getPosition(), this_collide, unit->getPosition(), unit_collide ) ) { new_dir = this_to_unit + old_dir; } else { new_dir = old_dir; } return true; } void UnitNode::walkTo( const cocos2d::Point& new_pos ) { this->changeUnitState( eUnitState::Walking ); Point origin_dir = new_pos - this->getPosition(); origin_dir.normalize(); float max_walk_length = new_pos.distance( this->getPosition() ); Point new_dir = this->pushToward( origin_dir, max_walk_length ); if( !this->isOscillate( new_dir ) ) { this->changeUnitDirection( new_dir ); } _battle_layer->onUnitMoved( this ); } void UnitNode::walkAlongPath( Path* path, float distance ) { if( path ) { Point last_pos = this->getPosition(); Point new_pos = path->steps.back(); Point to_pos = new_pos; if( new_pos.distance( last_pos ) > distance ) { Point dir = new_pos - last_pos; dir.normalize(); new_pos = last_pos + dir * distance; } Point unit_pos = this->getPosition(); if( unit_pos.distance( to_pos ) < 5.0 ) { path->steps.pop_back(); } this->walkTo( new_pos ); } } void UnitNode::walkAlongWalkPath( float distance ) { if( _walk_path ) { this->walkAlongPath( _walk_path, distance ); if( _walk_path->steps.size() == 0 ) { this->setWalkPath( nullptr ); this->changeUnitState( eUnitState::Idle ); _relax_frames = DEFAULT_RELAX_FRAMES; } } } void UnitNode::walkAlongTourPath( float distance ) { if( _tour_path ) { this->walkAlongPath( _tour_path, distance ); if( _tour_path->steps.size() == 0 ) { this->setTourPath( nullptr ); this->changeUnitState( eUnitState::Idle ); _relax_frames = DEFAULT_RELAX_FRAMES; } } } cocos2d::Point UnitNode::pushToward( const cocos2d::Point& dir, float distance ) { Point new_pos = dir * distance + this->getPosition(); Point origin_dir = dir; float max_walk_length = distance; Point new_dir = origin_dir; Point dest_pos = new_pos; //check units with round collide edge const UnitMap& collidable_units = _battle_layer->getAliveUnits(); for( auto pair : collidable_units ) { UnitNode* c = pair.second; if( c != this ) { if( c->willCollide( this, dest_pos ) ) { int unit_weight = c->getUnitWeight(); if( _weight == unit_weight ) { _weight++; } if( _weight < unit_weight || ( !c->isWalking() && !c->isIdle() ) ) { c->getAdvisedNewDir( this, new_dir, new_dir ); } } } } new_dir.normalize(); dest_pos = this->getPosition() + new_dir.getNormalized() * max_walk_length; //check borders std::vector<Collidable*> collidables; Terrain::getInstance()->getMeshByUnitRadius( _target_data->collide )->getNearbyBorders( this->getPosition(), max_walk_length, collidables ); std::set<Collidable*> steered_collidables; while( true ) { bool no_collide = true; for( auto c : collidables ) { if( c->willCollide( this, dest_pos ) ) { no_collide = false; int steered_count = (int)steered_collidables.count( c ); if( steered_count == 0 ) { steered_collidables.insert( c ); if ( !c->getAdvisedNewDir( this, cocos2d::Vec2( this->getPosition(), dest_pos ), new_dir ) ) { return origin_dir; } dest_pos = this->getPosition() + new_dir.getNormalized() * max_walk_length; break; } else { return origin_dir; } } } if( no_collide) { break; } } this->setPosition( dest_pos ); return new_dir; } bool UnitNode::isUnderControl() { return _state == eUnitState::UnderControl; } bool UnitNode::willCast() { return _next_state == eUnitState::Casting; } bool UnitNode::isCasting() { return _state == eUnitState::Casting; } bool UnitNode::isAttacking() { return _state == eUnitState::Attacking; } bool UnitNode::isWalking() { return _state == eUnitState::Walking; } bool UnitNode::isIdle() { return _state == eUnitState::Idle; } bool UnitNode::isDying() { return _state >= eUnitState::Dying; } bool UnitNode::isOscillate( const cocos2d::Point& new_dir ) { const cocos2d::Point& last_dir = this->getUnitDirection(); if( ( new_dir.x > 0 && last_dir.x <= 0 ) || ( new_dir.x <= 0 && last_dir.x > 0 ) || ( new_dir.y > 0 && last_dir.y <= 0 ) || ( new_dir.y <= 0 && last_dir.y > 0 ) ) { if( _same_dir_frame_count < _hesitate_frame ) { return true; } } return false; } void UnitNode::evaluateCatchUp() { const Point& pos = this->getPosition(); if( UnitNode* leader = _battle_layer->getLeaderUnit() ) { const Point& leader_pos = leader->getPosition(); float distance = pos.distance( leader_pos ); const ValueMap& game_config = ResourceManager::getInstance()->getGameConfig(); float catchup_start_distance = game_config.at( "catchup_start_distance" ).asFloat(); float catchup_stop_distance = game_config.at( "catchup_stop_distance" ).asFloat(); if( !_should_catch_up && distance > catchup_start_distance ) { this->setShouldCatchUp( true ); } else if( _should_catch_up && distance < catchup_stop_distance ) { this->setShouldCatchUp( false ); } } } void UnitNode::findPathToPosition( const cocos2d::Point& pos, int validate_frames ) { this->setWalkPath( Terrain::getInstance()->getMeshByUnitRadius( _target_data->collide )->findPath( this->getPosition(), pos, validate_frames ) ); } bool UnitNode::isHarmless() { return _target_data->atk <= 0; } bool UnitNode::canAttack( TargetNode* target_node ) { if( this->getUnitData()->atk_range <= 0 ) { return false; } if( this->getPosition().distance( target_node->getPosition() ) > _target_data->atk_range + target_node->getTargetData()->collide ) { return false; } if( Terrain::getInstance()->isBlocked( this->getPosition(), target_node->getPosition() ) ) { return false; } return true; } void UnitNode::attack( TargetNode* unit ) { this->setChasingTarget( unit ); Point dir = unit->getPosition() - this->getPosition(); dir.normalize(); this->changeUnitDirection( dir ); this->changeUnitState( eUnitState::Attacking ); } void UnitNode::onCharging() { std::string resource = _using_skill_params["charging_effect"].asString(); std::string effect_pos = _using_skill_params["charging_effect_pos"].asString(); if( resource != "" ) { spine::SkeletonAnimation* skeleton = ArmatureManager::getInstance()->createArmature( resource ); std::string name = Utils::stringFormat( "charging_%d", BulletNode::getNextBulletId() ); UnitNodeFollowSpineComponent* charging_component = UnitNodeFollowSpineComponent::create( this, effect_pos, skeleton, name, true ); if( effect_pos != "" ) { charging_component->setPosition( this->getLocalBonePos( effect_pos ) ); } this->addUnitComponent( charging_component, charging_component->getName(), eComponentLayer::OverObject ); charging_component->setAnimation( 0, "animation", false ); } } void UnitNode::onAttackBegan() { } void UnitNode::onAttacking() { TargetNode* target_node = _chasing_target; if( target_node != nullptr ) { UnitData* unit_data = dynamic_cast<UnitData*>( _target_data ); if( unit_data->is_melee ) { DamageCalculate* damage_calculator = DamageCalculate::create( "normal", 0 ); ValueMap result = damage_calculator->calculateDamage( _target_data, target_node->getTargetData() ); target_node->takeDamage( result, this ); if( !result.at( "miss" ).asBool() ) { std::string hit_resource = "effects/bullets/default_hit"; spine::SkeletonAnimation* hit_effect = ArmatureManager::getInstance()->createArmature( hit_resource ); hit_effect->setScale( 0.7f ); UnitNodeSpineComponent* component = UnitNodeSpineComponent::create( hit_effect, Utils::stringFormat( "bullet_%d_hit", BulletNode::getNextBulletId() ), true ); component->setPosition( target_node->getLocalHitPos() ); target_node->addUnitComponent( component, component->getName(), eComponentLayer::OverObject ); component->setAnimation( 0, "animation", false ); } } else { DamageCalculate* damage_calculator = DamageCalculate::create( "normal", 0 ); BulletNode* bullet = BulletNode::create( this, ResourceManager::getInstance()->getBulletData( _target_data->bullet_name ), damage_calculator, ValueMap() ); bullet->shootAt( target_node ); } } } void UnitNode::onCasting() { int sk_id = _using_skill_params["skill_id"].asInt(); _skills.at( sk_id )->activate( _using_skill_params ); } bool UnitNode::isUnitInDirectView( UnitNode* unit ) { UnitData* unit_data = dynamic_cast<UnitData*>( _target_data ); if( Terrain::getInstance()->isBlocked( this->getPosition(), unit->getPosition() ) ) { return false; } else if( !Math::isPositionInRange( unit->getPosition(), this->getPosition(), unit_data->guard_radius + unit->getUnitData()->collide ) ) { return false; } return true; } bool UnitNode::needRelax() { return ( _relax_frames > 0 ); } cocos2d::Point UnitNode::getNextWanderPos() { for( int i = 0; i < 3; i++ ) { float r = Utils::randomNumber( _wander_radius ); float angle = Utils::randomFloat() * M_PI; Point new_pos = Point( _born_position.x + cosf( angle ) * r, _born_position.y + sinf( angle ) * r ); if( _battle_layer->isPositionOK( new_pos, _target_data->collide ) ) { return new_pos; } } return Point::ZERO; } void UnitNode::setWalkPath( Path* path ) { CC_SAFE_RETAIN( path ); CC_SAFE_RELEASE( _walk_path ); _walk_path = path; } void UnitNode::setTourPath( Path* path ) { CC_SAFE_RETAIN( path ); CC_SAFE_RELEASE( _tour_path ); _tour_path = path; } UnitData* UnitNode::getUnitData() { return dynamic_cast<UnitData*>( _target_data ); } void UnitNode::jumpNumber( float amount, const std::string& type, bool is_critical, const std::string& name ) { JumpText* jump_text = JumpText::create( Utils::toStr( (int)amount ), type, is_critical, _camp, name ); this->addUnitComponent( jump_text, name, eComponentLayer::OverObject ); jump_text->setPosition( this->getLocalHeadPos() ); jump_text->start( is_critical ); } Skill* UnitNode::getSkill( int sk_id ) { return _skills.at( sk_id ); } std::string UnitNode::getSkillHintTypeById( int sk_id ) { return _skills.at( sk_id )->getSkillHintType(); } float UnitNode::getSkillRadiusById( int sk_id ) { return _skills.at( sk_id )->getSkillRadius(); } float UnitNode::getSkillRangeById( int sk_id ) { return _skills.at( sk_id )->getSkillRange(); } float UnitNode::getSkillMinRangeById( int sk_id ) { return _skills.at( sk_id )->getSkillMinRange(); } float UnitNode::getSkillMaxRangeById( int sk_id ) { return _skills.at( sk_id )->getSkillMaxRange(); } float UnitNode::getSkillCDById( int sk_id ) { return _skills.at( sk_id )->getSkillCD(); } bool UnitNode::isSkillReadyById( int sk_id ) { return _skills.at( sk_id )->isSkillReady(); } bool UnitNode::shouldSkillCastOnTouchDown( int sk_id ) { return _skills.at( sk_id )->shouldCastOnTouchDown(); } void UnitNode::makeSpeech( const std::string& content, float duration ) { Rect inset_rect = Rect( 100.0f, 40.0f, 60.0f, 60.0f ); ui::Scale9Sprite* window = ui::Scale9Sprite::createWithSpriteFrameName( "chat_popup.png", inset_rect ); window->setAnchorPoint( Point( 0.3f, 0 ) ); Label* content_label = Label::createWithTTF( content, "simhei.ttf", 36.0 ); // Label* content_label = Label::createWithSystemFont( content, "Helvetica", 40.0f ); content_label->setTextColor( Color4B::BLACK ); content_label->setLineBreakWithoutSpace( true ); content_label->setDimensions( 300, 0 ); content_label->setHorizontalAlignment( TextHAlignment::LEFT ); content_label->setVerticalAlignment( TextVAlignment::CENTER ); Size content_size = content_label->getContentSize(); Size real_content_size = Size( content_size.width + 60.0f, content_size.height + 70.0f ); window->setPreferredSize( real_content_size ); content_label->setAnchorPoint( Point( 0.5f, 1.0f ) ); content_label->setPosition( Point( real_content_size.width / 2, real_content_size.height - 20.0f ) ); window->addChild( content_label ); std::string name = Utils::stringFormat( "chat_popup_%d", BulletNode::getNextBulletId() ); TimeLimitComponent* component = TimeLimitComponent::create( duration, window, name, true ); component->setPosition( Point( this->getContentSize().width / 2, this->getContentSize().height ) ); this->addUnitComponent( component, component->getName(), eComponentLayer::OverObject ); } void UnitNode::setGuardTarget( UnitNode* guard_target ) { CC_SAFE_RELEASE( _guard_target ); _guard_target = guard_target; CC_SAFE_RETAIN( _guard_target ); } cocos2d::Point UnitNode::getGuardCenter() { if( _guard_target ) { return _guard_target->getPosition(); } else { return this->getPosition(); } } void UnitNode::setConcentrateOnWalk( bool b ) { _is_concentrate_on_walk = b; if( b ) { this->setChasingTarget( nullptr ); } } void UnitNode::setCharging( bool b, std::string effect_resource ) { if( !this->isCasting() && !this->willCast() ) { _is_charging = b; this->changeUnitState( _state, true ); if( b && !effect_resource.empty() ) { if( _charging_effect != nullptr ) { _charging_effect->setDuration( 0 ); } spine::SkeletonAnimation* skeleton = ArmatureManager::getInstance()->createArmature( effect_resource ); std::string name = Utils::stringFormat( "UnitCharging_%d", BulletNode::getNextBulletId() ); _charging_effect = TimeLimitSpineComponent::create( INT_MAX, skeleton, name, true ); _charging_effect->setPosition( this->getLocalBonePos( "ChargingPoint" ) ); _charging_effect->setAnimation( 0, "animation", true ); this->addUnitComponent( _charging_effect, name, eComponentLayer::OverObject ); } else if( !b && _charging_effect != nullptr ) { _charging_effect->setDuration( 0 ); _charging_effect = nullptr; } } } void UnitNode::setWeapon( Equipment* weapon ) { if( _weapon != nullptr ) { _target_data->sub( _weapon->getEquipData() ); } CC_SAFE_RELEASE( _weapon ); CC_SAFE_RETAIN( weapon ); _weapon = weapon; if( _weapon ) { _target_data->add( _weapon->getEquipData() ); } } void UnitNode::setArmor( Equipment* armor ) { if( _armor != nullptr ) { _target_data->sub( _armor->getEquipData() ); } CC_SAFE_RELEASE( _armor ); CC_SAFE_RETAIN( armor ); _armor = armor; if( _armor ) { _target_data->add( _armor->getEquipData() ); } } void UnitNode::setBoot( Equipment* boot ) { if( _boot != nullptr ) { _target_data->sub( _boot->getEquipData() ); } CC_SAFE_RELEASE( _boot ); CC_SAFE_RETAIN( boot ); _boot = boot; if( _boot ) { _target_data->add( _boot->getEquipData() ); } } void UnitNode::setAccessory( Equipment* accessory ) { if( _accessory != nullptr ) { _target_data->sub( _accessory->getEquipData() ); } CC_SAFE_RELEASE( _accessory ); CC_SAFE_RETAIN( accessory ); _accessory = accessory; if( _accessory ) { _target_data->add( _accessory->getEquipData() ); } } void UnitNode::setUnitScale( float scale ) { _desired_unit_scale = scale; ScaleTo* scale_to = ScaleTo::create( 0.5f, scale ); _front->runAction( scale_to ); if( _back != nullptr ) { ScaleTo* scale_to_back = ScaleTo::create( 0.5f, scale ); _back->runAction( scale_to_back ); } } float UnitNode::getUnitScale() { return _desired_unit_scale; } void UnitNode::setAttackable( bool b ) { TargetNode::setAttackable( b ); if( !b ) { _battle_layer->clearChasingTarget( this ); } } void UnitNode::updateHintNode( float delta ) { if( _has_hint_node ) { if( _hint_node != nullptr ) { //update hint node pos and rotation _hint_node->updateHintPos( _battle_layer, this->getPosition() ); } else { if( this->hasUnitTag( BATTLE_HINT_BOSS ) ) { _hint_node = BattleHintNode::create( BATTLE_HINT_BOSS ); } else if( this->hasUnitTag( BATTLE_HINT_HOSTAGE ) ) { _hint_node = BattleHintNode::create( BATTLE_HINT_HOSTAGE ); } else if( this->hasUnitTag( BATTLE_HINT_VILLIGER ) ) { _hint_node = BattleHintNode::create( BATTLE_HINT_VILLIGER ); } else if( this->hasUnitTag( BATTLE_HINT_VICE_BOSS ) ) { _hint_node = BattleHintNode::create( BATTLE_HINT_VICE_BOSS ); } else if( this->hasUnitTag( BATTLE_HINT_MASTER ) ) { _hint_node = BattleHintNode::create( BATTLE_HINT_MASTER ); } else if( this->hasUnitTag( BATTLE_HINT_ITEM ) ) { _hint_node = BattleHintNode::create( BATTLE_HINT_ITEM ); } else { _has_hint_node = false; } if( _hint_node != nullptr ) { _battle_layer->addToLayer( _hint_node, eBattleSubLayer::FloatLayer, Point::ZERO, 0 ); } } } } void UnitNode::setFormationPos( int formation_pos ) { _formation_pos = formation_pos; Label* lb = Label::createWithSystemFont( Utils::stringFormat( "%d", formation_pos ), "arial", 48 ); this->addChild( lb, 100 ); } bool UnitNode::isAtFormationPos() { UnitNode* leader_unit = _battle_layer->getLeaderUnit(); if( leader_unit == this ) { return true; } else { //todo Point formation_pos = _battle_layer->getFormationPos( _formation_pos ); if( this->getPosition().distance( formation_pos ) < 50.0f ) { return true; } return false; } } void UnitNode::walkToFormationPos( float delta ) { Point formation_pos = _battle_layer->getFormationPos( _formation_pos ); this->findPathToPosition( formation_pos ); float mov_speed = this->getUnitData()->move_speed * 1.5f; this->walkAlongWalkPath( mov_speed * delta ); } void UnitNode::refreshHpAndMpBar() { if( _hp_bar ) { _hp_bar->setPercentage( 100.0f * _target_data->current_hp / _target_data->hp ); } } void UnitNode::calculateTargetData() { } //private methods void UnitNode::updateBuffs( float delta ) { cocos2d::Map<std::string, Buff*> buffs = _buffs; for( auto pair : buffs ) { Buff* buff = pair.second; if( buff->shouldRecycle() ) { this->removeBuff( buff->getBuffId() ); } else { buff->updateFrame( delta ); } } } void UnitNode::updateSkills( float delta ) { for( auto skill : _skills ) { skill->updateFrame( delta ); } } void UnitNode::riseup( float duration, float delta_height ) { MoveBy* rise = MoveBy::create( duration, Point( 0, delta_height ) ); rise->setTag( 10000 ); _current_skeleton->runAction( rise ); } void UnitNode::falldown( float duration, float delta_height ) { _current_skeleton->stopActionByTag( 10000 ); _current_skeleton->setPosition( Point::ZERO ); } bool UnitNode::isAlive() { return _state < eUnitState::Dying; }
#include "DrawingBezierCycle.h" #include "Logic.h" #include <math.h> DrawingBezierCycle::DrawingBezierCycle() { } DrawingBezierCycle::DrawingBezierCycle(sf::Vector2f* position) { this->position = position; } DrawingBezierCycle::DrawingBezierCycle( float radius ,float x, float y, sf::Color color ) { cycle = sf::CircleShape(radius); cycle.setPosition(x,y); cycle.setFillColor(color); position = NULL; } DrawingBezierCycle::~DrawingBezierCycle(void) { } void DrawingBezierCycle::AI(sf::RenderWindow& renderWindow, map<string, float>& eventMap) { // for(std::vector<sf::Event>::iterator itr = eventVector.begin(); itr != eventVector.end();++itr) // { // if(itr->type == sf::Event::MouseButtonPressed) // { // float x = (float) itr->mouseButton.x; // float y = (float) itr->mouseButton.y; // x = getPosition().x -x + cycle.getRadius(); // y = getPosition().y -y + cycle.getRadius(); // // float r = std::sqrtf(x*x+y*y); // // // if ( r <= cycle.getRadius() ) // { // Logic::addEvent(new LogicEvent(this,LogicEvent::clicked)); // } // // } //} } void DrawingBezierCycle::setBezier( DrawingBezier* bezier) { this->bezier = bezier; } void DrawingBezierCycle::setPositionV( sf::Vector2f* position ) { this->position = position; } std::string DrawingBezierCycle::gettype() { return "DrawingBezierCycle"; }
#pragma once #include <string> using namespace std; template<typename DT> void readMatrix(string path, const string filename, DT*& arr, int* size, int dim); template<typename DT> void writeMatrix(string path, const string filename, DT* arr, int* size, int dim); #include "io_implementation.h"
/********************************************************************* Matt Marchant 2014 - 2016 http://trederia.blogspot.com xygine - Zlib license. This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. *********************************************************************/ #ifndef XY_MESH_RESOURCE_HPP_ #define XY_MESH_RESOURCE_HPP_ #include <xygine/mesh/Mesh.hpp> #include <xygine/mesh/ModelBuilder.hpp> #include <map> #include <memory> namespace xy { /*! \brief Manages the lifetimes of 3D meshes used by model components. Multiple model components may reference the same mesh, which can be retrieved from the MeshResource via its ID. A mesh must first be added to the resource via the add() function which takes a reference to a ModelBuilder instance, used to construct the mesh. The MeshRenderer has its own set of resource managers, including a MeshResource, so the most common usage would be to allow the MeshRenderer handle resource management rather than instancing this class yourself. */ class XY_EXPORT_API MeshResource final { public: using ID = std::uint32_t; MeshResource(); ~MeshResource() = default; /*! \brief Adds a mesh to the resource and maps it to the given ID. \param ID a unique ID for the mesh to be added \param MeshBuilder custom mesh builder used to create the mesh mapped to this ID \returns Reference to the newly added mesh */ Mesh& add(ID, ModelBuilder&); /*! \brief Returns a reference to the mesh with the given ID is it is found else returns a reference to the default mesh. */ Mesh& get(ID); private: std::map<ID, std::unique_ptr<Mesh>> m_meshes; VertexLayout m_defaultLayout; Mesh m_defaultMesh; }; } #endif //XY_MESH_RESOURCE_HPP_
#ifndef PATHAL #define PATHAL #include "Path.h" #include "Pos.h" #include "Map.h" //#include "SMap.h" #include "Util.h" #define isInRange(i, j) (i > 0 && j > 0 && i < 29 && j < 32) #define isValid(a) (a[0] > 0 && a[2] > 0 && a[1] < 28 && a[3] < 31) class PathAl { public: // Path* getPath(set<Node*>* star, char o) { // Path* rv = new Path; // t<Node*> *it = star->iterator(); // t<Node*> *next = it->next; // char prev = o; // do { // if(it->data->x2 < next->data->x1) { // prev = setRight(prev); // rv->push(prev); // } // else if(it->data->x1 > next->data->x2) { // prev = setLeft(prev); // rv->push(prev); // } // else if(next->data->y1 > it->data->y2) { // prev = setUp(prev); // rv->push(prev); // } // else if(next->data->y2 < it->data->y1) { // prev = setDown(prev); // rv->push(prev); // } // } while(it->next != NULL); // return rv; // } char setLeft(char o) { if(o == UP) { return TurnLeft; } if(o == DOWN) { return TurnRight; } if(o == RIGHT) { return TurnAround; } if(o == LEFT) return KeepForward; } char setRight(char o) { if(o == UP) { return TurnRight; } if(o == DOWN) { return TurnLeft; } if(o == RIGHT) { return KeepForward; } if(o == LEFT) return TurnAround; } char setUp(char o) { if(o == UP) { return KeepForward; } if(o == DOWN) { return TurnAround; } if(o == RIGHT) { return TurnLeft; } if(o == LEFT) return TurnRight; } char setDown(char o) { if(o == UP) { return TurnAround; } if(o == DOWN) { return KeepForward; } if(o == RIGHT) { return TurnRight; } if(o == LEFT) return TurnLeft; } short dx[4] = {0, 0, 1, -1}; short dy[4] = {1, -1, 0, 0}; #define distance(a, b) (a[0] < b[0] ? b[0] - a[1] : a[0] > b[0] ? a[1] - b[0]: a[2] > b[2] ? a[2] - b[3] : a[2] < b[2] ? b[2] - a[3]: 0) #define isNode(j, i) (map->map[j][i] == 6 || map->map[j][i] == 8) #define isFood(j, i) (map->map[j][i] == 8 || map->map[j][i] == 9) #define isWall(j, i) (map->map[j][i] == 0) vector<4> project(vector<4> pac, vector<2> dir, Map* map) { vector<4> rv; rv[0] = -1; if(dir[0] == 1) { for(short i = pac[1] + 1; i < 28; i++) { if(isNode(pac[2], i)) { rv[0] = i; rv[1] = i + 1; rv[2] = pac[2]; rv[3] = pac[3]; return rv; } else if(isWall(pac[2], i)) { break; } } } else if(dir[0] == -1) { for(short i = pac[0] - 1; i >= 1; i--) { if(isNode(pac[2], i)) { rv[0] = i - 1; rv[1] = i; rv[2] = pac[2]; rv[3] = pac[3]; return rv; } else if(isWall(pac[2], i)) { break; } } } else if(dir[1] == -1) { for(short i = pac[2] - 1; i >= 1; i--) { if(isNode(i, pac[0])) { rv[0] = pac[0]; rv[1] = pac[1]; rv[2] = i - 1; rv[3] = i; return rv; } else if(isWall(i, pac[0])) { break; } } } else { for(short i = pac[3] + 1; i < 31; i++) { if(isNode(i, pac[0])) { rv[0] = pac[0]; rv[1] = pac[1]; rv[2] = i; rv[3] = i + 1; return rv; } else if(isWall(i, pac[0])) { break; } } } } int z[4] = {1, -1, 0, 0}; int z2[4] = {0, 0, -1, 1}; void projectMod(vector<5> pac, vector<2> dir, Map* map, int n, vector<5>* rv) { (*rv)[0] = -1; if(dir[0] == 1) { for(short i = pac[1] + 1; i < 28; i++) { if(isNode(pac[2], i)) { (*rv)[0] = i; (*rv)[1] = i + 1; (*rv)[2] = pac[2]; (*rv)[3] = pac[3]; (*rv)[4] = n + distance(pac, (*rv)); break; //return (*rv); } else if(isWall(pac[2], i)) { break; } } } else if(dir[0] == -1) { for(short i = pac[0] - 1; i >= 1; i--) { if(isNode(pac[2], i)) { (*rv)[0] = i - 1; (*rv)[1] = i; (*rv)[2] = pac[2]; (*rv)[3] = pac[3]; (*rv)[4] = n + distance(pac, (*rv)); break; //return (*rv); } else if(isWall(pac[2], i)) { break; } } } else if(dir[1] == -1) { for(short i = pac[2] - 1; i >= 1; i--) { if(isNode(i, pac[0])) { (*rv)[0] = pac[0]; (*rv)[1] = pac[1]; (*rv)[2] = i - 1; (*rv)[3] = i; (*rv)[4] = n + distance(pac, (*rv)); break; //return (*rv); } else if(isWall(i, pac[0])) { break; } } } else { for(short i = pac[3] + 1; i < 31; i++) { if(isNode(i, pac[0])) { (*rv)[0] = pac[0]; (*rv)[1] = pac[1]; (*rv)[2] = i; (*rv)[3] = i + 1; (*rv)[4] = n + distance(pac, (*rv)); break; } else if(isWall(i, pac[0])) { break; } } } // find the next node in this direction, returns the node and distance } void projectMod(Pos* pac, char dir, Map* map, vector<5>* rv) { (*rv)[0] = -1; (*rv)[4] = 2; switch(dir) { case RIGHT: { for(short i = (*pac)[1] + 1; i < 28; i++) { (*rv)[4] += 1; if(isNode((*pac)[2], i)) { (*rv)[0] = i; (*rv)[1] = i + 1; (*rv)[2] = (*pac)[2]; (*rv)[3] = (*pac)[3]; //(*rv)[4] = distance((*pac), (*rv)); //return (*rv); break; } else if(isWall((*pac)[2], i)) { break; } } } case LEFT: { for(short i = (*pac)[0] - 1; i >= 1; i--) { (*rv)[4] += 1; if(isNode((*pac)[2], i)) { (*rv)[0] = i - 1; (*rv)[1] = i; (*rv)[2] = (*pac)[2]; (*rv)[3] = (*pac)[3]; //(*rv)[4] = distance((*pac), (*rv)); //return (*rv); break; } else if(isWall((*pac)[2], i)) { break; } } } case UP: { for(short i = (*pac)[2] - 1; i >= 1; i--) { (*rv)[4] += 1; if(isNode(i, (*pac)[0])) { (*rv)[0] = (*pac)[0]; (*rv)[1] = (*pac)[1]; (*rv)[2] = i - 1; (*rv)[3] = i; //(*rv)[4] = distance((*pac), (*rv)); //return (*rv); break; } else if(isWall(i, (*pac)[0])) { break; } } } case DOWN: { for(short i = (*pac)[3] + 1; i < 31; i++) { (*rv)[4] += 1; if(isNode(i, (*pac)[0])) { (*rv)[0] = (*pac)[0]; (*rv)[1] = (*pac)[1]; (*rv)[2] = i; (*rv)[3] = i + 1; //(*rv)[4] = distance((*pac), (*rv)); //return (*rv); break; } else if(isWall(i, (*pac)[0])) { break; } } } } // find the next node in the given direction, returns the node and distance } vector<6> projectModFood(Pos* pac, char dir, Map* map, int n, int f) { // find the next node in the given direction, returns the node and distance and that value of the food in those nodes vector<6> rv; rv[0] = -1; rv[4] = 2 + n; rv[5] = f; switch(dir) { case RIGHT: { for(short i = (*pac)[1] + 1; i < 28; i++) { rv[4] += 1; rv[5] += isFood((*pac)[2], i) ? 1 : 0; if(isNode((*pac)[2], i)) { rv[0] = i; rv[1] = i + 1; rv[2] = (*pac)[2]; rv[3] = (*pac)[3]; //rv[4] = distance((*pac), rv); return rv; } else if(isWall((*pac)[2], i)) { break; } } } case LEFT: { for(short i = (*pac)[0] - 1; i >= 1; i--) { rv[4] += 1; rv[5] += isFood((*pac)[2], i) ? 1 : 0; if(isNode((*pac)[2], i)) { rv[0] = i - 1; rv[1] = i; rv[2] = (*pac)[2]; rv[3] = (*pac)[3]; //rv[4] = distance((*pac), rv); return rv; } else if(isWall((*pac)[2], i)) { break; } } } case UP: { for(short i = (*pac)[2] - 1; i >= 1; i--) { rv[4] += 1; rv[5] += isFood(i, (*pac)[0]) ? 1 : 0; if(isNode(i, (*pac)[0])) { rv[0] = (*pac)[0]; rv[1] = (*pac)[1]; rv[2] = i - 1; rv[3] = i; //rv[4] = distance((*pac), rv); return rv; } else if(isWall(i, (*pac)[0])) { break; } } } case DOWN: { for(short i = (*pac)[3] + 1; i < 31; i++) { rv[4] += 1; rv[5] += isFood(i, (*pac)[0]) ? 1 : 0; if(isNode(i, (*pac)[0])) { rv[0] = (*pac)[0]; rv[1] = (*pac)[1]; rv[2] = i; rv[3] = i + 1; //rv[4] = distance((*pac), rv); return rv; } else if(isWall(i, (*pac)[0])) { break; } } } } } vector<6> projectModFood(vector<6> pac, char dir, Map* map, int n, int f) { // find the next node in the given direction, returns the node and distance and that value of the food in those nodes vector<6> rv; rv[0] = -1; rv[4] = 2 + n; rv[5] = f; switch(dir) { case RIGHT: { for(short i = pac[1] + 1; i < 28; i++) { rv[4] += 1; rv[5] += isFood(pac[2], i) ? 1 : 0; if(isNode(pac[2], i)) { rv[0] = i; rv[1] = i + 1; rv[2] = (pac)[2]; rv[3] = (pac)[3]; //rv[4] = distance(pac, rv); return rv; } else if(isWall(pac[2], i)) { break; } } } case LEFT: { for(short i = pac[0] - 1; i >= 1; i--) { rv[4] += 1; rv[5] += isFood((pac)[2], i) ? 1 : 0; if(isNode(pac[2], i)) { rv[0] = i - 1; rv[1] = i; rv[2] = pac[2]; rv[3] = pac[3]; //rv[4] = distance(pac, rv); return rv; } else if(isWall(pac[2], i)) { break; } } } case UP: { for(short i = (pac)[2] - 1; i >= 1; i--) { rv[4] += 1; rv[5] += isFood(i, (pac)[0]) ? 1 : 0; if(isNode(i, pac[0])) { rv[0] = pac[0]; rv[1] = pac[1]; rv[2] = i - 1; rv[3] = i; //rv[4] = distance(pac, rv); return rv; } else if(isWall(i, pac[0])) { break; } } } case DOWN: { for(short i = (pac)[3] + 1; i < 31; i++) { rv[4] += 1; rv[5] += isFood(i, (pac)[0]) ? 1 : 0; if(isNode(i, (pac)[0])) { rv[0] = (pac)[0]; rv[1] = (pac)[1]; rv[2] = i; rv[3] = i + 1; //rv[4] = distance(pac, rv); return rv; } else if(isWall(i, pac[0])) { break; } } } } } short dist[32][29]; #define isTarget(a, t) (a[0] == t[0] && a[1] == t[1] && a[2] == t[2] && a[3] == t[3]) #define visited(n) (dist[n[2]][n[0]] != -1) #define setVisited(n) dist[n[2]][n[0]] = n[4] #define val(n) dist[n[2]][n[0]] #define valAd(n) dist[n[2]][n[1]] #define withinBB(n) (n[0] > bb[0] && n[1] < bb[1] && n[2] > bb[2] && n[3] < bb[3]) int shortestPathD(vector<5> start, vector<5> t, Map* map) { memset(dist, -1, sizeof(dist[0][0]) * 32 * 29); Queue<vector<5>> q; val(start) = 0; start[4] = 0; vector<4> bb; bb[0] = min(start[0], t[0]) - 7; bb[1] = max(start[1], t[1]) + 7; bb[2] = min(start[2], t[2]) - 7; bb[3] = max(start[3], t[3]) + 7; q.push(start); vector<2> dir; short d = 1293; vector<5> n; while(q.size > 0) { const vector<5> &temp = q.pop(); for(int i = 0; i < 4; i++) { dir[0] = z[i]; dir[1] = z2[i]; projectMod(temp, dir, map, val(temp), &n); if(n[0] < 0 || !withinBB(n)) continue; if(!visited(n)) { setVisited(n); if(isTarget(n, t)) { d = n[4]; } else { q.push(n); } } else { if(n[4] < val(n)) { val(n) = n[4]; q.push(n); } if(isTarget(n, t)) { d = val(n); } } } } // for(int x = 0; x < 32; x++) { // for(int y = 0; y < 29; y++) { // Serial.print(dist[x][y]); // Serial.print(" "); // } // Serial.println(); // } return d; } char dirs[4] = { UP, RIGHT, LEFT, DOWN }; vector<2> shortestPathDWithFood(vector<6> start, vector<6> t, Map* map) { memset(dist, -1, sizeof(dist[0][0]) * 32 * 29); Queue<vector<6>> q; val(start) = 0; start[4] = 0; vector<4> bb; bb[0] = min(start[0], t[0]) - 7; bb[1] = max(start[1], t[1]) + 7; bb[2] = min(start[2], t[2]) - 7; bb[3] = max(start[3], t[3]) + 7; vector<2> r; q.push(start); short d = 1293; while(q.size > 0) { const vector<6> &temp = q.pop(); for(int i = 0; i < 4; i++) { vector<6> n = projectModFood(temp, dirs[i], map, val(temp), valAd(temp)); if(n[0] < 0 || !withinBB(n)) continue; if(!visited(n)) { setVisited(n); if(isTarget(n, t)) { d = n[4]; r[1] = n[5]; } else { q.push(n); } } else { if(n[4] < val(n)) { val(n) = n[4]; valAd(n) = n[5]; q.push(n); } if(isTarget(n, t)) { d = val(n); r[1] = valAd(n); } } } } r[0] = d; return r; } }; #endif
// This file has been generated by Py++. #ifndef WindowFactoryIterator_hpp__pyplusplus_wrapper #define WindowFactoryIterator_hpp__pyplusplus_wrapper void register_WindowFactoryIterator_class(); #endif//WindowFactoryIterator_hpp__pyplusplus_wrapper
#include "parser.h" #include "condenser.h" #include "draw.h" #include "labeller.h" #include <stdio.h> #include <iostream> #include <stdlib.h> using namespace std; int main(int argc, char *argv[]) { map<string, list<pair<string, int> > > callee_graph = parse(argv); //We create a string to int indexing and use it from now on to save space. //str_to_int is a mapping from function name to an index and int_to_str is the reverse mapping map<string, int> str_to_int; int count = 0; for (map<string, list<pair<string, int> > >::iterator i = callee_graph.begin(); i != callee_graph.end(); i++) str_to_int[i->first] = count++; string int_to_str[count]; count = 0; for (map<string, list<pair<string, int> > >::iterator i = callee_graph.begin(); i != callee_graph.end(); i++) int_to_str[count++] = i->first; // Checks for parsing -- works for now // for (map<string, list<pair<string, int> > >::iterator i = callee_graph.begin(); i != callee_graph.end(); i++) { // cout<<i->first<<"X"; // for (list<pair<string, int> >::iterator j = i->second.begin(); j != i->second.end(); j++) cout<<"X"<<j->first; // cout<<"X"<<endl; // } //For now we do not need the line number. //callee_graph_stripped represents a mapping of indexes connected to a list of other indexes list<int> callee_graph_stripped[count]; for (map<string, list<pair<string, int> > >::iterator i = callee_graph.begin(); i != callee_graph.end(); i++) for (list<pair<string, int> >::iterator j = i->second.begin(); j != i->second.end(); j++) callee_graph_stripped[str_to_int[i->first]].push_back(str_to_int[j->first]); //function_SCC gives a mapping between index and SCC number int SCC_count = 0; int* function_SCC = condense(callee_graph_stripped, count, SCC_count); int* SCC_transitions = (int *)malloc(SCC_count * SCC_count * sizeof(int)); for (int i = 0; i < SCC_count; i++) for (int j = 0; j < SCC_count; j++) SCC_transitions[i * SCC_count + j] = 0; for (int i = 0; i < count; i++) for (list<int>::iterator j = callee_graph_stripped[i].begin(); j != callee_graph_stripped[i].end(); j++) SCC_transitions[function_SCC[i] * SCC_count + function_SCC[*j]] = 1; int* labelling = label(SCC_count, str_to_int, function_SCC, SCC_transitions); drawdot(count, SCC_count, int_to_str, function_SCC, SCC_transitions, labelling); }
#include <stdio.h> #include <string.h> bool containsString(char *source, char *b){ //printf("%s %s\n", source, b); char * found = strstr(source, b); /* should return 0x18 */ if (found != NULL) /* strstr returns NULL if item not found */ { return true; } return false; } int main(){ char par1[300]; char par2[300]; scanf("%s", &par1); scanf("%s", &par2); //printf("%s\n", par1); const char *filename = par1; FILE *file = fopen(filename, "r"); if(file == NULL){ printf("Blad przy otwieraniu %s\n", filename); return 1; } char* s = new char[100]; //read line by line char* line = new char[300]; while (fgets(line, 300, file) != NULL) { //printf("%s\n", line); if(containsString(line, par2 )){ printf("%s\n", line ); } } fclose(file); return 0; }
// // Created by twome on 08/05/2020. // #ifndef GAMEOFLIFE_OPENGL_MENUSCREEN_H #define GAMEOFLIFE_OPENGL_MENUSCREEN_H #include "../base/Screen.h" class MenuScreen : public Screen { public: MenuScreen(); }; #endif //GAMEOFLIFE_OPENGL_MENUSCREEN_H
#include <iostream> #define FMT_HEADER_ONLY 1 #include <cxxopts.hpp> #include <fmt/format.h> #include <stdexcept> #include <string_view> #include "matrix.h" #include "utils.h" #include "sort.h" #include "utils.h" #include "gpu_sort_driver.h" #include "cpu_sort_driver.h" #include "timer.h" bool test_cpu(size_t rows, size_t cols, unsigned int thread_count, size_t iterations, std::string_view output_path) { fmt::print("Sorting on CPU using: {} threads\n", thread_count); fmt::print("Matrix size (rows, cols): ({}, {})\n", rows, cols); fmt::print("The output data will be saved in: {}\n", output_path); gms::csv_writer csv("iteracja", "wiersze", "kolumny", "liczba rdzeni", "czas sortowania [ns]"); gms::timer timer; gms::matrix<float> m{ rows, cols }; gms::cpu_sort_driver cpu_sort_driver{ std::move(m), thread_count }; for (size_t i = 0; i < iterations; ++i) { fmt::print("Iteration {} of {}.\n", i + 1, iterations); gms::fill_matrix_with_random(cpu_sort_driver.get_matrix(), 0.0f, 10.0f); timer.start(); cpu_sort_driver.run(); timer.stop(); const auto sort_time = timer.get_time(); csv.add_row(i, rows, cols, cpu_sort_driver.get_thread_count(), sort_time); if (!gms::validate_sorting(cpu_sort_driver.get_matrix(), gms::order::ascending)) { return false; } } return csv.save_to_file(output_path); } bool test_gpu(size_t rows, size_t cols, std::string_view kernel_name, size_t wg_size, size_t iterations, std::string_view output_path) { fmt::print("Sorting on GPU, work group size: {}\n", wg_size); fmt::print("Matrix size (rows, cols): ({}, {})\n", rows, cols); fmt::print("The output data will be saved in: {}\n", output_path); gms::csv_writer csv("iteracja", "wiersze", "kolumny", "rozmiar grupy roboczej", "czas zapisu bufora[ns]", "czas sortowania[ns]", "czas odczytu bufora[ns]"); gms::matrix<float> m{ rows, cols }; gms::gpu_sort_driver gpu_sort_driver{ std::move(m), kernel_name, wg_size }; for (size_t i = 0; i < iterations; ++i) { fmt::print("Iteration {} of {}.\n", i + 1, iterations); gms::fill_matrix_with_random(gpu_sort_driver.get_matrix(), 0.0f, 10.0f); gpu_sort_driver.run(); const auto sort_time = gpu_sort_driver.get_timing_info(); csv.add_row(i, rows, cols, wg_size, sort_time.write_time, sort_time.execution_time, sort_time.read_time); if (!gms::validate_sorting(gpu_sort_driver.get_matrix(), gms::order::ascending)) { return false; } } return csv.save_to_file(output_path); } bool test_both(size_t rows, size_t cols, unsigned int thread_count, std::string_view kernel_name, size_t wg_size, size_t iterations, std::string_view output_path) { fmt::print("Testing both CPU and GPU; thread count: {}; work group size: {}\n", thread_count, wg_size); fmt::print("Matrix size (rows, cols): ({}, {})\n", rows, cols); fmt::print("The output data will be saved in: {}\n", output_path); gms::csv_writer csv("iteracja", "wiersze", "kolumny", "liczba rdzeni", "czas sortowania [ns]", "rozmiar grupy roboczej", "gpu czas zapisu bufora[ns]", "gpu czas sortowania[ns]", "cpu czas odczytu bufora[ns]"); gms::timer timer; gms::matrix<float> m{ rows, cols }; gms::cpu_sort_driver cpu_sort_driver{ m, thread_count }; gms::gpu_sort_driver gpu_sort_driver{ std::move(m), kernel_name, wg_size }; for (size_t i = 0; i < iterations; ++i) { fmt::print("Iteration {} of {}.\n", i + 1, iterations); gms::fill_matrix_with_random(cpu_sort_driver.get_matrix(), 0.0f, 10.0f); gpu_sort_driver.set_matrix(cpu_sort_driver.get_matrix()); timer.start(); cpu_sort_driver.run(); timer.stop(); const auto cpu_sort_time = timer.get_time(); gms::fill_matrix_with_random(gpu_sort_driver.get_matrix(), 0.0f, 10.0f); gpu_sort_driver.run(); const auto gpu_sort_time = gpu_sort_driver.get_timing_info(); csv.add_row(i, rows, cols, thread_count, cpu_sort_time, wg_size, gpu_sort_time.write_time, gpu_sort_time.execution_time, gpu_sort_time.read_time); } return csv.save_to_file(output_path); } bool test_profiling(size_t rows, size_t cols, std::string_view kernel_name, size_t iterations, std::string_view output_path) { fmt::print("Testing different work group sizes\n"); fmt::print("Matrix size (rows, cols): ({}, {})\n", rows, cols); fmt::print("The output data will be saved in: {}\n", output_path); gms::csv_writer csv("iteracja", "wiersze", "kolumny", "rozmiar grupy roboczej", "czas zapisu bufora[ns]", "czas sortowania[ns]", "czas odczytu bufora[ns]"); gms::matrix<float> m{ rows, cols }; gms::fill_matrix_with_random(m, 0.0f, 10.0f); gms::gpu_sort_driver gpu_sort_driver{ m, kernel_name, 1 }; size_t wg_size{ 1 }; for (size_t i = 0; i < iterations; ++i) { fmt::print("Iteration {} of {}; work group size: {}\n", i + 1, iterations, wg_size); gpu_sort_driver.set_matrix(m); gpu_sort_driver.set_work_group_size(wg_size); gpu_sort_driver.run(); const auto sort_time = gpu_sort_driver.get_timing_info(); csv.add_row(i, rows, cols, wg_size, sort_time.write_time, sort_time.execution_time, sort_time.read_time); wg_size *= 2; } return csv.save_to_file(output_path); } int main(int argc, char* argv[]) { cxxopts::Options options("gpu_matrix_sort", "Test program that sorts in parallel the elements in rows of a 2d matrix."); options.add_options() ("b,both", "Test both GPU and CPU") ("c,cpu", "Test CPU only") ("g,gpu", "Test GPU only") ("p,profiling", "Test best size of work group <1, 512>") ("l,local", "Use GPU local memory", cxxopts::value<bool>()->default_value("false")) ("w,workgroupsize", "Size of the work grupy (power of 2)", cxxopts::value<size_t>()->default_value("64")) ("t,threads", "Number of CPU threads used", cxxopts::value<unsigned int>()->default_value("1")) ("r,rows", "Number of rows in the 2d matrix.", cxxopts::value<size_t>()->default_value("1024")) ("d,cols", "Number of columns in the 2d matrix.", cxxopts::value<size_t>()->default_value("256")) ("i,iterations", "Number of iterations.", cxxopts::value<size_t>()->default_value("1")) ("o,outputpath", "Output data file path.", cxxopts::value<std::string>()->default_value("test.csv")) ("h,help", "Print usage"); auto result = options.parse(argc, argv); bool local; size_t work_group_size, rows, cols, iterations; unsigned int threads; std::string output_path; try { local = result["local"].as<bool>(); work_group_size = result["workgroupsize"].as<size_t>(); threads = result["threads"].as<unsigned int>(); rows = result["rows"].as<size_t>(); cols = result["cols"].as<size_t>(); iterations = result["iterations"].as<size_t>(); output_path = result["outputpath"].as<std::string>(); } catch (const std::exception& e) { std::cerr << e.what() << "\n"; return -1; } if (result.count("help")) { fmt::print("{}\n", options.help()); return 0; } std::string kernel_path = "src/matrix_insert_sort.cl"; if (result.count("local")) { kernel_path = "src/matrix_insert_sort_local.cl"; } gms::matrix<float> mat{ rows, cols }; gms::fill_matrix_with_random(mat, 0.0f, 9.0f); if (result.count("both")) { test_both(rows, cols, threads, kernel_path, work_group_size, iterations, output_path); } else if (result.count("cpu")) { test_cpu(rows, cols, threads, iterations, output_path); } else if (result.count("gpu")) { test_gpu(rows, cols, kernel_path, work_group_size, iterations, output_path); } else if (result.count("profiling")) { test_profiling(rows, cols, kernel_path, iterations, output_path); } return 0; }
#pragma once #include <type_traits> namespace MissionImpossible { template <typename T> struct Always_True : std::true_type { }; template <typename T> inline constexpr bool Always_True_v = Always_True<T>::value; template <typename T> struct Always_False : std::false_type { }; template <typename T> inline constexpr bool Always_False_v = Always_False<T>::value; }
/* Copyright (c) 2013-2014 Sam Hardeman Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "NetworkControl.h" #include "Packet.h" #include "Client.h" #include "ClientProxy.h" #include "Broadcaster.h" #include "PacketHandler.h" #include <assert.h> using namespace IceNet; Event* NetworkControl::m_RecycleConnection = 0; NetworkControl* NetworkControl::m_Singleton = 0; int NetworkControl::m_InitCount = 0; NetworkControl::NetworkControl( void ) : m_StopRequestedEvent( TRUE ), m_NetworkThread( 0 ), m_LocalClient( 0 ), m_SocketTCP( 0 ), m_SocketUDP( 0 ), m_Flags( (Flags) ( PROTOCOL_TCP | PROTOCOL_UDP ) ) { // Initialize arrays to 0 memset( m_PublicIdClientMap, 0, sizeof( void* ) * USHRT_MAX ); memset( m_PrivateIdClientMap, 0, sizeof( void* ) * USHRT_MAX ); memset( m_PublicIdClientProxyMap, 0, sizeof( void* ) * USHRT_MAX ); #ifdef __linux__ rlimit limits; limits.rlim_cur = 9; limits.rlim_max = 9; setrlimit( RLIMIT_RTPRIO, &limits ); #endif if ( m_RecycleConnection == 0 ) { m_RecycleConnection = new Event( FALSE ); } } NetworkControl::ErrorCodes NetworkControl::InitializeServer( const char* listenPort, Flags flags ) { // Return if the networking has been initialized already if ( m_InitCount != 0 ) return ERROR_ALREADY_INIT; m_Singleton = new NetworkControl(); m_Singleton->m_Flags = flags; if ( m_Singleton->m_Flags & HANDLER_SYNC ) { m_Singleton->m_PacketHandler = new PacketHandler( 0 ); } else { m_Singleton->m_PacketHandler = 0; } #ifdef _WIN32 // Try to start WinSock if ( WSAStartup( MAKEWORD( 2, 0 ), &m_Singleton->m_WSAData ) == -1 ) { // WinSock fails delete m_Singleton; return ERROR_WSA; } #endif struct addrinfo hints; memset( &hints, 0, sizeof( hints ) ); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; hints.ai_flags = AI_PASSIVE; // Use local address to construct an addrinfo getaddrinfo( "0.0.0.0", listenPort, &hints, &m_Singleton->m_MyAddrInfoTCP ); // Create the TCP socket m_Singleton->m_SocketTCP = socket( m_Singleton->m_MyAddrInfoTCP->ai_family, m_Singleton->m_MyAddrInfoTCP->ai_socktype, m_Singleton->m_MyAddrInfoTCP->ai_protocol ); if ( m_Singleton->m_SocketTCP == INVALID_SOCKET ) { // TCP socket fails delete m_Singleton; return ERROR_SOCKET_FAIL_TCP; } // Bind the TCP socket if ( bind( m_Singleton->m_SocketTCP, m_Singleton->m_MyAddrInfoTCP->ai_addr, (int) m_Singleton->m_MyAddrInfoTCP->ai_addrlen ) == -1 ) { delete m_Singleton; return ERROR_BIND_FAIL_TCP; } // Start listening for connections if ( listen( m_Singleton->m_SocketTCP, CONNECTION_BACKLOG ) == -1 ) { delete m_Singleton; return ERROR_LISTEN_FAIL_TCP; } // If UDP has been enabled, go ahead and do all this for UDP if ( flags & PROTOCOL_UDP ) { memset( &hints, 0, sizeof( hints ) ); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; // For UDP hints.ai_protocol = IPPROTO_UDP; hints.ai_flags = AI_PASSIVE; getaddrinfo( "0.0.0.0", listenPort, &hints, &m_Singleton->m_MyAddrInfoUDP ); m_Singleton->m_SocketUDP = socket( m_Singleton->m_MyAddrInfoUDP->ai_family, m_Singleton->m_MyAddrInfoUDP->ai_socktype, m_Singleton->m_MyAddrInfoUDP->ai_protocol ); if ( m_Singleton->m_SocketUDP == INVALID_SOCKET ) { delete m_Singleton; return ERROR_SOCKET_FAIL_UDP; } if ( bind( m_Singleton->m_SocketUDP, m_Singleton->m_MyAddrInfoUDP->ai_addr, (int) m_Singleton->m_MyAddrInfoUDP->ai_addrlen ) == -1 ) { delete m_Singleton; return ERROR_BIND_FAIL_UDP; } } Broadcaster::GetSingleton(); m_Singleton->m_NetworkThread = new Thread( ServerEntry, 0 ); ++m_InitCount; // No error return ERROR_NONE; } NetworkControl::ErrorCodes NetworkControl::InitializeClient( const char* destinationPort, const char* ipAddress, Flags flags ) { if ( m_InitCount != 0 ) return ERROR_ALREADY_INIT; m_Singleton = new NetworkControl(); m_Singleton->m_Flags = flags; if ( m_Singleton->m_Flags & HANDLER_SYNC ) { m_Singleton->m_PacketHandler = new PacketHandler( 0 ); } else { m_Singleton->m_PacketHandler = 0; } #ifdef _WIN32 if ( WSAStartup( MAKEWORD( 2, 0 ), &m_Singleton->m_WSAData ) == -1 ) { delete m_Singleton; return ERROR_WSA; } #endif struct addrinfo hints; memset( &hints, 0, sizeof( hints ) ); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; hints.ai_flags = AI_PASSIVE; struct sockaddr_in sa; // store this IP address in sa: int valid = inet_pton( AF_INET, ipAddress, &(sa.sin_addr) ); if ( valid != 0 ) { getaddrinfo( ipAddress, destinationPort, &hints, &m_Singleton->m_MyAddrInfoTCP ); m_Singleton->m_SocketTCP = socket( m_Singleton->m_MyAddrInfoTCP->ai_family, m_Singleton->m_MyAddrInfoTCP->ai_socktype, m_Singleton->m_MyAddrInfoTCP->ai_protocol ); } if ( m_Singleton->m_SocketTCP == INVALID_SOCKET || valid == 0 ) { delete m_Singleton; return ERROR_SOCKET_FAIL_TCP; } if ( flags & PROTOCOL_UDP ) { memset( &hints, 0, sizeof( hints ) ); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; hints.ai_protocol = IPPROTO_UDP; hints.ai_flags = AI_PASSIVE; getaddrinfo( ipAddress, destinationPort, &hints, &m_Singleton->m_MyAddrInfoUDP ); m_Singleton->m_SocketUDP = socket( m_Singleton->m_MyAddrInfoUDP->ai_family, m_Singleton->m_MyAddrInfoUDP->ai_socktype, m_Singleton->m_MyAddrInfoUDP->ai_protocol ); if ( m_Singleton->m_SocketUDP == INVALID_SOCKET ) { delete m_Singleton; return ERROR_SOCKET_FAIL_UDP; } } Broadcaster::GetSingleton(); m_Singleton->m_NetworkThread = new Thread( ClientEntry, 0 ); ++m_InitCount; return ERROR_NONE; } NetworkControl::~NetworkControl( void ) { closesocket( m_SocketTCP ); closesocket( m_SocketUDP ); m_StopRequestedEvent.Set(); // Delete all clients if ( m_ClientIds.size() > 0 ) { for ( unsigned int i = 0; i < m_ClientIds.size(); ++i ) { m_PublicIdClientMap[ m_ClientIds[i].cc_PublicId ]->SetStop(); } } // Wait for everything else to clean up and shut down if ( m_NetworkThread != 0 ) m_NetworkThread->Wait( INFINITE ); delete m_NetworkThread; #ifdef _WIN32 WSACleanup(); #endif // Delete all clients if ( m_ClientIds.size() > 0 ) { for ( unsigned int i = 0; i < m_ClientIds.size(); ++i ) { delete m_PublicIdClientMap[ m_ClientIds[i].cc_PublicId ]; } } // Delete all clientproxies if ( m_ClientProxyIds.size() > 0 ) { for ( unsigned int i = 0; i < m_ClientProxyIds.size(); ++i ) { delete m_PublicIdClientProxyMap[ m_ClientProxyIds[i].cc_PublicId ]; } } if ( m_Singleton->m_Flags & HANDLER_SYNC ) { delete m_Singleton->m_PacketHandler; } } void NetworkControl::Deinitialize( void ) { assert( m_InitCount > 0 ); delete m_Singleton; m_Singleton = 0; --m_InitCount; m_RecycleConnection->Set(); } NetworkControl* NetworkControl::GetSingleton( void ) { return m_Singleton; } int NetworkControl::SendToServerTCP( Packet* packetToSend, bool deletePacket, int flags ) { // Calculate the real packet size (size of the string) unsigned short size = packetToSend->GetSize() + sizeof( unsigned short ); // Get the packet in string format char* buf = packetToSend->GetDataStream(); unsigned int sizeLeft = size; int sizeRead = 0; // Send until no bytes are left while ( sizeLeft > 0 ) { sizeRead = send( m_SocketTCP, &buf[size-sizeLeft], sizeLeft, flags ); sizeLeft -= sizeRead; // No bytes left or error if ( sizeRead <= 0 ) { break; } } if ( deletePacket ) delete packetToSend; return sizeRead; } int NetworkControl::SendToClientTCP( CLIENT_ID privateID, Packet* packetToSend, bool deletePacket, int flags ) { unsigned short size = packetToSend->GetSize() + sizeof( unsigned short ); char* buf = packetToSend->GetDataStream(); unsigned int sizeLeft = size; int sizeRead = 0; while ( sizeLeft > 0 && m_PrivateIdClientMap[privateID] != 0 ) { sizeRead = send( m_PrivateIdClientMap[privateID]->GetSocket(), &buf[size-sizeLeft], sizeLeft, flags ); sizeLeft -= sizeRead; if ( sizeRead <= 0 ) { break; } } if ( deletePacket ) delete packetToSend; return sizeRead; } int NetworkControl::SendToServerUDP( Packet* packetToSend, bool deletePacket, int flags ) { // Calculate the real packet size (size of the string) unsigned short size = packetToSend->GetSize() + sizeof( unsigned short ); // Get the packet in string format char* buf = packetToSend->GetDataStream(); unsigned int sizeLeft = size; int sizeRead = 0; // Send until no bytes are left sizeRead = sendto( m_SocketUDP, &buf[size-sizeLeft], sizeLeft, flags, m_MyAddrInfoUDP->ai_addr, (int) m_MyAddrInfoUDP->ai_addrlen ); if ( deletePacket ) delete packetToSend; return sizeRead; } int NetworkControl::SendToClientUDP( CLIENT_ID privateID, Packet* packetToSend, bool deletePacket, int flags ) { if ( m_PrivateIdClientMap[privateID] == 0 ) { if ( deletePacket ) delete packetToSend; return -1; } sockaddr udpOrig = m_PrivateIdClientMap[privateID]->GetUDPOrigin(); unsigned short size = packetToSend->GetSize() + sizeof( unsigned short ); char* buf = packetToSend->GetDataStream(); unsigned int sizeLeft = size; int sizeRead = 0; if ( m_PrivateIdClientMap[privateID]->m_UDPInitialized == true ) { const int b = sizeof ( sockaddr ); sizeRead = sendto( m_SocketUDP, &buf[size-sizeLeft], sizeLeft, flags, &udpOrig, b ); } if ( deletePacket ) delete packetToSend; return sizeRead; } void NetworkControl::BroadcastToAll( Packet* packetToSend ) { Broadcaster::GetSingleton()->AddToList( packetToSend ); } Client* NetworkControl::AddClient( CLIENT_ID publicId, CLIENT_ID privateId, bool local, SOCKET socket ) { assert( publicId != 0 ); m_ClientAccessMutex.Lock(); // Create a new client container object Client* newClientObj; newClientObj = new Client( publicId, privateId, local, socket ); ClientContainer newClient = { publicId, privateId }; // Add the client to the maps. Private ID is not required. m_PublicIdClientMap[ publicId ] = newClientObj; if ( privateId != 0 ) m_PrivateIdClientMap[ privateId ] = newClientObj; m_ClientIds.push_back( newClient ); m_ClientAccessMutex.Unlock(); return newClientObj; } void NetworkControl::RemoveClient( CLIENT_ID publicId, CLIENT_ID privateId ) { assert( publicId != 0 ); m_ClientAccessMutex.Lock(); if ( m_ClientIds.size() > 0 ) { for ( unsigned int i = 0; i < m_ClientIds.size(); i++ ) { if ( m_ClientIds[i].cc_PublicId == publicId ) { // Delete either by private ID or public ID if ( m_ClientIds[i].cc_PrivateId != 0 ) { delete m_PrivateIdClientMap[ m_ClientIds[i].cc_PrivateId ]; m_PrivateIdClientMap[ m_ClientIds[i].cc_PrivateId ] = 0; m_PublicIdClientMap[ m_ClientIds[i].cc_PublicId ] = 0; } else { delete m_PublicIdClientMap[ m_ClientIds[i].cc_PublicId ]; if ( m_ClientIds[i].cc_PrivateId != 0 ) m_PrivateIdClientMap[ m_ClientIds[i].cc_PrivateId ] = 0; m_PublicIdClientMap[ m_ClientIds[i].cc_PublicId ] = 0; } // Remove the client from the ID list m_ClientIds[i] = m_ClientIds.back(); m_ClientIds.pop_back(); break; } } } m_ClientAccessMutex.Unlock(); } ClientProxy* NetworkControl::AddClientProxy( CLIENT_ID publicId ) { assert( publicId != 0 ); m_ClientAccessMutex.Lock(); // Create a new client container object ClientProxy* newClientObj; newClientObj = new ClientProxy( publicId ); ClientContainer newClient = { publicId, 0 }; // Add the client to the maps. Private ID is not required. m_PublicIdClientProxyMap[ publicId ] = newClientObj; m_ClientProxyIds.push_back( newClient ); m_ClientAccessMutex.Unlock(); return newClientObj; } void NetworkControl::RemoveClientProxy( CLIENT_ID publicId ) { assert( publicId != 0 ); m_ClientAccessMutex.Lock(); if ( m_ClientProxyIds.size() > 0 ) { for ( unsigned int i = 0; i < m_ClientProxyIds.size(); i++ ) { if ( m_ClientProxyIds[i].cc_PublicId == publicId ) { delete m_PublicIdClientProxyMap[ m_ClientProxyIds[i].cc_PublicId ]; m_PublicIdClientProxyMap[ m_ClientProxyIds[i].cc_PublicId ] = 0; // Remove the client from the ID list m_ClientProxyIds[i] = m_ClientProxyIds.back(); m_ClientProxyIds.pop_back(); break; } } } m_ClientAccessMutex.Unlock(); } int NetworkControl::ConnectToHost( void ) { return connect( m_SocketTCP, m_MyAddrInfoTCP->ai_addr, (int) m_MyAddrInfoTCP->ai_addrlen ); } unsigned int NetworkControl::GetFlags( void ) { return m_Flags; } PacketHandler* NetworkControl::GetPacketHandler( void ) { return m_PacketHandler; } void NetworkControl::SetPublicId( CLIENT_ID id ) { m_LocalClient->m_PublicId = id; } void NetworkControl::SetPrivateId( CLIENT_ID id ) { m_LocalClient->m_PrivateId = id; }
#include<bits/stdc++.h> using namespace std; #define ll long long #define fr(i,n) for (ll i=0;i<n;i++) #define fr1(i,n) for(ll i=1;i<=n;i++) int main() { ll m,n,i,j,k ,t; cin>>t; while(t--) { string s; cin>>s; n=s.size(); ll cntl=0, cntr=0, cntd=0, cntu=0; fr(i, s.size()) { if(s[i]=='L')cntl++; if(s[i]=='R')cntr++; if(s[i]=='U')cntu++; if(s[i]=='D')cntd++; } ll needl_r=min(cntl, cntr); ll needu_d=min(cntu, cntd); if(cntl==0 or cntr==0)needl_r=0; if(cntu==0 or cntd==0)needu_d=0; if(needl_r>1 and needu_d==0 )needl_r=1; if(needu_d>1 and needl_r==0 )needu_d=1; string s1; fr(i, needl_r) s1+='L'; fr(i, needu_d) s1+='U'; fr(i, needl_r) s1+='R'; fr(i, needu_d) s1+='D'; cout<<s1.size()<<endl<<s1<<endl; } }
#include "../include/TextQuery.h" #include "../include/Configure.h" #include "../include/ReadFile.h" #include "../include/EditDistance.h" #include "../include/Redis.h" #include <iostream> #include <set> #include <json/json.h> #include <hiredis/hiredis.h> using std::cout; using std::endl; using std::set; using namespace Json; extern __thread const char* current_thread::threadName; extern __thread Redis* redis; int TextQuery::queryCache(){ _response = redis->get(_msg); cout << _response << endl; if(_response == "-1"){ cout << current_thread::threadName << "缓存未命中" << endl; return -1; } else{ cout << current_thread::threadName << "缓存命中" << endl; reply(); return 0; } } void TextQuery::query(){//处理业务逻辑 int ret = queryCache(); if(ret == 0){ return; } set<int> numSet;//单词序号的集合,去除重复序号 ReadFile *pread=ReadFile::getInstance(); size_t curPos = 0; string oneChar;//英文的一个字母或者中文的一个汉字 while(curPos != _msg.size()){ size_t wordLen = nBytesCode(_msg[curPos]); oneChar = _msg.substr(curPos,wordLen); for(auto number:pread->getIndex()[oneChar]){ numSet.insert(number); } curPos += wordLen;//字符后移 } // for(size_t i=0;i<_msg.size();i++){//依次遍历查询单词的每个字母 // for(auto number:pread->getIndex()[string(1,_msg[i])]){//遍历set集合 // numSet.insert(number); // } // } for(int number:numSet){//将候选词按最小编辑距离由小到大加入集合中 MyResult myresult; myresult._word=(pread->getDict()[number]).first; myresult._iFreq=(pread->getDict()[number]).second; myresult._iDist=distance(myresult._word); _resultQue.push(myresult); } geneJson();//以json格式要返回给客户端的消息 reply();//消息回送给客户端 redis->set(_msg,_response);//将查询结果保存至缓存 cout << "已将该候选词结果存在cache:" << _response << endl; } void TextQuery::reply(){ int jsonLen = sizeof(_response);//使用小火车私有协议 //_conn->send(response);//由线程池的线程(计算线程)完成数据的发送,在设计上来说,是不合理的 //数据发送的工作要交还给IO线程(Reactor所在的线程)完成 //将send的函数的执行延迟到IO线程去操作 _conn->sendInLoop(string(1,jsonLen)); _conn->sendInLoop(_response); } int TextQuery::distance(const string & rhs){ return editDistance(_msg,rhs); } void TextQuery::geneJson(){ Json::Value root; for(int i=0;i<3;i++){ root[_msg].append(_resultQue.top()._word); cout << _resultQue.top()._word << endl; _resultQue.pop(); } Json::StyledWriter stylewriter; cout << stylewriter.write(root) << endl; _response = stylewriter.write(root); }
#pragma once #include "headers.h" void slashAtk(GameObject* obj, int dmg); class Player : public Actor { private: TIMER dodgeTimer; bool dodge; public: Player(POINT p); virtual void draw(HDC& hdc); bool isDodge() { return dodge; } void setDodge() { dodge = true; } void unsetDodge() { dodge = false; } bool canDodge() { return dodgeTimer.getElapsedTime() > 600; } void setDodgeTimer() { dodgeTimer.set(); } };
#include <I2Cdev.h> #include <MPU6050.h> // Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation // is used in I2Cdev.h #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE #include <Wire.h> #endif // class default I2C address is 0x68 // specific I2C addresses may be passed as a parameter here // AD0 low = 0x68 (default for InvenSense evaluation board) // AD0 high = 0x69 MPU6050 accelgyro; //MPU6050 accelgyro(0x69); // <-- use for AD0 high int16_t ax, ay, az; int16_t gx, gy, gz; //Motor stuff int motorLFwd = 5; int motorLRev = 6; int motorRFwd = 9; int motorRRev = 10; double motorValueL, motorValueR; //Delay in microseconds for each motor double motorRateL = 10; double motorRateR = 10; //Higher value = greater delay = slower motor speed int gravityValue = 15000; int deadSpace = 200; //Time calculations unsigned long previousTimeL = 0; unsigned long previousTimeR = 0; unsigned long previousTimeDisp = 0; #define OUTPUT_READABLE_ACCELGYRO #define LED_PIN 12 bool blinkState = false; void setup() { // join I2C bus (I2Cdev library doesn't do this automatically) #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE Wire.begin(); #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE Fastwire::setup(400, true); #endif Serial.begin(38400); // initialize device Serial.println("Initializing I2C devices..."); accelgyro.initialize(); // verify connection Serial.println("Testing device connections..."); Serial.println(accelgyro.testConnection() ? "MPU6050 connection successful" : "MPU6050 connection failed"); // use the code below to change accel/gyro offset values /* Serial.println("Updating internal sensor offsets..."); // -76 -2359 1688 0 0 0 Serial.print(accelgyro.getXAccelOffset()); Serial.print("\t"); // -76 Serial.print(accelgyro.getYAccelOffset()); Serial.print("\t"); // -2359 Serial.print(accelgyro.getZAccelOffset()); Serial.print("\t"); // 1688 Serial.print(accelgyro.getXGyroOffset()); Serial.print("\t"); // 0 Serial.print(accelgyro.getYGyroOffset()); Serial.print("\t"); // 0 Serial.print(accelgyro.getZGyroOffset()); Serial.print("\t"); // 0 Serial.print("\n"); accelgyro.setXGyroOffset(220); accelgyro.setYGyroOffset(76); accelgyro.setZGyroOffset(-85); Serial.print(accelgyro.getXAccelOffset()); Serial.print("\t"); // -76 Serial.print(accelgyro.getYAccelOffset()); Serial.print("\t"); // -2359 Serial.print(accelgyro.getZAccelOffset()); Serial.print("\t"); // 1688 Serial.print(accelgyro.getXGyroOffset()); Serial.print("\t"); // 0 Serial.print(accelgyro.getYGyroOffset()); Serial.print("\t"); // 0 Serial.print(accelgyro.getZGyroOffset()); Serial.print("\t"); // 0 Serial.print("\n"); */ accelgyro.setXAccelOffset(-500); accelgyro.setYAccelOffset(-3920); accelgyro.setZAccelOffset(1480); // configure Arduino LED for pinMode(LED_PIN, OUTPUT); pinMode(motorLFwd, OUTPUT); pinMode(motorLRev, OUTPUT); pinMode(motorRFwd, OUTPUT); pinMode(motorRRev, OUTPUT); } void loop() { unsigned long currentTime = millis(); // read raw accel/gyro measurements from device accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz); // these methods (and a few others) are also available //accelgyro.getAcceleration(&ax, &ay, &az); //accelgyro.getRotation(&gx, &gy, &gz); if(currentTime - previousTimeDisp > 150) { #ifdef OUTPUT_READABLE_ACCELGYRO // display tab-separated accel/gyro x/y/z values Serial.print("a/g:\t"); Serial.print(ax); Serial.print("\t"); Serial.print(ay); Serial.print("\t"); Serial.print(az); Serial.print("\t"); Serial.print(gx); Serial.print("\t"); Serial.print(gy); Serial.print("\t"); Serial.println(gz); #endif previousTimeDisp = currentTime; } // blink LED to indicate activity blinkState = !blinkState; digitalWrite(LED_PIN, blinkState); /* * MOTOR STUFFFF */ if(ax > deadSpace || ax < -1*deadSpace) { motorValueL = map(abs(ax), 0, gravityValue, 0, 255); motorValueR = motorValueL; } //LEFT MOTOR if(currentTime - previousTimeL >= motorValueL*motorRateL) { analogWrite(motorLRev, 0); analogWrite(motorLFwd, motorValueL*motorRateL); previousTimeL = currentTime; } if(currentTime - previousTimeL >= motorValueL*motorRateL) { analogWrite(motorLFwd, 0); analogWrite(motorLRev, motorValueL*motorRateL); previousTimeL = currentTime; } //RIGHT MOTOR if(currentTime - previousTimeR >= motorValueR*motorRateR) { analogWrite(motorRRev, 0); analogWrite(motorRFwd, motorValueR*motorRateR); previousTimeR = currentTime; } if(currentTime - previousTimeR >= motorValueR*motorRateR) { analogWrite(motorRFwd, 0); analogWrite(motorRRev, motorValueR*motorRateR); previousTimeR = currentTime; } }
#include <iostream> #include <exception> #include <typeinfo> using namespace std; class A{virtual f(){};}; int main() { try { A *a=NULL; typeid(*a); } catch(exception &e) { cout<<"Standard Exception "<<e.what(); } system("pause"); return 0; }
#ifndef __Block_H__ #define __Block_H__ #include "cocos2d.h" USING_NS_CC; class Block :public CCSprite { public: //! block的尺寸.颜色. 字体内容.大小.颜色 static Block * create(CCSize size, ccColor3B color, CCString str, float strSize, ccColor3B strColor); bool init(CCSize size, ccColor3B color, CCString str, float strSize, ccColor3B strColor); //记录block的数量 static CCArray *array; static CCArray *getBlocksArray(); //记录行数 CC_SYNTHESIZE(int, _lineIndex, LineIndex); void moveDownAndCleanUp(); }; #endif
#ifndef CAMERA3D_H #define CAMERA3D_H #include "ICamera.h" #include "DemoUtils/GLInclude.h" class Camera3D : public ICamera { private: float X = 20.0; float Y = -20.0; float Z = 20.0; float CameraAngle = 0.0; public: virtual void Move(float dx,float dy,float dz) override { X += dx; Y += dy; Z += dz; } virtual void Rotate(float dangle) override { CameraAngle += dangle; } virtual void ApplyProjectionTransform() override { gluPerspective(90,1.0,1.0,-200.0); } virtual void ApplyViewTransform() override { glTranslatef(X,Y,Z); glRotatef(CameraAngle,0.0,1.0,0.0); glRotatef(-90.0,1.0,0.0,0.0); } Camera3D() {} virtual ~Camera3D() override {} }; #endif // CAMERA3D_H
#include "ConvertSortedListToBinarySearchTree.hpp" TreeNode *ConvertSortedListToBinarySearchTree::sortedListToBST(ListNode *head) { this->head = head; int len = list_len(head); return sortedListToBST(0, len - 1); } TreeNode *ConvertSortedListToBinarySearchTree::sortedListToBST(int start, int end) { if (start > end) return nullptr; int mid = (start + end) / 2; TreeNode *left = sortedListToBST(start, mid - 1); TreeNode *root = new TreeNode(head->val); head = head->next; TreeNode *right = sortedListToBST(mid + 1, end); root->left = left; root->right = right; return root; }
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: eyohn <sopka13@mail.ru> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/07/07 11:52:06 by eyohn #+# #+# */ /* Updated: 2021/07/07 14:26:20 by eyohn ### ########.fr */ /* */ /* ************************************************************************** */ #include "Character.hpp" #include "AWeapon.hpp" #include "Enemy.hpp" #include "PlasmaRifle.hpp" #include "PowerFist.hpp" #include "RadScorpion.hpp" #include "SuperMutant.hpp" int main(void) { Character* me = new Character("me"); std::cout << *me; Enemy* scorpion = new RadScorpion(); Enemy* mutant = new SuperMutant(); std::cout << *scorpion; std::cout << *mutant; AWeapon* plasma = new PlasmaRifle(); AWeapon* power = new PowerFist(); me->equip(plasma); std::cout << *me; me->attack(scorpion); std::cout << *me; std::cout << *scorpion; me->attack(mutant); std::cout << *me; std::cout << *mutant; me->equip(power); std::cout << *me; me->attack(scorpion); std::cout << *me; std::cout << *scorpion; me->attack(mutant); std::cout << *me; std::cout << *mutant; me->attack(scorpion); std::cout << *me; std::cout << *scorpion; delete me; delete scorpion; delete mutant; delete plasma; delete power; // Character* me = new Character("me"); // std::cout << *me; // Enemy* b = new RadScorpion(); // AWeapon* pr = new PlasmaRifle(); // AWeapon* pf = new PowerFist(); // me->equip(pr); // std::cout << *me; // me->equip(pf); // me->attack(b); // std::cout << *me; // me->equip(pr); // std::cout << *me; // me->attack(b); // std::cout << *me; // me->attack(b); // std::cout << *me; return (0); }
#include <iostream> #include <fstream> #include "Assignment4.h" using namespace std; //WORKS void CommunicationNetwork::addCity(std::string newCityName, std::string previousCityName){ //cout << newCityName << " " << previousCityName << endl; //INITIALIZE A CITY TO BE ADDED City *nn = new City; nn -> cityName = newCityName; //MAKE A CRAWLER POINTER TO TRAVERSE THE LIST City *crwl = head; //FIGURE OUT IF THE LIST IS EMPTY if(head == 0){ //IT IS //HEAD IS THE NEW CITY head = nn; }else{ //IT ISNT //FIND WHERE THE CITY SOULD GO if(previousCityName == "First"){ nn -> next = head; head -> previous = nn; head = nn; }else if(previousCityName == ""){ //IT SHOULD GO AT THE END APPARENTLY while(crwl -> next != nullptr){ crwl = crwl -> next; } crwl -> next = nn; nn -> previous = crwl; //RESETS THE HEAD TO NN BECASUE THAT IS THE NEW HEAD tail = nn; }else{ //IT SHOULD GO IN THE MIDDLE/END while(crwl -> cityName != previousCityName){ crwl = crwl -> next; } //IT NEEDS TO BE ADDED TO THE END if(crwl -> next == nullptr){ crwl -> next = nn; nn -> previous = crwl; tail = nn; //IT GOES SOMEWHERE IN THE MIDDLE }else{ crwl -> next -> previous = nn; nn -> next = crwl -> next; crwl -> next = nn; nn -> previous = crwl; } } } } //WORKS void CommunicationNetwork::transmitMsg(char* filename){ City *tmp = new City; tmp = head; string ss; ifstream mainfile; mainfile.open(filename); if(mainfile.is_open()){ while(mainfile >> ss){ while(tmp -> next != nullptr){ tmp -> message = ss; cout << tmp -> cityName << " received " << tmp -> message<< endl; tmp = tmp -> next; } tmp -> message = ss; cout << tmp -> cityName << " received " << tmp -> message << endl; tmp = tmp -> previous; while(tmp -> previous != nullptr){ tmp -> message = ss; cout << tmp -> cityName << " received " << tmp -> message << endl; tmp = tmp -> previous; } head -> message = ss; cout << head -> cityName << " received " << head -> message << endl; } } mainfile.close(); } //WORKS void CommunicationNetwork::printNetwork(){ cout << "===CURRENT PATH===" << endl; //THIS WONT WORK IF LIST OS EMPTY City *tmp = head; cout << "NULL <- "; while(tmp != nullptr){ cout << tmp -> cityName; if(tmp -> next != nullptr){ cout << " <-> "; } tmp = tmp -> next; } cout << " -> NULL" << endl; cout << "==================" << endl; } //WORKS void CommunicationNetwork::buildNetwork(){ string cities[10] = {"Los Angeles", "Phoenix", "Denver", "Dallas", "St. Louis", "Chicago", "Atlanta", "Washington, D.C.", "New York", "Boston"}; City *tmp; City *tmp1 = new City; tmp = tmp1; //THIS IS SUPER IMPORTANT!!!! head = tmp1; tmp -> cityName = cities[0]; for(int i = 1; i < 10; i++){ City *nn = new City; nn -> cityName = cities[i]; nn -> previous = tmp; tmp -> next = nn; tmp = nn; } } //WORKS void CommunicationNetwork::deleteCity(std::string removeCity){ City *tmp = head; City *tmpA; City *tmpB; bool exist = false; while(tmp -> cityName != removeCity && tmp != tail){ tmp = tmp -> next; } if(tmp -> cityName == removeCity){ exist = true; } if(exist){ tmpB = tmp -> previous; tmpA = tmp -> next; //END OF THE LIST if(tmp -> next == nullptr){ tmpB -> next = nullptr; tail = tmpB; //BEGINING OF THE LIST }else if(tmp -> previous == nullptr){ tmpA -> previous = nullptr; head = tmpA; //ANYWHERE ELSE }else{ tmpB -> next = tmpA; tmpA -> previous = tmpB; } delete tmp; } if(!exist){ cout << removeCity << " not found" << endl; } } //WORKS void CommunicationNetwork::deleteNetwork(){ City *tmp = head; City *nxt; while(nxt != nullptr){ nxt = tmp -> next; cout << "deleting " << tmp -> cityName << endl; delete tmp; tmp = nxt; } head = 0; } //WORKS CommunicationNetwork::CommunicationNetwork(){ City *nn = new City; City *head; head = nn; head = tail; } //WORKS CommunicationNetwork::~CommunicationNetwork(){ head = nullptr; tail = nullptr; }
#include "SecretDoor/SecretDoor.h" #include <iostream> #include <string> using namespace std; int main() { // declare and initialize variables SecretDoor game; int playCount = 0; int timesWon = 0; string playerName; // ask for player name and store into playerName cout << "What is your name? "; cin >> playerName; // Greet player Price is Right show style cout << "\n== " << playerName << " ,come on down to play Door Price Game! == " << endl; // ask player how many times to play cout << "How many times you would like to play? " ; cin >> playCount; // repeat game based on user input for (int x = 0; x < playCount; x++) { // starts new name game.newGame(); // force door C to be always picked each time. User has no choice or input.- game.guessDoorC(); game.guessDoorC(); // keep track of how many times won if(game.isWinner() == true) { timesWon++; } } // end if // // announce times game was won cout << "\nWOW! That is a new record folks!" << endl; cout << playerName << " has set a new Door Prize game record by winning " << timesWon << " times!" << endl; //end program return 0; }
#include <Windows.h> #include <TlHelp32.h> #include <tchar.h> #include "HOOK/HookAPIX.h" XLIB::CXHookAPI g_hookLog; XLIB::CXHookAPI g_hookMacFunc; XLIB::CXHookAPI g_hookProcess32First; XLIB::CXHookAPI g_hookProcess32FirstW; int __cdecl Log(char *x1, int x2, int x3, char x4); extern "C" __declspec(dllexport) void TestFuction() { ////do anything here//// } BOOL WINAPI FakeProcess32FirstW( HANDLE hSnapshot, LPPROCESSENTRY32W lppe ) { return FALSE; } BOOL WINAPI FakeProcess32First( HANDLE hSnapshot, LPPROCESSENTRY32 lppe ) { return FALSE; //return g_hookProcess32First.CallFunction(2, hSnapshot, lppe); } LPVOID QueryVMPCodeMemory() { MEMORY_BASIC_INFORMATION tagMemInfo = { 0 }; for (DWORD i = 0x2000000; i < 0x40000000; ) { if (VirtualQuery((LPVOID)i, &tagMemInfo, sizeof(MEMORY_BASIC_INFORMATION))) { if (0x0b000 == tagMemInfo.RegionSize && PAGE_EXECUTE_READWRITE == tagMemInfo.AllocationProtect && MEM_COMMIT == tagMemInfo.State && PAGE_EXECUTE_READ == tagMemInfo.Protect && MEM_MAPPED == tagMemInfo.Type && 0x6a406a == *(PDWORD)((PBYTE)i+0x6bb5)) { return (LPVOID)i; } i += tagMemInfo.RegionSize; } else { i += 0x1000; } } return NULL; } VOID __cdecl FakeFilter(XLIB::CStack_ESP *pStack) { PBYTE pData = (PBYTE)(*(PDWORD)pStack->ESP); PBYTE pDataMark = (PBYTE)(*(PDWORD)(pStack->ESP + 4)); BYTE aryData[] = { 0x37, 0x83, 0x62, 0xb4, 0xf0, 0xf8, 0x1f, 0xd9, 0x48, 0x59, 0x07, 0xea, 0xa9, 0xee, 0x3a, 0x3d }; BYTE aryMark[16] = {0}; if (memcmp(pDataMark, aryMark, sizeof(aryMark)) == 0 || 3 == pData[17] || memcmp(pDataMark + 8, aryMark, 8) == 0) { memcpy(pData, aryData, sizeof(aryData)); } } int __cdecl FakeLog(char *x1, int x2, int x3, char x4) { if (!g_hookMacFunc.IsHooked()) { LPVOID lpVmpMem = QueryVMPCodeMemory(); if(NULL != lpVmpMem) { LPVOID lpMacFunc = (PBYTE)lpVmpMem + 0x6bb5; if (g_hookMacFunc.InlineHookAddress(lpMacFunc, FakeFilter)) { g_hookLog.UnHook(); } } } return g_hookLog.CallFunction(4, x1, x2, x3, x4); } void Init() { HMODULE hModule = LoadLibrary(_T("Utility.dll")); if (NULL == hModule) { MessageBox(NULL, _T("ÆÆ½âʧ°Ü1"), _T("´íÎó"), MB_OK); return; } LPVOID pFuncLog = GetProcAddress(hModule, "Log"); if (NULL == pFuncLog) { FreeLibrary(hModule); MessageBox(NULL, _T("ÆÆ½âʧ°Ü2"), _T("´íÎó"), MB_OK); return; } HMODULE hKernel32 = LoadLibrary(_T("Kernel32.dll")); LPVOID lpProcess32First = GetProcAddress(hKernel32, "Process32First"); LPVOID lpProcess32FirstW = GetProcAddress(hKernel32, "Process32FirstW"); g_hookProcess32First.InlineHookFunction(lpProcess32First, FakeProcess32First); g_hookProcess32FirstW.InlineHookFunction(lpProcess32FirstW, FakeProcess32FirstW); if (!g_hookLog.IsHooked()) { if (!g_hookLog.InlineHookFunction(pFuncLog, FakeLog)) { FreeLibrary(hModule); MessageBox(NULL, _T("ÆÆ½âʧ°Ü3"), _T("´íÎó"), MB_OK); } } } BOOL WINAPI DllMain( _Out_ HINSTANCE hInstance, _In_ ULONG ulReason, LPVOID Reserved ) { switch (ulReason) { case DLL_PROCESS_ATTACH: Init(); break; default: break; } return TRUE; }
#pragma once #include <map> #include "../utility/entity.h" #include "../load/LoadFile.h" #include "../load/AdditionalParsing.h" class EntityManager : public LoadFile, public AdditionalParsing { typedef std::map<std::string, Entity> EntityMap; typedef std::map<std::string, Entity>::iterator EntityMapIter; std::string entityName; EntityMap entities; public: EntityManager() : heldItem("") {} std::string heldItem; Entity& getEntity(std::string name); std::vector<Position> blockedPositions(); void addEntity(std::string name, Entity entity); void store(std::string, std::string); };
#ifndef PARSER_H #define PARSER_H #include <unistd.h> #include <fcntl.h> #include <termios.h> #include <stdio.h> #include <stdlib.h> #include <iostream> #include <fstream> #include <string> #include <string.h> #include <map> #include <vector> #include <errno.h> #include <time.h> #include <stdint.h> #include <algorithm> //remove if #include <sstream> #include "word_node.h" class insulter { public: // destructor ~insulter(); //constructor insulter(); /******************************************************************************/ /** \brief Initalializes the insulter map. Ths map is a string to char map * the values assigned and derived are from the speakjet datasheet found below * https://www.sparkfun.com/datasheets/Components/General/speakjet-usermanual.pdf * * \par Assumptions, External Events, and Notes: * * \param[in,out] None * * \returns None *****************************************************************************/ void initialize_insulter_map(); /******************************************************************************/ /** \brief this function takes in a line like \SE\KE\OHIH\FAST\IH and a word like sky * to create a linked list of bytes we transform the line to all uppercase and get the correspoonding string to byte mapping * \SE\ -> SE -> 187 * * \par Assumptions, External Events, and Notes: * * \param[in] string line is a string representing how to enunciate a word string word is the word * * \returns None *****************************************************************************/ void make_word_node(std::string line, std::string word); /******************************************************************************/ /** \brief this function takes in a single enunciation like "KE" and returns the mapped value * for values like "3" we convert the string to an int and return that value. for values not * an int representation or in the map we throw an assertion. * * \par Assumptions, External Events, and Notes: * * \param[in] string key is he enunciation like "KE" * * \returns the byte value from the map *****************************************************************************/ uint8_t get_char(std::string key); /******************************************************************************/ /** \brief this function takes in a word and char value. the word is used to retrieve the * head of the linked list from the map. We then malloc for a new word node,store the value passed in as the byte representation * and place the newly created node at the end of the word linked list * * \par Assumptions, External Events, and Notes: * * \param[in] string word is a word like "sky" val is the value to store in the list * * \returns 0 or - 1 failure *****************************************************************************/ int16_t create_new_word_node(std::string word, int8_t val); /******************************************************************************/ /** \brief this function reads from the phrase a lator file transforms and parses the * lines into words and enunciations for following functions to store * * \par Assumptions, External Events, and Notes: * * \param[in] * * \returns none *****************************************************************************/ void initialize_insults(); /******************************************************************************/ /** \brief this function reads from the sentences txt file and stores the phrase in an array * for later processing * * \par Assumptions, External Events, and Notes: * * \param[in] * * \returns none *****************************************************************************/ void initialize_sentences(); /******************************************************************************/ /** \brief this function chooses a random insult from the array created by the sentences txt file * it then parses the words from the string. each word is mapped to the head of the linked list which is processed out via serual. * * \par Assumptions, External Events, and Notes: * * \param[in] * * \returns none *****************************************************************************/ int16_t say_sentence(); /******************************************************************************/ /** \brief this function takes the head of a word node list and iterates through the list * transmitting the enunciations byte by byte as well as monitor the ready pin on the speakjet * * \par Assumptions, External Events, and Notes: * * \param[in] pointer to the head of a list * * \returns none *****************************************************************************/ int16_t speak_word(word_node* head); /******************************************************************************/ /** \brief this function initializes the gpio uart serial pins on the rpi3 and zero * * \par Assumptions, External Events, and Notes: * assuming that bluetooth is disabled * * \param[in] none * * \returns none *****************************************************************************/ void initialize_serial(); /******************************************************************************/ /** \brief this function frees the linked list word that was created from the dictionary file * * \par Assumptions, External Events, and Notes: * * \param[in] pointer to head of word node list * * \returns none *****************************************************************************/ void free_word(word_node* word); /******************************************************************************/ /** \brief this function tests the serial communication by transmitting the receiving the bytes * * \par Assumptions, External Events, and Notes: * UART tx and RX are connected in loopback manner * \param[in] pointer to head of word node list * * \returns none *****************************************************************************/ void test_serial(); private: // map to store char commands to speakjet std::map<std::string, uint8_t> das_map; // map to store the head of linked list for a word std::map<std::string, word_node*>word_map; // int number_of_insults; std::vector<std::string> insults; // fd to write serial output to the speakjet to int16_t uart_fd; }; #endif
#include "card.h" #include <QString> #include <QDebug> Card::Card(size_t const& value, size_t const& suit, bool const& upsided): mUpSided(upsided), mValue(value), mSuit(suit) { mUpSideTextureId = (mSuit * 13) + value; normal.setWidth(70); normal.setHeight(90); min.setWidth(63); min.setHeight(81); QString name = "k" + QString::number(mUpSideTextureId) + ".png"; qDebug() << name; mUpTexture = new QImage(":/cards/Media/Cards/" + name); name = "k0.png"; mDownTexture = new QImage(":/cards/Media/Cards/" + name); if (upsided) { card = mUpTexture->scaled(normal.width(), normal.height(), Qt::IgnoreAspectRatio); } else { card = mDownTexture->scaled(normal.width(), normal.height(), Qt::IgnoreAspectRatio); } this->setPixmap(QPixmap::fromImage(card, Qt::AutoColor)); this->repaint(); } Card::~Card() { delete mDownTexture; delete mUpTexture; } void Card::Flip() { if (!LowRes) if (mUpSided) { card = mDownTexture->scaled(normal.width(), normal.height(), Qt::IgnoreAspectRatio); mUpSided = false; } else { card = mUpTexture->scaled(normal.width(), normal.height(), Qt::IgnoreAspectRatio); mUpSided = true; } else { if (mUpSided) { card = mDownTexture->scaled(min.width(), min.height(), Qt::IgnoreAspectRatio); mUpSided = false; } else { card = mUpTexture->scaled(min.width(), min.height(), Qt::IgnoreAspectRatio); mUpSided = true; } } this->setPixmap(QPixmap::fromImage(card, Qt::AutoColor)); this->repaint(); } size_t Card::GetValue() { return mValue; } size_t Card::GetSuit() { return mSuit; } bool Card::GetSide() { return mUpSided; } void Card::Resize(QSize WinSize) { if (WinSize.height() <= 1093) { if (mUpSided) card = mUpTexture->scaled(min.width(), min.height(), Qt::IgnoreAspectRatio); else card = mDownTexture->scaled(min.width(), min.height(), Qt::IgnoreAspectRatio); LowRes = 1; } else { if (mUpSided) card = mUpTexture->scaled(normal.width(), normal.height(), Qt::IgnoreAspectRatio); else card = mDownTexture->scaled(normal.width(), normal.height(), Qt::IgnoreAspectRatio); LowRes = 0; } this->setPixmap(QPixmap::fromImage(card, Qt::AutoColor)); } void Card::ResizeOnTable(QSize WinSize, size_t pos) { if (WinSize.height() <= 1093) { if (mUpSided) card = mUpTexture->scaled(min.width(), min.height(), Qt::IgnoreAspectRatio); else card = mDownTexture->scaled(min.width(), min.height(), Qt::IgnoreAspectRatio); LowRes = 1; this->setGeometry(166 + pos * 80, 80, 500, 500); } else { if (mUpSided) card = mUpTexture->scaled(normal.width(), normal.height(), Qt::IgnoreAspectRatio); else card = mDownTexture->scaled(normal.width(), normal.height(), Qt::IgnoreAspectRatio); LowRes = 0; this->setGeometry(280 + pos * 90, 150, 500, 500); } this->setPixmap(QPixmap::fromImage(card, Qt::AutoColor)); }
//************************************************************************** //** //** See jlquake.txt for copyright info. //** //** This program is free software; you can redistribute it and/or //** modify it under the terms of the GNU General Public License //** as published by the Free Software Foundation; either version 3 //** of the License, or (at your option) any later version. //** //** This program is distributed in the hope that it will be useful, //** but WITHOUT ANY WARRANTY; without even the implied warranty of //** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //** included (gnu.txt) GNU General Public License for more details. //** //************************************************************************** #include <cppunit/extensions/HelperMacros.h> #include "../../source/common/math/Vec3.h" class idVec3Test : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE( idVec3Test ); CPPUNIT_TEST( TestConstructor ); CPPUNIT_TEST( TestSet ); CPPUNIT_TEST( TestZero ); CPPUNIT_TEST( TestOperatorIndex ); CPPUNIT_TEST( TestOperatorAssign ); CPPUNIT_TEST( TestOperatorPlus ); CPPUNIT_TEST( TestOperatorMinus ); CPPUNIT_TEST( TestOperatorMultiplyVec ); CPPUNIT_TEST( TestOperatorMultiplyFloat ); CPPUNIT_TEST( TestOperatorDivideFloat ); CPPUNIT_TEST( TestOperatorPlusEqualsVec ); CPPUNIT_TEST( TestOperatorMinusEqualsVec ); CPPUNIT_TEST( TestOperatorMultiplyEqualsFloat ); CPPUNIT_TEST( TestOperatorFloatMultiplyVec ); CPPUNIT_TEST( TestCompare ); CPPUNIT_TEST( TestOperatorEquals ); CPPUNIT_TEST( TestOperatorNotEquals ); CPPUNIT_TEST( TestLength ); CPPUNIT_TEST( TestLengthSqr ); CPPUNIT_TEST( TestNormalize ); CPPUNIT_TEST( TestToFloatPtr ); CPPUNIT_TEST_SUITE_END(); public: virtual void setUp(); void TestConstructor(); void TestSet(); void TestZero(); void TestOperatorIndex(); void TestOperatorAssign(); void TestOperatorPlus(); void TestOperatorMinus(); void TestOperatorMultiplyVec(); void TestOperatorMultiplyFloat(); void TestOperatorDivideFloat(); void TestOperatorPlusEqualsVec(); void TestOperatorMinusEqualsVec(); void TestOperatorMultiplyEqualsFloat(); void TestOperatorFloatMultiplyVec(); void TestCompare(); void TestOperatorEquals(); void TestOperatorNotEquals(); void TestLength(); void TestLengthSqr(); void TestNormalize(); void TestToFloatPtr(); }; // Registers the fixture into the 'registry' CPPUNIT_TEST_SUITE_REGISTRATION( idVec3Test ); void idVec3Test::setUp() { idMath::Init(); } void idVec3Test::TestConstructor() { idVec3 v( 1.0f, 2.0f, 3.0f ); CPPUNIT_ASSERT_EQUAL( 1.0f, v.x ); CPPUNIT_ASSERT_EQUAL( 2.0f, v.y ); CPPUNIT_ASSERT_EQUAL( 3.0f, v.z ); } void idVec3Test::TestSet() { idVec3 v; v.Set( 1.0f, 2.0f, 3.0f ); CPPUNIT_ASSERT_EQUAL( 1.0f, v.x ); CPPUNIT_ASSERT_EQUAL( 2.0f, v.y ); CPPUNIT_ASSERT_EQUAL( 3.0f, v.z ); } void idVec3Test::TestZero() { idVec3 v( 1.0f, 2.0f, 3.0f ); v.Zero(); CPPUNIT_ASSERT_EQUAL( 0.0f, v.x ); CPPUNIT_ASSERT_EQUAL( 0.0f, v.y ); CPPUNIT_ASSERT_EQUAL( 0.0f, v.z ); } void idVec3Test::TestOperatorIndex() { idVec3 v( 1.0f, 2.0f, 3.0f ); CPPUNIT_ASSERT_EQUAL( 1.0f, v[ 0 ] ); CPPUNIT_ASSERT_EQUAL( 2.0f, v[ 1 ] ); CPPUNIT_ASSERT_EQUAL( 3.0f, v[ 2 ] ); } void idVec3Test::TestOperatorAssign() { idVec3 v; idVec3 v2( 1.0f, 2.0f, 3.0f ); v = v2; CPPUNIT_ASSERT_EQUAL( 1.0f, v.x ); CPPUNIT_ASSERT_EQUAL( 2.0f, v.y ); CPPUNIT_ASSERT_EQUAL( 3.0f, v.z ); } void idVec3Test::TestOperatorPlus() { idVec3 v1( 23.0f, 76.0f, 47.0f ); idVec3 v2( 4.0f, 5.0f, 6.0f ); idVec3 v = v1 + v2; CPPUNIT_ASSERT_EQUAL( 27.0f, v.x ); CPPUNIT_ASSERT_EQUAL( 81.0f, v.y ); CPPUNIT_ASSERT_EQUAL( 53.0f, v.z ); } void idVec3Test::TestOperatorMinus() { idVec3 v1( 34.0f, 73.0f, 83.0f ); idVec3 v2( 4.0f, 5.0f, 6.0f ); idVec3 v = v1 - v2; CPPUNIT_ASSERT_EQUAL( 30.0f, v.x ); CPPUNIT_ASSERT_EQUAL( 68.0f, v.y ); CPPUNIT_ASSERT_EQUAL( 77.0f, v.z ); } void idVec3Test::TestOperatorMultiplyVec() { idVec3 v1( 1.0f, 2.0f, 3.0f ); idVec3 v2( 4.0f, 5.0f, 6.0f ); CPPUNIT_ASSERT_EQUAL( 32.0f, v1 * v2 ); } void idVec3Test::TestOperatorMultiplyFloat() { idVec3 v1( 1.0f, 2.0f, 3.0f ); idVec3 v = v1 * 3; CPPUNIT_ASSERT_EQUAL( 3.0f, v.x ); CPPUNIT_ASSERT_EQUAL( 6.0f, v.y ); CPPUNIT_ASSERT_EQUAL( 9.0f, v.z ); } void idVec3Test::TestOperatorDivideFloat() { idVec3 v1( 15.0f, 9.0f, 12.0f ); idVec3 v = v1 / 3.0f; CPPUNIT_ASSERT_EQUAL( 5.0f, v.x ); CPPUNIT_ASSERT_EQUAL( 3.0f, v.y ); CPPUNIT_ASSERT_EQUAL( 4.0f, v.z ); } void idVec3Test::TestOperatorPlusEqualsVec() { idVec3 v( 1.0f, 2.0f, 3.0f ); idVec3 v2( 4.0f, 5.0f, 6.0f ); v += v2; CPPUNIT_ASSERT_EQUAL( 5.0f, v.x ); CPPUNIT_ASSERT_EQUAL( 7.0f, v.y ); CPPUNIT_ASSERT_EQUAL( 9.0f, v.z ); } void idVec3Test::TestOperatorMinusEqualsVec() { idVec3 v( 34.0f, 73.0f, 83.0f ); idVec3 v2( 4.0f, 5.0f, 6.0f ); v -= v2; CPPUNIT_ASSERT_EQUAL( 30.0f, v.x ); CPPUNIT_ASSERT_EQUAL( 68.0f, v.y ); CPPUNIT_ASSERT_EQUAL( 77.0f, v.z ); } void idVec3Test::TestOperatorMultiplyEqualsFloat() { idVec3 v( 1.0f, 2.0f, 3.0f ); v *= 3; CPPUNIT_ASSERT_EQUAL( 3.0f, v.x ); CPPUNIT_ASSERT_EQUAL( 6.0f, v.y ); CPPUNIT_ASSERT_EQUAL( 9.0f, v.z ); } void idVec3Test::TestOperatorFloatMultiplyVec() { idVec3 v1( 1.0f, 2.0f, 3.0f ); idVec3 v = 3 * v1; CPPUNIT_ASSERT_EQUAL( 3.0f, v.x ); CPPUNIT_ASSERT_EQUAL( 6.0f, v.y ); CPPUNIT_ASSERT_EQUAL( 9.0f, v.z ); } void idVec3Test::TestCompare() { idVec3 v1( 1.0f, 2.0f, 3.0f ); idVec3 v2( 1.0f, 2.0f, 3.0f ); idVec3 v3( 45.0f, 75.0f, 456.0f ); CPPUNIT_ASSERT_EQUAL( true, v1.Compare( v1 ) ); CPPUNIT_ASSERT_EQUAL( true, v1.Compare( v2 ) ); CPPUNIT_ASSERT_EQUAL( false, v1.Compare( v3 ) ); } void idVec3Test::TestOperatorEquals() { idVec3 v1( 1.0f, 2.0f, 3.0f ); idVec3 v2( 1.0f, 2.0f, 3.0f ); idVec3 v3( 45.0f, 75.0f, 456.0f ); CPPUNIT_ASSERT_EQUAL( true, v1 == v1 ); CPPUNIT_ASSERT_EQUAL( true, v1 == v2 ); CPPUNIT_ASSERT_EQUAL( false, v1 == v3 ); } void idVec3Test::TestOperatorNotEquals() { idVec3 v1( 1.0f, 2.0f, 3.0f ); idVec3 v2( 1.0f, 2.0f, 3.0f ); idVec3 v3( 45.0f, 75.0f, 456.0f ); CPPUNIT_ASSERT_EQUAL( false, v1 != v1 ); CPPUNIT_ASSERT_EQUAL( false, v1 != v2 ); CPPUNIT_ASSERT_EQUAL( true, v1 != v3 ); } void idVec3Test::TestLength() { idVec3 v( 1.0f, 2.0f, 3.0f ); CPPUNIT_ASSERT_DOUBLES_EQUAL( 3.74166f, v.Length(), 0.00001 ); } void idVec3Test::TestLengthSqr() { idVec3 v( 1.0f, 2.0f, 3.0f ); CPPUNIT_ASSERT_DOUBLES_EQUAL( 14.0f, v.LengthSqr(), 0.00001 ); } void idVec3Test::TestNormalize() { idVec3 v( 1.0f, 2.0f, 3.0f ); CPPUNIT_ASSERT_DOUBLES_EQUAL( 3.74166f, v.Normalize(), 0.00001 ); CPPUNIT_ASSERT_DOUBLES_EQUAL( 1.0f, v.Length(), 0.000001 ); } void idVec3Test::TestToFloatPtr() { idVec3 v( 1.0f, 2.0f, 3.0f ); CPPUNIT_ASSERT_EQUAL( 1.0f, v.ToFloatPtr()[ 0 ] ); CPPUNIT_ASSERT_EQUAL( 2.0f, v.ToFloatPtr()[ 1 ] ); CPPUNIT_ASSERT_EQUAL( 3.0f, v.ToFloatPtr()[ 2 ] ); }
#ifndef __FGInvincibilityPickUp__H__ #define __FGInvincibilityPickUp__H__ class FGInvincibilityPickUp:public LivingObject { protected: AudioCue* m_pPickedUpAudio; double m_bonusTime; public: FGInvincibilityPickUp(double invincibilityTime, const char* cameraName = GAME_DEFAULT_CAMERA_NAME, unsigned int drawRenderOrder = 0); virtual ~FGInvincibilityPickUp(); virtual void BeginCollision(b2Fixture* fixtureCollided, b2Fixture* fixtureCollidedAgainst, GameObject* objectCollidedagainst, b2Vec2 collisionNormal, b2Vec2 contactPoint, bool touching); virtual void OnDeath(); }; #endif
// C++ for the Windows Runtime vv1.0.170303.6 // Copyright (c) 2017 Microsoft Corporation. All rights reserved. #pragma once #include "../base.h" #include "Windows.Web.Http.Diagnostics.0.h" #include "Windows.Foundation.0.h" #include "Windows.System.Diagnostics.0.h" #include "Windows.Web.Http.0.h" #include "Windows.Foundation.Collections.1.h" #include "Windows.Foundation.1.h" WINRT_EXPORT namespace winrt { namespace ABI::Windows::Web::Http::Diagnostics { struct __declspec(uuid("bd811501-a056-4d39-b174-833b7b03b02c")) __declspec(novtable) IHttpDiagnosticProvider : Windows::Foundation::IInspectable { virtual HRESULT __stdcall abi_Start() = 0; virtual HRESULT __stdcall abi_Stop() = 0; virtual HRESULT __stdcall add_RequestSent(Windows::Foundation::TypedEventHandler<Windows::Web::Http::Diagnostics::HttpDiagnosticProvider, Windows::Web::Http::Diagnostics::HttpDiagnosticProviderRequestSentEventArgs> * handler, event_token * token) = 0; virtual HRESULT __stdcall remove_RequestSent(event_token token) = 0; virtual HRESULT __stdcall add_ResponseReceived(Windows::Foundation::TypedEventHandler<Windows::Web::Http::Diagnostics::HttpDiagnosticProvider, Windows::Web::Http::Diagnostics::HttpDiagnosticProviderResponseReceivedEventArgs> * handler, event_token * token) = 0; virtual HRESULT __stdcall remove_ResponseReceived(event_token token) = 0; virtual HRESULT __stdcall add_RequestResponseCompleted(Windows::Foundation::TypedEventHandler<Windows::Web::Http::Diagnostics::HttpDiagnosticProvider, Windows::Web::Http::Diagnostics::HttpDiagnosticProviderRequestResponseCompletedEventArgs> * handler, event_token * token) = 0; virtual HRESULT __stdcall remove_RequestResponseCompleted(event_token token) = 0; }; struct __declspec(uuid("735f98ee-94f6-4532-b26e-61e1b1e4efd4")) __declspec(novtable) IHttpDiagnosticProviderRequestResponseCompletedEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_ActivityId(GUID * value) = 0; virtual HRESULT __stdcall get_Timestamps(Windows::Web::Http::Diagnostics::IHttpDiagnosticProviderRequestResponseTimestamps ** value) = 0; virtual HRESULT __stdcall get_RequestedUri(Windows::Foundation::IUriRuntimeClass ** value) = 0; virtual HRESULT __stdcall get_ProcessId(uint32_t * value) = 0; virtual HRESULT __stdcall get_ThreadId(uint32_t * value) = 0; virtual HRESULT __stdcall get_Initiator(winrt::Windows::Web::Http::Diagnostics::HttpDiagnosticRequestInitiator * value) = 0; virtual HRESULT __stdcall get_SourceLocations(Windows::Foundation::Collections::IVectorView<Windows::Web::Http::Diagnostics::HttpDiagnosticSourceLocation> ** value) = 0; }; struct __declspec(uuid("e0afde10-55cf-4c01-91d4-a20557d849f0")) __declspec(novtable) IHttpDiagnosticProviderRequestResponseTimestamps : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_CacheCheckedTimestamp(Windows::Foundation::IReference<Windows::Foundation::DateTime> ** value) = 0; virtual HRESULT __stdcall get_ConnectionInitiatedTimestamp(Windows::Foundation::IReference<Windows::Foundation::DateTime> ** value) = 0; virtual HRESULT __stdcall get_NameResolvedTimestamp(Windows::Foundation::IReference<Windows::Foundation::DateTime> ** value) = 0; virtual HRESULT __stdcall get_SslNegotiatedTimestamp(Windows::Foundation::IReference<Windows::Foundation::DateTime> ** value) = 0; virtual HRESULT __stdcall get_ConnectionCompletedTimestamp(Windows::Foundation::IReference<Windows::Foundation::DateTime> ** value) = 0; virtual HRESULT __stdcall get_RequestSentTimestamp(Windows::Foundation::IReference<Windows::Foundation::DateTime> ** value) = 0; virtual HRESULT __stdcall get_RequestCompletedTimestamp(Windows::Foundation::IReference<Windows::Foundation::DateTime> ** value) = 0; virtual HRESULT __stdcall get_ResponseReceivedTimestamp(Windows::Foundation::IReference<Windows::Foundation::DateTime> ** value) = 0; virtual HRESULT __stdcall get_ResponseCompletedTimestamp(Windows::Foundation::IReference<Windows::Foundation::DateTime> ** value) = 0; }; struct __declspec(uuid("3f5196d0-4c1f-4ebe-a57a-06930771c50d")) __declspec(novtable) IHttpDiagnosticProviderRequestSentEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_Timestamp(Windows::Foundation::DateTime * value) = 0; virtual HRESULT __stdcall get_ActivityId(GUID * value) = 0; virtual HRESULT __stdcall get_Message(Windows::Web::Http::IHttpRequestMessage ** value) = 0; virtual HRESULT __stdcall get_ProcessId(uint32_t * value) = 0; virtual HRESULT __stdcall get_ThreadId(uint32_t * value) = 0; virtual HRESULT __stdcall get_Initiator(winrt::Windows::Web::Http::Diagnostics::HttpDiagnosticRequestInitiator * value) = 0; virtual HRESULT __stdcall get_SourceLocations(Windows::Foundation::Collections::IVectorView<Windows::Web::Http::Diagnostics::HttpDiagnosticSourceLocation> ** value) = 0; }; struct __declspec(uuid("a0a2566c-ab5f-4d66-bb2d-084cf41635d0")) __declspec(novtable) IHttpDiagnosticProviderResponseReceivedEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_Timestamp(Windows::Foundation::DateTime * value) = 0; virtual HRESULT __stdcall get_ActivityId(GUID * value) = 0; virtual HRESULT __stdcall get_Message(Windows::Web::Http::IHttpResponseMessage ** value) = 0; }; struct __declspec(uuid("5b824ec1-6a6c-47cc-afec-1e86bc26053b")) __declspec(novtable) IHttpDiagnosticProviderStatics : Windows::Foundation::IInspectable { virtual HRESULT __stdcall abi_CreateFromProcessDiagnosticInfo(Windows::System::Diagnostics::IProcessDiagnosticInfo * processDiagnosticInfo, Windows::Web::Http::Diagnostics::IHttpDiagnosticProvider ** value) = 0; }; struct __declspec(uuid("54a9d260-8860-423f-b6fa-d77716f647a7")) __declspec(novtable) IHttpDiagnosticSourceLocation : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_SourceUri(Windows::Foundation::IUriRuntimeClass ** value) = 0; virtual HRESULT __stdcall get_LineNumber(uint64_t * value) = 0; virtual HRESULT __stdcall get_ColumnNumber(uint64_t * value) = 0; }; } namespace ABI { template <> struct traits<Windows::Web::Http::Diagnostics::HttpDiagnosticProvider> { using default_interface = Windows::Web::Http::Diagnostics::IHttpDiagnosticProvider; }; template <> struct traits<Windows::Web::Http::Diagnostics::HttpDiagnosticProviderRequestResponseCompletedEventArgs> { using default_interface = Windows::Web::Http::Diagnostics::IHttpDiagnosticProviderRequestResponseCompletedEventArgs; }; template <> struct traits<Windows::Web::Http::Diagnostics::HttpDiagnosticProviderRequestResponseTimestamps> { using default_interface = Windows::Web::Http::Diagnostics::IHttpDiagnosticProviderRequestResponseTimestamps; }; template <> struct traits<Windows::Web::Http::Diagnostics::HttpDiagnosticProviderRequestSentEventArgs> { using default_interface = Windows::Web::Http::Diagnostics::IHttpDiagnosticProviderRequestSentEventArgs; }; template <> struct traits<Windows::Web::Http::Diagnostics::HttpDiagnosticProviderResponseReceivedEventArgs> { using default_interface = Windows::Web::Http::Diagnostics::IHttpDiagnosticProviderResponseReceivedEventArgs; }; template <> struct traits<Windows::Web::Http::Diagnostics::HttpDiagnosticSourceLocation> { using default_interface = Windows::Web::Http::Diagnostics::IHttpDiagnosticSourceLocation; }; } namespace Windows::Web::Http::Diagnostics { template <typename D> struct WINRT_EBO impl_IHttpDiagnosticProvider { void Start() const; void Stop() const; event_token RequestSent(const Windows::Foundation::TypedEventHandler<Windows::Web::Http::Diagnostics::HttpDiagnosticProvider, Windows::Web::Http::Diagnostics::HttpDiagnosticProviderRequestSentEventArgs> & handler) const; using RequestSent_revoker = event_revoker<IHttpDiagnosticProvider>; RequestSent_revoker RequestSent(auto_revoke_t, const Windows::Foundation::TypedEventHandler<Windows::Web::Http::Diagnostics::HttpDiagnosticProvider, Windows::Web::Http::Diagnostics::HttpDiagnosticProviderRequestSentEventArgs> & handler) const; void RequestSent(event_token token) const; event_token ResponseReceived(const Windows::Foundation::TypedEventHandler<Windows::Web::Http::Diagnostics::HttpDiagnosticProvider, Windows::Web::Http::Diagnostics::HttpDiagnosticProviderResponseReceivedEventArgs> & handler) const; using ResponseReceived_revoker = event_revoker<IHttpDiagnosticProvider>; ResponseReceived_revoker ResponseReceived(auto_revoke_t, const Windows::Foundation::TypedEventHandler<Windows::Web::Http::Diagnostics::HttpDiagnosticProvider, Windows::Web::Http::Diagnostics::HttpDiagnosticProviderResponseReceivedEventArgs> & handler) const; void ResponseReceived(event_token token) const; event_token RequestResponseCompleted(const Windows::Foundation::TypedEventHandler<Windows::Web::Http::Diagnostics::HttpDiagnosticProvider, Windows::Web::Http::Diagnostics::HttpDiagnosticProviderRequestResponseCompletedEventArgs> & handler) const; using RequestResponseCompleted_revoker = event_revoker<IHttpDiagnosticProvider>; RequestResponseCompleted_revoker RequestResponseCompleted(auto_revoke_t, const Windows::Foundation::TypedEventHandler<Windows::Web::Http::Diagnostics::HttpDiagnosticProvider, Windows::Web::Http::Diagnostics::HttpDiagnosticProviderRequestResponseCompletedEventArgs> & handler) const; void RequestResponseCompleted(event_token token) const; }; template <typename D> struct WINRT_EBO impl_IHttpDiagnosticProviderRequestResponseCompletedEventArgs { GUID ActivityId() const; Windows::Web::Http::Diagnostics::HttpDiagnosticProviderRequestResponseTimestamps Timestamps() const; Windows::Foundation::Uri RequestedUri() const; uint32_t ProcessId() const; uint32_t ThreadId() const; Windows::Web::Http::Diagnostics::HttpDiagnosticRequestInitiator Initiator() const; Windows::Foundation::Collections::IVectorView<Windows::Web::Http::Diagnostics::HttpDiagnosticSourceLocation> SourceLocations() const; }; template <typename D> struct WINRT_EBO impl_IHttpDiagnosticProviderRequestResponseTimestamps { Windows::Foundation::IReference<Windows::Foundation::DateTime> CacheCheckedTimestamp() const; Windows::Foundation::IReference<Windows::Foundation::DateTime> ConnectionInitiatedTimestamp() const; Windows::Foundation::IReference<Windows::Foundation::DateTime> NameResolvedTimestamp() const; Windows::Foundation::IReference<Windows::Foundation::DateTime> SslNegotiatedTimestamp() const; Windows::Foundation::IReference<Windows::Foundation::DateTime> ConnectionCompletedTimestamp() const; Windows::Foundation::IReference<Windows::Foundation::DateTime> RequestSentTimestamp() const; Windows::Foundation::IReference<Windows::Foundation::DateTime> RequestCompletedTimestamp() const; Windows::Foundation::IReference<Windows::Foundation::DateTime> ResponseReceivedTimestamp() const; Windows::Foundation::IReference<Windows::Foundation::DateTime> ResponseCompletedTimestamp() const; }; template <typename D> struct WINRT_EBO impl_IHttpDiagnosticProviderRequestSentEventArgs { Windows::Foundation::DateTime Timestamp() const; GUID ActivityId() const; Windows::Web::Http::HttpRequestMessage Message() const; uint32_t ProcessId() const; uint32_t ThreadId() const; Windows::Web::Http::Diagnostics::HttpDiagnosticRequestInitiator Initiator() const; Windows::Foundation::Collections::IVectorView<Windows::Web::Http::Diagnostics::HttpDiagnosticSourceLocation> SourceLocations() const; }; template <typename D> struct WINRT_EBO impl_IHttpDiagnosticProviderResponseReceivedEventArgs { Windows::Foundation::DateTime Timestamp() const; GUID ActivityId() const; Windows::Web::Http::HttpResponseMessage Message() const; }; template <typename D> struct WINRT_EBO impl_IHttpDiagnosticProviderStatics { Windows::Web::Http::Diagnostics::HttpDiagnosticProvider CreateFromProcessDiagnosticInfo(const Windows::System::Diagnostics::ProcessDiagnosticInfo & processDiagnosticInfo) const; }; template <typename D> struct WINRT_EBO impl_IHttpDiagnosticSourceLocation { Windows::Foundation::Uri SourceUri() const; uint64_t LineNumber() const; uint64_t ColumnNumber() const; }; } namespace impl { template <> struct traits<Windows::Web::Http::Diagnostics::IHttpDiagnosticProvider> { using abi = ABI::Windows::Web::Http::Diagnostics::IHttpDiagnosticProvider; template <typename D> using consume = Windows::Web::Http::Diagnostics::impl_IHttpDiagnosticProvider<D>; }; template <> struct traits<Windows::Web::Http::Diagnostics::IHttpDiagnosticProviderRequestResponseCompletedEventArgs> { using abi = ABI::Windows::Web::Http::Diagnostics::IHttpDiagnosticProviderRequestResponseCompletedEventArgs; template <typename D> using consume = Windows::Web::Http::Diagnostics::impl_IHttpDiagnosticProviderRequestResponseCompletedEventArgs<D>; }; template <> struct traits<Windows::Web::Http::Diagnostics::IHttpDiagnosticProviderRequestResponseTimestamps> { using abi = ABI::Windows::Web::Http::Diagnostics::IHttpDiagnosticProviderRequestResponseTimestamps; template <typename D> using consume = Windows::Web::Http::Diagnostics::impl_IHttpDiagnosticProviderRequestResponseTimestamps<D>; }; template <> struct traits<Windows::Web::Http::Diagnostics::IHttpDiagnosticProviderRequestSentEventArgs> { using abi = ABI::Windows::Web::Http::Diagnostics::IHttpDiagnosticProviderRequestSentEventArgs; template <typename D> using consume = Windows::Web::Http::Diagnostics::impl_IHttpDiagnosticProviderRequestSentEventArgs<D>; }; template <> struct traits<Windows::Web::Http::Diagnostics::IHttpDiagnosticProviderResponseReceivedEventArgs> { using abi = ABI::Windows::Web::Http::Diagnostics::IHttpDiagnosticProviderResponseReceivedEventArgs; template <typename D> using consume = Windows::Web::Http::Diagnostics::impl_IHttpDiagnosticProviderResponseReceivedEventArgs<D>; }; template <> struct traits<Windows::Web::Http::Diagnostics::IHttpDiagnosticProviderStatics> { using abi = ABI::Windows::Web::Http::Diagnostics::IHttpDiagnosticProviderStatics; template <typename D> using consume = Windows::Web::Http::Diagnostics::impl_IHttpDiagnosticProviderStatics<D>; }; template <> struct traits<Windows::Web::Http::Diagnostics::IHttpDiagnosticSourceLocation> { using abi = ABI::Windows::Web::Http::Diagnostics::IHttpDiagnosticSourceLocation; template <typename D> using consume = Windows::Web::Http::Diagnostics::impl_IHttpDiagnosticSourceLocation<D>; }; template <> struct traits<Windows::Web::Http::Diagnostics::HttpDiagnosticProvider> { using abi = ABI::Windows::Web::Http::Diagnostics::HttpDiagnosticProvider; static constexpr const wchar_t * name() noexcept { return L"Windows.Web.Http.Diagnostics.HttpDiagnosticProvider"; } }; template <> struct traits<Windows::Web::Http::Diagnostics::HttpDiagnosticProviderRequestResponseCompletedEventArgs> { using abi = ABI::Windows::Web::Http::Diagnostics::HttpDiagnosticProviderRequestResponseCompletedEventArgs; static constexpr const wchar_t * name() noexcept { return L"Windows.Web.Http.Diagnostics.HttpDiagnosticProviderRequestResponseCompletedEventArgs"; } }; template <> struct traits<Windows::Web::Http::Diagnostics::HttpDiagnosticProviderRequestResponseTimestamps> { using abi = ABI::Windows::Web::Http::Diagnostics::HttpDiagnosticProviderRequestResponseTimestamps; static constexpr const wchar_t * name() noexcept { return L"Windows.Web.Http.Diagnostics.HttpDiagnosticProviderRequestResponseTimestamps"; } }; template <> struct traits<Windows::Web::Http::Diagnostics::HttpDiagnosticProviderRequestSentEventArgs> { using abi = ABI::Windows::Web::Http::Diagnostics::HttpDiagnosticProviderRequestSentEventArgs; static constexpr const wchar_t * name() noexcept { return L"Windows.Web.Http.Diagnostics.HttpDiagnosticProviderRequestSentEventArgs"; } }; template <> struct traits<Windows::Web::Http::Diagnostics::HttpDiagnosticProviderResponseReceivedEventArgs> { using abi = ABI::Windows::Web::Http::Diagnostics::HttpDiagnosticProviderResponseReceivedEventArgs; static constexpr const wchar_t * name() noexcept { return L"Windows.Web.Http.Diagnostics.HttpDiagnosticProviderResponseReceivedEventArgs"; } }; template <> struct traits<Windows::Web::Http::Diagnostics::HttpDiagnosticSourceLocation> { using abi = ABI::Windows::Web::Http::Diagnostics::HttpDiagnosticSourceLocation; static constexpr const wchar_t * name() noexcept { return L"Windows.Web.Http.Diagnostics.HttpDiagnosticSourceLocation"; } }; } }
/* GPA2 - IFC Criado Por: Natalia Kelim Thiel Data: 01/04/2016 Descrição: Código fonte (source) da biblioteca para o uso do Sensor DS18B20 (Temperatura) */ #include "Arduino.h" #include "Temperatura.h" Temperatura::Temperatura() { _indice = 0; _titulo = "TEMPERATURA"; _arquivo = "tmp"; } float Temperatura::ler() { OneWire ds(3); // pino do sensor byte data[12]; byte addr[8]; if ( !ds.search(addr)) { //no more sensors on chain, reset search ds.reset_search(); return -1000; } if ( OneWire::crc8( addr, 7) != addr[7]) { Serial.println("CRC is not valid!"); return -1000; } if ( addr[0] != 0x10 && addr[0] != 0x28) { Serial.print("Device is not recognized"); return -1000; } ds.reset(); ds.select(addr); ds.write(0x44, 1); byte present = ds.reset(); ds.select(addr); ds.write(0xBE); for (int i = 0; i < 9; i++) { data[i] = ds.read(); } ds.reset_search(); byte MSB = data[1]; byte LSB = data[0]; float TRead = ((MSB << 8) | LSB); float Temperature = TRead / 16; //Serial.println("Temperatura: " + (String)Temperature); return Temperature; } boolean Temperatura::coletar() { // Adiciona no array mais uma temperatura if (_indice < 15) { // Se for menor que 15 adiciona no array _array[_indice] = ler(); // Adiciona a temperatura em um array _indice++; return false; } else { // Se maior que 15 então reinicia o contador _indice = 0; return true; } }
#include<stdio.h> #include<unordered_set> #include<set> using namespace std; char str[13]; unordered_set<string> member, active; // O(1+a) //set<string> member, active; // O(log n) int validate() { return member.count(str); } int activate() { return active.count(str); } int signup() { member.insert(str); return member.size(); } int close() { member.erase(str); active.erase(str); return member.size(); } int login() { if (member.count(str)) active.insert(str); return active.size(); } int logout() { active.erase(str); return active.size(); } int main() { freopen("input.txt", "r", stdin); int q, cmd, ret; scanf("%d", &q); while (q--) { scanf("%d%s", &cmd, str); if (cmd == 1) ret = validate(); if (cmd == 2) ret = activate(); if (cmd == 3) ret = signup(); if (cmd == 4) ret = close(); if (cmd == 5) ret = login(); if (cmd == 6) ret = logout(); printf("%d\n", ret); } return 0; }
#include <stdio.h> //2 /*(2,0) Mostre na tabela abaixo todos os passos (teste de mesa) e identifique qual será a saída do programa em C, para os valores lidos (x = 5 e y = 10). */ /* // 5 10 void func(int *px, int *py) { //endereço de memoria de py vai em px; printf("ANTES DA ATRIBUICAO \n px = %x \n py = %x \n", px, py); px = py; printf(" px = %x \n py = %x \n", px, py); //valor py = 10 * 10 = 100; *py = (*py) * (*px); //valor px = + 1 = 11 printf("px = %d \n", *px); *px = *px + 1; } */ int main(){ float y = 5.6, *py = &y, **ppy = &py; printf("%f \n", **ppy); //py++; //printf("%d \n", py); //15 //**ptx++ //int x=10, *px=&x, **ppx=&x; /*14 //int x = 10; //int *px = &x; //printf("%d\n", &x); //printf("%d\n", &px); //printf("%d\n", *&px); */ //04 //int a = 666, b = 6; //double c = 66.6; //int *pa, *pb = &b; //double *pc; //&pa = &a;//false //pb = &a;//true //*pc = c;//false //printf("%d", *pa); //*c = &pc; false //a = &pa; //*pb = &b; true //*pa = 1024; false //printf("%d", *pa); //pa = 1024; false //printf("%d", *pa); //03 //programa A /* int valor[] = {3,7,25,80,99}; int i = 0, *pValor; pValor = valor; // i = 0; i < 4 = 0 1 2 3 4 while(i < 4) { printf("%d \n",*pValor++); i++; } */ /* int valor[] = {3,7,25,80,99}; int i = 0, *pValor; pValor = valor; printf("%d\n", *pValor); while(i < 4) { printf("%d ",(*pValor)++); i++; }*/ /* //2 int x, y; x = 5; y = 10; //scanf("%d",&x); //scanf("%d",&y); func(&x,&y); //x=5 y= 101 printf("x = %d, y = %d", x, y); */ //01 = d; //Qual afirmativa é falsa? //a. *pti é igual a 10. true //b. pti armazena o endereço de i. true //c. ao se executar *pti = 30; i passará a ter o valor 30. true //d. ao se alterar o valor de i, pti(endereço de memoria) // será modificado. false //e. nenhuma das anteriores. /* int *pti; int i = 10; pti = &i; printf("%d\n", *pti); printf("%d\n", &i); printf("%d\n", pti); *pti = 30; printf("%d\n", i); i = 5; printf("%d\n", pti); printf("%d\n", *pti); */ }
#include <iostream> using namespace std; int main() { int t,a=0,b=0; cin>>t; int p,m=0; for( int i=0; i<t;i++) { int pa,pb; cin>>pa>>pb; a = a+pa; b = b+pb; if(a>b) { if(a-b>m ) { m = a-b; p=1; } } else { if(b-a>m) { m=b-a; p=2; } } } cout<<p<<" "<<m; return 0; }
class Solution { public: bool searchMatrix(vector<vector<int>>& matrix, int target) { for (int i = 0; i<matrix.size(); i++) { if (matrix[i].front()<=target&&matrix[i].back()>=target) { for (int l = 0,r = int(matrix[i].size())-1,mid = (l+r)/2; l<=r;mid = (l+r)/2) { if (matrix[i][mid]<target) { l = mid+1; } else if (matrix[i][mid]>target) { r = mid-1; } else return true; } } } return false; } };
/******************************************************************************* * Cristian Alexandrescu * * 2163013577ba2bc237f22b3f4d006856 * * 11a4bb2c77aca6a9927b85f259d9af10db791ce5cf884bb31e7f7a889d4fb385 * * bc9a53289baf23d369484f5343ed5d6c * *******************************************************************************/ /* Problem 11588 - Image Coding */ #include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; int main() { int nNoTestCases; cin >> nNoTestCases; for (int nCaseLoop = 1; nCaseLoop <= nNoTestCases; nCaseLoop++) { int nNoRows, nNoColumns, nNoBytesImportant, nNoBytesUnimportant; cin >> nNoRows >> nNoColumns >> nNoBytesImportant >> nNoBytesUnimportant; string oRow; vector<int> oVecnFreq('Z' - 'A' + 1); int nMaxFreq = 0, nMaxFreqCount = 0; for (int nRowLoop = 0; nRowLoop < nNoRows; nRowLoop++) { cin >> oRow; for_each( oRow.cbegin(), oRow.cend(), [&oVecnFreq, &nMaxFreq, &nMaxFreqCount](char cChar) { cChar -= 'A'; int nNewCharFreq = ++oVecnFreq[cChar]; if (nNewCharFreq > nMaxFreq) { nMaxFreq = nNewCharFreq; nMaxFreqCount = 1; } else if (nNewCharFreq == nMaxFreq) { nMaxFreqCount++; } } ); } auto nSol = nMaxFreq * nMaxFreqCount * nNoBytesImportant + (nNoRows * nNoColumns - nMaxFreq * nMaxFreqCount) * nNoBytesUnimportant; cout << "Case " << nCaseLoop << ": " << nSol << endl; } return 0; }
#ifndef BUY_WIN_CUT_H #define BUY_WIN_CUT_H #include <QDialog> #include <QtSql> #include<QCompleter> #include<QMenuBar> #include<QMenu> #include<QDate> #include<QSqlQuery> #include<QMessageBox> #include<QByteArray> #include<QtNetwork/QNetworkInterface> #include<QBuffer> #include<QFile> #include<QIODevice> #include<QPixmap> #include<QComboBox> #include<QFontComboBox> #include<QTableWidgetItem> #include<QTimer> #include<qtrpt.h> #include<qshortcut.h> #include<LimeReport> #include <QtConcurrent/QtConcurrent> #include<item_search.h> #include<invoice_search.h> namespace Ui { class buy_win_cut; } class buy_win_cut : public QDialog { Q_OBJECT public: explicit buy_win_cut(QWidget *parent = nullptr); ~buy_win_cut(); public slots: void clearAll(); private slots: void setData(); //void setData_int(); void setData_bcode(); void clearLines(); void setTable(); void getTotal(); void getTotal_items(); void enter_pressed_1(); void enter_pressed_2(); void enter_pressed_3(); void enter_pressed_4(); void print_save(); void print_bcode(); void save_items(); void set_edit(); void set_unedit(); void delete_row(); void update_time(); void update_itemsList(); void update_List(); void search_invoice(); void show_search(); void showEvent(QShowEvent *event); void on_quantity_returnPressed(); void on_price_buy_returnPressed(); void on_price_sell_returnPressed(); void on_discount_editingFinished(); void on_discount_returnPressed(); void on_dicount_perc_editingFinished(); void on_dicount_perc_returnPressed(); void on_tableWidget_itemChanged(QTableWidgetItem *item); void on_save_clicked(); void on_total_rec_textChanged(const QString &arg1); void on_saved_clicked(); void on_rec_no_textChanged(const QString &arg1); void on_pushButton_clicked(); void on_pushButton_2_clicked(); void on_pushButton_4_clicked(); void on_pushButton_5_clicked(); void on_rec_stat_currentIndexChanged(int index); void on_item_bcode_activated(const QString &arg1); void on_item_int_activated(const QString &arg1); void on_un_save_clicked(); void on_tableWidget_clicked(const QModelIndex &index); void on_pushButton_3_clicked(); void on_supp_name_currentIndexChanged(int index); void on_pushButton_6_clicked(); void on_pushButton_7_clicked(); void on_pushButton_9_clicked(); void on_tableWidget_2_clicked(const QModelIndex &index); void on_pushButton_8_clicked(); void on_pushButton_10_clicked(); void on_item_name_currentIndexChanged(int index); void slotGetCallbackData(const LimeReport::CallbackInfo &info, QVariant &data); void slotGetPrintCallbackData(const LimeReport::CallbackInfo &info, QVariant &data); private: Ui::buy_win_cut *ui; bool first_open = true; bool saved; bool unsaved; bool searching; int cur_search_index; QVector<int> search_list; int max_search_index; QString print_item_name , print_barcode , print_sell; QString shop_name,shop_phone,trade,tax; QSqlDatabase db; QSqlDatabase db2; QSqlQueryModel *model; QSqlQueryModel *model1; QSqlQueryModel *model2; QSqlQueryModel *model3; QSqlQueryModel *model4; QSqlQueryModel *model5; QSqlQueryModel *model6; QSqlQueryModel *model7; QSqlQueryModel *model8; QSqlQueryModel *model10; QSqlQueryModel *model11; QSqlQuery *qry_in; QTableView *tv; item_search *search; invoice_search *inv_search; LimeReport::ReportEngine *report; int cur_row; }; #endif // BUY_WIN_CUT_H
#pragma once #include <Windows.h> #include "Common.h" #include "Loading.h" #ifndef __CV_INCLUDE_ #define __CV_INCLUDE_ #include <opencv\cv.h> #include <opencv\cvaux.h> #include <opencv\highgui.h> #include "GlobalVars.h" using namespace cv; #endif // #! __CV_INCLUDE #include "NewPerson.h" #include "AcceptFace.h" #include "_FaceRecognizer.h" namespace FaceIdentifier { using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; using namespace cv; /// <summary> /// Summary for Main /// </summary> public ref class Main : public System::Windows::Forms::Form { public: Main(void); protected: /// <summary> /// Clean up any resources being used. /// </summary> ~Main(); protected: private: System::Windows::Forms::MenuStrip^ menu; private: System::Windows::Forms::ToolStripMenuItem^ personToolStripMenuItem; private: System::Windows::Forms::ToolStripMenuItem^ newToolStripMenuItem; private: System::Windows::Forms::Button^ button1; private: System::Windows::Forms::ToolStripMenuItem^ detectionToolStripMenuItem; private: System::Windows::Forms::ToolStripMenuItem^ startFaceDetectionToolStripMenuItem; private: System::Windows::Forms::PictureBox^ pbWebCam; System::Drawing::Bitmap ^bmp; IplImage *imgCopy; bool bugeger; private: System::Windows::Forms::Timer^ timer1; private: System::ComponentModel::IContainer^ components; protected: private: /// <summary> /// Required designer variable. /// </summary> #pragma region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> void InitializeComponent(void); #pragma endregion void resize(); IplImage *crop(IplImage *img, CvRect border); private: System::Void Main_Load(System::Object^ sender, System::EventArgs^ e); private: System::Void Main_Resize(System::Object^ sender, System::EventArgs^ e); private: System::Void newToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e); private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e); private:System::Void startFaceDetectionToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e); }; };
#include "DummyDecompressor.h" DummyDecompressor::DummyDecompressor(FILE* inputFile) { file = inputFile; } int DummyDecompressor::decompressNextByte() { Byte tmp; assert(1 == fread(&tmp, sizeof(Byte), 1, file)); return tmp; } void DummyDecompressor::close() { fclose(file); }
#include<iostream> using namespace std; class cDemo { int M_iNo1; int M_iNo2; public: cDemo() { } void fun1() { } void fun2() const { } void fun3 (cDemo *pPtr) { } void fun4(cDemo const *pPtr) { } }; int main () { cDemo obj1; const cDemo obj2; obj1.fun1(); obj1.fun2(); //obj1.fun3(&obj1); //obj1.fun3(&obj2); //obj1.fun4(&obj1); //obj1.fun4(&obj2); //obj2.fun1(); obj2.fun2(); //obj2.fun3(&obj2); //obj2.fun4(&obj1); //obj2.fun4(&obj2); return 0; }
#include<bits/stdc++.h> using namespace std; #define ff first #define ss second #define int long long #define pb push_back #define mp make_pair #define pii pair<int,int> #define vi vector<int> #define mii map<int,int> #define pqb priority_queue<int> #define pqs priority_queue<int,vi,greater<int> > #define setbits(x) __builtin_popcountll(x) #define zrobits(x) __builtin_ctzll(x) #define mod 1000000007 #define inf 1e18 #define ps(x,y) fixed<<setprecision(y)<<x mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); const int MAXN = 1e6+1; vector <int> adj[MAXN]; vector <int> vis(MAXN,0); vector <int> comp(MAXN,0); int cc; void c_p_c() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif } void dfs(int s) { vis[s] = 1; comp[s] = cc; for(int u:adj[s]) { if(!vis[u]) { dfs(u); } } return ; } int32_t main() { c_p_c(); int tc; cin >> tc; while(tc--) { int n,m; cin >> n >> m; vector <pair<int,int>> v; for(int i=0;i<m;i++) { int x,y; string eq,h="="; cin >> x >> eq >> y; if(eq == h) { adj[x].push_back(y); adj[y].push_back(x); } else { v.push_back({x,y}); } } cc = 0; for(int i=1;i<=n;i++) { if(!vis[i]) { cc++; dfs(i); } } int flag = 0; for(int i=0;i<v.size();i++) { if(comp[v[i].first] == comp[v[i].second]) { flag = 1; break; } } if(flag) { cout<<"NO"<<endl; } else { cout<<"YES"<<endl; } for(int i=1;i<=n;i++) adj[i].clear(); fill(vis.begin(),vis.end(),0); fill(comp.begin(),comp.end(),0); } return 0; }
#include <iostream> #include <stdio.h> #include <stdlib.h> using namespace std; int main() { double ne,na,nf; printf("Ingrese la nota de acumulados: \n"); scanf("%lf", &na); printf("Ingrese la nota de Examen: \n"); scanf("%lf", &ne); na=na*0.3; ne=ne*0.7; nf=na+ne; if (nf>=60) { printf("Estado de la nota: Apr\n"); } else { printf("Estado de la nota: Rep\n"); } printf("Nota Final es %lf \n\n", nf); system("PAUSE"); return 0; }
// Fill out your copyright notice in the Description page of Project Settings. #include "EscapeGame.h" #include "OpenDoorActor.h" // Sets default values for this component's properties UOpenDoorActor::UOpenDoorActor() { // Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features // off to improve performance if you don't need them. bWantsBeginPlay = true; PrimaryComponentTick.bCanEverTick = true; // ... } // Called when the game starts void UOpenDoorActor::BeginPlay() { Super::BeginPlay(); // ... Kode som ikke er generert av Unreal. ActorThatOpens = GetWorld()->GetFirstPlayerController()->GetPawn(); } void UOpenDoorActor::OpenDoor() { AActor* Owner = GetOwner(); FRotator NewRotation = FRotator(0.0f, -30.f, 0.0f); Owner->SetActorRotation(NewRotation); } // Called every frame void UOpenDoorActor::TickComponent( float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction ) { Super::TickComponent( DeltaTime, TickType, ThisTickFunction ); // ... if the ActorThatOPens is in the trigger, open the door. if (PressurePlate->IsOverlappingActor(ActorThatOpens)) { OpenDoor(); } }
#ifndef PE_EDITOR_H #define PE_EDITOR_H /* * @author Paradoxon powered by Jesus Christ */ #include <app/Message.h> #include <interface/View.h> #include <support/List.h> #ifdef B_ZETA_VERSION_1_0_0 #include <locale/Locale.h> #include <locale/LanguageNotifier.h> #else #define _T(a) a #endif #include "PEditor.h" #include "BasePlugin.h" #include "PDocument.h" #include "PluginManager.h" #include "PatternToolItem.h" #include "ColorToolItem.h" #include "FloatToolItem.h" class GraphEditor : public PEditor, public BView { public: GraphEditor(image_id newId); //++++++++++++++++PEditor virtual void AttachedToManager(void); virtual void DetachedFromManager(void); virtual BView* GetView(void){return this;}; virtual BHandler* GetHandler(void){return this;}; virtual BList* GetPCommandList(void); virtual void ValueChanged(void); virtual void InitAll(void); virtual void SetDirty(BRegion *region); virtual BMessage* GetConfiguration(void){return configMessage;}; virtual void SetConfiguration(BMessage *message){delete configMessage;configMessage=message;}; virtual void PreprocessBeforSave(BMessage *container); virtual void PreprocessAfterLoad(BMessage *container); //----------------PEditor //++++++++++++++++BView virtual void AttachedToWindow(void); virtual void DetachedFromWindow(void); virtual void Draw(BRect updateRect); virtual void MouseDown(BPoint where); virtual void MouseMoved( BPoint where, uint32 code, const BMessage *a_message); virtual void MouseUp(BPoint where); virtual void KeyDown(const char *bytes, int32 numBytes); virtual void KeyUp(const char *bytes, int32 numBytes); virtual void MessageReceived(BMessage *msg); virtual void FrameResized(float width, float height); //----------------BView protected: void Init(void); int32 id; char* renderString; BMenu *scaleMenu; ToolBar *toolBar; ToolItem *grid; ToolItem *addGroup; ToolItem *addBool; ToolItem *addText; FloatToolItem *penSize; ColorToolItem *colorItem; PatternToolItem *patternItem; BRect *printRect; bool key_hold; BPoint *startMouseDown; bool connecting; BPoint *fromPoint; BPoint *toPoint; BRect *selectRect; BMessage *nodeMessage; BMessage *fontMessage; BMessage *patternMessage; BMessage *configMessage; BMessage *connectionMessage; BMessage *groupMessage; BMessenger *sentTo; BMessenger *sentToMe; BRegion *rendersensitv; Renderer *activRenderer; Renderer *mouseReciver; BList *renderer; float scale; bool gridEnabled; image_id pluginID; private: }; #endif
#include <iostream> const double Inch_per_feet = 12.0; const double Meter_per_inch = 0.0254; const double Pound_per_kilogram = 2.2; int main(void) { using namespace std; cout << "Eenter your height of feet:____\b\b\b\b"; double ht_feet; cin >> ht_feet; cout << "Enter height of inch:____\b\b\b\b"; double ht_inch; cin >> ht_inch; // convert height double ht_meter = (ht_feet*Inch_per_feet + ht_inch)*Meter_per_inch; cout << "Enter your weight in pound:____\b\b\b\b"; double wt_pound; cin >> wt_pound; // convert weight double wt_kilogram = wt_pound/Pound_per_kilogram; //double BMI = wt_kilogram/ht_meter;// the BMI is kg/(meter)^2 double BMI = wt_kilogram/(ht_meter*ht_meter); cout << "BMI: " << BMI << endl; return 0; }
#include "stdafx.h" #include <iostream> #include "attack.h" #include "person.h" using namespace std; /** * Comment out the argc and argv, so we don't get * any compiler warnings. * @brief main * @return */ int main(int /*argc*/, char /**argv[]*/) { Person person("Mismis"); person.addWeightLog(WeightEntry(90, "04-03-3017")); person.addWeightLog(WeightEntry(92, "04-02-3017")); person.addWeightLog(WeightEntry(94, "04-01-3017")); cout << person.getWeights() << endl; // Press Enter to exit message, so we can se the output cout << "Press Enter to exit" << endl; getchar(); return 0; } /* * Old code for keeping :) */ void oldCodeFOrKeeping() { cout << "Init Attack log" << endl; Attack attack; attack.addAttack("127.0.0.1", "Dos"); attack.addAttack("192.168.1.1", "?"); for (auto log : attack.getLogs()) { cout << log << endl; } cout << "End"; }
//============================================== // Name : AKSHAY MUKESHBHAI KATRODIYA // Email : amkatrodiya@myseneca.ca // Student ID : 125298208 // Section : NAA // Date : 06/05/2021 //============================================== //I have done all the coding by myself and only copied the code that my professor provided to complete my workshops and assignments. #ifndef SDDS_POPULATION_H_ #define SDDS_POPULATION_H_ namespace sdds { struct PostalCode { char *postal_code; int population; }; void sort(); bool load(PostalCode &post); bool load(const char filename[]); void display(const PostalCode &postal_code); void display(); void deallocateMemory(); } #endif // SDDS_POPULATION_H_
#include <iostream> using namespace std; int main() { string str1,str2; cin >> str1 >> str2; if(str1.length()>str2.length()) cout<<str1; else cout << str2; return 0; }
#include "LambdaExpression.h" namespace txt { LambdaExpression::LambdaExpression(const std::function<std::string()>& func) : m_func(func) { } LambdaExpression::~LambdaExpression() { } std::string LambdaExpression::ExecImpl() const { return m_func(); } } // namespace txt
#include <bits/stdc++.h> using namespace std; using ll = long long int; void solve(){ ll n; cin >> n; ll t = 0, f = 0, s = 0; t = n / 3; n %= 3; if(n == 2){ if(t) { t--, f++; } else { cout << "-1\n"; return; } } else if(n == 1){ if(t > 1) { t-= 2, s++; } else { cout << "-1\n"; return; } } cout << t << " " << f << " " << s << '\n'; } int main(){ ios::sync_with_stdio(0); cin.tie(0); int t; cin >> t; while(t--){ solve(); } }
#pragma once #include <iostream> #include <cmath> #include "Vector.h" using namespace std; class Sphere { public: Vector center; Vector albedo; double r; bool miroir; bool transparent; // constructeur Sphere(Vector c, Vector couleur, double r, bool mirror = false, bool transp = false) : center(c), albedo(couleur), r(r), miroir(mirror), transparent(transp){}; // methods bool intersect(Ray &ray, Vector &P, Vector &N, double &t) // ici t est en référence, donc pas besoin de le return, sa valeur sera modifiée { // résout a*t^2 + b^t + c = 0 double a = 1; double b = 2 * ray.dir.dot(ray.origin - center); double c = (ray.origin - center).getNorm2() - r * r; double delta = b * b - 4 * a * c; if (delta < 0) return false; double t1 = (-b - sqrt(delta)) / (2 * a); double t2 = (-b + sqrt(delta)) / (2 * a); if (t2 < 0) return false; if (t1 > 0) t = t1; else t = t2; P = ray.origin + (ray.dir * t); N = (P - center).getNormalized(); return true; } };
#ifndef __UBLAS_JFLIB_EXTENSIONS_OPER_HPP__ #define __UBLAS_JFLIB_EXTENSIONS_OPER_HPP__ #include <jflib/jflib.hpp> #include <boost/numeric/ublas/vector.hpp> namespace boost { namespace numeric { namespace ublas { /* * \brief Define a new scalar operation which calculate square root of a number * */ template<class T> struct scalar_sqrt: public scalar_unary_functor<T> { typedef typename scalar_unary_functor<T>::argument_type argument_type; typedef typename scalar_unary_functor<T>::result_type result_type; static BOOST_UBLAS_INLINE result_type apply(argument_type t) { return std::sqrt(t); } }; /* * \brief Define a new scalar operation which calculate the log of the ratio of two numbers * */ template<class T1, class T2> struct scalar_logratio: public scalar_binary_functor<T1, T2> { typedef typename scalar_binary_functor<T1, T2>::argument1_type argument1_type; typedef typename scalar_binary_functor<T1, T2>::argument2_type argument2_type; typedef typename scalar_binary_functor<T1, T2>::result_type result_type; static BOOST_UBLAS_INLINE result_type apply(argument1_type t1, argument2_type t2) { return std::log(t1/t2); } }; // Square Root Function for vector expressions template<class E> BOOST_UBLAS_INLINE typename vector_unary_traits<E, scalar_sqrt<typename E::value_type> >::result_type Sqrt(const vector_expression<E> &e) { typedef typename vector_unary_traits<E, scalar_sqrt<typename E::value_type> >::expression_type expression_type; return expression_type (e ()); } }}} namespace jflib { #define UBLASVECTOR_UNARY_OP1(name,scalar_oper,ublas) \ template<class E> \ struct name<ublas::vector_expression<E>, false > { \ typedef ublas::scalar_oper<typename E::value_type> op_type; \ typedef ublas::vector_unary_traits<E, op_type> traits_type; \ typedef typename traits_type::expression_type expression_type; \ typedef typename traits_type::result_type result_type; \ typedef const ublas::vector_expression<E>& argument_type; \ \ static BOOST_UBLAS_INLINE result_type apply(argument_type e) { \ return expression_type(e()); \ } \ }; UBLASVECTOR_UNARY_OP1(Sqrt_impl,scalar_sqrt,boost::numeric::ublas) } #endif // __UBLAS_JFLIB_EXTENSIONS_OPER_HPP__
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include"manage.h" #include"client.h" #include"order.h" namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = nullptr); ~MainWindow(); void changeClient(); void changeManage(); private slots: void on_pushButton_clicked(); void on_pushButton_2_clicked(); private: Ui::MainWindow *ui; client *sw; manage *tw; order *od; }; #endif // MAINWINDOW_H
#include "inc/utility.hpp" #include <sstream> namespace astroblaster { std::string texture_not_found(std::string_view texture) { std::stringstream ss; ss << u8"Texture " << texture << u8" not found in manager."; return ss.str(); } std::string file_not_found(std::string_view file) { std::stringstream ss; ss << u8"File " << file << u8" not found or not readable."; return ss.str(); } }
#include <iostream> #include <stdlib.h> using namespace std; #define GET_MSG_TYPE(BYTE) ((BYTE & 0x300) >> 6) #define GET_INSTR_TYPE(BYTE) ((BYTE & 0x38) >> 3) #define IS_LOAD(INSTR) (INSTR == 0x00 ? 1:0) #define IS_STOP(INSTR) (INSTR == 0x01 ? 1:0) #define IS_QUERY(INSTR) (INSTR == 0x02 ? 1:0) #define GET_WATER_AMT(MSB, SecondByte) (((BYTE1 & 0x07)<<2)+((BYTE2 & 0xC0)>>6)) #define GET_CARTRIDGE(BYTE) ((BYTE & 0x07)<<1)+ #define GET_HEAT(BYTE) (BYTE & 0x07) #define GET_TIME(SecondByte, LSB) (((BYTE1 & 0bFF)<<7)+((BYTE2 & 0bFE)>>1)) #define IS_CONCCURRENT(BYTE) (BYTE & 0x01) //020000-8oz water //088000-cart 1 //0a0000-cart 4 //098000-cart 3 //15003d-heat/med-high/30s/conc //18003c-stir/30/no-conc int main(void){ //0x020000 long byte = 0x98000; long MSB = (byte & 0xFF0000)>>16; long SecondByte = (byte & 0xFF00)>>8; long LSB = byte & 0xFF; //cout<<"Byte: 10 0000 0000 0000 0000"<<endl; cout<<"MSB: "<<MSB<<endl; cout<<"SecondByte: "<<SecondByte<<endl; cout<<"LSB: "<<LSB<<endl; cout<<"Message type: "<<GET_MSG_TYPE(MSB)<<endl; cout<<"Instruction type: "<<GET_INSTR_TYPE(MSB)<<endl; cout<<"Cartridge #: "<<GET_CARTRIDGE(MSB)<<endl; system("PAUSE"); return(0); }
#include "PEngine/graphics/shader.h" #include "PEngine/string_constants.h" #include "PEngine/utilities/error.h" #include "PEngine/utilities/load_text_file.h" #include "PEngine/utilities/string_manipulations.h" #include <iostream> #include <fstream> #include <cstring> namespace pear { namespace graphics { unsigned int Shader::numAttributes = 0; Shader::Shader() : m_Program( 0 ), m_AttributeNum( 0 ) { } Shader::~Shader() { if( m_Program != 0 ) glDeleteProgram( m_Program ); } void Shader::use() { glUseProgram( m_Program ); for( unsigned int i = 0; i < numAttributes; i++ ) { glEnableVertexAttribArray( i ); } } void Shader::unuse() { glUseProgram( 0 ); for( unsigned int i = 0; i < numAttributes; i++ ) { glDisableVertexAttribArray( i ); } } void Shader::addAttribute( const char* attributeName ) { glBindAttribLocation( m_Program, numAttributes++, attributeName ); } GLint Shader::getUniformLocation( const char* uniformName ) { return glGetUniformLocation( m_Program, uniformName ); } void Shader::setUniform1f( const char* name, float value ) { glUniform1f( getUniformLocation( name ), value ); } void Shader::setUniform2f( const char* name, glm::vec2 vector ) { glUniform2f( getUniformLocation( name ), vector.x, vector.y ); } void Shader::setUniform3f( const char* name, glm::vec3 vector ) { glUniform3f( getUniformLocation( name ), vector.x, vector.y, vector.z ); } void Shader::setUniform4f( const char* name, glm::vec4 vector ) { glUniform4f( getUniformLocation( name ), vector.x, vector.y, vector.z, vector.w ); } void Shader::setUniform1i( const char* name, int value ) { glUniform1i( getUniformLocation( name ), value ); } void Shader::setUniform1ui( const char* name, unsigned int value ) { glUniform1ui( getUniformLocation( name ), value ); } void Shader::setUniformMat4( const char* name, const glm::mat4& matrix ) { glUniformMatrix4fv( getUniformLocation( name ), 1, GL_FALSE, &matrix[0][0] ); } void Shader::compileShaders( const char* source ) { m_Program = glCreateProgram(); m_VertexShaderID = glCreateShader( GL_VERTEX_SHADER ); m_FragmentShaderID = glCreateShader( GL_FRAGMENT_SHADER ); std::string vertexSource = ""; std::string fragmentSource = ""; std::string geometrySource = ""; std::string line; enum class ShaderType { VERTEX_SHADER, FRAGMENT_SHADER, GEOMETRY_SHADER, NO_SHADER } shader_type; shader_type = ShaderType::NO_SHADER; const std::string vertexShaderPrep = "#vertex_shader"; const std::string fragmentShaderPrep = "#fragment_shader"; const std::string geometryShaderPrep = "#geometry_shader"; for( unsigned int i = 0; i < utils::howManyLines( source ); ++i ) { line = utils::getLine( source, i ); bool isItPrepCom = false; if( ! line.compare( vertexShaderPrep ) ) { shader_type = ShaderType::VERTEX_SHADER; isItPrepCom = true; } else if( ! line.compare( fragmentShaderPrep ) ) { shader_type = ShaderType::FRAGMENT_SHADER; isItPrepCom = true; } else if( ! line.compare( geometryShaderPrep ) ) { shader_type = ShaderType::GEOMETRY_SHADER; isItPrepCom = true; } if( !isItPrepCom ) { switch( shader_type ) { case ShaderType::VERTEX_SHADER: { vertexSource += line + "\n"; } break; case ShaderType::FRAGMENT_SHADER: { fragmentSource += line + "\n"; } break; case ShaderType::GEOMETRY_SHADER: { geometrySource += line + "\n"; } break; case ShaderType::NO_SHADER: { } break; } } } //printf( "VERTEX_SHADER:\n%s", vertexSource.c_str() ); //printf( "FRAGMENT_SHADER:\n%s", fragmentSource.c_str() ); const char* contentsPtr = vertexSource.c_str(); glShaderSource( m_VertexShaderID, 1, &contentsPtr, NULL ); glCompileShader( m_VertexShaderID ); GLint success; GLchar infoLog[512]; glGetShaderiv( m_VertexShaderID, GL_COMPILE_STATUS, &success); if(!success) { glGetShaderInfoLog( m_VertexShaderID, 512, NULL, infoLog ); std::cout << "ERROR::VERTEX_SHADER::COMPILATION_FAILED\n" << infoLog << std::endl; } contentsPtr = fragmentSource.c_str(); glShaderSource( m_FragmentShaderID, 1, &contentsPtr, NULL ); glCompileShader( m_FragmentShaderID ); glGetShaderiv( m_FragmentShaderID, GL_COMPILE_STATUS, &success); if(!success) { glGetShaderInfoLog( m_FragmentShaderID, 512, NULL, infoLog ); std::cout << "ERROR::FRAGMENT_SHADER::COMPILATION_FAILED\n" << infoLog << std::endl; } } void Shader::compileShaders( const char* vertexPath, const char* fragmentPath ) { m_Program = glCreateProgram(); m_VertexShaderID = glCreateShader( GL_VERTEX_SHADER ); m_FragmentShaderID = glCreateShader( GL_FRAGMENT_SHADER ); compileShader( m_VertexShaderID, vertexPath ); compileShader( m_FragmentShaderID, fragmentPath ); } void Shader::linkShaders() { GLint success; GLchar infoLog[512]; glAttachShader( m_Program, m_VertexShaderID ); glAttachShader( m_Program, m_FragmentShaderID ); glLinkProgram( m_Program ); glGetProgramiv( m_Program, GL_LINK_STATUS, &success ); if( !success ) { glGetProgramInfoLog( m_Program, 512, NULL, infoLog ); std::cout << "Failed to link shader program!\n " << infoLog << std::endl; } glDetachShader( m_Program, m_VertexShaderID ); glDetachShader( m_Program, m_FragmentShaderID ); glDeleteShader( m_VertexShaderID ); glDeleteShader( m_FragmentShaderID ); } void Shader::compileShader( GLuint shader, const char* filePath ) { std::string path = std::string( "../src/Graphics/Shaders/" ) + filePath; std::ifstream file( path.c_str() ); if( file.fail() ) { utils::printError( "Failed to open %s\n", filePath ); } else { std::string content = ""; std::string line; while( std::getline( file, line ) ) { content += line + "\n"; } const char* contentsPtr = content.c_str(); glShaderSource( shader, 1, &contentsPtr, NULL ); glCompileShader( shader ); GLint success; GLchar infoLog[512]; glGetShaderiv( shader, GL_COMPILE_STATUS, &success); if(!success) { glGetShaderInfoLog( shader, 512, NULL, infoLog ); std::cout << "ERROR::SHADER::COMPILATION_FAILED\n"<< filePath << infoLog << std::endl; } } file.close(); } } }
#include<bits/stdc++.h> #include<stdio.h> using namespace std; #define ll long long #define scl(n) cin>>n; #define scc(c) cin>>c; #define fr(i,n) for (ll i=0;i<n;i++) #define fr1(i,n) for(ll i=1;i<=n;i++) #define pfl(x) printf("%lld\n",x) #define pb push_back #define l(s) s.size() #define asort(a) sort(a,a+n) #define all(x) (x).begin(), (x).end() #define dsort(a) sort(a,a+n,greater<int>()) #define vasort(v) sort(v.begin(), v.end()); #define vdsort(v) sort(v.begin(), v.end(),greater<int>()); #define uniquee(x) x.erase(unique(x.begin(), x.end()),x.end()) #define pn cout<<endl; #define md 1000000007 #define inf 1e18 #define debug cout<<"I am here"<<endl; #define ps cout<<" "; #define Pi acos(-1.0) #define mem(a,i) memset(a, i, sizeof(a)) #define tcas(i,t) for(ll i=1;i<=t;i++) #define pcas(i) cout<<"Case "<<i<<": "<<"\n"; #define fast ios_base::sync_with_stdio(0);cin.tie(NULL);cout.tie(NULL) #define N 3005 ll dp[N][N][4]; ll s[N], c[N]; ll m,n,b; ll solve(ll pos,ll lst ,ll cnt) { if(cnt==3)return 0; if(pos==n) { if(cnt!=3)return inf; else return 0; } ll &ret=dp[pos][lst][cnt]; if(ret !=-1)return ret; ll l,r; l=r=inf; // cout<<"pos "<<pos<<" "<<"lst "<<lst<<endl; if(s[pos] >s[lst]) l=c[pos]+solve(pos+1, pos, cnt+1); r=solve(pos+1, lst, cnt); return dp[pos][lst][cnt]=min(l, r); } int main() { fast; while(cin>>n) { mem(dp, -1); ll i,j,cnt=0,ans=inf,sum=0; //ll s[n], c[n]; fr1(i,n)cin>>s[i]; fr1(i, n)cin>>c[i]; // ans=solve(1, 0, 0); /* for(i=2; i<n;i++) { ll l=inf; for(j=1;j<i;j++) if(s[i] >s[j]) l=min(l, c[j]); ll r=inf; for(j=i+1; j<=n; j++) if(s[j]>s[i]) r=min(r, c[j]); ans=min(ans, l+c[i]+r); } if(ans>=inf)cout<<-1<<endl; else cout<<ans<<endl; */ } return 0; } ///Before submit=> /// *check for integer overflow,array bounds /// *check for n=1
#ifndef COURSE_H #define COURSE_H #include <iostream> #include <vector> //vector unlike List, allows us to work with [] !!!!! #include "Student.h" class Course{ private: std::string name; int id; int creditPoints; std::vector<Student*> students; public: Course(int _id, std::string _name, int _creditPoints); friend std::ostream& operator<<(std::ostream& os, const Course& course); inline int getId() const { return id; } inline int getCreditPoints() const { return creditPoints; } inline std::string getName() const { return name; } void registerStudent(Student& student); std::vector<Student*> completeCourse(); bool completeCourseForStudent(Student& student, bool isCompletedSuccessfully); bool deleteStudent(Student& student, bool isCompletedCourse); }; #endif
#include "pch.h" #include "Product.h" #include <string> using namespace std; Product::Product() { } Product::Product(string name, int qty, double price) { this->name = name; this->qty = qty; this->price = price; } Product::~Product() { } void Product::calculateAmount() { this->amount = qty * price; } string Product::getName() { return name; } int Product::getQty() { return qty; } double Product::getPrice() { return price; } double Product::getAmount() { return amount; }
#if 1 #include <opencv2/opencv.hpp> #include <iostream> # include <deque> #include <stdio.h> using namespace std; using namespace cv; #define D_USE_IPCAM 1 /** Function Headers */ void detectAndDisplay(Mat frame,double ); /** Global variables */ //String face_cascade_name = "/Users/dengyan/Desktop/build/etc/haarcascades/haarcascade_frontalface_alt_tree.xml"; //String face_cascade_name = "/Users/dengyan/Desktop/build/etc/haarcascades/haarcascade_frontalface_alt.xml"; String face_cascade_name = "/Users/dengyan/Desktop/build/etc/haarcascades/haarcascade_frontalface_alt2.xml"; //String face_cascade_name = "/Users/dengyan/Desktop/build/etc/haarcascades/haarcascade_frontalcatface.xml"; //String eyes_cascade_name = "/Users/dengyan/Desktop/build/etc/haarcascades/haarcascade_lefteye_2splits.xml"; String eyes_cascade_name = "/Users/dengyan/Desktop/build/etc/haarcascades/haarcascade_eye.xml"; //String eyes_cascade_name = "/Users/dengyan/Desktop/build/etc/haarcascades/haarcascade_eye_tree_eyeglasses.xml"; CascadeClassifier face_cascade; //定义人脸分类器 CascadeClassifier eyes_cascade; //定义人眼分类器 String window_name = "Capture - Face detection"; String window_picture = "picture"; int gray[255]; int forgray[255]; void calgray(Mat &photo) { for (int i = 0; i < photo.rows; i++) for (int j = 0; j < photo.cols; j++) forgray[photo.at<uchar>(i, j)]++; } double ans = 0; double rate = 0.15; int flag = 0; bool judge(int * fp, int sum) { ans = 0; for (int i = 0; i < 255; i++) { ans += abs(fp[i] - gray[i]); } ans /= sum; if (ans > rate) //两张图的变化大于0.2 return true; cout << rate << " " << ans << endl; return false; } int main(void) { Mat frame = imread("../meeting.jpg"); bool ret = false; //Mat frame; //-- 1. Load the cascades ret = face_cascade.load(face_cascade_name); if (!ret){ printf("--(!)Error loading face cascade\n"); return -1; }; ret = eyes_cascade.load(eyes_cascade_name); if (!ret){ printf("--(!)Error loading eyes cascade\n"); return -1; }; #if D_USE_IPCAM //-- 2. Read the video stream VideoCapture capture; capture.open("../cctv.mp4"); if (!capture.isOpened()) { printf("--(!)Error opening video capture\n"); return -1; } //capture.set(CAP_PROP_POS_FRAMES,1200 * 30); capture.set(CAP_PROP_POS_MSEC, 40 * 1000); while (capture.read(frame)) #endif { if (frame.empty()) { printf(" --(!) No captured frame -- Break!"); return -1; } double a = capture.get(CAP_PROP_POS_FRAMES); //-- 3. Apply the classifier to the frame detectAndDisplay(frame, a); #if D_USE_IPCAM int c = waitKey(30); #else int c = waitKey(0); #endif if ((char)c == 27) { return 0; } // escape } return 0; } /** @function detectAndDisplay */ int n = 0; void detectAndDisplay(Mat frame1,double f) { Mat frame_gray; std::vector<Rect> faces; cvtColor(frame1, frame_gray, COLOR_BGR2GRAY); memset(forgray, 0, sizeof(forgray)); calgray(frame_gray); equalizeHist(frame_gray, frame_gray); //-- Detect faces face_cascade.detectMultiScale(frame_gray, faces, 1.2, 10, CASCADE_SCALE_IMAGE, Size(50, 50), Size(500, 500)); for (size_t i = 0; i < faces.size(); i++) { //Point center(faces[i].x + faces[i].width / 2, faces[i].y + faces[i].height / 2); //ellipse(frame, center, Size(faces[i].width / 2, faces[i].height / 2), 0, 0, 360, Scalar(255, 0, 255), 4, 8, 0); rectangle(frame1, faces[i], Scalar(255, 0, 0), 2, 8, 0); } if (flag == 1) { //若刚刚以及截图并保存了 if (rate >= 0.15) { rate *= 0.99; if (faces.empty()) //如果没有检测到人,让阀值更快下降 rate -= 0.01 * ans; else //如果和上一次截图差不多,那么增加rate,如果差别相差大于0.3,则可以加速rate下降 rate += 0.001 * (0.3 - ans); } else flag = 0; } if (!faces.empty()) { if (judge(forgray, frame_gray.rows * frame_gray.cols)) { rate = 0.4; //由于此时截图了一次,不想让其再短时间之内再截图一次,提高阀值 flag = 1; cout << "write" << endl; memcpy(gray, forgray, sizeof(forgray)); imwrite("../" + to_string(n++) + ".png", frame1); } } //-- Show what you got namedWindow(window_name, 2); imshow(window_name, frame1); /*namedWindow(window_picture, 2); imshow(window_picture, frame1);*/ } #endif